UNPKG

llmxml

Version:

Convert between markdown and LLM-friendly pseudo-XML

1,472 lines (1,457 loc) 326 kB
import { unified } from 'unified'; import remarkParse from 'remark-parse'; import winston from 'winston'; import { EventEmitter } from 'events'; import { readFileSync } from 'fs'; import { dirname, join } from 'path'; import { fileURLToPath } from 'url'; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. __defProp(target, "default", { value: mod, enumerable: true }) , mod )); // node_modules/peggy/lib/grammar-error.js var require_grammar_error = __commonJS({ "node_modules/peggy/lib/grammar-error.js"(exports2, module2) { var setProtoOf = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d, b) { d.__proto__ = b; } || function(d, b) { for (const p in b) { if (Object.prototype.hasOwnProperty.call(b, p)) { d[p] = b[p]; } } }; var GrammarError = class _GrammarError extends Error { constructor(message, location, diagnostics) { super(message); setProtoOf(this, _GrammarError.prototype); this.name = "GrammarError"; this.location = location; if (diagnostics === void 0) { diagnostics = []; } this.diagnostics = diagnostics; this.stage = null; this.problems = [["error", message, location, diagnostics]]; } toString() { let str = super.toString(); if (this.location) { str += "\n at "; if (this.location.source !== void 0 && this.location.source !== null) { str += `${this.location.source}:`; } str += `${this.location.start.line}:${this.location.start.column}`; } for (const diag of this.diagnostics) { str += "\n from "; if (diag.location.source !== void 0 && diag.location.source !== null) { str += `${diag.location.source}:`; } str += `${diag.location.start.line}:${diag.location.start.column}: ${diag.message}`; } return str; } /** * Format the error with associated sources. The `location.source` should have * a `toString()` representation in order the result to look nice. If source * is `null` or `undefined`, it is skipped from the output * * Sample output: * ``` * Error: Label "head" is already defined * --> examples/arithmetics.pegjs:15:17 * | * 15 | = head:Factor head:(_ ("*" / "/") _ Factor)* { * | ^^^^ * note: Original label location * --> examples/arithmetics.pegjs:15:5 * | * 15 | = head:Factor head:(_ ("*" / "/") _ Factor)* { * | ^^^^ * ``` * * @param {import("./peg").SourceText[]} sources mapping from location source to source text * * @returns {string} the formatted error */ format(sources) { const srcLines = sources.map(({ source, text }) => ({ source, text: text.split(/\r\n|\n|\r/g) })); function entry(location, indent, message = "") { let str = ""; const src = srcLines.find(({ source }) => source === location.source); const s = location.start; if (src) { const e = location.end; const line = src.text[s.line - 1]; const last = s.line === e.line ? e.column : line.length + 1; const hatLen = last - s.column || 1; if (message) { str += ` note: ${message}`; } str += ` --> ${location.source}:${s.line}:${s.column} ${"".padEnd(indent)} | ${s.line.toString().padStart(indent)} | ${line} ${"".padEnd(indent)} | ${"".padEnd(s.column - 1)}${"".padEnd(hatLen, "^")}`; } else { str += ` at ${location.source}:${s.line}:${s.column}`; if (message) { str += `: ${message}`; } } return str; } function formatProblem(severity, message, location, diagnostics = []) { let maxLine; if (location) { maxLine = diagnostics.reduce( (t, { location: location2 }) => Math.max(t, location2.start.line), location.start.line ); } else { maxLine = Math.max.apply( null, diagnostics.map((d) => d.location.start.line) ); } maxLine = maxLine.toString().length; let str = `${severity}: ${message}`; if (location) { str += entry(location, maxLine); } for (const diag of diagnostics) { str += entry(diag.location, maxLine, diag.message); } return str; } return this.problems.filter((p) => p[0] !== "info").map((p) => formatProblem(...p)).join("\n\n"); } }; module2.exports = GrammarError; } }); // node_modules/peggy/lib/compiler/visitor.js var require_visitor = __commonJS({ "node_modules/peggy/lib/compiler/visitor.js"(exports2, module2) { var visitor2 = { build(functions) { function visit2(node, ...args) { return functions[node.type](node, ...args); } function visitNop() { } function visitExpression(node, ...args) { return visit2(node.expression, ...args); } function visitChildren(property) { return function(node, ...args) { node[property].forEach((child) => visit2(child, ...args)); }; } const DEFAULT_FUNCTIONS = { grammar(node, ...args) { if (node.topLevelInitializer) { visit2(node.topLevelInitializer, ...args); } if (node.initializer) { visit2(node.initializer, ...args); } node.rules.forEach((rule) => visit2(rule, ...args)); }, top_level_initializer: visitNop, initializer: visitNop, rule: visitExpression, named: visitExpression, choice: visitChildren("alternatives"), action: visitExpression, sequence: visitChildren("elements"), labeled: visitExpression, text: visitExpression, simple_and: visitExpression, simple_not: visitExpression, optional: visitExpression, zero_or_more: visitExpression, one_or_more: visitExpression, group: visitExpression, semantic_and: visitNop, semantic_not: visitNop, rule_ref: visitNop, literal: visitNop, class: visitNop, any: visitNop }; Object.keys(DEFAULT_FUNCTIONS).forEach((type) => { if (!Object.prototype.hasOwnProperty.call(functions, type)) { functions[type] = DEFAULT_FUNCTIONS[type]; } }); return visit2; } }; module2.exports = visitor2; } }); // node_modules/peggy/lib/compiler/asts.js var require_asts = __commonJS({ "node_modules/peggy/lib/compiler/asts.js"(exports2, module2) { var visitor2 = require_visitor(); var asts = { findRule(ast2, name) { for (let i = 0; i < ast2.rules.length; i++) { if (ast2.rules[i].name === name) { return ast2.rules[i]; } } return void 0; }, indexOfRule(ast2, name) { for (let i = 0; i < ast2.rules.length; i++) { if (ast2.rules[i].name === name) { return i; } } return -1; }, alwaysConsumesOnSuccess(ast2, node) { function consumesTrue() { return true; } function consumesFalse() { return false; } const consumes = visitor2.build({ choice(node2) { return node2.alternatives.every(consumes); }, sequence(node2) { return node2.elements.some(consumes); }, simple_and: consumesFalse, simple_not: consumesFalse, optional: consumesFalse, zero_or_more: consumesFalse, semantic_and: consumesFalse, semantic_not: consumesFalse, rule_ref(node2) { const rule = asts.findRule(ast2, node2.name); return rule ? consumes(rule) : void 0; }, literal(node2) { return node2.value !== ""; }, class: consumesTrue, any: consumesTrue }); return consumes(node); } }; module2.exports = asts; } }); // node_modules/peggy/lib/compiler/opcodes.js var require_opcodes = __commonJS({ "node_modules/peggy/lib/compiler/opcodes.js"(exports2, module2) { var opcodes = { // Stack Manipulation /** @deprecated Unused */ PUSH: 0, // PUSH c PUSH_EMPTY_STRING: 35, // PUSH_EMPTY_STRING PUSH_UNDEFINED: 1, // PUSH_UNDEFINED PUSH_NULL: 2, // PUSH_NULL PUSH_FAILED: 3, // PUSH_FAILED PUSH_EMPTY_ARRAY: 4, // PUSH_EMPTY_ARRAY PUSH_CURR_POS: 5, // PUSH_CURR_POS POP: 6, // POP POP_CURR_POS: 7, // POP_CURR_POS POP_N: 8, // POP_N n NIP: 9, // NIP APPEND: 10, // APPEND WRAP: 11, // WRAP n TEXT: 12, // TEXT PLUCK: 36, // PLUCK n, k, p1, ..., pK // Conditions and Loops IF: 13, // IF t, f IF_ERROR: 14, // IF_ERROR t, f IF_NOT_ERROR: 15, // IF_NOT_ERROR t, f WHILE_NOT_ERROR: 16, // WHILE_NOT_ERROR b // Matching MATCH_ANY: 17, // MATCH_ANY a, f, ... MATCH_STRING: 18, // MATCH_STRING s, a, f, ... MATCH_STRING_IC: 19, // MATCH_STRING_IC s, a, f, ... MATCH_CHAR_CLASS: 20, // MATCH_CHAR_CLASS c, a, f, ... /** @deprecated Replaced with `MATCH_CHAR_CLASS` */ MATCH_REGEXP: 20, // MATCH_REGEXP r, a, f, ... ACCEPT_N: 21, // ACCEPT_N n ACCEPT_STRING: 22, // ACCEPT_STRING s FAIL: 23, // FAIL e // Calls LOAD_SAVED_POS: 24, // LOAD_SAVED_POS p UPDATE_SAVED_POS: 25, // UPDATE_SAVED_POS CALL: 26, // CALL f, n, pc, p1, p2, ..., pN // Rules RULE: 27, // RULE r // Failure Reporting SILENT_FAILS_ON: 28, // SILENT_FAILS_ON SILENT_FAILS_OFF: 29 // SILENT_FAILS_OFF // Because the tests have hard-coded opcode numbers, don't renumber // existing opcodes. New opcodes that have been put in the correct // sections above are repeated here in order to ensure we don't // reuse them. // // 30-34 reserved for @mingun // PUSH_EMPTY_STRING: 35 // PLUCK: 36 }; module2.exports = opcodes; } }); // node_modules/peggy/lib/compiler/passes/inference-match-result.js var require_inference_match_result = __commonJS({ "node_modules/peggy/lib/compiler/passes/inference-match-result.js"(exports2, module2) { var visitor2 = require_visitor(); var asts = require_asts(); var GrammarError = require_grammar_error(); var ALWAYS_MATCH = 1; var SOMETIMES_MATCH = 0; var NEVER_MATCH = -1; function inferenceMatchResult2(ast2) { function sometimesMatch(node) { return node.match = SOMETIMES_MATCH; } function alwaysMatch(node) { inference(node.expression); return node.match = ALWAYS_MATCH; } function inferenceExpression(node) { return node.match = inference(node.expression); } function inferenceElements(elements, forChoice) { const length = elements.length; let always = 0; let never = 0; for (let i = 0; i < length; ++i) { const result = inference(elements[i]); if (result === ALWAYS_MATCH) { ++always; } if (result === NEVER_MATCH) { ++never; } } if (always === length) { return ALWAYS_MATCH; } if (forChoice) { return never === length ? NEVER_MATCH : SOMETIMES_MATCH; } return never > 0 ? NEVER_MATCH : SOMETIMES_MATCH; } const inference = visitor2.build({ rule(node) { let oldResult; let count = 0; if (typeof node.match === "undefined") { node.match = SOMETIMES_MATCH; do { oldResult = node.match; node.match = inference(node.expression); if (++count > 6) { throw new GrammarError( "Infinity cycle detected when trying to evaluate node match result", node.location ); } } while (oldResult !== node.match); } return node.match; }, named: inferenceExpression, choice(node) { return node.match = inferenceElements(node.alternatives, true); }, action: inferenceExpression, sequence(node) { return node.match = inferenceElements(node.elements, false); }, labeled: inferenceExpression, text: inferenceExpression, simple_and: inferenceExpression, simple_not(node) { return node.match = -inference(node.expression); }, optional: alwaysMatch, zero_or_more: alwaysMatch, one_or_more: inferenceExpression, group: inferenceExpression, semantic_and: sometimesMatch, semantic_not: sometimesMatch, rule_ref(node) { const rule = asts.findRule(ast2, node.name); return node.match = inference(rule); }, literal(node) { const match = node.value.length === 0 ? ALWAYS_MATCH : SOMETIMES_MATCH; return node.match = match; }, class(node) { const match = node.parts.length === 0 ? NEVER_MATCH : SOMETIMES_MATCH; return node.match = match; }, // |any| not match on empty input any: sometimesMatch }); inference(ast2); } inferenceMatchResult2.ALWAYS_MATCH = ALWAYS_MATCH; inferenceMatchResult2.SOMETIMES_MATCH = SOMETIMES_MATCH; inferenceMatchResult2.NEVER_MATCH = NEVER_MATCH; module2.exports = inferenceMatchResult2; } }); // node_modules/peggy/lib/compiler/passes/generate-bytecode.js var require_generate_bytecode = __commonJS({ "node_modules/peggy/lib/compiler/passes/generate-bytecode.js"(exports2, module2) { var asts = require_asts(); var op = require_opcodes(); var visitor2 = require_visitor(); var { ALWAYS_MATCH, SOMETIMES_MATCH, NEVER_MATCH } = require_inference_match_result(); function generateBytecode2(ast2) { const literals = []; const classes = []; const expectations = []; const functions = []; function addLiteralConst(value) { const index = literals.indexOf(value); return index === -1 ? literals.push(value) - 1 : index; } function addClassConst(node) { const cls = { value: node.parts, inverted: node.inverted, ignoreCase: node.ignoreCase }; const pattern = JSON.stringify(cls); const index = classes.findIndex((c) => JSON.stringify(c) === pattern); return index === -1 ? classes.push(cls) - 1 : index; } function addExpectedConst(expected) { const pattern = JSON.stringify(expected); const index = expectations.findIndex((e) => JSON.stringify(e) === pattern); return index === -1 ? expectations.push(expected) - 1 : index; } function addFunctionConst(predicate, params, node) { const func = { predicate, params, body: node.code, location: node.codeLocation }; const pattern = JSON.stringify(func); const index = functions.findIndex((f) => JSON.stringify(f) === pattern); return index === -1 ? functions.push(func) - 1 : index; } function cloneEnv(env) { const clone = {}; Object.keys(env).forEach((name) => { clone[name] = env[name]; }); return clone; } function buildSequence(first, ...args) { return first.concat(...args); } function buildCondition(match, condCode, thenCode, elseCode) { if (match === ALWAYS_MATCH) { return thenCode; } if (match === NEVER_MATCH) { return elseCode; } return condCode.concat( [thenCode.length, elseCode.length], thenCode, elseCode ); } function buildLoop(condCode, bodyCode) { return condCode.concat([bodyCode.length], bodyCode); } function buildCall(functionIndex, delta, env, sp) { const params = Object.keys(env).map((name) => sp - env[name]); return [op.CALL, functionIndex, delta, params.length].concat(params); } function buildSimplePredicate(expression, negative, context) { const match = expression.match | 0; return buildSequence( [op.PUSH_CURR_POS], [op.SILENT_FAILS_ON], generate(expression, { sp: context.sp + 1, env: cloneEnv(context.env), action: null }), [op.SILENT_FAILS_OFF], buildCondition( negative ? -match : match, [negative ? op.IF_ERROR : op.IF_NOT_ERROR], buildSequence( [op.POP], [negative ? op.POP : op.POP_CURR_POS], [op.PUSH_UNDEFINED] ), buildSequence( [op.POP], [negative ? op.POP_CURR_POS : op.POP], [op.PUSH_FAILED] ) ) ); } function buildSemanticPredicate(node, negative, context) { const functionIndex = addFunctionConst( true, Object.keys(context.env), node ); return buildSequence( [op.UPDATE_SAVED_POS], buildCall(functionIndex, 0, context.env, context.sp), buildCondition( node.match | 0, [op.IF], buildSequence( [op.POP], negative ? [op.PUSH_FAILED] : [op.PUSH_UNDEFINED] ), buildSequence( [op.POP], negative ? [op.PUSH_UNDEFINED] : [op.PUSH_FAILED] ) ) ); } function buildAppendLoop(expressionCode) { return buildLoop( [op.WHILE_NOT_ERROR], buildSequence([op.APPEND], expressionCode) ); } const generate = visitor2.build({ grammar(node) { node.rules.forEach(generate); node.literals = literals; node.classes = classes; node.expectations = expectations; node.functions = functions; }, rule(node) { node.bytecode = generate(node.expression, { sp: -1, // Stack pointer env: {}, // Mapping of label names to stack positions pluck: [], // Fields that have been picked action: null // Action nodes pass themselves to children here }); }, named(node, context) { const match = node.match | 0; const nameIndex = match === NEVER_MATCH ? null : addExpectedConst({ type: "rule", value: node.name }); return buildSequence( [op.SILENT_FAILS_ON], generate(node.expression, context), [op.SILENT_FAILS_OFF], buildCondition(match, [op.IF_ERROR], [op.FAIL, nameIndex], []) ); }, choice(node, context) { function buildAlternativesCode(alternatives, context2) { const match = alternatives[0].match | 0; const first = generate(alternatives[0], { sp: context2.sp, env: cloneEnv(context2.env), action: null }); if (match === ALWAYS_MATCH) { return first; } return buildSequence( first, alternatives.length > 1 ? buildCondition( SOMETIMES_MATCH, [op.IF_ERROR], buildSequence( [op.POP], buildAlternativesCode(alternatives.slice(1), context2) ), [] ) : [] ); } return buildAlternativesCode(node.alternatives, context); }, action(node, context) { const env = cloneEnv(context.env); const emitCall = node.expression.type !== "sequence" || node.expression.elements.length === 0; const expressionCode = generate(node.expression, { sp: context.sp + (emitCall ? 1 : 0), env, action: node }); const match = node.expression.match | 0; const functionIndex = emitCall && match !== NEVER_MATCH ? addFunctionConst(false, Object.keys(env), node) : null; return emitCall ? buildSequence( [op.PUSH_CURR_POS], expressionCode, buildCondition( match, [op.IF_NOT_ERROR], buildSequence( [op.LOAD_SAVED_POS, 1], buildCall(functionIndex, 1, env, context.sp + 2) ), [] ), [op.NIP] ) : expressionCode; }, sequence(node, context) { function buildElementsCode(elements, context2) { if (elements.length > 0) { const processedCount = node.elements.length - elements.length + 1; return buildSequence( generate(elements[0], { sp: context2.sp, env: context2.env, pluck: context2.pluck, action: null }), buildCondition( elements[0].match | 0, [op.IF_NOT_ERROR], buildElementsCode(elements.slice(1), { sp: context2.sp + 1, env: context2.env, pluck: context2.pluck, action: context2.action }), buildSequence( processedCount > 1 ? [op.POP_N, processedCount] : [op.POP], [op.POP_CURR_POS], [op.PUSH_FAILED] ) ) ); } else { if (context2.pluck.length > 0) { return buildSequence( [op.PLUCK, node.elements.length + 1, context2.pluck.length], context2.pluck.map((eSP) => context2.sp - eSP) ); } if (context2.action) { const functionIndex = addFunctionConst( false, Object.keys(context2.env), context2.action ); return buildSequence( [op.LOAD_SAVED_POS, node.elements.length], buildCall( functionIndex, node.elements.length + 1, context2.env, context2.sp ) ); } else { return buildSequence([op.WRAP, node.elements.length], [op.NIP]); } } } return buildSequence( [op.PUSH_CURR_POS], buildElementsCode(node.elements, { sp: context.sp + 1, env: context.env, pluck: [], action: context.action }) ); }, labeled(node, context) { let env = context.env; const label = node.label; const sp = context.sp + 1; if (label) { env = cloneEnv(context.env); context.env[node.label] = sp; } if (node.pick) { context.pluck.push(sp); } return generate(node.expression, { sp: context.sp, env, action: null }); }, text(node, context) { return buildSequence( [op.PUSH_CURR_POS], generate(node.expression, { sp: context.sp + 1, env: cloneEnv(context.env), action: null }), buildCondition( node.match | 0, [op.IF_NOT_ERROR], buildSequence([op.POP], [op.TEXT]), [op.NIP] ) ); }, simple_and(node, context) { return buildSimplePredicate(node.expression, false, context); }, simple_not(node, context) { return buildSimplePredicate(node.expression, true, context); }, optional(node, context) { return buildSequence( generate(node.expression, { sp: context.sp, env: cloneEnv(context.env), action: null }), buildCondition( // Check expression match, not the node match // If expression always match, no need to replace FAILED to NULL, // because FAILED will never appeared -(node.expression.match | 0), [op.IF_ERROR], buildSequence([op.POP], [op.PUSH_NULL]), [] ) ); }, zero_or_more(node, context) { const expressionCode = generate(node.expression, { sp: context.sp + 1, env: cloneEnv(context.env), action: null }); return buildSequence( [op.PUSH_EMPTY_ARRAY], expressionCode, buildAppendLoop(expressionCode), [op.POP] ); }, one_or_more(node, context) { const expressionCode = generate(node.expression, { sp: context.sp + 1, env: cloneEnv(context.env), action: null }); return buildSequence( [op.PUSH_EMPTY_ARRAY], expressionCode, buildCondition( // Condition depends on the expression match, not the node match node.expression.match | 0, [op.IF_NOT_ERROR], buildSequence(buildAppendLoop(expressionCode), [op.POP]), buildSequence([op.POP], [op.POP], [op.PUSH_FAILED]) ) ); }, group(node, context) { return generate(node.expression, { sp: context.sp, env: cloneEnv(context.env), action: null }); }, semantic_and(node, context) { return buildSemanticPredicate(node, false, context); }, semantic_not(node, context) { return buildSemanticPredicate(node, true, context); }, rule_ref(node) { return [op.RULE, asts.indexOfRule(ast2, node.name)]; }, literal(node) { if (node.value.length > 0) { const match = node.match | 0; const needConst = match === SOMETIMES_MATCH || match === ALWAYS_MATCH && !node.ignoreCase; const stringIndex = needConst ? addLiteralConst( node.ignoreCase ? node.value.toLowerCase() : node.value ) : null; const expectedIndex = match !== ALWAYS_MATCH ? addExpectedConst({ type: "literal", value: node.value, ignoreCase: node.ignoreCase }) : null; return buildCondition( match, node.ignoreCase ? [op.MATCH_STRING_IC, stringIndex] : [op.MATCH_STRING, stringIndex], node.ignoreCase ? [op.ACCEPT_N, node.value.length] : [op.ACCEPT_STRING, stringIndex], [op.FAIL, expectedIndex] ); } return [op.PUSH_EMPTY_STRING]; }, class(node) { const match = node.match | 0; const classIndex = match === SOMETIMES_MATCH ? addClassConst(node) : null; const expectedIndex = match !== ALWAYS_MATCH ? addExpectedConst({ type: "class", value: node.parts, inverted: node.inverted, ignoreCase: node.ignoreCase }) : null; return buildCondition( match, [op.MATCH_CHAR_CLASS, classIndex], [op.ACCEPT_N, 1], [op.FAIL, expectedIndex] ); }, any(node) { const match = node.match | 0; const expectedIndex = match !== ALWAYS_MATCH ? addExpectedConst({ type: "any" }) : null; return buildCondition( match, [op.MATCH_ANY], [op.ACCEPT_N, 1], [op.FAIL, expectedIndex] ); } }); generate(ast2); } module2.exports = generateBytecode2; } }); // node_modules/peggy/lib/compiler/stack.js var require_stack = __commonJS({ "node_modules/peggy/lib/compiler/stack.js"(exports2, module2) { var Stack = class { /** * Constructs the helper for tracking variable slots of the stack virtual machine * * @param {string} ruleName The name of rule that will be used in error messages * @param {string} varName The prefix for generated names of variables * @param {string} type The type of the variables. For JavaScript there are `var` or `let` */ constructor(ruleName, varName, type) { this.sp = -1; this.maxSp = -1; this.varName = varName; this.ruleName = ruleName; this.type = type; } /** * Returns name of the variable at the index `i`. * * @param {number} i Index for which name must be generated * @return {string} Generated name * * @throws {RangeError} If `i < 0`, which means a stack underflow (there are more `pop`s than `push`es) */ name(i) { if (i < 0) { throw new RangeError( `Rule '${this.ruleName}': The variable stack underflow: attempt to use a variable '${this.varName}<x>' at an index ${i}` ); } return this.varName + i; } /** * Assigns `exprCode` to the new variable in the stack, returns generated code. * As the result, the size of a stack increases on 1. * * @param {string} exprCode Any expression code that must be assigned to the new variable in the stack * @return {string} Assignment code */ push(exprCode) { const code = this.name(++this.sp) + " = " + exprCode + ";"; if (this.sp > this.maxSp) { this.maxSp = this.sp; } return code; } /** * Returns name or `n` names of the variable(s) from the top of the stack. * * @param {number} [n=1] Quantity of variables, which need to be removed from the stack * @return {string|string[]} Generated name(s). If `n > 1` than array has length of `n` * * @throws {RangeError} If the stack underflow (there are more `pop`s than `push`es) */ pop(n) { if (n !== void 0) { this.sp -= n; return Array.from({ length: n }, (v, i) => this.name(this.sp + 1 + i)); } return this.name(this.sp--); } /** * Returns name of the first free variable. The same as `index(0)`. * * @return {string} Generated name * * @throws {RangeError} If the stack is empty (there was no `push`'s yet) */ top() { return this.name(this.sp); } /** * Returns name of the variable at index `i`. * * @param {number} [i] Index of the variable from top of the stack * @return {string} Generated name * * @throws {RangeError} If `i < 0` or more than the stack size */ index(i) { if (i < 0) { throw new RangeError( `Rule '${this.ruleName}': The variable stack overflow: attempt to get a variable at a negative index ${i}` ); } return this.name(this.sp - i); } /** * Returns variable name that contains result (bottom of the stack). * * @return {string} Generated name * * @throws {RangeError} If the stack is empty (there was no `push`es yet) */ result() { if (this.maxSp < 0) { throw new RangeError( `Rule '${this.ruleName}': The variable stack is empty, can't get the result'` ); } return this.name(0); } /** * Returns defines of all used variables. * * @return {string} Generated define variable expression with the type `this.type`. * If the stack is empty, returns empty string */ defines() { if (this.maxSp < 0) { return ""; } return this.type + " " + Array.from({ length: this.maxSp + 1 }, (v, i) => this.name(i)).join(", ") + ";"; } /** * Checks that code in the `generateIf` and `generateElse` move the stack pointer in the same way. * * @param {number} pos Opcode number for error messages * @param {function()} generateIf First function that works with this stack * @param {function()} [generateElse] Second function that works with this stack * @return {undefined} * * @throws {Error} If `generateElse` is defined and the stack pointer moved differently in the * `generateIf` and `generateElse` */ checkedIf(pos, generateIf, generateElse) { const baseSp = this.sp; generateIf(); if (generateElse) { const thenSp = this.sp; this.sp = baseSp; generateElse(); if (thenSp !== this.sp) { throw new Error( "Rule '" + this.ruleName + "', position " + pos + ": Branches of a condition can't move the stack pointer differently (before: " + baseSp + ", after then: " + thenSp + ", after else: " + this.sp + ")." ); } } } /** * Checks that code in the `generateBody` do not move stack pointer. * * @param {number} pos Opcode number for error messages * @param {function()} generateBody Function that works with this stack * @return {undefined} * * @throws {Error} If `generateBody` move the stack pointer (if it contains unbalanced `push`es and `pop`s) */ checkedLoop(pos, generateBody) { const baseSp = this.sp; generateBody(); if (baseSp !== this.sp) { throw new Error( "Rule '" + this.ruleName + "', position " + pos + ": Body of a loop can't move the stack pointer (before: " + baseSp + ", after: " + this.sp + ")." ); } } }; module2.exports = Stack; } }); // node_modules/peggy/lib/version.js var require_version = __commonJS({ "node_modules/peggy/lib/version.js"(exports2, module2) { module2.exports = "2.0.1"; } }); // node_modules/peggy/lib/compiler/utils.js var require_utils = __commonJS({ "node_modules/peggy/lib/compiler/utils.js"(exports2) { function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } exports2.hex = hex; function stringEscape(s) { return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\0/g, "\\0").replace(/\x08/g, "\\b").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\v/g, "\\v").replace(/\f/g, "\\f").replace(/\r/g, "\\r").replace(/[\x00-\x0F]/g, (ch) => "\\x0" + hex(ch)).replace(/[\x10-\x1F\x7F-\xFF]/g, (ch) => "\\x" + hex(ch)).replace(/[\u0100-\u0FFF]/g, (ch) => "\\u0" + hex(ch)).replace(/[\u1000-\uFFFF]/g, (ch) => "\\u" + hex(ch)); } exports2.stringEscape = stringEscape; function regexpClassEscape(s) { return s.replace(/\\/g, "\\\\").replace(/\//g, "\\/").replace(/]/g, "\\]").replace(/\^/g, "\\^").replace(/-/g, "\\-").replace(/\0/g, "\\0").replace(/\x08/g, "\\b").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\v/g, "\\v").replace(/\f/g, "\\f").replace(/\r/g, "\\r").replace(/[\x00-\x0F]/g, (ch) => "\\x0" + hex(ch)).replace(/[\x10-\x1F\x7F-\xFF]/g, (ch) => "\\x" + hex(ch)).replace(/[\u0100-\u0FFF]/g, (ch) => "\\u0" + hex(ch)).replace(/[\u1000-\uFFFF]/g, (ch) => "\\u" + hex(ch)); } exports2.regexpClassEscape = regexpClassEscape; } }); // node_modules/source-map-generator/lib/base64.js var require_base64 = __commonJS({ "node_modules/source-map-generator/lib/base64.js"(exports2) { var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split( "" ); exports2.encode = function(number) { if (0 <= number && number < intToCharMap.length) { return intToCharMap[number]; } throw new TypeError("Must be between 0 and 63: " + number); }; } }); // node_modules/source-map-generator/lib/base64-vlq.js var require_base64_vlq = __commonJS({ "node_modules/source-map-generator/lib/base64-vlq.js"(exports2) { var base64 = require_base64(); var VLQ_BASE_SHIFT = 5; var VLQ_BASE = 1 << VLQ_BASE_SHIFT; var VLQ_BASE_MASK = VLQ_BASE - 1; var VLQ_CONTINUATION_BIT = VLQ_BASE; function toVLQSigned(aValue) { return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0; } exports2.encode = function base64VLQ_encode(aValue) { let encoded = ""; let digit; let vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; } }); // node_modules/source-map-generator/lib/util.js var require_util = __commonJS({ "node_modules/source-map-generator/lib/util.js"(exports2) { function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } throw new Error('"' + aName + '" is a required argument.'); } exports2.getArg = getArg; var supportsNullProto = function() { const obj = /* @__PURE__ */ Object.create(null); return !("__proto__" in obj); }(); function identity(s) { return s; } function toSetString(aStr) { if (isProtoString(aStr)) { return "$" + aStr; } return aStr; } exports2.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports2.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s) { if (!s) { return false; } const length = s.length; if (length < 9) { return false; } if (s.charCodeAt(length - 1) !== 95 || s.charCodeAt(length - 2) !== 95 || s.charCodeAt(length - 3) !== 111 || s.charCodeAt(length - 4) !== 116 || s.charCodeAt(length - 5) !== 111 || s.charCodeAt(length - 6) !== 114 || s.charCodeAt(length - 7) !== 112 || s.charCodeAt(length - 8) !== 95 || s.charCodeAt(length - 9) !== 95) { return false; } for (let i = length - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 36) { return false; } } return true; } function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 === null) { return 1; } if (aStr2 === null) { return -1; } if (aStr1 > aStr2) { return 1; } return -1; } function compareByGeneratedPositionsInflated(mappingA, mappingB) { let cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports2.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; var PROTOCOL = "http:"; var PROTOCOL_AND_HOST = `${PROTOCOL}//host`; function createSafeHandler(cb) { return (input) => { const type = getURLType(input); const base = buildSafeBase(input); const url = new URL(input, base); cb(url); const result = url.toString(); if (type === "absolute") { return result; } else if (type === "scheme-relative") { return result.slice(PROTOCOL.length); } else if (type === "path-absolute") { return result.slice(PROTOCOL_AND_HOST.length); } return computeRelativeURL(base, result); }; } function withBase(url, base) { return new URL(url, base).toString(); } function buildUniqueSegment(prefix, str) { let id = 0; do { const ident = prefix + id++; if (str.indexOf(ident) === -1) return ident; } while (true); } function buildSafeBase(str) { const maxDotParts = str.split("..").length - 1; const segment = buildUniqueSegment("p", str); let base = `${PROTOCOL_AND_HOST}/`; for (let i = 0; i < maxDotParts; i++) { base += `${segment}/`; } return base; } var ABSOLUTE_SCHEME = /^[A-Za-z0-9\+\-\.]+:/; function getURLType(url) { if (url[0] === "/") { if (url[1] === "/") return "scheme-relative"; return "path-absolute"; } return ABSOLUTE_SCHEME.test(url) ? "absolute" : "path-relative"; } function computeRelativeURL(rootURL, targetURL) { if (typeof rootURL === "string") rootURL = new URL(rootURL); if (typeof targetURL === "string") targetURL = new URL(targetURL); const targetParts = targetURL.pathname.split("/"); const rootParts = rootURL.pathname.split("/"); if (rootParts.length > 0 && !rootParts[rootParts.length - 1]) { rootParts.pop(); } while (targetParts.length > 0 && rootParts.length > 0 && targetParts[0] === rootParts[0]) { targetParts.shift(); rootParts.shift(); } const relativePath = rootParts.map(() => "..").concat(targetParts).join("/"); return relativePath + targetURL.search + targetURL.hash; } var ensureDirectory = createSafeHandler((url) => { url.pathname = url.pathname.replace(/\/?$/, "/"); }); var normalize = createSafeHandler((url) => { }); exports2.normalize = normalize; function join2(aRoot, aPath) { const pathType = getURLType(aPath); const rootType = getURLType(aRoot); aRoot = ensureDirectory(aRoot); if (pathType === "absolute") { return withBase(aPath, void 0); } if (rootType === "absolute") { return withBase(aPath, aRoot); } if (pathType === "scheme-relative") { return normalize(aPath); } if (rootType === "scheme-relative") { return withBase(aPath, withBase(aRoot, PROTOCOL_AND_HOST)).slice( PROTOCOL.length ); } if (pathType === "path-absolute") { return normalize(aPath); } if (rootType === "path-absolute") { return withBase(aPath, withBase(aRoot, PROTOCOL_AND_HOST)).slice( PROTOCOL_AND_HOST.length ); } const base = buildSafeBase(aPath + aRoot); const newPath = withBase(aPath, withBase(aRoot, base)); return computeRelativeURL(base, newPath); } exports2.join = join2; function relative(rootURL, targetURL) { const result = relativeIfPossible(rootURL, targetURL); return typeof result === "string" ? result : normalize(targetURL); } exports2.relative = relative; function relativeIfPossible(rootURL, targetURL) { const urlType = getURLType(rootURL); if (urlType !== getURLType(targetURL)) { return null; } const base = buildSafeBase(rootURL + targetURL); const root = new URL(rootURL, base); const target = new URL(targetURL, base); try { new URL("", target.toString()); } catch (err) { return null; } if (target.protocol !== root.protocol || target.user !== root.user || target.password !== root.password || target.hostname !== root.hostname || target.port !== root.port) { return null; } return computeRelativeURL(root, target); } } }); // node_modules/source-map-generator/lib/array-set.js var require_array_set = __commonJS({ "node_modules/source-map-generator/lib/array-set.js"(exports2) { var ArraySet = class _ArraySet { constructor() { this._array = []; this._set = /* @__PURE__ */ new Map(); } /** * Static method for creating ArraySet instances from an existing array. */ static fromArray(aArray, aAllowDuplicates) { const set = new _ArraySet(); for (let i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } return set; } /** * Return how many unique items are in this ArraySet. If duplicates have been * added, than those do not count towards the size. * * @returns Number */ size() { return this._set.size; } /** * Add the given string to this set. * * @param String aStr */ add(aStr, aAllowDuplicates) { const isDuplicate = this.has(aStr); const idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { this._set.set(aStr, idx); } } /** * Is the given string a member of this set? * * @param String aStr */ has(aStr) { return this._set.has(aStr); } /** * What is the index of the given string in the array? * * @param String aStr */ indexOf(aStr) { const idx = this._set.get(aStr); if (idx >= 0) { return idx; } throw new Error('"' + aStr + '" is not in the set.'); } /** * What is the element at the given index? * * @param Number aIdx */ at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error("No element indexed by " + aIdx); } /** * Returns the array representation of this set (which has the proper indices * indicated by indexOf). Note that this is a copy of the internal array used * for storing the members so that no one can mess with internal state. */ toArray() { return this._array.slice(); } }; exports2.ArraySet = ArraySet; } }); // node_modules/source-map-generator/lib/mapping-list.js var require_mapping_list = __commonJS({ "node_modules/source-map-generator/lib/mapping-list.js"(exports2) { var util = require_util(); function generatedPositionAfter(mappingA, mappingB) { const lineA = mappingA.generatedLine; const lineB = mappingB.generatedLine; const columnA = mappingA.generatedColumn; const columnB = mappingB.generatedColumn; return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; } var MappingList = class { constructor() { this._array = []; this._sorted = true; this._last = { generatedLine: -1, generatedColumn: 0 }; } /** * Iterate through internal items. This method takes the same arguments that * `Array.prototype.forEach` takes. * * NOTE: The order of the mappings is NOT guaranteed. */ unsortedForEach(aCallback, aThisArg) { this._array.forEach(aCallback, aThisArg); } /** * Add the given source mapping. * * @pa