All files / src/modules/implementations/journal/syntax ledger-parser.js

98.19% Statements 327/333
92.27% Branches 191/207
100% Functions 19/19
98.19% Lines 327/333

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 33467x 67x 803x 803x 803x 803x 803x 803x 803x 803x 95121x 7x 7x 95114x 95121x 803x 36121x 4x 4x 36117x 36121x 803x 204413x 204413x 204413x 1179755x 1179755x 216748x 216748x 216748x 963007x 963007x 1179755x 108373x 204413x 803x 108407x 108407x 108407x 108407x 108407x 6x 6x 108401x 108407x 803x 146699x 146699x 2009326x 2009326x 12x 12x 12x 2009314x 2009314x 2009311x 2009311x 2009326x 146579x 146699x 803x 11045x 11045x 18x 18x 18x 18x 18x 18x 11027x 11027x 11041x 11045x 11045x 803x 11045x 11045x 11045x 11001x 11001x 11045x 11045x 11045x 11045x 11045x 11045x 11045x 803x 34474x 568741x 568741x 568741x 568741x 34350x 34350x 34350x 34350x 34350x 568741x 124x 34474x 803x 14999x 14999x 14999x 1x 1x 14993x 14993x 14993x 14993x 14993x 14999x 14999x 14999x 14999x 14999x 14999x 14999x 14999x 14999x 14999x 803x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 34474x 803x 93375x 93375x 93375x 93375x 93375x 93374x 93374x 93374x 93375x 93373x 93375x 93375x 93373x 93373x 93375x 93371x 93371x 93375x 93375x     93370x 93375x 803x 2659x 2659x 2659x 2659x 2659x 803x 834x 834x 834x 824x 834x 1x 1x 834x 803x 803x 112768x 1x 1x 112768x 112768x 1x 1x 112768x 112768x 112768x 112768x 112768x 112768x 112768x 4531278x 4531278x 172986x 172986x 172986x 4531278x 172986x 172986x 172986x 4531235x 172986x 4531278x 13530x 13530x 13530x 13530x 159456x 4531278x 12738x 1753x 1753x 1753x 1753x 1753x 1753x 1753x 1753x 12738x 10985x 10985x 10985x 10985x 10985x 10985x 10972x 10972x 10985x 10985x 10985x 12738x 4531278x 35680x 35680x 1206x 1202x 1202x 1202x 1202x 1x 1x 1202x 1202x 1202x 1202x 1x 1x 1188x 1188x 4x 4x 35640x 35640x 111038x 111038x 4531278x 14999x 14999x 14999x 96039x 24x 24x 24x 96015x 1647x 1647x 1647x 1647x 94368x 94368x 94304x 924x 924x 924x 924x 93380x 93380x 5x 5x 5x 5x 4531278x 112762x 112726x     112726x 112701x 112768x 803x 419x 419x     419x 419x 419x 419x 112692x 112692x 112692x 112692x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 112692x 419x 419x 419x 419x 419x 419x 803x 67x  
'use strict';
module.exports = ({ amountParser: { parseAmountExpression }, ingestionWarning: { createWarning, warningCodes }, syntaxErrors: { syntaxError }, topLevelBlocks: { splitTopLevelBlocks }, core: { publicErrors: { createError, errorCodes }, }, external: { zod: { z } }, }) => {
    const DATE_LENGTH = 10;
    const COMMODITY_PROPERTY_NAMES = new Set(['default', 'format']);
    const CANONICAL_COMMODITY_FORMAT = /^(\d,?\d{3})(?:\.(\d+))?[ \t]+([^ \t]+)$/u;
    const isWhitespace = (code) => code === 32 || code === 9;
    const isCommoditySymbol = (value) => /^[\p{L}_]+$/u.test(value);
    const sourceLocation = (source, line, column) => ({ source, line, column });
    const optionsSchema = z.strictObject({ source: z.string().optional() });
    function assertCommoditySymbol(value, source, line, column) {
        if (!isCommoditySymbol(value)) {
            throw syntaxError(`Invalid commodity symbol ${JSON.stringify(value)}`, source, line, column);
        }
        return value;
    }
    function assertAccountName(value, source, line, column) {
        if (/[*~\t]| {2}/u.test(value)) {
            throw syntaxError(`Account name ${JSON.stringify(value)} cannot contain *, ~, tabs, or consecutive spaces`, source, line, column);
        }
        return value;
    }
    function isDateAt(input, offset) {
        if (input.length - offset < DATE_LENGTH)
            return false;
        for (let index = 0; index < DATE_LENGTH; index++) {
            const code = input.charCodeAt(offset + index);
            if (index === 4 || index === 7) {
                if (code !== 45)
                    return false;
            }
            else if (code < 48 || code > 57)
                return false;
        }
        return true;
    }
    function assertDate(value, source, line, column) {
        const year = Number(value.slice(0, 4));
        const month = Number(value.slice(5, 7));
        const day = Number(value.slice(8, 10));
        const date = new Date(Date.UTC(year, month - 1, day));
        if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) {
            throw syntaxError(`Invalid date ${JSON.stringify(value)}`, source, line, column);
        }
        return value;
    }
    function splitComment(input) {
        let quote = 0;
        for (let index = 0; index < input.length; index++) {
            const code = input.charCodeAt(index);
            if (quote) {
                if (code === quote)
                    quote = 0;
            }
            else if (code === 34 || code === 39)
                quote = code;
            else if (code === 59)
                return { text: input.slice(0, index).trimEnd(), comment: input.slice(index + 1).trim(), index };
        }
        return { text: input.trimEnd(), comment: null };
    }
    function parseCommentTags(comment) {
        const binary = /^:([^\s:;]+(?::[^\s:;]+)*:)(?:[ \t]+(.*))?$/u.exec(comment);
        if (binary) {
            return {
                tags: binary[1].slice(0, -1).split(':').map((name) => ({ name, value: null })),
                text: binary[2]?.trim() ?? '',
                tagged: true,
            };
        }
        const value = /^([^\s:;]+):[ \t]+(.*)$/u.exec(comment);
        return value
            ? { tags: [{ name: value[1], value: value[2].trim() }], text: '', tagged: true }
            : { tags: [], text: comment, tagged: false };
    }
    function parseComment(text, source, line, column) {
        const parsed = parseCommentTags(text);
        const location = sourceLocation(source, line, column);
        const tags = parsed.tags.map((tag) => {
            Object.defineProperty(tag, 'location', { value: location });
            return tag;
        });
        return {
            comment: parsed.tagged && !parsed.text
                ? null : { text: parsed.text, key: null, value: null, location },
            tags,
        };
    }
    function findFieldSeparator(input) {
        for (let index = 0; index < input.length; index++) {
            const code = input.charCodeAt(index);
            if (code === 9)
                return { start: index, end: index + 1 };
            if (code === 32 && input.charCodeAt(index + 1) === 32) {
                let end = index + 2;
                while (isWhitespace(input.charCodeAt(end)))
                    end++;
                return { start: index, end };
            }
        }
        return null;
    }
    function parseTransactionHeader(text, source, line) {
        let cursor = DATE_LENGTH;
        const date = assertDate(text.slice(0, cursor), source, line, 1);
        if (cursor < text.length && !isWhitespace(text.charCodeAt(cursor))) {
            throw syntaxError('Expected whitespace after transaction date', source, line, cursor + 1);
        }
        while (isWhitespace(text.charCodeAt(cursor)))
            cursor++;
        const parts = splitComment(text.slice(cursor));
        const description = parts.text.trim();
        if (!description)
            throw syntaxError('Expected a transaction description', source, line, cursor + 1);
        const parsedComment = parts.comment === null ? null : parseComment(parts.comment, source, line, cursor + (parts.index ?? 0) + 1);
        const tags = parsedComment?.tags || [];
        return {
            type: 'transaction', date, description,
            ...(tags.length > 0 ? { tags } : {}), postings: [],
            comments: parsedComment?.comment ? [parsedComment.comment] : [],
            location: sourceLocation(source, line, 1),
        };
    }
    function parsePosting(raw, source, line) {
        let indent = 0;
        while (isWhitespace(raw.charCodeAt(indent)))
            indent++;
        const parts = splitComment(raw.slice(indent));
        const separator = findFieldSeparator(parts.text);
        const account = (separator ? parts.text.slice(0, separator.start) : parts.text).trim();
        if (!account)
            throw syntaxError('Posting account cannot be empty', source, line, indent + 1);
        assertAccountName(account, source, line, indent + 1);
        const expressionText = separator ? parts.text.slice(separator.end).trim() : '';
        const expressionColumn = separator ? indent + separator.end + 1 : raw.length + 1;
        const expression = parseAmountExpression(expressionText, sourceLocation(source, line, expressionColumn));
        const postingDateMatch = parts.comment && /^\[(\d{4}-\d{2}-\d{2})\](?:\s|$)/u.exec(parts.comment);
        const commentAfterDate = postingDateMatch ? parts.comment.slice(postingDateMatch[0].length).trimStart() : parts.comment;
        const parsedComment = parts.comment === null || (postingDateMatch && !commentAfterDate) ? null : parseComment(commentAfterDate ?? '', source, line, indent + (parts.index ?? 0) + 1);
        const tags = parsedComment?.tags || [];
        return {
            type: 'posting', account,
            ...(expression || { amount: null, lotCost: null, cost: null, balanceAssignment: null, balanceAssertion: null }),
            postingDate: postingDateMatch ? assertDate(postingDateMatch[1], source, line, raw.indexOf('[') + 2) : null,
            comments: parsedComment?.comment ? [parsedComment.comment] : [],
            ...(tags.length > 0 ? { tags } : {}),
            location: sourceLocation(source, line, indent + 1),
        };
    }
    function parsePrice(text, source, line) {
        let cursor = 1;
        while (isWhitespace(text.charCodeAt(cursor)))
            cursor++;
        if (!isDateAt(text, cursor))
            throw syntaxError('Expected a date after P', source, line, cursor + 1);
        const date = assertDate(text.slice(cursor, cursor + DATE_LENGTH), source, line, cursor + 1);
        cursor += DATE_LENGTH;
        while (isWhitespace(text.charCodeAt(cursor)))
            cursor++;
        const symbolStart = cursor;
        while (cursor < text.length && !isWhitespace(text.charCodeAt(cursor)))
            cursor++;
        const commodity = assertCommoditySymbol(text.slice(symbolStart, cursor), source, line, symbolStart + 1);
        while (isWhitespace(text.charCodeAt(cursor)))
            cursor++;
        const parts = splitComment(text.slice(cursor));
        const expression = parseAmountExpression(parts.text, sourceLocation(source, line, cursor + 1));
        if (!expression || !expression.amount || expression.lotCost || expression.cost ||
            expression.balanceAssignment || expression.balanceAssertion) {
            throw syntaxError('Expected a simple amount in price directive', source, line, cursor + 1);
        }
        return { type: 'price', date, commodity, price: expression.amount, comment: parts.comment, location: sourceLocation(source, line, 1) };
    }
    function parseNamedDirective(text, keyword, type, source, line) {
        const value = splitComment(text.slice(keyword.length).trimStart());
        if (!value.text)
            throw syntaxError(`Expected a value after ${keyword}`, source, line, keyword.length + 1);
        return { type, name: value.text, comment: value.comment, location: sourceLocation(source, line, 1) };
    }
    function assertCommodityFormat(value, commodity, source, line, column) {
        const match = CANONICAL_COMMODITY_FORMAT.exec(value ?? '');
        if (!match)
            throw syntaxError('Expected a canonical commodity format', source, line, column);
        const symbol = assertCommoditySymbol(match[3], source, line, column);
        if (symbol !== commodity) {
            throw syntaxError(`Commodity format symbol ${JSON.stringify(symbol)} must match ${JSON.stringify(commodity)}`, source, line, column);
        }
    }
    /** Fast runtime parser. Its behavior is checked against ledger.ohm. */
    function parseStrict(sourceText, options, lineOffset) {
        if (typeof sourceText !== 'string') {
            throw createError(errorCodes.INVALID_API_INPUT, 'Ledger source text must be a string', TypeError);
        }
        const result = optionsSchema.safeParse(options ?? {});
        if (!result.success) {
            throw createError(errorCodes.INVALID_API_INPUT, `Invalid parse options: ${result.error.issues[0].message}`, TypeError);
        }
        const source = result.data.source || '<input>';
        const entries = [];
        let transaction = null;
        let commodity = null;
        let lineNumber = lineOffset || 0;
        let start = 0;
        for (let end = 0; end <= sourceText.length; end++) {
            if (end < sourceText.length && sourceText.charCodeAt(end) !== 10)
                continue;
            lineNumber++;
            let raw = sourceText.slice(start, end);
            if (raw.charCodeAt(raw.length - 1) === 13)
                raw = raw.slice(0, -1);
            start = end + 1;
            let first = 0;
            while (isWhitespace(raw.charCodeAt(first)))
                first++;
            const trimmed = raw.slice(first);
            if (!trimmed) {
                transaction = null;
                commodity = null;
                continue;
            }
            const marker = trimmed[0];
            if (marker === ';') {
                if (first === 0) {
                    transaction = null;
                    commodity = null;
                    entries.push({
                        type: 'comment', text: trimmed.slice(1).trim(),
                        location: sourceLocation(source, lineNumber, 1),
                    });
                    continue;
                }
                if (transaction && first > 0) {
                    const owner = transaction.postings.at(-1) || transaction;
                    const commentText = trimmed.slice(1).trim();
                    const parsedComment = parseComment(commentText, source, lineNumber, first + 1);
                    if (parsedComment.comment)
                        owner.comments.push(parsedComment.comment);
                    if (parsedComment.tags.length > 0) {
                        owner.tags = [...(owner.tags || []), ...parsedComment.tags];
                    }
                }
                if (transaction)
                    continue;
            }
            if (first > 0) {
                if (transaction)
                    transaction.postings.push(parsePosting(raw, source, lineNumber));
                else if (commodity) {
                    const property = splitComment(trimmed);
                    const separator = property.text.search(/[ \t]/);
                    const name = separator < 0 ? property.text : property.text.slice(0, separator);
                    if (!COMMODITY_PROPERTY_NAMES.has(name)) {
                        throw syntaxError(`Unsupported commodity property ${JSON.stringify(name)}`, source, lineNumber, first + 1);
                    }
                    const value = separator < 0 ? null : property.text.slice(separator).trim();
                    if (name === 'format')
                        assertCommodityFormat(value, commodity.symbol, source, lineNumber, first + 1);
                    if (name === 'default' && value !== null) {
                        throw syntaxError('Default commodity property does not accept a value', source, lineNumber, first + 1);
                    }
                    commodity.properties.push({ name, value, comment: property.comment, location: sourceLocation(source, lineNumber, first + 1) });
                }
                else
                    throw syntaxError('Unexpected indented line', source, lineNumber, first + 1);
                continue;
            }
            transaction = null;
            commodity = null;
            if (isDateAt(trimmed, 0)) {
                transaction = parseTransactionHeader(trimmed, source, lineNumber);
                entries.push(transaction);
            }
            else if (trimmed.startsWith('include') && isWhitespace(trimmed.charCodeAt(7))) {
                const { name, ...include } = parseNamedDirective(trimmed, 'include', 'include', source, lineNumber);
                entries.push({ ...include, path: name });
            }
            else if (trimmed.startsWith('account') && isWhitespace(trimmed.charCodeAt(7))) {
                const account = parseNamedDirective(trimmed, 'account', 'account', source, lineNumber);
                assertAccountName(account.name, source, lineNumber, 9);
                entries.push(account);
            }
            else if (trimmed.startsWith('tag') && isWhitespace(trimmed.charCodeAt(3)))
                entries.push(parseNamedDirective(trimmed, 'tag', 'tag', source, lineNumber));
            else if (trimmed.startsWith('commodity') && isWhitespace(trimmed.charCodeAt(9))) {
                const { name, ...directive } = parseNamedDirective(trimmed, 'commodity', 'commodity', source, lineNumber);
                commodity = { ...directive, symbol: assertCommoditySymbol(name, source, lineNumber, 11), properties: [] };
                entries.push(commodity);
            }
            else if (marker === 'P' && isWhitespace(trimmed.charCodeAt(1)))
                entries.push(parsePrice(trimmed, source, lineNumber));
            else {
                const keyword = trimmed.split(/[ \t]/, 1)[0];
                throw syntaxError(`Unsupported directive or transaction header ${JSON.stringify(keyword)}`, source, lineNumber, 1);
            }
        }
        for (const entry of entries) {
            if (entry.type === 'transaction' && entry.postings.length === 0) {
                throw syntaxError('Transaction has no postings', source, entry.location.line, 1);
            }
        }
        return { source, entries };
    }
    function parse(sourceText, options) {
        const result = optionsSchema.safeParse(options ?? {});
        if (!result.success) {
            throw createError(errorCodes.INVALID_API_INPUT, `Invalid parse options: ${result.error.issues[0].message}`, TypeError);
        }
        const source = result.data.source || '<input>';
        const entries = [];
        const warnings = [];
        for (const block of splitTopLevelBlocks(sourceText)) {
            try {
                entries.push(...parseStrict(block.sourceText, { source }, block.startLine - 1).entries);
            }
            catch (error) {
                if (error.code !== errorCodes.SYNTAX)
                    throw error;
                warnings.push(createWarning(warningCodes.SYNTAX_ERROR, error.detail || error.message, {
                    source,
                    line: error.line,
                    column: error.column,
                    startLine: block.startLine,
                    endLine: block.endLine,
                }));
            }
        }
        return {
            source,
            entries,
            ...(warnings.length > 0 ? { warnings } : {}),
        };
    }
    return { parse, parseStrict, $$private: { parseStrict } };
};