@decimalturn/toml-patch 0.3.8 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +475 -19
- package/dist/toml-patch.cjs.min.js +2 -2
- package/dist/toml-patch.cjs.min.js.map +1 -1
- package/dist/toml-patch.d.ts +289 -10
- package/dist/toml-patch.es.js +1525 -101
- package/dist/toml-patch.umd.min.js +2 -2
- package/dist/toml-patch.umd.min.js.map +1 -1
- package/package.json +8 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toml-patch.umd.min.js","sources":["../src/ast.ts","../src/tokenizer.ts","../src/cursor.ts","../src/location.ts","../src/parse-error.ts","../src/utils.ts","../src/parse-string.ts","../src/parse-toml.ts","../src/traverse.ts","../src/writer.ts","../src/generate.ts","../src/format.ts","../src/parse-js.ts","../src/to-toml.ts","../src/to-js.ts","../src/diff.ts","../src/find-by-path.ts","../src/index.ts","../src/patch.ts"],"sourcesContent":["import { Location } from './location';\n\nexport enum NodeType {\n Document = 'Document',\n Table = 'Table',\n TableKey = 'TableKey',\n TableArray = 'TableArray',\n TableArrayKey = 'TableArrayKey',\n KeyValue = 'KeyValue',\n Key = 'Key',\n String = 'String',\n Integer = 'Integer',\n Float = 'Float',\n Boolean = 'Boolean',\n DateTime = 'DateTime',\n InlineArray = 'InlineArray',\n InlineItem = 'InlineItem',\n InlineTable = 'InlineTable',\n Comment = 'Comment'\n}\n\n//\n// Abstract Syntax Tree\n//\n// AST nodes are used to represent TOML data\n//\nexport type AST = Iterable<Block>;\n\n//\n// Document\n//\n// Top-level document that stores AST nodes\n//\nexport interface Document extends TreeNode {\n type: NodeType.Document;\n items: Array<Block>;\n}\nexport function isDocument(node: TreeNode): node is Document {\n return node.type === NodeType.Document;\n}\n\n//\n// Table\n//\n// Top-level object\n//\n// v-------|\n// [table] |\n// b = \"c\" |\n// |\n// # note |\n// ^--|\n// [b]\n//\nexport interface Table extends TreeNode {\n type: NodeType.Table;\n key: TableKey;\n items: Array<KeyValue | Comment>;\n}\nexport function isTable(node: TreeNode): node is Table {\n return node.type === NodeType.Table;\n}\n\n//\n// TableKey\n//\n// Used to store bracket information for Table keys\n//\n// loc includes brackets\n//\n// [ key ]\n// ^-------^\n//\nexport interface TableKey extends TreeNode {\n type: NodeType.TableKey;\n item: Key;\n}\nexport function isTableKey(node: TreeNode): node is TableKey {\n return node.type === NodeType.TableKey;\n}\n\n//\n// TableArray\n//\n// Top-level array item\n//\n// v---------|\n// [[array]] |\n// a=\"b\" |\n// |\n// # details |\n// ^-|\n// [[array]]\n//\nexport interface TableArray extends TreeNode {\n type: NodeType.TableArray;\n key: TableArrayKey;\n items: Array<KeyValue | Comment>;\n}\nexport function isTableArray(node: TreeNode): node is TableArray {\n return node.type === NodeType.TableArray;\n}\n\n//\n// TableArrayKey\n//\n// Used to store bracket information for TableArray keys\n// loc includes brackets\n//\n// [[ key ]]\n// ^---------^\n//\nexport interface TableArrayKey extends TreeNode {\n type: NodeType.TableArrayKey;\n item: Key;\n}\nexport function isTableArrayKey(node: TreeNode): node is TableArrayKey {\n return node.type === NodeType.TableArrayKey;\n}\n\n//\n// KeyValue\n//\n// Key and Value nodes, with position information on equals sign\n//\n// key=\"value\" # note\n// ^---------^\n//\nexport interface KeyValue extends TreeNode {\n type: NodeType.KeyValue;\n key: Key;\n value: Value;\n\n // Column index (0-based) of the equals sign\n equals: number;\n}\nexport function isKeyValue(node: TreeNode): node is KeyValue {\n return node.type === NodeType.KeyValue;\n}\n\n//\n// Key\n//\n// Store raw key and parts (from dots)\n//\nexport interface Key extends TreeNode {\n type: NodeType.Key;\n raw: string;\n\n // Note: Array for keys with dots\n // e.g. a.b -> raw = 'a.b', value = ['a', 'b']\n value: string[];\n}\nexport function isKey(node: TreeNode): node is Key {\n return node.type === NodeType.Key;\n}\n\n//\n// String\n//\n// loc includes quotes\n//\n// a = \"string\"\n// ^------^\n//\nexport interface String extends TreeNode {\n type: NodeType.String;\n raw: string;\n value: string;\n}\nexport function isString(node: TreeNode): node is String {\n return node.type === NodeType.String;\n}\n\n//\n// Integer\n//\nexport interface Integer extends TreeNode {\n type: NodeType.Integer;\n raw: string;\n value: number;\n}\nexport function isInteger(node: TreeNode): node is Integer {\n return node.type === NodeType.Integer;\n}\n\n//\n// Float\n//\nexport interface Float extends TreeNode {\n type: NodeType.Float;\n raw: string;\n value: number;\n}\nexport function isFloat(node: TreeNode): node is Float {\n return node.type === NodeType.Float;\n}\n\n//\n// Boolean\n//\nexport interface Boolean extends TreeNode {\n type: NodeType.Boolean;\n\n // Only `true` and `false` are permitted\n // -> don't need separate raw and value\n value: boolean;\n}\nexport function isBoolean(node: TreeNode): node is Boolean {\n return node.type === NodeType.Boolean;\n}\n\n//\n// DateTime\n//\n// Note: Currently, Offset Date-Time, Local Date-Time, Local Date, and Local Time\n// are handled via raw\n//\nexport interface DateTime extends TreeNode {\n type: NodeType.DateTime;\n raw: string;\n value: Date;\n}\nexport function isDateTime(node: TreeNode): node is DateTime {\n return node.type === NodeType.DateTime;\n}\n\n//\n// InlineArray\n//\nexport interface InlineArray<TItem = TreeNode> extends TreeNode {\n type: NodeType.InlineArray;\n items: InlineArrayItem<TItem>[];\n}\nexport function isInlineArray(node: TreeNode): node is InlineArray {\n return node.type === NodeType.InlineArray;\n}\n\n//\n// InlineArrayItem\n//\n// loc for InlineArrayItem is from start of value to before comma\n// or end-of-value if no comma\n//\n// [ \"a\" ,\"b\", \"c\" ]\n// ^---^ ^-^ ^-^\n//\nexport interface InlineItem<TItem = TreeNode> extends TreeNode {\n type: NodeType.InlineItem;\n item: TItem;\n comma: boolean;\n}\nexport function isInlineItem(node: TreeNode): node is InlineItem {\n return node.type === NodeType.InlineItem;\n}\n\nexport interface InlineArrayItem<TItem = TreeNode> extends InlineItem<TItem> {}\n\n//\n// InlineTable\n//\nexport interface InlineTable extends TreeNode {\n type: NodeType.InlineTable;\n items: InlineTableItem[];\n}\nexport function isInlineTable(node: TreeNode): node is InlineTable {\n return node.type === NodeType.InlineTable;\n}\n\n//\n// InlineTableItem\n//\n// loc for InlineTableItem follows InlineArrayItem\n//\n// { a=\"b\" , c = \"d\" }\n// ^------^ ^--------^\n//\nexport interface InlineTableItem extends InlineItem<KeyValue> {}\n\n//\n// Comment\n//\n// loc starts at \"#\" and goes to end of comment (trailing whitespace ignored)\n//\n// # comment here\n// ^------------^\n//\nexport interface Comment extends TreeNode {\n type: NodeType.Comment;\n raw: string;\n}\nexport function isComment(node: TreeNode): node is Comment {\n return node.type === NodeType.Comment;\n}\n\n//\n// Combinations\n//\n\nexport interface WithItems extends TreeNode {\n items: TreeNode[];\n}\nexport function hasItems(node: TreeNode): node is WithItems {\n return (\n isDocument(node) ||\n isTable(node) ||\n isTableArray(node) ||\n isInlineTable(node) ||\n isInlineArray(node)\n );\n}\n\nexport interface WithItem extends TreeNode {\n item: TreeNode;\n}\nexport function hasItem(node: TreeNode): node is WithItem {\n return isTableKey(node) || isTableArrayKey(node) || isInlineItem(node);\n}\n\nexport type Block = KeyValue | Table | TableArray | Comment;\nexport function isBlock(node: TreeNode): node is Block {\n return isKeyValue(node) || isTable(node) || isTableArray(node) || isComment(node);\n}\n\nexport type Value<TInlineArrayItem = TreeNode> =\n | String\n | Integer\n | Float\n | Boolean\n | DateTime\n | InlineArray<TInlineArrayItem>\n | InlineTable;\nexport function isValue(node: TreeNode): node is Value {\n return (\n isString(node) ||\n isInteger(node) ||\n isFloat(node) ||\n isBoolean(node) ||\n isDateTime(node) ||\n isInlineArray(node) ||\n isInlineTable(node)\n );\n}\n\nexport interface TreeNode {\n type: NodeType;\n loc: Location;\n}\n","import Cursor, { iterator } from './cursor';\nimport { Location, Locator, createLocate, findPosition } from './location';\nimport ParseError from './parse-error';\n\nexport enum TokenType {\n Bracket = 'Bracket',\n Curly = 'Curly',\n Equal = 'Equal',\n Comma = 'Comma',\n Dot = 'Dot',\n Comment = 'Comment',\n Literal = 'Literal'\n}\n\nexport interface Token {\n type: TokenType;\n raw: string;\n loc: Location;\n}\n\nexport const IS_WHITESPACE = /\\s/;\nexport const IS_NEW_LINE = /(\\r\\n|\\n)/;\nexport const DOUBLE_QUOTE = `\"`;\nexport const SINGLE_QUOTE = `'`;\nexport const SPACE = ' ';\nexport const ESCAPE = '\\\\';\n\nconst IS_VALID_LEADING_CHARACTER = /[\\w,\\d,\\\",\\',\\+,\\-,\\_]/;\n\nexport function* tokenize(input: string): IterableIterator<Token> {\n const cursor = new Cursor(iterator(input));\n cursor.next();\n\n const locate = createLocate(input);\n\n while (!cursor.done) {\n if (IS_WHITESPACE.test(cursor.value!)) {\n // (skip whitespace)\n } else if (cursor.value === '[' || cursor.value === ']') {\n // Handle special characters: [, ], {, }, =, comma\n yield specialCharacter(cursor, locate, TokenType.Bracket);\n } else if (cursor.value === '{' || cursor.value === '}') {\n yield specialCharacter(cursor, locate, TokenType.Curly);\n } else if (cursor.value === '=') {\n yield specialCharacter(cursor, locate, TokenType.Equal);\n } else if (cursor.value === ',') {\n yield specialCharacter(cursor, locate, TokenType.Comma);\n } else if (cursor.value === '.') {\n yield specialCharacter(cursor, locate, TokenType.Dot);\n } else if (cursor.value === '#') {\n // Handle comments = # -> EOL\n yield comment(cursor, locate);\n } else {\n const multiline_char =\n checkThree(input, cursor.index, SINGLE_QUOTE) ||\n checkThree(input, cursor.index, DOUBLE_QUOTE);\n\n if (multiline_char) {\n // Multi-line literals or strings = no escaping\n yield multiline(cursor, locate, multiline_char, input);\n } else {\n yield string(cursor, locate, input);\n }\n }\n\n cursor.next();\n }\n}\n\nfunction specialCharacter(cursor: Cursor<string>, locate: Locator, type: TokenType): Token {\n return { type, raw: cursor.value!, loc: locate(cursor.index, cursor.index + 1) };\n}\n\nfunction comment(cursor: Cursor<string>, locate: Locator): Token {\n const start = cursor.index;\n let raw = cursor.value!;\n while (!cursor.peek().done && !IS_NEW_LINE.test(cursor.peek().value!)) {\n cursor.next();\n raw += cursor.value!;\n }\n\n // Early exit is ok for comment, no closing conditions\n\n return {\n type: TokenType.Comment,\n raw,\n loc: locate(start, cursor.index + 1)\n };\n}\n\nfunction multiline(\n cursor: Cursor<string>,\n locate: Locator,\n multiline_char: string,\n input: string\n): Token {\n const start = cursor.index;\n let quotes = multiline_char + multiline_char + multiline_char;\n let raw = quotes;\n\n // Skip over quotes\n cursor.next();\n cursor.next();\n cursor.next();\n\n // The reason why we need to check if there is more than three is because we have to match the last 3 quotes, not the first 3 that appears consecutively\n // See spec-string-basic-multiline-9.toml\n while (!cursor.done && (!checkThree(input, cursor.index, multiline_char) || CheckMoreThanThree(input, cursor.index, multiline_char))) {\n raw += cursor.value;\n cursor.next();\n }\n\n if (cursor.done) {\n throw new ParseError(\n input,\n findPosition(input, cursor.index),\n `Expected close of multiline string with ${quotes}, reached end of file`\n );\n }\n\n raw += quotes;\n\n cursor.next();\n cursor.next();\n\n return {\n type: TokenType.Literal,\n raw,\n loc: locate(start, cursor.index + 1)\n };\n}\n\nfunction string(cursor: Cursor<string>, locate: Locator, input: string): Token {\n // Remaining possibilities: keys, strings, literals, integer, float, boolean\n //\n // Special cases:\n // \"...\" -> quoted\n // '...' -> quoted\n // \"...\".'...' -> bare\n // 0000-00-00 00:00:00 -> bare\n //\n // See https://github.com/toml-lang/toml#offset-date-time\n //\n // | For the sake of readability, you may replace the T delimiter between date and time with a space (as permitted by RFC 3339 section 5.6).\n // | `odt4 = 1979-05-27 07:32:00Z`\n //\n // From RFC 3339:\n //\n // | NOTE: ISO 8601 defines date and time separated by \"T\".\n // | Applications using this syntax may choose, for the sake of\n // | readability, to specify a full-date and full-time separated by\n // | (say) a space character.\n\n // First, check for invalid characters\n if (!IS_VALID_LEADING_CHARACTER.test(cursor.value!)) {\n throw new ParseError(\n input,\n findPosition(input, cursor.index),\n `Unsupported character \"${cursor.value}\". Expected ALPHANUMERIC, \", ', +, -, or _`\n );\n }\n\n const start = cursor.index;\n let raw = cursor.value!;\n let double_quoted = cursor.value === DOUBLE_QUOTE;\n let single_quoted = cursor.value === SINGLE_QUOTE;\n\n const isFinished = (cursor: Cursor<string>) => {\n if (cursor.peek().done) return true;\n const next_item = cursor.peek().value!;\n\n return (\n !(double_quoted || single_quoted) &&\n (IS_WHITESPACE.test(next_item) ||\n next_item === ',' ||\n next_item === '.' ||\n next_item === ']' ||\n next_item === '}' ||\n next_item === '=' ||\n next_item === '#'\n )\n );\n };\n\n while (!cursor.done && !isFinished(cursor)) {\n cursor.next();\n\n if (cursor.value === DOUBLE_QUOTE) double_quoted = !double_quoted;\n if (cursor.value === SINGLE_QUOTE && !double_quoted) single_quoted = !single_quoted;\n\n raw += cursor.value!;\n\n if (cursor.peek().done) break;\n let next_item = cursor.peek().value!;\n\n // If next character is escape and currently double-quoted,\n // check for escaped quote\n if (double_quoted && cursor.value === ESCAPE) {\n if (next_item === DOUBLE_QUOTE) {\n raw += DOUBLE_QUOTE;\n cursor.next();\n } else if (next_item === ESCAPE) {\n raw += ESCAPE;\n cursor.next();\n }\n }\n }\n\n if (double_quoted || single_quoted) {\n throw new ParseError(\n input,\n findPosition(input, start),\n `Expected close of string with ${double_quoted ? DOUBLE_QUOTE : SINGLE_QUOTE}`\n );\n }\n\n return {\n type: TokenType.Literal,\n raw,\n loc: locate(start, cursor.index + 1)\n };\n}\n\n/**\n * Check if the current character and the next two characters are the same\n * and not escaped.\n *\n * @param input - The input string.\n * @param current - The current index in the input string.\n * @param check - The character to check for.\n * @returns ⚠️The character if found, otherwise false.\n */\nfunction checkThree(input: string, current: number, check: string): false | string {\n if (!check) {\n return false;\n }\n\n const has3 =\n input[current] === check &&\n input[current + 1] === check &&\n input[current + 2] === check;\n\n if (!has3) {\n return false;\n }\n\n // Check if the sequence is escaped\n const precedingText = input.slice(0, current); // Get the text before the current position\n const backslashes = precedingText.match(/\\\\+$/); // Match trailing backslashes\n\n if (!backslashes) {\n return check; // No backslashes means not escaped\n }\n \n const isEscaped = backslashes[0].length % 2 !== 0; // Odd number of backslashes means escaped\n\n return isEscaped ? false : check; // Return `check` if not escaped, otherwise `false`\n}\n\nexport function CheckMoreThanThree(input: string, current: number, check: string): boolean {\n \n if (!check) {\n return false;\n }\n\n return (\n input[current] === check &&\n input[current + 1] === check &&\n input[current + 2] === check &&\n input[current + 3] === check\n )\n\n}\n","export function iterator<T>(value: Iterable<T>): Iterator<T> {\n return value[Symbol.iterator]();\n}\n\n/**\n * Cursor<T>\n * \n * A utility class that wraps an iterator and provides additional functionality\n * such as peeking at the next value without advancing the iterator, tracking\n * the current index, and iterating over the values.\n * \n * @template T - The type of elements in the iterator.\n * \n * Properties:\n * - `iterator`: The underlying iterator being wrapped.\n * - `index`: The current index of the iterator (starts at -1).\n * - `value`: The current value of the iterator.\n * - `done`: A boolean indicating whether the iterator is complete.\n * - `peeked`: The result of peeking at the next value without advancing.\n * \n * Methods:\n * - `next()`: Advances the iterator and returns the next value.\n * - `peek()`: Returns the next value without advancing the iterator.\n * - `[Symbol.iterator]`: Makes the Cursor itself iterable.\n */\nexport default class Cursor<T> implements Iterator<T | undefined> {\n iterator: Iterator<T>;\n index: number;\n value?: T;\n done: boolean;\n peeked: IteratorResult<T | undefined> | null;\n\n constructor(iterator: Iterator<T>) {\n this.iterator = iterator;\n this.index = -1;\n this.value = undefined;\n this.done = false;\n this.peeked = null;\n }\n\n next(): IteratorResult<T | undefined> {\n if (this.done) return done();\n\n const result = this.peeked || this.iterator.next();\n\n this.index += 1;\n this.value = result.value;\n this.done = result.done ?? false;\n this.peeked = null;\n\n return result;\n }\n\n peek(): IteratorResult<T | undefined> {\n if (this.done) return done();\n if (this.peeked) return this.peeked;\n\n this.peeked = this.iterator.next();\n return this.peeked;\n }\n\n [Symbol.iterator]() {\n return this;\n }\n}\n\nfunction done(): IteratorResult<undefined> {\n return { value: undefined, done: true };\n}\n","export interface Location {\n start: Position;\n end: Position;\n}\n\nexport interface Position {\n // Note: line is 1-indexed while column is 0-indexed\n line: number;\n column: number;\n}\n\nexport interface Span {\n lines: number;\n columns: number;\n}\n\nexport function getSpan(location: Location): Span {\n return {\n lines: location.end.line - location.start.line + 1,\n columns: location.end.column - location.start.column\n };\n}\n\nexport type Locator = (start: number, end: number) => Location;\nexport function createLocate(input: string): Locator {\n const lines = findLines(input);\n\n return (start: number, end: number) => {\n return {\n start: findPosition(lines, start),\n end: findPosition(lines, end)\n };\n };\n}\n\nexport function findPosition(input: string | number[], index: number): Position {\n // abc\\ndef\\ng\n // 0123 4567 8\n // 012\n // 0\n //\n // lines = [3, 7, 9]\n //\n // c = 2: 0 -> 1, 2 - (undefined + 1 || 0) = 2\n // 3: 0 -> 1, 3 - (undefined + 1 || 0) = 3\n // e = 5: 1 -> 2, 5 - (3 + 1 || 0) = 1\n // g = 8: 2 -> 3, 8 - (7 + 1 || 0) = 0\n\n const lines = Array.isArray(input) ? input : findLines(input);\n const line = lines.findIndex(line_index => line_index >= index) + 1;\n const column = index - (lines[line - 2] + 1 || 0);\n\n return { line, column };\n}\n\nexport function getLine(input: string, position: Position): string {\n const lines = findLines(input);\n const start = lines[position.line - 2] || 0;\n const end = lines[position.line - 1] || input.length;\n\n return input.substr(start, end - start);\n}\n\nexport function findLines(input: string): number[] {\n // exec is stateful, so create new regexp each time\n const BY_NEW_LINE = /\\r\\n|\\n/g;\n const indexes: number[] = [];\n\n let match;\n while ((match = BY_NEW_LINE.exec(input)) != null) {\n indexes.push(match.index + match[0].length - 1);\n }\n indexes.push(input.length + 1);\n\n return indexes;\n}\n\nexport function clonePosition(position: Position): Position {\n return { line: position.line, column: position.column };\n}\n\nexport function cloneLocation(location: Location): Location {\n return { start: clonePosition(location.start), end: clonePosition(location.end) };\n}\n/**\n * Returns a Position at line 1, column 0.\n * This means that lines are 1-indexed and columns are 0-indexed.\n * \n * @returns A Position at line 1, column 0\n */\nexport function zero(): Position {\n return { line: 1, column: 0 };\n}\n","import { Position, getLine } from './location';\n\nexport default class ParseError extends Error {\n line: number;\n column: number;\n\n constructor(input: string, position: Position, message: string) {\n let error_message = `Error parsing TOML (${position.line}, ${position.column + 1}):\\n`;\n\n if (input) {\n const line = getLine(input, position);\n const pointer = `${whitespace(position.column)}^`;\n\n if (line) error_message += `${line}\\n${pointer}\\n`;\n }\n error_message += message;\n\n super(error_message);\n\n this.line = position.line;\n this.column = position.column;\n }\n}\n\nexport function isParseError(error: Error): error is ParseError {\n return error && Object.prototype.hasOwnProperty.call(error, 'line');\n}\n\nfunction whitespace(count: number, character: string = ' '): string {\n return character.repeat(count);\n}\n","export function last<TValue>(values: TValue[]): TValue | undefined {\n return values[values.length - 1];\n}\n\nexport type BlankObject = { [key: string]: any };\n\nexport function blank(): BlankObject {\n return Object.create(null);\n}\n\nexport function isString(value: any): value is string {\n return typeof value === 'string';\n}\n\nexport function isInteger(value: any): value is number {\n return typeof value === 'number' && value % 1 === 0 && isFinite(value) && !Object.is(value, -0);\n}\n\nexport function isFloat(value: any): value is number {\n return typeof value === 'number' && (!isInteger(value) || !isFinite(value) || Object.is(value, -0));\n}\n\nexport function isBoolean(value: any): value is boolean {\n return typeof value === 'boolean';\n}\n\nexport function isDate(value: any): value is Date {\n return Object.prototype.toString.call(value) === '[object Date]';\n}\n\nexport function isObject(value: any): boolean {\n return value && typeof value === 'object' && !isDate(value) && !Array.isArray(value);\n}\n\nexport function isIterable<T>(value: any): value is Iterable<T> {\n return value != null && typeof value[Symbol.iterator] === 'function';\n}\n\nexport function has(object: any, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(object, key);\n}\n\nexport function arraysEqual<TItem>(a: TItem[], b: TItem[]): boolean {\n if (a.length !== b.length) return false;\n\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n\n return true;\n}\n\nexport function datesEqual(a: any, b: any): boolean {\n return isDate(a) && isDate(b) && a.toISOString() === b.toISOString();\n}\n\nexport function pipe<TValue>(value: TValue, ...fns: Array<(value: TValue) => TValue>): TValue {\n return fns.reduce((value, fn) => fn(value), value);\n}\n\nexport function stableStringify(object: any): string {\n if (isObject(object)) {\n const key_values = Object.keys(object)\n .sort()\n .map(key => `${JSON.stringify(key)}:${stableStringify(object[key])}`);\n\n return `{${key_values.join(',')}}`;\n } else if (Array.isArray(object)) {\n return `[${object.map(stableStringify).join(',')}]`;\n } else {\n return JSON.stringify(object);\n }\n}\n\nexport function merge<TValue>(target: TValue[], values: TValue[]) {\n // __mutating__: merge values into target\n // Reference: https://dev.to/uilicious/javascript-array-push-is-945x-faster-than-array-concat-1oki\n const original_length = target.length;\n const added_length = values.length;\n target.length = original_length + added_length;\n\n for (let i = 0; i < added_length; i++) {\n target[original_length + i] = values[i];\n }\n}\n","import { SINGLE_QUOTE, DOUBLE_QUOTE } from './tokenizer';\nimport { pipe } from './utils';\n\nconst TRIPLE_DOUBLE_QUOTE = `\"\"\"`;\nconst TRIPLE_SINGLE_QUOTE = `'''`;\nconst LF = '\\\\n';\nconst CRLF = '\\\\r\\\\n';\nconst IS_CRLF = /\\r\\n/g;\nconst IS_LF = /\\n/g;\nconst IS_LEADING_NEW_LINE = /^(\\r\\n|\\n)/;\n// This regex is used to match an odd number of backslashes followed by a line ending\n// It uses a negative lookbehind to ensure that the backslash is not preceded by another backslash.\n// We need an odd number of backslashes so that the last one is not escaped.\nconst IS_LINE_ENDING_BACKSLASH = /(?<!\\\\)(?:\\\\\\\\)*(\\\\\\s*[\\n\\r\\n]\\s*)/g;\n\nexport function parseString(raw: string): string {\n if (raw.startsWith(TRIPLE_SINGLE_QUOTE)) {\n return pipe(\n trim(raw, 3),\n trimLeadingWhitespace\n );\n } else if (raw.startsWith(SINGLE_QUOTE)) {\n return trim(raw, 1);\n } else if (raw.startsWith(TRIPLE_DOUBLE_QUOTE)) {\n return pipe(\n trim(raw, 3),\n trimLeadingWhitespace,\n lineEndingBackslash,\n escapeNewLines,\n escapeDoubleQuotes,\n unescapeLargeUnicode\n );\n } else if (raw.startsWith(DOUBLE_QUOTE)) {\n return pipe(\n trim(raw, 1),\n unescapeLargeUnicode\n );\n } else {\n return raw;\n }\n}\n\nexport function escapeDoubleQuotes(value: string): string {\n let result = '';\n let precedingBackslashes = 0;\n\n for (let i = 0; i < value.length; i++) {\n const char = value[i];\n\n if (char === '\"' && precedingBackslashes % 2 === 0) {\n // If the current character is a quote and it is not escaped, escape it\n result += '\\\\\"';\n } else {\n // Otherwise, add the character as is\n result += char;\n }\n\n // Update the count of consecutive backslashes\n if (char === '\\\\') {\n precedingBackslashes++;\n } else {\n precedingBackslashes = 0; // Reset if the character is not a backslash\n }\n }\n\n return result;\n}\n\nexport function unescapeLargeUnicode(escaped: string): string {\n // JSON.parse handles everything except \\UXXXXXXXX\n // replace those instances with code point, escape that, and then parse\n const LARGE_UNICODE = /\\\\U[a-fA-F0-9]{8}/g;\n const json_escaped = escaped.replace(LARGE_UNICODE, value => {\n const code_point = parseInt(value.replace('\\\\U', ''), 16);\n const as_string = String.fromCodePoint(code_point);\n\n return trim(JSON.stringify(as_string), 1);\n });\n\n const fixed_json_escaped = escapeTabsForJSON(json_escaped);\n\n // Parse the properly escaped JSON string\n const parsed = JSON.parse(`\"${fixed_json_escaped}\"`);\n return parsed;\n}\n\nfunction escapeTabsForJSON(value: string): string {\n return value\n .replace(/\\t/g, '\\\\t')\n}\n\nexport function escape(value: string): string {\n return trim(JSON.stringify(value), 1);\n}\n\nfunction trim(value: string, count: number): string {\n return value.slice(count, value.length - count);\n}\n\nfunction trimLeadingWhitespace(value: string): string {\n return value.replace(IS_LEADING_NEW_LINE, '');\n}\n\nfunction escapeNewLines(value: string): string {\n return value.replace(IS_CRLF, CRLF).replace(IS_LF, LF);\n}\n\nfunction lineEndingBackslash(value: string): string {\n return value.replace(IS_LINE_ENDING_BACKSLASH, (match, group) => match.replace(group, ''));\n}\n","import {\n NodeType,\n KeyValue,\n Table,\n TableKey,\n TableArray,\n TableArrayKey,\n Key,\n Value,\n String,\n Integer,\n Float,\n Boolean,\n DateTime,\n InlineTable,\n InlineArray,\n InlineItem,\n Comment,\n AST,\n Block\n} from './ast';\nimport { Token, TokenType, tokenize, DOUBLE_QUOTE, SINGLE_QUOTE } from './tokenizer';\nimport { parseString } from './parse-string';\nimport Cursor from './cursor';\nimport { clonePosition, cloneLocation } from './location';\nimport ParseError from './parse-error';\nimport { merge } from './utils';\n\nconst TRUE = 'true';\nconst FALSE = 'false';\nconst HAS_E = /e/i;\nconst IS_DIVIDER = /\\_/g;\nconst IS_INF = /inf/;\nconst IS_NAN = /nan/;\nconst IS_HEX = /^0x/;\nconst IS_OCTAL = /^0o/;\nconst IS_BINARY = /^0b/;\nexport const IS_FULL_DATE = /(\\d{4})-(\\d{2})-(\\d{2})/;\nexport const IS_FULL_TIME = /(\\d{2}):(\\d{2}):(\\d{2})/;\n\nexport default function* parseTOML(input: string): AST {\n const tokens = tokenize(input);\n const cursor = new Cursor(tokens);\n\n while (!cursor.next().done) {\n yield* walkBlock(cursor, input);\n }\n}\n\nfunction* walkBlock(cursor: Cursor<Token>, input: string): IterableIterator<Block> {\n if (cursor.value!.type === TokenType.Comment) {\n yield comment(cursor);\n } else if (cursor.value!.type === TokenType.Bracket) {\n yield table(cursor, input);\n } else if (cursor.value!.type === TokenType.Literal) {\n yield* keyValue(cursor, input);\n } else {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n `Unexpected token \"${cursor.value!.type}\". Expected Comment, Bracket, or String`\n );\n }\n}\n\nfunction* walkValue(cursor: Cursor<Token>, input: string): IterableIterator<Value | Comment> {\n if (cursor.value!.type === TokenType.Literal) {\n if (cursor.value!.raw[0] === DOUBLE_QUOTE || cursor.value!.raw[0] === SINGLE_QUOTE) {\n yield string(cursor);\n } else if (cursor.value!.raw === TRUE || cursor.value!.raw === FALSE) {\n yield boolean(cursor);\n } else if (IS_FULL_DATE.test(cursor.value!.raw) || IS_FULL_TIME.test(cursor.value!.raw)) {\n yield datetime(cursor, input);\n } else if (\n (!cursor.peek().done && cursor.peek().value!.type === TokenType.Dot) ||\n IS_INF.test(cursor.value!.raw) ||\n IS_NAN.test(cursor.value!.raw) ||\n (HAS_E.test(cursor.value!.raw) && !IS_HEX.test(cursor.value!.raw))\n ) {\n yield float(cursor, input);\n } else {\n yield integer(cursor);\n }\n } else if (cursor.value!.type === TokenType.Curly) {\n yield inlineTable(cursor, input);\n } else if (cursor.value!.type === TokenType.Bracket) {\n const [inline_array, comments] = inlineArray(cursor, input);\n\n yield inline_array;\n yield* comments;\n } else {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n `Unrecognized token type \"${cursor.value!.type}\". Expected String, Curly, or Bracket`\n );\n }\n}\n\nfunction comment(cursor: Cursor<Token>): Comment {\n // # line comment\n // ^------------^ Comment\n return {\n type: NodeType.Comment,\n loc: cursor.value!.loc,\n raw: cursor.value!.raw\n };\n}\n\nfunction table(cursor: Cursor<Token>, input: string): Table | TableArray {\n // Table or TableArray\n //\n // [ key ]\n // ^-----^ TableKey\n // ^-^ Key\n //\n // [[ key ]]\n // ^ ------^ TableArrayKey\n // ^-^ Key\n //\n // a = \"b\" < Items\n // # c |\n // d = \"f\" <\n //\n // ...\n const type =\n !cursor.peek().done && cursor.peek().value!.type === TokenType.Bracket\n ? NodeType.TableArray\n : NodeType.Table;\n const is_table = type === NodeType.Table;\n\n if (is_table && cursor.value!.raw !== '[') {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n `Expected table opening \"[\", found ${cursor.value!.raw}`\n );\n }\n if (!is_table && (cursor.value!.raw !== '[' || cursor.peek().value!.raw !== '[')) {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n `Expected array of tables opening \"[[\", found ${cursor.value!.raw + cursor.peek().value!.raw}`\n );\n }\n\n // Set start location from opening tag\n const key = is_table\n ? ({\n type: NodeType.TableKey,\n loc: cursor.value!.loc\n } as Partial<TableKey>)\n : ({\n type: NodeType.TableArrayKey,\n loc: cursor.value!.loc\n } as Partial<TableArrayKey>);\n\n // Skip to cursor.value for key value\n cursor.next();\n if (type === NodeType.TableArray) cursor.next();\n\n if (cursor.done) {\n throw new ParseError(input, key.loc!.start, `Expected table key, reached end of file`);\n }\n\n key.item = {\n type: NodeType.Key,\n loc: cloneLocation(cursor.value!.loc),\n raw: cursor.value!.raw,\n value: [parseString(cursor.value!.raw)]\n };\n\n while (!cursor.peek().done && cursor.peek().value!.type === TokenType.Dot) {\n cursor.next();\n const dot = cursor.value!;\n\n cursor.next();\n const before = ' '.repeat(dot.loc.start.column - key.item.loc.end.column);\n const after = ' '.repeat(cursor.value!.loc.start.column - dot.loc.end.column);\n\n key.item.loc.end = cursor.value!.loc.end;\n key.item.raw += `${before}.${after}${cursor.value!.raw}`;\n key.item.value.push(parseString(cursor.value!.raw));\n }\n\n cursor.next();\n\n if (is_table && (cursor.done || cursor.value!.raw !== ']')) {\n throw new ParseError(\n input,\n cursor.done ? key.item.loc.end : cursor.value!.loc.start,\n `Expected table closing \"]\", found ${cursor.done ? 'end of file' : cursor.value!.raw}`\n );\n }\n if (\n !is_table &&\n (cursor.done ||\n cursor.peek().done ||\n cursor.value!.raw !== ']' ||\n cursor.peek().value!.raw !== ']')\n ) {\n throw new ParseError(\n input,\n cursor.done || cursor.peek().done ? key.item.loc.end : cursor.value!.loc.start,\n `Expected array of tables closing \"]]\", found ${\n cursor.done || cursor.peek().done\n ? 'end of file'\n : cursor.value!.raw + cursor.peek().value!.raw\n }`\n );\n }\n\n // Set end location from closing tag\n if (!is_table) cursor.next();\n key.loc!.end = cursor.value!.loc.end;\n\n // Add child items\n let items: Array<KeyValue | Comment> = [];\n while (!cursor.peek().done && cursor.peek().value!.type !== TokenType.Bracket) {\n cursor.next();\n merge(items, [...walkBlock(cursor, input)] as Array<KeyValue | Comment>);\n }\n\n return {\n type: is_table ? NodeType.Table : NodeType.TableArray,\n loc: {\n start: clonePosition(key.loc!.start),\n end: items.length\n ? clonePosition(items[items.length - 1].loc.end)\n : clonePosition(key.loc!.end)\n },\n key: key as TableKey | TableArrayKey,\n items\n } as Table | TableArray;\n}\n\nfunction keyValue(cursor: Cursor<Token>, input: string): Array<KeyValue | Comment> {\n // 3. KeyValue\n //\n // key = value\n // ^-^ key\n // ^ equals\n // ^---^ value\n const key: Key = {\n type: NodeType.Key,\n loc: cloneLocation(cursor.value!.loc),\n raw: cursor.value!.raw,\n value: [parseString(cursor.value!.raw)]\n };\n\n while (!cursor.peek().done && cursor.peek().value!.type === TokenType.Dot) {\n cursor.next();\n cursor.next();\n\n key.loc.end = cursor.value!.loc.end;\n key.raw += `.${cursor.value!.raw}`;\n key.value.push(parseString(cursor.value!.raw));\n }\n\n cursor.next();\n\n if (cursor.done || cursor.value!.type !== TokenType.Equal) {\n throw new ParseError(\n input,\n cursor.done ? key.loc.end : cursor.value!.loc.start,\n `Expected \"=\" for key-value, found ${cursor.done ? 'end of file' : cursor.value!.raw}`\n );\n }\n\n const equals = cursor.value!.loc.start.column;\n\n cursor.next();\n\n if (cursor.done) {\n throw new ParseError(input, key.loc.start, `Expected value for key-value, reached end of file`);\n }\n\n const [value, ...comments] = walkValue(cursor, input) as Iterable<Value | Comment>;\n\n return [\n {\n type: NodeType.KeyValue,\n key,\n value: value as Value,\n loc: {\n start: clonePosition(key.loc.start),\n end: clonePosition(value.loc.end)\n },\n equals\n },\n ...(comments as Comment[])\n ];\n}\n\nfunction string(cursor: Cursor<Token>): String {\n return {\n type: NodeType.String,\n loc: cursor.value!.loc,\n raw: cursor.value!.raw,\n value: parseString(cursor.value!.raw)\n };\n}\n\nfunction boolean(cursor: Cursor<Token>): Boolean {\n return {\n type: NodeType.Boolean,\n loc: cursor.value!.loc,\n value: cursor.value!.raw === TRUE\n };\n}\n\nfunction datetime(cursor: Cursor<Token>, input: string): DateTime {\n // Possible values:\n //\n // Offset Date-Time\n // | odt1 = 1979-05-27T07:32:00Z\n // | odt2 = 1979-05-27T00:32:00-07:00\n // | odt3 = 1979-05-27T00:32:00.999999-07:00\n // | odt4 = 1979-05-27 07:32:00Z\n //\n // Local Date-Time\n // | ldt1 = 1979-05-27T07:32:00\n // | ldt2 = 1979-05-27T00:32:00.999999\n //\n // Local Date\n // | ld1 = 1979-05-27\n //\n // Local Time\n // | lt1 = 07:32:00\n // | lt2 = 00:32:00.999999\n let loc = cursor.value!.loc;\n let raw = cursor.value!.raw;\n let value: Date;\n\n // If next token is string,\n // check if raw is full date and following is full time\n if (\n !cursor.peek().done &&\n cursor.peek().value!.type === TokenType.Literal &&\n IS_FULL_DATE.test(raw) &&\n IS_FULL_TIME.test(cursor.peek().value!.raw)\n ) {\n const start = loc.start;\n\n cursor.next();\n loc = { start, end: cursor.value!.loc.end };\n raw += ` ${cursor.value!.raw}`;\n }\n\n if (!cursor.peek().done && cursor.peek().value!.type === TokenType.Dot) {\n const start = loc.start;\n\n cursor.next();\n\n if (cursor.peek().done || cursor.peek().value!.type !== TokenType.Literal) {\n throw new ParseError(input, cursor.value!.loc.end, `Expected fractional value for DateTime`);\n }\n cursor.next();\n\n loc = { start, end: cursor.value!.loc.end };\n raw += `.${cursor.value!.raw}`;\n }\n\n if (!IS_FULL_DATE.test(raw)) {\n // For local time, use local ISO date\n const [local_date] = new Date().toISOString().split('T');\n value = new Date(`${local_date}T${raw}`);\n } else {\n value = new Date(raw.replace(' ', 'T'));\n }\n\n return {\n type: NodeType.DateTime,\n loc,\n raw,\n value\n };\n}\n\nfunction float(cursor: Cursor<Token>, input: string): Float {\n let loc = cursor.value!.loc;\n let raw = cursor.value!.raw;\n let value;\n\n if (IS_INF.test(raw)) {\n value = raw === '-inf' ? -Infinity : Infinity;\n } else if (IS_NAN.test(raw)) {\n value = raw === '-nan' ? -NaN : NaN;\n } else if (!cursor.peek().done && cursor.peek().value!.type === TokenType.Dot) {\n const start = loc.start;\n\n // From spec:\n // | A fractional part is a decimal point followed by one or more digits.\n //\n // -> Don't have to handle \"4.\" (i.e. nothing behind decimal place)\n\n cursor.next();\n\n if (cursor.peek().done || cursor.peek().value!.type !== TokenType.Literal) {\n throw new ParseError(input, cursor.value!.loc.end, `Expected fraction value for Float`);\n }\n cursor.next();\n\n raw += `.${cursor.value!.raw}`;\n loc = { start, end: cursor.value!.loc.end };\n value = Number(raw.replace(IS_DIVIDER, ''));\n } else {\n value = Number(raw.replace(IS_DIVIDER, ''));\n }\n\n return { type: NodeType.Float, loc, raw, value };\n}\n\nfunction integer(cursor: Cursor<Token>): Integer {\n // > Integer values -0 and +0 are valid and identical to an unprefixed zero\n if (cursor.value!.raw === '-0' || cursor.value!.raw === '+0') {\n return {\n type: NodeType.Integer,\n loc: cursor.value!.loc,\n raw: cursor.value!.raw,\n value: 0\n };\n }\n\n let radix = 10;\n if (IS_HEX.test(cursor.value!.raw)) {\n radix = 16;\n } else if (IS_OCTAL.test(cursor.value!.raw)) {\n radix = 8;\n } else if (IS_BINARY.test(cursor.value!.raw)) {\n radix = 2;\n }\n\n const value = parseInt(\n cursor\n .value!.raw.replace(IS_DIVIDER, '')\n .replace(IS_OCTAL, '')\n .replace(IS_BINARY, ''),\n radix\n );\n\n return {\n type: NodeType.Integer,\n loc: cursor.value!.loc,\n raw: cursor.value!.raw,\n value\n };\n}\n\nfunction inlineTable(cursor: Cursor<Token>, input: string): InlineTable {\n if (cursor.value!.raw !== '{') {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n `Expected \"{\" for inline table, found ${cursor.value!.raw}`\n );\n }\n\n // 6. InlineTable\n const value: InlineTable = {\n type: NodeType.InlineTable,\n loc: cloneLocation(cursor.value!.loc),\n items: []\n };\n\n cursor.next();\n\n while (\n !cursor.done &&\n !(cursor.value!.type === TokenType.Curly && (cursor.value as Token).raw === '}')\n ) {\n if ((cursor.value as Token).type === TokenType.Comma) {\n const previous = value.items[value.items.length - 1];\n if (!previous) {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n 'Found \",\" without previous value in inline table'\n );\n }\n\n previous.comma = true;\n previous.loc.end = cursor.value!.loc.start;\n\n cursor.next();\n continue;\n }\n\n const [item] = walkBlock(cursor, input);\n if (item.type !== NodeType.KeyValue) {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n `Only key-values are supported in inline tables, found ${item.type}`\n );\n }\n\n const inline_item: InlineItem<KeyValue> = {\n type: NodeType.InlineItem,\n loc: cloneLocation(item.loc),\n item,\n comma: false\n };\n\n value.items.push(inline_item);\n cursor.next();\n }\n\n if (\n cursor.done ||\n cursor.value!.type !== TokenType.Curly ||\n (cursor.value as Token).raw !== '}'\n ) {\n throw new ParseError(\n input,\n cursor.done ? value.loc.start : cursor.value!.loc.start,\n `Expected \"}\", found ${cursor.done ? 'end of file' : cursor.value!.raw}`\n );\n }\n\n value.loc.end = cursor.value!.loc.end;\n\n return value;\n}\n\nfunction inlineArray(cursor: Cursor<Token>, input: string): [InlineArray, Comment[]] {\n // 7. InlineArray\n if (cursor.value!.raw !== '[') {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n `Expected \"[\" for inline array, found ${cursor.value!.raw}`\n );\n }\n\n const value: InlineArray = {\n type: NodeType.InlineArray,\n loc: cloneLocation(cursor.value!.loc),\n items: []\n };\n let comments: Comment[] = [];\n\n cursor.next();\n\n while (\n !cursor.done &&\n !(cursor.value!.type === TokenType.Bracket && (cursor.value as Token).raw === ']')\n ) {\n if ((cursor.value as Token).type === TokenType.Comma) {\n const previous = value.items[value.items.length - 1];\n if (!previous) {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n 'Found \",\" without previous value for inline array'\n );\n }\n\n previous.comma = true;\n previous.loc.end = cursor.value!.loc.start;\n } else if ((cursor.value as Token).type === TokenType.Comment) {\n comments.push(comment(cursor));\n } else {\n const [item, ...additional_comments] = walkValue(cursor, input);\n const inline_item: InlineItem = {\n type: NodeType.InlineItem,\n loc: cloneLocation(item.loc),\n item,\n comma: false\n };\n\n value.items.push(inline_item);\n merge(comments, additional_comments as Comment[]);\n }\n\n cursor.next();\n }\n\n if (\n cursor.done ||\n cursor.value!.type !== TokenType.Bracket ||\n (cursor.value as Token).raw !== ']'\n ) {\n throw new ParseError(\n input,\n cursor.done ? value.loc.start : cursor.value!.loc.start,\n `Expected \"]\", found ${cursor.done ? 'end of file' : cursor.value!.raw}`\n );\n }\n\n value.loc.end = cursor.value!.loc.end;\n\n return [value, comments];\n}\n","import {\n NodeType,\n AST,\n TreeNode,\n Document,\n Table,\n TableKey,\n TableArray,\n TableArrayKey,\n KeyValue,\n Key,\n String,\n Integer,\n Float,\n Boolean,\n DateTime,\n Comment,\n InlineArray,\n InlineTable,\n InlineItem\n} from './ast';\nimport { isIterable } from './utils';\n\nexport type Visit<TNode = TreeNode> = (node: TNode, parent: TNode | null) => void;\nexport type EnterExit<TNode = TreeNode> = { enter?: Visit<TNode>; exit?: Visit<TNode> };\n\nexport type Visitor = {\n Document?: Visit<Document> | EnterExit<Document>;\n Table?: Visit<Table> | EnterExit<Table>;\n TableKey?: Visit<TableKey> | EnterExit<TableKey>;\n TableArray?: Visit<TableArray> | EnterExit<TableArray>;\n TableArrayKey?: Visit<TableArrayKey> | EnterExit<TableArrayKey>;\n KeyValue?: Visit<KeyValue> | EnterExit<KeyValue>;\n Key?: Visit<Key> | EnterExit<Key>;\n String?: Visit<String> | EnterExit<String>;\n Integer?: Visit<Integer> | EnterExit<Integer>;\n Float?: Visit<Float> | EnterExit<Float>;\n Boolean?: Visit<Boolean> | EnterExit<Boolean>;\n DateTime?: Visit<DateTime> | EnterExit<DateTime>;\n InlineArray?: Visit<InlineArray> | EnterExit<InlineArray>;\n InlineItem?: Visit<InlineItem> | EnterExit<InlineItem>;\n InlineTable?: Visit<InlineTable> | EnterExit<InlineTable>;\n Comment?: Visit<Comment> | EnterExit<Comment>;\n};\n\n////////////////////////////////////////////////////////////////////////////////\n// The traverse function is used to walk the AST and call the visitor functions\n////////////////////////////////////////////////////////////////////////////////\nexport default function traverse(ast: AST | TreeNode, visitor: Visitor) {\n if (isIterable(ast)) {\n traverseArray(ast, null);\n } else {\n traverseNode(ast, null);\n }\n\n function traverseArray(array: Iterable<TreeNode>, parent: TreeNode | null) {\n for (const node of array) {\n traverseNode(node, parent);\n }\n }\n\n function traverseNode(node: TreeNode, parent: TreeNode | null) {\n const visit = visitor[node.type];\n\n if (visit && typeof visit === 'function') {\n (visit as Visit)(node, parent);\n }\n\n if (visit && (visit as EnterExit).enter) {\n (visit as EnterExit).enter!(node, parent);\n }\n\n switch (node.type) {\n case NodeType.Document:\n traverseArray((node as Document).items, node);\n break;\n\n case NodeType.Table:\n traverseNode((node as Table).key, node);\n traverseArray((node as Table).items, node);\n break;\n case NodeType.TableKey:\n traverseNode((node as TableKey).item, node);\n break;\n\n case NodeType.TableArray:\n traverseNode((node as TableArray).key, node);\n traverseArray((node as TableArray).items, node);\n break;\n case NodeType.TableArrayKey:\n traverseNode((node as TableArrayKey).item, node);\n break;\n\n case NodeType.KeyValue:\n traverseNode((node as KeyValue).key, node);\n traverseNode((node as KeyValue).value, node);\n break;\n\n case NodeType.InlineArray:\n traverseArray((node as InlineArray).items, node);\n break;\n case NodeType.InlineItem:\n traverseNode((node as InlineItem).item, node);\n break;\n\n case NodeType.InlineTable:\n traverseArray((node as InlineTable).items, node);\n break;\n\n case NodeType.Key:\n case NodeType.String:\n case NodeType.Integer:\n case NodeType.Float:\n case NodeType.Boolean:\n case NodeType.DateTime:\n case NodeType.Comment:\n break;\n\n default:\n throw new Error(`Unrecognized node type \"${node.type}\"`);\n }\n\n if (visit && (visit as EnterExit).exit) {\n (visit as EnterExit).exit!(node, parent);\n }\n }\n}\n","import {\n NodeType,\n TreeNode,\n Document,\n Key,\n Value,\n InlineArray,\n InlineArrayItem,\n InlineTableItem,\n isKeyValue,\n isTable,\n isTableArray,\n isInlineTable,\n isInlineArray,\n hasItems,\n hasItem,\n isComment,\n isDocument,\n InlineTable,\n TableArray,\n Table,\n KeyValue,\n Comment,\n InlineItem,\n isInlineItem,\n Block,\n isBlock\n} from './ast';\nimport { Span, getSpan, clonePosition } from './location';\nimport { last } from './utils';\nimport traverse from './traverse';\n\n////////////////////////////////////////\n// The purpose of this file is to provide a way to modify the AST\n////////////////////////////////////////\n\n// Root node of the AST\nexport type Root = Document | TreeNode;\n\n// Store line and column offsets per node\n//\n// Some offsets are applied on enter (e.g. shift child items and next items)\n// Others are applied on exit (e.g. shift next items)\ntype Offsets = WeakMap<TreeNode, Span>;\n\nconst enter_offsets: WeakMap<Root, Offsets> = new WeakMap();\nconst getEnterOffsets = (root: Root) => {\n if (!enter_offsets.has(root)) {\n enter_offsets.set(root, new WeakMap());\n }\n return enter_offsets.get(root)!;\n};\n\nconst exit_offsets: WeakMap<Root, Offsets> = new WeakMap();\nconst getExitOffsets = (root: Root) => {\n if (!exit_offsets.has(root)) {\n exit_offsets.set(root, new WeakMap());\n }\n return exit_offsets.get(root)!;\n};\n//TODO: Add getOffsets function to get all offsets contained in the tree\nexport function replace(root: Root, parent: TreeNode, existing: TreeNode, replacement: TreeNode) {\n // First, replace existing node\n // (by index for items, item, or key/value)\n if (hasItems(parent)) {\n\n const index = parent.items.indexOf(existing);\n if (index < 0) {\n throw new Error(`Could not find existing item in parent node for replace`);\n }\n\n parent.items.splice(index, 1, replacement);\n\n // This next case is a special case for Inline-Table item\n // however due to the fact that both replacement of the whole Inline-Table and Inline-Table element will have the same parent,\n // we need to make sure it's not an Inline-Table \n } else if (isKeyValue(parent) && isInlineTable(parent.value) && !isInlineTable(existing)) {\n \n const index = parent.value.items.indexOf(existing as InlineTableItem);\n if (index < 0) {\n throw new Error(`Could not find existing item in parent node for replace`);\n } \n parent.value.items.splice(index, 1, replacement as InlineTableItem);\n\n } else if (hasItem(parent)) {\n\n parent.item = replacement;\n\n } else if (isKeyValue(parent)) {\n\n if (parent.key === existing) {\n parent.key = replacement as Key;\n } else {\n parent.value = replacement as Value;\n }\n\n } else {\n throw new Error(`Unsupported parent type \"${parent.type}\" for replace`);\n }\n\n // Shift the replacement node into the same start position as existing\n const shift = {\n lines: existing.loc.start.line - replacement.loc.start.line,\n columns: existing.loc.start.column - replacement.loc.start.column\n };\n shiftNode(replacement, shift);\n\n // Apply offsets after replacement node\n const existing_span = getSpan(existing.loc);\n const replacement_span = getSpan(replacement.loc);\n const offset = {\n lines: replacement_span.lines - existing_span.lines,\n columns: replacement_span.columns - existing_span.columns\n };\n\n addOffset(offset, getExitOffsets(root), replacement, existing);\n}\n/**\n * Inserts a child node into the AST.\n *\n * @param root - The root node of the AST\n * @param parent - The parent node to insert the child into\n * @param child - The child node to insert\n * @param index - The index at which to insert the child (optional)\n */\nexport function insert(root: Root, parent: TreeNode, child: TreeNode, index?: number) {\n if (!hasItems(parent)) {\n throw new Error(`Unsupported parent type \"${(parent as TreeNode).type}\" for insert`);\n }\n\n index = (index != null && typeof index === 'number') ? index : parent.items.length; \n\n let shift: Span;\n let offset: Span;\n if (isInlineArray(parent) || isInlineTable(parent)) {\n ({ shift, offset } = insertInline(parent, child as InlineItem, index));\n } else {\n ({ shift, offset } = insertOnNewLine(\n parent as Document | Table | TableArray,\n child as KeyValue | Comment,\n index\n ));\n }\n\n shiftNode(child, shift);\n\n // The child element is placed relative to the previous element,\n // if the previous element has an offset, need to position relative to that\n // -> Move previous offset to child's offset\n const previous = parent.items[index - 1];\n const previous_offset = previous && getExitOffsets(root).get(previous);\n if (previous_offset) {\n offset.lines += previous_offset.lines;\n offset.columns += previous_offset.columns;\n\n getExitOffsets(root).delete(previous!);\n }\n\n const offsets = getExitOffsets(root);\n offsets.set(child, offset);\n}\n\nfunction insertOnNewLine(\n parent: Document | Table | TableArray,\n child: Block,\n index: number\n): { shift: Span; offset: Span } {\n if (!isBlock(child)) {\n throw new Error(`Incompatible child type \"${(child as TreeNode).type}\"`);\n }\n\n const previous = parent.items[index - 1];\n const use_first_line = isDocument(parent) && !parent.items.length;\n\n parent.items.splice(index, 0, child);\n\n // Set start location from previous item or start of array\n // (previous is undefined for empty array or inserting at first item)\n const start = previous\n ? {\n line: previous.loc.end.line,\n column: !isComment(previous) ? previous.loc.start.column : parent.loc.start.column\n }\n : clonePosition(parent.loc.start);\n \n //TODO: Check the definition for block to see if using isBlock is more appropriate\n const is_block = isTable(child) || isTableArray(child);\n let leading_lines = 0;\n if (use_first_line) {\n // 0 leading lines\n } else if (is_block) {\n leading_lines = 2;\n } else {\n leading_lines = 1;\n }\n start.line += leading_lines;\n\n const shift = {\n lines: start.line - child.loc.start.line,\n columns: start.column - child.loc.start.column\n };\n\n // Apply offsets after child node\n const child_span = getSpan(child.loc);\n const offset = {\n lines: child_span.lines + (leading_lines - 1),\n columns: child_span.columns\n };\n\n return { shift, offset };\n}\n\n/**\n * Inserts an inline element into an inline array or table at the specified index.\n * This function handles positioning, comma management, and offset calculation for the inserted item.\n * \n * @param parent - The inline array or table where the child will be inserted\n * @param child - The inline item to insert\n * @param index - The index position where to insert the child\n * @returns An object containing shift and offset spans:\n * - shift: Adjustments needed to position the child correctly\n * - offset: Adjustments needed for elements that follow the insertion\n * @throws Error if the child is not a compatible inline item type\n */\nfunction insertInline(\n parent: InlineArray | InlineTable,\n child: InlineItem,\n index: number\n): { shift: Span; offset: Span } {\n if (!isInlineItem(child)) {\n throw new Error(`Incompatible child type \"${(child as TreeNode).type}\"`);\n }\n\n // Store preceding node and insert\n const previous = index != null ? parent.items[index - 1] : last(parent.items);\n const is_last = index == null || index === parent.items.length;\n\n parent.items.splice(index, 0, child);\n\n // Add commas as-needed\n const has_seperating_comma_before = !!previous;\n const has_seperating_comma_after = !is_last;\n const has_trailing_comma = is_last && child.comma === true;\n if (has_seperating_comma_before) {\n previous!.comma = true;\n }\n if (has_seperating_comma_after) {\n child.comma = true;\n }\n\n // Use a new line for documents, children of Table/TableArray,\n // and if an inline table is using new lines\n const use_new_line = isInlineArray(parent) && perLine(parent);\n\n // Set start location from previous item or start of array\n // (previous is undefined for empty array or inserting at first item)\n const start = previous\n ? {\n line: previous.loc.end.line,\n column: use_new_line\n ? !isComment(previous)\n ? previous.loc.start.column\n : parent.loc.start.column\n : previous.loc.end.column\n }\n : clonePosition(parent.loc.start);\n\n let leading_lines = 0;\n if (use_new_line) {\n leading_lines = 1;\n } else {\n const skip_comma = 2;\n const skip_bracket = 1;\n start.column += has_seperating_comma_before ? skip_comma : skip_bracket;\n }\n start.line += leading_lines;\n\n const shift = {\n lines: start.line - child.loc.start.line,\n columns: start.column - child.loc.start.column\n };\n\n // Apply offsets after child node\n const child_span = getSpan(child.loc);\n const offset = {\n lines: child_span.lines + (leading_lines - 1),\n columns: child_span.columns + (has_seperating_comma_before || has_seperating_comma_after ? 2 : 0) + (has_trailing_comma ? 1 : 0)\n };\n\n return { shift, offset };\n}\n\nexport function remove(root: Root, parent: TreeNode, node: TreeNode) {\n // Remove an element from the parent's items\n // (supports Document, Table, TableArray, InlineTable, and InlineArray\n //\n // X\n // [ 1, 2, 3 ]\n // ^-^\n // -> Remove element 2 and apply 0,-3 offset to 1\n //\n // [table]\n // a = 1\n // b = 2 # X\n // c = 3\n // -> Remove element 2 and apply -1,0 offset to 1\n if (!hasItems(parent)) {\n throw new Error(`Unsupported parent type \"${parent.type}\" for remove`);\n }\n\n let index = parent.items.indexOf(node);\n if (index < 0) {\n // Try again, looking at child items for nodes like InlineArrayItem\n index = parent.items.findIndex(item => hasItem(item) && item.item === node);\n\n if (index < 0) {\n throw new Error('Could not find node in parent for removal');\n }\n\n node = parent.items[index];\n }\n\n const previous = parent.items[index - 1];\n let next = parent.items[index + 1];\n\n // Remove node\n parent.items.splice(index, 1);\n let removed_span = getSpan(node.loc);\n\n // Remove an associated comment that appears on the same line\n //\n // [table]\n // a = 1\n // b = 2 # remove this too\n // c = 3\n //\n // TODO InlineTable - this only applies to comments in Table/TableArray\n if (next && isComment(next) && next.loc.start.line === node.loc.end.line) {\n // Add comment to removed\n removed_span = getSpan({ start: node.loc.start, end: next.loc.end });\n\n // Shift to next item\n // (use same index since node has already been removed)\n next = parent.items[index + 1];\n\n // Remove comment\n parent.items.splice(index, 1);\n }\n\n // For inline tables and arrays, check whether the line should be kept\n const is_inline = previous && isInlineItem(previous) || next && isInlineItem(next);\n const previous_on_same_line = previous && previous.loc.end.line === node.loc.start.line;\n const next_on_sameLine = next && next.loc.start.line === node.loc.end.line;\n const keep_line = is_inline && (previous_on_same_line || next_on_sameLine);\n\n const offset = {\n lines: -(removed_span.lines - (keep_line ? 1 : 0)),\n columns: -removed_span.columns\n };\n\n // If there is nothing left, don't perform any offsets\n if(previous === undefined && next === undefined) {\n offset.lines = 0;\n offset.columns = 0;\n }\n\n // Offset for comma and remove comma that appear in front of the element (if-needed)\n if (is_inline && previous_on_same_line) {\n offset.columns -= 2;\n }\n\n // If first element in array/inline-table, remove space for comma and space after element\n if (is_inline && !previous && next) {\n offset.columns -= 2;\n }\n\n if (is_inline && previous && !next) {\n (previous as InlineArrayItem | InlineTableItem).comma = false;\n }\n\n // Apply offsets after preceding node or before children of parent node\n const target = previous || parent;\n const target_offsets = previous ? getExitOffsets(root) : getEnterOffsets(root);\n const node_offsets = getExitOffsets(root);\n const previous_offset = target_offsets.get(target);\n if (previous_offset) {\n offset.lines += previous_offset.lines;\n offset.columns += previous_offset.columns;\n }\n const removed_offset = node_offsets.get(node);\n if (removed_offset) {\n offset.lines += removed_offset.lines;\n offset.columns += removed_offset.columns;\n }\n\n target_offsets.set(target, offset);\n}\n\nexport function applyBracketSpacing(\n root: Root,\n node: InlineArray | InlineTable,\n bracket_spacing: boolean = true\n) {\n // Can only add bracket spacing currently\n if (!bracket_spacing) return;\n if (!node.items.length) return;\n\n // Apply enter to node so that items are affected\n addOffset({ lines: 0, columns: 1 }, getEnterOffsets(root), node);\n\n // Apply exit to last node in items\n const last_item = last(node.items as TreeNode[])!;\n addOffset({ lines: 0, columns: 1 }, getExitOffsets(root), last_item);\n}\n\nexport function applyTrailingComma(\n root: Root,\n node: InlineArray | InlineTable,\n trailing_commas: boolean = false\n) {\n // Can only add trailing comma currently\n if (!trailing_commas) return;\n if (!node.items.length) return;\n\n const last_item = last(node.items)!;\n last_item.comma = true;\n\n addOffset({ lines: 0, columns: 1 }, getExitOffsets(root), last_item);\n}\n\n/**\n * Applies all accumulated write offsets (enter and exit) to the given AST node.\n * This function adjusts the start and end locations of each node in the tree based on\n * the offsets stored in the `enter` and `exit` maps. It ensures that the tree's location\n * data is consistent after modifications.\n *\n * @param root - The root node of the AST tree to which the write offsets will be applied.\n */\nexport function applyWrites(root: TreeNode) {\n const enter = getEnterOffsets(root);\n const exit = getExitOffsets(root);\n\n const offset: { lines: number; columns: { [index: number]: number } } = {\n lines: 0,\n columns: {}\n };\n\n function shiftStart(node: TreeNode) {\n\n const lineOffset = offset.lines;\n node.loc.start.line += lineOffset;\n \n const columnOffset = offset.columns[node.loc.start.line] || 0;\n node.loc.start.column += columnOffset\n\n const entering = enter.get(node);\n if (entering) {\n offset.lines += entering.lines;\n offset.columns[node.loc.start.line] =\n (offset.columns[node.loc.start.line] || 0) + entering.columns;\n }\n }\n\n function shiftEnd(node: TreeNode) {\n\n const lineOffset = offset.lines;\n node.loc.end.line += lineOffset;\n \n const columnOffset = offset.columns[node.loc.end.line] || 0;\n node.loc.end.column += columnOffset;\n\n const exiting = exit.get(node);\n if (exiting) {\n offset.lines += exiting.lines;\n offset.columns[node.loc.end.line] =\n (offset.columns[node.loc.end.line] || 0) + exiting.columns;\n }\n }\n\n const shiftLocation = {\n enter: shiftStart,\n exit: shiftEnd\n };\n\n traverse(root, {\n [NodeType.Document]: shiftLocation,\n [NodeType.Table]: shiftLocation,\n [NodeType.TableArray]: shiftLocation,\n [NodeType.InlineTable]: shiftLocation,\n [NodeType.InlineArray]: shiftLocation,\n\n [NodeType.InlineItem]: shiftLocation,\n [NodeType.TableKey]: shiftLocation,\n [NodeType.TableArrayKey]: shiftLocation,\n\n [NodeType.KeyValue]: {\n enter(node) {\n const start_line = node.loc.start.line + offset.lines;\n const key_offset = exit.get(node.key);\n node.equals += (offset.columns[start_line] || 0) + (key_offset ? key_offset.columns : 0);\n\n shiftStart(node);\n },\n exit: shiftEnd\n },\n\n [NodeType.Key]: shiftLocation,\n [NodeType.String]: shiftLocation,\n [NodeType.Integer]: shiftLocation,\n [NodeType.Float]: shiftLocation,\n [NodeType.Boolean]: shiftLocation,\n [NodeType.DateTime]: shiftLocation,\n [NodeType.Comment]: shiftLocation\n });\n\n enter_offsets.delete(root);\n exit_offsets.delete(root);\n}\n\nexport function shiftNode(\n node: TreeNode,\n span: Span,\n options: { first_line_only?: boolean } = {}\n): TreeNode {\n const { first_line_only = false } = options;\n const start_line = node.loc.start.line;\n const { lines, columns } = span;\n const move = (node: TreeNode) => {\n if (!first_line_only || node.loc.start.line === start_line) {\n node.loc.start.column += columns;\n node.loc.end.column += columns;\n }\n node.loc.start.line += lines;\n node.loc.end.line += lines;\n };\n\n traverse(node, {\n [NodeType.Table]: move,\n [NodeType.TableKey]: move,\n [NodeType.TableArray]: move,\n [NodeType.TableArrayKey]: move,\n [NodeType.KeyValue](node) {\n move(node);\n node.equals += columns;\n },\n [NodeType.Key]: move,\n [NodeType.String]: move,\n [NodeType.Integer]: move,\n [NodeType.Float]: move,\n [NodeType.Boolean]: move,\n [NodeType.DateTime]: move,\n [NodeType.InlineArray]: move,\n [NodeType.InlineItem]: move,\n [NodeType.InlineTable]: move,\n [NodeType.Comment]: move\n });\n\n return node;\n}\n\nfunction perLine(array: InlineArray): boolean {\n if (!array.items.length) return false;\n\n const span = getSpan(array.loc);\n return span.lines > array.items.length;\n}\n\nfunction addOffset(offset: Span, offsets: Offsets, node: TreeNode, from?: TreeNode) {\n const previous_offset = offsets.get(from || node);\n if (previous_offset) {\n offset.lines += previous_offset.lines;\n offset.columns += previous_offset.columns;\n }\n\n offsets.set(node, offset);\n}\n","import {\n NodeType,\n Document,\n Table,\n TableKey,\n TableArray,\n TableArrayKey,\n Value,\n KeyValue,\n Key,\n String,\n Integer,\n Float,\n Boolean,\n DateTime,\n InlineArray,\n InlineItem,\n InlineTable,\n Comment\n} from './ast';\nimport { zero, cloneLocation, clonePosition } from './location';\nimport { shiftNode } from './writer';\n\n/**\n * Generates a new TOML document node.\n *\n * @returns A new Document node.\n */\nexport function generateDocument(): Document {\n return {\n type: NodeType.Document,\n loc: { start: zero(), end: zero() },\n items: []\n };\n}\n\nexport function generateTable(key: string[]): Table {\n const table_key = generateTableKey(key);\n\n return {\n type: NodeType.Table,\n loc: cloneLocation(table_key.loc),\n key: table_key,\n items: []\n };\n}\n\nexport function generateTableKey(key: string[]): TableKey {\n const raw = keyValueToRaw(key);\n\n return {\n type: NodeType.TableKey,\n loc: {\n start: zero(),\n end: { line: 1, column: raw.length + 2 }\n },\n item: {\n type: NodeType.Key,\n loc: {\n start: { line: 1, column: 1 },\n end: { line: 1, column: raw.length + 1 }\n },\n value: key,\n raw\n }\n };\n}\n\nexport function generateTableArray(key: string[]): TableArray {\n const table_array_key = generateTableArrayKey(key);\n\n return {\n type: NodeType.TableArray,\n loc: cloneLocation(table_array_key.loc),\n key: table_array_key,\n items: []\n };\n}\n\nexport function generateTableArrayKey(key: string[]): TableArrayKey {\n const raw = keyValueToRaw(key);\n\n return {\n type: NodeType.TableArrayKey,\n loc: {\n start: zero(),\n end: { line: 1, column: raw.length + 4 }\n },\n item: {\n type: NodeType.Key,\n loc: {\n start: { line: 1, column: 2 },\n end: { line: 1, column: raw.length + 2 }\n },\n value: key,\n raw\n }\n };\n}\n\nexport function generateKeyValue(key: string[], value: Value): KeyValue {\n const key_node = generateKey(key);\n const { column } = key_node.loc.end;\n\n const equals = column + 1;\n\n shiftNode(\n value,\n { lines: 0, columns: column + 3 - value.loc.start.column },\n { first_line_only: true }\n );\n\n return {\n type: NodeType.KeyValue,\n loc: {\n start: clonePosition(key_node.loc.start),\n end: clonePosition(value.loc.end)\n },\n key: key_node,\n equals,\n value\n };\n}\n\nconst IS_BARE_KEY = /^[\\w-]+$/;\nfunction keyValueToRaw(value: string[]): string {\n return value.map(part => (IS_BARE_KEY.test(part) ? part : JSON.stringify(part))).join('.');\n}\n\nexport function generateKey(value: string[]): Key {\n const raw = keyValueToRaw(value);\n\n return {\n type: NodeType.Key,\n loc: { start: zero(), end: { line: 1, column: raw.length } },\n raw,\n value\n };\n}\n\nexport function generateString(value: string): String {\n const raw = JSON.stringify(value);\n\n return {\n type: NodeType.String,\n loc: { start: zero(), end: { line: 1, column: raw.length } },\n raw,\n value\n };\n}\n\nexport function generateInteger(value: number): Integer {\n const raw = value.toString();\n\n return {\n type: NodeType.Integer,\n loc: { start: zero(), end: { line: 1, column: raw.length } },\n raw,\n value\n };\n}\n\nexport function generateFloat(value: number): Float {\n let raw: string;\n \n if (value === Infinity) {\n raw = 'inf';\n } else if (value === -Infinity) {\n raw = '-inf';\n } else if (Number.isNaN(value)) {\n raw = 'nan';\n } else if (Object.is(value, -0)) {\n raw = '-0.0';\n } else {\n raw = value.toString();\n }\n\n return {\n type: NodeType.Float,\n loc: { start: zero(), end: { line: 1, column: raw.length } },\n raw,\n value\n };\n}\n\nexport function generateBoolean(value: boolean): Boolean {\n return {\n type: NodeType.Boolean,\n loc: { start: zero(), end: { line: 1, column: value ? 4 : 5 } },\n value\n };\n}\n\nexport function generateDateTime(value: Date): DateTime {\n const raw = value.toISOString();\n\n return {\n type: NodeType.DateTime,\n loc: { start: zero(), end: { line: 1, column: raw.length } },\n raw,\n value\n };\n}\n\nexport function generateInlineArray(): InlineArray {\n return {\n type: NodeType.InlineArray,\n loc: { start: zero(), end: { line: 1, column: 2 } },\n items: []\n };\n}\n\nexport function generateInlineItem(item: KeyValue | Value): InlineItem {\n return {\n type: NodeType.InlineItem,\n loc: cloneLocation(item.loc),\n item,\n comma: false\n };\n}\n\nexport function generateInlineTable(): InlineTable {\n return {\n type: NodeType.InlineTable,\n loc: { start: zero(), end: { line: 1, column: 2 } },\n items: []\n };\n}\n\nexport function generateComment(comment: string): Comment {\n if (!comment.startsWith('#')) comment = `# ${comment}`;\n\n return {\n type: NodeType.Comment,\n loc: { start: zero(), end: { line: 1, column: comment.length } },\n raw: comment\n };\n}\n","import {\n KeyValue,\n Table,\n InlineTable,\n TableArray,\n InlineArray,\n isInlineTable,\n isInlineArray,\n isKeyValue,\n Document\n} from './ast';\nimport { generateTable, generateDocument, generateTableArray } from './generate';\nimport { insert, remove, applyWrites, shiftNode } from './writer';\n\nexport interface Format {\n printWidth?: number;\n tabWidth?: number;\n useTabs?: boolean;\n trailingComma?: boolean;\n bracketSpacing?: boolean;\n}\n\nexport function formatTopLevel(document: Document): Document {\n const move_to_top_level = document.items.filter(item => {\n if (!isKeyValue(item)) return false;\n\n const is_inline_table = isInlineTable(item.value);\n const is_inline_array =\n isInlineArray(item.value) &&\n item.value.items.length &&\n isInlineTable(item.value.items[0].item);\n\n return is_inline_table || is_inline_array;\n }) as KeyValue[];\n\n move_to_top_level.forEach(node => {\n remove(document, document, node);\n\n if (isInlineTable(node.value)) {\n insert(document, document, formatTable(node));\n } else {\n formatTableArray(node).forEach(table_array => {\n insert(document, document, table_array);\n });\n }\n });\n\n applyWrites(document);\n return document;\n}\n\nfunction formatTable(key_value: KeyValue): Table {\n const table = generateTable(key_value.key.value);\n\n for (const item of (key_value.value as InlineTable).items) {\n insert(table, table, item.item);\n }\n\n applyWrites(table);\n return table;\n}\n\nfunction formatTableArray(key_value: KeyValue): TableArray[] {\n const root = generateDocument();\n\n for (const inline_array_item of (key_value.value as InlineArray).items) {\n const table_array = generateTableArray(key_value.key.value);\n insert(root, root, table_array);\n\n for (const inline_table_item of (inline_array_item.item as InlineTable).items) {\n insert(root, table_array, inline_table_item.item);\n }\n }\n\n applyWrites(root);\n return root.items as TableArray[];\n}\n\nexport function formatPrintWidth(document: Document, format: Format): Document {\n // TODO\n return document;\n}\n\nexport function formatEmptyLines(document: Document): Document {\n let shift = 0;\n let previous = 0;\n for (const item of document.items) {\n if (previous === 0 && item.loc.start.line > 1) {\n // Remove leading newlines\n shift = 1 - item.loc.start.line;\n } else if (item.loc.start.line + shift > previous + 2) {\n shift += previous + 2 - (item.loc.start.line + shift);\n }\n\n shiftNode(item, {\n lines: shift,\n columns: 0\n });\n previous = item.loc.end.line;\n }\n\n return document;\n}\n","import { Value, KeyValue, Document, InlineArray, InlineTable } from './ast';\nimport {\n generateDocument,\n generateKeyValue,\n generateInlineItem,\n generateString,\n generateInteger,\n generateFloat,\n generateBoolean,\n generateDateTime,\n generateInlineArray,\n generateInlineTable\n} from './generate';\nimport { Format, formatTopLevel, formatPrintWidth, formatEmptyLines } from './format';\nimport { isObject, isString, isInteger, isFloat, isBoolean, isDate, pipe } from './utils';\nimport { insert, applyWrites, applyBracketSpacing, applyTrailingComma } from './writer';\n\nconst default_format = {\n printWidth: 80,\n trailingComma: false,\n bracketSpacing: true\n};\n\nexport default function parseJS(value: any, format: Format = {}): Document {\n format = Object.assign({}, default_format, format);\n value = toJSON(value);\n\n // Reorder the elements in the object\n value = reorderElements(value);\n\n const document = generateDocument();\n for (const item of walkObject(value, format)) {\n insert(document, document, item);\n }\n applyWrites(document);\n\n // Heuristics:\n // 1. Top-level objects/arrays should be tables/table arrays\n // 2. Convert objects/arrays to tables/table arrays based on print width\n const formatted = pipe(\n document,\n formatTopLevel,\n document => formatPrintWidth(document, format),\n formatEmptyLines\n );\n\n return formatted;\n}\n\n/** \nThis function makes sure that properties that are simple values (not objects or arrays) are ordered first,\nand that objects and arrays are ordered last. This makes parseJS more reliable and easier to test.\n*/\nfunction reorderElements(value:any) : Object {\n // Pre-sort keys to avoid multiple iterations\n const simpleKeys: string[] = [];\n const complexKeys: string[] = [];\n \n // Separate keys in a single pass\n for (const key in value) {\n if (isObject(value[key]) || Array.isArray(value[key])) {\n complexKeys.push(key);\n } else {\n simpleKeys.push(key);\n }\n }\n \n // Create result with the correct order\n const result: Record<string, any> = {};\n \n // Add simple values first\n for (let i = 0; i < simpleKeys.length; i++) {\n const key = simpleKeys[i];\n result[key] = value[key];\n }\n \n // Then add complex values\n for (let i = 0; i < complexKeys.length; i++) {\n const key = complexKeys[i];\n result[key] = value[key];\n }\n \n return result;\n}\n\nfunction* walkObject(object: any, format: Format): IterableIterator<KeyValue> {\n for (const key of Object.keys(object)) {\n yield generateKeyValue([key], walkValue(object[key], format));\n }\n}\n\nfunction walkValue(value: any, format: Format): Value {\n if (value == null) {\n throw new Error('\"null\" and \"undefined\" values are not supported');\n }\n\n if (isString(value)) {\n return generateString(value);\n } else if (isInteger(value)) {\n return generateInteger(value);\n } else if (isFloat(value)) {\n return generateFloat(value);\n } else if (isBoolean(value)) {\n return generateBoolean(value);\n } else if (isDate(value)) {\n return generateDateTime(value);\n } else if (Array.isArray(value)) {\n return walkInlineArray(value, format);\n } else {\n return walkInlineTable(value, format);\n }\n}\n\nfunction walkInlineArray(value: Array<any>, format: Format): InlineArray {\n const inline_array = generateInlineArray();\n for (const element of value) {\n const item = walkValue(element, format);\n const inline_array_item = generateInlineItem(item);\n\n insert(inline_array, inline_array, inline_array_item);\n }\n applyBracketSpacing(inline_array, inline_array, format.bracketSpacing);\n applyTrailingComma(inline_array, inline_array, format.trailingComma);\n applyWrites(inline_array);\n\n return inline_array;\n}\n\nfunction walkInlineTable(value: object, format: Format): InlineTable | Value {\n value = toJSON(value);\n if (!isObject(value)) return walkValue(value, format);\n\n const inline_table = generateInlineTable();\n const items = [...walkObject(value, format)];\n for (const item of items) {\n const inline_table_item = generateInlineItem(item);\n\n insert(inline_table, inline_table, inline_table_item);\n }\n applyBracketSpacing(inline_table, inline_table, format.bracketSpacing);\n applyTrailingComma(inline_table, inline_table, format.trailingComma);\n applyWrites(inline_table);\n\n return inline_table;\n}\n\n/**\n * Handles custom object serialization by checking for and using toJSON methods\n * \n * @param value - The value to potentially convert\n * @returns The result of value.toJSON() if available, otherwise the original value\n */\nfunction toJSON(value: any): any {\n // Skip null/undefined values\n if (!value) {\n return value;\n }\n \n // Skip Date objects (they have special handling)\n if (isDate(value)) {\n return value;\n }\n \n // Use object's custom toJSON method if available\n if (typeof value.toJSON === 'function') {\n return value.toJSON();\n }\n \n // Otherwise return unmodified\n return value;\n}\n","import { NodeType, AST } from './ast';\nimport traverse from './traverse';\nimport { Location } from './location';\nimport { SPACE } from './tokenizer';\n\nconst BY_NEW_LINE = /(\\r\\n|\\n)/g;\n\n/**\n * Converts an Abstract Syntax Tree (AST) back to TOML format string.\n * \n * This function traverses the AST and reconstructs the original TOML document\n * by writing each node's raw content to the appropriate location coordinates.\n * It preserves the original formatting, spacing, and structure of the TOML file.\n * \n * @param ast - The Abstract Syntax Tree representing the parsed TOML document\n * @param newline - The newline character(s) to use (\\n by default)\n * @param options - Optional configuration object\n * @param options.trailingNewline - Number of trailing newlines to add (1 by default)\n * @returns The reconstructed TOML document as a string\n * \n * @example\n * ```typescript\n * const tomlString = toTOML(ast, '\\n', { trailingNewline: 1 });\n * ```\n */\nexport default function toTOML(ast: AST, newline: string = '\\n', options?: { trailingNewline?: number }): string {\n\n const trailingNewline = options?.trailingNewline ?? 1;\n\n const lines: string[] = [];\n\n traverse(ast, {\n [NodeType.TableKey](node) {\n const { start, end } = node.loc;\n\n write(lines, { start, end: { line: start.line, column: start.column + 1 } }, '[');\n write(lines, { start: { line: end.line, column: end.column - 1 }, end }, ']');\n },\n [NodeType.TableArrayKey](node) {\n const { start, end } = node.loc;\n\n write(lines, { start, end: { line: start.line, column: start.column + 2 } }, '[[');\n write(lines, { start: { line: end.line, column: end.column - 2 }, end }, ']]');\n },\n\n [NodeType.KeyValue](node) {\n const {\n start: { line }\n } = node.loc;\n write(\n lines,\n { start: { line, column: node.equals }, end: { line, column: node.equals + 1 } },\n '='\n );\n },\n [NodeType.Key](node) {\n write(lines, node.loc, node.raw);\n },\n\n [NodeType.String](node) {\n write(lines, node.loc, node.raw);\n },\n [NodeType.Integer](node) {\n write(lines, node.loc, node.raw);\n },\n [NodeType.Float](node) {\n write(lines, node.loc, node.raw);\n },\n [NodeType.Boolean](node) {\n write(lines, node.loc, node.value.toString());\n },\n [NodeType.DateTime](node) {\n write(lines, node.loc, node.raw);\n },\n\n [NodeType.InlineArray](node) {\n const { start, end } = node.loc;\n write(lines, { start, end: { line: start.line, column: start.column + 1 } }, '[');\n write(lines, { start: { line: end.line, column: end.column - 1 }, end }, ']');\n },\n\n [NodeType.InlineTable](node) {\n const { start, end } = node.loc;\n write(lines, { start, end: { line: start.line, column: start.column + 1 } }, '{');\n write(lines, { start: { line: end.line, column: end.column - 1 }, end }, '}');\n },\n [NodeType.InlineItem](node) {\n if (!node.comma) return;\n\n const start = node.loc.end;\n write(lines, { start, end: { line: start.line, column: start.column + 1 } }, ',');\n },\n\n [NodeType.Comment](node) {\n write(lines, node.loc, node.raw);\n }\n });\n\n return lines.join(newline) + newline.repeat(trailingNewline);\n}\n\n/**\n * Writes raw string content to specific location coordinates within a lines array.\n * \n * This function is responsible for placing TOML content at precise positions within\n * the output lines, handling multi-line content and preserving existing content\n * around the target location.\n * \n * @param lines - Array of string lines representing the TOML document being built.\n * Lines are 1-indexed but stored in 0-indexed array.\n * @param loc - Location object specifying where to write the content, containing:\n * - start: { line: number, column: number } - Starting position (1-indexed line, 0-indexed column)\n * - end: { line: number, column: number } - Ending position (1-indexed line, 0-indexed column)\n * @param raw - The raw string content to write at the specified location.\n * Can contain multiple lines separated by \\n or \\r\\n.\n * \n * @throws {Error} When there's a mismatch between location span and raw string line count\n * @throws {Error} When attempting to write to an uninitialized line\n * \n * @example\n * ```typescript\n * const lines = ['', ''];\n * const location = { start: { line: 1, column: 0 }, end: { line: 1, column: 3 } };\n * write(lines, location, 'key');\n * // Result: lines[0] becomes 'key'\n * ```\n */\nfunction write(lines: string[], loc: Location, raw: string) {\n const raw_lines = raw.split(BY_NEW_LINE).filter(line => line !== '\\n' && line !== '\\r\\n');\n const expected_lines = loc.end.line - loc.start.line + 1;\n\n if (raw_lines.length !== expected_lines) {\n throw new Error(\n `Mismatch between location and raw string, expected ${expected_lines} lines for \"${raw}\"`\n );\n }\n\n for (let i = loc.start.line; i <= loc.end.line; i++) {\n const line = getLine(lines, i);\n\n //Throw if line is uninitialized\n if (line === undefined) {\n throw new Error(\n `Line ${i} is uninitialized when writing \"${raw}\" at ${loc.start.line}:${loc.start.column} to ${loc.end.line}:${loc.end.column}`\n );\n }\n\n const is_start_line = i === loc.start.line;\n const is_end_line = i === loc.end.line;\n\n const before = is_start_line\n ? line.substr(0, loc.start.column).padEnd(loc.start.column, SPACE)\n : '';\n const after = is_end_line ? line.substr(loc.end.column) : '';\n\n lines[i - 1] = before + raw_lines[i - loc.start.line] + after;\n }\n}\n\n/**\n * Safely retrieves a line from the lines array, initializing empty lines as needed.\n * \n * This helper function handles the conversion between 1-indexed line numbers (used in locations)\n * and 0-indexed array positions. It ensures that accessing a line that doesn't exist yet\n * will initialize all preceding lines with empty strings.\n * \n * @param lines - Array of string lines representing the document\n * @param index - 1-indexed line number to retrieve\n * @returns The line content as a string, or empty string for new lines\n * \n * @example\n * ```typescript\n * const lines = ['first line'];\n * const line = getLine(lines, 3); // Initializes lines[1] and lines[2] as empty strings\n * // lines becomes ['first line', '', '']\n * ```\n */\nfunction getLine(lines: string[], index: number): string {\n if (!lines[index - 1]) {\n for (let i = 0; i < index; i++) {\n if (!lines[i]) lines[i] = '';\n }\n }\n\n return lines[index - 1];\n}\n","import { Value, NodeType, TreeNode, AST, isInlineTable } from './ast';\nimport traverse from './traverse';\nimport { last, blank, isDate, has } from './utils';\nimport ParseError from './parse-error';\n\nexport default function toJS(ast: AST, input: string = ''): any {\n const result = blank();\n const tables: Set<string> = new Set();\n const table_arrays: Set<string> = new Set();\n const defined: Set<string> = new Set();\n let active: any = result;\n let previous_active: any;\n let skip_depth = 0;\n\n traverse(ast, {\n [NodeType.Table](node) {\n const key = node.key.item.value;\n try {\n validateKey(result, key, node.type, { tables, table_arrays, defined });\n } catch (err) {\n const e = err as Error;\n throw new ParseError(input, node.key.loc.start, e.message);\n }\n\n const joined_key = joinKey(key);\n tables.add(joined_key);\n defined.add(joined_key);\n\n active = ensureTable(result, key);\n },\n\n [NodeType.TableArray](node) {\n const key = node.key.item.value;\n\n try {\n validateKey(result, key, node.type, { tables, table_arrays, defined });\n } catch (err) {\n const e = err as Error;\n throw new ParseError(input, node.key.loc.start, e.message);\n }\n\n const joined_key = joinKey(key);\n table_arrays.add(joined_key);\n defined.add(joined_key);\n\n active = ensureTableArray(result, key);\n },\n\n [NodeType.KeyValue]: {\n enter(node) {\n if (skip_depth > 0) return;\n\n const key = node.key.value;\n try {\n validateKey(active, key, node.type, { tables, table_arrays, defined });\n } catch (err) {\n const e = err as Error;\n throw new ParseError(input, node.key.loc.start, e.message);\n }\n\n const value = toValue(node.value);\n const target = key.length > 1 ? ensureTable(active, key.slice(0, -1)) : active;\n\n target[last(key)!] = value;\n defined.add(joinKey(key));\n }\n },\n\n [NodeType.InlineTable]: {\n enter() {\n // Handled by toValue\n skip_depth++;\n },\n exit() {\n skip_depth--;\n }\n }\n });\n\n return result;\n}\n\nexport function toValue(node: Value): any {\n switch (node.type) {\n case NodeType.InlineTable:\n const result = blank();\n\n node.items.forEach(({ item }) => {\n const key = item.key.value;\n const value = toValue(item.value);\n\n const target = key.length > 1 ? ensureTable(result, key.slice(0, -1)) : result;\n target[last(key)!] = value;\n });\n\n return result;\n\n case NodeType.InlineArray:\n return node.items.map(item => toValue(item.item as Value));\n\n case NodeType.String:\n case NodeType.Integer:\n case NodeType.Float:\n case NodeType.Boolean:\n case NodeType.DateTime:\n return node.value;\n\n default:\n throw new Error(`Unrecognized value type \"${(node as TreeNode).type}\"`);\n }\n}\n\nfunction validateKey(\n object: any,\n key: string[],\n type: NodeType.Table | NodeType.TableArray | NodeType.KeyValue,\n state: { tables: Set<string>; table_arrays: Set<string>; defined: Set<string> }\n) {\n // 1. Cannot override primitive value\n let parts: string[] = [];\n let index = 0;\n for (const part of key) {\n parts.push(part);\n\n if (!has(object, part)) return;\n if (isPrimitive(object[part])) {\n throw new Error(`Invalid key, a value has already been defined for ${parts.join('.')}`);\n }\n\n const joined_parts = joinKey(parts);\n if (Array.isArray(object[part]) && !state.table_arrays.has(joined_parts)) {\n throw new Error(`Invalid key, cannot add to a static array at ${joined_parts}`);\n }\n\n const next_is_last = index++ < key.length - 1;\n object = Array.isArray(object[part]) && next_is_last ? last(object[part]) : object[part];\n }\n\n const joined_key = joinKey(key);\n\n // 2. Cannot override table\n if (object && type === NodeType.Table && state.defined.has(joined_key)) {\n throw new Error(`Invalid key, a table has already been defined named ${joined_key}`);\n }\n\n // 3. Cannot add table array to static array or table\n if (object && type === NodeType.TableArray && !state.table_arrays.has(joined_key)) {\n throw new Error(`Invalid key, cannot add an array of tables to a table at ${joined_key}`);\n }\n}\n\nfunction ensureTable(object: any, key: string[]): any {\n const target = ensure(object, key.slice(0, -1));\n const last_key = last(key)!;\n if (!target[last_key]) {\n target[last_key] = blank();\n }\n\n return target[last_key];\n}\n\nfunction ensureTableArray(object: any, key: string[]): any {\n const target = ensure(object, key.slice(0, -1));\n const last_key = last(key)!;\n if (!target[last_key]) {\n target[last_key] = [];\n }\n\n const next = blank();\n target[last(key)!].push(next);\n\n return next;\n}\n\nfunction ensure(object: any, keys: string[]): any {\n return keys.reduce((active, subkey) => {\n if (!active[subkey]) {\n active[subkey] = blank();\n }\n return Array.isArray(active[subkey]) ? last(active[subkey]) : active[subkey];\n }, object);\n}\n\nfunction isPrimitive(value: any) {\n return typeof value !== 'object' && !isDate(value);\n}\n\nfunction joinKey(key: string[]): string {\n return key.join('.');\n}\n","import { isObject, datesEqual, stableStringify, merge } from './utils';\nimport { Path } from './find-by-path';\n\nexport enum ChangeType {\n Add = 'Add',\n Edit = 'Edit',\n Remove = 'Remove',\n Move = 'Move',\n Rename = 'Rename'\n}\n\nexport interface Add {\n type: ChangeType.Add;\n path: Path;\n}\nexport function isAdd(change: Change): change is Add {\n return change.type === ChangeType.Add;\n}\n\nexport interface Edit {\n type: ChangeType.Edit;\n path: Path;\n}\nexport function isEdit(change: Change): change is Edit {\n return change.type === ChangeType.Edit;\n}\n\nexport interface Remove {\n type: ChangeType.Remove;\n path: Path;\n}\nexport function isRemove(change: Change): change is Remove {\n return change.type === ChangeType.Remove;\n}\n\nexport interface Move {\n type: ChangeType.Move;\n path: Path;\n from: number;\n to: number;\n}\nexport function isMove(change: Change): change is Move {\n return change.type === ChangeType.Move;\n}\n\nexport interface Rename {\n type: ChangeType.Rename;\n path: Path;\n from: string;\n to: string;\n}\nexport function isRename(change: Change): change is Rename {\n return change.type === ChangeType.Rename;\n}\n\nexport type Change = Add | Edit | Remove | Move | Rename;\n\nexport default function diff(before: any, after: any, path: Path = []): Change[] {\n if (before === after || datesEqual(before, after)) {\n return [];\n }\n\n if (Array.isArray(before) && Array.isArray(after)) {\n return compareArrays(before, after, path);\n } else if (isObject(before) && isObject(after)) {\n return compareObjects(before, after, path);\n } else {\n return [\n {\n type: ChangeType.Edit,\n path\n }\n ];\n }\n}\n\nfunction compareObjects(before: any, after: any, path: Path = []): Change[] {\n let changes: Change[] = [];\n\n // 1. Get keys and stable values\n const before_keys = Object.keys(before);\n const before_stable = before_keys.map(key => stableStringify(before[key]));\n const after_keys = Object.keys(after);\n const after_stable = after_keys.map(key => stableStringify(after[key]));\n\n // Check for rename by seeing if object is in both before and after\n // and that key is no longer used in after\n const isRename = (stable: string, search: string[]) => {\n const index = search.indexOf(stable);\n if (index < 0) return false;\n\n const before_key = before_keys[before_stable.indexOf(stable)];\n return !after_keys.includes(before_key);\n };\n\n // 2. Check for changes, rename, and removed\n before_keys.forEach((key, index) => {\n const sub_path = path.concat(key);\n if (after_keys.includes(key)) {\n merge(changes, diff(before[key], after[key], sub_path));\n } else if (isRename(before_stable[index], after_stable)) {\n const to = after_keys[after_stable.indexOf(before_stable[index])];\n changes.push({\n type: ChangeType.Rename,\n path,\n from: key,\n to\n });\n } else {\n changes.push({\n type: ChangeType.Remove,\n path: sub_path\n });\n }\n });\n\n // 3. Check for additions\n after_keys.forEach((key, index) => {\n if (!before_keys.includes(key) && !isRename(after_stable[index], before_stable)) {\n changes.push({\n type: ChangeType.Add,\n path: path.concat(key)\n });\n }\n });\n\n return changes;\n}\n\nfunction compareArrays(before: any[], after: any[], path: Path = []): Change[] {\n let changes: Change[] = [];\n\n // 1. Convert arrays to stable objects\n const before_stable = before.map(stableStringify);\n const after_stable = after.map(stableStringify);\n\n // 2. Step through after array making changes to before array as-needed\n after_stable.forEach((value, index) => {\n const overflow = index >= before_stable.length;\n\n // Check if items are the same\n if (!overflow && before_stable[index] === value) {\n return;\n }\n\n // Check if item has been moved -> shift into place\n const from = before_stable.indexOf(value, index + 1);\n if (!overflow && from > -1) {\n changes.push({\n type: ChangeType.Move,\n path,\n from,\n to: index\n });\n\n const move = before_stable.splice(from, 1);\n before_stable.splice(index, 0, ...move);\n\n return;\n }\n\n // Check if item is removed -> assume it's been edited and replace\n const removed = !after_stable.includes(before_stable[index]);\n if (!overflow && removed) {\n merge(changes, diff(before[index], after[index], path.concat(index)));\n before_stable[index] = value;\n\n return;\n }\n\n // Add as new item and shift existing\n changes.push({\n type: ChangeType.Add,\n path: path.concat(index)\n });\n before_stable.splice(index, 0, value);\n });\n\n // 3. Remove any remaining overflow items\n for (let i = after_stable.length; i < before_stable.length; i++) {\n changes.push({\n type: ChangeType.Remove,\n path: path.concat(i)\n });\n }\n\n return changes;\n}\n","import { TreeNode, isKeyValue, isTable, isTableArray, hasItems, isInlineItem, hasItem } from './ast';\nimport { arraysEqual, stableStringify } from './utils';\n\nexport type Path = Array<string | number>;\n\nexport default function findByPath(node: TreeNode, path: Path): TreeNode {\n if (!path.length) return node;\n\n if (isKeyValue(node)) {\n return findByPath(node.value, path);\n }\n\n const indexes: { [key: string]: number } = {};\n let found;\n if (hasItems(node)) {\n node.items.some((item, index) => {\n try {\n let key: Path = [];\n if (isKeyValue(item)) {\n key = item.key.value;\n } else if (isTable(item)) {\n key = item.key.item.value;\n } else if (isTableArray(item)) {\n key = item.key.item.value;\n\n const key_string = stableStringify(key);\n if (!indexes[key_string]) {\n indexes[key_string] = 0;\n }\n const array_index = indexes[key_string]++;\n\n key = key.concat(array_index);\n } else if (isInlineItem(item) && isKeyValue(item.item)) {\n key = item.item.key.value;\n } else if (isInlineItem(item)) {\n key = [index];\n }\n\n if (key.length && arraysEqual(key, path.slice(0, key.length))) {\n found = findByPath(item, path.slice(key.length));\n return true;\n } else {\n return false;\n }\n } catch (err) {\n return false;\n }\n });\n }\n\n if (!found) {\n throw new Error(`Could not find node at path ${path.join('.')}`);\n }\n\n return found;\n}\n\nexport function tryFindByPath(node: TreeNode, path: Path): TreeNode | undefined {\n try {\n return findByPath(node, path);\n } catch (err) {}\n}\n\nexport function findParent(node: TreeNode, path: Path): TreeNode {\n let parent_path = path;\n let parent;\n while (parent_path.length && !parent) {\n parent_path = parent_path.slice(0, -1);\n parent = tryFindByPath(node, parent_path);\n }\n\n if (!parent) {\n throw new Error(`Count not find parent node for path ${path.join('.')}`);\n }\n\n return parent;\n}\n","import parseTOML from './parse-toml';\nimport parseJS from './parse-js';\nimport toTOML from './to-toml';\nimport toJS from './to-js';\nimport { Format } from './format';\n\n/**\n * Parses a TOML string into a JavaScript object.\n * The function converts TOML syntax to its JavaScript equivalent.\n * This proceeds in two steps: first, it parses the TOML string into an AST,\n * and then it converts the AST into a JavaScript object.\n * \n * @param value - The TOML string to parse\n * @returns The parsed JavaScript object\n */\nexport function parse(value: string): any {\n return toJS(parseTOML(value), value);\n}\n\n/**\n * Converts a JavaScript object to a TOML string.\n * \n * @param value - The JavaScript object to stringify\n * @param format - Optional formatting options for the resulting TOML\n * @returns The stringified TOML representation\n */\nexport function stringify(value: any, format?: Format): string {\n const document = parseJS(value, format);\n return toTOML(document.items);\n}\n\nexport { default as patch } from './patch';\n","import parseTOML from './parse-toml';\nimport parseJS from './parse-js';\nimport toJS from './to-js';\nimport toTOML from './to-toml';\nimport { Format } from './format';\nimport {\n isKeyValue,\n WithItems,\n KeyValue,\n isTable,\n TreeNode,\n Document,\n isDocument,\n Block,\n NodeType,\n isTableArray,\n isInlineArray,\n isInlineItem,\n hasItem,\n InlineItem,\n AST\n} from './ast';\nimport diff, { Change, isAdd, isEdit, isRemove, isMove, isRename } from './diff';\nimport findByPath, { tryFindByPath, findParent } from './find-by-path';\nimport { last, isInteger } from './utils';\nimport { insert, replace, remove, applyWrites } from './writer';\nimport { validate } from './validate';\n\nexport function toDocument(ast: AST) : Document {\n const items = [...ast];\n return {\n type: NodeType.Document,\n loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 0 } },\n items\n };\n}\n\n/**\n * Applies modifications to a TOML document by comparing an existing TOML string with updated JavaScript data.\n * \n * This function preserves formatting and comments from the existing TOML document while\n * applying changes from the updated data structure. It performs a diff between the existing\n * and updated data, then strategically applies only the necessary changes to maintain the\n * original document structure as much as possible.\n * \n * @param existing - The original TOML document as a string\n * @param updated - The updated JavaScript object with desired changes\n * @param format - Optional formatting options to apply to new or modified sections\n * @returns A new TOML string with the changes applied\n */\nexport default function patch(existing: string, updated: any, format?: Format): string {\n const existing_ast = parseTOML(existing);\n const items = [...existing_ast];\n\n const existing_js = toJS(items);\n const existing_document: Document = {\n type: NodeType.Document,\n loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 0 } },\n items\n };\n\n const updated_document = parseJS(updated, format);\n const changes = reorder(diff(existing_js, updated));\n\n\n\n const patched_document = applyChanges(existing_document, updated_document, changes);\n\n // Validate the patched_document\n //validate(patched_document);\n\n // Detect the line ending style from the original file\n let newline = '\\n'; // Default to LF\n const lfIndex = existing.indexOf('\\n');\n\n // Even if a LF is found, it could that there is a CR right before the LF\n if (lfIndex > 0 && existing.substring(lfIndex - 1, lfIndex) === '\\r') {\n newline = '\\r\\n'; // File uses CRLF\n }\n\n // Count consecutive trailing newlines\n function countTrailingNewlines(str: string, newlineChar: string): number {\n let count = 0;\n let pos = str.length;\n \n while (pos >= newlineChar.length) {\n if (str.substring(pos - newlineChar.length, pos) === newlineChar) {\n count++;\n pos -= newlineChar.length;\n } else {\n break;\n }\n }\n \n return count;\n }\n\n const trailingNewlineCount = countTrailingNewlines(existing, newline);\n\n return toTOML(patched_document.items, newline, { trailingNewline: trailingNewlineCount });\n}\n\nfunction reorder(changes: Change[]): Change[] {\n //Reorder deletions among themselves to avoid index issues\n // We want the path to be looking at the last item in the array first and go down from there\n \n let sorted = false;\n for (let i = 0; i < changes.length; i++) {\n const change = changes[i];\n if (isRemove(change)) {\n let j = i + 1;\n while (j < changes.length) {\n const next_change = changes[j];\n if (isRemove(next_change) && next_change.path[0] === change.path[0] && \n next_change.path[1] > change.path[1]) {\n changes.splice(j, 1);\n changes.splice(i, 0, next_change);\n // We reset i to the beginning of the loop to avoid skipping any changes\n i = 0\n break;\n }\n j++;\n }\n }\n }\n \n return changes;\n\n}\n\nfunction applyChanges(original: Document, updated: Document, changes: Change[]): Document {\n // Potential Changes:\n //\n // Add: Add key-value to object, add item to array\n // Edit: Change in value\n // Remove: Remove key-value from object, remove item from array\n // Move: Move item in array\n // Rename: Rename key in key-value\n //\n // Special consideration, inline comments need to move as-needed\n\n changes.forEach(change => {\n if (isAdd(change)) {\n const child = findByPath(updated, change.path);\n const parent_path = change.path.slice(0, -1);\n let index = last(change.path)! as number;\n\n let is_table_array = isTableArray(child);\n if (isInteger(index) && !parent_path.some(isInteger)) {\n const sibling = tryFindByPath(original, parent_path.concat(0));\n if (sibling && isTableArray(sibling)) {\n is_table_array = true;\n }\n }\n\n let parent: TreeNode;\n if (isTable(child)) {\n parent = original;\n } else if (is_table_array) {\n parent = original;\n\n // The index needs to be updated to top-level items\n // to properly account for other items, comments, and nesting\n const document = original as Document;\n const before = tryFindByPath(document, parent_path.concat(index - 1)) as Block | undefined;\n const after = tryFindByPath(document, parent_path.concat(index)) as Block | undefined;\n if (after) {\n index = document.items.indexOf(after);\n } else if (before) {\n index = document.items.indexOf(before) + 1;\n } else {\n index = document.items.length;\n }\n } else {\n parent = findParent(original, change.path);\n if (isKeyValue(parent)) {\n parent = parent.value;\n }\n }\n\n if (isTableArray(parent) || isInlineArray(parent) || isDocument(parent)) {\n insert(original, parent, child, index);\n } else {\n insert(original, parent, child);\n }\n } else if (isEdit(change)) {\n let existing = findByPath(original, change.path);\n let replacement = findByPath(updated, change.path);\n let parent;\n\n if (isKeyValue(existing) && isKeyValue(replacement)) {\n // Edit for key-value means value changes\n parent = existing;\n existing = existing.value;\n replacement = replacement.value;\n } else if (isKeyValue(existing) && isInlineItem(replacement) && isKeyValue(replacement.item)) {\n // Sometimes, the replacement looks like it could be an inline item, but the original is a key-value\n // In this case, we convert the replacement to a key-value to match the original\n parent = existing;\n existing = existing.value;\n replacement = replacement.item.value;\n } else {\n parent = findParent(original, change.path);\n }\n\n replace(original, parent, existing, replacement);\n } else if (isRemove(change)) {\n let parent = findParent(original, change.path);\n if (isKeyValue(parent)) parent = parent.value;\n\n const node = findByPath(original, change.path);\n\n remove(original, parent, node);\n } else if (isMove(change)) {\n let parent = findByPath(original, change.path);\n if (hasItem(parent)) parent = parent.item;\n if (isKeyValue(parent)) parent = parent.value;\n\n const node = (parent as WithItems).items[change.from];\n\n remove(original, parent, node);\n insert(original, parent, node, change.to);\n } else if (isRename(change)) {\n let parent = findByPath(original, change.path.concat(change.from)) as\n | KeyValue\n | InlineItem<KeyValue>;\n let replacement = findByPath(updated, change.path.concat(change.to)) as\n | KeyValue\n | InlineItem<KeyValue>;\n\n if (hasItem(parent)) parent = parent.item;\n if (hasItem(replacement)) replacement = replacement.item;\n\n replace(original, parent, parent.key, replacement.key);\n }\n });\n\n applyWrites(original);\n return original;\n}\n"],"names":["NodeType","TokenType","isDocument","node","type","Document","isTable","Table","isTableArray","TableArray","isKeyValue","KeyValue","isInlineArray","InlineArray","isInlineItem","InlineItem","isInlineTable","InlineTable","isComment","Comment","hasItems","hasItem","TableKey","isTableKey","TableArrayKey","isTableArrayKey","Cursor","constructor","iterator","this","index","value","undefined","done","peeked","next","result","_a","peek","Symbol","getSpan","location","lines","end","line","start","columns","column","findPosition","input","Array","isArray","findLines","findIndex","line_index","BY_NEW_LINE","indexes","match","exec","push","length","clonePosition","position","cloneLocation","ParseError","Error","message","error_message","substr","getLine","pointer","count","character","repeat","whitespace","super","IS_WHITESPACE","IS_NEW_LINE","DOUBLE_QUOTE","SINGLE_QUOTE","IS_VALID_LEADING_CHARACTER","tokenize","cursor","locate","createLocate","test","specialCharacter","Bracket","Curly","Equal","Comma","Dot","comment","multiline_char","checkThree","multiline","string","raw","loc","quotes","CheckMoreThanThree","Literal","double_quoted","single_quoted","isFinished","next_item","current","check","backslashes","slice","last","values","blank","Object","create","isInteger","isFinite","is","isDate","prototype","toString","call","isObject","has","object","key","hasOwnProperty","pipe","fns","reduce","fn","stableStringify","keys","sort","map","JSON","stringify","join","merge","target","original_length","added_length","i","IS_CRLF","IS_LF","IS_LEADING_NEW_LINE","IS_LINE_ENDING_BACKSLASH","parseString","startsWith","trim","trimLeadingWhitespace","lineEndingBackslash","escapeNewLines","escapeDoubleQuotes","unescapeLargeUnicode","precedingBackslashes","char","escaped","json_escaped","replace","code_point","parseInt","as_string","String","fromCodePoint","fixed_json_escaped","parse","group","TRUE","HAS_E","IS_DIVIDER","IS_INF","IS_NAN","IS_HEX","IS_OCTAL","IS_BINARY","IS_FULL_DATE","IS_FULL_TIME","parseTOML","tokens","walkBlock","is_table","item","Key","dot","before","after","items","table","equals","comments","walkValue","keyValue","Boolean","boolean","Date","local_date","toISOString","split","DateTime","datetime","Infinity","Number","Float","float","Integer","radix","integer","previous","comma","inline_item","inlineTable","inline_array","additional_comments","inlineArray","traverse","ast","visitor","traverseArray","array","parent","traverseNode","visit","enter","exit","enter_offsets","WeakMap","getEnterOffsets","root","set","get","exit_offsets","getExitOffsets","existing","replacement","indexOf","splice","shiftNode","existing_span","replacement_span","addOffset","insert","child","shift","offset","is_last","has_seperating_comma_before","has_seperating_comma_after","has_trailing_comma","use_new_line","perLine","leading_lines","skip_comma","skip_bracket","child_span","insertInline","use_first_line","is_block","insertOnNewLine","previous_offset","delete","remove","removed_span","is_inline","previous_on_same_line","next_on_sameLine","keep_line","target_offsets","node_offsets","removed_offset","applyBracketSpacing","bracket_spacing","last_item","applyTrailingComma","trailing_commas","applyWrites","shiftStart","lineOffset","columnOffset","entering","shiftEnd","exiting","shiftLocation","start_line","key_offset","span","options","first_line_only","move","offsets","from","generateDocument","generateTable","table_key","keyValueToRaw","generateTableKey","generateTableArray","table_array_key","generateTableArrayKey","generateKeyValue","key_node","generateKey","IS_BARE_KEY","part","generateInlineItem","formatTopLevel","document","filter","is_inline_table","is_inline_array","forEach","key_value","formatTable","inline_array_item","table_array","inline_table_item","formatTableArray","formatEmptyLines","default_format","printWidth","trailingComma","bracketSpacing","parseJS","format","assign","simpleKeys","complexKeys","reorderElements","toJSON","walkObject","formatted","formatPrintWidth","isString","generateString","generateInteger","isFloat","isNaN","generateFloat","isBoolean","generateBoolean","generateDateTime","element","walkInlineArray","inline_table","walkInlineTable","toTOML","newline","trailingNewline","write","raw_lines","expected_lines","is_start_line","is_end_line","padEnd","toJS","tables","Set","table_arrays","defined","active","skip_depth","validateKey","err","e","joined_key","joinKey","add","ensureTable","ensure","last_key","ensureTableArray","toValue","state","parts","joined_parts","next_is_last","subkey","ChangeType","isRemove","change","Remove","diff","path","b","a","changes","before_stable","after_stable","overflow","Move","to","removed","includes","concat","Add","compareArrays","before_keys","after_keys","isRename","stable","search","before_key","sub_path","Rename","compareObjects","Edit","findByPath","found","some","key_string","array_index","arraysEqual","tryFindByPath","findParent","parent_path","updated","existing_js","patched_document","original","isAdd","is_table_array","sibling","isEdit","isMove","applyChanges","j","next_change","reorder","lfIndex","substring","trailingNewlineCount","str","newlineChar","pos","countTrailingNewlines"],"mappings":";4OAEA,IAAYA,ECEAC,EDiCN,SAAUC,EAAWC,GACzB,OAAOA,EAAKC,OAASJ,EAASK,QAChC,CAoBM,SAAUC,EAAQH,GACtB,OAAOA,EAAKC,OAASJ,EAASO,KAChC,CAsCM,SAAUC,EAAaL,GAC3B,OAAOA,EAAKC,OAASJ,EAASS,UAChC,CAmCM,SAAUC,EAAWP,GACzB,OAAOA,EAAKC,OAASJ,EAASW,QAChC,CAgGM,SAAUC,EAAcT,GAC5B,OAAOA,EAAKC,OAASJ,EAASa,WAChC,CAgBM,SAAUC,EAAaX,GAC3B,OAAOA,EAAKC,OAASJ,EAASe,UAChC,CAWM,SAAUC,EAAcb,GAC5B,OAAOA,EAAKC,OAASJ,EAASiB,WAChC,CAwBM,SAAUC,EAAUf,GACxB,OAAOA,EAAKC,OAASJ,EAASmB,OAChC,CASM,SAAUC,EAASjB,GACvB,OACED,EAAWC,IACXG,EAAQH,IACRK,EAAaL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AEC,KAAM,EAAGG,OAAQ,IAC9D4I,SAGuBuI,GAAQ6F,EAAS5F,GAyC5C,SAAiB8D,GAKf,IAAK,IAAInP,EAAI,EAAGA,EAAImP,EAAQrU,OAAQkF,IAAK,CACvC,MAAM6O,EAASM,EAAQnP,GACvB,GAAI4O,GAASC,GAAS,CACpB,IAAI8C,EAAI3R,EAAI,EACZ,KAAO2R,EAAIxC,EAAQrU,QAAQ,CACzB,MAAM8W,EAAczC,EAAQwC,GAC5B,GAAI/C,GAASgD,IAAgBA,EAAY5C,KAAK,KAAOH,EAAOG,KAAK,IAC7D4C,EAAY5C,KAAK,GAAKH,EAAOG,KAAK,GAAI,CACxCG,EAAQrJ,OAAO6L,EAAG,GAClBxC,EAAQrJ,OAAO9F,EAAG,EAAG4R,GAErB5R,EAAI,EACJ,KACF,CACA2R,GACF,CACF,CACF,CAEA,OAAOxC,CAET,CAlEkB0C,CAAQ9C,GAAKmC,EAAaD,KAU1C,IAAIrE,EAAU,KACd,MAAMkF,EAAUnM,EAASE,QAAQ,MAG7BiM,EAAU,GAAkD,OAA7CnM,EAASoM,UAAUD,EAAU,EAAGA,KACjDlF,EAAU,QAoBZ,MAAMoF,EAhBN,SAA+BC,EAAaC,GAC1C,IAAIzW,EAAQ,EACR0W,EAAMF,EAAInX,OAEd,KAAOqX,GAAOD,EAAYpX,QACpBmX,EAAIF,UAAUI,EAAMD,EAAYpX,OAAQqX,KAASD,GACnDzW,IACA0W,GAAOD,EAAYpX,OAMvB,OAAOW,CACT,CAE6B2W,CAAsBzM,EAAUiH,GAE7D,OAAOD,GAAOwE,EAAiBtO,MAAO+J,EAAS,CAAEC,gBAAiBmF,GACpE,cD1EM,SAAoB/Y,EAAYoS,GAEpC,OAAOsB,GADUvB,GAAQnS,EAAOoS,GACTxI,MACzB"}
|
|
1
|
+
{"version":3,"file":"toml-patch.umd.min.js","sources":["../src/ast.ts","../src/tokenizer.ts","../src/cursor.ts","../src/location.ts","../src/parse-error.ts","../src/utils.ts","../src/parse-string.ts","../src/date-format.ts","../src/parse-toml.ts","../src/traverse.ts","../src/writer.ts","../src/generate.ts","../src/toml-format.ts","../src/parse-js.ts","../src/to-toml.ts","../src/to-js.ts","../src/diff.ts","../src/find-by-path.ts","../src/patch.ts","../node_modules/tslib/tslib.es6.js","../src/truncate.ts","../src/toml-document.ts","../src/index.ts"],"sourcesContent":["import { Location } from './location';\n\nexport enum NodeType {\n Document = 'Document',\n Table = 'Table',\n TableKey = 'TableKey',\n /**\n * Array of Tables node\n * More info: https://toml.io/en/latest#array-of-tables\n */\n TableArray = 'TableArray',\n TableArrayKey = 'TableArrayKey',\n KeyValue = 'KeyValue',\n Key = 'Key',\n String = 'String',\n Integer = 'Integer',\n Float = 'Float',\n Boolean = 'Boolean',\n DateTime = 'DateTime',\n InlineArray = 'InlineArray',\n InlineItem = 'InlineItem',\n InlineTable = 'InlineTable',\n /**\n * Comment node\n * More info: https://toml.io/en/latest#comment\n */\n Comment = 'Comment'\n}\n\n//\n// Abstract Syntax Tree\n//\n// AST nodes are used to represent TOML data\n//\nexport type AST = Iterable<Block>;\n\n//\n// Document\n//\n// Top-level document that stores AST nodes\n//\nexport interface Document extends TreeNode {\n type: NodeType.Document;\n items: Array<Block>;\n}\nexport function isDocument(node: TreeNode): node is Document {\n return node.type === NodeType.Document;\n}\n\n//\n// Table\n//\n// Top-level object\n//\n// v-------|\n// [table] |\n// b = \"c\" |\n// |\n// # note |\n// ^--|\n// [b]\n//\nexport interface Table extends TreeNode {\n type: NodeType.Table;\n key: TableKey;\n items: RowItem[];\n}\nexport function isTable(node: TreeNode): node is Table {\n return node.type === NodeType.Table;\n}\n\n//\n// TableKey\n//\n// Used to store bracket information for Table keys\n//\n// loc includes brackets\n//\n// [ key ]\n// ^-------^\n//\nexport interface TableKey extends TreeNode {\n type: NodeType.TableKey;\n item: Key;\n}\nexport function isTableKey(node: TreeNode): node is TableKey {\n return node.type === NodeType.TableKey;\n}\n\n//\n// TableArray\n//\n// Top-level array item\n//\n// v---------|\n// [[array]] |\n// a=\"b\" |\n// |\n// # details |\n// ^-|\n// [[array]]\n//\nexport interface TableArray extends TreeNode {\n type: NodeType.TableArray;\n key: TableArrayKey;\n items: RowItem[];\n}\n\n/**\n * Is a TableArray (aka array of tables)\n * @param node \n * @returns \n */\nexport function isTableArray(node: TreeNode): node is TableArray {\n return node.type === NodeType.TableArray;\n}\n\n//\n// TableArrayKey\n//\n// Used to store bracket information for TableArray keys\n// loc includes brackets\n//\n// [[ key ]]\n// ^---------^\n//\nexport interface TableArrayKey extends TreeNode {\n type: NodeType.TableArrayKey;\n item: Key;\n}\nexport function isTableArrayKey(node: TreeNode): node is TableArrayKey {\n return node.type === NodeType.TableArrayKey;\n}\n\n//\n// KeyValue\n//\n// Key and Value nodes, with position information on equals sign\n//\n// key=\"value\" # note\n// ^---------^\n//\nexport interface KeyValue extends TreeNode {\n type: NodeType.KeyValue;\n key: Key;\n value: Value;\n\n // Column index (0-based) of the equals sign\n equals: number;\n}\nexport function isKeyValue(node: TreeNode): node is KeyValue {\n return node.type === NodeType.KeyValue;\n}\n\n//\n// Key\n//\n// Store raw key and parts (from dots)\n//\nexport interface Key extends TreeNode {\n type: NodeType.Key;\n raw: string;\n\n // Note: Array for keys with dots\n // e.g. a.b -> raw = 'a.b', value = ['a', 'b']\n value: string[];\n}\nexport function isKey(node: TreeNode): node is Key {\n return node.type === NodeType.Key;\n}\n\n//\n// String\n//\n// loc includes quotes\n//\n// a = \"string\"\n// ^------^\n//\nexport interface String extends TreeNode {\n type: NodeType.String;\n raw: string;\n value: string;\n}\nexport function isString(node: TreeNode): node is String {\n return node.type === NodeType.String;\n}\n\n//\n// Integer\n//\nexport interface Integer extends TreeNode {\n type: NodeType.Integer;\n raw: string;\n value: number;\n}\nexport function isInteger(node: TreeNode): node is Integer {\n return node.type === NodeType.Integer;\n}\n\n//\n// Float\n//\nexport interface Float extends TreeNode {\n type: NodeType.Float;\n raw: string;\n value: number;\n}\nexport function isFloat(node: TreeNode): node is Float {\n return node.type === NodeType.Float;\n}\n\n//\n// Boolean\n//\nexport interface Boolean extends TreeNode {\n type: NodeType.Boolean;\n\n // Only `true` and `false` are permitted\n // -> don't need separate raw and value\n value: boolean;\n}\nexport function isBoolean(node: TreeNode): node is Boolean {\n return node.type === NodeType.Boolean;\n}\n\n//\n// DateTime\n//\n// Note: Currently, Offset Date-Time, Local Date-Time, Local Date, and Local Time\n// are handled via raw\n//\nexport interface DateTime extends TreeNode {\n type: NodeType.DateTime;\n raw: string;\n value: Date;\n}\nexport function isDateTime(node: TreeNode): node is DateTime {\n return node.type === NodeType.DateTime;\n}\n\n//\n// InlineArray\n//\nexport interface InlineArray<TItem = TreeNode> extends TreeNode {\n type: NodeType.InlineArray;\n items: InlineArrayItem<TItem>[];\n}\nexport function isInlineArray(node: TreeNode): node is InlineArray {\n return node.type === NodeType.InlineArray;\n}\n\n//\n// InlineArrayItem\n//\n// loc for InlineArrayItem is from start of value to before comma\n// or end-of-value if no comma\n//\n// [ \"a\" ,\"b\", \"c\" ]\n// ^---^ ^-^ ^-^\n//\nexport interface InlineItem<TItem = TreeNode> extends TreeNode {\n type: NodeType.InlineItem;\n item: TItem;\n comma: boolean;\n}\nexport function isInlineItem(node: TreeNode): node is InlineItem {\n return node.type === NodeType.InlineItem;\n}\n\nexport interface InlineArrayItem<TItem = TreeNode> extends InlineItem<TItem> {}\n\n//\n// InlineTable\n//\nexport interface InlineTable extends TreeNode {\n type: NodeType.InlineTable;\n items: InlineTableItem[];\n}\nexport function isInlineTable(node: TreeNode): node is InlineTable {\n return node.type === NodeType.InlineTable;\n}\n\n//\n// InlineTableItem\n//\n// loc for InlineTableItem follows InlineArrayItem\n//\n// { a=\"b\" , c = \"d\" }\n// ^------^ ^--------^\n//\nexport interface InlineTableItem extends InlineItem<KeyValue> {}\n\n//\n// Comment\n//\n// loc starts at \"#\" and goes to end of comment (trailing whitespace ignored)\n//\n// # comment here\n// ^------------^\n//\nexport interface Comment extends TreeNode {\n type: NodeType.Comment;\n raw: string;\n}\nexport function isComment(node: TreeNode): node is Comment {\n return node.type === NodeType.Comment;\n}\n\n//\n// Combinations\n//\n\n/**\n * RowItem represents items that can appear inside Table and TableArray sections.\n * These are the items that form the \"rows\" of content within table structures.\n * \n * Unlike Block items (which include Table and TableArray), RowItems can only be\n * KeyValue pairs and Comments - you cannot have nested tables within a table section.\n */\nexport type RowItem = KeyValue | Comment;\nexport function isRowItem(node: TreeNode): node is RowItem {\n return isKeyValue(node) || isComment(node);\n}\n\nexport interface WithItems extends TreeNode {\n items: TreeNode[];\n}\nexport function hasItems(node: TreeNode): node is WithItems {\n return (\n isDocument(node) ||\n isTable(node) ||\n isTableArray(node) ||\n isInlineTable(node) ||\n isInlineArray(node)\n );\n}\n\nexport interface WithItem extends TreeNode {\n item: TreeNode;\n}\nexport function hasItem(node: TreeNode): node is WithItem {\n return isTableKey(node) || isTableArrayKey(node) || isInlineItem(node);\n}\n\n/**\n * Block represents items that can appear at the root level (Document level) in TOML.\n * \n * Context and Usage:\n * - Block items are the fundamental top-level constructs in a TOML document\n * - They appear directly in Document containers and regular Table sections\n * - This is in contrast to InlineItems, which appear within inline containers\n * \n * Important Distinction:\n * - Table and TableArray can ONLY exist as Block items (they cannot appear inside inline containers)\n * - KeyValue and Comment can exist as BOTH Block items AND as InlineItems:\n * * As Block: When they appear at root level or inside regular Table sections\n * * As InlineItem: When they appear inside InlineTable or InlineArray containers\n * \n * Examples:\n * ```toml\n * # These are Block items at root level:\n * name = \"value\" # KeyValue as Block\n * # This is a comment # Comment as Block\n * [table] # Table as Block\n * [[array]] # TableArray as Block\n * \n * # These are Block items inside a Table:\n * [config]\n * setting = \"value\" # KeyValue as Block (inside Table)\n * # comment here # Comment as Block (inside Table)\n * \n * # These are InlineItems (NOT Block items):\n * array = [ \"a\", \"b\" ] # \"a\", \"b\" are InlineItems\n * table = { key = \"value\" } # key=\"value\" is InlineItem\n * ```\n * \n * Type Safety:\n * This distinction is crucial for the AST structure because:\n * - Document.items: Block[]\n * - Table.items: RowItem[] (KeyValue | Comment)\n * - TableArray.items: RowItem[] (KeyValue | Comment)\n * - InlineArray.items: InlineArrayItem[] (which extends InlineItem)\n * - InlineTable.items: InlineTableItem[] (which extends InlineItem)\n */\nexport type Block = KeyValue | Table | TableArray | Comment;\nexport function isBlock(node: TreeNode): node is Block {\n return isKeyValue(node) || isTable(node) || isTableArray(node) || isComment(node);\n}\n\nexport type Value<TInlineArrayItem = TreeNode> =\n | String\n | Integer\n | Float\n | Boolean\n | DateTime\n | InlineArray<TInlineArrayItem>\n | InlineTable;\nexport function isValue(node: TreeNode): node is Value {\n return (\n isString(node) ||\n isInteger(node) ||\n isFloat(node) ||\n isBoolean(node) ||\n isDateTime(node) ||\n isInlineArray(node) ||\n isInlineTable(node)\n );\n}\n\nexport interface TreeNode {\n type: NodeType;\n loc: Location;\n}\n","import Cursor, { iterator } from './cursor';\nimport { Location, Locator, createLocate, findPosition } from './location';\nimport ParseError from './parse-error';\n\nexport enum TokenType {\n Bracket = 'Bracket',\n Curly = 'Curly',\n Equal = 'Equal',\n Comma = 'Comma',\n Dot = 'Dot',\n Comment = 'Comment',\n Literal = 'Literal'\n}\n\nexport interface Token {\n type: TokenType;\n raw: string;\n loc: Location;\n}\n\nexport const IS_WHITESPACE = /\\s/;\nexport const IS_NEW_LINE = /(\\r\\n|\\n)/;\nexport const DOUBLE_QUOTE = `\"`;\nexport const SINGLE_QUOTE = `'`;\nexport const SPACE = ' ';\nexport const ESCAPE = '\\\\';\n\nconst IS_VALID_LEADING_CHARACTER = /[\\w,\\d,\\\",\\',\\+,\\-,\\_]/;\n\nexport function* tokenize(input: string): IterableIterator<Token> {\n const cursor = new Cursor(iterator(input));\n cursor.next();\n\n const locate = createLocate(input);\n\n while (!cursor.done) {\n if (IS_WHITESPACE.test(cursor.value!)) {\n // (skip whitespace)\n } else if (cursor.value === '[' || cursor.value === ']') {\n // Handle special characters: [, ], {, }, =, comma\n yield specialCharacter(cursor, locate, TokenType.Bracket);\n } else if (cursor.value === '{' || cursor.value === '}') {\n yield specialCharacter(cursor, locate, TokenType.Curly);\n } else if (cursor.value === '=') {\n yield specialCharacter(cursor, locate, TokenType.Equal);\n } else if (cursor.value === ',') {\n yield specialCharacter(cursor, locate, TokenType.Comma);\n } else if (cursor.value === '.') {\n yield specialCharacter(cursor, locate, TokenType.Dot);\n } else if (cursor.value === '#') {\n // Handle comments = # -> EOL\n yield comment(cursor, locate);\n } else {\n const multiline_char =\n checkThree(input, cursor.index, SINGLE_QUOTE) ||\n checkThree(input, cursor.index, DOUBLE_QUOTE);\n\n if (multiline_char) {\n // Multi-line literals or strings = no escaping\n yield multiline(cursor, locate, multiline_char, input);\n } else {\n yield string(cursor, locate, input);\n }\n }\n\n cursor.next();\n }\n}\n\nfunction specialCharacter(cursor: Cursor<string>, locate: Locator, type: TokenType): Token {\n return { type, raw: cursor.value!, loc: locate(cursor.index, cursor.index + 1) };\n}\n\nfunction comment(cursor: Cursor<string>, locate: Locator): Token {\n const start = cursor.index;\n let raw = cursor.value!;\n while (!cursor.peek().done && !IS_NEW_LINE.test(cursor.peek().value!)) {\n cursor.next();\n raw += cursor.value!;\n }\n\n // Early exit is ok for comment, no closing conditions\n\n return {\n type: TokenType.Comment,\n raw,\n loc: locate(start, cursor.index + 1)\n };\n}\n\nfunction multiline(\n cursor: Cursor<string>,\n locate: Locator,\n multiline_char: string,\n input: string\n): Token {\n const start = cursor.index;\n let quotes = multiline_char + multiline_char + multiline_char;\n let raw = quotes;\n\n // Skip over quotes\n cursor.next();\n cursor.next();\n cursor.next();\n\n // The reason why we need to check if there is more than three is because we have to match the last 3 quotes, not the first 3 that appears consecutively\n // See spec-string-basic-multiline-9.toml\n while (!cursor.done && (!checkThree(input, cursor.index, multiline_char) || CheckMoreThanThree(input, cursor.index, multiline_char))) {\n raw += cursor.value;\n cursor.next();\n }\n\n if (cursor.done) {\n throw new ParseError(\n input,\n findPosition(input, cursor.index),\n `Expected close of multiline string with ${quotes}, reached end of file`\n );\n }\n\n raw += quotes;\n\n cursor.next();\n cursor.next();\n\n return {\n type: TokenType.Literal,\n raw,\n loc: locate(start, cursor.index + 1)\n };\n}\n\nfunction string(cursor: Cursor<string>, locate: Locator, input: string): Token {\n // Remaining possibilities: keys, strings, literals, integer, float, boolean\n //\n // Special cases:\n // \"...\" -> quoted\n // '...' -> quoted\n // \"...\".'...' -> bare\n // 0000-00-00 00:00:00 -> bare\n //\n // See https://github.com/toml-lang/toml#offset-date-time\n //\n // | For the sake of readability, you may replace the T delimiter between date and time with a space (as permitted by RFC 3339 section 5.6).\n // | `odt4 = 1979-05-27 07:32:00Z`\n //\n // From RFC 3339:\n //\n // | NOTE: ISO 8601 defines date and time separated by \"T\".\n // | Applications using this syntax may choose, for the sake of\n // | readability, to specify a full-date and full-time separated by\n // | (say) a space character.\n\n // First, check for invalid characters\n if (!IS_VALID_LEADING_CHARACTER.test(cursor.value!)) {\n throw new ParseError(\n input,\n findPosition(input, cursor.index),\n `Unsupported character \"${cursor.value}\". Expected ALPHANUMERIC, \", ', +, -, or _`\n );\n }\n\n const start = cursor.index;\n let raw = cursor.value!;\n let double_quoted = cursor.value === DOUBLE_QUOTE;\n let single_quoted = cursor.value === SINGLE_QUOTE;\n\n const isFinished = (cursor: Cursor<string>) => {\n if (cursor.peek().done) return true;\n const next_item = cursor.peek().value!;\n\n return (\n !(double_quoted || single_quoted) &&\n (IS_WHITESPACE.test(next_item) ||\n next_item === ',' ||\n next_item === '.' ||\n next_item === ']' ||\n next_item === '}' ||\n next_item === '=' ||\n next_item === '#'\n )\n );\n };\n\n while (!cursor.done && !isFinished(cursor)) {\n cursor.next();\n\n if (cursor.value === DOUBLE_QUOTE) double_quoted = !double_quoted;\n if (cursor.value === SINGLE_QUOTE && !double_quoted) single_quoted = !single_quoted;\n\n raw += cursor.value!;\n\n if (cursor.peek().done) break;\n let next_item = cursor.peek().value!;\n\n // If next character is escape and currently double-quoted,\n // check for escaped quote\n if (double_quoted && cursor.value === ESCAPE) {\n if (next_item === DOUBLE_QUOTE) {\n raw += DOUBLE_QUOTE;\n cursor.next();\n } else if (next_item === ESCAPE) {\n raw += ESCAPE;\n cursor.next();\n }\n }\n }\n\n if (double_quoted || single_quoted) {\n throw new ParseError(\n input,\n findPosition(input, start),\n `Expected close of string with ${double_quoted ? DOUBLE_QUOTE : SINGLE_QUOTE}`\n );\n }\n\n return {\n type: TokenType.Literal,\n raw,\n loc: locate(start, cursor.index + 1)\n };\n}\n\n/**\n * Check if the current character and the next two characters are the same\n * and not escaped.\n *\n * @param input - The input string.\n * @param current - The current index in the input string.\n * @param check - The character to check for.\n * @returns ⚠️The character if found, otherwise false.\n */\nfunction checkThree(input: string, current: number, check: string): false | string {\n if (!check) {\n return false;\n }\n\n const has3 =\n input[current] === check &&\n input[current + 1] === check &&\n input[current + 2] === check;\n\n if (!has3) {\n return false;\n }\n\n // Check if the sequence is escaped\n const precedingText = input.slice(0, current); // Get the text before the current position\n const backslashes = precedingText.match(/\\\\+$/); // Match trailing backslashes\n\n if (!backslashes) {\n return check; // No backslashes means not escaped\n }\n \n const isEscaped = backslashes[0].length % 2 !== 0; // Odd number of backslashes means escaped\n\n return isEscaped ? false : check; // Return `check` if not escaped, otherwise `false`\n}\n\nexport function CheckMoreThanThree(input: string, current: number, check: string): boolean {\n \n if (!check) {\n return false;\n }\n\n return (\n input[current] === check &&\n input[current + 1] === check &&\n input[current + 2] === check &&\n input[current + 3] === check\n )\n\n}\n","export function iterator<T>(value: Iterable<T>): Iterator<T> {\n return value[Symbol.iterator]();\n}\n\n/**\n * Cursor<T>\n * \n * A utility class that wraps an iterator and provides additional functionality\n * such as peeking at the next value without advancing the iterator, tracking\n * the current index, and iterating over the values.\n * \n * @template T - The type of elements in the iterator.\n * \n * Properties:\n * - `iterator`: The underlying iterator being wrapped.\n * - `index`: The current index of the iterator (starts at -1).\n * - `value`: The current value of the iterator.\n * - `done`: A boolean indicating whether the iterator is complete.\n * - `peeked`: The result of peeking at the next value without advancing.\n * \n * Methods:\n * - `next()`: Advances the iterator and returns the next value.\n * - `peek()`: Returns the next value without advancing the iterator.\n * - `[Symbol.iterator]`: Makes the Cursor itself iterable.\n */\nexport default class Cursor<T> implements Iterator<T | undefined> {\n iterator: Iterator<T>;\n index: number;\n value?: T;\n done: boolean;\n peeked: IteratorResult<T | undefined> | null;\n\n constructor(iterator: Iterator<T>) {\n this.iterator = iterator;\n this.index = -1;\n this.value = undefined;\n this.done = false;\n this.peeked = null;\n }\n\n next(): IteratorResult<T | undefined> {\n if (this.done) return done();\n\n const result = this.peeked || this.iterator.next();\n\n this.index += 1;\n this.value = result.value;\n this.done = result.done ?? false;\n this.peeked = null;\n\n return result;\n }\n\n peek(): IteratorResult<T | undefined> {\n if (this.done) return done();\n if (this.peeked) return this.peeked;\n\n this.peeked = this.iterator.next();\n return this.peeked;\n }\n\n [Symbol.iterator]() {\n return this;\n }\n}\n\nfunction done(): IteratorResult<undefined> {\n return { value: undefined, done: true };\n}\n","export interface Location {\n start: Position;\n end: Position;\n}\n\nexport interface Position {\n // Note: line is 1-indexed while column is 0-indexed\n line: number;\n column: number;\n}\n\nexport interface Span {\n lines: number;\n columns: number;\n}\n\nexport function getSpan(location: Location): Span {\n return {\n lines: location.end.line - location.start.line + 1,\n columns: location.end.column - location.start.column\n };\n}\n\nexport type Locator = (start: number, end: number) => Location;\nexport function createLocate(input: string): Locator {\n const lines = findLines(input);\n\n return (start: number, end: number) => {\n return {\n start: findPosition(lines, start),\n end: findPosition(lines, end)\n };\n };\n}\n\nexport function findPosition(input: string | number[], index: number): Position {\n // abc\\ndef\\ng\n // 0123 4567 8\n // 012\n // 0\n //\n // lines = [3, 7, 9]\n //\n // c = 2: 0 -> 1, 2 - (undefined + 1 || 0) = 2\n // 3: 0 -> 1, 3 - (undefined + 1 || 0) = 3\n // e = 5: 1 -> 2, 5 - (3 + 1 || 0) = 1\n // g = 8: 2 -> 3, 8 - (7 + 1 || 0) = 0\n\n const lines = Array.isArray(input) ? input : findLines(input);\n const line = lines.findIndex(line_index => line_index >= index) + 1;\n const column = index - (lines[line - 2] + 1 || 0);\n\n return { line, column };\n}\n\nexport function getLine(input: string, position: Position): string {\n const lines = findLines(input);\n const start = lines[position.line - 2] || 0;\n const end = lines[position.line - 1] || input.length;\n\n return input.substr(start, end - start);\n}\n\nexport function findLines(input: string): number[] {\n // exec is stateful, so create new regexp each time\n const BY_NEW_LINE = /\\r\\n|\\n/g;\n const indexes: number[] = [];\n\n let match;\n while ((match = BY_NEW_LINE.exec(input)) != null) {\n indexes.push(match.index + match[0].length - 1);\n }\n indexes.push(input.length + 1);\n\n return indexes;\n}\n\nexport function clonePosition(position: Position): Position {\n return { line: position.line, column: position.column };\n}\n\nexport function cloneLocation(location: Location): Location {\n return { start: clonePosition(location.start), end: clonePosition(location.end) };\n}\n/**\n * Returns a Position at line 1, column 0.\n * This means that lines are 1-indexed and columns are 0-indexed.\n * \n * @returns A Position at line 1, column 0\n */\nexport function zero(): Position {\n return { line: 1, column: 0 };\n}\n","import { Position, getLine } from './location';\n\nexport default class ParseError extends Error {\n line: number;\n column: number;\n\n constructor(input: string, position: Position, message: string) {\n let error_message = `Error parsing TOML (${position.line}, ${position.column + 1}):\\n`;\n\n if (input) {\n const line = getLine(input, position);\n const pointer = `${whitespace(position.column)}^`;\n\n if (line) error_message += `${line}\\n${pointer}\\n`;\n }\n error_message += message;\n\n super(error_message);\n\n this.line = position.line;\n this.column = position.column;\n }\n}\n\nexport function isParseError(error: Error): error is ParseError {\n return error && Object.prototype.hasOwnProperty.call(error, 'line');\n}\n\nfunction whitespace(count: number, character: string = ' '): string {\n return character.repeat(count);\n}\n","export function last<TValue>(values: TValue[]): TValue | undefined {\n return values[values.length - 1];\n}\n\nexport type BlankObject = { [key: string]: any };\n\nexport function blank(): BlankObject {\n return Object.create(null);\n}\n\nexport function isString(value: any): value is string {\n return typeof value === 'string';\n}\n\nexport function isInteger(value: any): value is number {\n return typeof value === 'number' && value % 1 === 0 && isFinite(value) && !Object.is(value, -0);\n}\n\nexport function isFloat(value: any): value is number {\n return typeof value === 'number' && (!isInteger(value) || !isFinite(value) || Object.is(value, -0));\n}\n\nexport function isBoolean(value: any): value is boolean {\n return typeof value === 'boolean';\n}\n\nexport function isDate(value: any): value is Date {\n return Object.prototype.toString.call(value) === '[object Date]';\n}\n\nexport function isObject(value: any): boolean {\n return value && typeof value === 'object' && !isDate(value) && !Array.isArray(value);\n}\n\nexport function isIterable<T>(value: any): value is Iterable<T> {\n return value != null && typeof value[Symbol.iterator] === 'function';\n}\n\nexport function has(object: any, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(object, key);\n}\n\nexport function arraysEqual<TItem>(a: TItem[], b: TItem[]): boolean {\n if (a.length !== b.length) return false;\n\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n\n return true;\n}\n\nexport function datesEqual(a: any, b: any): boolean {\n return isDate(a) && isDate(b) && a.toISOString() === b.toISOString();\n}\n\nexport function pipe<TValue>(value: TValue, ...fns: Array<(value: TValue) => TValue>): TValue {\n return fns.reduce((value, fn) => fn(value), value);\n}\n\nexport function stableStringify(object: any): string {\n if (isObject(object)) {\n const key_values = Object.keys(object)\n .sort()\n .map(key => `${JSON.stringify(key)}:${stableStringify(object[key])}`);\n\n return `{${key_values.join(',')}}`;\n } else if (Array.isArray(object)) {\n return `[${object.map(stableStringify).join(',')}]`;\n } else {\n return JSON.stringify(object);\n }\n}\n\nexport function merge<TValue>(target: TValue[], values: TValue[]) {\n // __mutating__: merge values into target\n // Reference: https://dev.to/uilicious/javascript-array-push-is-945x-faster-than-array-concat-1oki\n const original_length = target.length;\n const added_length = values.length;\n target.length = original_length + added_length;\n\n for (let i = 0; i < added_length; i++) {\n target[original_length + i] = values[i];\n }\n}\n","import { SINGLE_QUOTE, DOUBLE_QUOTE } from './tokenizer';\nimport { pipe } from './utils';\n\nconst TRIPLE_DOUBLE_QUOTE = `\"\"\"`;\nconst TRIPLE_SINGLE_QUOTE = `'''`;\nconst LF = '\\\\n';\nconst CRLF = '\\\\r\\\\n';\nconst IS_CRLF = /\\r\\n/g;\nconst IS_LF = /\\n/g;\nconst IS_LEADING_NEW_LINE = /^(\\r\\n|\\n)/;\n// This regex is used to match an odd number of backslashes followed by a line ending\n// It uses a negative lookbehind to ensure that the backslash is not preceded by another backslash.\n// We need an odd number of backslashes so that the last one is not escaped.\nconst IS_LINE_ENDING_BACKSLASH = /(?<!\\\\)(?:\\\\\\\\)*(\\\\\\s*[\\n\\r\\n]\\s*)/g;\n\nexport function parseString(raw: string): string {\n if (raw.startsWith(TRIPLE_SINGLE_QUOTE)) {\n return pipe(\n trim(raw, 3),\n trimLeadingWhitespace\n );\n } else if (raw.startsWith(SINGLE_QUOTE)) {\n return trim(raw, 1);\n } else if (raw.startsWith(TRIPLE_DOUBLE_QUOTE)) {\n return pipe(\n trim(raw, 3),\n trimLeadingWhitespace,\n lineEndingBackslash,\n escapeNewLines,\n escapeDoubleQuotes,\n unescapeLargeUnicode\n );\n } else if (raw.startsWith(DOUBLE_QUOTE)) {\n return pipe(\n trim(raw, 1),\n unescapeLargeUnicode\n );\n } else {\n return raw;\n }\n}\n\nexport function escapeDoubleQuotes(value: string): string {\n let result = '';\n let precedingBackslashes = 0;\n\n for (let i = 0; i < value.length; i++) {\n const char = value[i];\n\n if (char === '\"' && precedingBackslashes % 2 === 0) {\n // If the current character is a quote and it is not escaped, escape it\n result += '\\\\\"';\n } else {\n // Otherwise, add the character as is\n result += char;\n }\n\n // Update the count of consecutive backslashes\n if (char === '\\\\') {\n precedingBackslashes++;\n } else {\n precedingBackslashes = 0; // Reset if the character is not a backslash\n }\n }\n\n return result;\n}\n\nexport function unescapeLargeUnicode(escaped: string): string {\n // JSON.parse handles everything except \\UXXXXXXXX\n // replace those instances with code point, escape that, and then parse\n const LARGE_UNICODE = /\\\\U[a-fA-F0-9]{8}/g;\n const json_escaped = escaped.replace(LARGE_UNICODE, value => {\n const code_point = parseInt(value.replace('\\\\U', ''), 16);\n const as_string = String.fromCodePoint(code_point);\n\n return trim(JSON.stringify(as_string), 1);\n });\n\n const fixed_json_escaped = escapeTabsForJSON(json_escaped);\n\n // Parse the properly escaped JSON string\n const parsed = JSON.parse(`\"${fixed_json_escaped}\"`);\n return parsed;\n}\n\nfunction escapeTabsForJSON(value: string): string {\n return value\n .replace(/\\t/g, '\\\\t')\n}\n\nexport function escape(value: string): string {\n return trim(JSON.stringify(value), 1);\n}\n\nfunction trim(value: string, count: number): string {\n return value.slice(count, value.length - count);\n}\n\nfunction trimLeadingWhitespace(value: string): string {\n return value.replace(IS_LEADING_NEW_LINE, '');\n}\n\nfunction escapeNewLines(value: string): string {\n return value.replace(IS_CRLF, CRLF).replace(IS_LF, LF);\n}\n\nfunction lineEndingBackslash(value: string): string {\n return value.replace(IS_LINE_ENDING_BACKSLASH, (match, group) => match.replace(group, ''));\n}\n","/**\n * Central module for TOML date/time format handling and custom date classes.\n * This module provides all the patterns, classes, and utilities needed to work\n * with the different date/time formats supported by the TOML specification.\n */\n\n/**\n * Helper class containing all date format patterns and utilities for TOML date/time handling\n */\nexport class DateFormatHelper {\n // Patterns for different date/time formats\n static readonly IS_DATE_ONLY = /^\\d{4}-\\d{2}-\\d{2}$/;\n static readonly IS_TIME_ONLY = /^\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?$/;\n static readonly IS_LOCAL_DATETIME_T = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?$/;\n static readonly IS_LOCAL_DATETIME_SPACE = /^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?$/;\n static readonly IS_OFFSET_DATETIME_T = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:[Zz]|[+-]\\d{2}:\\d{2})$/;\n static readonly IS_OFFSET_DATETIME_SPACE = /^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:[Zz]|[+-]\\d{2}:\\d{2})$/;\n \n // Legacy patterns from parse-toml.ts (for compatibility)\n static readonly IS_FULL_DATE = /(\\d{4})-(\\d{2})-(\\d{2})/;\n static readonly IS_FULL_TIME = /(\\d{2}):(\\d{2}):(\\d{2})/;\n\n /**\n * Creates a custom date/time object that preserves the original TOML date/time format.\n * \n * This method detects the TOML date/time format from the raw string and returns an appropriate\n * custom date/time instance (e.g., LocalDate, LocalTime, LocalDateTime, OffsetDateTime) or a Date,\n * using the provided new JavaScript Date value.\n * \n * @param {Date} newJSDate - The new JavaScript Date object representing the updated \n * date/time value. This is used as the source for constructing the custom date/time object.\n * In some cases, this may be a custom date/time object (e.g., LocalTime) instead of a native Date.\n * @param {string} originalRaw - The original TOML date/time string as it appeared in the input.\n * Used to detect the specific TOML date/time format and to extract formatting details (e.g., separator, offset).\n * \n * @returns {Date | LocalDate | LocalTime | LocalDateTime | OffsetDateTime}\n * Returns a custom date/time object that matches the original TOML format:\n * - LocalDate for date-only values (e.g., \"2024-01-15\")\n * - LocalTime for time-only values (e.g., \"10:30:00\")\n * - LocalDateTime for local datetimes (e.g., \"2024-01-15T10:30:00\" or \"2024-01-15 10:30:00\")\n * - OffsetDateTime for datetimes with offsets (e.g., \"2024-01-15T10:30:00+02:00\")\n * - Date (native JS Date) as a fallback if the format is unrecognized\n * \n * Format-specific behavior:\n * - Date-only: Returns a LocalDate constructed from the date part of newJSDate.\n * - Time-only: Returns a LocalTime, either from newJSDate (if already LocalTime) or constructed from its time part.\n * - Local datetime: Returns a LocalDateTime, preserving the separator (T or space).\n * - Offset datetime: Returns an OffsetDateTime, reconstructing the date/time with the original offset and separator.\n * - Fallback: Returns newJSDate as-is.\n */\n static createDateWithOriginalFormat(newJSDate: Date, originalRaw: string): Date {\n if (DateFormatHelper.IS_DATE_ONLY.test(originalRaw)) {\n // Local date (date-only) - format: 2024-01-15\n // Check if newJSDate has time components - if so, upgrade appropriately\n if (\n newJSDate.getUTCHours() !== 0 ||\n newJSDate.getUTCMinutes() !== 0 ||\n newJSDate.getUTCSeconds() !== 0 ||\n newJSDate.getUTCMilliseconds() !== 0\n ) {\n // Check if the new value is an OffsetDateTime (has offset information)\n if (newJSDate instanceof OffsetDateTime) {\n // Upgrade to OffsetDateTime - it already has the right format\n return newJSDate;\n }\n \n // Upgrade from date-only to local datetime with time components\n // Use T separator as it's the more common format\n let isoString = newJSDate.toISOString().replace('Z', '');\n // Strip .000 milliseconds if present (don't show unnecessary precision)\n isoString = isoString.replace(/\\.000$/, '');\n return new LocalDateTime(isoString, false);\n }\n const dateStr = newJSDate.toISOString().split('T')[0];\n return new LocalDate(dateStr);\n } else if (DateFormatHelper.IS_TIME_ONLY.test(originalRaw)) {\n // Local time (time-only) - format: 10:30:00\n // For time-only values, we need to handle this more carefully\n // The newJSDate might be a LocalTime object itself\n if (newJSDate instanceof LocalTime) {\n // If the new date is already a LocalTime, use its toISOString\n return newJSDate;\n } else {\n // Determine if originalRaw had milliseconds and how many digits\n const msMatch = originalRaw.match(/\\.(\\d+)\\s*$/);\n \n // Extract time from a regular Date object\n const isoString = newJSDate.toISOString();\n if (isoString && isoString.includes('T')) {\n let newTime = isoString.split('T')[1].split('Z')[0];\n if (msMatch) {\n // Original had milliseconds, preserve the number of digits\n const msDigits = msMatch[1].length;\n const [h, m, sMs] = newTime.split(':');\n const [s] = sMs.split('.');\n const ms = String(newJSDate.getUTCMilliseconds()).padStart(3, '0').slice(0, msDigits);\n newTime = `${h}:${m}:${s}.${ms}`;\n }\n // If original had no milliseconds, keep newTime as-is (with milliseconds if present)\n return new LocalTime(newTime, originalRaw);\n } else {\n // Fallback: construct time from the Date object directly\n const hours = String(newJSDate.getUTCHours()).padStart(2, '0');\n const minutes = String(newJSDate.getUTCMinutes()).padStart(2, '0');\n const seconds = String(newJSDate.getUTCSeconds()).padStart(2, '0');\n const milliseconds = newJSDate.getUTCMilliseconds();\n let timeStr: string;\n if (msMatch) {\n const msDigits = msMatch[1].length;\n let ms = String(milliseconds).padStart(3, '0').slice(0, msDigits);\n timeStr = `${hours}:${minutes}:${seconds}.${ms}`;\n } else if (milliseconds > 0) {\n // No original milliseconds, but new value has them - include them\n // Note: milliseconds > 0 ensures we don't format \".0\" for zero milliseconds\n const ms = String(milliseconds).padStart(3, '0').replace(/0+$/, '');\n timeStr = `${hours}:${minutes}:${seconds}.${ms}`;\n } else {\n timeStr = `${hours}:${minutes}:${seconds}`;\n }\n return new LocalTime(timeStr, originalRaw);\n }\n }\n } else if (DateFormatHelper.IS_LOCAL_DATETIME_T.test(originalRaw)) {\n // Local datetime with T separator - format: 2024-01-15T10:30:00\n // Determine if originalRaw had milliseconds and how many digits\n const msMatch = originalRaw.match(/\\.(\\d+)\\s*$/);\n let isoString = newJSDate.toISOString().replace('Z', '');\n if (msMatch) {\n // Original had milliseconds, preserve the number of digits\n const msDigits = msMatch[1].length;\n // isoString is like \"2024-01-15T10:30:00.123\"\n const [datePart, timePart] = isoString.split('T');\n const [h, m, sMs] = timePart.split(':');\n const [s] = sMs.split('.');\n const ms = String(newJSDate.getUTCMilliseconds()).padStart(3, '0').slice(0, msDigits);\n isoString = `${datePart}T${h}:${m}:${s}.${ms}`;\n }\n // If original had no milliseconds, keep isoString as-is (with milliseconds if present)\n return new LocalDateTime(isoString, false, originalRaw);\n } else if (DateFormatHelper.IS_LOCAL_DATETIME_SPACE.test(originalRaw)) {\n // Local datetime with space separator - format: 2024-01-15 10:30:00\n const msMatch = originalRaw.match(/\\.(\\d+)\\s*$/);\n let isoString = newJSDate.toISOString().replace('Z', '').replace('T', ' ');\n if (msMatch) {\n const msDigits = msMatch[1].length;\n // isoString is like \"2024-01-15 10:30:00.123\"\n const [datePart, timePart] = isoString.split(' ');\n const [h, m, sMs] = timePart.split(':');\n const [s] = sMs.split('.');\n const ms = String(newJSDate.getUTCMilliseconds()).padStart(3, '0').slice(0, msDigits);\n isoString = `${datePart} ${h}:${m}:${s}.${ms}`;\n }\n // If original had no milliseconds, keep isoString as-is (with milliseconds if present)\n return new LocalDateTime(isoString, true, originalRaw);\n } else if (DateFormatHelper.IS_OFFSET_DATETIME_T.test(originalRaw) || DateFormatHelper.IS_OFFSET_DATETIME_SPACE.test(originalRaw)) {\n // Offset datetime - preserve the original timezone offset and separator\n const offsetMatch = originalRaw.match(/([+-]\\d{2}:\\d{2}|[Zz])$/);\n const originalOffset = offsetMatch ? (offsetMatch[1] === 'z' ? 'Z' : offsetMatch[1]) : 'Z';\n const useSpaceSeparator = DateFormatHelper.IS_OFFSET_DATETIME_SPACE.test(originalRaw);\n \n // Check if original had milliseconds and preserve precision\n const msMatch = originalRaw.match(/\\.(\\d+)(?:[Zz]|[+-]\\d{2}:\\d{2})\\s*$/);\n \n // Convert UTC time to local time in the original timezone\n const utcTime = newJSDate.getTime();\n let offsetMinutes = 0;\n \n if (originalOffset !== 'Z') {\n const sign = originalOffset[0] === '+' ? 1 : -1;\n const [hours, minutes] = originalOffset.slice(1).split(':');\n offsetMinutes = sign * (parseInt(hours) * 60 + parseInt(minutes));\n }\n \n // Create local time by applying the offset to UTC\n const localTime = new Date(utcTime + offsetMinutes * 60000);\n \n // Format the local time components\n const year = localTime.getUTCFullYear();\n const month = String(localTime.getUTCMonth() + 1).padStart(2, '0');\n const day = String(localTime.getUTCDate()).padStart(2, '0');\n const hours = String(localTime.getUTCHours()).padStart(2, '0');\n const minutes = String(localTime.getUTCMinutes()).padStart(2, '0');\n const seconds = String(localTime.getUTCSeconds()).padStart(2, '0');\n const milliseconds = localTime.getUTCMilliseconds();\n \n const separator = useSpaceSeparator ? ' ' : 'T';\n let timePart = `${hours}:${minutes}:${seconds}`;\n \n // Handle millisecond precision\n if (msMatch) {\n const msDigits = msMatch[1].length;\n const ms = String(milliseconds).padStart(3, '0').slice(0, msDigits);\n timePart += `.${ms}`;\n } else if (milliseconds > 0) {\n // Original had no milliseconds, but new value has them\n const ms = String(milliseconds).padStart(3, '0').replace(/0+$/, '');\n timePart += `.${ms}`;\n }\n \n const newDateTimeString = `${year}-${month}-${day}${separator}${timePart}${originalOffset}`;\n return new OffsetDateTime(newDateTimeString, useSpaceSeparator);\n } else {\n // Fallback to regular Date\n return newJSDate;\n }\n }\n}\n\n/**\n * Custom Date class for local dates (date-only).\n * Format: 1979-05-27\n */\nexport class LocalDate extends Date {\n\n constructor(value: string) {\n super(value);\n }\n \n toISOString(): string {\n const year = this.getUTCFullYear();\n const month = String(this.getUTCMonth() + 1).padStart(2, '0');\n const day = String(this.getUTCDate()).padStart(2, '0');\n return `${year}-${month}-${day}`;\n }\n}\n\n/**\n * Custom Date class for local times (time-only)\n * Format: 07:32:00 or 07:32:00.999\n */\nexport class LocalTime extends Date {\n originalFormat: string;\n \n constructor(value: string, originalFormat: string) {\n // For local time, use a fixed date (1970-01-01) and the provided time\n super(`1970-01-01T${value}`);\n this.originalFormat = originalFormat;\n }\n \n toISOString(): string {\n const hours = String(this.getUTCHours()).padStart(2, '0');\n const minutes = String(this.getUTCMinutes()).padStart(2, '0');\n const seconds = String(this.getUTCSeconds()).padStart(2, '0');\n const milliseconds = this.getUTCMilliseconds();\n \n // Check if the original format had milliseconds\n const originalHadMs = this.originalFormat && this.originalFormat.includes('.');\n \n if (originalHadMs) {\n // Determine the number of millisecond digits from the original format\n const msMatch = this.originalFormat.match(/\\.(\\d+)\\s*$/);\n const msDigits = msMatch ? msMatch[1].length : 3;\n \n const ms = String(milliseconds).padStart(3, '0').slice(0, msDigits);\n return `${hours}:${minutes}:${seconds}.${ms}`;\n } else if (milliseconds > 0) {\n // Original had no milliseconds, but current has non-zero milliseconds\n // Show them with trailing zeros removed\n const ms = String(milliseconds).padStart(3, '0').replace(/0+$/, '');\n return `${hours}:${minutes}:${seconds}.${ms}`;\n }\n \n return `${hours}:${minutes}:${seconds}`;\n }\n}\n\n/**\n * Custom Date class for local datetime (no timezone)\n * Format: 1979-05-27T07:32:00 or 1979-05-27 07:32:00\n */\nexport class LocalDateTime extends Date {\n useSpaceSeparator: boolean = false;\n originalFormat: string;\n \n constructor(value: string, useSpaceSeparator: boolean = false, originalFormat?: string) {\n // Convert space to T for Date parsing, but remember the original format\n super(value.replace(' ', 'T') + 'Z');\n this.useSpaceSeparator = useSpaceSeparator;\n this.originalFormat = originalFormat || value;\n }\n \n toISOString(): string {\n const year = this.getUTCFullYear();\n const month = String(this.getUTCMonth() + 1).padStart(2, '0');\n const day = String(this.getUTCDate()).padStart(2, '0');\n const hours = String(this.getUTCHours()).padStart(2, '0');\n const minutes = String(this.getUTCMinutes()).padStart(2, '0');\n const seconds = String(this.getUTCSeconds()).padStart(2, '0');\n const milliseconds = this.getUTCMilliseconds();\n \n const datePart = `${year}-${month}-${day}`;\n const separator = this.useSpaceSeparator ? ' ' : 'T';\n \n // Check if the original format had milliseconds\n const originalHadMs = this.originalFormat && this.originalFormat.includes('.');\n \n if (originalHadMs) {\n // Determine the number of millisecond digits from the original format\n const msMatch = this.originalFormat.match(/\\.(\\d+)\\s*$/);\n const msDigits = msMatch ? msMatch[1].length : 3;\n \n const ms = String(milliseconds).padStart(3, '0').slice(0, msDigits);\n return `${datePart}${separator}${hours}:${minutes}:${seconds}.${ms}`;\n } else if (milliseconds > 0) {\n // Original had no milliseconds, but current has non-zero milliseconds\n // Show them with trailing zeros removed\n const ms = String(milliseconds).padStart(3, '0').replace(/0+$/, '');\n return `${datePart}${separator}${hours}:${minutes}:${seconds}.${ms}`;\n }\n \n return `${datePart}${separator}${hours}:${minutes}:${seconds}`;\n }\n}\n\n/**\n * Custom Date class for offset datetime that preserves space separator\n * Format: 1979-05-27T07:32:00Z or 1979-05-27 07:32:00-07:00\n */\nexport class OffsetDateTime extends Date {\n useSpaceSeparator: boolean = false;\n originalOffset?: string;\n originalFormat: string;\n \n constructor(value: string, useSpaceSeparator: boolean = false) {\n super(value.replace(' ', 'T'));\n this.useSpaceSeparator = useSpaceSeparator;\n this.originalFormat = value;\n \n // Extract and preserve the original offset\n const offsetMatch = value.match(/([+-]\\d{2}:\\d{2}|[Zz])$/);\n if (offsetMatch) {\n this.originalOffset = offsetMatch[1] === 'z' ? 'Z' : offsetMatch[1];\n }\n }\n \n toISOString(): string {\n if (this.originalOffset) {\n // Calculate the local time in the original timezone\n const utcTime = this.getTime();\n let offsetMinutes = 0;\n \n if (this.originalOffset !== 'Z') {\n const sign = this.originalOffset[0] === '+' ? 1 : -1;\n const [hours, minutes] = this.originalOffset.slice(1).split(':');\n offsetMinutes = sign * (parseInt(hours) * 60 + parseInt(minutes));\n }\n \n const localTime = new Date(utcTime + offsetMinutes * 60000);\n const year = localTime.getUTCFullYear();\n const month = String(localTime.getUTCMonth() + 1).padStart(2, '0');\n const day = String(localTime.getUTCDate()).padStart(2, '0');\n const hours = String(localTime.getUTCHours()).padStart(2, '0');\n const minutes = String(localTime.getUTCMinutes()).padStart(2, '0');\n const seconds = String(localTime.getUTCSeconds()).padStart(2, '0');\n const milliseconds = localTime.getUTCMilliseconds();\n \n const datePart = `${year}-${month}-${day}`;\n const separator = this.useSpaceSeparator ? ' ' : 'T';\n \n // Check if the original format had milliseconds\n const originalHadMs = this.originalFormat && this.originalFormat.includes('.');\n \n if (originalHadMs) {\n // Determine the number of millisecond digits from the original format\n const msMatch = this.originalFormat.match(/\\.(\\d+)(?:[Zz]|[+-]\\d{2}:\\d{2})\\s*$/);\n const msDigits = msMatch ? msMatch[1].length : 3;\n \n const ms = String(milliseconds).padStart(3, '0').slice(0, msDigits);\n return `${datePart}${separator}${hours}:${minutes}:${seconds}.${ms}${this.originalOffset}`;\n } else if (milliseconds > 0) {\n // Original had no milliseconds, but current has non-zero milliseconds\n // Show them with trailing zeros removed\n const ms = String(milliseconds).padStart(3, '0').replace(/0+$/, '');\n return `${datePart}${separator}${hours}:${minutes}:${seconds}.${ms}${this.originalOffset}`;\n }\n \n return `${datePart}${separator}${hours}:${minutes}:${seconds}${this.originalOffset}`;\n }\n \n const isoString = super.toISOString();\n if (this.useSpaceSeparator) {\n return isoString.replace('T', ' ');\n }\n return isoString;\n }\n}","import {\n NodeType,\n KeyValue,\n Table,\n TableKey,\n TableArray,\n TableArrayKey,\n Key,\n Value,\n String,\n Integer,\n Float,\n Boolean,\n DateTime,\n InlineTable,\n InlineArray,\n InlineItem,\n Comment,\n AST,\n Block\n} from './ast';\nimport { Token, TokenType, tokenize, DOUBLE_QUOTE, SINGLE_QUOTE } from './tokenizer';\nimport { parseString } from './parse-string';\nimport Cursor from './cursor';\nimport { clonePosition, cloneLocation } from './location';\nimport ParseError from './parse-error';\nimport { merge } from './utils';\n\nimport {\n DateFormatHelper,\n LocalDate,\n LocalTime,\n LocalDateTime,\n OffsetDateTime\n} from './date-format';\n\n// Create a shorter alias for convenience\nconst dateFormatHelper = DateFormatHelper;\n\nconst TRUE = 'true';\nconst FALSE = 'false';\nconst HAS_E = /e/i;\nconst IS_DIVIDER = /\\_/g;\nconst IS_INF = /inf/;\nconst IS_NAN = /nan/;\nconst IS_HEX = /^0x/;\nconst IS_OCTAL = /^0o/;\nconst IS_BINARY = /^0b/;\n\n// Export the date classes for external use\nexport {\n LocalDate,\n LocalTime,\n LocalDateTime,\n OffsetDateTime,\n DateFormatHelper\n} from './date-format';\n\nexport default function* parseTOML(input: string): AST {\n const tokens = tokenize(input);\n const cursor = new Cursor(tokens);\n\n while (!cursor.next().done) {\n yield* walkBlock(cursor, input);\n }\n}\n\n/**\n * Continues parsing TOML from a remaining string and appends the results to an existing AST.\n * \n * @param existingAst - The existing AST to append to\n * @param remainingString - The remaining TOML string to parse\n * @returns A new complete AST with both the existing and newly parsed items\n */\nexport function* continueParsingTOML(existingAst: AST, remainingString: string): AST {\n // Yield all items from the existing AST\n for (const item of existingAst) {\n yield item;\n }\n \n // Parse and yield all items from the remaining string\n for (const item of parseTOML(remainingString)) {\n yield item;\n }\n}\n\nfunction* walkBlock(cursor: Cursor<Token>, input: string): IterableIterator<Block> {\n if (cursor.value!.type === TokenType.Comment) {\n yield comment(cursor);\n } else if (cursor.value!.type === TokenType.Bracket) {\n yield table(cursor, input);\n } else if (cursor.value!.type === TokenType.Literal) {\n yield* keyValue(cursor, input);\n } else {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n `Unexpected token \"${cursor.value!.type}\". Expected Comment, Bracket, or String`\n );\n }\n}\n\nfunction* walkValue(cursor: Cursor<Token>, input: string): IterableIterator<Value | Comment> {\n if (cursor.value!.type === TokenType.Literal) {\n if (cursor.value!.raw[0] === DOUBLE_QUOTE || cursor.value!.raw[0] === SINGLE_QUOTE) {\n yield string(cursor);\n } else if (cursor.value!.raw === TRUE || cursor.value!.raw === FALSE) {\n yield boolean(cursor);\n } else if (dateFormatHelper.IS_FULL_DATE.test(cursor.value!.raw) || dateFormatHelper.IS_FULL_TIME.test(cursor.value!.raw)) {\n yield datetime(cursor, input);\n } else if (\n (!cursor.peek().done && cursor.peek().value!.type === TokenType.Dot) ||\n IS_INF.test(cursor.value!.raw) ||\n IS_NAN.test(cursor.value!.raw) ||\n (HAS_E.test(cursor.value!.raw) && !IS_HEX.test(cursor.value!.raw))\n ) {\n yield float(cursor, input);\n } else {\n yield integer(cursor);\n }\n } else if (cursor.value!.type === TokenType.Curly) {\n yield inlineTable(cursor, input);\n } else if (cursor.value!.type === TokenType.Bracket) {\n const [inline_array, comments] = inlineArray(cursor, input);\n\n yield inline_array;\n yield* comments;\n } else {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n `Unrecognized token type \"${cursor.value!.type}\". Expected String, Curly, or Bracket`\n );\n }\n}\n\nfunction comment(cursor: Cursor<Token>): Comment {\n // # line comment\n // ^------------^ Comment\n return {\n type: NodeType.Comment,\n loc: cursor.value!.loc,\n raw: cursor.value!.raw\n };\n}\n\nfunction table(cursor: Cursor<Token>, input: string): Table | TableArray {\n // Table or TableArray\n //\n // [ key ]\n // ^-----^ TableKey\n // ^-^ Key\n //\n // [[ key ]]\n // ^ ------^ TableArrayKey\n // ^-^ Key\n //\n // a = \"b\" < Items\n // # c |\n // d = \"f\" <\n //\n // ...\n const type =\n !cursor.peek().done && cursor.peek().value!.type === TokenType.Bracket\n ? NodeType.TableArray\n : NodeType.Table;\n const is_table = type === NodeType.Table;\n\n if (is_table && cursor.value!.raw !== '[') {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n `Expected table opening \"[\", found ${cursor.value!.raw}`\n );\n }\n if (!is_table && (cursor.value!.raw !== '[' || cursor.peek().value!.raw !== '[')) {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n `Expected array of tables opening \"[[\", found ${cursor.value!.raw + cursor.peek().value!.raw}`\n );\n }\n\n // Set start location from opening tag\n const key = is_table\n ? ({\n type: NodeType.TableKey,\n loc: cursor.value!.loc\n } as Partial<TableKey>)\n : ({\n type: NodeType.TableArrayKey,\n loc: cursor.value!.loc\n } as Partial<TableArrayKey>);\n\n // Skip to cursor.value for key value\n cursor.next();\n if (type === NodeType.TableArray) cursor.next();\n\n if (cursor.done) {\n throw new ParseError(input, key.loc!.start, `Expected table key, reached end of file`);\n }\n\n key.item = {\n type: NodeType.Key,\n loc: cloneLocation(cursor.value!.loc),\n raw: cursor.value!.raw,\n value: [parseString(cursor.value!.raw)]\n };\n\n while (!cursor.peek().done && cursor.peek().value!.type === TokenType.Dot) {\n cursor.next();\n const dot = cursor.value!;\n\n cursor.next();\n const before = ' '.repeat(dot.loc.start.column - key.item.loc.end.column);\n const after = ' '.repeat(cursor.value!.loc.start.column - dot.loc.end.column);\n\n key.item.loc.end = cursor.value!.loc.end;\n key.item.raw += `${before}.${after}${cursor.value!.raw}`;\n key.item.value.push(parseString(cursor.value!.raw));\n }\n\n cursor.next();\n\n if (is_table && (cursor.done || cursor.value!.raw !== ']')) {\n throw new ParseError(\n input,\n cursor.done ? key.item.loc.end : cursor.value!.loc.start,\n `Expected table closing \"]\", found ${cursor.done ? 'end of file' : cursor.value!.raw}`\n );\n }\n if (\n !is_table &&\n (cursor.done ||\n cursor.peek().done ||\n cursor.value!.raw !== ']' ||\n cursor.peek().value!.raw !== ']')\n ) {\n throw new ParseError(\n input,\n cursor.done || cursor.peek().done ? key.item.loc.end : cursor.value!.loc.start,\n `Expected array of tables closing \"]]\", found ${\n cursor.done || cursor.peek().done\n ? 'end of file'\n : cursor.value!.raw + cursor.peek().value!.raw\n }`\n );\n }\n\n // Set end location from closing tag\n if (!is_table) cursor.next();\n key.loc!.end = cursor.value!.loc.end;\n\n // Add child items\n let items: Array<KeyValue | Comment> = [];\n while (!cursor.peek().done && cursor.peek().value!.type !== TokenType.Bracket) {\n cursor.next();\n merge(items, [...walkBlock(cursor, input)] as Array<KeyValue | Comment>);\n }\n\n return {\n type: is_table ? NodeType.Table : NodeType.TableArray,\n loc: {\n start: clonePosition(key.loc!.start),\n end: items.length\n ? clonePosition(items[items.length - 1].loc.end)\n : clonePosition(key.loc!.end)\n },\n key: key as TableKey | TableArrayKey,\n items\n } as Table | TableArray;\n}\n\nfunction keyValue(cursor: Cursor<Token>, input: string): Array<KeyValue | Comment> {\n // 3. KeyValue\n //\n // key = value\n // ^-^ key\n // ^ equals\n // ^---^ value\n const key: Key = {\n type: NodeType.Key,\n loc: cloneLocation(cursor.value!.loc),\n raw: cursor.value!.raw,\n value: [parseString(cursor.value!.raw)]\n };\n\n while (!cursor.peek().done && cursor.peek().value!.type === TokenType.Dot) {\n cursor.next();\n cursor.next();\n\n key.loc.end = cursor.value!.loc.end;\n key.raw += `.${cursor.value!.raw}`;\n key.value.push(parseString(cursor.value!.raw));\n }\n\n cursor.next();\n\n if (cursor.done || cursor.value!.type !== TokenType.Equal) {\n throw new ParseError(\n input,\n cursor.done ? key.loc.end : cursor.value!.loc.start,\n `Expected \"=\" for key-value, found ${cursor.done ? 'end of file' : cursor.value!.raw}`\n );\n }\n\n const equals = cursor.value!.loc.start.column;\n\n cursor.next();\n\n if (cursor.done) {\n throw new ParseError(input, key.loc.start, `Expected value for key-value, reached end of file`);\n }\n\n const [value, ...comments] = walkValue(cursor, input) as Iterable<Value | Comment>;\n\n return [\n {\n type: NodeType.KeyValue,\n key,\n value: value as Value,\n loc: {\n start: clonePosition(key.loc.start),\n end: clonePosition(value.loc.end)\n },\n equals\n },\n ...(comments as Comment[])\n ];\n}\n\nfunction string(cursor: Cursor<Token>): String {\n return {\n type: NodeType.String,\n loc: cursor.value!.loc,\n raw: cursor.value!.raw,\n value: parseString(cursor.value!.raw)\n };\n}\n\nfunction boolean(cursor: Cursor<Token>): Boolean {\n return {\n type: NodeType.Boolean,\n loc: cursor.value!.loc,\n value: cursor.value!.raw === TRUE\n };\n}\n\nfunction datetime(cursor: Cursor<Token>, input: string): DateTime {\n // Possible values:\n //\n // Offset Date-Time\n // | odt1 = 1979-05-27T07:32:00Z\n // | odt2 = 1979-05-27T00:32:00-07:00\n // | odt3 = 1979-05-27T00:32:00.999999-07:00\n // | odt4 = 1979-05-27 07:32:00Z\n //\n // Local Date-Time\n // | ldt1 = 1979-05-27T07:32:00\n // | ldt2 = 1979-05-27T00:32:00.999999\n //\n // Local Date\n // | ld1 = 1979-05-27\n //\n // Local Time\n // | lt1 = 07:32:00\n // | lt2 = 00:32:00.999999\n let loc = cursor.value!.loc;\n let raw = cursor.value!.raw;\n let value: Date;\n\n // If next token is string,\n // check if raw is full date and following is full time\n if (\n !cursor.peek().done &&\n cursor.peek().value!.type === TokenType.Literal &&\n dateFormatHelper.IS_FULL_DATE.test(raw) &&\n dateFormatHelper.IS_FULL_TIME.test(cursor.peek().value!.raw)\n ) {\n const start = loc.start;\n\n cursor.next();\n loc = { start, end: cursor.value!.loc.end };\n raw += ` ${cursor.value!.raw}`;\n }\n\n if (!cursor.peek().done && cursor.peek().value!.type === TokenType.Dot) {\n const start = loc.start;\n\n cursor.next();\n\n if (cursor.peek().done || cursor.peek().value!.type !== TokenType.Literal) {\n throw new ParseError(input, cursor.value!.loc.end, `Expected fractional value for DateTime`);\n }\n cursor.next();\n\n loc = { start, end: cursor.value!.loc.end };\n raw += `.${cursor.value!.raw}`;\n }\n\n if (!dateFormatHelper.IS_FULL_DATE.test(raw)) {\n // Local time only (e.g., \"07:32:00\" or \"07:32:00.999\")\n if (dateFormatHelper.IS_TIME_ONLY.test(raw)) {\n value = new LocalTime(raw, raw) as any;\n } else {\n // For other time formats, use local ISO date\n const [local_date] = new Date().toISOString().split('T');\n value = new Date(`${local_date}T${raw}`);\n }\n } else if (dateFormatHelper.IS_DATE_ONLY.test(raw)) {\n // Local date only (e.g., \"1979-05-27\")\n value = new LocalDate(raw) as any;\n } else if (dateFormatHelper.IS_LOCAL_DATETIME_T.test(raw)) {\n // Local datetime with T separator (e.g., \"1979-05-27T07:32:00\")\n value = new LocalDateTime(raw, false) as any;\n } else if (dateFormatHelper.IS_LOCAL_DATETIME_SPACE.test(raw)) {\n // Local datetime with space separator (e.g., \"1979-05-27 07:32:00\")\n value = new LocalDateTime(raw, true) as any;\n } else if (dateFormatHelper.IS_OFFSET_DATETIME_T.test(raw)) {\n // Offset datetime with T separator (e.g., \"1979-05-27T07:32:00Z\" or \"1979-05-27T07:32:00-07:00\")\n value = new OffsetDateTime(raw, false) as any;\n } else if (dateFormatHelper.IS_OFFSET_DATETIME_SPACE.test(raw)) {\n // Offset datetime with space separator (e.g., \"1979-05-27 07:32:00Z\")\n value = new OffsetDateTime(raw, true) as any;\n } else {\n // Default: offset datetime with T separator or any other format\n value = new Date(raw.replace(' ', 'T'));\n }\n\n return {\n type: NodeType.DateTime,\n loc,\n raw,\n value\n };\n}\n\nfunction float(cursor: Cursor<Token>, input: string): Float {\n let loc = cursor.value!.loc;\n let raw = cursor.value!.raw;\n let value;\n\n if (IS_INF.test(raw)) {\n value = raw === '-inf' ? -Infinity : Infinity;\n } else if (IS_NAN.test(raw)) {\n value = raw === '-nan' ? -NaN : NaN;\n } else if (!cursor.peek().done && cursor.peek().value!.type === TokenType.Dot) {\n const start = loc.start;\n\n // From spec:\n // | A fractional part is a decimal point followed by one or more digits.\n //\n // -> Don't have to handle \"4.\" (i.e. nothing behind decimal place)\n\n cursor.next();\n\n if (cursor.peek().done || cursor.peek().value!.type !== TokenType.Literal) {\n throw new ParseError(input, cursor.value!.loc.end, `Expected fraction value for Float`);\n }\n cursor.next();\n\n raw += `.${cursor.value!.raw}`;\n loc = { start, end: cursor.value!.loc.end };\n value = Number(raw.replace(IS_DIVIDER, ''));\n } else {\n value = Number(raw.replace(IS_DIVIDER, ''));\n }\n\n return { type: NodeType.Float, loc, raw, value };\n}\n\nfunction integer(cursor: Cursor<Token>): Integer {\n // > Integer values -0 and +0 are valid and identical to an unprefixed zero\n if (cursor.value!.raw === '-0' || cursor.value!.raw === '+0') {\n return {\n type: NodeType.Integer,\n loc: cursor.value!.loc,\n raw: cursor.value!.raw,\n value: 0\n };\n }\n\n let radix = 10;\n if (IS_HEX.test(cursor.value!.raw)) {\n radix = 16;\n } else if (IS_OCTAL.test(cursor.value!.raw)) {\n radix = 8;\n } else if (IS_BINARY.test(cursor.value!.raw)) {\n radix = 2;\n }\n\n const value = parseInt(\n cursor\n .value!.raw.replace(IS_DIVIDER, '')\n .replace(IS_OCTAL, '')\n .replace(IS_BINARY, ''),\n radix\n );\n\n return {\n type: NodeType.Integer,\n loc: cursor.value!.loc,\n raw: cursor.value!.raw,\n value\n };\n}\n\nfunction inlineTable(cursor: Cursor<Token>, input: string): InlineTable {\n if (cursor.value!.raw !== '{') {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n `Expected \"{\" for inline table, found ${cursor.value!.raw}`\n );\n }\n\n // 6. InlineTable\n const value: InlineTable = {\n type: NodeType.InlineTable,\n loc: cloneLocation(cursor.value!.loc),\n items: []\n };\n\n cursor.next();\n\n while (\n !cursor.done &&\n !(cursor.value!.type === TokenType.Curly && (cursor.value as Token).raw === '}')\n ) {\n if ((cursor.value as Token).type === TokenType.Comma) {\n const previous = value.items[value.items.length - 1];\n if (!previous) {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n 'Found \",\" without previous value in inline table'\n );\n }\n\n previous.comma = true;\n previous.loc.end = cursor.value!.loc.start;\n\n cursor.next();\n continue;\n }\n\n const [item] = walkBlock(cursor, input);\n if (item.type !== NodeType.KeyValue) {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n `Only key-values are supported in inline tables, found ${item.type}`\n );\n }\n\n const inline_item: InlineItem<KeyValue> = {\n type: NodeType.InlineItem,\n loc: cloneLocation(item.loc),\n item,\n comma: false\n };\n\n value.items.push(inline_item);\n cursor.next();\n }\n\n if (\n cursor.done ||\n cursor.value!.type !== TokenType.Curly ||\n (cursor.value as Token).raw !== '}'\n ) {\n throw new ParseError(\n input,\n cursor.done ? value.loc.start : cursor.value!.loc.start,\n `Expected \"}\", found ${cursor.done ? 'end of file' : cursor.value!.raw}`\n );\n }\n\n value.loc.end = cursor.value!.loc.end;\n\n return value;\n}\n\nfunction inlineArray(cursor: Cursor<Token>, input: string): [InlineArray, Comment[]] {\n // 7. InlineArray\n if (cursor.value!.raw !== '[') {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n `Expected \"[\" for inline array, found ${cursor.value!.raw}`\n );\n }\n\n const value: InlineArray = {\n type: NodeType.InlineArray,\n loc: cloneLocation(cursor.value!.loc),\n items: []\n };\n let comments: Comment[] = [];\n\n cursor.next();\n\n while (\n !cursor.done &&\n !(cursor.value!.type === TokenType.Bracket && (cursor.value as Token).raw === ']')\n ) {\n if ((cursor.value as Token).type === TokenType.Comma) {\n const previous = value.items[value.items.length - 1];\n if (!previous) {\n throw new ParseError(\n input,\n cursor.value!.loc.start,\n 'Found \",\" without previous value for inline array'\n );\n }\n\n previous.comma = true;\n previous.loc.end = cursor.value!.loc.start;\n } else if ((cursor.value as Token).type === TokenType.Comment) {\n comments.push(comment(cursor));\n } else {\n const [item, ...additional_comments] = walkValue(cursor, input);\n const inline_item: InlineItem = {\n type: NodeType.InlineItem,\n loc: cloneLocation(item.loc),\n item,\n comma: false\n };\n\n value.items.push(inline_item);\n merge(comments, additional_comments as Comment[]);\n }\n\n cursor.next();\n }\n\n if (\n cursor.done ||\n cursor.value!.type !== TokenType.Bracket ||\n (cursor.value as Token).raw !== ']'\n ) {\n throw new ParseError(\n input,\n cursor.done ? value.loc.start : cursor.value!.loc.start,\n `Expected \"]\", found ${cursor.done ? 'end of file' : cursor.value!.raw}`\n );\n }\n\n value.loc.end = cursor.value!.loc.end;\n\n return [value, comments];\n}\n","import {\n NodeType,\n AST,\n TreeNode,\n Document,\n Table,\n TableKey,\n TableArray,\n TableArrayKey,\n KeyValue,\n Key,\n String,\n Integer,\n Float,\n Boolean,\n DateTime,\n Comment,\n InlineArray,\n InlineTable,\n InlineItem\n} from './ast';\nimport { isIterable } from './utils';\n\nexport type Visit<TNode = TreeNode> = (node: TNode, parent: TNode | null) => void;\nexport type EnterExit<TNode = TreeNode> = { enter?: Visit<TNode>; exit?: Visit<TNode> };\n\nexport type Visitor = {\n Document?: Visit<Document> | EnterExit<Document>;\n Table?: Visit<Table> | EnterExit<Table>;\n TableKey?: Visit<TableKey> | EnterExit<TableKey>;\n TableArray?: Visit<TableArray> | EnterExit<TableArray>;\n TableArrayKey?: Visit<TableArrayKey> | EnterExit<TableArrayKey>;\n KeyValue?: Visit<KeyValue> | EnterExit<KeyValue>;\n Key?: Visit<Key> | EnterExit<Key>;\n String?: Visit<String> | EnterExit<String>;\n Integer?: Visit<Integer> | EnterExit<Integer>;\n Float?: Visit<Float> | EnterExit<Float>;\n Boolean?: Visit<Boolean> | EnterExit<Boolean>;\n DateTime?: Visit<DateTime> | EnterExit<DateTime>;\n InlineArray?: Visit<InlineArray> | EnterExit<InlineArray>;\n InlineItem?: Visit<InlineItem> | EnterExit<InlineItem>;\n InlineTable?: Visit<InlineTable> | EnterExit<InlineTable>;\n Comment?: Visit<Comment> | EnterExit<Comment>;\n};\n\n////////////////////////////////////////////////////////////////////////////////\n// The traverse function is used to walk the AST and call the visitor functions\n////////////////////////////////////////////////////////////////////////////////\nexport default function traverse(ast: AST | TreeNode, visitor: Visitor) {\n if (isIterable(ast)) {\n traverseArray(ast, null);\n } else {\n traverseNode(ast, null);\n }\n\n function traverseArray(array: Iterable<TreeNode>, parent: TreeNode | null) {\n for (const node of array) {\n traverseNode(node, parent);\n }\n }\n\n function traverseNode(node: TreeNode, parent: TreeNode | null) {\n const visit = visitor[node.type];\n\n if (visit && typeof visit === 'function') {\n (visit as Visit)(node, parent);\n }\n\n if (visit && (visit as EnterExit).enter) {\n (visit as EnterExit).enter!(node, parent);\n }\n\n switch (node.type) {\n case NodeType.Document:\n traverseArray((node as Document).items, node);\n break;\n\n case NodeType.Table:\n traverseNode((node as Table).key, node);\n traverseArray((node as Table).items, node);\n break;\n case NodeType.TableKey:\n traverseNode((node as TableKey).item, node);\n break;\n\n case NodeType.TableArray:\n traverseNode((node as TableArray).key, node);\n traverseArray((node as TableArray).items, node);\n break;\n case NodeType.TableArrayKey:\n traverseNode((node as TableArrayKey).item, node);\n break;\n\n case NodeType.KeyValue:\n traverseNode((node as KeyValue).key, node);\n traverseNode((node as KeyValue).value, node);\n break;\n\n case NodeType.InlineArray:\n traverseArray((node as InlineArray).items, node);\n break;\n case NodeType.InlineItem:\n traverseNode((node as InlineItem).item, node);\n break;\n\n case NodeType.InlineTable:\n traverseArray((node as InlineTable).items, node);\n break;\n\n case NodeType.Key:\n case NodeType.String:\n case NodeType.Integer:\n case NodeType.Float:\n case NodeType.Boolean:\n case NodeType.DateTime:\n case NodeType.Comment:\n break;\n\n default:\n throw new Error(`Unrecognized node type \"${node.type}\"`);\n }\n\n if (visit && (visit as EnterExit).exit) {\n (visit as EnterExit).exit!(node, parent);\n }\n }\n}\n","import {\n NodeType,\n TreeNode,\n Document,\n Key,\n Value,\n InlineArray,\n InlineArrayItem,\n InlineTableItem,\n isKeyValue,\n isTable,\n isTableArray,\n isInlineTable,\n isInlineArray,\n hasItems,\n hasItem,\n isComment,\n isDocument,\n InlineTable,\n TableArray,\n Table,\n KeyValue,\n Comment,\n InlineItem,\n isInlineItem,\n Block,\n isBlock,\n DateTime,\n isDateTime\n} from './ast';\nimport { Span, getSpan, clonePosition } from './location';\nimport { last } from './utils';\nimport traverse from './traverse';\n\n////////////////////////////////////////\n// The purpose of this file is to provide a way to modify the AST\n////////////////////////////////////////\n\nimport { DateFormatHelper } from './date-format';\n\n// Create a shorter alias for convenience\nconst dateFormatHelper = DateFormatHelper;\n\n// Root node of the AST\nexport type Root = Document | TreeNode;\n\n// Store line and column offsets per node\n//\n// Some offsets are applied on enter (e.g. shift child items and next items)\n// Others are applied on exit (e.g. shift next items)\ntype Offsets = WeakMap<TreeNode, Span>;\n\nconst enter_offsets: WeakMap<Root, Offsets> = new WeakMap();\nconst getEnterOffsets = (root: Root) => {\n if (!enter_offsets.has(root)) {\n enter_offsets.set(root, new WeakMap());\n }\n return enter_offsets.get(root)!;\n};\n\nconst exit_offsets: WeakMap<Root, Offsets> = new WeakMap();\nconst getExitOffsets = (root: Root) => {\n if (!exit_offsets.has(root)) {\n exit_offsets.set(root, new WeakMap());\n }\n return exit_offsets.get(root)!;\n};\n//TODO: Add getOffsets function to get all offsets contained in the tree\nexport function replace(root: Root, parent: TreeNode, existing: TreeNode, replacement: TreeNode) {\n \n // Special handling for DateTime nodes to preserve original format\n if (isDateTime(existing) && isDateTime(replacement)) {\n // Analyze the original raw format and create a properly formatted replacement\n const originalRaw = existing.raw;\n const newValue = replacement.value;\n \n // Create a new date with the original format preserved\n const formattedDate = dateFormatHelper.createDateWithOriginalFormat(newValue, originalRaw);\n \n // Update the replacement with the properly formatted date\n replacement.value = formattedDate;\n replacement.raw = formattedDate.toISOString();\n \n // Adjust the location information to match the new raw length\n const lengthDiff = replacement.raw.length - originalRaw.length;\n if (lengthDiff !== 0) {\n replacement.loc.end.column = replacement.loc.start.column + replacement.raw.length;\n }\n }\n \n // First, replace existing node\n // (by index for items, item, or key/value)\n if (hasItems(parent)) {\n\n const index = parent.items.indexOf(existing);\n if (index < 0) {\n throw new Error(`Could not find existing item in parent node for replace`);\n }\n\n parent.items.splice(index, 1, replacement);\n\n // This next case is a special case for Inline-Table item\n // however due to the fact that both replacement of the whole Inline-Table and Inline-Table element will have the same parent,\n // we need to make sure it's not an Inline-Table \n } else if (isKeyValue(parent) && isInlineTable(parent.value) && !isInlineTable(existing)) {\n \n const index = parent.value.items.indexOf(existing as InlineTableItem);\n if (index < 0) {\n throw new Error(`Could not find existing item in parent node for replace`);\n } \n parent.value.items.splice(index, 1, replacement as InlineTableItem);\n\n } else if (hasItem(parent)) {\n\n parent.item = replacement;\n\n } else if (isKeyValue(parent)) {\n\n if (parent.key === existing) {\n parent.key = replacement as Key;\n } else {\n parent.value = replacement as Value;\n }\n\n } else {\n throw new Error(`Unsupported parent type \"${parent.type}\" for replace`);\n }\n\n // Shift the replacement node into the same start position as existing\n const shift = {\n lines: existing.loc.start.line - replacement.loc.start.line,\n columns: existing.loc.start.column - replacement.loc.start.column\n };\n shiftNode(replacement, shift);\n\n // Apply offsets after replacement node\n const existing_span = getSpan(existing.loc);\n const replacement_span = getSpan(replacement.loc);\n const offset = {\n lines: replacement_span.lines - existing_span.lines,\n columns: replacement_span.columns - existing_span.columns\n };\n\n addOffset(offset, getExitOffsets(root), replacement, existing);\n}\n/**\n * Inserts a child node into the AST.\n *\n * @param root - The root node of the AST\n * @param parent - The parent node to insert the child into\n * @param child - The child node to insert\n * @param index - The index at which to insert the child (optional)\n * @param forceInline - Whether to force inline positioning even for document-level insertions (optional)\n */\nexport function insert(root: Root, parent: TreeNode, child: TreeNode, index?: number, forceInline?: boolean) {\n if (!hasItems(parent)) {\n throw new Error(`Unsupported parent type \"${(parent as TreeNode).type}\" for insert`);\n }\n\n index = (index != null && typeof index === 'number') ? index : parent.items.length; \n\n let shift: Span;\n let offset: Span;\n if (isInlineArray(parent) || isInlineTable(parent)) {\n ({ shift, offset } = insertInline(parent, child as InlineItem, index));\n } else if (forceInline && isDocument(parent)) {\n ({ shift, offset } = insertInlineAtRoot(parent, child, index));\n } else {\n ({ shift, offset } = insertOnNewLine(\n parent as Document | Table | TableArray,\n child as KeyValue | Comment,\n index\n ));\n }\n\n shiftNode(child, shift);\n\n // The child element is placed relative to the previous element,\n // if the previous element has an offset, need to position relative to that\n // -> Move previous offset to child's offset\n const previous = parent.items[index - 1];\n const previous_offset = previous && getExitOffsets(root).get(previous);\n if (previous_offset) {\n offset.lines += previous_offset.lines;\n offset.columns += previous_offset.columns;\n\n getExitOffsets(root).delete(previous!);\n }\n\n const offsets = getExitOffsets(root);\n offsets.set(child, offset);\n}\n\nfunction insertOnNewLine(\n parent: Document | Table | TableArray,\n child: Block,\n index: number\n): { shift: Span; offset: Span } {\n\n if (!isBlock(child)) {\n throw new Error(`Incompatible child type \"${(child as TreeNode).type}\"`);\n }\n\n const previous = parent.items[index - 1];\n const use_first_line = isDocument(parent) && !parent.items.length;\n\n parent.items.splice(index, 0, child);\n\n // Set start location from previous item or start of array\n // (previous is undefined for empty array or inserting at first item)\n const start = previous\n ? {\n line: previous.loc.end.line,\n column: !isComment(previous) ? previous.loc.start.column : parent.loc.start.column\n }\n : clonePosition(parent.loc.start);\n \n const isSquareBracketsStructure = isTable(child) || isTableArray(child);\n let leading_lines = 0;\n if (use_first_line) {\n // 0 leading lines\n } else if (isSquareBracketsStructure) {\n leading_lines = 2;\n } else {\n leading_lines = 1;\n }\n start.line += leading_lines;\n\n const shift = {\n lines: start.line - child.loc.start.line,\n columns: start.column - child.loc.start.column\n };\n\n // Apply offsets after child node\n const child_span = getSpan(child.loc);\n const offset = {\n lines: child_span.lines + (leading_lines - 1),\n columns: child_span.columns\n };\n\n return { shift, offset };\n}\n\n/**\n * Calculates positioning (shift and offset) for inserting a child into a parent container.\n * This function handles the core positioning logic used to insert an inline item inside a table (or at the document root level).\n * \n * @param parent - The parent container (Document, InlineArray or InlineTable)\n * @param child - The child node to be inserted\n * @param index - The insertion index within the parent's items\n * @param options - Configuration options for positioning calculation\n * @param options.useNewLine - Whether to place the child on a new line\n * @param options.skipCommaSpace - Number of columns to skip for comma + space (default: 2)\n * @param options.skipBracketSpace - Number of columns to skip for bracket/space (default: 1)\n * @param options.hasCommaHandling - Whether comma handling logic should be applied\n * @param options.isLastElement - Whether this is the last element in the container\n * @param options.hasSeparatingCommaBefore - Whether a comma should precede this element\n * @param options.hasSeparatingCommaAfter - Whether a comma should follow this element\n * @param options.hasTrailingComma - Whether the element has a trailing comma\n * @returns Object containing shift (positioning adjustment for the child) and offset (adjustment for following elements)\n */\nfunction calculateInlinePositioning(\n parent: Document | InlineArray | InlineTable,\n child: TreeNode,\n index: number,\n options: {\n useNewLine?: boolean;\n skipCommaSpace?: number;\n skipBracketSpace?: number;\n hasCommaHandling?: boolean;\n isLastElement?: boolean;\n hasSeparatingCommaBefore?: boolean;\n hasSeparatingCommaAfter?: boolean;\n hasTrailingComma?: boolean;\n } = {}\n): { shift: Span; offset: Span } {\n \n // Configuration options with default values\n const {\n useNewLine = false,\n skipCommaSpace = 2,\n skipBracketSpace = 1,\n hasCommaHandling = false,\n isLastElement = false,\n hasSeparatingCommaBefore = false,\n hasSeparatingCommaAfter = false,\n hasTrailingComma = false\n } = options;\n\n // Store preceding node\n const previous = index > 0 ? parent.items[index - 1] : undefined;\n\n // Set start location from previous item or start of parent\n const start = previous\n ? {\n line: previous.loc.end.line,\n column: useNewLine\n ? !isComment(previous)\n ? previous.loc.start.column\n : parent.loc.start.column\n : previous.loc.end.column\n }\n : clonePosition(parent.loc.start);\n\n let leading_lines = 0;\n if (useNewLine) {\n leading_lines = 1;\n } else {\n // Add spacing for inline positioning\n const hasSpacing = hasSeparatingCommaBefore || (!hasCommaHandling && !!previous);\n if (hasSpacing && hasCommaHandling) {\n start.column += skipCommaSpace;\n } else if (hasSpacing || (hasCommaHandling && !previous)) {\n start.column += skipBracketSpace;\n }\n }\n start.line += leading_lines;\n\n const shift = {\n lines: start.line - child.loc.start.line,\n columns: start.column - child.loc.start.column\n };\n\n // Apply offsets after child node\n const child_span = getSpan(child.loc);\n \n if (!hasCommaHandling) {\n // For documents or contexts without comma handling, simpler offset calculation\n const offset = {\n lines: child_span.lines + (leading_lines - 1),\n columns: child_span.columns\n };\n return { shift, offset };\n }\n\n // Special case: Fix trailing comma spacing issue for arrays that have trailing commas\n const has_trailing_comma_spacing_bug = \n hasSeparatingCommaBefore && \n hasTrailingComma && \n !hasSeparatingCommaAfter && \n isLastElement; \n\n let trailing_comma_offset_adjustment = 0;\n if (has_trailing_comma_spacing_bug) {\n trailing_comma_offset_adjustment = -1;\n }\n \n const offset = {\n lines: child_span.lines + (leading_lines - 1),\n columns: child_span.columns + \n (hasSeparatingCommaBefore || hasSeparatingCommaAfter ? skipCommaSpace : 0) + \n (hasTrailingComma ? 1 + trailing_comma_offset_adjustment : 0)\n };\n\n return { shift, offset };\n}\n\nfunction insertInline(\n parent: InlineArray | InlineTable,\n child: InlineItem,\n index: number\n): { shift: Span; offset: Span } {\n if (!isInlineItem(child)) {\n throw new Error(`Incompatible child type \"${(child as TreeNode).type}\"`);\n }\n\n // Store preceding node and insert\n const previous = index != null ? parent.items[index - 1] : last(parent.items as TreeNode[]);\n const is_last = index == null || index === parent.items.length;\n\n parent.items.splice(index, 0, child);\n\n // Add commas as-needed\n const has_separating_comma_before = !!previous;\n const has_separating_comma_after = !is_last;\n if (has_separating_comma_before) {\n (previous as InlineArrayItem | InlineTableItem).comma = true;\n }\n if (has_separating_comma_after) {\n child.comma = true;\n }\n\n // Use new line for inline arrays that span multiple lines\n const use_new_line = isInlineArray(parent) && perLine(parent);\n const has_trailing_comma = is_last && child.comma === true;\n\n return calculateInlinePositioning(parent, child, index, {\n useNewLine: use_new_line,\n hasCommaHandling: true,\n isLastElement: is_last,\n hasSeparatingCommaBefore: has_separating_comma_before,\n hasSeparatingCommaAfter: has_separating_comma_after,\n hasTrailingComma: has_trailing_comma\n });\n}\n\n/**\n * Inserts a child into a Document with inline positioning behavior.\n * This provides inline-style spacing while maintaining Document's Block item types.\n */\nfunction insertInlineAtRoot(\n parent: Document,\n child: TreeNode,\n index: number\n): { shift: Span; offset: Span } {\n // Calculate positioning as if inserting into an inline context\n const result = calculateInlinePositioning(parent, child, index, {\n useNewLine: false,\n hasCommaHandling: false\n });\n \n // Insert the child directly into the Document (as a Block item)\n parent.items.splice(index, 0, child as KeyValue | Comment);\n \n return result;\n}\n\nexport function remove(root: Root, parent: TreeNode, node: TreeNode) {\n // Remove an element from the parent's items\n // (supports Document, Table, TableArray, InlineTable, and InlineArray\n //\n // X\n // [ 1, 2, 3 ]\n // ^-^\n // -> Remove element 2 and apply 0,-3 offset to 1\n //\n // [table]\n // a = 1\n // b = 2 # X\n // c = 3\n // -> Remove element 2 and apply -1,0 offset to 1\n if (!hasItems(parent)) {\n throw new Error(`Unsupported parent type \"${parent.type}\" for remove`);\n }\n\n let index = parent.items.indexOf(node);\n if (index < 0) {\n // Try again, looking at child items for nodes like InlineArrayItem\n index = parent.items.findIndex(item => hasItem(item) && item.item === node);\n\n if (index < 0) {\n throw new Error('Could not find node in parent for removal');\n }\n\n node = parent.items[index];\n }\n\n const previous = parent.items[index - 1];\n let next = parent.items[index + 1];\n\n // Remove node\n parent.items.splice(index, 1);\n let removed_span = getSpan(node.loc);\n\n // Remove an associated comment that appears on the same line\n //\n // [table]\n // a = 1\n // b = 2 # remove this too\n // c = 3\n //\n // TODO InlineTable - this only applies to comments in Table/TableArray\n if (next && isComment(next) && next.loc.start.line === node.loc.end.line) {\n // Add comment to removed\n removed_span = getSpan({ start: node.loc.start, end: next.loc.end });\n\n // Shift to next item\n // (use same index since node has already been removed)\n next = parent.items[index + 1];\n\n // Remove comment\n parent.items.splice(index, 1);\n }\n\n // For inline tables and arrays, check whether the line should be kept\n const is_inline = previous && isInlineItem(previous) || next && isInlineItem(next);\n const previous_on_same_line = previous && previous.loc.end.line === node.loc.start.line;\n const next_on_sameLine = next && next.loc.start.line === node.loc.end.line;\n const keep_line = is_inline && (previous_on_same_line || next_on_sameLine);\n\n const offset = {\n lines: -(removed_span.lines - (keep_line ? 1 : 0)),\n columns: -removed_span.columns\n };\n\n // If there is nothing left, don't perform any offsets\n if(previous === undefined && next === undefined) {\n offset.lines = 0;\n offset.columns = 0;\n }\n\n // Offset for comma and remove comma that appear in front of the element (if-needed)\n if (is_inline && previous_on_same_line) {\n offset.columns -= 2;\n }\n\n // If first element in array/inline-table, remove space for comma and space after element\n if (is_inline && !previous && next) {\n offset.columns -= 2;\n }\n\n if (is_inline && previous && !next) {\n // When removing the last element, preserve trailing comma preference\n // If the removed element had a trailing comma, transfer it to the new last element\n const removedHadTrailingComma = (node as InlineArrayItem | InlineTableItem).comma;\n if (removedHadTrailingComma) {\n (previous as InlineArrayItem | InlineTableItem).comma = true;\n } else {\n (previous as InlineArrayItem | InlineTableItem).comma = false;\n }\n }\n\n // Apply offsets after preceding node or before children of parent node\n const target = previous || parent;\n const target_offsets = previous ? getExitOffsets(root) : getEnterOffsets(root);\n const node_offsets = getExitOffsets(root);\n const previous_offset = target_offsets.get(target);\n if (previous_offset) {\n offset.lines += previous_offset.lines;\n offset.columns += previous_offset.columns;\n }\n const removed_offset = node_offsets.get(node);\n if (removed_offset) {\n offset.lines += removed_offset.lines;\n offset.columns += removed_offset.columns;\n }\n\n target_offsets.set(target, offset);\n}\n\nexport function applyBracketSpacing(\n root: Root,\n node: InlineArray | InlineTable,\n bracket_spacing: boolean = true\n) {\n // Can only add bracket spacing currently\n if (!bracket_spacing) return;\n if (!node.items.length) return;\n\n // Apply enter to node so that items are affected\n addOffset({ lines: 0, columns: 1 }, getEnterOffsets(root), node);\n\n // Apply exit to last node in items\n const last_item = last(node.items as TreeNode[])!;\n addOffset({ lines: 0, columns: 1 }, getExitOffsets(root), last_item);\n}\n\nexport function applyTrailingComma(\n root: Root,\n node: InlineArray | InlineTable,\n trailing_commas: boolean = false\n) {\n // Can only add trailing comma currently\n if (!trailing_commas) return;\n if (!node.items.length) return;\n\n const last_item = last(node.items)!;\n last_item.comma = true;\n\n addOffset({ lines: 0, columns: 1 }, getExitOffsets(root), last_item);\n}\n\n/**\n * Applies all accumulated write offsets (enter and exit) to the given AST node.\n * This function adjusts the start and end locations of each node in the tree based on\n * the offsets stored in the `enter` and `exit` maps. It ensures that the tree's location\n * data is consistent after modifications.\n *\n * @param root - The root node of the AST tree to which the write offsets will be applied.\n */\nexport function applyWrites(root: TreeNode) {\n const enter = getEnterOffsets(root);\n const exit = getExitOffsets(root);\n\n const offset: { lines: number; columns: { [index: number]: number } } = {\n lines: 0,\n columns: {}\n };\n\n function shiftStart(node: TreeNode) {\n\n const lineOffset = offset.lines;\n node.loc.start.line += lineOffset;\n \n const columnOffset = offset.columns[node.loc.start.line] || 0;\n node.loc.start.column += columnOffset\n\n const entering = enter.get(node);\n if (entering) {\n offset.lines += entering.lines;\n offset.columns[node.loc.start.line] =\n (offset.columns[node.loc.start.line] || 0) + entering.columns;\n }\n }\n\n function shiftEnd(node: TreeNode) {\n\n const lineOffset = offset.lines;\n node.loc.end.line += lineOffset;\n \n const columnOffset = offset.columns[node.loc.end.line] || 0;\n node.loc.end.column += columnOffset;\n\n const exiting = exit.get(node);\n if (exiting) {\n offset.lines += exiting.lines;\n offset.columns[node.loc.end.line] =\n (offset.columns[node.loc.end.line] || 0) + exiting.columns;\n }\n }\n\n const shiftLocation = {\n enter: shiftStart,\n exit: shiftEnd\n };\n\n traverse(root, {\n [NodeType.Document]: shiftLocation,\n [NodeType.Table]: shiftLocation,\n [NodeType.TableArray]: shiftLocation,\n [NodeType.InlineTable]: shiftLocation,\n [NodeType.InlineArray]: shiftLocation,\n\n [NodeType.InlineItem]: shiftLocation,\n [NodeType.TableKey]: shiftLocation,\n [NodeType.TableArrayKey]: shiftLocation,\n\n [NodeType.KeyValue]: {\n enter(node) {\n const start_line = node.loc.start.line + offset.lines;\n const key_offset = exit.get(node.key);\n node.equals += (offset.columns[start_line] || 0) + (key_offset ? key_offset.columns : 0);\n\n shiftStart(node);\n },\n exit: shiftEnd\n },\n\n [NodeType.Key]: shiftLocation,\n [NodeType.String]: shiftLocation,\n [NodeType.Integer]: shiftLocation,\n [NodeType.Float]: shiftLocation,\n [NodeType.Boolean]: shiftLocation,\n [NodeType.DateTime]: shiftLocation,\n [NodeType.Comment]: shiftLocation\n });\n\n enter_offsets.delete(root);\n exit_offsets.delete(root);\n}\n\nexport function shiftNode(\n node: TreeNode,\n span: Span,\n options: { first_line_only?: boolean } = {}\n): TreeNode {\n const { first_line_only = false } = options;\n const start_line = node.loc.start.line;\n const { lines, columns } = span;\n const move = (node: TreeNode) => {\n if (!first_line_only || node.loc.start.line === start_line) {\n node.loc.start.column += columns;\n node.loc.end.column += columns;\n }\n node.loc.start.line += lines;\n node.loc.end.line += lines;\n };\n\n traverse(node, {\n [NodeType.Table]: move,\n [NodeType.TableKey]: move,\n [NodeType.TableArray]: move,\n [NodeType.TableArrayKey]: move,\n [NodeType.KeyValue](node) {\n move(node);\n node.equals += columns;\n },\n [NodeType.Key]: move,\n [NodeType.String]: move,\n [NodeType.Integer]: move,\n [NodeType.Float]: move,\n [NodeType.Boolean]: move,\n [NodeType.DateTime]: move,\n [NodeType.InlineArray]: move,\n [NodeType.InlineItem]: move,\n [NodeType.InlineTable]: move,\n [NodeType.Comment]: move\n });\n\n return node;\n}\n\nfunction perLine(array: InlineArray): boolean {\n if (!array.items.length) return false;\n\n const span = getSpan(array.loc);\n return span.lines > array.items.length;\n}\n\nfunction addOffset(offset: Span, offsets: Offsets, node: TreeNode, from?: TreeNode) {\n const previous_offset = offsets.get(from || node);\n if (previous_offset) {\n offset.lines += previous_offset.lines;\n offset.columns += previous_offset.columns;\n }\n\n offsets.set(node, offset);\n}\n","import {\n NodeType,\n Document,\n Table,\n TableKey,\n TableArray,\n TableArrayKey,\n Value,\n KeyValue,\n Key,\n String,\n Integer,\n Float,\n Boolean,\n DateTime,\n InlineArray,\n InlineItem,\n InlineTable,\n Comment\n} from './ast';\nimport { zero, cloneLocation, clonePosition } from './location';\nimport { shiftNode } from './writer';\n\n/**\n * Generates a new TOML document node.\n *\n * @returns A new Document node.\n */\nexport function generateDocument(): Document {\n return {\n type: NodeType.Document,\n loc: { start: zero(), end: zero() },\n items: []\n };\n}\n\nexport function generateTable(key: string[]): Table {\n const table_key = generateTableKey(key);\n\n return {\n type: NodeType.Table,\n loc: cloneLocation(table_key.loc),\n key: table_key,\n items: []\n };\n}\n\nexport function generateTableKey(key: string[]): TableKey {\n const raw = keyValueToRaw(key);\n\n return {\n type: NodeType.TableKey,\n loc: {\n start: zero(),\n end: { line: 1, column: raw.length + 2 }\n },\n item: {\n type: NodeType.Key,\n loc: {\n start: { line: 1, column: 1 },\n end: { line: 1, column: raw.length + 1 }\n },\n value: key,\n raw\n }\n };\n}\n\nexport function generateTableArray(key: string[]): TableArray {\n const table_array_key = generateTableArrayKey(key);\n\n return {\n type: NodeType.TableArray,\n loc: cloneLocation(table_array_key.loc),\n key: table_array_key,\n items: []\n };\n}\n\nexport function generateTableArrayKey(key: string[]): TableArrayKey {\n const raw = keyValueToRaw(key);\n\n return {\n type: NodeType.TableArrayKey,\n loc: {\n start: zero(),\n end: { line: 1, column: raw.length + 4 }\n },\n item: {\n type: NodeType.Key,\n loc: {\n start: { line: 1, column: 2 },\n end: { line: 1, column: raw.length + 2 }\n },\n value: key,\n raw\n }\n };\n}\n\nexport function generateKeyValue(key: string[], value: Value): KeyValue {\n const key_node = generateKey(key);\n const { column } = key_node.loc.end;\n\n const equals = column + 1;\n\n shiftNode(\n value,\n { lines: 0, columns: column + 3 - value.loc.start.column },\n { first_line_only: true }\n );\n\n return {\n type: NodeType.KeyValue,\n loc: {\n start: clonePosition(key_node.loc.start),\n end: clonePosition(value.loc.end)\n },\n key: key_node,\n equals,\n value\n };\n}\n\nconst IS_BARE_KEY = /^[\\w-]+$/;\nfunction keyValueToRaw(value: string[]): string {\n return value.map(part => (IS_BARE_KEY.test(part) ? part : JSON.stringify(part))).join('.');\n}\n\nexport function generateKey(value: string[]): Key {\n const raw = keyValueToRaw(value);\n\n return {\n type: NodeType.Key,\n loc: { start: zero(), end: { line: 1, column: raw.length } },\n raw,\n value\n };\n}\n\nexport function generateString(value: string): String {\n const raw = JSON.stringify(value);\n\n return {\n type: NodeType.String,\n loc: { start: zero(), end: { line: 1, column: raw.length } },\n raw,\n value\n };\n}\n\nexport function generateInteger(value: number): Integer {\n const raw = value.toString();\n\n return {\n type: NodeType.Integer,\n loc: { start: zero(), end: { line: 1, column: raw.length } },\n raw,\n value\n };\n}\n\nexport function generateFloat(value: number): Float {\n let raw: string;\n \n if (value === Infinity) {\n raw = 'inf';\n } else if (value === -Infinity) {\n raw = '-inf';\n } else if (Number.isNaN(value)) {\n raw = 'nan';\n } else if (Object.is(value, -0)) {\n raw = '-0.0';\n } else {\n raw = value.toString();\n }\n\n return {\n type: NodeType.Float,\n loc: { start: zero(), end: { line: 1, column: raw.length } },\n raw,\n value\n };\n}\n\nexport function generateBoolean(value: boolean): Boolean {\n return {\n type: NodeType.Boolean,\n loc: { start: zero(), end: { line: 1, column: value ? 4 : 5 } },\n value\n };\n}\n\nexport function generateDateTime(value: Date): DateTime {\n // Custom date classes have their own toISOString() implementations\n // that return the properly formatted strings for each TOML date/time type\n const raw = value.toISOString();\n\n return {\n type: NodeType.DateTime,\n loc: { start: zero(), end: { line: 1, column: raw.length } },\n raw,\n value\n };\n}\n\nexport function generateInlineArray(): InlineArray {\n return {\n type: NodeType.InlineArray,\n loc: { start: zero(), end: { line: 1, column: 2 } },\n items: []\n };\n}\n\nexport function generateInlineItem(item: KeyValue | Value): InlineItem {\n return {\n type: NodeType.InlineItem,\n loc: cloneLocation(item.loc),\n item,\n comma: false\n };\n}\n\nexport function generateInlineTable(): InlineTable {\n return {\n type: NodeType.InlineTable,\n loc: { start: zero(), end: { line: 1, column: 2 } },\n items: []\n };\n}\n\nexport function generateComment(comment: string): Comment {\n if (!comment.startsWith('#')) comment = `# ${comment}`;\n\n return {\n type: NodeType.Comment,\n loc: { start: zero(), end: { line: 1, column: comment.length } },\n raw: comment\n };\n}\n","import {\n KeyValue,\n Table,\n InlineTable,\n TableArray,\n InlineArray,\n isInlineTable,\n isInlineArray,\n isKeyValue,\n Document,\n TreeNode\n} from './ast';\nimport { generateTable, generateDocument, generateTableArray } from './generate';\nimport { insert, remove, applyWrites, shiftNode } from './writer';\nimport parseTOML from './parse-toml';\n\n// Default formatting values\nexport const DEFAULT_NEWLINE = '\\n';\nexport const DEFAULT_TRAILING_NEWLINE = 1;\nexport const DEFAULT_TRAILING_COMMA = false;\nexport const DEFAULT_BRACKET_SPACING = true;\nexport const DEFAULT_INLINE_TABLE_START = 1;\n\n// Detects if trailing commas are used in the existing TOML by examining the AST\n// Returns true if trailing commas are used, false if not or comma-separated structures found (ie. default to false)\nexport function detectTrailingComma(ast: Iterable<any>): boolean {\n // Convert iterable to array and look for the first inline array or inline table to determine trailing comma preference\n const items = Array.from(ast);\n for (const item of items) {\n const result = findTrailingCommaInNode(item);\n if (result !== null) {\n return result;\n }\n }\n // Return default if no comma-separated structures are found\n return DEFAULT_TRAILING_COMMA;\n}\n\n// Detects if bracket spacing is used in inline arrays and tables by examining the raw string\n// Returns true if bracket spacing is found, false if not or no bracket structures found (default to true)\nexport function detectBracketSpacing(tomlString: string, ast: Iterable<any>): boolean {\n // Convert iterable to array and look for inline arrays and tables\n const items = Array.from(ast);\n for (const item of items) {\n const result = findBracketSpacingInNode(item, tomlString);\n if (result !== null) {\n return result;\n }\n }\n // Return default if no bracket structures are found\n return DEFAULT_BRACKET_SPACING;\n}\n\n// Helper function to recursively search for bracket spacing in a node\nfunction findBracketSpacingInNode(node: any, tomlString: string): boolean | null {\n if (!node || typeof node !== 'object') {\n return null;\n }\n\n // Check if this is an InlineArray or InlineTable\n if ((node.type === 'InlineArray' || node.type === 'InlineTable') && node.loc) {\n const bracketSpacing = checkBracketSpacingInLocation(node.loc, tomlString);\n if (bracketSpacing !== null) {\n return bracketSpacing;\n }\n }\n\n // Recursively check nested structures\n if (node.items && Array.isArray(node.items)) {\n for (const child of node.items) {\n const result = findBracketSpacingInNode(child, tomlString);\n if (result !== null) {\n return result;\n }\n // Also check nested item if it exists\n if (child.item) {\n const nestedResult = findBracketSpacingInNode(child.item, tomlString);\n if (nestedResult !== null) {\n return nestedResult;\n }\n }\n }\n }\n\n // Check other properties that might contain nodes\n for (const prop of ['value', 'key', 'item']) {\n if (node[prop]) {\n const result = findBracketSpacingInNode(node[prop], tomlString);\n if (result !== null) {\n return result;\n }\n }\n }\n\n return null;\n}\n\n// Helper function to check bracket spacing in a specific location\nfunction checkBracketSpacingInLocation(loc: any, tomlString: string): boolean | null {\n if (!loc || !loc.start || !loc.end) {\n return null;\n }\n\n // Extract the raw text for this location\n const lines = tomlString.split(/\\r?\\n/);\n const startLine = loc.start.line - 1; // Convert to 0-based\n const endLine = loc.end.line - 1;\n const startCol = loc.start.column;\n const endCol = loc.end.column;\n\n let rawText = '';\n if (startLine === endLine) {\n rawText = lines[startLine]?.substring(startCol, endCol + 1) || '';\n } else {\n // Multi-line case\n if (lines[startLine]) {\n rawText += lines[startLine].substring(startCol);\n }\n for (let i = startLine + 1; i < endLine; i++) {\n rawText += '\\n' + (lines[i] || '');\n }\n if (lines[endLine]) {\n rawText += '\\n' + lines[endLine].substring(0, endCol + 1);\n }\n }\n\n // Check for bracket spacing patterns\n // For arrays: [ elements ] vs [elements]\n // For tables: { elements } vs {elements}\n const arrayMatch = rawText.match(/^\\[(\\s*)/);\n const tableMatch = rawText.match(/^\\{(\\s*)/);\n \n if (arrayMatch) {\n // Check if there's a space after the opening bracket\n return arrayMatch[1].length > 0;\n }\n \n if (tableMatch) {\n // Check if there's a space after the opening brace\n return tableMatch[1].length > 0;\n }\n\n return null;\n}\n\n// Helper function to recursively search for comma usage in a node\nfunction findTrailingCommaInNode(node: any): boolean | null {\n if (!node || typeof node !== 'object') {\n return null;\n }\n\n // Check if this is an InlineArray\n if (node.type === 'InlineArray' && node.items && Array.isArray(node.items)) {\n return checkTrailingCommaInItems(node.items);\n }\n\n // Check if this is an InlineTable\n if (node.type === 'InlineTable' && node.items && Array.isArray(node.items)) {\n return checkTrailingCommaInItems(node.items);\n }\n\n // Check if this is a KeyValue with a value that might contain arrays/tables\n if (node.type === 'KeyValue' && node.value) {\n return findTrailingCommaInNode(node.value);\n }\n\n // For other node types, recursively check any items array\n if (node.items && Array.isArray(node.items)) {\n for (const item of node.items) {\n const result = findTrailingCommaInNode(item);\n if (result !== null) {\n return result;\n }\n }\n }\n\n return null;\n}\n\n// Check trailing comma usage in an array of inline items\nfunction checkTrailingCommaInItems(items: any[]): boolean | null {\n if (items.length === 0) {\n return null;\n }\n\n // Check the last item to see if it has a trailing comma\n const lastItem = items[items.length - 1];\n if (lastItem && typeof lastItem === 'object' && 'comma' in lastItem) {\n return lastItem.comma === true;\n }\n\n return false;\n}\n\n// Helper function to detect if an InlineArray originally had trailing commas\nexport function arrayHadTrailingCommas(node: TreeNode): boolean {\n if (!isInlineArray(node)) return false;\n if (node.items.length === 0) return false;\n // Check if the last item has a trailing comma\n const lastItem = node.items[node.items.length - 1];\n return lastItem.comma === true;\n}\n\n// Helper function to detect if an InlineTable originally had trailing commas\nexport function tableHadTrailingCommas(node: TreeNode): boolean {\n if (!isInlineTable(node)) return false;\n if (node.items.length === 0) return false;\n // Check if the last item has a trailing comma\n const lastItem = node.items[node.items.length - 1];\n return lastItem.comma === true;\n}\n\n// Returns the detected newline (\\n or \\r\\n) from a string, defaulting to \\n\nexport function detectNewline(str: string): string {\n const lfIndex = str.indexOf('\\n');\n if (lfIndex > 0 && str.substring(lfIndex - 1, lfIndex) === '\\r') {\n return '\\r\\n';\n }\n return '\\n';\n}\n\n// Counts consecutive trailing newlines at the end of a string\nexport function countTrailingNewlines(str: string, newlineChar: string): number {\n let count = 0;\n let pos = str.length;\n while (pos >= newlineChar.length) {\n if (str.substring(pos - newlineChar.length, pos) === newlineChar) {\n count++;\n pos -= newlineChar.length;\n } else {\n break;\n }\n }\n return count;\n}\n\n/**\n * Validates a format object and warns about unsupported properties.\n * Throws errors for supported properties with invalid types.\n * @param format - The format object to validate\n * @returns The validated format object with only supported properties and correct types\n */\nexport function validateFormatObject(format: any): any {\n if (!format || typeof format !== 'object') {\n return {};\n }\n\n const supportedProperties = new Set(['newLine', 'trailingNewline', 'trailingComma', 'bracketSpacing', 'inlineTableStart']);\n const validatedFormat: any = {};\n const unsupportedProperties: string[] = [];\n const invalidTypeProperties: string[] = [];\n\n // Check all enumerable properties of the format object\n for (const key in format) {\n if (Object.prototype.hasOwnProperty.call(format, key)) {\n if (supportedProperties.has(key)) {\n const value = format[key];\n \n // Type validation for each property\n switch (key) {\n case 'newLine':\n if (typeof value === 'string') {\n validatedFormat.newLine = value;\n } else {\n invalidTypeProperties.push(`${key} (expected string, got ${typeof value})`);\n }\n break;\n \n case 'trailingNewline':\n if (typeof value === 'boolean' || typeof value === 'number') {\n validatedFormat.trailingNewline = value;\n } else {\n invalidTypeProperties.push(`${key} (expected boolean or number, got ${typeof value})`);\n }\n break;\n \n case 'trailingComma':\n case 'bracketSpacing':\n if (typeof value === 'boolean') {\n validatedFormat[key] = value;\n } else {\n invalidTypeProperties.push(`${key} (expected boolean, got ${typeof value})`);\n }\n break;\n \n case 'inlineTableStart':\n if (typeof value === 'number' && Number.isInteger(value) && value >= 0) {\n validatedFormat.inlineTableStart = value;\n } else if (value === undefined || value === null) {\n // Allow undefined/null to use default\n validatedFormat.inlineTableStart = value;\n } else {\n invalidTypeProperties.push(`${key} (expected non-negative integer or undefined, got ${typeof value})`);\n }\n break;\n }\n } else {\n unsupportedProperties.push(key);\n }\n }\n }\n\n // Warn about unsupported properties\n if (unsupportedProperties.length > 0) {\n console.warn(`toml-patch: Ignoring unsupported format properties: ${unsupportedProperties.join(', ')}. Supported properties are: ${Array.from(supportedProperties).join(', ')}`);\n }\n\n // Throw error for invalid types\n if (invalidTypeProperties.length > 0) {\n throw new TypeError(`Invalid types for format properties: ${invalidTypeProperties.join(', ')}`);\n }\n\n return validatedFormat;\n}\n\n/**\n * Resolves a format parameter to a TomlFormat instance.\n * Handles TomlFormat instances and partial TomlFormat objects as well as undefined.\n * \n * @param format - The format parameter to resolve (TomlFormat instance, partial format object, or undefined)\n * @param fallbackFormat - The fallback TomlFormat to use when no format is provided\n * @returns A resolved TomlFormat instance\n */\nexport function resolveTomlFormat(format: Partial<TomlFormat> | TomlFormat | undefined, fallbackFormat: TomlFormat): TomlFormat {\n if (format) {\n // If format is provided, validate and merge it with fallback\n if (format instanceof TomlFormat) {\n return format;\n } else {\n // Validate the format object and warn about unsupported properties\n const validatedFormat = validateFormatObject(format);\n \n // Create a new TomlFormat instance with validated properties\n return new TomlFormat(\n validatedFormat.newLine ?? fallbackFormat.newLine,\n validatedFormat.trailingNewline ?? fallbackFormat.trailingNewline,\n validatedFormat.trailingComma ?? fallbackFormat.trailingComma,\n validatedFormat.bracketSpacing ?? fallbackFormat.bracketSpacing,\n validatedFormat.inlineTableStart !== undefined ? validatedFormat.inlineTableStart : fallbackFormat.inlineTableStart\n );\n }\n } else {\n // Use fallback format when no format is provided\n return fallbackFormat;\n }\n}\n\nexport class TomlFormat {\n \n /**\n * The line ending character(s) to use in the output TOML.\n * This option affects only the stringification process, not the internal representation (AST).\n * \n * @example\n * - '\\n' for Unix/Linux line endings\n * - '\\r\\n' for Windows line endings\n */\n newLine: string;\n \n /**\n * The number of trailing newlines to add at the end of the TOML document.\n * This option affects only the stringification process, not the internal representation (AST).\n * \n * @example\n * - 0: No trailing newline\n * - 1: One trailing newline (standard)\n * - 2: Two trailing newlines (adds extra spacing)\n */\n trailingNewline: number;\n \n /**\n * Whether to add trailing commas after the last element in arrays and inline tables.\n * \n * @example\n * - true: [1, 2, 3,] and { x = 1, y = 2, }\n * - false: [1, 2, 3] and { x = 1, y = 2 }\n */\n trailingComma: boolean;\n \n /**\n * Whether to add spaces after opening brackets/braces and before closing brackets/braces\n * in arrays and inline tables.\n * \n * @example\n * - true: [ 1, 2, 3 ] and { x = 1, y = 2 }\n * - false: [1, 2, 3] and {x = 1, y = 2}\n */\n bracketSpacing: boolean;\n\n /**\n * The nesting depth at which new tables should start being formatted as inline tables.\n * When adding new tables during patching or stringifying objects:\n * - Tables at depth >= inlineTableStart will be formatted as inline tables\n * - Tables at depth < inlineTableStart will be formatted as separate table sections\n * \n * @example\n * - 0: All tables are inline tables including top-level tables (root level)\n * - 1: Top-level tables as sections, nested tables as inline (default)\n * - 2: Two levels as sections, deeper nesting as inline\n */\n inlineTableStart?: number;\n\n // These options were part of the original TimHall's version and are not yet implemented\n //printWidth?: number;\n //tabWidth?: number;\n //useTabs?: boolean;\n \n constructor(newLine?: string, trailingNewline?: number, trailingComma?: boolean, bracketSpacing?: boolean, inlineTableStart?: number) {\n // Use provided values or fall back to defaults\n this.newLine = newLine ?? DEFAULT_NEWLINE;\n this.trailingNewline = trailingNewline ?? DEFAULT_TRAILING_NEWLINE;\n this.trailingComma = trailingComma ?? DEFAULT_TRAILING_COMMA;\n this.bracketSpacing = bracketSpacing ?? DEFAULT_BRACKET_SPACING;\n this.inlineTableStart = inlineTableStart ?? DEFAULT_INLINE_TABLE_START;\n }\n\n /**\n * Creates a new TomlFormat instance with default formatting preferences.\n * \n * @returns A new TomlFormat instance with default values:\n * - newLine: '\\n'\n * - trailingNewline: 1\n * - trailingComma: false\n * - bracketSpacing: true\n * - inlineTableStart: 1\n */\n static default(): TomlFormat {\n return new TomlFormat(\n DEFAULT_NEWLINE,\n DEFAULT_TRAILING_NEWLINE,\n DEFAULT_TRAILING_COMMA,\n DEFAULT_BRACKET_SPACING,\n DEFAULT_INLINE_TABLE_START\n );\n }\n\n /**\n * Auto-detects formatting preferences from an existing TOML string.\n * \n * This method analyzes the provided TOML string to determine formatting\n * preferences such as line endings, trailing newlines, and comma usage.\n * \n * @param tomlString - The TOML string to analyze for formatting patterns\n * @returns A new TomlFormat instance with detected formatting preferences\n * \n * @example\n * ```typescript\n * const toml = 'array = [\"a\", \"b\", \"c\",]\\ntable = { x = 1, y = 2, }';\n * const format = TomlFormat.autoDetectFormat(toml);\n * // format.trailingComma will be true\n * // format.newLine will be '\\n'\n * // format.trailingNewline will be 0 (no trailing newline)\n * ```\n */\n static autoDetectFormat(tomlString: string): TomlFormat {\n const format = TomlFormat.default();\n \n // Detect line ending style\n format.newLine = detectNewline(tomlString);\n \n // Detect trailing newline count\n format.trailingNewline = countTrailingNewlines(tomlString, format.newLine);\n \n // Parse the TOML to detect comma and bracket spacing usage patterns\n try {\n const ast = parseTOML(tomlString);\n // Convert to array once to avoid consuming the iterator multiple times\n const astArray = Array.from(ast);\n format.trailingComma = detectTrailingComma(astArray);\n format.bracketSpacing = detectBracketSpacing(tomlString, astArray);\n } catch (error) {\n // If parsing fails, fall back to defaults\n // This ensures the method is robust against malformed TOML\n format.trailingComma = DEFAULT_TRAILING_COMMA;\n format.bracketSpacing = DEFAULT_BRACKET_SPACING;\n }\n \n // inlineTableStart uses default value since auto-detection would require\n // complex analysis of nested table formatting preferences\n format.inlineTableStart = DEFAULT_INLINE_TABLE_START;\n \n return format;\n }\n}\nexport function formatTopLevel(document: Document, format: TomlFormat): Document {\n\n // If inlineTableStart is 0, convert all top-level tables to inline tables\n if (format.inlineTableStart === 0) {\n return document;\n }\n\n const move_to_top_level = document.items.filter(item => {\n if (!isKeyValue(item)) return false;\n\n const is_inline_table = isInlineTable(item.value);\n const is_inline_array =\n isInlineArray(item.value) &&\n item.value.items.length &&\n isInlineTable(item.value.items[0].item);\n\n // Only move to top level if the depth is less than inlineTableStart\n if (is_inline_table || is_inline_array) {\n const depth = calculateTableDepth(item.key.value);\n return format.inlineTableStart === undefined || depth < format.inlineTableStart;\n }\n\n return false;\n }) as KeyValue[];\n\n move_to_top_level.forEach(node => {\n remove(document, document, node);\n\n if (isInlineTable(node.value)) {\n insert(document, document, formatTable(node));\n } else {\n formatTableArray(node).forEach(table_array => {\n insert(document, document, table_array);\n });\n }\n });\n\n applyWrites(document);\n return document;\n}\n\nfunction formatTable(key_value: KeyValue): Table {\n const table = generateTable(key_value.key.value);\n\n for (const item of (key_value.value as InlineTable).items) {\n insert(table, table, item.item);\n }\n\n applyWrites(table);\n return table;\n}\n\nfunction formatTableArray(key_value: KeyValue): TableArray[] {\n const root = generateDocument();\n\n for (const inline_array_item of (key_value.value as InlineArray).items) {\n const table_array = generateTableArray(key_value.key.value);\n insert(root, root, table_array);\n\n for (const inline_table_item of (inline_array_item.item as InlineTable).items) {\n insert(root, table_array, inline_table_item.item);\n }\n }\n\n applyWrites(root);\n return root.items as TableArray[];\n}\n\n/**\n * Updates a table's location end position after removing inline table items.\n * When inline table content is removed from a parent table, the parent table's \n * end position needs to be adjusted to reflect where the content actually ends.\n * \n * @param table - The table whose end position should be updated\n */\nexport function postInlineItemRemovalAdjustment(table: Table): void {\n if (table.items.length > 0) {\n const lastItem = table.items[table.items.length - 1];\n table.loc.end.line = lastItem.loc.end.line;\n table.loc.end.column = lastItem.loc.end.column;\n } else {\n // If no items left, table ends at the header line\n table.loc.end.line = table.key.loc.end.line;\n table.loc.end.column = table.key.loc.end.column;\n }\n}\n\n/**\n * Calculates the nesting depth of a table based on its key path.\n * Root level tables (e.g., [table]) have depth 0.\n * First level nested tables (e.g., [table.nested]) have depth 1.\n * \n * @param keyPath - Array representing the table key path (e.g., ['table', 'nested'])\n * @returns The nesting depth (0 for root level, 1+ for nested levels)\n */\nexport function calculateTableDepth(keyPath: string[]): number {\n return Math.max(0, keyPath.length - 1);\n}\n\n/**\n * Converts nested inline tables to separate table sections based on the inlineTableStart depth setting.\n * This function recursively processes all tables in the document and extracts inline tables that are\n * at a depth less than the inlineTableStart threshold.\n */\nexport function formatNestedTablesMultiline(document: Document, format: TomlFormat): Document {\n // If inlineTableStart is undefined, use the default behavior (no conversion)\n // If inlineTableStart is 0, all should be inline (no conversion)\n if (format.inlineTableStart === undefined || format.inlineTableStart === 0) {\n return document;\n }\n\n const additionalTables: Table[] = [];\n \n // Process all existing tables for nested inline tables\n for (const item of document.items) {\n if (isKeyValue(item) && isInlineTable(item.value)) {\n // This is a top-level inline table (depth 0)\n const depth = calculateTableDepth(item.key.value);\n if (depth < format.inlineTableStart) {\n // Convert to a separate table\n const table = formatTable(item);\n \n // Remove the original inline table item\n remove(document, document, item);\n \n // Add the new table\n insert(document, document, table);\n \n // Process this table for further nested inlines\n processTableForNestedInlines(table, additionalTables, format);\n }\n } else if (item.type === 'Table') {\n // Process existing table for nested inline tables\n processTableForNestedInlines(item as Table, additionalTables, format);\n }\n }\n \n // Add all the additional tables to the document\n for (const table of additionalTables) {\n insert(document, document, table);\n }\n\n applyWrites(document);\n return document;\n}\n\n/**\n * Recursively processes a table for nested inline tables and extracts them as separate tables\n * when they are at a depth less than the inlineTableStart threshold.\n */\nfunction processTableForNestedInlines(table: Table, additionalTables: Table[], format: TomlFormat): void {\n // Process from end to beginning to avoid index issues when removing items\n for (let i = table.items.length - 1; i >= 0; i--) {\n const item = table.items[i];\n if (isKeyValue(item) && isInlineTable(item.value)) {\n // Calculate the depth of this nested table\n const nestedTableKey = [...table.key.item.value, ...item.key.value];\n const depth = calculateTableDepth(nestedTableKey);\n \n // Only convert to separate table if depth is less than inlineTableStart\n if (depth < (format.inlineTableStart ?? 1)) {\n // Convert this inline table to a separate table section\n const separateTable = generateTable(nestedTableKey);\n \n // Move all items from the inline table to the separate table\n for (const inlineItem of item.value.items) {\n insert(separateTable, separateTable, inlineItem.item);\n }\n \n // Remove this item from the original table\n remove(table, table, item);\n \n // Update the parent table's end position after removal\n postInlineItemRemovalAdjustment(table);\n \n // Add this table to be inserted into the document\n additionalTables.push(separateTable);\n \n // Recursively process the new table for further nested inlines\n processTableForNestedInlines(separateTable, additionalTables, format);\n }\n }\n }\n}\n\nexport function formatPrintWidth(document: Document, format: TomlFormat): Document {\n // TODO\n return document;\n}\n\nexport function formatEmptyLines(document: Document): Document {\n let shift = 0;\n let previous = 0;\n for (const item of document.items) {\n if (previous === 0 && item.loc.start.line > 1) {\n // Remove leading newlines\n shift = 1 - item.loc.start.line;\n } else if (item.loc.start.line + shift > previous + 2) {\n shift += previous + 2 - (item.loc.start.line + shift);\n }\n\n shiftNode(item, {\n lines: shift,\n columns: 0\n });\n previous = item.loc.end.line;\n }\n\n return document;\n}","import { Value, KeyValue, Document, InlineArray, InlineTable } from './ast';\nimport {\n generateDocument,\n generateKeyValue,\n generateInlineItem,\n generateString,\n generateInteger,\n generateFloat,\n generateBoolean,\n generateDateTime,\n generateInlineArray,\n generateInlineTable\n} from './generate';\nimport { TomlFormat, formatTopLevel, formatPrintWidth, formatEmptyLines, formatNestedTablesMultiline } from './toml-format';\nimport { isObject, isString, isInteger, isFloat, isBoolean, isDate, pipe } from './utils';\nimport { insert, applyWrites, applyBracketSpacing, applyTrailingComma } from './writer';\n\n\nexport default function parseJS(value: any, format: TomlFormat = TomlFormat.default()): Document {\n value = toJSON(value);\n\n // Reorder the elements in the object\n value = reorderElements(value);\n\n const document = generateDocument();\n for (const item of walkObject(value, format)) {\n insert(document, document, item);\n }\n applyWrites(document);\n\n // Heuristics:\n // 1. Top-level objects/arrays should be tables/table arrays\n // 2. Convert objects/arrays to tables/table arrays based on print width\n // 3. Convert nested inline tables to separate tables based on preferNestedTablesMultiline\n const formatted = pipe(\n document,\n document => formatTopLevel(document, format),\n document => formatNestedTablesMultiline(document, format),\n document => formatPrintWidth(document, format)\n );\n\n // Apply formatEmptyLines only once at the end\n return formatEmptyLines(formatted);\n}\n\n/** \nThis function makes sure that properties that are simple values (not objects or arrays) are ordered first,\nand that objects and arrays are ordered last. This makes parseJS more reliable and easier to test.\n*/\nfunction reorderElements(value:any) : Object {\n // Pre-sort keys to avoid multiple iterations\n const simpleKeys: string[] = [];\n const complexKeys: string[] = [];\n \n // Separate keys in a single pass\n for (const key in value) {\n if (isObject(value[key]) || Array.isArray(value[key])) {\n complexKeys.push(key);\n } else {\n simpleKeys.push(key);\n }\n }\n \n // Create result with the correct order\n const result: Record<string, any> = {};\n \n // Add simple values first\n for (let i = 0; i < simpleKeys.length; i++) {\n const key = simpleKeys[i];\n result[key] = value[key];\n }\n \n // Then add complex values\n for (let i = 0; i < complexKeys.length; i++) {\n const key = complexKeys[i];\n result[key] = value[key];\n }\n \n return result;\n}\n\nfunction* walkObject(object: any, format: TomlFormat): IterableIterator<KeyValue> {\n for (const key of Object.keys(object)) {\n yield generateKeyValue([key], walkValue(object[key], format));\n }\n}\n\nfunction walkValue(value: any, format: TomlFormat): Value {\n if (value == null) {\n throw new Error('\"null\" and \"undefined\" values are not supported');\n }\n\n if (isString(value)) {\n return generateString(value);\n } else if (isInteger(value)) {\n return generateInteger(value);\n } else if (isFloat(value)) {\n return generateFloat(value);\n } else if (isBoolean(value)) {\n return generateBoolean(value);\n } else if (isDate(value)) {\n return generateDateTime(value);\n } else if (Array.isArray(value)) {\n return walkInlineArray(value, format);\n } else {\n return walkInlineTable(value, format);\n }\n}\n\nfunction walkInlineArray(value: Array<any>, format: TomlFormat): InlineArray {\n const inline_array = generateInlineArray();\n for (const element of value) {\n const item = walkValue(element, format);\n const inline_array_item = generateInlineItem(item);\n\n insert(inline_array, inline_array, inline_array_item);\n }\n applyBracketSpacing(inline_array, inline_array, format.bracketSpacing);\n applyTrailingComma(inline_array, inline_array, format.trailingComma);\n applyWrites(inline_array);\n\n return inline_array;\n}\n\nfunction walkInlineTable(value: object, format: TomlFormat): InlineTable | Value {\n value = toJSON(value);\n if (!isObject(value)) return walkValue(value, format);\n\n const inline_table = generateInlineTable();\n const items = [...walkObject(value, format)];\n for (const item of items) {\n const inline_table_item = generateInlineItem(item);\n\n insert(inline_table, inline_table, inline_table_item);\n }\n applyBracketSpacing(inline_table, inline_table, format.bracketSpacing);\n applyTrailingComma(inline_table, inline_table, format.trailingComma);\n applyWrites(inline_table);\n\n return inline_table;\n}\n\n/**\n * Handles custom object serialization by checking for and using toJSON methods\n * \n * @param value - The value to potentially convert\n * @returns The result of value.toJSON() if available, otherwise the original value\n */\nfunction toJSON(value: any): any {\n // Skip null/undefined values\n if (!value) {\n return value;\n }\n \n // Skip Date objects (they have special handling)\n if (isDate(value)) {\n return value;\n }\n \n // Use object's custom toJSON method if available\n if (typeof value.toJSON === 'function') {\n return value.toJSON();\n }\n \n // Otherwise return unmodified\n return value;\n}\n","import { NodeType, AST } from './ast';\nimport traverse from './traverse';\nimport { Location } from './location';\nimport { SPACE } from './tokenizer';\nimport { TomlFormat } from './toml-format';\n\nconst BY_NEW_LINE = /(\\r\\n|\\n)/g;\n\n/**\n * Converts an Abstract Syntax Tree (AST) back to TOML format string.\n * \n * This function traverses the AST and reconstructs the original TOML document\n * by writing each node's raw content to the appropriate location coordinates.\n * It preserves the original formatting, spacing, and structure of the TOML file.\n * \n * @param ast - The Abstract Syntax Tree representing the parsed TOML document\n * @param newline - The newline character(s) to use (\\n by default)\n * @param options - Optional configuration object\n * @param options.trailingNewline - Number of trailing newlines to add (1 by default)\n * @returns The reconstructed TOML document as a string\n * \n * @example\n * ```typescript\n * const tomlString = toTOML(ast, '\\n', { trailingNewline: 1 });\n * ```\n */\nexport default function toTOML(ast: AST, format: TomlFormat): string {\n\n const lines: string[] = [];\n\n traverse(ast, {\n [NodeType.TableKey](node) {\n const { start, end } = node.loc;\n\n write(lines, { start, end: { line: start.line, column: start.column + 1 } }, '[');\n write(lines, { start: { line: end.line, column: end.column - 1 }, end }, ']');\n },\n [NodeType.TableArrayKey](node) {\n const { start, end } = node.loc;\n\n write(lines, { start, end: { line: start.line, column: start.column + 2 } }, '[[');\n write(lines, { start: { line: end.line, column: end.column - 2 }, end }, ']]');\n },\n\n [NodeType.KeyValue](node) {\n const {\n start: { line }\n } = node.loc;\n write(\n lines,\n { start: { line, column: node.equals }, end: { line, column: node.equals + 1 } },\n '='\n );\n },\n [NodeType.Key](node) {\n write(lines, node.loc, node.raw);\n },\n\n [NodeType.String](node) {\n write(lines, node.loc, node.raw);\n },\n [NodeType.Integer](node) {\n write(lines, node.loc, node.raw);\n },\n [NodeType.Float](node) {\n write(lines, node.loc, node.raw);\n },\n [NodeType.Boolean](node) {\n write(lines, node.loc, node.value.toString());\n },\n [NodeType.DateTime](node) {\n write(lines, node.loc, node.raw);\n },\n\n [NodeType.InlineArray](node) {\n const { start, end } = node.loc;\n write(lines, { start, end: { line: start.line, column: start.column + 1 } }, '[');\n write(lines, { start: { line: end.line, column: end.column - 1 }, end }, ']');\n },\n\n [NodeType.InlineTable](node) {\n const { start, end } = node.loc;\n write(lines, { start, end: { line: start.line, column: start.column + 1 } }, '{');\n write(lines, { start: { line: end.line, column: end.column - 1 }, end }, '}');\n },\n [NodeType.InlineItem](node) {\n if (!node.comma) return;\n\n const start = node.loc.end;\n write(lines, { start, end: { line: start.line, column: start.column + 1 } }, ',');\n },\n\n [NodeType.Comment](node) {\n write(lines, node.loc, node.raw);\n }\n });\n\n return lines.join(format.newLine) + format.newLine.repeat(format.trailingNewline);\n}\n\n/**\n * Writes raw string content to specific location coordinates within a lines array.\n * \n * This function is responsible for placing TOML content at precise positions within\n * the output lines, handling multi-line content and preserving existing content\n * around the target location.\n * \n * @param lines - Array of string lines representing the TOML document being built.\n * Lines are 1-indexed but stored in 0-indexed array.\n * @param loc - Location object specifying where to write the content, containing:\n * - start: { line: number, column: number } - Starting position (1-indexed line, 0-indexed column)\n * - end: { line: number, column: number } - Ending position (1-indexed line, 0-indexed column)\n * @param raw - The raw string content to write at the specified location.\n * Can contain multiple lines separated by \\n or \\r\\n.\n * \n * @throws {Error} When there's a mismatch between location span and raw string line count\n * @throws {Error} When attempting to write to an uninitialized line\n * \n * @example\n * ```typescript\n * const lines = ['', ''];\n * const location = { start: { line: 1, column: 0 }, end: { line: 1, column: 3 } };\n * write(lines, location, 'key');\n * // Result: lines[0] becomes 'key'\n * ```\n */\nfunction write(lines: string[], loc: Location, raw: string) {\n const raw_lines = raw.split(BY_NEW_LINE).filter(line => line !== '\\n' && line !== '\\r\\n');\n const expected_lines = loc.end.line - loc.start.line + 1;\n\n if (raw_lines.length !== expected_lines) {\n throw new Error(\n `Mismatch between location and raw string, expected ${expected_lines} lines for \"${raw}\"`\n );\n }\n\n for (let i = loc.start.line; i <= loc.end.line; i++) {\n const line = getLine(lines, i);\n\n //Throw if line is uninitialized\n if (line === undefined) {\n throw new Error(\n `Line ${i} is uninitialized when writing \"${raw}\" at ${loc.start.line}:${loc.start.column} to ${loc.end.line}:${loc.end.column}`\n );\n }\n\n const is_start_line = i === loc.start.line;\n const is_end_line = i === loc.end.line;\n\n const before = is_start_line\n ? line.substr(0, loc.start.column).padEnd(loc.start.column, SPACE)\n : '';\n const after = is_end_line ? line.substr(loc.end.column) : '';\n\n lines[i - 1] = before + raw_lines[i - loc.start.line] + after;\n }\n}\n\n/**\n * Safely retrieves a line from the lines array, initializing empty lines as needed.\n * \n * This helper function handles the conversion between 1-indexed line numbers (used in locations)\n * and 0-indexed array positions. It ensures that accessing a line that doesn't exist yet\n * will initialize all preceding lines with empty strings.\n * \n * @param lines - Array of string lines representing the document\n * @param index - 1-indexed line number to retrieve\n * @returns The line content as a string, or empty string for new lines\n * \n * @example\n * ```typescript\n * const lines = ['first line'];\n * const line = getLine(lines, 3); // Initializes lines[1] and lines[2] as empty strings\n * // lines becomes ['first line', '', '']\n * ```\n */\nfunction getLine(lines: string[], index: number): string {\n if (!lines[index - 1]) {\n for (let i = 0; i < index; i++) {\n if (!lines[i]) lines[i] = '';\n }\n }\n\n return lines[index - 1];\n}\n","import { Value, NodeType, TreeNode, AST, isInlineTable } from './ast';\nimport traverse from './traverse';\nimport { last, blank, isDate, has } from './utils';\nimport ParseError from './parse-error';\n\n/**\n * Converts the given AST to a JavaScript object.\n * \n * @param ast The abstract syntax tree to convert.\n * @param input The original input string (used for error reporting).\n * @returns The JavaScript object representation of the AST.\n */\nexport default function toJS(ast: AST, input: string = ''): any {\n const result = blank();\n const tables: Set<string> = new Set();\n const table_arrays: Set<string> = new Set();\n const defined: Set<string> = new Set();\n let active: any = result;\n let previous_active: any;\n let skip_depth = 0;\n\n traverse(ast, {\n [NodeType.Table](node) {\n const key = node.key.item.value;\n try {\n validateKey(result, key, node.type, { tables, table_arrays, defined });\n } catch (err) {\n const e = err as Error;\n throw new ParseError(input, node.key.loc.start, e.message);\n }\n\n const joined_key = joinKey(key);\n tables.add(joined_key);\n defined.add(joined_key);\n\n active = ensureTable(result, key);\n },\n\n [NodeType.TableArray](node) {\n const key = node.key.item.value;\n\n try {\n validateKey(result, key, node.type, { tables, table_arrays, defined });\n } catch (err) {\n const e = err as Error;\n throw new ParseError(input, node.key.loc.start, e.message);\n }\n\n const joined_key = joinKey(key);\n table_arrays.add(joined_key);\n defined.add(joined_key);\n\n active = ensureTableArray(result, key);\n },\n\n [NodeType.KeyValue]: {\n enter(node) {\n if (skip_depth > 0) return;\n\n const key = node.key.value;\n try {\n validateKey(active, key, node.type, { tables, table_arrays, defined });\n } catch (err) {\n const e = err as Error;\n throw new ParseError(input, node.key.loc.start, e.message);\n }\n\n const value = toValue(node.value);\n const target = key.length > 1 ? ensureTable(active, key.slice(0, -1)) : active;\n\n target[last(key)!] = value;\n defined.add(joinKey(key));\n }\n },\n\n [NodeType.InlineTable]: {\n enter() {\n // Handled by toValue\n skip_depth++;\n },\n exit() {\n skip_depth--;\n }\n }\n });\n\n return result;\n}\n\nexport function toValue(node: Value): any {\n switch (node.type) {\n case NodeType.InlineTable:\n const result = blank();\n\n node.items.forEach(({ item }) => {\n const key = item.key.value;\n const value = toValue(item.value);\n\n const target = key.length > 1 ? ensureTable(result, key.slice(0, -1)) : result;\n target[last(key)!] = value;\n });\n\n return result;\n\n case NodeType.InlineArray:\n return node.items.map(item => toValue(item.item as Value));\n\n case NodeType.String:\n case NodeType.Integer:\n case NodeType.Float:\n case NodeType.Boolean:\n case NodeType.DateTime:\n return node.value;\n\n default:\n throw new Error(`Unrecognized value type \"${(node as TreeNode).type}\"`);\n }\n}\n\nfunction validateKey(\n object: any,\n key: string[],\n type: NodeType.Table | NodeType.TableArray | NodeType.KeyValue,\n state: { tables: Set<string>; table_arrays: Set<string>; defined: Set<string> }\n) {\n // 1. Cannot override primitive value\n let parts: string[] = [];\n let index = 0;\n for (const part of key) {\n parts.push(part);\n\n if (!has(object, part)) return;\n if (isPrimitive(object[part])) {\n throw new Error(`Invalid key, a value has already been defined for ${parts.join('.')}`);\n }\n\n const joined_parts = joinKey(parts);\n if (Array.isArray(object[part]) && !state.table_arrays.has(joined_parts)) {\n throw new Error(`Invalid key, cannot add to a static array at ${joined_parts}`);\n }\n\n const next_is_last = index++ < key.length - 1;\n object = Array.isArray(object[part]) && next_is_last ? last(object[part]) : object[part];\n }\n\n const joined_key = joinKey(key);\n\n // 2. Cannot override table\n if (object && type === NodeType.Table && state.defined.has(joined_key)) {\n throw new Error(`Invalid key, a table has already been defined named ${joined_key}`);\n }\n\n // 3. Cannot add table array to static array or table\n if (object && type === NodeType.TableArray && !state.table_arrays.has(joined_key)) {\n throw new Error(`Invalid key, cannot add an array of tables to a table at ${joined_key}`);\n }\n}\n\nfunction ensureTable(object: any, key: string[]): any {\n const target = ensure(object, key.slice(0, -1));\n const last_key = last(key)!;\n if (!target[last_key]) {\n target[last_key] = blank();\n }\n\n return target[last_key];\n}\n\nfunction ensureTableArray(object: any, key: string[]): any {\n const target = ensure(object, key.slice(0, -1));\n const last_key = last(key)!;\n if (!target[last_key]) {\n target[last_key] = [];\n }\n\n const next = blank();\n target[last(key)!].push(next);\n\n return next;\n}\n\nfunction ensure(object: any, keys: string[]): any {\n return keys.reduce((active, subkey) => {\n if (!active[subkey]) {\n active[subkey] = blank();\n }\n return Array.isArray(active[subkey]) ? last(active[subkey]) : active[subkey];\n }, object);\n}\n\nfunction isPrimitive(value: any) {\n return typeof value !== 'object' && !isDate(value);\n}\n\nfunction joinKey(key: string[]): string {\n return key.join('.');\n}\n","import { isObject, datesEqual, stableStringify, merge } from './utils';\nimport { Path } from './find-by-path';\n\nexport enum ChangeType {\n Add = 'Add',\n Edit = 'Edit',\n Remove = 'Remove',\n Move = 'Move',\n Rename = 'Rename'\n}\n\nexport interface Add {\n type: ChangeType.Add;\n path: Path;\n}\nexport function isAdd(change: Change): change is Add {\n return change.type === ChangeType.Add;\n}\n\nexport interface Edit {\n type: ChangeType.Edit;\n path: Path;\n}\nexport function isEdit(change: Change): change is Edit {\n return change.type === ChangeType.Edit;\n}\n\nexport interface Remove {\n type: ChangeType.Remove;\n path: Path;\n}\nexport function isRemove(change: Change): change is Remove {\n return change.type === ChangeType.Remove;\n}\n\nexport interface Move {\n type: ChangeType.Move;\n path: Path;\n from: number;\n to: number;\n}\nexport function isMove(change: Change): change is Move {\n return change.type === ChangeType.Move;\n}\n\nexport interface Rename {\n type: ChangeType.Rename;\n path: Path;\n from: string;\n to: string;\n}\nexport function isRename(change: Change): change is Rename {\n return change.type === ChangeType.Rename;\n}\n\nexport type Change = Add | Edit | Remove | Move | Rename;\n\nexport default function diff(before: any, after: any, path: Path = []): Change[] {\n if (before === after || datesEqual(before, after)) {\n return [];\n }\n\n if (Array.isArray(before) && Array.isArray(after)) {\n return compareArrays(before, after, path);\n } else if (isObject(before) && isObject(after)) {\n return compareObjects(before, after, path);\n } else {\n return [\n {\n type: ChangeType.Edit,\n path\n }\n ];\n }\n}\n\nfunction compareObjects(before: any, after: any, path: Path = []): Change[] {\n let changes: Change[] = [];\n\n // 1. Get keys and stable values\n const before_keys = Object.keys(before);\n const before_stable = before_keys.map(key => stableStringify(before[key]));\n const after_keys = Object.keys(after);\n const after_stable = after_keys.map(key => stableStringify(after[key]));\n\n // Check for rename by seeing if object is in both before and after\n // and that key is no longer used in after\n const isRename = (stable: string, search: string[]) => {\n const index = search.indexOf(stable);\n if (index < 0) return false;\n\n const before_key = before_keys[before_stable.indexOf(stable)];\n return !after_keys.includes(before_key);\n };\n\n // 2. Check for changes, rename, and removed\n before_keys.forEach((key, index) => {\n const sub_path = path.concat(key);\n if (after_keys.includes(key)) {\n merge(changes, diff(before[key], after[key], sub_path));\n } else if (isRename(before_stable[index], after_stable)) {\n const to = after_keys[after_stable.indexOf(before_stable[index])];\n changes.push({\n type: ChangeType.Rename,\n path,\n from: key,\n to\n });\n } else {\n changes.push({\n type: ChangeType.Remove,\n path: sub_path\n });\n }\n });\n\n // 3. Check for additions\n after_keys.forEach((key, index) => {\n if (!before_keys.includes(key) && !isRename(after_stable[index], before_stable)) {\n changes.push({\n type: ChangeType.Add,\n path: path.concat(key)\n });\n }\n });\n\n return changes;\n}\n\nfunction compareArrays(before: any[], after: any[], path: Path = []): Change[] {\n let changes: Change[] = [];\n\n // 1. Convert arrays to stable objects\n const before_stable = before.map(stableStringify);\n const after_stable = after.map(stableStringify);\n\n // 2. Step through after array making changes to before array as-needed\n after_stable.forEach((value, index) => {\n const overflow = index >= before_stable.length;\n\n // Check if items are the same\n if (!overflow && before_stable[index] === value) {\n return;\n }\n\n // Check if item has been moved -> shift into place\n const from = before_stable.indexOf(value, index + 1);\n if (!overflow && from > -1) {\n changes.push({\n type: ChangeType.Move,\n path,\n from,\n to: index\n });\n\n const move = before_stable.splice(from, 1);\n before_stable.splice(index, 0, ...move);\n\n return;\n }\n\n // Check if item is removed -> assume it's been edited and replace\n const removed = !after_stable.includes(before_stable[index]);\n if (!overflow && removed) {\n merge(changes, diff(before[index], after[index], path.concat(index)));\n before_stable[index] = value;\n\n return;\n }\n\n // Add as new item and shift existing\n changes.push({\n type: ChangeType.Add,\n path: path.concat(index)\n });\n before_stable.splice(index, 0, value);\n });\n\n // 3. Remove any remaining overflow items\n for (let i = after_stable.length; i < before_stable.length; i++) {\n changes.push({\n type: ChangeType.Remove,\n path: path.concat(i)\n });\n }\n\n return changes;\n}\n","import { TreeNode, isKeyValue, isTable, isTableArray, hasItems, isInlineItem, hasItem } from './ast';\nimport { arraysEqual, stableStringify } from './utils';\n\nexport type Path = Array<string | number>;\n\nexport default function findByPath(node: TreeNode, path: Path): TreeNode {\n if (!path.length) {\n // If this is an InlineItem containing a KeyValue, return the KeyValue\n if (isInlineItem(node) && isKeyValue(node.item)) {\n return node.item;\n }\n return node;\n }\n\n if (isKeyValue(node)) {\n return findByPath(node.value, path);\n }\n\n const indexes: { [key: string]: number } = {};\n let found;\n if (hasItems(node)) {\n node.items.some((item, index) => {\n try {\n let key: Path = [];\n if (isKeyValue(item)) {\n key = item.key.value;\n } else if (isTable(item)) {\n key = item.key.item.value;\n } else if (isTableArray(item)) {\n key = item.key.item.value;\n\n const key_string = stableStringify(key);\n if (!indexes[key_string]) {\n indexes[key_string] = 0;\n }\n const array_index = indexes[key_string]++;\n\n key = key.concat(array_index);\n } else if (isInlineItem(item) && isKeyValue(item.item)) {\n key = item.item.key.value;\n } else if (isInlineItem(item)) {\n key = [index];\n }\n\n if (key.length && arraysEqual(key, path.slice(0, key.length))) {\n found = findByPath(item, path.slice(key.length));\n return true;\n } else {\n return false;\n }\n } catch (err) {\n return false;\n }\n });\n }\n\n if (!found) {\n throw new Error(`Could not find node at path ${path.join('.')}`);\n }\n\n return found;\n}\n\nexport function tryFindByPath(node: TreeNode, path: Path): TreeNode | undefined {\n try {\n return findByPath(node, path);\n } catch (err) {}\n}\n\nexport function findParent(node: TreeNode, path: Path): TreeNode {\n let parent_path = path;\n let parent;\n while (parent_path.length && !parent) {\n parent_path = parent_path.slice(0, -1);\n parent = tryFindByPath(node, parent_path);\n }\n\n if (!parent) {\n throw new Error(`Count not find parent node for path ${path.join('.')}`);\n }\n\n return parent;\n}\n","import parseTOML from './parse-toml';\nimport parseJS from './parse-js';\nimport toJS from './to-js';\nimport toTOML from './to-toml';\nimport { TomlFormat } from './toml-format';\nimport {\n isKeyValue,\n WithItems,\n KeyValue,\n isTable,\n TreeNode,\n Document,\n isDocument,\n Block,\n NodeType,\n isTableArray,\n isInlineArray,\n isInlineTable,\n isInlineItem,\n hasItem,\n InlineItem,\n AST,\n Table\n} from './ast';\nimport diff, { Change, isAdd, isEdit, isRemove, isMove, isRename } from './diff';\nimport findByPath, { tryFindByPath, findParent } from './find-by-path';\nimport { last, isInteger } from './utils';\nimport { insert, replace, remove, applyWrites } from './writer';\nimport { generateInlineItem, generateTable } from './generate';\nimport { validate } from './validate';\nimport { arrayHadTrailingCommas, tableHadTrailingCommas, resolveTomlFormat, postInlineItemRemovalAdjustment, calculateTableDepth } from './toml-format';\n\nexport function toDocument(ast: AST) : Document {\n const items = [...ast];\n return {\n type: NodeType.Document,\n loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 0 } },\n items\n };\n}\n\n/**\n * Applies modifications to a TOML document by comparing an existing TOML string with updated JavaScript data.\n * \n * This function preserves formatting and comments from the existing TOML document while\n * applying changes from the updated data structure. It performs a diff between the existing\n * and updated data, then strategically applies only the necessary changes to maintain the\n * original document structure as much as possible.\n * \n * @param existing - The original TOML document as a string\n * @param updated - The updated JavaScript object with desired changes\n * @param format - Optional formatting options to apply to new or modified sections\n * @returns A new TOML string with the changes applied\n */\nexport default function patch(existing: string, updated: any, format?: Partial<TomlFormat> | TomlFormat): string {\n const existing_ast = parseTOML(existing);\n\n // Auto-detect formatting preferences from the existing TOML string for fallback\n const autoDetectedFormat = TomlFormat.autoDetectFormat(existing);\n const fmt = resolveTomlFormat(format, autoDetectedFormat);\n\n return patchAst(existing_ast, updated, fmt).tomlString;\n}\n\nexport function patchAst(existing_ast:AST, updated: any, format: TomlFormat): { tomlString: string; document: Document } {\n const items = [...existing_ast];\n\n const existing_js = toJS(items);\n const existing_document: Document = {\n type: NodeType.Document,\n loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 0 } },\n items\n };\n\n // Certain formatting options should not be applied to the updated document during patching, because it would\n // override the existing formatting too aggressively. For example, preferNestedTablesMultiline would\n // convert all nested tables to multiline, which is not be desired during patching.\n // Therefore, we create a modified format for generating the updated document used for diffing.\n const diffing_fmt = resolveTomlFormat({...format, inlineTableStart: undefined}, format);\n const updated_document = parseJS(updated, diffing_fmt);\n \n const changes = reorder(diff(existing_js, updated));\n\n if (changes.length === 0) {\n return {\n tomlString: toTOML(items, format),\n document: existing_document\n };\n }\n\n const patched_document = applyChanges(existing_document, updated_document, changes, format);\n\n // Validate the patched_document\n // This would prevent overlapping element positions in the AST, but since those are handled at stringification time, we can skip this for now\n //validate(patched_document);\n\n return {\n tomlString: toTOML(patched_document.items, format),\n document: patched_document\n };\n}\n\nfunction reorder(changes: Change[]): Change[] {\n //Reorder deletions among themselves to avoid index issues\n // We want the path to be looking at the last item in the array first and go down from there\n \n let sorted = false;\n for (let i = 0; i < changes.length; i++) {\n const change = changes[i];\n if (isRemove(change)) {\n let j = i + 1;\n while (j < changes.length) {\n const next_change = changes[j];\n if (isRemove(next_change) && next_change.path[0] === change.path[0] && \n next_change.path[1] > change.path[1]) {\n changes.splice(j, 1);\n changes.splice(i, 0, next_change);\n // We reset i to the beginning of the loop to avoid skipping any changes\n i = 0\n break;\n }\n j++;\n }\n }\n }\n \n return changes;\n\n}\n\n/**\n * Applies a list of changes to the original TOML document AST while preserving formatting and structure.\n * \n * This function processes different types of changes (Add, Edit, Remove, Move, Rename) and applies them\n * to the original document in a way that maintains the existing formatting preferences, comments, and\n * structural elements as much as possible. Special handling is provided for different node types like\n * inline tables, arrays, and table arrays to ensure proper formatting consistency.\n * \n * @param original - The original TOML document AST to be modified\n * @param updated - The updated document AST containing new values for changes\n * @param changes - Array of change objects describing what modifications to apply\n * @param format - Formatting preferences to use for newly added elements\n * @returns The modified original document with all changes applied\n * \n * @example\n * ```typescript\n * const changes = [\n * { type: 'add', path: ['newKey'], value: 'newValue' },\n * { type: 'edit', path: ['existingKey'], value: 'updatedValue' }\n * ];\n * const result = applyChanges(originalDoc, updatedDoc, changes, format);\n * ```\n */\nfunction applyChanges(original: Document, updated: Document, changes: Change[], format: TomlFormat): Document {\n // Potential Changes:\n //\n // Add: Add key-value to object, add item to array\n // Edit: Change in value\n // Remove: Remove key-value from object, remove item from array\n // Move: Move item in array\n // Rename: Rename key in key-value\n //\n // Special consideration, inline comments need to move as-needed\n\n changes.forEach(change => {\n if (isAdd(change)) {\n\n const child = findByPath(updated, change.path);\n const parent_path = change.path.slice(0, -1);\n let index = last(change.path)! as number;\n\n let is_table_array = isTableArray(child);\n if (isInteger(index) && !parent_path.some(isInteger)) {\n const sibling = tryFindByPath(original, parent_path.concat(0));\n if (sibling && isTableArray(sibling)) {\n is_table_array = true;\n }\n }\n\n // Determine the parent node where the new child will be inserted\n let parent: TreeNode;\n if (isTable(child)) {\n parent = original;\n } else if (is_table_array) {\n parent = original;\n\n // The index needs to be updated to top-level items\n // to properly account for other items, comments, and nesting\n const document = original as Document;\n const before = tryFindByPath(document, parent_path.concat(index - 1)) as Block | undefined;\n const after = tryFindByPath(document, parent_path.concat(index)) as Block | undefined;\n if (after) {\n index = document.items.indexOf(after);\n } else if (before) {\n index = document.items.indexOf(before) + 1;\n } else {\n index = document.items.length;\n }\n } else {\n parent = findParent(original, change.path);\n if (isKeyValue(parent)) {\n parent = parent.value;\n }\n }\n\n if (isTableArray(parent) || isInlineArray(parent) || isDocument(parent)) {\n // Special handling for InlineArray: preserve original trailing comma format\n if (isInlineArray(parent)) {\n const originalHadTrailingCommas = arrayHadTrailingCommas(parent);\n // If this is an InlineItem being added to an array, check its comma setting\n if (isInlineItem(child)) {\n // The child comes from the updated document with global format applied\n // Override with the original array's format\n child.comma = originalHadTrailingCommas;\n }\n }\n \n // Check if we should convert nested inline tables to multiline tables\n if (format.inlineTableStart !== undefined && format.inlineTableStart > 0 && isDocument(parent) && isTable(child)) {\n const additionalTables = convertNestedInlineTablesToMultiline(child, original, format);\n \n // Insert the main table first\n insert(original, parent, child, index);\n \n // Then insert all the additional tables\n for (const table of additionalTables) {\n insert(original, original, table, undefined);\n }\n } else {\n insert(original, parent, child, index);\n }\n } else if (isInlineTable(parent)) {\n // Special handling for adding KeyValue to InlineTable\n // Preserve original trailing comma format\n const originalHadTrailingCommas = tableHadTrailingCommas(parent);\n // InlineTable items must be wrapped in InlineItem\n if (isKeyValue(child)) {\n const inlineItem = generateInlineItem(child);\n // Override with the original table's format\n inlineItem.comma = originalHadTrailingCommas;\n insert(original, parent, inlineItem);\n } else {\n insert(original, parent, child);\n }\n } else {\n // Check if we should convert inline tables to multiline tables when adding to existing tables\n if (format.inlineTableStart !== undefined && format.inlineTableStart > 0 && isKeyValue(child) && isInlineTable(child.value) && isTable(parent)) {\n // Calculate the depth of the inline table that would be created\n const baseTableKey = parent.key.item.value;\n const nestedTableKey = [...baseTableKey, ...child.key.value];\n const depth = calculateTableDepth(nestedTableKey);\n \n // Convert to separate section only if depth is less than inlineTableStart\n if (depth < format.inlineTableStart) {\n convertInlineTableToSeparateSection(child, parent, original, format);\n } else {\n insert(original, parent, child);\n }\n } else if (format.inlineTableStart === 0 && isKeyValue(child) && isInlineTable(child.value) && isDocument(parent)) {\n insert(original, parent, child, undefined, true);\n } else {\n insert(original, parent, child);\n }\n }\n\n } else if (isEdit(change)) {\n let existing = findByPath(original, change.path);\n let replacement = findByPath(updated, change.path);\n let parent;\n\n if (isKeyValue(existing) && isKeyValue(replacement)) {\n // Edit for key-value means value changes\n\n // Special handling for arrays: preserve original trailing comma format\n if (isInlineArray(existing.value) && isInlineArray(replacement.value)) {\n const originalHadTrailingCommas = arrayHadTrailingCommas(existing.value);\n const newArray = replacement.value;\n \n // Apply or remove trailing comma based on original format\n if (newArray.items.length > 0) {\n const lastItem = newArray.items[newArray.items.length - 1];\n lastItem.comma = originalHadTrailingCommas;\n }\n }\n \n // Special handling for inline tables: preserve original trailing comma format\n if (isInlineTable(existing.value) && isInlineTable(replacement.value)) {\n const originalHadTrailingCommas = tableHadTrailingCommas(existing.value);\n const newTable = replacement.value;\n \n // Apply or remove trailing comma based on original format\n if (newTable.items.length > 0) {\n const lastItem = newTable.items[newTable.items.length - 1];\n lastItem.comma = originalHadTrailingCommas;\n }\n }\n \n parent = existing;\n existing = existing.value;\n replacement = replacement.value;\n } else if (isKeyValue(existing) && isInlineItem(replacement) && isKeyValue(replacement.item)) {\n // Sometimes, the replacement looks like it could be an inline item, but the original is a key-value\n // In this case, we convert the replacement to a key-value to match the original\n parent = existing;\n existing = existing.value;\n replacement = replacement.item.value;\n } else if (isInlineItem(existing) && isKeyValue(replacement)) {\n // Editing inline table item: existing is InlineItem, replacement is KeyValue\n // We need to replace the KeyValue inside the InlineItem, preserving the InlineItem wrapper\n parent = existing;\n existing = existing.item;\n } else {\n parent = findParent(original, change.path);\n // Special handling for array element edits\n if (isKeyValue(parent)) {\n // Check if we're actually editing an array element\n const parentPath = change.path.slice(0, -1);\n const arrayNode = findByPath(original, parentPath);\n if (isKeyValue(arrayNode) && isInlineArray(arrayNode.value)) {\n parent = arrayNode.value;\n }\n }\n }\n\n replace(original, parent, existing, replacement);\n } else if (isRemove(change)) {\n let parent = findParent(original, change.path);\n if (isKeyValue(parent)) parent = parent.value;\n\n const node = findByPath(original, change.path);\n\n remove(original, parent, node);\n } else if (isMove(change)) {\n let parent = findByPath(original, change.path);\n if (hasItem(parent)) parent = parent.item;\n if (isKeyValue(parent)) parent = parent.value;\n\n const node = (parent as WithItems).items[change.from];\n\n remove(original, parent, node);\n insert(original, parent, node, change.to);\n } else if (isRename(change)) {\n let parent = findByPath(original, change.path.concat(change.from)) as\n | KeyValue\n | InlineItem<KeyValue>;\n let replacement = findByPath(updated, change.path.concat(change.to)) as\n | KeyValue\n | InlineItem<KeyValue>;\n\n if (hasItem(parent)) parent = parent.item;\n if (hasItem(replacement)) replacement = replacement.item;\n\n replace(original, parent, parent.key, replacement.key);\n }\n });\n\n applyWrites(original);\n return original;\n}\n\n/**\n * Converts nested inline tables to separate table sections based on the inlineTableStart depth setting.\n * This function recursively processes a table and extracts any inline tables within it,\n * creating separate table sections with properly nested keys.\n * \n * @param table - The table to process for nested inline tables\n * @param original - The original document for inserting new items\n * @param format - The formatting options\n * @returns Array of additional tables that should be added to the document\n */\nfunction convertNestedInlineTablesToMultiline(table: Table, original: Document, format: TomlFormat): Table[] {\n const additionalTables: Table[] = [];\n \n const processTableForNestedInlines = (currentTable: Table, tablesToAdd: Table[]) => {\n for (let i = currentTable.items.length - 1; i >= 0; i--) {\n const item = currentTable.items[i];\n if (isKeyValue(item) && isInlineTable(item.value)) {\n // Calculate the depth of this nested table\n const nestedTableKey = [...currentTable.key.item.value, ...item.key.value];\n const depth = calculateTableDepth(nestedTableKey);\n \n // Only convert to separate table if depth is less than inlineTableStart\n if (depth < (format.inlineTableStart ?? 1) && format.inlineTableStart !== 0) {\n // Convert this inline table to a separate table section\n const separateTable = generateTable(nestedTableKey);\n \n // Move all items from the inline table to the separate table\n for (const inlineItem of item.value.items) {\n if (isInlineItem(inlineItem) && isKeyValue(inlineItem.item)) {\n insert(original, separateTable, inlineItem.item, undefined);\n }\n }\n \n // Remove this item from the original table\n currentTable.items.splice(i, 1);\n \n // Update the parent table's end position after removal\n postInlineItemRemovalAdjustment(currentTable);\n \n // Queue this table to be added to the document\n tablesToAdd.push(separateTable);\n \n // Recursively process the new table for further nested inlines\n processTableForNestedInlines(separateTable, tablesToAdd);\n }\n }\n }\n };\n \n processTableForNestedInlines(table, additionalTables);\n return additionalTables;\n}\n\n/**\n * Converts an inline table to a separate table section when adding to an existing table.\n * This function creates a new table section with the combined key path and moves all\n * properties from the inline table to the separate table section.\n * \n * @param child - The KeyValue node with an InlineTable as its value\n * @param parent - The parent table where the KeyValue would be added\n * @param original - The original document for inserting new items\n * @param format - The formatting options\n */\nfunction convertInlineTableToSeparateSection(child: KeyValue, parent: Table, original: Document, format: TomlFormat): void {\n // Convert the inline table to a separate table section\n const baseTableKey = parent.key.item.value; // Get the parent table's key path\n const nestedTableKey = [...baseTableKey, ...child.key.value]; // Combine with the new key\n const separateTable = generateTable(nestedTableKey);\n \n // We know child.value is an InlineTable from the calling context\n if (isInlineTable(child.value)) {\n // Move all items from the inline table to the separate table\n for (const inlineItem of child.value.items) {\n if (isInlineItem(inlineItem) && isKeyValue(inlineItem.item)) {\n insert(original, separateTable, inlineItem.item, undefined);\n }\n }\n }\n \n // Add the separate table to the document\n insert(original, original, separateTable, undefined);\n \n // Update the parent table's end position since we're not adding the inline table to it\n postInlineItemRemovalAdjustment(parent);\n \n // Also handle any nested inline tables within the new table\n const additionalTables = convertNestedInlineTablesToMultiline(separateTable, original, format);\n for (const table of additionalTables) {\n insert(original, original, table, undefined);\n }\n}","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\r\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\r\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nvar ownKeys = function(o) {\r\n ownKeys = Object.getOwnPropertyNames || function (o) {\r\n var ar = [];\r\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\r\n return ar;\r\n };\r\n return ownKeys(o);\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose, inner;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n if (async) inner = dispose;\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n var r, s = 0;\r\n function next() {\r\n while (r = env.stack.pop()) {\r\n try {\r\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\r\n if (r.dispose) {\r\n var result = r.dispose.call(r.value);\r\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n else s |= 1;\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\r\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\r\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\r\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\r\n });\r\n }\r\n return path;\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __esDecorate: __esDecorate,\r\n __runInitializers: __runInitializers,\r\n __propKey: __propKey,\r\n __setFunctionName: __setFunctionName,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n __rewriteRelativeImportExtension: __rewriteRelativeImportExtension,\r\n};\r\n","import { AST, Block } from './ast';\nimport { Position } from './location';\n\n/**\n * Compares two positions to determine their ordering.\n * @param pos1 - First position\n * @param pos2 - Second position\n * @returns Negative if pos1 < pos2, 0 if equal, positive if pos1 > pos2\n */\nfunction comparePositions(pos1: Position, pos2: Position): number {\n if (pos1.line !== pos2.line) {\n return pos1.line - pos2.line;\n }\n return pos1.column - pos2.column;\n}\n\n/**\n * Checks if a block node should be included based on its location.\n * A block is included if its end position is before the limit position.\n * This ensures that only complete blocks that don't contain the change are kept.\n * @param node - The block node to check\n * @param limit - The position limit\n * @returns true if the block should be included\n */\nfunction shouldIncludeBlock(node: Block, limit: Position): boolean {\n return comparePositions(node.loc.end, limit) < 0;\n}\n\n/**\n * Truncates an AST based on a position (line, column) in the source string.\n * \n * This function filters the AST to include only the nodes that end before\n * the specified position. This ensures that blocks containing changes are\n * excluded and can be reparsed. This is useful for incremental parsing scenarios\n * where you want to keep only the unchanged portion of the AST.\n * \n * Special handling: If the truncation point falls within a Table or TableArray\n * (e.g., in a comment inside the table), the entire table is excluded to ensure\n * proper reparsing.\n * \n * @param ast - The AST to truncate\n * @param line - The line number (1-indexed) at which to truncate\n * @param column - The column number (0-indexed) at which to truncate\n * @returns An object containing the truncated AST and the end position of the last included node\n * \n * @example\n * ```typescript\n * const ast = parseTOML(tomlString);\n * // Get AST up to line 5, column 10 (only nodes that end before this position)\n * const { truncatedAst, lastEndPosition } = truncateAst(ast, 5, 10);\n * for (const node of truncatedAst) {\n * // process node\n * }\n * ```\n */\nexport function truncateAst(ast: AST, line: number, column: number): { \n truncatedAst: AST; \n lastEndPosition: Position | null \n} {\n const limit: Position = { line, column };\n const nodes: Block[] = [];\n let lastEndPosition: Position | null = null;\n \n for (const node of ast) {\n const nodeEndsBeforeLimit = comparePositions(node.loc.end, limit) < 0;\n const nodeStartsBeforeLimit = comparePositions(node.loc.start, limit) < 0;\n \n if (nodeEndsBeforeLimit) {\n // Node completely ends before the limit - include it\n nodes.push(node);\n lastEndPosition = node.loc.end;\n } else if (nodeStartsBeforeLimit && !nodeEndsBeforeLimit) {\n // Node starts before the limit but ends at or after it\n // This means the truncation point is within this node\n // For Table/TableArray nodes, don't include them if the change is inside\n // This ensures the entire table gets reparsed\n break;\n } else {\n // Node starts at or after the limit - stop\n break;\n }\n }\n \n return {\n truncatedAst: nodes,\n lastEndPosition\n };\n}\n\n/**\n * Finds the last block node in an AST that ends before the specified position.\n * \n * @param ast - The AST to search\n * @param line - The line number (1-indexed)\n * @param column - The column number (0-indexed)\n * @returns The last block node that ends before the position, or undefined if no such node exists\n * \n * @example\n * ```typescript\n * const ast = parseTOML(tomlString);\n * const lastNode = findLastNodeBeforePosition(ast, 5, 10);\n * if (lastNode) {\n * console.log('Last node type:', lastNode.type);\n * }\n * ```\n */\nexport function findLastNodeBeforePosition(ast: AST, line: number, column: number): Block | undefined {\n const limit: Position = { line, column };\n let lastNode: Block | undefined = undefined;\n \n for (const node of ast) {\n if (shouldIncludeBlock(node, limit)) {\n lastNode = node;\n } else {\n // Once we encounter a node that starts after the limit, we can stop\n break;\n }\n }\n \n return lastNode;\n}\n","import parseTOML, { continueParsingTOML } from './parse-toml';\nimport toTOML from './to-toml';\nimport toJS from './to-js';\nimport { TomlFormat } from './toml-format';\nimport { AST, Block } from './ast';\nimport { patchAst } from './patch';\nimport { detectNewline, resolveTomlFormat } from './toml-format';\nimport { truncateAst } from './truncate';\n\n/**\n * TomlDocument encapsulates a TOML AST and provides methods to interact with it.\n */\nexport class TomlDocument {\n #ast: Block[];\n #currentTomlString: string;\n #Format: TomlFormat;\n\n /**\n * Initializes the TomlDocument with a TOML string, parsing it into an AST.\n * @param tomlString - The TOML string to parse\n */\n constructor(tomlString: string) {\n this.#currentTomlString = tomlString;\n this.#ast = Array.from(parseTOML(tomlString));\n // Auto-detect formatting preferences from the original TOML string\n this.#Format = TomlFormat.autoDetectFormat(tomlString);\n }\n\n get toTomlString(): string {\n return this.#currentTomlString;\n }\n\n /**\n * Returns the JavaScript object representation of the TOML document.\n */\n get toJsObject(): any {\n const jsObject = toJS(this.#ast);\n // Convert custom date classes to regular JavaScript Date objects\n return convertCustomDateClasses(jsObject);\n }\n\n /**\n * Returns the internal AST (for testing purposes).\n * @internal\n */\n get ast(): Block[] {\n return this.#ast;\n }\n\n /**\n * Applies a patch to the current AST using a modified JS object.\n * Updates the internal AST. Use toTomlString getter to retrieve the updated TOML string.\n * @param updatedObject - The modified JS object to patch with\n * @param format - Optional formatting options\n */\n patch(updatedObject: any, format?: Partial<TomlFormat> | TomlFormat) : void {\n\n const fmt = resolveTomlFormat(format, this.#Format);\n\n const { tomlString, document } = patchAst(\n this.#ast,\n updatedObject,\n fmt\n );\n this.#ast = document.items;\n this.#currentTomlString = tomlString;\n }\n\n /**\n * Updates the internal document by supplying a modified tomlString.\n * Use toJsObject getter to retrieve the updated JS object representation.\n * @param tomlString - The modified TOML string to update with\n */\n update(tomlString: string): void {\n if (tomlString === this.toTomlString) {\n return;\n }\n\n // Now, let's check where the first difference is\n const existingLines = this.toTomlString.split(this.#Format.newLine);\n const newLineChar = detectNewline(tomlString);\n const newTextLines = tomlString.split(newLineChar);\n let firstDiffLineIndex = 0;\n while (\n firstDiffLineIndex < existingLines.length &&\n firstDiffLineIndex < newTextLines.length &&\n existingLines[firstDiffLineIndex] === newTextLines[firstDiffLineIndex]\n ) {\n firstDiffLineIndex++;\n }\n\n // Calculate the 1-based line number and 0-based column where the first difference occurs\n \n let firstDiffColumn = 0;\n \n // If we're within the bounds of both arrays, find the column where they differ\n if (firstDiffLineIndex < existingLines.length && firstDiffLineIndex < newTextLines.length) {\n const existingLine = existingLines[firstDiffLineIndex];\n const newLine = newTextLines[firstDiffLineIndex];\n \n // Find the first character position where the lines differ\n for (let i = 0; i < Math.max(existingLine.length, newLine.length); i++) {\n if (existingLine[i] !== newLine[i]) {\n firstDiffColumn = i;\n break;\n }\n }\n }\n\n let firstDiffLine = firstDiffLineIndex + 1; // Convert to 1-based\n const { truncatedAst, lastEndPosition } = truncateAst(this.#ast, firstDiffLine, firstDiffColumn);\n\n // Determine where to continue parsing from in the new string\n // If lastEndPosition exists, continue from there; otherwise from the start of the document\n const continueFromLine = lastEndPosition ? lastEndPosition.line : 1;\n const continueFromColumn = lastEndPosition ? lastEndPosition.column + 1 : 0;\n\n // Based on the first difference, we can re-parse only the affected part\n // We will need to supply the remaining string after where the AST was truncated\n const remainingLines = newTextLines.slice(continueFromLine - 1);\n \n // If there's a partial line match, we need to extract only the part after the continuation column\n if (remainingLines.length > 0 && continueFromColumn > 0) {\n remainingLines[0] = remainingLines[0].substring(continueFromColumn);\n }\n \n const remainingToml = remainingLines.join(this.#Format.newLine);\n \n this.#ast = Array.from(continueParsingTOML(truncatedAst, remainingToml));\n this.#currentTomlString = tomlString;\n \n // Update the auto-detected format with the new string's characteristics\n this.#Format = TomlFormat.autoDetectFormat(tomlString);\n }\n\n /**\n * Overwrites the internal AST by fully re-parsing the supplied tomlString.\n * This is simpler but slower than update() which uses incremental parsing.\n * @param tomlString - The TOML string to overwrite with\n */\n overwrite(tomlString: string): void {\n if (tomlString === this.toTomlString) {\n return;\n }\n\n // Re-parse the entire document\n this.#ast = Array.from(parseTOML(tomlString));\n this.#currentTomlString = tomlString;\n \n // Update the auto-detected format with the new string's characteristics\n this.#Format = TomlFormat.autoDetectFormat(tomlString);\n }\n}\n\n/**\n * Recursively converts custom date classes to regular JavaScript Date objects.\n * This ensures that the toJsObject property returns standard Date objects\n * while preserving the custom classes internally for TOML formatting.\n */\nfunction convertCustomDateClasses(obj: any): any {\n if (obj instanceof Date) {\n // Convert custom date classes to regular Date objects\n return new Date(obj.getTime());\n } else if (Array.isArray(obj)) {\n return obj.map(convertCustomDateClasses);\n } else if (obj && typeof obj === 'object') {\n const result: any = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = convertCustomDateClasses(value);\n }\n return result;\n }\n return obj;\n}\n","import parseTOML from './parse-toml';\nimport parseJS from './parse-js';\nimport toTOML from './to-toml';\nimport toJS from './to-js';\nimport { TomlFormat, resolveTomlFormat } from './toml-format';\n\n/**\n * Parses a TOML string into a JavaScript object.\n * The function converts TOML syntax to its JavaScript equivalent.\n * This proceeds in two steps: first, it parses the TOML string into an AST,\n * and then it converts the AST into a JavaScript object.\n * \n * @param value - The TOML string to parse\n * @returns The parsed JavaScript object\n */\nexport function parse(value: string): any {\n return toJS(parseTOML(value), value);\n}\n\n/**\n * Converts a JavaScript object to a TOML string.\n * \n * @param value - The JavaScript object to stringify\n * @param format - Optional formatting options for the resulting TOML\n * @returns The stringified TOML representation\n */\nexport function stringify(value: any, format?: Partial<TomlFormat> | TomlFormat): string {\n const fmt = resolveTomlFormat(format, TomlFormat.default());\n \n const document = parseJS(value, fmt);\n return toTOML(document.items, fmt);\n}\n\nexport { default as patch } from './patch';\n\n/**\n * TomlFormat class for configuring TOML formatting options.\n * \n * This class allows you to customize how TOML documents are formatted when using\n * the stringify() and patch() functions. It provides control over line endings,\n * spacing, trailing commas, and other formatting preferences.\n * \n * @example\n * ```typescript\n * import { patch, TomlFormat } from '@decimalturn/toml-patch';\n * \n * // Create a custom format configuration\n * const format = TomlFormat.default();\n * format.newLine = '\\r\\n'; // Windows line endings\n * format.trailingNewline = 0; // No trailing newline\n * format.trailingComma = true; // Add trailing commas\n * format.bracketSpacing = false; // No spaces in brackets\n * \n * // Apply the patch with custom formatting\n * const result = patch(existingToml, updatedData, format);\n * ```\n */\nexport { TomlFormat } from './toml-format';\n\n/**\n * TomlDocument encapsulates a TOML AST and provides methods to interact with it.\n */\nexport { TomlDocument } from './toml-document';\n"],"names":["NodeType","TokenType","isDocument","node","type","Document","isTable","Table","isTableArray","TableArray","isKeyValue","KeyValue","isDateTime","DateTime","isInlineArray","InlineArray","isInlineItem","InlineItem","isInlineTable","InlineTable","isComment","Comment","hasItems","hasItem","TableKey","isTableKey","TableArrayKey","isTableArrayKey","Cursor","constructor","iterator","this","index","value","undefined","done","peeked","next","result","_a","peek","Symbol","getSpan","location","lines","end","line","start","columns","column","findPosition","input","Array","isArray","findLines","findIndex","line_index","BY_NEW_LINE","indexes","match","exec","push","length","clonePosition","position","cloneLocation","ParseError","Error","message","error_message","substr","getLine","pointer","count","character","repeat","whitespace","super","IS_WHITESPACE","IS_NEW_LINE","DOUBLE_QUOTE","SINGLE_QUOTE","IS_VALID_LEADING_CHARACTER","tokenize","cursor","locate","createLocate","test","specialCharacter","Bracket","Curly","Equal","Comma","Dot","comment","multiline_char","checkThree","multiline","string","raw","loc","quotes","CheckMoreThanThree","Literal","double_quoted","single_quoted","isFinished","next_item","current","check","backslashes","slice","last","values","blank","Object","create","isInteger","isFinite","is","isDate","prototype","toString","call","isObject","has","object","key","hasOwnProperty","pipe","fns","reduce","fn","stableStringify","keys","sort","map","JSON","stringify","join","merge","target","original_length","added_length","i","IS_CRLF","IS_LF","IS_LEADING_NEW_LINE","IS_LINE_ENDING_BACKSLASH","parseString","startsWith","trim","trimLeadingWhitespace","lineEndingBackslash","escapeNewLines","escapeDoubleQuotes","unescapeLargeUnicode","precedingBackslashes","char","escaped","json_escaped","replace","code_point","parseInt","as_string","String","fromCodePoint","fixed_json_escaped","parse","group","DateFormatHelper","createDateWithOriginalFormat","newJSDate","originalRaw","IS_DATE_ONLY","getUTCHours","getUTCMinutes","getUTCSeconds","getUTCMilliseconds","OffsetDateTime","isoString","toISOString","LocalDateTime","dateStr","split","LocalDate","IS_TIME_ONLY","LocalTime","msMatch","includes","newTime","msDigits","h","m","sMs","s","padStart","hours","minutes","seconds","milliseconds","timeStr","IS_LOCAL_DATETIME_T","datePart","timePart","IS_LOCAL_DATETIME_SPACE","IS_OFFSET_DATETIME_T","IS_OFFSET_DATETIME_SPACE","offsetMatch","originalOffset","useSpaceSeparator","utcTime","getTime","offsetMinutes","sign","localTime","Date","year","getUTCFullYear","month","getUTCMonth","day","getUTCDate","separator","IS_FULL_DATE","IS_FULL_TIME","originalFormat","dateFormatHelper","TRUE","HAS_E","IS_DIVIDER","IS_INF","IS_NAN","IS_HEX","IS_OCTAL","IS_BINARY","parseTOML","tokens","walkBlock","is_table","item","Key","dot","before","after","items","table","equals","comments","walkValue","keyValue","Boolean","boolean","local_date","datetime","Infinity","Number","Float","float","Integer","radix","integer","previous","comma","inline_item","inlineTable","inline_array","additional_comments","inlineArray","traverse","ast","visitor","traverseArray","array","parent","traverseNode","visit","enter","exit","enter_offsets","WeakMap","getEnterOffsets","root","set","get","exit_offsets","getExitOffsets","existing","replacement","newValue","formattedDate","indexOf","splice","shiftNode","existing_span","replacement_span","addOffset","insert","child","forceInline","shift","offset","is_last","has_separating_comma_before","has_separating_comma_after","use_new_line","perLine","has_trailing_comma","calculateInlinePositioning","useNewLine","hasCommaHandling","isLastElement","hasSeparatingCommaBefore","hasSeparatingCommaAfter","hasTrailingComma","insertInline","insertInlineAtRoot","use_first_line","isSquareBracketsStructure","leading_lines","child_span","insertOnNewLine","previous_offset","delete","options","skipCommaSpace","skipBracketSpace","hasSpacing","trailing_comma_offset_adjustment","remove","removed_span","is_inline","previous_on_same_line","next_on_sameLine","keep_line","removedHadTrailingComma","target_offsets","node_offsets","removed_offset","applyBracketSpacing","bracket_spacing","last_item","applyTrailingComma","trailing_commas","applyWrites","shiftStart","lineOffset","columnOffset","entering","shiftEnd","exiting","shiftLocation","start_line","key_offset","span","first_line_only","move","offsets","from","generateDocument","generateTable","table_key","keyValueToRaw","generateTableKey","generateTableArray","table_array_key","generateTableArrayKey","generateKeyValue","key_node","generateKey","IS_BARE_KEY","part","generateInlineItem","DEFAULT_TRAILING_COMMA","DEFAULT_BRACKET_SPACING","findBracketSpacingInNode","tomlString","bracketSpacing","startLine","endLine","startCol","endCol","rawText","substring","arrayMatch","tableMatch","checkBracketSpacingInLocation","nestedResult","prop","findTrailingCommaInNode","checkTrailingCommaInItems","lastItem","arrayHadTrailingCommas","tableHadTrailingCommas","detectNewline","str","lfIndex","resolveTomlFormat","format","fallbackFormat","TomlFormat","validatedFormat","supportedProperties","Set","unsupportedProperties","invalidTypeProperties","newLine","trailingNewline","inlineTableStart","console","warn","TypeError","validateFormatObject","_b","_c","trailingComma","_d","autoDetectFormat","default","newlineChar","pos","countTrailingNewlines","astArray","detectTrailingComma","detectBracketSpacing","error","formatTopLevel","document","filter","is_inline_table","is_inline_array","depth","calculateTableDepth","forEach","formatTable","key_value","inline_array_item","table_array","inline_table_item","formatTableArray","postInlineItemRemovalAdjustment","keyPath","Math","max","processTableForNestedInlines","additionalTables","nestedTableKey","separateTable","inlineItem","parseJS","simpleKeys","complexKeys","reorderElements","toJSON","walkObject","formatted","formatNestedTablesMultiline","formatPrintWidth","formatEmptyLines","isString","generateString","generateInteger","isFloat","isNaN","generateFloat","isBoolean","generateBoolean","generateDateTime","element","walkInlineArray","inline_table","walkInlineTable","toTOML","write","raw_lines","expected_lines","is_start_line","is_end_line","padEnd","toJS","tables","table_arrays","defined","active","skip_depth","validateKey","err","e","joined_key","joinKey","add","ensureTable","ensure","last_key","ensureTableArray","toValue","state","parts","joined_parts","next_is_last","subkey","ChangeType","isRemove","change","Remove","diff","path","b","a","changes","before_stable","after_stable","overflow","Move","to","removed","concat","Add","compareArrays","before_keys","after_keys","isRename","stable","search","before_key","sub_path","Rename","compareObjects","Edit","findByPath","found","some","key_string","array_index","arraysEqual","tryFindByPath","findParent","parent_path","patchAst","existing_ast","updated","existing_js","existing_document","updated_document","assign","j","next_change","reorder","patched_document","original","isAdd","is_table_array","sibling","originalHadTrailingCommas","convertNestedInlineTablesToMultiline","baseTableKey","convertInlineTableToSeparateSection","isEdit","newArray","newTable","parentPath","arrayNode","isMove","applyChanges","currentTable","tablesToAdd","__classPrivateFieldGet","receiver","kind","f","__classPrivateFieldSet","comparePositions","pos1","pos2","SuppressedError","convertCustomDateClasses","obj","entries","_TomlDocument_ast","_TomlDocument_currentTomlString","_TomlDocument_Format","toTomlString","toJsObject","patch","updatedObject","fmt","update","existingLines","newLineChar","newTextLines","firstDiffLineIndex","firstDiffColumn","existingLine","firstDiffLine","truncatedAst","lastEndPosition","limit","nodes","nodeEndsBeforeLimit","nodeStartsBeforeLimit","truncateAst","continueFromLine","continueFromColumn","remainingLines","remainingToml","existingAst","remainingString","continueParsingTOML","overwrite"],"mappings":";4OAEA,IAAYA,ECEAC,EDyCN,SAAUC,EAAWC,GACzB,OAAOA,EAAKC,OAASJ,EAASK,QAChC,CAoBM,SAAUC,EAAQH,GACtB,OAAOA,EAAKC,OAASJ,EAASO,KAChC,CA4CM,SAAUC,EAAaL,GAC3B,OAAOA,EAAKC,OAASJ,EAASS,UAChC,CAmCM,SAAUC,EAAWP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