From 4c7a01150c49ceacd0f5acf6493e90e2c335bc21 Mon Sep 17 00:00:00 2001 From: Jalil Arfaoui Date: Tue, 3 Dec 2024 23:12:08 +0100 Subject: [PATCH] =?UTF-8?q?fix(documentation):=20patch=20publicodes=201.2?= =?UTF-8?q?=20pour=20r=C3=A9cup=C3=A9rer=20le=20fix=20du=20scroll=20de=20l?= =?UTF-8?q?a=20documentation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 +- package.json | 2 +- publicodes/README.md | 11 + publicodes/dist/index.cjs | 5348 +++++++++++++++++++++++++++++++++ publicodes/dist/index.cjs.map | 1 + publicodes/dist/index.d.cts | 639 ++++ publicodes/dist/index.d.ts | 639 ++++ publicodes/dist/index.js | 5326 ++++++++++++++++++++++++++++++++ publicodes/dist/index.js.map | 1 + publicodes/package.json | 58 + site/package.json | 2 +- yarn.lock | 22 +- 12 files changed, 12047 insertions(+), 5 deletions(-) create mode 100644 publicodes/README.md create mode 100644 publicodes/dist/index.cjs create mode 100644 publicodes/dist/index.cjs.map create mode 100644 publicodes/dist/index.d.cts create mode 100644 publicodes/dist/index.d.ts create mode 100644 publicodes/dist/index.js create mode 100644 publicodes/dist/index.js.map create mode 100644 publicodes/package.json diff --git a/.gitignore b/.gitignore index 88bb08782..b2a45b2a4 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ package-lock.json node_modules/ .env dist/ +!publicodes/dist/ storybook-static/ # Local Netlify folder @@ -23,4 +24,4 @@ storybook-static/ !**/.yarn/plugins !**/.yarn/releases !**/.yarn/sdks -!**/.yarn/versions \ No newline at end of file +!**/.yarn/versions diff --git a/package.json b/package.json index a17239e37..c3144c026 100644 --- a/package.json +++ b/package.json @@ -52,7 +52,7 @@ "eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-vitest": "^0.3.22", "prettier": "^3.0.3", - "publicodes": "^1.2.0", + "publicodes": "file:./publicodes", "rimraf": "^5.0.1" }, "resolutions": { diff --git a/publicodes/README.md b/publicodes/README.md new file mode 100644 index 000000000..0b061fbc6 --- /dev/null +++ b/publicodes/README.md @@ -0,0 +1,11 @@ +# `publicodes` + +The publicodes engine that interprets a set of publicodes rules. + +[Documentation](https://publi.codes/docs/api/core) + +## Installation + +```sh +npm install publicodes +``` diff --git a/publicodes/dist/index.cjs b/publicodes/dist/index.cjs new file mode 100644 index 000000000..635b5600c --- /dev/null +++ b/publicodes/dist/index.cjs @@ -0,0 +1,5348 @@ +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 __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +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. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// ../../node_modules/nearley/lib/nearley.js +var require_nearley = __commonJS({ + "../../node_modules/nearley/lib/nearley.js"(exports, module2) { + (function(root, factory) { + if (typeof module2 === "object" && module2.exports) { + module2.exports = factory(); + } else { + root.nearley = factory(); + } + })(exports, function() { + function Rule2(name, symbols, postprocess) { + this.id = ++Rule2.highestId; + this.name = name; + this.symbols = symbols; + this.postprocess = postprocess; + return this; + } + Rule2.highestId = 0; + Rule2.prototype.toString = function(withCursorAt) { + var symbolSequence = typeof withCursorAt === "undefined" ? this.symbols.map(getSymbolShortDisplay).join(" ") : this.symbols.slice(0, withCursorAt).map(getSymbolShortDisplay).join(" ") + " \u25CF " + this.symbols.slice(withCursorAt).map(getSymbolShortDisplay).join(" "); + return this.name + " \u2192 " + symbolSequence; + }; + function State(rule, dot2, reference, wantedBy) { + this.rule = rule; + this.dot = dot2; + this.reference = reference; + this.data = []; + this.wantedBy = wantedBy; + this.isComplete = this.dot === rule.symbols.length; + } + State.prototype.toString = function() { + return "{" + this.rule.toString(this.dot) + "}, from: " + (this.reference || 0); + }; + State.prototype.nextState = function(child) { + var state = new State(this.rule, this.dot + 1, this.reference, this.wantedBy); + state.left = this; + state.right = child; + if (state.isComplete) { + state.data = state.build(); + state.right = void 0; + } + return state; + }; + State.prototype.build = function() { + var children = []; + var node = this; + do { + children.push(node.right.data); + node = node.left; + } while (node.left); + children.reverse(); + return children; + }; + State.prototype.finish = function() { + if (this.rule.postprocess) { + this.data = this.rule.postprocess(this.data, this.reference, Parser2.fail); + } + }; + function Column(grammar, index) { + this.grammar = grammar; + this.index = index; + this.states = []; + this.wants = {}; + this.scannable = []; + this.completed = {}; + } + Column.prototype.process = function(nextColumn) { + var states = this.states; + var wants = this.wants; + var completed = this.completed; + for (var w = 0; w < states.length; w++) { + var state = states[w]; + if (state.isComplete) { + state.finish(); + if (state.data !== Parser2.fail) { + var wantedBy = state.wantedBy; + for (var i = wantedBy.length; i--; ) { + var left = wantedBy[i]; + this.complete(left, state); + } + if (state.reference === this.index) { + var exp = state.rule.name; + (this.completed[exp] = this.completed[exp] || []).push(state); + } + } + } else { + var exp = state.rule.symbols[state.dot]; + if (typeof exp !== "string") { + this.scannable.push(state); + continue; + } + if (wants[exp]) { + wants[exp].push(state); + if (completed.hasOwnProperty(exp)) { + var nulls = completed[exp]; + for (var i = 0; i < nulls.length; i++) { + var right = nulls[i]; + this.complete(state, right); + } + } + } else { + wants[exp] = [state]; + this.predict(exp); + } + } + } + }; + Column.prototype.predict = function(exp) { + var rules = this.grammar.byName[exp] || []; + for (var i = 0; i < rules.length; i++) { + var r = rules[i]; + var wantedBy = this.wants[exp]; + var s = new State(r, 0, this.index, wantedBy); + this.states.push(s); + } + }; + Column.prototype.complete = function(left, right) { + var copy = left.nextState(right); + this.states.push(copy); + }; + function Grammar2(rules, start) { + this.rules = rules; + this.start = start || this.rules[0].name; + var byName = this.byName = {}; + this.rules.forEach(function(rule) { + if (!byName.hasOwnProperty(rule.name)) { + byName[rule.name] = []; + } + byName[rule.name].push(rule); + }); + } + Grammar2.fromCompiled = function(rules, start) { + var lexer2 = rules.Lexer; + if (rules.ParserStart) { + start = rules.ParserStart; + rules = rules.ParserRules; + } + var rules = rules.map(function(r) { + return new Rule2(r.name, r.symbols, r.postprocess); + }); + var g = new Grammar2(rules, start); + g.lexer = lexer2; + return g; + }; + function StreamLexer() { + this.reset(""); + } + StreamLexer.prototype.reset = function(data, state) { + this.buffer = data; + this.index = 0; + this.line = state ? state.line : 1; + this.lastLineBreak = state ? -state.col : 0; + }; + StreamLexer.prototype.next = function() { + if (this.index < this.buffer.length) { + var ch = this.buffer[this.index++]; + if (ch === "\n") { + this.line += 1; + this.lastLineBreak = this.index; + } + return { value: ch }; + } + }; + StreamLexer.prototype.save = function() { + return { + line: this.line, + col: this.index - this.lastLineBreak + }; + }; + StreamLexer.prototype.formatError = function(token, message) { + var buffer = this.buffer; + if (typeof buffer === "string") { + var lines = buffer.split("\n").slice( + Math.max(0, this.line - 5), + this.line + ); + var nextLineBreak = buffer.indexOf("\n", this.index); + if (nextLineBreak === -1) + nextLineBreak = buffer.length; + var col = this.index - this.lastLineBreak; + var lastLineDigits = String(this.line).length; + message += " at line " + this.line + " col " + col + ":\n\n"; + message += lines.map(function(line, i) { + return pad2(this.line - lines.length + i + 1, lastLineDigits) + " " + line; + }, this).join("\n"); + message += "\n" + pad2("", lastLineDigits + col) + "^\n"; + return message; + } else { + return message + " at index " + (this.index - 1); + } + function pad2(n, length) { + var s = String(n); + return Array(length - s.length + 1).join(" ") + s; + } + }; + function Parser2(rules, start, options) { + if (rules instanceof Grammar2) { + var grammar = rules; + var options = start; + } else { + var grammar = Grammar2.fromCompiled(rules, start); + } + this.grammar = grammar; + this.options = { + keepHistory: false, + lexer: grammar.lexer || new StreamLexer() + }; + for (var key in options || {}) { + this.options[key] = options[key]; + } + this.lexer = this.options.lexer; + this.lexerState = void 0; + var column = new Column(grammar, 0); + var table = this.table = [column]; + column.wants[grammar.start] = []; + column.predict(grammar.start); + column.process(); + this.current = 0; + } + Parser2.fail = {}; + Parser2.prototype.feed = function(chunk) { + var lexer2 = this.lexer; + lexer2.reset(chunk, this.lexerState); + var token; + while (true) { + try { + token = lexer2.next(); + if (!token) { + break; + } + } catch (e) { + var nextColumn = new Column(this.grammar, this.current + 1); + this.table.push(nextColumn); + var err = new Error(this.reportLexerError(e)); + err.offset = this.current; + err.token = e.token; + throw err; + } + var column = this.table[this.current]; + if (!this.options.keepHistory) { + delete this.table[this.current - 1]; + } + var n = this.current + 1; + var nextColumn = new Column(this.grammar, n); + this.table.push(nextColumn); + var literal = token.text !== void 0 ? token.text : token.value; + var value = lexer2.constructor === StreamLexer ? token.value : token; + var scannable = column.scannable; + for (var w = scannable.length; w--; ) { + var state = scannable[w]; + var expect = state.rule.symbols[state.dot]; + if (expect.test ? expect.test(value) : expect.type ? expect.type === token.type : expect.literal === literal) { + var next = state.nextState({ data: value, token, isToken: true, reference: n - 1 }); + nextColumn.states.push(next); + } + } + nextColumn.process(); + if (nextColumn.states.length === 0) { + var err = new Error(this.reportError(token)); + err.offset = this.current; + err.token = token; + throw err; + } + if (this.options.keepHistory) { + column.lexerState = lexer2.save(); + } + this.current++; + } + if (column) { + this.lexerState = lexer2.save(); + } + this.results = this.finish(); + return this; + }; + Parser2.prototype.reportLexerError = function(lexerError) { + var tokenDisplay, lexerMessage; + var token = lexerError.token; + if (token) { + tokenDisplay = "input " + JSON.stringify(token.text[0]) + " (lexer error)"; + lexerMessage = this.lexer.formatError(token, "Syntax error"); + } else { + tokenDisplay = "input (lexer error)"; + lexerMessage = lexerError.message; + } + return this.reportErrorCommon(lexerMessage, tokenDisplay); + }; + Parser2.prototype.reportError = function(token) { + var tokenDisplay = (token.type ? token.type + " token: " : "") + JSON.stringify(token.value !== void 0 ? token.value : token); + var lexerMessage = this.lexer.formatError(token, "Syntax error"); + return this.reportErrorCommon(lexerMessage, tokenDisplay); + }; + Parser2.prototype.reportErrorCommon = function(lexerMessage, tokenDisplay) { + var lines = []; + lines.push(lexerMessage); + var lastColumnIndex = this.table.length - 2; + var lastColumn = this.table[lastColumnIndex]; + var expectantStates = lastColumn.states.filter(function(state) { + var nextSymbol = state.rule.symbols[state.dot]; + return nextSymbol && typeof nextSymbol !== "string"; + }); + if (expectantStates.length === 0) { + lines.push("Unexpected " + tokenDisplay + ". I did not expect any more input. Here is the state of my parse table:\n"); + this.displayStateStack(lastColumn.states, lines); + } else { + lines.push("Unexpected " + tokenDisplay + ". Instead, I was expecting to see one of the following:\n"); + var stateStacks = expectantStates.map(function(state) { + return this.buildFirstStateStack(state, []) || [state]; + }, this); + stateStacks.forEach(function(stateStack) { + var state = stateStack[0]; + var nextSymbol = state.rule.symbols[state.dot]; + var symbolDisplay = this.getSymbolDisplay(nextSymbol); + lines.push("A " + symbolDisplay + " based on:"); + this.displayStateStack(stateStack, lines); + }, this); + } + lines.push(""); + return lines.join("\n"); + }; + Parser2.prototype.displayStateStack = function(stateStack, lines) { + var lastDisplay; + var sameDisplayCount = 0; + for (var j = 0; j < stateStack.length; j++) { + var state = stateStack[j]; + var display = state.rule.toString(state.dot); + if (display === lastDisplay) { + sameDisplayCount++; + } else { + if (sameDisplayCount > 0) { + lines.push(" ^ " + sameDisplayCount + " more lines identical to this"); + } + sameDisplayCount = 0; + lines.push(" " + display); + } + lastDisplay = display; + } + }; + Parser2.prototype.getSymbolDisplay = function(symbol) { + return getSymbolLongDisplay(symbol); + }; + Parser2.prototype.buildFirstStateStack = function(state, visited) { + if (visited.indexOf(state) !== -1) { + return null; + } + if (state.wantedBy.length === 0) { + return [state]; + } + var prevState = state.wantedBy[0]; + var childVisited = [state].concat(visited); + var childResult = this.buildFirstStateStack(prevState, childVisited); + if (childResult === null) { + return null; + } + return [state].concat(childResult); + }; + Parser2.prototype.save = function() { + var column = this.table[this.current]; + column.lexerState = this.lexerState; + return column; + }; + Parser2.prototype.restore = function(column) { + var index = column.index; + this.current = index; + this.table[index] = column; + this.table.splice(index + 1); + this.lexerState = column.lexerState; + this.results = this.finish(); + }; + Parser2.prototype.rewind = function(index) { + if (!this.options.keepHistory) { + throw new Error("set option `keepHistory` to enable rewinding"); + } + this.restore(this.table[index]); + }; + Parser2.prototype.finish = function() { + var considerations = []; + var start = this.grammar.start; + var column = this.table[this.table.length - 1]; + column.states.forEach(function(t) { + if (t.rule.name === start && t.dot === t.rule.symbols.length && t.reference === 0 && t.data !== Parser2.fail) { + considerations.push(t); + } + }); + return considerations.map(function(c) { + return c.data; + }); + }; + function getSymbolLongDisplay(symbol) { + var type = typeof symbol; + if (type === "string") { + return symbol; + } else if (type === "object") { + if (symbol.literal) { + return JSON.stringify(symbol.literal); + } else if (symbol instanceof RegExp) { + return "character matching " + symbol; + } else if (symbol.type) { + return symbol.type + " token"; + } else if (symbol.test) { + return "token matching " + String(symbol.test); + } else { + throw new Error("Unknown symbol type: " + symbol); + } + } + } + function getSymbolShortDisplay(symbol) { + var type = typeof symbol; + if (type === "string") { + return symbol; + } else if (type === "object") { + if (symbol.literal) { + return JSON.stringify(symbol.literal); + } else if (symbol instanceof RegExp) { + return symbol.toString(); + } else if (symbol.type) { + return "%" + symbol.type; + } else if (symbol.test) { + return "<" + String(symbol.test) + ">"; + } else { + throw new Error("Unknown symbol type: " + symbol); + } + } + } + return { + Parser: Parser2, + Grammar: Grammar2, + Rule: Rule2 + }; + }); + } +}); + +// ../../node_modules/moo/moo.js +var require_moo = __commonJS({ + "../../node_modules/moo/moo.js"(exports, module2) { + (function(root, factory) { + if (typeof define === "function" && define.amd) { + define([], factory); + } else if (typeof module2 === "object" && module2.exports) { + module2.exports = factory(); + } else { + root.moo = factory(); + } + })(exports, function() { + "use strict"; + var hasOwnProperty = Object.prototype.hasOwnProperty; + var toString = Object.prototype.toString; + var hasSticky = typeof new RegExp().sticky === "boolean"; + function isRegExp(o) { + return o && toString.call(o) === "[object RegExp]"; + } + function isObject(o) { + return o && typeof o === "object" && !isRegExp(o) && !Array.isArray(o); + } + function reEscape(s) { + return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"); + } + function reGroups(s) { + var re = new RegExp("|" + s); + return re.exec("").length - 1; + } + function reCapture(s) { + return "(" + s + ")"; + } + function reUnion(regexps) { + if (!regexps.length) + return "(?!)"; + var source = regexps.map(function(s) { + return "(?:" + s + ")"; + }).join("|"); + return "(?:" + source + ")"; + } + function regexpOrLiteral(obj) { + if (typeof obj === "string") { + return "(?:" + reEscape(obj) + ")"; + } else if (isRegExp(obj)) { + if (obj.ignoreCase) + throw new Error("RegExp /i flag not allowed"); + if (obj.global) + throw new Error("RegExp /g flag is implied"); + if (obj.sticky) + throw new Error("RegExp /y flag is implied"); + if (obj.multiline) + throw new Error("RegExp /m flag is implied"); + return obj.source; + } else { + throw new Error("Not a pattern: " + obj); + } + } + function pad2(s, length) { + if (s.length > length) { + return s; + } + return Array(length - s.length + 1).join(" ") + s; + } + function lastNLines(string2, numLines) { + var position = string2.length; + var lineBreaks = 0; + while (true) { + var idx = string2.lastIndexOf("\n", position - 1); + if (idx === -1) { + break; + } else { + lineBreaks++; + } + position = idx; + if (lineBreaks === numLines) { + break; + } + if (position === 0) { + break; + } + } + var startPosition = lineBreaks < numLines ? 0 : position + 1; + return string2.substring(startPosition).split("\n"); + } + function objectToRules(object) { + var keys = Object.getOwnPropertyNames(object); + var result = []; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var thing = object[key]; + var rules = [].concat(thing); + if (key === "include") { + for (var j = 0; j < rules.length; j++) { + result.push({ include: rules[j] }); + } + continue; + } + var match = []; + rules.forEach(function(rule) { + if (isObject(rule)) { + if (match.length) + result.push(ruleOptions(key, match)); + result.push(ruleOptions(key, rule)); + match = []; + } else { + match.push(rule); + } + }); + if (match.length) + result.push(ruleOptions(key, match)); + } + return result; + } + function arrayToRules(array) { + var result = []; + for (var i = 0; i < array.length; i++) { + var obj = array[i]; + if (obj.include) { + var include = [].concat(obj.include); + for (var j = 0; j < include.length; j++) { + result.push({ include: include[j] }); + } + continue; + } + if (!obj.type) { + throw new Error("Rule has no type: " + JSON.stringify(obj)); + } + result.push(ruleOptions(obj.type, obj)); + } + return result; + } + function ruleOptions(type, obj) { + if (!isObject(obj)) { + obj = { match: obj }; + } + if (obj.include) { + throw new Error("Matching rules cannot also include states"); + } + var options = { + defaultType: type, + lineBreaks: !!obj.error || !!obj.fallback, + pop: false, + next: null, + push: null, + error: false, + fallback: false, + value: null, + type: null, + shouldThrow: false + }; + for (var key in obj) { + if (hasOwnProperty.call(obj, key)) { + options[key] = obj[key]; + } + } + if (typeof options.type === "string" && type !== options.type) { + throw new Error("Type transform cannot be a string (type '" + options.type + "' for token '" + type + "')"); + } + var match = options.match; + options.match = Array.isArray(match) ? match : match ? [match] : []; + options.match.sort(function(a, b) { + return isRegExp(a) && isRegExp(b) ? 0 : isRegExp(b) ? -1 : isRegExp(a) ? 1 : b.length - a.length; + }); + return options; + } + function toRules(spec) { + return Array.isArray(spec) ? arrayToRules(spec) : objectToRules(spec); + } + var defaultErrorRule = ruleOptions("error", { lineBreaks: true, shouldThrow: true }); + function compileRules(rules, hasStates) { + var errorRule = null; + var fast = /* @__PURE__ */ Object.create(null); + var fastAllowed = true; + var unicodeFlag = null; + var groups = []; + var parts = []; + for (var i = 0; i < rules.length; i++) { + if (rules[i].fallback) { + fastAllowed = false; + } + } + for (var i = 0; i < rules.length; i++) { + var options = rules[i]; + if (options.include) { + throw new Error("Inheritance is not allowed in stateless lexers"); + } + if (options.error || options.fallback) { + if (errorRule) { + if (!options.fallback === !errorRule.fallback) { + throw new Error("Multiple " + (options.fallback ? "fallback" : "error") + " rules not allowed (for token '" + options.defaultType + "')"); + } else { + throw new Error("fallback and error are mutually exclusive (for token '" + options.defaultType + "')"); + } + } + errorRule = options; + } + var match = options.match.slice(); + if (fastAllowed) { + while (match.length && typeof match[0] === "string" && match[0].length === 1) { + var word2 = match.shift(); + fast[word2.charCodeAt(0)] = options; + } + } + if (options.pop || options.push || options.next) { + if (!hasStates) { + throw new Error("State-switching options are not allowed in stateless lexers (for token '" + options.defaultType + "')"); + } + if (options.fallback) { + throw new Error("State-switching options are not allowed on fallback tokens (for token '" + options.defaultType + "')"); + } + } + if (match.length === 0) { + continue; + } + fastAllowed = false; + groups.push(options); + for (var j = 0; j < match.length; j++) { + var obj = match[j]; + if (!isRegExp(obj)) { + continue; + } + if (unicodeFlag === null) { + unicodeFlag = obj.unicode; + } else if (unicodeFlag !== obj.unicode && options.fallback === false) { + throw new Error("If one rule is /u then all must be"); + } + } + var pat = reUnion(match.map(regexpOrLiteral)); + var regexp = new RegExp(pat); + if (regexp.test("")) { + throw new Error("RegExp matches empty string: " + regexp); + } + var groupCount = reGroups(pat); + if (groupCount > 0) { + throw new Error("RegExp has capture groups: " + regexp + "\nUse (?: \u2026 ) instead"); + } + if (!options.lineBreaks && regexp.test("\n")) { + throw new Error("Rule should declare lineBreaks: " + regexp); + } + parts.push(reCapture(pat)); + } + var fallbackRule = errorRule && errorRule.fallback; + var flags = hasSticky && !fallbackRule ? "ym" : "gm"; + var suffix = hasSticky || fallbackRule ? "" : "|"; + if (unicodeFlag === true) + flags += "u"; + var combined = new RegExp(reUnion(parts) + suffix, flags); + return { regexp: combined, groups, fast, error: errorRule || defaultErrorRule }; + } + function compile(rules) { + var result = compileRules(toRules(rules)); + return new Lexer2({ start: result }, "start"); + } + function checkStateGroup(g, name, map) { + var state = g && (g.push || g.next); + if (state && !map[state]) { + throw new Error("Missing state '" + state + "' (in token '" + g.defaultType + "' of state '" + name + "')"); + } + if (g && g.pop && +g.pop !== 1) { + throw new Error("pop must be 1 (in token '" + g.defaultType + "' of state '" + name + "')"); + } + } + function compileStates(states, start) { + var all = states.$all ? toRules(states.$all) : []; + delete states.$all; + var keys = Object.getOwnPropertyNames(states); + if (!start) + start = keys[0]; + var ruleMap = /* @__PURE__ */ Object.create(null); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + ruleMap[key] = toRules(states[key]).concat(all); + } + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var rules = ruleMap[key]; + var included = /* @__PURE__ */ Object.create(null); + for (var j = 0; j < rules.length; j++) { + var rule = rules[j]; + if (!rule.include) + continue; + var splice = [j, 1]; + if (rule.include !== key && !included[rule.include]) { + included[rule.include] = true; + var newRules = ruleMap[rule.include]; + if (!newRules) { + throw new Error("Cannot include nonexistent state '" + rule.include + "' (in state '" + key + "')"); + } + for (var k = 0; k < newRules.length; k++) { + var newRule = newRules[k]; + if (rules.indexOf(newRule) !== -1) + continue; + splice.push(newRule); + } + } + rules.splice.apply(rules, splice); + j--; + } + } + var map = /* @__PURE__ */ Object.create(null); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + map[key] = compileRules(ruleMap[key], true); + } + for (var i = 0; i < keys.length; i++) { + var name = keys[i]; + var state = map[name]; + var groups = state.groups; + for (var j = 0; j < groups.length; j++) { + checkStateGroup(groups[j], name, map); + } + var fastKeys = Object.getOwnPropertyNames(state.fast); + for (var j = 0; j < fastKeys.length; j++) { + checkStateGroup(state.fast[fastKeys[j]], name, map); + } + } + return new Lexer2(map, start); + } + function keywordTransform(map) { + var isMap = typeof Map !== "undefined"; + var reverseMap = isMap ? /* @__PURE__ */ new Map() : /* @__PURE__ */ Object.create(null); + var types = Object.getOwnPropertyNames(map); + for (var i = 0; i < types.length; i++) { + var tokenType = types[i]; + var item = map[tokenType]; + var keywordList = Array.isArray(item) ? item : [item]; + keywordList.forEach(function(keyword) { + if (typeof keyword !== "string") { + throw new Error("keyword must be string (in keyword '" + tokenType + "')"); + } + if (isMap) { + reverseMap.set(keyword, tokenType); + } else { + reverseMap[keyword] = tokenType; + } + }); + } + return function(k) { + return isMap ? reverseMap.get(k) : reverseMap[k]; + }; + } + var Lexer2 = function(states, state) { + this.startState = state; + this.states = states; + this.buffer = ""; + this.stack = []; + this.reset(); + }; + Lexer2.prototype.reset = function(data, info) { + this.buffer = data || ""; + this.index = 0; + this.line = info ? info.line : 1; + this.col = info ? info.col : 1; + this.queuedToken = info ? info.queuedToken : null; + this.queuedText = info ? info.queuedText : ""; + this.queuedThrow = info ? info.queuedThrow : null; + this.setState(info ? info.state : this.startState); + this.stack = info && info.stack ? info.stack.slice() : []; + return this; + }; + Lexer2.prototype.save = function() { + return { + line: this.line, + col: this.col, + state: this.state, + stack: this.stack.slice(), + queuedToken: this.queuedToken, + queuedText: this.queuedText, + queuedThrow: this.queuedThrow + }; + }; + Lexer2.prototype.setState = function(state) { + if (!state || this.state === state) + return; + this.state = state; + var info = this.states[state]; + this.groups = info.groups; + this.error = info.error; + this.re = info.regexp; + this.fast = info.fast; + }; + Lexer2.prototype.popState = function() { + this.setState(this.stack.pop()); + }; + Lexer2.prototype.pushState = function(state) { + this.stack.push(this.state); + this.setState(state); + }; + var eat = hasSticky ? function(re, buffer) { + return re.exec(buffer); + } : function(re, buffer) { + var match = re.exec(buffer); + if (match[0].length === 0) { + return null; + } + return match; + }; + Lexer2.prototype._getGroup = function(match) { + var groupCount = this.groups.length; + for (var i = 0; i < groupCount; i++) { + if (match[i + 1] !== void 0) { + return this.groups[i]; + } + } + throw new Error("Cannot find token type for matched text"); + }; + function tokenToString() { + return this.value; + } + Lexer2.prototype.next = function() { + var index = this.index; + if (this.queuedGroup) { + var token = this._token(this.queuedGroup, this.queuedText, index); + this.queuedGroup = null; + this.queuedText = ""; + return token; + } + var buffer = this.buffer; + if (index === buffer.length) { + return; + } + var group = this.fast[buffer.charCodeAt(index)]; + if (group) { + return this._token(group, buffer.charAt(index), index); + } + var re = this.re; + re.lastIndex = index; + var match = eat(re, buffer); + var error = this.error; + if (match == null) { + return this._token(error, buffer.slice(index, buffer.length), index); + } + var group = this._getGroup(match); + var text = match[0]; + if (error.fallback && match.index !== index) { + this.queuedGroup = group; + this.queuedText = text; + return this._token(error, buffer.slice(index, match.index), index); + } + return this._token(group, text, index); + }; + Lexer2.prototype._token = function(group, text, offset) { + var lineBreaks = 0; + if (group.lineBreaks) { + var matchNL = /\n/g; + var nl = 1; + if (text === "\n") { + lineBreaks = 1; + } else { + while (matchNL.exec(text)) { + lineBreaks++; + nl = matchNL.lastIndex; + } + } + } + var token = { + type: typeof group.type === "function" && group.type(text) || group.defaultType, + value: typeof group.value === "function" ? group.value(text) : text, + text, + toString: tokenToString, + offset, + lineBreaks, + line: this.line, + col: this.col + }; + var size = text.length; + this.index += size; + this.line += lineBreaks; + if (lineBreaks !== 0) { + this.col = size - nl + 1; + } else { + this.col += size; + } + if (group.shouldThrow) { + var err = new Error(this.formatError(token, "invalid syntax")); + throw err; + } + if (group.pop) + this.popState(); + else if (group.push) + this.pushState(group.push); + else if (group.next) + this.setState(group.next); + return token; + }; + if (typeof Symbol !== "undefined" && Symbol.iterator) { + var LexerIterator = function(lexer2) { + this.lexer = lexer2; + }; + LexerIterator.prototype.next = function() { + var token = this.lexer.next(); + return { value: token, done: !token }; + }; + LexerIterator.prototype[Symbol.iterator] = function() { + return this; + }; + Lexer2.prototype[Symbol.iterator] = function() { + return new LexerIterator(this); + }; + } + Lexer2.prototype.formatError = function(token, message) { + if (token == null) { + var text = this.buffer.slice(this.index); + var token = { + text, + offset: this.index, + lineBreaks: text.indexOf("\n") === -1 ? 0 : 1, + line: this.line, + col: this.col + }; + } + var numLinesAround = 2; + var firstDisplayedLine = Math.max(token.line - numLinesAround, 1); + var lastDisplayedLine = token.line + numLinesAround; + var lastLineDigits = String(lastDisplayedLine).length; + var displayedLines = lastNLines( + this.buffer, + this.line - token.line + numLinesAround + 1 + ).slice(0, 5); + var errorLines = []; + errorLines.push(message + " at line " + token.line + " col " + token.col + ":"); + errorLines.push(""); + for (var i = 0; i < displayedLines.length; i++) { + var line = displayedLines[i]; + var lineNo = firstDisplayedLine + i; + errorLines.push(pad2(String(lineNo), lastLineDigits) + " " + line); + if (lineNo === token.line) { + errorLines.push(pad2("", lastLineDigits + token.col + 1) + "^"); + } + } + return errorLines.join("\n"); + }; + Lexer2.prototype.clone = function() { + return new Lexer2(this.states, this.state); + }; + Lexer2.prototype.has = function(tokenType) { + return true; + }; + return { + compile, + states: compileStates, + error: Object.freeze({ error: true }), + fallback: Object.freeze({ fallback: true }), + keywords: keywordTransform + }; + }); + } +}); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + PublicodesError: () => PublicodesError, + capitalise0: () => capitalise0, + default: () => Engine, + formatValue: () => formatValue, + isPublicodesError: () => isPublicodesError, + parseExpression: () => parseExpression, + parsePublicodes: () => parsePublicodes, + parseUnit: () => parseUnit, + reduceAST: () => reduceAST, + serializeEvaluation: () => serializeEvaluation, + serializeUnit: () => serializeUnit, + simplifyNodeUnit: () => simplifyNodeUnit, + transformAST: () => makeASTTransformer, + traverseASTNode: () => traverseASTNode, + utils: () => ruleUtils_exports +}); +module.exports = __toCommonJS(src_exports); + +// src/error.ts +var isPublicodesError = (error, name) => error instanceof PublicodesError && (name === void 0 ? true : error.name === name); +var PublicodesError = class extends Error { + name; + info; + constructor(name, message, info, originalError) { + super(buildMessage(name, message, info, originalError)); + this.name = name; + this.info = info; + } +}; +var buildMessage = (name, message, info, originalError) => { + const types = { + SyntaxError: "Erreur syntaxique", + EvaluationError: "Erreur d'\xE9valuation", + UnknownRule: "R\xE8gle inconnue", + PrivateRule: "R\xE8gle priv\xE9e" + }; + const isError = /error/i.test(name); + return ` +[ ${types[name] ?? name} ]` + (info && "dottedName" in info && info.dottedName?.length ? ` +\u27A1\uFE0F Dans la r\xE8gle "${info.dottedName}"` : "") + ` +${isError ? "\u2716\uFE0F" : "\u26A0\uFE0F"} ${message}` + (originalError ? "\n" + (isError ? " " : "\u2139\uFE0F ") + originalError.message : ""); +}; +var PublicodesInternalError = class extends PublicodesError { + constructor(payload) { + super( + "InternalError", + ` +Erreur interne du moteur. + +Cette erreur est le signe d'un bug dans publicodes. Pour nous aider \xE0 le r\xE9soudre, vous pouvez copier ce texte dans un nouveau ticket : https://github.com/betagouv/mon-entreprise/issues/new. + +payload: +${JSON.stringify(payload, null, 2)} +`, + payload + ); + } +}; +var UnreachableCaseError = class extends PublicodesInternalError { + constructor(value) { + super(value); + } +}; +function warning(logger, message, information, originalError) { + logger.warn( + buildMessage("Avertissement", message, information, originalError) + ); +} +function experimentalRuleWarning(logger, dottedName) { + logger.warn( + buildMessage( + "Avertissement", + "Cette r\xE8gle est taggu\xE9e comme experimentale. \n\nCela veut dire qu'elle peut \xEAtre modifi\xE9e, renomm\xE9e, ou supprim\xE9e sans qu'il n'y ait de changement de version majeure dans l'API.\n", + { dottedName } + ) + ); +} + +// src/utils.ts +function addToMapSet(map, key, value) { + if (map.has(key)) { + map.get(key).add(value); + return; + } + map.set(key, /* @__PURE__ */ new Set([value])); +} +function mergeWithArray(obj1, obj2) { + return Object.entries(obj2).reduce( + (obj, [key, value]) => ({ + ...obj, + [key]: [...obj[key] ?? [], ...value] + }), + obj1 + ); +} +var weakCopyObj = (obj) => { + const copy = {}; + for (const key in obj) { + copy[key] = obj[key]; + } + return copy; +}; + +// src/AST/index.ts +function makeASTTransformer(fn, stopOnUpdate = true) { + function transform(node) { + const updatedNode = fn(node, transform); + if (updatedNode === false) { + return node; + } + if (updatedNode === void 0) { + return traverseASTNode(transform, node); + } + return stopOnUpdate ? updatedNode : traverseASTNode(transform, updatedNode); + } + return transform; +} +function makeASTVisitor(fn) { + function visit(node) { + switch (fn(node, visit)) { + case "continue": + traverseASTNode(transformizedVisit, node); + return; + case "stop": + return; + } + } + const transformizedVisit = (node) => { + visit(node); + return node; + }; + return visit; +} +function reduceAST(fn, start, node) { + function traverseFn(acc, node2) { + const result = fn(acc, node2, traverseFn.bind(null, start)); + if (result === void 0) { + return getChildrenNodes(node2).reduce(traverseFn, acc); + } + return result; + } + return traverseFn(start, node); +} +function getChildrenNodes(node) { + const nodes = []; + traverseASTNode((node2) => { + nodes.push(node2); + return node2; + }, node); + return nodes; +} +function traverseParsedRules(fn, parsedRules) { + const ret = {}; + for (const name in parsedRules) { + ret[name] = fn(parsedRules[name]); + } + return ret; +} +var traverseASTNode = (fn, node) => { + node = traverseSourceMap(fn, node); + switch (node.nodeKind) { + case "rule": + return traverseRuleNode(fn, node); + case "reference": + case "constant": + return node; + case "arrondi": + return traverseArrondiNode(fn, node); + case "simplifier unit\xE9": + case "variable manquante": + case "est non applicable": + case "est non d\xE9fini": + return traverseUnaryOperationNode(fn, node); + case "bar\xE8me": + case "taux progressif": + case "grille": + return traverseNodeWithTranches(fn, node); + case "une possibilit\xE9": + return traverseArrayNode(fn, node); + case "dur\xE9e": + return traverseDur\u00E9eNode(fn, node); + case "r\xE9soudre r\xE9f\xE9rence circulaire": + return traverseR\u00E9soudreR\u00E9f\u00E9renceCirculaireNode(fn, node); + case "inversion": + return traverseInversionNode(fn, node); + case "operation": + return traverseOperationNode(fn, node); + case "contexte": + return traverseContexteNode(fn, node); + case "unit\xE9": + return traverseUnit\u00E9Node(fn, node); + case "variations": + return traverseVariationNode(fn, node); + case "replacementRule": + return traverseReplacementNode(fn, node); + case "texte": + return traverseTextNode(fn, node); + case "condition": + return traverseConditionNode(fn, node); + default: + throw new UnreachableCaseError(node); + } +}; +var traverseSourceMap = (fn, node) => { + if (!("sourceMap" in node) || !node.sourceMap || !node.sourceMap.args) { + return node; + } + const sourceMap = node.sourceMap; + const args = {}; + for (const key in sourceMap.args) { + const value = sourceMap.args[key]; + args[key] = Array.isArray(value) ? value.map((v) => fn(v)) : fn(value); + } + return { + ...node, + sourceMap: { + ...sourceMap, + args + } + }; +}; +var traverseRuleNode = (fn, node) => { + const copy = weakCopyObj(node); + copy.suggestions = {}; + for (const key in node.suggestions) { + copy.suggestions[key] = fn(node.suggestions[key]); + } + copy.replacements = node.replacements.map(fn); + copy.explanation = { + ruleDisabledByItsParent: node.explanation.ruleDisabledByItsParent, + nullableParent: node.explanation.nullableParent ? fn(node.explanation.nullableParent) : void 0, + parents: node.explanation.parents.map(fn), + valeur: fn(node.explanation.valeur) + }; + return copy; +}; +var traverseReplacementNode = (fn, node) => ({ + ...node, + definitionRule: fn(node.definitionRule), + replacedReference: fn(node.replacedReference), + whiteListedNames: node.whiteListedNames.map(fn), + blackListedNames: node.blackListedNames.map(fn) +}); +var traverseUnaryOperationNode = (fn, node) => ({ + ...node, + explanation: fn(node.explanation) +}); +function traverseTranche(fn, tranches) { + return tranches.map((tranche) => ({ + ...tranche, + ...tranche.plafond && { plafond: fn(tranche.plafond) }, + ..."montant" in tranche && { montant: fn(tranche.montant) }, + ..."taux" in tranche && { taux: fn(tranche.taux) } + })); +} +var traverseNodeWithTranches = (fn, node) => ({ + ...node, + explanation: { + assiette: fn(node.explanation.assiette), + multiplicateur: fn(node.explanation.multiplicateur), + tranches: traverseTranche(fn, node.explanation.tranches) + } +}); +var traverseArrayNode = (fn, node) => ({ + ...node, + explanation: node.explanation.map(fn) +}); +var traverseOperationNode = (fn, node) => { + const copy = weakCopyObj(node); + copy.explanation = [fn(node.explanation[0]), fn(node.explanation[1])]; + return copy; +}; +var traverseDur\u00E9eNode = (fn, node) => ({ + ...node, + explanation: { + depuis: fn(node.explanation.depuis), + "jusqu'\xE0": fn(node.explanation["jusqu'\xE0"]) + } +}); +var traverseInversionNode = (fn, node) => ({ + ...node, + explanation: { + ...node.explanation, + inversionCandidates: node.explanation.inversionCandidates.map(fn) + // TODO + } +}); +var traverseArrondiNode = (fn, node) => ({ + ...node, + explanation: { + valeur: fn(node.explanation.valeur), + arrondi: fn(node.explanation.arrondi) + } +}); +var traverseR\u00E9soudreR\u00E9f\u00E9renceCirculaireNode = (fn, node) => ({ + ...node, + explanation: { + ...node.explanation, + valeur: fn(node.explanation.valeur) + } +}); +var traverseTextNode = (fn, node) => ({ + ...node, + explanation: node.explanation.map( + (element) => typeof element === "string" ? element : fn(element) + ) +}); +var traverseContexteNode = (fn, node) => ({ + ...node, + explanation: { + ...node.explanation, + contexte: node.explanation.contexte.map(([name, value]) => [ + fn(name), + fn(value) + ]), + valeur: fn(node.explanation.valeur) + } +}); +var traverseUnit\u00E9Node = (fn, node) => { + const copy = weakCopyObj(node); + copy.explanation = fn(node.explanation); + return copy; +}; +var traverseVariationNode = (fn, node) => ({ + ...node, + explanation: node.explanation.map(({ condition, consequence }) => ({ + condition: fn(condition), + consequence: consequence && fn(consequence) + })) +}); +var traverseConditionNode = (fn, node) => { + const copy = weakCopyObj(node); + copy.explanation = { + si: fn(node.explanation.si), + alors: fn(node.explanation.alors), + sinon: fn(node.explanation.sinon) + }; + return copy; +}; + +// src/evaluationFunctions.ts +var evaluationFunctions = { + constant: (node) => node +}; +function registerEvaluationFunction(nodeKind, evaluationFunction) { + evaluationFunctions ??= {}; + if (evaluationFunctions[nodeKind]) { + throw new PublicodesError( + "EvaluationError", + `Multiple evaluation functions registered for the nodeKind \x1B[4m${nodeKind}`, + { dottedName: "" } + ); + } + evaluationFunctions[nodeKind] = evaluationFunction; +} + +// src/inferNodeType.ts +var UNDEFINED_TYPE = { + isNullable: void 0, + type: void 0 +}; +function inferNodesTypes(newRulesNames, parsedRules, nodesTypes) { + function inferNodeUnitAndCache(node) { + if (!node || typeof node !== "object") { + return UNDEFINED_TYPE; + } + if (nodesTypes.has(node)) { + return nodesTypes.get(node); + } + nodesTypes.set(node, UNDEFINED_TYPE); + const type = inferNodeType(node); + nodesTypes.set(node, type); + return type; + } + function inferNodeType(node) { + switch (node.nodeKind) { + case "bar\xE8me": + case "dur\xE9e": + case "grille": + case "taux progressif": + return { isNullable: false, type: "number" }; + case "est non d\xE9fini": + case "est non applicable": + return { isNullable: false, type: "boolean" }; + case "constant": + return { + isNullable: node.isNullable ?? node.nodeValue === null, + type: node.type + }; + case "operation": + return { + isNullable: ["<", "<=", ">", ">=", "/", "*"].includes(node.operationKind) ? inferNodeUnitAndCache(node.explanation[0]).isNullable || inferNodeUnitAndCache(node.explanation[1]).isNullable : node.operationKind === "-" ? inferNodeUnitAndCache(node.explanation[0]).isNullable : false, + type: ["<", "<=", ">", ">=", "=", "!=", "et", "ou"].includes( + node.operationKind + ) ? "boolean" : "number" + }; + case "inversion": + case "replacementRule": + case "r\xE9soudre r\xE9f\xE9rence circulaire": + return { isNullable: false, type: "number" }; + case "texte": + case "une possibilit\xE9": + return { isNullable: false, type: "string" }; + case "contexte": + case "rule": + case "arrondi": + return inferNodeUnitAndCache(node.explanation.valeur); + case "unit\xE9": + case "simplifier unit\xE9": + case "variable manquante": + return inferNodeUnitAndCache(node.explanation); + case "condition": + return { + isNullable: [ + node.explanation.si, + node.explanation.alors, + node.explanation.sinon + ].some((n) => inferNodeUnitAndCache(n).isNullable), + type: inferNodeUnitAndCache(node.explanation.alors).type ?? inferNodeUnitAndCache(node.explanation.sinon).type + }; + case "variations": { + const consequencesTypes = node.explanation.map( + ({ consequence }) => inferNodeUnitAndCache(consequence) + ); + return { + isNullable: consequencesTypes.some( + (consequence) => consequence.isNullable + ), + type: consequencesTypes.map((c) => c.type).find((type) => type !== void 0) + }; + } + case "reference": + return inferNodeUnitAndCache(parsedRules[node.dottedName]); + } + } + newRulesNames.forEach((name) => { + const rule = parsedRules[name]; + inferNodeUnitAndCache(rule); + rule.explanation.parents.forEach(inferNodeUnitAndCache); + }); + return nodesTypes; +} + +// src/evaluationUtils.ts +var collectNodeMissing = (node) => "missingVariables" in node ? node.missingVariables : {}; +var bonus = (missings = {}) => Object.fromEntries( + Object.entries(missings).map(([key, value]) => [key, value + 1]) +); +var mergeMissing = (left = {}, right = {}) => Object.fromEntries( + [...Object.keys(left), ...Object.keys(right)].map((key) => [ + key, + (left[key] ?? 0) + (right[key] ?? 0) + ]) +); +var mergeAllMissing = (missings) => missings.map(collectNodeMissing).reduce(mergeMissing, {}); +var defaultNode = (nodeValue) => ({ + nodeValue, + type: typeof nodeValue, + isDefault: true, + nodeKind: "constant" +}); +var notApplicableNode = { + nodeKind: "constant", + nodeValue: null, + missingVariables: {}, + type: void 0, + isNullable: true +}; +var undefinedNode = { + nodeKind: "constant", + nodeValue: void 0, + missingVariables: {}, + type: void 0, + isNullable: false +}; +var undefinedNumberNode = { + ...undefinedNode, + type: "number" +}; + +// src/mecanisms/inlineMecanism.ts +function createParseInlinedMecanism(name, args, body) { + let parsedBody; + let parsedDefaultArgs; + function parseInlineMecanism(providedArgs, context) { + parsedBody ??= parse(body, createContext({ dottedName: "INLINE_MECANISM" })); + parsedDefaultArgs ??= {}; + for (const name2 in args) { + if ("par d\xE9faut" in args[name2]) { + parsedDefaultArgs[name2] = parse( + args[name2]["par d\xE9faut"], + createContext({}) + ); + } + } + if (Object.keys(args).length === 1 && "valeur" in args) { + providedArgs = { + valeur: providedArgs + }; + } + const parsedProvidedArgs = {}; + for (const name2 in providedArgs) { + parsedProvidedArgs[name2] = parse(providedArgs[name2], context); + } + const parsedInlineMecanism = makeASTTransformer((node) => { + if (node.nodeKind !== "reference" || !(node.name in args)) { + return; + } + const argName = node.name; + if (argName in parsedProvidedArgs) { + return parsedProvidedArgs[argName]; + } + if (argName in parsedDefaultArgs) { + return parsedDefaultArgs[argName]; + } + throw new PublicodesError( + "SyntaxError", + `Il manque la cl\xE9 '${argName} dans le m\xE9canisme ${name}`, + { dottedName: argName } + ); + })(parsedBody); + parsedInlineMecanism.sourceMap = { + mecanismName: name, + args: parsedProvidedArgs + }; + return parsedInlineMecanism; + } + parseInlineMecanism.nom = name; + return Object.assign(parseInlineMecanism, "name", { + value: `parse${toCamelCase(name)}Inline` + }); +} +function createParseInlinedMecanismWithArray(name, args, body) { + function parseInlineMecanism(providedArgs, context) { + if (Object.keys(args).length === 1 && "valeur" in args) { + providedArgs = { + valeur: providedArgs + }; + } + const parsedProvidedArgs = {}; + for (const name2 in providedArgs) { + const value = providedArgs[name2]; + parsedProvidedArgs[name2] = Array.isArray(value) ? value.map((v) => parse(v, context)) : parse(value, context); + } + const parsedInlineMecanism = parse(body(parsedProvidedArgs), context); + parsedInlineMecanism.sourceMap = { + mecanismName: name, + args: parsedProvidedArgs + }; + return parsedInlineMecanism; + } + parseInlineMecanism.nom = name; + return Object.assign(parseInlineMecanism, "name", { + value: `parse${toCamelCase(name)}Inline` + }); +} +function toCamelCase(str) { + return str.replace(/(?:^\w|[A-Z]|\b\w)/g, (ltr) => ltr.toUpperCase()).replace(/\s+/g, ""); +} + +// src/mecanisms/abattement.ts +var abattement_default = createParseInlinedMecanism( + "abattement", + { + abattement: {}, + valeur: {} + }, + { + "-": ["valeur", "abattement"], + plancher: 0 + } +); + +// src/mecanisms/applicable.ts +var applicable_default = createParseInlinedMecanism( + "applicable si", + { + "applicable si": {}, + valeur: {} + }, + { + condition: { + si: "applicable si != non", + alors: "valeur", + sinon: notApplicableNode + } + } +); + +// src/units.ts +var parseUnit = (string2, getUnitKey = (x) => x) => { + if (string2.includes(" /") || string2.includes("/ ")) { + throw new Error( + `L'unit\xE9 "${string2}" ne doit pas contenir d'espace avant et apr\xE8s "/"` + ); + } + const [a, ...b] = string2.split("/"); + const splitUnit = (string3) => decomposePower( + string3.split(".").filter(Boolean).map((unit) => getUnitKey(unit)) + ); + const result = { + numerators: splitUnit(a), + denominators: b.flatMap((u) => splitUnit(u)) + }; + return result; +}; +var lastNumberFromString = /(\d+)(?!.*[A-Za-z])/g; +function getUnitCounts(baseUnits) { + const countUnits = {}; + baseUnits.forEach((e) => { + const powerMatch = e.match(lastNumberFromString); + if (powerMatch != null) { + const power = powerMatch[0]; + const primaryUnit = e.split(power)[0]; + countUnits[primaryUnit] = (countUnits[primaryUnit] ?? 0) + +power; + } else { + countUnits[e] = (countUnits[e] ?? 0) + 1; + } + }); + return countUnits; +} +function decomposePower(baseUnits) { + const unitCounts = getUnitCounts(baseUnits); + return Object.entries(unitCounts).flatMap( + ([primaryUnit, power]) => Array(power).fill(primaryUnit) + ); +} +function combinePower(baseUnit) { + const unitCounts = getUnitCounts(baseUnit); + return Object.entries(unitCounts).map( + ([primaryUnit, power]) => power > 1 ? `${primaryUnit}${power}` : primaryUnit + ); +} +var printUnits = (units, count, formatUnit2 = (x) => x) => { + return combinePower(units.map((unit) => formatUnit2(unit, count))).join("."); +}; +var plural = 2; +function serializeUnit(rawUnit, count = plural, formatUnit2 = (x) => x) { + if (rawUnit === null || typeof rawUnit !== "object") { + return typeof rawUnit === "string" ? formatUnit2(rawUnit, count) : rawUnit; + } + const unit = simplify(rawUnit); + const { numerators = [], denominators = [] } = unit; + const n = numerators.length > 0; + const d = denominators.length > 0; + const string2 = !n && !d ? "" : n && !d ? printUnits(numerators, count, formatUnit2) : !n && d ? `/${printUnits(denominators, 1, formatUnit2)}` : `${printUnits(numerators, plural, formatUnit2)}/${printUnits( + denominators, + 1, + formatUnit2 + )}`; + return string2; +} +var noUnit = { numerators: [], denominators: [] }; +var inferUnit = (operator, rawUnits) => { + if (operator === "/") { + if (rawUnits.length !== 2) { + throw new PublicodesError( + "InternalError", + "Infer units of a division with units.length !== 2)", + {} + ); + } + return inferUnit("*", [ + rawUnits[0] || noUnit, + { + numerators: (rawUnits[1] || noUnit).denominators, + denominators: (rawUnits[1] || noUnit).numerators + } + ]); + } + const units = rawUnits.filter(Boolean); + if (units.length <= 1) { + return units[0]; + } + if (operator === "*") + return simplify({ + numerators: units.flatMap((u) => u?.numerators ?? []), + denominators: units.flatMap((u) => u?.denominators ?? []) + }); + if (operator === "-" || operator === "+") { + return rawUnits.find((u) => u); + } + return void 0; +}; +var equals = (a, b) => { + if (Array.isArray(a) && Array.isArray(b)) { + return a.length === b.length && a.every((_, i) => a[i] === b[i]); + } else { + return a === b; + } +}; +var removeOnce = (element, eqFn = equals) => (list) => { + const index = list.findIndex((e) => eqFn(e, element)); + return list.filter((_, i) => i !== index); +}; +var simplify = (unit, eqFn = equals) => { + const simplifiedUnit = [...unit.numerators, ...unit.denominators].reduce( + ({ numerators, denominators }, next) => numerators.find((u) => eqFn(next, u)) && denominators.find((u) => eqFn(next, u)) ? { + numerators: removeOnce(next, eqFn)(numerators), + denominators: removeOnce(next, eqFn)(denominators) + } : { numerators, denominators }, + unit + ); + return simplifiedUnit; +}; +var convertTable = { + "mois/an": 12, + "jour/an": 365, + "jour/mois": 365 / 12, + "trimestre/an": 4, + "mois/trimestre": 3, + "jour/trimestre": 365 / 12 * 3, + "\u20AC/k\u20AC": 10 ** 3, + "g/kg": 10 ** 3, + "mg/g": 10 ** 3, + "mg/kg": 10 ** 6, + "m/km": 10 ** 3, + "cm/m": 10 ** 2, + "mm/cm": 10 ** 1, + "mm/m": 10 ** 3, + "cm/km": 10 ** 5, + "mm/km": 10 ** 6 +}; +function singleUnitConversionFactor(from, to) { + return convertTable[`${to}/${from}`] || convertTable[`${from}/${to}`] && 1 / convertTable[`${from}/${to}`]; +} +function unitsConversionFactor(from, to) { + let factor = 100 ** // Factor is mutliplied or divided 100 for each '%' in units + (to.filter((unit) => unit === "%").length - from.filter((unit) => unit === "%").length); + [factor] = from.reduce( + ([value, toUnits], fromUnit) => { + const index = toUnits.findIndex( + (toUnit) => !!singleUnitConversionFactor(fromUnit, toUnit) + ); + const factor2 = singleUnitConversionFactor(fromUnit, toUnits[index]) || 1; + return [ + value * factor2, + [...toUnits.slice(0, index + 1), ...toUnits.slice(index + 1)] + ]; + }, + [factor, to] + ); + return factor; +} +var equivalentTable = { + "kW.h": "kWh", + "mn/h": "noeud" +}; +function areEquivalentSerializedUnit(serializedFrom, serializedTo) { + if (!serializedFrom || !serializedTo) + return false; + return serializedFrom === serializedTo || serializedFrom === equivalentTable[serializedTo] || serializedTo === equivalentTable[serializedFrom]; +} +function convertUnit(from, to, value) { + const serializedFrom = serializeUnit(from); + const serializedTo = serializeUnit(to); + if (!areEquivalentSerializedUnit(serializedFrom, serializedTo) && !areUnitConvertible(from, to)) { + throw new PublicodesError( + "EngineError", + `Impossible de convertir l'unit\xE9 '${serializedFrom}' en '${serializedTo}'`, + {} + ); + } + if (!value) { + return value; + } + if (from === void 0) { + return value; + } + const [fromSimplified, factorTo] = simplifyUnitWithValue(from || noUnit); + const [toSimplified, factorFrom] = simplifyUnitWithValue(to || noUnit); + return round( + value * factorTo / factorFrom * unitsConversionFactor( + fromSimplified.numerators, + toSimplified.numerators + ) * unitsConversionFactor( + toSimplified.denominators, + fromSimplified.denominators + ) + ); +} +var convertibleUnitClasses = unitClasses(convertTable); +function unitClasses(convertTable2) { + return Object.keys(convertTable2).reduce( + (classes, ratio) => { + const [a, b] = ratio.split("/"); + const ia = classes.findIndex((units) => units.has(a)); + const ib = classes.findIndex((units) => units.has(b)); + if (ia > -1 && ib > -1 && ia !== ib) { + throw new PublicodesError("EngineError", `Invalid ratio ${ratio}`, {}); + } else if (ia === -1 && ib === -1) { + classes.push(/* @__PURE__ */ new Set([a, b])); + } else if (ia > -1) { + classes[ia].add(b); + } else if (ib > -1) { + classes[ib].add(a); + } + return classes; + }, + [] + ); +} +function areSameClass(a, b) { + return a === b || convertibleUnitClasses.some( + (unitsClass) => unitsClass.has(a) && unitsClass.has(b) + ); +} +function round(value) { + return +value.toFixed(16); +} +function simplifyUnit(unit) { + const { numerators, denominators } = simplify(unit, areSameClass); + if (numerators.length && numerators.every((symb) => symb === "%")) { + return { numerators: ["%"], denominators }; + } + return removePercentages({ numerators, denominators }); +} +function simplifyUnitWithValue(unit, value = 1) { + const factor = unitsConversionFactor(unit.numerators, unit.denominators); + return [ + simplify(removePercentages(unit), areSameClass), + value ? round(value * factor) : value + ]; +} +var removePercentages = (unit) => ({ + numerators: unit.numerators.filter((e) => e !== "%"), + denominators: unit.denominators.filter((e) => e !== "%") +}); +function areUnitConvertible(a, b) { + if (a == null || b == null) { + return true; + } + const countByUnitClass = (units) => units.reduce((counters, unit) => { + const classIndex = convertibleUnitClasses.findIndex( + (unitClass) => unitClass.has(unit) + ); + const key = classIndex === -1 ? unit : "" + classIndex; + return { ...counters, [key]: 1 + (counters[key] ?? 0) }; + }, {}); + const [numA, denomA, numB, denomB] = [ + a.numerators, + a.denominators, + b.numerators, + b.denominators + ].map(countByUnitClass); + const uniq = (arr) => [...new Set(arr)]; + const unitClasses2 = [numA, denomA, numB, denomB].map(Object.keys).flat(); + return uniq(unitClasses2).every( + (unitClass) => (numA[unitClass] || 0) - (denomA[unitClass] || 0) === (numB[unitClass] || 0) - (denomB[unitClass] || 0) || unitClass === "%" + ); +} + +// src/mecanisms/arrondi.ts +function roundWithPrecision(n, fractionDigits) { + return +n.toFixed(fractionDigits); +} +var evaluate = function(node) { + const valeur = simplifyNodeUnit(this.evaluateNode(node.explanation.valeur)); + const nodeValue = valeur.nodeValue; + let arrondi = node.explanation.arrondi; + if (nodeValue !== false) { + arrondi = this.evaluateNode(arrondi); + if (typeof arrondi.nodeValue === "number" && !serializeUnit(arrondi.unit)?.match(/décimales?/)) { + throw new PublicodesError( + "EvaluationError", + `L'unit\xE9 ${serializeUnit( + arrondi.unit + )} de l'arrondi est inconnu. Vous devez utiliser l'unit\xE9 \u201Cd\xE9cimales\u201D`, + { dottedName: this.cache._meta.evaluationRuleStack[0] } + ); + } + } + return { + ...node, + nodeValue: typeof valeur.nodeValue !== "number" || !("nodeValue" in arrondi) ? valeur.nodeValue : typeof arrondi.nodeValue === "number" ? roundWithPrecision(valeur.nodeValue, arrondi.nodeValue) : arrondi.nodeValue === true ? roundWithPrecision(valeur.nodeValue, 0) : arrondi.nodeValue === void 0 ? void 0 : valeur.nodeValue, + explanation: { valeur, arrondi }, + missingVariables: mergeAllMissing([valeur, arrondi]), + unit: valeur.unit + }; +}; +function parseArrondi(v, context) { + const explanation = { + valeur: parse(v.valeur, context), + arrondi: parse(v.arrondi, context) + }; + return { + explanation, + nodeKind: parseArrondi.nom + }; +} +parseArrondi.nom = "arrondi"; +registerEvaluationFunction(parseArrondi.nom, evaluate); + +// src/nodeUnits.ts +function simplifyNodeUnit(node) { + if (!node.unit) { + return node; + } + const unit = simplifyUnit(node.unit); + return convertNodeToUnit(unit, node); +} +function convertNodeToUnit(to, node) { + return { + ...node, + nodeValue: node.unit && typeof node.nodeValue === "number" ? convertUnit(node.unit, to, node.nodeValue) : node.nodeValue, + unit: to + }; +} + +// src/format.ts +var numberFormatter = ({ + style, + maximumFractionDigits = 2, + minimumFractionDigits = 0, + language +}) => (value) => { + const adaptedMinimumFractionDigits = style === "currency" && maximumFractionDigits >= 2 && minimumFractionDigits === 0 && !Number.isInteger(value) ? 2 : minimumFractionDigits; + return Intl.NumberFormat(language, { + style, + currency: "EUR", + maximumFractionDigits, + minimumFractionDigits: adaptedMinimumFractionDigits + }).format(value); +}; +function formatNumber({ + maximumFractionDigits, + minimumFractionDigits, + language, + formatUnit: formatUnit2, + unit, + nodeValue +}) { + if (typeof nodeValue !== "number") { + return nodeValue; + } + const serializedUnit = unit ? serializeUnit(unit, nodeValue, formatUnit2) : void 0; + switch (serializedUnit) { + case "\u20AC": + return numberFormatter({ + style: "currency", + maximumFractionDigits, + minimumFractionDigits, + language + })(nodeValue); + case "%": + return numberFormatter({ + style: "percent", + maximumFractionDigits, + language + })(nodeValue / 100); + default: + return numberFormatter({ + style: "decimal", + minimumFractionDigits, + maximumFractionDigits, + language + })(nodeValue) + (typeof serializedUnit === "string" ? `\xA0${serializedUnit}` : ""); + } +} +function capitalise0(name) { + return name && name[0].toUpperCase() + name.slice(1); +} +var booleanTranslations = { + fr: { true: "oui", false: "non" }, + en: { true: "yes", false: "no" } +}; +function formatValue(value, { language = "fr", displayedUnit, formatUnit: formatUnit2, precision = 2 } = {}) { + let nodeValue = typeof value === "number" || typeof value === "undefined" || value === null ? value : value.nodeValue; + if (typeof nodeValue === "number" && Number.isNaN(nodeValue)) { + return "Erreur dans le calcul du nombre"; + } + if (nodeValue === void 0) { + return "Pas encore d\xE9fini"; + } + if (nodeValue === null) { + return "Non applicable"; + } + if (typeof nodeValue === "string") { + return nodeValue.replace("\\n", "\n"); + } + if (typeof nodeValue === "boolean") + return booleanTranslations[language][nodeValue]; + if (typeof nodeValue === "number") { + let unit = typeof value === "number" || typeof value === "undefined" || !("unit" in value) ? void 0 : value.unit; + if (unit) { + const simplifiedNode = simplifyNodeUnit({ + unit, + nodeValue + }); + unit = simplifiedNode.unit; + nodeValue = simplifiedNode.nodeValue; + } + return formatNumber({ + minimumFractionDigits: 0, + maximumFractionDigits: precision, + language, + formatUnit: formatUnit2, + nodeValue, + unit: displayedUnit ?? unit + }).trim(); + } + return void 0; +} + +// src/ruleUtils.ts +var ruleUtils_exports = {}; +__export(ruleUtils_exports, { + contextNameToDottedName: () => contextNameToDottedName, + cyclicDependencies: () => cyclicDependencies, + decodeRuleName: () => decodeRuleName, + disambiguateReference: () => disambiguateReference, + disambiguateReferenceNode: () => disambiguateReferenceNode, + encodeRuleName: () => encodeRuleName, + findCommonAncestor: () => findCommonAncestor, + getChildrenRules: () => getChildrenRules, + isAccessible: () => isAccessible, + isExperimental: () => isExperimental, + nameLeaf: () => nameLeaf, + ruleParent: () => ruleParent, + ruleParents: () => ruleParents, + ruleWithDedicatedDocumentationPage: () => ruleWithDedicatedDocumentationPage, + updateReferencesMapsFromReferenceNode: () => updateReferencesMapsFromReferenceNode +}); + +// src/AST/findCycles.ts +function has(obj, key) { + return obj != null && Object.prototype.hasOwnProperty.call(obj, key); +} +function constant(value) { + return function() { + return value; + }; +} +var DEFAULT_EDGE_NAME = "\0"; +var EDGE_KEY_DELIM = ""; +var incrementOrInitEntry = (map, k) => { + if (map[k]) { + map[k]++; + } else { + map[k] = 1; + } +}; +var decrementOrRemoveEntry = (map, k) => { + if (!--map[k]) { + delete map[k]; + } +}; +var edgeArgsToId = (isDirected, v_, w_, name) => { + let v = "" + v_; + let w = "" + w_; + if (!isDirected && v > w) { + const tmp = v; + v = w; + w = tmp; + } + return v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM + (name === void 0 ? DEFAULT_EDGE_NAME : name); +}; +var edgeArgsToObj = (isDirected, v_, w_, name) => { + let v = "" + v_; + let w = "" + w_; + if (!isDirected && v > w) { + const tmp = v; + v = w; + w = tmp; + } + const edgeObj = { v, w }; + if (name) { + edgeObj.name = name; + } + return edgeObj; +}; +var edgeObjToId = (isDirected, edgeObj) => { + return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name); +}; +var Graph = class { + _nodeCount = 0; + _edgeCount = 0; + _isDirected; + _label; + _defaultNodeLabelFn; + _defaultEdgeLabelFn; + _nodes; + _in; + _preds; + _out; + _sucs; + _edgeObjs; + _edgeLabels; + constructor(opts = {}) { + this._isDirected = has(opts, "directed") ? opts.directed : true; + this._label = void 0; + this._defaultNodeLabelFn = constant(void 0); + this._defaultEdgeLabelFn = constant(void 0); + this._nodes = {}; + this._in = {}; + this._preds = {}; + this._out = {}; + this._sucs = {}; + this._edgeObjs = {}; + this._edgeLabels = {}; + } + /* === Graph functions ========= */ + isDirected() { + return this._isDirected; + } + setGraph(label) { + this._label = label; + return this; + } + graph() { + return this._label; + } + /* === Node functions ========== */ + nodeCount() { + return this._nodeCount; + } + nodes() { + return Object.keys(this._nodes); + } + setNode(v, value = void 0) { + if (has(this._nodes, v)) { + if (arguments.length > 1) { + this._nodes[v] = value; + } + return this; + } + this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v); + this._in[v] = {}; + this._preds[v] = {}; + this._out[v] = {}; + this._sucs[v] = {}; + ++this._nodeCount; + return this; + } + setNodes(vs, value) { + vs.forEach((v) => { + if (value !== void 0) { + this.setNode(v, value); + } else { + this.setNode(v); + } + }); + return this; + } + node(v) { + return this._nodes[v]; + } + hasNode(v) { + return has(this._nodes, v); + } + successors(v) { + const sucsV = this._sucs[v]; + if (sucsV) { + return Object.keys(sucsV); + } + } + /* === Edge functions ========== */ + edgeCount() { + return this._edgeCount; + } + edges() { + return Object.values(this._edgeObjs); + } + setEdge(v, w, value = void 0, name = void 0) { + v = "" + v; + w = "" + w; + const e = edgeArgsToId(this._isDirected, v, w, name); + if (has(this._edgeLabels, e)) { + if (value !== void 0) { + this._edgeLabels[e] = value; + } + return this; + } + this.setNode(v); + this.setNode(w); + this._edgeLabels[e] = value !== void 0 ? value : this._defaultEdgeLabelFn(v, w, name); + const edgeObj = edgeArgsToObj(this._isDirected, v, w, name); + v = edgeObj.v; + w = edgeObj.w; + Object.freeze(edgeObj); + this._edgeObjs[e] = edgeObj; + incrementOrInitEntry(this._preds[w], v); + incrementOrInitEntry(this._sucs[v], w); + this._in[w][e] = edgeObj; + this._out[v][e] = edgeObj; + this._edgeCount++; + return this; + } + edge(v, w, name) { + const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); + return this._edgeLabels[e]; + } + hasEdge(v, w, name) { + const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); + return has(this._edgeLabels, e); + } + removeEdge(v, w, name) { + const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); + const edge = this._edgeObjs[e]; + if (edge) { + v = edge.v; + w = edge.w; + delete this._edgeLabels[e]; + delete this._edgeObjs[e]; + decrementOrRemoveEntry(this._preds[w], v); + decrementOrRemoveEntry(this._sucs[v], w); + delete this._in[w][e]; + delete this._out[v][e]; + this._edgeCount--; + } + return this; + } + outEdges(v, w = void 0) { + const outV = this._out[v]; + if (outV) { + const edges = Object.values(outV); + if (w === void 0) { + return edges; + } + return edges.filter(function(edge) { + return edge.w === w; + }); + } + } +}; +function tarjan(graph) { + let index = 0; + const stack = []; + const visited = {}; + const results = []; + function dfs(v) { + const entry = visited[v] = { + onStack: true, + lowlink: index, + index: index++ + }; + stack.push(v); + graph.successors(v).forEach(function(w) { + if (!Object.prototype.hasOwnProperty.call(visited, w)) { + dfs(w); + entry.lowlink = Math.min(entry.lowlink, visited[w].lowlink); + } else if (visited[w].onStack) { + entry.lowlink = Math.min(entry.lowlink, visited[w].index); + } + }); + if (entry.lowlink === entry.index) { + const cmpt = []; + let w; + do { + w = stack.pop(); + visited[w].onStack = false; + cmpt.push(w); + } while (v !== w); + results.push(cmpt); + } + } + graph.nodes().forEach(function(v) { + if (!Object.prototype.hasOwnProperty.call(visited, v)) { + dfs(v); + } + }); + return results; +} +function findCycles(graph) { + return tarjan(graph).filter(function(cmpt) { + return cmpt.length > 1 || cmpt.length === 1 && graph.hasEdge(cmpt[0], cmpt[0]); + }); +} + +// src/AST/graph.ts +function buildDependenciesGraph(rulesDeps) { + const g = new Graph(); + [...rulesDeps.entries()].forEach(([ruleDottedName, dependencies]) => { + dependencies.forEach((depDottedName) => { + g.setEdge(ruleDottedName, depDottedName); + }); + }); + return g; +} +function squashCycle(rulesDependenciesObject, cycle) { + function* loopFrom(i) { + let j = i; + while (true) { + yield cycle[j++ % cycle.length]; + } + } + const smallCycleStartingAt = []; + for (let i = 0; i < cycle.length; i++) { + const smallCycle = []; + let previousVertex = void 0; + for (const vertex of loopFrom(i)) { + if (previousVertex === void 0) { + smallCycle.push(vertex); + previousVertex = vertex; + } else if (rulesDependenciesObject.get(previousVertex)?.has(vertex)) { + if (smallCycle.includes(vertex)) { + smallCycle.splice(0, smallCycle.lastIndexOf(vertex)); + break; + } + smallCycle.push(vertex); + previousVertex = vertex; + } + } + smallCycleStartingAt.push(smallCycle); + } + const smallest = smallCycleStartingAt.reduce( + (minCycle, someCycle) => someCycle.length > minCycle.length ? minCycle : someCycle + ); + return smallest; +} +function cyclicDependencies(rawRules) { + const { referencesMaps } = parsePublicodes(rawRules); + const dependenciesGraph = buildDependenciesGraph(referencesMaps.referencesIn); + const cycles = findCycles(dependenciesGraph); + const reversedCycles = cycles.map((c) => c.reverse()); + const smallCycles = reversedCycles.map( + (cycle) => squashCycle(referencesMaps.referencesIn, cycle) + ); + const printableStronglyConnectedComponents = reversedCycles.map( + (c, i) => printInDotFormat(dependenciesGraph, c, smallCycles[i]) + ); + return [smallCycles, printableStronglyConnectedComponents]; +} +var edgeIsInCycle = (cycle, v, w) => { + for (let i = 0; i < cycle.length + 1; i++) { + if (v === cycle[i] && w === cycle[(i + 1) % cycle.length]) + return true; + } + return false; +}; +function printInDotFormat(dependenciesGraph, cycle, subCycleToHighlight) { + const edgesSet = /* @__PURE__ */ new Set(); + cycle.forEach((vertex) => { + dependenciesGraph.outEdges(vertex).filter(({ w }) => cycle.includes(w)).forEach(({ v, w }) => { + edgesSet.add( + `"${v}" -> "${w}"` + (edgeIsInCycle(subCycleToHighlight, v, w) ? " [color=red]" : "") + ); + }); + }); + return `digraph Cycle { + ${[...edgesSet].join(";\n ")}; +}`; +} + +// src/ruleUtils.ts +var splitName = (str) => str.split(" . "); +var joinName = (strs) => strs.join(" . "); +var nameLeaf = (dottedName) => splitName(dottedName).slice(-1)?.[0]; +var encodeRuleName = (dottedName) => dottedName?.replace(/\s\.\s/g, "/").replace(/-/g, "\u2011").replace(/\s/g, "-"); +var decodeRuleName = (dottedName) => dottedName.replace(/\//g, " . ").replace(/-/g, " ").replace(/\u2011/g, "-"); +var contextNameToDottedName = (contextName) => contextName.endsWith("$SITUATION") ? ruleParent(contextName) : contextName; +var ruleParent = (dottedName) => joinName(splitName(dottedName).slice(0, -1)); +function ruleParents(dottedName) { + return splitName(dottedName).slice(0, -1).map((_, i, arr) => joinName(arr.slice(0, i + 1))).reverse(); +} +var getChildrenRules = (parsedRules, dottedName) => { + const childrenRules = Object.keys(parsedRules).filter( + (ruleDottedName) => ruleDottedName.startsWith(dottedName) && splitName(ruleDottedName).length === splitName(dottedName).length + 1 + ); + return childrenRules; +}; +function findCommonAncestor(dottedName1, dottedName2) { + const splitDottedName1 = splitName(dottedName1); + const splitDottedName2 = splitName(dottedName2); + const index = splitDottedName1.findIndex( + (value, i) => splitDottedName2[i] !== value + ); + return index === -1 ? dottedName1 : joinName(splitDottedName1.slice(0, index)); +} +function isAccessible(rules, contextName, name) { + if (!(name in rules)) { + throw new PublicodesError( + "InternalError", + `La r\xE8gle "${name}" n'existe pas`, + { dottedName: name } + ); + } + const commonAncestor = findCommonAncestor(contextName, name); + const parents = [name, ...ruleParents(name), ""]; + const rulesToCheckForPrivacy = parents.slice( + 0, + Math.max(parents.indexOf(commonAncestor) - 1, 0) + ); + return rulesToCheckForPrivacy.every( + (dottedName) => !(dottedName in rules) || rules[dottedName].private === false + ); +} +function isExperimental(rules, name) { + if (!(name in rules)) { + throw new PublicodesError( + "InternalError", + `La r\xE8gle "${name}" n'existe pas`, + { dottedName: name } + ); + } + const parents = [name, ...ruleParents(name)]; + return parents.some( + (dottedName) => dottedName in rules && rules[dottedName].rawNode?.experimental === "oui" + ); +} +function dottedNameFromContext(context, partialName) { + return context ? context + " . " + partialName : partialName; +} +function disambiguateReference(rules, referencedFrom = "", partialName) { + const possibleContexts = ruleParents(referencedFrom); + possibleContexts.push(referencedFrom); + if (partialName.startsWith("^ . ")) { + const numberParent = partialName.match(/^(\^ \. )+/)[0].length / 4; + partialName = partialName.replace(/^(\^ \. )+/, ""); + possibleContexts.splice(-numberParent); + } + const rootContext = possibleContexts.pop(); + possibleContexts.unshift(rootContext); + possibleContexts.push(""); + const context = possibleContexts.find((context2) => { + const dottedName = dottedNameFromContext(context2, partialName); + if (!(dottedName in rules)) { + return false; + } + if (dottedName === referencedFrom) { + return false; + } + return isAccessible(rules, referencedFrom, dottedName); + }); + if (context !== void 0) { + return dottedNameFromContext(context, partialName); + } + if (referencedFrom.endsWith(partialName)) { + return referencedFrom; + } + const possibleDottedName = possibleContexts.map( + (c) => dottedNameFromContext(c, partialName) + ); + if (possibleDottedName.every((dottedName) => !(dottedName in rules))) { + throw new PublicodesError( + "SyntaxError", + `La r\xE9f\xE9rence "${partialName}" est introuvable. +V\xE9rifiez que l'orthographe et l'espace de nom sont corrects`, + { dottedName: contextNameToDottedName(referencedFrom) } + ); + } + throw new PublicodesError( + "SyntaxError", + `La r\xE8gle "${possibleDottedName.find( + (dottedName) => dottedName in rules + )}" n'est pas accessible depuis "${referencedFrom}". + Cela vient du fait qu'elle est priv\xE9e ou qu'un de ses parent est priv\xE9`, + { dottedName: contextNameToDottedName(referencedFrom) } + ); +} +function ruleWithDedicatedDocumentationPage(rule) { + return rule.virtualRule !== true && rule.type !== "groupe" && rule.type !== "texte" && rule.type !== "paragraphe" && rule.type !== "notification"; +} +function updateReferencesMapsFromReferenceNode(node, referencesMaps, ruleDottedName) { + if (node.nodeKind === "reference") { + addToMapSet( + referencesMaps.referencesIn, + ruleDottedName ?? node.contextDottedName, + node.dottedName + ); + addToMapSet( + referencesMaps.rulesThatUse, + node.dottedName, + ruleDottedName ?? node.contextDottedName + ); + } +} +function disambiguateReferenceNode(node, parsedRules) { + if (node.nodeKind !== "reference") { + return; + } + if (node.dottedName) { + return node; + } + node.dottedName = disambiguateReference( + parsedRules, + node.contextDottedName, + node.name + ); + node.title = parsedRules[node.dottedName].title; + node.acronym = parsedRules[node.dottedName].rawNode.acronyme; + return node; +} + +// src/rule.ts +function parseRule(nom, rawRule, context) { + const privateRule = rawRule.priv\u00E9 === "oui" || nom.startsWith("[priv\xE9] "); + nom = nom.replace(/^\[privé\] /, ""); + const dottedName = [context.dottedName, nom].filter(Boolean).join(" . "); + const name = nameLeaf(dottedName); + const title = capitalise0(rawRule["titre"] ?? name); + if (context.parsedRules[dottedName]) { + throw new PublicodesError( + "EvaluationError", + `La r\xE9f\xE9rence '${dottedName}' a d\xE9j\xE0 \xE9t\xE9 d\xE9finie`, + { dottedName } + ); + } + const ruleValue = {}; + for (const key in rawRule) { + if (mecanismKeys.includes(key)) { + ruleValue[key] = rawRule[key]; + } + } + if ("formule" in rawRule) { + ruleValue.valeur = rawRule.formule; + } + if (!privateRule && !dottedName.endsWith("$SITUATION")) { + ruleValue["dans la situation"] = `${dottedName} . $SITUATION`; + ruleValue["avec"] = weakCopyObj(ruleValue["avec"]) ?? {}; + const situationValue = weakCopyObj(undefinedNode); + situationValue.isNullable = rawRule["possiblement non applicable"] === "oui"; + ruleValue["avec"]["[priv\xE9] $SITUATION"] = { + valeur: situationValue + }; + if (ruleValue["par d\xE9faut"] != null) { + ruleValue["par d\xE9faut"] = { + valeur: ruleValue["par d\xE9faut"], + "variable manquante": dottedName + }; + } + } + const currentDottedNameContext = context.dottedName; + context.dottedName = dottedName; + context.parsedRules[dottedName] = void 0; + const explanation = { + valeur: parse(ruleValue, context), + // We include a list of references to the parents to implement the branch + // desactivation feature. When evaluating a rule we only need to know the + // first nullable parent, but this is something that we can't determine at + // this stage : + // - we need to run remplacements (which works on references in the ASTs + // which is why we insert these “virtual” references) + // - we need to infer unit of the rules + // + // An alternative implementation would be possible that would colocate the + // code related to branch desactivation (ie find the first nullable parent + // statically after rules parsing) + parents: ruleParents(dottedName).map( + (parent) => ({ + dottedName: parent, + nodeKind: "reference", + contextDottedName: context.dottedName + }) + ) + }; + const suggestions = {}; + if (rawRule.suggestions) { + for (const name2 in rawRule.suggestions) { + suggestions[name2] = parse(rawRule.suggestions[name2], context); + } + } + context.parsedRules[dottedName] = { + dottedName, + replacements: [ + ...parseRendNonApplicable(rawRule["rend non applicable"], context), + ...parseReplacements(rawRule.remplace, context) + ], + title, + private: privateRule, + suggestions, + nodeKind: "rule", + explanation, + rawNode: rawRule, + virtualRule: privateRule + }; + context.dottedName = currentDottedNameContext; + return context.parsedRules[dottedName]; +} +function parseRules(rules, context) { + for (const dottedName in rules) { + let rule = rules[dottedName]; + if (typeof rule === "string" || typeof rule === "number") { + rule = { valeur: `${rule}` }; + } + if (typeof rule !== "object") { + throw new PublicodesError( + "SyntaxError", + `Rule ${dottedName} is incorrectly written. Please give it a proper value.`, + { dottedName } + ); + } + const copy = rule === null ? {} : weakCopyObj(rule); + parseRule(dottedName, copy, context); + } +} +registerEvaluationFunction("rule", function evaluate2(node) { + const { ruleDisabledByItsParent, nullableParent, parentMissingVariables } = evaluateDisablingParent(this, node); + let valeurEvaluation = { + ...node.explanation.valeur, + nodeValue: null, + missingVariables: {} + }; + if (!ruleDisabledByItsParent) { + if (this.cache._meta.evaluationRuleStack.filter( + (dottedName) => dottedName === node.dottedName + ).length > 1) { + valeurEvaluation = { + nodeValue: void 0 + }; + } else { + this.cache._meta.evaluationRuleStack.unshift(node.dottedName); + valeurEvaluation = this.evaluateNode(node.explanation.valeur); + this.cache._meta.evaluationRuleStack.shift(); + } + } + valeurEvaluation.missingVariables ??= {}; + updateRuleMissingVariables(this, node, valeurEvaluation); + const evaluation = { + ...valeurEvaluation, + missingVariables: mergeMissing( + valeurEvaluation.missingVariables, + parentMissingVariables + ), + ...node, + explanation: { + parents: node.explanation.parents, + valeur: valeurEvaluation, + nullableParent, + ruleDisabledByItsParent + } + }; + return evaluation; +}); +function updateRuleMissingVariables(engine, node, valeurEvaluation) { + if (node.private === true || !isAccessible(engine.context.parsedRules, "", node.dottedName)) { + return; + } + if (valeurEvaluation.nodeValue === void 0 && !Object.keys(valeurEvaluation.missingVariables).length) { + valeurEvaluation.missingVariables[node.dottedName] = 1; + } + return; +} +function evaluateDisablingParent(engine, node) { + if (node.private) { + return { ruleDisabledByItsParent: false, parentMissingVariables: {} }; + } + const nodesTypes = engine.context.nodesTypes; + const nullableParent = node.explanation.parents.find( + (ref) => nodesTypes.get(ref)?.isNullable || nodesTypes.get(ref)?.type === "boolean" + ); + if (!nullableParent) { + return { ruleDisabledByItsParent: false, parentMissingVariables: {} }; + } + if ( + // TODO: remove this condition and the associated "parentRuleStack", cycles + // should be detected and avoided at parse time. + !engine.cache._meta.parentRuleStack.includes(node.dottedName) + ) { + engine.cache._meta.parentRuleStack.unshift(node.dottedName); + let parentIsNotApplicable = defaultNode(false); + if (nodesTypes.get(nullableParent)?.isNullable) { + parentIsNotApplicable = engine.evaluateNode({ + nodeKind: "est non applicable", + explanation: nullableParent + }); + } + if (parentIsNotApplicable.nodeValue !== true && nodesTypes.get(nullableParent)?.type === "boolean") { + parentIsNotApplicable = engine.evaluateNode({ + nodeKind: "operation", + operator: "=", + operationKind: "=", + explanation: [nullableParent, defaultNode(false)] + }); + } + engine.cache._meta.parentRuleStack.shift(); + if (parentIsNotApplicable.nodeValue === true) { + return { + ruleDisabledByItsParent: true, + parentMissingVariables: parentIsNotApplicable.missingVariables ?? {}, + nullableParent + }; + } + } + let parentMissingVariables = {}; + if (nodesTypes.get(nullableParent)?.type === "boolean") { + const parentEvaluation = engine.evaluateNode(nullableParent); + parentMissingVariables = parentEvaluation.missingVariables ?? {}; + return { + ruleDisabledByItsParent: parentEvaluation.nodeValue === false, + parentMissingVariables, + nullableParent + }; + } + return { + ruleDisabledByItsParent: false, + parentMissingVariables, + nullableParent + }; +} + +// src/mecanisms/avec.ts +function parseAvec(v, context) { + parseRules(v.avec, context); + const valeur = parse(v.valeur, context); + return valeur; +} +parseAvec.nom = "avec"; + +// src/mecanisms/trancheUtils.ts +var parseTranches = (tranches, context) => { + return tranches.map((node, i) => { + if (!node.plafond && i > tranches.length) { + throw new PublicodesError( + "SyntaxError", + `La tranche n\xB0${i} du bar\xE8me n'a pas de plafond pr\xE9cis\xE9. Seule la derni\xE8re tranche peut ne pas \xEAtre plafonn\xE9e`, + { dottedName: "" } + ); + } + return { + ...node, + ...node.taux !== void 0 ? { taux: parse(node.taux, context) } : {}, + ...node.montant !== void 0 ? { montant: parse(node.montant, context) } : {}, + plafond: "plafond" in node ? parse(node.plafond, context) : { + nodeValue: Infinity, + nodeKind: "constant", + type: "number", + isNullable: false + } + }; + }); +}; +function evaluatePlafondUntilActiveTranche({ multiplicateur, assiette, parsedTranches }) { + return parsedTranches.reduce( + ([tranches, activeTrancheFound], parsedTranche, i) => { + if (activeTrancheFound) { + return [ + [...tranches, { ...parsedTranche, isAfterActive: true }], + activeTrancheFound + ]; + } + const plafond = this.evaluateNode(parsedTranche.plafond); + const plancher = tranches[i - 1] ? tranches[i - 1].plafond : { nodeValue: 0 }; + let plafondValue = plafond.nodeValue === void 0 || multiplicateur.nodeValue === void 0 ? void 0 : plafond.nodeValue * multiplicateur.nodeValue; + try { + plafondValue = plafondValue === Infinity || plafondValue === 0 ? plafondValue : convertUnit( + inferUnit("*", [plafond.unit, multiplicateur.unit]), + assiette.unit, + plafondValue + ); + } catch (e) { + warning( + this.context.logger, + `L'unit\xE9 du plafond de la tranche n\xB0${i + 1} n'est pas compatible avec celle l'assiette`, + { dottedName: this.cache._meta.evaluationRuleStack[0] }, + e + ); + } + const plancherValue = tranches[i - 1] ? tranches[i - 1].plafondValue : 0; + const isAfterActive = plancherValue === void 0 || assiette.nodeValue === void 0 ? void 0 : plancherValue > assiette.nodeValue; + const calculationValues = [plafond, assiette, multiplicateur, plancher]; + if (calculationValues.some((node) => node.nodeValue === void 0)) { + return [ + [ + ...tranches, + { + ...parsedTranche, + plafond, + plafondValue, + plancherValue, + nodeValue: void 0, + isActive: void 0, + isAfterActive, + missingVariables: mergeAllMissing(calculationValues) + } + ], + false + ]; + } + if (!!tranches[i - 1] && !!plancherValue && plafondValue <= plancherValue) { + throw new PublicodesError( + "EvaluationError", + `Le plafond de la tranche n\xB0${i + 1} a une valeur inf\xE9rieure \xE0 celui de la tranche pr\xE9c\xE9dente`, + { dottedName: this.cache._meta.evaluationRuleStack[0] } + ); + } + const tranche = { + ...parsedTranche, + plafond, + plancherValue, + plafondValue, + isAfterActive, + isActive: assiette.nodeValue >= plancherValue && assiette.nodeValue < plafondValue + }; + return [[...tranches, tranche], tranche.isActive]; + }, + [[], false] + )[0]; +} + +// src/mecanisms/barème.ts +function parseBar\u00E8me(v, context) { + const explanation = { + assiette: parse(v.assiette, context), + multiplicateur: v.multiplicateur ? parse(v.multiplicateur, context) : defaultNode(1), + tranches: parseTranches(v.tranches, context) + }; + return { + explanation, + nodeKind: "bar\xE8me" + }; +} +function evaluateBar\u00E8me(tranches, assiette, evaluate15) { + return tranches.map((tranche) => { + if (tranche.isAfterActive) { + return { ...tranche, nodeValue: 0 }; + } + const taux = evaluate15(tranche.taux); + const missingVariables = mergeAllMissing([taux, tranche]); + if ([ + assiette.nodeValue, + taux.nodeValue, + tranche.plafondValue, + tranche.plancherValue + ].some((value) => value === void 0)) { + return { + ...tranche, + taux, + nodeValue: void 0, + missingVariables + }; + } + return { + ...tranche, + taux, + ..."unit" in assiette && { unit: assiette.unit }, + nodeValue: (Math.min(assiette.nodeValue, tranche.plafondValue) - tranche.plancherValue) * convertUnit(taux.unit, parseUnit(""), taux.nodeValue), + missingVariables + }; + }); +} +var evaluate3 = function(node) { + const evaluate15 = this.evaluateNode.bind(this); + const assiette = this.evaluateNode( + node.explanation.assiette + ); + const multiplicateur = this.evaluateNode(node.explanation.multiplicateur); + if (multiplicateur.nodeValue === 0) { + throw new PublicodesError( + "EvaluationError", + `Le multiplicateur ne peut pas \xEAtre nul`, + { dottedName: this.cache._meta.evaluationRuleStack[0] } + ); + } + let tranches = node.explanation.tranches; + let nodeValue = assiette.nodeValue; + if (![0, void 0, null].includes(assiette.nodeValue)) { + tranches = evaluateBar\u00E8me( + evaluatePlafondUntilActiveTranche.call(this, { + parsedTranches: node.explanation.tranches, + assiette, + multiplicateur + }), + assiette, + evaluate15 + ); + nodeValue = tranches.reduce( + (value, { nodeValue: nodeValue2 }) => nodeValue2 == void 0 ? void 0 : value + nodeValue2, + 0 + ); + } + return { + ...node, + nodeValue, + missingVariables: mergeAllMissing([assiette, multiplicateur, ...tranches]), + explanation: { + assiette, + multiplicateur, + tranches + }, + unit: assiette.unit + }; +}; +registerEvaluationFunction("bar\xE8me", evaluate3); + +// src/mecanisms/condition.ts +var evaluate4 = function(node) { + let evaluation; + const condition = this.evaluateNode(node.explanation.si); + let alors = node.explanation.alors; + let sinon = node.explanation.sinon; + if ("unit" in condition) { + throw new PublicodesError( + "EvaluationError", + "La condition doit \xEAtre de type bool\xE9en", + { dottedName: this.cache._meta.evaluationRuleStack[0] } + ); + } + if (condition.nodeValue === true) { + alors = this.evaluateNode(node.explanation.alors); + alors.isActive = true; + evaluation = alors; + } else if (condition.nodeValue === false) { + sinon = this.evaluateNode(node.explanation.sinon); + evaluation = sinon; + } else if (condition.nodeValue === null) { + evaluation = condition; + } else if (condition.nodeValue === void 0) { + sinon = this.evaluateNode(node.explanation.sinon); + alors = this.evaluateNode(node.explanation.alors); + evaluation = { + ...condition, + missingVariables: mergeAllMissing([sinon, alors]) + }; + } else { + throw new PublicodesError( + "EvaluationError", + "La condition doit \xEAtre de type bool\xE9en", + { dottedName: this.cache._meta.evaluationRuleStack[0] } + ); + } + const unit = evaluation.unit ?? alors.unit; + return { + nodeValue: evaluation.nodeValue, + missingVariables: mergeMissing( + bonus(condition.missingVariables), + evaluation.missingVariables + ), + ...unit != void 0 ? { unit } : {}, + ...node, + explanation: { si: condition, alors, sinon } + }; +}; +function parseCondition(v, context) { + const explanation = { + si: parse(v.si, context), + alors: parse(v.alors, context), + sinon: parse(v.sinon, context) + }; + return { + explanation, + nodeKind: "condition" + }; +} +parseCondition.nom = "condition"; +registerEvaluationFunction("condition", evaluate4); + +// src/mecanisms/contexte.ts +function parseMecanismContexte(v, context) { + const contexte = Object.keys(v.contexte).map((dottedName) => [ + parse(dottedName, context), + parse(v.contexte[dottedName], context) + ]); + const node = parse(v.valeur, context); + return { + explanation: { + valeur: node, + contexte, + subEngineId: context.subEngineIncrementingNumber++ + }, + nodeKind: parseMecanismContexte.nom + }; +} +parseMecanismContexte.nom = "contexte"; +var evaluateContexte = function(node) { + const amendedSituation = Object.fromEntries( + node.explanation.contexte.filter(([originRule, replacement]) => { + const originRuleEvaluation = this.evaluateNode(originRule); + const replacementEvaluation = this.evaluateNode(replacement); + return originRuleEvaluation.nodeValue !== replacementEvaluation.nodeValue || serializeUnit(originRuleEvaluation.unit) !== serializeUnit(replacementEvaluation.unit); + }).map( + ([originRule, replacement]) => [originRule.dottedName, replacement] + ) + ); + if (this.cache._meta.currentContexteSituation === JSON.stringify(amendedSituation)) { + return { + ...notApplicableNode, + ...node + }; + } + const engine = this.shallowCopy(); + engine.subEngineId = node.explanation.subEngineId; + this.subEngines[node.explanation.subEngineId] = engine; + if (Object.keys(amendedSituation).length) { + engine.setSituation(amendedSituation, { + keepPreviousSituation: true + }); + Object.entries(amendedSituation).forEach(([originDottedName, value]) => { + const evaluation = this.cache.nodes.get(value); + if (!evaluation) { + throw new PublicodesError( + "InternalError", + "The situation should have already been evaluated", + { + dottedName: this.context.dottedName + } + ); + } + const originRule = engine.context.parsedRules[originDottedName + " . $SITUATION"]; + if (!originRule?.explanation.valeur) { + throw new PublicodesError( + "InternalError", + "The origin rule should be defined", + { + dottedName: this.context.dottedName + } + ); + } + engine.cache.nodes.set(originRule.explanation.valeur, evaluation); + }); + } + engine.cache._meta.currentContexteSituation = JSON.stringify(amendedSituation); + const evaluatedNode = engine.evaluateNode(node.explanation.valeur); + return { + ...node, + nodeValue: evaluatedNode.nodeValue, + explanation: { + ...node.explanation, + valeur: evaluatedNode + }, + missingVariables: evaluatedNode.missingVariables, + ..."unit" in evaluatedNode && { unit: evaluatedNode.unit } + }; +}; +registerEvaluationFunction("contexte", evaluateContexte); + +// src/date.ts +function normalizeDateString(dateString) { + let [day, month, year] = dateString.split("/"); + if (!year) { + ; + [day, month, year] = ["01", day, month]; + } + return normalizeDate(+year, +month, +day); +} +var pad = (n) => +n < 10 ? `0${n}` : "" + n; +function normalizeDate(year, month, day) { + const date2 = new Date(+year, +month - 1, +day); + if (!+date2 || date2.getDate() !== +day) { + throw new PublicodesError( + "SyntaxError", + `La date ${day}/${month}/${year} n'est pas valide`, + { dottedName: "" } + ); + } + return `${pad(day)}/${pad(month)}/${pad(year)}`; +} +function convertToDate(value) { + const [day, month, year] = normalizeDateString(value).split("/"); + const result = new Date(+year, +month - 1, +day); + result.setMinutes(result.getMinutes() - result.getTimezoneOffset()); + return result; +} +function convertToString(date2) { + return normalizeDate(date2.getFullYear(), date2.getMonth() + 1, date2.getDate()); +} +function getYear(date2) { + return +date2.slice(-4); +} +function getTrimestreCivil(date2) { + const [, month, year] = date2.split("/"); + const trimester = Math.floor((Number.parseInt(month, 10) - 1) / 3); + const startingMonth = 3 * trimester + 1; + return `01/${startingMonth.toString().padStart(2, "0")}/${year}`; +} +function getDifferenceInDays(from, to) { + const millisecondsPerDay = 1e3 * 60 * 60 * 24; + return (convertToDate(to).getTime() - convertToDate(from).getTime()) / millisecondsPerDay; +} +function getDifferenceInMonths(from, to) { + const [dayFrom, monthFrom, yearFrom] = from.split("/").map((x) => +x); + const [dayTo, monthTo, yearTo] = to.split("/").map((x) => +x); + const numberOfFullMonth = monthTo - monthFrom + 12 * (yearTo - yearFrom); + const numDayMonthFrom = new Date(yearFrom, monthFrom, 0).getDate(); + const numDayMonthTo = new Date(yearTo, monthTo, 0).getDate(); + const prorataMonthFrom = (dayFrom - 1) / numDayMonthFrom; + const prorataMonthTo = dayTo / numDayMonthTo; + return numberOfFullMonth - prorataMonthFrom + prorataMonthTo; +} +function getDifferenceInYears(from, to) { + const differenceInDays = getDifferenceInDays(from, to); + const isLeapYear = (year) => year % 4 === 0 && year % 100 !== 0 || year % 400 === 0; + const after1stMarch = (date2) => date2 >= new Date(date2.getFullYear(), 2, 1); + const fromDate = convertToDate(from); + const toDate = convertToDate(to); + const fromYear = fromDate.getFullYear() + (after1stMarch(fromDate) ? 1 : 0); + const toYear = toDate.getFullYear() + (after1stMarch(fromDate) ? 0 : -1); + const leapYearsCount = Array.from( + { length: toYear - fromYear + 1 }, + (_, i) => fromYear + i + ).filter(isLeapYear).length; + return (differenceInDays - leapYearsCount) / 365; +} +function getDifferenceInTrimestreCivils(from, to) { + return Math.floor( + getDifferenceInMonths(getTrimestreCivil(from), getTrimestreCivil(to)) / 3 + ) + 1; +} +function getDifferenceInYearsCivil(from, to) { + const fromYear = "01/" + getYear(from); + const toYear = "01/" + getYear(to); + return Math.floor(getDifferenceInYears(fromYear, toYear)) + 1; +} + +// src/mecanisms/durée.ts +var evaluate5 = function(node) { + const fromNode = this.evaluateNode(node.explanation.depuis); + const toNode = this.evaluateNode(node.explanation["jusqu'\xE0"]); + const from = fromNode.nodeValue; + const to = toNode.nodeValue; + let nodeValue; + if (from === null || to === null) { + nodeValue = null; + } else if (from === void 0 || to === void 0) { + nodeValue = void 0; + } else { + switch (node.unit.numerators[0]) { + case "jour": + nodeValue = getDifferenceInDays(from, to); + break; + case "mois": + nodeValue = getDifferenceInMonths(from, to); + break; + case "an": + nodeValue = getDifferenceInYears(from, to); + break; + case "trimestre": + nodeValue = getDifferenceInMonths(from, to) / 3; + break; + case "trimestre civil": + nodeValue = getDifferenceInTrimestreCivils(from, to); + break; + case "ann\xE9e civile": + nodeValue = getDifferenceInYearsCivil(from, to); + break; + } + } + if (typeof nodeValue === "number") { + nodeValue = Math.max(0, nodeValue); + } + return { + ...node, + missingVariables: mergeAllMissing([fromNode, toNode]), + nodeValue, + explanation: { + depuis: fromNode, + "jusqu'\xE0": toNode + } + }; +}; +var today = defaultNode(convertToString(/* @__PURE__ */ new Date())); +var dur_e_default = (v, context) => { + const explanation = { + depuis: parse(v.depuis ?? today, context), + "jusqu'\xE0": parse(v["jusqu'\xE0"] ?? today, context) + }; + const unit = v.unit\u00E9 ? parseUnit(v.unit\u00E9) : parseUnit("jour"); + if (unit.denominators.length > 0 || unit.numerators.length > 1 || !possibleUnit.includes(unit.numerators[0])) { + throw new PublicodesError( + "SyntaxError", + `Seules les unit\xE9s suivantes sont accept\xE9es pour une dur\xE9e : ${possibleUnit.join( + ", " + )}. + L'unit\xE9 fournie est: ${unit.numerators[0]}`, + { + dottedName: context.dottedName + } + ); + } + return { + explanation, + unit, + nodeKind: "dur\xE9e" + }; +}; +registerEvaluationFunction("dur\xE9e", evaluate5); +var possibleUnit = [ + "mois", + "jour", + "an", + "trimestre", + "trimestre civil", + "ann\xE9e civile" +]; + +// src/mecanisms/est.ts +function parseEstNonD\u00E9fini(v, context) { + const explanation = parse(v, context); + return { + explanation, + nodeKind: "est non d\xE9fini" + }; +} +parseEstNonD\u00E9fini.nom = "est non d\xE9fini"; +var parseEstD\u00E9fini = createParseInlinedMecanism( + "est d\xE9fini", + { + valeur: {} + }, + { + "=": [{ "est non d\xE9fini": "valeur" }, "non"] + } +); +var parseEstApplicable = createParseInlinedMecanism( + "est applicable", + { + valeur: {} + }, + { + "=": [{ "est non applicable": "valeur" }, "non"] + } +); +var evaluate6 = function(node) { + const valeur = this.evaluateNode(node.explanation); + let nodeValue = false; + if (valeur.nodeValue === void 0) { + nodeValue = true; + } + return { + ...node, + nodeValue, + missingVariables: valeur.missingVariables, + explanation: valeur + }; +}; +registerEvaluationFunction("est non d\xE9fini", evaluate6); + +// src/mecanisms/est-non-applicable.ts +function parseEstNonApplicable(v, context) { + const explanation = parse(v, context); + return { + explanation, + nodeKind: "est non applicable" + }; +} +parseEstNonApplicable.nom = "est non applicable"; +var isNotApplicable = (node) => { + return { + nodeKind: "est non applicable", + explanation: node + }; +}; +var evaluateIsNotApplicable = function(node) { + const valeur = node.explanation; + if (this.context.nodesTypes.get(valeur)?.isNullable === false && valeur.nodeKind !== "rule" && valeur.nodeKind !== "reference") { + return { ...node, nodeValue: false, missingVariables: {} }; + } + if (this.cache.nodes.has(valeur) && this.cache.nodes.get(valeur) !== void 0) { + return { + ...node, + nodeValue: this.cache.nodes.get(valeur)?.nodeValue === null, + missingVariables: this.cache.nodes.get(valeur)?.missingVariables ?? {} + }; + } + switch (valeur.nodeKind) { + case "rule": { + const { ruleDisabledByItsParent, parentMissingVariables } = evaluateDisablingParent(this, valeur); + if (ruleDisabledByItsParent) { + return { + ...node, + nodeValue: true, + missingVariables: parentMissingVariables + }; + } + const isNotApplicableEvaluation = this.evaluateNode( + isNotApplicable(valeur.explanation.valeur) + ); + const missingVariables = mergeMissing( + parentMissingVariables, + isNotApplicableEvaluation.missingVariables + ); + if (isNotApplicableEvaluation.nodeValue === false && this.context.nodesTypes.get( + this.context.parsedRules[`${valeur.dottedName} . $SITUATION`] + )?.isNullable && !Object.keys(isNotApplicableEvaluation.missingVariables).length) { + missingVariables[valeur.dottedName] = 1; + } + return { + ...node, + nodeValue: isNotApplicableEvaluation.nodeValue, + missingVariables + }; + } + case "reference": + return { + ...this.evaluateNode( + isNotApplicable(this.context.parsedRules[valeur.dottedName]) + ), + ...node + }; + case "condition": + return { + ...this.evaluateNode({ + ...valeur, + explanation: { + si: valeur.explanation.si, + alors: isNotApplicable(valeur.explanation.alors), + sinon: isNotApplicable(valeur.explanation.sinon) + } + }), + ...node + }; + } + const evaluatedValeur = this.evaluateNode(valeur); + return { + ...node, + nodeValue: evaluatedValeur.nodeValue === void 0 ? void 0 : evaluatedValeur.nodeValue === null, + missingVariables: evaluatedValeur.missingVariables + }; +}; +registerEvaluationFunction("est non applicable", evaluateIsNotApplicable); + +// src/mecanisms/grille.ts +function parseGrille(v, context) { + const explanation = { + assiette: parse(v.assiette, context), + multiplicateur: v.multiplicateur ? parse(v.multiplicateur, context) : defaultNode(1), + tranches: parseTranches(v.tranches, context) + }; + return { + explanation, + nodeKind: "grille" + }; +} +var evaluate7 = function(node) { + const evaluate15 = this.evaluateNode.bind(this); + const assiette = this.evaluateNode(node.explanation.assiette); + const multiplicateur = this.evaluateNode(node.explanation.multiplicateur); + if (multiplicateur.nodeValue === 0) { + throw new PublicodesError( + "EvaluationError", + `Le multiplicateur ne peut pas \xEAtre nul`, + { + dottedName: this.cache._meta.evaluationRuleStack[0] + } + ); + } + const tranches = evaluatePlafondUntilActiveTranche.call(this, { + parsedTranches: node.explanation.tranches, + assiette, + multiplicateur + }).map((tranche) => { + if (tranche.isActive === false) { + return tranche; + } + const montant = evaluate15(tranche.montant); + return { + ...tranche, + montant, + nodeValue: montant.nodeValue, + unit: montant.unit, + missingVariables: mergeAllMissing([montant, tranche]) + }; + }); + let activeTranches; + const activeTranche = tranches.find((tranche) => tranche.isActive); + if (activeTranche) { + activeTranches = [activeTranche]; + } else if (tranches[tranches.length - 1].isAfterActive === false) { + activeTranches = [{ nodeValue: false }]; + } else { + activeTranches = tranches.filter( + (tranche) => tranche.isActive === void 0 + ); + } + const nodeValue = !activeTranches[0] ? false : activeTranches[0].isActive === void 0 ? void 0 : activeTranches[0].nodeValue; + return { + ...node, + nodeValue, + missingVariables: mergeAllMissing([ + assiette, + multiplicateur, + ...activeTranches + ]), + explanation: { + ...node.explanation, + assiette, + multiplicateur, + tranches + }, + unit: activeTranches[0]?.unit ?? void 0 + }; +}; +registerEvaluationFunction("grille", evaluate7); + +// src/uniroot.ts +function uniroot(func, lowerLimit, upperLimit, errorTol = 0, maxIter = 100, acceptableErrorTol = 0) { + let a = lowerLimit, b = upperLimit, c = a, fa = func(a), fb = func(b), fc = fa, actualTolerance, newStep, prevStep, p, q, fallback = void 0; + while (maxIter-- > 0) { + prevStep = b - a; + if (Math.abs(fc) < Math.abs(fb)) { + ; + a = b, b = c, c = a; + fa = fb, fb = fc, fc = fa; + } + actualTolerance = 1e-15 * Math.abs(b) + errorTol / 2; + newStep = (c - b) / 2; + if (Math.abs(newStep) <= actualTolerance || fb === 0) { + return b; + } + if (Math.abs(prevStep) >= actualTolerance && Math.abs(fa) > Math.abs(fb)) { + let t1, t2; + const cb = c - b; + if (a === c) { + t1 = fb / fa; + p = cb * t1; + q = 1 - t1; + } else { + ; + q = fa / fc, t1 = fb / fc, t2 = fb / fa; + p = t2 * (cb * q * (q - t1) - (b - a) * (t1 - 1)); + q = (q - 1) * (t1 - 1) * (t2 - 1); + } + if (p > 0) { + q = -q; + } else { + p = -p; + } + if (p < 0.75 * cb * q - Math.abs(actualTolerance * q) / 2 && p < Math.abs(prevStep * q / 2)) { + newStep = p / q; + } + } + if (Math.abs(newStep) < actualTolerance) { + newStep = newStep > 0 ? actualTolerance : -actualTolerance; + } + ; + a = b, fa = fb; + b += newStep, fb = func(b); + if (fb > 0 && fc > 0 || fb < 0 && fc < 0) { + ; + c = a, fc = fa; + } + if (Math.abs(fb) < errorTol) { + return b; + } + if (Math.abs(fb) < acceptableErrorTol) { + fallback = b; + } + } + return fallback; +} + +// src/mecanisms/inversion.ts +var evaluateInversion = function(node) { + const inversionEngine = this.shallowCopy(); + if (this.cache._meta.evaluationRuleStack.slice(1).includes(node.explanation.ruleToInverse)) { + return { + ...undefinedNumberNode, + ...node + }; + } + inversionEngine.cache._meta.parentRuleStack = [ + ...this.cache._meta.parentRuleStack + ]; + inversionEngine.cache._meta.evaluationRuleStack = [ + ...this.cache._meta.evaluationRuleStack + ]; + const inversionGoal = node.explanation.inversionCandidates.find( + (candidate) => { + if (this.cache._meta.evaluationRuleStack.includes(candidate.dottedName)) { + return false; + } + const evaluation = inversionEngine.evaluateNode( + inversionEngine.context.parsedRules[`${candidate.dottedName} . $SITUATION`] + ); + return typeof evaluation.nodeValue === "number" && !(candidate.dottedName in evaluation.missingVariables); + } + ); + if (inversionGoal === void 0) { + return { + ...node, + nodeValue: void 0, + missingVariables: { + ...Object.fromEntries( + node.explanation.inversionCandidates.map((candidate) => [ + candidate.dottedName, + 1 + ]) + ), + [node.explanation.ruleToInverse]: 1 + } + }; + } + const evaluatedInversionGoal = inversionEngine.evaluateNode(inversionGoal); + let numberOfIteration = 0; + inversionEngine.setSituation( + { + [inversionGoal.dottedName]: undefinedNumberNode + }, + { keepPreviousSituation: true } + ); + inversionEngine.cache.traversedVariablesStack = this.cache.traversedVariablesStack ? [] : void 0; + let lastEvaluation; + const evaluateWithValue = (n) => { + numberOfIteration++; + inversionEngine.setSituation( + { + [node.explanation.ruleToInverse]: { + nodeValue: n, + nodeKind: "constant", + type: "number", + unit: evaluatedInversionGoal.unit + } + }, + { keepPreviousSituation: true } + ); + inversionEngine.cache.traversedVariablesStack = this.cache.traversedVariablesStack ? [] : void 0; + lastEvaluation = inversionEngine.evaluateNode(inversionGoal); + return lastEvaluation; + }; + const goal = evaluatedInversionGoal.nodeValue; + let nodeValue = void 0; + const x1 = goal; + const y1Node = evaluateWithValue(x1); + const y1 = y1Node.nodeValue; + const coeff = y1 > goal ? 0.9 : 1.2; + const x2 = y1 !== void 0 ? x1 * goal * coeff / y1 : 2e3; + const y2Node = evaluateWithValue(x2); + const y2 = y2Node.nodeValue; + const maxIterations = this.context.inversionMaxIterations ?? 10; + if (y1 !== void 0 || y2 !== void 0) { + const test = (x) => { + const y = x === x1 ? y1 : x === x2 ? y2 : evaluateWithValue(x).nodeValue; + return y - goal; + }; + const defaultMin = -1e6; + const defaultMax = 1e8; + const nearestBelowGoal = y2 !== void 0 && y2 < goal && (y2 > y1 || y1 > goal) ? x2 : y1 !== void 0 && y1 < goal && (y1 > y2 || y2 > goal) ? x1 : defaultMin; + const nearestAboveGoal = y2 !== void 0 && y2 > goal && (y2 < y1 || y1 < goal) ? x2 : y1 !== void 0 && y1 > goal && (y1 < y2 || y2 < goal) ? x1 : defaultMax; + nodeValue = uniroot( + test, + nearestBelowGoal, + nearestAboveGoal, + 0.1, + maxIterations, + 1 + ); + } + if (nodeValue == void 0) { + this.cache.inversionFail = true; + } + if (this.cache.traversedVariablesStack) { + const traversedVariablesStack = this.cache.traversedVariablesStack[0]; + if (traversedVariablesStack) { + ; + (lastEvaluation.traversedVariables ?? []).forEach( + (v) => traversedVariablesStack.add(v) + ); + } + } + return { + ...node, + nodeValue, + unit: evaluatedInversionGoal.unit, + explanation: { + ...node.explanation, + inversionGoal, + numberOfIteration, + inversionFail: this.cache.inversionFail + }, + missingVariables: lastEvaluation.missingVariables + }; +}; +var mecanismInversion = (v, context) => { + let avec = typeof v === "object" && "avec" in v ? v.avec : v; + if (v === null) { + throw new PublicodesError( + "SyntaxError", + "Il manque les r\xE8gles avec laquelle effectuer le calcul d'inversion dans le m\xE9canisme `inversion num\xE9rique`", + { dottedName: context.dottedName } + ); + } + if (!Array.isArray(avec)) { + avec = [avec]; + } + return { + explanation: { + ruleToInverse: context.dottedName, + inversionCandidates: avec.map((node) => ({ + ...parse(node, context) + })) + }, + nodeKind: "inversion" + }; +}; +registerEvaluationFunction("inversion", evaluateInversion); + +// src/mecanisms/max-min.ts +var parseMaximumDe = createParseInlinedMecanismWithArray( + "le maximum de", + { + valeur: { type: "liste" } + }, + ({ valeur }) => valeur.reduce( + (acc, value) => ({ + condition: { + si: { + "est non applicable": "$INTERNAL valeur" + }, + alors: "$INTERNAL acc", + sinon: { + condition: { + si: { + ou: [ + { "est non applicable": "$INTERNAL acc" }, + { ">": ["$INTERNAL valeur", "$INTERNAL acc"] } + ] + }, + alors: "$INTERNAL valeur", + sinon: "$INTERNAL acc" + } + } + }, + avec: { + "[priv\xE9] $INTERNAL valeur": { valeur: value }, + "[priv\xE9] $INTERNAL acc": { valeur: acc } + } + }), + notApplicableNode + ) +); +var parseMinimumDe = createParseInlinedMecanismWithArray( + "le minimum de", + { + valeur: { type: "liste" } + }, + ({ valeur }) => valeur.reduce( + (acc, value) => ({ + condition: { + si: { + "est non applicable": "$INTERNAL valeur" + }, + alors: "$INTERNAL acc", + sinon: { + condition: { + si: { + ou: [ + { "est non applicable": "$INTERNAL acc" }, + { "<": ["$INTERNAL valeur", "$INTERNAL acc"] } + ] + }, + alors: "$INTERNAL valeur", + sinon: "$INTERNAL acc" + } + } + }, + avec: { + "[priv\xE9] $INTERNAL valeur": { valeur: value }, + "[priv\xE9] $INTERNAL acc": { valeur: acc } + } + }), + notApplicableNode + ) +); + +// src/mecanisms/somme.tsx +function reduceToSumNodes(valeurs) { + return valeurs.reverse().reduce((acc, value) => ({ "+": [value, acc] }), notApplicableNode); +} +var somme_default = createParseInlinedMecanismWithArray( + "somme", + { + valeur: { type: "liste" } + }, + ({ valeur }) => reduceToSumNodes([...valeur]) +); + +// src/mecanisms/moyenne.ts +var moyenne_default = createParseInlinedMecanismWithArray( + "moyenne", + { + valeur: { type: "liste" } + }, + ({ valeur }) => { + const valeurs = [...valeur]; + return { + "/": [ + reduceToSumNodes(valeurs), + reduceToSumNodes(valeurs.map(oneIfApplicable)) + ] + }; + } +); +function oneIfApplicable(exp) { + return { + "applicable si": { "est applicable": exp }, + valeur: 1 + }; +} + +// src/mecanisms/non-applicable.ts +var non_applicable_default = createParseInlinedMecanism( + "non applicable si", + { + "non applicable si": {}, + valeur: {} + }, + { + condition: { + si: "non applicable si = non", + alors: "valeur", + sinon: notApplicableNode + } + } +); + +// src/mecanisms/one-possibility.ts +var mecanismOnePossibility = (v, context) => { + if (Array.isArray(v)) { + v = { + possibilit\u00E9s: v + }; + } + return { + ...v, + explanation: v.possibilit\u00E9s.map((p) => parse(p, context)), + context: context.dottedName, + nodeKind: "une possibilit\xE9" + }; +}; +registerEvaluationFunction("une possibilit\xE9", (node) => ({ + ...node, + missingVariables: { [node.context]: 1 }, + nodeValue: void 0 +})); + +// src/mecanisms/operation.ts +var knownOperations = { + "*": [(a, b) => a * b, "\xD7"], + "/": [(a, b) => a / b, "\u2215"], + "+": [(a, b) => a + b], + "-": [(a, b) => a - b, "\u2212"], + "<": [(a, b) => a < b], + "<=": [(a, b) => a <= b, "\u2264"], + ">": [(a, b) => a > b], + ">=": [(a, b) => a >= b, "\u2265"], + "=": [(a, b) => (a ?? false) === (b ?? false)], + "!=": [(a, b) => (a ?? false) !== (b ?? false), "\u2260"], + et: [(a, b) => (a ?? false) && (b ?? false)], + ou: [(a, b) => (a ?? false) || (b ?? false)] +}; +var parseOperation = (k, symbol) => (v, context) => { + const explanation = v.map((node) => parse(node, context)); + return { + ...v, + nodeKind: "operation", + operationKind: k, + operator: symbol || k, + explanation + }; +}; +var evaluate8 = function(node) { + let node1 = this.evaluateNode(node.explanation[0]); + let evaluatedNode = { + ...node, + missingVariables: {} + }; + if (node1.nodeValue === null && ["<", ">", "<=", ">=", "/", "*", "-", "et"].includes( + node.operationKind + ) || node1.nodeValue === 0 && ["/", "*"].includes(node.operationKind) || node1.nodeValue === false && node.operationKind === "et" || node1.nodeValue === true && node.operationKind === "ou") { + return { + ...evaluatedNode, + nodeValue: node.operationKind === "et" ? false : node1.nodeValue, + missingVariables: node1.missingVariables + }; + } + let node2 = this.evaluateNode(node.explanation[1]); + evaluatedNode.explanation = [node1, node2]; + if (node.operationKind === "/" && node2.nodeValue === 0) { + throw new PublicodesError("EvaluationError", `Division by zero`, { + dottedName: this.cache._meta.evaluationRuleStack[0] + }); + } + if (node2.nodeValue === null && ["<", ">", "<=", ">=", "/", "*", "et"].includes(node.operationKind) || node2.nodeValue === 0 && ["*"].includes(node.operationKind) || node2.nodeValue === false && node.operationKind === "et" || node2.nodeValue === true && node.operationKind === "ou") { + return { + ...evaluatedNode, + nodeValue: node.operationKind === "et" ? false : node2.nodeValue, + missingVariables: node2.missingVariables + }; + } + evaluatedNode.missingVariables = mergeAllMissing([node1, node2]); + if (node1.nodeValue === void 0 || node2.nodeValue === void 0) { + evaluatedNode = { + ...evaluatedNode, + nodeValue: void 0 + }; + } + const isAdditionOrSubstractionWithPercentage = ["+", "-"].includes(node.operationKind) && serializeUnit(node2.unit) === "%" && serializeUnit(node1.unit) !== "%"; + if (!("nodeValue" in evaluatedNode) && !["/", "*"].includes(node.operationKind) && !isAdditionOrSubstractionWithPercentage) { + try { + if (node1.unit && "unit" in node2) { + node2 = convertNodeToUnit(node1.unit, node2); + } else if (node2.unit) { + node1 = convertNodeToUnit(node2.unit, node1); + } + } catch (e) { + warning( + this.context.logger, + `Dans l'expression '${node.operationKind}', la partie gauche (unit\xE9: ${serializeUnit( + node1.unit + )}) n'est pas compatible avec la partie droite (unit\xE9: ${serializeUnit( + node2.unit + )})`, + { dottedName: this.cache._meta.evaluationRuleStack[0] }, + e + ); + } + } + const operatorFunction = knownOperations[node.operationKind][0]; + const a = node1.nodeValue; + const b = node2.nodeValue; + evaluatedNode.nodeValue = "nodeValue" in evaluatedNode ? evaluatedNode.nodeValue : ["<", ">", "<=", ">=", "*", "/"].includes(node.operationKind) && node2.nodeValue === null ? null : [a, b].every( + (value) => typeof value === "string" && value.match?.(/^[\d]{2}\/[\d]{2}\/[\d]{4}$/) + ) ? ( + // We convert the date objects to timestamps to support comparison with the "===" operator: + // new Date('2020-01-01') !== new Date('2020-01-01') + operatorFunction( + convertToDate(a).getTime(), + convertToDate(b).getTime() + ) + ) : operatorFunction(a, b); + if (node.operationKind === "*" && inferUnit("*", [node1.unit, node2.unit])?.numerators.includes("%")) { + const unit = inferUnit("*", [node1.unit, node2.unit]); + const nodeValue = evaluatedNode.nodeValue; + return { + ...evaluatedNode, + nodeValue: typeof nodeValue === "number" ? nodeValue / 100 : nodeValue, + unit: inferUnit("*", [unit, { numerators: [], denominators: ["%"] }]) + }; + } + if (isAdditionOrSubstractionWithPercentage) { + const unit = inferUnit("*", [node1.unit, node2.unit]); + return { + ...evaluatedNode, + nodeValue: typeof node1.nodeValue === "number" && typeof node2.nodeValue === "number" ? node1.nodeValue * (1 + node2.nodeValue / 100 * (node.operationKind === "-" ? -1 : 1)) : evaluatedNode.nodeValue, + unit: inferUnit("*", [unit, { numerators: [], denominators: ["%"] }]) + }; + } + if (node.operationKind === "*" || node.operationKind === "/" || node.operationKind === "-" || node.operationKind === "+") { + return { + ...evaluatedNode, + unit: inferUnit(node.operationKind, [node1.unit, node2.unit]) + }; + } + return evaluatedNode; +}; +registerEvaluationFunction("operation", evaluate8); +var operationDispatch = Object.fromEntries( + Object.entries(knownOperations).map(([k, [, symbol]]) => [ + k, + parseOperation(k, symbol) + ]) +); +var operation_default = operationDispatch; + +// src/mecanisms/parDéfaut.ts +var parD_faut_default = createParseInlinedMecanism( + "par d\xE9faut", + { + "par d\xE9faut": {}, + valeur: {} + }, + { + condition: { + si: { "est non d\xE9fini": "valeur" }, + alors: "par d\xE9faut", + sinon: "valeur" + } + } +); + +// src/mecanisms/plafond.ts +var plafond_default = createParseInlinedMecanism( + "plafond", + { + plafond: {}, + valeur: {} + }, + { + condition: { + si: { et: ["plafond != non", "valeur > plafond"] }, + alors: "plafond", + sinon: "valeur" + } + } +); + +// src/mecanisms/plancher.ts +var plancher_default = createParseInlinedMecanism( + "plancher", + { + plancher: {}, + valeur: {} + }, + { + condition: { + si: { et: ["plancher != non", "valeur < plancher"] }, + alors: "plancher", + sinon: "valeur" + } + } +); + +// src/mecanisms/product.ts +function reduceToProduitNodes(valeurs) { + return valeurs.reduce((acc, value) => ({ "*": [value, acc] }), defaultNode(1)); +} +var product_default = createParseInlinedMecanismWithArray( + "produit", + { + valeur: { type: "liste" } + }, + ({ valeur }) => ({ + valeur: reduceToProduitNodes([...valeur]), + "simplifier l'unit\xE9": "oui" + }) +); + +// src/mecanisms/résoudre-référence-circulaire.ts +var evaluateR\u00E9soudreR\u00E9f\u00E9renceCirculaire = function(node) { + if (this.cache._meta.evaluationRuleStack.slice(1).includes(node.explanation.ruleToSolve)) { + return { + ...undefinedNumberNode, + ...node + }; + } + let numberOfIterations = 0; + const calculationEngine = this.shallowCopy(); + calculationEngine.cache._meta.parentRuleStack = [ + ...this.cache._meta.parentRuleStack + ]; + calculationEngine.cache._meta.evaluationRuleStack = [ + ...this.cache._meta.evaluationRuleStack + ]; + const maxIterations = this.context.inversionMaxIterations ?? 25; + const evaluateWithValue = (n) => { + numberOfIterations++; + calculationEngine.setSituation( + { + [node.explanation.ruleToSolve]: { + ...undefinedNumberNode, + nodeValue: n + } + }, + { keepPreviousSituation: true } + ); + return calculationEngine.evaluateNode(node.explanation.valeur); + }; + const inversionFailed = Symbol("inversion failed"); + let nodeValue = inversionFailed; + const x0 = 1; + let valeur = evaluateWithValue(x0); + const y0 = valeur.nodeValue; + const unit = valeur.unit; + if (y0 !== void 0) { + const test = (x) => { + if (x === x0) { + return y0 - x0; + } + valeur = evaluateWithValue(x); + const y = valeur.nodeValue; + return y - x; + }; + const defaultMin = -1e6; + const defaultMax = 1e8; + nodeValue = uniroot(test, defaultMin, defaultMax, 0.5, maxIterations, 2); + } + if (nodeValue === inversionFailed) { + nodeValue = void 0; + this.cache.inversionFail = true; + } + if (nodeValue !== void 0) { + valeur = evaluateWithValue(nodeValue); + } + return { + ...node, + unit, + nodeValue, + explanation: { + ...node.explanation, + valeur, + numberOfIterations + }, + missingVariables: valeur.missingVariables + }; +}; +function parseR\u00E9soudreR\u00E9f\u00E9renceCirculaire(v, context) { + return { + explanation: { + ruleToSolve: context.dottedName, + valeur: parse(v.valeur, context) + }, + nodeKind: "r\xE9soudre r\xE9f\xE9rence circulaire" + }; +} +parseR\u00E9soudreR\u00E9f\u00E9renceCirculaire.nom = "r\xE9soudre la r\xE9f\xE9rence circulaire"; +registerEvaluationFunction( + "r\xE9soudre r\xE9f\xE9rence circulaire", + evaluateR\u00E9soudreR\u00E9f\u00E9renceCirculaire +); + +// src/mecanisms/simplifier-unité.ts +function parseSimplifierUnit\u00E9(v, context) { + const explanation = parse(v.valeur, context); + return { + explanation, + nodeKind: "simplifier unit\xE9" + }; +} +parseSimplifierUnit\u00E9.nom = "simplifier l'unit\xE9"; +registerEvaluationFunction("simplifier unit\xE9", function evaluate9(node) { + const valeur = this.evaluateNode(node.explanation); + const nodeValue = valeur.nodeValue; + const defaultReturn = { + ...valeur, + ...node, + explanation: valeur + }; + if (nodeValue == null) { + return defaultReturn; + } + if (!valeur.unit) { + return { + ...defaultReturn, + unit: valeur.unit + }; + } + const unit = simplifyUnit(valeur.unit); + return { + ...defaultReturn, + nodeValue: typeof nodeValue === "number" ? convertUnit(valeur.unit, unit, nodeValue) : nodeValue, + unit + }; +}); + +// src/mecanisms/situation.ts +var situation_default = createParseInlinedMecanism( + "dans la situation", + { + valeur: {}, + "dans la situation": {} + }, + { + condition: { + si: { "est non d\xE9fini": "dans la situation" }, + alors: "valeur", + sinon: "dans la situation" + } + } +); + +// src/mecanisms/tauxProgressif.ts +function parseTauxProgressif(v, context) { + const explanation = { + assiette: parse(v.assiette, context), + multiplicateur: v.multiplicateur ? parse(v.multiplicateur, context) : defaultNode(1), + tranches: parseTranches(v.tranches, context) + }; + return { + explanation, + nodeKind: "taux progressif" + }; +} +var evaluate10 = function(node) { + const evaluate15 = this.evaluateNode.bind(this); + const assiette = this.evaluateNode(node.explanation.assiette); + const multiplicateur = this.evaluateNode(node.explanation.multiplicateur); + if (multiplicateur.nodeValue === 0) { + throw new PublicodesError("EvaluationError", `Division by zero`, { + dottedName: "" + }); + } + const tranches = evaluatePlafondUntilActiveTranche.call(this, { + parsedTranches: node.explanation.tranches, + assiette, + multiplicateur + }); + const evaluatedNode = { + ...node, + explanation: { + tranches, + assiette, + multiplicateur + }, + unit: parseUnit("%") + }; + const lastTranche = tranches[tranches.length - 1]; + if (tranches.every(({ isActive }) => isActive === false) || lastTranche.isActive && lastTranche.plafond.nodeValue === Infinity) { + const taux = convertNodeToUnit(parseUnit("%"), evaluate15(lastTranche.taux)); + const { nodeValue: nodeValue2, missingVariables } = taux; + lastTranche.taux = taux; + lastTranche.nodeValue = nodeValue2; + lastTranche.missingVariables = missingVariables; + return { + ...evaluatedNode, + nodeValue: nodeValue2, + missingVariables + }; + } + if (tranches.every(({ isActive }) => isActive !== true) || typeof assiette.nodeValue !== "number") { + return { + ...evaluatedNode, + nodeValue: void 0, + missingVariables: mergeAllMissing(tranches) + }; + } + const activeTrancheIndex = tranches.findIndex( + ({ isActive }) => isActive === true + ); + const activeTranche = tranches[activeTrancheIndex]; + activeTranche.taux = convertNodeToUnit( + parseUnit("%"), + evaluate15(activeTranche.taux) + ); + const previousTranche = tranches[activeTrancheIndex - 1]; + if (previousTranche) { + previousTranche.taux = convertNodeToUnit( + parseUnit("%"), + evaluate15(previousTranche.taux) + ); + previousTranche.isActive = true; + } + const previousTaux = previousTranche ? previousTranche.taux : activeTranche.taux; + const calculationValues = [previousTaux, activeTranche.taux]; + if (calculationValues.some((n) => n.nodeValue === void 0)) { + activeTranche.nodeValue = void 0; + return { + ...evaluatedNode, + nodeValue: void 0, + missingVariables: mergeAllMissing(calculationValues) + }; + } + const lowerTaux = previousTaux.nodeValue; + const upperTaux = activeTranche.taux.nodeValue; + const plancher = activeTranche.plancherValue; + const plafond = activeTranche.plafondValue; + const coeff = (upperTaux - lowerTaux) / (plafond - plancher); + const nodeValue = lowerTaux + (assiette.nodeValue - plancher) * coeff; + activeTranche.nodeValue = nodeValue; + return { + ...evaluatedNode, + nodeValue, + missingVariables: {} + }; +}; +registerEvaluationFunction("taux progressif", evaluate10); + +// src/mecanisms/texte.ts +var NAME = "texte"; +function parseTexte(texte, context) { + const explanation = []; + let lastIndex = 0; + for (const { 0: expression, index } of texte.matchAll(/{{(.|\n)*?}}/g)) { + const publicodeExpression = expression.slice(2, -2).trim(); + const parsedNode = parse(publicodeExpression, context); + explanation.push(texte.substring(lastIndex, index), parsedNode); + lastIndex = (index ?? 0) + expression.length; + } + explanation.push(texte.slice(lastIndex)); + return { + nodeKind: NAME, + explanation + }; +} +parseTexte.nom = NAME; +registerEvaluationFunction(NAME, function evaluate11(node) { + const explanation = node.explanation.map( + (element) => typeof element === "string" ? element : this.evaluateNode(element) + ); + return { + ...node, + explanation, + missingVariables: mergeAllMissing( + node.explanation.filter( + (element) => typeof element !== "string" + ) + ), + nodeValue: explanation.map( + (element) => typeof element === "string" ? element : formatValue(element) + ).join("") + }; +}); + +// src/mecanisms/toutes-ces-conditions.ts +var toutes_ces_conditions_default = createParseInlinedMecanismWithArray( + "toutes ces conditions", + { + valeur: { type: "liste" } + }, + ({ valeur }) => valeur.reduce( + (acc, value) => ({ et: [acc, value] }), + "oui" + ) +); + +// src/mecanisms/une-de-ces-conditions.ts +var une_de_ces_conditions_default = createParseInlinedMecanismWithArray( + "une de ces conditions", + { + valeur: { type: "liste" } + }, + ({ valeur }) => valeur.reduce( + (acc, value) => ({ ou: [acc, value] }), + "non" + ) +); + +// src/mecanisms/unité.ts +function parseUnit\u00E9(v, context) { + const explanation = parse(v.valeur, context); + const unit = parseUnit(v.unit\u00E9, context.getUnitKey); + return { + explanation, + unit, + nodeKind: parseUnit\u00E9.nom + }; +} +parseUnit\u00E9.nom = "unit\xE9"; +registerEvaluationFunction(parseUnit\u00E9.nom, function evaluate12(node) { + const valeur = this.evaluateNode(node.explanation); + let nodeValue = valeur.nodeValue; + if (nodeValue !== null && "unit" in node) { + try { + nodeValue = convertUnit( + valeur.unit, + node.unit, + valeur.nodeValue + ); + } catch (e) { + warning( + this.context.logger, + "Erreur lors de la conversion d'unit\xE9 explicite", + { dottedName: this.cache._meta.evaluationRuleStack[0] }, + e + ); + } + } + return { + ...node, + nodeValue, + explanation: valeur, + missingVariables: valeur.missingVariables + }; +}); + +// src/mecanisms/variablesManquantes.ts +function parseVariableManquante(v, context) { + return { + missingVariable: v["variable manquante"], + nodeKind: parseVariableManquante.nom, + explanation: parse(v.valeur, context) + }; +} +parseVariableManquante.nom = "variable manquante"; +registerEvaluationFunction(parseVariableManquante.nom, function evaluate13(node) { + const valeur = this.evaluateNode(node.explanation); + const maxMissingScore = Object.values(valeur.missingVariables).reduce( + (a, b) => a > b ? a : b, + 0 + ); + return { + ...node, + nodeValue: valeur.nodeValue, + unit: valeur.unit, + explanation: valeur, + missingVariables: mergeMissing(valeur.missingVariables, { + [node.missingVariable]: maxMissingScore + 1 + }) + }; +}); + +// src/mecanisms/variations.ts +function parseVariations(v, context) { + const explanation = v.map( + ({ si, alors, sinon }) => sinon !== void 0 ? { consequence: parse(sinon, context), condition: defaultNode(true) } : { consequence: parse(alors, context), condition: parse(si, context) } + ); + return { + explanation, + nodeKind: "variations" + }; +} +var evaluate14 = function(node) { + const [nodeValue, explanation, unit] = node.explanation.reduce( + ([evaluation, explanations, unit2, previousConditions], { condition, consequence }, i) => { + if (previousConditions === true) { + return [ + evaluation, + [...explanations, { condition, consequence }], + unit2, + previousConditions + ]; + } + const evaluatedCondition = this.evaluateNode(condition); + const currentCondition = previousConditions === void 0 ? previousConditions : !previousConditions && (evaluatedCondition.nodeValue === void 0 ? void 0 : evaluatedCondition.nodeValue !== false && evaluatedCondition.nodeValue !== null); + if (currentCondition === false || currentCondition === null) { + return [ + evaluation, + [...explanations, { condition: evaluatedCondition, consequence }], + unit2, + previousConditions + ]; + } + let evaluatedConsequence = void 0; + if (evaluatedCondition.nodeValue !== false && evaluatedCondition.nodeValue !== null) { + evaluatedConsequence = this.evaluateNode(consequence); + if (unit2) { + try { + evaluatedConsequence = convertNodeToUnit( + unit2, + evaluatedConsequence + ); + } catch (e) { + warning( + this.context.logger, + `L'unit\xE9 de la branche n\xB0 ${i + 1} du m\xE9canisme 'variations' n'est pas compatible avec celle d'une branche pr\xE9c\xE9dente`, + { dottedName: this.cache._meta.evaluationRuleStack[0] }, + e + ); + } + } + } + return [ + currentCondition && evaluatedConsequence?.nodeValue, + [ + ...explanations, + { + condition: evaluatedCondition, + consequence: evaluatedConsequence ?? consequence + } + ], + unit2 || evaluatedConsequence?.unit, + previousConditions || currentCondition + ]; + }, + [null, [], void 0, false] + ); + return { + ...node, + nodeValue, + ...unit !== void 0 && { unit }, + explanation, + missingVariables: explanation.reduce( + (values, { condition, consequence }) => mergeMissing( + values, + mergeMissing( + bonus(condition.missingVariables), + "nodeValue" in condition && condition.nodeValue !== false && condition.nodeValue !== null ? consequence.missingVariables : {} + ) + ), + {} + ) + }; +}; +registerEvaluationFunction("variations", evaluate14); + +// src/parseExpression.ts +var import_nearley = __toESM(require_nearley(), 1); + +// src/grammarFunctions.js +var binaryOperation = ([A, , operator, , B]) => ({ + [operator.value.toLowerCase()]: [A, B] +}); +var unaryOperation = ([operator, , A]) => ({ + [operator]: [number([{ value: "0" }]), A] +}); +var variable = (arg) => { + return { + variable: arg.value + }; +}; +var JSONObject = ([{ value }]) => { + value; +}; +var number = ([{ value }]) => ({ + constant: { + type: "number", + nodeValue: parseFloat(value) + } +}); +var numberWithUnit = (value) => ({ + ...number(value), + unit\u00E9: value[2].value +}); +var date = ([{ value }]) => { + return { + constant: { + type: "date", + nodeValue: normalizeDateString(value) + } + }; +}; +var boolean = ([{ value }]) => ({ + constant: { + type: "boolean", + nodeValue: value === "oui" + } +}); +var string = ([{ value }]) => ({ + constant: { + type: "string", + nodeValue: value.slice(1, -1) + } +}); + +// src/grammar.codegen.js +var import_moo = __toESM(require_moo(), 1); +function id(x) { + return x[0]; +} +var dateRegexp = `(?:(?:0?[1-9]|[12][0-9]|3[01])\\/)?(?:0?[1-9]|1[012])\\/\\d{4}`; +var letter = "[a-zA-Z\xC0-\u017F\u20AC$%\xB0]"; +var letterOrNumber = "[a-zA-Z\xC0-\u017F0-9',]"; +var word = `${letter}(?:[-']?${letterOrNumber}+)*`; +var numberRegExp = "-?(?:[1-9][0-9]+|[0-9])(?:\\.[0-9]+)?"; +var lexer = import_moo.default.compile({ + "(": "(", + ")": ")", + "[": "[", + "]": "]", + comparison: [">", "<", ">=", "<=", "=", "!="], + date: new RegExp(dateRegexp), + boolean: ["oui", "non"], + number: new RegExp(numberRegExp), + word: new RegExp(word), + string: [/'.*'/, /".*"/], + parentSelector: "^", + JSONObject: /{.*}/, + additionSubstraction: /[\+-]/, + multiplicationDivision: ["*", "/"], + dot: " . ", + ".": ".", + space: { match: /[\s]+/, lineBreaks: true } +}); +var join = (args) => ({ value: args.map((x) => x && x.value).join("") }); +var flattenJoin = (args) => join(args.flat()); +var Lexer = lexer; +var ParserRules = [ + { "name": "main", "symbols": ["Comparison"], "postprocess": id }, + { "name": "main", "symbols": ["NumericValue"], "postprocess": id }, + { "name": "main", "symbols": ["Date"], "postprocess": id }, + { "name": "main", "symbols": ["NonNumericTerminal"], "postprocess": id }, + { "name": "main", "symbols": ["JSONObject"], "postprocess": id }, + { "name": "NumericValue", "symbols": ["AdditionSubstraction"], "postprocess": id }, + { "name": "NumericValue", "symbols": ["Negation"], "postprocess": id }, + { "name": "NumericTerminal", "symbols": ["Variable"], "postprocess": id }, + { "name": "NumericTerminal", "symbols": ["number"], "postprocess": id }, + { "name": "Negation", "symbols": [{ "literal": "-" }, lexer.has("space") ? { type: "space" } : space, "Parentheses"], "postprocess": unaryOperation }, + { "name": "Parentheses", "symbols": [{ "literal": "(" }, lexer.has("space") ? { type: "space" } : space, "NumericValue", lexer.has("space") ? { type: "space" } : space, { "literal": ")" }], "postprocess": ([, , e]) => e }, + { "name": "Parentheses", "symbols": [{ "literal": "(" }, "NumericValue", { "literal": ")" }], "postprocess": ([, e]) => e }, + { "name": "Parentheses", "symbols": ["NumericTerminal"], "postprocess": id }, + { "name": "Date", "symbols": ["Variable"], "postprocess": id }, + { "name": "Date", "symbols": [lexer.has("date") ? { type: "date" } : date], "postprocess": date }, + { "name": "Comparison", "symbols": ["Comparable", lexer.has("space") ? { type: "space" } : space, lexer.has("comparison") ? { type: "comparison" } : comparison, lexer.has("space") ? { type: "space" } : space, "Comparable"], "postprocess": binaryOperation }, + { "name": "Comparison", "symbols": ["Date", lexer.has("space") ? { type: "space" } : space, lexer.has("comparison") ? { type: "comparison" } : comparison, lexer.has("space") ? { type: "space" } : space, "Date"], "postprocess": binaryOperation }, + { "name": "Comparable$subexpression$1", "symbols": ["AdditionSubstraction"] }, + { "name": "Comparable$subexpression$1", "symbols": ["NonNumericTerminal"] }, + { "name": "Comparable", "symbols": ["Comparable$subexpression$1"], "postprocess": ([[e]]) => e }, + { "name": "NonNumericTerminal", "symbols": [lexer.has("boolean") ? { type: "boolean" } : boolean], "postprocess": boolean }, + { "name": "NonNumericTerminal", "symbols": [lexer.has("string") ? { type: "string" } : string], "postprocess": string }, + { "name": "Variable", "symbols": ["VariableWithoutParentSelector"], "postprocess": ([x]) => variable(x) }, + { "name": "Variable$ebnf$1", "symbols": [] }, + { "name": "Variable$ebnf$1$subexpression$1", "symbols": [lexer.has("parentSelector") ? { type: "parentSelector" } : parentSelector, lexer.has("dot") ? { type: "dot" } : dot], "postprocess": join }, + { "name": "Variable$ebnf$1", "symbols": ["Variable$ebnf$1", "Variable$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) { + return d[0].concat([d[1]]); + } }, + { "name": "Variable", "symbols": ["Variable$ebnf$1", "VariableWithoutParentSelector"], "postprocess": (x) => variable(flattenJoin(x)) }, + { "name": "VariableWithoutParentSelector$ebnf$1", "symbols": [] }, + { "name": "VariableWithoutParentSelector$ebnf$1$subexpression$1", "symbols": [lexer.has("dot") ? { type: "dot" } : dot, "Words"], "postprocess": join }, + { "name": "VariableWithoutParentSelector$ebnf$1", "symbols": ["VariableWithoutParentSelector$ebnf$1", "VariableWithoutParentSelector$ebnf$1$subexpression$1"], "postprocess": function arrpush2(d) { + return d[0].concat([d[1]]); + } }, + { "name": "VariableWithoutParentSelector", "symbols": ["Words", "VariableWithoutParentSelector$ebnf$1"], "postprocess": (x) => flattenJoin(x) }, + { "name": "Words$ebnf$1$subexpression$1$ebnf$1", "symbols": [lexer.has("space") ? { type: "space" } : space], "postprocess": id }, + { "name": "Words$ebnf$1$subexpression$1$ebnf$1", "symbols": [], "postprocess": function(d) { + return null; + } }, + { "name": "Words$ebnf$1$subexpression$1", "symbols": ["Words$ebnf$1$subexpression$1$ebnf$1", "WordOrNumber"], "postprocess": join }, + { "name": "Words$ebnf$1", "symbols": ["Words$ebnf$1$subexpression$1"] }, + { "name": "Words$ebnf$1$subexpression$2$ebnf$1", "symbols": [lexer.has("space") ? { type: "space" } : space], "postprocess": id }, + { "name": "Words$ebnf$1$subexpression$2$ebnf$1", "symbols": [], "postprocess": function(d) { + return null; + } }, + { "name": "Words$ebnf$1$subexpression$2", "symbols": ["Words$ebnf$1$subexpression$2$ebnf$1", "WordOrNumber"], "postprocess": join }, + { "name": "Words$ebnf$1", "symbols": ["Words$ebnf$1", "Words$ebnf$1$subexpression$2"], "postprocess": function arrpush3(d) { + return d[0].concat([d[1]]); + } }, + { "name": "Words", "symbols": ["WordOrKeyword", "Words$ebnf$1"], "postprocess": flattenJoin }, + { "name": "Words", "symbols": [lexer.has("word") ? { type: "word" } : word], "postprocess": id }, + { "name": "WordOrKeyword", "symbols": [lexer.has("word") ? { type: "word" } : word], "postprocess": id }, + { "name": "WordOrKeyword", "symbols": [lexer.has("boolean") ? { type: "boolean" } : boolean], "postprocess": id }, + { "name": "WordOrNumber", "symbols": ["WordOrKeyword"], "postprocess": id }, + { "name": "WordOrNumber", "symbols": [lexer.has("number") ? { type: "number" } : number], "postprocess": id }, + { "name": "Unit$ebnf$1", "symbols": [] }, + { "name": "Unit$ebnf$1", "symbols": ["Unit$ebnf$1", "UnitNumerator"], "postprocess": function arrpush4(d) { + return d[0].concat([d[1]]); + } }, + { "name": "Unit$ebnf$2", "symbols": [] }, + { "name": "Unit$ebnf$2", "symbols": ["Unit$ebnf$2", "UnitDenominator"], "postprocess": function arrpush5(d) { + return d[0].concat([d[1]]); + } }, + { "name": "Unit", "symbols": ["Unit$ebnf$1", "Unit$ebnf$2"], "postprocess": flattenJoin }, + { "name": "UnitNumerator", "symbols": ["Words"], "postprocess": id }, + { "name": "UnitNumerator", "symbols": [{ "literal": "." }, "UnitNumerator"], "postprocess": join }, + { "name": "UnitDenominator$ebnf$1", "symbols": [] }, + { "name": "UnitDenominator$ebnf$1$subexpression$1", "symbols": [lexer.has("space") ? { type: "space" } : space] }, + { "name": "UnitDenominator$ebnf$1", "symbols": ["UnitDenominator$ebnf$1", "UnitDenominator$ebnf$1$subexpression$1"], "postprocess": function arrpush6(d) { + return d[0].concat([d[1]]); + } }, + { "name": "UnitDenominator$ebnf$2", "symbols": ["UnitNumerator"] }, + { "name": "UnitDenominator$ebnf$2", "symbols": ["UnitDenominator$ebnf$2", "UnitNumerator"], "postprocess": function arrpush7(d) { + return d[0].concat([d[1]]); + } }, + { "name": "UnitDenominator", "symbols": ["UnitDenominator$ebnf$1", { "literal": "/" }, "UnitDenominator$ebnf$2"], "postprocess": flattenJoin }, + { "name": "AdditionSubstraction", "symbols": ["AdditionSubstraction", lexer.has("space") ? { type: "space" } : space, lexer.has("additionSubstraction") ? { type: "additionSubstraction" } : additionSubstraction, lexer.has("space") ? { type: "space" } : space, "MultiplicationDivision"], "postprocess": binaryOperation }, + { "name": "AdditionSubstraction", "symbols": ["MultiplicationDivision"], "postprocess": id }, + { "name": "MultiplicationDivision", "symbols": ["MultiplicationDivision", lexer.has("space") ? { type: "space" } : space, lexer.has("multiplicationDivision") ? { type: "multiplicationDivision" } : multiplicationDivision, lexer.has("space") ? { type: "space" } : space, "Parentheses"], "postprocess": binaryOperation }, + { "name": "MultiplicationDivision", "symbols": ["Parentheses"], "postprocess": id }, + { "name": "number", "symbols": [lexer.has("number") ? { type: "number" } : number], "postprocess": number }, + { "name": "number$ebnf$1$subexpression$1", "symbols": [lexer.has("space") ? { type: "space" } : space] }, + { "name": "number$ebnf$1", "symbols": ["number$ebnf$1$subexpression$1"], "postprocess": id }, + { "name": "number$ebnf$1", "symbols": [], "postprocess": function(d) { + return null; + } }, + { "name": "number", "symbols": [lexer.has("number") ? { type: "number" } : number, "number$ebnf$1", "Unit"], "postprocess": numberWithUnit }, + { "name": "JSONObject", "symbols": [lexer.has("JSONObject") ? { type: "JSONObject" } : JSONObject], "postprocess": JSONObject } +]; +var ParserStart = "main"; +var grammar_codegen_default = { Lexer, ParserRules, ParserStart }; + +// src/parseExpression.ts +var { Grammar, Parser } = import_nearley.default; +var compiledGrammar = Grammar.fromCompiled(grammar_codegen_default); +var parser = new Parser(compiledGrammar); +var initialState = parser.save(); +function parseExpression(rawNode, dottedName) { + const singleLineExpression = (rawNode + "").replace(/\s*\n\s*/g, " ").trim(); + try { + parser.restore(initialState); + const [parseResult] = parser.feed(singleLineExpression).results; + if (parseResult == null) { + throw new PublicodesError( + "InternalError", + ` +Un probl\xE8me est survenu lors du parsing de l'expression \`${singleLineExpression}\` : + + le parseur Nearley n'a pas r\xE9ussi \xE0 parser l'expression. +`, + { dottedName } + ); + } + return parseResult; + } catch (e) { + if (e instanceof PublicodesError) { + throw e; + } + throw new PublicodesError( + "SyntaxError", + `\`${singleLineExpression}\` n'est pas une expression valide`, + { dottedName }, + e + ); + } +} + +// src/reference.ts +function parseReference(v, context) { + if (!context.dottedName) { + throw new PublicodesError( + "InternalError", + "Une r\xE9f\xE9rence ne peut pas exister en dehors d'une r\xE8gle (`context.dottedName` est vide)", + { + dottedName: v + } + ); + } + if (!v) { + throw new PublicodesError( + "SyntaxError", + "Une r\xE9f\xE9rence ne peut pas \xEAtre vide", + { + dottedName: context.dottedName + } + ); + } + return { + nodeKind: "reference", + name: v, + contextDottedName: context.dottedName + }; +} +registerEvaluationFunction("reference", function evaluateReference(node) { + if (!node.dottedName) { + throw new PublicodesInternalError(node); + } + const explanation = this.evaluateNode( + this.context.parsedRules[node.dottedName] + ); + delete explanation.sourceMap; + return { + ...explanation, + ...node + }; +}); + +// src/parse.ts +function parse(rawNode, context) { + if (rawNode == void 0) { + throw new PublicodesError( + "SyntaxError", + ` + Une des valeurs de la formule est vide. + V\xE9rifiez que tous les champs \xE0 droite des deux points sont remplis`, + { dottedName: context.dottedName } + ); + } + if (typeof rawNode === "boolean") { + throw new PublicodesError( + "SyntaxError", + ` +Les valeurs bool\xE9ennes true / false ne sont accept\xE9es. +Utilisez leur contrepartie fran\xE7aise : 'oui' / 'non'`, + { dottedName: context.dottedName } + ); + } + const node = typeof rawNode === "object" ? rawNode : parseExpression(rawNode, context.dottedName); + if ("nodeKind" in node) { + return node; + } + return { + ...parseChainedMecanisms(node, context), + rawNode + }; +} +function parseMecanism(rawNode, context) { + if (Array.isArray(rawNode)) { + throw new PublicodesError( + "SyntaxError", + ` +Il manque le nom du m\xE9canisme pour le tableau : [${rawNode.map((x) => `'${x}'`).join(", ")}] +Les m\xE9canisme possibles sont : 'somme', 'le maximum de', 'le minimum de', 'toutes ces conditions', 'une de ces conditions'. + `, + { dottedName: context.dottedName } + ); + } + const keys = Object.keys(rawNode); + if (keys.length > 1) { + throw new PublicodesError( + "SyntaxError", + ` +Les m\xE9canismes suivants se situent au m\xEAme niveau : ${keys.map((x) => `'${x}'`).join(", ")} +Cela vient probablement d'une erreur dans l'indentation + `, + { dottedName: context.dottedName } + ); + } + if (keys.length === 0) { + return { nodeKind: "constant", nodeValue: void 0 }; + } + const mecanismName = keys[0]; + const values = rawNode[mecanismName]; + const parseFn = parseFunctions[mecanismName]; + if (!parseFn) { + throw new PublicodesError( + "SyntaxError", + `Le m\xE9canisme "${mecanismName}" est inconnu. + +V\xE9rifiez qu'il n'y ait pas d'erreur dans l'orthographe du nom.`, + { dottedName: context.dottedName } + ); + } + try { + return parseFn(values, context); + } catch (e) { + if (e instanceof PublicodesError) { + throw e; + } + throw new PublicodesError( + "SyntaxError", + mecanismName ? `\u27A1\uFE0F Dans le m\xE9canisme ${mecanismName} +${e.message}` : e.message, + { dottedName: context.dottedName } + ); + } +} +var chainableMecanisms = [ + parseMecanismContexte, + parseVariableManquante, + parseAvec, + applicable_default, + non_applicable_default, + parseArrondi, + parseUnit\u00E9, + parseSimplifierUnit\u00E9, + plancher_default, + plafond_default, + parD_faut_default, + situation_default, + parseR\u00E9soudreR\u00E9f\u00E9renceCirculaire, + abattement_default +]; +function parseChainedMecanisms(rawNode, context) { + const parseFn = chainableMecanisms.find((fn) => fn.nom in rawNode); + if (!parseFn) { + return parseMecanism(rawNode, context); + } + const { [parseFn.nom]: param, ...valeur } = rawNode; + return parseMecanism( + { + [parseFn.nom]: { + valeur, + [parseFn.nom]: param + } + }, + context + ); +} +var parseFunctions = { + ...operation_default, + ...chainableMecanisms.reduce((acc, fn) => ({ [fn.nom]: fn, ...acc }), {}), + "inversion num\xE9rique": mecanismInversion, + "le maximum de": parseMaximumDe, + "le minimum de": parseMinimumDe, + "taux progressif": parseTauxProgressif, + "toutes ces conditions": toutes_ces_conditions_default, + "est non d\xE9fini": parseEstNonD\u00E9fini, + "est non applicable": parseEstNonApplicable, + "est applicable": parseEstApplicable, + "est d\xE9fini": parseEstD\u00E9fini, + "une de ces conditions": une_de_ces_conditions_default, + "une possibilit\xE9": mecanismOnePossibility, + condition: parseCondition, + bar\u00E8me: parseBar\u00E8me, + dur\u00E9e: dur_e_default, + grille: parseGrille, + multiplication: product_default, + produit: product_default, + somme: somme_default, + moyenne: moyenne_default, + [parseTexte.nom]: parseTexte, + valeur: parse, + variable: parseReference, + variations: parseVariations, + constant: (v) => ({ + type: v.type, + // In the documentation we want to display constants defined in the source + // with their full precision. This is especially useful for percentages like + // APEC 0,036 %. + fullPrecision: true, + isNullable: v.nodeValue == null, + missingVariables: {}, + nodeValue: v.nodeValue, + nodeKind: "constant" + }) +}; +var mecanismKeys = Object.keys(parseFunctions); + +// src/replacement.ts +var remplacementRuleId = 0; +var cache = {}; +function parseReplacements(replacements, context) { + if (!replacements) { + return []; + } + return (Array.isArray(replacements) ? replacements : [replacements]).map( + (replacement) => { + if (typeof replacement === "string") { + replacement = { "r\xE9f\xE9rences \xE0": replacement }; + } + const replacedReference = parse(replacement["r\xE9f\xE9rences \xE0"], context); + const [whiteListedNames, blackListedNames] = [ + replacement.dans ?? [], + replacement["sauf dans"] ?? [] + ].map( + (dottedName) => Array.isArray(dottedName) ? dottedName : [dottedName] + ).map((refs) => refs.map((ref) => parse(ref, context))); + if (replacement.priorit\u00E9 != null && (typeof replacement.priorit\u00E9 !== "number" || replacement.priorit\u00E9 < 0)) { + throw new PublicodesError( + "SyntaxError", + "La priorit\xE9 du remplacement doit \xEAtre un nombre positif", + context + ); + } + return { + nodeKind: "replacementRule", + rawNode: replacement, + priority: replacement.priorit\u00E9, + definitionRule: parse(context.dottedName, context), + replacedReference, + replaceByNonApplicable: false, + whiteListedNames, + blackListedNames, + remplacementRuleId: remplacementRuleId++ + }; + } + ); +} +function parseRendNonApplicable(rules, context) { + const rendNonApplicableReplacements = parseReplacements(rules, context); + rendNonApplicableReplacements.forEach( + (r) => r.replaceByNonApplicable = true + ); + return rendNonApplicableReplacements; +} +function getReplacements(parsedRules) { + const ret = {}; + for (const dottedName in parsedRules) { + const rule = parsedRules[dottedName]; + for (const replacement of rule.replacements) { + if (!replacement.replacedReference.dottedName) { + throw new PublicodesInternalError(replacement); + } + const key = replacement.replacedReference.dottedName; + ret[key] = [...ret[key] ?? [], replacement]; + } + } + return ret; +} +function inlineReplacements({ + newRules, + previousReplacements, + parsedRules, + referencesMaps +}) { + const newReplacements = getReplacements(newRules); + const ruleNamesWithNewReplacements = /* @__PURE__ */ new Set([]); + for (const replacedReference in newReplacements) { + const rulesThatUse = referencesMaps.rulesThatUse.get(replacedReference) ?? []; + for (const value of rulesThatUse) { + ruleNamesWithNewReplacements.add(value); + } + } + const newRuleNamesWithPreviousReplacements = new Set( + Object.keys(newRules).filter( + (ruleName) => [...referencesMaps.referencesIn.get(ruleName) ?? /* @__PURE__ */ new Set()].some( + (reference) => (previousReplacements[reference] ?? []).length + ) + ) + ); + const replacements = mergeWithArray(previousReplacements, newReplacements); + if (!newRuleNamesWithPreviousReplacements.size && !ruleNamesWithNewReplacements.size) { + return [parsedRules, replacements]; + } + const inlinePreviousReplacement = makeReplacementInliner( + previousReplacements, + referencesMaps + ); + const inlineNewReplacement = makeReplacementInliner( + newReplacements, + referencesMaps + ); + newRuleNamesWithPreviousReplacements.forEach((name) => { + parsedRules[name] = inlinePreviousReplacement( + parsedRules[name] + ); + }); + ruleNamesWithNewReplacements.forEach((name) => { + parsedRules[name] = inlineNewReplacement( + parsedRules[name] + ); + }); + return [parsedRules, replacements]; +} +function makeReplacementInliner(replacements, referencesMaps) { + return makeASTTransformer((node, transform) => { + if (node.nodeKind === "replacementRule" || node.nodeKind === "inversion" || node.nodeKind === "une possibilit\xE9") { + return false; + } + if (node.nodeKind === "contexte") { + return { + ...node, + explanation: { + ...node.explanation, + valeur: transform(node.explanation.valeur), + contexte: node.explanation.contexte.map(([name, value]) => [ + name, + transform(value) + ]) + } + }; + } + if (node.nodeKind === "reference") { + if (!node.dottedName) { + throw new PublicodesInternalError(node); + } + const replacedReferenceNode = replace( + node, + replacements[node.dottedName] ?? [] + ); + makeASTVisitor((n) => { + updateReferencesMapsFromReferenceNode( + n, + referencesMaps, + node.contextDottedName + ); + return "continue"; + })(replacedReferenceNode); + return replacedReferenceNode; + } + }); +} +function replace(node, replacements) { + const applicableReplacements = replacements.filter( + ({ definitionRule }) => definitionRule.dottedName !== node.contextDottedName + ).filter( + ({ whiteListedNames }) => !whiteListedNames.length || whiteListedNames.some( + (name) => node.contextDottedName.startsWith(name.dottedName) + ) + ).filter( + ({ blackListedNames }) => !blackListedNames.length || blackListedNames.every( + (name) => !node.contextDottedName.startsWith(name.dottedName) + ) + ).reverse().sort((a, b) => { + const result = (b.priority ?? 0) - (a.priority ?? 0); + if (result !== 0) { + return result; + } + return b.definitionRule.dottedName.localeCompare( + a.definitionRule.dottedName + ); + }); + if (!applicableReplacements.length) { + return node; + } + const applicableReplacementsCacheKey = applicableReplacements.map((n) => n.remplacementRuleId).join("-"); + if (cache[applicableReplacementsCacheKey]) { + return cache[applicableReplacementsCacheKey]; + } + const replacementNode = { + nodeKind: "variations", + explanation: [ + ...applicableReplacements.map( + ({ definitionRule, replaceByNonApplicable }) => replaceByNonApplicable ? { + condition: definitionRule, + consequence: notApplicableNode + } : { + condition: estApplicable(definitionRule), + consequence: definitionRule + } + ), + { condition: oui, consequence: node } + ] + }; + replacementNode.sourceMap = { + mecanismName: "replacement", + args: { + applicableReplacements, + originalNode: node + } + }; + cache[applicableReplacementsCacheKey] = replacementNode; + return cache[applicableReplacementsCacheKey]; +} +function estApplicable(node) { + return { + nodeKind: "condition", + explanation: { + si: { nodeKind: "est non applicable", explanation: node }, + alors: non, + sinon: oui + } + }; +} +var oui = defaultNode(true); +var non = defaultNode(false); + +// src/parsePublicodes.ts +function createContext(partialContext) { + return { + dottedName: "", + logger: console, + getUnitKey: (x) => x, + parsedRules: {}, + referencesMaps: { referencesIn: /* @__PURE__ */ new Map(), rulesThatUse: /* @__PURE__ */ new Map() }, + nodesTypes: /* @__PURE__ */ new WeakMap(), + rulesReplacements: {}, + allowOrphanRules: false, + subEngineIncrementingNumber: 1, + ...partialContext + }; +} +function copyContext(context) { + return { + ...context, + parsedRules: { ...context.parsedRules }, + referencesMaps: { + referencesIn: new Map(context.referencesMaps.referencesIn), + rulesThatUse: new Map(context.referencesMaps.rulesThatUse) + } + }; +} +function parsePublicodes(rawRules, partialContext = createContext({})) { + if (typeof rawRules === "string") + throw new PublicodesError( + "EngineError", + "Publicodes does not parse yaml rule sets itself anymore. Please provide a parsed js object. E.g. the `eemeli/yaml` package.", + {} + ); + const rules = weakCopyObj(rawRules); + const context = createContext(partialContext); + const previousParsedRules = context.parsedRules; + context.parsedRules = {}; + parseRules(rules, context); + let parsedRules = {}; + for (const dottedName in previousParsedRules) { + parsedRules[dottedName] = previousParsedRules[dottedName]; + } + for (const dottedName in context.parsedRules) { + parsedRules[dottedName] = context.parsedRules[dottedName]; + } + const [newRules, referencesMaps] = disambiguateReferencesAndCollectDependencies( + parsedRules, + context.parsedRules, + context.referencesMaps, + context.allowOrphanRules + ); + let rulesReplacements; + [parsedRules, rulesReplacements] = inlineReplacements({ + parsedRules, + newRules, + referencesMaps, + previousReplacements: context.rulesReplacements + }); + const nodesTypes = inferNodesTypes( + Object.keys(newRules), + parsedRules, + context.nodesTypes + ); + return { + parsedRules, + nodesTypes, + referencesMaps, + rulesReplacements + }; +} +function disambiguateReferencesAndCollectDependencies(parsedRules, newRules, referencesMaps, allowOrphanRules) { + const disambiguateReference2 = makeASTTransformer( + (node) => disambiguateReferenceNode(node, parsedRules) + ); + const disambiguateReferencesAndCollectDependencies2 = makeASTTransformer( + (node) => { + const n = disambiguateReferenceNode(node, parsedRules); + if (n) { + updateReferencesMapsFromReferenceNode(n, referencesMaps); + } + return n; + } + ); + const disambiguatedRules = traverseParsedRules((node) => { + if (node.nodeKind === "replacementRule") { + return disambiguateReference2(node); + } + if (node.nodeKind === "rule") { + const parentUndefined = node.explanation.parents.find( + (n) => !(n.dottedName in parsedRules) + ); + if (!allowOrphanRules && parentUndefined) { + throw new PublicodesError( + "SyntaxError", + `La r\xE8gle parente "${parentUndefined.dottedName}" n'existe pas`, + { + dottedName: node.dottedName + } + ); + } + } + return disambiguateReferencesAndCollectDependencies2(node); + }, newRules); + return [ + disambiguatedRules, + referencesMaps + ]; +} + +// src/traversedVariables.ts +function computeTraversedVariableBeforeEval(traversedVariablesStack, parsedNode, cachedNode, publicParsedRules, isTraversedVariablesBoundary2) { + if (traversedVariablesStack === void 0) { + return; + } + if (cachedNode !== void 0) { + cachedNode.traversedVariables?.forEach( + (name) => traversedVariablesStack[0]?.add(name) + ); + return; + } + if (isTraversedVariablesBoundary2) { + traversedVariablesStack.unshift(/* @__PURE__ */ new Set()); + } + if (parsedNode.nodeKind === "reference" && parsedNode.dottedName && parsedNode.dottedName in publicParsedRules) { + traversedVariablesStack[0].add(parsedNode.dottedName); + } +} +function isTraversedVariablesBoundary(traversedVariablesStack, parsedNode) { + return !!traversedVariablesStack && (traversedVariablesStack.length === 0 || parsedNode.nodeKind === "rule"); +} +function computeTraversedVariableAfterEval(traversedVariablesStack, evaluatedNode, isTraversedVariablesBoundary2) { + if (traversedVariablesStack === void 0) { + return; + } + if (isTraversedVariablesBoundary2) { + evaluatedNode.traversedVariables = Array.from( + traversedVariablesStack.shift() ?? [] + ); + if (traversedVariablesStack.length > 0) { + evaluatedNode.traversedVariables.forEach((name) => { + traversedVariablesStack[0].add(name); + }); + } + } +} + +// src/serializeEvaluation.ts +function serializeEvaluation(node) { + if (typeof node.nodeValue === "number") { + const serializedUnit = serializeUnit(node.unit); + return "" + node.nodeValue + (serializedUnit ? serializedUnit.replace(/\s/g, "") : ""); + } else if (typeof node.nodeValue === "boolean") { + return node.nodeValue ? "oui" : "non"; + } else if (typeof node.nodeValue === "string") { + return `'${node.nodeValue}'`; + } +} + +// src/index.ts +var emptyCache = () => ({ + _meta: { + evaluationRuleStack: [], + parentRuleStack: [] + }, + traversedVariablesStack: void 0, + nodes: /* @__PURE__ */ new Map() +}); +var Engine = class _Engine { + baseContext; + context; + publicParsedRules; + cache = emptyCache(); + // The subEngines attribute is used to get an outside reference to the + // `contexte` intermediate calculations. The `contexte` mechanism uses + // `shallowCopy` to instanciate a new engine, and we want to keep a reference + // to it for the documentation. + // + // TODO: A better implementation would to remove the "runtime" concept of + // "subEngines" and instead duplicate all rules names in the scope of the + // `contexte` as described in + // https://github.com/publicodes/publicodes/discussions/92 + subEngines = []; + subEngineId; + constructor(rules = {}, options = {}) { + const initialContext = { + dottedName: "", + ...options + }; + this.baseContext = createContext({ + ...initialContext, + ...parsePublicodes(rules, initialContext) + }); + this.context = this.baseContext; + this.publicParsedRules = {}; + for (const name in this.baseContext.parsedRules) { + const rule = this.baseContext.parsedRules[name]; + if (!rule.private && isAccessible(this.baseContext.parsedRules, "", name)) { + this.publicParsedRules[name] = rule; + } + } + } + resetCache() { + this.cache = emptyCache(); + } + setSituation(situation = {}, options = {}) { + this.resetCache(); + const keepPreviousSituation = options.keepPreviousSituation ?? false; + Object.keys(situation).forEach((name) => { + if (!(name in this.baseContext.parsedRules)) { + throw new PublicodesError( + "EvaluationError", + `Erreur lors de la mise \xE0 jour de la situation : ${name} n'existe pas dans la base de r\xE8gle.`, + { dottedName: name } + ); + } + if (this.baseContext.parsedRules[name].private) { + throw new PublicodesError( + "EvaluationError", + `Erreur lors de la mise \xE0 jour de la situation : ${name} est une r\xE8gle priv\xE9e (il n'est pas possible de modifier une r\xE8gle priv\xE9e).`, + { dottedName: name } + ); + } + }); + const situationToParse = Object.fromEntries( + Object.entries(situation).map(([nom, value]) => [ + `[priv\xE9] ${nom} . $SITUATION`, + value && typeof value === "object" && "nodeKind" in value ? { valeur: value } : value + ]) + ); + const savedBaseContext = copyContext(this.baseContext); + try { + this.context = { + ...this.baseContext, + ...parsePublicodes( + situationToParse, + keepPreviousSituation ? this.context : this.baseContext + ) + }; + } catch (error) { + this.baseContext = savedBaseContext; + throw error; + } + this.baseContext = savedBaseContext; + Object.keys(situation).forEach((nom) => { + if (isExperimental(this.context.parsedRules, nom)) { + experimentalRuleWarning(this.baseContext.logger, nom); + } + this.checkExperimentalRule( + this.context.parsedRules[`${nom} . $SITUATION`] + ); + }); + return this; + } + inversionFail() { + return !!this.cache.inversionFail; + } + getRule(dottedName) { + if (!(dottedName in this.baseContext.parsedRules)) { + throw new PublicodesError( + "UnknownRule", + `La r\xE8gle '${dottedName}' n'existe pas`, + { dottedName } + ); + } + if (!(dottedName in this.publicParsedRules)) { + throw new PublicodesError( + "PrivateRule", + `La r\xE8gle ${dottedName} est une r\xE8gle priv\xE9e.`, + { dottedName } + ); + } + return this.publicParsedRules[dottedName]; + } + getParsedRules() { + return this.publicParsedRules; + } + evaluate(value) { + const cachedNode = this.cache.nodes.get(value); + if (cachedNode) { + return cachedNode; + } + this.context = Object.assign( + this.context, + parsePublicodes( + { + "[priv\xE9] $EVALUATION": value && typeof value === "object" && "nodeKind" in value ? { valeur: value } : value + }, + this.context + ) + ); + this.checkExperimentalRule(this.context.parsedRules["$EVALUATION"]); + this.cache._meta = emptyCache()._meta; + const evaluation = this.evaluateNode( + this.context.parsedRules["$EVALUATION"].explanation.valeur + ); + this.cache.nodes.set(value, evaluation); + return evaluation; + } + evaluateNode(parsedNode) { + const cachedNode = this.cache.nodes.get(parsedNode); + let traversedVariableBoundary = false; + if (this.cache.traversedVariablesStack) { + traversedVariableBoundary = isTraversedVariablesBoundary( + this.cache.traversedVariablesStack, + parsedNode + ); + computeTraversedVariableBeforeEval( + this.cache.traversedVariablesStack, + parsedNode, + cachedNode, + this.publicParsedRules, + traversedVariableBoundary + ); + } + if (cachedNode !== void 0) { + return cachedNode; + } + if (!evaluationFunctions[parsedNode.nodeKind]) { + throw new PublicodesError( + "EvaluationError", + `Unknown "nodeKind": ${parsedNode.nodeKind}`, + { dottedName: "" } + ); + } + const evaluatedNode = evaluationFunctions[parsedNode.nodeKind].call( + this, + parsedNode + ); + if (this.cache.traversedVariablesStack) { + computeTraversedVariableAfterEval( + this.cache.traversedVariablesStack, + evaluatedNode, + traversedVariableBoundary + ); + } + this.cache.nodes.set(parsedNode, evaluatedNode); + return evaluatedNode; + } + /** + * Shallow Engine instance copy. Keeps references to the original Engine instance attributes. + */ + shallowCopy() { + const newEngine = new _Engine(); + newEngine.baseContext = copyContext(this.baseContext); + newEngine.context = copyContext(this.context); + newEngine.publicParsedRules = this.publicParsedRules; + newEngine.cache = { + ...emptyCache(), + nodes: new Map(this.cache.nodes) + }; + return newEngine; + } + checkExperimentalRule = makeASTVisitor((node) => { + if (node.nodeKind === "reference" && isExperimental(this.context.parsedRules, node.dottedName)) { + experimentalRuleWarning( + this.baseContext.logger, + node.dottedName + ); + } + return "continue"; + }); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + PublicodesError, + capitalise0, + formatValue, + isPublicodesError, + parseExpression, + parsePublicodes, + parseUnit, + reduceAST, + serializeEvaluation, + serializeUnit, + simplifyNodeUnit, + transformAST, + traverseASTNode, + utils +}); +//# sourceMappingURL=index.cjs.map \ No newline at end of file diff --git a/publicodes/dist/index.cjs.map b/publicodes/dist/index.cjs.map new file mode 100644 index 000000000..0b93a808a --- /dev/null +++ b/publicodes/dist/index.cjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../node_modules/nearley/lib/nearley.js","../../../node_modules/moo/moo.js","../src/index.ts","../src/error.ts","../src/utils.ts","../src/AST/index.ts","../src/evaluationFunctions.ts","../src/inferNodeType.ts","../src/evaluationUtils.ts","../src/mecanisms/inlineMecanism.ts","../src/mecanisms/abattement.ts","../src/mecanisms/applicable.ts","../src/units.ts","../src/mecanisms/arrondi.ts","../src/nodeUnits.ts","../src/format.ts","../src/ruleUtils.ts","../src/AST/findCycles.ts","../src/AST/graph.ts","../src/rule.ts","../src/mecanisms/avec.ts","../src/mecanisms/trancheUtils.ts","../src/mecanisms/barème.ts","../src/mecanisms/condition.ts","../src/mecanisms/contexte.ts","../src/date.ts","../src/mecanisms/durée.ts","../src/mecanisms/est.ts","../src/mecanisms/est-non-applicable.ts","../src/mecanisms/grille.ts","../src/uniroot.ts","../src/mecanisms/inversion.ts","../src/mecanisms/max-min.ts","../src/mecanisms/somme.tsx","../src/mecanisms/moyenne.ts","../src/mecanisms/non-applicable.ts","../src/mecanisms/one-possibility.ts","../src/mecanisms/operation.ts","../src/mecanisms/parDéfaut.ts","../src/mecanisms/plafond.ts","../src/mecanisms/plancher.ts","../src/mecanisms/product.ts","../src/mecanisms/résoudre-référence-circulaire.ts","../src/mecanisms/simplifier-unité.ts","../src/mecanisms/situation.ts","../src/mecanisms/tauxProgressif.ts","../src/mecanisms/texte.ts","../src/mecanisms/toutes-ces-conditions.ts","../src/mecanisms/une-de-ces-conditions.ts","../src/mecanisms/unité.ts","../src/mecanisms/variablesManquantes.ts","../src/mecanisms/variations.ts","../src/parseExpression.ts","../src/grammarFunctions.js","../src/grammar.codegen.js","../src/reference.ts","../src/parse.ts","../src/replacement.ts","../src/parsePublicodes.ts","../src/traversedVariables.ts","../src/serializeEvaluation.ts"],"sourcesContent":["(function(root, factory) {\n if (typeof module === 'object' && module.exports) {\n module.exports = factory();\n } else {\n root.nearley = factory();\n }\n}(this, function() {\n\n function Rule(name, symbols, postprocess) {\n this.id = ++Rule.highestId;\n this.name = name;\n this.symbols = symbols; // a list of literal | regex class | nonterminal\n this.postprocess = postprocess;\n return this;\n }\n Rule.highestId = 0;\n\n Rule.prototype.toString = function(withCursorAt) {\n var symbolSequence = (typeof withCursorAt === \"undefined\")\n ? this.symbols.map(getSymbolShortDisplay).join(' ')\n : ( this.symbols.slice(0, withCursorAt).map(getSymbolShortDisplay).join(' ')\n + \" ● \"\n + this.symbols.slice(withCursorAt).map(getSymbolShortDisplay).join(' ') );\n return this.name + \" → \" + symbolSequence;\n }\n\n\n // a State is a rule at a position from a given starting point in the input stream (reference)\n function State(rule, dot, reference, wantedBy) {\n this.rule = rule;\n this.dot = dot;\n this.reference = reference;\n this.data = [];\n this.wantedBy = wantedBy;\n this.isComplete = this.dot === rule.symbols.length;\n }\n\n State.prototype.toString = function() {\n return \"{\" + this.rule.toString(this.dot) + \"}, from: \" + (this.reference || 0);\n };\n\n State.prototype.nextState = function(child) {\n var state = new State(this.rule, this.dot + 1, this.reference, this.wantedBy);\n state.left = this;\n state.right = child;\n if (state.isComplete) {\n state.data = state.build();\n // Having right set here will prevent the right state and its children\n // form being garbage collected\n state.right = undefined;\n }\n return state;\n };\n\n State.prototype.build = function() {\n var children = [];\n var node = this;\n do {\n children.push(node.right.data);\n node = node.left;\n } while (node.left);\n children.reverse();\n return children;\n };\n\n State.prototype.finish = function() {\n if (this.rule.postprocess) {\n this.data = this.rule.postprocess(this.data, this.reference, Parser.fail);\n }\n };\n\n\n function Column(grammar, index) {\n this.grammar = grammar;\n this.index = index;\n this.states = [];\n this.wants = {}; // states indexed by the non-terminal they expect\n this.scannable = []; // list of states that expect a token\n this.completed = {}; // states that are nullable\n }\n\n\n Column.prototype.process = function(nextColumn) {\n var states = this.states;\n var wants = this.wants;\n var completed = this.completed;\n\n for (var w = 0; w < states.length; w++) { // nb. we push() during iteration\n var state = states[w];\n\n if (state.isComplete) {\n state.finish();\n if (state.data !== Parser.fail) {\n // complete\n var wantedBy = state.wantedBy;\n for (var i = wantedBy.length; i--; ) { // this line is hot\n var left = wantedBy[i];\n this.complete(left, state);\n }\n\n // special-case nullables\n if (state.reference === this.index) {\n // make sure future predictors of this rule get completed.\n var exp = state.rule.name;\n (this.completed[exp] = this.completed[exp] || []).push(state);\n }\n }\n\n } else {\n // queue scannable states\n var exp = state.rule.symbols[state.dot];\n if (typeof exp !== 'string') {\n this.scannable.push(state);\n continue;\n }\n\n // predict\n if (wants[exp]) {\n wants[exp].push(state);\n\n if (completed.hasOwnProperty(exp)) {\n var nulls = completed[exp];\n for (var i = 0; i < nulls.length; i++) {\n var right = nulls[i];\n this.complete(state, right);\n }\n }\n } else {\n wants[exp] = [state];\n this.predict(exp);\n }\n }\n }\n }\n\n Column.prototype.predict = function(exp) {\n var rules = this.grammar.byName[exp] || [];\n\n for (var i = 0; i < rules.length; i++) {\n var r = rules[i];\n var wantedBy = this.wants[exp];\n var s = new State(r, 0, this.index, wantedBy);\n this.states.push(s);\n }\n }\n\n Column.prototype.complete = function(left, right) {\n var copy = left.nextState(right);\n this.states.push(copy);\n }\n\n\n function Grammar(rules, start) {\n this.rules = rules;\n this.start = start || this.rules[0].name;\n var byName = this.byName = {};\n this.rules.forEach(function(rule) {\n if (!byName.hasOwnProperty(rule.name)) {\n byName[rule.name] = [];\n }\n byName[rule.name].push(rule);\n });\n }\n\n // So we can allow passing (rules, start) directly to Parser for backwards compatibility\n Grammar.fromCompiled = function(rules, start) {\n var lexer = rules.Lexer;\n if (rules.ParserStart) {\n start = rules.ParserStart;\n rules = rules.ParserRules;\n }\n var rules = rules.map(function (r) { return (new Rule(r.name, r.symbols, r.postprocess)); });\n var g = new Grammar(rules, start);\n g.lexer = lexer; // nb. storing lexer on Grammar is iffy, but unavoidable\n return g;\n }\n\n\n function StreamLexer() {\n this.reset(\"\");\n }\n\n StreamLexer.prototype.reset = function(data, state) {\n this.buffer = data;\n this.index = 0;\n this.line = state ? state.line : 1;\n this.lastLineBreak = state ? -state.col : 0;\n }\n\n StreamLexer.prototype.next = function() {\n if (this.index < this.buffer.length) {\n var ch = this.buffer[this.index++];\n if (ch === '\\n') {\n this.line += 1;\n this.lastLineBreak = this.index;\n }\n return {value: ch};\n }\n }\n\n StreamLexer.prototype.save = function() {\n return {\n line: this.line,\n col: this.index - this.lastLineBreak,\n }\n }\n\n StreamLexer.prototype.formatError = function(token, message) {\n // nb. this gets called after consuming the offending token,\n // so the culprit is index-1\n var buffer = this.buffer;\n if (typeof buffer === 'string') {\n var lines = buffer\n .split(\"\\n\")\n .slice(\n Math.max(0, this.line - 5), \n this.line\n );\n\n var nextLineBreak = buffer.indexOf('\\n', this.index);\n if (nextLineBreak === -1) nextLineBreak = buffer.length;\n var col = this.index - this.lastLineBreak;\n var lastLineDigits = String(this.line).length;\n message += \" at line \" + this.line + \" col \" + col + \":\\n\\n\";\n message += lines\n .map(function(line, i) {\n return pad(this.line - lines.length + i + 1, lastLineDigits) + \" \" + line;\n }, this)\n .join(\"\\n\");\n message += \"\\n\" + pad(\"\", lastLineDigits + col) + \"^\\n\";\n return message;\n } else {\n return message + \" at index \" + (this.index - 1);\n }\n\n function pad(n, length) {\n var s = String(n);\n return Array(length - s.length + 1).join(\" \") + s;\n }\n }\n\n function Parser(rules, start, options) {\n if (rules instanceof Grammar) {\n var grammar = rules;\n var options = start;\n } else {\n var grammar = Grammar.fromCompiled(rules, start);\n }\n this.grammar = grammar;\n\n // Read options\n this.options = {\n keepHistory: false,\n lexer: grammar.lexer || new StreamLexer,\n };\n for (var key in (options || {})) {\n this.options[key] = options[key];\n }\n\n // Setup lexer\n this.lexer = this.options.lexer;\n this.lexerState = undefined;\n\n // Setup a table\n var column = new Column(grammar, 0);\n var table = this.table = [column];\n\n // I could be expecting anything.\n column.wants[grammar.start] = [];\n column.predict(grammar.start);\n // TODO what if start rule is nullable?\n column.process();\n this.current = 0; // token index\n }\n\n // create a reserved token for indicating a parse fail\n Parser.fail = {};\n\n Parser.prototype.feed = function(chunk) {\n var lexer = this.lexer;\n lexer.reset(chunk, this.lexerState);\n\n var token;\n while (true) {\n try {\n token = lexer.next();\n if (!token) {\n break;\n }\n } catch (e) {\n // Create the next column so that the error reporter\n // can display the correctly predicted states.\n var nextColumn = new Column(this.grammar, this.current + 1);\n this.table.push(nextColumn);\n var err = new Error(this.reportLexerError(e));\n err.offset = this.current;\n err.token = e.token;\n throw err;\n }\n // We add new states to table[current+1]\n var column = this.table[this.current];\n\n // GC unused states\n if (!this.options.keepHistory) {\n delete this.table[this.current - 1];\n }\n\n var n = this.current + 1;\n var nextColumn = new Column(this.grammar, n);\n this.table.push(nextColumn);\n\n // Advance all tokens that expect the symbol\n var literal = token.text !== undefined ? token.text : token.value;\n var value = lexer.constructor === StreamLexer ? token.value : token;\n var scannable = column.scannable;\n for (var w = scannable.length; w--; ) {\n var state = scannable[w];\n var expect = state.rule.symbols[state.dot];\n // Try to consume the token\n // either regex or literal\n if (expect.test ? expect.test(value) :\n expect.type ? expect.type === token.type\n : expect.literal === literal) {\n // Add it\n var next = state.nextState({data: value, token: token, isToken: true, reference: n - 1});\n nextColumn.states.push(next);\n }\n }\n\n // Next, for each of the rules, we either\n // (a) complete it, and try to see if the reference row expected that\n // rule\n // (b) predict the next nonterminal it expects by adding that\n // nonterminal's start state\n // To prevent duplication, we also keep track of rules we have already\n // added\n\n nextColumn.process();\n\n // If needed, throw an error:\n if (nextColumn.states.length === 0) {\n // No states at all! This is not good.\n var err = new Error(this.reportError(token));\n err.offset = this.current;\n err.token = token;\n throw err;\n }\n\n // maybe save lexer state\n if (this.options.keepHistory) {\n column.lexerState = lexer.save()\n }\n\n this.current++;\n }\n if (column) {\n this.lexerState = lexer.save()\n }\n\n // Incrementally keep track of results\n this.results = this.finish();\n\n // Allow chaining, for whatever it's worth\n return this;\n };\n\n Parser.prototype.reportLexerError = function(lexerError) {\n var tokenDisplay, lexerMessage;\n // Planning to add a token property to moo's thrown error\n // even on erroring tokens to be used in error display below\n var token = lexerError.token;\n if (token) {\n tokenDisplay = \"input \" + JSON.stringify(token.text[0]) + \" (lexer error)\";\n lexerMessage = this.lexer.formatError(token, \"Syntax error\");\n } else {\n tokenDisplay = \"input (lexer error)\";\n lexerMessage = lexerError.message;\n }\n return this.reportErrorCommon(lexerMessage, tokenDisplay);\n };\n\n Parser.prototype.reportError = function(token) {\n var tokenDisplay = (token.type ? token.type + \" token: \" : \"\") + JSON.stringify(token.value !== undefined ? token.value : token);\n var lexerMessage = this.lexer.formatError(token, \"Syntax error\");\n return this.reportErrorCommon(lexerMessage, tokenDisplay);\n };\n\n Parser.prototype.reportErrorCommon = function(lexerMessage, tokenDisplay) {\n var lines = [];\n lines.push(lexerMessage);\n var lastColumnIndex = this.table.length - 2;\n var lastColumn = this.table[lastColumnIndex];\n var expectantStates = lastColumn.states\n .filter(function(state) {\n var nextSymbol = state.rule.symbols[state.dot];\n return nextSymbol && typeof nextSymbol !== \"string\";\n });\n\n if (expectantStates.length === 0) {\n lines.push('Unexpected ' + tokenDisplay + '. I did not expect any more input. Here is the state of my parse table:\\n');\n this.displayStateStack(lastColumn.states, lines);\n } else {\n lines.push('Unexpected ' + tokenDisplay + '. Instead, I was expecting to see one of the following:\\n');\n // Display a \"state stack\" for each expectant state\n // - which shows you how this state came to be, step by step.\n // If there is more than one derivation, we only display the first one.\n var stateStacks = expectantStates\n .map(function(state) {\n return this.buildFirstStateStack(state, []) || [state];\n }, this);\n // Display each state that is expecting a terminal symbol next.\n stateStacks.forEach(function(stateStack) {\n var state = stateStack[0];\n var nextSymbol = state.rule.symbols[state.dot];\n var symbolDisplay = this.getSymbolDisplay(nextSymbol);\n lines.push('A ' + symbolDisplay + ' based on:');\n this.displayStateStack(stateStack, lines);\n }, this);\n }\n lines.push(\"\");\n return lines.join(\"\\n\");\n }\n \n Parser.prototype.displayStateStack = function(stateStack, lines) {\n var lastDisplay;\n var sameDisplayCount = 0;\n for (var j = 0; j < stateStack.length; j++) {\n var state = stateStack[j];\n var display = state.rule.toString(state.dot);\n if (display === lastDisplay) {\n sameDisplayCount++;\n } else {\n if (sameDisplayCount > 0) {\n lines.push(' ^ ' + sameDisplayCount + ' more lines identical to this');\n }\n sameDisplayCount = 0;\n lines.push(' ' + display);\n }\n lastDisplay = display;\n }\n };\n\n Parser.prototype.getSymbolDisplay = function(symbol) {\n return getSymbolLongDisplay(symbol);\n };\n\n /*\n Builds a the first state stack. You can think of a state stack as the call stack\n of the recursive-descent parser which the Nearley parse algorithm simulates.\n A state stack is represented as an array of state objects. Within a\n state stack, the first item of the array will be the starting\n state, with each successive item in the array going further back into history.\n\n This function needs to be given a starting state and an empty array representing\n the visited states, and it returns an single state stack.\n\n */\n Parser.prototype.buildFirstStateStack = function(state, visited) {\n if (visited.indexOf(state) !== -1) {\n // Found cycle, return null\n // to eliminate this path from the results, because\n // we don't know how to display it meaningfully\n return null;\n }\n if (state.wantedBy.length === 0) {\n return [state];\n }\n var prevState = state.wantedBy[0];\n var childVisited = [state].concat(visited);\n var childResult = this.buildFirstStateStack(prevState, childVisited);\n if (childResult === null) {\n return null;\n }\n return [state].concat(childResult);\n };\n\n Parser.prototype.save = function() {\n var column = this.table[this.current];\n column.lexerState = this.lexerState;\n return column;\n };\n\n Parser.prototype.restore = function(column) {\n var index = column.index;\n this.current = index;\n this.table[index] = column;\n this.table.splice(index + 1);\n this.lexerState = column.lexerState;\n\n // Incrementally keep track of results\n this.results = this.finish();\n };\n\n // nb. deprecated: use save/restore instead!\n Parser.prototype.rewind = function(index) {\n if (!this.options.keepHistory) {\n throw new Error('set option `keepHistory` to enable rewinding')\n }\n // nb. recall column (table) indicies fall between token indicies.\n // col 0 -- token 0 -- col 1\n this.restore(this.table[index]);\n };\n\n Parser.prototype.finish = function() {\n // Return the possible parsings\n var considerations = [];\n var start = this.grammar.start;\n var column = this.table[this.table.length - 1]\n column.states.forEach(function (t) {\n if (t.rule.name === start\n && t.dot === t.rule.symbols.length\n && t.reference === 0\n && t.data !== Parser.fail) {\n considerations.push(t);\n }\n });\n return considerations.map(function(c) {return c.data; });\n };\n\n function getSymbolLongDisplay(symbol) {\n var type = typeof symbol;\n if (type === \"string\") {\n return symbol;\n } else if (type === \"object\") {\n if (symbol.literal) {\n return JSON.stringify(symbol.literal);\n } else if (symbol instanceof RegExp) {\n return 'character matching ' + symbol;\n } else if (symbol.type) {\n return symbol.type + ' token';\n } else if (symbol.test) {\n return 'token matching ' + String(symbol.test);\n } else {\n throw new Error('Unknown symbol type: ' + symbol);\n }\n }\n }\n\n function getSymbolShortDisplay(symbol) {\n var type = typeof symbol;\n if (type === \"string\") {\n return symbol;\n } else if (type === \"object\") {\n if (symbol.literal) {\n return JSON.stringify(symbol.literal);\n } else if (symbol instanceof RegExp) {\n return symbol.toString();\n } else if (symbol.type) {\n return '%' + symbol.type;\n } else if (symbol.test) {\n return '<' + String(symbol.test) + '>';\n } else {\n throw new Error('Unknown symbol type: ' + symbol);\n }\n }\n }\n\n return {\n Parser: Parser,\n Grammar: Grammar,\n Rule: Rule,\n };\n\n}));\n","(function(root, factory) {\n if (typeof define === 'function' && define.amd) {\n define([], factory) /* global define */\n } else if (typeof module === 'object' && module.exports) {\n module.exports = factory()\n } else {\n root.moo = factory()\n }\n}(this, function() {\n 'use strict';\n\n var hasOwnProperty = Object.prototype.hasOwnProperty\n var toString = Object.prototype.toString\n var hasSticky = typeof new RegExp().sticky === 'boolean'\n\n /***************************************************************************/\n\n function isRegExp(o) { return o && toString.call(o) === '[object RegExp]' }\n function isObject(o) { return o && typeof o === 'object' && !isRegExp(o) && !Array.isArray(o) }\n\n function reEscape(s) {\n return s.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&')\n }\n function reGroups(s) {\n var re = new RegExp('|' + s)\n return re.exec('').length - 1\n }\n function reCapture(s) {\n return '(' + s + ')'\n }\n function reUnion(regexps) {\n if (!regexps.length) return '(?!)'\n var source = regexps.map(function(s) {\n return \"(?:\" + s + \")\"\n }).join('|')\n return \"(?:\" + source + \")\"\n }\n\n function regexpOrLiteral(obj) {\n if (typeof obj === 'string') {\n return '(?:' + reEscape(obj) + ')'\n\n } else if (isRegExp(obj)) {\n // TODO: consider /u support\n if (obj.ignoreCase) throw new Error('RegExp /i flag not allowed')\n if (obj.global) throw new Error('RegExp /g flag is implied')\n if (obj.sticky) throw new Error('RegExp /y flag is implied')\n if (obj.multiline) throw new Error('RegExp /m flag is implied')\n return obj.source\n\n } else {\n throw new Error('Not a pattern: ' + obj)\n }\n }\n\n function pad(s, length) {\n if (s.length > length) {\n return s\n }\n return Array(length - s.length + 1).join(\" \") + s\n }\n\n function lastNLines(string, numLines) {\n var position = string.length\n var lineBreaks = 0;\n while (true) {\n var idx = string.lastIndexOf(\"\\n\", position - 1)\n if (idx === -1) {\n break;\n } else {\n lineBreaks++\n }\n position = idx\n if (lineBreaks === numLines) {\n break;\n }\n if (position === 0) {\n break;\n }\n }\n var startPosition = \n lineBreaks < numLines ?\n 0 : \n position + 1\n return string.substring(startPosition).split(\"\\n\")\n }\n\n function objectToRules(object) {\n var keys = Object.getOwnPropertyNames(object)\n var result = []\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i]\n var thing = object[key]\n var rules = [].concat(thing)\n if (key === 'include') {\n for (var j = 0; j < rules.length; j++) {\n result.push({include: rules[j]})\n }\n continue\n }\n var match = []\n rules.forEach(function(rule) {\n if (isObject(rule)) {\n if (match.length) result.push(ruleOptions(key, match))\n result.push(ruleOptions(key, rule))\n match = []\n } else {\n match.push(rule)\n }\n })\n if (match.length) result.push(ruleOptions(key, match))\n }\n return result\n }\n\n function arrayToRules(array) {\n var result = []\n for (var i = 0; i < array.length; i++) {\n var obj = array[i]\n if (obj.include) {\n var include = [].concat(obj.include)\n for (var j = 0; j < include.length; j++) {\n result.push({include: include[j]})\n }\n continue\n }\n if (!obj.type) {\n throw new Error('Rule has no type: ' + JSON.stringify(obj))\n }\n result.push(ruleOptions(obj.type, obj))\n }\n return result\n }\n\n function ruleOptions(type, obj) {\n if (!isObject(obj)) {\n obj = { match: obj }\n }\n if (obj.include) {\n throw new Error('Matching rules cannot also include states')\n }\n\n // nb. error and fallback imply lineBreaks\n var options = {\n defaultType: type,\n lineBreaks: !!obj.error || !!obj.fallback,\n pop: false,\n next: null,\n push: null,\n error: false,\n fallback: false,\n value: null,\n type: null,\n shouldThrow: false,\n }\n\n // Avoid Object.assign(), so we support IE9+\n for (var key in obj) {\n if (hasOwnProperty.call(obj, key)) {\n options[key] = obj[key]\n }\n }\n\n // type transform cannot be a string\n if (typeof options.type === 'string' && type !== options.type) {\n throw new Error(\"Type transform cannot be a string (type '\" + options.type + \"' for token '\" + type + \"')\")\n }\n\n // convert to array\n var match = options.match\n options.match = Array.isArray(match) ? match : match ? [match] : []\n options.match.sort(function(a, b) {\n return isRegExp(a) && isRegExp(b) ? 0\n : isRegExp(b) ? -1 : isRegExp(a) ? +1 : b.length - a.length\n })\n return options\n }\n\n function toRules(spec) {\n return Array.isArray(spec) ? arrayToRules(spec) : objectToRules(spec)\n }\n\n var defaultErrorRule = ruleOptions('error', {lineBreaks: true, shouldThrow: true})\n function compileRules(rules, hasStates) {\n var errorRule = null\n var fast = Object.create(null)\n var fastAllowed = true\n var unicodeFlag = null\n var groups = []\n var parts = []\n\n // If there is a fallback rule, then disable fast matching\n for (var i = 0; i < rules.length; i++) {\n if (rules[i].fallback) {\n fastAllowed = false\n }\n }\n\n for (var i = 0; i < rules.length; i++) {\n var options = rules[i]\n\n if (options.include) {\n // all valid inclusions are removed by states() preprocessor\n throw new Error('Inheritance is not allowed in stateless lexers')\n }\n\n if (options.error || options.fallback) {\n // errorRule can only be set once\n if (errorRule) {\n if (!options.fallback === !errorRule.fallback) {\n throw new Error(\"Multiple \" + (options.fallback ? \"fallback\" : \"error\") + \" rules not allowed (for token '\" + options.defaultType + \"')\")\n } else {\n throw new Error(\"fallback and error are mutually exclusive (for token '\" + options.defaultType + \"')\")\n }\n }\n errorRule = options\n }\n\n var match = options.match.slice()\n if (fastAllowed) {\n while (match.length && typeof match[0] === 'string' && match[0].length === 1) {\n var word = match.shift()\n fast[word.charCodeAt(0)] = options\n }\n }\n\n // Warn about inappropriate state-switching options\n if (options.pop || options.push || options.next) {\n if (!hasStates) {\n throw new Error(\"State-switching options are not allowed in stateless lexers (for token '\" + options.defaultType + \"')\")\n }\n if (options.fallback) {\n throw new Error(\"State-switching options are not allowed on fallback tokens (for token '\" + options.defaultType + \"')\")\n }\n }\n\n // Only rules with a .match are included in the RegExp\n if (match.length === 0) {\n continue\n }\n fastAllowed = false\n\n groups.push(options)\n\n // Check unicode flag is used everywhere or nowhere\n for (var j = 0; j < match.length; j++) {\n var obj = match[j]\n if (!isRegExp(obj)) {\n continue\n }\n\n if (unicodeFlag === null) {\n unicodeFlag = obj.unicode\n } else if (unicodeFlag !== obj.unicode && options.fallback === false) {\n throw new Error('If one rule is /u then all must be')\n }\n }\n\n // convert to RegExp\n var pat = reUnion(match.map(regexpOrLiteral))\n\n // validate\n var regexp = new RegExp(pat)\n if (regexp.test(\"\")) {\n throw new Error(\"RegExp matches empty string: \" + regexp)\n }\n var groupCount = reGroups(pat)\n if (groupCount > 0) {\n throw new Error(\"RegExp has capture groups: \" + regexp + \"\\nUse (?: … ) instead\")\n }\n\n // try and detect rules matching newlines\n if (!options.lineBreaks && regexp.test('\\n')) {\n throw new Error('Rule should declare lineBreaks: ' + regexp)\n }\n\n // store regex\n parts.push(reCapture(pat))\n }\n\n\n // If there's no fallback rule, use the sticky flag so we only look for\n // matches at the current index.\n //\n // If we don't support the sticky flag, then fake it using an irrefutable\n // match (i.e. an empty pattern).\n var fallbackRule = errorRule && errorRule.fallback\n var flags = hasSticky && !fallbackRule ? 'ym' : 'gm'\n var suffix = hasSticky || fallbackRule ? '' : '|'\n\n if (unicodeFlag === true) flags += \"u\"\n var combined = new RegExp(reUnion(parts) + suffix, flags)\n return {regexp: combined, groups: groups, fast: fast, error: errorRule || defaultErrorRule}\n }\n\n function compile(rules) {\n var result = compileRules(toRules(rules))\n return new Lexer({start: result}, 'start')\n }\n\n function checkStateGroup(g, name, map) {\n var state = g && (g.push || g.next)\n if (state && !map[state]) {\n throw new Error(\"Missing state '\" + state + \"' (in token '\" + g.defaultType + \"' of state '\" + name + \"')\")\n }\n if (g && g.pop && +g.pop !== 1) {\n throw new Error(\"pop must be 1 (in token '\" + g.defaultType + \"' of state '\" + name + \"')\")\n }\n }\n function compileStates(states, start) {\n var all = states.$all ? toRules(states.$all) : []\n delete states.$all\n\n var keys = Object.getOwnPropertyNames(states)\n if (!start) start = keys[0]\n\n var ruleMap = Object.create(null)\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i]\n ruleMap[key] = toRules(states[key]).concat(all)\n }\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i]\n var rules = ruleMap[key]\n var included = Object.create(null)\n for (var j = 0; j < rules.length; j++) {\n var rule = rules[j]\n if (!rule.include) continue\n var splice = [j, 1]\n if (rule.include !== key && !included[rule.include]) {\n included[rule.include] = true\n var newRules = ruleMap[rule.include]\n if (!newRules) {\n throw new Error(\"Cannot include nonexistent state '\" + rule.include + \"' (in state '\" + key + \"')\")\n }\n for (var k = 0; k < newRules.length; k++) {\n var newRule = newRules[k]\n if (rules.indexOf(newRule) !== -1) continue\n splice.push(newRule)\n }\n }\n rules.splice.apply(rules, splice)\n j--\n }\n }\n\n var map = Object.create(null)\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i]\n map[key] = compileRules(ruleMap[key], true)\n }\n\n for (var i = 0; i < keys.length; i++) {\n var name = keys[i]\n var state = map[name]\n var groups = state.groups\n for (var j = 0; j < groups.length; j++) {\n checkStateGroup(groups[j], name, map)\n }\n var fastKeys = Object.getOwnPropertyNames(state.fast)\n for (var j = 0; j < fastKeys.length; j++) {\n checkStateGroup(state.fast[fastKeys[j]], name, map)\n }\n }\n\n return new Lexer(map, start)\n }\n\n function keywordTransform(map) {\n\n // Use a JavaScript Map to map keywords to their corresponding token type\n // unless Map is unsupported, then fall back to using an Object:\n var isMap = typeof Map !== 'undefined'\n var reverseMap = isMap ? new Map : Object.create(null)\n\n var types = Object.getOwnPropertyNames(map)\n for (var i = 0; i < types.length; i++) {\n var tokenType = types[i]\n var item = map[tokenType]\n var keywordList = Array.isArray(item) ? item : [item]\n keywordList.forEach(function(keyword) {\n if (typeof keyword !== 'string') {\n throw new Error(\"keyword must be string (in keyword '\" + tokenType + \"')\")\n }\n if (isMap) {\n reverseMap.set(keyword, tokenType)\n } else {\n reverseMap[keyword] = tokenType\n }\n })\n }\n return function(k) {\n return isMap ? reverseMap.get(k) : reverseMap[k]\n }\n }\n\n /***************************************************************************/\n\n var Lexer = function(states, state) {\n this.startState = state\n this.states = states\n this.buffer = ''\n this.stack = []\n this.reset()\n }\n\n Lexer.prototype.reset = function(data, info) {\n this.buffer = data || ''\n this.index = 0\n this.line = info ? info.line : 1\n this.col = info ? info.col : 1\n this.queuedToken = info ? info.queuedToken : null\n this.queuedText = info ? info.queuedText: \"\";\n this.queuedThrow = info ? info.queuedThrow : null\n this.setState(info ? info.state : this.startState)\n this.stack = info && info.stack ? info.stack.slice() : []\n return this\n }\n\n Lexer.prototype.save = function() {\n return {\n line: this.line,\n col: this.col,\n state: this.state,\n stack: this.stack.slice(),\n queuedToken: this.queuedToken,\n queuedText: this.queuedText,\n queuedThrow: this.queuedThrow,\n }\n }\n\n Lexer.prototype.setState = function(state) {\n if (!state || this.state === state) return\n this.state = state\n var info = this.states[state]\n this.groups = info.groups\n this.error = info.error\n this.re = info.regexp\n this.fast = info.fast\n }\n\n Lexer.prototype.popState = function() {\n this.setState(this.stack.pop())\n }\n\n Lexer.prototype.pushState = function(state) {\n this.stack.push(this.state)\n this.setState(state)\n }\n\n var eat = hasSticky ? function(re, buffer) { // assume re is /y\n return re.exec(buffer)\n } : function(re, buffer) { // assume re is /g\n var match = re.exec(buffer)\n // will always match, since we used the |(?:) trick\n if (match[0].length === 0) {\n return null\n }\n return match\n }\n\n Lexer.prototype._getGroup = function(match) {\n var groupCount = this.groups.length\n for (var i = 0; i < groupCount; i++) {\n if (match[i + 1] !== undefined) {\n return this.groups[i]\n }\n }\n throw new Error('Cannot find token type for matched text')\n }\n\n function tokenToString() {\n return this.value\n }\n\n Lexer.prototype.next = function() {\n var index = this.index\n\n // If a fallback token matched, we don't need to re-run the RegExp\n if (this.queuedGroup) {\n var token = this._token(this.queuedGroup, this.queuedText, index)\n this.queuedGroup = null\n this.queuedText = \"\"\n return token\n }\n\n var buffer = this.buffer\n if (index === buffer.length) {\n return // EOF\n }\n\n // Fast matching for single characters\n var group = this.fast[buffer.charCodeAt(index)]\n if (group) {\n return this._token(group, buffer.charAt(index), index)\n }\n\n // Execute RegExp\n var re = this.re\n re.lastIndex = index\n var match = eat(re, buffer)\n\n // Error tokens match the remaining buffer\n var error = this.error\n if (match == null) {\n return this._token(error, buffer.slice(index, buffer.length), index)\n }\n\n var group = this._getGroup(match)\n var text = match[0]\n\n if (error.fallback && match.index !== index) {\n this.queuedGroup = group\n this.queuedText = text\n\n // Fallback tokens contain the unmatched portion of the buffer\n return this._token(error, buffer.slice(index, match.index), index)\n }\n\n return this._token(group, text, index)\n }\n\n Lexer.prototype._token = function(group, text, offset) {\n // count line breaks\n var lineBreaks = 0\n if (group.lineBreaks) {\n var matchNL = /\\n/g\n var nl = 1\n if (text === '\\n') {\n lineBreaks = 1\n } else {\n while (matchNL.exec(text)) { lineBreaks++; nl = matchNL.lastIndex }\n }\n }\n\n var token = {\n type: (typeof group.type === 'function' && group.type(text)) || group.defaultType,\n value: typeof group.value === 'function' ? group.value(text) : text,\n text: text,\n toString: tokenToString,\n offset: offset,\n lineBreaks: lineBreaks,\n line: this.line,\n col: this.col,\n }\n // nb. adding more props to token object will make V8 sad!\n\n var size = text.length\n this.index += size\n this.line += lineBreaks\n if (lineBreaks !== 0) {\n this.col = size - nl + 1\n } else {\n this.col += size\n }\n\n // throw, if no rule with {error: true}\n if (group.shouldThrow) {\n var err = new Error(this.formatError(token, \"invalid syntax\"))\n throw err;\n }\n\n if (group.pop) this.popState()\n else if (group.push) this.pushState(group.push)\n else if (group.next) this.setState(group.next)\n\n return token\n }\n\n if (typeof Symbol !== 'undefined' && Symbol.iterator) {\n var LexerIterator = function(lexer) {\n this.lexer = lexer\n }\n\n LexerIterator.prototype.next = function() {\n var token = this.lexer.next()\n return {value: token, done: !token}\n }\n\n LexerIterator.prototype[Symbol.iterator] = function() {\n return this\n }\n\n Lexer.prototype[Symbol.iterator] = function() {\n return new LexerIterator(this)\n }\n }\n\n Lexer.prototype.formatError = function(token, message) {\n if (token == null) {\n // An undefined token indicates EOF\n var text = this.buffer.slice(this.index)\n var token = {\n text: text,\n offset: this.index,\n lineBreaks: text.indexOf('\\n') === -1 ? 0 : 1,\n line: this.line,\n col: this.col,\n }\n }\n \n var numLinesAround = 2\n var firstDisplayedLine = Math.max(token.line - numLinesAround, 1)\n var lastDisplayedLine = token.line + numLinesAround\n var lastLineDigits = String(lastDisplayedLine).length\n var displayedLines = lastNLines(\n this.buffer, \n (this.line - token.line) + numLinesAround + 1\n )\n .slice(0, 5)\n var errorLines = []\n errorLines.push(message + \" at line \" + token.line + \" col \" + token.col + \":\")\n errorLines.push(\"\")\n for (var i = 0; i < displayedLines.length; i++) {\n var line = displayedLines[i]\n var lineNo = firstDisplayedLine + i\n errorLines.push(pad(String(lineNo), lastLineDigits) + \" \" + line);\n if (lineNo === token.line) {\n errorLines.push(pad(\"\", lastLineDigits + token.col + 1) + \"^\")\n }\n }\n return errorLines.join(\"\\n\")\n }\n\n Lexer.prototype.clone = function() {\n return new Lexer(this.states, this.state)\n }\n\n Lexer.prototype.has = function(tokenType) {\n return true\n }\n\n\n return {\n compile: compile,\n states: compileStates,\n error: Object.freeze({error: true}),\n fallback: Object.freeze({fallback: true}),\n keywords: keywordTransform,\n }\n\n}));\n","import { makeASTVisitor } from './AST/index'\nimport { type ASTNode, type EvaluatedNode, type NodeKind } from './AST/types'\nimport { PublicodesError, experimentalRuleWarning } from './error'\nimport { evaluationFunctions } from './evaluationFunctions'\nimport parsePublicodes, {\n\tContext,\n\tRawPublicodes,\n\tcopyContext,\n\tcreateContext,\n} from './parsePublicodes'\nimport { type Rule, type RuleNode } from './rule'\nimport * as utils from './ruleUtils'\nimport {\n\tcomputeTraversedVariableAfterEval,\n\tcomputeTraversedVariableBeforeEval,\n\tisTraversedVariablesBoundary,\n} from './traversedVariables'\n\nconst emptyCache = (): Cache => ({\n\t_meta: {\n\t\tevaluationRuleStack: [],\n\t\tparentRuleStack: [],\n\t},\n\ttraversedVariablesStack: undefined,\n\tnodes: new Map(),\n})\n\ntype Cache = {\n\tinversionFail?: boolean\n\t_meta: {\n\t\tevaluationRuleStack: Array\n\t\tparentRuleStack: Array\n\t\tcurrentContexteSituation?: string\n\t}\n\t/**\n\t * Every time we encounter a reference to a rule in an expression we add it\n\t * to the current Set of traversed variables. Because we evaluate the\n\t * expression graph “top to bottom” (ie. we start by the high-level goal and\n\t * recursively evaluate its dependencies), we need to handle rule\n\t * “boundaries”, so that when we “enter” in the evaluation of a dependency,\n\t * we start with a clear empty set of traversed variables. Then, when we go\n\t * back to the referencer rule, we need to add all to merge the two sets :\n\t * rules already traversed in the current expression and the one from the\n\t * reference.\n\t */\n\ttraversedVariablesStack?: Array>\n\tnodes: Map\n}\n\nexport {\n\treduceAST,\n\tmakeASTTransformer as transformAST,\n\ttraverseASTNode,\n} from './AST/index'\nexport { type Evaluation, type Unit } from './AST/types'\nexport { PublicodesError, isPublicodesError } from './error'\nexport { capitalise0, formatValue } from './format'\nexport { simplifyNodeUnit } from './nodeUnits'\nexport { parseExpression, type ExprAST } from './parseExpression'\nexport { default as serializeEvaluation } from './serializeEvaluation'\nexport { parseUnit, serializeUnit } from './units'\nexport { parsePublicodes, utils }\n\nexport { type ASTNode, type EvaluatedNode, type Rule, type RuleNode }\n\nexport type PublicodesExpression = string | Record | number\n\nexport type Logger = {\n\tlog(message: string): void\n\twarn(message: string): void\n\terror(message: string): void\n}\n\ntype Options = Partial<\n\tPick\n>\n\nexport type EvaluationFunction = (\n\tthis: Engine,\n\tnode: ASTNode & { nodeKind: Kind },\n) => { nodeKind: Kind } & EvaluatedNode\n\nexport type ParsedRules = Record>\n\nexport default class Engine {\n\tbaseContext: Context\n\tcontext: Context\n\tpublicParsedRules: ParsedRules\n\n\tcache: Cache = emptyCache()\n\n\t// The subEngines attribute is used to get an outside reference to the\n\t// `contexte` intermediate calculations. The `contexte` mechanism uses\n\t// `shallowCopy` to instanciate a new engine, and we want to keep a reference\n\t// to it for the documentation.\n\t//\n\t// TODO: A better implementation would to remove the \"runtime\" concept of\n\t// \"subEngines\" and instead duplicate all rules names in the scope of the\n\t// `contexte` as described in\n\t// https://github.com/publicodes/publicodes/discussions/92\n\tsubEngines: Array> = []\n\tsubEngineId: number | undefined\n\n\tconstructor(rules: RawPublicodes = {}, options: Options = {}) {\n\t\tconst initialContext = {\n\t\t\tdottedName: '' as const,\n\t\t\t...options,\n\t\t}\n\t\tthis.baseContext = createContext({\n\t\t\t...initialContext,\n\t\t\t...parsePublicodes(rules, initialContext),\n\t\t})\n\t\tthis.context = this.baseContext\n\n\t\tthis.publicParsedRules = {} as ParsedRules\n\t\tfor (const name in this.baseContext.parsedRules) {\n\t\t\tconst rule = this.baseContext.parsedRules[name]\n\t\t\tif (\n\t\t\t\t!(rule as RuleNode).private &&\n\t\t\t\tutils.isAccessible(this.baseContext.parsedRules, '', name)\n\t\t\t) {\n\t\t\t\tthis.publicParsedRules[name] = rule as RuleNode\n\t\t\t}\n\t\t}\n\t}\n\n\tresetCache() {\n\t\tthis.cache = emptyCache()\n\t}\n\n\tsetSituation(\n\t\tsituation: Partial> = {},\n\t\toptions: { keepPreviousSituation?: boolean } = {},\n\t) {\n\t\tthis.resetCache()\n\n\t\tconst keepPreviousSituation = options.keepPreviousSituation ?? false\n\n\t\tObject.keys(situation).forEach((name) => {\n\t\t\tif (!(name in this.baseContext.parsedRules)) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'EvaluationError',\n\t\t\t\t\t`Erreur lors de la mise à jour de la situation : ${name} n'existe pas dans la base de règle.`,\n\t\t\t\t\t{ dottedName: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (this.baseContext.parsedRules[name].private) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'EvaluationError',\n\t\t\t\t\t`Erreur lors de la mise à jour de la situation : ${name} est une règle privée (il n'est pas possible de modifier une règle privée).`,\n\t\t\t\t\t{ dottedName: name },\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\n\t\t// The situation is implemented as a special sub namespace `$SITUATION`,\n\t\t// present on each non-private rules\n\t\tconst situationToParse = Object.fromEntries(\n\t\t\tObject.entries(situation).map(([nom, value]) => [\n\t\t\t\t`[privé] ${nom} . $SITUATION`,\n\t\t\t\tvalue && typeof value === 'object' && 'nodeKind' in value ?\n\t\t\t\t\t{ valeur: value }\n\t\t\t\t:\tvalue,\n\t\t\t]),\n\t\t)\n\n\t\tconst savedBaseContext = copyContext(this.baseContext)\n\n\t\ttry {\n\t\t\tthis.context = {\n\t\t\t\t...this.baseContext,\n\t\t\t\t...parsePublicodes(\n\t\t\t\t\tsituationToParse as RawPublicodes,\n\t\t\t\t\tkeepPreviousSituation ? this.context : this.baseContext,\n\t\t\t\t),\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.baseContext = savedBaseContext\n\n\t\t\tthrow error\n\t\t}\n\t\tthis.baseContext = savedBaseContext\n\n\t\tObject.keys(situation).forEach((nom) => {\n\t\t\tif (utils.isExperimental(this.context.parsedRules, nom)) {\n\t\t\t\texperimentalRuleWarning(this.baseContext.logger, nom)\n\t\t\t}\n\t\t\tthis.checkExperimentalRule(\n\t\t\t\tthis.context.parsedRules[`${nom} . $SITUATION`],\n\t\t\t)\n\t\t})\n\t\treturn this\n\t}\n\n\tinversionFail(): boolean {\n\t\treturn !!this.cache.inversionFail\n\t}\n\n\tgetRule(dottedName: Name): ParsedRules[Name] {\n\t\tif (!(dottedName in this.baseContext.parsedRules)) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'UnknownRule',\n\t\t\t\t`La règle '${dottedName}' n'existe pas`,\n\t\t\t\t{ dottedName },\n\t\t\t)\n\t\t}\n\n\t\tif (!(dottedName in this.publicParsedRules)) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'PrivateRule',\n\t\t\t\t`La règle ${dottedName} est une règle privée.`,\n\t\t\t\t{ dottedName },\n\t\t\t)\n\t\t}\n\n\t\treturn this.publicParsedRules[dottedName]\n\t}\n\n\tgetParsedRules(): ParsedRules {\n\t\treturn this.publicParsedRules\n\t}\n\n\tevaluate(value: PublicodesExpression): EvaluatedNode {\n\t\tconst cachedNode = this.cache.nodes.get(value)\n\t\tif (cachedNode) {\n\t\t\treturn cachedNode\n\t\t}\n\t\tthis.context = Object.assign(\n\t\t\tthis.context,\n\t\t\tparsePublicodes(\n\t\t\t\t{\n\t\t\t\t\t'[privé] $EVALUATION':\n\t\t\t\t\t\tvalue && typeof value === 'object' && 'nodeKind' in value ?\n\t\t\t\t\t\t\t{ valeur: value }\n\t\t\t\t\t\t:\tvalue,\n\t\t\t\t},\n\t\t\t\tthis.context,\n\t\t\t),\n\t\t)\n\t\tthis.checkExperimentalRule(this.context.parsedRules['$EVALUATION'])\n\t\tthis.cache._meta = emptyCache()._meta\n\n\t\tconst evaluation = this.evaluateNode(\n\t\t\tthis.context.parsedRules['$EVALUATION'].explanation.valeur,\n\t\t)\n\t\tthis.cache.nodes.set(value, evaluation)\n\t\treturn evaluation\n\t}\n\n\tevaluateNode(parsedNode: T): EvaluatedNode & T {\n\t\tconst cachedNode = this.cache.nodes.get(parsedNode)\n\t\tlet traversedVariableBoundary: boolean = false\n\t\tif (this.cache.traversedVariablesStack) {\n\t\t\ttraversedVariableBoundary = isTraversedVariablesBoundary(\n\t\t\t\tthis.cache.traversedVariablesStack,\n\t\t\t\tparsedNode,\n\t\t\t)\n\t\t\tcomputeTraversedVariableBeforeEval(\n\t\t\t\tthis.cache.traversedVariablesStack,\n\t\t\t\tparsedNode,\n\t\t\t\tcachedNode,\n\t\t\t\tthis.publicParsedRules,\n\t\t\t\ttraversedVariableBoundary,\n\t\t\t)\n\t\t}\n\n\t\tif (cachedNode !== undefined) {\n\t\t\treturn cachedNode\n\t\t}\n\n\t\tif (!evaluationFunctions[parsedNode.nodeKind]) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'EvaluationError',\n\t\t\t\t`Unknown \"nodeKind\": ${parsedNode.nodeKind}`,\n\t\t\t\t{ dottedName: '' },\n\t\t\t)\n\t\t}\n\n\t\tconst evaluatedNode = evaluationFunctions[parsedNode.nodeKind].call(\n\t\t\tthis,\n\t\t\tparsedNode,\n\t\t)\n\t\tif (this.cache.traversedVariablesStack) {\n\t\t\tcomputeTraversedVariableAfterEval(\n\t\t\t\tthis.cache.traversedVariablesStack,\n\t\t\t\tevaluatedNode,\n\t\t\t\ttraversedVariableBoundary,\n\t\t\t)\n\t\t}\n\n\t\tthis.cache.nodes.set(parsedNode, evaluatedNode)\n\t\treturn evaluatedNode\n\t}\n\n\t/**\n\t * Shallow Engine instance copy. Keeps references to the original Engine instance attributes.\n\t */\n\tshallowCopy(): Engine {\n\t\tconst newEngine = new Engine()\n\t\tnewEngine.baseContext = copyContext(this.baseContext)\n\t\tnewEngine.context = copyContext(this.context)\n\t\tnewEngine.publicParsedRules = this.publicParsedRules\n\t\tnewEngine.cache = {\n\t\t\t...emptyCache(),\n\n\t\t\tnodes: new Map(this.cache.nodes),\n\t\t}\n\t\treturn newEngine\n\t}\n\n\tprivate checkExperimentalRule = makeASTVisitor((node) => {\n\t\tif (\n\t\t\tnode.nodeKind === 'reference' &&\n\t\t\tutils.isExperimental(this.context.parsedRules, node.dottedName as string)\n\t\t) {\n\t\t\texperimentalRuleWarning(\n\t\t\t\tthis.baseContext.logger,\n\t\t\t\tnode.dottedName as string,\n\t\t\t)\n\t\t}\n\t\treturn 'continue'\n\t})\n}\n","import { Logger } from '.'\n\n/**\n * Each error name with corresponding type in info value\n */\ninterface PublicodesErrorTypes {\n\tInternalError: {\n\t\tdottedName?: string\n\t}\n\tEngineError: Record\n\tSyntaxError: {\n\t\tdottedName: string\n\t}\n\tEvaluationError: {\n\t\tdottedName: string\n\t}\n\tUnknownRule: {\n\t\tdottedName: string\n\t}\n\tPrivateRule: {\n\t\tdottedName: string\n\t}\n}\n\n/**\n * Return true if `error` is a PublicodesError,\n * use `name` parameter to check and narow error type\n * @example\n * try {\n * \tnew Engine().evaluate()\n * } catch (error) {\n * \tif (isPublicodesError(error, 'EngineError')) {\n * \t\tconsole.log(error.info)\n * \t}\n * }\n */\nexport const isPublicodesError = (\n\terror: unknown,\n\tname?: Name,\n): error is PublicodesError<\n\ttypeof name extends undefined ? keyof PublicodesErrorTypes : Name\n> =>\n\terror instanceof PublicodesError &&\n\t(name === undefined ? true : error.name === name)\n\n/**\n * Generic error for Publicodes\n */\nexport class PublicodesError<\n\tName extends keyof PublicodesErrorTypes,\n> extends Error {\n\tname: Name\n\tinfo: PublicodesErrorTypes[Name]\n\n\tconstructor(\n\t\tname: Name,\n\t\tmessage: string,\n\t\tinfo: PublicodesErrorTypes[Name],\n\t\toriginalError?: Error,\n\t) {\n\t\tsuper(buildMessage(name, message, info, originalError))\n\t\tthis.name = name\n\t\tthis.info = info\n\t}\n}\n\nconst buildMessage = (\n\tname: string,\n\tmessage: string,\n\tinfo?: PublicodesErrorTypes[keyof PublicodesErrorTypes],\n\toriginalError?: Error,\n) => {\n\tconst types: Partial> = {\n\t\tSyntaxError: 'Erreur syntaxique',\n\t\tEvaluationError: \"Erreur d'évaluation\",\n\t\tUnknownRule: 'Règle inconnue',\n\t\tPrivateRule: 'Règle privée',\n\t}\n\tconst isError = /error/i.test(name)\n\n\treturn (\n\t\t`\\n[ ${types[name] ?? name} ]` +\n\t\t(info && 'dottedName' in info && info.dottedName?.length ?\n\t\t\t`\\n➡️ Dans la règle \"${info.dottedName}\"`\n\t\t:\t'') +\n\t\t`\\n${isError ? '✖️' : '⚠️'} ${message}` +\n\t\t(originalError ?\n\t\t\t'\\n' + (isError ? ' ' : 'ℹ️ ') + originalError.message\n\t\t:\t'')\n\t)\n}\n\n/**\n * @deprecated Throw an internal server error, replace this by `throw new PublicodesError('InternalError', ...)`\n */\nexport class PublicodesInternalError extends PublicodesError<'InternalError'> {\n\tconstructor(payload: Record) {\n\t\tsuper(\n\t\t\t'InternalError',\n\t\t\t`\nErreur interne du moteur.\n\nCette erreur est le signe d'un bug dans publicodes. Pour nous aider à le résoudre, vous pouvez copier ce texte dans un nouveau ticket : https://github.com/betagouv/mon-entreprise/issues/new.\n\npayload:\n${JSON.stringify(payload, null, 2)}\n`,\n\t\t\tpayload,\n\t\t)\n\t}\n}\n\n/**\n * Use this error in default case of a switch to check exhaustivity statically\n * inspired by https://github.com/ts-essentials/ts-essentials#exhaustive-switch-cases\n */\nexport class UnreachableCaseError extends PublicodesInternalError {\n\tconstructor(value: never) {\n\t\tsuper(value)\n\t}\n}\n\nexport function warning(\n\tlogger: Logger,\n\tmessage: string,\n\tinformation: { dottedName: string },\n\toriginalError?: Error,\n) {\n\tlogger.warn(\n\t\tbuildMessage('Avertissement', message, information, originalError),\n\t)\n}\n\nexport function experimentalRuleWarning(logger: Logger, dottedName: string) {\n\tlogger.warn(\n\t\tbuildMessage(\n\t\t\t'Avertissement',\n\t\t\t\"Cette règle est tagguée comme experimentale. \\n\\nCela veut dire qu'elle peut être modifiée, renommée, ou supprimée sans qu'il n'y ait de changement de version majeure dans l'API.\\n\",\n\t\t\t{ dottedName },\n\t\t),\n\t)\n}\n","export function addToMapSet(map: Map>, key: T, value: T) {\n\tif (map.has(key)) {\n\t\tmap.get(key)!.add(value)\n\t\treturn\n\t}\n\tmap.set(key, new Set([value]))\n}\n\nexport function mergeWithArray<\n\tN extends string | number | symbol,\n\tM extends string | number | symbol,\n\tT,\n>(obj1: Record>, obj2: Record>): Record>\n\nexport function mergeWithArray<\n\tN extends string | number | symbol,\n\tM extends string | number | symbol,\n\tT,\n>(\n\tobj1: Partial>>,\n\tobj2: Partial>>,\n): Partial>>\n\nexport function mergeWithArray(\n\tobj1: Partial>>,\n\tobj2: Partial>>,\n): Partial>> {\n\treturn (Object.entries(obj2) as Array<[K, Array]>).reduce(\n\t\t(obj, [key, value]) => ({\n\t\t\t...obj,\n\t\t\t[key]: [...(obj[key] ?? []), ...value],\n\t\t}),\n\t\tobj1,\n\t) as Partial>>\n}\n\nexport const weakCopyObj = >(obj: T): T => {\n\tconst copy = {} as T\n\tfor (const key in obj) {\n\t\tcopy[key] = obj[key]\n\t}\n\n\treturn copy\n}\n","import { ParsedRules } from '..'\nimport { UnreachableCaseError } from '../error'\nimport { TrancheNodes } from '../mecanisms/trancheUtils'\nimport { ReferenceNode } from '../reference'\nimport { ReplacementRule } from '../replacement'\nimport { weakCopyObj } from '../utils'\nimport {\n\tASTNode,\n\tASTTransformer,\n\tASTVisitor,\n\tNodeKind,\n\tTraverseFunction,\n} from './types'\n\n/**\n\tThis function creates a transormation of the AST from on a simpler\n\tcallback function `fn`\n\n\t`fn` will be called with the nodes of the ASTTree during the exploration\n\n\tThe outcome of the callback function has an influence on the exploration of the AST :\n\t- `false`, the node is not updated and the exploration does not continue further down this branch\n\t- `undefined`, the node is not updated but the exploration continues and its children will be transformed\n\t- `ASTNode`, the node is transformed to the new value and the exploration does not continue further down the branch\n\n\t`updateFn` : It is possible to specifically use the updated version of a child\n\tby using the function passed as second argument. The returned value will be the\n\ttransformed version of the node.\n\t*/\nexport function makeASTTransformer(\n\tfn: (node: ASTNode, transform: ASTTransformer) => ASTNode | undefined | false,\n\tstopOnUpdate = true,\n): ASTTransformer {\n\tfunction transform(node: ASTNode): ASTNode {\n\t\tconst updatedNode = fn(node, transform)\n\t\tif (updatedNode === false) {\n\t\t\treturn node\n\t\t}\n\t\tif (updatedNode === undefined) {\n\t\t\treturn traverseASTNode(transform, node)\n\t\t}\n\t\treturn stopOnUpdate ? updatedNode : traverseASTNode(transform, updatedNode)\n\t}\n\treturn transform\n}\nexport function makeASTVisitor(\n\tfn: (node: ASTNode, visit: ASTVisitor) => 'continue' | 'stop',\n): ASTVisitor {\n\tfunction visit(node: ASTNode) {\n\t\tswitch (fn(node, visit)) {\n\t\t\tcase 'continue':\n\t\t\t\ttraverseASTNode(transformizedVisit, node)\n\t\t\t\treturn\n\t\t\tcase 'stop':\n\t\t\t\treturn\n\t\t}\n\t}\n\tconst transformizedVisit: ASTTransformer = (node) => {\n\t\tvisit(node)\n\t\treturn node\n\t}\n\treturn visit\n}\n\n// Can be made more flexible with other args like a filter function (ASTNode -> Bool).\nexport function iterAST(\n\tchildrenSelector: (node: ASTNode) => Iterable,\n\tnode: ASTNode,\n): ASTNode[] {\n\tfunction* iterate(node: ASTNode): IterableIterator {\n\t\tyield node\n\t\tconst selectedSubNodes = childrenSelector(node)\n\t\tfor (const subNode of selectedSubNodes) yield* iterate(subNode)\n\t}\n\treturn [...iterate(node)]\n}\n\n/**\n * This function allows to construct a specific value while exploring the AST with\n * a simple reducing function as argument.\n *\n * `fn` will be called with the currently reduced value `acc` and the current node of the AST\n *\n * If the callback function returns:\n * - `undefined`, the exploration continues further down and all the children are reduced\n * \tsuccessively to a single value\n * - `T`, the reduced value is returned\n *\n * `reduceFn` : It is possible to specifically use the reduced value of a child\n * by using the function passed as second argument. The returned value will be the reduced version\n * of the node\n */\nexport function reduceAST(\n\tfn: (acc: T, n: ASTNode, reduceFn: (n: ASTNode) => T) => T | undefined,\n\tstart: T,\n\tnode: ASTNode,\n): T {\n\tfunction traverseFn(acc: T, node: ASTNode): T {\n\t\tconst result = fn(acc, node, traverseFn.bind(null, start))\n\t\tif (result === undefined) {\n\t\t\treturn getChildrenNodes(node).reduce(traverseFn, acc)\n\t\t}\n\t\treturn result\n\t}\n\treturn traverseFn(start, node)\n}\n\nexport function getChildrenNodes(node: ASTNode): ASTNode[] {\n\tconst nodes: ASTNode[] = []\n\ttraverseASTNode((node) => {\n\t\tnodes.push(node)\n\t\treturn node\n\t}, node)\n\treturn nodes\n}\n\nexport function traverseParsedRules(\n\tfn: ASTTransformer,\n\tparsedRules: ParsedRules,\n): ParsedRules {\n\tconst ret = {} as Record\n\tfor (const name in parsedRules) {\n\t\tret[name] = fn(parsedRules[name])\n\t}\n\n\treturn ret as ParsedRules\n}\n\n/**\n * Apply a transform function on children. Not recursive.\n */\nexport const traverseASTNode: TraverseFunction = (fn, node) => {\n\tnode = traverseSourceMap(fn, node)\n\tswitch (node.nodeKind) {\n\t\tcase 'rule':\n\t\t\treturn traverseRuleNode(fn, node)\n\t\tcase 'reference':\n\t\tcase 'constant':\n\t\t\treturn node\n\t\tcase 'arrondi':\n\t\t\treturn traverseArrondiNode(fn, node)\n\t\tcase 'simplifier unité':\n\t\tcase 'variable manquante':\n\t\tcase 'est non applicable':\n\t\tcase 'est non défini':\n\t\t\treturn traverseUnaryOperationNode(fn, node)\n\t\tcase 'barème':\n\t\tcase 'taux progressif':\n\t\tcase 'grille':\n\t\t\treturn traverseNodeWithTranches(fn, node)\n\t\tcase 'une possibilité':\n\t\t\treturn traverseArrayNode(fn, node)\n\t\tcase 'durée':\n\t\t\treturn traverseDuréeNode(fn, node)\n\t\tcase 'résoudre référence circulaire':\n\t\t\treturn traverseRésoudreRéférenceCirculaireNode(fn, node)\n\t\tcase 'inversion':\n\t\t\treturn traverseInversionNode(fn, node)\n\t\tcase 'operation':\n\t\t\treturn traverseOperationNode(fn, node)\n\n\t\tcase 'contexte':\n\t\t\treturn traverseContexteNode(fn, node)\n\t\tcase 'unité':\n\t\t\treturn traverseUnitéNode(fn, node)\n\t\tcase 'variations':\n\t\t\treturn traverseVariationNode(fn, node)\n\t\tcase 'replacementRule':\n\t\t\treturn traverseReplacementNode(fn, node)\n\t\tcase 'texte':\n\t\t\treturn traverseTextNode(fn, node)\n\t\tcase 'condition':\n\t\t\treturn traverseConditionNode(fn, node)\n\n\t\tdefault:\n\t\t\tthrow new UnreachableCaseError(node)\n\t}\n}\n\nconst traverseSourceMap: TraverseFunction = (fn, node) => {\n\tif (!('sourceMap' in node) || !node.sourceMap || !node.sourceMap.args) {\n\t\treturn node\n\t}\n\tconst sourceMap = node.sourceMap\n\n\tconst args = {}\n\tfor (const key in sourceMap.args) {\n\t\tconst value = sourceMap.args[key]\n\t\targs[key] = Array.isArray(value) ? value.map((v) => fn(v)) : fn(value)\n\t}\n\n\treturn {\n\t\t...node,\n\t\tsourceMap: {\n\t\t\t...sourceMap,\n\t\t\targs,\n\t\t},\n\t}\n}\n\nconst traverseRuleNode: TraverseFunction<'rule'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\tcopy.suggestions = {}\n\tfor (const key in node.suggestions) {\n\t\tcopy.suggestions[key] = fn(node.suggestions[key])\n\t}\n\tcopy.replacements = node.replacements.map(fn) as Array\n\tcopy.explanation = {\n\t\truleDisabledByItsParent: node.explanation.ruleDisabledByItsParent,\n\t\tnullableParent:\n\t\t\tnode.explanation.nullableParent ?\n\t\t\t\tfn(node.explanation.nullableParent)\n\t\t\t:\tundefined,\n\t\tparents: node.explanation.parents.map(fn),\n\t\tvaleur: fn(node.explanation.valeur),\n\t}\n\n\treturn copy\n}\n\nconst traverseReplacementNode: TraverseFunction<'replacementRule'> = (\n\tfn,\n\tnode,\n) =>\n\t({\n\t\t...node,\n\t\tdefinitionRule: fn(node.definitionRule),\n\t\treplacedReference: fn(node.replacedReference),\n\t\twhiteListedNames: node.whiteListedNames.map(fn),\n\t\tblackListedNames: node.blackListedNames.map(fn),\n\t}) as ReplacementRule\n\nconst traverseUnaryOperationNode: TraverseFunction<\n\t| 'simplifier unité'\n\t| 'est non applicable'\n\t| 'est non défini'\n\t| 'variable manquante'\n> = (fn, node) => ({\n\t...node,\n\texplanation: fn(node.explanation),\n})\n\nfunction traverseTranche(fn: (n: ASTNode) => ASTNode, tranches: TrancheNodes) {\n\treturn tranches.map((tranche) => ({\n\t\t...tranche,\n\t\t...(tranche.plafond && { plafond: fn(tranche.plafond) }),\n\t\t...('montant' in tranche && { montant: fn(tranche.montant) }),\n\t\t...('taux' in tranche && { taux: fn(tranche.taux) }),\n\t}))\n}\nconst traverseNodeWithTranches: TraverseFunction<\n\t'barème' | 'taux progressif' | 'grille'\n> = (fn, node) => ({\n\t...node,\n\texplanation: {\n\t\tassiette: fn(node.explanation.assiette),\n\t\tmultiplicateur: fn(node.explanation.multiplicateur),\n\t\ttranches: traverseTranche(fn, node.explanation.tranches),\n\t},\n})\n\nconst traverseArrayNode: TraverseFunction<'une possibilité'> = (fn, node) => ({\n\t...node,\n\texplanation: node.explanation.map(fn),\n})\n\nconst traverseOperationNode: TraverseFunction<'operation'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\tcopy.explanation = [fn(node.explanation[0]), fn(node.explanation[1])]\n\n\treturn copy\n}\n\nconst traverseDuréeNode: TraverseFunction<'durée'> = (fn, node) => ({\n\t...node,\n\texplanation: {\n\t\tdepuis: fn(node.explanation.depuis),\n\t\t\"jusqu'à\": fn(node.explanation[\"jusqu'à\"]),\n\t},\n})\n\nconst traverseInversionNode: TraverseFunction<'inversion'> = (fn, node) => ({\n\t...node,\n\texplanation: {\n\t\t...node.explanation,\n\t\tinversionCandidates: node.explanation.inversionCandidates.map(fn) as any, // TODO\n\t},\n})\n\nconst traverseArrondiNode: TraverseFunction<'arrondi'> = (fn, node) => ({\n\t...node,\n\texplanation: {\n\t\tvaleur: fn(node.explanation.valeur),\n\t\tarrondi: fn(node.explanation.arrondi),\n\t},\n})\n\nconst traverseRésoudreRéférenceCirculaireNode: TraverseFunction<\n\t'résoudre référence circulaire'\n> = (fn, node) => ({\n\t...node,\n\texplanation: {\n\t\t...node.explanation,\n\t\tvaleur: fn(node.explanation.valeur),\n\t},\n})\n\nconst traverseTextNode: TraverseFunction<'texte'> = (fn, node) => ({\n\t...node,\n\texplanation: node.explanation.map((element) =>\n\t\ttypeof element === 'string' ? element : fn(element),\n\t),\n})\n\nconst traverseContexteNode: TraverseFunction<'contexte'> = (fn, node) => ({\n\t...node,\n\texplanation: {\n\t\t...node.explanation,\n\t\tcontexte: node.explanation.contexte.map(([name, value]) => [\n\t\t\tfn(name) as ReferenceNode,\n\t\t\tfn(value),\n\t\t]),\n\t\tvaleur: fn(node.explanation.valeur),\n\t},\n})\n\nconst traverseUnitéNode: TraverseFunction<'unité'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\tcopy.explanation = fn(node.explanation)\n\n\treturn copy\n}\n\nconst traverseVariationNode: TraverseFunction<'variations'> = (fn, node) => ({\n\t...node,\n\texplanation: node.explanation.map(({ condition, consequence }) => ({\n\t\tcondition: fn(condition),\n\t\tconsequence: consequence && fn(consequence),\n\t})),\n})\n\nconst traverseConditionNode: TraverseFunction<'condition'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\tcopy.explanation = {\n\t\tsi: fn(node.explanation.si),\n\t\talors: fn(node.explanation.alors),\n\t\tsinon: fn(node.explanation.sinon),\n\t}\n\n\treturn copy\n}\n","import { EvaluationFunction, PublicodesError } from '.'\nimport { ASTNode } from './AST/types'\n\nexport let evaluationFunctions = {\n\tconstant: (node) => node,\n} as any\n\nexport function registerEvaluationFunction<\n\tNodeName extends ASTNode['nodeKind'],\n>(nodeKind: NodeName, evaluationFunction: EvaluationFunction) {\n\tevaluationFunctions ??= {}\n\tif (evaluationFunctions[nodeKind]) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t`Multiple evaluation functions registered for the nodeKind \\x1b[4m${nodeKind}`,\n\t\t\t{ dottedName: '' },\n\t\t)\n\t}\n\tevaluationFunctions[nodeKind] = evaluationFunction\n}\n","import { ParsedRules } from '.'\nimport { ASTNode, ConstantNode } from './AST/types'\n\nexport type NodesTypes = WeakMap\n\n// TODO: Currently only handle nullability, but the infering logic should be\n// extended to support the full unit type system.\nexport type InferedType = {\n\tisNullable: boolean | undefined\n} & Pick\n\nconst UNDEFINED_TYPE = {\n\tisNullable: undefined,\n\ttype: undefined,\n}\n\nexport default function inferNodesTypes(\n\tnewRulesNames: Array,\n\tparsedRules: ParsedRules,\n\tnodesTypes: NodesTypes,\n) {\n\tfunction inferNodeUnitAndCache(node: ASTNode): InferedType {\n\t\tif (!node || typeof node !== 'object') {\n\t\t\treturn UNDEFINED_TYPE\n\t\t}\n\t\tif (nodesTypes.has(node)) {\n\t\t\treturn nodesTypes.get(node)!\n\t\t}\n\t\t// Sometimes there are cycles, so we need to prevent infinite loop by setting a default\n\t\tnodesTypes.set(node, UNDEFINED_TYPE)\n\t\tconst type = inferNodeType(node)\n\t\tnodesTypes.set(node, type)\n\t\treturn type\n\t}\n\n\tfunction inferNodeType(node: ASTNode): InferedType {\n\t\tswitch (node.nodeKind) {\n\t\t\tcase 'barème':\n\t\t\tcase 'durée':\n\t\t\tcase 'grille':\n\t\t\tcase 'taux progressif':\n\t\t\t\treturn { isNullable: false, type: 'number' }\n\t\t\tcase 'est non défini':\n\t\t\tcase 'est non applicable':\n\t\t\t\treturn { isNullable: false, type: 'boolean' }\n\n\t\t\tcase 'constant':\n\t\t\t\treturn {\n\t\t\t\t\tisNullable: node.isNullable ?? node.nodeValue === null,\n\t\t\t\t\ttype: node.type,\n\t\t\t\t}\n\t\t\tcase 'operation':\n\t\t\t\treturn {\n\t\t\t\t\tisNullable:\n\t\t\t\t\t\t['<', '<=', '>', '>=', '/', '*'].includes(node.operationKind) ?\n\t\t\t\t\t\t\tinferNodeUnitAndCache(node.explanation[0]).isNullable ||\n\t\t\t\t\t\t\tinferNodeUnitAndCache(node.explanation[1]).isNullable\n\t\t\t\t\t\t: node.operationKind === '-' ?\n\t\t\t\t\t\t\tinferNodeUnitAndCache(node.explanation[0]).isNullable\n\t\t\t\t\t\t:\tfalse,\n\t\t\t\t\ttype:\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\t['<', '<=', '>', '>=', '=', '!=', 'et', 'ou'].includes(\n\t\t\t\t\t\t\t\tnode.operationKind,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t) ?\n\t\t\t\t\t\t\t'boolean'\n\t\t\t\t\t\t:\t'number',\n\t\t\t\t}\n\n\t\t\tcase 'inversion':\n\t\t\tcase 'replacementRule':\n\t\t\tcase 'résoudre référence circulaire':\n\t\t\t\treturn { isNullable: false, type: 'number' }\n\t\t\tcase 'texte':\n\t\t\tcase 'une possibilité':\n\t\t\t\treturn { isNullable: false, type: 'string' }\n\n\t\t\tcase 'contexte':\n\t\t\tcase 'rule':\n\t\t\tcase 'arrondi':\n\t\t\t\treturn inferNodeUnitAndCache(node.explanation.valeur)\n\t\t\tcase 'unité':\n\t\t\tcase 'simplifier unité':\n\t\t\tcase 'variable manquante':\n\t\t\t\treturn inferNodeUnitAndCache(node.explanation)\n\t\t\tcase 'condition':\n\t\t\t\treturn {\n\t\t\t\t\tisNullable: [\n\t\t\t\t\t\tnode.explanation.si,\n\t\t\t\t\t\tnode.explanation.alors,\n\t\t\t\t\t\tnode.explanation.sinon,\n\t\t\t\t\t].some((n) => inferNodeUnitAndCache(n).isNullable),\n\t\t\t\t\ttype:\n\t\t\t\t\t\tinferNodeUnitAndCache(node.explanation.alors).type ??\n\t\t\t\t\t\tinferNodeUnitAndCache(node.explanation.sinon).type,\n\t\t\t\t}\n\n\t\t\tcase 'variations': {\n\t\t\t\tconst consequencesTypes = node.explanation.map(({ consequence }) =>\n\t\t\t\t\tinferNodeUnitAndCache(consequence),\n\t\t\t\t)\n\t\t\t\treturn {\n\t\t\t\t\tisNullable: consequencesTypes.some(\n\t\t\t\t\t\t(consequence) => consequence.isNullable,\n\t\t\t\t\t),\n\t\t\t\t\ttype: consequencesTypes\n\t\t\t\t\t\t.map((c) => c.type)\n\t\t\t\t\t\t.find((type) => type !== undefined),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcase 'reference':\n\t\t\t\treturn inferNodeUnitAndCache(parsedRules[node.dottedName as string])\n\t\t}\n\t}\n\n\tnewRulesNames.forEach((name) => {\n\t\tconst rule = parsedRules[name]\n\t\tinferNodeUnitAndCache(rule)\n\t\trule.explanation.parents.forEach(inferNodeUnitAndCache)\n\t})\n\n\treturn nodesTypes\n}\n","import { ASTNode, ConstantNode, EvaluatedNode, Evaluation } from './AST/types'\n\nexport const collectNodeMissing = (\n\tnode: EvaluatedNode | ASTNode,\n): Record =>\n\t'missingVariables' in node ? node.missingVariables : {}\n\nexport const bonus = (missings: Record = {}) =>\n\tObject.fromEntries(\n\t\tObject.entries(missings).map(([key, value]) => [key, value + 1]),\n\t)\nexport const mergeMissing = (\n\tleft: Record | undefined = {},\n\tright: Record | undefined = {},\n): Record =>\n\tObject.fromEntries(\n\t\t[...Object.keys(left), ...Object.keys(right)].map((key) => [\n\t\t\tkey,\n\t\t\t(left[key] ?? 0) + (right[key] ?? 0),\n\t\t]),\n\t)\n\nexport const mergeAllMissing = (missings: Array) =>\n\tmissings.map(collectNodeMissing).reduce(mergeMissing, {})\n\nexport const defaultNode = (nodeValue: Evaluation) =>\n\t({\n\t\tnodeValue,\n\t\ttype: typeof nodeValue,\n\t\tisDefault: true,\n\t\tnodeKind: 'constant',\n\t}) as ConstantNode\n\nexport const notApplicableNode = {\n\tnodeKind: 'constant',\n\tnodeValue: null,\n\tmissingVariables: {},\n\ttype: undefined,\n\tisNullable: true,\n} as EvaluatedNode<'constant'>\n\nexport const undefinedNode = {\n\tnodeKind: 'constant',\n\tnodeValue: undefined,\n\tmissingVariables: {},\n\ttype: undefined,\n\tisNullable: false,\n} as EvaluatedNode<'constant'>\n\nexport const undefinedNumberNode = {\n\t...undefinedNode,\n\ttype: 'number',\n} as EvaluatedNode<'constant'>\n","import { PublicodesExpression } from '..'\nimport { makeASTTransformer } from '../AST'\nimport { ASTNode } from '../AST/types'\nimport { PublicodesError } from '../error'\nimport parse from '../parse'\nimport { Context, createContext } from '../parsePublicodes'\n\nexport function createParseInlinedMecanism(\n\tname: string,\n\targs: Record,\n\tbody: PublicodesExpression,\n) {\n\tlet parsedBody\n\tlet parsedDefaultArgs\n\tfunction parseInlineMecanism(providedArgs, context) {\n\t\tparsedBody ??= parse(body, createContext({ dottedName: 'INLINE_MECANISM' }))\n\t\tparsedDefaultArgs ??= {}\n\t\tfor (const name in args) {\n\t\t\tif ('par défaut' in args[name]) {\n\t\t\t\tparsedDefaultArgs[name] = parse(\n\t\t\t\t\targs[name]['par défaut'],\n\t\t\t\t\tcreateContext({}),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// Case of unary mecanism\n\t\tif (Object.keys(args).length === 1 && 'valeur' in args) {\n\t\t\tprovidedArgs = {\n\t\t\t\tvaleur: providedArgs,\n\t\t\t}\n\t\t}\n\n\t\tconst parsedProvidedArgs = {}\n\t\tfor (const name in providedArgs) {\n\t\t\tparsedProvidedArgs[name] = parse(providedArgs[name], context)\n\t\t}\n\n\t\tconst parsedInlineMecanism = makeASTTransformer((node) => {\n\t\t\tif (node.nodeKind !== 'reference' || !(node.name in args)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst argName = node.name\n\t\t\tif (argName in parsedProvidedArgs) {\n\t\t\t\treturn parsedProvidedArgs[argName]\n\t\t\t}\n\t\t\tif (argName in parsedDefaultArgs) {\n\t\t\t\treturn parsedDefaultArgs[argName]\n\t\t\t}\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'SyntaxError',\n\t\t\t\t`Il manque la clé '${argName} dans le mécanisme ${name}`,\n\t\t\t\t{ dottedName: argName },\n\t\t\t)\n\t\t})(parsedBody)\n\n\t\tparsedInlineMecanism.sourceMap = {\n\t\t\tmecanismName: name,\n\t\t\targs: parsedProvidedArgs,\n\t\t}\n\n\t\treturn parsedInlineMecanism\n\t}\n\n\tparseInlineMecanism.nom = name\n\n\treturn Object.assign(parseInlineMecanism, 'name', {\n\t\tvalue: `parse${toCamelCase(name)}Inline`,\n\t})\n}\n\n/**\n Note : Les transformations de mécanisme opérant sur les listes sont plus couteuses que celles opérant sur des scalaires.\n\n Cela vient du fait qu'il n'y a pas la possibilité de définir ces transformations dans publicodes : il manque le type liste et les opérations de bases associées (reduce, map).\n\n On doit donc déplier l'opération statiquement, au parsing, ce qui prend plus de temps, au parsing et à l'évaluation. somme: [1,2,3] est transformé en (1 + 2) + 3).\n\n De manière général, les baisse en performances de cette PR sont attenduee : il s'agit d'une contrepartie logique de l'utilisation de mécanisme de base publicodes. Ce qu'on gagne en solidité de l'évaluation & en amélioration du typage, on le perd en performance. C'est logique puisque l'evaluation de ces mécanisme n'est plus du JS natif mais passe par une structure intermédiaire.\n\n Pour améliorer les perfs, il y a plusieurs pistes :\n\n\t- optimiser d'avantage les opérations de bases\n\t- ajouter les listes et les opérations sur les listes dans publicodes\n\t- ajouter une implémentation \"native\" de certains mécanismes utilisés (on gagne quand même à les décomposer en mécanismes de base pour la partie spécification et typage).\n */\nexport function createParseInlinedMecanismWithArray(\n\tname: string,\n\targs: Record,\n\tbody: (\n\t\targs: Record>,\n\t) => PublicodesExpression,\n) {\n\tfunction parseInlineMecanism(providedArgs, context: Context) {\n\t\t// Case of unary mecanism\n\t\tif (Object.keys(args).length === 1 && 'valeur' in args) {\n\t\t\tprovidedArgs = {\n\t\t\t\tvaleur: providedArgs,\n\t\t\t}\n\t\t}\n\n\t\tconst parsedProvidedArgs = {}\n\t\tfor (const name in providedArgs) {\n\t\t\tconst value = providedArgs[name]\n\t\t\tparsedProvidedArgs[name] =\n\t\t\t\tArray.isArray(value) ?\n\t\t\t\t\tvalue.map((v) => parse(v, context))\n\t\t\t\t:\tparse(value, context)\n\t\t}\n\n\t\tconst parsedInlineMecanism = parse(body(parsedProvidedArgs), context)\n\t\tparsedInlineMecanism.sourceMap = {\n\t\t\tmecanismName: name,\n\t\t\targs: parsedProvidedArgs,\n\t\t}\n\t\treturn parsedInlineMecanism\n\t}\n\n\tparseInlineMecanism.nom = name\n\n\treturn Object.assign(parseInlineMecanism, 'name', {\n\t\tvalue: `parse${toCamelCase(name)}Inline`,\n\t})\n}\n\nfunction toCamelCase(str: string) {\n\treturn str\n\t\t.replace(/(?:^\\w|[A-Z]|\\b\\w)/g, (ltr) => ltr.toUpperCase())\n\t\t.replace(/\\s+/g, '')\n}\n","import { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'abattement',\n\t{\n\t\tabattement: {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\t'-': ['valeur', 'abattement'],\n\t\tplancher: 0,\n\t},\n)\n","import { notApplicableNode } from '../evaluationUtils'\nimport { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'applicable si',\n\t{\n\t\t'applicable si': {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: 'applicable si != non',\n\t\t\talors: 'valeur',\n\t\t\tsinon: notApplicableNode,\n\t\t},\n\t},\n)\n","import { BaseUnit, Evaluation, Unit } from './AST/types'\nimport { PublicodesError } from './error'\n\nexport type getUnitKey = (writtenUnit: string) => string\nexport type formatUnit = (unit: string, count: number) => string\n\nexport const parseUnit = (\n\tstring: string,\n\tgetUnitKey: getUnitKey = (x) => x,\n): Unit => {\n\tif (string.includes(' /') || string.includes('/ ')) {\n\t\tthrow new Error(\n\t\t\t`L'unité \"${string}\" ne doit pas contenir d'espace avant et après \"/\"`,\n\t\t)\n\t}\n\tconst [a, ...b] = string.split('/')\n\t// denominator could be 'x/y' or 'x.y' or 'x.y/z'\n\tconst splitUnit = (string: string): string[] =>\n\t\tdecomposePower(\n\t\t\tstring\n\t\t\t\t.split('.')\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.map((unit) => getUnitKey(unit)),\n\t\t)\n\tconst result = {\n\t\tnumerators: splitUnit(a),\n\t\tdenominators: b.flatMap((u) => splitUnit(u)),\n\t}\n\treturn result\n}\n\nconst lastNumberFromString = /(\\d+)(?!.*[A-Za-z])/g\n\n/**\n * Count the number of each unit, e.g. [m, m, kg, kg] -> {m: 2, kg: 2}\n */\nfunction getUnitCounts(baseUnits: Array): Record {\n\tconst countUnits = {}\n\tbaseUnits.forEach((e) => {\n\t\tconst powerMatch = e.match(lastNumberFromString)\n\t\tif (powerMatch != null) {\n\t\t\tconst power = powerMatch[0]\n\t\t\tconst primaryUnit = e.split(power)[0]\n\t\t\tcountUnits[primaryUnit] = (countUnits[primaryUnit] ?? 0) + +power\n\t\t} else {\n\t\t\tcountUnits[e] = (countUnits[e] ?? 0) + 1\n\t\t}\n\t})\n\treturn countUnits\n}\n\n/**\n * Decompose power of units, e.g. [m2] -> [m, m] or [kg2, m3] -> [kg, kg, m, m, m]\n */\nfunction decomposePower(baseUnits: Array): Array {\n\tconst unitCounts = getUnitCounts(baseUnits)\n\treturn Object.entries(unitCounts).flatMap(([primaryUnit, power]) =>\n\t\tArray(power).fill(primaryUnit),\n\t)\n}\n\n/**\n * Combine power of units, e.g. [m2, m] -> [m3] or [m, m, kg, kg] -> [m2, kg2]\n */\nfunction combinePower(baseUnit: Array): Array {\n\tconst unitCounts = getUnitCounts(baseUnit)\n\treturn Object.entries(unitCounts).map(([primaryUnit, power]) =>\n\t\tpower > 1 ? `${primaryUnit}${power}` : primaryUnit,\n\t)\n}\n\nconst printUnits = (\n\tunits: Array,\n\tcount: number,\n\tformatUnit: formatUnit = (x) => x,\n): string => {\n\treturn combinePower(units.map((unit) => formatUnit(unit, count))).join('.')\n}\n\nconst plural = 2\nexport function serializeUnit(\n\trawUnit: Unit | undefined | string,\n\tcount: number = plural,\n\tformatUnit: formatUnit = (x) => x,\n): string | undefined {\n\tif (rawUnit === null || typeof rawUnit !== 'object') {\n\t\treturn typeof rawUnit === 'string' ? formatUnit(rawUnit, count) : rawUnit\n\t}\n\tconst unit = simplify(rawUnit)\n\tconst { numerators = [], denominators = [] } = unit\n\n\tconst n = numerators.length > 0\n\tconst d = denominators.length > 0\n\tconst string =\n\t\t!n && !d ? ''\n\t\t: n && !d ? printUnits(numerators, count, formatUnit)\n\t\t: !n && d ? `/${printUnits(denominators, 1, formatUnit)}`\n\t\t: `${printUnits(numerators, plural, formatUnit)}/${printUnits(\n\t\t\t\tdenominators,\n\t\t\t\t1,\n\t\t\t\tformatUnit,\n\t\t\t)}`\n\n\treturn string\n}\n\ntype SupportedOperators = '*' | '/' | '+' | '-'\n\nconst noUnit = { numerators: [], denominators: [] }\nexport const inferUnit = (\n\toperator: SupportedOperators,\n\trawUnits: Array,\n): Unit | undefined => {\n\tif (operator === '/') {\n\t\tif (rawUnits.length !== 2) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'InternalError',\n\t\t\t\t'Infer units of a division with units.length !== 2)',\n\t\t\t\t{},\n\t\t\t)\n\t\t}\n\n\t\treturn inferUnit('*', [\n\t\t\trawUnits[0] || noUnit,\n\t\t\t{\n\t\t\t\tnumerators: (rawUnits[1] || noUnit).denominators,\n\t\t\t\tdenominators: (rawUnits[1] || noUnit).numerators,\n\t\t\t},\n\t\t])\n\t}\n\tconst units = rawUnits.filter(Boolean)\n\tif (units.length <= 1) {\n\t\treturn units[0]\n\t}\n\tif (operator === '*')\n\t\treturn simplify({\n\t\t\tnumerators: units.flatMap((u) => u?.numerators ?? []),\n\t\t\tdenominators: units.flatMap((u) => u?.denominators ?? []),\n\t\t})\n\n\tif (operator === '-' || operator === '+') {\n\t\treturn rawUnits.find((u) => u)\n\t}\n\n\treturn undefined\n}\n\nconst equals = (a: T, b: T) => {\n\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\treturn a.length === b.length && a.every((_, i) => a[i] === b[i])\n\t} else {\n\t\treturn a === b\n\t}\n}\n\nexport const removeOnce =\n\t(element: T, eqFn: (a: T, b: T) => boolean = equals) =>\n\t(list: Array): Array => {\n\t\tconst index = list.findIndex((e) => eqFn(e, element))\n\t\treturn list.filter((_, i) => i !== index)\n\t}\n\nconst simplify = (\n\tunit: Unit,\n\teqFn: (a: string, b: string) => boolean = equals,\n): Unit => {\n\tconst simplifiedUnit = [...unit.numerators, ...unit.denominators].reduce(\n\t\t({ numerators, denominators }, next) =>\n\t\t\t(\n\t\t\t\tnumerators.find((u) => eqFn(next, u)) &&\n\t\t\t\tdenominators.find((u) => eqFn(next, u))\n\t\t\t) ?\n\t\t\t\t{\n\t\t\t\t\tnumerators: removeOnce(next, eqFn)(numerators),\n\t\t\t\t\tdenominators: removeOnce(next, eqFn)(denominators),\n\t\t\t\t}\n\t\t\t:\t{ numerators, denominators },\n\t\tunit,\n\t)\n\treturn simplifiedUnit\n}\n\nconst convertTable: ConvertTable = {\n\t'mois/an': 12,\n\t'jour/an': 365,\n\t'jour/mois': 365 / 12,\n\t'trimestre/an': 4,\n\t'mois/trimestre': 3,\n\t'jour/trimestre': (365 / 12) * 3,\n\t'€/k€': 10 ** 3,\n\t'g/kg': 10 ** 3,\n\t'mg/g': 10 ** 3,\n\t'mg/kg': 10 ** 6,\n\t'm/km': 10 ** 3,\n\t'cm/m': 10 ** 2,\n\t'mm/cm': 10 ** 1,\n\t'mm/m': 10 ** 3,\n\t'cm/km': 10 ** 5,\n\t'mm/km': 10 ** 6,\n}\n\nfunction singleUnitConversionFactor(\n\tfrom: string,\n\tto: string,\n): number | undefined {\n\treturn (\n\t\tconvertTable[`${to}/${from}`] ||\n\t\t(convertTable[`${from}/${to}`] && 1 / convertTable[`${from}/${to}`])\n\t)\n}\nfunction unitsConversionFactor(from: string[], to: string[]): number {\n\tlet factor =\n\t\t100 **\n\t\t// Factor is mutliplied or divided 100 for each '%' in units\n\t\t(to.filter((unit) => unit === '%').length -\n\t\t\tfrom.filter((unit) => unit === '%').length)\n\t;[factor] = from.reduce(\n\t\t([value, toUnits], fromUnit) => {\n\t\t\tconst index = toUnits.findIndex(\n\t\t\t\t(toUnit) => !!singleUnitConversionFactor(fromUnit, toUnit),\n\t\t\t)\n\t\t\tconst factor = singleUnitConversionFactor(fromUnit, toUnits[index]) || 1\n\t\t\treturn [\n\t\t\t\tvalue * factor,\n\t\t\t\t[...toUnits.slice(0, index + 1), ...toUnits.slice(index + 1)],\n\t\t\t]\n\t\t},\n\t\t[factor, to],\n\t)\n\treturn factor\n}\n\n// TODO(@clemog):\n// - Deal with other equivalent units : l: 'dm3',\n// - Convert unit instead of ignore warning\nconst equivalentTable = {\n\t'kW.h': 'kWh',\n\t'mn/h': 'noeud',\n}\n\nfunction areEquivalentSerializedUnit(\n\tserializedFrom: string | undefined,\n\tserializedTo: string | undefined,\n): boolean {\n\tif (!serializedFrom || !serializedTo) return false\n\treturn (\n\t\tserializedFrom === serializedTo ||\n\t\tserializedFrom === equivalentTable[serializedTo] ||\n\t\tserializedTo === equivalentTable[serializedFrom]\n\t)\n}\n\nexport function convertUnit>(\n\tfrom: Unit | undefined,\n\tto: Unit | undefined,\n\tvalue: ValType,\n): ValType {\n\tconst serializedFrom = serializeUnit(from)\n\tconst serializedTo = serializeUnit(to)\n\tif (\n\t\t!areEquivalentSerializedUnit(serializedFrom, serializedTo) &&\n\t\t!areUnitConvertible(from, to)\n\t) {\n\t\tthrow new PublicodesError(\n\t\t\t'EngineError',\n\t\t\t`Impossible de convertir l'unité '${serializedFrom}' en '${serializedTo}'`,\n\t\t\t{},\n\t\t)\n\t}\n\tif (!value) {\n\t\treturn value\n\t}\n\tif (from === undefined) {\n\t\treturn value\n\t}\n\tconst [fromSimplified, factorTo] = simplifyUnitWithValue(from || noUnit)\n\tconst [toSimplified, factorFrom] = simplifyUnitWithValue(to || noUnit)\n\treturn round(\n\t\t(((value as number) * factorTo) / factorFrom) *\n\t\t\tunitsConversionFactor(\n\t\t\t\tfromSimplified.numerators,\n\t\t\t\ttoSimplified.numerators,\n\t\t\t) *\n\t\t\tunitsConversionFactor(\n\t\t\t\ttoSimplified.denominators,\n\t\t\t\tfromSimplified.denominators,\n\t\t\t),\n\t) as any\n}\n\nconst convertibleUnitClasses = unitClasses(convertTable)\ntype unitClasses = Array>\ntype ConvertTable = { readonly [index: string]: number }\n\n// Reduce the convertTable provided by the user into a list of compatibles\n// classes.\nfunction unitClasses(convertTable: ConvertTable) {\n\treturn Object.keys(convertTable).reduce(\n\t\t(classes: unitClasses, ratio: string) => {\n\t\t\tconst [a, b] = ratio.split('/')\n\t\t\tconst ia = classes.findIndex((units) => units.has(a))\n\t\t\tconst ib = classes.findIndex((units) => units.has(b))\n\t\t\tif (ia > -1 && ib > -1 && ia !== ib) {\n\t\t\t\tthrow new PublicodesError('EngineError', `Invalid ratio ${ratio}`, {})\n\t\t\t} else if (ia === -1 && ib === -1) {\n\t\t\t\tclasses.push(new Set([a, b]))\n\t\t\t} else if (ia > -1) {\n\t\t\t\tclasses[ia].add(b)\n\t\t\t} else if (ib > -1) {\n\t\t\t\tclasses[ib].add(a)\n\t\t\t}\n\t\t\treturn classes\n\t\t},\n\t\t[],\n\t)\n}\n\nfunction areSameClass(a: string, b: string) {\n\treturn (\n\t\ta === b ||\n\t\tconvertibleUnitClasses.some(\n\t\t\t(unitsClass) => unitsClass.has(a) && unitsClass.has(b),\n\t\t)\n\t)\n}\n\nfunction round(value: number) {\n\treturn +value.toFixed(16)\n}\n\nexport function simplifyUnit(unit: Unit): Unit {\n\tconst { numerators, denominators } = simplify(unit, areSameClass)\n\tif (numerators.length && numerators.every((symb) => symb === '%')) {\n\t\treturn { numerators: ['%'], denominators }\n\t}\n\treturn removePercentages({ numerators, denominators })\n}\n\nfunction simplifyUnitWithValue(unit: Unit, value = 1): [Unit, number] {\n\tconst factor = unitsConversionFactor(unit.numerators, unit.denominators)\n\treturn [\n\t\tsimplify(removePercentages(unit), areSameClass),\n\t\tvalue ? round(value * factor) : value,\n\t]\n}\n\nconst removePercentages = (unit: Unit): Unit => ({\n\tnumerators: unit.numerators.filter((e) => e !== '%'),\n\tdenominators: unit.denominators.filter((e) => e !== '%'),\n})\n\nexport function areUnitConvertible(a: Unit | undefined, b: Unit | undefined) {\n\tif (a == null || b == null) {\n\t\treturn true\n\t}\n\tconst countByUnitClass = (units: Array) =>\n\t\tunits.reduce((counters, unit) => {\n\t\t\tconst classIndex = convertibleUnitClasses.findIndex((unitClass) =>\n\t\t\t\tunitClass.has(unit),\n\t\t\t)\n\t\t\tconst key = classIndex === -1 ? unit : '' + classIndex\n\t\t\treturn { ...counters, [key]: 1 + (counters[key] ?? 0) }\n\t\t}, {})\n\n\tconst [numA, denomA, numB, denomB] = [\n\t\ta.numerators,\n\t\ta.denominators,\n\t\tb.numerators,\n\t\tb.denominators,\n\t].map(countByUnitClass)\n\tconst uniq = (arr: Array): Array => [...new Set(arr)]\n\tconst unitClasses = [numA, denomA, numB, denomB].map(Object.keys).flat()\n\treturn uniq(unitClasses).every(\n\t\t(unitClass) =>\n\t\t\t(numA[unitClass] || 0) - (denomA[unitClass] || 0) ===\n\t\t\t\t(numB[unitClass] || 0) - (denomB[unitClass] || 0) || unitClass === '%',\n\t)\n}\n","import { EvaluationFunction, simplifyNodeUnit } from '..'\nimport { ASTNode, EvaluatedNode } from '../AST/types'\nimport { PublicodesError } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport { serializeUnit } from '../units'\n\nexport type ArrondiNode = {\n\texplanation: {\n\t\tarrondi: ASTNode\n\t\tvaleur: ASTNode\n\t}\n\tnodeKind: 'arrondi'\n}\n\nfunction roundWithPrecision(n: number, fractionDigits: number) {\n\treturn +n.toFixed(fractionDigits)\n}\n\nconst evaluate: EvaluationFunction<'arrondi'> = function (node) {\n\t// We need to simplify the node unit to correctly round values containing\n\t// percentages units, see #1358\n\tconst valeur = simplifyNodeUnit(this.evaluateNode(node.explanation.valeur))\n\tconst nodeValue = valeur.nodeValue\n\tlet arrondi = node.explanation.arrondi\n\tif (nodeValue !== false) {\n\t\tarrondi = this.evaluateNode(arrondi)\n\n\t\tif (\n\t\t\ttypeof (arrondi as EvaluatedNode).nodeValue === 'number' &&\n\t\t\t!serializeUnit((arrondi as EvaluatedNode).unit)?.match(/décimales?/)\n\t\t) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'EvaluationError',\n\t\t\t\t`L'unité ${serializeUnit(\n\t\t\t\t\t(arrondi as EvaluatedNode).unit,\n\t\t\t\t)} de l'arrondi est inconnu. Vous devez utiliser l'unité “décimales”`,\n\t\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t\t)\n\t\t}\n\t}\n\n\treturn {\n\t\t...node,\n\t\tnodeValue:\n\t\t\ttypeof valeur.nodeValue !== 'number' || !('nodeValue' in arrondi) ?\n\t\t\t\tvaleur.nodeValue\n\t\t\t: typeof arrondi.nodeValue === 'number' ?\n\t\t\t\troundWithPrecision(valeur.nodeValue, arrondi.nodeValue)\n\t\t\t: arrondi.nodeValue === true ? roundWithPrecision(valeur.nodeValue, 0)\n\t\t\t: arrondi.nodeValue === undefined ? undefined\n\t\t\t: valeur.nodeValue,\n\t\texplanation: { valeur, arrondi },\n\t\tmissingVariables: mergeAllMissing([valeur, arrondi]),\n\t\tunit: valeur.unit,\n\t}\n}\n\nexport default function parseArrondi(v, context) {\n\tconst explanation = {\n\t\tvaleur: parse(v.valeur, context),\n\t\tarrondi: parse(v.arrondi, context),\n\t}\n\treturn {\n\t\texplanation,\n\t\tnodeKind: parseArrondi.nom,\n\t}\n}\n\nparseArrondi.nom = 'arrondi' as const\n\nregisterEvaluationFunction(parseArrondi.nom, evaluate)\n","import { EvaluatedNode, Unit } from './AST/types'\nimport { convertUnit, simplifyUnit } from './units'\n\nexport function simplifyNodeUnit(node) {\n\tif (!node.unit) {\n\t\treturn node\n\t}\n\tconst unit = simplifyUnit(node.unit)\n\n\treturn convertNodeToUnit(unit, node)\n}\n\nexport function convertNodeToUnit(\n\tto: Unit | undefined,\n\tnode: Node,\n): Node {\n\treturn {\n\t\t...node,\n\t\tnodeValue:\n\t\t\tnode.unit && typeof node.nodeValue === 'number' ?\n\t\t\t\tconvertUnit(node.unit, to, node.nodeValue)\n\t\t\t:\tnode.nodeValue,\n\t\tunit: to,\n\t}\n}\n","import { Evaluation, Unit } from './AST/types'\nimport { simplifyNodeUnit } from './nodeUnits'\nimport { formatUnit, serializeUnit } from './units'\n\nexport const numberFormatter =\n\t({\n\t\tstyle,\n\t\tmaximumFractionDigits = 2,\n\t\tminimumFractionDigits = 0,\n\t\tlanguage,\n\t}: {\n\t\tstyle?: string\n\t\tmaximumFractionDigits?: number\n\t\tminimumFractionDigits?: number\n\t\tlanguage?: string\n\t}) =>\n\t(value: number) => {\n\t\t// When we format currency we don't want to display a single decimal digit\n\t\t// ie 8,1€ but we want to display 8,10€\n\t\tconst adaptedMinimumFractionDigits =\n\t\t\t(\n\t\t\t\tstyle === 'currency' &&\n\t\t\t\tmaximumFractionDigits >= 2 &&\n\t\t\t\tminimumFractionDigits === 0 &&\n\t\t\t\t!Number.isInteger(value)\n\t\t\t) ?\n\t\t\t\t2\n\t\t\t:\tminimumFractionDigits\n\t\treturn Intl.NumberFormat(language, {\n\t\t\tstyle,\n\t\t\tcurrency: 'EUR',\n\t\t\tmaximumFractionDigits,\n\t\t\tminimumFractionDigits: adaptedMinimumFractionDigits,\n\t\t}).format(value)\n\t}\n\nexport const formatCurrency = (\n\tnodeValue: number | undefined,\n\tlanguage: string,\n) => {\n\treturn nodeValue == undefined ? '' : (\n\t\t\t(formatNumber({ unit: '€', language, nodeValue }) ?? '').replace(\n\t\t\t\t/^(-)?€/,\n\t\t\t\t'$1€\\u00A0',\n\t\t\t)\n\t\t)\n}\n\nexport const formatPercentage = (nodeValue: number | undefined) =>\n\tnodeValue == undefined ? '' : (\n\t\tformatNumber({ unit: '%', nodeValue, maximumFractionDigits: 2 })\n\t)\n\ntype formatValueOptions = {\n\tmaximumFractionDigits?: number\n\tminimumFractionDigits?: number\n\tlanguage?: string\n\tunit?: Unit | string\n\tformatUnit?: formatUnit\n\tnodeValue: number\n}\n\nfunction formatNumber({\n\tmaximumFractionDigits,\n\tminimumFractionDigits,\n\tlanguage,\n\tformatUnit,\n\tunit,\n\tnodeValue,\n}: formatValueOptions) {\n\tif (typeof nodeValue !== 'number') {\n\t\treturn nodeValue\n\t}\n\tconst serializedUnit =\n\t\tunit ? serializeUnit(unit, nodeValue, formatUnit) : undefined\n\tswitch (serializedUnit) {\n\t\tcase '€':\n\t\t\treturn numberFormatter({\n\t\t\t\tstyle: 'currency',\n\t\t\t\tmaximumFractionDigits,\n\t\t\t\tminimumFractionDigits,\n\t\t\t\tlanguage,\n\t\t\t})(nodeValue)\n\t\tcase '%':\n\t\t\treturn numberFormatter({\n\t\t\t\tstyle: 'percent',\n\t\t\t\tmaximumFractionDigits,\n\t\t\t\tlanguage,\n\t\t\t})(nodeValue / 100)\n\t\tdefault:\n\t\t\treturn (\n\t\t\t\tnumberFormatter({\n\t\t\t\t\tstyle: 'decimal',\n\t\t\t\t\tminimumFractionDigits,\n\t\t\t\t\tmaximumFractionDigits,\n\t\t\t\t\tlanguage,\n\t\t\t\t})(nodeValue) +\n\t\t\t\t(typeof serializedUnit === 'string' ? `\\u00A0${serializedUnit}` : '')\n\t\t\t)\n\t}\n}\n\nexport function capitalise0(name: undefined): undefined\nexport function capitalise0(name: string): string\nexport function capitalise0(name?: string) {\n\treturn name && name[0].toUpperCase() + name.slice(1)\n}\n\nconst booleanTranslations = {\n\tfr: { true: 'oui', false: 'non' },\n\ten: { true: 'yes', false: 'no' },\n}\n\ntype Options = {\n\tlanguage?: string\n\tdisplayedUnit?: string\n\tprecision?: number\n\tformatUnit?: formatUnit\n}\n\nexport function formatValue(\n\tvalue: number | { nodeValue: Evaluation; unit?: Unit } | undefined,\n\n\t{ language = 'fr', displayedUnit, formatUnit, precision = 2 }: Options = {},\n) {\n\tlet nodeValue =\n\t\t(\n\t\t\ttypeof value === 'number' ||\n\t\t\ttypeof value === 'undefined' ||\n\t\t\tvalue === null\n\t\t) ?\n\t\t\tvalue\n\t\t:\tvalue.nodeValue\n\n\tif (typeof nodeValue === 'number' && Number.isNaN(nodeValue)) {\n\t\treturn 'Erreur dans le calcul du nombre'\n\t}\n\tif (nodeValue === undefined) {\n\t\treturn 'Pas encore défini'\n\t}\n\tif (nodeValue === null) {\n\t\treturn 'Non applicable'\n\t}\n\tif (typeof nodeValue === 'string') {\n\t\treturn nodeValue.replace('\\\\n', '\\n')\n\t}\n\tif (typeof nodeValue === 'boolean')\n\t\treturn booleanTranslations[language][nodeValue]\n\tif (typeof nodeValue === 'number') {\n\t\tlet unit =\n\t\t\t(\n\t\t\t\ttypeof value === 'number' ||\n\t\t\t\ttypeof value === 'undefined' ||\n\t\t\t\t!('unit' in value)\n\t\t\t) ?\n\t\t\t\tundefined\n\t\t\t:\tvalue.unit\n\t\tif (unit) {\n\t\t\tconst simplifiedNode = simplifyNodeUnit({\n\t\t\t\tunit,\n\t\t\t\tnodeValue,\n\t\t\t})\n\t\t\tunit = simplifiedNode.unit\n\t\t\tnodeValue = simplifiedNode.nodeValue as number\n\t\t}\n\t\treturn formatNumber({\n\t\t\tminimumFractionDigits: 0,\n\t\t\tmaximumFractionDigits: precision,\n\t\t\tlanguage,\n\t\t\tformatUnit,\n\t\t\tnodeValue,\n\t\t\tunit: displayedUnit ?? unit,\n\t\t}).trim()\n\t}\n\treturn undefined\n}\n\nexport function serializeValue(\n\t{ nodeValue, unit }: { nodeValue: Evaluation; unit?: Unit },\n\t{ format }: { format: formatUnit },\n) {\n\tconst serializedUnit = (\n\t\tunit && typeof nodeValue === 'number' ?\n\t\t\tserializeUnit(unit, nodeValue, format)\n\t\t:\t'')?.replace(/\\s*\\/\\s*/g, '/')\n\treturn `${nodeValue} ${serializedUnit}`.trim()\n}\n","import { ParsedRules } from '.'\nimport { ASTNode } from './AST/types'\nimport { PublicodesError } from './error'\nimport { ReferencesMaps } from './parsePublicodes'\nimport { ReferenceNode } from './reference'\nimport { RuleNode } from './rule'\nimport { addToMapSet } from './utils'\n\nexport { cyclicDependencies } from './AST/graph'\n\nconst splitName = (str: string) => str.split(' . ')\nconst joinName = (strs: Array) => strs.join(' . ')\n\n/**\n * Returns the last part of a dottedName (the leaf).\n */\nexport const nameLeaf = (dottedName: string) =>\n\tsplitName(dottedName).slice(-1)?.[0]\n\n/**\n * Encodes a dottedName for the URL to be secure.\n * @see {@link decodeRuleName}\n */\nexport const encodeRuleName = (dottedName: string): string =>\n\tdottedName\n\t\t?.replace(/\\s\\.\\s/g, '/')\n\t\t.replace(/-/g, '\\u2011') // replace with a insecable tiret to differenciate from space\n\t\t.replace(/\\s/g, '-')\n\n/**\n * Decodes an encoded dottedName.\n * @see {@link encodeRuleName}\n */\nexport const decodeRuleName = (dottedName: string): string =>\n\tdottedName\n\t\t.replace(/\\//g, ' . ')\n\t\t.replace(/-/g, ' ')\n\t\t.replace(/\\u2011/g, '-')\n\n/**\n * Return dottedName from contextName\n */\nexport const contextNameToDottedName = (contextName: string) =>\n\tcontextName.endsWith('$SITUATION') ? ruleParent(contextName) : contextName\n\n/**\n * Returns the parent dottedName\n */\nexport const ruleParent = (dottedName: string): string =>\n\tjoinName(splitName(dottedName).slice(0, -1))\n\n/**\n * Returns an array of dottedName from near parent to far parent.\n */\nexport function ruleParents(dottedName: string): Array {\n\treturn splitName(dottedName)\n\t\t.slice(0, -1)\n\t\t.map((_, i, arr) => joinName(arr.slice(0, i + 1)))\n\t\t.reverse()\n}\n\n/**\n * Returns an array of all child rules of a dottedName\n */\nexport const getChildrenRules = (\n\tparsedRules: ParsedRules,\n\tdottedName: string,\n) => {\n\tconst childrenRules = Object.keys(parsedRules).filter(\n\t\t(ruleDottedName) =>\n\t\t\truleDottedName.startsWith(dottedName) &&\n\t\t\tsplitName(ruleDottedName).length === splitName(dottedName).length + 1,\n\t)\n\n\treturn childrenRules\n}\n\n/**\n * Finds the common ancestor of two dottedName\n */\nexport function findCommonAncestor(dottedName1: string, dottedName2: string) {\n\tconst splitDottedName1 = splitName(dottedName1)\n\tconst splitDottedName2 = splitName(dottedName2)\n\tconst index = splitDottedName1.findIndex(\n\t\t(value, i) => splitDottedName2[i] !== value,\n\t)\n\n\treturn index === -1 ? dottedName1 : joinName(splitDottedName1.slice(0, index))\n}\n\n/**\n * Check wether a rule is accessible from a namespace.\n *\n * Takes into account that some namespace can be `private`, i.e. that they can only be\n * accessed by immediate parent, children or siblings.\n *\n * @param rules The parsed rules\n * @param contextName The context of the call\n * @param name The namespace checked for accessibility\n */\nexport function isAccessible(\n\trules: Record,\n\tcontextName: string,\n\tname: string,\n) {\n\tif (!(name in rules)) {\n\t\tthrow new PublicodesError(\n\t\t\t'InternalError',\n\t\t\t`La règle \"${name}\" n'existe pas`,\n\t\t\t{ dottedName: name },\n\t\t)\n\t}\n\n\tconst commonAncestor = findCommonAncestor(contextName, name)\n\tconst parents = [name, ...ruleParents(name), '']\n\tconst rulesToCheckForPrivacy = parents.slice(\n\t\t0,\n\t\tMath.max(parents.indexOf(commonAncestor) - 1, 0),\n\t)\n\n\treturn rulesToCheckForPrivacy.every(\n\t\t(dottedName) =>\n\t\t\t!(dottedName in rules) || rules[dottedName].private === false,\n\t)\n}\n\n/**\n * Check wether a rule is tagged as experimental.\n *\n * Takes into account the a children of an experimental rule is also experimental\n *\n * @param rules The parsed rules\n * @param name The namespace checked for experimental\n */\nexport function isExperimental(rules: Record, name: string) {\n\tif (!(name in rules)) {\n\t\tthrow new PublicodesError(\n\t\t\t'InternalError',\n\t\t\t`La règle \"${name}\" n'existe pas`,\n\t\t\t{ dottedName: name },\n\t\t)\n\t}\n\tconst parents = [name, ...ruleParents(name)]\n\treturn parents.some(\n\t\t(dottedName) =>\n\t\t\tdottedName in rules && rules[dottedName].rawNode?.experimental === 'oui',\n\t)\n}\n\nfunction dottedNameFromContext(context: string, partialName: string) {\n\treturn context ? context + ' . ' + partialName : partialName\n}\nexport function disambiguateReference>(\n\trules: R,\n\treferencedFrom = '',\n\tpartialName: string,\n): keyof R {\n\tconst possibleContexts = ruleParents(referencedFrom)\n\tpossibleContexts.push(referencedFrom)\n\n\t// If the partialName starts with ^ . ^ . ^ . , we want to go up in the parents\n\tif (partialName.startsWith('^ . ')) {\n\t\tconst numberParent = partialName.match(/^(\\^ \\. )+/)![0].length / 4\n\t\tpartialName = partialName.replace(/^(\\^ \\. )+/, '')\n\t\tpossibleContexts.splice(-numberParent)\n\t}\n\n\tconst rootContext = possibleContexts.pop()\n\tpossibleContexts.unshift(rootContext as string)\n\tpossibleContexts.push('')\n\n\tconst context = possibleContexts.find((context) => {\n\t\tconst dottedName = dottedNameFromContext(context, partialName)\n\t\tif (!(dottedName in rules)) {\n\t\t\treturn false\n\t\t}\n\t\tif (dottedName === referencedFrom) {\n\t\t\treturn false\n\t\t}\n\t\treturn isAccessible(rules, referencedFrom, dottedName)\n\t})\n\n\tif (context !== undefined) {\n\t\treturn dottedNameFromContext(context, partialName) as keyof R\n\t}\n\n\t// The last possibility we want to check is if the rule is referencing itself\n\tif (referencedFrom.endsWith(partialName)) {\n\t\treturn referencedFrom as keyof R\n\t}\n\n\tconst possibleDottedName = possibleContexts.map((c) =>\n\t\tdottedNameFromContext(c, partialName),\n\t)\n\n\tif (possibleDottedName.every((dottedName) => !(dottedName in rules))) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`La référence \"${partialName}\" est introuvable.\nVérifiez que l'orthographe et l'espace de nom sont corrects`,\n\t\t\t{ dottedName: contextNameToDottedName(referencedFrom) },\n\t\t)\n\t}\n\n\tthrow new PublicodesError(\n\t\t'SyntaxError',\n\t\t`La règle \"${possibleDottedName.find(\n\t\t\t(dottedName) => dottedName in rules,\n\t\t)}\" n'est pas accessible depuis \"${referencedFrom}\".\n\tCela vient du fait qu'elle est privée ou qu'un de ses parent est privé`,\n\t\t{ dottedName: contextNameToDottedName(referencedFrom) },\n\t)\n}\n\nexport function ruleWithDedicatedDocumentationPage(rule) {\n\treturn (\n\t\trule.virtualRule !== true &&\n\t\trule.type !== 'groupe' &&\n\t\trule.type !== 'texte' &&\n\t\trule.type !== 'paragraphe' &&\n\t\trule.type !== 'notification'\n\t)\n}\n\nexport function updateReferencesMapsFromReferenceNode(\n\tnode: ASTNode,\n\treferencesMaps: ReferencesMaps,\n\truleDottedName?: string,\n) {\n\tif (node.nodeKind === 'reference') {\n\t\taddToMapSet(\n\t\t\treferencesMaps.referencesIn,\n\t\t\truleDottedName ?? node.contextDottedName,\n\t\t\tnode.dottedName,\n\t\t)\n\t\taddToMapSet(\n\t\t\treferencesMaps.rulesThatUse,\n\t\t\tnode.dottedName,\n\t\t\truleDottedName ?? node.contextDottedName,\n\t\t)\n\t}\n}\nexport function disambiguateReferenceNode(\n\tnode: ASTNode,\n\tparsedRules: ParsedRules,\n): ReferenceNode | undefined {\n\tif (node.nodeKind !== 'reference') {\n\t\treturn\n\t}\n\tif (node.dottedName) {\n\t\treturn node\n\t}\n\n\tnode.dottedName = disambiguateReference(\n\t\tparsedRules,\n\t\tnode.contextDottedName,\n\t\tnode.name,\n\t)\n\tnode.title = parsedRules[node.dottedName].title\n\tnode.acronym = parsedRules[node.dottedName].rawNode.acronyme\n\treturn node\n}\n","/* eslint-disable prefer-rest-params */\n/* eslint-disable @typescript-eslint/no-this-alias */\n// Adapted from https://github.com/dagrejs/graphlib (MIT license)\n// and https://github.com/lodash/lodash (MIT license)\n\n// TODO: type this\n\nfunction has(obj, key) {\n\treturn obj != null && Object.prototype.hasOwnProperty.call(obj, key)\n}\nfunction constant(value) {\n\treturn function () {\n\t\treturn value\n\t}\n}\n\nconst DEFAULT_EDGE_NAME = '\\x00'\nconst EDGE_KEY_DELIM = '\\x01'\n\nconst incrementOrInitEntry = (map, k) => {\n\tif (map[k]) {\n\t\tmap[k]++\n\t} else {\n\t\tmap[k] = 1\n\t}\n}\n\nconst decrementOrRemoveEntry = (map, k) => {\n\tif (!--map[k]) {\n\t\tdelete map[k]\n\t}\n}\n\nconst edgeArgsToId = (isDirected, v_, w_, name) => {\n\tlet v = '' + v_\n\tlet w = '' + w_\n\tif (!isDirected && v > w) {\n\t\tconst tmp = v\n\t\tv = w\n\t\tw = tmp\n\t}\n\treturn (\n\t\tv +\n\t\tEDGE_KEY_DELIM +\n\t\tw +\n\t\tEDGE_KEY_DELIM +\n\t\t(name === undefined ? DEFAULT_EDGE_NAME : name)\n\t)\n}\n\nconst edgeArgsToObj = (isDirected, v_, w_, name) => {\n\tlet v = '' + v_\n\tlet w = '' + w_\n\tif (!isDirected && v > w) {\n\t\tconst tmp = v\n\t\tv = w\n\t\tw = tmp\n\t}\n\tconst edgeObj: any = { v: v, w: w }\n\tif (name) {\n\t\tedgeObj.name = name\n\t}\n\treturn edgeObj\n}\n\nconst edgeObjToId = (isDirected, edgeObj) => {\n\treturn edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name)\n}\nexport class Graph {\n\tprivate _nodeCount = 0\n\tprivate _edgeCount = 0\n\n\tprivate _isDirected: any\n\n\tprivate _label: undefined\n\tprivate _defaultNodeLabelFn: (...args: any[]) => any\n\tprivate _defaultEdgeLabelFn: (...args: any[]) => any\n\tprivate _nodes: Record\n\tprivate _in: Record\n\tprivate _preds: Record>\n\tprivate _out: Record>\n\tprivate _sucs: Record>\n\tprivate _edgeObjs: Record\n\tprivate _edgeLabels: Record\n\n\tconstructor(opts: Record = {}) {\n\t\tthis._isDirected = has(opts, 'directed') ? opts.directed : true\n\n\t\t// Label for the graph itself\n\t\tthis._label = undefined\n\n\t\t// Defaults to be set when creating a new node\n\t\tthis._defaultNodeLabelFn = constant(undefined)\n\n\t\t// Defaults to be set when creating a new edge\n\t\tthis._defaultEdgeLabelFn = constant(undefined)\n\n\t\t// v -> label\n\t\tthis._nodes = {}\n\n\t\t// v -> edgeObj\n\t\tthis._in = {}\n\n\t\t// u -> v -> Number\n\t\tthis._preds = {}\n\n\t\t// v -> edgeObj\n\t\tthis._out = {} as Record>\n\n\t\t// v -> w -> Number\n\t\tthis._sucs = {}\n\n\t\t// e -> edgeObj\n\t\tthis._edgeObjs = {}\n\n\t\t// e -> label\n\t\tthis._edgeLabels = {}\n\t}\n\n\t/* === Graph functions ========= */\n\n\tisDirected() {\n\t\treturn this._isDirected\n\t}\n\tsetGraph(label) {\n\t\tthis._label = label\n\t\treturn this\n\t}\n\tgraph() {\n\t\treturn this._label\n\t}\n\n\t/* === Node functions ========== */\n\n\tnodeCount() {\n\t\treturn this._nodeCount\n\t}\n\tnodes() {\n\t\treturn Object.keys(this._nodes)\n\t}\n\tsetNode(v, value: any = undefined) {\n\t\tif (has(this._nodes, v)) {\n\t\t\tif (arguments.length > 1) {\n\t\t\t\tthis._nodes[v] = value\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tthis._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v)\n\t\tthis._in[v] = {}\n\t\tthis._preds[v] = {}\n\t\tthis._out[v] = {}\n\t\tthis._sucs[v] = {}\n\t\t++this._nodeCount\n\t\treturn this\n\t}\n\tsetNodes(vs, value) {\n\t\tvs.forEach((v) => {\n\t\t\tif (value !== undefined) {\n\t\t\t\tthis.setNode(v, value)\n\t\t\t} else {\n\t\t\t\tthis.setNode(v)\n\t\t\t}\n\t\t})\n\t\treturn this\n\t}\n\tnode(v) {\n\t\treturn this._nodes[v]\n\t}\n\thasNode(v) {\n\t\treturn has(this._nodes, v)\n\t}\n\tsuccessors(v) {\n\t\tconst sucsV = this._sucs[v]\n\t\tif (sucsV) {\n\t\t\treturn Object.keys(sucsV)\n\t\t}\n\t}\n\n\t/* === Edge functions ========== */\n\n\tedgeCount() {\n\t\treturn this._edgeCount\n\t}\n\tedges() {\n\t\treturn Object.values(this._edgeObjs)\n\t}\n\tsetEdge(\n\t\tv: string,\n\t\tw: string,\n\t\tvalue: any = undefined,\n\t\tname: string | undefined = undefined,\n\t) {\n\t\tv = '' + v\n\t\tw = '' + w\n\n\t\tconst e = edgeArgsToId(this._isDirected, v, w, name)\n\t\tif (has(this._edgeLabels, e)) {\n\t\t\tif (value !== undefined) {\n\t\t\t\tthis._edgeLabels[e] = value\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\t// It didn't exist, so we need to create it.\n\t\t// First ensure the nodes exist.\n\t\tthis.setNode(v)\n\t\tthis.setNode(w)\n\n\t\tthis._edgeLabels[e] =\n\t\t\tvalue !== undefined ? value : this._defaultEdgeLabelFn(v, w, name)\n\n\t\tconst edgeObj = edgeArgsToObj(this._isDirected, v, w, name)\n\t\t// Ensure we add undirected edges in a consistent way.\n\t\tv = edgeObj.v\n\t\tw = edgeObj.w\n\n\t\tObject.freeze(edgeObj)\n\t\tthis._edgeObjs[e] = edgeObj\n\t\tincrementOrInitEntry(this._preds[w], v)\n\t\tincrementOrInitEntry(this._sucs[v], w)\n\t\tthis._in[w][e] = edgeObj\n\t\tthis._out[v][e] = edgeObj\n\t\tthis._edgeCount++\n\t\treturn this\n\t}\n\n\tedge(v, w, name) {\n\t\tconst e =\n\t\t\targuments.length === 1 ?\n\t\t\t\tedgeObjToId(this._isDirected, arguments[0])\n\t\t\t:\tedgeArgsToId(this._isDirected, v, w, name)\n\t\treturn this._edgeLabels[e]\n\t}\n\n\thasEdge(v, w, name) {\n\t\tconst e =\n\t\t\targuments.length === 1 ?\n\t\t\t\tedgeObjToId(this._isDirected, arguments[0])\n\t\t\t:\tedgeArgsToId(this._isDirected, v, w, name)\n\t\treturn has(this._edgeLabels, e)\n\t}\n\n\tremoveEdge(v, w, name) {\n\t\tconst e =\n\t\t\targuments.length === 1 ?\n\t\t\t\tedgeObjToId(this._isDirected, arguments[0])\n\t\t\t:\tedgeArgsToId(this._isDirected, v, w, name)\n\t\tconst edge = this._edgeObjs[e]\n\t\tif (edge) {\n\t\t\tv = edge.v\n\t\t\tw = edge.w\n\t\t\tdelete this._edgeLabels[e]\n\t\t\tdelete this._edgeObjs[e]\n\t\t\tdecrementOrRemoveEntry(this._preds[w], v)\n\t\t\tdecrementOrRemoveEntry(this._sucs[v], w)\n\t\t\tdelete this._in[w][e]\n\t\t\tdelete this._out[v][e]\n\t\t\tthis._edgeCount--\n\t\t}\n\t\treturn this\n\t}\n\n\toutEdges(v: string, w: string | undefined = undefined) {\n\t\tconst outV = this._out[v]\n\t\tif (outV) {\n\t\t\tconst edges: any = Object.values(outV)\n\t\t\tif (w === undefined) {\n\t\t\t\treturn edges\n\t\t\t}\n\t\t\treturn edges.filter(function (edge) {\n\t\t\t\treturn edge.w === w\n\t\t\t})\n\t\t}\n\t}\n}\n\n/** Cycles stuff **/\n\nfunction tarjan(graph) {\n\tlet index = 0\n\tconst stack: any[] = []\n\tconst visited = {} // node id -> { onStack, lowlink, index }\n\tconst results: any[] = []\n\n\tfunction dfs(v) {\n\t\tconst entry = (visited[v] = {\n\t\t\tonStack: true,\n\t\t\tlowlink: index,\n\t\t\tindex: index++,\n\t\t})\n\t\tstack.push(v)\n\n\t\tgraph.successors(v).forEach(function (w) {\n\t\t\tif (!Object.prototype.hasOwnProperty.call(visited, w)) {\n\t\t\t\tdfs(w)\n\t\t\t\tentry.lowlink = Math.min(entry.lowlink, visited[w].lowlink)\n\t\t\t} else if (visited[w].onStack) {\n\t\t\t\tentry.lowlink = Math.min(entry.lowlink, visited[w].index)\n\t\t\t}\n\t\t})\n\n\t\tif (entry.lowlink === entry.index) {\n\t\t\tconst cmpt: any[] = []\n\t\t\tlet w\n\t\t\tdo {\n\t\t\t\tw = stack.pop()\n\t\t\t\tvisited[w].onStack = false\n\t\t\t\tcmpt.push(w)\n\t\t\t} while (v !== w)\n\t\t\tresults.push(cmpt)\n\t\t}\n\t}\n\n\tgraph.nodes().forEach(function (v) {\n\t\tif (!Object.prototype.hasOwnProperty.call(visited, v)) {\n\t\t\tdfs(v)\n\t\t}\n\t})\n\n\treturn results\n}\n\nexport function findCycles(graph): string[][] {\n\treturn tarjan(graph).filter(function (cmpt) {\n\t\treturn (\n\t\t\tcmpt.length > 1 || (cmpt.length === 1 && graph.hasEdge(cmpt[0], cmpt[0]))\n\t\t)\n\t})\n}\n","import parsePublicodes from '../parsePublicodes'\nimport { findCycles, Graph } from './findCycles'\n\ntype GraphCycles = string[][]\n\nfunction buildDependenciesGraph(rulesDeps: Map>) {\n\tconst g = new Graph()\n\t;[...rulesDeps.entries()].forEach(([ruleDottedName, dependencies]) => {\n\t\tdependencies.forEach((depDottedName) => {\n\t\t\tg.setEdge(ruleDottedName, depDottedName)\n\t\t})\n\t})\n\treturn g\n}\n\ntype RawRules = Parameters[0]\n\nexport function cyclesInDependenciesGraph(rawRules: RawRules): GraphCycles {\n\tconst { referencesMaps } = parsePublicodes(rawRules)\n\tconst dependenciesGraph = buildDependenciesGraph(referencesMaps.referencesIn)\n\tconst cycles = findCycles(dependenciesGraph)\n\n\treturn cycles.map((c) => c.reverse())\n}\n\n/**\n * Make the cycle as small as possible.\n */\nexport function squashCycle(\n\trulesDependenciesObject: Map>,\n\tcycle: string[],\n): string[] {\n\tfunction* loopFrom(i: number) {\n\t\tlet j = i\n\t\twhile (true) {\n\t\t\tyield cycle[j++ % cycle.length]\n\t\t}\n\t}\n\tconst smallCycleStartingAt: string[][] = []\n\tfor (let i = 0; i < cycle.length; i++) {\n\t\tconst smallCycle: string[] = []\n\t\tlet previousVertex: string | undefined = undefined\n\t\tfor (const vertex of loopFrom(i)) {\n\t\t\tif (previousVertex === undefined) {\n\t\t\t\tsmallCycle.push(vertex)\n\t\t\t\tpreviousVertex = vertex\n\t\t\t} else if (rulesDependenciesObject.get(previousVertex)?.has(vertex)) {\n\t\t\t\tif (smallCycle.includes(vertex)) {\n\t\t\t\t\tsmallCycle.splice(0, smallCycle.lastIndexOf(vertex))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tsmallCycle.push(vertex)\n\t\t\t\tpreviousVertex = vertex\n\t\t\t}\n\t\t}\n\t\tsmallCycleStartingAt.push(smallCycle)\n\t}\n\n\tconst smallest = smallCycleStartingAt.reduce((minCycle, someCycle) =>\n\t\tsomeCycle.length > minCycle.length ? minCycle : someCycle,\n\t)\n\treturn smallest\n}\n\n/**\n * This function is useful so as to print the dependencies at each node of the\n * cycle.\n * ⚠️ Indeed, the findCycles function returns the cycle found using the\n * Tarjan method, which is **not necessarily the smallest cycle**. However, the\n * smallest cycle is more readable.\n */\nexport function cyclicDependencies(\n\trawRules: RawRules,\n): [GraphCycles, string[]] {\n\tconst { referencesMaps } = parsePublicodes(rawRules)\n\tconst dependenciesGraph = buildDependenciesGraph(referencesMaps.referencesIn)\n\tconst cycles = findCycles(dependenciesGraph)\n\n\tconst reversedCycles = cycles.map((c) => c.reverse())\n\n\tconst smallCycles = reversedCycles.map((cycle) =>\n\t\tsquashCycle(referencesMaps.referencesIn, cycle),\n\t)\n\n\tconst printableStronglyConnectedComponents = reversedCycles.map((c, i) =>\n\t\tprintInDotFormat(dependenciesGraph, c, smallCycles[i]),\n\t)\n\n\treturn [smallCycles, printableStronglyConnectedComponents]\n}\n\n/**\n * Is edge in the cycle, in the same order?\n */\nconst edgeIsInCycle = (cycle: string[], v: string, w: string): boolean => {\n\tfor (let i = 0; i < cycle.length + 1; i++) {\n\t\tif (v === cycle[i] && w === cycle[(i + 1) % cycle.length]) return true\n\t}\n\treturn false\n}\n\nexport function printInDotFormat(\n\tdependenciesGraph: Graph,\n\tcycle: string[],\n\tsubCycleToHighlight: string[],\n) {\n\tconst edgesSet = new Set()\n\tcycle.forEach((vertex) => {\n\t\tdependenciesGraph\n\t\t\t.outEdges(vertex)\n\t\t\t.filter(({ w }) => cycle.includes(w))\n\t\t\t.forEach(({ v, w }) => {\n\t\t\t\tedgesSet.add(\n\t\t\t\t\t`\"${v}\" -> \"${w}\"` +\n\t\t\t\t\t\t(edgeIsInCycle(subCycleToHighlight, v, w) ? ' [color=red]' : ''),\n\t\t\t\t)\n\t\t\t})\n\t})\n\treturn `digraph Cycle {\\n\\t${[...edgesSet].join(';\\n\\t')};\\n}`\n}\n","import Engine from '.'\nimport { ASTNode, EvaluatedNode, MissingVariables } from './AST/types'\nimport { PublicodesError } from './error'\nimport { registerEvaluationFunction } from './evaluationFunctions'\nimport { defaultNode, mergeMissing, undefinedNode } from './evaluationUtils'\nimport { capitalise0 } from './format'\nimport parse, { mecanismKeys } from './parse'\nimport { Context, RawRule } from './parsePublicodes'\nimport {\n\tReplacementRule,\n\tparseRendNonApplicable,\n\tparseReplacements,\n} from './replacement'\nimport { isAccessible, nameLeaf, ruleParents } from './ruleUtils'\nimport { weakCopyObj } from './utils'\n\nexport type Rule = {\n\tformule?: Record | string\n\tvaleur?: Record | string\n\tquestion?: string\n\tdescription?: string\n\tunité?: string\n\tacronyme?: string\n\texemples?: any\n\trésumé?: string\n\ticônes?: string\n\ttitre?: string\n\tsévérité?: string\n\ttype?: string\n\texperimental?: 'oui'\n\t'possiblement non applicable'?: 'oui'\n\tprivé?: 'oui'\n\tnote?: string\n\tremplace?: Remplace | Array\n\t'rend non applicable'?: Remplace | Array\n\tsuggestions?: Record>\n\tréférences?: { [source: string]: string }\n\tAPI?: string\n\t'identifiant court'?: string\n} & Record\n\ntype Remplace =\n\t| {\n\t\t\t'références à': string\n\t\t\tdans?: Array | string\n\t\t\t'sauf dans'?: Array | string\n\t\t\tpriorité?: number\n\t\t\t// eslint-disable-next-line no-mixed-spaces-and-tabs\n\t }\n\t| string\n\nexport type RuleNode = {\n\tdottedName: Name\n\ttitle: string\n\tnodeKind: 'rule'\n\tvirtualRule: boolean\n\tprivate: boolean\n\trawNode: Rule\n\treplacements: Array\n\texplanation: {\n\t\tvaleur: ASTNode\n\t\tparents: Array\n\t\tnullableParent?: ASTNode\n\t\truleDisabledByItsParent: boolean\n\t}\n\tsuggestions: Record\n\t'identifiant court'?: string\n}\n\nfunction parseRule(nom: string, rawRule: Rule, context: Context): RuleNode {\n\tconst privateRule = rawRule.privé === 'oui' || nom.startsWith('[privé] ')\n\tnom = nom.replace(/^\\[privé\\] /, '')\n\tconst dottedName = [context.dottedName, nom].filter(Boolean).join(' . ')\n\n\tconst name = nameLeaf(dottedName)\n\tconst title = capitalise0(rawRule['titre'] ?? name)\n\n\tif (context.parsedRules[dottedName]) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t`La référence '${dottedName}' a déjà été définie`,\n\t\t\t{ dottedName },\n\t\t)\n\t}\n\n\tconst ruleValue: Record = {}\n\n\tfor (const key in rawRule) {\n\t\tif (mecanismKeys.includes(key)) {\n\t\t\truleValue[key] = rawRule[key]\n\t\t}\n\t}\n\tif ('formule' in rawRule) {\n\t\truleValue.valeur = rawRule.formule\n\t}\n\tif (!privateRule && !dottedName.endsWith('$SITUATION')) {\n\t\t// We create a $SITUATION child rule for each rule that is not private\n\t\t// This value will be used to evaluate the rule in the current situation (`setSituation`)\n\t\truleValue['dans la situation'] = `${dottedName} . $SITUATION`\n\t\truleValue['avec'] =\n\t\t\tweakCopyObj(ruleValue['avec'] as Record) ?? {}\n\t\tconst situationValue = weakCopyObj(undefinedNode)\n\t\tsituationValue.isNullable = rawRule['possiblement non applicable'] === 'oui'\n\t\t;(ruleValue['avec'] as Record)['[privé] $SITUATION'] = {\n\t\t\tvaleur: situationValue,\n\t\t}\n\n\t\t// If the `par défaut` value is used, then the rule should be listed as a missingVariables\n\t\tif (ruleValue['par défaut'] != null) {\n\t\t\truleValue['par défaut'] = {\n\t\t\t\tvaleur: ruleValue['par défaut'],\n\t\t\t\t'variable manquante': dottedName,\n\t\t\t}\n\t\t}\n\t}\n\n\t// const ruleContext = weakCopyObj(context)\n\t// ruleContext.dottedName = dottedName\n\t// const ruleContext = { ...context, dottedName }\n\tconst currentDottedNameContext = context.dottedName\n\tcontext.dottedName = dottedName\n\n\t// The following ensures that nested rules appears after the root rule when\n\t// iterating over parsedRule\n\tcontext.parsedRules[dottedName] = undefined as any\n\n\tconst explanation = {\n\t\tvaleur: parse(ruleValue, context),\n\t\t// We include a list of references to the parents to implement the branch\n\t\t// desactivation feature. When evaluating a rule we only need to know the\n\t\t// first nullable parent, but this is something that we can't determine at\n\t\t// this stage :\n\t\t// - we need to run remplacements (which works on references in the ASTs\n\t\t// which is why we insert these “virtual” references)\n\t\t// - we need to infer unit of the rules\n\t\t//\n\t\t// An alternative implementation would be possible that would colocate the\n\t\t// code related to branch desactivation (ie find the first nullable parent\n\t\t// statically after rules parsing)\n\t\tparents: ruleParents(dottedName).map(\n\t\t\t(parent) =>\n\t\t\t\t({\n\t\t\t\t\tdottedName: parent,\n\t\t\t\t\tnodeKind: 'reference',\n\t\t\t\t\tcontextDottedName: context.dottedName,\n\t\t\t\t}) as ASTNode<'reference'>,\n\t\t),\n\t}\n\n\tconst suggestions = {} as Record\n\tif (rawRule.suggestions) {\n\t\tfor (const name in rawRule.suggestions) {\n\t\t\tsuggestions[name] = parse(rawRule.suggestions[name], context)\n\t\t}\n\t}\n\n\tcontext.parsedRules[dottedName] = {\n\t\tdottedName,\n\t\treplacements: [\n\t\t\t...parseRendNonApplicable(rawRule['rend non applicable'], context),\n\t\t\t...parseReplacements(rawRule.remplace, context),\n\t\t],\n\t\ttitle: title,\n\t\tprivate: privateRule,\n\t\tsuggestions,\n\t\tnodeKind: 'rule',\n\t\texplanation,\n\t\trawNode: rawRule,\n\t\tvirtualRule: privateRule,\n\t} as RuleNode\n\tcontext.dottedName = currentDottedNameContext\n\treturn context.parsedRules[dottedName]\n}\n\nexport function parseRules(\n\trules: Partial>,\n\tcontext: Context,\n) {\n\tfor (const dottedName in rules) {\n\t\tlet rule = rules[dottedName]\n\n\t\tif (typeof rule === 'string' || typeof rule === 'number') {\n\t\t\trule = { valeur: `${rule}` }\n\t\t}\n\t\tif (typeof rule !== 'object') {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'SyntaxError',\n\t\t\t\t`Rule ${dottedName} is incorrectly written. Please give it a proper value.`,\n\t\t\t\t{ dottedName },\n\t\t\t)\n\t\t}\n\t\tconst copy = rule === null ? {} : weakCopyObj(rule)\n\t\tparseRule(dottedName, copy, context)\n\t}\n}\n\nregisterEvaluationFunction('rule', function evaluate(node) {\n\tconst { ruleDisabledByItsParent, nullableParent, parentMissingVariables } =\n\t\tevaluateDisablingParent(this, node)\n\n\tlet valeurEvaluation: EvaluatedNode = {\n\t\t...node.explanation.valeur,\n\t\tnodeValue: null,\n\t\tmissingVariables: {},\n\t}\n\tif (!ruleDisabledByItsParent) {\n\t\tif (\n\t\t\tthis.cache._meta.evaluationRuleStack.filter(\n\t\t\t\t(dottedName) => dottedName === node.dottedName,\n\t\t\t).length > 1\n\t\t) {\n\t\t\t// TODO : remettre ce warning. Je ne sais pas pourquoi, mais la base de règle de mon-entreprise lève un warning sur quasiment toutes les cotisations\n\t\t\t// \t\t\twarning(\n\t\t\t// \t\t\t\tthis.context.logger,\n\t\t\t// \t\t\t\t`Un cycle a été détecté lors de l'évaluation de cette règle.\n\n\t\t\t// Par défaut cette règle sera évaluée à 'null'.\n\t\t\t// Pour indiquer au moteur de résoudre la référence circulaire en trouvant le point fixe\n\t\t\t// de la fonction, il vous suffit d'ajouter l'attribut suivant niveau de la règle :\n\n\t\t\t// \t${node.dottedName}:\n\t\t\t// \t\trésoudre la référence circulaire: oui\"\n\t\t\t// \t\t...\n\t\t\t// `,\n\t\t\t// \t\t\t\t{ dottedName: node.dottedName }\n\t\t\t// \t\t\t)\n\n\t\t\tvaleurEvaluation = {\n\t\t\t\tnodeValue: undefined,\n\t\t\t} as EvaluatedNode\n\t\t} else {\n\t\t\tthis.cache._meta.evaluationRuleStack.unshift(node.dottedName)\n\t\t\tvaleurEvaluation = this.evaluateNode(node.explanation.valeur)\n\t\t\tthis.cache._meta.evaluationRuleStack.shift()\n\t\t}\n\t}\n\tvaleurEvaluation.missingVariables ??= {}\n\tupdateRuleMissingVariables(this, node, valeurEvaluation)\n\tconst evaluation = {\n\t\t...valeurEvaluation,\n\t\tmissingVariables: mergeMissing(\n\t\t\tvaleurEvaluation.missingVariables,\n\t\t\tparentMissingVariables,\n\t\t),\n\t\t...node,\n\t\texplanation: {\n\t\t\tparents: node.explanation.parents,\n\t\t\tvaleur: valeurEvaluation,\n\t\t\tnullableParent,\n\t\t\truleDisabledByItsParent,\n\t\t},\n\t}\n\n\treturn evaluation\n})\n\n/*\n\tWe implement the terminal case for missing variables manually here as\n\ta rule is missing if it is undefined and has no other missing dependencies\n*/\nfunction updateRuleMissingVariables(\n\tengine: Engine,\n\tnode: RuleNode,\n\tvaleurEvaluation: EvaluatedNode,\n): void {\n\tif (\n\t\tnode.private === true ||\n\t\t!isAccessible(engine.context.parsedRules, '', node.dottedName)\n\t) {\n\t\treturn\n\t}\n\n\tif (\n\t\tvaleurEvaluation.nodeValue === undefined &&\n\t\t!Object.keys(valeurEvaluation.missingVariables).length\n\t) {\n\t\tvaleurEvaluation.missingVariables[node.dottedName] = 1\n\t}\n\n\treturn\n}\n\nexport function evaluateDisablingParent(\n\tengine: Engine,\n\tnode: RuleNode,\n): {\n\truleDisabledByItsParent: boolean\n\tparentMissingVariables: MissingVariables\n\tnullableParent?: ASTNode\n} {\n\tif (node.private) {\n\t\t// We do not need to check if a private rule is disabled by its parent :\n\t\t// they are accessible only from its sibling or parent\n\t\t// (which would already be disabled)\n\t\treturn { ruleDisabledByItsParent: false, parentMissingVariables: {} }\n\t}\n\n\tconst nodesTypes = engine.context.nodesTypes\n\tconst nullableParent = node.explanation.parents.find(\n\t\t(ref) =>\n\t\t\tnodesTypes.get(ref)?.isNullable ||\n\t\t\tnodesTypes.get(ref)?.type === 'boolean',\n\t)\n\n\tif (!nullableParent) {\n\t\treturn { ruleDisabledByItsParent: false, parentMissingVariables: {} }\n\t}\n\n\tif (\n\t\t// TODO: remove this condition and the associated \"parentRuleStack\", cycles\n\t\t// should be detected and avoided at parse time.\n\t\t!engine.cache._meta.parentRuleStack.includes(node.dottedName)\n\t) {\n\t\tengine.cache._meta.parentRuleStack.unshift(node.dottedName)\n\t\tlet parentIsNotApplicable = defaultNode(false) as EvaluatedNode\n\t\tif (nodesTypes.get(nullableParent)?.isNullable) {\n\t\t\tparentIsNotApplicable = engine.evaluateNode({\n\t\t\t\tnodeKind: 'est non applicable',\n\t\t\t\texplanation: nullableParent,\n\t\t\t})\n\t\t}\n\t\tif (\n\t\t\tparentIsNotApplicable.nodeValue !== true &&\n\t\t\tnodesTypes.get(nullableParent)?.type === 'boolean'\n\t\t) {\n\t\t\tparentIsNotApplicable = engine.evaluateNode({\n\t\t\t\tnodeKind: 'operation',\n\t\t\t\toperator: '=',\n\t\t\t\toperationKind: '=',\n\t\t\t\texplanation: [nullableParent, defaultNode(false)],\n\t\t\t})\n\t\t}\n\n\t\tengine.cache._meta.parentRuleStack.shift()\n\t\tif (parentIsNotApplicable.nodeValue === true) {\n\t\t\treturn {\n\t\t\t\truleDisabledByItsParent: true,\n\t\t\t\tparentMissingVariables: parentIsNotApplicable.missingVariables ?? {},\n\t\t\t\tnullableParent,\n\t\t\t}\n\t\t}\n\t}\n\n\tlet parentMissingVariables: MissingVariables = {}\n\n\tif (nodesTypes.get(nullableParent)?.type === 'boolean') {\n\t\tconst parentEvaluation = engine.evaluateNode(nullableParent)\n\t\tparentMissingVariables = parentEvaluation.missingVariables ?? {}\n\t\treturn {\n\t\t\truleDisabledByItsParent: parentEvaluation.nodeValue === false,\n\t\t\tparentMissingVariables,\n\t\t\tnullableParent,\n\t\t}\n\t}\n\n\treturn {\n\t\truleDisabledByItsParent: false,\n\t\tparentMissingVariables,\n\t\tnullableParent,\n\t}\n}\n","import parse from '../parse'\nimport { Context } from '../parsePublicodes'\nimport { parseRules } from '../rule'\n\nexport default function parseAvec(v, context: Context) {\n\tparseRules(v.avec, context)\n\tconst valeur = parse(v.valeur, context)\n\treturn valeur\n}\n\nparseAvec.nom = 'avec' as const\n","import Engine from '..'\nimport { ASTNode, Evaluation } from '../AST/types'\nimport { PublicodesError, warning } from '../error'\nimport { mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport { convertUnit, inferUnit } from '../units'\n\ntype TrancheNode = { taux: ASTNode } | { montant: ASTNode }\nexport type TrancheNodes = Array<\n\tTrancheNode & { plafond?: ASTNode; isActive?: boolean }\n>\n\nexport const parseTranches = (tranches, context): TrancheNodes => {\n\treturn tranches.map((node, i) => {\n\t\tif (!node.plafond && i > tranches.length) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'SyntaxError',\n\t\t\t\t`La tranche n°${i} du barème n'a pas de plafond précisé. Seule la dernière tranche peut ne pas être plafonnée`,\n\t\t\t\t{ dottedName: '' },\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...node,\n\t\t\t...(node.taux !== undefined ? { taux: parse(node.taux, context) } : {}),\n\t\t\t...(node.montant !== undefined ?\n\t\t\t\t{ montant: parse(node.montant, context) }\n\t\t\t:\t{}),\n\t\t\tplafond:\n\t\t\t\t'plafond' in node ?\n\t\t\t\t\tparse(node.plafond, context)\n\t\t\t\t:\t{\n\t\t\t\t\t\tnodeValue: Infinity,\n\t\t\t\t\t\tnodeKind: 'constant',\n\t\t\t\t\t\ttype: 'number',\n\t\t\t\t\t\tisNullable: false,\n\t\t\t\t\t},\n\t\t}\n\t})\n}\n\nexport function evaluatePlafondUntilActiveTranche(\n\tthis: Engine,\n\t{ multiplicateur, assiette, parsedTranches },\n) {\n\treturn parsedTranches.reduce(\n\t\t([tranches, activeTrancheFound], parsedTranche, i: number) => {\n\t\t\tif (activeTrancheFound) {\n\t\t\t\treturn [\n\t\t\t\t\t[...tranches, { ...parsedTranche, isAfterActive: true }],\n\t\t\t\t\tactiveTrancheFound,\n\t\t\t\t]\n\t\t\t}\n\n\t\t\tconst plafond = this.evaluateNode(parsedTranche.plafond)\n\t\t\tconst plancher =\n\t\t\t\ttranches[i - 1] ? tranches[i - 1].plafond : { nodeValue: 0 }\n\n\t\t\tlet plafondValue: Evaluation =\n\t\t\t\t(\n\t\t\t\t\tplafond.nodeValue === undefined ||\n\t\t\t\t\tmultiplicateur.nodeValue === undefined\n\t\t\t\t) ?\n\t\t\t\t\tundefined\n\t\t\t\t:\tplafond.nodeValue * multiplicateur.nodeValue\n\n\t\t\ttry {\n\t\t\t\tplafondValue =\n\t\t\t\t\tplafondValue === Infinity || plafondValue === 0 ?\n\t\t\t\t\t\tplafondValue\n\t\t\t\t\t:\tconvertUnit(\n\t\t\t\t\t\t\tinferUnit('*', [plafond.unit, multiplicateur.unit]),\n\t\t\t\t\t\t\tassiette.unit,\n\t\t\t\t\t\t\tplafondValue,\n\t\t\t\t\t\t)\n\t\t\t} catch (e) {\n\t\t\t\twarning(\n\t\t\t\t\tthis.context.logger,\n\t\t\t\t\t`L'unité du plafond de la tranche n°${\n\t\t\t\t\t\ti + 1\n\t\t\t\t\t} n'est pas compatible avec celle l'assiette`,\n\t\t\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t\t\t\te,\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst plancherValue = tranches[i - 1] ? tranches[i - 1].plafondValue : 0\n\t\t\tconst isAfterActive =\n\t\t\t\tplancherValue === undefined || assiette.nodeValue === undefined ?\n\t\t\t\t\tundefined\n\t\t\t\t:\tplancherValue > assiette.nodeValue\n\n\t\t\tconst calculationValues = [plafond, assiette, multiplicateur, plancher]\n\t\t\tif (calculationValues.some((node) => node.nodeValue === undefined)) {\n\t\t\t\treturn [\n\t\t\t\t\t[\n\t\t\t\t\t\t...tranches,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...parsedTranche,\n\t\t\t\t\t\t\tplafond,\n\t\t\t\t\t\t\tplafondValue,\n\t\t\t\t\t\t\tplancherValue,\n\t\t\t\t\t\t\tnodeValue: undefined,\n\t\t\t\t\t\t\tisActive: undefined,\n\t\t\t\t\t\t\tisAfterActive,\n\t\t\t\t\t\t\tmissingVariables: mergeAllMissing(calculationValues),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tfalse,\n\t\t\t\t]\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\t!!tranches[i - 1] &&\n\t\t\t\t!!plancherValue &&\n\t\t\t\t(plafondValue as number) <= plancherValue\n\t\t\t) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'EvaluationError',\n\t\t\t\t\t`Le plafond de la tranche n°${\n\t\t\t\t\t\ti + 1\n\t\t\t\t\t} a une valeur inférieure à celui de la tranche précédente`,\n\t\t\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst tranche = {\n\t\t\t\t...parsedTranche,\n\t\t\t\tplafond,\n\t\t\t\tplancherValue,\n\t\t\t\tplafondValue,\n\t\t\t\tisAfterActive,\n\t\t\t\tisActive:\n\t\t\t\t\tassiette.nodeValue >= plancherValue &&\n\t\t\t\t\tassiette.nodeValue < (plafondValue as number),\n\t\t\t}\n\n\t\t\treturn [[...tranches, tranche], tranche.isActive]\n\t\t},\n\t\t[[], false],\n\t)[0]\n}\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode, EvaluatedNode, NodeKind } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { defaultNode, mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport { convertUnit, parseUnit } from '../units'\nimport {\n\tTrancheNodes,\n\tevaluatePlafondUntilActiveTranche,\n\tparseTranches,\n} from './trancheUtils'\n\n// Barème en taux marginaux.\nexport type BarèmeNode = {\n\texplanation: {\n\t\ttranches: TrancheNodes\n\t\tmultiplicateur: ASTNode\n\t\tassiette: ASTNode\n\t}\n\tnodeKind: 'barème'\n}\nexport default function parseBarème(v, context): BarèmeNode {\n\tconst explanation = {\n\t\tassiette: parse(v.assiette, context),\n\t\tmultiplicateur:\n\t\t\tv.multiplicateur ? parse(v.multiplicateur, context) : defaultNode(1),\n\t\ttranches: parseTranches(v.tranches, context),\n\t}\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'barème',\n\t}\n}\n\nfunction evaluateBarème(tranches, assiette, evaluate) {\n\treturn tranches.map((tranche) => {\n\t\tif (tranche.isAfterActive) {\n\t\t\treturn { ...tranche, nodeValue: 0 }\n\t\t}\n\t\tconst taux = evaluate(tranche.taux)\n\t\tconst missingVariables = mergeAllMissing([taux, tranche])\n\n\t\tif (\n\t\t\t[\n\t\t\t\tassiette.nodeValue,\n\t\t\t\ttaux.nodeValue,\n\t\t\t\ttranche.plafondValue,\n\t\t\t\ttranche.plancherValue,\n\t\t\t].some((value) => value === undefined)\n\t\t) {\n\t\t\treturn {\n\t\t\t\t...tranche,\n\t\t\t\ttaux,\n\t\t\t\tnodeValue: undefined,\n\t\t\t\tmissingVariables,\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\t...tranche,\n\t\t\ttaux,\n\t\t\t...('unit' in assiette && { unit: assiette.unit }),\n\t\t\tnodeValue:\n\t\t\t\t(Math.min(assiette.nodeValue, tranche.plafondValue) -\n\t\t\t\t\ttranche.plancherValue) *\n\t\t\t\tconvertUnit(taux.unit, parseUnit(''), taux.nodeValue as number),\n\t\t\tmissingVariables,\n\t\t}\n\t})\n}\nconst evaluate: EvaluationFunction<'barème'> = function (node) {\n\tconst evaluate = this.evaluateNode.bind(this)\n\tconst assiette = this.evaluateNode(\n\t\tnode.explanation.assiette,\n\t) as EvaluatedNode\n\tconst multiplicateur = this.evaluateNode(node.explanation.multiplicateur)\n\n\tif (multiplicateur.nodeValue === 0) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t`Le multiplicateur ne peut pas être nul`,\n\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t)\n\t}\n\n\tlet tranches: any = node.explanation.tranches\n\tlet nodeValue = assiette.nodeValue\n\n\tif (![0, undefined, null].includes(assiette.nodeValue)) {\n\t\ttranches = evaluateBarème(\n\t\t\tevaluatePlafondUntilActiveTranche.call(this, {\n\t\t\t\tparsedTranches: node.explanation.tranches,\n\t\t\t\tassiette,\n\t\t\t\tmultiplicateur,\n\t\t\t}),\n\t\t\tassiette,\n\t\t\tevaluate,\n\t\t)\n\t\tnodeValue = tranches.reduce(\n\t\t\t(value, { nodeValue }) =>\n\t\t\t\tnodeValue == undefined ? undefined : value + nodeValue,\n\t\t\t0,\n\t\t)\n\t}\n\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\tmissingVariables: mergeAllMissing([assiette, multiplicateur, ...tranches]),\n\t\texplanation: {\n\t\t\tassiette,\n\t\t\tmultiplicateur,\n\t\t\ttranches,\n\t\t},\n\t\tunit: assiette.unit,\n\t} as any\n}\n\nregisterEvaluationFunction('barème', evaluate)\n","import { EvaluationFunction } from '..'\nimport { ASTNode } from '../AST/types'\nimport { PublicodesError } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { bonus, mergeAllMissing, mergeMissing } from '../evaluationUtils'\nimport parse from '../parse'\n\nexport type ConditionNode = {\n\texplanation: {\n\t\tsi: ASTNode\n\t\talors: ASTNode\n\t\tsinon: ASTNode\n\t}\n\tnodeKind: 'condition'\n}\n\nconst evaluate: EvaluationFunction<'condition'> = function (node) {\n\tlet evaluation\n\tconst condition = this.evaluateNode(node.explanation.si)\n\tlet alors = node.explanation.alors\n\tlet sinon = node.explanation.sinon\n\tif ('unit' in condition) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t'La condition doit être de type booléen',\n\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t)\n\t}\n\tif (condition.nodeValue === true) {\n\t\talors = this.evaluateNode(node.explanation.alors)\n\t\t;(alors as any).isActive = true\n\t\tevaluation = alors\n\t} else if (condition.nodeValue === false) {\n\t\tsinon = this.evaluateNode(node.explanation.sinon)\n\t\tevaluation = sinon\n\t} else if (condition.nodeValue === null) {\n\t\tevaluation = condition\n\t} else if (condition.nodeValue === undefined) {\n\t\tsinon = this.evaluateNode(node.explanation.sinon)\n\t\talors = this.evaluateNode(node.explanation.alors)\n\t\tevaluation = {\n\t\t\t...condition,\n\t\t\tmissingVariables: mergeAllMissing([sinon, alors]),\n\t\t}\n\t} else {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t'La condition doit être de type booléen',\n\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t)\n\t}\n\tconst unit = evaluation.unit ?? (alors as any).unit\n\treturn {\n\t\tnodeValue: evaluation.nodeValue,\n\t\tmissingVariables: mergeMissing(\n\t\t\tbonus(condition.missingVariables),\n\t\t\tevaluation.missingVariables,\n\t\t),\n\t\t...(unit != undefined ? { unit } : {}),\n\t\t...node,\n\t\texplanation: { si: condition, alors, sinon },\n\t}\n}\nexport default function parseCondition(v, context) {\n\tconst explanation = {\n\t\tsi: parse(v.si, context),\n\t\talors: parse(v.alors, context),\n\t\tsinon: parse(v.sinon, context),\n\t}\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'condition',\n\t} as ConditionNode\n}\n\nparseCondition.nom = 'condition'\n\nregisterEvaluationFunction('condition', evaluate)\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { notApplicableNode } from '../evaluationUtils'\nimport parse from '../parse'\nimport { ReferenceNode } from '../reference'\nimport { serializeUnit } from '../units'\n\nexport type ContextNode = {\n\texplanation: {\n\t\tvaleur: ASTNode\n\t\tcontexte: Array<[ReferenceNode, ASTNode]>\n\t\tsubEngineId: number\n\t}\n\tnodeKind: 'contexte'\n}\n\nexport default function parseMecanismContexte(v, context) {\n\tconst contexte = Object.keys(v.contexte).map((dottedName) => [\n\t\tparse(dottedName, context),\n\t\tparse(v.contexte[dottedName], context),\n\t])\n\n\tconst node = parse(v.valeur, context)\n\n\treturn {\n\t\texplanation: {\n\t\t\tvaleur: node,\n\t\t\tcontexte,\n\t\t\tsubEngineId: context.subEngineIncrementingNumber++,\n\t\t},\n\t\tnodeKind: parseMecanismContexte.nom,\n\t} as ContextNode\n}\nparseMecanismContexte.nom = 'contexte' as const\n\nconst evaluateContexte: EvaluationFunction<'contexte'> = function (node) {\n\tconst amendedSituation = Object.fromEntries(\n\t\tnode.explanation.contexte\n\t\t\t.filter(([originRule, replacement]) => {\n\t\t\t\tconst originRuleEvaluation = this.evaluateNode(originRule)\n\t\t\t\tconst replacementEvaluation = this.evaluateNode(replacement)\n\t\t\t\treturn (\n\t\t\t\t\toriginRuleEvaluation.nodeValue !== replacementEvaluation.nodeValue ||\n\t\t\t\t\tserializeUnit(originRuleEvaluation.unit) !==\n\t\t\t\t\t\tserializeUnit(replacementEvaluation.unit)\n\t\t\t\t)\n\t\t\t})\n\t\t\t.map(\n\t\t\t\t([originRule, replacement]) =>\n\t\t\t\t\t[originRule.dottedName, replacement] as [string, ASTNode],\n\t\t\t),\n\t)\n\tif (\n\t\tthis.cache._meta.currentContexteSituation ===\n\t\tJSON.stringify(amendedSituation)\n\t) {\n\t\t// If the situation is the same as the last time we evaluated the contexte, it means that\n\t\t// there is a loop\n\t\treturn {\n\t\t\t...notApplicableNode,\n\t\t\t...node,\n\t\t}\n\t}\n\n\tconst engine = this.shallowCopy()\n\tengine.subEngineId = node.explanation.subEngineId\n\tthis.subEngines[node.explanation.subEngineId] = engine\n\tif (Object.keys(amendedSituation).length) {\n\t\tengine.setSituation(amendedSituation, {\n\t\t\tkeepPreviousSituation: true,\n\t\t})\n\n\t\t// The following code ensure that we use the **origin context** evaluation\n\t\t// for the values in the ammended situation\n\n\t\t// We do so by altering the cache so that the situation rule seems to have already\n\t\t// been evaluated\n\n\t\t// This is not an elegant way of doing so, but its temporary.\n\t\t// The correct implementation is discussed in :\n\t\t// https://github.com/publicodes/publicodes/discussions/92\n\t\tObject.entries(amendedSituation).forEach(([originDottedName, value]) => {\n\t\t\tconst evaluation = this.cache.nodes.get(value)\n\t\t\tif (!evaluation) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'InternalError',\n\t\t\t\t\t'The situation should have already been evaluated',\n\t\t\t\t\t{\n\t\t\t\t\t\tdottedName: this.context.dottedName,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst originRule =\n\t\t\t\tengine.context.parsedRules[originDottedName + ' . $SITUATION']\n\t\t\tif (!originRule?.explanation.valeur) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'InternalError',\n\t\t\t\t\t'The origin rule should be defined',\n\t\t\t\t\t{\n\t\t\t\t\t\tdottedName: this.context.dottedName,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tengine.cache.nodes.set(originRule.explanation.valeur, evaluation)\n\t\t})\n\t}\n\n\tengine.cache._meta.currentContexteSituation = JSON.stringify(amendedSituation)\n\tconst evaluatedNode = engine.evaluateNode(node.explanation.valeur)\n\n\treturn {\n\t\t...node,\n\t\tnodeValue: evaluatedNode.nodeValue,\n\t\texplanation: {\n\t\t\t...node.explanation,\n\t\t\tvaleur: evaluatedNode,\n\t\t},\n\t\tmissingVariables: evaluatedNode.missingVariables,\n\t\t...('unit' in evaluatedNode && { unit: evaluatedNode.unit }),\n\t}\n}\n\nregisterEvaluationFunction('contexte', evaluateContexte)\n","import { PublicodesError } from './error'\n\nexport function normalizeDateString(dateString: string): string {\n\tlet [day, month, year] = dateString.split('/')\n\tif (!year) {\n\t\t;[day, month, year] = ['01', day, month]\n\t}\n\treturn normalizeDate(+year, +month, +day)\n}\n\nconst pad = (n: number): string => (+n < 10 ? `0${n}` : '' + n)\nexport function normalizeDate(\n\tyear: number,\n\tmonth: number,\n\tday: number,\n): string {\n\tconst date = new Date(+year, +month - 1, +day)\n\tif (!+date || date.getDate() !== +day) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`La date ${day}/${month}/${year} n'est pas valide`,\n\t\t\t{ dottedName: '' },\n\t\t)\n\t}\n\treturn `${pad(day)}/${pad(month)}/${pad(year)}`\n}\n\nexport function convertToDate(value: string): Date {\n\tconst [day, month, year] = normalizeDateString(value).split('/')\n\tconst result = new Date(+year, +month - 1, +day)\n\t// Reset date to utc midnight for exact calculation of day difference (no\n\t// daylight saving effect)\n\tresult.setMinutes(result.getMinutes() - result.getTimezoneOffset())\n\treturn result\n}\n\nexport function convertToString(date: Date): string {\n\treturn normalizeDate(date.getFullYear(), date.getMonth() + 1, date.getDate())\n}\n\nexport function getRelativeDate(date: string, dayDifferential: number): string {\n\tconst relativeDate = new Date(convertToDate(date))\n\trelativeDate.setDate(relativeDate.getDate() + dayDifferential)\n\treturn convertToString(relativeDate)\n}\n\nexport function getYear(date: string): number {\n\treturn +date.slice(-4)\n}\n\nexport function getTrimestreCivil(date: string) {\n\tconst [, month, year] = date.split('/')\n\tconst trimester = Math.floor((Number.parseInt(month, 10) - 1) / 3)\n\tconst startingMonth = 3 * trimester + 1\n\treturn `01/${startingMonth.toString().padStart(2, '0')}/${year}`\n}\n\nexport function getDifferenceInDays(from: string, to: string): number {\n\tconst millisecondsPerDay = 1000 * 60 * 60 * 24\n\treturn (\n\t\t(convertToDate(to).getTime() - convertToDate(from).getTime()) /\n\t\tmillisecondsPerDay\n\t)\n}\n\nexport function getDifferenceInMonths(from: string, to: string): number {\n\t// We want to compute the difference in actual month between the two dates\n\t// For date that start during a month, a pro-rata will be done depending on\n\t// the duration of the month in days\n\tconst [dayFrom, monthFrom, yearFrom] = from.split('/').map((x) => +x)\n\tconst [dayTo, monthTo, yearTo] = to.split('/').map((x) => +x)\n\tconst numberOfFullMonth = monthTo - monthFrom + 12 * (yearTo - yearFrom)\n\tconst numDayMonthFrom = new Date(yearFrom, monthFrom, 0).getDate()\n\tconst numDayMonthTo = new Date(yearTo, monthTo, 0).getDate()\n\tconst prorataMonthFrom = (dayFrom - 1) / numDayMonthFrom\n\tconst prorataMonthTo = dayTo / numDayMonthTo\n\treturn numberOfFullMonth - prorataMonthFrom + prorataMonthTo\n}\n\nexport function getDifferenceInYears(from: string, to: string): number {\n\tconst differenceInDays = getDifferenceInDays(from, to)\n\n\tconst isLeapYear = (year: number) =>\n\t\t(year % 4 === 0 && year % 100 !== 0) || year % 400 === 0\n\tconst after1stMarch = (date: Date) =>\n\t\tdate >= new Date(date.getFullYear(), 2, 1)\n\n\tconst fromDate = convertToDate(from)\n\tconst toDate = convertToDate(to)\n\n\tconst fromYear = fromDate.getFullYear() + (after1stMarch(fromDate) ? 1 : 0)\n\tconst toYear = toDate.getFullYear() + (after1stMarch(fromDate) ? 0 : -1)\n\n\tconst leapYearsCount = Array.from(\n\t\t{ length: toYear - fromYear + 1 },\n\t\t(_, i) => fromYear + i,\n\t).filter(isLeapYear).length\n\n\treturn (differenceInDays - leapYearsCount) / 365\n}\n\nexport function getDifferenceInTrimestreCivils(\n\tfrom: string,\n\tto: string,\n): number {\n\treturn (\n\t\tMath.floor(\n\t\t\tgetDifferenceInMonths(getTrimestreCivil(from), getTrimestreCivil(to)) / 3,\n\t\t) + 1\n\t)\n}\n\nexport function getDifferenceInYearsCivil(from: string, to: string): number {\n\tconst fromYear = '01/' + getYear(from)\n\tconst toYear = '01/' + getYear(to)\n\treturn Math.floor(getDifferenceInYears(fromYear, toYear)) + 1\n}\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode, Evaluation, Unit } from '../AST/types'\nimport {\n\tconvertToString,\n\tgetDifferenceInDays,\n\tgetDifferenceInMonths,\n\tgetDifferenceInTrimestreCivils,\n\tgetDifferenceInYears,\n\tgetDifferenceInYearsCivil,\n} from '../date'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { defaultNode, mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport { parseUnit } from '../units'\n\nexport type DuréeNode = {\n\texplanation: {\n\t\tdepuis: ASTNode\n\t\t\"jusqu'à\": ASTNode\n\t}\n\tunit: Unit\n\tnodeKind: 'durée'\n}\nconst evaluate: EvaluationFunction<'durée'> = function (node) {\n\tconst fromNode = this.evaluateNode(node.explanation.depuis)\n\tconst toNode = this.evaluateNode(node.explanation[\"jusqu'à\"])\n\n\tconst from = fromNode.nodeValue as Evaluation\n\tconst to = toNode.nodeValue as Evaluation\n\n\tlet nodeValue: Evaluation\n\tif (from === null || to === null) {\n\t\tnodeValue = null\n\t} else if (from === undefined || to === undefined) {\n\t\tnodeValue = undefined\n\t} else {\n\t\tswitch (node.unit.numerators[0] as PossibleUnit) {\n\t\t\tcase 'jour':\n\t\t\t\tnodeValue = getDifferenceInDays(from, to)\n\t\t\t\tbreak\n\t\t\tcase 'mois':\n\t\t\t\tnodeValue = getDifferenceInMonths(from, to)\n\t\t\t\tbreak\n\t\t\tcase 'an':\n\t\t\t\tnodeValue = getDifferenceInYears(from, to)\n\t\t\t\tbreak\n\t\t\tcase 'trimestre':\n\t\t\t\tnodeValue = getDifferenceInMonths(from, to) / 3\n\t\t\t\tbreak\n\t\t\tcase 'trimestre civil':\n\t\t\t\tnodeValue = getDifferenceInTrimestreCivils(from, to)\n\t\t\t\tbreak\n\t\t\tcase 'année civile':\n\t\t\t\tnodeValue = getDifferenceInYearsCivil(from, to)\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\tif (typeof nodeValue === 'number') {\n\t\tnodeValue = Math.max(0, nodeValue)\n\t}\n\n\treturn {\n\t\t...node,\n\t\tmissingVariables: mergeAllMissing([fromNode, toNode]),\n\t\tnodeValue,\n\t\texplanation: {\n\t\t\tdepuis: fromNode,\n\t\t\t\"jusqu'à\": toNode,\n\t\t},\n\t}\n}\n\nconst today = defaultNode(convertToString(new Date()))\nexport default (v, context) => {\n\tconst explanation = {\n\t\tdepuis: parse(v.depuis ?? today, context),\n\t\t\"jusqu'à\": parse(v[\"jusqu'à\"] ?? today, context),\n\t}\n\tconst unit = v.unité ? parseUnit(v.unité) : parseUnit('jour')\n\tif (\n\t\tunit.denominators.length > 0 ||\n\t\tunit.numerators.length > 1 ||\n\t\t!possibleUnit.includes(unit.numerators[0] as PossibleUnit)\n\t) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`Seules les unités suivantes sont acceptées pour une durée : ${possibleUnit.join(\n\t\t\t\t', ',\n\t\t\t)}.\n\tL'unité fournie est: ${unit.numerators[0]}`,\n\t\t\t{\n\t\t\t\tdottedName: context.dottedName,\n\t\t\t},\n\t\t)\n\t}\n\treturn {\n\t\texplanation,\n\t\tunit,\n\t\tnodeKind: 'durée',\n\t} as DuréeNode\n}\n\nregisterEvaluationFunction('durée', evaluate)\n\ntype PossibleUnit = (typeof possibleUnit)[number]\nconst possibleUnit = [\n\t'mois',\n\t'jour',\n\t'an',\n\t'trimestre',\n\t'trimestre civil',\n\t'année civile',\n] as const\n","import { EvaluationFunction } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport parse from '../parse'\nimport { createParseInlinedMecanism } from './inlineMecanism'\n\nexport type EstNonDéfiniNode = {\n\texplanation: ASTNode\n\tnodeKind: 'est non défini'\n}\n\nexport function parseEstNonDéfini(v, context) {\n\tconst explanation = parse(v, context)\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'est non défini',\n\t} as EstNonDéfiniNode\n}\nparseEstNonDéfini.nom = 'est non défini'\n\nconst parseEstDéfini = createParseInlinedMecanism(\n\t'est défini',\n\t{\n\t\tvaleur: {},\n\t},\n\t{\n\t\t'=': [{ 'est non défini': 'valeur' }, 'non'],\n\t},\n)\n\nconst parseEstApplicable = createParseInlinedMecanism(\n\t'est applicable',\n\t{\n\t\tvaleur: {},\n\t},\n\t{\n\t\t'=': [{ 'est non applicable': 'valeur' }, 'non'],\n\t},\n)\n\nexport { parseEstDéfini, parseEstApplicable }\n\nconst evaluate: EvaluationFunction<'est non défini'> = function (node) {\n\tconst valeur = this.evaluateNode(node.explanation)\n\tlet nodeValue: boolean | undefined | null = false\n\tif (valeur.nodeValue === undefined) {\n\t\tnodeValue = true\n\t}\n\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\tmissingVariables: valeur.missingVariables,\n\t\texplanation: valeur,\n\t}\n}\nregisterEvaluationFunction('est non défini', evaluate)\n","import { EvaluationFunction } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport { evaluateDisablingParent } from '../rule'\n\nexport type EstNonApplicableNode = {\n\texplanation: ASTNode\n\tnodeKind: 'est non applicable'\n}\nexport function parseEstNonApplicable(v, context) {\n\tconst explanation = parse(v, context)\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'est non applicable' as const,\n\t} as EstNonApplicableNode\n}\nparseEstNonApplicable.nom = 'est non applicable'\n\nconst isNotApplicable = (node: ASTNode) => {\n\treturn {\n\t\tnodeKind: 'est non applicable' as const,\n\t\texplanation: node,\n\t}\n}\n\nconst evaluateIsNotApplicable: EvaluationFunction<'est non applicable'> =\n\tfunction (node) {\n\t\tconst valeur = node.explanation\n\n\t\tif (\n\t\t\tthis.context.nodesTypes.get(valeur)?.isNullable === false &&\n\t\t\tvaleur.nodeKind !== 'rule' &&\n\t\t\tvaleur.nodeKind !== 'reference'\n\t\t) {\n\t\t\treturn { ...node, nodeValue: false, missingVariables: {} }\n\t\t}\n\n\t\tif (\n\t\t\tthis.cache.nodes.has(valeur) &&\n\t\t\tthis.cache.nodes.get(valeur) !== undefined\n\t\t) {\n\t\t\treturn {\n\t\t\t\t...node,\n\t\t\t\tnodeValue: this.cache.nodes.get(valeur)?.nodeValue === null,\n\t\t\t\tmissingVariables: this.cache.nodes.get(valeur)?.missingVariables ?? {},\n\t\t\t}\n\t\t}\n\n\t\tswitch (valeur.nodeKind) {\n\t\t\tcase 'rule': {\n\t\t\t\tconst { ruleDisabledByItsParent, parentMissingVariables } =\n\t\t\t\t\tevaluateDisablingParent(this, valeur)\n\n\t\t\t\tif (ruleDisabledByItsParent) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...node,\n\t\t\t\t\t\tnodeValue: true,\n\t\t\t\t\t\tmissingVariables: parentMissingVariables,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst isNotApplicableEvaluation = this.evaluateNode(\n\t\t\t\t\tisNotApplicable(valeur.explanation.valeur),\n\t\t\t\t)\n\t\t\t\tconst missingVariables = mergeMissing(\n\t\t\t\t\tparentMissingVariables,\n\t\t\t\t\tisNotApplicableEvaluation.missingVariables,\n\t\t\t\t)\n\t\t\t\t// If the rule can be disabled thought the situation, it should be listed inside the missing variables\n\t\t\t\tif (\n\t\t\t\t\tisNotApplicableEvaluation.nodeValue === false &&\n\t\t\t\t\tthis.context.nodesTypes.get(\n\t\t\t\t\t\tthis.context.parsedRules[`${valeur.dottedName} . $SITUATION`],\n\t\t\t\t\t)?.isNullable &&\n\t\t\t\t\t!Object.keys(isNotApplicableEvaluation.missingVariables).length\n\t\t\t\t) {\n\t\t\t\t\tmissingVariables[valeur.dottedName] = 1\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\t...node,\n\t\t\t\t\tnodeValue: isNotApplicableEvaluation.nodeValue,\n\t\t\t\t\tmissingVariables,\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'reference':\n\t\t\t\treturn {\n\t\t\t\t\t...this.evaluateNode(\n\t\t\t\t\t\tisNotApplicable(this.context.parsedRules[valeur.dottedName!]),\n\t\t\t\t\t),\n\t\t\t\t\t...node,\n\t\t\t\t}\n\n\t\t\tcase 'condition':\n\t\t\t\treturn {\n\t\t\t\t\t...this.evaluateNode({\n\t\t\t\t\t\t...valeur,\n\t\t\t\t\t\texplanation: {\n\t\t\t\t\t\t\tsi: valeur.explanation.si,\n\t\t\t\t\t\t\talors: isNotApplicable(valeur.explanation.alors),\n\t\t\t\t\t\t\tsinon: isNotApplicable(valeur.explanation.sinon),\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t\t...node,\n\t\t\t\t}\n\t\t}\n\t\tconst evaluatedValeur = this.evaluateNode(valeur)\n\n\t\treturn {\n\t\t\t...node,\n\t\t\tnodeValue:\n\t\t\t\tevaluatedValeur.nodeValue === undefined ?\n\t\t\t\t\tundefined\n\t\t\t\t:\tevaluatedValeur.nodeValue === null,\n\t\t\tmissingVariables: evaluatedValeur.missingVariables,\n\t\t}\n\t}\n\nregisterEvaluationFunction('est non applicable', evaluateIsNotApplicable)\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { defaultNode, mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport {\n\tevaluatePlafondUntilActiveTranche,\n\tparseTranches,\n\tTrancheNodes,\n} from './trancheUtils'\n\nexport type GrilleNode = {\n\texplanation: {\n\t\tassiette: ASTNode\n\t\tmultiplicateur: ASTNode\n\t\ttranches: TrancheNodes\n\t}\n\tnodeKind: 'grille'\n}\n\nexport default function parseGrille(v, context): GrilleNode {\n\tconst explanation = {\n\t\tassiette: parse(v.assiette, context),\n\t\tmultiplicateur:\n\t\t\tv.multiplicateur ? parse(v.multiplicateur, context) : defaultNode(1),\n\t\ttranches: parseTranches(v.tranches, context),\n\t}\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'grille',\n\t}\n}\n\nconst evaluate: EvaluationFunction<'grille'> = function (node) {\n\tconst evaluate = this.evaluateNode.bind(this)\n\tconst assiette = this.evaluateNode(node.explanation.assiette)\n\tconst multiplicateur = this.evaluateNode(node.explanation.multiplicateur)\n\n\tif (multiplicateur.nodeValue === 0) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t`Le multiplicateur ne peut pas être nul`,\n\t\t\t{\n\t\t\t\tdottedName: this.cache._meta.evaluationRuleStack[0],\n\t\t\t},\n\t\t)\n\t}\n\n\tconst tranches = evaluatePlafondUntilActiveTranche\n\t\t.call(this, {\n\t\t\tparsedTranches: node.explanation.tranches,\n\t\t\tassiette,\n\t\t\tmultiplicateur,\n\t\t})\n\t\t.map((tranche) => {\n\t\t\tif (tranche.isActive === false) {\n\t\t\t\treturn tranche\n\t\t\t}\n\t\t\tconst montant = evaluate(tranche.montant)\n\t\t\treturn {\n\t\t\t\t...tranche,\n\t\t\t\tmontant,\n\t\t\t\tnodeValue: montant.nodeValue,\n\t\t\t\tunit: montant.unit,\n\t\t\t\tmissingVariables: mergeAllMissing([montant, tranche]),\n\t\t\t}\n\t\t})\n\n\tlet activeTranches\n\tconst activeTranche = tranches.find((tranche) => tranche.isActive)\n\tif (activeTranche) {\n\t\tactiveTranches = [activeTranche]\n\t} else if (tranches[tranches.length - 1].isAfterActive === false) {\n\t\tactiveTranches = [{ nodeValue: false }]\n\t} else {\n\t\tactiveTranches = tranches.filter(\n\t\t\t(tranche) => tranche.isActive === undefined,\n\t\t)\n\t}\n\n\tconst nodeValue =\n\t\t!activeTranches[0] ? false\n\t\t: activeTranches[0].isActive === undefined ? undefined\n\t\t: activeTranches[0].nodeValue\n\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\tmissingVariables: mergeAllMissing([\n\t\t\tassiette,\n\t\t\tmultiplicateur,\n\t\t\t...activeTranches,\n\t\t]),\n\t\texplanation: {\n\t\t\t...node.explanation,\n\t\t\tassiette,\n\t\t\tmultiplicateur,\n\t\t\ttranches,\n\t\t},\n\t\tunit: activeTranches[0]?.unit ?? undefined,\n\t} as any\n}\n\nregisterEvaluationFunction('grille', evaluate)\n","// We use a JavaScript implementation of the Brent method to find the root (the\n// \"zero\") of a monotone function. There are other methods like the\n// Newton-Raphson method, but they take the derivative of the function as an\n// input, wich in our case is costly to calculate. The Brent method doesn't\n// need to calculate the derivative.\n// An interesting description of the algorithm can be found here:\n// https://blogs.mathworks.com/cleve/2015/10/26/zeroin-part-2-brents-version/\n\n/**\n * Copied from https://gist.github.com/borgar/3317728\n *\n * Searches the interval from lowerLimit to upperLimit\n * for a root (i.e., zero) of the function func with respect to\n * its first argument using Brent's method root-finding algorithm.\n *\n * Translated from zeroin.c in http://www.netlib.org/c/brent.shar.\n *\n * Copyright (c) 2012 Borgar Thorsteinsson \n * MIT License, http://www.opensource.org/licenses/mit-license.php\n *\n * @param func function for which the root is sought.\n * @param lowerLimit the lower point of the interval to be searched.\n * @param upperLimit the upper point of the interval to be searched.\n * @param errorTol the desired accuracy (convergence tolerance).\n * @param maxIter the maximum number of iterations.\n * @param acceptableErrorTol return a result even if errorTol isn't reached after maxIter.\n * @returns an estimate for the root within accuracy.\n *\n */\nexport default function uniroot(\n\tfunc: (x: number) => number,\n\tlowerLimit: number,\n\tupperLimit: number,\n\terrorTol = 0,\n\tmaxIter = 100,\n\tacceptableErrorTol = 0,\n) {\n\tlet a = lowerLimit,\n\t\tb = upperLimit,\n\t\tc = a,\n\t\tfa = func(a),\n\t\tfb = func(b),\n\t\tfc = fa,\n\t\tactualTolerance: number,\n\t\tnewStep: number, // Step at this iteration\n\t\tprevStep: number, // Distance from the last but one to the last approximation\n\t\tp: number, // Interpolation step is calculated in the form p/q; division is delayed until the last moment\n\t\tq: number,\n\t\tfallback: number | undefined = undefined\n\n\twhile (maxIter-- > 0) {\n\t\tprevStep = b - a\n\n\t\tif (Math.abs(fc) < Math.abs(fb)) {\n\t\t\t// Swap data for b to be the best approximation\n\t\t\t;(a = b), (b = c), (c = a)\n\t\t\t;(fa = fb), (fb = fc), (fc = fa)\n\t\t}\n\n\t\tactualTolerance = 1e-15 * Math.abs(b) + errorTol / 2\n\t\tnewStep = (c - b) / 2\n\n\t\tif (Math.abs(newStep) <= actualTolerance || fb === 0) {\n\t\t\treturn b // Acceptable approx. is found\n\t\t}\n\n\t\t// Decide if the interpolation can be tried\n\t\tif (Math.abs(prevStep) >= actualTolerance && Math.abs(fa) > Math.abs(fb)) {\n\t\t\t// If prevStep was large enough and was in true direction, Interpolatiom may be tried\n\t\t\tlet t1: number, t2: number\n\t\t\tconst cb = c - b\n\t\t\tif (a === c) {\n\t\t\t\t// If we have only two distinct points linear interpolation can only be applied\n\t\t\t\tt1 = fb / fa\n\t\t\t\tp = cb * t1\n\t\t\t\tq = 1.0 - t1\n\t\t\t} else {\n\t\t\t\t// Quadric inverse interpolation\n\t\t\t\t;(q = fa / fc), (t1 = fb / fc), (t2 = fb / fa)\n\t\t\t\tp = t2 * (cb * q * (q - t1) - (b - a) * (t1 - 1))\n\t\t\t\tq = (q - 1) * (t1 - 1) * (t2 - 1)\n\t\t\t}\n\n\t\t\tif (p > 0) {\n\t\t\t\tq = -q // p was calculated with the opposite sign; make p positive\n\t\t\t} else {\n\t\t\t\tp = -p // and assign possible minus to q\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tp < 0.75 * cb * q - Math.abs(actualTolerance * q) / 2 &&\n\t\t\t\tp < Math.abs((prevStep * q) / 2)\n\t\t\t) {\n\t\t\t\t// If (b + p / q) falls in [b,c] and isn't too large it is accepted\n\t\t\t\tnewStep = p / q\n\t\t\t}\n\n\t\t\t// If p/q is too large then the bissection procedure can reduce [b,c] range to more extent\n\t\t}\n\n\t\tif (Math.abs(newStep) < actualTolerance) {\n\t\t\t// Adjust the step to be not less than tolerance\n\t\t\tnewStep = newStep > 0 ? actualTolerance : -actualTolerance\n\t\t}\n\n\t\t;(a = b), (fa = fb) // Save the previous approx.\n\t\t;(b += newStep), (fb = func(b)) // Do step to a new approxim.\n\n\t\tif ((fb > 0 && fc > 0) || (fb < 0 && fc < 0)) {\n\t\t\t;(c = a), (fc = fa) // Adjust c for it to have a sign opposite to that of b\n\t\t}\n\t\tif (Math.abs(fb) < errorTol) {\n\t\t\treturn b\n\t\t}\n\t\tif (Math.abs(fb) < acceptableErrorTol) {\n\t\t\tfallback = b\n\t\t}\n\t}\n\treturn fallback\n}\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode, EvaluatedNode, Unit } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { undefinedNumberNode } from '../evaluationUtils'\nimport parse from '../parse'\nimport { Context } from '../parsePublicodes'\nimport { ReferenceNode } from '../reference'\nimport uniroot from '../uniroot'\n\nexport type InversionNode = {\n\texplanation: {\n\t\truleToInverse: string\n\t\tinversionCandidates: Array\n\t\tunit?: Unit\n\n\t\t// Explanation computed during evaluation\n\t\tinversionGoal?: ASTNode\n\t\tnumberOfIteration?: number\n\t\tinversionFail?: boolean\n\t}\n\tnodeKind: 'inversion'\n}\n\n// The user of the inversion mechanism has to define a list of \"inversion\n// candidates\". At runtime, the evaluation function of the mechanism will look\n// at the situation value of these candidates, and use the first one that is\n// defined as its \"goal\" for the inversion\n//\n// The game is then to find an input such as the computed value of the \"goal\" is\n// equal to its situation value, mathematically we search for the zero of the\n// function x → f(x) - goal. The iteration logic between each test is\n// implemented in the `uniroot` file.\nexport const evaluateInversion: EvaluationFunction<'inversion'> = function (\n\tnode,\n) {\n\tconst inversionEngine = this.shallowCopy()\n\tif (\n\t\tthis.cache._meta.evaluationRuleStack\n\t\t\t.slice(1)\n\t\t\t.includes(node.explanation.ruleToInverse)\n\t) {\n\t\treturn {\n\t\t\t...undefinedNumberNode,\n\t\t\t...node,\n\t\t}\n\t}\n\tinversionEngine.cache._meta.parentRuleStack = [\n\t\t...this.cache._meta.parentRuleStack,\n\t]\n\tinversionEngine.cache._meta.evaluationRuleStack = [\n\t\t...this.cache._meta.evaluationRuleStack,\n\t]\n\tconst inversionGoal = node.explanation.inversionCandidates.find(\n\t\t(candidate) => {\n\t\t\tif (\n\t\t\t\tthis.cache._meta.evaluationRuleStack.includes(candidate.dottedName!)\n\t\t\t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tconst evaluation = inversionEngine.evaluateNode(\n\t\t\t\tinversionEngine.context.parsedRules[\n\t\t\t\t\t`${candidate.dottedName} . $SITUATION`\n\t\t\t\t],\n\t\t\t)\n\t\t\treturn (\n\t\t\t\ttypeof evaluation.nodeValue === 'number' &&\n\t\t\t\t!(candidate.dottedName! in evaluation.missingVariables)\n\t\t\t)\n\t\t},\n\t)\n\n\tif (inversionGoal === undefined) {\n\t\treturn {\n\t\t\t...node,\n\t\t\tnodeValue: undefined,\n\t\t\tmissingVariables: {\n\t\t\t\t...Object.fromEntries(\n\t\t\t\t\tnode.explanation.inversionCandidates.map((candidate) => [\n\t\t\t\t\t\tcandidate.dottedName,\n\t\t\t\t\t\t1,\n\t\t\t\t\t]),\n\t\t\t\t),\n\t\t\t\t[node.explanation.ruleToInverse]: 1,\n\t\t\t},\n\t\t}\n\t}\n\tconst evaluatedInversionGoal = inversionEngine.evaluateNode(inversionGoal)\n\tlet numberOfIteration = 0\n\n\tinversionEngine.setSituation(\n\t\t{\n\t\t\t[inversionGoal.dottedName!]: undefinedNumberNode,\n\t\t},\n\t\t{ keepPreviousSituation: true },\n\t)\n\tinversionEngine.cache.traversedVariablesStack =\n\t\tthis.cache.traversedVariablesStack ? [] : undefined\n\n\tlet lastEvaluation: EvaluatedNode\n\tconst evaluateWithValue = (n: number) => {\n\t\tnumberOfIteration++\n\t\tinversionEngine.setSituation(\n\t\t\t{\n\t\t\t\t[node.explanation.ruleToInverse]: {\n\t\t\t\t\tnodeValue: n,\n\t\t\t\t\tnodeKind: 'constant',\n\t\t\t\t\ttype: 'number',\n\t\t\t\t\tunit: evaluatedInversionGoal.unit,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{ keepPreviousSituation: true },\n\t\t)\n\t\tinversionEngine.cache.traversedVariablesStack =\n\t\t\tthis.cache.traversedVariablesStack ? [] : undefined\n\n\t\tlastEvaluation = inversionEngine.evaluateNode(inversionGoal)\n\t\treturn lastEvaluation\n\t}\n\n\tconst goal = evaluatedInversionGoal.nodeValue as number\n\tlet nodeValue: number | undefined | undefined = undefined\n\n\t// We do some blind attempts here to avoid using the default minimum and\n\t// maximum of +/- 10^8 that are required by the `uniroot` function. For the\n\t// first attempt we use the goal value as a very rough first approximation.\n\t// For the second attempt we do a proportionality coefficient with the result\n\t// from the first try and the goal value. The two attempts are then used in\n\t// the following way:\n\t// - if both results are `undefined` we assume that the inversion is impossible\n\t// because of missing variables\n\t// - otherwise, we calculate the missing variables of the node as the union of\n\t// the missings variables of our two attempts\n\t// - we cache the result of our two attempts so that `uniroot` doesn't\n\t// recompute them\n\tconst x1 = goal\n\tconst y1Node = evaluateWithValue(x1)\n\tconst y1 = y1Node.nodeValue as number\n\tconst coeff = y1 > goal ? 0.9 : 1.2\n\tconst x2 = y1 !== undefined ? (x1 * goal * coeff) / y1 : 2000\n\tconst y2Node = evaluateWithValue(x2)\n\tconst y2 = y2Node.nodeValue as number\n\n\tconst maxIterations = this.context.inversionMaxIterations ?? 10\n\n\tif (y1 !== undefined || y2 !== undefined) {\n\t\t// The `uniroot` function parameter. It will be called with its `min` and\n\t\t// `max` arguments, so we can use our cached nodes if the function is called\n\t\t// with the already computed x1 or x2.\n\t\tconst test = (x: number): number => {\n\t\t\tconst y =\n\t\t\t\tx === x1 ? y1\n\t\t\t\t: x === x2 ? y2\n\t\t\t\t: evaluateWithValue(x).nodeValue\n\t\t\treturn (y as number) - goal\n\t\t}\n\n\t\tconst defaultMin = -1000000\n\t\tconst defaultMax = 100000000\n\t\tconst nearestBelowGoal =\n\t\t\ty2 !== undefined && y2 < goal && (y2 > y1 || y1 > goal) ? x2\n\t\t\t: y1 !== undefined && y1 < goal && (y1 > y2 || y2 > goal) ? x1\n\t\t\t: defaultMin\n\t\tconst nearestAboveGoal =\n\t\t\ty2 !== undefined && y2 > goal && (y2 < y1 || y1 < goal) ? x2\n\t\t\t: y1 !== undefined && y1 > goal && (y1 < y2 || y2 < goal) ? x1\n\t\t\t: defaultMax\n\n\t\tnodeValue = uniroot(\n\t\t\ttest,\n\t\t\tnearestBelowGoal,\n\t\t\tnearestAboveGoal,\n\t\t\t0.1,\n\t\t\tmaxIterations,\n\t\t\t1,\n\t\t)\n\t}\n\n\tif (nodeValue == undefined) {\n\t\tthis.cache.inversionFail = true\n\t}\n\n\t// Uncomment to display the two attempts and their result\n\t// console.table([\n\t// \t{ x: x1, y: y1 },\n\t// \t{ x: x2, y: y2 },\n\t// ])\n\t// console.log('iteration inversion:', numberOfIteration)\n\tif (this.cache.traversedVariablesStack) {\n\t\tconst traversedVariablesStack = this.cache.traversedVariablesStack[0]\n\t\tif (traversedVariablesStack) {\n\t\t\t;(lastEvaluation!.traversedVariables ?? []).forEach((v) =>\n\t\t\t\ttraversedVariablesStack.add(v),\n\t\t\t)\n\t\t}\n\t}\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\tunit: evaluatedInversionGoal.unit,\n\t\texplanation: {\n\t\t\t...node.explanation,\n\t\t\tinversionGoal,\n\t\t\tnumberOfIteration,\n\t\t\tinversionFail: this.cache.inversionFail,\n\t\t},\n\t\tmissingVariables: lastEvaluation!.missingVariables,\n\t}\n}\n\nexport const mecanismInversion = (v, context: Context) => {\n\tlet avec = typeof v === 'object' && 'avec' in v ? v.avec : v\n\tif (v === null) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t\"Il manque les règles avec laquelle effectuer le calcul d'inversion dans le mécanisme `inversion numérique`\",\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\tif (!Array.isArray(avec)) {\n\t\tavec = [avec]\n\t}\n\treturn {\n\t\texplanation: {\n\t\t\truleToInverse: context.dottedName,\n\t\t\tinversionCandidates: avec.map((node) => ({\n\t\t\t\t...parse(node, context),\n\t\t\t})),\n\t\t},\n\t\tnodeKind: 'inversion',\n\t} as InversionNode\n}\n\nregisterEvaluationFunction('inversion', evaluateInversion)\n","import { PublicodesExpression } from '..'\nimport { notApplicableNode } from '../evaluationUtils'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\n\nexport const parseMaximumDe = createParseInlinedMecanismWithArray(\n\t'le maximum de',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) =>\n\t\t(valeur as Array).reduce(\n\t\t\t(acc, value) => ({\n\t\t\t\tcondition: {\n\t\t\t\t\tsi: {\n\t\t\t\t\t\t'est non applicable': '$INTERNAL valeur',\n\t\t\t\t\t},\n\t\t\t\t\talors: '$INTERNAL acc',\n\t\t\t\t\tsinon: {\n\t\t\t\t\t\tcondition: {\n\t\t\t\t\t\t\tsi: {\n\t\t\t\t\t\t\t\tou: [\n\t\t\t\t\t\t\t\t\t{ 'est non applicable': '$INTERNAL acc' },\n\t\t\t\t\t\t\t\t\t{ '>': ['$INTERNAL valeur', '$INTERNAL acc'] },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\talors: '$INTERNAL valeur',\n\t\t\t\t\t\t\tsinon: '$INTERNAL acc',\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tavec: {\n\t\t\t\t\t'[privé] $INTERNAL valeur': { valeur: value },\n\t\t\t\t\t'[privé] $INTERNAL acc': { valeur: acc },\n\t\t\t\t},\n\t\t\t}),\n\t\t\tnotApplicableNode,\n\t\t),\n)\n\nexport const parseMinimumDe = createParseInlinedMecanismWithArray(\n\t'le minimum de',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) =>\n\t\t(valeur as Array).reduce(\n\t\t\t(acc, value) => ({\n\t\t\t\tcondition: {\n\t\t\t\t\tsi: {\n\t\t\t\t\t\t'est non applicable': '$INTERNAL valeur',\n\t\t\t\t\t},\n\t\t\t\t\talors: '$INTERNAL acc',\n\t\t\t\t\tsinon: {\n\t\t\t\t\t\tcondition: {\n\t\t\t\t\t\t\tsi: {\n\t\t\t\t\t\t\t\tou: [\n\t\t\t\t\t\t\t\t\t{ 'est non applicable': '$INTERNAL acc' },\n\t\t\t\t\t\t\t\t\t{ '<': ['$INTERNAL valeur', '$INTERNAL acc'] },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\talors: '$INTERNAL valeur',\n\t\t\t\t\t\t\tsinon: '$INTERNAL acc',\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tavec: {\n\t\t\t\t\t'[privé] $INTERNAL valeur': { valeur: value },\n\t\t\t\t\t'[privé] $INTERNAL acc': { valeur: acc },\n\t\t\t\t},\n\t\t\t}),\n\t\t\tnotApplicableNode,\n\t\t),\n)\n","import { PublicodesExpression } from '..'\nimport { notApplicableNode } from '../evaluationUtils'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\n\nexport function reduceToSumNodes(\n\tvaleurs: Array,\n): PublicodesExpression {\n\treturn valeurs\n\t\t.reverse()\n\t\t.reduce((acc, value) => ({ '+': [value, acc] }), notApplicableNode)\n}\n\nexport default createParseInlinedMecanismWithArray(\n\t'somme',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) =>\n\t\treduceToSumNodes([...(valeur as Array)]),\n)\n","import { PublicodesExpression } from '..'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\nimport { reduceToSumNodes } from './somme'\n\nexport default createParseInlinedMecanismWithArray(\n\t'moyenne',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) => {\n\t\tconst valeurs = [...(valeur as Array)]\n\n\t\treturn {\n\t\t\t'/': [\n\t\t\t\treduceToSumNodes(valeurs),\n\t\t\t\treduceToSumNodes(valeurs.map(oneIfApplicable)),\n\t\t\t],\n\t\t}\n\t},\n)\n\nfunction oneIfApplicable(exp: PublicodesExpression): PublicodesExpression {\n\treturn {\n\t\t'applicable si': { 'est applicable': exp },\n\t\tvaleur: 1,\n\t}\n}\n","import { notApplicableNode } from '../evaluationUtils'\nimport { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'non applicable si',\n\t{\n\t\t'non applicable si': {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: 'non applicable si = non',\n\t\t\talors: 'valeur',\n\t\t\tsinon: notApplicableNode,\n\t\t},\n\t},\n)\n","import { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport parse from '../parse'\nimport { Context } from '../parsePublicodes'\n\nexport type PossibilityNode = {\n\texplanation: Array\n\t'choix obligatoire'?: 'oui' | 'non'\n\tcontext: string\n\tnodeKind: 'une possibilité'\n}\n// TODO : This isn't a real mecanism, cf. #963\nexport const mecanismOnePossibility = (v, context: Context) => {\n\tif (Array.isArray(v)) {\n\t\tv = {\n\t\t\tpossibilités: v,\n\t\t}\n\t}\n\treturn {\n\t\t...v,\n\t\texplanation: v.possibilités.map((p) => parse(p, context)),\n\t\tcontext: context.dottedName,\n\t\tnodeKind: 'une possibilité',\n\t} as PossibilityNode\n}\nregisterEvaluationFunction<'une possibilité'>('une possibilité', (node) => ({\n\t...node,\n\tmissingVariables: { [node.context]: 1 },\n\tnodeValue: undefined,\n}))\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode, EvaluatedNode } from '../AST/types'\nimport { convertToDate } from '../date'\nimport { warning } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeAllMissing } from '../evaluationUtils'\nimport { convertNodeToUnit } from '../nodeUnits'\nimport parse from '../parse'\nimport { inferUnit, serializeUnit } from '../units'\n\nconst knownOperations = {\n\t'*': [(a, b) => a * b, '×'],\n\t'/': [(a, b) => a / b, '∕'],\n\t'+': [(a, b) => a + b],\n\t'-': [(a, b) => a - b, '−'],\n\t'<': [(a, b) => a < b],\n\t'<=': [(a, b) => a <= b, '≤'],\n\t'>': [(a, b) => a > b],\n\t'>=': [(a, b) => a >= b, '≥'],\n\t'=': [(a, b) => (a ?? false) === (b ?? false)],\n\t'!=': [(a, b) => (a ?? false) !== (b ?? false), '≠'],\n\tet: [(a, b) => (a ?? false) && (b ?? false)],\n\tou: [(a, b) => (a ?? false) || (b ?? false)],\n} as const\n\nexport type OperationNode = {\n\tnodeKind: 'operation'\n\texplanation: [ASTNode, ASTNode]\n\toperationKind: keyof typeof knownOperations\n\toperator: string\n}\n\nconst parseOperation = (k, symbol) => (v, context) => {\n\tconst explanation = v.map((node) => parse(node, context))\n\n\treturn {\n\t\t...v,\n\t\tnodeKind: 'operation',\n\t\toperationKind: k,\n\t\toperator: symbol || k,\n\t\texplanation,\n\t} as OperationNode\n}\n\nconst evaluate: EvaluationFunction<'operation'> = function (node) {\n\tlet node1 = this.evaluateNode(node.explanation[0])\n\n\tlet evaluatedNode: EvaluatedNode & OperationNode = {\n\t\t...node,\n\t\tmissingVariables: {},\n\t} as EvaluatedNode & OperationNode\n\n\t// LAZY EVALUATION\n\tif (\n\t\t(node1.nodeValue === null &&\n\t\t\t['<', '>', '<=', '>=', '/', '*', '-', 'et'].includes(\n\t\t\t\tnode.operationKind,\n\t\t\t)) ||\n\t\t(node1.nodeValue === 0 && ['/', '*'].includes(node.operationKind)) ||\n\t\t(node1.nodeValue === false && node.operationKind === 'et') ||\n\t\t(node1.nodeValue === true && node.operationKind === 'ou')\n\t) {\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: node.operationKind === 'et' ? false : node1.nodeValue,\n\t\t\tmissingVariables: node1.missingVariables,\n\t\t}\n\t}\n\n\tlet node2 = this.evaluateNode(node.explanation[1])\n\tevaluatedNode.explanation = [node1, node2]\n\n\tif (node.operationKind === '/' && node2.nodeValue === 0) {\n\t\tthrow new PublicodesError('EvaluationError', `Division by zero`, {\n\t\t\tdottedName: this.cache._meta.evaluationRuleStack[0],\n\t\t})\n\t}\n\n\t// LAZY EVALUATION 2\n\tif (\n\t\t(node2.nodeValue === null &&\n\t\t\t['<', '>', '<=', '>=', '/', '*', 'et'].includes(node.operationKind)) ||\n\t\t(node2.nodeValue === 0 && ['*'].includes(node.operationKind)) ||\n\t\t(node2.nodeValue === false && node.operationKind === 'et') ||\n\t\t(node2.nodeValue === true && node.operationKind === 'ou')\n\t) {\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: node.operationKind === 'et' ? false : node2.nodeValue,\n\t\t\tmissingVariables: node2.missingVariables,\n\t\t}\n\t}\n\n\tevaluatedNode.missingVariables = mergeAllMissing([node1, node2])\n\n\tif (node1.nodeValue === undefined || node2.nodeValue === undefined) {\n\t\tevaluatedNode = {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: undefined,\n\t\t}\n\t}\n\n\tconst isAdditionOrSubstractionWithPercentage =\n\t\t['+', '-'].includes(node.operationKind) &&\n\t\tserializeUnit(node2.unit) === '%' &&\n\t\tserializeUnit(node1.unit) !== '%'\n\n\tif (\n\t\t!('nodeValue' in evaluatedNode) &&\n\t\t!['/', '*'].includes(node.operationKind) &&\n\t\t!isAdditionOrSubstractionWithPercentage\n\t) {\n\t\ttry {\n\t\t\tif (node1.unit && 'unit' in node2) {\n\t\t\t\tnode2 = convertNodeToUnit(node1.unit, node2)\n\t\t\t} else if (node2.unit) {\n\t\t\t\tnode1 = convertNodeToUnit(node2.unit, node1)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\twarning(\n\t\t\t\tthis.context.logger,\n\t\t\t\t`Dans l'expression '${\n\t\t\t\t\tnode.operationKind\n\t\t\t\t}', la partie gauche (unité: ${serializeUnit(\n\t\t\t\t\tnode1.unit,\n\t\t\t\t)}) n'est pas compatible avec la partie droite (unité: ${serializeUnit(\n\t\t\t\t\tnode2.unit,\n\t\t\t\t)})`,\n\t\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t\t\te,\n\t\t\t)\n\t\t}\n\t}\n\n\tconst operatorFunction = knownOperations[node.operationKind][0]\n\n\tconst a = node1.nodeValue as string | boolean | null\n\tconst b = node2.nodeValue as string | boolean | null\n\n\tevaluatedNode.nodeValue =\n\t\t'nodeValue' in evaluatedNode ? evaluatedNode.nodeValue\n\t\t: (\n\t\t\t['<', '>', '<=', '>=', '*', '/'].includes(node.operationKind) &&\n\t\t\tnode2.nodeValue === null\n\t\t) ?\n\t\t\tnull\n\t\t: (\n\t\t\t[a, b].every(\n\t\t\t\t(value) =>\n\t\t\t\t\ttypeof value === 'string' &&\n\t\t\t\t\tvalue.match?.(/^[\\d]{2}\\/[\\d]{2}\\/[\\d]{4}$/),\n\t\t\t)\n\t\t) ?\n\t\t\t// We convert the date objects to timestamps to support comparison with the \"===\" operator:\n\t\t\t// new Date('2020-01-01') !== new Date('2020-01-01')\n\t\t\toperatorFunction(\n\t\t\t\tconvertToDate(a as string).getTime(),\n\t\t\t\tconvertToDate(b as string).getTime(),\n\t\t\t)\n\t\t:\toperatorFunction(a, b)\n\n\tif (\n\t\tnode.operationKind === '*' &&\n\t\tinferUnit('*', [node1.unit, node2.unit])?.numerators.includes('%')\n\t) {\n\t\tconst unit = inferUnit('*', [node1.unit, node2.unit])\n\t\tconst nodeValue = evaluatedNode.nodeValue\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: typeof nodeValue === 'number' ? nodeValue / 100 : nodeValue,\n\t\t\tunit: inferUnit('*', [unit, { numerators: [], denominators: ['%'] }]),\n\t\t}\n\t}\n\n\t// Addition or substraction of scalar with a percentage is a multiplication\n\t// TODO : this logic should be handle statically by changing sum with percentage into product.\n\t// It can be done when we'll have a sound type/unit inference\n\tif (isAdditionOrSubstractionWithPercentage) {\n\t\tconst unit = inferUnit('*', [node1.unit, node2.unit])\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue:\n\t\t\t\t(\n\t\t\t\t\ttypeof node1.nodeValue === 'number' &&\n\t\t\t\t\ttypeof node2.nodeValue === 'number'\n\t\t\t\t) ?\n\t\t\t\t\tnode1.nodeValue *\n\t\t\t\t\t(1 + (node2.nodeValue / 100) * (node.operationKind === '-' ? -1 : 1))\n\t\t\t\t:\tevaluatedNode.nodeValue,\n\t\t\tunit: inferUnit('*', [unit, { numerators: [], denominators: ['%'] }]),\n\t\t}\n\t}\n\n\tif (\n\t\tnode.operationKind === '*' ||\n\t\tnode.operationKind === '/' ||\n\t\tnode.operationKind === '-' ||\n\t\tnode.operationKind === '+'\n\t) {\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tunit: inferUnit(node.operationKind, [node1.unit, node2.unit]),\n\t\t}\n\t}\n\n\treturn evaluatedNode\n}\n\nregisterEvaluationFunction('operation', evaluate)\n\nconst operationDispatch = Object.fromEntries(\n\tObject.entries(knownOperations).map(([k, [, symbol]]) => [\n\t\tk,\n\t\tparseOperation(k, symbol),\n\t]),\n)\n\nexport default operationDispatch\n","import { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'par défaut',\n\t{\n\t\t'par défaut': {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: { 'est non défini': 'valeur' },\n\t\t\talors: 'par défaut',\n\t\t\tsinon: 'valeur',\n\t\t},\n\t},\n)\n","import { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'plafond',\n\t{\n\t\tplafond: {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: { et: ['plafond != non', 'valeur > plafond'] },\n\t\t\talors: 'plafond',\n\t\t\tsinon: 'valeur',\n\t\t},\n\t},\n)\n","import { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'plancher',\n\t{\n\t\tplancher: {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: { et: ['plancher != non', 'valeur < plancher'] },\n\t\t\talors: 'plancher',\n\t\t\tsinon: 'valeur',\n\t\t},\n\t},\n)\n","import { PublicodesExpression } from '..'\nimport { defaultNode } from '../evaluationUtils'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\n\nexport function reduceToProduitNodes(\n\tvaleurs: Array,\n): PublicodesExpression {\n\treturn valeurs.reduce((acc, value) => ({ '*': [value, acc] }), defaultNode(1))\n}\n\nexport default createParseInlinedMecanismWithArray(\n\t'produit',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) => ({\n\t\tvaleur: reduceToProduitNodes([...(valeur as Array)]),\n\t\t\"simplifier l'unité\": 'oui',\n\t}),\n)\n","import { EvaluationFunction } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { undefinedNumberNode } from '../evaluationUtils'\nimport parse from '../parse'\nimport { Context } from '../parsePublicodes'\nimport uniroot from '../uniroot'\n\nexport type RésoudreRéférenceCirculaireNode = {\n\texplanation: {\n\t\truleToSolve: string\n\t\tvaleur: ASTNode\n\t}\n\tnodeKind: 'résoudre référence circulaire'\n}\n\nexport const evaluateRésoudreRéférenceCirculaire: EvaluationFunction<'résoudre référence circulaire'> =\n\tfunction (node) {\n\t\tif (\n\t\t\tthis.cache._meta.evaluationRuleStack\n\t\t\t\t.slice(1)\n\t\t\t\t.includes(node.explanation.ruleToSolve)\n\t\t) {\n\t\t\treturn {\n\t\t\t\t...undefinedNumberNode,\n\t\t\t\t...node,\n\t\t\t}\n\t\t}\n\n\t\tlet numberOfIterations = 0\n\t\tconst calculationEngine = this.shallowCopy()\n\t\tcalculationEngine.cache._meta.parentRuleStack = [\n\t\t\t...this.cache._meta.parentRuleStack,\n\t\t]\n\t\tcalculationEngine.cache._meta.evaluationRuleStack = [\n\t\t\t...this.cache._meta.evaluationRuleStack,\n\t\t]\n\t\tconst maxIterations = this.context.inversionMaxIterations ?? 25\n\n\t\tconst evaluateWithValue = (n: number) => {\n\t\t\tnumberOfIterations++\n\t\t\tcalculationEngine.setSituation(\n\t\t\t\t{\n\t\t\t\t\t[node.explanation.ruleToSolve]: {\n\t\t\t\t\t\t...undefinedNumberNode,\n\t\t\t\t\t\tnodeValue: n,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ keepPreviousSituation: true },\n\t\t\t)\n\n\t\t\treturn calculationEngine.evaluateNode(node.explanation.valeur)\n\t\t}\n\n\t\tconst inversionFailed = Symbol('inversion failed')\n\n\t\tlet nodeValue: number | undefined | typeof inversionFailed = inversionFailed\n\n\t\tconst x0 = 1\n\t\tlet valeur = evaluateWithValue(x0)\n\t\tconst y0 = valeur.nodeValue as number\n\t\tconst unit = valeur.unit\n\t\tif (y0 !== undefined) {\n\t\t\t// The `uniroot` function parameter. It will be called with its `min` and\n\t\t\t// `max` arguments, so we can use our cached nodes if the function is called\n\t\t\t// with the already computed x1 or x2.\n\t\t\tconst test = (x: number): number => {\n\t\t\t\tif (x === x0) {\n\t\t\t\t\treturn y0 - x0\n\t\t\t\t}\n\t\t\t\tvaleur = evaluateWithValue(x)\n\t\t\t\tconst y = valeur.nodeValue\n\t\t\t\treturn (y as number) - x\n\t\t\t}\n\n\t\t\tconst defaultMin = -1_000_000\n\t\t\tconst defaultMax = 100_000_000\n\n\t\t\tnodeValue = uniroot(test, defaultMin, defaultMax, 0.5, maxIterations, 2)\n\t\t}\n\n\t\tif (nodeValue === inversionFailed) {\n\t\t\tnodeValue = undefined\n\t\t\tthis.cache.inversionFail = true\n\t\t}\n\t\tif (nodeValue !== undefined) {\n\t\t\tvaleur = evaluateWithValue(nodeValue)\n\t\t}\n\t\treturn {\n\t\t\t...node,\n\t\t\tunit,\n\t\t\tnodeValue,\n\t\t\texplanation: {\n\t\t\t\t...node.explanation,\n\t\t\t\tvaleur,\n\t\t\t\tnumberOfIterations,\n\t\t\t},\n\t\t\tmissingVariables: valeur.missingVariables,\n\t\t}\n\t}\n\nexport default function parseRésoudreRéférenceCirculaire(v, context: Context) {\n\treturn {\n\t\texplanation: {\n\t\t\truleToSolve: context.dottedName,\n\t\t\tvaleur: parse(v.valeur, context),\n\t\t},\n\t\tnodeKind: 'résoudre référence circulaire',\n\t} as RésoudreRéférenceCirculaireNode\n}\n\nparseRésoudreRéférenceCirculaire.nom = 'résoudre la référence circulaire'\n\nregisterEvaluationFunction(\n\t'résoudre référence circulaire',\n\tevaluateRésoudreRéférenceCirculaire,\n)\n","import { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport parse from '../parse'\nimport { convertUnit, simplifyUnit } from '../units'\n\nexport type SimplifierUnitéNode = {\n\texplanation: ASTNode\n\tnodeKind: 'simplifier unité'\n}\n\nexport default function parseSimplifierUnité(v, context): SimplifierUnitéNode {\n\tconst explanation = parse(v.valeur, context)\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'simplifier unité',\n\t}\n}\n\nparseSimplifierUnité.nom = \"simplifier l'unité\" as const\n\nregisterEvaluationFunction('simplifier unité', function evaluate(node) {\n\tconst valeur = this.evaluateNode(node.explanation)\n\tconst nodeValue = valeur.nodeValue\n\tconst defaultReturn = {\n\t\t...valeur,\n\t\t...node,\n\t\texplanation: valeur,\n\t}\n\tif (nodeValue == null) {\n\t\treturn defaultReturn\n\t}\n\n\tif (!valeur.unit) {\n\t\treturn {\n\t\t\t...defaultReturn,\n\t\t\tunit: valeur.unit,\n\t\t}\n\t}\n\tconst unit = simplifyUnit(valeur.unit)\n\n\treturn {\n\t\t...defaultReturn,\n\t\tnodeValue:\n\t\t\ttypeof nodeValue === 'number' ?\n\t\t\t\tconvertUnit(valeur.unit, unit, nodeValue)\n\t\t\t:\tnodeValue,\n\t\tunit,\n\t}\n})\n","import { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'dans la situation',\n\t{\n\t\tvaleur: {},\n\t\t'dans la situation': {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: { 'est non défini': 'dans la situation' },\n\t\t\talors: 'valeur',\n\t\t\tsinon: 'dans la situation',\n\t\t},\n\t},\n)\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { defaultNode, mergeAllMissing } from '../evaluationUtils'\nimport { convertNodeToUnit } from '../nodeUnits'\nimport parse from '../parse'\nimport { parseUnit } from '../units'\nimport {\n\tevaluatePlafondUntilActiveTranche,\n\tparseTranches,\n\tTrancheNodes,\n} from './trancheUtils'\n\nexport type TauxProgressifNode = {\n\texplanation: {\n\t\ttranches: TrancheNodes\n\t\tmultiplicateur: ASTNode\n\t\tassiette: ASTNode\n\t}\n\tnodeKind: 'taux progressif'\n}\nexport default function parseTauxProgressif(v, context): TauxProgressifNode {\n\tconst explanation = {\n\t\tassiette: parse(v.assiette, context),\n\t\tmultiplicateur:\n\t\t\tv.multiplicateur ? parse(v.multiplicateur, context) : defaultNode(1),\n\t\ttranches: parseTranches(v.tranches, context),\n\t} as TauxProgressifNode['explanation']\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'taux progressif',\n\t}\n}\n\nconst evaluate: EvaluationFunction<'taux progressif'> = function (node) {\n\tconst evaluate = this.evaluateNode.bind(this)\n\tconst assiette = this.evaluateNode(node.explanation.assiette)\n\tconst multiplicateur = this.evaluateNode(node.explanation.multiplicateur)\n\tif (multiplicateur.nodeValue === 0) {\n\t\tthrow new PublicodesError('EvaluationError', `Division by zero`, {\n\t\t\tdottedName: '',\n\t\t})\n\t}\n\tconst tranches = evaluatePlafondUntilActiveTranche.call(this, {\n\t\tparsedTranches: node.explanation.tranches,\n\t\tassiette,\n\t\tmultiplicateur,\n\t})\n\n\tconst evaluatedNode = {\n\t\t...node,\n\t\texplanation: {\n\t\t\ttranches,\n\t\t\tassiette,\n\t\t\tmultiplicateur,\n\t\t},\n\t\tunit: parseUnit('%'),\n\t}\n\n\tconst lastTranche = tranches[tranches.length - 1]\n\tif (\n\t\ttranches.every(({ isActive }) => isActive === false) ||\n\t\t(lastTranche.isActive && lastTranche.plafond.nodeValue === Infinity)\n\t) {\n\t\tconst taux = convertNodeToUnit(parseUnit('%'), evaluate(lastTranche.taux))\n\t\tconst { nodeValue, missingVariables } = taux\n\t\tlastTranche.taux = taux\n\t\tlastTranche.nodeValue = nodeValue\n\t\tlastTranche.missingVariables = missingVariables\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue,\n\t\t\tmissingVariables,\n\t\t}\n\t}\n\n\tif (\n\t\ttranches.every(({ isActive }) => isActive !== true) ||\n\t\ttypeof assiette.nodeValue !== 'number'\n\t) {\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: undefined,\n\t\t\tmissingVariables: mergeAllMissing(tranches),\n\t\t}\n\t}\n\n\tconst activeTrancheIndex = tranches.findIndex(\n\t\t({ isActive }) => isActive === true,\n\t)\n\tconst activeTranche = tranches[activeTrancheIndex]\n\tactiveTranche.taux = convertNodeToUnit(\n\t\tparseUnit('%'),\n\t\tevaluate(activeTranche.taux),\n\t)\n\n\tconst previousTranche = tranches[activeTrancheIndex - 1]\n\tif (previousTranche) {\n\t\tpreviousTranche.taux = convertNodeToUnit(\n\t\t\tparseUnit('%'),\n\t\t\tevaluate(previousTranche.taux),\n\t\t)\n\t\tpreviousTranche.isActive = true\n\t}\n\tconst previousTaux =\n\t\tpreviousTranche ? previousTranche.taux : activeTranche.taux\n\tconst calculationValues = [previousTaux, activeTranche.taux]\n\tif (calculationValues.some((n) => n.nodeValue === undefined)) {\n\t\tactiveTranche.nodeValue = undefined\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: undefined,\n\t\t\tmissingVariables: mergeAllMissing(calculationValues),\n\t\t}\n\t}\n\n\tconst lowerTaux = previousTaux.nodeValue\n\tconst upperTaux = activeTranche.taux.nodeValue\n\tconst plancher = activeTranche.plancherValue\n\tconst plafond = activeTranche.plafondValue\n\tconst coeff = (upperTaux - lowerTaux) / (plafond - plancher)\n\tconst nodeValue = lowerTaux + (assiette.nodeValue - plancher) * coeff\n\tactiveTranche.nodeValue = nodeValue\n\treturn {\n\t\t...evaluatedNode,\n\t\tnodeValue,\n\t\tmissingVariables: {},\n\t}\n}\n\nregisterEvaluationFunction('taux progressif', evaluate)\n","import { ASTNode, formatValue } from '..'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\n\nconst NAME = 'texte' as const\n\nexport type TexteNode = {\n\texplanation: Array\n\tnodeKind: typeof NAME\n}\n\nexport default function parseTexte(texte: string, context): TexteNode {\n\tconst explanation = [] as TexteNode['explanation']\n\tlet lastIndex = 0\n\tfor (const { 0: expression, index } of texte.matchAll(/{{(.|\\n)*?}}/g)) {\n\t\tconst publicodeExpression = expression.slice(2, -2).trim()\n\t\tconst parsedNode = parse(publicodeExpression, context)\n\t\texplanation.push(texte.substring(lastIndex, index), parsedNode)\n\t\tlastIndex = (index ?? 0) + expression.length\n\t}\n\texplanation.push(texte.slice(lastIndex))\n\treturn {\n\t\tnodeKind: NAME,\n\t\texplanation,\n\t}\n}\nparseTexte.nom = NAME\n\nregisterEvaluationFunction(NAME, function evaluate(node) {\n\tconst explanation = node.explanation.map((element) =>\n\t\ttypeof element === 'string' ? element : this.evaluateNode(element),\n\t)\n\n\treturn {\n\t\t...node,\n\t\texplanation,\n\t\tmissingVariables: mergeAllMissing(\n\t\t\tnode.explanation.filter(\n\t\t\t\t(element) => typeof element !== 'string',\n\t\t\t) as Array,\n\t\t),\n\t\tnodeValue: explanation\n\t\t\t.map((element) =>\n\t\t\t\ttypeof element === 'string' ? element : formatValue(element),\n\t\t\t)\n\t\t\t.join(''),\n\t}\n})\n","import { PublicodesExpression } from '..'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\n\nexport default createParseInlinedMecanismWithArray(\n\t'toutes ces conditions',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) =>\n\t\t(valeur as Array).reduce(\n\t\t\t(acc, value) => ({ et: [acc, value] }),\n\t\t\t'oui',\n\t\t),\n)\n","import { PublicodesExpression } from '..'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\n\nexport default createParseInlinedMecanismWithArray(\n\t'une de ces conditions',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) =>\n\t\t(valeur as Array).reduce(\n\t\t\t(acc, value) => ({ ou: [acc, value] }),\n\t\t\t'non',\n\t\t),\n)\n","import { ASTNode, Unit } from '../AST/types'\nimport { warning } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport parse from '../parse'\nimport { convertUnit, parseUnit } from '../units'\n\nexport type UnitéNode = {\n\tunit: Unit\n\texplanation: ASTNode\n\tnodeKind: 'unité'\n}\n\nexport default function parseUnité(v, context): UnitéNode {\n\tconst explanation = parse(v.valeur, context)\n\tconst unit = parseUnit(v.unité, context.getUnitKey)\n\n\treturn {\n\t\texplanation,\n\t\tunit,\n\t\tnodeKind: parseUnité.nom,\n\t}\n}\n\nparseUnité.nom = 'unité' as const\n\nregisterEvaluationFunction(parseUnité.nom, function evaluate(node) {\n\tconst valeur = this.evaluateNode(node.explanation)\n\n\tlet nodeValue = valeur.nodeValue\n\tif (nodeValue !== null && 'unit' in node) {\n\t\ttry {\n\t\t\tnodeValue = convertUnit(\n\t\t\t\tvaleur.unit,\n\t\t\t\tnode.unit,\n\t\t\t\tvaleur.nodeValue as number,\n\t\t\t)\n\t\t} catch (e) {\n\t\t\twarning(\n\t\t\t\tthis.context.logger,\n\t\t\t\t\"Erreur lors de la conversion d'unité explicite\",\n\t\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t\t\te,\n\t\t\t)\n\t\t}\n\t}\n\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\texplanation: valeur,\n\t\tmissingVariables: valeur.missingVariables,\n\t}\n})\n","import { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeMissing } from '../evaluationUtils'\nimport parse from '../parse'\n\nexport type VariableManquanteNode = {\n\tmissingVariable: string\n\texplanation: ASTNode\n\tnodeKind: 'variable manquante'\n}\n\nexport default function parseVariableManquante(\n\tv,\n\tcontext,\n): VariableManquanteNode {\n\treturn {\n\t\tmissingVariable: v['variable manquante'],\n\t\tnodeKind: parseVariableManquante.nom,\n\t\texplanation: parse(v.valeur, context),\n\t}\n}\n\nparseVariableManquante.nom = 'variable manquante' as const\n\nregisterEvaluationFunction(parseVariableManquante.nom, function evaluate(node) {\n\tconst valeur = this.evaluateNode(node.explanation)\n\n\tconst maxMissingScore = Object.values(valeur.missingVariables).reduce(\n\t\t(a, b) => (a > b ? a : b),\n\t\t0,\n\t)\n\n\treturn {\n\t\t...node,\n\t\tnodeValue: valeur.nodeValue,\n\t\tunit: valeur.unit,\n\t\texplanation: valeur,\n\t\tmissingVariables: mergeMissing(valeur.missingVariables, {\n\t\t\t[node.missingVariable]: maxMissingScore + 1,\n\t\t}),\n\t}\n})\n","import { EvaluationFunction } from '..'\nimport { ASTNode, EvaluatedNode, Unit } from '../AST/types'\nimport { warning } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { bonus, defaultNode, mergeMissing } from '../evaluationUtils'\nimport { convertNodeToUnit } from '../nodeUnits'\nimport parse from '../parse'\n\nexport type VariationNode = {\n\texplanation: Array<{\n\t\tcondition: ASTNode\n\t\tconsequence: ASTNode\n\t\tsatisfied?: boolean\n\t}>\n\tnodeKind: 'variations'\n}\n\nexport default function parseVariations(v, context): VariationNode {\n\tconst explanation = v.map(({ si, alors, sinon }) =>\n\t\tsinon !== undefined ?\n\t\t\t{ consequence: parse(sinon, context), condition: defaultNode(true) }\n\t\t:\t{ consequence: parse(alors, context), condition: parse(si, context) },\n\t)\n\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'variations',\n\t}\n}\n\nconst evaluate: EvaluationFunction<'variations'> = function (node) {\n\tconst [nodeValue, explanation, unit] = node.explanation.reduce<\n\t\t[\n\t\t\tEvaluatedNode['nodeValue'],\n\t\t\tVariationNode['explanation'],\n\t\t\tUnit | undefined,\n\t\t\tboolean | undefined,\n\t\t]\n\t>(\n\t\t(\n\t\t\t[evaluation, explanations, unit, previousConditions],\n\t\t\t{ condition, consequence },\n\t\t\ti: number,\n\t\t) => {\n\t\t\tif (previousConditions === true) {\n\t\t\t\treturn [\n\t\t\t\t\tevaluation,\n\t\t\t\t\t[...explanations, { condition, consequence }],\n\t\t\t\t\tunit,\n\t\t\t\t\tpreviousConditions,\n\t\t\t\t]\n\t\t\t}\n\t\t\tconst evaluatedCondition = this.evaluateNode(condition)\n\t\t\tconst currentCondition =\n\t\t\t\tpreviousConditions === undefined ? previousConditions : (\n\t\t\t\t\t!previousConditions &&\n\t\t\t\t\t(evaluatedCondition.nodeValue === undefined ?\n\t\t\t\t\t\tundefined\n\t\t\t\t\t:\tevaluatedCondition.nodeValue !== false &&\n\t\t\t\t\t\tevaluatedCondition.nodeValue !== null)\n\t\t\t\t)\n\n\t\t\tif (currentCondition === false || currentCondition === null) {\n\t\t\t\treturn [\n\t\t\t\t\tevaluation,\n\t\t\t\t\t[...explanations, { condition: evaluatedCondition, consequence }],\n\t\t\t\t\tunit,\n\t\t\t\t\tpreviousConditions,\n\t\t\t\t]\n\t\t\t}\n\t\t\tlet evaluatedConsequence: EvaluatedNode | undefined = undefined\n\t\t\tif (\n\t\t\t\tevaluatedCondition.nodeValue !== false &&\n\t\t\t\tevaluatedCondition.nodeValue !== null\n\t\t\t) {\n\t\t\t\tevaluatedConsequence = this.evaluateNode(consequence!)\n\t\t\t\tif (unit) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tevaluatedConsequence = convertNodeToUnit(\n\t\t\t\t\t\t\tunit,\n\t\t\t\t\t\t\tevaluatedConsequence!,\n\t\t\t\t\t\t)\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\twarning(\n\t\t\t\t\t\t\tthis.context.logger,\n\t\t\t\t\t\t\t`L'unité de la branche n° ${\n\t\t\t\t\t\t\t\ti + 1\n\t\t\t\t\t\t\t} du mécanisme 'variations' n'est pas compatible avec celle d'une branche précédente`,\n\t\t\t\t\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t\t\t\t\t\te,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn [\n\t\t\t\tcurrentCondition && evaluatedConsequence?.nodeValue,\n\t\t\t\t[\n\t\t\t\t\t...explanations,\n\t\t\t\t\t{\n\t\t\t\t\t\tcondition: evaluatedCondition,\n\t\t\t\t\t\tconsequence: evaluatedConsequence ?? consequence,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tunit || evaluatedConsequence?.unit,\n\t\t\t\tpreviousConditions || currentCondition,\n\t\t\t]\n\t\t},\n\t\t[null, [], undefined, false],\n\t)\n\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\t...(unit !== undefined && { unit }),\n\t\texplanation,\n\t\tmissingVariables: explanation.reduce(\n\t\t\t(values, { condition, consequence }) =>\n\t\t\t\tmergeMissing(\n\t\t\t\t\tvalues,\n\t\t\t\t\tmergeMissing(\n\t\t\t\t\t\tbonus((condition as EvaluatedNode).missingVariables),\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\t'nodeValue' in condition &&\n\t\t\t\t\t\t\t\tcondition.nodeValue !== false &&\n\t\t\t\t\t\t\t\tcondition.nodeValue !== null\n\t\t\t\t\t\t) ?\n\t\t\t\t\t\t\t(consequence as EvaluatedNode).missingVariables\n\t\t\t\t\t\t:\t{},\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t{},\n\t\t),\n\t}\n}\n\nregisterEvaluationFunction('variations', evaluate)\n","import nearley from 'nearley'\nimport { PublicodesError } from './error'\nimport grammar from './grammar.codegen'\n\n// TODO: nearley is currently exported as a CommonJS module which is why we need\n// to destructure the default import instead of directly importing the symbols\n// we need. This is sub-optimal because we our bundler will not tree-shake\n// unused nearley symbols.\n// https://github.com/kach/nearley/issues/535\nconst { Grammar, Parser } = nearley\n\nconst compiledGrammar = Grammar.fromCompiled(grammar)\n\nconst parser = new Parser(compiledGrammar)\nconst initialState = parser.save()\n\ntype BinaryOp =\n\t| { '+': [ExprAST, ExprAST] }\n\t| { '-': [ExprAST, ExprAST] }\n\t| { '*': [ExprAST, ExprAST] }\n\t| { '/': [ExprAST, ExprAST] }\n\t| { '>': [ExprAST, ExprAST] }\n\t| { '<': [ExprAST, ExprAST] }\n\t| { '>=': [ExprAST, ExprAST] }\n\t| { '<=': [ExprAST, ExprAST] }\n\t| { '=': [ExprAST, ExprAST] }\n\t| { '!=': [ExprAST, ExprAST] }\n\ntype UnaryOp = { '-': [{ value: 0 }, ExprAST] }\n\n/** AST of a publicodes expression. */\nexport type ExprAST =\n\t| BinaryOp\n\t| UnaryOp\n\t| { variable: string }\n\t| { constant: { type: 'number'; nodeValue: number }; unité?: string }\n\t| { constant: { type: 'boolean'; nodeValue: boolean } }\n\t| { constant: { type: 'string' | 'date'; nodeValue: string } }\n\n/**\n * Parse a publicodes expression into an JSON object representing the AST.\n *\n * The parsing is done with the [nearley](https://nearley.js.org/) parser\n *\n * @param rawNode The expression to parse\n * @param dottedName The dottedName of the rule being parsed\n *\n * @returns The parsing result as a JSON object\n *\n * @throws A `SyntaxError` if the expression is invalid\n * @throws A `PublicodesInternalError` if the parser is unable to parse the expression\n *\n * @example\n * ```ts\n * parseExpression('20.3 * nombre', 'foo . bar')\n * // returns { \"*\": [ { constant: { type: \"number\", nodeValue: 20.3 } }, { variable:\"nombre\" } ] }\n * ```\n */\nexport function parseExpression(rawNode: string, dottedName: string): ExprAST {\n\t/* Strings correspond to infix expressions.\n\t * Indeed, a subset of expressions like simple arithmetic operations `3 + (quantity * 2)` or like `salary [month]` are more explicit that their prefixed counterparts.\n\t * This function makes them prefixed operations. */\n\tconst singleLineExpression = (rawNode + '').replace(/\\s*\\n\\s*/g, ' ').trim()\n\n\ttry {\n\t\tparser.restore(initialState)\n\t\tconst [parseResult] = parser.feed(singleLineExpression).results\n\n\t\tif (parseResult == null) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'InternalError',\n\t\t\t\t`\nUn problème est survenu lors du parsing de l'expression \\`${singleLineExpression}\\` :\n\n\tle parseur Nearley n'a pas réussi à parser l'expression.\n`,\n\t\t\t\t{ dottedName },\n\t\t\t)\n\t\t}\n\t\treturn parseResult\n\t} catch (e) {\n\t\tif (e instanceof PublicodesError) {\n\t\t\tthrow e\n\t\t}\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`\\`${singleLineExpression}\\` n'est pas une expression valide`,\n\t\t\t{ dottedName },\n\t\t\te,\n\t\t)\n\t}\n}\n","/* Those are postprocessor functions for the Nearley grammar.ne.\nThe advantage of putting them here is to get prettier's JS formatting, since Nealrey doesn't support it https://github.com/kach/nearley/issues/310 */\nimport { normalizeDateString } from './date.ts'\n\nexport const binaryOperation = ([A, , operator, , B]) => ({\n\t[operator.value.toLowerCase()]: [A, B],\n})\n\nexport const unaryOperation = ([operator, , A]) => ({\n\t[operator]: [number([{ value: '0' }]), A],\n})\n\nexport const variable = (arg) => {\n\treturn {\n\t\tvariable: arg.value,\n\t}\n}\n\nexport const JSONObject = ([{ value }]) => {\n\tvalue\n\t// TODO\n}\nexport const number = ([{ value }]) => ({\n\tconstant: {\n\t\ttype: 'number',\n\t\tnodeValue: parseFloat(value),\n\t},\n})\n\nexport const numberWithUnit = (value) => ({\n\t...number(value),\n\tunité: value[2].value,\n})\n\nexport const date = ([{ value }]) => {\n\treturn {\n\t\tconstant: {\n\t\t\ttype: 'date',\n\t\t\tnodeValue: normalizeDateString(value),\n\t\t},\n\t}\n}\n\nexport const boolean = ([{ value }]) => ({\n\tconstant: {\n\t\ttype: 'boolean',\n\t\tnodeValue: value === 'oui',\n\t},\n})\n\nexport const string = ([{ value }]) => ({\n\tconstant: {\n\t\ttype: 'string',\n\t\tnodeValue: value.slice(1, -1),\n\t},\n})\n","// Generated automatically by nearley, version 2.20.1\n// http://github.com/Hardmath123/nearley\nfunction id(x) { return x[0]; }\n\nimport {\n string, date, variable, binaryOperation, unaryOperation, boolean, number, numberWithUnit, JSONObject\n} from './grammarFunctions.js';\nimport moo from \"moo\";\n\n\nconst dateRegexp = `(?:(?:0?[1-9]|[12][0-9]|3[01])\\\\/)?(?:0?[1-9]|1[012])\\\\/\\\\d{4}`\nconst letter = '[a-zA-Z\\u00C0-\\u017F€$%°]';\nconst letterOrNumber = '[a-zA-Z\\u00C0-\\u017F0-9\\',]';\nconst word = `${letter}(?:[-']?${letterOrNumber}+)*`;\n\nconst numberRegExp = '-?(?:[1-9][0-9]+|[0-9])(?:\\\\.[0-9]+)?';\nconst lexer = moo.compile({\n '(': '(',\n ')': ')',\n '[': '[',\n ']': ']',\n comparison: ['>','<','>=','<=','=','!='],\n date: new RegExp(dateRegexp),\n\tboolean: ['oui','non'],\n number: new RegExp(numberRegExp),\n word: new RegExp(word),\n string: [/'.*'/, /\".*\"/],\n parentSelector: \"^\",\n JSONObject: /{.*}/,\n additionSubstraction: /[\\+-]/,\n multiplicationDivision: ['*','/'],\n dot: ' . ',\n \".\": '.',\n space: { match: /[\\s]+/, lineBreaks: true },\n});\n\nconst join = (args) => ({value: (args.map(x => x && x.value).join(\"\"))})\nconst flattenJoin = (args) => join(args.flat())\nlet Lexer = lexer;\nlet ParserRules = [\n {\"name\": \"main\", \"symbols\": [\"Comparison\"], \"postprocess\": id},\n {\"name\": \"main\", \"symbols\": [\"NumericValue\"], \"postprocess\": id},\n {\"name\": \"main\", \"symbols\": [\"Date\"], \"postprocess\": id},\n {\"name\": \"main\", \"symbols\": [\"NonNumericTerminal\"], \"postprocess\": id},\n {\"name\": \"main\", \"symbols\": [\"JSONObject\"], \"postprocess\": id},\n {\"name\": \"NumericValue\", \"symbols\": [\"AdditionSubstraction\"], \"postprocess\": id},\n {\"name\": \"NumericValue\", \"symbols\": [\"Negation\"], \"postprocess\": id},\n {\"name\": \"NumericTerminal\", \"symbols\": [\"Variable\"], \"postprocess\": id},\n {\"name\": \"NumericTerminal\", \"symbols\": [\"number\"], \"postprocess\": id},\n {\"name\": \"Negation\", \"symbols\": [{\"literal\":\"-\"}, (lexer.has(\"space\") ? {type: \"space\"} : space), \"Parentheses\"], \"postprocess\": unaryOperation},\n {\"name\": \"Parentheses\", \"symbols\": [{\"literal\":\"(\"}, (lexer.has(\"space\") ? {type: \"space\"} : space), \"NumericValue\", (lexer.has(\"space\") ? {type: \"space\"} : space), {\"literal\":\")\"}], \"postprocess\": ([,,e]) => e},\n {\"name\": \"Parentheses\", \"symbols\": [{\"literal\":\"(\"}, \"NumericValue\", {\"literal\":\")\"}], \"postprocess\": ([,e]) => e},\n {\"name\": \"Parentheses\", \"symbols\": [\"NumericTerminal\"], \"postprocess\": id},\n {\"name\": \"Date\", \"symbols\": [\"Variable\"], \"postprocess\": id},\n {\"name\": \"Date\", \"symbols\": [(lexer.has(\"date\") ? {type: \"date\"} : date)], \"postprocess\": date},\n {\"name\": \"Comparison\", \"symbols\": [\"Comparable\", (lexer.has(\"space\") ? {type: \"space\"} : space), (lexer.has(\"comparison\") ? {type: \"comparison\"} : comparison), (lexer.has(\"space\") ? {type: \"space\"} : space), \"Comparable\"], \"postprocess\": binaryOperation},\n {\"name\": \"Comparison\", \"symbols\": [\"Date\", (lexer.has(\"space\") ? {type: \"space\"} : space), (lexer.has(\"comparison\") ? {type: \"comparison\"} : comparison), (lexer.has(\"space\") ? {type: \"space\"} : space), \"Date\"], \"postprocess\": binaryOperation},\n {\"name\": \"Comparable$subexpression$1\", \"symbols\": [\"AdditionSubstraction\"]},\n {\"name\": \"Comparable$subexpression$1\", \"symbols\": [\"NonNumericTerminal\"]},\n {\"name\": \"Comparable\", \"symbols\": [\"Comparable$subexpression$1\"], \"postprocess\": ([[e]]) => e},\n {\"name\": \"NonNumericTerminal\", \"symbols\": [(lexer.has(\"boolean\") ? {type: \"boolean\"} : boolean)], \"postprocess\": boolean},\n {\"name\": \"NonNumericTerminal\", \"symbols\": [(lexer.has(\"string\") ? {type: \"string\"} : string)], \"postprocess\": string},\n {\"name\": \"Variable\", \"symbols\": [\"VariableWithoutParentSelector\"], \"postprocess\": ([x]) => variable(x)},\n {\"name\": \"Variable$ebnf$1\", \"symbols\": []},\n {\"name\": \"Variable$ebnf$1$subexpression$1\", \"symbols\": [(lexer.has(\"parentSelector\") ? {type: \"parentSelector\"} : parentSelector), (lexer.has(\"dot\") ? {type: \"dot\"} : dot)], \"postprocess\": join},\n {\"name\": \"Variable$ebnf$1\", \"symbols\": [\"Variable$ebnf$1\", \"Variable$ebnf$1$subexpression$1\"], \"postprocess\": function arrpush(d) {return d[0].concat([d[1]]);}},\n {\"name\": \"Variable\", \"symbols\": [\"Variable$ebnf$1\", \"VariableWithoutParentSelector\"], \"postprocess\": x => variable(flattenJoin(x))},\n {\"name\": \"VariableWithoutParentSelector$ebnf$1\", \"symbols\": []},\n {\"name\": \"VariableWithoutParentSelector$ebnf$1$subexpression$1\", \"symbols\": [(lexer.has(\"dot\") ? {type: \"dot\"} : dot), \"Words\"], \"postprocess\": join},\n {\"name\": \"VariableWithoutParentSelector$ebnf$1\", \"symbols\": [\"VariableWithoutParentSelector$ebnf$1\", \"VariableWithoutParentSelector$ebnf$1$subexpression$1\"], \"postprocess\": function arrpush(d) {return d[0].concat([d[1]]);}},\n {\"name\": \"VariableWithoutParentSelector\", \"symbols\": [\"Words\", \"VariableWithoutParentSelector$ebnf$1\"], \"postprocess\": x => flattenJoin(x)},\n {\"name\": \"Words$ebnf$1$subexpression$1$ebnf$1\", \"symbols\": [(lexer.has(\"space\") ? {type: \"space\"} : space)], \"postprocess\": id},\n {\"name\": \"Words$ebnf$1$subexpression$1$ebnf$1\", \"symbols\": [], \"postprocess\": function(d) {return null;}},\n {\"name\": \"Words$ebnf$1$subexpression$1\", \"symbols\": [\"Words$ebnf$1$subexpression$1$ebnf$1\", \"WordOrNumber\"], \"postprocess\": join},\n {\"name\": \"Words$ebnf$1\", \"symbols\": [\"Words$ebnf$1$subexpression$1\"]},\n {\"name\": \"Words$ebnf$1$subexpression$2$ebnf$1\", \"symbols\": [(lexer.has(\"space\") ? {type: \"space\"} : space)], \"postprocess\": id},\n {\"name\": \"Words$ebnf$1$subexpression$2$ebnf$1\", \"symbols\": [], \"postprocess\": function(d) {return null;}},\n {\"name\": \"Words$ebnf$1$subexpression$2\", \"symbols\": [\"Words$ebnf$1$subexpression$2$ebnf$1\", \"WordOrNumber\"], \"postprocess\": join},\n {\"name\": \"Words$ebnf$1\", \"symbols\": [\"Words$ebnf$1\", \"Words$ebnf$1$subexpression$2\"], \"postprocess\": function arrpush(d) {return d[0].concat([d[1]]);}},\n {\"name\": \"Words\", \"symbols\": [\"WordOrKeyword\", \"Words$ebnf$1\"], \"postprocess\": flattenJoin},\n {\"name\": \"Words\", \"symbols\": [(lexer.has(\"word\") ? {type: \"word\"} : word)], \"postprocess\": id},\n {\"name\": \"WordOrKeyword\", \"symbols\": [(lexer.has(\"word\") ? {type: \"word\"} : word)], \"postprocess\": id},\n {\"name\": \"WordOrKeyword\", \"symbols\": [(lexer.has(\"boolean\") ? {type: \"boolean\"} : boolean)], \"postprocess\": id},\n {\"name\": \"WordOrNumber\", \"symbols\": [\"WordOrKeyword\"], \"postprocess\": id},\n {\"name\": \"WordOrNumber\", \"symbols\": [(lexer.has(\"number\") ? {type: \"number\"} : number)], \"postprocess\": id},\n {\"name\": \"Unit$ebnf$1\", \"symbols\": []},\n {\"name\": \"Unit$ebnf$1\", \"symbols\": [\"Unit$ebnf$1\", \"UnitNumerator\"], \"postprocess\": function arrpush(d) {return d[0].concat([d[1]]);}},\n {\"name\": \"Unit$ebnf$2\", \"symbols\": []},\n {\"name\": \"Unit$ebnf$2\", \"symbols\": [\"Unit$ebnf$2\", \"UnitDenominator\"], \"postprocess\": function arrpush(d) {return d[0].concat([d[1]]);}},\n {\"name\": \"Unit\", \"symbols\": [\"Unit$ebnf$1\", \"Unit$ebnf$2\"], \"postprocess\": flattenJoin},\n {\"name\": \"UnitNumerator\", \"symbols\": [\"Words\"], \"postprocess\": id},\n {\"name\": \"UnitNumerator\", \"symbols\": [{\"literal\":\".\"}, \"UnitNumerator\"], \"postprocess\": join},\n {\"name\": \"UnitDenominator$ebnf$1\", \"symbols\": []},\n {\"name\": \"UnitDenominator$ebnf$1$subexpression$1\", \"symbols\": [(lexer.has(\"space\") ? {type: \"space\"} : space)]},\n {\"name\": \"UnitDenominator$ebnf$1\", \"symbols\": [\"UnitDenominator$ebnf$1\", \"UnitDenominator$ebnf$1$subexpression$1\"], \"postprocess\": function arrpush(d) {return d[0].concat([d[1]]);}},\n {\"name\": \"UnitDenominator$ebnf$2\", \"symbols\": [\"UnitNumerator\"]},\n {\"name\": \"UnitDenominator$ebnf$2\", \"symbols\": [\"UnitDenominator$ebnf$2\", \"UnitNumerator\"], \"postprocess\": function arrpush(d) {return d[0].concat([d[1]]);}},\n {\"name\": \"UnitDenominator\", \"symbols\": [\"UnitDenominator$ebnf$1\", {\"literal\":\"/\"}, \"UnitDenominator$ebnf$2\"], \"postprocess\": flattenJoin},\n {\"name\": \"AdditionSubstraction\", \"symbols\": [\"AdditionSubstraction\", (lexer.has(\"space\") ? {type: \"space\"} : space), (lexer.has(\"additionSubstraction\") ? {type: \"additionSubstraction\"} : additionSubstraction), (lexer.has(\"space\") ? {type: \"space\"} : space), \"MultiplicationDivision\"], \"postprocess\": binaryOperation},\n {\"name\": \"AdditionSubstraction\", \"symbols\": [\"MultiplicationDivision\"], \"postprocess\": id},\n {\"name\": \"MultiplicationDivision\", \"symbols\": [\"MultiplicationDivision\", (lexer.has(\"space\") ? {type: \"space\"} : space), (lexer.has(\"multiplicationDivision\") ? {type: \"multiplicationDivision\"} : multiplicationDivision), (lexer.has(\"space\") ? {type: \"space\"} : space), \"Parentheses\"], \"postprocess\": binaryOperation},\n {\"name\": \"MultiplicationDivision\", \"symbols\": [\"Parentheses\"], \"postprocess\": id},\n {\"name\": \"number\", \"symbols\": [(lexer.has(\"number\") ? {type: \"number\"} : number)], \"postprocess\": number},\n {\"name\": \"number$ebnf$1$subexpression$1\", \"symbols\": [(lexer.has(\"space\") ? {type: \"space\"} : space)]},\n {\"name\": \"number$ebnf$1\", \"symbols\": [\"number$ebnf$1$subexpression$1\"], \"postprocess\": id},\n {\"name\": \"number$ebnf$1\", \"symbols\": [], \"postprocess\": function(d) {return null;}},\n {\"name\": \"number\", \"symbols\": [(lexer.has(\"number\") ? {type: \"number\"} : number), \"number$ebnf$1\", \"Unit\"], \"postprocess\": numberWithUnit},\n {\"name\": \"JSONObject\", \"symbols\": [(lexer.has(\"JSONObject\") ? {type: \"JSONObject\"} : JSONObject)], \"postprocess\": JSONObject}\n];\nlet ParserStart = \"main\";\nexport default { Lexer, ParserRules, ParserStart };\n","import { PublicodesError, PublicodesInternalError } from './error'\nimport { registerEvaluationFunction } from './evaluationFunctions'\nimport { Context } from './parsePublicodes'\n\nexport type ReferenceNode = {\n\tnodeKind: 'reference'\n\tname: string\n\tcontextDottedName: string\n\tdottedName?: string\n\ttitle?: string\n\tacronym?: string\n}\n\nexport default function parseReference(\n\tv: string,\n\tcontext: Context,\n): ReferenceNode {\n\tif (!context.dottedName) {\n\t\tthrow new PublicodesError(\n\t\t\t'InternalError',\n\t\t\t\"Une référence ne peut pas exister en dehors d'une règle (`context.dottedName` est vide)\",\n\t\t\t{\n\t\t\t\tdottedName: v,\n\t\t\t},\n\t\t)\n\t}\n\tif (!v) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t'Une référence ne peut pas être vide',\n\t\t\t{\n\t\t\t\tdottedName: context.dottedName,\n\t\t\t},\n\t\t)\n\t}\n\n\treturn {\n\t\tnodeKind: 'reference',\n\t\tname: v,\n\t\tcontextDottedName: context.dottedName,\n\t}\n}\n\nregisterEvaluationFunction('reference', function evaluateReference(node) {\n\tif (!node.dottedName) {\n\t\tthrow new PublicodesInternalError(node)\n\t}\n\tconst explanation = this.evaluateNode(\n\t\tthis.context.parsedRules[node.dottedName],\n\t)\n\tdelete explanation.sourceMap\n\treturn {\n\t\t...explanation,\n\t\t...node,\n\t}\n})\n","import { ASTNode } from './AST/types'\nimport { PublicodesError } from './error'\nimport abattement from './mecanisms/abattement'\nimport applicable from './mecanisms/applicable'\nimport arrondi from './mecanisms/arrondi'\nimport avec from './mecanisms/avec'\nimport barème from './mecanisms/barème'\nimport condition from './mecanisms/condition'\nimport contexte from './mecanisms/contexte'\nimport durée from './mecanisms/durée'\nimport {\n\tparseEstApplicable,\n\tparseEstDéfini,\n\tparseEstNonDéfini,\n} from './mecanisms/est'\nimport { parseEstNonApplicable } from './mecanisms/est-non-applicable'\nimport grille from './mecanisms/grille'\nimport { mecanismInversion } from './mecanisms/inversion'\nimport { parseMaximumDe, parseMinimumDe } from './mecanisms/max-min'\nimport moyenne from './mecanisms/moyenne'\nimport nonApplicable from './mecanisms/non-applicable'\nimport { mecanismOnePossibility } from './mecanisms/one-possibility'\nimport operations from './mecanisms/operation'\nimport parDéfaut from './mecanisms/parDéfaut'\nimport plafond from './mecanisms/plafond'\nimport plancher from './mecanisms/plancher'\nimport produit from './mecanisms/product'\nimport résoudreRéférenceCirculaire from './mecanisms/résoudre-référence-circulaire'\nimport simplifierUnité from './mecanisms/simplifier-unité'\nimport situation from './mecanisms/situation'\nimport somme from './mecanisms/somme'\nimport tauxProgressif from './mecanisms/tauxProgressif'\nimport texte from './mecanisms/texte'\nimport toutesCesConditions from './mecanisms/toutes-ces-conditions'\nimport uneDeCesConditions from './mecanisms/une-de-ces-conditions'\nimport unité from './mecanisms/unité'\nimport variableManquante from './mecanisms/variablesManquantes'\nimport variations from './mecanisms/variations'\nimport { parseExpression } from './parseExpression'\nimport { Context } from './parsePublicodes'\nimport parseReference from './reference'\n\nexport default function parse(rawNode, context: Context): ASTNode {\n\tif (rawNode == undefined) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`\n\tUne des valeurs de la formule est vide.\n\tVérifiez que tous les champs à droite des deux points sont remplis`,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\tif (typeof rawNode === 'boolean') {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`\nLes valeurs booléennes true / false ne sont acceptées.\nUtilisez leur contrepartie française : 'oui' / 'non'`,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\tconst node =\n\t\ttypeof rawNode === 'object' ? rawNode : (\n\t\t\tparseExpression(rawNode, context.dottedName)\n\t\t)\n\tif ('nodeKind' in node) {\n\t\treturn node\n\t}\n\n\treturn {\n\t\t...parseChainedMecanisms(node, context),\n\t\trawNode,\n\t}\n}\n\nfunction parseMecanism(rawNode, context: Context) {\n\tif (Array.isArray(rawNode)) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`\nIl manque le nom du mécanisme pour le tableau : [${rawNode\n\t\t\t\t.map((x) => `'${x}'`)\n\t\t\t\t.join(', ')}]\nLes mécanisme possibles sont : 'somme', 'le maximum de', 'le minimum de', 'toutes ces conditions', 'une de ces conditions'.\n\t\t`,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\n\tconst keys = Object.keys(rawNode)\n\tif (keys.length > 1) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`\nLes mécanismes suivants se situent au même niveau : ${keys\n\t\t\t\t.map((x) => `'${x}'`)\n\t\t\t\t.join(', ')}\nCela vient probablement d'une erreur dans l'indentation\n\t`,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\tif (keys.length === 0) {\n\t\treturn { nodeKind: 'constant', nodeValue: undefined }\n\t}\n\n\tconst mecanismName = keys[0]\n\tconst values = rawNode[mecanismName]\n\tconst parseFn = parseFunctions[mecanismName]\n\n\tif (!parseFn) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`Le mécanisme \"${mecanismName}\" est inconnu.\n\nVérifiez qu'il n'y ait pas d'erreur dans l'orthographe du nom.`,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\ttry {\n\t\treturn parseFn(values, context)\n\t} catch (e) {\n\t\tif (e instanceof PublicodesError) {\n\t\t\tthrow e\n\t\t}\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\tmecanismName ?\n\t\t\t\t`➡️ Dans le mécanisme ${mecanismName}\n${e.message}`\n\t\t\t:\te.message,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n}\n\n// Chainable mecanisme in their composition order (first one is applyied first)\nconst chainableMecanisms = [\n\tcontexte,\n\tvariableManquante,\n\tavec,\n\tapplicable,\n\tnonApplicable,\n\tarrondi,\n\tunité,\n\tsimplifierUnité,\n\tplancher,\n\tplafond,\n\tparDéfaut,\n\tsituation,\n\trésoudreRéférenceCirculaire,\n\tabattement,\n]\n\nfunction parseChainedMecanisms(rawNode, context: Context): ASTNode {\n\tconst parseFn = chainableMecanisms.find((fn) => fn.nom in rawNode)\n\tif (!parseFn) {\n\t\treturn parseMecanism(rawNode, context)\n\t}\n\tconst { [parseFn.nom]: param, ...valeur } = rawNode\n\n\treturn parseMecanism(\n\t\t{\n\t\t\t[parseFn.nom]: {\n\t\t\t\tvaleur,\n\t\t\t\t[parseFn.nom]: param,\n\t\t\t},\n\t\t},\n\t\tcontext,\n\t)\n}\n\nconst parseFunctions = {\n\t...operations,\n\t...chainableMecanisms.reduce((acc, fn) => ({ [fn.nom]: fn, ...acc }), {}),\n\t'inversion numérique': mecanismInversion,\n\t'le maximum de': parseMaximumDe,\n\t'le minimum de': parseMinimumDe,\n\t'taux progressif': tauxProgressif,\n\t'toutes ces conditions': toutesCesConditions,\n\t'est non défini': parseEstNonDéfini,\n\t'est non applicable': parseEstNonApplicable,\n\t'est applicable': parseEstApplicable,\n\t'est défini': parseEstDéfini,\n\t'une de ces conditions': uneDeCesConditions,\n\t'une possibilité': mecanismOnePossibility,\n\tcondition,\n\tbarème,\n\tdurée,\n\tgrille,\n\tmultiplication: produit,\n\tproduit,\n\tsomme,\n\tmoyenne,\n\t[texte.nom]: texte,\n\tvaleur: parse,\n\tvariable: parseReference,\n\tvariations,\n\tconstant: (v) => ({\n\t\ttype: v.type,\n\t\t// In the documentation we want to display constants defined in the source\n\t\t// with their full precision. This is especially useful for percentages like\n\t\t// APEC 0,036 %.\n\t\tfullPrecision: true,\n\t\tisNullable: v.nodeValue == null,\n\t\tmissingVariables: {},\n\t\tnodeValue: v.nodeValue,\n\t\tnodeKind: 'constant',\n\t}),\n}\n\nexport const mecanismKeys = Object.keys(parseFunctions)\n","import { ParsedRules, PublicodesError } from '.'\nimport { makeASTTransformer, makeASTVisitor } from './AST'\nimport { ASTNode } from './AST/types'\nimport { PublicodesInternalError } from './error'\nimport { defaultNode, notApplicableNode } from './evaluationUtils'\nimport parse from './parse'\nimport { Context, ReferencesMaps, RulesReplacements } from './parsePublicodes'\nimport { Rule, RuleNode } from './rule'\nimport { updateReferencesMapsFromReferenceNode } from './ruleUtils'\nimport { mergeWithArray } from './utils'\n\nexport type ReplacementRule = {\n\tnodeKind: 'replacementRule'\n\tdefinitionRule: ASTNode<'reference'> & { dottedName: string }\n\treplacedReference: ASTNode<'reference'>\n\tpriority?: number\n\twhiteListedNames: Array>\n\trawNode: any\n\tblackListedNames: Array>\n\tremplacementRuleId: number\n\treplaceByNonApplicable: boolean\n}\n\n// Replacements depend on the context and their evaluation implies using\n// \"variations\" node everywhere there is a reference to the original rule.\n// However for performance reason we want to mutualize identical \"variations\"\n// nodes instead of duplicating them, to avoid wasteful computations.\n//\n// The implementation works by first attributing an identifier for each\n// replacementRule. We then use this identifier to create a cache key that\n// represents the combinaison of applicables replacements for a given reference.\n// For example if replacements 12, 13 et 643 are applicable we use the key\n// `12-13-643` as the cache identifier in the `inlineReplacements` function.\nlet remplacementRuleId = 0\nconst cache = {}\n\nexport function parseReplacements(\n\treplacements: Rule['remplace'],\n\tcontext: Context,\n): Array {\n\tif (!replacements) {\n\t\treturn []\n\t}\n\n\treturn (Array.isArray(replacements) ? replacements : [replacements]).map(\n\t\t(replacement) => {\n\t\t\tif (typeof replacement === 'string') {\n\t\t\t\treplacement = { 'références à': replacement }\n\t\t\t}\n\n\t\t\tconst replacedReference = parse(replacement['références à'], context)\n\n\t\t\tconst [whiteListedNames, blackListedNames] = [\n\t\t\t\treplacement.dans ?? [],\n\t\t\t\treplacement['sauf dans'] ?? [],\n\t\t\t]\n\t\t\t\t.map((dottedName) =>\n\t\t\t\t\tArray.isArray(dottedName) ? dottedName : [dottedName],\n\t\t\t\t)\n\t\t\t\t.map((refs) => refs.map((ref) => parse(ref, context)))\n\t\t\tif (\n\t\t\t\treplacement.priorité != null &&\n\t\t\t\t(typeof replacement.priorité !== 'number' || replacement.priorité < 0)\n\t\t\t) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'SyntaxError',\n\t\t\t\t\t'La priorité du remplacement doit être un nombre positif',\n\t\t\t\t\tcontext,\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tnodeKind: 'replacementRule',\n\t\t\t\trawNode: replacement,\n\t\t\t\tpriority: replacement.priorité,\n\t\t\t\tdefinitionRule: parse(context.dottedName, context),\n\t\t\t\treplacedReference,\n\t\t\t\treplaceByNonApplicable: false,\n\t\t\t\twhiteListedNames,\n\t\t\t\tblackListedNames,\n\t\t\t\tremplacementRuleId: remplacementRuleId++,\n\t\t\t} as ReplacementRule\n\t\t},\n\t)\n}\n\nexport function parseRendNonApplicable(\n\trules: Rule['rend non applicable'],\n\tcontext: Context,\n): Array {\n\tconst rendNonApplicableReplacements = parseReplacements(rules, context)\n\trendNonApplicableReplacements.forEach(\n\t\t(r) => (r.replaceByNonApplicable = true),\n\t)\n\treturn rendNonApplicableReplacements\n}\n\nexport function getReplacements(\n\tparsedRules: Record,\n): RulesReplacements {\n\tconst ret = {}\n\tfor (const dottedName in parsedRules) {\n\t\tconst rule = parsedRules[dottedName]\n\t\tfor (const replacement of rule.replacements) {\n\t\t\tif (!replacement.replacedReference.dottedName) {\n\t\t\t\tthrow new PublicodesInternalError(replacement)\n\t\t\t}\n\t\t\tconst key = replacement.replacedReference.dottedName\n\t\t\tret[key] = [...(ret[key] ?? []), replacement]\n\t\t}\n\t}\n\n\treturn ret\n}\n\nexport function inlineReplacements<\n\tNewNames extends string,\n\tPreviousNames extends string,\n>({\n\tnewRules,\n\tpreviousReplacements,\n\tparsedRules,\n\treferencesMaps,\n}: {\n\tnewRules: ParsedRules\n\tpreviousReplacements: RulesReplacements\n\tparsedRules: ParsedRules\n\treferencesMaps: ReferencesMaps\n}): [\n\tParsedRules,\n\tRulesReplacements,\n] {\n\ttype Names = NewNames | PreviousNames\n\tconst newReplacements = getReplacements(newRules) as RulesReplacements\n\n\tconst ruleNamesWithNewReplacements = new Set([]) as Set\n\tfor (const replacedReference in newReplacements) {\n\t\tconst rulesThatUse =\n\t\t\treferencesMaps.rulesThatUse.get(replacedReference as NewNames | Names) ??\n\t\t\t[]\n\n\t\tfor (const value of rulesThatUse) {\n\t\t\truleNamesWithNewReplacements.add(value)\n\t\t}\n\t}\n\n\tconst newRuleNamesWithPreviousReplacements: Set = new Set(\n\t\t(Object.keys(newRules) as Array).filter((ruleName) =>\n\t\t\t[...(referencesMaps.referencesIn.get(ruleName) ?? new Set())].some(\n\t\t\t\t(reference) =>\n\t\t\t\t\t(previousReplacements[reference as PreviousNames] ?? []).length,\n\t\t\t),\n\t\t),\n\t)\n\n\tconst replacements = mergeWithArray(previousReplacements, newReplacements)\n\tif (\n\t\t!newRuleNamesWithPreviousReplacements.size &&\n\t\t!ruleNamesWithNewReplacements.size\n\t) {\n\t\treturn [parsedRules, replacements]\n\t}\n\n\tconst inlinePreviousReplacement = makeReplacementInliner(\n\t\tpreviousReplacements,\n\t\treferencesMaps,\n\t)\n\tconst inlineNewReplacement = makeReplacementInliner(\n\t\tnewReplacements,\n\t\treferencesMaps,\n\t)\n\n\tnewRuleNamesWithPreviousReplacements.forEach((name) => {\n\t\tparsedRules[name] = inlinePreviousReplacement(\n\t\t\tparsedRules[name],\n\t\t) as RuleNode\n\t})\n\truleNamesWithNewReplacements.forEach((name) => {\n\t\tparsedRules[name] = inlineNewReplacement(\n\t\t\tparsedRules[name],\n\t\t) as RuleNode\n\t})\n\n\treturn [parsedRules, replacements]\n}\n\nexport function makeReplacementInliner(\n\treplacements: RulesReplacements,\n\treferencesMaps: ReferencesMaps,\n): (n: ASTNode) => ASTNode {\n\treturn makeASTTransformer((node, transform) => {\n\t\tif (\n\t\t\tnode.nodeKind === 'replacementRule' ||\n\t\t\tnode.nodeKind === 'inversion' ||\n\t\t\tnode.nodeKind === 'une possibilité'\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tif (node.nodeKind === 'contexte') {\n\t\t\t// We don't replace references in contexte keys\n\t\t\treturn {\n\t\t\t\t...node,\n\t\t\t\texplanation: {\n\t\t\t\t\t...node.explanation,\n\t\t\t\t\tvaleur: transform(node.explanation.valeur),\n\t\t\t\t\tcontexte: node.explanation.contexte.map(([name, value]) => [\n\t\t\t\t\t\tname,\n\t\t\t\t\t\ttransform(value),\n\t\t\t\t\t]),\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\tif (node.nodeKind === 'reference') {\n\t\t\tif (!node.dottedName) {\n\t\t\t\tthrow new PublicodesInternalError(node)\n\t\t\t}\n\t\t\tconst replacedReferenceNode = replace(\n\t\t\t\tnode,\n\t\t\t\treplacements[node.dottedName] ?? [],\n\t\t\t)\n\t\t\t// Collect inlined replacement\n\t\t\tmakeASTVisitor((n) => {\n\t\t\t\tupdateReferencesMapsFromReferenceNode(\n\t\t\t\t\tn,\n\t\t\t\t\treferencesMaps,\n\t\t\t\t\tnode.contextDottedName,\n\t\t\t\t)\n\t\t\t\treturn 'continue'\n\t\t\t})(replacedReferenceNode)\n\t\t\treturn replacedReferenceNode\n\t\t}\n\t})\n}\n\nfunction replace(\n\tnode: ASTNode<'reference'>,\n\treplacements: Array,\n): ASTNode {\n\t// TODO : handle transitivité\n\n\tconst applicableReplacements = replacements\n\t\t.filter(\n\t\t\t({ definitionRule }) =>\n\t\t\t\tdefinitionRule.dottedName !== node.contextDottedName,\n\t\t)\n\t\t.filter(\n\t\t\t({ whiteListedNames }) =>\n\t\t\t\t!whiteListedNames.length ||\n\t\t\t\twhiteListedNames.some((name) =>\n\t\t\t\t\tnode.contextDottedName.startsWith(name.dottedName as string),\n\t\t\t\t),\n\t\t)\n\t\t.filter(\n\t\t\t({ blackListedNames }) =>\n\t\t\t\t!blackListedNames.length ||\n\t\t\t\tblackListedNames.every(\n\t\t\t\t\t(name) =>\n\t\t\t\t\t\t!node.contextDottedName.startsWith(name.dottedName as string),\n\t\t\t\t),\n\t\t)\n\t\t.reverse()\n\t\t.sort((a, b) => {\n\t\t\tconst result = (b.priority ?? 0) - (a.priority ?? 0)\n\t\t\tif (result !== 0) {\n\t\t\t\treturn result\n\t\t\t}\n\t\t\treturn b.definitionRule.dottedName.localeCompare(\n\t\t\t\ta.definitionRule.dottedName,\n\t\t\t)\n\t\t})\n\n\tif (!applicableReplacements.length) {\n\t\treturn node\n\t}\n\n\tconst applicableReplacementsCacheKey = applicableReplacements\n\t\t.map((n) => n.remplacementRuleId)\n\t\t.join('-')\n\tif (cache[applicableReplacementsCacheKey]) {\n\t\treturn cache[applicableReplacementsCacheKey]\n\t}\n\tconst replacementNode = {\n\t\tnodeKind: 'variations',\n\t\texplanation: [\n\t\t\t...applicableReplacements.map(\n\t\t\t\t({ definitionRule, replaceByNonApplicable }) =>\n\t\t\t\t\treplaceByNonApplicable ?\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcondition: definitionRule,\n\t\t\t\t\t\t\tconsequence: notApplicableNode,\n\t\t\t\t\t\t}\n\t\t\t\t\t:\t{\n\t\t\t\t\t\t\tcondition: estApplicable(definitionRule),\n\t\t\t\t\t\t\tconsequence: definitionRule,\n\t\t\t\t\t\t},\n\t\t\t),\n\t\t\t{ condition: oui, consequence: node },\n\t\t],\n\t} as ASTNode<'variations'>\n\n\treplacementNode.sourceMap = {\n\t\tmecanismName: 'replacement',\n\t\targs: {\n\t\t\tapplicableReplacements,\n\t\t\toriginalNode: node,\n\t\t},\n\t}\n\tcache[applicableReplacementsCacheKey] = replacementNode\n\treturn cache[applicableReplacementsCacheKey]\n}\n\nfunction estApplicable(node: ASTNode) {\n\treturn {\n\t\tnodeKind: 'condition',\n\t\texplanation: {\n\t\t\tsi: { nodeKind: 'est non applicable', explanation: node },\n\t\t\talors: non,\n\t\t\tsinon: oui,\n\t\t},\n\t} as ASTNode<'condition'>\n}\n\nconst oui = defaultNode(true)\nconst non = defaultNode(false)\n","import { Logger, ParsedRules } from '.'\nimport { makeASTTransformer, traverseParsedRules } from './AST'\nimport { PublicodesError } from './error'\nimport inferNodeType, { NodesTypes } from './inferNodeType'\nimport { ReplacementRule, inlineReplacements } from './replacement'\nimport { Rule, parseRules } from './rule'\nimport {\n\tdisambiguateReferenceNode,\n\tupdateReferencesMapsFromReferenceNode,\n} from './ruleUtils'\nimport { getUnitKey } from './units'\nimport { weakCopyObj } from './utils'\n\nexport type Context = {\n\tdottedName: RuleNames | ''\n\tparsedRules: ParsedRules\n\tnodesTypes: NodesTypes\n\treferencesMaps: ReferencesMaps\n\trulesReplacements: RulesReplacements\n\tgetUnitKey?: getUnitKey\n\tlogger: Logger\n\tinversionMaxIterations?: number\n\t/**\n\t * Don't throw an error if the parent of a rule is not found.\n\t * This is useful to parse partial rule sets (e.g. optimized ones).\n\t */\n\tallowOrphanRules: boolean\n\t/**\n\t * This is used to generate unique IDs for sub-engines, we need to generate them at\n\t * */\n\tsubEngineIncrementingNumber?: number\n}\n\nexport type RulesReplacements = Partial<\n\tRecord\n>\n\nexport type ReferencesMaps = {\n\treferencesIn: Map>\n\trulesThatUse: Map>\n}\n\nexport type RawRule = Omit | string | number | null\nexport type RawPublicodes = Partial<\n\tRecord\n>\n\nexport function createContext(\n\tpartialContext: Partial>,\n): Context {\n\treturn {\n\t\tdottedName: '',\n\t\tlogger: console,\n\t\tgetUnitKey: (x) => x,\n\t\tparsedRules: {} as ParsedRules,\n\t\treferencesMaps: { referencesIn: new Map(), rulesThatUse: new Map() },\n\t\tnodesTypes: new WeakMap(),\n\t\trulesReplacements: {},\n\t\tallowOrphanRules: false,\n\n\t\tsubEngineIncrementingNumber: 1,\n\n\t\t...partialContext,\n\t}\n}\n\nexport function copyContext(context: C): C {\n\treturn {\n\t\t...context,\n\t\tparsedRules: { ...context.parsedRules },\n\t\treferencesMaps: {\n\t\t\treferencesIn: new Map(context.referencesMaps.referencesIn),\n\t\t\trulesThatUse: new Map(context.referencesMaps.rulesThatUse),\n\t\t},\n\t}\n}\nexport default function parsePublicodes<\n\tContextNames extends string,\n\tNewRulesNames extends string,\n>(\n\trawRules: RawPublicodes,\n\tpartialContext: Partial> = createContext({}),\n): Pick<\n\tContext,\n\t'parsedRules' | 'nodesTypes' | 'referencesMaps' | 'rulesReplacements'\n> {\n\t// STEP 1 : get the rules as an object\n\n\tif (typeof rawRules === 'string')\n\t\tthrow new PublicodesError(\n\t\t\t'EngineError',\n\t\t\t'Publicodes does not parse yaml rule sets itself anymore. Please provide a parsed js object. E.g. the `eemeli/yaml` package.',\n\t\t\t{},\n\t\t)\n\n\t// let rules = { ...rawRules } // take 7-8ms\n\tconst rules = weakCopyObj(rawRules) // take 1-2ms\n\n\t// STEP 2: Rules parsing\n\tconst context = createContext(partialContext)\n\tconst previousParsedRules = context.parsedRules\n\tcontext.parsedRules = {} as ParsedRules\n\tparseRules(rules, context)\n\n\tlet parsedRules = {} as ParsedRules\n\tfor (const dottedName in previousParsedRules) {\n\t\tparsedRules[dottedName] = previousParsedRules[dottedName]\n\t}\n\tfor (const dottedName in context.parsedRules) {\n\t\tparsedRules[dottedName] = context.parsedRules[dottedName]\n\t}\n\n\t// STEP 3: Disambiguate reference\n\tconst [newRules, referencesMaps] =\n\t\tdisambiguateReferencesAndCollectDependencies(\n\t\t\tparsedRules,\n\t\t\tcontext.parsedRules,\n\t\t\tcontext.referencesMaps,\n\t\t\tcontext.allowOrphanRules,\n\t\t)\n\n\t// STEP 4: Inline replacements\n\tlet rulesReplacements\n\t\t// eslint-disable-next-line prefer-const\n\t;[parsedRules, rulesReplacements] = inlineReplacements<\n\t\tNewRulesNames,\n\t\tContextNames\n\t>({\n\t\tparsedRules,\n\t\tnewRules: newRules as any,\n\t\treferencesMaps,\n\t\tpreviousReplacements: context.rulesReplacements,\n\t})\n\n\t// STEP 5: type inference\n\tconst nodesTypes = inferNodeType(\n\t\tObject.keys(newRules),\n\t\tparsedRules,\n\t\tcontext.nodesTypes,\n\t)\n\n\treturn {\n\t\tparsedRules,\n\t\tnodesTypes,\n\t\treferencesMaps,\n\t\trulesReplacements,\n\t}\n}\n\nfunction disambiguateReferencesAndCollectDependencies<\n\tNewNames extends string,\n\tPreviousNames extends string,\n>(\n\tparsedRules: ParsedRules,\n\tnewRules: ParsedRules,\n\treferencesMaps: ReferencesMaps,\n\tallowOrphanRules: boolean,\n): [\n\tparsedRules: ParsedRules,\n\treferencesMap: ReferencesMaps,\n] {\n\tconst disambiguateReference = makeASTTransformer((node) =>\n\t\tdisambiguateReferenceNode(node, parsedRules),\n\t)\n\tconst disambiguateReferencesAndCollectDependencies = makeASTTransformer(\n\t\t(node) => {\n\t\t\tconst n = disambiguateReferenceNode(node, parsedRules)\n\t\t\tif (n) {\n\t\t\t\tupdateReferencesMapsFromReferenceNode(n, referencesMaps)\n\t\t\t}\n\t\t\treturn n\n\t\t},\n\t)\n\tconst disambiguatedRules = traverseParsedRules((node) => {\n\t\tif (node.nodeKind === 'replacementRule') {\n\t\t\t// The dependencies of replacements will be collected later, during the inlining\n\t\t\treturn disambiguateReference(node)\n\t\t}\n\t\tif (node.nodeKind === 'rule') {\n\t\t\tconst parentUndefined = (node.explanation.parents as any).find(\n\t\t\t\t(n: any) => !(n.dottedName in parsedRules),\n\t\t\t)\n\t\t\tif (!allowOrphanRules && parentUndefined) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'SyntaxError',\n\t\t\t\t\t`La règle parente \"${parentUndefined.dottedName}\" n'existe pas`,\n\t\t\t\t\t{\n\t\t\t\t\t\tdottedName: node.dottedName,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\treturn disambiguateReferencesAndCollectDependencies(node)\n\t}, newRules)\n\treturn [\n\t\tdisambiguatedRules,\n\t\treferencesMaps as ReferencesMaps,\n\t]\n}\n","import { ASTNode, EvaluatedNode } from '.'\n\nexport function computeTraversedVariableBeforeEval(\n\ttraversedVariablesStack: Array> | undefined,\n\tparsedNode: ASTNode,\n\tcachedNode: EvaluatedNode | undefined,\n\tpublicParsedRules: Record,\n\tisTraversedVariablesBoundary: boolean,\n) {\n\tif (traversedVariablesStack === undefined) {\n\t\treturn\n\t}\n\tif (cachedNode !== undefined) {\n\t\tcachedNode.traversedVariables?.forEach(\n\t\t\t(name) => traversedVariablesStack[0]?.add(name),\n\t\t)\n\t\treturn\n\t}\n\n\tif (isTraversedVariablesBoundary) {\n\t\t// Note: we use `unshift` instead of the more usual `push` to reverse the\n\t\t// order of the elements in the stack. This simplify access to the “top\n\t\t// element” with [0], instead of [length - 1]. We could also use the new\n\t\t// method `.at(-1)` but it isn't supported below Node v16.\n\t\ttraversedVariablesStack.unshift(new Set())\n\t}\n\n\tif (\n\t\tparsedNode.nodeKind === 'reference' &&\n\t\tparsedNode.dottedName &&\n\t\tparsedNode.dottedName in publicParsedRules\n\t) {\n\t\ttraversedVariablesStack[0].add(parsedNode.dottedName)\n\t}\n}\n\nexport function isTraversedVariablesBoundary(\n\ttraversedVariablesStack: Array> | undefined,\n\tparsedNode: ASTNode,\n) {\n\treturn (\n\t\t!!traversedVariablesStack &&\n\t\t(traversedVariablesStack.length === 0 || parsedNode.nodeKind === 'rule')\n\t)\n}\n\nexport function computeTraversedVariableAfterEval(\n\ttraversedVariablesStack: Array> | undefined,\n\tevaluatedNode: EvaluatedNode,\n\tisTraversedVariablesBoundary: boolean,\n) {\n\tif (traversedVariablesStack === undefined) {\n\t\treturn\n\t}\n\tif (isTraversedVariablesBoundary) {\n\t\tevaluatedNode.traversedVariables = Array.from(\n\t\t\ttraversedVariablesStack.shift() ?? [],\n\t\t)\n\n\t\tif (traversedVariablesStack.length > 0) {\n\t\t\tevaluatedNode.traversedVariables.forEach((name) => {\n\t\t\t\ttraversedVariablesStack[0].add(name)\n\t\t\t})\n\t\t}\n\t}\n}\n","import { EvaluatedNode } from './index'\nimport { serializeUnit } from './units'\nexport default function serializeEvaluation(\n\tnode: EvaluatedNode,\n): string | undefined {\n\tif (typeof node.nodeValue === 'number') {\n\t\tconst serializedUnit = serializeUnit(node.unit)\n\t\treturn (\n\t\t\t'' +\n\t\t\tnode.nodeValue +\n\t\t\t(serializedUnit ? serializedUnit.replace(/\\s/g, '') : '')\n\t\t)\n\t} else if (typeof node.nodeValue === 'boolean') {\n\t\treturn node.nodeValue ? 'oui' : 'non'\n\t} else if (typeof node.nodeValue === 'string') {\n\t\treturn `'${node.nodeValue}'`\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,uDAAAA,SAAA;AAAA,KAAC,SAAS,MAAM,SAAS;AACrB,UAAI,OAAOA,YAAW,YAAYA,QAA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AAAA,QACA,uBAAuB,WAAW,QAAQ;AAAA,QAC1C,EAAE,YAAY,GAAG;AAAA,MAClB;AAAA,IACD;AAEA,UAAM,gBAAgB,oBAAoB,WAAW,QAAQ,EAAE;AAAA,MAC9D;AAAA,MACA;AAAA,IACD;AACA,QAAI,KAAK,MAAM,yBAAyB;AACvC;AAAA,QACC,KAAK,MAAM;AAAA,QACX;AAAA,QACA;AAAA,MACD;AAAA,IACD;AAEA,SAAK,MAAM,MAAM,IAAI,YAAY,aAAa;AAC9C,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA,EAKA,cAA4B;AAC3B,UAAM,YAAY,IAAI,QAAa;AACnC,cAAU,cAAc,YAAY,KAAK,WAAW;AACpD,cAAU,UAAU,YAAY,KAAK,OAAO;AAC5C,cAAU,oBAAoB,KAAK;AACnC,cAAU,QAAQ;AAAA,MACjB,GAAG,WAAW;AAAA,MAEd,OAAO,IAAI,IAAI,KAAK,MAAM,KAAK;AAAA,IAChC;AACA,WAAO;AAAA,EACR;AAAA,EAEQ,wBAAwB,eAAe,CAAC,SAAS;AACxD,QACC,KAAK,aAAa,eACZ,eAAe,KAAK,QAAQ,aAAa,KAAK,UAAoB,GACvE;AACD;AAAA,QACC,KAAK,YAAY;AAAA,QACjB,KAAK;AAAA,MACN;AAAA,IACD;AACA,WAAO;AAAA,EACR,CAAC;AACF;","names":["module","Rule","dot","Parser","Grammar","lexer","pad","module","pad","string","word","Lexer","lexer","node","name","string","formatUnit","factor","convertTable","unitClasses","formatUnit","context","name","evaluate","evaluate","nodeValue","evaluate","date","date","evaluate","evaluate","evaluate","evaluate","evaluate","evaluate","nodeValue","evaluate","evaluate","evaluate","evaluate","unit","moo","arrpush","nearley","disambiguateReference","disambiguateReferencesAndCollectDependencies","isTraversedVariablesBoundary"]} \ No newline at end of file diff --git a/publicodes/dist/index.d.cts b/publicodes/dist/index.d.cts new file mode 100644 index 000000000..5c2116361 --- /dev/null +++ b/publicodes/dist/index.d.cts @@ -0,0 +1,639 @@ +type ArrondiNode = { + explanation: { + arrondi: ASTNode; + valeur: ASTNode; + }; + nodeKind: 'arrondi'; +}; + +type TrancheNode = { + taux: ASTNode; +} | { + montant: ASTNode; +}; +type TrancheNodes = Array; + +type BarèmeNode = { + explanation: { + tranches: TrancheNodes; + multiplicateur: ASTNode; + assiette: ASTNode; + }; + nodeKind: 'barème'; +}; + +type ConditionNode = { + explanation: { + si: ASTNode; + alors: ASTNode; + sinon: ASTNode; + }; + nodeKind: 'condition'; +}; + +type NodesTypes = WeakMap; +type InferedType = { + isNullable: boolean | undefined; +} & Pick; + +type Rule = { + formule?: Record | string; + valeur?: Record | string; + question?: string; + description?: string; + unité?: string; + acronyme?: string; + exemples?: any; + résumé?: string; + icônes?: string; + titre?: string; + sévérité?: string; + type?: string; + experimental?: 'oui'; + 'possiblement non applicable'?: 'oui'; + privé?: 'oui'; + note?: string; + remplace?: Remplace | Array; + 'rend non applicable'?: Remplace | Array; + suggestions?: Record>; + références?: { + [source: string]: string; + }; + API?: string; + 'identifiant court'?: string; +} & Record; +type Remplace = { + 'références à': string; + dans?: Array | string; + 'sauf dans'?: Array | string; + priorité?: number; +} | string; +type RuleNode = { + dottedName: Name; + title: string; + nodeKind: 'rule'; + virtualRule: boolean; + private: boolean; + rawNode: Rule; + replacements: Array; + explanation: { + valeur: ASTNode; + parents: Array; + nullableParent?: ASTNode; + ruleDisabledByItsParent: boolean; + }; + suggestions: Record; + 'identifiant court'?: string; +}; + +type ReplacementRule = { + nodeKind: 'replacementRule'; + definitionRule: ASTNode<'reference'> & { + dottedName: string; + }; + replacedReference: ASTNode<'reference'>; + priority?: number; + whiteListedNames: Array>; + rawNode: any; + blackListedNames: Array>; + remplacementRuleId: number; + replaceByNonApplicable: boolean; +}; + +type getUnitKey = (writtenUnit: string) => string; +type formatUnit = (unit: string, count: number) => string; +declare const parseUnit: (string: string, getUnitKey?: getUnitKey) => Unit; +declare function serializeUnit(rawUnit: Unit | undefined | string, count?: number, formatUnit?: formatUnit): string | undefined; + +type Context = { + dottedName: RuleNames | ''; + parsedRules: ParsedRules; + nodesTypes: NodesTypes; + referencesMaps: ReferencesMaps; + rulesReplacements: RulesReplacements; + getUnitKey?: getUnitKey; + logger: Logger; + inversionMaxIterations?: number; + /** + * Don't throw an error if the parent of a rule is not found. + * This is useful to parse partial rule sets (e.g. optimized ones). + */ + allowOrphanRules: boolean; + /** + * This is used to generate unique IDs for sub-engines, we need to generate them at + * */ + subEngineIncrementingNumber?: number; +}; +type RulesReplacements = Partial>; +type ReferencesMaps = { + referencesIn: Map>; + rulesThatUse: Map>; +}; +type RawRule = Omit | string | number | null; +type RawPublicodes = Partial>; +declare function parsePublicodes(rawRules: RawPublicodes, partialContext?: Partial>): Pick, 'parsedRules' | 'nodesTypes' | 'referencesMaps' | 'rulesReplacements'>; + +type ReferenceNode = { + nodeKind: 'reference'; + name: string; + contextDottedName: string; + dottedName?: string; + title?: string; + acronym?: string; +}; + +type ContextNode = { + explanation: { + valeur: ASTNode; + contexte: Array<[ReferenceNode, ASTNode]>; + subEngineId: number; + }; + nodeKind: 'contexte'; +}; + +type DuréeNode = { + explanation: { + depuis: ASTNode; + "jusqu'à": ASTNode; + }; + unit: Unit; + nodeKind: 'durée'; +}; + +type EstNonDéfiniNode = { + explanation: ASTNode; + nodeKind: 'est non défini'; +}; + +type EstNonApplicableNode = { + explanation: ASTNode; + nodeKind: 'est non applicable'; +}; + +type GrilleNode = { + explanation: { + assiette: ASTNode; + multiplicateur: ASTNode; + tranches: TrancheNodes; + }; + nodeKind: 'grille'; +}; + +type InversionNode = { + explanation: { + ruleToInverse: string; + inversionCandidates: Array; + unit?: Unit; + inversionGoal?: ASTNode; + numberOfIteration?: number; + inversionFail?: boolean; + }; + nodeKind: 'inversion'; +}; + +type PossibilityNode = { + explanation: Array; + 'choix obligatoire'?: 'oui' | 'non'; + context: string; + nodeKind: 'une possibilité'; +}; + +declare const knownOperations: { + readonly '*': readonly [(a: any, b: any) => number, "×"]; + readonly '/': readonly [(a: any, b: any) => number, "∕"]; + readonly '+': readonly [(a: any, b: any) => any]; + readonly '-': readonly [(a: any, b: any) => number, "−"]; + readonly '<': readonly [(a: any, b: any) => boolean]; + readonly '<=': readonly [(a: any, b: any) => boolean, "≤"]; + readonly '>': readonly [(a: any, b: any) => boolean]; + readonly '>=': readonly [(a: any, b: any) => boolean, "≥"]; + readonly '=': readonly [(a: any, b: any) => boolean]; + readonly '!=': readonly [(a: any, b: any) => boolean, "≠"]; + readonly et: readonly [(a: any, b: any) => any]; + readonly ou: readonly [(a: any, b: any) => any]; +}; +type OperationNode = { + nodeKind: 'operation'; + explanation: [ASTNode, ASTNode]; + operationKind: keyof typeof knownOperations; + operator: string; +}; + +type RésoudreRéférenceCirculaireNode = { + explanation: { + ruleToSolve: string; + valeur: ASTNode; + }; + nodeKind: 'résoudre référence circulaire'; +}; + +type SimplifierUnitéNode = { + explanation: ASTNode; + nodeKind: 'simplifier unité'; +}; + +type TauxProgressifNode = { + explanation: { + tranches: TrancheNodes; + multiplicateur: ASTNode; + assiette: ASTNode; + }; + nodeKind: 'taux progressif'; +}; + +declare const NAME: "texte"; +type TexteNode = { + explanation: Array; + nodeKind: typeof NAME; +}; + +type UnitéNode = { + unit: Unit; + explanation: ASTNode; + nodeKind: 'unité'; +}; + +type VariableManquanteNode = { + missingVariable: string; + explanation: ASTNode; + nodeKind: 'variable manquante'; +}; + +type VariationNode = { + explanation: Array<{ + condition: ASTNode; + consequence: ASTNode; + satisfied?: boolean; + }>; + nodeKind: 'variations'; +}; + +type ConstantNode = { + type: 'boolean' | 'number' | 'string' | 'date' | undefined; + nodeValue: Evaluation; + nodeKind: 'constant'; + isNullable?: boolean; + isDefault?: boolean; + fullPrecision?: boolean; +}; +type PossibleNodes = RuleNode | ReferenceNode | ArrondiNode | BarèmeNode | DuréeNode | GrilleNode | EstNonApplicableNode | EstNonDéfiniNode | InversionNode | OperationNode | PossibilityNode | ContextNode | SimplifierUnitéNode | RésoudreRéférenceCirculaireNode | TauxProgressifNode | UnitéNode | VariationNode | ConditionNode | ConstantNode | ReplacementRule | VariableManquanteNode | TexteNode; +type NodeKind = PossibleNodes['nodeKind']; +type ASTNode = PossibleNodes & { + nodeKind: N; + isDefault?: boolean; + sourceMap?: { + mecanismName: string; + args: Record>; + }; + rawNode?: string | Record; +} & (EvaluationDecoration | {}); +type ASTTransformer = (n: ASTNode) => ASTNode; +type TraverseFunction = (fn: ASTTransformer, node: ASTNode) => ASTNode; +type BaseUnit = string; +type Unit = { + numerators: Array; + denominators: Array; +}; +type EvaluationDecoration = { + nodeValue: Evaluation; + unit?: Unit; + traversedVariables?: Array; + missingVariables: MissingVariables; +}; +type Types = number | boolean | string | Record; +type Evaluation = T | null | undefined; +type EvaluatedNode = EvaluationDecoration & ASTNode; +type MissingVariables = Record; + +type GraphCycles = string[][]; +type RawRules = Parameters[0]; +/** + * This function is useful so as to print the dependencies at each node of the + * cycle. + * ⚠️ Indeed, the findCycles function returns the cycle found using the + * Tarjan method, which is **not necessarily the smallest cycle**. However, the + * smallest cycle is more readable. + */ +declare function cyclicDependencies(rawRules: RawRules): [GraphCycles, string[]]; + +/** + * Returns the last part of a dottedName (the leaf). + */ +declare const nameLeaf: (dottedName: string) => string; +/** + * Encodes a dottedName for the URL to be secure. + * @see {@link decodeRuleName} + */ +declare const encodeRuleName: (dottedName: string) => string; +/** + * Decodes an encoded dottedName. + * @see {@link encodeRuleName} + */ +declare const decodeRuleName: (dottedName: string) => string; +/** + * Return dottedName from contextName + */ +declare const contextNameToDottedName: (contextName: string) => string; +/** + * Returns the parent dottedName + */ +declare const ruleParent: (dottedName: string) => string; +/** + * Returns an array of dottedName from near parent to far parent. + */ +declare function ruleParents(dottedName: string): Array; +/** + * Returns an array of all child rules of a dottedName + */ +declare const getChildrenRules: (parsedRules: ParsedRules, dottedName: string) => string[]; +/** + * Finds the common ancestor of two dottedName + */ +declare function findCommonAncestor(dottedName1: string, dottedName2: string): string; +/** + * Check wether a rule is accessible from a namespace. + * + * Takes into account that some namespace can be `private`, i.e. that they can only be + * accessed by immediate parent, children or siblings. + * + * @param rules The parsed rules + * @param contextName The context of the call + * @param name The namespace checked for accessibility + */ +declare function isAccessible(rules: Record, contextName: string, name: string): boolean; +/** + * Check wether a rule is tagged as experimental. + * + * Takes into account the a children of an experimental rule is also experimental + * + * @param rules The parsed rules + * @param name The namespace checked for experimental + */ +declare function isExperimental(rules: Record, name: string): boolean; +declare function disambiguateReference>(rules: R, referencedFrom: string | undefined, partialName: string): keyof R; +declare function ruleWithDedicatedDocumentationPage(rule: any): boolean; +declare function updateReferencesMapsFromReferenceNode(node: ASTNode, referencesMaps: ReferencesMaps, ruleDottedName?: string): void; +declare function disambiguateReferenceNode(node: ASTNode, parsedRules: ParsedRules): ReferenceNode | undefined; + +declare const ruleUtils_contextNameToDottedName: typeof contextNameToDottedName; +declare const ruleUtils_cyclicDependencies: typeof cyclicDependencies; +declare const ruleUtils_decodeRuleName: typeof decodeRuleName; +declare const ruleUtils_disambiguateReference: typeof disambiguateReference; +declare const ruleUtils_disambiguateReferenceNode: typeof disambiguateReferenceNode; +declare const ruleUtils_encodeRuleName: typeof encodeRuleName; +declare const ruleUtils_findCommonAncestor: typeof findCommonAncestor; +declare const ruleUtils_getChildrenRules: typeof getChildrenRules; +declare const ruleUtils_isAccessible: typeof isAccessible; +declare const ruleUtils_isExperimental: typeof isExperimental; +declare const ruleUtils_nameLeaf: typeof nameLeaf; +declare const ruleUtils_ruleParent: typeof ruleParent; +declare const ruleUtils_ruleParents: typeof ruleParents; +declare const ruleUtils_ruleWithDedicatedDocumentationPage: typeof ruleWithDedicatedDocumentationPage; +declare const ruleUtils_updateReferencesMapsFromReferenceNode: typeof updateReferencesMapsFromReferenceNode; +declare namespace ruleUtils { + export { + ruleUtils_contextNameToDottedName as contextNameToDottedName, + ruleUtils_cyclicDependencies as cyclicDependencies, + ruleUtils_decodeRuleName as decodeRuleName, + ruleUtils_disambiguateReference as disambiguateReference, + ruleUtils_disambiguateReferenceNode as disambiguateReferenceNode, + ruleUtils_encodeRuleName as encodeRuleName, + ruleUtils_findCommonAncestor as findCommonAncestor, + ruleUtils_getChildrenRules as getChildrenRules, + ruleUtils_isAccessible as isAccessible, + ruleUtils_isExperimental as isExperimental, + ruleUtils_nameLeaf as nameLeaf, + ruleUtils_ruleParent as ruleParent, + ruleUtils_ruleParents as ruleParents, + ruleUtils_ruleWithDedicatedDocumentationPage as ruleWithDedicatedDocumentationPage, + ruleUtils_updateReferencesMapsFromReferenceNode as updateReferencesMapsFromReferenceNode, + }; +} + +/** + This function creates a transormation of the AST from on a simpler + callback function `fn` + + `fn` will be called with the nodes of the ASTTree during the exploration + + The outcome of the callback function has an influence on the exploration of the AST : + - `false`, the node is not updated and the exploration does not continue further down this branch + - `undefined`, the node is not updated but the exploration continues and its children will be transformed + - `ASTNode`, the node is transformed to the new value and the exploration does not continue further down the branch + + `updateFn` : It is possible to specifically use the updated version of a child + by using the function passed as second argument. The returned value will be the + transformed version of the node. + */ +declare function makeASTTransformer(fn: (node: ASTNode, transform: ASTTransformer) => ASTNode | undefined | false, stopOnUpdate?: boolean): ASTTransformer; +/** + * This function allows to construct a specific value while exploring the AST with + * a simple reducing function as argument. + * + * `fn` will be called with the currently reduced value `acc` and the current node of the AST + * + * If the callback function returns: + * - `undefined`, the exploration continues further down and all the children are reduced + * successively to a single value + * - `T`, the reduced value is returned + * + * `reduceFn` : It is possible to specifically use the reduced value of a child + * by using the function passed as second argument. The returned value will be the reduced version + * of the node + */ +declare function reduceAST(fn: (acc: T, n: ASTNode, reduceFn: (n: ASTNode) => T) => T | undefined, start: T, node: ASTNode): T; +/** + * Apply a transform function on children. Not recursive. + */ +declare const traverseASTNode: TraverseFunction; + +/** + * Each error name with corresponding type in info value + */ +interface PublicodesErrorTypes { + InternalError: { + dottedName?: string; + }; + EngineError: Record; + SyntaxError: { + dottedName: string; + }; + EvaluationError: { + dottedName: string; + }; + UnknownRule: { + dottedName: string; + }; + PrivateRule: { + dottedName: string; + }; +} +/** + * Return true if `error` is a PublicodesError, + * use `name` parameter to check and narow error type + * @example + * try { + * new Engine().evaluate() + * } catch (error) { + * if (isPublicodesError(error, 'EngineError')) { + * console.log(error.info) + * } + * } + */ +declare const isPublicodesError: (error: unknown, name?: Name | undefined) => error is PublicodesError; +/** + * Generic error for Publicodes + */ +declare class PublicodesError extends Error { + name: Name; + info: PublicodesErrorTypes[Name]; + constructor(name: Name, message: string, info: PublicodesErrorTypes[Name], originalError?: Error); +} + +declare function capitalise0(name: undefined): undefined; +declare function capitalise0(name: string): string; +type Options$1 = { + language?: string; + displayedUnit?: string; + precision?: number; + formatUnit?: formatUnit; +}; +declare function formatValue(value: number | { + nodeValue: Evaluation; + unit?: Unit; +} | undefined, { language, displayedUnit, formatUnit, precision }?: Options$1): any; + +declare function simplifyNodeUnit(node: any): any; + +type BinaryOp = { + '+': [ExprAST, ExprAST]; +} | { + '-': [ExprAST, ExprAST]; +} | { + '*': [ExprAST, ExprAST]; +} | { + '/': [ExprAST, ExprAST]; +} | { + '>': [ExprAST, ExprAST]; +} | { + '<': [ExprAST, ExprAST]; +} | { + '>=': [ExprAST, ExprAST]; +} | { + '<=': [ExprAST, ExprAST]; +} | { + '=': [ExprAST, ExprAST]; +} | { + '!=': [ExprAST, ExprAST]; +}; +type UnaryOp = { + '-': [{ + value: 0; + }, ExprAST]; +}; +/** AST of a publicodes expression. */ +type ExprAST = BinaryOp | UnaryOp | { + variable: string; +} | { + constant: { + type: 'number'; + nodeValue: number; + }; + unité?: string; +} | { + constant: { + type: 'boolean'; + nodeValue: boolean; + }; +} | { + constant: { + type: 'string' | 'date'; + nodeValue: string; + }; +}; +/** + * Parse a publicodes expression into an JSON object representing the AST. + * + * The parsing is done with the [nearley](https://nearley.js.org/) parser + * + * @param rawNode The expression to parse + * @param dottedName The dottedName of the rule being parsed + * + * @returns The parsing result as a JSON object + * + * @throws A `SyntaxError` if the expression is invalid + * @throws A `PublicodesInternalError` if the parser is unable to parse the expression + * + * @example + * ```ts + * parseExpression('20.3 * nombre', 'foo . bar') + * // returns { "*": [ { constant: { type: "number", nodeValue: 20.3 } }, { variable:"nombre" } ] } + * ``` + */ +declare function parseExpression(rawNode: string, dottedName: string): ExprAST; + +declare function serializeEvaluation(node: EvaluatedNode): string | undefined; + +type Cache = { + inversionFail?: boolean; + _meta: { + evaluationRuleStack: Array; + parentRuleStack: Array; + currentContexteSituation?: string; + }; + /** + * Every time we encounter a reference to a rule in an expression we add it + * to the current Set of traversed variables. Because we evaluate the + * expression graph “top to bottom” (ie. we start by the high-level goal and + * recursively evaluate its dependencies), we need to handle rule + * “boundaries”, so that when we “enter” in the evaluation of a dependency, + * we start with a clear empty set of traversed variables. Then, when we go + * back to the referencer rule, we need to add all to merge the two sets : + * rules already traversed in the current expression and the one from the + * reference. + */ + traversedVariablesStack?: Array>; + nodes: Map; +}; + +type PublicodesExpression = string | Record | number; +type Logger = { + log(message: string): void; + warn(message: string): void; + error(message: string): void; +}; +type Options = Partial>; +type EvaluationFunction = (this: Engine, node: ASTNode & { + nodeKind: Kind; +}) => { + nodeKind: Kind; +} & EvaluatedNode; +type ParsedRules = Record>; +declare class Engine { + baseContext: Context; + context: Context; + publicParsedRules: ParsedRules; + cache: Cache; + subEngines: Array>; + subEngineId: number | undefined; + constructor(rules?: RawPublicodes, options?: Options); + resetCache(): void; + setSituation(situation?: Partial>, options?: { + keepPreviousSituation?: boolean; + }): this; + inversionFail(): boolean; + getRule(dottedName: Name): ParsedRules[Name]; + getParsedRules(): ParsedRules; + evaluate(value: PublicodesExpression): EvaluatedNode; + evaluateNode(parsedNode: T): EvaluatedNode & T; + /** + * Shallow Engine instance copy. Keeps references to the original Engine instance attributes. + */ + shallowCopy(): Engine; + private checkExperimentalRule; +} + +export { ASTNode, EvaluatedNode, Evaluation, EvaluationFunction, ExprAST, Logger, ParsedRules, PublicodesError, PublicodesExpression, Rule, RuleNode, Unit, capitalise0, Engine as default, formatValue, isPublicodesError, parseExpression, parsePublicodes, parseUnit, reduceAST, serializeEvaluation, serializeUnit, simplifyNodeUnit, makeASTTransformer as transformAST, traverseASTNode, ruleUtils as utils }; diff --git a/publicodes/dist/index.d.ts b/publicodes/dist/index.d.ts new file mode 100644 index 000000000..5c2116361 --- /dev/null +++ b/publicodes/dist/index.d.ts @@ -0,0 +1,639 @@ +type ArrondiNode = { + explanation: { + arrondi: ASTNode; + valeur: ASTNode; + }; + nodeKind: 'arrondi'; +}; + +type TrancheNode = { + taux: ASTNode; +} | { + montant: ASTNode; +}; +type TrancheNodes = Array; + +type BarèmeNode = { + explanation: { + tranches: TrancheNodes; + multiplicateur: ASTNode; + assiette: ASTNode; + }; + nodeKind: 'barème'; +}; + +type ConditionNode = { + explanation: { + si: ASTNode; + alors: ASTNode; + sinon: ASTNode; + }; + nodeKind: 'condition'; +}; + +type NodesTypes = WeakMap; +type InferedType = { + isNullable: boolean | undefined; +} & Pick; + +type Rule = { + formule?: Record | string; + valeur?: Record | string; + question?: string; + description?: string; + unité?: string; + acronyme?: string; + exemples?: any; + résumé?: string; + icônes?: string; + titre?: string; + sévérité?: string; + type?: string; + experimental?: 'oui'; + 'possiblement non applicable'?: 'oui'; + privé?: 'oui'; + note?: string; + remplace?: Remplace | Array; + 'rend non applicable'?: Remplace | Array; + suggestions?: Record>; + références?: { + [source: string]: string; + }; + API?: string; + 'identifiant court'?: string; +} & Record; +type Remplace = { + 'références à': string; + dans?: Array | string; + 'sauf dans'?: Array | string; + priorité?: number; +} | string; +type RuleNode = { + dottedName: Name; + title: string; + nodeKind: 'rule'; + virtualRule: boolean; + private: boolean; + rawNode: Rule; + replacements: Array; + explanation: { + valeur: ASTNode; + parents: Array; + nullableParent?: ASTNode; + ruleDisabledByItsParent: boolean; + }; + suggestions: Record; + 'identifiant court'?: string; +}; + +type ReplacementRule = { + nodeKind: 'replacementRule'; + definitionRule: ASTNode<'reference'> & { + dottedName: string; + }; + replacedReference: ASTNode<'reference'>; + priority?: number; + whiteListedNames: Array>; + rawNode: any; + blackListedNames: Array>; + remplacementRuleId: number; + replaceByNonApplicable: boolean; +}; + +type getUnitKey = (writtenUnit: string) => string; +type formatUnit = (unit: string, count: number) => string; +declare const parseUnit: (string: string, getUnitKey?: getUnitKey) => Unit; +declare function serializeUnit(rawUnit: Unit | undefined | string, count?: number, formatUnit?: formatUnit): string | undefined; + +type Context = { + dottedName: RuleNames | ''; + parsedRules: ParsedRules; + nodesTypes: NodesTypes; + referencesMaps: ReferencesMaps; + rulesReplacements: RulesReplacements; + getUnitKey?: getUnitKey; + logger: Logger; + inversionMaxIterations?: number; + /** + * Don't throw an error if the parent of a rule is not found. + * This is useful to parse partial rule sets (e.g. optimized ones). + */ + allowOrphanRules: boolean; + /** + * This is used to generate unique IDs for sub-engines, we need to generate them at + * */ + subEngineIncrementingNumber?: number; +}; +type RulesReplacements = Partial>; +type ReferencesMaps = { + referencesIn: Map>; + rulesThatUse: Map>; +}; +type RawRule = Omit | string | number | null; +type RawPublicodes = Partial>; +declare function parsePublicodes(rawRules: RawPublicodes, partialContext?: Partial>): Pick, 'parsedRules' | 'nodesTypes' | 'referencesMaps' | 'rulesReplacements'>; + +type ReferenceNode = { + nodeKind: 'reference'; + name: string; + contextDottedName: string; + dottedName?: string; + title?: string; + acronym?: string; +}; + +type ContextNode = { + explanation: { + valeur: ASTNode; + contexte: Array<[ReferenceNode, ASTNode]>; + subEngineId: number; + }; + nodeKind: 'contexte'; +}; + +type DuréeNode = { + explanation: { + depuis: ASTNode; + "jusqu'à": ASTNode; + }; + unit: Unit; + nodeKind: 'durée'; +}; + +type EstNonDéfiniNode = { + explanation: ASTNode; + nodeKind: 'est non défini'; +}; + +type EstNonApplicableNode = { + explanation: ASTNode; + nodeKind: 'est non applicable'; +}; + +type GrilleNode = { + explanation: { + assiette: ASTNode; + multiplicateur: ASTNode; + tranches: TrancheNodes; + }; + nodeKind: 'grille'; +}; + +type InversionNode = { + explanation: { + ruleToInverse: string; + inversionCandidates: Array; + unit?: Unit; + inversionGoal?: ASTNode; + numberOfIteration?: number; + inversionFail?: boolean; + }; + nodeKind: 'inversion'; +}; + +type PossibilityNode = { + explanation: Array; + 'choix obligatoire'?: 'oui' | 'non'; + context: string; + nodeKind: 'une possibilité'; +}; + +declare const knownOperations: { + readonly '*': readonly [(a: any, b: any) => number, "×"]; + readonly '/': readonly [(a: any, b: any) => number, "∕"]; + readonly '+': readonly [(a: any, b: any) => any]; + readonly '-': readonly [(a: any, b: any) => number, "−"]; + readonly '<': readonly [(a: any, b: any) => boolean]; + readonly '<=': readonly [(a: any, b: any) => boolean, "≤"]; + readonly '>': readonly [(a: any, b: any) => boolean]; + readonly '>=': readonly [(a: any, b: any) => boolean, "≥"]; + readonly '=': readonly [(a: any, b: any) => boolean]; + readonly '!=': readonly [(a: any, b: any) => boolean, "≠"]; + readonly et: readonly [(a: any, b: any) => any]; + readonly ou: readonly [(a: any, b: any) => any]; +}; +type OperationNode = { + nodeKind: 'operation'; + explanation: [ASTNode, ASTNode]; + operationKind: keyof typeof knownOperations; + operator: string; +}; + +type RésoudreRéférenceCirculaireNode = { + explanation: { + ruleToSolve: string; + valeur: ASTNode; + }; + nodeKind: 'résoudre référence circulaire'; +}; + +type SimplifierUnitéNode = { + explanation: ASTNode; + nodeKind: 'simplifier unité'; +}; + +type TauxProgressifNode = { + explanation: { + tranches: TrancheNodes; + multiplicateur: ASTNode; + assiette: ASTNode; + }; + nodeKind: 'taux progressif'; +}; + +declare const NAME: "texte"; +type TexteNode = { + explanation: Array; + nodeKind: typeof NAME; +}; + +type UnitéNode = { + unit: Unit; + explanation: ASTNode; + nodeKind: 'unité'; +}; + +type VariableManquanteNode = { + missingVariable: string; + explanation: ASTNode; + nodeKind: 'variable manquante'; +}; + +type VariationNode = { + explanation: Array<{ + condition: ASTNode; + consequence: ASTNode; + satisfied?: boolean; + }>; + nodeKind: 'variations'; +}; + +type ConstantNode = { + type: 'boolean' | 'number' | 'string' | 'date' | undefined; + nodeValue: Evaluation; + nodeKind: 'constant'; + isNullable?: boolean; + isDefault?: boolean; + fullPrecision?: boolean; +}; +type PossibleNodes = RuleNode | ReferenceNode | ArrondiNode | BarèmeNode | DuréeNode | GrilleNode | EstNonApplicableNode | EstNonDéfiniNode | InversionNode | OperationNode | PossibilityNode | ContextNode | SimplifierUnitéNode | RésoudreRéférenceCirculaireNode | TauxProgressifNode | UnitéNode | VariationNode | ConditionNode | ConstantNode | ReplacementRule | VariableManquanteNode | TexteNode; +type NodeKind = PossibleNodes['nodeKind']; +type ASTNode = PossibleNodes & { + nodeKind: N; + isDefault?: boolean; + sourceMap?: { + mecanismName: string; + args: Record>; + }; + rawNode?: string | Record; +} & (EvaluationDecoration | {}); +type ASTTransformer = (n: ASTNode) => ASTNode; +type TraverseFunction = (fn: ASTTransformer, node: ASTNode) => ASTNode; +type BaseUnit = string; +type Unit = { + numerators: Array; + denominators: Array; +}; +type EvaluationDecoration = { + nodeValue: Evaluation; + unit?: Unit; + traversedVariables?: Array; + missingVariables: MissingVariables; +}; +type Types = number | boolean | string | Record; +type Evaluation = T | null | undefined; +type EvaluatedNode = EvaluationDecoration & ASTNode; +type MissingVariables = Record; + +type GraphCycles = string[][]; +type RawRules = Parameters[0]; +/** + * This function is useful so as to print the dependencies at each node of the + * cycle. + * ⚠️ Indeed, the findCycles function returns the cycle found using the + * Tarjan method, which is **not necessarily the smallest cycle**. However, the + * smallest cycle is more readable. + */ +declare function cyclicDependencies(rawRules: RawRules): [GraphCycles, string[]]; + +/** + * Returns the last part of a dottedName (the leaf). + */ +declare const nameLeaf: (dottedName: string) => string; +/** + * Encodes a dottedName for the URL to be secure. + * @see {@link decodeRuleName} + */ +declare const encodeRuleName: (dottedName: string) => string; +/** + * Decodes an encoded dottedName. + * @see {@link encodeRuleName} + */ +declare const decodeRuleName: (dottedName: string) => string; +/** + * Return dottedName from contextName + */ +declare const contextNameToDottedName: (contextName: string) => string; +/** + * Returns the parent dottedName + */ +declare const ruleParent: (dottedName: string) => string; +/** + * Returns an array of dottedName from near parent to far parent. + */ +declare function ruleParents(dottedName: string): Array; +/** + * Returns an array of all child rules of a dottedName + */ +declare const getChildrenRules: (parsedRules: ParsedRules, dottedName: string) => string[]; +/** + * Finds the common ancestor of two dottedName + */ +declare function findCommonAncestor(dottedName1: string, dottedName2: string): string; +/** + * Check wether a rule is accessible from a namespace. + * + * Takes into account that some namespace can be `private`, i.e. that they can only be + * accessed by immediate parent, children or siblings. + * + * @param rules The parsed rules + * @param contextName The context of the call + * @param name The namespace checked for accessibility + */ +declare function isAccessible(rules: Record, contextName: string, name: string): boolean; +/** + * Check wether a rule is tagged as experimental. + * + * Takes into account the a children of an experimental rule is also experimental + * + * @param rules The parsed rules + * @param name The namespace checked for experimental + */ +declare function isExperimental(rules: Record, name: string): boolean; +declare function disambiguateReference>(rules: R, referencedFrom: string | undefined, partialName: string): keyof R; +declare function ruleWithDedicatedDocumentationPage(rule: any): boolean; +declare function updateReferencesMapsFromReferenceNode(node: ASTNode, referencesMaps: ReferencesMaps, ruleDottedName?: string): void; +declare function disambiguateReferenceNode(node: ASTNode, parsedRules: ParsedRules): ReferenceNode | undefined; + +declare const ruleUtils_contextNameToDottedName: typeof contextNameToDottedName; +declare const ruleUtils_cyclicDependencies: typeof cyclicDependencies; +declare const ruleUtils_decodeRuleName: typeof decodeRuleName; +declare const ruleUtils_disambiguateReference: typeof disambiguateReference; +declare const ruleUtils_disambiguateReferenceNode: typeof disambiguateReferenceNode; +declare const ruleUtils_encodeRuleName: typeof encodeRuleName; +declare const ruleUtils_findCommonAncestor: typeof findCommonAncestor; +declare const ruleUtils_getChildrenRules: typeof getChildrenRules; +declare const ruleUtils_isAccessible: typeof isAccessible; +declare const ruleUtils_isExperimental: typeof isExperimental; +declare const ruleUtils_nameLeaf: typeof nameLeaf; +declare const ruleUtils_ruleParent: typeof ruleParent; +declare const ruleUtils_ruleParents: typeof ruleParents; +declare const ruleUtils_ruleWithDedicatedDocumentationPage: typeof ruleWithDedicatedDocumentationPage; +declare const ruleUtils_updateReferencesMapsFromReferenceNode: typeof updateReferencesMapsFromReferenceNode; +declare namespace ruleUtils { + export { + ruleUtils_contextNameToDottedName as contextNameToDottedName, + ruleUtils_cyclicDependencies as cyclicDependencies, + ruleUtils_decodeRuleName as decodeRuleName, + ruleUtils_disambiguateReference as disambiguateReference, + ruleUtils_disambiguateReferenceNode as disambiguateReferenceNode, + ruleUtils_encodeRuleName as encodeRuleName, + ruleUtils_findCommonAncestor as findCommonAncestor, + ruleUtils_getChildrenRules as getChildrenRules, + ruleUtils_isAccessible as isAccessible, + ruleUtils_isExperimental as isExperimental, + ruleUtils_nameLeaf as nameLeaf, + ruleUtils_ruleParent as ruleParent, + ruleUtils_ruleParents as ruleParents, + ruleUtils_ruleWithDedicatedDocumentationPage as ruleWithDedicatedDocumentationPage, + ruleUtils_updateReferencesMapsFromReferenceNode as updateReferencesMapsFromReferenceNode, + }; +} + +/** + This function creates a transormation of the AST from on a simpler + callback function `fn` + + `fn` will be called with the nodes of the ASTTree during the exploration + + The outcome of the callback function has an influence on the exploration of the AST : + - `false`, the node is not updated and the exploration does not continue further down this branch + - `undefined`, the node is not updated but the exploration continues and its children will be transformed + - `ASTNode`, the node is transformed to the new value and the exploration does not continue further down the branch + + `updateFn` : It is possible to specifically use the updated version of a child + by using the function passed as second argument. The returned value will be the + transformed version of the node. + */ +declare function makeASTTransformer(fn: (node: ASTNode, transform: ASTTransformer) => ASTNode | undefined | false, stopOnUpdate?: boolean): ASTTransformer; +/** + * This function allows to construct a specific value while exploring the AST with + * a simple reducing function as argument. + * + * `fn` will be called with the currently reduced value `acc` and the current node of the AST + * + * If the callback function returns: + * - `undefined`, the exploration continues further down and all the children are reduced + * successively to a single value + * - `T`, the reduced value is returned + * + * `reduceFn` : It is possible to specifically use the reduced value of a child + * by using the function passed as second argument. The returned value will be the reduced version + * of the node + */ +declare function reduceAST(fn: (acc: T, n: ASTNode, reduceFn: (n: ASTNode) => T) => T | undefined, start: T, node: ASTNode): T; +/** + * Apply a transform function on children. Not recursive. + */ +declare const traverseASTNode: TraverseFunction; + +/** + * Each error name with corresponding type in info value + */ +interface PublicodesErrorTypes { + InternalError: { + dottedName?: string; + }; + EngineError: Record; + SyntaxError: { + dottedName: string; + }; + EvaluationError: { + dottedName: string; + }; + UnknownRule: { + dottedName: string; + }; + PrivateRule: { + dottedName: string; + }; +} +/** + * Return true if `error` is a PublicodesError, + * use `name` parameter to check and narow error type + * @example + * try { + * new Engine().evaluate() + * } catch (error) { + * if (isPublicodesError(error, 'EngineError')) { + * console.log(error.info) + * } + * } + */ +declare const isPublicodesError: (error: unknown, name?: Name | undefined) => error is PublicodesError; +/** + * Generic error for Publicodes + */ +declare class PublicodesError extends Error { + name: Name; + info: PublicodesErrorTypes[Name]; + constructor(name: Name, message: string, info: PublicodesErrorTypes[Name], originalError?: Error); +} + +declare function capitalise0(name: undefined): undefined; +declare function capitalise0(name: string): string; +type Options$1 = { + language?: string; + displayedUnit?: string; + precision?: number; + formatUnit?: formatUnit; +}; +declare function formatValue(value: number | { + nodeValue: Evaluation; + unit?: Unit; +} | undefined, { language, displayedUnit, formatUnit, precision }?: Options$1): any; + +declare function simplifyNodeUnit(node: any): any; + +type BinaryOp = { + '+': [ExprAST, ExprAST]; +} | { + '-': [ExprAST, ExprAST]; +} | { + '*': [ExprAST, ExprAST]; +} | { + '/': [ExprAST, ExprAST]; +} | { + '>': [ExprAST, ExprAST]; +} | { + '<': [ExprAST, ExprAST]; +} | { + '>=': [ExprAST, ExprAST]; +} | { + '<=': [ExprAST, ExprAST]; +} | { + '=': [ExprAST, ExprAST]; +} | { + '!=': [ExprAST, ExprAST]; +}; +type UnaryOp = { + '-': [{ + value: 0; + }, ExprAST]; +}; +/** AST of a publicodes expression. */ +type ExprAST = BinaryOp | UnaryOp | { + variable: string; +} | { + constant: { + type: 'number'; + nodeValue: number; + }; + unité?: string; +} | { + constant: { + type: 'boolean'; + nodeValue: boolean; + }; +} | { + constant: { + type: 'string' | 'date'; + nodeValue: string; + }; +}; +/** + * Parse a publicodes expression into an JSON object representing the AST. + * + * The parsing is done with the [nearley](https://nearley.js.org/) parser + * + * @param rawNode The expression to parse + * @param dottedName The dottedName of the rule being parsed + * + * @returns The parsing result as a JSON object + * + * @throws A `SyntaxError` if the expression is invalid + * @throws A `PublicodesInternalError` if the parser is unable to parse the expression + * + * @example + * ```ts + * parseExpression('20.3 * nombre', 'foo . bar') + * // returns { "*": [ { constant: { type: "number", nodeValue: 20.3 } }, { variable:"nombre" } ] } + * ``` + */ +declare function parseExpression(rawNode: string, dottedName: string): ExprAST; + +declare function serializeEvaluation(node: EvaluatedNode): string | undefined; + +type Cache = { + inversionFail?: boolean; + _meta: { + evaluationRuleStack: Array; + parentRuleStack: Array; + currentContexteSituation?: string; + }; + /** + * Every time we encounter a reference to a rule in an expression we add it + * to the current Set of traversed variables. Because we evaluate the + * expression graph “top to bottom” (ie. we start by the high-level goal and + * recursively evaluate its dependencies), we need to handle rule + * “boundaries”, so that when we “enter” in the evaluation of a dependency, + * we start with a clear empty set of traversed variables. Then, when we go + * back to the referencer rule, we need to add all to merge the two sets : + * rules already traversed in the current expression and the one from the + * reference. + */ + traversedVariablesStack?: Array>; + nodes: Map; +}; + +type PublicodesExpression = string | Record | number; +type Logger = { + log(message: string): void; + warn(message: string): void; + error(message: string): void; +}; +type Options = Partial>; +type EvaluationFunction = (this: Engine, node: ASTNode & { + nodeKind: Kind; +}) => { + nodeKind: Kind; +} & EvaluatedNode; +type ParsedRules = Record>; +declare class Engine { + baseContext: Context; + context: Context; + publicParsedRules: ParsedRules; + cache: Cache; + subEngines: Array>; + subEngineId: number | undefined; + constructor(rules?: RawPublicodes, options?: Options); + resetCache(): void; + setSituation(situation?: Partial>, options?: { + keepPreviousSituation?: boolean; + }): this; + inversionFail(): boolean; + getRule(dottedName: Name): ParsedRules[Name]; + getParsedRules(): ParsedRules; + evaluate(value: PublicodesExpression): EvaluatedNode; + evaluateNode(parsedNode: T): EvaluatedNode & T; + /** + * Shallow Engine instance copy. Keeps references to the original Engine instance attributes. + */ + shallowCopy(): Engine; + private checkExperimentalRule; +} + +export { ASTNode, EvaluatedNode, Evaluation, EvaluationFunction, ExprAST, Logger, ParsedRules, PublicodesError, PublicodesExpression, Rule, RuleNode, Unit, capitalise0, Engine as default, formatValue, isPublicodesError, parseExpression, parsePublicodes, parseUnit, reduceAST, serializeEvaluation, serializeUnit, simplifyNodeUnit, makeASTTransformer as transformAST, traverseASTNode, ruleUtils as utils }; diff --git a/publicodes/dist/index.js b/publicodes/dist/index.js new file mode 100644 index 000000000..cb17790b5 --- /dev/null +++ b/publicodes/dist/index.js @@ -0,0 +1,5326 @@ +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 __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +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. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// ../../node_modules/nearley/lib/nearley.js +var require_nearley = __commonJS({ + "../../node_modules/nearley/lib/nearley.js"(exports, module) { + (function(root, factory) { + if (typeof module === "object" && module.exports) { + module.exports = factory(); + } else { + root.nearley = factory(); + } + })(exports, function() { + function Rule2(name, symbols, postprocess) { + this.id = ++Rule2.highestId; + this.name = name; + this.symbols = symbols; + this.postprocess = postprocess; + return this; + } + Rule2.highestId = 0; + Rule2.prototype.toString = function(withCursorAt) { + var symbolSequence = typeof withCursorAt === "undefined" ? this.symbols.map(getSymbolShortDisplay).join(" ") : this.symbols.slice(0, withCursorAt).map(getSymbolShortDisplay).join(" ") + " \u25CF " + this.symbols.slice(withCursorAt).map(getSymbolShortDisplay).join(" "); + return this.name + " \u2192 " + symbolSequence; + }; + function State(rule, dot2, reference, wantedBy) { + this.rule = rule; + this.dot = dot2; + this.reference = reference; + this.data = []; + this.wantedBy = wantedBy; + this.isComplete = this.dot === rule.symbols.length; + } + State.prototype.toString = function() { + return "{" + this.rule.toString(this.dot) + "}, from: " + (this.reference || 0); + }; + State.prototype.nextState = function(child) { + var state = new State(this.rule, this.dot + 1, this.reference, this.wantedBy); + state.left = this; + state.right = child; + if (state.isComplete) { + state.data = state.build(); + state.right = void 0; + } + return state; + }; + State.prototype.build = function() { + var children = []; + var node = this; + do { + children.push(node.right.data); + node = node.left; + } while (node.left); + children.reverse(); + return children; + }; + State.prototype.finish = function() { + if (this.rule.postprocess) { + this.data = this.rule.postprocess(this.data, this.reference, Parser2.fail); + } + }; + function Column(grammar, index) { + this.grammar = grammar; + this.index = index; + this.states = []; + this.wants = {}; + this.scannable = []; + this.completed = {}; + } + Column.prototype.process = function(nextColumn) { + var states = this.states; + var wants = this.wants; + var completed = this.completed; + for (var w = 0; w < states.length; w++) { + var state = states[w]; + if (state.isComplete) { + state.finish(); + if (state.data !== Parser2.fail) { + var wantedBy = state.wantedBy; + for (var i = wantedBy.length; i--; ) { + var left = wantedBy[i]; + this.complete(left, state); + } + if (state.reference === this.index) { + var exp = state.rule.name; + (this.completed[exp] = this.completed[exp] || []).push(state); + } + } + } else { + var exp = state.rule.symbols[state.dot]; + if (typeof exp !== "string") { + this.scannable.push(state); + continue; + } + if (wants[exp]) { + wants[exp].push(state); + if (completed.hasOwnProperty(exp)) { + var nulls = completed[exp]; + for (var i = 0; i < nulls.length; i++) { + var right = nulls[i]; + this.complete(state, right); + } + } + } else { + wants[exp] = [state]; + this.predict(exp); + } + } + } + }; + Column.prototype.predict = function(exp) { + var rules = this.grammar.byName[exp] || []; + for (var i = 0; i < rules.length; i++) { + var r = rules[i]; + var wantedBy = this.wants[exp]; + var s = new State(r, 0, this.index, wantedBy); + this.states.push(s); + } + }; + Column.prototype.complete = function(left, right) { + var copy = left.nextState(right); + this.states.push(copy); + }; + function Grammar2(rules, start) { + this.rules = rules; + this.start = start || this.rules[0].name; + var byName = this.byName = {}; + this.rules.forEach(function(rule) { + if (!byName.hasOwnProperty(rule.name)) { + byName[rule.name] = []; + } + byName[rule.name].push(rule); + }); + } + Grammar2.fromCompiled = function(rules, start) { + var lexer2 = rules.Lexer; + if (rules.ParserStart) { + start = rules.ParserStart; + rules = rules.ParserRules; + } + var rules = rules.map(function(r) { + return new Rule2(r.name, r.symbols, r.postprocess); + }); + var g = new Grammar2(rules, start); + g.lexer = lexer2; + return g; + }; + function StreamLexer() { + this.reset(""); + } + StreamLexer.prototype.reset = function(data, state) { + this.buffer = data; + this.index = 0; + this.line = state ? state.line : 1; + this.lastLineBreak = state ? -state.col : 0; + }; + StreamLexer.prototype.next = function() { + if (this.index < this.buffer.length) { + var ch = this.buffer[this.index++]; + if (ch === "\n") { + this.line += 1; + this.lastLineBreak = this.index; + } + return { value: ch }; + } + }; + StreamLexer.prototype.save = function() { + return { + line: this.line, + col: this.index - this.lastLineBreak + }; + }; + StreamLexer.prototype.formatError = function(token, message) { + var buffer = this.buffer; + if (typeof buffer === "string") { + var lines = buffer.split("\n").slice( + Math.max(0, this.line - 5), + this.line + ); + var nextLineBreak = buffer.indexOf("\n", this.index); + if (nextLineBreak === -1) + nextLineBreak = buffer.length; + var col = this.index - this.lastLineBreak; + var lastLineDigits = String(this.line).length; + message += " at line " + this.line + " col " + col + ":\n\n"; + message += lines.map(function(line, i) { + return pad2(this.line - lines.length + i + 1, lastLineDigits) + " " + line; + }, this).join("\n"); + message += "\n" + pad2("", lastLineDigits + col) + "^\n"; + return message; + } else { + return message + " at index " + (this.index - 1); + } + function pad2(n, length) { + var s = String(n); + return Array(length - s.length + 1).join(" ") + s; + } + }; + function Parser2(rules, start, options) { + if (rules instanceof Grammar2) { + var grammar = rules; + var options = start; + } else { + var grammar = Grammar2.fromCompiled(rules, start); + } + this.grammar = grammar; + this.options = { + keepHistory: false, + lexer: grammar.lexer || new StreamLexer() + }; + for (var key in options || {}) { + this.options[key] = options[key]; + } + this.lexer = this.options.lexer; + this.lexerState = void 0; + var column = new Column(grammar, 0); + var table = this.table = [column]; + column.wants[grammar.start] = []; + column.predict(grammar.start); + column.process(); + this.current = 0; + } + Parser2.fail = {}; + Parser2.prototype.feed = function(chunk) { + var lexer2 = this.lexer; + lexer2.reset(chunk, this.lexerState); + var token; + while (true) { + try { + token = lexer2.next(); + if (!token) { + break; + } + } catch (e) { + var nextColumn = new Column(this.grammar, this.current + 1); + this.table.push(nextColumn); + var err = new Error(this.reportLexerError(e)); + err.offset = this.current; + err.token = e.token; + throw err; + } + var column = this.table[this.current]; + if (!this.options.keepHistory) { + delete this.table[this.current - 1]; + } + var n = this.current + 1; + var nextColumn = new Column(this.grammar, n); + this.table.push(nextColumn); + var literal = token.text !== void 0 ? token.text : token.value; + var value = lexer2.constructor === StreamLexer ? token.value : token; + var scannable = column.scannable; + for (var w = scannable.length; w--; ) { + var state = scannable[w]; + var expect = state.rule.symbols[state.dot]; + if (expect.test ? expect.test(value) : expect.type ? expect.type === token.type : expect.literal === literal) { + var next = state.nextState({ data: value, token, isToken: true, reference: n - 1 }); + nextColumn.states.push(next); + } + } + nextColumn.process(); + if (nextColumn.states.length === 0) { + var err = new Error(this.reportError(token)); + err.offset = this.current; + err.token = token; + throw err; + } + if (this.options.keepHistory) { + column.lexerState = lexer2.save(); + } + this.current++; + } + if (column) { + this.lexerState = lexer2.save(); + } + this.results = this.finish(); + return this; + }; + Parser2.prototype.reportLexerError = function(lexerError) { + var tokenDisplay, lexerMessage; + var token = lexerError.token; + if (token) { + tokenDisplay = "input " + JSON.stringify(token.text[0]) + " (lexer error)"; + lexerMessage = this.lexer.formatError(token, "Syntax error"); + } else { + tokenDisplay = "input (lexer error)"; + lexerMessage = lexerError.message; + } + return this.reportErrorCommon(lexerMessage, tokenDisplay); + }; + Parser2.prototype.reportError = function(token) { + var tokenDisplay = (token.type ? token.type + " token: " : "") + JSON.stringify(token.value !== void 0 ? token.value : token); + var lexerMessage = this.lexer.formatError(token, "Syntax error"); + return this.reportErrorCommon(lexerMessage, tokenDisplay); + }; + Parser2.prototype.reportErrorCommon = function(lexerMessage, tokenDisplay) { + var lines = []; + lines.push(lexerMessage); + var lastColumnIndex = this.table.length - 2; + var lastColumn = this.table[lastColumnIndex]; + var expectantStates = lastColumn.states.filter(function(state) { + var nextSymbol = state.rule.symbols[state.dot]; + return nextSymbol && typeof nextSymbol !== "string"; + }); + if (expectantStates.length === 0) { + lines.push("Unexpected " + tokenDisplay + ". I did not expect any more input. Here is the state of my parse table:\n"); + this.displayStateStack(lastColumn.states, lines); + } else { + lines.push("Unexpected " + tokenDisplay + ". Instead, I was expecting to see one of the following:\n"); + var stateStacks = expectantStates.map(function(state) { + return this.buildFirstStateStack(state, []) || [state]; + }, this); + stateStacks.forEach(function(stateStack) { + var state = stateStack[0]; + var nextSymbol = state.rule.symbols[state.dot]; + var symbolDisplay = this.getSymbolDisplay(nextSymbol); + lines.push("A " + symbolDisplay + " based on:"); + this.displayStateStack(stateStack, lines); + }, this); + } + lines.push(""); + return lines.join("\n"); + }; + Parser2.prototype.displayStateStack = function(stateStack, lines) { + var lastDisplay; + var sameDisplayCount = 0; + for (var j = 0; j < stateStack.length; j++) { + var state = stateStack[j]; + var display = state.rule.toString(state.dot); + if (display === lastDisplay) { + sameDisplayCount++; + } else { + if (sameDisplayCount > 0) { + lines.push(" ^ " + sameDisplayCount + " more lines identical to this"); + } + sameDisplayCount = 0; + lines.push(" " + display); + } + lastDisplay = display; + } + }; + Parser2.prototype.getSymbolDisplay = function(symbol) { + return getSymbolLongDisplay(symbol); + }; + Parser2.prototype.buildFirstStateStack = function(state, visited) { + if (visited.indexOf(state) !== -1) { + return null; + } + if (state.wantedBy.length === 0) { + return [state]; + } + var prevState = state.wantedBy[0]; + var childVisited = [state].concat(visited); + var childResult = this.buildFirstStateStack(prevState, childVisited); + if (childResult === null) { + return null; + } + return [state].concat(childResult); + }; + Parser2.prototype.save = function() { + var column = this.table[this.current]; + column.lexerState = this.lexerState; + return column; + }; + Parser2.prototype.restore = function(column) { + var index = column.index; + this.current = index; + this.table[index] = column; + this.table.splice(index + 1); + this.lexerState = column.lexerState; + this.results = this.finish(); + }; + Parser2.prototype.rewind = function(index) { + if (!this.options.keepHistory) { + throw new Error("set option `keepHistory` to enable rewinding"); + } + this.restore(this.table[index]); + }; + Parser2.prototype.finish = function() { + var considerations = []; + var start = this.grammar.start; + var column = this.table[this.table.length - 1]; + column.states.forEach(function(t) { + if (t.rule.name === start && t.dot === t.rule.symbols.length && t.reference === 0 && t.data !== Parser2.fail) { + considerations.push(t); + } + }); + return considerations.map(function(c) { + return c.data; + }); + }; + function getSymbolLongDisplay(symbol) { + var type = typeof symbol; + if (type === "string") { + return symbol; + } else if (type === "object") { + if (symbol.literal) { + return JSON.stringify(symbol.literal); + } else if (symbol instanceof RegExp) { + return "character matching " + symbol; + } else if (symbol.type) { + return symbol.type + " token"; + } else if (symbol.test) { + return "token matching " + String(symbol.test); + } else { + throw new Error("Unknown symbol type: " + symbol); + } + } + } + function getSymbolShortDisplay(symbol) { + var type = typeof symbol; + if (type === "string") { + return symbol; + } else if (type === "object") { + if (symbol.literal) { + return JSON.stringify(symbol.literal); + } else if (symbol instanceof RegExp) { + return symbol.toString(); + } else if (symbol.type) { + return "%" + symbol.type; + } else if (symbol.test) { + return "<" + String(symbol.test) + ">"; + } else { + throw new Error("Unknown symbol type: " + symbol); + } + } + } + return { + Parser: Parser2, + Grammar: Grammar2, + Rule: Rule2 + }; + }); + } +}); + +// ../../node_modules/moo/moo.js +var require_moo = __commonJS({ + "../../node_modules/moo/moo.js"(exports, module) { + (function(root, factory) { + if (typeof define === "function" && define.amd) { + define([], factory); + } else if (typeof module === "object" && module.exports) { + module.exports = factory(); + } else { + root.moo = factory(); + } + })(exports, function() { + "use strict"; + var hasOwnProperty = Object.prototype.hasOwnProperty; + var toString = Object.prototype.toString; + var hasSticky = typeof new RegExp().sticky === "boolean"; + function isRegExp(o) { + return o && toString.call(o) === "[object RegExp]"; + } + function isObject(o) { + return o && typeof o === "object" && !isRegExp(o) && !Array.isArray(o); + } + function reEscape(s) { + return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"); + } + function reGroups(s) { + var re = new RegExp("|" + s); + return re.exec("").length - 1; + } + function reCapture(s) { + return "(" + s + ")"; + } + function reUnion(regexps) { + if (!regexps.length) + return "(?!)"; + var source = regexps.map(function(s) { + return "(?:" + s + ")"; + }).join("|"); + return "(?:" + source + ")"; + } + function regexpOrLiteral(obj) { + if (typeof obj === "string") { + return "(?:" + reEscape(obj) + ")"; + } else if (isRegExp(obj)) { + if (obj.ignoreCase) + throw new Error("RegExp /i flag not allowed"); + if (obj.global) + throw new Error("RegExp /g flag is implied"); + if (obj.sticky) + throw new Error("RegExp /y flag is implied"); + if (obj.multiline) + throw new Error("RegExp /m flag is implied"); + return obj.source; + } else { + throw new Error("Not a pattern: " + obj); + } + } + function pad2(s, length) { + if (s.length > length) { + return s; + } + return Array(length - s.length + 1).join(" ") + s; + } + function lastNLines(string2, numLines) { + var position = string2.length; + var lineBreaks = 0; + while (true) { + var idx = string2.lastIndexOf("\n", position - 1); + if (idx === -1) { + break; + } else { + lineBreaks++; + } + position = idx; + if (lineBreaks === numLines) { + break; + } + if (position === 0) { + break; + } + } + var startPosition = lineBreaks < numLines ? 0 : position + 1; + return string2.substring(startPosition).split("\n"); + } + function objectToRules(object) { + var keys = Object.getOwnPropertyNames(object); + var result = []; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var thing = object[key]; + var rules = [].concat(thing); + if (key === "include") { + for (var j = 0; j < rules.length; j++) { + result.push({ include: rules[j] }); + } + continue; + } + var match = []; + rules.forEach(function(rule) { + if (isObject(rule)) { + if (match.length) + result.push(ruleOptions(key, match)); + result.push(ruleOptions(key, rule)); + match = []; + } else { + match.push(rule); + } + }); + if (match.length) + result.push(ruleOptions(key, match)); + } + return result; + } + function arrayToRules(array) { + var result = []; + for (var i = 0; i < array.length; i++) { + var obj = array[i]; + if (obj.include) { + var include = [].concat(obj.include); + for (var j = 0; j < include.length; j++) { + result.push({ include: include[j] }); + } + continue; + } + if (!obj.type) { + throw new Error("Rule has no type: " + JSON.stringify(obj)); + } + result.push(ruleOptions(obj.type, obj)); + } + return result; + } + function ruleOptions(type, obj) { + if (!isObject(obj)) { + obj = { match: obj }; + } + if (obj.include) { + throw new Error("Matching rules cannot also include states"); + } + var options = { + defaultType: type, + lineBreaks: !!obj.error || !!obj.fallback, + pop: false, + next: null, + push: null, + error: false, + fallback: false, + value: null, + type: null, + shouldThrow: false + }; + for (var key in obj) { + if (hasOwnProperty.call(obj, key)) { + options[key] = obj[key]; + } + } + if (typeof options.type === "string" && type !== options.type) { + throw new Error("Type transform cannot be a string (type '" + options.type + "' for token '" + type + "')"); + } + var match = options.match; + options.match = Array.isArray(match) ? match : match ? [match] : []; + options.match.sort(function(a, b) { + return isRegExp(a) && isRegExp(b) ? 0 : isRegExp(b) ? -1 : isRegExp(a) ? 1 : b.length - a.length; + }); + return options; + } + function toRules(spec) { + return Array.isArray(spec) ? arrayToRules(spec) : objectToRules(spec); + } + var defaultErrorRule = ruleOptions("error", { lineBreaks: true, shouldThrow: true }); + function compileRules(rules, hasStates) { + var errorRule = null; + var fast = /* @__PURE__ */ Object.create(null); + var fastAllowed = true; + var unicodeFlag = null; + var groups = []; + var parts = []; + for (var i = 0; i < rules.length; i++) { + if (rules[i].fallback) { + fastAllowed = false; + } + } + for (var i = 0; i < rules.length; i++) { + var options = rules[i]; + if (options.include) { + throw new Error("Inheritance is not allowed in stateless lexers"); + } + if (options.error || options.fallback) { + if (errorRule) { + if (!options.fallback === !errorRule.fallback) { + throw new Error("Multiple " + (options.fallback ? "fallback" : "error") + " rules not allowed (for token '" + options.defaultType + "')"); + } else { + throw new Error("fallback and error are mutually exclusive (for token '" + options.defaultType + "')"); + } + } + errorRule = options; + } + var match = options.match.slice(); + if (fastAllowed) { + while (match.length && typeof match[0] === "string" && match[0].length === 1) { + var word2 = match.shift(); + fast[word2.charCodeAt(0)] = options; + } + } + if (options.pop || options.push || options.next) { + if (!hasStates) { + throw new Error("State-switching options are not allowed in stateless lexers (for token '" + options.defaultType + "')"); + } + if (options.fallback) { + throw new Error("State-switching options are not allowed on fallback tokens (for token '" + options.defaultType + "')"); + } + } + if (match.length === 0) { + continue; + } + fastAllowed = false; + groups.push(options); + for (var j = 0; j < match.length; j++) { + var obj = match[j]; + if (!isRegExp(obj)) { + continue; + } + if (unicodeFlag === null) { + unicodeFlag = obj.unicode; + } else if (unicodeFlag !== obj.unicode && options.fallback === false) { + throw new Error("If one rule is /u then all must be"); + } + } + var pat = reUnion(match.map(regexpOrLiteral)); + var regexp = new RegExp(pat); + if (regexp.test("")) { + throw new Error("RegExp matches empty string: " + regexp); + } + var groupCount = reGroups(pat); + if (groupCount > 0) { + throw new Error("RegExp has capture groups: " + regexp + "\nUse (?: \u2026 ) instead"); + } + if (!options.lineBreaks && regexp.test("\n")) { + throw new Error("Rule should declare lineBreaks: " + regexp); + } + parts.push(reCapture(pat)); + } + var fallbackRule = errorRule && errorRule.fallback; + var flags = hasSticky && !fallbackRule ? "ym" : "gm"; + var suffix = hasSticky || fallbackRule ? "" : "|"; + if (unicodeFlag === true) + flags += "u"; + var combined = new RegExp(reUnion(parts) + suffix, flags); + return { regexp: combined, groups, fast, error: errorRule || defaultErrorRule }; + } + function compile(rules) { + var result = compileRules(toRules(rules)); + return new Lexer2({ start: result }, "start"); + } + function checkStateGroup(g, name, map) { + var state = g && (g.push || g.next); + if (state && !map[state]) { + throw new Error("Missing state '" + state + "' (in token '" + g.defaultType + "' of state '" + name + "')"); + } + if (g && g.pop && +g.pop !== 1) { + throw new Error("pop must be 1 (in token '" + g.defaultType + "' of state '" + name + "')"); + } + } + function compileStates(states, start) { + var all = states.$all ? toRules(states.$all) : []; + delete states.$all; + var keys = Object.getOwnPropertyNames(states); + if (!start) + start = keys[0]; + var ruleMap = /* @__PURE__ */ Object.create(null); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + ruleMap[key] = toRules(states[key]).concat(all); + } + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var rules = ruleMap[key]; + var included = /* @__PURE__ */ Object.create(null); + for (var j = 0; j < rules.length; j++) { + var rule = rules[j]; + if (!rule.include) + continue; + var splice = [j, 1]; + if (rule.include !== key && !included[rule.include]) { + included[rule.include] = true; + var newRules = ruleMap[rule.include]; + if (!newRules) { + throw new Error("Cannot include nonexistent state '" + rule.include + "' (in state '" + key + "')"); + } + for (var k = 0; k < newRules.length; k++) { + var newRule = newRules[k]; + if (rules.indexOf(newRule) !== -1) + continue; + splice.push(newRule); + } + } + rules.splice.apply(rules, splice); + j--; + } + } + var map = /* @__PURE__ */ Object.create(null); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + map[key] = compileRules(ruleMap[key], true); + } + for (var i = 0; i < keys.length; i++) { + var name = keys[i]; + var state = map[name]; + var groups = state.groups; + for (var j = 0; j < groups.length; j++) { + checkStateGroup(groups[j], name, map); + } + var fastKeys = Object.getOwnPropertyNames(state.fast); + for (var j = 0; j < fastKeys.length; j++) { + checkStateGroup(state.fast[fastKeys[j]], name, map); + } + } + return new Lexer2(map, start); + } + function keywordTransform(map) { + var isMap = typeof Map !== "undefined"; + var reverseMap = isMap ? /* @__PURE__ */ new Map() : /* @__PURE__ */ Object.create(null); + var types = Object.getOwnPropertyNames(map); + for (var i = 0; i < types.length; i++) { + var tokenType = types[i]; + var item = map[tokenType]; + var keywordList = Array.isArray(item) ? item : [item]; + keywordList.forEach(function(keyword) { + if (typeof keyword !== "string") { + throw new Error("keyword must be string (in keyword '" + tokenType + "')"); + } + if (isMap) { + reverseMap.set(keyword, tokenType); + } else { + reverseMap[keyword] = tokenType; + } + }); + } + return function(k) { + return isMap ? reverseMap.get(k) : reverseMap[k]; + }; + } + var Lexer2 = function(states, state) { + this.startState = state; + this.states = states; + this.buffer = ""; + this.stack = []; + this.reset(); + }; + Lexer2.prototype.reset = function(data, info) { + this.buffer = data || ""; + this.index = 0; + this.line = info ? info.line : 1; + this.col = info ? info.col : 1; + this.queuedToken = info ? info.queuedToken : null; + this.queuedText = info ? info.queuedText : ""; + this.queuedThrow = info ? info.queuedThrow : null; + this.setState(info ? info.state : this.startState); + this.stack = info && info.stack ? info.stack.slice() : []; + return this; + }; + Lexer2.prototype.save = function() { + return { + line: this.line, + col: this.col, + state: this.state, + stack: this.stack.slice(), + queuedToken: this.queuedToken, + queuedText: this.queuedText, + queuedThrow: this.queuedThrow + }; + }; + Lexer2.prototype.setState = function(state) { + if (!state || this.state === state) + return; + this.state = state; + var info = this.states[state]; + this.groups = info.groups; + this.error = info.error; + this.re = info.regexp; + this.fast = info.fast; + }; + Lexer2.prototype.popState = function() { + this.setState(this.stack.pop()); + }; + Lexer2.prototype.pushState = function(state) { + this.stack.push(this.state); + this.setState(state); + }; + var eat = hasSticky ? function(re, buffer) { + return re.exec(buffer); + } : function(re, buffer) { + var match = re.exec(buffer); + if (match[0].length === 0) { + return null; + } + return match; + }; + Lexer2.prototype._getGroup = function(match) { + var groupCount = this.groups.length; + for (var i = 0; i < groupCount; i++) { + if (match[i + 1] !== void 0) { + return this.groups[i]; + } + } + throw new Error("Cannot find token type for matched text"); + }; + function tokenToString() { + return this.value; + } + Lexer2.prototype.next = function() { + var index = this.index; + if (this.queuedGroup) { + var token = this._token(this.queuedGroup, this.queuedText, index); + this.queuedGroup = null; + this.queuedText = ""; + return token; + } + var buffer = this.buffer; + if (index === buffer.length) { + return; + } + var group = this.fast[buffer.charCodeAt(index)]; + if (group) { + return this._token(group, buffer.charAt(index), index); + } + var re = this.re; + re.lastIndex = index; + var match = eat(re, buffer); + var error = this.error; + if (match == null) { + return this._token(error, buffer.slice(index, buffer.length), index); + } + var group = this._getGroup(match); + var text = match[0]; + if (error.fallback && match.index !== index) { + this.queuedGroup = group; + this.queuedText = text; + return this._token(error, buffer.slice(index, match.index), index); + } + return this._token(group, text, index); + }; + Lexer2.prototype._token = function(group, text, offset) { + var lineBreaks = 0; + if (group.lineBreaks) { + var matchNL = /\n/g; + var nl = 1; + if (text === "\n") { + lineBreaks = 1; + } else { + while (matchNL.exec(text)) { + lineBreaks++; + nl = matchNL.lastIndex; + } + } + } + var token = { + type: typeof group.type === "function" && group.type(text) || group.defaultType, + value: typeof group.value === "function" ? group.value(text) : text, + text, + toString: tokenToString, + offset, + lineBreaks, + line: this.line, + col: this.col + }; + var size = text.length; + this.index += size; + this.line += lineBreaks; + if (lineBreaks !== 0) { + this.col = size - nl + 1; + } else { + this.col += size; + } + if (group.shouldThrow) { + var err = new Error(this.formatError(token, "invalid syntax")); + throw err; + } + if (group.pop) + this.popState(); + else if (group.push) + this.pushState(group.push); + else if (group.next) + this.setState(group.next); + return token; + }; + if (typeof Symbol !== "undefined" && Symbol.iterator) { + var LexerIterator = function(lexer2) { + this.lexer = lexer2; + }; + LexerIterator.prototype.next = function() { + var token = this.lexer.next(); + return { value: token, done: !token }; + }; + LexerIterator.prototype[Symbol.iterator] = function() { + return this; + }; + Lexer2.prototype[Symbol.iterator] = function() { + return new LexerIterator(this); + }; + } + Lexer2.prototype.formatError = function(token, message) { + if (token == null) { + var text = this.buffer.slice(this.index); + var token = { + text, + offset: this.index, + lineBreaks: text.indexOf("\n") === -1 ? 0 : 1, + line: this.line, + col: this.col + }; + } + var numLinesAround = 2; + var firstDisplayedLine = Math.max(token.line - numLinesAround, 1); + var lastDisplayedLine = token.line + numLinesAround; + var lastLineDigits = String(lastDisplayedLine).length; + var displayedLines = lastNLines( + this.buffer, + this.line - token.line + numLinesAround + 1 + ).slice(0, 5); + var errorLines = []; + errorLines.push(message + " at line " + token.line + " col " + token.col + ":"); + errorLines.push(""); + for (var i = 0; i < displayedLines.length; i++) { + var line = displayedLines[i]; + var lineNo = firstDisplayedLine + i; + errorLines.push(pad2(String(lineNo), lastLineDigits) + " " + line); + if (lineNo === token.line) { + errorLines.push(pad2("", lastLineDigits + token.col + 1) + "^"); + } + } + return errorLines.join("\n"); + }; + Lexer2.prototype.clone = function() { + return new Lexer2(this.states, this.state); + }; + Lexer2.prototype.has = function(tokenType) { + return true; + }; + return { + compile, + states: compileStates, + error: Object.freeze({ error: true }), + fallback: Object.freeze({ fallback: true }), + keywords: keywordTransform + }; + }); + } +}); + +// src/error.ts +var isPublicodesError = (error, name) => error instanceof PublicodesError && (name === void 0 ? true : error.name === name); +var PublicodesError = class extends Error { + name; + info; + constructor(name, message, info, originalError) { + super(buildMessage(name, message, info, originalError)); + this.name = name; + this.info = info; + } +}; +var buildMessage = (name, message, info, originalError) => { + const types = { + SyntaxError: "Erreur syntaxique", + EvaluationError: "Erreur d'\xE9valuation", + UnknownRule: "R\xE8gle inconnue", + PrivateRule: "R\xE8gle priv\xE9e" + }; + const isError = /error/i.test(name); + return ` +[ ${types[name] ?? name} ]` + (info && "dottedName" in info && info.dottedName?.length ? ` +\u27A1\uFE0F Dans la r\xE8gle "${info.dottedName}"` : "") + ` +${isError ? "\u2716\uFE0F" : "\u26A0\uFE0F"} ${message}` + (originalError ? "\n" + (isError ? " " : "\u2139\uFE0F ") + originalError.message : ""); +}; +var PublicodesInternalError = class extends PublicodesError { + constructor(payload) { + super( + "InternalError", + ` +Erreur interne du moteur. + +Cette erreur est le signe d'un bug dans publicodes. Pour nous aider \xE0 le r\xE9soudre, vous pouvez copier ce texte dans un nouveau ticket : https://github.com/betagouv/mon-entreprise/issues/new. + +payload: +${JSON.stringify(payload, null, 2)} +`, + payload + ); + } +}; +var UnreachableCaseError = class extends PublicodesInternalError { + constructor(value) { + super(value); + } +}; +function warning(logger, message, information, originalError) { + logger.warn( + buildMessage("Avertissement", message, information, originalError) + ); +} +function experimentalRuleWarning(logger, dottedName) { + logger.warn( + buildMessage( + "Avertissement", + "Cette r\xE8gle est taggu\xE9e comme experimentale. \n\nCela veut dire qu'elle peut \xEAtre modifi\xE9e, renomm\xE9e, ou supprim\xE9e sans qu'il n'y ait de changement de version majeure dans l'API.\n", + { dottedName } + ) + ); +} + +// src/utils.ts +function addToMapSet(map, key, value) { + if (map.has(key)) { + map.get(key).add(value); + return; + } + map.set(key, /* @__PURE__ */ new Set([value])); +} +function mergeWithArray(obj1, obj2) { + return Object.entries(obj2).reduce( + (obj, [key, value]) => ({ + ...obj, + [key]: [...obj[key] ?? [], ...value] + }), + obj1 + ); +} +var weakCopyObj = (obj) => { + const copy = {}; + for (const key in obj) { + copy[key] = obj[key]; + } + return copy; +}; + +// src/AST/index.ts +function makeASTTransformer(fn, stopOnUpdate = true) { + function transform(node) { + const updatedNode = fn(node, transform); + if (updatedNode === false) { + return node; + } + if (updatedNode === void 0) { + return traverseASTNode(transform, node); + } + return stopOnUpdate ? updatedNode : traverseASTNode(transform, updatedNode); + } + return transform; +} +function makeASTVisitor(fn) { + function visit(node) { + switch (fn(node, visit)) { + case "continue": + traverseASTNode(transformizedVisit, node); + return; + case "stop": + return; + } + } + const transformizedVisit = (node) => { + visit(node); + return node; + }; + return visit; +} +function reduceAST(fn, start, node) { + function traverseFn(acc, node2) { + const result = fn(acc, node2, traverseFn.bind(null, start)); + if (result === void 0) { + return getChildrenNodes(node2).reduce(traverseFn, acc); + } + return result; + } + return traverseFn(start, node); +} +function getChildrenNodes(node) { + const nodes = []; + traverseASTNode((node2) => { + nodes.push(node2); + return node2; + }, node); + return nodes; +} +function traverseParsedRules(fn, parsedRules) { + const ret = {}; + for (const name in parsedRules) { + ret[name] = fn(parsedRules[name]); + } + return ret; +} +var traverseASTNode = (fn, node) => { + node = traverseSourceMap(fn, node); + switch (node.nodeKind) { + case "rule": + return traverseRuleNode(fn, node); + case "reference": + case "constant": + return node; + case "arrondi": + return traverseArrondiNode(fn, node); + case "simplifier unit\xE9": + case "variable manquante": + case "est non applicable": + case "est non d\xE9fini": + return traverseUnaryOperationNode(fn, node); + case "bar\xE8me": + case "taux progressif": + case "grille": + return traverseNodeWithTranches(fn, node); + case "une possibilit\xE9": + return traverseArrayNode(fn, node); + case "dur\xE9e": + return traverseDur\u00E9eNode(fn, node); + case "r\xE9soudre r\xE9f\xE9rence circulaire": + return traverseR\u00E9soudreR\u00E9f\u00E9renceCirculaireNode(fn, node); + case "inversion": + return traverseInversionNode(fn, node); + case "operation": + return traverseOperationNode(fn, node); + case "contexte": + return traverseContexteNode(fn, node); + case "unit\xE9": + return traverseUnit\u00E9Node(fn, node); + case "variations": + return traverseVariationNode(fn, node); + case "replacementRule": + return traverseReplacementNode(fn, node); + case "texte": + return traverseTextNode(fn, node); + case "condition": + return traverseConditionNode(fn, node); + default: + throw new UnreachableCaseError(node); + } +}; +var traverseSourceMap = (fn, node) => { + if (!("sourceMap" in node) || !node.sourceMap || !node.sourceMap.args) { + return node; + } + const sourceMap = node.sourceMap; + const args = {}; + for (const key in sourceMap.args) { + const value = sourceMap.args[key]; + args[key] = Array.isArray(value) ? value.map((v) => fn(v)) : fn(value); + } + return { + ...node, + sourceMap: { + ...sourceMap, + args + } + }; +}; +var traverseRuleNode = (fn, node) => { + const copy = weakCopyObj(node); + copy.suggestions = {}; + for (const key in node.suggestions) { + copy.suggestions[key] = fn(node.suggestions[key]); + } + copy.replacements = node.replacements.map(fn); + copy.explanation = { + ruleDisabledByItsParent: node.explanation.ruleDisabledByItsParent, + nullableParent: node.explanation.nullableParent ? fn(node.explanation.nullableParent) : void 0, + parents: node.explanation.parents.map(fn), + valeur: fn(node.explanation.valeur) + }; + return copy; +}; +var traverseReplacementNode = (fn, node) => ({ + ...node, + definitionRule: fn(node.definitionRule), + replacedReference: fn(node.replacedReference), + whiteListedNames: node.whiteListedNames.map(fn), + blackListedNames: node.blackListedNames.map(fn) +}); +var traverseUnaryOperationNode = (fn, node) => ({ + ...node, + explanation: fn(node.explanation) +}); +function traverseTranche(fn, tranches) { + return tranches.map((tranche) => ({ + ...tranche, + ...tranche.plafond && { plafond: fn(tranche.plafond) }, + ..."montant" in tranche && { montant: fn(tranche.montant) }, + ..."taux" in tranche && { taux: fn(tranche.taux) } + })); +} +var traverseNodeWithTranches = (fn, node) => ({ + ...node, + explanation: { + assiette: fn(node.explanation.assiette), + multiplicateur: fn(node.explanation.multiplicateur), + tranches: traverseTranche(fn, node.explanation.tranches) + } +}); +var traverseArrayNode = (fn, node) => ({ + ...node, + explanation: node.explanation.map(fn) +}); +var traverseOperationNode = (fn, node) => { + const copy = weakCopyObj(node); + copy.explanation = [fn(node.explanation[0]), fn(node.explanation[1])]; + return copy; +}; +var traverseDur\u00E9eNode = (fn, node) => ({ + ...node, + explanation: { + depuis: fn(node.explanation.depuis), + "jusqu'\xE0": fn(node.explanation["jusqu'\xE0"]) + } +}); +var traverseInversionNode = (fn, node) => ({ + ...node, + explanation: { + ...node.explanation, + inversionCandidates: node.explanation.inversionCandidates.map(fn) + // TODO + } +}); +var traverseArrondiNode = (fn, node) => ({ + ...node, + explanation: { + valeur: fn(node.explanation.valeur), + arrondi: fn(node.explanation.arrondi) + } +}); +var traverseR\u00E9soudreR\u00E9f\u00E9renceCirculaireNode = (fn, node) => ({ + ...node, + explanation: { + ...node.explanation, + valeur: fn(node.explanation.valeur) + } +}); +var traverseTextNode = (fn, node) => ({ + ...node, + explanation: node.explanation.map( + (element) => typeof element === "string" ? element : fn(element) + ) +}); +var traverseContexteNode = (fn, node) => ({ + ...node, + explanation: { + ...node.explanation, + contexte: node.explanation.contexte.map(([name, value]) => [ + fn(name), + fn(value) + ]), + valeur: fn(node.explanation.valeur) + } +}); +var traverseUnit\u00E9Node = (fn, node) => { + const copy = weakCopyObj(node); + copy.explanation = fn(node.explanation); + return copy; +}; +var traverseVariationNode = (fn, node) => ({ + ...node, + explanation: node.explanation.map(({ condition, consequence }) => ({ + condition: fn(condition), + consequence: consequence && fn(consequence) + })) +}); +var traverseConditionNode = (fn, node) => { + const copy = weakCopyObj(node); + copy.explanation = { + si: fn(node.explanation.si), + alors: fn(node.explanation.alors), + sinon: fn(node.explanation.sinon) + }; + return copy; +}; + +// src/evaluationFunctions.ts +var evaluationFunctions = { + constant: (node) => node +}; +function registerEvaluationFunction(nodeKind, evaluationFunction) { + evaluationFunctions ??= {}; + if (evaluationFunctions[nodeKind]) { + throw new PublicodesError( + "EvaluationError", + `Multiple evaluation functions registered for the nodeKind \x1B[4m${nodeKind}`, + { dottedName: "" } + ); + } + evaluationFunctions[nodeKind] = evaluationFunction; +} + +// src/inferNodeType.ts +var UNDEFINED_TYPE = { + isNullable: void 0, + type: void 0 +}; +function inferNodesTypes(newRulesNames, parsedRules, nodesTypes) { + function inferNodeUnitAndCache(node) { + if (!node || typeof node !== "object") { + return UNDEFINED_TYPE; + } + if (nodesTypes.has(node)) { + return nodesTypes.get(node); + } + nodesTypes.set(node, UNDEFINED_TYPE); + const type = inferNodeType(node); + nodesTypes.set(node, type); + return type; + } + function inferNodeType(node) { + switch (node.nodeKind) { + case "bar\xE8me": + case "dur\xE9e": + case "grille": + case "taux progressif": + return { isNullable: false, type: "number" }; + case "est non d\xE9fini": + case "est non applicable": + return { isNullable: false, type: "boolean" }; + case "constant": + return { + isNullable: node.isNullable ?? node.nodeValue === null, + type: node.type + }; + case "operation": + return { + isNullable: ["<", "<=", ">", ">=", "/", "*"].includes(node.operationKind) ? inferNodeUnitAndCache(node.explanation[0]).isNullable || inferNodeUnitAndCache(node.explanation[1]).isNullable : node.operationKind === "-" ? inferNodeUnitAndCache(node.explanation[0]).isNullable : false, + type: ["<", "<=", ">", ">=", "=", "!=", "et", "ou"].includes( + node.operationKind + ) ? "boolean" : "number" + }; + case "inversion": + case "replacementRule": + case "r\xE9soudre r\xE9f\xE9rence circulaire": + return { isNullable: false, type: "number" }; + case "texte": + case "une possibilit\xE9": + return { isNullable: false, type: "string" }; + case "contexte": + case "rule": + case "arrondi": + return inferNodeUnitAndCache(node.explanation.valeur); + case "unit\xE9": + case "simplifier unit\xE9": + case "variable manquante": + return inferNodeUnitAndCache(node.explanation); + case "condition": + return { + isNullable: [ + node.explanation.si, + node.explanation.alors, + node.explanation.sinon + ].some((n) => inferNodeUnitAndCache(n).isNullable), + type: inferNodeUnitAndCache(node.explanation.alors).type ?? inferNodeUnitAndCache(node.explanation.sinon).type + }; + case "variations": { + const consequencesTypes = node.explanation.map( + ({ consequence }) => inferNodeUnitAndCache(consequence) + ); + return { + isNullable: consequencesTypes.some( + (consequence) => consequence.isNullable + ), + type: consequencesTypes.map((c) => c.type).find((type) => type !== void 0) + }; + } + case "reference": + return inferNodeUnitAndCache(parsedRules[node.dottedName]); + } + } + newRulesNames.forEach((name) => { + const rule = parsedRules[name]; + inferNodeUnitAndCache(rule); + rule.explanation.parents.forEach(inferNodeUnitAndCache); + }); + return nodesTypes; +} + +// src/evaluationUtils.ts +var collectNodeMissing = (node) => "missingVariables" in node ? node.missingVariables : {}; +var bonus = (missings = {}) => Object.fromEntries( + Object.entries(missings).map(([key, value]) => [key, value + 1]) +); +var mergeMissing = (left = {}, right = {}) => Object.fromEntries( + [...Object.keys(left), ...Object.keys(right)].map((key) => [ + key, + (left[key] ?? 0) + (right[key] ?? 0) + ]) +); +var mergeAllMissing = (missings) => missings.map(collectNodeMissing).reduce(mergeMissing, {}); +var defaultNode = (nodeValue) => ({ + nodeValue, + type: typeof nodeValue, + isDefault: true, + nodeKind: "constant" +}); +var notApplicableNode = { + nodeKind: "constant", + nodeValue: null, + missingVariables: {}, + type: void 0, + isNullable: true +}; +var undefinedNode = { + nodeKind: "constant", + nodeValue: void 0, + missingVariables: {}, + type: void 0, + isNullable: false +}; +var undefinedNumberNode = { + ...undefinedNode, + type: "number" +}; + +// src/mecanisms/inlineMecanism.ts +function createParseInlinedMecanism(name, args, body) { + let parsedBody; + let parsedDefaultArgs; + function parseInlineMecanism(providedArgs, context) { + parsedBody ??= parse(body, createContext({ dottedName: "INLINE_MECANISM" })); + parsedDefaultArgs ??= {}; + for (const name2 in args) { + if ("par d\xE9faut" in args[name2]) { + parsedDefaultArgs[name2] = parse( + args[name2]["par d\xE9faut"], + createContext({}) + ); + } + } + if (Object.keys(args).length === 1 && "valeur" in args) { + providedArgs = { + valeur: providedArgs + }; + } + const parsedProvidedArgs = {}; + for (const name2 in providedArgs) { + parsedProvidedArgs[name2] = parse(providedArgs[name2], context); + } + const parsedInlineMecanism = makeASTTransformer((node) => { + if (node.nodeKind !== "reference" || !(node.name in args)) { + return; + } + const argName = node.name; + if (argName in parsedProvidedArgs) { + return parsedProvidedArgs[argName]; + } + if (argName in parsedDefaultArgs) { + return parsedDefaultArgs[argName]; + } + throw new PublicodesError( + "SyntaxError", + `Il manque la cl\xE9 '${argName} dans le m\xE9canisme ${name}`, + { dottedName: argName } + ); + })(parsedBody); + parsedInlineMecanism.sourceMap = { + mecanismName: name, + args: parsedProvidedArgs + }; + return parsedInlineMecanism; + } + parseInlineMecanism.nom = name; + return Object.assign(parseInlineMecanism, "name", { + value: `parse${toCamelCase(name)}Inline` + }); +} +function createParseInlinedMecanismWithArray(name, args, body) { + function parseInlineMecanism(providedArgs, context) { + if (Object.keys(args).length === 1 && "valeur" in args) { + providedArgs = { + valeur: providedArgs + }; + } + const parsedProvidedArgs = {}; + for (const name2 in providedArgs) { + const value = providedArgs[name2]; + parsedProvidedArgs[name2] = Array.isArray(value) ? value.map((v) => parse(v, context)) : parse(value, context); + } + const parsedInlineMecanism = parse(body(parsedProvidedArgs), context); + parsedInlineMecanism.sourceMap = { + mecanismName: name, + args: parsedProvidedArgs + }; + return parsedInlineMecanism; + } + parseInlineMecanism.nom = name; + return Object.assign(parseInlineMecanism, "name", { + value: `parse${toCamelCase(name)}Inline` + }); +} +function toCamelCase(str) { + return str.replace(/(?:^\w|[A-Z]|\b\w)/g, (ltr) => ltr.toUpperCase()).replace(/\s+/g, ""); +} + +// src/mecanisms/abattement.ts +var abattement_default = createParseInlinedMecanism( + "abattement", + { + abattement: {}, + valeur: {} + }, + { + "-": ["valeur", "abattement"], + plancher: 0 + } +); + +// src/mecanisms/applicable.ts +var applicable_default = createParseInlinedMecanism( + "applicable si", + { + "applicable si": {}, + valeur: {} + }, + { + condition: { + si: "applicable si != non", + alors: "valeur", + sinon: notApplicableNode + } + } +); + +// src/units.ts +var parseUnit = (string2, getUnitKey = (x) => x) => { + if (string2.includes(" /") || string2.includes("/ ")) { + throw new Error( + `L'unit\xE9 "${string2}" ne doit pas contenir d'espace avant et apr\xE8s "/"` + ); + } + const [a, ...b] = string2.split("/"); + const splitUnit = (string3) => decomposePower( + string3.split(".").filter(Boolean).map((unit) => getUnitKey(unit)) + ); + const result = { + numerators: splitUnit(a), + denominators: b.flatMap((u) => splitUnit(u)) + }; + return result; +}; +var lastNumberFromString = /(\d+)(?!.*[A-Za-z])/g; +function getUnitCounts(baseUnits) { + const countUnits = {}; + baseUnits.forEach((e) => { + const powerMatch = e.match(lastNumberFromString); + if (powerMatch != null) { + const power = powerMatch[0]; + const primaryUnit = e.split(power)[0]; + countUnits[primaryUnit] = (countUnits[primaryUnit] ?? 0) + +power; + } else { + countUnits[e] = (countUnits[e] ?? 0) + 1; + } + }); + return countUnits; +} +function decomposePower(baseUnits) { + const unitCounts = getUnitCounts(baseUnits); + return Object.entries(unitCounts).flatMap( + ([primaryUnit, power]) => Array(power).fill(primaryUnit) + ); +} +function combinePower(baseUnit) { + const unitCounts = getUnitCounts(baseUnit); + return Object.entries(unitCounts).map( + ([primaryUnit, power]) => power > 1 ? `${primaryUnit}${power}` : primaryUnit + ); +} +var printUnits = (units, count, formatUnit2 = (x) => x) => { + return combinePower(units.map((unit) => formatUnit2(unit, count))).join("."); +}; +var plural = 2; +function serializeUnit(rawUnit, count = plural, formatUnit2 = (x) => x) { + if (rawUnit === null || typeof rawUnit !== "object") { + return typeof rawUnit === "string" ? formatUnit2(rawUnit, count) : rawUnit; + } + const unit = simplify(rawUnit); + const { numerators = [], denominators = [] } = unit; + const n = numerators.length > 0; + const d = denominators.length > 0; + const string2 = !n && !d ? "" : n && !d ? printUnits(numerators, count, formatUnit2) : !n && d ? `/${printUnits(denominators, 1, formatUnit2)}` : `${printUnits(numerators, plural, formatUnit2)}/${printUnits( + denominators, + 1, + formatUnit2 + )}`; + return string2; +} +var noUnit = { numerators: [], denominators: [] }; +var inferUnit = (operator, rawUnits) => { + if (operator === "/") { + if (rawUnits.length !== 2) { + throw new PublicodesError( + "InternalError", + "Infer units of a division with units.length !== 2)", + {} + ); + } + return inferUnit("*", [ + rawUnits[0] || noUnit, + { + numerators: (rawUnits[1] || noUnit).denominators, + denominators: (rawUnits[1] || noUnit).numerators + } + ]); + } + const units = rawUnits.filter(Boolean); + if (units.length <= 1) { + return units[0]; + } + if (operator === "*") + return simplify({ + numerators: units.flatMap((u) => u?.numerators ?? []), + denominators: units.flatMap((u) => u?.denominators ?? []) + }); + if (operator === "-" || operator === "+") { + return rawUnits.find((u) => u); + } + return void 0; +}; +var equals = (a, b) => { + if (Array.isArray(a) && Array.isArray(b)) { + return a.length === b.length && a.every((_, i) => a[i] === b[i]); + } else { + return a === b; + } +}; +var removeOnce = (element, eqFn = equals) => (list) => { + const index = list.findIndex((e) => eqFn(e, element)); + return list.filter((_, i) => i !== index); +}; +var simplify = (unit, eqFn = equals) => { + const simplifiedUnit = [...unit.numerators, ...unit.denominators].reduce( + ({ numerators, denominators }, next) => numerators.find((u) => eqFn(next, u)) && denominators.find((u) => eqFn(next, u)) ? { + numerators: removeOnce(next, eqFn)(numerators), + denominators: removeOnce(next, eqFn)(denominators) + } : { numerators, denominators }, + unit + ); + return simplifiedUnit; +}; +var convertTable = { + "mois/an": 12, + "jour/an": 365, + "jour/mois": 365 / 12, + "trimestre/an": 4, + "mois/trimestre": 3, + "jour/trimestre": 365 / 12 * 3, + "\u20AC/k\u20AC": 10 ** 3, + "g/kg": 10 ** 3, + "mg/g": 10 ** 3, + "mg/kg": 10 ** 6, + "m/km": 10 ** 3, + "cm/m": 10 ** 2, + "mm/cm": 10 ** 1, + "mm/m": 10 ** 3, + "cm/km": 10 ** 5, + "mm/km": 10 ** 6 +}; +function singleUnitConversionFactor(from, to) { + return convertTable[`${to}/${from}`] || convertTable[`${from}/${to}`] && 1 / convertTable[`${from}/${to}`]; +} +function unitsConversionFactor(from, to) { + let factor = 100 ** // Factor is mutliplied or divided 100 for each '%' in units + (to.filter((unit) => unit === "%").length - from.filter((unit) => unit === "%").length); + [factor] = from.reduce( + ([value, toUnits], fromUnit) => { + const index = toUnits.findIndex( + (toUnit) => !!singleUnitConversionFactor(fromUnit, toUnit) + ); + const factor2 = singleUnitConversionFactor(fromUnit, toUnits[index]) || 1; + return [ + value * factor2, + [...toUnits.slice(0, index + 1), ...toUnits.slice(index + 1)] + ]; + }, + [factor, to] + ); + return factor; +} +var equivalentTable = { + "kW.h": "kWh", + "mn/h": "noeud" +}; +function areEquivalentSerializedUnit(serializedFrom, serializedTo) { + if (!serializedFrom || !serializedTo) + return false; + return serializedFrom === serializedTo || serializedFrom === equivalentTable[serializedTo] || serializedTo === equivalentTable[serializedFrom]; +} +function convertUnit(from, to, value) { + const serializedFrom = serializeUnit(from); + const serializedTo = serializeUnit(to); + if (!areEquivalentSerializedUnit(serializedFrom, serializedTo) && !areUnitConvertible(from, to)) { + throw new PublicodesError( + "EngineError", + `Impossible de convertir l'unit\xE9 '${serializedFrom}' en '${serializedTo}'`, + {} + ); + } + if (!value) { + return value; + } + if (from === void 0) { + return value; + } + const [fromSimplified, factorTo] = simplifyUnitWithValue(from || noUnit); + const [toSimplified, factorFrom] = simplifyUnitWithValue(to || noUnit); + return round( + value * factorTo / factorFrom * unitsConversionFactor( + fromSimplified.numerators, + toSimplified.numerators + ) * unitsConversionFactor( + toSimplified.denominators, + fromSimplified.denominators + ) + ); +} +var convertibleUnitClasses = unitClasses(convertTable); +function unitClasses(convertTable2) { + return Object.keys(convertTable2).reduce( + (classes, ratio) => { + const [a, b] = ratio.split("/"); + const ia = classes.findIndex((units) => units.has(a)); + const ib = classes.findIndex((units) => units.has(b)); + if (ia > -1 && ib > -1 && ia !== ib) { + throw new PublicodesError("EngineError", `Invalid ratio ${ratio}`, {}); + } else if (ia === -1 && ib === -1) { + classes.push(/* @__PURE__ */ new Set([a, b])); + } else if (ia > -1) { + classes[ia].add(b); + } else if (ib > -1) { + classes[ib].add(a); + } + return classes; + }, + [] + ); +} +function areSameClass(a, b) { + return a === b || convertibleUnitClasses.some( + (unitsClass) => unitsClass.has(a) && unitsClass.has(b) + ); +} +function round(value) { + return +value.toFixed(16); +} +function simplifyUnit(unit) { + const { numerators, denominators } = simplify(unit, areSameClass); + if (numerators.length && numerators.every((symb) => symb === "%")) { + return { numerators: ["%"], denominators }; + } + return removePercentages({ numerators, denominators }); +} +function simplifyUnitWithValue(unit, value = 1) { + const factor = unitsConversionFactor(unit.numerators, unit.denominators); + return [ + simplify(removePercentages(unit), areSameClass), + value ? round(value * factor) : value + ]; +} +var removePercentages = (unit) => ({ + numerators: unit.numerators.filter((e) => e !== "%"), + denominators: unit.denominators.filter((e) => e !== "%") +}); +function areUnitConvertible(a, b) { + if (a == null || b == null) { + return true; + } + const countByUnitClass = (units) => units.reduce((counters, unit) => { + const classIndex = convertibleUnitClasses.findIndex( + (unitClass) => unitClass.has(unit) + ); + const key = classIndex === -1 ? unit : "" + classIndex; + return { ...counters, [key]: 1 + (counters[key] ?? 0) }; + }, {}); + const [numA, denomA, numB, denomB] = [ + a.numerators, + a.denominators, + b.numerators, + b.denominators + ].map(countByUnitClass); + const uniq = (arr) => [...new Set(arr)]; + const unitClasses2 = [numA, denomA, numB, denomB].map(Object.keys).flat(); + return uniq(unitClasses2).every( + (unitClass) => (numA[unitClass] || 0) - (denomA[unitClass] || 0) === (numB[unitClass] || 0) - (denomB[unitClass] || 0) || unitClass === "%" + ); +} + +// src/mecanisms/arrondi.ts +function roundWithPrecision(n, fractionDigits) { + return +n.toFixed(fractionDigits); +} +var evaluate = function(node) { + const valeur = simplifyNodeUnit(this.evaluateNode(node.explanation.valeur)); + const nodeValue = valeur.nodeValue; + let arrondi = node.explanation.arrondi; + if (nodeValue !== false) { + arrondi = this.evaluateNode(arrondi); + if (typeof arrondi.nodeValue === "number" && !serializeUnit(arrondi.unit)?.match(/décimales?/)) { + throw new PublicodesError( + "EvaluationError", + `L'unit\xE9 ${serializeUnit( + arrondi.unit + )} de l'arrondi est inconnu. Vous devez utiliser l'unit\xE9 \u201Cd\xE9cimales\u201D`, + { dottedName: this.cache._meta.evaluationRuleStack[0] } + ); + } + } + return { + ...node, + nodeValue: typeof valeur.nodeValue !== "number" || !("nodeValue" in arrondi) ? valeur.nodeValue : typeof arrondi.nodeValue === "number" ? roundWithPrecision(valeur.nodeValue, arrondi.nodeValue) : arrondi.nodeValue === true ? roundWithPrecision(valeur.nodeValue, 0) : arrondi.nodeValue === void 0 ? void 0 : valeur.nodeValue, + explanation: { valeur, arrondi }, + missingVariables: mergeAllMissing([valeur, arrondi]), + unit: valeur.unit + }; +}; +function parseArrondi(v, context) { + const explanation = { + valeur: parse(v.valeur, context), + arrondi: parse(v.arrondi, context) + }; + return { + explanation, + nodeKind: parseArrondi.nom + }; +} +parseArrondi.nom = "arrondi"; +registerEvaluationFunction(parseArrondi.nom, evaluate); + +// src/nodeUnits.ts +function simplifyNodeUnit(node) { + if (!node.unit) { + return node; + } + const unit = simplifyUnit(node.unit); + return convertNodeToUnit(unit, node); +} +function convertNodeToUnit(to, node) { + return { + ...node, + nodeValue: node.unit && typeof node.nodeValue === "number" ? convertUnit(node.unit, to, node.nodeValue) : node.nodeValue, + unit: to + }; +} + +// src/format.ts +var numberFormatter = ({ + style, + maximumFractionDigits = 2, + minimumFractionDigits = 0, + language +}) => (value) => { + const adaptedMinimumFractionDigits = style === "currency" && maximumFractionDigits >= 2 && minimumFractionDigits === 0 && !Number.isInteger(value) ? 2 : minimumFractionDigits; + return Intl.NumberFormat(language, { + style, + currency: "EUR", + maximumFractionDigits, + minimumFractionDigits: adaptedMinimumFractionDigits + }).format(value); +}; +function formatNumber({ + maximumFractionDigits, + minimumFractionDigits, + language, + formatUnit: formatUnit2, + unit, + nodeValue +}) { + if (typeof nodeValue !== "number") { + return nodeValue; + } + const serializedUnit = unit ? serializeUnit(unit, nodeValue, formatUnit2) : void 0; + switch (serializedUnit) { + case "\u20AC": + return numberFormatter({ + style: "currency", + maximumFractionDigits, + minimumFractionDigits, + language + })(nodeValue); + case "%": + return numberFormatter({ + style: "percent", + maximumFractionDigits, + language + })(nodeValue / 100); + default: + return numberFormatter({ + style: "decimal", + minimumFractionDigits, + maximumFractionDigits, + language + })(nodeValue) + (typeof serializedUnit === "string" ? `\xA0${serializedUnit}` : ""); + } +} +function capitalise0(name) { + return name && name[0].toUpperCase() + name.slice(1); +} +var booleanTranslations = { + fr: { true: "oui", false: "non" }, + en: { true: "yes", false: "no" } +}; +function formatValue(value, { language = "fr", displayedUnit, formatUnit: formatUnit2, precision = 2 } = {}) { + let nodeValue = typeof value === "number" || typeof value === "undefined" || value === null ? value : value.nodeValue; + if (typeof nodeValue === "number" && Number.isNaN(nodeValue)) { + return "Erreur dans le calcul du nombre"; + } + if (nodeValue === void 0) { + return "Pas encore d\xE9fini"; + } + if (nodeValue === null) { + return "Non applicable"; + } + if (typeof nodeValue === "string") { + return nodeValue.replace("\\n", "\n"); + } + if (typeof nodeValue === "boolean") + return booleanTranslations[language][nodeValue]; + if (typeof nodeValue === "number") { + let unit = typeof value === "number" || typeof value === "undefined" || !("unit" in value) ? void 0 : value.unit; + if (unit) { + const simplifiedNode = simplifyNodeUnit({ + unit, + nodeValue + }); + unit = simplifiedNode.unit; + nodeValue = simplifiedNode.nodeValue; + } + return formatNumber({ + minimumFractionDigits: 0, + maximumFractionDigits: precision, + language, + formatUnit: formatUnit2, + nodeValue, + unit: displayedUnit ?? unit + }).trim(); + } + return void 0; +} + +// src/ruleUtils.ts +var ruleUtils_exports = {}; +__export(ruleUtils_exports, { + contextNameToDottedName: () => contextNameToDottedName, + cyclicDependencies: () => cyclicDependencies, + decodeRuleName: () => decodeRuleName, + disambiguateReference: () => disambiguateReference, + disambiguateReferenceNode: () => disambiguateReferenceNode, + encodeRuleName: () => encodeRuleName, + findCommonAncestor: () => findCommonAncestor, + getChildrenRules: () => getChildrenRules, + isAccessible: () => isAccessible, + isExperimental: () => isExperimental, + nameLeaf: () => nameLeaf, + ruleParent: () => ruleParent, + ruleParents: () => ruleParents, + ruleWithDedicatedDocumentationPage: () => ruleWithDedicatedDocumentationPage, + updateReferencesMapsFromReferenceNode: () => updateReferencesMapsFromReferenceNode +}); + +// src/AST/findCycles.ts +function has(obj, key) { + return obj != null && Object.prototype.hasOwnProperty.call(obj, key); +} +function constant(value) { + return function() { + return value; + }; +} +var DEFAULT_EDGE_NAME = "\0"; +var EDGE_KEY_DELIM = ""; +var incrementOrInitEntry = (map, k) => { + if (map[k]) { + map[k]++; + } else { + map[k] = 1; + } +}; +var decrementOrRemoveEntry = (map, k) => { + if (!--map[k]) { + delete map[k]; + } +}; +var edgeArgsToId = (isDirected, v_, w_, name) => { + let v = "" + v_; + let w = "" + w_; + if (!isDirected && v > w) { + const tmp = v; + v = w; + w = tmp; + } + return v + EDGE_KEY_DELIM + w + EDGE_KEY_DELIM + (name === void 0 ? DEFAULT_EDGE_NAME : name); +}; +var edgeArgsToObj = (isDirected, v_, w_, name) => { + let v = "" + v_; + let w = "" + w_; + if (!isDirected && v > w) { + const tmp = v; + v = w; + w = tmp; + } + const edgeObj = { v, w }; + if (name) { + edgeObj.name = name; + } + return edgeObj; +}; +var edgeObjToId = (isDirected, edgeObj) => { + return edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name); +}; +var Graph = class { + _nodeCount = 0; + _edgeCount = 0; + _isDirected; + _label; + _defaultNodeLabelFn; + _defaultEdgeLabelFn; + _nodes; + _in; + _preds; + _out; + _sucs; + _edgeObjs; + _edgeLabels; + constructor(opts = {}) { + this._isDirected = has(opts, "directed") ? opts.directed : true; + this._label = void 0; + this._defaultNodeLabelFn = constant(void 0); + this._defaultEdgeLabelFn = constant(void 0); + this._nodes = {}; + this._in = {}; + this._preds = {}; + this._out = {}; + this._sucs = {}; + this._edgeObjs = {}; + this._edgeLabels = {}; + } + /* === Graph functions ========= */ + isDirected() { + return this._isDirected; + } + setGraph(label) { + this._label = label; + return this; + } + graph() { + return this._label; + } + /* === Node functions ========== */ + nodeCount() { + return this._nodeCount; + } + nodes() { + return Object.keys(this._nodes); + } + setNode(v, value = void 0) { + if (has(this._nodes, v)) { + if (arguments.length > 1) { + this._nodes[v] = value; + } + return this; + } + this._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v); + this._in[v] = {}; + this._preds[v] = {}; + this._out[v] = {}; + this._sucs[v] = {}; + ++this._nodeCount; + return this; + } + setNodes(vs, value) { + vs.forEach((v) => { + if (value !== void 0) { + this.setNode(v, value); + } else { + this.setNode(v); + } + }); + return this; + } + node(v) { + return this._nodes[v]; + } + hasNode(v) { + return has(this._nodes, v); + } + successors(v) { + const sucsV = this._sucs[v]; + if (sucsV) { + return Object.keys(sucsV); + } + } + /* === Edge functions ========== */ + edgeCount() { + return this._edgeCount; + } + edges() { + return Object.values(this._edgeObjs); + } + setEdge(v, w, value = void 0, name = void 0) { + v = "" + v; + w = "" + w; + const e = edgeArgsToId(this._isDirected, v, w, name); + if (has(this._edgeLabels, e)) { + if (value !== void 0) { + this._edgeLabels[e] = value; + } + return this; + } + this.setNode(v); + this.setNode(w); + this._edgeLabels[e] = value !== void 0 ? value : this._defaultEdgeLabelFn(v, w, name); + const edgeObj = edgeArgsToObj(this._isDirected, v, w, name); + v = edgeObj.v; + w = edgeObj.w; + Object.freeze(edgeObj); + this._edgeObjs[e] = edgeObj; + incrementOrInitEntry(this._preds[w], v); + incrementOrInitEntry(this._sucs[v], w); + this._in[w][e] = edgeObj; + this._out[v][e] = edgeObj; + this._edgeCount++; + return this; + } + edge(v, w, name) { + const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); + return this._edgeLabels[e]; + } + hasEdge(v, w, name) { + const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); + return has(this._edgeLabels, e); + } + removeEdge(v, w, name) { + const e = arguments.length === 1 ? edgeObjToId(this._isDirected, arguments[0]) : edgeArgsToId(this._isDirected, v, w, name); + const edge = this._edgeObjs[e]; + if (edge) { + v = edge.v; + w = edge.w; + delete this._edgeLabels[e]; + delete this._edgeObjs[e]; + decrementOrRemoveEntry(this._preds[w], v); + decrementOrRemoveEntry(this._sucs[v], w); + delete this._in[w][e]; + delete this._out[v][e]; + this._edgeCount--; + } + return this; + } + outEdges(v, w = void 0) { + const outV = this._out[v]; + if (outV) { + const edges = Object.values(outV); + if (w === void 0) { + return edges; + } + return edges.filter(function(edge) { + return edge.w === w; + }); + } + } +}; +function tarjan(graph) { + let index = 0; + const stack = []; + const visited = {}; + const results = []; + function dfs(v) { + const entry = visited[v] = { + onStack: true, + lowlink: index, + index: index++ + }; + stack.push(v); + graph.successors(v).forEach(function(w) { + if (!Object.prototype.hasOwnProperty.call(visited, w)) { + dfs(w); + entry.lowlink = Math.min(entry.lowlink, visited[w].lowlink); + } else if (visited[w].onStack) { + entry.lowlink = Math.min(entry.lowlink, visited[w].index); + } + }); + if (entry.lowlink === entry.index) { + const cmpt = []; + let w; + do { + w = stack.pop(); + visited[w].onStack = false; + cmpt.push(w); + } while (v !== w); + results.push(cmpt); + } + } + graph.nodes().forEach(function(v) { + if (!Object.prototype.hasOwnProperty.call(visited, v)) { + dfs(v); + } + }); + return results; +} +function findCycles(graph) { + return tarjan(graph).filter(function(cmpt) { + return cmpt.length > 1 || cmpt.length === 1 && graph.hasEdge(cmpt[0], cmpt[0]); + }); +} + +// src/AST/graph.ts +function buildDependenciesGraph(rulesDeps) { + const g = new Graph(); + [...rulesDeps.entries()].forEach(([ruleDottedName, dependencies]) => { + dependencies.forEach((depDottedName) => { + g.setEdge(ruleDottedName, depDottedName); + }); + }); + return g; +} +function squashCycle(rulesDependenciesObject, cycle) { + function* loopFrom(i) { + let j = i; + while (true) { + yield cycle[j++ % cycle.length]; + } + } + const smallCycleStartingAt = []; + for (let i = 0; i < cycle.length; i++) { + const smallCycle = []; + let previousVertex = void 0; + for (const vertex of loopFrom(i)) { + if (previousVertex === void 0) { + smallCycle.push(vertex); + previousVertex = vertex; + } else if (rulesDependenciesObject.get(previousVertex)?.has(vertex)) { + if (smallCycle.includes(vertex)) { + smallCycle.splice(0, smallCycle.lastIndexOf(vertex)); + break; + } + smallCycle.push(vertex); + previousVertex = vertex; + } + } + smallCycleStartingAt.push(smallCycle); + } + const smallest = smallCycleStartingAt.reduce( + (minCycle, someCycle) => someCycle.length > minCycle.length ? minCycle : someCycle + ); + return smallest; +} +function cyclicDependencies(rawRules) { + const { referencesMaps } = parsePublicodes(rawRules); + const dependenciesGraph = buildDependenciesGraph(referencesMaps.referencesIn); + const cycles = findCycles(dependenciesGraph); + const reversedCycles = cycles.map((c) => c.reverse()); + const smallCycles = reversedCycles.map( + (cycle) => squashCycle(referencesMaps.referencesIn, cycle) + ); + const printableStronglyConnectedComponents = reversedCycles.map( + (c, i) => printInDotFormat(dependenciesGraph, c, smallCycles[i]) + ); + return [smallCycles, printableStronglyConnectedComponents]; +} +var edgeIsInCycle = (cycle, v, w) => { + for (let i = 0; i < cycle.length + 1; i++) { + if (v === cycle[i] && w === cycle[(i + 1) % cycle.length]) + return true; + } + return false; +}; +function printInDotFormat(dependenciesGraph, cycle, subCycleToHighlight) { + const edgesSet = /* @__PURE__ */ new Set(); + cycle.forEach((vertex) => { + dependenciesGraph.outEdges(vertex).filter(({ w }) => cycle.includes(w)).forEach(({ v, w }) => { + edgesSet.add( + `"${v}" -> "${w}"` + (edgeIsInCycle(subCycleToHighlight, v, w) ? " [color=red]" : "") + ); + }); + }); + return `digraph Cycle { + ${[...edgesSet].join(";\n ")}; +}`; +} + +// src/ruleUtils.ts +var splitName = (str) => str.split(" . "); +var joinName = (strs) => strs.join(" . "); +var nameLeaf = (dottedName) => splitName(dottedName).slice(-1)?.[0]; +var encodeRuleName = (dottedName) => dottedName?.replace(/\s\.\s/g, "/").replace(/-/g, "\u2011").replace(/\s/g, "-"); +var decodeRuleName = (dottedName) => dottedName.replace(/\//g, " . ").replace(/-/g, " ").replace(/\u2011/g, "-"); +var contextNameToDottedName = (contextName) => contextName.endsWith("$SITUATION") ? ruleParent(contextName) : contextName; +var ruleParent = (dottedName) => joinName(splitName(dottedName).slice(0, -1)); +function ruleParents(dottedName) { + return splitName(dottedName).slice(0, -1).map((_, i, arr) => joinName(arr.slice(0, i + 1))).reverse(); +} +var getChildrenRules = (parsedRules, dottedName) => { + const childrenRules = Object.keys(parsedRules).filter( + (ruleDottedName) => ruleDottedName.startsWith(dottedName) && splitName(ruleDottedName).length === splitName(dottedName).length + 1 + ); + return childrenRules; +}; +function findCommonAncestor(dottedName1, dottedName2) { + const splitDottedName1 = splitName(dottedName1); + const splitDottedName2 = splitName(dottedName2); + const index = splitDottedName1.findIndex( + (value, i) => splitDottedName2[i] !== value + ); + return index === -1 ? dottedName1 : joinName(splitDottedName1.slice(0, index)); +} +function isAccessible(rules, contextName, name) { + if (!(name in rules)) { + throw new PublicodesError( + "InternalError", + `La r\xE8gle "${name}" n'existe pas`, + { dottedName: name } + ); + } + const commonAncestor = findCommonAncestor(contextName, name); + const parents = [name, ...ruleParents(name), ""]; + const rulesToCheckForPrivacy = parents.slice( + 0, + Math.max(parents.indexOf(commonAncestor) - 1, 0) + ); + return rulesToCheckForPrivacy.every( + (dottedName) => !(dottedName in rules) || rules[dottedName].private === false + ); +} +function isExperimental(rules, name) { + if (!(name in rules)) { + throw new PublicodesError( + "InternalError", + `La r\xE8gle "${name}" n'existe pas`, + { dottedName: name } + ); + } + const parents = [name, ...ruleParents(name)]; + return parents.some( + (dottedName) => dottedName in rules && rules[dottedName].rawNode?.experimental === "oui" + ); +} +function dottedNameFromContext(context, partialName) { + return context ? context + " . " + partialName : partialName; +} +function disambiguateReference(rules, referencedFrom = "", partialName) { + const possibleContexts = ruleParents(referencedFrom); + possibleContexts.push(referencedFrom); + if (partialName.startsWith("^ . ")) { + const numberParent = partialName.match(/^(\^ \. )+/)[0].length / 4; + partialName = partialName.replace(/^(\^ \. )+/, ""); + possibleContexts.splice(-numberParent); + } + const rootContext = possibleContexts.pop(); + possibleContexts.unshift(rootContext); + possibleContexts.push(""); + const context = possibleContexts.find((context2) => { + const dottedName = dottedNameFromContext(context2, partialName); + if (!(dottedName in rules)) { + return false; + } + if (dottedName === referencedFrom) { + return false; + } + return isAccessible(rules, referencedFrom, dottedName); + }); + if (context !== void 0) { + return dottedNameFromContext(context, partialName); + } + if (referencedFrom.endsWith(partialName)) { + return referencedFrom; + } + const possibleDottedName = possibleContexts.map( + (c) => dottedNameFromContext(c, partialName) + ); + if (possibleDottedName.every((dottedName) => !(dottedName in rules))) { + throw new PublicodesError( + "SyntaxError", + `La r\xE9f\xE9rence "${partialName}" est introuvable. +V\xE9rifiez que l'orthographe et l'espace de nom sont corrects`, + { dottedName: contextNameToDottedName(referencedFrom) } + ); + } + throw new PublicodesError( + "SyntaxError", + `La r\xE8gle "${possibleDottedName.find( + (dottedName) => dottedName in rules + )}" n'est pas accessible depuis "${referencedFrom}". + Cela vient du fait qu'elle est priv\xE9e ou qu'un de ses parent est priv\xE9`, + { dottedName: contextNameToDottedName(referencedFrom) } + ); +} +function ruleWithDedicatedDocumentationPage(rule) { + return rule.virtualRule !== true && rule.type !== "groupe" && rule.type !== "texte" && rule.type !== "paragraphe" && rule.type !== "notification"; +} +function updateReferencesMapsFromReferenceNode(node, referencesMaps, ruleDottedName) { + if (node.nodeKind === "reference") { + addToMapSet( + referencesMaps.referencesIn, + ruleDottedName ?? node.contextDottedName, + node.dottedName + ); + addToMapSet( + referencesMaps.rulesThatUse, + node.dottedName, + ruleDottedName ?? node.contextDottedName + ); + } +} +function disambiguateReferenceNode(node, parsedRules) { + if (node.nodeKind !== "reference") { + return; + } + if (node.dottedName) { + return node; + } + node.dottedName = disambiguateReference( + parsedRules, + node.contextDottedName, + node.name + ); + node.title = parsedRules[node.dottedName].title; + node.acronym = parsedRules[node.dottedName].rawNode.acronyme; + return node; +} + +// src/rule.ts +function parseRule(nom, rawRule, context) { + const privateRule = rawRule.priv\u00E9 === "oui" || nom.startsWith("[priv\xE9] "); + nom = nom.replace(/^\[privé\] /, ""); + const dottedName = [context.dottedName, nom].filter(Boolean).join(" . "); + const name = nameLeaf(dottedName); + const title = capitalise0(rawRule["titre"] ?? name); + if (context.parsedRules[dottedName]) { + throw new PublicodesError( + "EvaluationError", + `La r\xE9f\xE9rence '${dottedName}' a d\xE9j\xE0 \xE9t\xE9 d\xE9finie`, + { dottedName } + ); + } + const ruleValue = {}; + for (const key in rawRule) { + if (mecanismKeys.includes(key)) { + ruleValue[key] = rawRule[key]; + } + } + if ("formule" in rawRule) { + ruleValue.valeur = rawRule.formule; + } + if (!privateRule && !dottedName.endsWith("$SITUATION")) { + ruleValue["dans la situation"] = `${dottedName} . $SITUATION`; + ruleValue["avec"] = weakCopyObj(ruleValue["avec"]) ?? {}; + const situationValue = weakCopyObj(undefinedNode); + situationValue.isNullable = rawRule["possiblement non applicable"] === "oui"; + ruleValue["avec"]["[priv\xE9] $SITUATION"] = { + valeur: situationValue + }; + if (ruleValue["par d\xE9faut"] != null) { + ruleValue["par d\xE9faut"] = { + valeur: ruleValue["par d\xE9faut"], + "variable manquante": dottedName + }; + } + } + const currentDottedNameContext = context.dottedName; + context.dottedName = dottedName; + context.parsedRules[dottedName] = void 0; + const explanation = { + valeur: parse(ruleValue, context), + // We include a list of references to the parents to implement the branch + // desactivation feature. When evaluating a rule we only need to know the + // first nullable parent, but this is something that we can't determine at + // this stage : + // - we need to run remplacements (which works on references in the ASTs + // which is why we insert these “virtual” references) + // - we need to infer unit of the rules + // + // An alternative implementation would be possible that would colocate the + // code related to branch desactivation (ie find the first nullable parent + // statically after rules parsing) + parents: ruleParents(dottedName).map( + (parent) => ({ + dottedName: parent, + nodeKind: "reference", + contextDottedName: context.dottedName + }) + ) + }; + const suggestions = {}; + if (rawRule.suggestions) { + for (const name2 in rawRule.suggestions) { + suggestions[name2] = parse(rawRule.suggestions[name2], context); + } + } + context.parsedRules[dottedName] = { + dottedName, + replacements: [ + ...parseRendNonApplicable(rawRule["rend non applicable"], context), + ...parseReplacements(rawRule.remplace, context) + ], + title, + private: privateRule, + suggestions, + nodeKind: "rule", + explanation, + rawNode: rawRule, + virtualRule: privateRule + }; + context.dottedName = currentDottedNameContext; + return context.parsedRules[dottedName]; +} +function parseRules(rules, context) { + for (const dottedName in rules) { + let rule = rules[dottedName]; + if (typeof rule === "string" || typeof rule === "number") { + rule = { valeur: `${rule}` }; + } + if (typeof rule !== "object") { + throw new PublicodesError( + "SyntaxError", + `Rule ${dottedName} is incorrectly written. Please give it a proper value.`, + { dottedName } + ); + } + const copy = rule === null ? {} : weakCopyObj(rule); + parseRule(dottedName, copy, context); + } +} +registerEvaluationFunction("rule", function evaluate2(node) { + const { ruleDisabledByItsParent, nullableParent, parentMissingVariables } = evaluateDisablingParent(this, node); + let valeurEvaluation = { + ...node.explanation.valeur, + nodeValue: null, + missingVariables: {} + }; + if (!ruleDisabledByItsParent) { + if (this.cache._meta.evaluationRuleStack.filter( + (dottedName) => dottedName === node.dottedName + ).length > 1) { + valeurEvaluation = { + nodeValue: void 0 + }; + } else { + this.cache._meta.evaluationRuleStack.unshift(node.dottedName); + valeurEvaluation = this.evaluateNode(node.explanation.valeur); + this.cache._meta.evaluationRuleStack.shift(); + } + } + valeurEvaluation.missingVariables ??= {}; + updateRuleMissingVariables(this, node, valeurEvaluation); + const evaluation = { + ...valeurEvaluation, + missingVariables: mergeMissing( + valeurEvaluation.missingVariables, + parentMissingVariables + ), + ...node, + explanation: { + parents: node.explanation.parents, + valeur: valeurEvaluation, + nullableParent, + ruleDisabledByItsParent + } + }; + return evaluation; +}); +function updateRuleMissingVariables(engine, node, valeurEvaluation) { + if (node.private === true || !isAccessible(engine.context.parsedRules, "", node.dottedName)) { + return; + } + if (valeurEvaluation.nodeValue === void 0 && !Object.keys(valeurEvaluation.missingVariables).length) { + valeurEvaluation.missingVariables[node.dottedName] = 1; + } + return; +} +function evaluateDisablingParent(engine, node) { + if (node.private) { + return { ruleDisabledByItsParent: false, parentMissingVariables: {} }; + } + const nodesTypes = engine.context.nodesTypes; + const nullableParent = node.explanation.parents.find( + (ref) => nodesTypes.get(ref)?.isNullable || nodesTypes.get(ref)?.type === "boolean" + ); + if (!nullableParent) { + return { ruleDisabledByItsParent: false, parentMissingVariables: {} }; + } + if ( + // TODO: remove this condition and the associated "parentRuleStack", cycles + // should be detected and avoided at parse time. + !engine.cache._meta.parentRuleStack.includes(node.dottedName) + ) { + engine.cache._meta.parentRuleStack.unshift(node.dottedName); + let parentIsNotApplicable = defaultNode(false); + if (nodesTypes.get(nullableParent)?.isNullable) { + parentIsNotApplicable = engine.evaluateNode({ + nodeKind: "est non applicable", + explanation: nullableParent + }); + } + if (parentIsNotApplicable.nodeValue !== true && nodesTypes.get(nullableParent)?.type === "boolean") { + parentIsNotApplicable = engine.evaluateNode({ + nodeKind: "operation", + operator: "=", + operationKind: "=", + explanation: [nullableParent, defaultNode(false)] + }); + } + engine.cache._meta.parentRuleStack.shift(); + if (parentIsNotApplicable.nodeValue === true) { + return { + ruleDisabledByItsParent: true, + parentMissingVariables: parentIsNotApplicable.missingVariables ?? {}, + nullableParent + }; + } + } + let parentMissingVariables = {}; + if (nodesTypes.get(nullableParent)?.type === "boolean") { + const parentEvaluation = engine.evaluateNode(nullableParent); + parentMissingVariables = parentEvaluation.missingVariables ?? {}; + return { + ruleDisabledByItsParent: parentEvaluation.nodeValue === false, + parentMissingVariables, + nullableParent + }; + } + return { + ruleDisabledByItsParent: false, + parentMissingVariables, + nullableParent + }; +} + +// src/mecanisms/avec.ts +function parseAvec(v, context) { + parseRules(v.avec, context); + const valeur = parse(v.valeur, context); + return valeur; +} +parseAvec.nom = "avec"; + +// src/mecanisms/trancheUtils.ts +var parseTranches = (tranches, context) => { + return tranches.map((node, i) => { + if (!node.plafond && i > tranches.length) { + throw new PublicodesError( + "SyntaxError", + `La tranche n\xB0${i} du bar\xE8me n'a pas de plafond pr\xE9cis\xE9. Seule la derni\xE8re tranche peut ne pas \xEAtre plafonn\xE9e`, + { dottedName: "" } + ); + } + return { + ...node, + ...node.taux !== void 0 ? { taux: parse(node.taux, context) } : {}, + ...node.montant !== void 0 ? { montant: parse(node.montant, context) } : {}, + plafond: "plafond" in node ? parse(node.plafond, context) : { + nodeValue: Infinity, + nodeKind: "constant", + type: "number", + isNullable: false + } + }; + }); +}; +function evaluatePlafondUntilActiveTranche({ multiplicateur, assiette, parsedTranches }) { + return parsedTranches.reduce( + ([tranches, activeTrancheFound], parsedTranche, i) => { + if (activeTrancheFound) { + return [ + [...tranches, { ...parsedTranche, isAfterActive: true }], + activeTrancheFound + ]; + } + const plafond = this.evaluateNode(parsedTranche.plafond); + const plancher = tranches[i - 1] ? tranches[i - 1].plafond : { nodeValue: 0 }; + let plafondValue = plafond.nodeValue === void 0 || multiplicateur.nodeValue === void 0 ? void 0 : plafond.nodeValue * multiplicateur.nodeValue; + try { + plafondValue = plafondValue === Infinity || plafondValue === 0 ? plafondValue : convertUnit( + inferUnit("*", [plafond.unit, multiplicateur.unit]), + assiette.unit, + plafondValue + ); + } catch (e) { + warning( + this.context.logger, + `L'unit\xE9 du plafond de la tranche n\xB0${i + 1} n'est pas compatible avec celle l'assiette`, + { dottedName: this.cache._meta.evaluationRuleStack[0] }, + e + ); + } + const plancherValue = tranches[i - 1] ? tranches[i - 1].plafondValue : 0; + const isAfterActive = plancherValue === void 0 || assiette.nodeValue === void 0 ? void 0 : plancherValue > assiette.nodeValue; + const calculationValues = [plafond, assiette, multiplicateur, plancher]; + if (calculationValues.some((node) => node.nodeValue === void 0)) { + return [ + [ + ...tranches, + { + ...parsedTranche, + plafond, + plafondValue, + plancherValue, + nodeValue: void 0, + isActive: void 0, + isAfterActive, + missingVariables: mergeAllMissing(calculationValues) + } + ], + false + ]; + } + if (!!tranches[i - 1] && !!plancherValue && plafondValue <= plancherValue) { + throw new PublicodesError( + "EvaluationError", + `Le plafond de la tranche n\xB0${i + 1} a une valeur inf\xE9rieure \xE0 celui de la tranche pr\xE9c\xE9dente`, + { dottedName: this.cache._meta.evaluationRuleStack[0] } + ); + } + const tranche = { + ...parsedTranche, + plafond, + plancherValue, + plafondValue, + isAfterActive, + isActive: assiette.nodeValue >= plancherValue && assiette.nodeValue < plafondValue + }; + return [[...tranches, tranche], tranche.isActive]; + }, + [[], false] + )[0]; +} + +// src/mecanisms/barème.ts +function parseBar\u00E8me(v, context) { + const explanation = { + assiette: parse(v.assiette, context), + multiplicateur: v.multiplicateur ? parse(v.multiplicateur, context) : defaultNode(1), + tranches: parseTranches(v.tranches, context) + }; + return { + explanation, + nodeKind: "bar\xE8me" + }; +} +function evaluateBar\u00E8me(tranches, assiette, evaluate15) { + return tranches.map((tranche) => { + if (tranche.isAfterActive) { + return { ...tranche, nodeValue: 0 }; + } + const taux = evaluate15(tranche.taux); + const missingVariables = mergeAllMissing([taux, tranche]); + if ([ + assiette.nodeValue, + taux.nodeValue, + tranche.plafondValue, + tranche.plancherValue + ].some((value) => value === void 0)) { + return { + ...tranche, + taux, + nodeValue: void 0, + missingVariables + }; + } + return { + ...tranche, + taux, + ..."unit" in assiette && { unit: assiette.unit }, + nodeValue: (Math.min(assiette.nodeValue, tranche.plafondValue) - tranche.plancherValue) * convertUnit(taux.unit, parseUnit(""), taux.nodeValue), + missingVariables + }; + }); +} +var evaluate3 = function(node) { + const evaluate15 = this.evaluateNode.bind(this); + const assiette = this.evaluateNode( + node.explanation.assiette + ); + const multiplicateur = this.evaluateNode(node.explanation.multiplicateur); + if (multiplicateur.nodeValue === 0) { + throw new PublicodesError( + "EvaluationError", + `Le multiplicateur ne peut pas \xEAtre nul`, + { dottedName: this.cache._meta.evaluationRuleStack[0] } + ); + } + let tranches = node.explanation.tranches; + let nodeValue = assiette.nodeValue; + if (![0, void 0, null].includes(assiette.nodeValue)) { + tranches = evaluateBar\u00E8me( + evaluatePlafondUntilActiveTranche.call(this, { + parsedTranches: node.explanation.tranches, + assiette, + multiplicateur + }), + assiette, + evaluate15 + ); + nodeValue = tranches.reduce( + (value, { nodeValue: nodeValue2 }) => nodeValue2 == void 0 ? void 0 : value + nodeValue2, + 0 + ); + } + return { + ...node, + nodeValue, + missingVariables: mergeAllMissing([assiette, multiplicateur, ...tranches]), + explanation: { + assiette, + multiplicateur, + tranches + }, + unit: assiette.unit + }; +}; +registerEvaluationFunction("bar\xE8me", evaluate3); + +// src/mecanisms/condition.ts +var evaluate4 = function(node) { + let evaluation; + const condition = this.evaluateNode(node.explanation.si); + let alors = node.explanation.alors; + let sinon = node.explanation.sinon; + if ("unit" in condition) { + throw new PublicodesError( + "EvaluationError", + "La condition doit \xEAtre de type bool\xE9en", + { dottedName: this.cache._meta.evaluationRuleStack[0] } + ); + } + if (condition.nodeValue === true) { + alors = this.evaluateNode(node.explanation.alors); + alors.isActive = true; + evaluation = alors; + } else if (condition.nodeValue === false) { + sinon = this.evaluateNode(node.explanation.sinon); + evaluation = sinon; + } else if (condition.nodeValue === null) { + evaluation = condition; + } else if (condition.nodeValue === void 0) { + sinon = this.evaluateNode(node.explanation.sinon); + alors = this.evaluateNode(node.explanation.alors); + evaluation = { + ...condition, + missingVariables: mergeAllMissing([sinon, alors]) + }; + } else { + throw new PublicodesError( + "EvaluationError", + "La condition doit \xEAtre de type bool\xE9en", + { dottedName: this.cache._meta.evaluationRuleStack[0] } + ); + } + const unit = evaluation.unit ?? alors.unit; + return { + nodeValue: evaluation.nodeValue, + missingVariables: mergeMissing( + bonus(condition.missingVariables), + evaluation.missingVariables + ), + ...unit != void 0 ? { unit } : {}, + ...node, + explanation: { si: condition, alors, sinon } + }; +}; +function parseCondition(v, context) { + const explanation = { + si: parse(v.si, context), + alors: parse(v.alors, context), + sinon: parse(v.sinon, context) + }; + return { + explanation, + nodeKind: "condition" + }; +} +parseCondition.nom = "condition"; +registerEvaluationFunction("condition", evaluate4); + +// src/mecanisms/contexte.ts +function parseMecanismContexte(v, context) { + const contexte = Object.keys(v.contexte).map((dottedName) => [ + parse(dottedName, context), + parse(v.contexte[dottedName], context) + ]); + const node = parse(v.valeur, context); + return { + explanation: { + valeur: node, + contexte, + subEngineId: context.subEngineIncrementingNumber++ + }, + nodeKind: parseMecanismContexte.nom + }; +} +parseMecanismContexte.nom = "contexte"; +var evaluateContexte = function(node) { + const amendedSituation = Object.fromEntries( + node.explanation.contexte.filter(([originRule, replacement]) => { + const originRuleEvaluation = this.evaluateNode(originRule); + const replacementEvaluation = this.evaluateNode(replacement); + return originRuleEvaluation.nodeValue !== replacementEvaluation.nodeValue || serializeUnit(originRuleEvaluation.unit) !== serializeUnit(replacementEvaluation.unit); + }).map( + ([originRule, replacement]) => [originRule.dottedName, replacement] + ) + ); + if (this.cache._meta.currentContexteSituation === JSON.stringify(amendedSituation)) { + return { + ...notApplicableNode, + ...node + }; + } + const engine = this.shallowCopy(); + engine.subEngineId = node.explanation.subEngineId; + this.subEngines[node.explanation.subEngineId] = engine; + if (Object.keys(amendedSituation).length) { + engine.setSituation(amendedSituation, { + keepPreviousSituation: true + }); + Object.entries(amendedSituation).forEach(([originDottedName, value]) => { + const evaluation = this.cache.nodes.get(value); + if (!evaluation) { + throw new PublicodesError( + "InternalError", + "The situation should have already been evaluated", + { + dottedName: this.context.dottedName + } + ); + } + const originRule = engine.context.parsedRules[originDottedName + " . $SITUATION"]; + if (!originRule?.explanation.valeur) { + throw new PublicodesError( + "InternalError", + "The origin rule should be defined", + { + dottedName: this.context.dottedName + } + ); + } + engine.cache.nodes.set(originRule.explanation.valeur, evaluation); + }); + } + engine.cache._meta.currentContexteSituation = JSON.stringify(amendedSituation); + const evaluatedNode = engine.evaluateNode(node.explanation.valeur); + return { + ...node, + nodeValue: evaluatedNode.nodeValue, + explanation: { + ...node.explanation, + valeur: evaluatedNode + }, + missingVariables: evaluatedNode.missingVariables, + ..."unit" in evaluatedNode && { unit: evaluatedNode.unit } + }; +}; +registerEvaluationFunction("contexte", evaluateContexte); + +// src/date.ts +function normalizeDateString(dateString) { + let [day, month, year] = dateString.split("/"); + if (!year) { + ; + [day, month, year] = ["01", day, month]; + } + return normalizeDate(+year, +month, +day); +} +var pad = (n) => +n < 10 ? `0${n}` : "" + n; +function normalizeDate(year, month, day) { + const date2 = new Date(+year, +month - 1, +day); + if (!+date2 || date2.getDate() !== +day) { + throw new PublicodesError( + "SyntaxError", + `La date ${day}/${month}/${year} n'est pas valide`, + { dottedName: "" } + ); + } + return `${pad(day)}/${pad(month)}/${pad(year)}`; +} +function convertToDate(value) { + const [day, month, year] = normalizeDateString(value).split("/"); + const result = new Date(+year, +month - 1, +day); + result.setMinutes(result.getMinutes() - result.getTimezoneOffset()); + return result; +} +function convertToString(date2) { + return normalizeDate(date2.getFullYear(), date2.getMonth() + 1, date2.getDate()); +} +function getYear(date2) { + return +date2.slice(-4); +} +function getTrimestreCivil(date2) { + const [, month, year] = date2.split("/"); + const trimester = Math.floor((Number.parseInt(month, 10) - 1) / 3); + const startingMonth = 3 * trimester + 1; + return `01/${startingMonth.toString().padStart(2, "0")}/${year}`; +} +function getDifferenceInDays(from, to) { + const millisecondsPerDay = 1e3 * 60 * 60 * 24; + return (convertToDate(to).getTime() - convertToDate(from).getTime()) / millisecondsPerDay; +} +function getDifferenceInMonths(from, to) { + const [dayFrom, monthFrom, yearFrom] = from.split("/").map((x) => +x); + const [dayTo, monthTo, yearTo] = to.split("/").map((x) => +x); + const numberOfFullMonth = monthTo - monthFrom + 12 * (yearTo - yearFrom); + const numDayMonthFrom = new Date(yearFrom, monthFrom, 0).getDate(); + const numDayMonthTo = new Date(yearTo, monthTo, 0).getDate(); + const prorataMonthFrom = (dayFrom - 1) / numDayMonthFrom; + const prorataMonthTo = dayTo / numDayMonthTo; + return numberOfFullMonth - prorataMonthFrom + prorataMonthTo; +} +function getDifferenceInYears(from, to) { + const differenceInDays = getDifferenceInDays(from, to); + const isLeapYear = (year) => year % 4 === 0 && year % 100 !== 0 || year % 400 === 0; + const after1stMarch = (date2) => date2 >= new Date(date2.getFullYear(), 2, 1); + const fromDate = convertToDate(from); + const toDate = convertToDate(to); + const fromYear = fromDate.getFullYear() + (after1stMarch(fromDate) ? 1 : 0); + const toYear = toDate.getFullYear() + (after1stMarch(fromDate) ? 0 : -1); + const leapYearsCount = Array.from( + { length: toYear - fromYear + 1 }, + (_, i) => fromYear + i + ).filter(isLeapYear).length; + return (differenceInDays - leapYearsCount) / 365; +} +function getDifferenceInTrimestreCivils(from, to) { + return Math.floor( + getDifferenceInMonths(getTrimestreCivil(from), getTrimestreCivil(to)) / 3 + ) + 1; +} +function getDifferenceInYearsCivil(from, to) { + const fromYear = "01/" + getYear(from); + const toYear = "01/" + getYear(to); + return Math.floor(getDifferenceInYears(fromYear, toYear)) + 1; +} + +// src/mecanisms/durée.ts +var evaluate5 = function(node) { + const fromNode = this.evaluateNode(node.explanation.depuis); + const toNode = this.evaluateNode(node.explanation["jusqu'\xE0"]); + const from = fromNode.nodeValue; + const to = toNode.nodeValue; + let nodeValue; + if (from === null || to === null) { + nodeValue = null; + } else if (from === void 0 || to === void 0) { + nodeValue = void 0; + } else { + switch (node.unit.numerators[0]) { + case "jour": + nodeValue = getDifferenceInDays(from, to); + break; + case "mois": + nodeValue = getDifferenceInMonths(from, to); + break; + case "an": + nodeValue = getDifferenceInYears(from, to); + break; + case "trimestre": + nodeValue = getDifferenceInMonths(from, to) / 3; + break; + case "trimestre civil": + nodeValue = getDifferenceInTrimestreCivils(from, to); + break; + case "ann\xE9e civile": + nodeValue = getDifferenceInYearsCivil(from, to); + break; + } + } + if (typeof nodeValue === "number") { + nodeValue = Math.max(0, nodeValue); + } + return { + ...node, + missingVariables: mergeAllMissing([fromNode, toNode]), + nodeValue, + explanation: { + depuis: fromNode, + "jusqu'\xE0": toNode + } + }; +}; +var today = defaultNode(convertToString(/* @__PURE__ */ new Date())); +var dur_e_default = (v, context) => { + const explanation = { + depuis: parse(v.depuis ?? today, context), + "jusqu'\xE0": parse(v["jusqu'\xE0"] ?? today, context) + }; + const unit = v.unit\u00E9 ? parseUnit(v.unit\u00E9) : parseUnit("jour"); + if (unit.denominators.length > 0 || unit.numerators.length > 1 || !possibleUnit.includes(unit.numerators[0])) { + throw new PublicodesError( + "SyntaxError", + `Seules les unit\xE9s suivantes sont accept\xE9es pour une dur\xE9e : ${possibleUnit.join( + ", " + )}. + L'unit\xE9 fournie est: ${unit.numerators[0]}`, + { + dottedName: context.dottedName + } + ); + } + return { + explanation, + unit, + nodeKind: "dur\xE9e" + }; +}; +registerEvaluationFunction("dur\xE9e", evaluate5); +var possibleUnit = [ + "mois", + "jour", + "an", + "trimestre", + "trimestre civil", + "ann\xE9e civile" +]; + +// src/mecanisms/est.ts +function parseEstNonD\u00E9fini(v, context) { + const explanation = parse(v, context); + return { + explanation, + nodeKind: "est non d\xE9fini" + }; +} +parseEstNonD\u00E9fini.nom = "est non d\xE9fini"; +var parseEstD\u00E9fini = createParseInlinedMecanism( + "est d\xE9fini", + { + valeur: {} + }, + { + "=": [{ "est non d\xE9fini": "valeur" }, "non"] + } +); +var parseEstApplicable = createParseInlinedMecanism( + "est applicable", + { + valeur: {} + }, + { + "=": [{ "est non applicable": "valeur" }, "non"] + } +); +var evaluate6 = function(node) { + const valeur = this.evaluateNode(node.explanation); + let nodeValue = false; + if (valeur.nodeValue === void 0) { + nodeValue = true; + } + return { + ...node, + nodeValue, + missingVariables: valeur.missingVariables, + explanation: valeur + }; +}; +registerEvaluationFunction("est non d\xE9fini", evaluate6); + +// src/mecanisms/est-non-applicable.ts +function parseEstNonApplicable(v, context) { + const explanation = parse(v, context); + return { + explanation, + nodeKind: "est non applicable" + }; +} +parseEstNonApplicable.nom = "est non applicable"; +var isNotApplicable = (node) => { + return { + nodeKind: "est non applicable", + explanation: node + }; +}; +var evaluateIsNotApplicable = function(node) { + const valeur = node.explanation; + if (this.context.nodesTypes.get(valeur)?.isNullable === false && valeur.nodeKind !== "rule" && valeur.nodeKind !== "reference") { + return { ...node, nodeValue: false, missingVariables: {} }; + } + if (this.cache.nodes.has(valeur) && this.cache.nodes.get(valeur) !== void 0) { + return { + ...node, + nodeValue: this.cache.nodes.get(valeur)?.nodeValue === null, + missingVariables: this.cache.nodes.get(valeur)?.missingVariables ?? {} + }; + } + switch (valeur.nodeKind) { + case "rule": { + const { ruleDisabledByItsParent, parentMissingVariables } = evaluateDisablingParent(this, valeur); + if (ruleDisabledByItsParent) { + return { + ...node, + nodeValue: true, + missingVariables: parentMissingVariables + }; + } + const isNotApplicableEvaluation = this.evaluateNode( + isNotApplicable(valeur.explanation.valeur) + ); + const missingVariables = mergeMissing( + parentMissingVariables, + isNotApplicableEvaluation.missingVariables + ); + if (isNotApplicableEvaluation.nodeValue === false && this.context.nodesTypes.get( + this.context.parsedRules[`${valeur.dottedName} . $SITUATION`] + )?.isNullable && !Object.keys(isNotApplicableEvaluation.missingVariables).length) { + missingVariables[valeur.dottedName] = 1; + } + return { + ...node, + nodeValue: isNotApplicableEvaluation.nodeValue, + missingVariables + }; + } + case "reference": + return { + ...this.evaluateNode( + isNotApplicable(this.context.parsedRules[valeur.dottedName]) + ), + ...node + }; + case "condition": + return { + ...this.evaluateNode({ + ...valeur, + explanation: { + si: valeur.explanation.si, + alors: isNotApplicable(valeur.explanation.alors), + sinon: isNotApplicable(valeur.explanation.sinon) + } + }), + ...node + }; + } + const evaluatedValeur = this.evaluateNode(valeur); + return { + ...node, + nodeValue: evaluatedValeur.nodeValue === void 0 ? void 0 : evaluatedValeur.nodeValue === null, + missingVariables: evaluatedValeur.missingVariables + }; +}; +registerEvaluationFunction("est non applicable", evaluateIsNotApplicable); + +// src/mecanisms/grille.ts +function parseGrille(v, context) { + const explanation = { + assiette: parse(v.assiette, context), + multiplicateur: v.multiplicateur ? parse(v.multiplicateur, context) : defaultNode(1), + tranches: parseTranches(v.tranches, context) + }; + return { + explanation, + nodeKind: "grille" + }; +} +var evaluate7 = function(node) { + const evaluate15 = this.evaluateNode.bind(this); + const assiette = this.evaluateNode(node.explanation.assiette); + const multiplicateur = this.evaluateNode(node.explanation.multiplicateur); + if (multiplicateur.nodeValue === 0) { + throw new PublicodesError( + "EvaluationError", + `Le multiplicateur ne peut pas \xEAtre nul`, + { + dottedName: this.cache._meta.evaluationRuleStack[0] + } + ); + } + const tranches = evaluatePlafondUntilActiveTranche.call(this, { + parsedTranches: node.explanation.tranches, + assiette, + multiplicateur + }).map((tranche) => { + if (tranche.isActive === false) { + return tranche; + } + const montant = evaluate15(tranche.montant); + return { + ...tranche, + montant, + nodeValue: montant.nodeValue, + unit: montant.unit, + missingVariables: mergeAllMissing([montant, tranche]) + }; + }); + let activeTranches; + const activeTranche = tranches.find((tranche) => tranche.isActive); + if (activeTranche) { + activeTranches = [activeTranche]; + } else if (tranches[tranches.length - 1].isAfterActive === false) { + activeTranches = [{ nodeValue: false }]; + } else { + activeTranches = tranches.filter( + (tranche) => tranche.isActive === void 0 + ); + } + const nodeValue = !activeTranches[0] ? false : activeTranches[0].isActive === void 0 ? void 0 : activeTranches[0].nodeValue; + return { + ...node, + nodeValue, + missingVariables: mergeAllMissing([ + assiette, + multiplicateur, + ...activeTranches + ]), + explanation: { + ...node.explanation, + assiette, + multiplicateur, + tranches + }, + unit: activeTranches[0]?.unit ?? void 0 + }; +}; +registerEvaluationFunction("grille", evaluate7); + +// src/uniroot.ts +function uniroot(func, lowerLimit, upperLimit, errorTol = 0, maxIter = 100, acceptableErrorTol = 0) { + let a = lowerLimit, b = upperLimit, c = a, fa = func(a), fb = func(b), fc = fa, actualTolerance, newStep, prevStep, p, q, fallback = void 0; + while (maxIter-- > 0) { + prevStep = b - a; + if (Math.abs(fc) < Math.abs(fb)) { + ; + a = b, b = c, c = a; + fa = fb, fb = fc, fc = fa; + } + actualTolerance = 1e-15 * Math.abs(b) + errorTol / 2; + newStep = (c - b) / 2; + if (Math.abs(newStep) <= actualTolerance || fb === 0) { + return b; + } + if (Math.abs(prevStep) >= actualTolerance && Math.abs(fa) > Math.abs(fb)) { + let t1, t2; + const cb = c - b; + if (a === c) { + t1 = fb / fa; + p = cb * t1; + q = 1 - t1; + } else { + ; + q = fa / fc, t1 = fb / fc, t2 = fb / fa; + p = t2 * (cb * q * (q - t1) - (b - a) * (t1 - 1)); + q = (q - 1) * (t1 - 1) * (t2 - 1); + } + if (p > 0) { + q = -q; + } else { + p = -p; + } + if (p < 0.75 * cb * q - Math.abs(actualTolerance * q) / 2 && p < Math.abs(prevStep * q / 2)) { + newStep = p / q; + } + } + if (Math.abs(newStep) < actualTolerance) { + newStep = newStep > 0 ? actualTolerance : -actualTolerance; + } + ; + a = b, fa = fb; + b += newStep, fb = func(b); + if (fb > 0 && fc > 0 || fb < 0 && fc < 0) { + ; + c = a, fc = fa; + } + if (Math.abs(fb) < errorTol) { + return b; + } + if (Math.abs(fb) < acceptableErrorTol) { + fallback = b; + } + } + return fallback; +} + +// src/mecanisms/inversion.ts +var evaluateInversion = function(node) { + const inversionEngine = this.shallowCopy(); + if (this.cache._meta.evaluationRuleStack.slice(1).includes(node.explanation.ruleToInverse)) { + return { + ...undefinedNumberNode, + ...node + }; + } + inversionEngine.cache._meta.parentRuleStack = [ + ...this.cache._meta.parentRuleStack + ]; + inversionEngine.cache._meta.evaluationRuleStack = [ + ...this.cache._meta.evaluationRuleStack + ]; + const inversionGoal = node.explanation.inversionCandidates.find( + (candidate) => { + if (this.cache._meta.evaluationRuleStack.includes(candidate.dottedName)) { + return false; + } + const evaluation = inversionEngine.evaluateNode( + inversionEngine.context.parsedRules[`${candidate.dottedName} . $SITUATION`] + ); + return typeof evaluation.nodeValue === "number" && !(candidate.dottedName in evaluation.missingVariables); + } + ); + if (inversionGoal === void 0) { + return { + ...node, + nodeValue: void 0, + missingVariables: { + ...Object.fromEntries( + node.explanation.inversionCandidates.map((candidate) => [ + candidate.dottedName, + 1 + ]) + ), + [node.explanation.ruleToInverse]: 1 + } + }; + } + const evaluatedInversionGoal = inversionEngine.evaluateNode(inversionGoal); + let numberOfIteration = 0; + inversionEngine.setSituation( + { + [inversionGoal.dottedName]: undefinedNumberNode + }, + { keepPreviousSituation: true } + ); + inversionEngine.cache.traversedVariablesStack = this.cache.traversedVariablesStack ? [] : void 0; + let lastEvaluation; + const evaluateWithValue = (n) => { + numberOfIteration++; + inversionEngine.setSituation( + { + [node.explanation.ruleToInverse]: { + nodeValue: n, + nodeKind: "constant", + type: "number", + unit: evaluatedInversionGoal.unit + } + }, + { keepPreviousSituation: true } + ); + inversionEngine.cache.traversedVariablesStack = this.cache.traversedVariablesStack ? [] : void 0; + lastEvaluation = inversionEngine.evaluateNode(inversionGoal); + return lastEvaluation; + }; + const goal = evaluatedInversionGoal.nodeValue; + let nodeValue = void 0; + const x1 = goal; + const y1Node = evaluateWithValue(x1); + const y1 = y1Node.nodeValue; + const coeff = y1 > goal ? 0.9 : 1.2; + const x2 = y1 !== void 0 ? x1 * goal * coeff / y1 : 2e3; + const y2Node = evaluateWithValue(x2); + const y2 = y2Node.nodeValue; + const maxIterations = this.context.inversionMaxIterations ?? 10; + if (y1 !== void 0 || y2 !== void 0) { + const test = (x) => { + const y = x === x1 ? y1 : x === x2 ? y2 : evaluateWithValue(x).nodeValue; + return y - goal; + }; + const defaultMin = -1e6; + const defaultMax = 1e8; + const nearestBelowGoal = y2 !== void 0 && y2 < goal && (y2 > y1 || y1 > goal) ? x2 : y1 !== void 0 && y1 < goal && (y1 > y2 || y2 > goal) ? x1 : defaultMin; + const nearestAboveGoal = y2 !== void 0 && y2 > goal && (y2 < y1 || y1 < goal) ? x2 : y1 !== void 0 && y1 > goal && (y1 < y2 || y2 < goal) ? x1 : defaultMax; + nodeValue = uniroot( + test, + nearestBelowGoal, + nearestAboveGoal, + 0.1, + maxIterations, + 1 + ); + } + if (nodeValue == void 0) { + this.cache.inversionFail = true; + } + if (this.cache.traversedVariablesStack) { + const traversedVariablesStack = this.cache.traversedVariablesStack[0]; + if (traversedVariablesStack) { + ; + (lastEvaluation.traversedVariables ?? []).forEach( + (v) => traversedVariablesStack.add(v) + ); + } + } + return { + ...node, + nodeValue, + unit: evaluatedInversionGoal.unit, + explanation: { + ...node.explanation, + inversionGoal, + numberOfIteration, + inversionFail: this.cache.inversionFail + }, + missingVariables: lastEvaluation.missingVariables + }; +}; +var mecanismInversion = (v, context) => { + let avec = typeof v === "object" && "avec" in v ? v.avec : v; + if (v === null) { + throw new PublicodesError( + "SyntaxError", + "Il manque les r\xE8gles avec laquelle effectuer le calcul d'inversion dans le m\xE9canisme `inversion num\xE9rique`", + { dottedName: context.dottedName } + ); + } + if (!Array.isArray(avec)) { + avec = [avec]; + } + return { + explanation: { + ruleToInverse: context.dottedName, + inversionCandidates: avec.map((node) => ({ + ...parse(node, context) + })) + }, + nodeKind: "inversion" + }; +}; +registerEvaluationFunction("inversion", evaluateInversion); + +// src/mecanisms/max-min.ts +var parseMaximumDe = createParseInlinedMecanismWithArray( + "le maximum de", + { + valeur: { type: "liste" } + }, + ({ valeur }) => valeur.reduce( + (acc, value) => ({ + condition: { + si: { + "est non applicable": "$INTERNAL valeur" + }, + alors: "$INTERNAL acc", + sinon: { + condition: { + si: { + ou: [ + { "est non applicable": "$INTERNAL acc" }, + { ">": ["$INTERNAL valeur", "$INTERNAL acc"] } + ] + }, + alors: "$INTERNAL valeur", + sinon: "$INTERNAL acc" + } + } + }, + avec: { + "[priv\xE9] $INTERNAL valeur": { valeur: value }, + "[priv\xE9] $INTERNAL acc": { valeur: acc } + } + }), + notApplicableNode + ) +); +var parseMinimumDe = createParseInlinedMecanismWithArray( + "le minimum de", + { + valeur: { type: "liste" } + }, + ({ valeur }) => valeur.reduce( + (acc, value) => ({ + condition: { + si: { + "est non applicable": "$INTERNAL valeur" + }, + alors: "$INTERNAL acc", + sinon: { + condition: { + si: { + ou: [ + { "est non applicable": "$INTERNAL acc" }, + { "<": ["$INTERNAL valeur", "$INTERNAL acc"] } + ] + }, + alors: "$INTERNAL valeur", + sinon: "$INTERNAL acc" + } + } + }, + avec: { + "[priv\xE9] $INTERNAL valeur": { valeur: value }, + "[priv\xE9] $INTERNAL acc": { valeur: acc } + } + }), + notApplicableNode + ) +); + +// src/mecanisms/somme.tsx +function reduceToSumNodes(valeurs) { + return valeurs.reverse().reduce((acc, value) => ({ "+": [value, acc] }), notApplicableNode); +} +var somme_default = createParseInlinedMecanismWithArray( + "somme", + { + valeur: { type: "liste" } + }, + ({ valeur }) => reduceToSumNodes([...valeur]) +); + +// src/mecanisms/moyenne.ts +var moyenne_default = createParseInlinedMecanismWithArray( + "moyenne", + { + valeur: { type: "liste" } + }, + ({ valeur }) => { + const valeurs = [...valeur]; + return { + "/": [ + reduceToSumNodes(valeurs), + reduceToSumNodes(valeurs.map(oneIfApplicable)) + ] + }; + } +); +function oneIfApplicable(exp) { + return { + "applicable si": { "est applicable": exp }, + valeur: 1 + }; +} + +// src/mecanisms/non-applicable.ts +var non_applicable_default = createParseInlinedMecanism( + "non applicable si", + { + "non applicable si": {}, + valeur: {} + }, + { + condition: { + si: "non applicable si = non", + alors: "valeur", + sinon: notApplicableNode + } + } +); + +// src/mecanisms/one-possibility.ts +var mecanismOnePossibility = (v, context) => { + if (Array.isArray(v)) { + v = { + possibilit\u00E9s: v + }; + } + return { + ...v, + explanation: v.possibilit\u00E9s.map((p) => parse(p, context)), + context: context.dottedName, + nodeKind: "une possibilit\xE9" + }; +}; +registerEvaluationFunction("une possibilit\xE9", (node) => ({ + ...node, + missingVariables: { [node.context]: 1 }, + nodeValue: void 0 +})); + +// src/mecanisms/operation.ts +var knownOperations = { + "*": [(a, b) => a * b, "\xD7"], + "/": [(a, b) => a / b, "\u2215"], + "+": [(a, b) => a + b], + "-": [(a, b) => a - b, "\u2212"], + "<": [(a, b) => a < b], + "<=": [(a, b) => a <= b, "\u2264"], + ">": [(a, b) => a > b], + ">=": [(a, b) => a >= b, "\u2265"], + "=": [(a, b) => (a ?? false) === (b ?? false)], + "!=": [(a, b) => (a ?? false) !== (b ?? false), "\u2260"], + et: [(a, b) => (a ?? false) && (b ?? false)], + ou: [(a, b) => (a ?? false) || (b ?? false)] +}; +var parseOperation = (k, symbol) => (v, context) => { + const explanation = v.map((node) => parse(node, context)); + return { + ...v, + nodeKind: "operation", + operationKind: k, + operator: symbol || k, + explanation + }; +}; +var evaluate8 = function(node) { + let node1 = this.evaluateNode(node.explanation[0]); + let evaluatedNode = { + ...node, + missingVariables: {} + }; + if (node1.nodeValue === null && ["<", ">", "<=", ">=", "/", "*", "-", "et"].includes( + node.operationKind + ) || node1.nodeValue === 0 && ["/", "*"].includes(node.operationKind) || node1.nodeValue === false && node.operationKind === "et" || node1.nodeValue === true && node.operationKind === "ou") { + return { + ...evaluatedNode, + nodeValue: node.operationKind === "et" ? false : node1.nodeValue, + missingVariables: node1.missingVariables + }; + } + let node2 = this.evaluateNode(node.explanation[1]); + evaluatedNode.explanation = [node1, node2]; + if (node.operationKind === "/" && node2.nodeValue === 0) { + throw new PublicodesError("EvaluationError", `Division by zero`, { + dottedName: this.cache._meta.evaluationRuleStack[0] + }); + } + if (node2.nodeValue === null && ["<", ">", "<=", ">=", "/", "*", "et"].includes(node.operationKind) || node2.nodeValue === 0 && ["*"].includes(node.operationKind) || node2.nodeValue === false && node.operationKind === "et" || node2.nodeValue === true && node.operationKind === "ou") { + return { + ...evaluatedNode, + nodeValue: node.operationKind === "et" ? false : node2.nodeValue, + missingVariables: node2.missingVariables + }; + } + evaluatedNode.missingVariables = mergeAllMissing([node1, node2]); + if (node1.nodeValue === void 0 || node2.nodeValue === void 0) { + evaluatedNode = { + ...evaluatedNode, + nodeValue: void 0 + }; + } + const isAdditionOrSubstractionWithPercentage = ["+", "-"].includes(node.operationKind) && serializeUnit(node2.unit) === "%" && serializeUnit(node1.unit) !== "%"; + if (!("nodeValue" in evaluatedNode) && !["/", "*"].includes(node.operationKind) && !isAdditionOrSubstractionWithPercentage) { + try { + if (node1.unit && "unit" in node2) { + node2 = convertNodeToUnit(node1.unit, node2); + } else if (node2.unit) { + node1 = convertNodeToUnit(node2.unit, node1); + } + } catch (e) { + warning( + this.context.logger, + `Dans l'expression '${node.operationKind}', la partie gauche (unit\xE9: ${serializeUnit( + node1.unit + )}) n'est pas compatible avec la partie droite (unit\xE9: ${serializeUnit( + node2.unit + )})`, + { dottedName: this.cache._meta.evaluationRuleStack[0] }, + e + ); + } + } + const operatorFunction = knownOperations[node.operationKind][0]; + const a = node1.nodeValue; + const b = node2.nodeValue; + evaluatedNode.nodeValue = "nodeValue" in evaluatedNode ? evaluatedNode.nodeValue : ["<", ">", "<=", ">=", "*", "/"].includes(node.operationKind) && node2.nodeValue === null ? null : [a, b].every( + (value) => typeof value === "string" && value.match?.(/^[\d]{2}\/[\d]{2}\/[\d]{4}$/) + ) ? ( + // We convert the date objects to timestamps to support comparison with the "===" operator: + // new Date('2020-01-01') !== new Date('2020-01-01') + operatorFunction( + convertToDate(a).getTime(), + convertToDate(b).getTime() + ) + ) : operatorFunction(a, b); + if (node.operationKind === "*" && inferUnit("*", [node1.unit, node2.unit])?.numerators.includes("%")) { + const unit = inferUnit("*", [node1.unit, node2.unit]); + const nodeValue = evaluatedNode.nodeValue; + return { + ...evaluatedNode, + nodeValue: typeof nodeValue === "number" ? nodeValue / 100 : nodeValue, + unit: inferUnit("*", [unit, { numerators: [], denominators: ["%"] }]) + }; + } + if (isAdditionOrSubstractionWithPercentage) { + const unit = inferUnit("*", [node1.unit, node2.unit]); + return { + ...evaluatedNode, + nodeValue: typeof node1.nodeValue === "number" && typeof node2.nodeValue === "number" ? node1.nodeValue * (1 + node2.nodeValue / 100 * (node.operationKind === "-" ? -1 : 1)) : evaluatedNode.nodeValue, + unit: inferUnit("*", [unit, { numerators: [], denominators: ["%"] }]) + }; + } + if (node.operationKind === "*" || node.operationKind === "/" || node.operationKind === "-" || node.operationKind === "+") { + return { + ...evaluatedNode, + unit: inferUnit(node.operationKind, [node1.unit, node2.unit]) + }; + } + return evaluatedNode; +}; +registerEvaluationFunction("operation", evaluate8); +var operationDispatch = Object.fromEntries( + Object.entries(knownOperations).map(([k, [, symbol]]) => [ + k, + parseOperation(k, symbol) + ]) +); +var operation_default = operationDispatch; + +// src/mecanisms/parDéfaut.ts +var parD_faut_default = createParseInlinedMecanism( + "par d\xE9faut", + { + "par d\xE9faut": {}, + valeur: {} + }, + { + condition: { + si: { "est non d\xE9fini": "valeur" }, + alors: "par d\xE9faut", + sinon: "valeur" + } + } +); + +// src/mecanisms/plafond.ts +var plafond_default = createParseInlinedMecanism( + "plafond", + { + plafond: {}, + valeur: {} + }, + { + condition: { + si: { et: ["plafond != non", "valeur > plafond"] }, + alors: "plafond", + sinon: "valeur" + } + } +); + +// src/mecanisms/plancher.ts +var plancher_default = createParseInlinedMecanism( + "plancher", + { + plancher: {}, + valeur: {} + }, + { + condition: { + si: { et: ["plancher != non", "valeur < plancher"] }, + alors: "plancher", + sinon: "valeur" + } + } +); + +// src/mecanisms/product.ts +function reduceToProduitNodes(valeurs) { + return valeurs.reduce((acc, value) => ({ "*": [value, acc] }), defaultNode(1)); +} +var product_default = createParseInlinedMecanismWithArray( + "produit", + { + valeur: { type: "liste" } + }, + ({ valeur }) => ({ + valeur: reduceToProduitNodes([...valeur]), + "simplifier l'unit\xE9": "oui" + }) +); + +// src/mecanisms/résoudre-référence-circulaire.ts +var evaluateR\u00E9soudreR\u00E9f\u00E9renceCirculaire = function(node) { + if (this.cache._meta.evaluationRuleStack.slice(1).includes(node.explanation.ruleToSolve)) { + return { + ...undefinedNumberNode, + ...node + }; + } + let numberOfIterations = 0; + const calculationEngine = this.shallowCopy(); + calculationEngine.cache._meta.parentRuleStack = [ + ...this.cache._meta.parentRuleStack + ]; + calculationEngine.cache._meta.evaluationRuleStack = [ + ...this.cache._meta.evaluationRuleStack + ]; + const maxIterations = this.context.inversionMaxIterations ?? 25; + const evaluateWithValue = (n) => { + numberOfIterations++; + calculationEngine.setSituation( + { + [node.explanation.ruleToSolve]: { + ...undefinedNumberNode, + nodeValue: n + } + }, + { keepPreviousSituation: true } + ); + return calculationEngine.evaluateNode(node.explanation.valeur); + }; + const inversionFailed = Symbol("inversion failed"); + let nodeValue = inversionFailed; + const x0 = 1; + let valeur = evaluateWithValue(x0); + const y0 = valeur.nodeValue; + const unit = valeur.unit; + if (y0 !== void 0) { + const test = (x) => { + if (x === x0) { + return y0 - x0; + } + valeur = evaluateWithValue(x); + const y = valeur.nodeValue; + return y - x; + }; + const defaultMin = -1e6; + const defaultMax = 1e8; + nodeValue = uniroot(test, defaultMin, defaultMax, 0.5, maxIterations, 2); + } + if (nodeValue === inversionFailed) { + nodeValue = void 0; + this.cache.inversionFail = true; + } + if (nodeValue !== void 0) { + valeur = evaluateWithValue(nodeValue); + } + return { + ...node, + unit, + nodeValue, + explanation: { + ...node.explanation, + valeur, + numberOfIterations + }, + missingVariables: valeur.missingVariables + }; +}; +function parseR\u00E9soudreR\u00E9f\u00E9renceCirculaire(v, context) { + return { + explanation: { + ruleToSolve: context.dottedName, + valeur: parse(v.valeur, context) + }, + nodeKind: "r\xE9soudre r\xE9f\xE9rence circulaire" + }; +} +parseR\u00E9soudreR\u00E9f\u00E9renceCirculaire.nom = "r\xE9soudre la r\xE9f\xE9rence circulaire"; +registerEvaluationFunction( + "r\xE9soudre r\xE9f\xE9rence circulaire", + evaluateR\u00E9soudreR\u00E9f\u00E9renceCirculaire +); + +// src/mecanisms/simplifier-unité.ts +function parseSimplifierUnit\u00E9(v, context) { + const explanation = parse(v.valeur, context); + return { + explanation, + nodeKind: "simplifier unit\xE9" + }; +} +parseSimplifierUnit\u00E9.nom = "simplifier l'unit\xE9"; +registerEvaluationFunction("simplifier unit\xE9", function evaluate9(node) { + const valeur = this.evaluateNode(node.explanation); + const nodeValue = valeur.nodeValue; + const defaultReturn = { + ...valeur, + ...node, + explanation: valeur + }; + if (nodeValue == null) { + return defaultReturn; + } + if (!valeur.unit) { + return { + ...defaultReturn, + unit: valeur.unit + }; + } + const unit = simplifyUnit(valeur.unit); + return { + ...defaultReturn, + nodeValue: typeof nodeValue === "number" ? convertUnit(valeur.unit, unit, nodeValue) : nodeValue, + unit + }; +}); + +// src/mecanisms/situation.ts +var situation_default = createParseInlinedMecanism( + "dans la situation", + { + valeur: {}, + "dans la situation": {} + }, + { + condition: { + si: { "est non d\xE9fini": "dans la situation" }, + alors: "valeur", + sinon: "dans la situation" + } + } +); + +// src/mecanisms/tauxProgressif.ts +function parseTauxProgressif(v, context) { + const explanation = { + assiette: parse(v.assiette, context), + multiplicateur: v.multiplicateur ? parse(v.multiplicateur, context) : defaultNode(1), + tranches: parseTranches(v.tranches, context) + }; + return { + explanation, + nodeKind: "taux progressif" + }; +} +var evaluate10 = function(node) { + const evaluate15 = this.evaluateNode.bind(this); + const assiette = this.evaluateNode(node.explanation.assiette); + const multiplicateur = this.evaluateNode(node.explanation.multiplicateur); + if (multiplicateur.nodeValue === 0) { + throw new PublicodesError("EvaluationError", `Division by zero`, { + dottedName: "" + }); + } + const tranches = evaluatePlafondUntilActiveTranche.call(this, { + parsedTranches: node.explanation.tranches, + assiette, + multiplicateur + }); + const evaluatedNode = { + ...node, + explanation: { + tranches, + assiette, + multiplicateur + }, + unit: parseUnit("%") + }; + const lastTranche = tranches[tranches.length - 1]; + if (tranches.every(({ isActive }) => isActive === false) || lastTranche.isActive && lastTranche.plafond.nodeValue === Infinity) { + const taux = convertNodeToUnit(parseUnit("%"), evaluate15(lastTranche.taux)); + const { nodeValue: nodeValue2, missingVariables } = taux; + lastTranche.taux = taux; + lastTranche.nodeValue = nodeValue2; + lastTranche.missingVariables = missingVariables; + return { + ...evaluatedNode, + nodeValue: nodeValue2, + missingVariables + }; + } + if (tranches.every(({ isActive }) => isActive !== true) || typeof assiette.nodeValue !== "number") { + return { + ...evaluatedNode, + nodeValue: void 0, + missingVariables: mergeAllMissing(tranches) + }; + } + const activeTrancheIndex = tranches.findIndex( + ({ isActive }) => isActive === true + ); + const activeTranche = tranches[activeTrancheIndex]; + activeTranche.taux = convertNodeToUnit( + parseUnit("%"), + evaluate15(activeTranche.taux) + ); + const previousTranche = tranches[activeTrancheIndex - 1]; + if (previousTranche) { + previousTranche.taux = convertNodeToUnit( + parseUnit("%"), + evaluate15(previousTranche.taux) + ); + previousTranche.isActive = true; + } + const previousTaux = previousTranche ? previousTranche.taux : activeTranche.taux; + const calculationValues = [previousTaux, activeTranche.taux]; + if (calculationValues.some((n) => n.nodeValue === void 0)) { + activeTranche.nodeValue = void 0; + return { + ...evaluatedNode, + nodeValue: void 0, + missingVariables: mergeAllMissing(calculationValues) + }; + } + const lowerTaux = previousTaux.nodeValue; + const upperTaux = activeTranche.taux.nodeValue; + const plancher = activeTranche.plancherValue; + const plafond = activeTranche.plafondValue; + const coeff = (upperTaux - lowerTaux) / (plafond - plancher); + const nodeValue = lowerTaux + (assiette.nodeValue - plancher) * coeff; + activeTranche.nodeValue = nodeValue; + return { + ...evaluatedNode, + nodeValue, + missingVariables: {} + }; +}; +registerEvaluationFunction("taux progressif", evaluate10); + +// src/mecanisms/texte.ts +var NAME = "texte"; +function parseTexte(texte, context) { + const explanation = []; + let lastIndex = 0; + for (const { 0: expression, index } of texte.matchAll(/{{(.|\n)*?}}/g)) { + const publicodeExpression = expression.slice(2, -2).trim(); + const parsedNode = parse(publicodeExpression, context); + explanation.push(texte.substring(lastIndex, index), parsedNode); + lastIndex = (index ?? 0) + expression.length; + } + explanation.push(texte.slice(lastIndex)); + return { + nodeKind: NAME, + explanation + }; +} +parseTexte.nom = NAME; +registerEvaluationFunction(NAME, function evaluate11(node) { + const explanation = node.explanation.map( + (element) => typeof element === "string" ? element : this.evaluateNode(element) + ); + return { + ...node, + explanation, + missingVariables: mergeAllMissing( + node.explanation.filter( + (element) => typeof element !== "string" + ) + ), + nodeValue: explanation.map( + (element) => typeof element === "string" ? element : formatValue(element) + ).join("") + }; +}); + +// src/mecanisms/toutes-ces-conditions.ts +var toutes_ces_conditions_default = createParseInlinedMecanismWithArray( + "toutes ces conditions", + { + valeur: { type: "liste" } + }, + ({ valeur }) => valeur.reduce( + (acc, value) => ({ et: [acc, value] }), + "oui" + ) +); + +// src/mecanisms/une-de-ces-conditions.ts +var une_de_ces_conditions_default = createParseInlinedMecanismWithArray( + "une de ces conditions", + { + valeur: { type: "liste" } + }, + ({ valeur }) => valeur.reduce( + (acc, value) => ({ ou: [acc, value] }), + "non" + ) +); + +// src/mecanisms/unité.ts +function parseUnit\u00E9(v, context) { + const explanation = parse(v.valeur, context); + const unit = parseUnit(v.unit\u00E9, context.getUnitKey); + return { + explanation, + unit, + nodeKind: parseUnit\u00E9.nom + }; +} +parseUnit\u00E9.nom = "unit\xE9"; +registerEvaluationFunction(parseUnit\u00E9.nom, function evaluate12(node) { + const valeur = this.evaluateNode(node.explanation); + let nodeValue = valeur.nodeValue; + if (nodeValue !== null && "unit" in node) { + try { + nodeValue = convertUnit( + valeur.unit, + node.unit, + valeur.nodeValue + ); + } catch (e) { + warning( + this.context.logger, + "Erreur lors de la conversion d'unit\xE9 explicite", + { dottedName: this.cache._meta.evaluationRuleStack[0] }, + e + ); + } + } + return { + ...node, + nodeValue, + explanation: valeur, + missingVariables: valeur.missingVariables + }; +}); + +// src/mecanisms/variablesManquantes.ts +function parseVariableManquante(v, context) { + return { + missingVariable: v["variable manquante"], + nodeKind: parseVariableManquante.nom, + explanation: parse(v.valeur, context) + }; +} +parseVariableManquante.nom = "variable manquante"; +registerEvaluationFunction(parseVariableManquante.nom, function evaluate13(node) { + const valeur = this.evaluateNode(node.explanation); + const maxMissingScore = Object.values(valeur.missingVariables).reduce( + (a, b) => a > b ? a : b, + 0 + ); + return { + ...node, + nodeValue: valeur.nodeValue, + unit: valeur.unit, + explanation: valeur, + missingVariables: mergeMissing(valeur.missingVariables, { + [node.missingVariable]: maxMissingScore + 1 + }) + }; +}); + +// src/mecanisms/variations.ts +function parseVariations(v, context) { + const explanation = v.map( + ({ si, alors, sinon }) => sinon !== void 0 ? { consequence: parse(sinon, context), condition: defaultNode(true) } : { consequence: parse(alors, context), condition: parse(si, context) } + ); + return { + explanation, + nodeKind: "variations" + }; +} +var evaluate14 = function(node) { + const [nodeValue, explanation, unit] = node.explanation.reduce( + ([evaluation, explanations, unit2, previousConditions], { condition, consequence }, i) => { + if (previousConditions === true) { + return [ + evaluation, + [...explanations, { condition, consequence }], + unit2, + previousConditions + ]; + } + const evaluatedCondition = this.evaluateNode(condition); + const currentCondition = previousConditions === void 0 ? previousConditions : !previousConditions && (evaluatedCondition.nodeValue === void 0 ? void 0 : evaluatedCondition.nodeValue !== false && evaluatedCondition.nodeValue !== null); + if (currentCondition === false || currentCondition === null) { + return [ + evaluation, + [...explanations, { condition: evaluatedCondition, consequence }], + unit2, + previousConditions + ]; + } + let evaluatedConsequence = void 0; + if (evaluatedCondition.nodeValue !== false && evaluatedCondition.nodeValue !== null) { + evaluatedConsequence = this.evaluateNode(consequence); + if (unit2) { + try { + evaluatedConsequence = convertNodeToUnit( + unit2, + evaluatedConsequence + ); + } catch (e) { + warning( + this.context.logger, + `L'unit\xE9 de la branche n\xB0 ${i + 1} du m\xE9canisme 'variations' n'est pas compatible avec celle d'une branche pr\xE9c\xE9dente`, + { dottedName: this.cache._meta.evaluationRuleStack[0] }, + e + ); + } + } + } + return [ + currentCondition && evaluatedConsequence?.nodeValue, + [ + ...explanations, + { + condition: evaluatedCondition, + consequence: evaluatedConsequence ?? consequence + } + ], + unit2 || evaluatedConsequence?.unit, + previousConditions || currentCondition + ]; + }, + [null, [], void 0, false] + ); + return { + ...node, + nodeValue, + ...unit !== void 0 && { unit }, + explanation, + missingVariables: explanation.reduce( + (values, { condition, consequence }) => mergeMissing( + values, + mergeMissing( + bonus(condition.missingVariables), + "nodeValue" in condition && condition.nodeValue !== false && condition.nodeValue !== null ? consequence.missingVariables : {} + ) + ), + {} + ) + }; +}; +registerEvaluationFunction("variations", evaluate14); + +// src/parseExpression.ts +var import_nearley = __toESM(require_nearley(), 1); + +// src/grammarFunctions.js +var binaryOperation = ([A, , operator, , B]) => ({ + [operator.value.toLowerCase()]: [A, B] +}); +var unaryOperation = ([operator, , A]) => ({ + [operator]: [number([{ value: "0" }]), A] +}); +var variable = (arg) => { + return { + variable: arg.value + }; +}; +var JSONObject = ([{ value }]) => { + value; +}; +var number = ([{ value }]) => ({ + constant: { + type: "number", + nodeValue: parseFloat(value) + } +}); +var numberWithUnit = (value) => ({ + ...number(value), + unit\u00E9: value[2].value +}); +var date = ([{ value }]) => { + return { + constant: { + type: "date", + nodeValue: normalizeDateString(value) + } + }; +}; +var boolean = ([{ value }]) => ({ + constant: { + type: "boolean", + nodeValue: value === "oui" + } +}); +var string = ([{ value }]) => ({ + constant: { + type: "string", + nodeValue: value.slice(1, -1) + } +}); + +// src/grammar.codegen.js +var import_moo = __toESM(require_moo(), 1); +function id(x) { + return x[0]; +} +var dateRegexp = `(?:(?:0?[1-9]|[12][0-9]|3[01])\\/)?(?:0?[1-9]|1[012])\\/\\d{4}`; +var letter = "[a-zA-Z\xC0-\u017F\u20AC$%\xB0]"; +var letterOrNumber = "[a-zA-Z\xC0-\u017F0-9',]"; +var word = `${letter}(?:[-']?${letterOrNumber}+)*`; +var numberRegExp = "-?(?:[1-9][0-9]+|[0-9])(?:\\.[0-9]+)?"; +var lexer = import_moo.default.compile({ + "(": "(", + ")": ")", + "[": "[", + "]": "]", + comparison: [">", "<", ">=", "<=", "=", "!="], + date: new RegExp(dateRegexp), + boolean: ["oui", "non"], + number: new RegExp(numberRegExp), + word: new RegExp(word), + string: [/'.*'/, /".*"/], + parentSelector: "^", + JSONObject: /{.*}/, + additionSubstraction: /[\+-]/, + multiplicationDivision: ["*", "/"], + dot: " . ", + ".": ".", + space: { match: /[\s]+/, lineBreaks: true } +}); +var join = (args) => ({ value: args.map((x) => x && x.value).join("") }); +var flattenJoin = (args) => join(args.flat()); +var Lexer = lexer; +var ParserRules = [ + { "name": "main", "symbols": ["Comparison"], "postprocess": id }, + { "name": "main", "symbols": ["NumericValue"], "postprocess": id }, + { "name": "main", "symbols": ["Date"], "postprocess": id }, + { "name": "main", "symbols": ["NonNumericTerminal"], "postprocess": id }, + { "name": "main", "symbols": ["JSONObject"], "postprocess": id }, + { "name": "NumericValue", "symbols": ["AdditionSubstraction"], "postprocess": id }, + { "name": "NumericValue", "symbols": ["Negation"], "postprocess": id }, + { "name": "NumericTerminal", "symbols": ["Variable"], "postprocess": id }, + { "name": "NumericTerminal", "symbols": ["number"], "postprocess": id }, + { "name": "Negation", "symbols": [{ "literal": "-" }, lexer.has("space") ? { type: "space" } : space, "Parentheses"], "postprocess": unaryOperation }, + { "name": "Parentheses", "symbols": [{ "literal": "(" }, lexer.has("space") ? { type: "space" } : space, "NumericValue", lexer.has("space") ? { type: "space" } : space, { "literal": ")" }], "postprocess": ([, , e]) => e }, + { "name": "Parentheses", "symbols": [{ "literal": "(" }, "NumericValue", { "literal": ")" }], "postprocess": ([, e]) => e }, + { "name": "Parentheses", "symbols": ["NumericTerminal"], "postprocess": id }, + { "name": "Date", "symbols": ["Variable"], "postprocess": id }, + { "name": "Date", "symbols": [lexer.has("date") ? { type: "date" } : date], "postprocess": date }, + { "name": "Comparison", "symbols": ["Comparable", lexer.has("space") ? { type: "space" } : space, lexer.has("comparison") ? { type: "comparison" } : comparison, lexer.has("space") ? { type: "space" } : space, "Comparable"], "postprocess": binaryOperation }, + { "name": "Comparison", "symbols": ["Date", lexer.has("space") ? { type: "space" } : space, lexer.has("comparison") ? { type: "comparison" } : comparison, lexer.has("space") ? { type: "space" } : space, "Date"], "postprocess": binaryOperation }, + { "name": "Comparable$subexpression$1", "symbols": ["AdditionSubstraction"] }, + { "name": "Comparable$subexpression$1", "symbols": ["NonNumericTerminal"] }, + { "name": "Comparable", "symbols": ["Comparable$subexpression$1"], "postprocess": ([[e]]) => e }, + { "name": "NonNumericTerminal", "symbols": [lexer.has("boolean") ? { type: "boolean" } : boolean], "postprocess": boolean }, + { "name": "NonNumericTerminal", "symbols": [lexer.has("string") ? { type: "string" } : string], "postprocess": string }, + { "name": "Variable", "symbols": ["VariableWithoutParentSelector"], "postprocess": ([x]) => variable(x) }, + { "name": "Variable$ebnf$1", "symbols": [] }, + { "name": "Variable$ebnf$1$subexpression$1", "symbols": [lexer.has("parentSelector") ? { type: "parentSelector" } : parentSelector, lexer.has("dot") ? { type: "dot" } : dot], "postprocess": join }, + { "name": "Variable$ebnf$1", "symbols": ["Variable$ebnf$1", "Variable$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) { + return d[0].concat([d[1]]); + } }, + { "name": "Variable", "symbols": ["Variable$ebnf$1", "VariableWithoutParentSelector"], "postprocess": (x) => variable(flattenJoin(x)) }, + { "name": "VariableWithoutParentSelector$ebnf$1", "symbols": [] }, + { "name": "VariableWithoutParentSelector$ebnf$1$subexpression$1", "symbols": [lexer.has("dot") ? { type: "dot" } : dot, "Words"], "postprocess": join }, + { "name": "VariableWithoutParentSelector$ebnf$1", "symbols": ["VariableWithoutParentSelector$ebnf$1", "VariableWithoutParentSelector$ebnf$1$subexpression$1"], "postprocess": function arrpush2(d) { + return d[0].concat([d[1]]); + } }, + { "name": "VariableWithoutParentSelector", "symbols": ["Words", "VariableWithoutParentSelector$ebnf$1"], "postprocess": (x) => flattenJoin(x) }, + { "name": "Words$ebnf$1$subexpression$1$ebnf$1", "symbols": [lexer.has("space") ? { type: "space" } : space], "postprocess": id }, + { "name": "Words$ebnf$1$subexpression$1$ebnf$1", "symbols": [], "postprocess": function(d) { + return null; + } }, + { "name": "Words$ebnf$1$subexpression$1", "symbols": ["Words$ebnf$1$subexpression$1$ebnf$1", "WordOrNumber"], "postprocess": join }, + { "name": "Words$ebnf$1", "symbols": ["Words$ebnf$1$subexpression$1"] }, + { "name": "Words$ebnf$1$subexpression$2$ebnf$1", "symbols": [lexer.has("space") ? { type: "space" } : space], "postprocess": id }, + { "name": "Words$ebnf$1$subexpression$2$ebnf$1", "symbols": [], "postprocess": function(d) { + return null; + } }, + { "name": "Words$ebnf$1$subexpression$2", "symbols": ["Words$ebnf$1$subexpression$2$ebnf$1", "WordOrNumber"], "postprocess": join }, + { "name": "Words$ebnf$1", "symbols": ["Words$ebnf$1", "Words$ebnf$1$subexpression$2"], "postprocess": function arrpush3(d) { + return d[0].concat([d[1]]); + } }, + { "name": "Words", "symbols": ["WordOrKeyword", "Words$ebnf$1"], "postprocess": flattenJoin }, + { "name": "Words", "symbols": [lexer.has("word") ? { type: "word" } : word], "postprocess": id }, + { "name": "WordOrKeyword", "symbols": [lexer.has("word") ? { type: "word" } : word], "postprocess": id }, + { "name": "WordOrKeyword", "symbols": [lexer.has("boolean") ? { type: "boolean" } : boolean], "postprocess": id }, + { "name": "WordOrNumber", "symbols": ["WordOrKeyword"], "postprocess": id }, + { "name": "WordOrNumber", "symbols": [lexer.has("number") ? { type: "number" } : number], "postprocess": id }, + { "name": "Unit$ebnf$1", "symbols": [] }, + { "name": "Unit$ebnf$1", "symbols": ["Unit$ebnf$1", "UnitNumerator"], "postprocess": function arrpush4(d) { + return d[0].concat([d[1]]); + } }, + { "name": "Unit$ebnf$2", "symbols": [] }, + { "name": "Unit$ebnf$2", "symbols": ["Unit$ebnf$2", "UnitDenominator"], "postprocess": function arrpush5(d) { + return d[0].concat([d[1]]); + } }, + { "name": "Unit", "symbols": ["Unit$ebnf$1", "Unit$ebnf$2"], "postprocess": flattenJoin }, + { "name": "UnitNumerator", "symbols": ["Words"], "postprocess": id }, + { "name": "UnitNumerator", "symbols": [{ "literal": "." }, "UnitNumerator"], "postprocess": join }, + { "name": "UnitDenominator$ebnf$1", "symbols": [] }, + { "name": "UnitDenominator$ebnf$1$subexpression$1", "symbols": [lexer.has("space") ? { type: "space" } : space] }, + { "name": "UnitDenominator$ebnf$1", "symbols": ["UnitDenominator$ebnf$1", "UnitDenominator$ebnf$1$subexpression$1"], "postprocess": function arrpush6(d) { + return d[0].concat([d[1]]); + } }, + { "name": "UnitDenominator$ebnf$2", "symbols": ["UnitNumerator"] }, + { "name": "UnitDenominator$ebnf$2", "symbols": ["UnitDenominator$ebnf$2", "UnitNumerator"], "postprocess": function arrpush7(d) { + return d[0].concat([d[1]]); + } }, + { "name": "UnitDenominator", "symbols": ["UnitDenominator$ebnf$1", { "literal": "/" }, "UnitDenominator$ebnf$2"], "postprocess": flattenJoin }, + { "name": "AdditionSubstraction", "symbols": ["AdditionSubstraction", lexer.has("space") ? { type: "space" } : space, lexer.has("additionSubstraction") ? { type: "additionSubstraction" } : additionSubstraction, lexer.has("space") ? { type: "space" } : space, "MultiplicationDivision"], "postprocess": binaryOperation }, + { "name": "AdditionSubstraction", "symbols": ["MultiplicationDivision"], "postprocess": id }, + { "name": "MultiplicationDivision", "symbols": ["MultiplicationDivision", lexer.has("space") ? { type: "space" } : space, lexer.has("multiplicationDivision") ? { type: "multiplicationDivision" } : multiplicationDivision, lexer.has("space") ? { type: "space" } : space, "Parentheses"], "postprocess": binaryOperation }, + { "name": "MultiplicationDivision", "symbols": ["Parentheses"], "postprocess": id }, + { "name": "number", "symbols": [lexer.has("number") ? { type: "number" } : number], "postprocess": number }, + { "name": "number$ebnf$1$subexpression$1", "symbols": [lexer.has("space") ? { type: "space" } : space] }, + { "name": "number$ebnf$1", "symbols": ["number$ebnf$1$subexpression$1"], "postprocess": id }, + { "name": "number$ebnf$1", "symbols": [], "postprocess": function(d) { + return null; + } }, + { "name": "number", "symbols": [lexer.has("number") ? { type: "number" } : number, "number$ebnf$1", "Unit"], "postprocess": numberWithUnit }, + { "name": "JSONObject", "symbols": [lexer.has("JSONObject") ? { type: "JSONObject" } : JSONObject], "postprocess": JSONObject } +]; +var ParserStart = "main"; +var grammar_codegen_default = { Lexer, ParserRules, ParserStart }; + +// src/parseExpression.ts +var { Grammar, Parser } = import_nearley.default; +var compiledGrammar = Grammar.fromCompiled(grammar_codegen_default); +var parser = new Parser(compiledGrammar); +var initialState = parser.save(); +function parseExpression(rawNode, dottedName) { + const singleLineExpression = (rawNode + "").replace(/\s*\n\s*/g, " ").trim(); + try { + parser.restore(initialState); + const [parseResult] = parser.feed(singleLineExpression).results; + if (parseResult == null) { + throw new PublicodesError( + "InternalError", + ` +Un probl\xE8me est survenu lors du parsing de l'expression \`${singleLineExpression}\` : + + le parseur Nearley n'a pas r\xE9ussi \xE0 parser l'expression. +`, + { dottedName } + ); + } + return parseResult; + } catch (e) { + if (e instanceof PublicodesError) { + throw e; + } + throw new PublicodesError( + "SyntaxError", + `\`${singleLineExpression}\` n'est pas une expression valide`, + { dottedName }, + e + ); + } +} + +// src/reference.ts +function parseReference(v, context) { + if (!context.dottedName) { + throw new PublicodesError( + "InternalError", + "Une r\xE9f\xE9rence ne peut pas exister en dehors d'une r\xE8gle (`context.dottedName` est vide)", + { + dottedName: v + } + ); + } + if (!v) { + throw new PublicodesError( + "SyntaxError", + "Une r\xE9f\xE9rence ne peut pas \xEAtre vide", + { + dottedName: context.dottedName + } + ); + } + return { + nodeKind: "reference", + name: v, + contextDottedName: context.dottedName + }; +} +registerEvaluationFunction("reference", function evaluateReference(node) { + if (!node.dottedName) { + throw new PublicodesInternalError(node); + } + const explanation = this.evaluateNode( + this.context.parsedRules[node.dottedName] + ); + delete explanation.sourceMap; + return { + ...explanation, + ...node + }; +}); + +// src/parse.ts +function parse(rawNode, context) { + if (rawNode == void 0) { + throw new PublicodesError( + "SyntaxError", + ` + Une des valeurs de la formule est vide. + V\xE9rifiez que tous les champs \xE0 droite des deux points sont remplis`, + { dottedName: context.dottedName } + ); + } + if (typeof rawNode === "boolean") { + throw new PublicodesError( + "SyntaxError", + ` +Les valeurs bool\xE9ennes true / false ne sont accept\xE9es. +Utilisez leur contrepartie fran\xE7aise : 'oui' / 'non'`, + { dottedName: context.dottedName } + ); + } + const node = typeof rawNode === "object" ? rawNode : parseExpression(rawNode, context.dottedName); + if ("nodeKind" in node) { + return node; + } + return { + ...parseChainedMecanisms(node, context), + rawNode + }; +} +function parseMecanism(rawNode, context) { + if (Array.isArray(rawNode)) { + throw new PublicodesError( + "SyntaxError", + ` +Il manque le nom du m\xE9canisme pour le tableau : [${rawNode.map((x) => `'${x}'`).join(", ")}] +Les m\xE9canisme possibles sont : 'somme', 'le maximum de', 'le minimum de', 'toutes ces conditions', 'une de ces conditions'. + `, + { dottedName: context.dottedName } + ); + } + const keys = Object.keys(rawNode); + if (keys.length > 1) { + throw new PublicodesError( + "SyntaxError", + ` +Les m\xE9canismes suivants se situent au m\xEAme niveau : ${keys.map((x) => `'${x}'`).join(", ")} +Cela vient probablement d'une erreur dans l'indentation + `, + { dottedName: context.dottedName } + ); + } + if (keys.length === 0) { + return { nodeKind: "constant", nodeValue: void 0 }; + } + const mecanismName = keys[0]; + const values = rawNode[mecanismName]; + const parseFn = parseFunctions[mecanismName]; + if (!parseFn) { + throw new PublicodesError( + "SyntaxError", + `Le m\xE9canisme "${mecanismName}" est inconnu. + +V\xE9rifiez qu'il n'y ait pas d'erreur dans l'orthographe du nom.`, + { dottedName: context.dottedName } + ); + } + try { + return parseFn(values, context); + } catch (e) { + if (e instanceof PublicodesError) { + throw e; + } + throw new PublicodesError( + "SyntaxError", + mecanismName ? `\u27A1\uFE0F Dans le m\xE9canisme ${mecanismName} +${e.message}` : e.message, + { dottedName: context.dottedName } + ); + } +} +var chainableMecanisms = [ + parseMecanismContexte, + parseVariableManquante, + parseAvec, + applicable_default, + non_applicable_default, + parseArrondi, + parseUnit\u00E9, + parseSimplifierUnit\u00E9, + plancher_default, + plafond_default, + parD_faut_default, + situation_default, + parseR\u00E9soudreR\u00E9f\u00E9renceCirculaire, + abattement_default +]; +function parseChainedMecanisms(rawNode, context) { + const parseFn = chainableMecanisms.find((fn) => fn.nom in rawNode); + if (!parseFn) { + return parseMecanism(rawNode, context); + } + const { [parseFn.nom]: param, ...valeur } = rawNode; + return parseMecanism( + { + [parseFn.nom]: { + valeur, + [parseFn.nom]: param + } + }, + context + ); +} +var parseFunctions = { + ...operation_default, + ...chainableMecanisms.reduce((acc, fn) => ({ [fn.nom]: fn, ...acc }), {}), + "inversion num\xE9rique": mecanismInversion, + "le maximum de": parseMaximumDe, + "le minimum de": parseMinimumDe, + "taux progressif": parseTauxProgressif, + "toutes ces conditions": toutes_ces_conditions_default, + "est non d\xE9fini": parseEstNonD\u00E9fini, + "est non applicable": parseEstNonApplicable, + "est applicable": parseEstApplicable, + "est d\xE9fini": parseEstD\u00E9fini, + "une de ces conditions": une_de_ces_conditions_default, + "une possibilit\xE9": mecanismOnePossibility, + condition: parseCondition, + bar\u00E8me: parseBar\u00E8me, + dur\u00E9e: dur_e_default, + grille: parseGrille, + multiplication: product_default, + produit: product_default, + somme: somme_default, + moyenne: moyenne_default, + [parseTexte.nom]: parseTexte, + valeur: parse, + variable: parseReference, + variations: parseVariations, + constant: (v) => ({ + type: v.type, + // In the documentation we want to display constants defined in the source + // with their full precision. This is especially useful for percentages like + // APEC 0,036 %. + fullPrecision: true, + isNullable: v.nodeValue == null, + missingVariables: {}, + nodeValue: v.nodeValue, + nodeKind: "constant" + }) +}; +var mecanismKeys = Object.keys(parseFunctions); + +// src/replacement.ts +var remplacementRuleId = 0; +var cache = {}; +function parseReplacements(replacements, context) { + if (!replacements) { + return []; + } + return (Array.isArray(replacements) ? replacements : [replacements]).map( + (replacement) => { + if (typeof replacement === "string") { + replacement = { "r\xE9f\xE9rences \xE0": replacement }; + } + const replacedReference = parse(replacement["r\xE9f\xE9rences \xE0"], context); + const [whiteListedNames, blackListedNames] = [ + replacement.dans ?? [], + replacement["sauf dans"] ?? [] + ].map( + (dottedName) => Array.isArray(dottedName) ? dottedName : [dottedName] + ).map((refs) => refs.map((ref) => parse(ref, context))); + if (replacement.priorit\u00E9 != null && (typeof replacement.priorit\u00E9 !== "number" || replacement.priorit\u00E9 < 0)) { + throw new PublicodesError( + "SyntaxError", + "La priorit\xE9 du remplacement doit \xEAtre un nombre positif", + context + ); + } + return { + nodeKind: "replacementRule", + rawNode: replacement, + priority: replacement.priorit\u00E9, + definitionRule: parse(context.dottedName, context), + replacedReference, + replaceByNonApplicable: false, + whiteListedNames, + blackListedNames, + remplacementRuleId: remplacementRuleId++ + }; + } + ); +} +function parseRendNonApplicable(rules, context) { + const rendNonApplicableReplacements = parseReplacements(rules, context); + rendNonApplicableReplacements.forEach( + (r) => r.replaceByNonApplicable = true + ); + return rendNonApplicableReplacements; +} +function getReplacements(parsedRules) { + const ret = {}; + for (const dottedName in parsedRules) { + const rule = parsedRules[dottedName]; + for (const replacement of rule.replacements) { + if (!replacement.replacedReference.dottedName) { + throw new PublicodesInternalError(replacement); + } + const key = replacement.replacedReference.dottedName; + ret[key] = [...ret[key] ?? [], replacement]; + } + } + return ret; +} +function inlineReplacements({ + newRules, + previousReplacements, + parsedRules, + referencesMaps +}) { + const newReplacements = getReplacements(newRules); + const ruleNamesWithNewReplacements = /* @__PURE__ */ new Set([]); + for (const replacedReference in newReplacements) { + const rulesThatUse = referencesMaps.rulesThatUse.get(replacedReference) ?? []; + for (const value of rulesThatUse) { + ruleNamesWithNewReplacements.add(value); + } + } + const newRuleNamesWithPreviousReplacements = new Set( + Object.keys(newRules).filter( + (ruleName) => [...referencesMaps.referencesIn.get(ruleName) ?? /* @__PURE__ */ new Set()].some( + (reference) => (previousReplacements[reference] ?? []).length + ) + ) + ); + const replacements = mergeWithArray(previousReplacements, newReplacements); + if (!newRuleNamesWithPreviousReplacements.size && !ruleNamesWithNewReplacements.size) { + return [parsedRules, replacements]; + } + const inlinePreviousReplacement = makeReplacementInliner( + previousReplacements, + referencesMaps + ); + const inlineNewReplacement = makeReplacementInliner( + newReplacements, + referencesMaps + ); + newRuleNamesWithPreviousReplacements.forEach((name) => { + parsedRules[name] = inlinePreviousReplacement( + parsedRules[name] + ); + }); + ruleNamesWithNewReplacements.forEach((name) => { + parsedRules[name] = inlineNewReplacement( + parsedRules[name] + ); + }); + return [parsedRules, replacements]; +} +function makeReplacementInliner(replacements, referencesMaps) { + return makeASTTransformer((node, transform) => { + if (node.nodeKind === "replacementRule" || node.nodeKind === "inversion" || node.nodeKind === "une possibilit\xE9") { + return false; + } + if (node.nodeKind === "contexte") { + return { + ...node, + explanation: { + ...node.explanation, + valeur: transform(node.explanation.valeur), + contexte: node.explanation.contexte.map(([name, value]) => [ + name, + transform(value) + ]) + } + }; + } + if (node.nodeKind === "reference") { + if (!node.dottedName) { + throw new PublicodesInternalError(node); + } + const replacedReferenceNode = replace( + node, + replacements[node.dottedName] ?? [] + ); + makeASTVisitor((n) => { + updateReferencesMapsFromReferenceNode( + n, + referencesMaps, + node.contextDottedName + ); + return "continue"; + })(replacedReferenceNode); + return replacedReferenceNode; + } + }); +} +function replace(node, replacements) { + const applicableReplacements = replacements.filter( + ({ definitionRule }) => definitionRule.dottedName !== node.contextDottedName + ).filter( + ({ whiteListedNames }) => !whiteListedNames.length || whiteListedNames.some( + (name) => node.contextDottedName.startsWith(name.dottedName) + ) + ).filter( + ({ blackListedNames }) => !blackListedNames.length || blackListedNames.every( + (name) => !node.contextDottedName.startsWith(name.dottedName) + ) + ).reverse().sort((a, b) => { + const result = (b.priority ?? 0) - (a.priority ?? 0); + if (result !== 0) { + return result; + } + return b.definitionRule.dottedName.localeCompare( + a.definitionRule.dottedName + ); + }); + if (!applicableReplacements.length) { + return node; + } + const applicableReplacementsCacheKey = applicableReplacements.map((n) => n.remplacementRuleId).join("-"); + if (cache[applicableReplacementsCacheKey]) { + return cache[applicableReplacementsCacheKey]; + } + const replacementNode = { + nodeKind: "variations", + explanation: [ + ...applicableReplacements.map( + ({ definitionRule, replaceByNonApplicable }) => replaceByNonApplicable ? { + condition: definitionRule, + consequence: notApplicableNode + } : { + condition: estApplicable(definitionRule), + consequence: definitionRule + } + ), + { condition: oui, consequence: node } + ] + }; + replacementNode.sourceMap = { + mecanismName: "replacement", + args: { + applicableReplacements, + originalNode: node + } + }; + cache[applicableReplacementsCacheKey] = replacementNode; + return cache[applicableReplacementsCacheKey]; +} +function estApplicable(node) { + return { + nodeKind: "condition", + explanation: { + si: { nodeKind: "est non applicable", explanation: node }, + alors: non, + sinon: oui + } + }; +} +var oui = defaultNode(true); +var non = defaultNode(false); + +// src/parsePublicodes.ts +function createContext(partialContext) { + return { + dottedName: "", + logger: console, + getUnitKey: (x) => x, + parsedRules: {}, + referencesMaps: { referencesIn: /* @__PURE__ */ new Map(), rulesThatUse: /* @__PURE__ */ new Map() }, + nodesTypes: /* @__PURE__ */ new WeakMap(), + rulesReplacements: {}, + allowOrphanRules: false, + subEngineIncrementingNumber: 1, + ...partialContext + }; +} +function copyContext(context) { + return { + ...context, + parsedRules: { ...context.parsedRules }, + referencesMaps: { + referencesIn: new Map(context.referencesMaps.referencesIn), + rulesThatUse: new Map(context.referencesMaps.rulesThatUse) + } + }; +} +function parsePublicodes(rawRules, partialContext = createContext({})) { + if (typeof rawRules === "string") + throw new PublicodesError( + "EngineError", + "Publicodes does not parse yaml rule sets itself anymore. Please provide a parsed js object. E.g. the `eemeli/yaml` package.", + {} + ); + const rules = weakCopyObj(rawRules); + const context = createContext(partialContext); + const previousParsedRules = context.parsedRules; + context.parsedRules = {}; + parseRules(rules, context); + let parsedRules = {}; + for (const dottedName in previousParsedRules) { + parsedRules[dottedName] = previousParsedRules[dottedName]; + } + for (const dottedName in context.parsedRules) { + parsedRules[dottedName] = context.parsedRules[dottedName]; + } + const [newRules, referencesMaps] = disambiguateReferencesAndCollectDependencies( + parsedRules, + context.parsedRules, + context.referencesMaps, + context.allowOrphanRules + ); + let rulesReplacements; + [parsedRules, rulesReplacements] = inlineReplacements({ + parsedRules, + newRules, + referencesMaps, + previousReplacements: context.rulesReplacements + }); + const nodesTypes = inferNodesTypes( + Object.keys(newRules), + parsedRules, + context.nodesTypes + ); + return { + parsedRules, + nodesTypes, + referencesMaps, + rulesReplacements + }; +} +function disambiguateReferencesAndCollectDependencies(parsedRules, newRules, referencesMaps, allowOrphanRules) { + const disambiguateReference2 = makeASTTransformer( + (node) => disambiguateReferenceNode(node, parsedRules) + ); + const disambiguateReferencesAndCollectDependencies2 = makeASTTransformer( + (node) => { + const n = disambiguateReferenceNode(node, parsedRules); + if (n) { + updateReferencesMapsFromReferenceNode(n, referencesMaps); + } + return n; + } + ); + const disambiguatedRules = traverseParsedRules((node) => { + if (node.nodeKind === "replacementRule") { + return disambiguateReference2(node); + } + if (node.nodeKind === "rule") { + const parentUndefined = node.explanation.parents.find( + (n) => !(n.dottedName in parsedRules) + ); + if (!allowOrphanRules && parentUndefined) { + throw new PublicodesError( + "SyntaxError", + `La r\xE8gle parente "${parentUndefined.dottedName}" n'existe pas`, + { + dottedName: node.dottedName + } + ); + } + } + return disambiguateReferencesAndCollectDependencies2(node); + }, newRules); + return [ + disambiguatedRules, + referencesMaps + ]; +} + +// src/traversedVariables.ts +function computeTraversedVariableBeforeEval(traversedVariablesStack, parsedNode, cachedNode, publicParsedRules, isTraversedVariablesBoundary2) { + if (traversedVariablesStack === void 0) { + return; + } + if (cachedNode !== void 0) { + cachedNode.traversedVariables?.forEach( + (name) => traversedVariablesStack[0]?.add(name) + ); + return; + } + if (isTraversedVariablesBoundary2) { + traversedVariablesStack.unshift(/* @__PURE__ */ new Set()); + } + if (parsedNode.nodeKind === "reference" && parsedNode.dottedName && parsedNode.dottedName in publicParsedRules) { + traversedVariablesStack[0].add(parsedNode.dottedName); + } +} +function isTraversedVariablesBoundary(traversedVariablesStack, parsedNode) { + return !!traversedVariablesStack && (traversedVariablesStack.length === 0 || parsedNode.nodeKind === "rule"); +} +function computeTraversedVariableAfterEval(traversedVariablesStack, evaluatedNode, isTraversedVariablesBoundary2) { + if (traversedVariablesStack === void 0) { + return; + } + if (isTraversedVariablesBoundary2) { + evaluatedNode.traversedVariables = Array.from( + traversedVariablesStack.shift() ?? [] + ); + if (traversedVariablesStack.length > 0) { + evaluatedNode.traversedVariables.forEach((name) => { + traversedVariablesStack[0].add(name); + }); + } + } +} + +// src/serializeEvaluation.ts +function serializeEvaluation(node) { + if (typeof node.nodeValue === "number") { + const serializedUnit = serializeUnit(node.unit); + return "" + node.nodeValue + (serializedUnit ? serializedUnit.replace(/\s/g, "") : ""); + } else if (typeof node.nodeValue === "boolean") { + return node.nodeValue ? "oui" : "non"; + } else if (typeof node.nodeValue === "string") { + return `'${node.nodeValue}'`; + } +} + +// src/index.ts +var emptyCache = () => ({ + _meta: { + evaluationRuleStack: [], + parentRuleStack: [] + }, + traversedVariablesStack: void 0, + nodes: /* @__PURE__ */ new Map() +}); +var Engine = class _Engine { + baseContext; + context; + publicParsedRules; + cache = emptyCache(); + // The subEngines attribute is used to get an outside reference to the + // `contexte` intermediate calculations. The `contexte` mechanism uses + // `shallowCopy` to instanciate a new engine, and we want to keep a reference + // to it for the documentation. + // + // TODO: A better implementation would to remove the "runtime" concept of + // "subEngines" and instead duplicate all rules names in the scope of the + // `contexte` as described in + // https://github.com/publicodes/publicodes/discussions/92 + subEngines = []; + subEngineId; + constructor(rules = {}, options = {}) { + const initialContext = { + dottedName: "", + ...options + }; + this.baseContext = createContext({ + ...initialContext, + ...parsePublicodes(rules, initialContext) + }); + this.context = this.baseContext; + this.publicParsedRules = {}; + for (const name in this.baseContext.parsedRules) { + const rule = this.baseContext.parsedRules[name]; + if (!rule.private && isAccessible(this.baseContext.parsedRules, "", name)) { + this.publicParsedRules[name] = rule; + } + } + } + resetCache() { + this.cache = emptyCache(); + } + setSituation(situation = {}, options = {}) { + this.resetCache(); + const keepPreviousSituation = options.keepPreviousSituation ?? false; + Object.keys(situation).forEach((name) => { + if (!(name in this.baseContext.parsedRules)) { + throw new PublicodesError( + "EvaluationError", + `Erreur lors de la mise \xE0 jour de la situation : ${name} n'existe pas dans la base de r\xE8gle.`, + { dottedName: name } + ); + } + if (this.baseContext.parsedRules[name].private) { + throw new PublicodesError( + "EvaluationError", + `Erreur lors de la mise \xE0 jour de la situation : ${name} est une r\xE8gle priv\xE9e (il n'est pas possible de modifier une r\xE8gle priv\xE9e).`, + { dottedName: name } + ); + } + }); + const situationToParse = Object.fromEntries( + Object.entries(situation).map(([nom, value]) => [ + `[priv\xE9] ${nom} . $SITUATION`, + value && typeof value === "object" && "nodeKind" in value ? { valeur: value } : value + ]) + ); + const savedBaseContext = copyContext(this.baseContext); + try { + this.context = { + ...this.baseContext, + ...parsePublicodes( + situationToParse, + keepPreviousSituation ? this.context : this.baseContext + ) + }; + } catch (error) { + this.baseContext = savedBaseContext; + throw error; + } + this.baseContext = savedBaseContext; + Object.keys(situation).forEach((nom) => { + if (isExperimental(this.context.parsedRules, nom)) { + experimentalRuleWarning(this.baseContext.logger, nom); + } + this.checkExperimentalRule( + this.context.parsedRules[`${nom} . $SITUATION`] + ); + }); + return this; + } + inversionFail() { + return !!this.cache.inversionFail; + } + getRule(dottedName) { + if (!(dottedName in this.baseContext.parsedRules)) { + throw new PublicodesError( + "UnknownRule", + `La r\xE8gle '${dottedName}' n'existe pas`, + { dottedName } + ); + } + if (!(dottedName in this.publicParsedRules)) { + throw new PublicodesError( + "PrivateRule", + `La r\xE8gle ${dottedName} est une r\xE8gle priv\xE9e.`, + { dottedName } + ); + } + return this.publicParsedRules[dottedName]; + } + getParsedRules() { + return this.publicParsedRules; + } + evaluate(value) { + const cachedNode = this.cache.nodes.get(value); + if (cachedNode) { + return cachedNode; + } + this.context = Object.assign( + this.context, + parsePublicodes( + { + "[priv\xE9] $EVALUATION": value && typeof value === "object" && "nodeKind" in value ? { valeur: value } : value + }, + this.context + ) + ); + this.checkExperimentalRule(this.context.parsedRules["$EVALUATION"]); + this.cache._meta = emptyCache()._meta; + const evaluation = this.evaluateNode( + this.context.parsedRules["$EVALUATION"].explanation.valeur + ); + this.cache.nodes.set(value, evaluation); + return evaluation; + } + evaluateNode(parsedNode) { + const cachedNode = this.cache.nodes.get(parsedNode); + let traversedVariableBoundary = false; + if (this.cache.traversedVariablesStack) { + traversedVariableBoundary = isTraversedVariablesBoundary( + this.cache.traversedVariablesStack, + parsedNode + ); + computeTraversedVariableBeforeEval( + this.cache.traversedVariablesStack, + parsedNode, + cachedNode, + this.publicParsedRules, + traversedVariableBoundary + ); + } + if (cachedNode !== void 0) { + return cachedNode; + } + if (!evaluationFunctions[parsedNode.nodeKind]) { + throw new PublicodesError( + "EvaluationError", + `Unknown "nodeKind": ${parsedNode.nodeKind}`, + { dottedName: "" } + ); + } + const evaluatedNode = evaluationFunctions[parsedNode.nodeKind].call( + this, + parsedNode + ); + if (this.cache.traversedVariablesStack) { + computeTraversedVariableAfterEval( + this.cache.traversedVariablesStack, + evaluatedNode, + traversedVariableBoundary + ); + } + this.cache.nodes.set(parsedNode, evaluatedNode); + return evaluatedNode; + } + /** + * Shallow Engine instance copy. Keeps references to the original Engine instance attributes. + */ + shallowCopy() { + const newEngine = new _Engine(); + newEngine.baseContext = copyContext(this.baseContext); + newEngine.context = copyContext(this.context); + newEngine.publicParsedRules = this.publicParsedRules; + newEngine.cache = { + ...emptyCache(), + nodes: new Map(this.cache.nodes) + }; + return newEngine; + } + checkExperimentalRule = makeASTVisitor((node) => { + if (node.nodeKind === "reference" && isExperimental(this.context.parsedRules, node.dottedName)) { + experimentalRuleWarning( + this.baseContext.logger, + node.dottedName + ); + } + return "continue"; + }); +}; +export { + PublicodesError, + capitalise0, + Engine as default, + formatValue, + isPublicodesError, + parseExpression, + parsePublicodes, + parseUnit, + reduceAST, + serializeEvaluation, + serializeUnit, + simplifyNodeUnit, + makeASTTransformer as transformAST, + traverseASTNode, + ruleUtils_exports as utils +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/publicodes/dist/index.js.map b/publicodes/dist/index.js.map new file mode 100644 index 000000000..41ba9e543 --- /dev/null +++ b/publicodes/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../node_modules/nearley/lib/nearley.js","../../../node_modules/moo/moo.js","../src/error.ts","../src/utils.ts","../src/AST/index.ts","../src/evaluationFunctions.ts","../src/inferNodeType.ts","../src/evaluationUtils.ts","../src/mecanisms/inlineMecanism.ts","../src/mecanisms/abattement.ts","../src/mecanisms/applicable.ts","../src/units.ts","../src/mecanisms/arrondi.ts","../src/nodeUnits.ts","../src/format.ts","../src/ruleUtils.ts","../src/AST/findCycles.ts","../src/AST/graph.ts","../src/rule.ts","../src/mecanisms/avec.ts","../src/mecanisms/trancheUtils.ts","../src/mecanisms/barème.ts","../src/mecanisms/condition.ts","../src/mecanisms/contexte.ts","../src/date.ts","../src/mecanisms/durée.ts","../src/mecanisms/est.ts","../src/mecanisms/est-non-applicable.ts","../src/mecanisms/grille.ts","../src/uniroot.ts","../src/mecanisms/inversion.ts","../src/mecanisms/max-min.ts","../src/mecanisms/somme.tsx","../src/mecanisms/moyenne.ts","../src/mecanisms/non-applicable.ts","../src/mecanisms/one-possibility.ts","../src/mecanisms/operation.ts","../src/mecanisms/parDéfaut.ts","../src/mecanisms/plafond.ts","../src/mecanisms/plancher.ts","../src/mecanisms/product.ts","../src/mecanisms/résoudre-référence-circulaire.ts","../src/mecanisms/simplifier-unité.ts","../src/mecanisms/situation.ts","../src/mecanisms/tauxProgressif.ts","../src/mecanisms/texte.ts","../src/mecanisms/toutes-ces-conditions.ts","../src/mecanisms/une-de-ces-conditions.ts","../src/mecanisms/unité.ts","../src/mecanisms/variablesManquantes.ts","../src/mecanisms/variations.ts","../src/parseExpression.ts","../src/grammarFunctions.js","../src/grammar.codegen.js","../src/reference.ts","../src/parse.ts","../src/replacement.ts","../src/parsePublicodes.ts","../src/traversedVariables.ts","../src/serializeEvaluation.ts","../src/index.ts"],"sourcesContent":["(function(root, factory) {\n if (typeof module === 'object' && module.exports) {\n module.exports = factory();\n } else {\n root.nearley = factory();\n }\n}(this, function() {\n\n function Rule(name, symbols, postprocess) {\n this.id = ++Rule.highestId;\n this.name = name;\n this.symbols = symbols; // a list of literal | regex class | nonterminal\n this.postprocess = postprocess;\n return this;\n }\n Rule.highestId = 0;\n\n Rule.prototype.toString = function(withCursorAt) {\n var symbolSequence = (typeof withCursorAt === \"undefined\")\n ? this.symbols.map(getSymbolShortDisplay).join(' ')\n : ( this.symbols.slice(0, withCursorAt).map(getSymbolShortDisplay).join(' ')\n + \" ● \"\n + this.symbols.slice(withCursorAt).map(getSymbolShortDisplay).join(' ') );\n return this.name + \" → \" + symbolSequence;\n }\n\n\n // a State is a rule at a position from a given starting point in the input stream (reference)\n function State(rule, dot, reference, wantedBy) {\n this.rule = rule;\n this.dot = dot;\n this.reference = reference;\n this.data = [];\n this.wantedBy = wantedBy;\n this.isComplete = this.dot === rule.symbols.length;\n }\n\n State.prototype.toString = function() {\n return \"{\" + this.rule.toString(this.dot) + \"}, from: \" + (this.reference || 0);\n };\n\n State.prototype.nextState = function(child) {\n var state = new State(this.rule, this.dot + 1, this.reference, this.wantedBy);\n state.left = this;\n state.right = child;\n if (state.isComplete) {\n state.data = state.build();\n // Having right set here will prevent the right state and its children\n // form being garbage collected\n state.right = undefined;\n }\n return state;\n };\n\n State.prototype.build = function() {\n var children = [];\n var node = this;\n do {\n children.push(node.right.data);\n node = node.left;\n } while (node.left);\n children.reverse();\n return children;\n };\n\n State.prototype.finish = function() {\n if (this.rule.postprocess) {\n this.data = this.rule.postprocess(this.data, this.reference, Parser.fail);\n }\n };\n\n\n function Column(grammar, index) {\n this.grammar = grammar;\n this.index = index;\n this.states = [];\n this.wants = {}; // states indexed by the non-terminal they expect\n this.scannable = []; // list of states that expect a token\n this.completed = {}; // states that are nullable\n }\n\n\n Column.prototype.process = function(nextColumn) {\n var states = this.states;\n var wants = this.wants;\n var completed = this.completed;\n\n for (var w = 0; w < states.length; w++) { // nb. we push() during iteration\n var state = states[w];\n\n if (state.isComplete) {\n state.finish();\n if (state.data !== Parser.fail) {\n // complete\n var wantedBy = state.wantedBy;\n for (var i = wantedBy.length; i--; ) { // this line is hot\n var left = wantedBy[i];\n this.complete(left, state);\n }\n\n // special-case nullables\n if (state.reference === this.index) {\n // make sure future predictors of this rule get completed.\n var exp = state.rule.name;\n (this.completed[exp] = this.completed[exp] || []).push(state);\n }\n }\n\n } else {\n // queue scannable states\n var exp = state.rule.symbols[state.dot];\n if (typeof exp !== 'string') {\n this.scannable.push(state);\n continue;\n }\n\n // predict\n if (wants[exp]) {\n wants[exp].push(state);\n\n if (completed.hasOwnProperty(exp)) {\n var nulls = completed[exp];\n for (var i = 0; i < nulls.length; i++) {\n var right = nulls[i];\n this.complete(state, right);\n }\n }\n } else {\n wants[exp] = [state];\n this.predict(exp);\n }\n }\n }\n }\n\n Column.prototype.predict = function(exp) {\n var rules = this.grammar.byName[exp] || [];\n\n for (var i = 0; i < rules.length; i++) {\n var r = rules[i];\n var wantedBy = this.wants[exp];\n var s = new State(r, 0, this.index, wantedBy);\n this.states.push(s);\n }\n }\n\n Column.prototype.complete = function(left, right) {\n var copy = left.nextState(right);\n this.states.push(copy);\n }\n\n\n function Grammar(rules, start) {\n this.rules = rules;\n this.start = start || this.rules[0].name;\n var byName = this.byName = {};\n this.rules.forEach(function(rule) {\n if (!byName.hasOwnProperty(rule.name)) {\n byName[rule.name] = [];\n }\n byName[rule.name].push(rule);\n });\n }\n\n // So we can allow passing (rules, start) directly to Parser for backwards compatibility\n Grammar.fromCompiled = function(rules, start) {\n var lexer = rules.Lexer;\n if (rules.ParserStart) {\n start = rules.ParserStart;\n rules = rules.ParserRules;\n }\n var rules = rules.map(function (r) { return (new Rule(r.name, r.symbols, r.postprocess)); });\n var g = new Grammar(rules, start);\n g.lexer = lexer; // nb. storing lexer on Grammar is iffy, but unavoidable\n return g;\n }\n\n\n function StreamLexer() {\n this.reset(\"\");\n }\n\n StreamLexer.prototype.reset = function(data, state) {\n this.buffer = data;\n this.index = 0;\n this.line = state ? state.line : 1;\n this.lastLineBreak = state ? -state.col : 0;\n }\n\n StreamLexer.prototype.next = function() {\n if (this.index < this.buffer.length) {\n var ch = this.buffer[this.index++];\n if (ch === '\\n') {\n this.line += 1;\n this.lastLineBreak = this.index;\n }\n return {value: ch};\n }\n }\n\n StreamLexer.prototype.save = function() {\n return {\n line: this.line,\n col: this.index - this.lastLineBreak,\n }\n }\n\n StreamLexer.prototype.formatError = function(token, message) {\n // nb. this gets called after consuming the offending token,\n // so the culprit is index-1\n var buffer = this.buffer;\n if (typeof buffer === 'string') {\n var lines = buffer\n .split(\"\\n\")\n .slice(\n Math.max(0, this.line - 5), \n this.line\n );\n\n var nextLineBreak = buffer.indexOf('\\n', this.index);\n if (nextLineBreak === -1) nextLineBreak = buffer.length;\n var col = this.index - this.lastLineBreak;\n var lastLineDigits = String(this.line).length;\n message += \" at line \" + this.line + \" col \" + col + \":\\n\\n\";\n message += lines\n .map(function(line, i) {\n return pad(this.line - lines.length + i + 1, lastLineDigits) + \" \" + line;\n }, this)\n .join(\"\\n\");\n message += \"\\n\" + pad(\"\", lastLineDigits + col) + \"^\\n\";\n return message;\n } else {\n return message + \" at index \" + (this.index - 1);\n }\n\n function pad(n, length) {\n var s = String(n);\n return Array(length - s.length + 1).join(\" \") + s;\n }\n }\n\n function Parser(rules, start, options) {\n if (rules instanceof Grammar) {\n var grammar = rules;\n var options = start;\n } else {\n var grammar = Grammar.fromCompiled(rules, start);\n }\n this.grammar = grammar;\n\n // Read options\n this.options = {\n keepHistory: false,\n lexer: grammar.lexer || new StreamLexer,\n };\n for (var key in (options || {})) {\n this.options[key] = options[key];\n }\n\n // Setup lexer\n this.lexer = this.options.lexer;\n this.lexerState = undefined;\n\n // Setup a table\n var column = new Column(grammar, 0);\n var table = this.table = [column];\n\n // I could be expecting anything.\n column.wants[grammar.start] = [];\n column.predict(grammar.start);\n // TODO what if start rule is nullable?\n column.process();\n this.current = 0; // token index\n }\n\n // create a reserved token for indicating a parse fail\n Parser.fail = {};\n\n Parser.prototype.feed = function(chunk) {\n var lexer = this.lexer;\n lexer.reset(chunk, this.lexerState);\n\n var token;\n while (true) {\n try {\n token = lexer.next();\n if (!token) {\n break;\n }\n } catch (e) {\n // Create the next column so that the error reporter\n // can display the correctly predicted states.\n var nextColumn = new Column(this.grammar, this.current + 1);\n this.table.push(nextColumn);\n var err = new Error(this.reportLexerError(e));\n err.offset = this.current;\n err.token = e.token;\n throw err;\n }\n // We add new states to table[current+1]\n var column = this.table[this.current];\n\n // GC unused states\n if (!this.options.keepHistory) {\n delete this.table[this.current - 1];\n }\n\n var n = this.current + 1;\n var nextColumn = new Column(this.grammar, n);\n this.table.push(nextColumn);\n\n // Advance all tokens that expect the symbol\n var literal = token.text !== undefined ? token.text : token.value;\n var value = lexer.constructor === StreamLexer ? token.value : token;\n var scannable = column.scannable;\n for (var w = scannable.length; w--; ) {\n var state = scannable[w];\n var expect = state.rule.symbols[state.dot];\n // Try to consume the token\n // either regex or literal\n if (expect.test ? expect.test(value) :\n expect.type ? expect.type === token.type\n : expect.literal === literal) {\n // Add it\n var next = state.nextState({data: value, token: token, isToken: true, reference: n - 1});\n nextColumn.states.push(next);\n }\n }\n\n // Next, for each of the rules, we either\n // (a) complete it, and try to see if the reference row expected that\n // rule\n // (b) predict the next nonterminal it expects by adding that\n // nonterminal's start state\n // To prevent duplication, we also keep track of rules we have already\n // added\n\n nextColumn.process();\n\n // If needed, throw an error:\n if (nextColumn.states.length === 0) {\n // No states at all! This is not good.\n var err = new Error(this.reportError(token));\n err.offset = this.current;\n err.token = token;\n throw err;\n }\n\n // maybe save lexer state\n if (this.options.keepHistory) {\n column.lexerState = lexer.save()\n }\n\n this.current++;\n }\n if (column) {\n this.lexerState = lexer.save()\n }\n\n // Incrementally keep track of results\n this.results = this.finish();\n\n // Allow chaining, for whatever it's worth\n return this;\n };\n\n Parser.prototype.reportLexerError = function(lexerError) {\n var tokenDisplay, lexerMessage;\n // Planning to add a token property to moo's thrown error\n // even on erroring tokens to be used in error display below\n var token = lexerError.token;\n if (token) {\n tokenDisplay = \"input \" + JSON.stringify(token.text[0]) + \" (lexer error)\";\n lexerMessage = this.lexer.formatError(token, \"Syntax error\");\n } else {\n tokenDisplay = \"input (lexer error)\";\n lexerMessage = lexerError.message;\n }\n return this.reportErrorCommon(lexerMessage, tokenDisplay);\n };\n\n Parser.prototype.reportError = function(token) {\n var tokenDisplay = (token.type ? token.type + \" token: \" : \"\") + JSON.stringify(token.value !== undefined ? token.value : token);\n var lexerMessage = this.lexer.formatError(token, \"Syntax error\");\n return this.reportErrorCommon(lexerMessage, tokenDisplay);\n };\n\n Parser.prototype.reportErrorCommon = function(lexerMessage, tokenDisplay) {\n var lines = [];\n lines.push(lexerMessage);\n var lastColumnIndex = this.table.length - 2;\n var lastColumn = this.table[lastColumnIndex];\n var expectantStates = lastColumn.states\n .filter(function(state) {\n var nextSymbol = state.rule.symbols[state.dot];\n return nextSymbol && typeof nextSymbol !== \"string\";\n });\n\n if (expectantStates.length === 0) {\n lines.push('Unexpected ' + tokenDisplay + '. I did not expect any more input. Here is the state of my parse table:\\n');\n this.displayStateStack(lastColumn.states, lines);\n } else {\n lines.push('Unexpected ' + tokenDisplay + '. Instead, I was expecting to see one of the following:\\n');\n // Display a \"state stack\" for each expectant state\n // - which shows you how this state came to be, step by step.\n // If there is more than one derivation, we only display the first one.\n var stateStacks = expectantStates\n .map(function(state) {\n return this.buildFirstStateStack(state, []) || [state];\n }, this);\n // Display each state that is expecting a terminal symbol next.\n stateStacks.forEach(function(stateStack) {\n var state = stateStack[0];\n var nextSymbol = state.rule.symbols[state.dot];\n var symbolDisplay = this.getSymbolDisplay(nextSymbol);\n lines.push('A ' + symbolDisplay + ' based on:');\n this.displayStateStack(stateStack, lines);\n }, this);\n }\n lines.push(\"\");\n return lines.join(\"\\n\");\n }\n \n Parser.prototype.displayStateStack = function(stateStack, lines) {\n var lastDisplay;\n var sameDisplayCount = 0;\n for (var j = 0; j < stateStack.length; j++) {\n var state = stateStack[j];\n var display = state.rule.toString(state.dot);\n if (display === lastDisplay) {\n sameDisplayCount++;\n } else {\n if (sameDisplayCount > 0) {\n lines.push(' ^ ' + sameDisplayCount + ' more lines identical to this');\n }\n sameDisplayCount = 0;\n lines.push(' ' + display);\n }\n lastDisplay = display;\n }\n };\n\n Parser.prototype.getSymbolDisplay = function(symbol) {\n return getSymbolLongDisplay(symbol);\n };\n\n /*\n Builds a the first state stack. You can think of a state stack as the call stack\n of the recursive-descent parser which the Nearley parse algorithm simulates.\n A state stack is represented as an array of state objects. Within a\n state stack, the first item of the array will be the starting\n state, with each successive item in the array going further back into history.\n\n This function needs to be given a starting state and an empty array representing\n the visited states, and it returns an single state stack.\n\n */\n Parser.prototype.buildFirstStateStack = function(state, visited) {\n if (visited.indexOf(state) !== -1) {\n // Found cycle, return null\n // to eliminate this path from the results, because\n // we don't know how to display it meaningfully\n return null;\n }\n if (state.wantedBy.length === 0) {\n return [state];\n }\n var prevState = state.wantedBy[0];\n var childVisited = [state].concat(visited);\n var childResult = this.buildFirstStateStack(prevState, childVisited);\n if (childResult === null) {\n return null;\n }\n return [state].concat(childResult);\n };\n\n Parser.prototype.save = function() {\n var column = this.table[this.current];\n column.lexerState = this.lexerState;\n return column;\n };\n\n Parser.prototype.restore = function(column) {\n var index = column.index;\n this.current = index;\n this.table[index] = column;\n this.table.splice(index + 1);\n this.lexerState = column.lexerState;\n\n // Incrementally keep track of results\n this.results = this.finish();\n };\n\n // nb. deprecated: use save/restore instead!\n Parser.prototype.rewind = function(index) {\n if (!this.options.keepHistory) {\n throw new Error('set option `keepHistory` to enable rewinding')\n }\n // nb. recall column (table) indicies fall between token indicies.\n // col 0 -- token 0 -- col 1\n this.restore(this.table[index]);\n };\n\n Parser.prototype.finish = function() {\n // Return the possible parsings\n var considerations = [];\n var start = this.grammar.start;\n var column = this.table[this.table.length - 1]\n column.states.forEach(function (t) {\n if (t.rule.name === start\n && t.dot === t.rule.symbols.length\n && t.reference === 0\n && t.data !== Parser.fail) {\n considerations.push(t);\n }\n });\n return considerations.map(function(c) {return c.data; });\n };\n\n function getSymbolLongDisplay(symbol) {\n var type = typeof symbol;\n if (type === \"string\") {\n return symbol;\n } else if (type === \"object\") {\n if (symbol.literal) {\n return JSON.stringify(symbol.literal);\n } else if (symbol instanceof RegExp) {\n return 'character matching ' + symbol;\n } else if (symbol.type) {\n return symbol.type + ' token';\n } else if (symbol.test) {\n return 'token matching ' + String(symbol.test);\n } else {\n throw new Error('Unknown symbol type: ' + symbol);\n }\n }\n }\n\n function getSymbolShortDisplay(symbol) {\n var type = typeof symbol;\n if (type === \"string\") {\n return symbol;\n } else if (type === \"object\") {\n if (symbol.literal) {\n return JSON.stringify(symbol.literal);\n } else if (symbol instanceof RegExp) {\n return symbol.toString();\n } else if (symbol.type) {\n return '%' + symbol.type;\n } else if (symbol.test) {\n return '<' + String(symbol.test) + '>';\n } else {\n throw new Error('Unknown symbol type: ' + symbol);\n }\n }\n }\n\n return {\n Parser: Parser,\n Grammar: Grammar,\n Rule: Rule,\n };\n\n}));\n","(function(root, factory) {\n if (typeof define === 'function' && define.amd) {\n define([], factory) /* global define */\n } else if (typeof module === 'object' && module.exports) {\n module.exports = factory()\n } else {\n root.moo = factory()\n }\n}(this, function() {\n 'use strict';\n\n var hasOwnProperty = Object.prototype.hasOwnProperty\n var toString = Object.prototype.toString\n var hasSticky = typeof new RegExp().sticky === 'boolean'\n\n /***************************************************************************/\n\n function isRegExp(o) { return o && toString.call(o) === '[object RegExp]' }\n function isObject(o) { return o && typeof o === 'object' && !isRegExp(o) && !Array.isArray(o) }\n\n function reEscape(s) {\n return s.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&')\n }\n function reGroups(s) {\n var re = new RegExp('|' + s)\n return re.exec('').length - 1\n }\n function reCapture(s) {\n return '(' + s + ')'\n }\n function reUnion(regexps) {\n if (!regexps.length) return '(?!)'\n var source = regexps.map(function(s) {\n return \"(?:\" + s + \")\"\n }).join('|')\n return \"(?:\" + source + \")\"\n }\n\n function regexpOrLiteral(obj) {\n if (typeof obj === 'string') {\n return '(?:' + reEscape(obj) + ')'\n\n } else if (isRegExp(obj)) {\n // TODO: consider /u support\n if (obj.ignoreCase) throw new Error('RegExp /i flag not allowed')\n if (obj.global) throw new Error('RegExp /g flag is implied')\n if (obj.sticky) throw new Error('RegExp /y flag is implied')\n if (obj.multiline) throw new Error('RegExp /m flag is implied')\n return obj.source\n\n } else {\n throw new Error('Not a pattern: ' + obj)\n }\n }\n\n function pad(s, length) {\n if (s.length > length) {\n return s\n }\n return Array(length - s.length + 1).join(\" \") + s\n }\n\n function lastNLines(string, numLines) {\n var position = string.length\n var lineBreaks = 0;\n while (true) {\n var idx = string.lastIndexOf(\"\\n\", position - 1)\n if (idx === -1) {\n break;\n } else {\n lineBreaks++\n }\n position = idx\n if (lineBreaks === numLines) {\n break;\n }\n if (position === 0) {\n break;\n }\n }\n var startPosition = \n lineBreaks < numLines ?\n 0 : \n position + 1\n return string.substring(startPosition).split(\"\\n\")\n }\n\n function objectToRules(object) {\n var keys = Object.getOwnPropertyNames(object)\n var result = []\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i]\n var thing = object[key]\n var rules = [].concat(thing)\n if (key === 'include') {\n for (var j = 0; j < rules.length; j++) {\n result.push({include: rules[j]})\n }\n continue\n }\n var match = []\n rules.forEach(function(rule) {\n if (isObject(rule)) {\n if (match.length) result.push(ruleOptions(key, match))\n result.push(ruleOptions(key, rule))\n match = []\n } else {\n match.push(rule)\n }\n })\n if (match.length) result.push(ruleOptions(key, match))\n }\n return result\n }\n\n function arrayToRules(array) {\n var result = []\n for (var i = 0; i < array.length; i++) {\n var obj = array[i]\n if (obj.include) {\n var include = [].concat(obj.include)\n for (var j = 0; j < include.length; j++) {\n result.push({include: include[j]})\n }\n continue\n }\n if (!obj.type) {\n throw new Error('Rule has no type: ' + JSON.stringify(obj))\n }\n result.push(ruleOptions(obj.type, obj))\n }\n return result\n }\n\n function ruleOptions(type, obj) {\n if (!isObject(obj)) {\n obj = { match: obj }\n }\n if (obj.include) {\n throw new Error('Matching rules cannot also include states')\n }\n\n // nb. error and fallback imply lineBreaks\n var options = {\n defaultType: type,\n lineBreaks: !!obj.error || !!obj.fallback,\n pop: false,\n next: null,\n push: null,\n error: false,\n fallback: false,\n value: null,\n type: null,\n shouldThrow: false,\n }\n\n // Avoid Object.assign(), so we support IE9+\n for (var key in obj) {\n if (hasOwnProperty.call(obj, key)) {\n options[key] = obj[key]\n }\n }\n\n // type transform cannot be a string\n if (typeof options.type === 'string' && type !== options.type) {\n throw new Error(\"Type transform cannot be a string (type '\" + options.type + \"' for token '\" + type + \"')\")\n }\n\n // convert to array\n var match = options.match\n options.match = Array.isArray(match) ? match : match ? [match] : []\n options.match.sort(function(a, b) {\n return isRegExp(a) && isRegExp(b) ? 0\n : isRegExp(b) ? -1 : isRegExp(a) ? +1 : b.length - a.length\n })\n return options\n }\n\n function toRules(spec) {\n return Array.isArray(spec) ? arrayToRules(spec) : objectToRules(spec)\n }\n\n var defaultErrorRule = ruleOptions('error', {lineBreaks: true, shouldThrow: true})\n function compileRules(rules, hasStates) {\n var errorRule = null\n var fast = Object.create(null)\n var fastAllowed = true\n var unicodeFlag = null\n var groups = []\n var parts = []\n\n // If there is a fallback rule, then disable fast matching\n for (var i = 0; i < rules.length; i++) {\n if (rules[i].fallback) {\n fastAllowed = false\n }\n }\n\n for (var i = 0; i < rules.length; i++) {\n var options = rules[i]\n\n if (options.include) {\n // all valid inclusions are removed by states() preprocessor\n throw new Error('Inheritance is not allowed in stateless lexers')\n }\n\n if (options.error || options.fallback) {\n // errorRule can only be set once\n if (errorRule) {\n if (!options.fallback === !errorRule.fallback) {\n throw new Error(\"Multiple \" + (options.fallback ? \"fallback\" : \"error\") + \" rules not allowed (for token '\" + options.defaultType + \"')\")\n } else {\n throw new Error(\"fallback and error are mutually exclusive (for token '\" + options.defaultType + \"')\")\n }\n }\n errorRule = options\n }\n\n var match = options.match.slice()\n if (fastAllowed) {\n while (match.length && typeof match[0] === 'string' && match[0].length === 1) {\n var word = match.shift()\n fast[word.charCodeAt(0)] = options\n }\n }\n\n // Warn about inappropriate state-switching options\n if (options.pop || options.push || options.next) {\n if (!hasStates) {\n throw new Error(\"State-switching options are not allowed in stateless lexers (for token '\" + options.defaultType + \"')\")\n }\n if (options.fallback) {\n throw new Error(\"State-switching options are not allowed on fallback tokens (for token '\" + options.defaultType + \"')\")\n }\n }\n\n // Only rules with a .match are included in the RegExp\n if (match.length === 0) {\n continue\n }\n fastAllowed = false\n\n groups.push(options)\n\n // Check unicode flag is used everywhere or nowhere\n for (var j = 0; j < match.length; j++) {\n var obj = match[j]\n if (!isRegExp(obj)) {\n continue\n }\n\n if (unicodeFlag === null) {\n unicodeFlag = obj.unicode\n } else if (unicodeFlag !== obj.unicode && options.fallback === false) {\n throw new Error('If one rule is /u then all must be')\n }\n }\n\n // convert to RegExp\n var pat = reUnion(match.map(regexpOrLiteral))\n\n // validate\n var regexp = new RegExp(pat)\n if (regexp.test(\"\")) {\n throw new Error(\"RegExp matches empty string: \" + regexp)\n }\n var groupCount = reGroups(pat)\n if (groupCount > 0) {\n throw new Error(\"RegExp has capture groups: \" + regexp + \"\\nUse (?: … ) instead\")\n }\n\n // try and detect rules matching newlines\n if (!options.lineBreaks && regexp.test('\\n')) {\n throw new Error('Rule should declare lineBreaks: ' + regexp)\n }\n\n // store regex\n parts.push(reCapture(pat))\n }\n\n\n // If there's no fallback rule, use the sticky flag so we only look for\n // matches at the current index.\n //\n // If we don't support the sticky flag, then fake it using an irrefutable\n // match (i.e. an empty pattern).\n var fallbackRule = errorRule && errorRule.fallback\n var flags = hasSticky && !fallbackRule ? 'ym' : 'gm'\n var suffix = hasSticky || fallbackRule ? '' : '|'\n\n if (unicodeFlag === true) flags += \"u\"\n var combined = new RegExp(reUnion(parts) + suffix, flags)\n return {regexp: combined, groups: groups, fast: fast, error: errorRule || defaultErrorRule}\n }\n\n function compile(rules) {\n var result = compileRules(toRules(rules))\n return new Lexer({start: result}, 'start')\n }\n\n function checkStateGroup(g, name, map) {\n var state = g && (g.push || g.next)\n if (state && !map[state]) {\n throw new Error(\"Missing state '\" + state + \"' (in token '\" + g.defaultType + \"' of state '\" + name + \"')\")\n }\n if (g && g.pop && +g.pop !== 1) {\n throw new Error(\"pop must be 1 (in token '\" + g.defaultType + \"' of state '\" + name + \"')\")\n }\n }\n function compileStates(states, start) {\n var all = states.$all ? toRules(states.$all) : []\n delete states.$all\n\n var keys = Object.getOwnPropertyNames(states)\n if (!start) start = keys[0]\n\n var ruleMap = Object.create(null)\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i]\n ruleMap[key] = toRules(states[key]).concat(all)\n }\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i]\n var rules = ruleMap[key]\n var included = Object.create(null)\n for (var j = 0; j < rules.length; j++) {\n var rule = rules[j]\n if (!rule.include) continue\n var splice = [j, 1]\n if (rule.include !== key && !included[rule.include]) {\n included[rule.include] = true\n var newRules = ruleMap[rule.include]\n if (!newRules) {\n throw new Error(\"Cannot include nonexistent state '\" + rule.include + \"' (in state '\" + key + \"')\")\n }\n for (var k = 0; k < newRules.length; k++) {\n var newRule = newRules[k]\n if (rules.indexOf(newRule) !== -1) continue\n splice.push(newRule)\n }\n }\n rules.splice.apply(rules, splice)\n j--\n }\n }\n\n var map = Object.create(null)\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i]\n map[key] = compileRules(ruleMap[key], true)\n }\n\n for (var i = 0; i < keys.length; i++) {\n var name = keys[i]\n var state = map[name]\n var groups = state.groups\n for (var j = 0; j < groups.length; j++) {\n checkStateGroup(groups[j], name, map)\n }\n var fastKeys = Object.getOwnPropertyNames(state.fast)\n for (var j = 0; j < fastKeys.length; j++) {\n checkStateGroup(state.fast[fastKeys[j]], name, map)\n }\n }\n\n return new Lexer(map, start)\n }\n\n function keywordTransform(map) {\n\n // Use a JavaScript Map to map keywords to their corresponding token type\n // unless Map is unsupported, then fall back to using an Object:\n var isMap = typeof Map !== 'undefined'\n var reverseMap = isMap ? new Map : Object.create(null)\n\n var types = Object.getOwnPropertyNames(map)\n for (var i = 0; i < types.length; i++) {\n var tokenType = types[i]\n var item = map[tokenType]\n var keywordList = Array.isArray(item) ? item : [item]\n keywordList.forEach(function(keyword) {\n if (typeof keyword !== 'string') {\n throw new Error(\"keyword must be string (in keyword '\" + tokenType + \"')\")\n }\n if (isMap) {\n reverseMap.set(keyword, tokenType)\n } else {\n reverseMap[keyword] = tokenType\n }\n })\n }\n return function(k) {\n return isMap ? reverseMap.get(k) : reverseMap[k]\n }\n }\n\n /***************************************************************************/\n\n var Lexer = function(states, state) {\n this.startState = state\n this.states = states\n this.buffer = ''\n this.stack = []\n this.reset()\n }\n\n Lexer.prototype.reset = function(data, info) {\n this.buffer = data || ''\n this.index = 0\n this.line = info ? info.line : 1\n this.col = info ? info.col : 1\n this.queuedToken = info ? info.queuedToken : null\n this.queuedText = info ? info.queuedText: \"\";\n this.queuedThrow = info ? info.queuedThrow : null\n this.setState(info ? info.state : this.startState)\n this.stack = info && info.stack ? info.stack.slice() : []\n return this\n }\n\n Lexer.prototype.save = function() {\n return {\n line: this.line,\n col: this.col,\n state: this.state,\n stack: this.stack.slice(),\n queuedToken: this.queuedToken,\n queuedText: this.queuedText,\n queuedThrow: this.queuedThrow,\n }\n }\n\n Lexer.prototype.setState = function(state) {\n if (!state || this.state === state) return\n this.state = state\n var info = this.states[state]\n this.groups = info.groups\n this.error = info.error\n this.re = info.regexp\n this.fast = info.fast\n }\n\n Lexer.prototype.popState = function() {\n this.setState(this.stack.pop())\n }\n\n Lexer.prototype.pushState = function(state) {\n this.stack.push(this.state)\n this.setState(state)\n }\n\n var eat = hasSticky ? function(re, buffer) { // assume re is /y\n return re.exec(buffer)\n } : function(re, buffer) { // assume re is /g\n var match = re.exec(buffer)\n // will always match, since we used the |(?:) trick\n if (match[0].length === 0) {\n return null\n }\n return match\n }\n\n Lexer.prototype._getGroup = function(match) {\n var groupCount = this.groups.length\n for (var i = 0; i < groupCount; i++) {\n if (match[i + 1] !== undefined) {\n return this.groups[i]\n }\n }\n throw new Error('Cannot find token type for matched text')\n }\n\n function tokenToString() {\n return this.value\n }\n\n Lexer.prototype.next = function() {\n var index = this.index\n\n // If a fallback token matched, we don't need to re-run the RegExp\n if (this.queuedGroup) {\n var token = this._token(this.queuedGroup, this.queuedText, index)\n this.queuedGroup = null\n this.queuedText = \"\"\n return token\n }\n\n var buffer = this.buffer\n if (index === buffer.length) {\n return // EOF\n }\n\n // Fast matching for single characters\n var group = this.fast[buffer.charCodeAt(index)]\n if (group) {\n return this._token(group, buffer.charAt(index), index)\n }\n\n // Execute RegExp\n var re = this.re\n re.lastIndex = index\n var match = eat(re, buffer)\n\n // Error tokens match the remaining buffer\n var error = this.error\n if (match == null) {\n return this._token(error, buffer.slice(index, buffer.length), index)\n }\n\n var group = this._getGroup(match)\n var text = match[0]\n\n if (error.fallback && match.index !== index) {\n this.queuedGroup = group\n this.queuedText = text\n\n // Fallback tokens contain the unmatched portion of the buffer\n return this._token(error, buffer.slice(index, match.index), index)\n }\n\n return this._token(group, text, index)\n }\n\n Lexer.prototype._token = function(group, text, offset) {\n // count line breaks\n var lineBreaks = 0\n if (group.lineBreaks) {\n var matchNL = /\\n/g\n var nl = 1\n if (text === '\\n') {\n lineBreaks = 1\n } else {\n while (matchNL.exec(text)) { lineBreaks++; nl = matchNL.lastIndex }\n }\n }\n\n var token = {\n type: (typeof group.type === 'function' && group.type(text)) || group.defaultType,\n value: typeof group.value === 'function' ? group.value(text) : text,\n text: text,\n toString: tokenToString,\n offset: offset,\n lineBreaks: lineBreaks,\n line: this.line,\n col: this.col,\n }\n // nb. adding more props to token object will make V8 sad!\n\n var size = text.length\n this.index += size\n this.line += lineBreaks\n if (lineBreaks !== 0) {\n this.col = size - nl + 1\n } else {\n this.col += size\n }\n\n // throw, if no rule with {error: true}\n if (group.shouldThrow) {\n var err = new Error(this.formatError(token, \"invalid syntax\"))\n throw err;\n }\n\n if (group.pop) this.popState()\n else if (group.push) this.pushState(group.push)\n else if (group.next) this.setState(group.next)\n\n return token\n }\n\n if (typeof Symbol !== 'undefined' && Symbol.iterator) {\n var LexerIterator = function(lexer) {\n this.lexer = lexer\n }\n\n LexerIterator.prototype.next = function() {\n var token = this.lexer.next()\n return {value: token, done: !token}\n }\n\n LexerIterator.prototype[Symbol.iterator] = function() {\n return this\n }\n\n Lexer.prototype[Symbol.iterator] = function() {\n return new LexerIterator(this)\n }\n }\n\n Lexer.prototype.formatError = function(token, message) {\n if (token == null) {\n // An undefined token indicates EOF\n var text = this.buffer.slice(this.index)\n var token = {\n text: text,\n offset: this.index,\n lineBreaks: text.indexOf('\\n') === -1 ? 0 : 1,\n line: this.line,\n col: this.col,\n }\n }\n \n var numLinesAround = 2\n var firstDisplayedLine = Math.max(token.line - numLinesAround, 1)\n var lastDisplayedLine = token.line + numLinesAround\n var lastLineDigits = String(lastDisplayedLine).length\n var displayedLines = lastNLines(\n this.buffer, \n (this.line - token.line) + numLinesAround + 1\n )\n .slice(0, 5)\n var errorLines = []\n errorLines.push(message + \" at line \" + token.line + \" col \" + token.col + \":\")\n errorLines.push(\"\")\n for (var i = 0; i < displayedLines.length; i++) {\n var line = displayedLines[i]\n var lineNo = firstDisplayedLine + i\n errorLines.push(pad(String(lineNo), lastLineDigits) + \" \" + line);\n if (lineNo === token.line) {\n errorLines.push(pad(\"\", lastLineDigits + token.col + 1) + \"^\")\n }\n }\n return errorLines.join(\"\\n\")\n }\n\n Lexer.prototype.clone = function() {\n return new Lexer(this.states, this.state)\n }\n\n Lexer.prototype.has = function(tokenType) {\n return true\n }\n\n\n return {\n compile: compile,\n states: compileStates,\n error: Object.freeze({error: true}),\n fallback: Object.freeze({fallback: true}),\n keywords: keywordTransform,\n }\n\n}));\n","import { Logger } from '.'\n\n/**\n * Each error name with corresponding type in info value\n */\ninterface PublicodesErrorTypes {\n\tInternalError: {\n\t\tdottedName?: string\n\t}\n\tEngineError: Record\n\tSyntaxError: {\n\t\tdottedName: string\n\t}\n\tEvaluationError: {\n\t\tdottedName: string\n\t}\n\tUnknownRule: {\n\t\tdottedName: string\n\t}\n\tPrivateRule: {\n\t\tdottedName: string\n\t}\n}\n\n/**\n * Return true if `error` is a PublicodesError,\n * use `name` parameter to check and narow error type\n * @example\n * try {\n * \tnew Engine().evaluate()\n * } catch (error) {\n * \tif (isPublicodesError(error, 'EngineError')) {\n * \t\tconsole.log(error.info)\n * \t}\n * }\n */\nexport const isPublicodesError = (\n\terror: unknown,\n\tname?: Name,\n): error is PublicodesError<\n\ttypeof name extends undefined ? keyof PublicodesErrorTypes : Name\n> =>\n\terror instanceof PublicodesError &&\n\t(name === undefined ? true : error.name === name)\n\n/**\n * Generic error for Publicodes\n */\nexport class PublicodesError<\n\tName extends keyof PublicodesErrorTypes,\n> extends Error {\n\tname: Name\n\tinfo: PublicodesErrorTypes[Name]\n\n\tconstructor(\n\t\tname: Name,\n\t\tmessage: string,\n\t\tinfo: PublicodesErrorTypes[Name],\n\t\toriginalError?: Error,\n\t) {\n\t\tsuper(buildMessage(name, message, info, originalError))\n\t\tthis.name = name\n\t\tthis.info = info\n\t}\n}\n\nconst buildMessage = (\n\tname: string,\n\tmessage: string,\n\tinfo?: PublicodesErrorTypes[keyof PublicodesErrorTypes],\n\toriginalError?: Error,\n) => {\n\tconst types: Partial> = {\n\t\tSyntaxError: 'Erreur syntaxique',\n\t\tEvaluationError: \"Erreur d'évaluation\",\n\t\tUnknownRule: 'Règle inconnue',\n\t\tPrivateRule: 'Règle privée',\n\t}\n\tconst isError = /error/i.test(name)\n\n\treturn (\n\t\t`\\n[ ${types[name] ?? name} ]` +\n\t\t(info && 'dottedName' in info && info.dottedName?.length ?\n\t\t\t`\\n➡️ Dans la règle \"${info.dottedName}\"`\n\t\t:\t'') +\n\t\t`\\n${isError ? '✖️' : '⚠️'} ${message}` +\n\t\t(originalError ?\n\t\t\t'\\n' + (isError ? ' ' : 'ℹ️ ') + originalError.message\n\t\t:\t'')\n\t)\n}\n\n/**\n * @deprecated Throw an internal server error, replace this by `throw new PublicodesError('InternalError', ...)`\n */\nexport class PublicodesInternalError extends PublicodesError<'InternalError'> {\n\tconstructor(payload: Record) {\n\t\tsuper(\n\t\t\t'InternalError',\n\t\t\t`\nErreur interne du moteur.\n\nCette erreur est le signe d'un bug dans publicodes. Pour nous aider à le résoudre, vous pouvez copier ce texte dans un nouveau ticket : https://github.com/betagouv/mon-entreprise/issues/new.\n\npayload:\n${JSON.stringify(payload, null, 2)}\n`,\n\t\t\tpayload,\n\t\t)\n\t}\n}\n\n/**\n * Use this error in default case of a switch to check exhaustivity statically\n * inspired by https://github.com/ts-essentials/ts-essentials#exhaustive-switch-cases\n */\nexport class UnreachableCaseError extends PublicodesInternalError {\n\tconstructor(value: never) {\n\t\tsuper(value)\n\t}\n}\n\nexport function warning(\n\tlogger: Logger,\n\tmessage: string,\n\tinformation: { dottedName: string },\n\toriginalError?: Error,\n) {\n\tlogger.warn(\n\t\tbuildMessage('Avertissement', message, information, originalError),\n\t)\n}\n\nexport function experimentalRuleWarning(logger: Logger, dottedName: string) {\n\tlogger.warn(\n\t\tbuildMessage(\n\t\t\t'Avertissement',\n\t\t\t\"Cette règle est tagguée comme experimentale. \\n\\nCela veut dire qu'elle peut être modifiée, renommée, ou supprimée sans qu'il n'y ait de changement de version majeure dans l'API.\\n\",\n\t\t\t{ dottedName },\n\t\t),\n\t)\n}\n","export function addToMapSet(map: Map>, key: T, value: T) {\n\tif (map.has(key)) {\n\t\tmap.get(key)!.add(value)\n\t\treturn\n\t}\n\tmap.set(key, new Set([value]))\n}\n\nexport function mergeWithArray<\n\tN extends string | number | symbol,\n\tM extends string | number | symbol,\n\tT,\n>(obj1: Record>, obj2: Record>): Record>\n\nexport function mergeWithArray<\n\tN extends string | number | symbol,\n\tM extends string | number | symbol,\n\tT,\n>(\n\tobj1: Partial>>,\n\tobj2: Partial>>,\n): Partial>>\n\nexport function mergeWithArray(\n\tobj1: Partial>>,\n\tobj2: Partial>>,\n): Partial>> {\n\treturn (Object.entries(obj2) as Array<[K, Array]>).reduce(\n\t\t(obj, [key, value]) => ({\n\t\t\t...obj,\n\t\t\t[key]: [...(obj[key] ?? []), ...value],\n\t\t}),\n\t\tobj1,\n\t) as Partial>>\n}\n\nexport const weakCopyObj = >(obj: T): T => {\n\tconst copy = {} as T\n\tfor (const key in obj) {\n\t\tcopy[key] = obj[key]\n\t}\n\n\treturn copy\n}\n","import { ParsedRules } from '..'\nimport { UnreachableCaseError } from '../error'\nimport { TrancheNodes } from '../mecanisms/trancheUtils'\nimport { ReferenceNode } from '../reference'\nimport { ReplacementRule } from '../replacement'\nimport { weakCopyObj } from '../utils'\nimport {\n\tASTNode,\n\tASTTransformer,\n\tASTVisitor,\n\tNodeKind,\n\tTraverseFunction,\n} from './types'\n\n/**\n\tThis function creates a transormation of the AST from on a simpler\n\tcallback function `fn`\n\n\t`fn` will be called with the nodes of the ASTTree during the exploration\n\n\tThe outcome of the callback function has an influence on the exploration of the AST :\n\t- `false`, the node is not updated and the exploration does not continue further down this branch\n\t- `undefined`, the node is not updated but the exploration continues and its children will be transformed\n\t- `ASTNode`, the node is transformed to the new value and the exploration does not continue further down the branch\n\n\t`updateFn` : It is possible to specifically use the updated version of a child\n\tby using the function passed as second argument. The returned value will be the\n\ttransformed version of the node.\n\t*/\nexport function makeASTTransformer(\n\tfn: (node: ASTNode, transform: ASTTransformer) => ASTNode | undefined | false,\n\tstopOnUpdate = true,\n): ASTTransformer {\n\tfunction transform(node: ASTNode): ASTNode {\n\t\tconst updatedNode = fn(node, transform)\n\t\tif (updatedNode === false) {\n\t\t\treturn node\n\t\t}\n\t\tif (updatedNode === undefined) {\n\t\t\treturn traverseASTNode(transform, node)\n\t\t}\n\t\treturn stopOnUpdate ? updatedNode : traverseASTNode(transform, updatedNode)\n\t}\n\treturn transform\n}\nexport function makeASTVisitor(\n\tfn: (node: ASTNode, visit: ASTVisitor) => 'continue' | 'stop',\n): ASTVisitor {\n\tfunction visit(node: ASTNode) {\n\t\tswitch (fn(node, visit)) {\n\t\t\tcase 'continue':\n\t\t\t\ttraverseASTNode(transformizedVisit, node)\n\t\t\t\treturn\n\t\t\tcase 'stop':\n\t\t\t\treturn\n\t\t}\n\t}\n\tconst transformizedVisit: ASTTransformer = (node) => {\n\t\tvisit(node)\n\t\treturn node\n\t}\n\treturn visit\n}\n\n// Can be made more flexible with other args like a filter function (ASTNode -> Bool).\nexport function iterAST(\n\tchildrenSelector: (node: ASTNode) => Iterable,\n\tnode: ASTNode,\n): ASTNode[] {\n\tfunction* iterate(node: ASTNode): IterableIterator {\n\t\tyield node\n\t\tconst selectedSubNodes = childrenSelector(node)\n\t\tfor (const subNode of selectedSubNodes) yield* iterate(subNode)\n\t}\n\treturn [...iterate(node)]\n}\n\n/**\n * This function allows to construct a specific value while exploring the AST with\n * a simple reducing function as argument.\n *\n * `fn` will be called with the currently reduced value `acc` and the current node of the AST\n *\n * If the callback function returns:\n * - `undefined`, the exploration continues further down and all the children are reduced\n * \tsuccessively to a single value\n * - `T`, the reduced value is returned\n *\n * `reduceFn` : It is possible to specifically use the reduced value of a child\n * by using the function passed as second argument. The returned value will be the reduced version\n * of the node\n */\nexport function reduceAST(\n\tfn: (acc: T, n: ASTNode, reduceFn: (n: ASTNode) => T) => T | undefined,\n\tstart: T,\n\tnode: ASTNode,\n): T {\n\tfunction traverseFn(acc: T, node: ASTNode): T {\n\t\tconst result = fn(acc, node, traverseFn.bind(null, start))\n\t\tif (result === undefined) {\n\t\t\treturn getChildrenNodes(node).reduce(traverseFn, acc)\n\t\t}\n\t\treturn result\n\t}\n\treturn traverseFn(start, node)\n}\n\nexport function getChildrenNodes(node: ASTNode): ASTNode[] {\n\tconst nodes: ASTNode[] = []\n\ttraverseASTNode((node) => {\n\t\tnodes.push(node)\n\t\treturn node\n\t}, node)\n\treturn nodes\n}\n\nexport function traverseParsedRules(\n\tfn: ASTTransformer,\n\tparsedRules: ParsedRules,\n): ParsedRules {\n\tconst ret = {} as Record\n\tfor (const name in parsedRules) {\n\t\tret[name] = fn(parsedRules[name])\n\t}\n\n\treturn ret as ParsedRules\n}\n\n/**\n * Apply a transform function on children. Not recursive.\n */\nexport const traverseASTNode: TraverseFunction = (fn, node) => {\n\tnode = traverseSourceMap(fn, node)\n\tswitch (node.nodeKind) {\n\t\tcase 'rule':\n\t\t\treturn traverseRuleNode(fn, node)\n\t\tcase 'reference':\n\t\tcase 'constant':\n\t\t\treturn node\n\t\tcase 'arrondi':\n\t\t\treturn traverseArrondiNode(fn, node)\n\t\tcase 'simplifier unité':\n\t\tcase 'variable manquante':\n\t\tcase 'est non applicable':\n\t\tcase 'est non défini':\n\t\t\treturn traverseUnaryOperationNode(fn, node)\n\t\tcase 'barème':\n\t\tcase 'taux progressif':\n\t\tcase 'grille':\n\t\t\treturn traverseNodeWithTranches(fn, node)\n\t\tcase 'une possibilité':\n\t\t\treturn traverseArrayNode(fn, node)\n\t\tcase 'durée':\n\t\t\treturn traverseDuréeNode(fn, node)\n\t\tcase 'résoudre référence circulaire':\n\t\t\treturn traverseRésoudreRéférenceCirculaireNode(fn, node)\n\t\tcase 'inversion':\n\t\t\treturn traverseInversionNode(fn, node)\n\t\tcase 'operation':\n\t\t\treturn traverseOperationNode(fn, node)\n\n\t\tcase 'contexte':\n\t\t\treturn traverseContexteNode(fn, node)\n\t\tcase 'unité':\n\t\t\treturn traverseUnitéNode(fn, node)\n\t\tcase 'variations':\n\t\t\treturn traverseVariationNode(fn, node)\n\t\tcase 'replacementRule':\n\t\t\treturn traverseReplacementNode(fn, node)\n\t\tcase 'texte':\n\t\t\treturn traverseTextNode(fn, node)\n\t\tcase 'condition':\n\t\t\treturn traverseConditionNode(fn, node)\n\n\t\tdefault:\n\t\t\tthrow new UnreachableCaseError(node)\n\t}\n}\n\nconst traverseSourceMap: TraverseFunction = (fn, node) => {\n\tif (!('sourceMap' in node) || !node.sourceMap || !node.sourceMap.args) {\n\t\treturn node\n\t}\n\tconst sourceMap = node.sourceMap\n\n\tconst args = {}\n\tfor (const key in sourceMap.args) {\n\t\tconst value = sourceMap.args[key]\n\t\targs[key] = Array.isArray(value) ? value.map((v) => fn(v)) : fn(value)\n\t}\n\n\treturn {\n\t\t...node,\n\t\tsourceMap: {\n\t\t\t...sourceMap,\n\t\t\targs,\n\t\t},\n\t}\n}\n\nconst traverseRuleNode: TraverseFunction<'rule'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\tcopy.suggestions = {}\n\tfor (const key in node.suggestions) {\n\t\tcopy.suggestions[key] = fn(node.suggestions[key])\n\t}\n\tcopy.replacements = node.replacements.map(fn) as Array\n\tcopy.explanation = {\n\t\truleDisabledByItsParent: node.explanation.ruleDisabledByItsParent,\n\t\tnullableParent:\n\t\t\tnode.explanation.nullableParent ?\n\t\t\t\tfn(node.explanation.nullableParent)\n\t\t\t:\tundefined,\n\t\tparents: node.explanation.parents.map(fn),\n\t\tvaleur: fn(node.explanation.valeur),\n\t}\n\n\treturn copy\n}\n\nconst traverseReplacementNode: TraverseFunction<'replacementRule'> = (\n\tfn,\n\tnode,\n) =>\n\t({\n\t\t...node,\n\t\tdefinitionRule: fn(node.definitionRule),\n\t\treplacedReference: fn(node.replacedReference),\n\t\twhiteListedNames: node.whiteListedNames.map(fn),\n\t\tblackListedNames: node.blackListedNames.map(fn),\n\t}) as ReplacementRule\n\nconst traverseUnaryOperationNode: TraverseFunction<\n\t| 'simplifier unité'\n\t| 'est non applicable'\n\t| 'est non défini'\n\t| 'variable manquante'\n> = (fn, node) => ({\n\t...node,\n\texplanation: fn(node.explanation),\n})\n\nfunction traverseTranche(fn: (n: ASTNode) => ASTNode, tranches: TrancheNodes) {\n\treturn tranches.map((tranche) => ({\n\t\t...tranche,\n\t\t...(tranche.plafond && { plafond: fn(tranche.plafond) }),\n\t\t...('montant' in tranche && { montant: fn(tranche.montant) }),\n\t\t...('taux' in tranche && { taux: fn(tranche.taux) }),\n\t}))\n}\nconst traverseNodeWithTranches: TraverseFunction<\n\t'barème' | 'taux progressif' | 'grille'\n> = (fn, node) => ({\n\t...node,\n\texplanation: {\n\t\tassiette: fn(node.explanation.assiette),\n\t\tmultiplicateur: fn(node.explanation.multiplicateur),\n\t\ttranches: traverseTranche(fn, node.explanation.tranches),\n\t},\n})\n\nconst traverseArrayNode: TraverseFunction<'une possibilité'> = (fn, node) => ({\n\t...node,\n\texplanation: node.explanation.map(fn),\n})\n\nconst traverseOperationNode: TraverseFunction<'operation'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\tcopy.explanation = [fn(node.explanation[0]), fn(node.explanation[1])]\n\n\treturn copy\n}\n\nconst traverseDuréeNode: TraverseFunction<'durée'> = (fn, node) => ({\n\t...node,\n\texplanation: {\n\t\tdepuis: fn(node.explanation.depuis),\n\t\t\"jusqu'à\": fn(node.explanation[\"jusqu'à\"]),\n\t},\n})\n\nconst traverseInversionNode: TraverseFunction<'inversion'> = (fn, node) => ({\n\t...node,\n\texplanation: {\n\t\t...node.explanation,\n\t\tinversionCandidates: node.explanation.inversionCandidates.map(fn) as any, // TODO\n\t},\n})\n\nconst traverseArrondiNode: TraverseFunction<'arrondi'> = (fn, node) => ({\n\t...node,\n\texplanation: {\n\t\tvaleur: fn(node.explanation.valeur),\n\t\tarrondi: fn(node.explanation.arrondi),\n\t},\n})\n\nconst traverseRésoudreRéférenceCirculaireNode: TraverseFunction<\n\t'résoudre référence circulaire'\n> = (fn, node) => ({\n\t...node,\n\texplanation: {\n\t\t...node.explanation,\n\t\tvaleur: fn(node.explanation.valeur),\n\t},\n})\n\nconst traverseTextNode: TraverseFunction<'texte'> = (fn, node) => ({\n\t...node,\n\texplanation: node.explanation.map((element) =>\n\t\ttypeof element === 'string' ? element : fn(element),\n\t),\n})\n\nconst traverseContexteNode: TraverseFunction<'contexte'> = (fn, node) => ({\n\t...node,\n\texplanation: {\n\t\t...node.explanation,\n\t\tcontexte: node.explanation.contexte.map(([name, value]) => [\n\t\t\tfn(name) as ReferenceNode,\n\t\t\tfn(value),\n\t\t]),\n\t\tvaleur: fn(node.explanation.valeur),\n\t},\n})\n\nconst traverseUnitéNode: TraverseFunction<'unité'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\tcopy.explanation = fn(node.explanation)\n\n\treturn copy\n}\n\nconst traverseVariationNode: TraverseFunction<'variations'> = (fn, node) => ({\n\t...node,\n\texplanation: node.explanation.map(({ condition, consequence }) => ({\n\t\tcondition: fn(condition),\n\t\tconsequence: consequence && fn(consequence),\n\t})),\n})\n\nconst traverseConditionNode: TraverseFunction<'condition'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\tcopy.explanation = {\n\t\tsi: fn(node.explanation.si),\n\t\talors: fn(node.explanation.alors),\n\t\tsinon: fn(node.explanation.sinon),\n\t}\n\n\treturn copy\n}\n","import { EvaluationFunction, PublicodesError } from '.'\nimport { ASTNode } from './AST/types'\n\nexport let evaluationFunctions = {\n\tconstant: (node) => node,\n} as any\n\nexport function registerEvaluationFunction<\n\tNodeName extends ASTNode['nodeKind'],\n>(nodeKind: NodeName, evaluationFunction: EvaluationFunction) {\n\tevaluationFunctions ??= {}\n\tif (evaluationFunctions[nodeKind]) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t`Multiple evaluation functions registered for the nodeKind \\x1b[4m${nodeKind}`,\n\t\t\t{ dottedName: '' },\n\t\t)\n\t}\n\tevaluationFunctions[nodeKind] = evaluationFunction\n}\n","import { ParsedRules } from '.'\nimport { ASTNode, ConstantNode } from './AST/types'\n\nexport type NodesTypes = WeakMap\n\n// TODO: Currently only handle nullability, but the infering logic should be\n// extended to support the full unit type system.\nexport type InferedType = {\n\tisNullable: boolean | undefined\n} & Pick\n\nconst UNDEFINED_TYPE = {\n\tisNullable: undefined,\n\ttype: undefined,\n}\n\nexport default function inferNodesTypes(\n\tnewRulesNames: Array,\n\tparsedRules: ParsedRules,\n\tnodesTypes: NodesTypes,\n) {\n\tfunction inferNodeUnitAndCache(node: ASTNode): InferedType {\n\t\tif (!node || typeof node !== 'object') {\n\t\t\treturn UNDEFINED_TYPE\n\t\t}\n\t\tif (nodesTypes.has(node)) {\n\t\t\treturn nodesTypes.get(node)!\n\t\t}\n\t\t// Sometimes there are cycles, so we need to prevent infinite loop by setting a default\n\t\tnodesTypes.set(node, UNDEFINED_TYPE)\n\t\tconst type = inferNodeType(node)\n\t\tnodesTypes.set(node, type)\n\t\treturn type\n\t}\n\n\tfunction inferNodeType(node: ASTNode): InferedType {\n\t\tswitch (node.nodeKind) {\n\t\t\tcase 'barème':\n\t\t\tcase 'durée':\n\t\t\tcase 'grille':\n\t\t\tcase 'taux progressif':\n\t\t\t\treturn { isNullable: false, type: 'number' }\n\t\t\tcase 'est non défini':\n\t\t\tcase 'est non applicable':\n\t\t\t\treturn { isNullable: false, type: 'boolean' }\n\n\t\t\tcase 'constant':\n\t\t\t\treturn {\n\t\t\t\t\tisNullable: node.isNullable ?? node.nodeValue === null,\n\t\t\t\t\ttype: node.type,\n\t\t\t\t}\n\t\t\tcase 'operation':\n\t\t\t\treturn {\n\t\t\t\t\tisNullable:\n\t\t\t\t\t\t['<', '<=', '>', '>=', '/', '*'].includes(node.operationKind) ?\n\t\t\t\t\t\t\tinferNodeUnitAndCache(node.explanation[0]).isNullable ||\n\t\t\t\t\t\t\tinferNodeUnitAndCache(node.explanation[1]).isNullable\n\t\t\t\t\t\t: node.operationKind === '-' ?\n\t\t\t\t\t\t\tinferNodeUnitAndCache(node.explanation[0]).isNullable\n\t\t\t\t\t\t:\tfalse,\n\t\t\t\t\ttype:\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\t['<', '<=', '>', '>=', '=', '!=', 'et', 'ou'].includes(\n\t\t\t\t\t\t\t\tnode.operationKind,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t) ?\n\t\t\t\t\t\t\t'boolean'\n\t\t\t\t\t\t:\t'number',\n\t\t\t\t}\n\n\t\t\tcase 'inversion':\n\t\t\tcase 'replacementRule':\n\t\t\tcase 'résoudre référence circulaire':\n\t\t\t\treturn { isNullable: false, type: 'number' }\n\t\t\tcase 'texte':\n\t\t\tcase 'une possibilité':\n\t\t\t\treturn { isNullable: false, type: 'string' }\n\n\t\t\tcase 'contexte':\n\t\t\tcase 'rule':\n\t\t\tcase 'arrondi':\n\t\t\t\treturn inferNodeUnitAndCache(node.explanation.valeur)\n\t\t\tcase 'unité':\n\t\t\tcase 'simplifier unité':\n\t\t\tcase 'variable manquante':\n\t\t\t\treturn inferNodeUnitAndCache(node.explanation)\n\t\t\tcase 'condition':\n\t\t\t\treturn {\n\t\t\t\t\tisNullable: [\n\t\t\t\t\t\tnode.explanation.si,\n\t\t\t\t\t\tnode.explanation.alors,\n\t\t\t\t\t\tnode.explanation.sinon,\n\t\t\t\t\t].some((n) => inferNodeUnitAndCache(n).isNullable),\n\t\t\t\t\ttype:\n\t\t\t\t\t\tinferNodeUnitAndCache(node.explanation.alors).type ??\n\t\t\t\t\t\tinferNodeUnitAndCache(node.explanation.sinon).type,\n\t\t\t\t}\n\n\t\t\tcase 'variations': {\n\t\t\t\tconst consequencesTypes = node.explanation.map(({ consequence }) =>\n\t\t\t\t\tinferNodeUnitAndCache(consequence),\n\t\t\t\t)\n\t\t\t\treturn {\n\t\t\t\t\tisNullable: consequencesTypes.some(\n\t\t\t\t\t\t(consequence) => consequence.isNullable,\n\t\t\t\t\t),\n\t\t\t\t\ttype: consequencesTypes\n\t\t\t\t\t\t.map((c) => c.type)\n\t\t\t\t\t\t.find((type) => type !== undefined),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcase 'reference':\n\t\t\t\treturn inferNodeUnitAndCache(parsedRules[node.dottedName as string])\n\t\t}\n\t}\n\n\tnewRulesNames.forEach((name) => {\n\t\tconst rule = parsedRules[name]\n\t\tinferNodeUnitAndCache(rule)\n\t\trule.explanation.parents.forEach(inferNodeUnitAndCache)\n\t})\n\n\treturn nodesTypes\n}\n","import { ASTNode, ConstantNode, EvaluatedNode, Evaluation } from './AST/types'\n\nexport const collectNodeMissing = (\n\tnode: EvaluatedNode | ASTNode,\n): Record =>\n\t'missingVariables' in node ? node.missingVariables : {}\n\nexport const bonus = (missings: Record = {}) =>\n\tObject.fromEntries(\n\t\tObject.entries(missings).map(([key, value]) => [key, value + 1]),\n\t)\nexport const mergeMissing = (\n\tleft: Record | undefined = {},\n\tright: Record | undefined = {},\n): Record =>\n\tObject.fromEntries(\n\t\t[...Object.keys(left), ...Object.keys(right)].map((key) => [\n\t\t\tkey,\n\t\t\t(left[key] ?? 0) + (right[key] ?? 0),\n\t\t]),\n\t)\n\nexport const mergeAllMissing = (missings: Array) =>\n\tmissings.map(collectNodeMissing).reduce(mergeMissing, {})\n\nexport const defaultNode = (nodeValue: Evaluation) =>\n\t({\n\t\tnodeValue,\n\t\ttype: typeof nodeValue,\n\t\tisDefault: true,\n\t\tnodeKind: 'constant',\n\t}) as ConstantNode\n\nexport const notApplicableNode = {\n\tnodeKind: 'constant',\n\tnodeValue: null,\n\tmissingVariables: {},\n\ttype: undefined,\n\tisNullable: true,\n} as EvaluatedNode<'constant'>\n\nexport const undefinedNode = {\n\tnodeKind: 'constant',\n\tnodeValue: undefined,\n\tmissingVariables: {},\n\ttype: undefined,\n\tisNullable: false,\n} as EvaluatedNode<'constant'>\n\nexport const undefinedNumberNode = {\n\t...undefinedNode,\n\ttype: 'number',\n} as EvaluatedNode<'constant'>\n","import { PublicodesExpression } from '..'\nimport { makeASTTransformer } from '../AST'\nimport { ASTNode } from '../AST/types'\nimport { PublicodesError } from '../error'\nimport parse from '../parse'\nimport { Context, createContext } from '../parsePublicodes'\n\nexport function createParseInlinedMecanism(\n\tname: string,\n\targs: Record,\n\tbody: PublicodesExpression,\n) {\n\tlet parsedBody\n\tlet parsedDefaultArgs\n\tfunction parseInlineMecanism(providedArgs, context) {\n\t\tparsedBody ??= parse(body, createContext({ dottedName: 'INLINE_MECANISM' }))\n\t\tparsedDefaultArgs ??= {}\n\t\tfor (const name in args) {\n\t\t\tif ('par défaut' in args[name]) {\n\t\t\t\tparsedDefaultArgs[name] = parse(\n\t\t\t\t\targs[name]['par défaut'],\n\t\t\t\t\tcreateContext({}),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// Case of unary mecanism\n\t\tif (Object.keys(args).length === 1 && 'valeur' in args) {\n\t\t\tprovidedArgs = {\n\t\t\t\tvaleur: providedArgs,\n\t\t\t}\n\t\t}\n\n\t\tconst parsedProvidedArgs = {}\n\t\tfor (const name in providedArgs) {\n\t\t\tparsedProvidedArgs[name] = parse(providedArgs[name], context)\n\t\t}\n\n\t\tconst parsedInlineMecanism = makeASTTransformer((node) => {\n\t\t\tif (node.nodeKind !== 'reference' || !(node.name in args)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst argName = node.name\n\t\t\tif (argName in parsedProvidedArgs) {\n\t\t\t\treturn parsedProvidedArgs[argName]\n\t\t\t}\n\t\t\tif (argName in parsedDefaultArgs) {\n\t\t\t\treturn parsedDefaultArgs[argName]\n\t\t\t}\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'SyntaxError',\n\t\t\t\t`Il manque la clé '${argName} dans le mécanisme ${name}`,\n\t\t\t\t{ dottedName: argName },\n\t\t\t)\n\t\t})(parsedBody)\n\n\t\tparsedInlineMecanism.sourceMap = {\n\t\t\tmecanismName: name,\n\t\t\targs: parsedProvidedArgs,\n\t\t}\n\n\t\treturn parsedInlineMecanism\n\t}\n\n\tparseInlineMecanism.nom = name\n\n\treturn Object.assign(parseInlineMecanism, 'name', {\n\t\tvalue: `parse${toCamelCase(name)}Inline`,\n\t})\n}\n\n/**\n Note : Les transformations de mécanisme opérant sur les listes sont plus couteuses que celles opérant sur des scalaires.\n\n Cela vient du fait qu'il n'y a pas la possibilité de définir ces transformations dans publicodes : il manque le type liste et les opérations de bases associées (reduce, map).\n\n On doit donc déplier l'opération statiquement, au parsing, ce qui prend plus de temps, au parsing et à l'évaluation. somme: [1,2,3] est transformé en (1 + 2) + 3).\n\n De manière général, les baisse en performances de cette PR sont attenduee : il s'agit d'une contrepartie logique de l'utilisation de mécanisme de base publicodes. Ce qu'on gagne en solidité de l'évaluation & en amélioration du typage, on le perd en performance. C'est logique puisque l'evaluation de ces mécanisme n'est plus du JS natif mais passe par une structure intermédiaire.\n\n Pour améliorer les perfs, il y a plusieurs pistes :\n\n\t- optimiser d'avantage les opérations de bases\n\t- ajouter les listes et les opérations sur les listes dans publicodes\n\t- ajouter une implémentation \"native\" de certains mécanismes utilisés (on gagne quand même à les décomposer en mécanismes de base pour la partie spécification et typage).\n */\nexport function createParseInlinedMecanismWithArray(\n\tname: string,\n\targs: Record,\n\tbody: (\n\t\targs: Record>,\n\t) => PublicodesExpression,\n) {\n\tfunction parseInlineMecanism(providedArgs, context: Context) {\n\t\t// Case of unary mecanism\n\t\tif (Object.keys(args).length === 1 && 'valeur' in args) {\n\t\t\tprovidedArgs = {\n\t\t\t\tvaleur: providedArgs,\n\t\t\t}\n\t\t}\n\n\t\tconst parsedProvidedArgs = {}\n\t\tfor (const name in providedArgs) {\n\t\t\tconst value = providedArgs[name]\n\t\t\tparsedProvidedArgs[name] =\n\t\t\t\tArray.isArray(value) ?\n\t\t\t\t\tvalue.map((v) => parse(v, context))\n\t\t\t\t:\tparse(value, context)\n\t\t}\n\n\t\tconst parsedInlineMecanism = parse(body(parsedProvidedArgs), context)\n\t\tparsedInlineMecanism.sourceMap = {\n\t\t\tmecanismName: name,\n\t\t\targs: parsedProvidedArgs,\n\t\t}\n\t\treturn parsedInlineMecanism\n\t}\n\n\tparseInlineMecanism.nom = name\n\n\treturn Object.assign(parseInlineMecanism, 'name', {\n\t\tvalue: `parse${toCamelCase(name)}Inline`,\n\t})\n}\n\nfunction toCamelCase(str: string) {\n\treturn str\n\t\t.replace(/(?:^\\w|[A-Z]|\\b\\w)/g, (ltr) => ltr.toUpperCase())\n\t\t.replace(/\\s+/g, '')\n}\n","import { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'abattement',\n\t{\n\t\tabattement: {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\t'-': ['valeur', 'abattement'],\n\t\tplancher: 0,\n\t},\n)\n","import { notApplicableNode } from '../evaluationUtils'\nimport { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'applicable si',\n\t{\n\t\t'applicable si': {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: 'applicable si != non',\n\t\t\talors: 'valeur',\n\t\t\tsinon: notApplicableNode,\n\t\t},\n\t},\n)\n","import { BaseUnit, Evaluation, Unit } from './AST/types'\nimport { PublicodesError } from './error'\n\nexport type getUnitKey = (writtenUnit: string) => string\nexport type formatUnit = (unit: string, count: number) => string\n\nexport const parseUnit = (\n\tstring: string,\n\tgetUnitKey: getUnitKey = (x) => x,\n): Unit => {\n\tif (string.includes(' /') || string.includes('/ ')) {\n\t\tthrow new Error(\n\t\t\t`L'unité \"${string}\" ne doit pas contenir d'espace avant et après \"/\"`,\n\t\t)\n\t}\n\tconst [a, ...b] = string.split('/')\n\t// denominator could be 'x/y' or 'x.y' or 'x.y/z'\n\tconst splitUnit = (string: string): string[] =>\n\t\tdecomposePower(\n\t\t\tstring\n\t\t\t\t.split('.')\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.map((unit) => getUnitKey(unit)),\n\t\t)\n\tconst result = {\n\t\tnumerators: splitUnit(a),\n\t\tdenominators: b.flatMap((u) => splitUnit(u)),\n\t}\n\treturn result\n}\n\nconst lastNumberFromString = /(\\d+)(?!.*[A-Za-z])/g\n\n/**\n * Count the number of each unit, e.g. [m, m, kg, kg] -> {m: 2, kg: 2}\n */\nfunction getUnitCounts(baseUnits: Array): Record {\n\tconst countUnits = {}\n\tbaseUnits.forEach((e) => {\n\t\tconst powerMatch = e.match(lastNumberFromString)\n\t\tif (powerMatch != null) {\n\t\t\tconst power = powerMatch[0]\n\t\t\tconst primaryUnit = e.split(power)[0]\n\t\t\tcountUnits[primaryUnit] = (countUnits[primaryUnit] ?? 0) + +power\n\t\t} else {\n\t\t\tcountUnits[e] = (countUnits[e] ?? 0) + 1\n\t\t}\n\t})\n\treturn countUnits\n}\n\n/**\n * Decompose power of units, e.g. [m2] -> [m, m] or [kg2, m3] -> [kg, kg, m, m, m]\n */\nfunction decomposePower(baseUnits: Array): Array {\n\tconst unitCounts = getUnitCounts(baseUnits)\n\treturn Object.entries(unitCounts).flatMap(([primaryUnit, power]) =>\n\t\tArray(power).fill(primaryUnit),\n\t)\n}\n\n/**\n * Combine power of units, e.g. [m2, m] -> [m3] or [m, m, kg, kg] -> [m2, kg2]\n */\nfunction combinePower(baseUnit: Array): Array {\n\tconst unitCounts = getUnitCounts(baseUnit)\n\treturn Object.entries(unitCounts).map(([primaryUnit, power]) =>\n\t\tpower > 1 ? `${primaryUnit}${power}` : primaryUnit,\n\t)\n}\n\nconst printUnits = (\n\tunits: Array,\n\tcount: number,\n\tformatUnit: formatUnit = (x) => x,\n): string => {\n\treturn combinePower(units.map((unit) => formatUnit(unit, count))).join('.')\n}\n\nconst plural = 2\nexport function serializeUnit(\n\trawUnit: Unit | undefined | string,\n\tcount: number = plural,\n\tformatUnit: formatUnit = (x) => x,\n): string | undefined {\n\tif (rawUnit === null || typeof rawUnit !== 'object') {\n\t\treturn typeof rawUnit === 'string' ? formatUnit(rawUnit, count) : rawUnit\n\t}\n\tconst unit = simplify(rawUnit)\n\tconst { numerators = [], denominators = [] } = unit\n\n\tconst n = numerators.length > 0\n\tconst d = denominators.length > 0\n\tconst string =\n\t\t!n && !d ? ''\n\t\t: n && !d ? printUnits(numerators, count, formatUnit)\n\t\t: !n && d ? `/${printUnits(denominators, 1, formatUnit)}`\n\t\t: `${printUnits(numerators, plural, formatUnit)}/${printUnits(\n\t\t\t\tdenominators,\n\t\t\t\t1,\n\t\t\t\tformatUnit,\n\t\t\t)}`\n\n\treturn string\n}\n\ntype SupportedOperators = '*' | '/' | '+' | '-'\n\nconst noUnit = { numerators: [], denominators: [] }\nexport const inferUnit = (\n\toperator: SupportedOperators,\n\trawUnits: Array,\n): Unit | undefined => {\n\tif (operator === '/') {\n\t\tif (rawUnits.length !== 2) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'InternalError',\n\t\t\t\t'Infer units of a division with units.length !== 2)',\n\t\t\t\t{},\n\t\t\t)\n\t\t}\n\n\t\treturn inferUnit('*', [\n\t\t\trawUnits[0] || noUnit,\n\t\t\t{\n\t\t\t\tnumerators: (rawUnits[1] || noUnit).denominators,\n\t\t\t\tdenominators: (rawUnits[1] || noUnit).numerators,\n\t\t\t},\n\t\t])\n\t}\n\tconst units = rawUnits.filter(Boolean)\n\tif (units.length <= 1) {\n\t\treturn units[0]\n\t}\n\tif (operator === '*')\n\t\treturn simplify({\n\t\t\tnumerators: units.flatMap((u) => u?.numerators ?? []),\n\t\t\tdenominators: units.flatMap((u) => u?.denominators ?? []),\n\t\t})\n\n\tif (operator === '-' || operator === '+') {\n\t\treturn rawUnits.find((u) => u)\n\t}\n\n\treturn undefined\n}\n\nconst equals = (a: T, b: T) => {\n\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\treturn a.length === b.length && a.every((_, i) => a[i] === b[i])\n\t} else {\n\t\treturn a === b\n\t}\n}\n\nexport const removeOnce =\n\t(element: T, eqFn: (a: T, b: T) => boolean = equals) =>\n\t(list: Array): Array => {\n\t\tconst index = list.findIndex((e) => eqFn(e, element))\n\t\treturn list.filter((_, i) => i !== index)\n\t}\n\nconst simplify = (\n\tunit: Unit,\n\teqFn: (a: string, b: string) => boolean = equals,\n): Unit => {\n\tconst simplifiedUnit = [...unit.numerators, ...unit.denominators].reduce(\n\t\t({ numerators, denominators }, next) =>\n\t\t\t(\n\t\t\t\tnumerators.find((u) => eqFn(next, u)) &&\n\t\t\t\tdenominators.find((u) => eqFn(next, u))\n\t\t\t) ?\n\t\t\t\t{\n\t\t\t\t\tnumerators: removeOnce(next, eqFn)(numerators),\n\t\t\t\t\tdenominators: removeOnce(next, eqFn)(denominators),\n\t\t\t\t}\n\t\t\t:\t{ numerators, denominators },\n\t\tunit,\n\t)\n\treturn simplifiedUnit\n}\n\nconst convertTable: ConvertTable = {\n\t'mois/an': 12,\n\t'jour/an': 365,\n\t'jour/mois': 365 / 12,\n\t'trimestre/an': 4,\n\t'mois/trimestre': 3,\n\t'jour/trimestre': (365 / 12) * 3,\n\t'€/k€': 10 ** 3,\n\t'g/kg': 10 ** 3,\n\t'mg/g': 10 ** 3,\n\t'mg/kg': 10 ** 6,\n\t'm/km': 10 ** 3,\n\t'cm/m': 10 ** 2,\n\t'mm/cm': 10 ** 1,\n\t'mm/m': 10 ** 3,\n\t'cm/km': 10 ** 5,\n\t'mm/km': 10 ** 6,\n}\n\nfunction singleUnitConversionFactor(\n\tfrom: string,\n\tto: string,\n): number | undefined {\n\treturn (\n\t\tconvertTable[`${to}/${from}`] ||\n\t\t(convertTable[`${from}/${to}`] && 1 / convertTable[`${from}/${to}`])\n\t)\n}\nfunction unitsConversionFactor(from: string[], to: string[]): number {\n\tlet factor =\n\t\t100 **\n\t\t// Factor is mutliplied or divided 100 for each '%' in units\n\t\t(to.filter((unit) => unit === '%').length -\n\t\t\tfrom.filter((unit) => unit === '%').length)\n\t;[factor] = from.reduce(\n\t\t([value, toUnits], fromUnit) => {\n\t\t\tconst index = toUnits.findIndex(\n\t\t\t\t(toUnit) => !!singleUnitConversionFactor(fromUnit, toUnit),\n\t\t\t)\n\t\t\tconst factor = singleUnitConversionFactor(fromUnit, toUnits[index]) || 1\n\t\t\treturn [\n\t\t\t\tvalue * factor,\n\t\t\t\t[...toUnits.slice(0, index + 1), ...toUnits.slice(index + 1)],\n\t\t\t]\n\t\t},\n\t\t[factor, to],\n\t)\n\treturn factor\n}\n\n// TODO(@clemog):\n// - Deal with other equivalent units : l: 'dm3',\n// - Convert unit instead of ignore warning\nconst equivalentTable = {\n\t'kW.h': 'kWh',\n\t'mn/h': 'noeud',\n}\n\nfunction areEquivalentSerializedUnit(\n\tserializedFrom: string | undefined,\n\tserializedTo: string | undefined,\n): boolean {\n\tif (!serializedFrom || !serializedTo) return false\n\treturn (\n\t\tserializedFrom === serializedTo ||\n\t\tserializedFrom === equivalentTable[serializedTo] ||\n\t\tserializedTo === equivalentTable[serializedFrom]\n\t)\n}\n\nexport function convertUnit>(\n\tfrom: Unit | undefined,\n\tto: Unit | undefined,\n\tvalue: ValType,\n): ValType {\n\tconst serializedFrom = serializeUnit(from)\n\tconst serializedTo = serializeUnit(to)\n\tif (\n\t\t!areEquivalentSerializedUnit(serializedFrom, serializedTo) &&\n\t\t!areUnitConvertible(from, to)\n\t) {\n\t\tthrow new PublicodesError(\n\t\t\t'EngineError',\n\t\t\t`Impossible de convertir l'unité '${serializedFrom}' en '${serializedTo}'`,\n\t\t\t{},\n\t\t)\n\t}\n\tif (!value) {\n\t\treturn value\n\t}\n\tif (from === undefined) {\n\t\treturn value\n\t}\n\tconst [fromSimplified, factorTo] = simplifyUnitWithValue(from || noUnit)\n\tconst [toSimplified, factorFrom] = simplifyUnitWithValue(to || noUnit)\n\treturn round(\n\t\t(((value as number) * factorTo) / factorFrom) *\n\t\t\tunitsConversionFactor(\n\t\t\t\tfromSimplified.numerators,\n\t\t\t\ttoSimplified.numerators,\n\t\t\t) *\n\t\t\tunitsConversionFactor(\n\t\t\t\ttoSimplified.denominators,\n\t\t\t\tfromSimplified.denominators,\n\t\t\t),\n\t) as any\n}\n\nconst convertibleUnitClasses = unitClasses(convertTable)\ntype unitClasses = Array>\ntype ConvertTable = { readonly [index: string]: number }\n\n// Reduce the convertTable provided by the user into a list of compatibles\n// classes.\nfunction unitClasses(convertTable: ConvertTable) {\n\treturn Object.keys(convertTable).reduce(\n\t\t(classes: unitClasses, ratio: string) => {\n\t\t\tconst [a, b] = ratio.split('/')\n\t\t\tconst ia = classes.findIndex((units) => units.has(a))\n\t\t\tconst ib = classes.findIndex((units) => units.has(b))\n\t\t\tif (ia > -1 && ib > -1 && ia !== ib) {\n\t\t\t\tthrow new PublicodesError('EngineError', `Invalid ratio ${ratio}`, {})\n\t\t\t} else if (ia === -1 && ib === -1) {\n\t\t\t\tclasses.push(new Set([a, b]))\n\t\t\t} else if (ia > -1) {\n\t\t\t\tclasses[ia].add(b)\n\t\t\t} else if (ib > -1) {\n\t\t\t\tclasses[ib].add(a)\n\t\t\t}\n\t\t\treturn classes\n\t\t},\n\t\t[],\n\t)\n}\n\nfunction areSameClass(a: string, b: string) {\n\treturn (\n\t\ta === b ||\n\t\tconvertibleUnitClasses.some(\n\t\t\t(unitsClass) => unitsClass.has(a) && unitsClass.has(b),\n\t\t)\n\t)\n}\n\nfunction round(value: number) {\n\treturn +value.toFixed(16)\n}\n\nexport function simplifyUnit(unit: Unit): Unit {\n\tconst { numerators, denominators } = simplify(unit, areSameClass)\n\tif (numerators.length && numerators.every((symb) => symb === '%')) {\n\t\treturn { numerators: ['%'], denominators }\n\t}\n\treturn removePercentages({ numerators, denominators })\n}\n\nfunction simplifyUnitWithValue(unit: Unit, value = 1): [Unit, number] {\n\tconst factor = unitsConversionFactor(unit.numerators, unit.denominators)\n\treturn [\n\t\tsimplify(removePercentages(unit), areSameClass),\n\t\tvalue ? round(value * factor) : value,\n\t]\n}\n\nconst removePercentages = (unit: Unit): Unit => ({\n\tnumerators: unit.numerators.filter((e) => e !== '%'),\n\tdenominators: unit.denominators.filter((e) => e !== '%'),\n})\n\nexport function areUnitConvertible(a: Unit | undefined, b: Unit | undefined) {\n\tif (a == null || b == null) {\n\t\treturn true\n\t}\n\tconst countByUnitClass = (units: Array) =>\n\t\tunits.reduce((counters, unit) => {\n\t\t\tconst classIndex = convertibleUnitClasses.findIndex((unitClass) =>\n\t\t\t\tunitClass.has(unit),\n\t\t\t)\n\t\t\tconst key = classIndex === -1 ? unit : '' + classIndex\n\t\t\treturn { ...counters, [key]: 1 + (counters[key] ?? 0) }\n\t\t}, {})\n\n\tconst [numA, denomA, numB, denomB] = [\n\t\ta.numerators,\n\t\ta.denominators,\n\t\tb.numerators,\n\t\tb.denominators,\n\t].map(countByUnitClass)\n\tconst uniq = (arr: Array): Array => [...new Set(arr)]\n\tconst unitClasses = [numA, denomA, numB, denomB].map(Object.keys).flat()\n\treturn uniq(unitClasses).every(\n\t\t(unitClass) =>\n\t\t\t(numA[unitClass] || 0) - (denomA[unitClass] || 0) ===\n\t\t\t\t(numB[unitClass] || 0) - (denomB[unitClass] || 0) || unitClass === '%',\n\t)\n}\n","import { EvaluationFunction, simplifyNodeUnit } from '..'\nimport { ASTNode, EvaluatedNode } from '../AST/types'\nimport { PublicodesError } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport { serializeUnit } from '../units'\n\nexport type ArrondiNode = {\n\texplanation: {\n\t\tarrondi: ASTNode\n\t\tvaleur: ASTNode\n\t}\n\tnodeKind: 'arrondi'\n}\n\nfunction roundWithPrecision(n: number, fractionDigits: number) {\n\treturn +n.toFixed(fractionDigits)\n}\n\nconst evaluate: EvaluationFunction<'arrondi'> = function (node) {\n\t// We need to simplify the node unit to correctly round values containing\n\t// percentages units, see #1358\n\tconst valeur = simplifyNodeUnit(this.evaluateNode(node.explanation.valeur))\n\tconst nodeValue = valeur.nodeValue\n\tlet arrondi = node.explanation.arrondi\n\tif (nodeValue !== false) {\n\t\tarrondi = this.evaluateNode(arrondi)\n\n\t\tif (\n\t\t\ttypeof (arrondi as EvaluatedNode).nodeValue === 'number' &&\n\t\t\t!serializeUnit((arrondi as EvaluatedNode).unit)?.match(/décimales?/)\n\t\t) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'EvaluationError',\n\t\t\t\t`L'unité ${serializeUnit(\n\t\t\t\t\t(arrondi as EvaluatedNode).unit,\n\t\t\t\t)} de l'arrondi est inconnu. Vous devez utiliser l'unité “décimales”`,\n\t\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t\t)\n\t\t}\n\t}\n\n\treturn {\n\t\t...node,\n\t\tnodeValue:\n\t\t\ttypeof valeur.nodeValue !== 'number' || !('nodeValue' in arrondi) ?\n\t\t\t\tvaleur.nodeValue\n\t\t\t: typeof arrondi.nodeValue === 'number' ?\n\t\t\t\troundWithPrecision(valeur.nodeValue, arrondi.nodeValue)\n\t\t\t: arrondi.nodeValue === true ? roundWithPrecision(valeur.nodeValue, 0)\n\t\t\t: arrondi.nodeValue === undefined ? undefined\n\t\t\t: valeur.nodeValue,\n\t\texplanation: { valeur, arrondi },\n\t\tmissingVariables: mergeAllMissing([valeur, arrondi]),\n\t\tunit: valeur.unit,\n\t}\n}\n\nexport default function parseArrondi(v, context) {\n\tconst explanation = {\n\t\tvaleur: parse(v.valeur, context),\n\t\tarrondi: parse(v.arrondi, context),\n\t}\n\treturn {\n\t\texplanation,\n\t\tnodeKind: parseArrondi.nom,\n\t}\n}\n\nparseArrondi.nom = 'arrondi' as const\n\nregisterEvaluationFunction(parseArrondi.nom, evaluate)\n","import { EvaluatedNode, Unit } from './AST/types'\nimport { convertUnit, simplifyUnit } from './units'\n\nexport function simplifyNodeUnit(node) {\n\tif (!node.unit) {\n\t\treturn node\n\t}\n\tconst unit = simplifyUnit(node.unit)\n\n\treturn convertNodeToUnit(unit, node)\n}\n\nexport function convertNodeToUnit(\n\tto: Unit | undefined,\n\tnode: Node,\n): Node {\n\treturn {\n\t\t...node,\n\t\tnodeValue:\n\t\t\tnode.unit && typeof node.nodeValue === 'number' ?\n\t\t\t\tconvertUnit(node.unit, to, node.nodeValue)\n\t\t\t:\tnode.nodeValue,\n\t\tunit: to,\n\t}\n}\n","import { Evaluation, Unit } from './AST/types'\nimport { simplifyNodeUnit } from './nodeUnits'\nimport { formatUnit, serializeUnit } from './units'\n\nexport const numberFormatter =\n\t({\n\t\tstyle,\n\t\tmaximumFractionDigits = 2,\n\t\tminimumFractionDigits = 0,\n\t\tlanguage,\n\t}: {\n\t\tstyle?: string\n\t\tmaximumFractionDigits?: number\n\t\tminimumFractionDigits?: number\n\t\tlanguage?: string\n\t}) =>\n\t(value: number) => {\n\t\t// When we format currency we don't want to display a single decimal digit\n\t\t// ie 8,1€ but we want to display 8,10€\n\t\tconst adaptedMinimumFractionDigits =\n\t\t\t(\n\t\t\t\tstyle === 'currency' &&\n\t\t\t\tmaximumFractionDigits >= 2 &&\n\t\t\t\tminimumFractionDigits === 0 &&\n\t\t\t\t!Number.isInteger(value)\n\t\t\t) ?\n\t\t\t\t2\n\t\t\t:\tminimumFractionDigits\n\t\treturn Intl.NumberFormat(language, {\n\t\t\tstyle,\n\t\t\tcurrency: 'EUR',\n\t\t\tmaximumFractionDigits,\n\t\t\tminimumFractionDigits: adaptedMinimumFractionDigits,\n\t\t}).format(value)\n\t}\n\nexport const formatCurrency = (\n\tnodeValue: number | undefined,\n\tlanguage: string,\n) => {\n\treturn nodeValue == undefined ? '' : (\n\t\t\t(formatNumber({ unit: '€', language, nodeValue }) ?? '').replace(\n\t\t\t\t/^(-)?€/,\n\t\t\t\t'$1€\\u00A0',\n\t\t\t)\n\t\t)\n}\n\nexport const formatPercentage = (nodeValue: number | undefined) =>\n\tnodeValue == undefined ? '' : (\n\t\tformatNumber({ unit: '%', nodeValue, maximumFractionDigits: 2 })\n\t)\n\ntype formatValueOptions = {\n\tmaximumFractionDigits?: number\n\tminimumFractionDigits?: number\n\tlanguage?: string\n\tunit?: Unit | string\n\tformatUnit?: formatUnit\n\tnodeValue: number\n}\n\nfunction formatNumber({\n\tmaximumFractionDigits,\n\tminimumFractionDigits,\n\tlanguage,\n\tformatUnit,\n\tunit,\n\tnodeValue,\n}: formatValueOptions) {\n\tif (typeof nodeValue !== 'number') {\n\t\treturn nodeValue\n\t}\n\tconst serializedUnit =\n\t\tunit ? serializeUnit(unit, nodeValue, formatUnit) : undefined\n\tswitch (serializedUnit) {\n\t\tcase '€':\n\t\t\treturn numberFormatter({\n\t\t\t\tstyle: 'currency',\n\t\t\t\tmaximumFractionDigits,\n\t\t\t\tminimumFractionDigits,\n\t\t\t\tlanguage,\n\t\t\t})(nodeValue)\n\t\tcase '%':\n\t\t\treturn numberFormatter({\n\t\t\t\tstyle: 'percent',\n\t\t\t\tmaximumFractionDigits,\n\t\t\t\tlanguage,\n\t\t\t})(nodeValue / 100)\n\t\tdefault:\n\t\t\treturn (\n\t\t\t\tnumberFormatter({\n\t\t\t\t\tstyle: 'decimal',\n\t\t\t\t\tminimumFractionDigits,\n\t\t\t\t\tmaximumFractionDigits,\n\t\t\t\t\tlanguage,\n\t\t\t\t})(nodeValue) +\n\t\t\t\t(typeof serializedUnit === 'string' ? `\\u00A0${serializedUnit}` : '')\n\t\t\t)\n\t}\n}\n\nexport function capitalise0(name: undefined): undefined\nexport function capitalise0(name: string): string\nexport function capitalise0(name?: string) {\n\treturn name && name[0].toUpperCase() + name.slice(1)\n}\n\nconst booleanTranslations = {\n\tfr: { true: 'oui', false: 'non' },\n\ten: { true: 'yes', false: 'no' },\n}\n\ntype Options = {\n\tlanguage?: string\n\tdisplayedUnit?: string\n\tprecision?: number\n\tformatUnit?: formatUnit\n}\n\nexport function formatValue(\n\tvalue: number | { nodeValue: Evaluation; unit?: Unit } | undefined,\n\n\t{ language = 'fr', displayedUnit, formatUnit, precision = 2 }: Options = {},\n) {\n\tlet nodeValue =\n\t\t(\n\t\t\ttypeof value === 'number' ||\n\t\t\ttypeof value === 'undefined' ||\n\t\t\tvalue === null\n\t\t) ?\n\t\t\tvalue\n\t\t:\tvalue.nodeValue\n\n\tif (typeof nodeValue === 'number' && Number.isNaN(nodeValue)) {\n\t\treturn 'Erreur dans le calcul du nombre'\n\t}\n\tif (nodeValue === undefined) {\n\t\treturn 'Pas encore défini'\n\t}\n\tif (nodeValue === null) {\n\t\treturn 'Non applicable'\n\t}\n\tif (typeof nodeValue === 'string') {\n\t\treturn nodeValue.replace('\\\\n', '\\n')\n\t}\n\tif (typeof nodeValue === 'boolean')\n\t\treturn booleanTranslations[language][nodeValue]\n\tif (typeof nodeValue === 'number') {\n\t\tlet unit =\n\t\t\t(\n\t\t\t\ttypeof value === 'number' ||\n\t\t\t\ttypeof value === 'undefined' ||\n\t\t\t\t!('unit' in value)\n\t\t\t) ?\n\t\t\t\tundefined\n\t\t\t:\tvalue.unit\n\t\tif (unit) {\n\t\t\tconst simplifiedNode = simplifyNodeUnit({\n\t\t\t\tunit,\n\t\t\t\tnodeValue,\n\t\t\t})\n\t\t\tunit = simplifiedNode.unit\n\t\t\tnodeValue = simplifiedNode.nodeValue as number\n\t\t}\n\t\treturn formatNumber({\n\t\t\tminimumFractionDigits: 0,\n\t\t\tmaximumFractionDigits: precision,\n\t\t\tlanguage,\n\t\t\tformatUnit,\n\t\t\tnodeValue,\n\t\t\tunit: displayedUnit ?? unit,\n\t\t}).trim()\n\t}\n\treturn undefined\n}\n\nexport function serializeValue(\n\t{ nodeValue, unit }: { nodeValue: Evaluation; unit?: Unit },\n\t{ format }: { format: formatUnit },\n) {\n\tconst serializedUnit = (\n\t\tunit && typeof nodeValue === 'number' ?\n\t\t\tserializeUnit(unit, nodeValue, format)\n\t\t:\t'')?.replace(/\\s*\\/\\s*/g, '/')\n\treturn `${nodeValue} ${serializedUnit}`.trim()\n}\n","import { ParsedRules } from '.'\nimport { ASTNode } from './AST/types'\nimport { PublicodesError } from './error'\nimport { ReferencesMaps } from './parsePublicodes'\nimport { ReferenceNode } from './reference'\nimport { RuleNode } from './rule'\nimport { addToMapSet } from './utils'\n\nexport { cyclicDependencies } from './AST/graph'\n\nconst splitName = (str: string) => str.split(' . ')\nconst joinName = (strs: Array) => strs.join(' . ')\n\n/**\n * Returns the last part of a dottedName (the leaf).\n */\nexport const nameLeaf = (dottedName: string) =>\n\tsplitName(dottedName).slice(-1)?.[0]\n\n/**\n * Encodes a dottedName for the URL to be secure.\n * @see {@link decodeRuleName}\n */\nexport const encodeRuleName = (dottedName: string): string =>\n\tdottedName\n\t\t?.replace(/\\s\\.\\s/g, '/')\n\t\t.replace(/-/g, '\\u2011') // replace with a insecable tiret to differenciate from space\n\t\t.replace(/\\s/g, '-')\n\n/**\n * Decodes an encoded dottedName.\n * @see {@link encodeRuleName}\n */\nexport const decodeRuleName = (dottedName: string): string =>\n\tdottedName\n\t\t.replace(/\\//g, ' . ')\n\t\t.replace(/-/g, ' ')\n\t\t.replace(/\\u2011/g, '-')\n\n/**\n * Return dottedName from contextName\n */\nexport const contextNameToDottedName = (contextName: string) =>\n\tcontextName.endsWith('$SITUATION') ? ruleParent(contextName) : contextName\n\n/**\n * Returns the parent dottedName\n */\nexport const ruleParent = (dottedName: string): string =>\n\tjoinName(splitName(dottedName).slice(0, -1))\n\n/**\n * Returns an array of dottedName from near parent to far parent.\n */\nexport function ruleParents(dottedName: string): Array {\n\treturn splitName(dottedName)\n\t\t.slice(0, -1)\n\t\t.map((_, i, arr) => joinName(arr.slice(0, i + 1)))\n\t\t.reverse()\n}\n\n/**\n * Returns an array of all child rules of a dottedName\n */\nexport const getChildrenRules = (\n\tparsedRules: ParsedRules,\n\tdottedName: string,\n) => {\n\tconst childrenRules = Object.keys(parsedRules).filter(\n\t\t(ruleDottedName) =>\n\t\t\truleDottedName.startsWith(dottedName) &&\n\t\t\tsplitName(ruleDottedName).length === splitName(dottedName).length + 1,\n\t)\n\n\treturn childrenRules\n}\n\n/**\n * Finds the common ancestor of two dottedName\n */\nexport function findCommonAncestor(dottedName1: string, dottedName2: string) {\n\tconst splitDottedName1 = splitName(dottedName1)\n\tconst splitDottedName2 = splitName(dottedName2)\n\tconst index = splitDottedName1.findIndex(\n\t\t(value, i) => splitDottedName2[i] !== value,\n\t)\n\n\treturn index === -1 ? dottedName1 : joinName(splitDottedName1.slice(0, index))\n}\n\n/**\n * Check wether a rule is accessible from a namespace.\n *\n * Takes into account that some namespace can be `private`, i.e. that they can only be\n * accessed by immediate parent, children or siblings.\n *\n * @param rules The parsed rules\n * @param contextName The context of the call\n * @param name The namespace checked for accessibility\n */\nexport function isAccessible(\n\trules: Record,\n\tcontextName: string,\n\tname: string,\n) {\n\tif (!(name in rules)) {\n\t\tthrow new PublicodesError(\n\t\t\t'InternalError',\n\t\t\t`La règle \"${name}\" n'existe pas`,\n\t\t\t{ dottedName: name },\n\t\t)\n\t}\n\n\tconst commonAncestor = findCommonAncestor(contextName, name)\n\tconst parents = [name, ...ruleParents(name), '']\n\tconst rulesToCheckForPrivacy = parents.slice(\n\t\t0,\n\t\tMath.max(parents.indexOf(commonAncestor) - 1, 0),\n\t)\n\n\treturn rulesToCheckForPrivacy.every(\n\t\t(dottedName) =>\n\t\t\t!(dottedName in rules) || rules[dottedName].private === false,\n\t)\n}\n\n/**\n * Check wether a rule is tagged as experimental.\n *\n * Takes into account the a children of an experimental rule is also experimental\n *\n * @param rules The parsed rules\n * @param name The namespace checked for experimental\n */\nexport function isExperimental(rules: Record, name: string) {\n\tif (!(name in rules)) {\n\t\tthrow new PublicodesError(\n\t\t\t'InternalError',\n\t\t\t`La règle \"${name}\" n'existe pas`,\n\t\t\t{ dottedName: name },\n\t\t)\n\t}\n\tconst parents = [name, ...ruleParents(name)]\n\treturn parents.some(\n\t\t(dottedName) =>\n\t\t\tdottedName in rules && rules[dottedName].rawNode?.experimental === 'oui',\n\t)\n}\n\nfunction dottedNameFromContext(context: string, partialName: string) {\n\treturn context ? context + ' . ' + partialName : partialName\n}\nexport function disambiguateReference>(\n\trules: R,\n\treferencedFrom = '',\n\tpartialName: string,\n): keyof R {\n\tconst possibleContexts = ruleParents(referencedFrom)\n\tpossibleContexts.push(referencedFrom)\n\n\t// If the partialName starts with ^ . ^ . ^ . , we want to go up in the parents\n\tif (partialName.startsWith('^ . ')) {\n\t\tconst numberParent = partialName.match(/^(\\^ \\. )+/)![0].length / 4\n\t\tpartialName = partialName.replace(/^(\\^ \\. )+/, '')\n\t\tpossibleContexts.splice(-numberParent)\n\t}\n\n\tconst rootContext = possibleContexts.pop()\n\tpossibleContexts.unshift(rootContext as string)\n\tpossibleContexts.push('')\n\n\tconst context = possibleContexts.find((context) => {\n\t\tconst dottedName = dottedNameFromContext(context, partialName)\n\t\tif (!(dottedName in rules)) {\n\t\t\treturn false\n\t\t}\n\t\tif (dottedName === referencedFrom) {\n\t\t\treturn false\n\t\t}\n\t\treturn isAccessible(rules, referencedFrom, dottedName)\n\t})\n\n\tif (context !== undefined) {\n\t\treturn dottedNameFromContext(context, partialName) as keyof R\n\t}\n\n\t// The last possibility we want to check is if the rule is referencing itself\n\tif (referencedFrom.endsWith(partialName)) {\n\t\treturn referencedFrom as keyof R\n\t}\n\n\tconst possibleDottedName = possibleContexts.map((c) =>\n\t\tdottedNameFromContext(c, partialName),\n\t)\n\n\tif (possibleDottedName.every((dottedName) => !(dottedName in rules))) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`La référence \"${partialName}\" est introuvable.\nVérifiez que l'orthographe et l'espace de nom sont corrects`,\n\t\t\t{ dottedName: contextNameToDottedName(referencedFrom) },\n\t\t)\n\t}\n\n\tthrow new PublicodesError(\n\t\t'SyntaxError',\n\t\t`La règle \"${possibleDottedName.find(\n\t\t\t(dottedName) => dottedName in rules,\n\t\t)}\" n'est pas accessible depuis \"${referencedFrom}\".\n\tCela vient du fait qu'elle est privée ou qu'un de ses parent est privé`,\n\t\t{ dottedName: contextNameToDottedName(referencedFrom) },\n\t)\n}\n\nexport function ruleWithDedicatedDocumentationPage(rule) {\n\treturn (\n\t\trule.virtualRule !== true &&\n\t\trule.type !== 'groupe' &&\n\t\trule.type !== 'texte' &&\n\t\trule.type !== 'paragraphe' &&\n\t\trule.type !== 'notification'\n\t)\n}\n\nexport function updateReferencesMapsFromReferenceNode(\n\tnode: ASTNode,\n\treferencesMaps: ReferencesMaps,\n\truleDottedName?: string,\n) {\n\tif (node.nodeKind === 'reference') {\n\t\taddToMapSet(\n\t\t\treferencesMaps.referencesIn,\n\t\t\truleDottedName ?? node.contextDottedName,\n\t\t\tnode.dottedName,\n\t\t)\n\t\taddToMapSet(\n\t\t\treferencesMaps.rulesThatUse,\n\t\t\tnode.dottedName,\n\t\t\truleDottedName ?? node.contextDottedName,\n\t\t)\n\t}\n}\nexport function disambiguateReferenceNode(\n\tnode: ASTNode,\n\tparsedRules: ParsedRules,\n): ReferenceNode | undefined {\n\tif (node.nodeKind !== 'reference') {\n\t\treturn\n\t}\n\tif (node.dottedName) {\n\t\treturn node\n\t}\n\n\tnode.dottedName = disambiguateReference(\n\t\tparsedRules,\n\t\tnode.contextDottedName,\n\t\tnode.name,\n\t)\n\tnode.title = parsedRules[node.dottedName].title\n\tnode.acronym = parsedRules[node.dottedName].rawNode.acronyme\n\treturn node\n}\n","/* eslint-disable prefer-rest-params */\n/* eslint-disable @typescript-eslint/no-this-alias */\n// Adapted from https://github.com/dagrejs/graphlib (MIT license)\n// and https://github.com/lodash/lodash (MIT license)\n\n// TODO: type this\n\nfunction has(obj, key) {\n\treturn obj != null && Object.prototype.hasOwnProperty.call(obj, key)\n}\nfunction constant(value) {\n\treturn function () {\n\t\treturn value\n\t}\n}\n\nconst DEFAULT_EDGE_NAME = '\\x00'\nconst EDGE_KEY_DELIM = '\\x01'\n\nconst incrementOrInitEntry = (map, k) => {\n\tif (map[k]) {\n\t\tmap[k]++\n\t} else {\n\t\tmap[k] = 1\n\t}\n}\n\nconst decrementOrRemoveEntry = (map, k) => {\n\tif (!--map[k]) {\n\t\tdelete map[k]\n\t}\n}\n\nconst edgeArgsToId = (isDirected, v_, w_, name) => {\n\tlet v = '' + v_\n\tlet w = '' + w_\n\tif (!isDirected && v > w) {\n\t\tconst tmp = v\n\t\tv = w\n\t\tw = tmp\n\t}\n\treturn (\n\t\tv +\n\t\tEDGE_KEY_DELIM +\n\t\tw +\n\t\tEDGE_KEY_DELIM +\n\t\t(name === undefined ? DEFAULT_EDGE_NAME : name)\n\t)\n}\n\nconst edgeArgsToObj = (isDirected, v_, w_, name) => {\n\tlet v = '' + v_\n\tlet w = '' + w_\n\tif (!isDirected && v > w) {\n\t\tconst tmp = v\n\t\tv = w\n\t\tw = tmp\n\t}\n\tconst edgeObj: any = { v: v, w: w }\n\tif (name) {\n\t\tedgeObj.name = name\n\t}\n\treturn edgeObj\n}\n\nconst edgeObjToId = (isDirected, edgeObj) => {\n\treturn edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name)\n}\nexport class Graph {\n\tprivate _nodeCount = 0\n\tprivate _edgeCount = 0\n\n\tprivate _isDirected: any\n\n\tprivate _label: undefined\n\tprivate _defaultNodeLabelFn: (...args: any[]) => any\n\tprivate _defaultEdgeLabelFn: (...args: any[]) => any\n\tprivate _nodes: Record\n\tprivate _in: Record\n\tprivate _preds: Record>\n\tprivate _out: Record>\n\tprivate _sucs: Record>\n\tprivate _edgeObjs: Record\n\tprivate _edgeLabels: Record\n\n\tconstructor(opts: Record = {}) {\n\t\tthis._isDirected = has(opts, 'directed') ? opts.directed : true\n\n\t\t// Label for the graph itself\n\t\tthis._label = undefined\n\n\t\t// Defaults to be set when creating a new node\n\t\tthis._defaultNodeLabelFn = constant(undefined)\n\n\t\t// Defaults to be set when creating a new edge\n\t\tthis._defaultEdgeLabelFn = constant(undefined)\n\n\t\t// v -> label\n\t\tthis._nodes = {}\n\n\t\t// v -> edgeObj\n\t\tthis._in = {}\n\n\t\t// u -> v -> Number\n\t\tthis._preds = {}\n\n\t\t// v -> edgeObj\n\t\tthis._out = {} as Record>\n\n\t\t// v -> w -> Number\n\t\tthis._sucs = {}\n\n\t\t// e -> edgeObj\n\t\tthis._edgeObjs = {}\n\n\t\t// e -> label\n\t\tthis._edgeLabels = {}\n\t}\n\n\t/* === Graph functions ========= */\n\n\tisDirected() {\n\t\treturn this._isDirected\n\t}\n\tsetGraph(label) {\n\t\tthis._label = label\n\t\treturn this\n\t}\n\tgraph() {\n\t\treturn this._label\n\t}\n\n\t/* === Node functions ========== */\n\n\tnodeCount() {\n\t\treturn this._nodeCount\n\t}\n\tnodes() {\n\t\treturn Object.keys(this._nodes)\n\t}\n\tsetNode(v, value: any = undefined) {\n\t\tif (has(this._nodes, v)) {\n\t\t\tif (arguments.length > 1) {\n\t\t\t\tthis._nodes[v] = value\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tthis._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v)\n\t\tthis._in[v] = {}\n\t\tthis._preds[v] = {}\n\t\tthis._out[v] = {}\n\t\tthis._sucs[v] = {}\n\t\t++this._nodeCount\n\t\treturn this\n\t}\n\tsetNodes(vs, value) {\n\t\tvs.forEach((v) => {\n\t\t\tif (value !== undefined) {\n\t\t\t\tthis.setNode(v, value)\n\t\t\t} else {\n\t\t\t\tthis.setNode(v)\n\t\t\t}\n\t\t})\n\t\treturn this\n\t}\n\tnode(v) {\n\t\treturn this._nodes[v]\n\t}\n\thasNode(v) {\n\t\treturn has(this._nodes, v)\n\t}\n\tsuccessors(v) {\n\t\tconst sucsV = this._sucs[v]\n\t\tif (sucsV) {\n\t\t\treturn Object.keys(sucsV)\n\t\t}\n\t}\n\n\t/* === Edge functions ========== */\n\n\tedgeCount() {\n\t\treturn this._edgeCount\n\t}\n\tedges() {\n\t\treturn Object.values(this._edgeObjs)\n\t}\n\tsetEdge(\n\t\tv: string,\n\t\tw: string,\n\t\tvalue: any = undefined,\n\t\tname: string | undefined = undefined,\n\t) {\n\t\tv = '' + v\n\t\tw = '' + w\n\n\t\tconst e = edgeArgsToId(this._isDirected, v, w, name)\n\t\tif (has(this._edgeLabels, e)) {\n\t\t\tif (value !== undefined) {\n\t\t\t\tthis._edgeLabels[e] = value\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\t// It didn't exist, so we need to create it.\n\t\t// First ensure the nodes exist.\n\t\tthis.setNode(v)\n\t\tthis.setNode(w)\n\n\t\tthis._edgeLabels[e] =\n\t\t\tvalue !== undefined ? value : this._defaultEdgeLabelFn(v, w, name)\n\n\t\tconst edgeObj = edgeArgsToObj(this._isDirected, v, w, name)\n\t\t// Ensure we add undirected edges in a consistent way.\n\t\tv = edgeObj.v\n\t\tw = edgeObj.w\n\n\t\tObject.freeze(edgeObj)\n\t\tthis._edgeObjs[e] = edgeObj\n\t\tincrementOrInitEntry(this._preds[w], v)\n\t\tincrementOrInitEntry(this._sucs[v], w)\n\t\tthis._in[w][e] = edgeObj\n\t\tthis._out[v][e] = edgeObj\n\t\tthis._edgeCount++\n\t\treturn this\n\t}\n\n\tedge(v, w, name) {\n\t\tconst e =\n\t\t\targuments.length === 1 ?\n\t\t\t\tedgeObjToId(this._isDirected, arguments[0])\n\t\t\t:\tedgeArgsToId(this._isDirected, v, w, name)\n\t\treturn this._edgeLabels[e]\n\t}\n\n\thasEdge(v, w, name) {\n\t\tconst e =\n\t\t\targuments.length === 1 ?\n\t\t\t\tedgeObjToId(this._isDirected, arguments[0])\n\t\t\t:\tedgeArgsToId(this._isDirected, v, w, name)\n\t\treturn has(this._edgeLabels, e)\n\t}\n\n\tremoveEdge(v, w, name) {\n\t\tconst e =\n\t\t\targuments.length === 1 ?\n\t\t\t\tedgeObjToId(this._isDirected, arguments[0])\n\t\t\t:\tedgeArgsToId(this._isDirected, v, w, name)\n\t\tconst edge = this._edgeObjs[e]\n\t\tif (edge) {\n\t\t\tv = edge.v\n\t\t\tw = edge.w\n\t\t\tdelete this._edgeLabels[e]\n\t\t\tdelete this._edgeObjs[e]\n\t\t\tdecrementOrRemoveEntry(this._preds[w], v)\n\t\t\tdecrementOrRemoveEntry(this._sucs[v], w)\n\t\t\tdelete this._in[w][e]\n\t\t\tdelete this._out[v][e]\n\t\t\tthis._edgeCount--\n\t\t}\n\t\treturn this\n\t}\n\n\toutEdges(v: string, w: string | undefined = undefined) {\n\t\tconst outV = this._out[v]\n\t\tif (outV) {\n\t\t\tconst edges: any = Object.values(outV)\n\t\t\tif (w === undefined) {\n\t\t\t\treturn edges\n\t\t\t}\n\t\t\treturn edges.filter(function (edge) {\n\t\t\t\treturn edge.w === w\n\t\t\t})\n\t\t}\n\t}\n}\n\n/** Cycles stuff **/\n\nfunction tarjan(graph) {\n\tlet index = 0\n\tconst stack: any[] = []\n\tconst visited = {} // node id -> { onStack, lowlink, index }\n\tconst results: any[] = []\n\n\tfunction dfs(v) {\n\t\tconst entry = (visited[v] = {\n\t\t\tonStack: true,\n\t\t\tlowlink: index,\n\t\t\tindex: index++,\n\t\t})\n\t\tstack.push(v)\n\n\t\tgraph.successors(v).forEach(function (w) {\n\t\t\tif (!Object.prototype.hasOwnProperty.call(visited, w)) {\n\t\t\t\tdfs(w)\n\t\t\t\tentry.lowlink = Math.min(entry.lowlink, visited[w].lowlink)\n\t\t\t} else if (visited[w].onStack) {\n\t\t\t\tentry.lowlink = Math.min(entry.lowlink, visited[w].index)\n\t\t\t}\n\t\t})\n\n\t\tif (entry.lowlink === entry.index) {\n\t\t\tconst cmpt: any[] = []\n\t\t\tlet w\n\t\t\tdo {\n\t\t\t\tw = stack.pop()\n\t\t\t\tvisited[w].onStack = false\n\t\t\t\tcmpt.push(w)\n\t\t\t} while (v !== w)\n\t\t\tresults.push(cmpt)\n\t\t}\n\t}\n\n\tgraph.nodes().forEach(function (v) {\n\t\tif (!Object.prototype.hasOwnProperty.call(visited, v)) {\n\t\t\tdfs(v)\n\t\t}\n\t})\n\n\treturn results\n}\n\nexport function findCycles(graph): string[][] {\n\treturn tarjan(graph).filter(function (cmpt) {\n\t\treturn (\n\t\t\tcmpt.length > 1 || (cmpt.length === 1 && graph.hasEdge(cmpt[0], cmpt[0]))\n\t\t)\n\t})\n}\n","import parsePublicodes from '../parsePublicodes'\nimport { findCycles, Graph } from './findCycles'\n\ntype GraphCycles = string[][]\n\nfunction buildDependenciesGraph(rulesDeps: Map>) {\n\tconst g = new Graph()\n\t;[...rulesDeps.entries()].forEach(([ruleDottedName, dependencies]) => {\n\t\tdependencies.forEach((depDottedName) => {\n\t\t\tg.setEdge(ruleDottedName, depDottedName)\n\t\t})\n\t})\n\treturn g\n}\n\ntype RawRules = Parameters[0]\n\nexport function cyclesInDependenciesGraph(rawRules: RawRules): GraphCycles {\n\tconst { referencesMaps } = parsePublicodes(rawRules)\n\tconst dependenciesGraph = buildDependenciesGraph(referencesMaps.referencesIn)\n\tconst cycles = findCycles(dependenciesGraph)\n\n\treturn cycles.map((c) => c.reverse())\n}\n\n/**\n * Make the cycle as small as possible.\n */\nexport function squashCycle(\n\trulesDependenciesObject: Map>,\n\tcycle: string[],\n): string[] {\n\tfunction* loopFrom(i: number) {\n\t\tlet j = i\n\t\twhile (true) {\n\t\t\tyield cycle[j++ % cycle.length]\n\t\t}\n\t}\n\tconst smallCycleStartingAt: string[][] = []\n\tfor (let i = 0; i < cycle.length; i++) {\n\t\tconst smallCycle: string[] = []\n\t\tlet previousVertex: string | undefined = undefined\n\t\tfor (const vertex of loopFrom(i)) {\n\t\t\tif (previousVertex === undefined) {\n\t\t\t\tsmallCycle.push(vertex)\n\t\t\t\tpreviousVertex = vertex\n\t\t\t} else if (rulesDependenciesObject.get(previousVertex)?.has(vertex)) {\n\t\t\t\tif (smallCycle.includes(vertex)) {\n\t\t\t\t\tsmallCycle.splice(0, smallCycle.lastIndexOf(vertex))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tsmallCycle.push(vertex)\n\t\t\t\tpreviousVertex = vertex\n\t\t\t}\n\t\t}\n\t\tsmallCycleStartingAt.push(smallCycle)\n\t}\n\n\tconst smallest = smallCycleStartingAt.reduce((minCycle, someCycle) =>\n\t\tsomeCycle.length > minCycle.length ? minCycle : someCycle,\n\t)\n\treturn smallest\n}\n\n/**\n * This function is useful so as to print the dependencies at each node of the\n * cycle.\n * ⚠️ Indeed, the findCycles function returns the cycle found using the\n * Tarjan method, which is **not necessarily the smallest cycle**. However, the\n * smallest cycle is more readable.\n */\nexport function cyclicDependencies(\n\trawRules: RawRules,\n): [GraphCycles, string[]] {\n\tconst { referencesMaps } = parsePublicodes(rawRules)\n\tconst dependenciesGraph = buildDependenciesGraph(referencesMaps.referencesIn)\n\tconst cycles = findCycles(dependenciesGraph)\n\n\tconst reversedCycles = cycles.map((c) => c.reverse())\n\n\tconst smallCycles = reversedCycles.map((cycle) =>\n\t\tsquashCycle(referencesMaps.referencesIn, cycle),\n\t)\n\n\tconst printableStronglyConnectedComponents = reversedCycles.map((c, i) =>\n\t\tprintInDotFormat(dependenciesGraph, c, smallCycles[i]),\n\t)\n\n\treturn [smallCycles, printableStronglyConnectedComponents]\n}\n\n/**\n * Is edge in the cycle, in the same order?\n */\nconst edgeIsInCycle = (cycle: string[], v: string, w: string): boolean => {\n\tfor (let i = 0; i < cycle.length + 1; i++) {\n\t\tif (v === cycle[i] && w === cycle[(i + 1) % cycle.length]) return true\n\t}\n\treturn false\n}\n\nexport function printInDotFormat(\n\tdependenciesGraph: Graph,\n\tcycle: string[],\n\tsubCycleToHighlight: string[],\n) {\n\tconst edgesSet = new Set()\n\tcycle.forEach((vertex) => {\n\t\tdependenciesGraph\n\t\t\t.outEdges(vertex)\n\t\t\t.filter(({ w }) => cycle.includes(w))\n\t\t\t.forEach(({ v, w }) => {\n\t\t\t\tedgesSet.add(\n\t\t\t\t\t`\"${v}\" -> \"${w}\"` +\n\t\t\t\t\t\t(edgeIsInCycle(subCycleToHighlight, v, w) ? ' [color=red]' : ''),\n\t\t\t\t)\n\t\t\t})\n\t})\n\treturn `digraph Cycle {\\n\\t${[...edgesSet].join(';\\n\\t')};\\n}`\n}\n","import Engine from '.'\nimport { ASTNode, EvaluatedNode, MissingVariables } from './AST/types'\nimport { PublicodesError } from './error'\nimport { registerEvaluationFunction } from './evaluationFunctions'\nimport { defaultNode, mergeMissing, undefinedNode } from './evaluationUtils'\nimport { capitalise0 } from './format'\nimport parse, { mecanismKeys } from './parse'\nimport { Context, RawRule } from './parsePublicodes'\nimport {\n\tReplacementRule,\n\tparseRendNonApplicable,\n\tparseReplacements,\n} from './replacement'\nimport { isAccessible, nameLeaf, ruleParents } from './ruleUtils'\nimport { weakCopyObj } from './utils'\n\nexport type Rule = {\n\tformule?: Record | string\n\tvaleur?: Record | string\n\tquestion?: string\n\tdescription?: string\n\tunité?: string\n\tacronyme?: string\n\texemples?: any\n\trésumé?: string\n\ticônes?: string\n\ttitre?: string\n\tsévérité?: string\n\ttype?: string\n\texperimental?: 'oui'\n\t'possiblement non applicable'?: 'oui'\n\tprivé?: 'oui'\n\tnote?: string\n\tremplace?: Remplace | Array\n\t'rend non applicable'?: Remplace | Array\n\tsuggestions?: Record>\n\tréférences?: { [source: string]: string }\n\tAPI?: string\n\t'identifiant court'?: string\n} & Record\n\ntype Remplace =\n\t| {\n\t\t\t'références à': string\n\t\t\tdans?: Array | string\n\t\t\t'sauf dans'?: Array | string\n\t\t\tpriorité?: number\n\t\t\t// eslint-disable-next-line no-mixed-spaces-and-tabs\n\t }\n\t| string\n\nexport type RuleNode = {\n\tdottedName: Name\n\ttitle: string\n\tnodeKind: 'rule'\n\tvirtualRule: boolean\n\tprivate: boolean\n\trawNode: Rule\n\treplacements: Array\n\texplanation: {\n\t\tvaleur: ASTNode\n\t\tparents: Array\n\t\tnullableParent?: ASTNode\n\t\truleDisabledByItsParent: boolean\n\t}\n\tsuggestions: Record\n\t'identifiant court'?: string\n}\n\nfunction parseRule(nom: string, rawRule: Rule, context: Context): RuleNode {\n\tconst privateRule = rawRule.privé === 'oui' || nom.startsWith('[privé] ')\n\tnom = nom.replace(/^\\[privé\\] /, '')\n\tconst dottedName = [context.dottedName, nom].filter(Boolean).join(' . ')\n\n\tconst name = nameLeaf(dottedName)\n\tconst title = capitalise0(rawRule['titre'] ?? name)\n\n\tif (context.parsedRules[dottedName]) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t`La référence '${dottedName}' a déjà été définie`,\n\t\t\t{ dottedName },\n\t\t)\n\t}\n\n\tconst ruleValue: Record = {}\n\n\tfor (const key in rawRule) {\n\t\tif (mecanismKeys.includes(key)) {\n\t\t\truleValue[key] = rawRule[key]\n\t\t}\n\t}\n\tif ('formule' in rawRule) {\n\t\truleValue.valeur = rawRule.formule\n\t}\n\tif (!privateRule && !dottedName.endsWith('$SITUATION')) {\n\t\t// We create a $SITUATION child rule for each rule that is not private\n\t\t// This value will be used to evaluate the rule in the current situation (`setSituation`)\n\t\truleValue['dans la situation'] = `${dottedName} . $SITUATION`\n\t\truleValue['avec'] =\n\t\t\tweakCopyObj(ruleValue['avec'] as Record) ?? {}\n\t\tconst situationValue = weakCopyObj(undefinedNode)\n\t\tsituationValue.isNullable = rawRule['possiblement non applicable'] === 'oui'\n\t\t;(ruleValue['avec'] as Record)['[privé] $SITUATION'] = {\n\t\t\tvaleur: situationValue,\n\t\t}\n\n\t\t// If the `par défaut` value is used, then the rule should be listed as a missingVariables\n\t\tif (ruleValue['par défaut'] != null) {\n\t\t\truleValue['par défaut'] = {\n\t\t\t\tvaleur: ruleValue['par défaut'],\n\t\t\t\t'variable manquante': dottedName,\n\t\t\t}\n\t\t}\n\t}\n\n\t// const ruleContext = weakCopyObj(context)\n\t// ruleContext.dottedName = dottedName\n\t// const ruleContext = { ...context, dottedName }\n\tconst currentDottedNameContext = context.dottedName\n\tcontext.dottedName = dottedName\n\n\t// The following ensures that nested rules appears after the root rule when\n\t// iterating over parsedRule\n\tcontext.parsedRules[dottedName] = undefined as any\n\n\tconst explanation = {\n\t\tvaleur: parse(ruleValue, context),\n\t\t// We include a list of references to the parents to implement the branch\n\t\t// desactivation feature. When evaluating a rule we only need to know the\n\t\t// first nullable parent, but this is something that we can't determine at\n\t\t// this stage :\n\t\t// - we need to run remplacements (which works on references in the ASTs\n\t\t// which is why we insert these “virtual” references)\n\t\t// - we need to infer unit of the rules\n\t\t//\n\t\t// An alternative implementation would be possible that would colocate the\n\t\t// code related to branch desactivation (ie find the first nullable parent\n\t\t// statically after rules parsing)\n\t\tparents: ruleParents(dottedName).map(\n\t\t\t(parent) =>\n\t\t\t\t({\n\t\t\t\t\tdottedName: parent,\n\t\t\t\t\tnodeKind: 'reference',\n\t\t\t\t\tcontextDottedName: context.dottedName,\n\t\t\t\t}) as ASTNode<'reference'>,\n\t\t),\n\t}\n\n\tconst suggestions = {} as Record\n\tif (rawRule.suggestions) {\n\t\tfor (const name in rawRule.suggestions) {\n\t\t\tsuggestions[name] = parse(rawRule.suggestions[name], context)\n\t\t}\n\t}\n\n\tcontext.parsedRules[dottedName] = {\n\t\tdottedName,\n\t\treplacements: [\n\t\t\t...parseRendNonApplicable(rawRule['rend non applicable'], context),\n\t\t\t...parseReplacements(rawRule.remplace, context),\n\t\t],\n\t\ttitle: title,\n\t\tprivate: privateRule,\n\t\tsuggestions,\n\t\tnodeKind: 'rule',\n\t\texplanation,\n\t\trawNode: rawRule,\n\t\tvirtualRule: privateRule,\n\t} as RuleNode\n\tcontext.dottedName = currentDottedNameContext\n\treturn context.parsedRules[dottedName]\n}\n\nexport function parseRules(\n\trules: Partial>,\n\tcontext: Context,\n) {\n\tfor (const dottedName in rules) {\n\t\tlet rule = rules[dottedName]\n\n\t\tif (typeof rule === 'string' || typeof rule === 'number') {\n\t\t\trule = { valeur: `${rule}` }\n\t\t}\n\t\tif (typeof rule !== 'object') {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'SyntaxError',\n\t\t\t\t`Rule ${dottedName} is incorrectly written. Please give it a proper value.`,\n\t\t\t\t{ dottedName },\n\t\t\t)\n\t\t}\n\t\tconst copy = rule === null ? {} : weakCopyObj(rule)\n\t\tparseRule(dottedName, copy, context)\n\t}\n}\n\nregisterEvaluationFunction('rule', function evaluate(node) {\n\tconst { ruleDisabledByItsParent, nullableParent, parentMissingVariables } =\n\t\tevaluateDisablingParent(this, node)\n\n\tlet valeurEvaluation: EvaluatedNode = {\n\t\t...node.explanation.valeur,\n\t\tnodeValue: null,\n\t\tmissingVariables: {},\n\t}\n\tif (!ruleDisabledByItsParent) {\n\t\tif (\n\t\t\tthis.cache._meta.evaluationRuleStack.filter(\n\t\t\t\t(dottedName) => dottedName === node.dottedName,\n\t\t\t).length > 1\n\t\t) {\n\t\t\t// TODO : remettre ce warning. Je ne sais pas pourquoi, mais la base de règle de mon-entreprise lève un warning sur quasiment toutes les cotisations\n\t\t\t// \t\t\twarning(\n\t\t\t// \t\t\t\tthis.context.logger,\n\t\t\t// \t\t\t\t`Un cycle a été détecté lors de l'évaluation de cette règle.\n\n\t\t\t// Par défaut cette règle sera évaluée à 'null'.\n\t\t\t// Pour indiquer au moteur de résoudre la référence circulaire en trouvant le point fixe\n\t\t\t// de la fonction, il vous suffit d'ajouter l'attribut suivant niveau de la règle :\n\n\t\t\t// \t${node.dottedName}:\n\t\t\t// \t\trésoudre la référence circulaire: oui\"\n\t\t\t// \t\t...\n\t\t\t// `,\n\t\t\t// \t\t\t\t{ dottedName: node.dottedName }\n\t\t\t// \t\t\t)\n\n\t\t\tvaleurEvaluation = {\n\t\t\t\tnodeValue: undefined,\n\t\t\t} as EvaluatedNode\n\t\t} else {\n\t\t\tthis.cache._meta.evaluationRuleStack.unshift(node.dottedName)\n\t\t\tvaleurEvaluation = this.evaluateNode(node.explanation.valeur)\n\t\t\tthis.cache._meta.evaluationRuleStack.shift()\n\t\t}\n\t}\n\tvaleurEvaluation.missingVariables ??= {}\n\tupdateRuleMissingVariables(this, node, valeurEvaluation)\n\tconst evaluation = {\n\t\t...valeurEvaluation,\n\t\tmissingVariables: mergeMissing(\n\t\t\tvaleurEvaluation.missingVariables,\n\t\t\tparentMissingVariables,\n\t\t),\n\t\t...node,\n\t\texplanation: {\n\t\t\tparents: node.explanation.parents,\n\t\t\tvaleur: valeurEvaluation,\n\t\t\tnullableParent,\n\t\t\truleDisabledByItsParent,\n\t\t},\n\t}\n\n\treturn evaluation\n})\n\n/*\n\tWe implement the terminal case for missing variables manually here as\n\ta rule is missing if it is undefined and has no other missing dependencies\n*/\nfunction updateRuleMissingVariables(\n\tengine: Engine,\n\tnode: RuleNode,\n\tvaleurEvaluation: EvaluatedNode,\n): void {\n\tif (\n\t\tnode.private === true ||\n\t\t!isAccessible(engine.context.parsedRules, '', node.dottedName)\n\t) {\n\t\treturn\n\t}\n\n\tif (\n\t\tvaleurEvaluation.nodeValue === undefined &&\n\t\t!Object.keys(valeurEvaluation.missingVariables).length\n\t) {\n\t\tvaleurEvaluation.missingVariables[node.dottedName] = 1\n\t}\n\n\treturn\n}\n\nexport function evaluateDisablingParent(\n\tengine: Engine,\n\tnode: RuleNode,\n): {\n\truleDisabledByItsParent: boolean\n\tparentMissingVariables: MissingVariables\n\tnullableParent?: ASTNode\n} {\n\tif (node.private) {\n\t\t// We do not need to check if a private rule is disabled by its parent :\n\t\t// they are accessible only from its sibling or parent\n\t\t// (which would already be disabled)\n\t\treturn { ruleDisabledByItsParent: false, parentMissingVariables: {} }\n\t}\n\n\tconst nodesTypes = engine.context.nodesTypes\n\tconst nullableParent = node.explanation.parents.find(\n\t\t(ref) =>\n\t\t\tnodesTypes.get(ref)?.isNullable ||\n\t\t\tnodesTypes.get(ref)?.type === 'boolean',\n\t)\n\n\tif (!nullableParent) {\n\t\treturn { ruleDisabledByItsParent: false, parentMissingVariables: {} }\n\t}\n\n\tif (\n\t\t// TODO: remove this condition and the associated \"parentRuleStack\", cycles\n\t\t// should be detected and avoided at parse time.\n\t\t!engine.cache._meta.parentRuleStack.includes(node.dottedName)\n\t) {\n\t\tengine.cache._meta.parentRuleStack.unshift(node.dottedName)\n\t\tlet parentIsNotApplicable = defaultNode(false) as EvaluatedNode\n\t\tif (nodesTypes.get(nullableParent)?.isNullable) {\n\t\t\tparentIsNotApplicable = engine.evaluateNode({\n\t\t\t\tnodeKind: 'est non applicable',\n\t\t\t\texplanation: nullableParent,\n\t\t\t})\n\t\t}\n\t\tif (\n\t\t\tparentIsNotApplicable.nodeValue !== true &&\n\t\t\tnodesTypes.get(nullableParent)?.type === 'boolean'\n\t\t) {\n\t\t\tparentIsNotApplicable = engine.evaluateNode({\n\t\t\t\tnodeKind: 'operation',\n\t\t\t\toperator: '=',\n\t\t\t\toperationKind: '=',\n\t\t\t\texplanation: [nullableParent, defaultNode(false)],\n\t\t\t})\n\t\t}\n\n\t\tengine.cache._meta.parentRuleStack.shift()\n\t\tif (parentIsNotApplicable.nodeValue === true) {\n\t\t\treturn {\n\t\t\t\truleDisabledByItsParent: true,\n\t\t\t\tparentMissingVariables: parentIsNotApplicable.missingVariables ?? {},\n\t\t\t\tnullableParent,\n\t\t\t}\n\t\t}\n\t}\n\n\tlet parentMissingVariables: MissingVariables = {}\n\n\tif (nodesTypes.get(nullableParent)?.type === 'boolean') {\n\t\tconst parentEvaluation = engine.evaluateNode(nullableParent)\n\t\tparentMissingVariables = parentEvaluation.missingVariables ?? {}\n\t\treturn {\n\t\t\truleDisabledByItsParent: parentEvaluation.nodeValue === false,\n\t\t\tparentMissingVariables,\n\t\t\tnullableParent,\n\t\t}\n\t}\n\n\treturn {\n\t\truleDisabledByItsParent: false,\n\t\tparentMissingVariables,\n\t\tnullableParent,\n\t}\n}\n","import parse from '../parse'\nimport { Context } from '../parsePublicodes'\nimport { parseRules } from '../rule'\n\nexport default function parseAvec(v, context: Context) {\n\tparseRules(v.avec, context)\n\tconst valeur = parse(v.valeur, context)\n\treturn valeur\n}\n\nparseAvec.nom = 'avec' as const\n","import Engine from '..'\nimport { ASTNode, Evaluation } from '../AST/types'\nimport { PublicodesError, warning } from '../error'\nimport { mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport { convertUnit, inferUnit } from '../units'\n\ntype TrancheNode = { taux: ASTNode } | { montant: ASTNode }\nexport type TrancheNodes = Array<\n\tTrancheNode & { plafond?: ASTNode; isActive?: boolean }\n>\n\nexport const parseTranches = (tranches, context): TrancheNodes => {\n\treturn tranches.map((node, i) => {\n\t\tif (!node.plafond && i > tranches.length) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'SyntaxError',\n\t\t\t\t`La tranche n°${i} du barème n'a pas de plafond précisé. Seule la dernière tranche peut ne pas être plafonnée`,\n\t\t\t\t{ dottedName: '' },\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...node,\n\t\t\t...(node.taux !== undefined ? { taux: parse(node.taux, context) } : {}),\n\t\t\t...(node.montant !== undefined ?\n\t\t\t\t{ montant: parse(node.montant, context) }\n\t\t\t:\t{}),\n\t\t\tplafond:\n\t\t\t\t'plafond' in node ?\n\t\t\t\t\tparse(node.plafond, context)\n\t\t\t\t:\t{\n\t\t\t\t\t\tnodeValue: Infinity,\n\t\t\t\t\t\tnodeKind: 'constant',\n\t\t\t\t\t\ttype: 'number',\n\t\t\t\t\t\tisNullable: false,\n\t\t\t\t\t},\n\t\t}\n\t})\n}\n\nexport function evaluatePlafondUntilActiveTranche(\n\tthis: Engine,\n\t{ multiplicateur, assiette, parsedTranches },\n) {\n\treturn parsedTranches.reduce(\n\t\t([tranches, activeTrancheFound], parsedTranche, i: number) => {\n\t\t\tif (activeTrancheFound) {\n\t\t\t\treturn [\n\t\t\t\t\t[...tranches, { ...parsedTranche, isAfterActive: true }],\n\t\t\t\t\tactiveTrancheFound,\n\t\t\t\t]\n\t\t\t}\n\n\t\t\tconst plafond = this.evaluateNode(parsedTranche.plafond)\n\t\t\tconst plancher =\n\t\t\t\ttranches[i - 1] ? tranches[i - 1].plafond : { nodeValue: 0 }\n\n\t\t\tlet plafondValue: Evaluation =\n\t\t\t\t(\n\t\t\t\t\tplafond.nodeValue === undefined ||\n\t\t\t\t\tmultiplicateur.nodeValue === undefined\n\t\t\t\t) ?\n\t\t\t\t\tundefined\n\t\t\t\t:\tplafond.nodeValue * multiplicateur.nodeValue\n\n\t\t\ttry {\n\t\t\t\tplafondValue =\n\t\t\t\t\tplafondValue === Infinity || plafondValue === 0 ?\n\t\t\t\t\t\tplafondValue\n\t\t\t\t\t:\tconvertUnit(\n\t\t\t\t\t\t\tinferUnit('*', [plafond.unit, multiplicateur.unit]),\n\t\t\t\t\t\t\tassiette.unit,\n\t\t\t\t\t\t\tplafondValue,\n\t\t\t\t\t\t)\n\t\t\t} catch (e) {\n\t\t\t\twarning(\n\t\t\t\t\tthis.context.logger,\n\t\t\t\t\t`L'unité du plafond de la tranche n°${\n\t\t\t\t\t\ti + 1\n\t\t\t\t\t} n'est pas compatible avec celle l'assiette`,\n\t\t\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t\t\t\te,\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst plancherValue = tranches[i - 1] ? tranches[i - 1].plafondValue : 0\n\t\t\tconst isAfterActive =\n\t\t\t\tplancherValue === undefined || assiette.nodeValue === undefined ?\n\t\t\t\t\tundefined\n\t\t\t\t:\tplancherValue > assiette.nodeValue\n\n\t\t\tconst calculationValues = [plafond, assiette, multiplicateur, plancher]\n\t\t\tif (calculationValues.some((node) => node.nodeValue === undefined)) {\n\t\t\t\treturn [\n\t\t\t\t\t[\n\t\t\t\t\t\t...tranches,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...parsedTranche,\n\t\t\t\t\t\t\tplafond,\n\t\t\t\t\t\t\tplafondValue,\n\t\t\t\t\t\t\tplancherValue,\n\t\t\t\t\t\t\tnodeValue: undefined,\n\t\t\t\t\t\t\tisActive: undefined,\n\t\t\t\t\t\t\tisAfterActive,\n\t\t\t\t\t\t\tmissingVariables: mergeAllMissing(calculationValues),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tfalse,\n\t\t\t\t]\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\t!!tranches[i - 1] &&\n\t\t\t\t!!plancherValue &&\n\t\t\t\t(plafondValue as number) <= plancherValue\n\t\t\t) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'EvaluationError',\n\t\t\t\t\t`Le plafond de la tranche n°${\n\t\t\t\t\t\ti + 1\n\t\t\t\t\t} a une valeur inférieure à celui de la tranche précédente`,\n\t\t\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst tranche = {\n\t\t\t\t...parsedTranche,\n\t\t\t\tplafond,\n\t\t\t\tplancherValue,\n\t\t\t\tplafondValue,\n\t\t\t\tisAfterActive,\n\t\t\t\tisActive:\n\t\t\t\t\tassiette.nodeValue >= plancherValue &&\n\t\t\t\t\tassiette.nodeValue < (plafondValue as number),\n\t\t\t}\n\n\t\t\treturn [[...tranches, tranche], tranche.isActive]\n\t\t},\n\t\t[[], false],\n\t)[0]\n}\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode, EvaluatedNode, NodeKind } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { defaultNode, mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport { convertUnit, parseUnit } from '../units'\nimport {\n\tTrancheNodes,\n\tevaluatePlafondUntilActiveTranche,\n\tparseTranches,\n} from './trancheUtils'\n\n// Barème en taux marginaux.\nexport type BarèmeNode = {\n\texplanation: {\n\t\ttranches: TrancheNodes\n\t\tmultiplicateur: ASTNode\n\t\tassiette: ASTNode\n\t}\n\tnodeKind: 'barème'\n}\nexport default function parseBarème(v, context): BarèmeNode {\n\tconst explanation = {\n\t\tassiette: parse(v.assiette, context),\n\t\tmultiplicateur:\n\t\t\tv.multiplicateur ? parse(v.multiplicateur, context) : defaultNode(1),\n\t\ttranches: parseTranches(v.tranches, context),\n\t}\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'barème',\n\t}\n}\n\nfunction evaluateBarème(tranches, assiette, evaluate) {\n\treturn tranches.map((tranche) => {\n\t\tif (tranche.isAfterActive) {\n\t\t\treturn { ...tranche, nodeValue: 0 }\n\t\t}\n\t\tconst taux = evaluate(tranche.taux)\n\t\tconst missingVariables = mergeAllMissing([taux, tranche])\n\n\t\tif (\n\t\t\t[\n\t\t\t\tassiette.nodeValue,\n\t\t\t\ttaux.nodeValue,\n\t\t\t\ttranche.plafondValue,\n\t\t\t\ttranche.plancherValue,\n\t\t\t].some((value) => value === undefined)\n\t\t) {\n\t\t\treturn {\n\t\t\t\t...tranche,\n\t\t\t\ttaux,\n\t\t\t\tnodeValue: undefined,\n\t\t\t\tmissingVariables,\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\t...tranche,\n\t\t\ttaux,\n\t\t\t...('unit' in assiette && { unit: assiette.unit }),\n\t\t\tnodeValue:\n\t\t\t\t(Math.min(assiette.nodeValue, tranche.plafondValue) -\n\t\t\t\t\ttranche.plancherValue) *\n\t\t\t\tconvertUnit(taux.unit, parseUnit(''), taux.nodeValue as number),\n\t\t\tmissingVariables,\n\t\t}\n\t})\n}\nconst evaluate: EvaluationFunction<'barème'> = function (node) {\n\tconst evaluate = this.evaluateNode.bind(this)\n\tconst assiette = this.evaluateNode(\n\t\tnode.explanation.assiette,\n\t) as EvaluatedNode\n\tconst multiplicateur = this.evaluateNode(node.explanation.multiplicateur)\n\n\tif (multiplicateur.nodeValue === 0) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t`Le multiplicateur ne peut pas être nul`,\n\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t)\n\t}\n\n\tlet tranches: any = node.explanation.tranches\n\tlet nodeValue = assiette.nodeValue\n\n\tif (![0, undefined, null].includes(assiette.nodeValue)) {\n\t\ttranches = evaluateBarème(\n\t\t\tevaluatePlafondUntilActiveTranche.call(this, {\n\t\t\t\tparsedTranches: node.explanation.tranches,\n\t\t\t\tassiette,\n\t\t\t\tmultiplicateur,\n\t\t\t}),\n\t\t\tassiette,\n\t\t\tevaluate,\n\t\t)\n\t\tnodeValue = tranches.reduce(\n\t\t\t(value, { nodeValue }) =>\n\t\t\t\tnodeValue == undefined ? undefined : value + nodeValue,\n\t\t\t0,\n\t\t)\n\t}\n\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\tmissingVariables: mergeAllMissing([assiette, multiplicateur, ...tranches]),\n\t\texplanation: {\n\t\t\tassiette,\n\t\t\tmultiplicateur,\n\t\t\ttranches,\n\t\t},\n\t\tunit: assiette.unit,\n\t} as any\n}\n\nregisterEvaluationFunction('barème', evaluate)\n","import { EvaluationFunction } from '..'\nimport { ASTNode } from '../AST/types'\nimport { PublicodesError } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { bonus, mergeAllMissing, mergeMissing } from '../evaluationUtils'\nimport parse from '../parse'\n\nexport type ConditionNode = {\n\texplanation: {\n\t\tsi: ASTNode\n\t\talors: ASTNode\n\t\tsinon: ASTNode\n\t}\n\tnodeKind: 'condition'\n}\n\nconst evaluate: EvaluationFunction<'condition'> = function (node) {\n\tlet evaluation\n\tconst condition = this.evaluateNode(node.explanation.si)\n\tlet alors = node.explanation.alors\n\tlet sinon = node.explanation.sinon\n\tif ('unit' in condition) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t'La condition doit être de type booléen',\n\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t)\n\t}\n\tif (condition.nodeValue === true) {\n\t\talors = this.evaluateNode(node.explanation.alors)\n\t\t;(alors as any).isActive = true\n\t\tevaluation = alors\n\t} else if (condition.nodeValue === false) {\n\t\tsinon = this.evaluateNode(node.explanation.sinon)\n\t\tevaluation = sinon\n\t} else if (condition.nodeValue === null) {\n\t\tevaluation = condition\n\t} else if (condition.nodeValue === undefined) {\n\t\tsinon = this.evaluateNode(node.explanation.sinon)\n\t\talors = this.evaluateNode(node.explanation.alors)\n\t\tevaluation = {\n\t\t\t...condition,\n\t\t\tmissingVariables: mergeAllMissing([sinon, alors]),\n\t\t}\n\t} else {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t'La condition doit être de type booléen',\n\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t)\n\t}\n\tconst unit = evaluation.unit ?? (alors as any).unit\n\treturn {\n\t\tnodeValue: evaluation.nodeValue,\n\t\tmissingVariables: mergeMissing(\n\t\t\tbonus(condition.missingVariables),\n\t\t\tevaluation.missingVariables,\n\t\t),\n\t\t...(unit != undefined ? { unit } : {}),\n\t\t...node,\n\t\texplanation: { si: condition, alors, sinon },\n\t}\n}\nexport default function parseCondition(v, context) {\n\tconst explanation = {\n\t\tsi: parse(v.si, context),\n\t\talors: parse(v.alors, context),\n\t\tsinon: parse(v.sinon, context),\n\t}\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'condition',\n\t} as ConditionNode\n}\n\nparseCondition.nom = 'condition'\n\nregisterEvaluationFunction('condition', evaluate)\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { notApplicableNode } from '../evaluationUtils'\nimport parse from '../parse'\nimport { ReferenceNode } from '../reference'\nimport { serializeUnit } from '../units'\n\nexport type ContextNode = {\n\texplanation: {\n\t\tvaleur: ASTNode\n\t\tcontexte: Array<[ReferenceNode, ASTNode]>\n\t\tsubEngineId: number\n\t}\n\tnodeKind: 'contexte'\n}\n\nexport default function parseMecanismContexte(v, context) {\n\tconst contexte = Object.keys(v.contexte).map((dottedName) => [\n\t\tparse(dottedName, context),\n\t\tparse(v.contexte[dottedName], context),\n\t])\n\n\tconst node = parse(v.valeur, context)\n\n\treturn {\n\t\texplanation: {\n\t\t\tvaleur: node,\n\t\t\tcontexte,\n\t\t\tsubEngineId: context.subEngineIncrementingNumber++,\n\t\t},\n\t\tnodeKind: parseMecanismContexte.nom,\n\t} as ContextNode\n}\nparseMecanismContexte.nom = 'contexte' as const\n\nconst evaluateContexte: EvaluationFunction<'contexte'> = function (node) {\n\tconst amendedSituation = Object.fromEntries(\n\t\tnode.explanation.contexte\n\t\t\t.filter(([originRule, replacement]) => {\n\t\t\t\tconst originRuleEvaluation = this.evaluateNode(originRule)\n\t\t\t\tconst replacementEvaluation = this.evaluateNode(replacement)\n\t\t\t\treturn (\n\t\t\t\t\toriginRuleEvaluation.nodeValue !== replacementEvaluation.nodeValue ||\n\t\t\t\t\tserializeUnit(originRuleEvaluation.unit) !==\n\t\t\t\t\t\tserializeUnit(replacementEvaluation.unit)\n\t\t\t\t)\n\t\t\t})\n\t\t\t.map(\n\t\t\t\t([originRule, replacement]) =>\n\t\t\t\t\t[originRule.dottedName, replacement] as [string, ASTNode],\n\t\t\t),\n\t)\n\tif (\n\t\tthis.cache._meta.currentContexteSituation ===\n\t\tJSON.stringify(amendedSituation)\n\t) {\n\t\t// If the situation is the same as the last time we evaluated the contexte, it means that\n\t\t// there is a loop\n\t\treturn {\n\t\t\t...notApplicableNode,\n\t\t\t...node,\n\t\t}\n\t}\n\n\tconst engine = this.shallowCopy()\n\tengine.subEngineId = node.explanation.subEngineId\n\tthis.subEngines[node.explanation.subEngineId] = engine\n\tif (Object.keys(amendedSituation).length) {\n\t\tengine.setSituation(amendedSituation, {\n\t\t\tkeepPreviousSituation: true,\n\t\t})\n\n\t\t// The following code ensure that we use the **origin context** evaluation\n\t\t// for the values in the ammended situation\n\n\t\t// We do so by altering the cache so that the situation rule seems to have already\n\t\t// been evaluated\n\n\t\t// This is not an elegant way of doing so, but its temporary.\n\t\t// The correct implementation is discussed in :\n\t\t// https://github.com/publicodes/publicodes/discussions/92\n\t\tObject.entries(amendedSituation).forEach(([originDottedName, value]) => {\n\t\t\tconst evaluation = this.cache.nodes.get(value)\n\t\t\tif (!evaluation) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'InternalError',\n\t\t\t\t\t'The situation should have already been evaluated',\n\t\t\t\t\t{\n\t\t\t\t\t\tdottedName: this.context.dottedName,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst originRule =\n\t\t\t\tengine.context.parsedRules[originDottedName + ' . $SITUATION']\n\t\t\tif (!originRule?.explanation.valeur) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'InternalError',\n\t\t\t\t\t'The origin rule should be defined',\n\t\t\t\t\t{\n\t\t\t\t\t\tdottedName: this.context.dottedName,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tengine.cache.nodes.set(originRule.explanation.valeur, evaluation)\n\t\t})\n\t}\n\n\tengine.cache._meta.currentContexteSituation = JSON.stringify(amendedSituation)\n\tconst evaluatedNode = engine.evaluateNode(node.explanation.valeur)\n\n\treturn {\n\t\t...node,\n\t\tnodeValue: evaluatedNode.nodeValue,\n\t\texplanation: {\n\t\t\t...node.explanation,\n\t\t\tvaleur: evaluatedNode,\n\t\t},\n\t\tmissingVariables: evaluatedNode.missingVariables,\n\t\t...('unit' in evaluatedNode && { unit: evaluatedNode.unit }),\n\t}\n}\n\nregisterEvaluationFunction('contexte', evaluateContexte)\n","import { PublicodesError } from './error'\n\nexport function normalizeDateString(dateString: string): string {\n\tlet [day, month, year] = dateString.split('/')\n\tif (!year) {\n\t\t;[day, month, year] = ['01', day, month]\n\t}\n\treturn normalizeDate(+year, +month, +day)\n}\n\nconst pad = (n: number): string => (+n < 10 ? `0${n}` : '' + n)\nexport function normalizeDate(\n\tyear: number,\n\tmonth: number,\n\tday: number,\n): string {\n\tconst date = new Date(+year, +month - 1, +day)\n\tif (!+date || date.getDate() !== +day) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`La date ${day}/${month}/${year} n'est pas valide`,\n\t\t\t{ dottedName: '' },\n\t\t)\n\t}\n\treturn `${pad(day)}/${pad(month)}/${pad(year)}`\n}\n\nexport function convertToDate(value: string): Date {\n\tconst [day, month, year] = normalizeDateString(value).split('/')\n\tconst result = new Date(+year, +month - 1, +day)\n\t// Reset date to utc midnight for exact calculation of day difference (no\n\t// daylight saving effect)\n\tresult.setMinutes(result.getMinutes() - result.getTimezoneOffset())\n\treturn result\n}\n\nexport function convertToString(date: Date): string {\n\treturn normalizeDate(date.getFullYear(), date.getMonth() + 1, date.getDate())\n}\n\nexport function getRelativeDate(date: string, dayDifferential: number): string {\n\tconst relativeDate = new Date(convertToDate(date))\n\trelativeDate.setDate(relativeDate.getDate() + dayDifferential)\n\treturn convertToString(relativeDate)\n}\n\nexport function getYear(date: string): number {\n\treturn +date.slice(-4)\n}\n\nexport function getTrimestreCivil(date: string) {\n\tconst [, month, year] = date.split('/')\n\tconst trimester = Math.floor((Number.parseInt(month, 10) - 1) / 3)\n\tconst startingMonth = 3 * trimester + 1\n\treturn `01/${startingMonth.toString().padStart(2, '0')}/${year}`\n}\n\nexport function getDifferenceInDays(from: string, to: string): number {\n\tconst millisecondsPerDay = 1000 * 60 * 60 * 24\n\treturn (\n\t\t(convertToDate(to).getTime() - convertToDate(from).getTime()) /\n\t\tmillisecondsPerDay\n\t)\n}\n\nexport function getDifferenceInMonths(from: string, to: string): number {\n\t// We want to compute the difference in actual month between the two dates\n\t// For date that start during a month, a pro-rata will be done depending on\n\t// the duration of the month in days\n\tconst [dayFrom, monthFrom, yearFrom] = from.split('/').map((x) => +x)\n\tconst [dayTo, monthTo, yearTo] = to.split('/').map((x) => +x)\n\tconst numberOfFullMonth = monthTo - monthFrom + 12 * (yearTo - yearFrom)\n\tconst numDayMonthFrom = new Date(yearFrom, monthFrom, 0).getDate()\n\tconst numDayMonthTo = new Date(yearTo, monthTo, 0).getDate()\n\tconst prorataMonthFrom = (dayFrom - 1) / numDayMonthFrom\n\tconst prorataMonthTo = dayTo / numDayMonthTo\n\treturn numberOfFullMonth - prorataMonthFrom + prorataMonthTo\n}\n\nexport function getDifferenceInYears(from: string, to: string): number {\n\tconst differenceInDays = getDifferenceInDays(from, to)\n\n\tconst isLeapYear = (year: number) =>\n\t\t(year % 4 === 0 && year % 100 !== 0) || year % 400 === 0\n\tconst after1stMarch = (date: Date) =>\n\t\tdate >= new Date(date.getFullYear(), 2, 1)\n\n\tconst fromDate = convertToDate(from)\n\tconst toDate = convertToDate(to)\n\n\tconst fromYear = fromDate.getFullYear() + (after1stMarch(fromDate) ? 1 : 0)\n\tconst toYear = toDate.getFullYear() + (after1stMarch(fromDate) ? 0 : -1)\n\n\tconst leapYearsCount = Array.from(\n\t\t{ length: toYear - fromYear + 1 },\n\t\t(_, i) => fromYear + i,\n\t).filter(isLeapYear).length\n\n\treturn (differenceInDays - leapYearsCount) / 365\n}\n\nexport function getDifferenceInTrimestreCivils(\n\tfrom: string,\n\tto: string,\n): number {\n\treturn (\n\t\tMath.floor(\n\t\t\tgetDifferenceInMonths(getTrimestreCivil(from), getTrimestreCivil(to)) / 3,\n\t\t) + 1\n\t)\n}\n\nexport function getDifferenceInYearsCivil(from: string, to: string): number {\n\tconst fromYear = '01/' + getYear(from)\n\tconst toYear = '01/' + getYear(to)\n\treturn Math.floor(getDifferenceInYears(fromYear, toYear)) + 1\n}\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode, Evaluation, Unit } from '../AST/types'\nimport {\n\tconvertToString,\n\tgetDifferenceInDays,\n\tgetDifferenceInMonths,\n\tgetDifferenceInTrimestreCivils,\n\tgetDifferenceInYears,\n\tgetDifferenceInYearsCivil,\n} from '../date'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { defaultNode, mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport { parseUnit } from '../units'\n\nexport type DuréeNode = {\n\texplanation: {\n\t\tdepuis: ASTNode\n\t\t\"jusqu'à\": ASTNode\n\t}\n\tunit: Unit\n\tnodeKind: 'durée'\n}\nconst evaluate: EvaluationFunction<'durée'> = function (node) {\n\tconst fromNode = this.evaluateNode(node.explanation.depuis)\n\tconst toNode = this.evaluateNode(node.explanation[\"jusqu'à\"])\n\n\tconst from = fromNode.nodeValue as Evaluation\n\tconst to = toNode.nodeValue as Evaluation\n\n\tlet nodeValue: Evaluation\n\tif (from === null || to === null) {\n\t\tnodeValue = null\n\t} else if (from === undefined || to === undefined) {\n\t\tnodeValue = undefined\n\t} else {\n\t\tswitch (node.unit.numerators[0] as PossibleUnit) {\n\t\t\tcase 'jour':\n\t\t\t\tnodeValue = getDifferenceInDays(from, to)\n\t\t\t\tbreak\n\t\t\tcase 'mois':\n\t\t\t\tnodeValue = getDifferenceInMonths(from, to)\n\t\t\t\tbreak\n\t\t\tcase 'an':\n\t\t\t\tnodeValue = getDifferenceInYears(from, to)\n\t\t\t\tbreak\n\t\t\tcase 'trimestre':\n\t\t\t\tnodeValue = getDifferenceInMonths(from, to) / 3\n\t\t\t\tbreak\n\t\t\tcase 'trimestre civil':\n\t\t\t\tnodeValue = getDifferenceInTrimestreCivils(from, to)\n\t\t\t\tbreak\n\t\t\tcase 'année civile':\n\t\t\t\tnodeValue = getDifferenceInYearsCivil(from, to)\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\tif (typeof nodeValue === 'number') {\n\t\tnodeValue = Math.max(0, nodeValue)\n\t}\n\n\treturn {\n\t\t...node,\n\t\tmissingVariables: mergeAllMissing([fromNode, toNode]),\n\t\tnodeValue,\n\t\texplanation: {\n\t\t\tdepuis: fromNode,\n\t\t\t\"jusqu'à\": toNode,\n\t\t},\n\t}\n}\n\nconst today = defaultNode(convertToString(new Date()))\nexport default (v, context) => {\n\tconst explanation = {\n\t\tdepuis: parse(v.depuis ?? today, context),\n\t\t\"jusqu'à\": parse(v[\"jusqu'à\"] ?? today, context),\n\t}\n\tconst unit = v.unité ? parseUnit(v.unité) : parseUnit('jour')\n\tif (\n\t\tunit.denominators.length > 0 ||\n\t\tunit.numerators.length > 1 ||\n\t\t!possibleUnit.includes(unit.numerators[0] as PossibleUnit)\n\t) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`Seules les unités suivantes sont acceptées pour une durée : ${possibleUnit.join(\n\t\t\t\t', ',\n\t\t\t)}.\n\tL'unité fournie est: ${unit.numerators[0]}`,\n\t\t\t{\n\t\t\t\tdottedName: context.dottedName,\n\t\t\t},\n\t\t)\n\t}\n\treturn {\n\t\texplanation,\n\t\tunit,\n\t\tnodeKind: 'durée',\n\t} as DuréeNode\n}\n\nregisterEvaluationFunction('durée', evaluate)\n\ntype PossibleUnit = (typeof possibleUnit)[number]\nconst possibleUnit = [\n\t'mois',\n\t'jour',\n\t'an',\n\t'trimestre',\n\t'trimestre civil',\n\t'année civile',\n] as const\n","import { EvaluationFunction } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport parse from '../parse'\nimport { createParseInlinedMecanism } from './inlineMecanism'\n\nexport type EstNonDéfiniNode = {\n\texplanation: ASTNode\n\tnodeKind: 'est non défini'\n}\n\nexport function parseEstNonDéfini(v, context) {\n\tconst explanation = parse(v, context)\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'est non défini',\n\t} as EstNonDéfiniNode\n}\nparseEstNonDéfini.nom = 'est non défini'\n\nconst parseEstDéfini = createParseInlinedMecanism(\n\t'est défini',\n\t{\n\t\tvaleur: {},\n\t},\n\t{\n\t\t'=': [{ 'est non défini': 'valeur' }, 'non'],\n\t},\n)\n\nconst parseEstApplicable = createParseInlinedMecanism(\n\t'est applicable',\n\t{\n\t\tvaleur: {},\n\t},\n\t{\n\t\t'=': [{ 'est non applicable': 'valeur' }, 'non'],\n\t},\n)\n\nexport { parseEstDéfini, parseEstApplicable }\n\nconst evaluate: EvaluationFunction<'est non défini'> = function (node) {\n\tconst valeur = this.evaluateNode(node.explanation)\n\tlet nodeValue: boolean | undefined | null = false\n\tif (valeur.nodeValue === undefined) {\n\t\tnodeValue = true\n\t}\n\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\tmissingVariables: valeur.missingVariables,\n\t\texplanation: valeur,\n\t}\n}\nregisterEvaluationFunction('est non défini', evaluate)\n","import { EvaluationFunction } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport { evaluateDisablingParent } from '../rule'\n\nexport type EstNonApplicableNode = {\n\texplanation: ASTNode\n\tnodeKind: 'est non applicable'\n}\nexport function parseEstNonApplicable(v, context) {\n\tconst explanation = parse(v, context)\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'est non applicable' as const,\n\t} as EstNonApplicableNode\n}\nparseEstNonApplicable.nom = 'est non applicable'\n\nconst isNotApplicable = (node: ASTNode) => {\n\treturn {\n\t\tnodeKind: 'est non applicable' as const,\n\t\texplanation: node,\n\t}\n}\n\nconst evaluateIsNotApplicable: EvaluationFunction<'est non applicable'> =\n\tfunction (node) {\n\t\tconst valeur = node.explanation\n\n\t\tif (\n\t\t\tthis.context.nodesTypes.get(valeur)?.isNullable === false &&\n\t\t\tvaleur.nodeKind !== 'rule' &&\n\t\t\tvaleur.nodeKind !== 'reference'\n\t\t) {\n\t\t\treturn { ...node, nodeValue: false, missingVariables: {} }\n\t\t}\n\n\t\tif (\n\t\t\tthis.cache.nodes.has(valeur) &&\n\t\t\tthis.cache.nodes.get(valeur) !== undefined\n\t\t) {\n\t\t\treturn {\n\t\t\t\t...node,\n\t\t\t\tnodeValue: this.cache.nodes.get(valeur)?.nodeValue === null,\n\t\t\t\tmissingVariables: this.cache.nodes.get(valeur)?.missingVariables ?? {},\n\t\t\t}\n\t\t}\n\n\t\tswitch (valeur.nodeKind) {\n\t\t\tcase 'rule': {\n\t\t\t\tconst { ruleDisabledByItsParent, parentMissingVariables } =\n\t\t\t\t\tevaluateDisablingParent(this, valeur)\n\n\t\t\t\tif (ruleDisabledByItsParent) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...node,\n\t\t\t\t\t\tnodeValue: true,\n\t\t\t\t\t\tmissingVariables: parentMissingVariables,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst isNotApplicableEvaluation = this.evaluateNode(\n\t\t\t\t\tisNotApplicable(valeur.explanation.valeur),\n\t\t\t\t)\n\t\t\t\tconst missingVariables = mergeMissing(\n\t\t\t\t\tparentMissingVariables,\n\t\t\t\t\tisNotApplicableEvaluation.missingVariables,\n\t\t\t\t)\n\t\t\t\t// If the rule can be disabled thought the situation, it should be listed inside the missing variables\n\t\t\t\tif (\n\t\t\t\t\tisNotApplicableEvaluation.nodeValue === false &&\n\t\t\t\t\tthis.context.nodesTypes.get(\n\t\t\t\t\t\tthis.context.parsedRules[`${valeur.dottedName} . $SITUATION`],\n\t\t\t\t\t)?.isNullable &&\n\t\t\t\t\t!Object.keys(isNotApplicableEvaluation.missingVariables).length\n\t\t\t\t) {\n\t\t\t\t\tmissingVariables[valeur.dottedName] = 1\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\t...node,\n\t\t\t\t\tnodeValue: isNotApplicableEvaluation.nodeValue,\n\t\t\t\t\tmissingVariables,\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'reference':\n\t\t\t\treturn {\n\t\t\t\t\t...this.evaluateNode(\n\t\t\t\t\t\tisNotApplicable(this.context.parsedRules[valeur.dottedName!]),\n\t\t\t\t\t),\n\t\t\t\t\t...node,\n\t\t\t\t}\n\n\t\t\tcase 'condition':\n\t\t\t\treturn {\n\t\t\t\t\t...this.evaluateNode({\n\t\t\t\t\t\t...valeur,\n\t\t\t\t\t\texplanation: {\n\t\t\t\t\t\t\tsi: valeur.explanation.si,\n\t\t\t\t\t\t\talors: isNotApplicable(valeur.explanation.alors),\n\t\t\t\t\t\t\tsinon: isNotApplicable(valeur.explanation.sinon),\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t\t...node,\n\t\t\t\t}\n\t\t}\n\t\tconst evaluatedValeur = this.evaluateNode(valeur)\n\n\t\treturn {\n\t\t\t...node,\n\t\t\tnodeValue:\n\t\t\t\tevaluatedValeur.nodeValue === undefined ?\n\t\t\t\t\tundefined\n\t\t\t\t:\tevaluatedValeur.nodeValue === null,\n\t\t\tmissingVariables: evaluatedValeur.missingVariables,\n\t\t}\n\t}\n\nregisterEvaluationFunction('est non applicable', evaluateIsNotApplicable)\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { defaultNode, mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport {\n\tevaluatePlafondUntilActiveTranche,\n\tparseTranches,\n\tTrancheNodes,\n} from './trancheUtils'\n\nexport type GrilleNode = {\n\texplanation: {\n\t\tassiette: ASTNode\n\t\tmultiplicateur: ASTNode\n\t\ttranches: TrancheNodes\n\t}\n\tnodeKind: 'grille'\n}\n\nexport default function parseGrille(v, context): GrilleNode {\n\tconst explanation = {\n\t\tassiette: parse(v.assiette, context),\n\t\tmultiplicateur:\n\t\t\tv.multiplicateur ? parse(v.multiplicateur, context) : defaultNode(1),\n\t\ttranches: parseTranches(v.tranches, context),\n\t}\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'grille',\n\t}\n}\n\nconst evaluate: EvaluationFunction<'grille'> = function (node) {\n\tconst evaluate = this.evaluateNode.bind(this)\n\tconst assiette = this.evaluateNode(node.explanation.assiette)\n\tconst multiplicateur = this.evaluateNode(node.explanation.multiplicateur)\n\n\tif (multiplicateur.nodeValue === 0) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t`Le multiplicateur ne peut pas être nul`,\n\t\t\t{\n\t\t\t\tdottedName: this.cache._meta.evaluationRuleStack[0],\n\t\t\t},\n\t\t)\n\t}\n\n\tconst tranches = evaluatePlafondUntilActiveTranche\n\t\t.call(this, {\n\t\t\tparsedTranches: node.explanation.tranches,\n\t\t\tassiette,\n\t\t\tmultiplicateur,\n\t\t})\n\t\t.map((tranche) => {\n\t\t\tif (tranche.isActive === false) {\n\t\t\t\treturn tranche\n\t\t\t}\n\t\t\tconst montant = evaluate(tranche.montant)\n\t\t\treturn {\n\t\t\t\t...tranche,\n\t\t\t\tmontant,\n\t\t\t\tnodeValue: montant.nodeValue,\n\t\t\t\tunit: montant.unit,\n\t\t\t\tmissingVariables: mergeAllMissing([montant, tranche]),\n\t\t\t}\n\t\t})\n\n\tlet activeTranches\n\tconst activeTranche = tranches.find((tranche) => tranche.isActive)\n\tif (activeTranche) {\n\t\tactiveTranches = [activeTranche]\n\t} else if (tranches[tranches.length - 1].isAfterActive === false) {\n\t\tactiveTranches = [{ nodeValue: false }]\n\t} else {\n\t\tactiveTranches = tranches.filter(\n\t\t\t(tranche) => tranche.isActive === undefined,\n\t\t)\n\t}\n\n\tconst nodeValue =\n\t\t!activeTranches[0] ? false\n\t\t: activeTranches[0].isActive === undefined ? undefined\n\t\t: activeTranches[0].nodeValue\n\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\tmissingVariables: mergeAllMissing([\n\t\t\tassiette,\n\t\t\tmultiplicateur,\n\t\t\t...activeTranches,\n\t\t]),\n\t\texplanation: {\n\t\t\t...node.explanation,\n\t\t\tassiette,\n\t\t\tmultiplicateur,\n\t\t\ttranches,\n\t\t},\n\t\tunit: activeTranches[0]?.unit ?? undefined,\n\t} as any\n}\n\nregisterEvaluationFunction('grille', evaluate)\n","// We use a JavaScript implementation of the Brent method to find the root (the\n// \"zero\") of a monotone function. There are other methods like the\n// Newton-Raphson method, but they take the derivative of the function as an\n// input, wich in our case is costly to calculate. The Brent method doesn't\n// need to calculate the derivative.\n// An interesting description of the algorithm can be found here:\n// https://blogs.mathworks.com/cleve/2015/10/26/zeroin-part-2-brents-version/\n\n/**\n * Copied from https://gist.github.com/borgar/3317728\n *\n * Searches the interval from lowerLimit to upperLimit\n * for a root (i.e., zero) of the function func with respect to\n * its first argument using Brent's method root-finding algorithm.\n *\n * Translated from zeroin.c in http://www.netlib.org/c/brent.shar.\n *\n * Copyright (c) 2012 Borgar Thorsteinsson \n * MIT License, http://www.opensource.org/licenses/mit-license.php\n *\n * @param func function for which the root is sought.\n * @param lowerLimit the lower point of the interval to be searched.\n * @param upperLimit the upper point of the interval to be searched.\n * @param errorTol the desired accuracy (convergence tolerance).\n * @param maxIter the maximum number of iterations.\n * @param acceptableErrorTol return a result even if errorTol isn't reached after maxIter.\n * @returns an estimate for the root within accuracy.\n *\n */\nexport default function uniroot(\n\tfunc: (x: number) => number,\n\tlowerLimit: number,\n\tupperLimit: number,\n\terrorTol = 0,\n\tmaxIter = 100,\n\tacceptableErrorTol = 0,\n) {\n\tlet a = lowerLimit,\n\t\tb = upperLimit,\n\t\tc = a,\n\t\tfa = func(a),\n\t\tfb = func(b),\n\t\tfc = fa,\n\t\tactualTolerance: number,\n\t\tnewStep: number, // Step at this iteration\n\t\tprevStep: number, // Distance from the last but one to the last approximation\n\t\tp: number, // Interpolation step is calculated in the form p/q; division is delayed until the last moment\n\t\tq: number,\n\t\tfallback: number | undefined = undefined\n\n\twhile (maxIter-- > 0) {\n\t\tprevStep = b - a\n\n\t\tif (Math.abs(fc) < Math.abs(fb)) {\n\t\t\t// Swap data for b to be the best approximation\n\t\t\t;(a = b), (b = c), (c = a)\n\t\t\t;(fa = fb), (fb = fc), (fc = fa)\n\t\t}\n\n\t\tactualTolerance = 1e-15 * Math.abs(b) + errorTol / 2\n\t\tnewStep = (c - b) / 2\n\n\t\tif (Math.abs(newStep) <= actualTolerance || fb === 0) {\n\t\t\treturn b // Acceptable approx. is found\n\t\t}\n\n\t\t// Decide if the interpolation can be tried\n\t\tif (Math.abs(prevStep) >= actualTolerance && Math.abs(fa) > Math.abs(fb)) {\n\t\t\t// If prevStep was large enough and was in true direction, Interpolatiom may be tried\n\t\t\tlet t1: number, t2: number\n\t\t\tconst cb = c - b\n\t\t\tif (a === c) {\n\t\t\t\t// If we have only two distinct points linear interpolation can only be applied\n\t\t\t\tt1 = fb / fa\n\t\t\t\tp = cb * t1\n\t\t\t\tq = 1.0 - t1\n\t\t\t} else {\n\t\t\t\t// Quadric inverse interpolation\n\t\t\t\t;(q = fa / fc), (t1 = fb / fc), (t2 = fb / fa)\n\t\t\t\tp = t2 * (cb * q * (q - t1) - (b - a) * (t1 - 1))\n\t\t\t\tq = (q - 1) * (t1 - 1) * (t2 - 1)\n\t\t\t}\n\n\t\t\tif (p > 0) {\n\t\t\t\tq = -q // p was calculated with the opposite sign; make p positive\n\t\t\t} else {\n\t\t\t\tp = -p // and assign possible minus to q\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tp < 0.75 * cb * q - Math.abs(actualTolerance * q) / 2 &&\n\t\t\t\tp < Math.abs((prevStep * q) / 2)\n\t\t\t) {\n\t\t\t\t// If (b + p / q) falls in [b,c] and isn't too large it is accepted\n\t\t\t\tnewStep = p / q\n\t\t\t}\n\n\t\t\t// If p/q is too large then the bissection procedure can reduce [b,c] range to more extent\n\t\t}\n\n\t\tif (Math.abs(newStep) < actualTolerance) {\n\t\t\t// Adjust the step to be not less than tolerance\n\t\t\tnewStep = newStep > 0 ? actualTolerance : -actualTolerance\n\t\t}\n\n\t\t;(a = b), (fa = fb) // Save the previous approx.\n\t\t;(b += newStep), (fb = func(b)) // Do step to a new approxim.\n\n\t\tif ((fb > 0 && fc > 0) || (fb < 0 && fc < 0)) {\n\t\t\t;(c = a), (fc = fa) // Adjust c for it to have a sign opposite to that of b\n\t\t}\n\t\tif (Math.abs(fb) < errorTol) {\n\t\t\treturn b\n\t\t}\n\t\tif (Math.abs(fb) < acceptableErrorTol) {\n\t\t\tfallback = b\n\t\t}\n\t}\n\treturn fallback\n}\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode, EvaluatedNode, Unit } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { undefinedNumberNode } from '../evaluationUtils'\nimport parse from '../parse'\nimport { Context } from '../parsePublicodes'\nimport { ReferenceNode } from '../reference'\nimport uniroot from '../uniroot'\n\nexport type InversionNode = {\n\texplanation: {\n\t\truleToInverse: string\n\t\tinversionCandidates: Array\n\t\tunit?: Unit\n\n\t\t// Explanation computed during evaluation\n\t\tinversionGoal?: ASTNode\n\t\tnumberOfIteration?: number\n\t\tinversionFail?: boolean\n\t}\n\tnodeKind: 'inversion'\n}\n\n// The user of the inversion mechanism has to define a list of \"inversion\n// candidates\". At runtime, the evaluation function of the mechanism will look\n// at the situation value of these candidates, and use the first one that is\n// defined as its \"goal\" for the inversion\n//\n// The game is then to find an input such as the computed value of the \"goal\" is\n// equal to its situation value, mathematically we search for the zero of the\n// function x → f(x) - goal. The iteration logic between each test is\n// implemented in the `uniroot` file.\nexport const evaluateInversion: EvaluationFunction<'inversion'> = function (\n\tnode,\n) {\n\tconst inversionEngine = this.shallowCopy()\n\tif (\n\t\tthis.cache._meta.evaluationRuleStack\n\t\t\t.slice(1)\n\t\t\t.includes(node.explanation.ruleToInverse)\n\t) {\n\t\treturn {\n\t\t\t...undefinedNumberNode,\n\t\t\t...node,\n\t\t}\n\t}\n\tinversionEngine.cache._meta.parentRuleStack = [\n\t\t...this.cache._meta.parentRuleStack,\n\t]\n\tinversionEngine.cache._meta.evaluationRuleStack = [\n\t\t...this.cache._meta.evaluationRuleStack,\n\t]\n\tconst inversionGoal = node.explanation.inversionCandidates.find(\n\t\t(candidate) => {\n\t\t\tif (\n\t\t\t\tthis.cache._meta.evaluationRuleStack.includes(candidate.dottedName!)\n\t\t\t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tconst evaluation = inversionEngine.evaluateNode(\n\t\t\t\tinversionEngine.context.parsedRules[\n\t\t\t\t\t`${candidate.dottedName} . $SITUATION`\n\t\t\t\t],\n\t\t\t)\n\t\t\treturn (\n\t\t\t\ttypeof evaluation.nodeValue === 'number' &&\n\t\t\t\t!(candidate.dottedName! in evaluation.missingVariables)\n\t\t\t)\n\t\t},\n\t)\n\n\tif (inversionGoal === undefined) {\n\t\treturn {\n\t\t\t...node,\n\t\t\tnodeValue: undefined,\n\t\t\tmissingVariables: {\n\t\t\t\t...Object.fromEntries(\n\t\t\t\t\tnode.explanation.inversionCandidates.map((candidate) => [\n\t\t\t\t\t\tcandidate.dottedName,\n\t\t\t\t\t\t1,\n\t\t\t\t\t]),\n\t\t\t\t),\n\t\t\t\t[node.explanation.ruleToInverse]: 1,\n\t\t\t},\n\t\t}\n\t}\n\tconst evaluatedInversionGoal = inversionEngine.evaluateNode(inversionGoal)\n\tlet numberOfIteration = 0\n\n\tinversionEngine.setSituation(\n\t\t{\n\t\t\t[inversionGoal.dottedName!]: undefinedNumberNode,\n\t\t},\n\t\t{ keepPreviousSituation: true },\n\t)\n\tinversionEngine.cache.traversedVariablesStack =\n\t\tthis.cache.traversedVariablesStack ? [] : undefined\n\n\tlet lastEvaluation: EvaluatedNode\n\tconst evaluateWithValue = (n: number) => {\n\t\tnumberOfIteration++\n\t\tinversionEngine.setSituation(\n\t\t\t{\n\t\t\t\t[node.explanation.ruleToInverse]: {\n\t\t\t\t\tnodeValue: n,\n\t\t\t\t\tnodeKind: 'constant',\n\t\t\t\t\ttype: 'number',\n\t\t\t\t\tunit: evaluatedInversionGoal.unit,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{ keepPreviousSituation: true },\n\t\t)\n\t\tinversionEngine.cache.traversedVariablesStack =\n\t\t\tthis.cache.traversedVariablesStack ? [] : undefined\n\n\t\tlastEvaluation = inversionEngine.evaluateNode(inversionGoal)\n\t\treturn lastEvaluation\n\t}\n\n\tconst goal = evaluatedInversionGoal.nodeValue as number\n\tlet nodeValue: number | undefined | undefined = undefined\n\n\t// We do some blind attempts here to avoid using the default minimum and\n\t// maximum of +/- 10^8 that are required by the `uniroot` function. For the\n\t// first attempt we use the goal value as a very rough first approximation.\n\t// For the second attempt we do a proportionality coefficient with the result\n\t// from the first try and the goal value. The two attempts are then used in\n\t// the following way:\n\t// - if both results are `undefined` we assume that the inversion is impossible\n\t// because of missing variables\n\t// - otherwise, we calculate the missing variables of the node as the union of\n\t// the missings variables of our two attempts\n\t// - we cache the result of our two attempts so that `uniroot` doesn't\n\t// recompute them\n\tconst x1 = goal\n\tconst y1Node = evaluateWithValue(x1)\n\tconst y1 = y1Node.nodeValue as number\n\tconst coeff = y1 > goal ? 0.9 : 1.2\n\tconst x2 = y1 !== undefined ? (x1 * goal * coeff) / y1 : 2000\n\tconst y2Node = evaluateWithValue(x2)\n\tconst y2 = y2Node.nodeValue as number\n\n\tconst maxIterations = this.context.inversionMaxIterations ?? 10\n\n\tif (y1 !== undefined || y2 !== undefined) {\n\t\t// The `uniroot` function parameter. It will be called with its `min` and\n\t\t// `max` arguments, so we can use our cached nodes if the function is called\n\t\t// with the already computed x1 or x2.\n\t\tconst test = (x: number): number => {\n\t\t\tconst y =\n\t\t\t\tx === x1 ? y1\n\t\t\t\t: x === x2 ? y2\n\t\t\t\t: evaluateWithValue(x).nodeValue\n\t\t\treturn (y as number) - goal\n\t\t}\n\n\t\tconst defaultMin = -1000000\n\t\tconst defaultMax = 100000000\n\t\tconst nearestBelowGoal =\n\t\t\ty2 !== undefined && y2 < goal && (y2 > y1 || y1 > goal) ? x2\n\t\t\t: y1 !== undefined && y1 < goal && (y1 > y2 || y2 > goal) ? x1\n\t\t\t: defaultMin\n\t\tconst nearestAboveGoal =\n\t\t\ty2 !== undefined && y2 > goal && (y2 < y1 || y1 < goal) ? x2\n\t\t\t: y1 !== undefined && y1 > goal && (y1 < y2 || y2 < goal) ? x1\n\t\t\t: defaultMax\n\n\t\tnodeValue = uniroot(\n\t\t\ttest,\n\t\t\tnearestBelowGoal,\n\t\t\tnearestAboveGoal,\n\t\t\t0.1,\n\t\t\tmaxIterations,\n\t\t\t1,\n\t\t)\n\t}\n\n\tif (nodeValue == undefined) {\n\t\tthis.cache.inversionFail = true\n\t}\n\n\t// Uncomment to display the two attempts and their result\n\t// console.table([\n\t// \t{ x: x1, y: y1 },\n\t// \t{ x: x2, y: y2 },\n\t// ])\n\t// console.log('iteration inversion:', numberOfIteration)\n\tif (this.cache.traversedVariablesStack) {\n\t\tconst traversedVariablesStack = this.cache.traversedVariablesStack[0]\n\t\tif (traversedVariablesStack) {\n\t\t\t;(lastEvaluation!.traversedVariables ?? []).forEach((v) =>\n\t\t\t\ttraversedVariablesStack.add(v),\n\t\t\t)\n\t\t}\n\t}\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\tunit: evaluatedInversionGoal.unit,\n\t\texplanation: {\n\t\t\t...node.explanation,\n\t\t\tinversionGoal,\n\t\t\tnumberOfIteration,\n\t\t\tinversionFail: this.cache.inversionFail,\n\t\t},\n\t\tmissingVariables: lastEvaluation!.missingVariables,\n\t}\n}\n\nexport const mecanismInversion = (v, context: Context) => {\n\tlet avec = typeof v === 'object' && 'avec' in v ? v.avec : v\n\tif (v === null) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t\"Il manque les règles avec laquelle effectuer le calcul d'inversion dans le mécanisme `inversion numérique`\",\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\tif (!Array.isArray(avec)) {\n\t\tavec = [avec]\n\t}\n\treturn {\n\t\texplanation: {\n\t\t\truleToInverse: context.dottedName,\n\t\t\tinversionCandidates: avec.map((node) => ({\n\t\t\t\t...parse(node, context),\n\t\t\t})),\n\t\t},\n\t\tnodeKind: 'inversion',\n\t} as InversionNode\n}\n\nregisterEvaluationFunction('inversion', evaluateInversion)\n","import { PublicodesExpression } from '..'\nimport { notApplicableNode } from '../evaluationUtils'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\n\nexport const parseMaximumDe = createParseInlinedMecanismWithArray(\n\t'le maximum de',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) =>\n\t\t(valeur as Array).reduce(\n\t\t\t(acc, value) => ({\n\t\t\t\tcondition: {\n\t\t\t\t\tsi: {\n\t\t\t\t\t\t'est non applicable': '$INTERNAL valeur',\n\t\t\t\t\t},\n\t\t\t\t\talors: '$INTERNAL acc',\n\t\t\t\t\tsinon: {\n\t\t\t\t\t\tcondition: {\n\t\t\t\t\t\t\tsi: {\n\t\t\t\t\t\t\t\tou: [\n\t\t\t\t\t\t\t\t\t{ 'est non applicable': '$INTERNAL acc' },\n\t\t\t\t\t\t\t\t\t{ '>': ['$INTERNAL valeur', '$INTERNAL acc'] },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\talors: '$INTERNAL valeur',\n\t\t\t\t\t\t\tsinon: '$INTERNAL acc',\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tavec: {\n\t\t\t\t\t'[privé] $INTERNAL valeur': { valeur: value },\n\t\t\t\t\t'[privé] $INTERNAL acc': { valeur: acc },\n\t\t\t\t},\n\t\t\t}),\n\t\t\tnotApplicableNode,\n\t\t),\n)\n\nexport const parseMinimumDe = createParseInlinedMecanismWithArray(\n\t'le minimum de',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) =>\n\t\t(valeur as Array).reduce(\n\t\t\t(acc, value) => ({\n\t\t\t\tcondition: {\n\t\t\t\t\tsi: {\n\t\t\t\t\t\t'est non applicable': '$INTERNAL valeur',\n\t\t\t\t\t},\n\t\t\t\t\talors: '$INTERNAL acc',\n\t\t\t\t\tsinon: {\n\t\t\t\t\t\tcondition: {\n\t\t\t\t\t\t\tsi: {\n\t\t\t\t\t\t\t\tou: [\n\t\t\t\t\t\t\t\t\t{ 'est non applicable': '$INTERNAL acc' },\n\t\t\t\t\t\t\t\t\t{ '<': ['$INTERNAL valeur', '$INTERNAL acc'] },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\talors: '$INTERNAL valeur',\n\t\t\t\t\t\t\tsinon: '$INTERNAL acc',\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tavec: {\n\t\t\t\t\t'[privé] $INTERNAL valeur': { valeur: value },\n\t\t\t\t\t'[privé] $INTERNAL acc': { valeur: acc },\n\t\t\t\t},\n\t\t\t}),\n\t\t\tnotApplicableNode,\n\t\t),\n)\n","import { PublicodesExpression } from '..'\nimport { notApplicableNode } from '../evaluationUtils'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\n\nexport function reduceToSumNodes(\n\tvaleurs: Array,\n): PublicodesExpression {\n\treturn valeurs\n\t\t.reverse()\n\t\t.reduce((acc, value) => ({ '+': [value, acc] }), notApplicableNode)\n}\n\nexport default createParseInlinedMecanismWithArray(\n\t'somme',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) =>\n\t\treduceToSumNodes([...(valeur as Array)]),\n)\n","import { PublicodesExpression } from '..'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\nimport { reduceToSumNodes } from './somme'\n\nexport default createParseInlinedMecanismWithArray(\n\t'moyenne',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) => {\n\t\tconst valeurs = [...(valeur as Array)]\n\n\t\treturn {\n\t\t\t'/': [\n\t\t\t\treduceToSumNodes(valeurs),\n\t\t\t\treduceToSumNodes(valeurs.map(oneIfApplicable)),\n\t\t\t],\n\t\t}\n\t},\n)\n\nfunction oneIfApplicable(exp: PublicodesExpression): PublicodesExpression {\n\treturn {\n\t\t'applicable si': { 'est applicable': exp },\n\t\tvaleur: 1,\n\t}\n}\n","import { notApplicableNode } from '../evaluationUtils'\nimport { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'non applicable si',\n\t{\n\t\t'non applicable si': {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: 'non applicable si = non',\n\t\t\talors: 'valeur',\n\t\t\tsinon: notApplicableNode,\n\t\t},\n\t},\n)\n","import { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport parse from '../parse'\nimport { Context } from '../parsePublicodes'\n\nexport type PossibilityNode = {\n\texplanation: Array\n\t'choix obligatoire'?: 'oui' | 'non'\n\tcontext: string\n\tnodeKind: 'une possibilité'\n}\n// TODO : This isn't a real mecanism, cf. #963\nexport const mecanismOnePossibility = (v, context: Context) => {\n\tif (Array.isArray(v)) {\n\t\tv = {\n\t\t\tpossibilités: v,\n\t\t}\n\t}\n\treturn {\n\t\t...v,\n\t\texplanation: v.possibilités.map((p) => parse(p, context)),\n\t\tcontext: context.dottedName,\n\t\tnodeKind: 'une possibilité',\n\t} as PossibilityNode\n}\nregisterEvaluationFunction<'une possibilité'>('une possibilité', (node) => ({\n\t...node,\n\tmissingVariables: { [node.context]: 1 },\n\tnodeValue: undefined,\n}))\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode, EvaluatedNode } from '../AST/types'\nimport { convertToDate } from '../date'\nimport { warning } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeAllMissing } from '../evaluationUtils'\nimport { convertNodeToUnit } from '../nodeUnits'\nimport parse from '../parse'\nimport { inferUnit, serializeUnit } from '../units'\n\nconst knownOperations = {\n\t'*': [(a, b) => a * b, '×'],\n\t'/': [(a, b) => a / b, '∕'],\n\t'+': [(a, b) => a + b],\n\t'-': [(a, b) => a - b, '−'],\n\t'<': [(a, b) => a < b],\n\t'<=': [(a, b) => a <= b, '≤'],\n\t'>': [(a, b) => a > b],\n\t'>=': [(a, b) => a >= b, '≥'],\n\t'=': [(a, b) => (a ?? false) === (b ?? false)],\n\t'!=': [(a, b) => (a ?? false) !== (b ?? false), '≠'],\n\tet: [(a, b) => (a ?? false) && (b ?? false)],\n\tou: [(a, b) => (a ?? false) || (b ?? false)],\n} as const\n\nexport type OperationNode = {\n\tnodeKind: 'operation'\n\texplanation: [ASTNode, ASTNode]\n\toperationKind: keyof typeof knownOperations\n\toperator: string\n}\n\nconst parseOperation = (k, symbol) => (v, context) => {\n\tconst explanation = v.map((node) => parse(node, context))\n\n\treturn {\n\t\t...v,\n\t\tnodeKind: 'operation',\n\t\toperationKind: k,\n\t\toperator: symbol || k,\n\t\texplanation,\n\t} as OperationNode\n}\n\nconst evaluate: EvaluationFunction<'operation'> = function (node) {\n\tlet node1 = this.evaluateNode(node.explanation[0])\n\n\tlet evaluatedNode: EvaluatedNode & OperationNode = {\n\t\t...node,\n\t\tmissingVariables: {},\n\t} as EvaluatedNode & OperationNode\n\n\t// LAZY EVALUATION\n\tif (\n\t\t(node1.nodeValue === null &&\n\t\t\t['<', '>', '<=', '>=', '/', '*', '-', 'et'].includes(\n\t\t\t\tnode.operationKind,\n\t\t\t)) ||\n\t\t(node1.nodeValue === 0 && ['/', '*'].includes(node.operationKind)) ||\n\t\t(node1.nodeValue === false && node.operationKind === 'et') ||\n\t\t(node1.nodeValue === true && node.operationKind === 'ou')\n\t) {\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: node.operationKind === 'et' ? false : node1.nodeValue,\n\t\t\tmissingVariables: node1.missingVariables,\n\t\t}\n\t}\n\n\tlet node2 = this.evaluateNode(node.explanation[1])\n\tevaluatedNode.explanation = [node1, node2]\n\n\tif (node.operationKind === '/' && node2.nodeValue === 0) {\n\t\tthrow new PublicodesError('EvaluationError', `Division by zero`, {\n\t\t\tdottedName: this.cache._meta.evaluationRuleStack[0],\n\t\t})\n\t}\n\n\t// LAZY EVALUATION 2\n\tif (\n\t\t(node2.nodeValue === null &&\n\t\t\t['<', '>', '<=', '>=', '/', '*', 'et'].includes(node.operationKind)) ||\n\t\t(node2.nodeValue === 0 && ['*'].includes(node.operationKind)) ||\n\t\t(node2.nodeValue === false && node.operationKind === 'et') ||\n\t\t(node2.nodeValue === true && node.operationKind === 'ou')\n\t) {\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: node.operationKind === 'et' ? false : node2.nodeValue,\n\t\t\tmissingVariables: node2.missingVariables,\n\t\t}\n\t}\n\n\tevaluatedNode.missingVariables = mergeAllMissing([node1, node2])\n\n\tif (node1.nodeValue === undefined || node2.nodeValue === undefined) {\n\t\tevaluatedNode = {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: undefined,\n\t\t}\n\t}\n\n\tconst isAdditionOrSubstractionWithPercentage =\n\t\t['+', '-'].includes(node.operationKind) &&\n\t\tserializeUnit(node2.unit) === '%' &&\n\t\tserializeUnit(node1.unit) !== '%'\n\n\tif (\n\t\t!('nodeValue' in evaluatedNode) &&\n\t\t!['/', '*'].includes(node.operationKind) &&\n\t\t!isAdditionOrSubstractionWithPercentage\n\t) {\n\t\ttry {\n\t\t\tif (node1.unit && 'unit' in node2) {\n\t\t\t\tnode2 = convertNodeToUnit(node1.unit, node2)\n\t\t\t} else if (node2.unit) {\n\t\t\t\tnode1 = convertNodeToUnit(node2.unit, node1)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\twarning(\n\t\t\t\tthis.context.logger,\n\t\t\t\t`Dans l'expression '${\n\t\t\t\t\tnode.operationKind\n\t\t\t\t}', la partie gauche (unité: ${serializeUnit(\n\t\t\t\t\tnode1.unit,\n\t\t\t\t)}) n'est pas compatible avec la partie droite (unité: ${serializeUnit(\n\t\t\t\t\tnode2.unit,\n\t\t\t\t)})`,\n\t\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t\t\te,\n\t\t\t)\n\t\t}\n\t}\n\n\tconst operatorFunction = knownOperations[node.operationKind][0]\n\n\tconst a = node1.nodeValue as string | boolean | null\n\tconst b = node2.nodeValue as string | boolean | null\n\n\tevaluatedNode.nodeValue =\n\t\t'nodeValue' in evaluatedNode ? evaluatedNode.nodeValue\n\t\t: (\n\t\t\t['<', '>', '<=', '>=', '*', '/'].includes(node.operationKind) &&\n\t\t\tnode2.nodeValue === null\n\t\t) ?\n\t\t\tnull\n\t\t: (\n\t\t\t[a, b].every(\n\t\t\t\t(value) =>\n\t\t\t\t\ttypeof value === 'string' &&\n\t\t\t\t\tvalue.match?.(/^[\\d]{2}\\/[\\d]{2}\\/[\\d]{4}$/),\n\t\t\t)\n\t\t) ?\n\t\t\t// We convert the date objects to timestamps to support comparison with the \"===\" operator:\n\t\t\t// new Date('2020-01-01') !== new Date('2020-01-01')\n\t\t\toperatorFunction(\n\t\t\t\tconvertToDate(a as string).getTime(),\n\t\t\t\tconvertToDate(b as string).getTime(),\n\t\t\t)\n\t\t:\toperatorFunction(a, b)\n\n\tif (\n\t\tnode.operationKind === '*' &&\n\t\tinferUnit('*', [node1.unit, node2.unit])?.numerators.includes('%')\n\t) {\n\t\tconst unit = inferUnit('*', [node1.unit, node2.unit])\n\t\tconst nodeValue = evaluatedNode.nodeValue\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: typeof nodeValue === 'number' ? nodeValue / 100 : nodeValue,\n\t\t\tunit: inferUnit('*', [unit, { numerators: [], denominators: ['%'] }]),\n\t\t}\n\t}\n\n\t// Addition or substraction of scalar with a percentage is a multiplication\n\t// TODO : this logic should be handle statically by changing sum with percentage into product.\n\t// It can be done when we'll have a sound type/unit inference\n\tif (isAdditionOrSubstractionWithPercentage) {\n\t\tconst unit = inferUnit('*', [node1.unit, node2.unit])\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue:\n\t\t\t\t(\n\t\t\t\t\ttypeof node1.nodeValue === 'number' &&\n\t\t\t\t\ttypeof node2.nodeValue === 'number'\n\t\t\t\t) ?\n\t\t\t\t\tnode1.nodeValue *\n\t\t\t\t\t(1 + (node2.nodeValue / 100) * (node.operationKind === '-' ? -1 : 1))\n\t\t\t\t:\tevaluatedNode.nodeValue,\n\t\t\tunit: inferUnit('*', [unit, { numerators: [], denominators: ['%'] }]),\n\t\t}\n\t}\n\n\tif (\n\t\tnode.operationKind === '*' ||\n\t\tnode.operationKind === '/' ||\n\t\tnode.operationKind === '-' ||\n\t\tnode.operationKind === '+'\n\t) {\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tunit: inferUnit(node.operationKind, [node1.unit, node2.unit]),\n\t\t}\n\t}\n\n\treturn evaluatedNode\n}\n\nregisterEvaluationFunction('operation', evaluate)\n\nconst operationDispatch = Object.fromEntries(\n\tObject.entries(knownOperations).map(([k, [, symbol]]) => [\n\t\tk,\n\t\tparseOperation(k, symbol),\n\t]),\n)\n\nexport default operationDispatch\n","import { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'par défaut',\n\t{\n\t\t'par défaut': {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: { 'est non défini': 'valeur' },\n\t\t\talors: 'par défaut',\n\t\t\tsinon: 'valeur',\n\t\t},\n\t},\n)\n","import { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'plafond',\n\t{\n\t\tplafond: {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: { et: ['plafond != non', 'valeur > plafond'] },\n\t\t\talors: 'plafond',\n\t\t\tsinon: 'valeur',\n\t\t},\n\t},\n)\n","import { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'plancher',\n\t{\n\t\tplancher: {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: { et: ['plancher != non', 'valeur < plancher'] },\n\t\t\talors: 'plancher',\n\t\t\tsinon: 'valeur',\n\t\t},\n\t},\n)\n","import { PublicodesExpression } from '..'\nimport { defaultNode } from '../evaluationUtils'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\n\nexport function reduceToProduitNodes(\n\tvaleurs: Array,\n): PublicodesExpression {\n\treturn valeurs.reduce((acc, value) => ({ '*': [value, acc] }), defaultNode(1))\n}\n\nexport default createParseInlinedMecanismWithArray(\n\t'produit',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) => ({\n\t\tvaleur: reduceToProduitNodes([...(valeur as Array)]),\n\t\t\"simplifier l'unité\": 'oui',\n\t}),\n)\n","import { EvaluationFunction } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { undefinedNumberNode } from '../evaluationUtils'\nimport parse from '../parse'\nimport { Context } from '../parsePublicodes'\nimport uniroot from '../uniroot'\n\nexport type RésoudreRéférenceCirculaireNode = {\n\texplanation: {\n\t\truleToSolve: string\n\t\tvaleur: ASTNode\n\t}\n\tnodeKind: 'résoudre référence circulaire'\n}\n\nexport const evaluateRésoudreRéférenceCirculaire: EvaluationFunction<'résoudre référence circulaire'> =\n\tfunction (node) {\n\t\tif (\n\t\t\tthis.cache._meta.evaluationRuleStack\n\t\t\t\t.slice(1)\n\t\t\t\t.includes(node.explanation.ruleToSolve)\n\t\t) {\n\t\t\treturn {\n\t\t\t\t...undefinedNumberNode,\n\t\t\t\t...node,\n\t\t\t}\n\t\t}\n\n\t\tlet numberOfIterations = 0\n\t\tconst calculationEngine = this.shallowCopy()\n\t\tcalculationEngine.cache._meta.parentRuleStack = [\n\t\t\t...this.cache._meta.parentRuleStack,\n\t\t]\n\t\tcalculationEngine.cache._meta.evaluationRuleStack = [\n\t\t\t...this.cache._meta.evaluationRuleStack,\n\t\t]\n\t\tconst maxIterations = this.context.inversionMaxIterations ?? 25\n\n\t\tconst evaluateWithValue = (n: number) => {\n\t\t\tnumberOfIterations++\n\t\t\tcalculationEngine.setSituation(\n\t\t\t\t{\n\t\t\t\t\t[node.explanation.ruleToSolve]: {\n\t\t\t\t\t\t...undefinedNumberNode,\n\t\t\t\t\t\tnodeValue: n,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ keepPreviousSituation: true },\n\t\t\t)\n\n\t\t\treturn calculationEngine.evaluateNode(node.explanation.valeur)\n\t\t}\n\n\t\tconst inversionFailed = Symbol('inversion failed')\n\n\t\tlet nodeValue: number | undefined | typeof inversionFailed = inversionFailed\n\n\t\tconst x0 = 1\n\t\tlet valeur = evaluateWithValue(x0)\n\t\tconst y0 = valeur.nodeValue as number\n\t\tconst unit = valeur.unit\n\t\tif (y0 !== undefined) {\n\t\t\t// The `uniroot` function parameter. It will be called with its `min` and\n\t\t\t// `max` arguments, so we can use our cached nodes if the function is called\n\t\t\t// with the already computed x1 or x2.\n\t\t\tconst test = (x: number): number => {\n\t\t\t\tif (x === x0) {\n\t\t\t\t\treturn y0 - x0\n\t\t\t\t}\n\t\t\t\tvaleur = evaluateWithValue(x)\n\t\t\t\tconst y = valeur.nodeValue\n\t\t\t\treturn (y as number) - x\n\t\t\t}\n\n\t\t\tconst defaultMin = -1_000_000\n\t\t\tconst defaultMax = 100_000_000\n\n\t\t\tnodeValue = uniroot(test, defaultMin, defaultMax, 0.5, maxIterations, 2)\n\t\t}\n\n\t\tif (nodeValue === inversionFailed) {\n\t\t\tnodeValue = undefined\n\t\t\tthis.cache.inversionFail = true\n\t\t}\n\t\tif (nodeValue !== undefined) {\n\t\t\tvaleur = evaluateWithValue(nodeValue)\n\t\t}\n\t\treturn {\n\t\t\t...node,\n\t\t\tunit,\n\t\t\tnodeValue,\n\t\t\texplanation: {\n\t\t\t\t...node.explanation,\n\t\t\t\tvaleur,\n\t\t\t\tnumberOfIterations,\n\t\t\t},\n\t\t\tmissingVariables: valeur.missingVariables,\n\t\t}\n\t}\n\nexport default function parseRésoudreRéférenceCirculaire(v, context: Context) {\n\treturn {\n\t\texplanation: {\n\t\t\truleToSolve: context.dottedName,\n\t\t\tvaleur: parse(v.valeur, context),\n\t\t},\n\t\tnodeKind: 'résoudre référence circulaire',\n\t} as RésoudreRéférenceCirculaireNode\n}\n\nparseRésoudreRéférenceCirculaire.nom = 'résoudre la référence circulaire'\n\nregisterEvaluationFunction(\n\t'résoudre référence circulaire',\n\tevaluateRésoudreRéférenceCirculaire,\n)\n","import { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport parse from '../parse'\nimport { convertUnit, simplifyUnit } from '../units'\n\nexport type SimplifierUnitéNode = {\n\texplanation: ASTNode\n\tnodeKind: 'simplifier unité'\n}\n\nexport default function parseSimplifierUnité(v, context): SimplifierUnitéNode {\n\tconst explanation = parse(v.valeur, context)\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'simplifier unité',\n\t}\n}\n\nparseSimplifierUnité.nom = \"simplifier l'unité\" as const\n\nregisterEvaluationFunction('simplifier unité', function evaluate(node) {\n\tconst valeur = this.evaluateNode(node.explanation)\n\tconst nodeValue = valeur.nodeValue\n\tconst defaultReturn = {\n\t\t...valeur,\n\t\t...node,\n\t\texplanation: valeur,\n\t}\n\tif (nodeValue == null) {\n\t\treturn defaultReturn\n\t}\n\n\tif (!valeur.unit) {\n\t\treturn {\n\t\t\t...defaultReturn,\n\t\t\tunit: valeur.unit,\n\t\t}\n\t}\n\tconst unit = simplifyUnit(valeur.unit)\n\n\treturn {\n\t\t...defaultReturn,\n\t\tnodeValue:\n\t\t\ttypeof nodeValue === 'number' ?\n\t\t\t\tconvertUnit(valeur.unit, unit, nodeValue)\n\t\t\t:\tnodeValue,\n\t\tunit,\n\t}\n})\n","import { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'dans la situation',\n\t{\n\t\tvaleur: {},\n\t\t'dans la situation': {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: { 'est non défini': 'dans la situation' },\n\t\t\talors: 'valeur',\n\t\t\tsinon: 'dans la situation',\n\t\t},\n\t},\n)\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { defaultNode, mergeAllMissing } from '../evaluationUtils'\nimport { convertNodeToUnit } from '../nodeUnits'\nimport parse from '../parse'\nimport { parseUnit } from '../units'\nimport {\n\tevaluatePlafondUntilActiveTranche,\n\tparseTranches,\n\tTrancheNodes,\n} from './trancheUtils'\n\nexport type TauxProgressifNode = {\n\texplanation: {\n\t\ttranches: TrancheNodes\n\t\tmultiplicateur: ASTNode\n\t\tassiette: ASTNode\n\t}\n\tnodeKind: 'taux progressif'\n}\nexport default function parseTauxProgressif(v, context): TauxProgressifNode {\n\tconst explanation = {\n\t\tassiette: parse(v.assiette, context),\n\t\tmultiplicateur:\n\t\t\tv.multiplicateur ? parse(v.multiplicateur, context) : defaultNode(1),\n\t\ttranches: parseTranches(v.tranches, context),\n\t} as TauxProgressifNode['explanation']\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'taux progressif',\n\t}\n}\n\nconst evaluate: EvaluationFunction<'taux progressif'> = function (node) {\n\tconst evaluate = this.evaluateNode.bind(this)\n\tconst assiette = this.evaluateNode(node.explanation.assiette)\n\tconst multiplicateur = this.evaluateNode(node.explanation.multiplicateur)\n\tif (multiplicateur.nodeValue === 0) {\n\t\tthrow new PublicodesError('EvaluationError', `Division by zero`, {\n\t\t\tdottedName: '',\n\t\t})\n\t}\n\tconst tranches = evaluatePlafondUntilActiveTranche.call(this, {\n\t\tparsedTranches: node.explanation.tranches,\n\t\tassiette,\n\t\tmultiplicateur,\n\t})\n\n\tconst evaluatedNode = {\n\t\t...node,\n\t\texplanation: {\n\t\t\ttranches,\n\t\t\tassiette,\n\t\t\tmultiplicateur,\n\t\t},\n\t\tunit: parseUnit('%'),\n\t}\n\n\tconst lastTranche = tranches[tranches.length - 1]\n\tif (\n\t\ttranches.every(({ isActive }) => isActive === false) ||\n\t\t(lastTranche.isActive && lastTranche.plafond.nodeValue === Infinity)\n\t) {\n\t\tconst taux = convertNodeToUnit(parseUnit('%'), evaluate(lastTranche.taux))\n\t\tconst { nodeValue, missingVariables } = taux\n\t\tlastTranche.taux = taux\n\t\tlastTranche.nodeValue = nodeValue\n\t\tlastTranche.missingVariables = missingVariables\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue,\n\t\t\tmissingVariables,\n\t\t}\n\t}\n\n\tif (\n\t\ttranches.every(({ isActive }) => isActive !== true) ||\n\t\ttypeof assiette.nodeValue !== 'number'\n\t) {\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: undefined,\n\t\t\tmissingVariables: mergeAllMissing(tranches),\n\t\t}\n\t}\n\n\tconst activeTrancheIndex = tranches.findIndex(\n\t\t({ isActive }) => isActive === true,\n\t)\n\tconst activeTranche = tranches[activeTrancheIndex]\n\tactiveTranche.taux = convertNodeToUnit(\n\t\tparseUnit('%'),\n\t\tevaluate(activeTranche.taux),\n\t)\n\n\tconst previousTranche = tranches[activeTrancheIndex - 1]\n\tif (previousTranche) {\n\t\tpreviousTranche.taux = convertNodeToUnit(\n\t\t\tparseUnit('%'),\n\t\t\tevaluate(previousTranche.taux),\n\t\t)\n\t\tpreviousTranche.isActive = true\n\t}\n\tconst previousTaux =\n\t\tpreviousTranche ? previousTranche.taux : activeTranche.taux\n\tconst calculationValues = [previousTaux, activeTranche.taux]\n\tif (calculationValues.some((n) => n.nodeValue === undefined)) {\n\t\tactiveTranche.nodeValue = undefined\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: undefined,\n\t\t\tmissingVariables: mergeAllMissing(calculationValues),\n\t\t}\n\t}\n\n\tconst lowerTaux = previousTaux.nodeValue\n\tconst upperTaux = activeTranche.taux.nodeValue\n\tconst plancher = activeTranche.plancherValue\n\tconst plafond = activeTranche.plafondValue\n\tconst coeff = (upperTaux - lowerTaux) / (plafond - plancher)\n\tconst nodeValue = lowerTaux + (assiette.nodeValue - plancher) * coeff\n\tactiveTranche.nodeValue = nodeValue\n\treturn {\n\t\t...evaluatedNode,\n\t\tnodeValue,\n\t\tmissingVariables: {},\n\t}\n}\n\nregisterEvaluationFunction('taux progressif', evaluate)\n","import { ASTNode, formatValue } from '..'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\n\nconst NAME = 'texte' as const\n\nexport type TexteNode = {\n\texplanation: Array\n\tnodeKind: typeof NAME\n}\n\nexport default function parseTexte(texte: string, context): TexteNode {\n\tconst explanation = [] as TexteNode['explanation']\n\tlet lastIndex = 0\n\tfor (const { 0: expression, index } of texte.matchAll(/{{(.|\\n)*?}}/g)) {\n\t\tconst publicodeExpression = expression.slice(2, -2).trim()\n\t\tconst parsedNode = parse(publicodeExpression, context)\n\t\texplanation.push(texte.substring(lastIndex, index), parsedNode)\n\t\tlastIndex = (index ?? 0) + expression.length\n\t}\n\texplanation.push(texte.slice(lastIndex))\n\treturn {\n\t\tnodeKind: NAME,\n\t\texplanation,\n\t}\n}\nparseTexte.nom = NAME\n\nregisterEvaluationFunction(NAME, function evaluate(node) {\n\tconst explanation = node.explanation.map((element) =>\n\t\ttypeof element === 'string' ? element : this.evaluateNode(element),\n\t)\n\n\treturn {\n\t\t...node,\n\t\texplanation,\n\t\tmissingVariables: mergeAllMissing(\n\t\t\tnode.explanation.filter(\n\t\t\t\t(element) => typeof element !== 'string',\n\t\t\t) as Array,\n\t\t),\n\t\tnodeValue: explanation\n\t\t\t.map((element) =>\n\t\t\t\ttypeof element === 'string' ? element : formatValue(element),\n\t\t\t)\n\t\t\t.join(''),\n\t}\n})\n","import { PublicodesExpression } from '..'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\n\nexport default createParseInlinedMecanismWithArray(\n\t'toutes ces conditions',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) =>\n\t\t(valeur as Array).reduce(\n\t\t\t(acc, value) => ({ et: [acc, value] }),\n\t\t\t'oui',\n\t\t),\n)\n","import { PublicodesExpression } from '..'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\n\nexport default createParseInlinedMecanismWithArray(\n\t'une de ces conditions',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) =>\n\t\t(valeur as Array).reduce(\n\t\t\t(acc, value) => ({ ou: [acc, value] }),\n\t\t\t'non',\n\t\t),\n)\n","import { ASTNode, Unit } from '../AST/types'\nimport { warning } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport parse from '../parse'\nimport { convertUnit, parseUnit } from '../units'\n\nexport type UnitéNode = {\n\tunit: Unit\n\texplanation: ASTNode\n\tnodeKind: 'unité'\n}\n\nexport default function parseUnité(v, context): UnitéNode {\n\tconst explanation = parse(v.valeur, context)\n\tconst unit = parseUnit(v.unité, context.getUnitKey)\n\n\treturn {\n\t\texplanation,\n\t\tunit,\n\t\tnodeKind: parseUnité.nom,\n\t}\n}\n\nparseUnité.nom = 'unité' as const\n\nregisterEvaluationFunction(parseUnité.nom, function evaluate(node) {\n\tconst valeur = this.evaluateNode(node.explanation)\n\n\tlet nodeValue = valeur.nodeValue\n\tif (nodeValue !== null && 'unit' in node) {\n\t\ttry {\n\t\t\tnodeValue = convertUnit(\n\t\t\t\tvaleur.unit,\n\t\t\t\tnode.unit,\n\t\t\t\tvaleur.nodeValue as number,\n\t\t\t)\n\t\t} catch (e) {\n\t\t\twarning(\n\t\t\t\tthis.context.logger,\n\t\t\t\t\"Erreur lors de la conversion d'unité explicite\",\n\t\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t\t\te,\n\t\t\t)\n\t\t}\n\t}\n\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\texplanation: valeur,\n\t\tmissingVariables: valeur.missingVariables,\n\t}\n})\n","import { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeMissing } from '../evaluationUtils'\nimport parse from '../parse'\n\nexport type VariableManquanteNode = {\n\tmissingVariable: string\n\texplanation: ASTNode\n\tnodeKind: 'variable manquante'\n}\n\nexport default function parseVariableManquante(\n\tv,\n\tcontext,\n): VariableManquanteNode {\n\treturn {\n\t\tmissingVariable: v['variable manquante'],\n\t\tnodeKind: parseVariableManquante.nom,\n\t\texplanation: parse(v.valeur, context),\n\t}\n}\n\nparseVariableManquante.nom = 'variable manquante' as const\n\nregisterEvaluationFunction(parseVariableManquante.nom, function evaluate(node) {\n\tconst valeur = this.evaluateNode(node.explanation)\n\n\tconst maxMissingScore = Object.values(valeur.missingVariables).reduce(\n\t\t(a, b) => (a > b ? a : b),\n\t\t0,\n\t)\n\n\treturn {\n\t\t...node,\n\t\tnodeValue: valeur.nodeValue,\n\t\tunit: valeur.unit,\n\t\texplanation: valeur,\n\t\tmissingVariables: mergeMissing(valeur.missingVariables, {\n\t\t\t[node.missingVariable]: maxMissingScore + 1,\n\t\t}),\n\t}\n})\n","import { EvaluationFunction } from '..'\nimport { ASTNode, EvaluatedNode, Unit } from '../AST/types'\nimport { warning } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { bonus, defaultNode, mergeMissing } from '../evaluationUtils'\nimport { convertNodeToUnit } from '../nodeUnits'\nimport parse from '../parse'\n\nexport type VariationNode = {\n\texplanation: Array<{\n\t\tcondition: ASTNode\n\t\tconsequence: ASTNode\n\t\tsatisfied?: boolean\n\t}>\n\tnodeKind: 'variations'\n}\n\nexport default function parseVariations(v, context): VariationNode {\n\tconst explanation = v.map(({ si, alors, sinon }) =>\n\t\tsinon !== undefined ?\n\t\t\t{ consequence: parse(sinon, context), condition: defaultNode(true) }\n\t\t:\t{ consequence: parse(alors, context), condition: parse(si, context) },\n\t)\n\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'variations',\n\t}\n}\n\nconst evaluate: EvaluationFunction<'variations'> = function (node) {\n\tconst [nodeValue, explanation, unit] = node.explanation.reduce<\n\t\t[\n\t\t\tEvaluatedNode['nodeValue'],\n\t\t\tVariationNode['explanation'],\n\t\t\tUnit | undefined,\n\t\t\tboolean | undefined,\n\t\t]\n\t>(\n\t\t(\n\t\t\t[evaluation, explanations, unit, previousConditions],\n\t\t\t{ condition, consequence },\n\t\t\ti: number,\n\t\t) => {\n\t\t\tif (previousConditions === true) {\n\t\t\t\treturn [\n\t\t\t\t\tevaluation,\n\t\t\t\t\t[...explanations, { condition, consequence }],\n\t\t\t\t\tunit,\n\t\t\t\t\tpreviousConditions,\n\t\t\t\t]\n\t\t\t}\n\t\t\tconst evaluatedCondition = this.evaluateNode(condition)\n\t\t\tconst currentCondition =\n\t\t\t\tpreviousConditions === undefined ? previousConditions : (\n\t\t\t\t\t!previousConditions &&\n\t\t\t\t\t(evaluatedCondition.nodeValue === undefined ?\n\t\t\t\t\t\tundefined\n\t\t\t\t\t:\tevaluatedCondition.nodeValue !== false &&\n\t\t\t\t\t\tevaluatedCondition.nodeValue !== null)\n\t\t\t\t)\n\n\t\t\tif (currentCondition === false || currentCondition === null) {\n\t\t\t\treturn [\n\t\t\t\t\tevaluation,\n\t\t\t\t\t[...explanations, { condition: evaluatedCondition, consequence }],\n\t\t\t\t\tunit,\n\t\t\t\t\tpreviousConditions,\n\t\t\t\t]\n\t\t\t}\n\t\t\tlet evaluatedConsequence: EvaluatedNode | undefined = undefined\n\t\t\tif (\n\t\t\t\tevaluatedCondition.nodeValue !== false &&\n\t\t\t\tevaluatedCondition.nodeValue !== null\n\t\t\t) {\n\t\t\t\tevaluatedConsequence = this.evaluateNode(consequence!)\n\t\t\t\tif (unit) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tevaluatedConsequence = convertNodeToUnit(\n\t\t\t\t\t\t\tunit,\n\t\t\t\t\t\t\tevaluatedConsequence!,\n\t\t\t\t\t\t)\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\twarning(\n\t\t\t\t\t\t\tthis.context.logger,\n\t\t\t\t\t\t\t`L'unité de la branche n° ${\n\t\t\t\t\t\t\t\ti + 1\n\t\t\t\t\t\t\t} du mécanisme 'variations' n'est pas compatible avec celle d'une branche précédente`,\n\t\t\t\t\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t\t\t\t\t\te,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn [\n\t\t\t\tcurrentCondition && evaluatedConsequence?.nodeValue,\n\t\t\t\t[\n\t\t\t\t\t...explanations,\n\t\t\t\t\t{\n\t\t\t\t\t\tcondition: evaluatedCondition,\n\t\t\t\t\t\tconsequence: evaluatedConsequence ?? consequence,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tunit || evaluatedConsequence?.unit,\n\t\t\t\tpreviousConditions || currentCondition,\n\t\t\t]\n\t\t},\n\t\t[null, [], undefined, false],\n\t)\n\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\t...(unit !== undefined && { unit }),\n\t\texplanation,\n\t\tmissingVariables: explanation.reduce(\n\t\t\t(values, { condition, consequence }) =>\n\t\t\t\tmergeMissing(\n\t\t\t\t\tvalues,\n\t\t\t\t\tmergeMissing(\n\t\t\t\t\t\tbonus((condition as EvaluatedNode).missingVariables),\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\t'nodeValue' in condition &&\n\t\t\t\t\t\t\t\tcondition.nodeValue !== false &&\n\t\t\t\t\t\t\t\tcondition.nodeValue !== null\n\t\t\t\t\t\t) ?\n\t\t\t\t\t\t\t(consequence as EvaluatedNode).missingVariables\n\t\t\t\t\t\t:\t{},\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t{},\n\t\t),\n\t}\n}\n\nregisterEvaluationFunction('variations', evaluate)\n","import nearley from 'nearley'\nimport { PublicodesError } from './error'\nimport grammar from './grammar.codegen'\n\n// TODO: nearley is currently exported as a CommonJS module which is why we need\n// to destructure the default import instead of directly importing the symbols\n// we need. This is sub-optimal because we our bundler will not tree-shake\n// unused nearley symbols.\n// https://github.com/kach/nearley/issues/535\nconst { Grammar, Parser } = nearley\n\nconst compiledGrammar = Grammar.fromCompiled(grammar)\n\nconst parser = new Parser(compiledGrammar)\nconst initialState = parser.save()\n\ntype BinaryOp =\n\t| { '+': [ExprAST, ExprAST] }\n\t| { '-': [ExprAST, ExprAST] }\n\t| { '*': [ExprAST, ExprAST] }\n\t| { '/': [ExprAST, ExprAST] }\n\t| { '>': [ExprAST, ExprAST] }\n\t| { '<': [ExprAST, ExprAST] }\n\t| { '>=': [ExprAST, ExprAST] }\n\t| { '<=': [ExprAST, ExprAST] }\n\t| { '=': [ExprAST, ExprAST] }\n\t| { '!=': [ExprAST, ExprAST] }\n\ntype UnaryOp = { '-': [{ value: 0 }, ExprAST] }\n\n/** AST of a publicodes expression. */\nexport type ExprAST =\n\t| BinaryOp\n\t| UnaryOp\n\t| { variable: string }\n\t| { constant: { type: 'number'; nodeValue: number }; unité?: string }\n\t| { constant: { type: 'boolean'; nodeValue: boolean } }\n\t| { constant: { type: 'string' | 'date'; nodeValue: string } }\n\n/**\n * Parse a publicodes expression into an JSON object representing the AST.\n *\n * The parsing is done with the [nearley](https://nearley.js.org/) parser\n *\n * @param rawNode The expression to parse\n * @param dottedName The dottedName of the rule being parsed\n *\n * @returns The parsing result as a JSON object\n *\n * @throws A `SyntaxError` if the expression is invalid\n * @throws A `PublicodesInternalError` if the parser is unable to parse the expression\n *\n * @example\n * ```ts\n * parseExpression('20.3 * nombre', 'foo . bar')\n * // returns { \"*\": [ { constant: { type: \"number\", nodeValue: 20.3 } }, { variable:\"nombre\" } ] }\n * ```\n */\nexport function parseExpression(rawNode: string, dottedName: string): ExprAST {\n\t/* Strings correspond to infix expressions.\n\t * Indeed, a subset of expressions like simple arithmetic operations `3 + (quantity * 2)` or like `salary [month]` are more explicit that their prefixed counterparts.\n\t * This function makes them prefixed operations. */\n\tconst singleLineExpression = (rawNode + '').replace(/\\s*\\n\\s*/g, ' ').trim()\n\n\ttry {\n\t\tparser.restore(initialState)\n\t\tconst [parseResult] = parser.feed(singleLineExpression).results\n\n\t\tif (parseResult == null) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'InternalError',\n\t\t\t\t`\nUn problème est survenu lors du parsing de l'expression \\`${singleLineExpression}\\` :\n\n\tle parseur Nearley n'a pas réussi à parser l'expression.\n`,\n\t\t\t\t{ dottedName },\n\t\t\t)\n\t\t}\n\t\treturn parseResult\n\t} catch (e) {\n\t\tif (e instanceof PublicodesError) {\n\t\t\tthrow e\n\t\t}\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`\\`${singleLineExpression}\\` n'est pas une expression valide`,\n\t\t\t{ dottedName },\n\t\t\te,\n\t\t)\n\t}\n}\n","/* Those are postprocessor functions for the Nearley grammar.ne.\nThe advantage of putting them here is to get prettier's JS formatting, since Nealrey doesn't support it https://github.com/kach/nearley/issues/310 */\nimport { normalizeDateString } from './date.ts'\n\nexport const binaryOperation = ([A, , operator, , B]) => ({\n\t[operator.value.toLowerCase()]: [A, B],\n})\n\nexport const unaryOperation = ([operator, , A]) => ({\n\t[operator]: [number([{ value: '0' }]), A],\n})\n\nexport const variable = (arg) => {\n\treturn {\n\t\tvariable: arg.value,\n\t}\n}\n\nexport const JSONObject = ([{ value }]) => {\n\tvalue\n\t// TODO\n}\nexport const number = ([{ value }]) => ({\n\tconstant: {\n\t\ttype: 'number',\n\t\tnodeValue: parseFloat(value),\n\t},\n})\n\nexport const numberWithUnit = (value) => ({\n\t...number(value),\n\tunité: value[2].value,\n})\n\nexport const date = ([{ value }]) => {\n\treturn {\n\t\tconstant: {\n\t\t\ttype: 'date',\n\t\t\tnodeValue: normalizeDateString(value),\n\t\t},\n\t}\n}\n\nexport const boolean = ([{ value }]) => ({\n\tconstant: {\n\t\ttype: 'boolean',\n\t\tnodeValue: value === 'oui',\n\t},\n})\n\nexport const string = ([{ value }]) => ({\n\tconstant: {\n\t\ttype: 'string',\n\t\tnodeValue: value.slice(1, -1),\n\t},\n})\n","// Generated automatically by nearley, version 2.20.1\n// http://github.com/Hardmath123/nearley\nfunction id(x) { return x[0]; }\n\nimport {\n string, date, variable, binaryOperation, unaryOperation, boolean, number, numberWithUnit, JSONObject\n} from './grammarFunctions.js';\nimport moo from \"moo\";\n\n\nconst dateRegexp = `(?:(?:0?[1-9]|[12][0-9]|3[01])\\\\/)?(?:0?[1-9]|1[012])\\\\/\\\\d{4}`\nconst letter = '[a-zA-Z\\u00C0-\\u017F€$%°]';\nconst letterOrNumber = '[a-zA-Z\\u00C0-\\u017F0-9\\',]';\nconst word = `${letter}(?:[-']?${letterOrNumber}+)*`;\n\nconst numberRegExp = '-?(?:[1-9][0-9]+|[0-9])(?:\\\\.[0-9]+)?';\nconst lexer = moo.compile({\n '(': '(',\n ')': ')',\n '[': '[',\n ']': ']',\n comparison: ['>','<','>=','<=','=','!='],\n date: new RegExp(dateRegexp),\n\tboolean: ['oui','non'],\n number: new RegExp(numberRegExp),\n word: new RegExp(word),\n string: [/'.*'/, /\".*\"/],\n parentSelector: \"^\",\n JSONObject: /{.*}/,\n additionSubstraction: /[\\+-]/,\n multiplicationDivision: ['*','/'],\n dot: ' . ',\n \".\": '.',\n space: { match: /[\\s]+/, lineBreaks: true },\n});\n\nconst join = (args) => ({value: (args.map(x => x && x.value).join(\"\"))})\nconst flattenJoin = (args) => join(args.flat())\nlet Lexer = lexer;\nlet ParserRules = [\n {\"name\": \"main\", \"symbols\": [\"Comparison\"], \"postprocess\": id},\n {\"name\": \"main\", \"symbols\": [\"NumericValue\"], \"postprocess\": id},\n {\"name\": \"main\", \"symbols\": [\"Date\"], \"postprocess\": id},\n {\"name\": \"main\", \"symbols\": [\"NonNumericTerminal\"], \"postprocess\": id},\n {\"name\": \"main\", \"symbols\": [\"JSONObject\"], \"postprocess\": id},\n {\"name\": \"NumericValue\", \"symbols\": [\"AdditionSubstraction\"], \"postprocess\": id},\n {\"name\": \"NumericValue\", \"symbols\": [\"Negation\"], \"postprocess\": id},\n {\"name\": \"NumericTerminal\", \"symbols\": [\"Variable\"], \"postprocess\": id},\n {\"name\": \"NumericTerminal\", \"symbols\": [\"number\"], \"postprocess\": id},\n {\"name\": \"Negation\", \"symbols\": [{\"literal\":\"-\"}, (lexer.has(\"space\") ? {type: \"space\"} : space), \"Parentheses\"], \"postprocess\": unaryOperation},\n {\"name\": \"Parentheses\", \"symbols\": [{\"literal\":\"(\"}, (lexer.has(\"space\") ? {type: \"space\"} : space), \"NumericValue\", (lexer.has(\"space\") ? {type: \"space\"} : space), {\"literal\":\")\"}], \"postprocess\": ([,,e]) => e},\n {\"name\": \"Parentheses\", \"symbols\": [{\"literal\":\"(\"}, \"NumericValue\", {\"literal\":\")\"}], \"postprocess\": ([,e]) => e},\n {\"name\": \"Parentheses\", \"symbols\": [\"NumericTerminal\"], \"postprocess\": id},\n {\"name\": \"Date\", \"symbols\": [\"Variable\"], \"postprocess\": id},\n {\"name\": \"Date\", \"symbols\": [(lexer.has(\"date\") ? {type: \"date\"} : date)], \"postprocess\": date},\n {\"name\": \"Comparison\", \"symbols\": [\"Comparable\", (lexer.has(\"space\") ? {type: \"space\"} : space), (lexer.has(\"comparison\") ? {type: \"comparison\"} : comparison), (lexer.has(\"space\") ? {type: \"space\"} : space), \"Comparable\"], \"postprocess\": binaryOperation},\n {\"name\": \"Comparison\", \"symbols\": [\"Date\", (lexer.has(\"space\") ? {type: \"space\"} : space), (lexer.has(\"comparison\") ? {type: \"comparison\"} : comparison), (lexer.has(\"space\") ? {type: \"space\"} : space), \"Date\"], \"postprocess\": binaryOperation},\n {\"name\": \"Comparable$subexpression$1\", \"symbols\": [\"AdditionSubstraction\"]},\n {\"name\": \"Comparable$subexpression$1\", \"symbols\": [\"NonNumericTerminal\"]},\n {\"name\": \"Comparable\", \"symbols\": [\"Comparable$subexpression$1\"], \"postprocess\": ([[e]]) => e},\n {\"name\": \"NonNumericTerminal\", \"symbols\": [(lexer.has(\"boolean\") ? {type: \"boolean\"} : boolean)], \"postprocess\": boolean},\n {\"name\": \"NonNumericTerminal\", \"symbols\": [(lexer.has(\"string\") ? {type: \"string\"} : string)], \"postprocess\": string},\n {\"name\": \"Variable\", \"symbols\": [\"VariableWithoutParentSelector\"], \"postprocess\": ([x]) => variable(x)},\n {\"name\": \"Variable$ebnf$1\", \"symbols\": []},\n {\"name\": \"Variable$ebnf$1$subexpression$1\", \"symbols\": [(lexer.has(\"parentSelector\") ? {type: \"parentSelector\"} : parentSelector), (lexer.has(\"dot\") ? {type: \"dot\"} : dot)], \"postprocess\": join},\n {\"name\": \"Variable$ebnf$1\", \"symbols\": [\"Variable$ebnf$1\", \"Variable$ebnf$1$subexpression$1\"], \"postprocess\": function arrpush(d) {return d[0].concat([d[1]]);}},\n {\"name\": \"Variable\", \"symbols\": [\"Variable$ebnf$1\", \"VariableWithoutParentSelector\"], \"postprocess\": x => variable(flattenJoin(x))},\n {\"name\": \"VariableWithoutParentSelector$ebnf$1\", \"symbols\": []},\n {\"name\": \"VariableWithoutParentSelector$ebnf$1$subexpression$1\", \"symbols\": [(lexer.has(\"dot\") ? {type: \"dot\"} : dot), \"Words\"], \"postprocess\": join},\n {\"name\": \"VariableWithoutParentSelector$ebnf$1\", \"symbols\": [\"VariableWithoutParentSelector$ebnf$1\", \"VariableWithoutParentSelector$ebnf$1$subexpression$1\"], \"postprocess\": function arrpush(d) {return d[0].concat([d[1]]);}},\n {\"name\": \"VariableWithoutParentSelector\", \"symbols\": [\"Words\", \"VariableWithoutParentSelector$ebnf$1\"], \"postprocess\": x => flattenJoin(x)},\n {\"name\": \"Words$ebnf$1$subexpression$1$ebnf$1\", \"symbols\": [(lexer.has(\"space\") ? {type: \"space\"} : space)], \"postprocess\": id},\n {\"name\": \"Words$ebnf$1$subexpression$1$ebnf$1\", \"symbols\": [], \"postprocess\": function(d) {return null;}},\n {\"name\": \"Words$ebnf$1$subexpression$1\", \"symbols\": [\"Words$ebnf$1$subexpression$1$ebnf$1\", \"WordOrNumber\"], \"postprocess\": join},\n {\"name\": \"Words$ebnf$1\", \"symbols\": [\"Words$ebnf$1$subexpression$1\"]},\n {\"name\": \"Words$ebnf$1$subexpression$2$ebnf$1\", \"symbols\": [(lexer.has(\"space\") ? {type: \"space\"} : space)], \"postprocess\": id},\n {\"name\": \"Words$ebnf$1$subexpression$2$ebnf$1\", \"symbols\": [], \"postprocess\": function(d) {return null;}},\n {\"name\": \"Words$ebnf$1$subexpression$2\", \"symbols\": [\"Words$ebnf$1$subexpression$2$ebnf$1\", \"WordOrNumber\"], \"postprocess\": join},\n {\"name\": \"Words$ebnf$1\", \"symbols\": [\"Words$ebnf$1\", \"Words$ebnf$1$subexpression$2\"], \"postprocess\": function arrpush(d) {return d[0].concat([d[1]]);}},\n {\"name\": \"Words\", \"symbols\": [\"WordOrKeyword\", \"Words$ebnf$1\"], \"postprocess\": flattenJoin},\n {\"name\": \"Words\", \"symbols\": [(lexer.has(\"word\") ? {type: \"word\"} : word)], \"postprocess\": id},\n {\"name\": \"WordOrKeyword\", \"symbols\": [(lexer.has(\"word\") ? {type: \"word\"} : word)], \"postprocess\": id},\n {\"name\": \"WordOrKeyword\", \"symbols\": [(lexer.has(\"boolean\") ? {type: \"boolean\"} : boolean)], \"postprocess\": id},\n {\"name\": \"WordOrNumber\", \"symbols\": [\"WordOrKeyword\"], \"postprocess\": id},\n {\"name\": \"WordOrNumber\", \"symbols\": [(lexer.has(\"number\") ? {type: \"number\"} : number)], \"postprocess\": id},\n {\"name\": \"Unit$ebnf$1\", \"symbols\": []},\n {\"name\": \"Unit$ebnf$1\", \"symbols\": [\"Unit$ebnf$1\", \"UnitNumerator\"], \"postprocess\": function arrpush(d) {return d[0].concat([d[1]]);}},\n {\"name\": \"Unit$ebnf$2\", \"symbols\": []},\n {\"name\": \"Unit$ebnf$2\", \"symbols\": [\"Unit$ebnf$2\", \"UnitDenominator\"], \"postprocess\": function arrpush(d) {return d[0].concat([d[1]]);}},\n {\"name\": \"Unit\", \"symbols\": [\"Unit$ebnf$1\", \"Unit$ebnf$2\"], \"postprocess\": flattenJoin},\n {\"name\": \"UnitNumerator\", \"symbols\": [\"Words\"], \"postprocess\": id},\n {\"name\": \"UnitNumerator\", \"symbols\": [{\"literal\":\".\"}, \"UnitNumerator\"], \"postprocess\": join},\n {\"name\": \"UnitDenominator$ebnf$1\", \"symbols\": []},\n {\"name\": \"UnitDenominator$ebnf$1$subexpression$1\", \"symbols\": [(lexer.has(\"space\") ? {type: \"space\"} : space)]},\n {\"name\": \"UnitDenominator$ebnf$1\", \"symbols\": [\"UnitDenominator$ebnf$1\", \"UnitDenominator$ebnf$1$subexpression$1\"], \"postprocess\": function arrpush(d) {return d[0].concat([d[1]]);}},\n {\"name\": \"UnitDenominator$ebnf$2\", \"symbols\": [\"UnitNumerator\"]},\n {\"name\": \"UnitDenominator$ebnf$2\", \"symbols\": [\"UnitDenominator$ebnf$2\", \"UnitNumerator\"], \"postprocess\": function arrpush(d) {return d[0].concat([d[1]]);}},\n {\"name\": \"UnitDenominator\", \"symbols\": [\"UnitDenominator$ebnf$1\", {\"literal\":\"/\"}, \"UnitDenominator$ebnf$2\"], \"postprocess\": flattenJoin},\n {\"name\": \"AdditionSubstraction\", \"symbols\": [\"AdditionSubstraction\", (lexer.has(\"space\") ? {type: \"space\"} : space), (lexer.has(\"additionSubstraction\") ? {type: \"additionSubstraction\"} : additionSubstraction), (lexer.has(\"space\") ? {type: \"space\"} : space), \"MultiplicationDivision\"], \"postprocess\": binaryOperation},\n {\"name\": \"AdditionSubstraction\", \"symbols\": [\"MultiplicationDivision\"], \"postprocess\": id},\n {\"name\": \"MultiplicationDivision\", \"symbols\": [\"MultiplicationDivision\", (lexer.has(\"space\") ? {type: \"space\"} : space), (lexer.has(\"multiplicationDivision\") ? {type: \"multiplicationDivision\"} : multiplicationDivision), (lexer.has(\"space\") ? {type: \"space\"} : space), \"Parentheses\"], \"postprocess\": binaryOperation},\n {\"name\": \"MultiplicationDivision\", \"symbols\": [\"Parentheses\"], \"postprocess\": id},\n {\"name\": \"number\", \"symbols\": [(lexer.has(\"number\") ? {type: \"number\"} : number)], \"postprocess\": number},\n {\"name\": \"number$ebnf$1$subexpression$1\", \"symbols\": [(lexer.has(\"space\") ? {type: \"space\"} : space)]},\n {\"name\": \"number$ebnf$1\", \"symbols\": [\"number$ebnf$1$subexpression$1\"], \"postprocess\": id},\n {\"name\": \"number$ebnf$1\", \"symbols\": [], \"postprocess\": function(d) {return null;}},\n {\"name\": \"number\", \"symbols\": [(lexer.has(\"number\") ? {type: \"number\"} : number), \"number$ebnf$1\", \"Unit\"], \"postprocess\": numberWithUnit},\n {\"name\": \"JSONObject\", \"symbols\": [(lexer.has(\"JSONObject\") ? {type: \"JSONObject\"} : JSONObject)], \"postprocess\": JSONObject}\n];\nlet ParserStart = \"main\";\nexport default { Lexer, ParserRules, ParserStart };\n","import { PublicodesError, PublicodesInternalError } from './error'\nimport { registerEvaluationFunction } from './evaluationFunctions'\nimport { Context } from './parsePublicodes'\n\nexport type ReferenceNode = {\n\tnodeKind: 'reference'\n\tname: string\n\tcontextDottedName: string\n\tdottedName?: string\n\ttitle?: string\n\tacronym?: string\n}\n\nexport default function parseReference(\n\tv: string,\n\tcontext: Context,\n): ReferenceNode {\n\tif (!context.dottedName) {\n\t\tthrow new PublicodesError(\n\t\t\t'InternalError',\n\t\t\t\"Une référence ne peut pas exister en dehors d'une règle (`context.dottedName` est vide)\",\n\t\t\t{\n\t\t\t\tdottedName: v,\n\t\t\t},\n\t\t)\n\t}\n\tif (!v) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t'Une référence ne peut pas être vide',\n\t\t\t{\n\t\t\t\tdottedName: context.dottedName,\n\t\t\t},\n\t\t)\n\t}\n\n\treturn {\n\t\tnodeKind: 'reference',\n\t\tname: v,\n\t\tcontextDottedName: context.dottedName,\n\t}\n}\n\nregisterEvaluationFunction('reference', function evaluateReference(node) {\n\tif (!node.dottedName) {\n\t\tthrow new PublicodesInternalError(node)\n\t}\n\tconst explanation = this.evaluateNode(\n\t\tthis.context.parsedRules[node.dottedName],\n\t)\n\tdelete explanation.sourceMap\n\treturn {\n\t\t...explanation,\n\t\t...node,\n\t}\n})\n","import { ASTNode } from './AST/types'\nimport { PublicodesError } from './error'\nimport abattement from './mecanisms/abattement'\nimport applicable from './mecanisms/applicable'\nimport arrondi from './mecanisms/arrondi'\nimport avec from './mecanisms/avec'\nimport barème from './mecanisms/barème'\nimport condition from './mecanisms/condition'\nimport contexte from './mecanisms/contexte'\nimport durée from './mecanisms/durée'\nimport {\n\tparseEstApplicable,\n\tparseEstDéfini,\n\tparseEstNonDéfini,\n} from './mecanisms/est'\nimport { parseEstNonApplicable } from './mecanisms/est-non-applicable'\nimport grille from './mecanisms/grille'\nimport { mecanismInversion } from './mecanisms/inversion'\nimport { parseMaximumDe, parseMinimumDe } from './mecanisms/max-min'\nimport moyenne from './mecanisms/moyenne'\nimport nonApplicable from './mecanisms/non-applicable'\nimport { mecanismOnePossibility } from './mecanisms/one-possibility'\nimport operations from './mecanisms/operation'\nimport parDéfaut from './mecanisms/parDéfaut'\nimport plafond from './mecanisms/plafond'\nimport plancher from './mecanisms/plancher'\nimport produit from './mecanisms/product'\nimport résoudreRéférenceCirculaire from './mecanisms/résoudre-référence-circulaire'\nimport simplifierUnité from './mecanisms/simplifier-unité'\nimport situation from './mecanisms/situation'\nimport somme from './mecanisms/somme'\nimport tauxProgressif from './mecanisms/tauxProgressif'\nimport texte from './mecanisms/texte'\nimport toutesCesConditions from './mecanisms/toutes-ces-conditions'\nimport uneDeCesConditions from './mecanisms/une-de-ces-conditions'\nimport unité from './mecanisms/unité'\nimport variableManquante from './mecanisms/variablesManquantes'\nimport variations from './mecanisms/variations'\nimport { parseExpression } from './parseExpression'\nimport { Context } from './parsePublicodes'\nimport parseReference from './reference'\n\nexport default function parse(rawNode, context: Context): ASTNode {\n\tif (rawNode == undefined) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`\n\tUne des valeurs de la formule est vide.\n\tVérifiez que tous les champs à droite des deux points sont remplis`,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\tif (typeof rawNode === 'boolean') {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`\nLes valeurs booléennes true / false ne sont acceptées.\nUtilisez leur contrepartie française : 'oui' / 'non'`,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\tconst node =\n\t\ttypeof rawNode === 'object' ? rawNode : (\n\t\t\tparseExpression(rawNode, context.dottedName)\n\t\t)\n\tif ('nodeKind' in node) {\n\t\treturn node\n\t}\n\n\treturn {\n\t\t...parseChainedMecanisms(node, context),\n\t\trawNode,\n\t}\n}\n\nfunction parseMecanism(rawNode, context: Context) {\n\tif (Array.isArray(rawNode)) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`\nIl manque le nom du mécanisme pour le tableau : [${rawNode\n\t\t\t\t.map((x) => `'${x}'`)\n\t\t\t\t.join(', ')}]\nLes mécanisme possibles sont : 'somme', 'le maximum de', 'le minimum de', 'toutes ces conditions', 'une de ces conditions'.\n\t\t`,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\n\tconst keys = Object.keys(rawNode)\n\tif (keys.length > 1) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`\nLes mécanismes suivants se situent au même niveau : ${keys\n\t\t\t\t.map((x) => `'${x}'`)\n\t\t\t\t.join(', ')}\nCela vient probablement d'une erreur dans l'indentation\n\t`,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\tif (keys.length === 0) {\n\t\treturn { nodeKind: 'constant', nodeValue: undefined }\n\t}\n\n\tconst mecanismName = keys[0]\n\tconst values = rawNode[mecanismName]\n\tconst parseFn = parseFunctions[mecanismName]\n\n\tif (!parseFn) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`Le mécanisme \"${mecanismName}\" est inconnu.\n\nVérifiez qu'il n'y ait pas d'erreur dans l'orthographe du nom.`,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\ttry {\n\t\treturn parseFn(values, context)\n\t} catch (e) {\n\t\tif (e instanceof PublicodesError) {\n\t\t\tthrow e\n\t\t}\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\tmecanismName ?\n\t\t\t\t`➡️ Dans le mécanisme ${mecanismName}\n${e.message}`\n\t\t\t:\te.message,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n}\n\n// Chainable mecanisme in their composition order (first one is applyied first)\nconst chainableMecanisms = [\n\tcontexte,\n\tvariableManquante,\n\tavec,\n\tapplicable,\n\tnonApplicable,\n\tarrondi,\n\tunité,\n\tsimplifierUnité,\n\tplancher,\n\tplafond,\n\tparDéfaut,\n\tsituation,\n\trésoudreRéférenceCirculaire,\n\tabattement,\n]\n\nfunction parseChainedMecanisms(rawNode, context: Context): ASTNode {\n\tconst parseFn = chainableMecanisms.find((fn) => fn.nom in rawNode)\n\tif (!parseFn) {\n\t\treturn parseMecanism(rawNode, context)\n\t}\n\tconst { [parseFn.nom]: param, ...valeur } = rawNode\n\n\treturn parseMecanism(\n\t\t{\n\t\t\t[parseFn.nom]: {\n\t\t\t\tvaleur,\n\t\t\t\t[parseFn.nom]: param,\n\t\t\t},\n\t\t},\n\t\tcontext,\n\t)\n}\n\nconst parseFunctions = {\n\t...operations,\n\t...chainableMecanisms.reduce((acc, fn) => ({ [fn.nom]: fn, ...acc }), {}),\n\t'inversion numérique': mecanismInversion,\n\t'le maximum de': parseMaximumDe,\n\t'le minimum de': parseMinimumDe,\n\t'taux progressif': tauxProgressif,\n\t'toutes ces conditions': toutesCesConditions,\n\t'est non défini': parseEstNonDéfini,\n\t'est non applicable': parseEstNonApplicable,\n\t'est applicable': parseEstApplicable,\n\t'est défini': parseEstDéfini,\n\t'une de ces conditions': uneDeCesConditions,\n\t'une possibilité': mecanismOnePossibility,\n\tcondition,\n\tbarème,\n\tdurée,\n\tgrille,\n\tmultiplication: produit,\n\tproduit,\n\tsomme,\n\tmoyenne,\n\t[texte.nom]: texte,\n\tvaleur: parse,\n\tvariable: parseReference,\n\tvariations,\n\tconstant: (v) => ({\n\t\ttype: v.type,\n\t\t// In the documentation we want to display constants defined in the source\n\t\t// with their full precision. This is especially useful for percentages like\n\t\t// APEC 0,036 %.\n\t\tfullPrecision: true,\n\t\tisNullable: v.nodeValue == null,\n\t\tmissingVariables: {},\n\t\tnodeValue: v.nodeValue,\n\t\tnodeKind: 'constant',\n\t}),\n}\n\nexport const mecanismKeys = Object.keys(parseFunctions)\n","import { ParsedRules, PublicodesError } from '.'\nimport { makeASTTransformer, makeASTVisitor } from './AST'\nimport { ASTNode } from './AST/types'\nimport { PublicodesInternalError } from './error'\nimport { defaultNode, notApplicableNode } from './evaluationUtils'\nimport parse from './parse'\nimport { Context, ReferencesMaps, RulesReplacements } from './parsePublicodes'\nimport { Rule, RuleNode } from './rule'\nimport { updateReferencesMapsFromReferenceNode } from './ruleUtils'\nimport { mergeWithArray } from './utils'\n\nexport type ReplacementRule = {\n\tnodeKind: 'replacementRule'\n\tdefinitionRule: ASTNode<'reference'> & { dottedName: string }\n\treplacedReference: ASTNode<'reference'>\n\tpriority?: number\n\twhiteListedNames: Array>\n\trawNode: any\n\tblackListedNames: Array>\n\tremplacementRuleId: number\n\treplaceByNonApplicable: boolean\n}\n\n// Replacements depend on the context and their evaluation implies using\n// \"variations\" node everywhere there is a reference to the original rule.\n// However for performance reason we want to mutualize identical \"variations\"\n// nodes instead of duplicating them, to avoid wasteful computations.\n//\n// The implementation works by first attributing an identifier for each\n// replacementRule. We then use this identifier to create a cache key that\n// represents the combinaison of applicables replacements for a given reference.\n// For example if replacements 12, 13 et 643 are applicable we use the key\n// `12-13-643` as the cache identifier in the `inlineReplacements` function.\nlet remplacementRuleId = 0\nconst cache = {}\n\nexport function parseReplacements(\n\treplacements: Rule['remplace'],\n\tcontext: Context,\n): Array {\n\tif (!replacements) {\n\t\treturn []\n\t}\n\n\treturn (Array.isArray(replacements) ? replacements : [replacements]).map(\n\t\t(replacement) => {\n\t\t\tif (typeof replacement === 'string') {\n\t\t\t\treplacement = { 'références à': replacement }\n\t\t\t}\n\n\t\t\tconst replacedReference = parse(replacement['références à'], context)\n\n\t\t\tconst [whiteListedNames, blackListedNames] = [\n\t\t\t\treplacement.dans ?? [],\n\t\t\t\treplacement['sauf dans'] ?? [],\n\t\t\t]\n\t\t\t\t.map((dottedName) =>\n\t\t\t\t\tArray.isArray(dottedName) ? dottedName : [dottedName],\n\t\t\t\t)\n\t\t\t\t.map((refs) => refs.map((ref) => parse(ref, context)))\n\t\t\tif (\n\t\t\t\treplacement.priorité != null &&\n\t\t\t\t(typeof replacement.priorité !== 'number' || replacement.priorité < 0)\n\t\t\t) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'SyntaxError',\n\t\t\t\t\t'La priorité du remplacement doit être un nombre positif',\n\t\t\t\t\tcontext,\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tnodeKind: 'replacementRule',\n\t\t\t\trawNode: replacement,\n\t\t\t\tpriority: replacement.priorité,\n\t\t\t\tdefinitionRule: parse(context.dottedName, context),\n\t\t\t\treplacedReference,\n\t\t\t\treplaceByNonApplicable: false,\n\t\t\t\twhiteListedNames,\n\t\t\t\tblackListedNames,\n\t\t\t\tremplacementRuleId: remplacementRuleId++,\n\t\t\t} as ReplacementRule\n\t\t},\n\t)\n}\n\nexport function parseRendNonApplicable(\n\trules: Rule['rend non applicable'],\n\tcontext: Context,\n): Array {\n\tconst rendNonApplicableReplacements = parseReplacements(rules, context)\n\trendNonApplicableReplacements.forEach(\n\t\t(r) => (r.replaceByNonApplicable = true),\n\t)\n\treturn rendNonApplicableReplacements\n}\n\nexport function getReplacements(\n\tparsedRules: Record,\n): RulesReplacements {\n\tconst ret = {}\n\tfor (const dottedName in parsedRules) {\n\t\tconst rule = parsedRules[dottedName]\n\t\tfor (const replacement of rule.replacements) {\n\t\t\tif (!replacement.replacedReference.dottedName) {\n\t\t\t\tthrow new PublicodesInternalError(replacement)\n\t\t\t}\n\t\t\tconst key = replacement.replacedReference.dottedName\n\t\t\tret[key] = [...(ret[key] ?? []), replacement]\n\t\t}\n\t}\n\n\treturn ret\n}\n\nexport function inlineReplacements<\n\tNewNames extends string,\n\tPreviousNames extends string,\n>({\n\tnewRules,\n\tpreviousReplacements,\n\tparsedRules,\n\treferencesMaps,\n}: {\n\tnewRules: ParsedRules\n\tpreviousReplacements: RulesReplacements\n\tparsedRules: ParsedRules\n\treferencesMaps: ReferencesMaps\n}): [\n\tParsedRules,\n\tRulesReplacements,\n] {\n\ttype Names = NewNames | PreviousNames\n\tconst newReplacements = getReplacements(newRules) as RulesReplacements\n\n\tconst ruleNamesWithNewReplacements = new Set([]) as Set\n\tfor (const replacedReference in newReplacements) {\n\t\tconst rulesThatUse =\n\t\t\treferencesMaps.rulesThatUse.get(replacedReference as NewNames | Names) ??\n\t\t\t[]\n\n\t\tfor (const value of rulesThatUse) {\n\t\t\truleNamesWithNewReplacements.add(value)\n\t\t}\n\t}\n\n\tconst newRuleNamesWithPreviousReplacements: Set = new Set(\n\t\t(Object.keys(newRules) as Array).filter((ruleName) =>\n\t\t\t[...(referencesMaps.referencesIn.get(ruleName) ?? new Set())].some(\n\t\t\t\t(reference) =>\n\t\t\t\t\t(previousReplacements[reference as PreviousNames] ?? []).length,\n\t\t\t),\n\t\t),\n\t)\n\n\tconst replacements = mergeWithArray(previousReplacements, newReplacements)\n\tif (\n\t\t!newRuleNamesWithPreviousReplacements.size &&\n\t\t!ruleNamesWithNewReplacements.size\n\t) {\n\t\treturn [parsedRules, replacements]\n\t}\n\n\tconst inlinePreviousReplacement = makeReplacementInliner(\n\t\tpreviousReplacements,\n\t\treferencesMaps,\n\t)\n\tconst inlineNewReplacement = makeReplacementInliner(\n\t\tnewReplacements,\n\t\treferencesMaps,\n\t)\n\n\tnewRuleNamesWithPreviousReplacements.forEach((name) => {\n\t\tparsedRules[name] = inlinePreviousReplacement(\n\t\t\tparsedRules[name],\n\t\t) as RuleNode\n\t})\n\truleNamesWithNewReplacements.forEach((name) => {\n\t\tparsedRules[name] = inlineNewReplacement(\n\t\t\tparsedRules[name],\n\t\t) as RuleNode\n\t})\n\n\treturn [parsedRules, replacements]\n}\n\nexport function makeReplacementInliner(\n\treplacements: RulesReplacements,\n\treferencesMaps: ReferencesMaps,\n): (n: ASTNode) => ASTNode {\n\treturn makeASTTransformer((node, transform) => {\n\t\tif (\n\t\t\tnode.nodeKind === 'replacementRule' ||\n\t\t\tnode.nodeKind === 'inversion' ||\n\t\t\tnode.nodeKind === 'une possibilité'\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tif (node.nodeKind === 'contexte') {\n\t\t\t// We don't replace references in contexte keys\n\t\t\treturn {\n\t\t\t\t...node,\n\t\t\t\texplanation: {\n\t\t\t\t\t...node.explanation,\n\t\t\t\t\tvaleur: transform(node.explanation.valeur),\n\t\t\t\t\tcontexte: node.explanation.contexte.map(([name, value]) => [\n\t\t\t\t\t\tname,\n\t\t\t\t\t\ttransform(value),\n\t\t\t\t\t]),\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\tif (node.nodeKind === 'reference') {\n\t\t\tif (!node.dottedName) {\n\t\t\t\tthrow new PublicodesInternalError(node)\n\t\t\t}\n\t\t\tconst replacedReferenceNode = replace(\n\t\t\t\tnode,\n\t\t\t\treplacements[node.dottedName] ?? [],\n\t\t\t)\n\t\t\t// Collect inlined replacement\n\t\t\tmakeASTVisitor((n) => {\n\t\t\t\tupdateReferencesMapsFromReferenceNode(\n\t\t\t\t\tn,\n\t\t\t\t\treferencesMaps,\n\t\t\t\t\tnode.contextDottedName,\n\t\t\t\t)\n\t\t\t\treturn 'continue'\n\t\t\t})(replacedReferenceNode)\n\t\t\treturn replacedReferenceNode\n\t\t}\n\t})\n}\n\nfunction replace(\n\tnode: ASTNode<'reference'>,\n\treplacements: Array,\n): ASTNode {\n\t// TODO : handle transitivité\n\n\tconst applicableReplacements = replacements\n\t\t.filter(\n\t\t\t({ definitionRule }) =>\n\t\t\t\tdefinitionRule.dottedName !== node.contextDottedName,\n\t\t)\n\t\t.filter(\n\t\t\t({ whiteListedNames }) =>\n\t\t\t\t!whiteListedNames.length ||\n\t\t\t\twhiteListedNames.some((name) =>\n\t\t\t\t\tnode.contextDottedName.startsWith(name.dottedName as string),\n\t\t\t\t),\n\t\t)\n\t\t.filter(\n\t\t\t({ blackListedNames }) =>\n\t\t\t\t!blackListedNames.length ||\n\t\t\t\tblackListedNames.every(\n\t\t\t\t\t(name) =>\n\t\t\t\t\t\t!node.contextDottedName.startsWith(name.dottedName as string),\n\t\t\t\t),\n\t\t)\n\t\t.reverse()\n\t\t.sort((a, b) => {\n\t\t\tconst result = (b.priority ?? 0) - (a.priority ?? 0)\n\t\t\tif (result !== 0) {\n\t\t\t\treturn result\n\t\t\t}\n\t\t\treturn b.definitionRule.dottedName.localeCompare(\n\t\t\t\ta.definitionRule.dottedName,\n\t\t\t)\n\t\t})\n\n\tif (!applicableReplacements.length) {\n\t\treturn node\n\t}\n\n\tconst applicableReplacementsCacheKey = applicableReplacements\n\t\t.map((n) => n.remplacementRuleId)\n\t\t.join('-')\n\tif (cache[applicableReplacementsCacheKey]) {\n\t\treturn cache[applicableReplacementsCacheKey]\n\t}\n\tconst replacementNode = {\n\t\tnodeKind: 'variations',\n\t\texplanation: [\n\t\t\t...applicableReplacements.map(\n\t\t\t\t({ definitionRule, replaceByNonApplicable }) =>\n\t\t\t\t\treplaceByNonApplicable ?\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcondition: definitionRule,\n\t\t\t\t\t\t\tconsequence: notApplicableNode,\n\t\t\t\t\t\t}\n\t\t\t\t\t:\t{\n\t\t\t\t\t\t\tcondition: estApplicable(definitionRule),\n\t\t\t\t\t\t\tconsequence: definitionRule,\n\t\t\t\t\t\t},\n\t\t\t),\n\t\t\t{ condition: oui, consequence: node },\n\t\t],\n\t} as ASTNode<'variations'>\n\n\treplacementNode.sourceMap = {\n\t\tmecanismName: 'replacement',\n\t\targs: {\n\t\t\tapplicableReplacements,\n\t\t\toriginalNode: node,\n\t\t},\n\t}\n\tcache[applicableReplacementsCacheKey] = replacementNode\n\treturn cache[applicableReplacementsCacheKey]\n}\n\nfunction estApplicable(node: ASTNode) {\n\treturn {\n\t\tnodeKind: 'condition',\n\t\texplanation: {\n\t\t\tsi: { nodeKind: 'est non applicable', explanation: node },\n\t\t\talors: non,\n\t\t\tsinon: oui,\n\t\t},\n\t} as ASTNode<'condition'>\n}\n\nconst oui = defaultNode(true)\nconst non = defaultNode(false)\n","import { Logger, ParsedRules } from '.'\nimport { makeASTTransformer, traverseParsedRules } from './AST'\nimport { PublicodesError } from './error'\nimport inferNodeType, { NodesTypes } from './inferNodeType'\nimport { ReplacementRule, inlineReplacements } from './replacement'\nimport { Rule, parseRules } from './rule'\nimport {\n\tdisambiguateReferenceNode,\n\tupdateReferencesMapsFromReferenceNode,\n} from './ruleUtils'\nimport { getUnitKey } from './units'\nimport { weakCopyObj } from './utils'\n\nexport type Context = {\n\tdottedName: RuleNames | ''\n\tparsedRules: ParsedRules\n\tnodesTypes: NodesTypes\n\treferencesMaps: ReferencesMaps\n\trulesReplacements: RulesReplacements\n\tgetUnitKey?: getUnitKey\n\tlogger: Logger\n\tinversionMaxIterations?: number\n\t/**\n\t * Don't throw an error if the parent of a rule is not found.\n\t * This is useful to parse partial rule sets (e.g. optimized ones).\n\t */\n\tallowOrphanRules: boolean\n\t/**\n\t * This is used to generate unique IDs for sub-engines, we need to generate them at\n\t * */\n\tsubEngineIncrementingNumber?: number\n}\n\nexport type RulesReplacements = Partial<\n\tRecord\n>\n\nexport type ReferencesMaps = {\n\treferencesIn: Map>\n\trulesThatUse: Map>\n}\n\nexport type RawRule = Omit | string | number | null\nexport type RawPublicodes = Partial<\n\tRecord\n>\n\nexport function createContext(\n\tpartialContext: Partial>,\n): Context {\n\treturn {\n\t\tdottedName: '',\n\t\tlogger: console,\n\t\tgetUnitKey: (x) => x,\n\t\tparsedRules: {} as ParsedRules,\n\t\treferencesMaps: { referencesIn: new Map(), rulesThatUse: new Map() },\n\t\tnodesTypes: new WeakMap(),\n\t\trulesReplacements: {},\n\t\tallowOrphanRules: false,\n\n\t\tsubEngineIncrementingNumber: 1,\n\n\t\t...partialContext,\n\t}\n}\n\nexport function copyContext(context: C): C {\n\treturn {\n\t\t...context,\n\t\tparsedRules: { ...context.parsedRules },\n\t\treferencesMaps: {\n\t\t\treferencesIn: new Map(context.referencesMaps.referencesIn),\n\t\t\trulesThatUse: new Map(context.referencesMaps.rulesThatUse),\n\t\t},\n\t}\n}\nexport default function parsePublicodes<\n\tContextNames extends string,\n\tNewRulesNames extends string,\n>(\n\trawRules: RawPublicodes,\n\tpartialContext: Partial> = createContext({}),\n): Pick<\n\tContext,\n\t'parsedRules' | 'nodesTypes' | 'referencesMaps' | 'rulesReplacements'\n> {\n\t// STEP 1 : get the rules as an object\n\n\tif (typeof rawRules === 'string')\n\t\tthrow new PublicodesError(\n\t\t\t'EngineError',\n\t\t\t'Publicodes does not parse yaml rule sets itself anymore. Please provide a parsed js object. E.g. the `eemeli/yaml` package.',\n\t\t\t{},\n\t\t)\n\n\t// let rules = { ...rawRules } // take 7-8ms\n\tconst rules = weakCopyObj(rawRules) // take 1-2ms\n\n\t// STEP 2: Rules parsing\n\tconst context = createContext(partialContext)\n\tconst previousParsedRules = context.parsedRules\n\tcontext.parsedRules = {} as ParsedRules\n\tparseRules(rules, context)\n\n\tlet parsedRules = {} as ParsedRules\n\tfor (const dottedName in previousParsedRules) {\n\t\tparsedRules[dottedName] = previousParsedRules[dottedName]\n\t}\n\tfor (const dottedName in context.parsedRules) {\n\t\tparsedRules[dottedName] = context.parsedRules[dottedName]\n\t}\n\n\t// STEP 3: Disambiguate reference\n\tconst [newRules, referencesMaps] =\n\t\tdisambiguateReferencesAndCollectDependencies(\n\t\t\tparsedRules,\n\t\t\tcontext.parsedRules,\n\t\t\tcontext.referencesMaps,\n\t\t\tcontext.allowOrphanRules,\n\t\t)\n\n\t// STEP 4: Inline replacements\n\tlet rulesReplacements\n\t\t// eslint-disable-next-line prefer-const\n\t;[parsedRules, rulesReplacements] = inlineReplacements<\n\t\tNewRulesNames,\n\t\tContextNames\n\t>({\n\t\tparsedRules,\n\t\tnewRules: newRules as any,\n\t\treferencesMaps,\n\t\tpreviousReplacements: context.rulesReplacements,\n\t})\n\n\t// STEP 5: type inference\n\tconst nodesTypes = inferNodeType(\n\t\tObject.keys(newRules),\n\t\tparsedRules,\n\t\tcontext.nodesTypes,\n\t)\n\n\treturn {\n\t\tparsedRules,\n\t\tnodesTypes,\n\t\treferencesMaps,\n\t\trulesReplacements,\n\t}\n}\n\nfunction disambiguateReferencesAndCollectDependencies<\n\tNewNames extends string,\n\tPreviousNames extends string,\n>(\n\tparsedRules: ParsedRules,\n\tnewRules: ParsedRules,\n\treferencesMaps: ReferencesMaps,\n\tallowOrphanRules: boolean,\n): [\n\tparsedRules: ParsedRules,\n\treferencesMap: ReferencesMaps,\n] {\n\tconst disambiguateReference = makeASTTransformer((node) =>\n\t\tdisambiguateReferenceNode(node, parsedRules),\n\t)\n\tconst disambiguateReferencesAndCollectDependencies = makeASTTransformer(\n\t\t(node) => {\n\t\t\tconst n = disambiguateReferenceNode(node, parsedRules)\n\t\t\tif (n) {\n\t\t\t\tupdateReferencesMapsFromReferenceNode(n, referencesMaps)\n\t\t\t}\n\t\t\treturn n\n\t\t},\n\t)\n\tconst disambiguatedRules = traverseParsedRules((node) => {\n\t\tif (node.nodeKind === 'replacementRule') {\n\t\t\t// The dependencies of replacements will be collected later, during the inlining\n\t\t\treturn disambiguateReference(node)\n\t\t}\n\t\tif (node.nodeKind === 'rule') {\n\t\t\tconst parentUndefined = (node.explanation.parents as any).find(\n\t\t\t\t(n: any) => !(n.dottedName in parsedRules),\n\t\t\t)\n\t\t\tif (!allowOrphanRules && parentUndefined) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'SyntaxError',\n\t\t\t\t\t`La règle parente \"${parentUndefined.dottedName}\" n'existe pas`,\n\t\t\t\t\t{\n\t\t\t\t\t\tdottedName: node.dottedName,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\treturn disambiguateReferencesAndCollectDependencies(node)\n\t}, newRules)\n\treturn [\n\t\tdisambiguatedRules,\n\t\treferencesMaps as ReferencesMaps,\n\t]\n}\n","import { ASTNode, EvaluatedNode } from '.'\n\nexport function computeTraversedVariableBeforeEval(\n\ttraversedVariablesStack: Array> | undefined,\n\tparsedNode: ASTNode,\n\tcachedNode: EvaluatedNode | undefined,\n\tpublicParsedRules: Record,\n\tisTraversedVariablesBoundary: boolean,\n) {\n\tif (traversedVariablesStack === undefined) {\n\t\treturn\n\t}\n\tif (cachedNode !== undefined) {\n\t\tcachedNode.traversedVariables?.forEach(\n\t\t\t(name) => traversedVariablesStack[0]?.add(name),\n\t\t)\n\t\treturn\n\t}\n\n\tif (isTraversedVariablesBoundary) {\n\t\t// Note: we use `unshift` instead of the more usual `push` to reverse the\n\t\t// order of the elements in the stack. This simplify access to the “top\n\t\t// element” with [0], instead of [length - 1]. We could also use the new\n\t\t// method `.at(-1)` but it isn't supported below Node v16.\n\t\ttraversedVariablesStack.unshift(new Set())\n\t}\n\n\tif (\n\t\tparsedNode.nodeKind === 'reference' &&\n\t\tparsedNode.dottedName &&\n\t\tparsedNode.dottedName in publicParsedRules\n\t) {\n\t\ttraversedVariablesStack[0].add(parsedNode.dottedName)\n\t}\n}\n\nexport function isTraversedVariablesBoundary(\n\ttraversedVariablesStack: Array> | undefined,\n\tparsedNode: ASTNode,\n) {\n\treturn (\n\t\t!!traversedVariablesStack &&\n\t\t(traversedVariablesStack.length === 0 || parsedNode.nodeKind === 'rule')\n\t)\n}\n\nexport function computeTraversedVariableAfterEval(\n\ttraversedVariablesStack: Array> | undefined,\n\tevaluatedNode: EvaluatedNode,\n\tisTraversedVariablesBoundary: boolean,\n) {\n\tif (traversedVariablesStack === undefined) {\n\t\treturn\n\t}\n\tif (isTraversedVariablesBoundary) {\n\t\tevaluatedNode.traversedVariables = Array.from(\n\t\t\ttraversedVariablesStack.shift() ?? [],\n\t\t)\n\n\t\tif (traversedVariablesStack.length > 0) {\n\t\t\tevaluatedNode.traversedVariables.forEach((name) => {\n\t\t\t\ttraversedVariablesStack[0].add(name)\n\t\t\t})\n\t\t}\n\t}\n}\n","import { EvaluatedNode } from './index'\nimport { serializeUnit } from './units'\nexport default function serializeEvaluation(\n\tnode: EvaluatedNode,\n): string | undefined {\n\tif (typeof node.nodeValue === 'number') {\n\t\tconst serializedUnit = serializeUnit(node.unit)\n\t\treturn (\n\t\t\t'' +\n\t\t\tnode.nodeValue +\n\t\t\t(serializedUnit ? serializedUnit.replace(/\\s/g, '') : '')\n\t\t)\n\t} else if (typeof node.nodeValue === 'boolean') {\n\t\treturn node.nodeValue ? 'oui' : 'non'\n\t} else if (typeof node.nodeValue === 'string') {\n\t\treturn `'${node.nodeValue}'`\n\t}\n}\n","import { makeASTVisitor } from './AST/index'\nimport { type ASTNode, type EvaluatedNode, type NodeKind } from './AST/types'\nimport { PublicodesError, experimentalRuleWarning } from './error'\nimport { evaluationFunctions } from './evaluationFunctions'\nimport parsePublicodes, {\n\tContext,\n\tRawPublicodes,\n\tcopyContext,\n\tcreateContext,\n} from './parsePublicodes'\nimport { type Rule, type RuleNode } from './rule'\nimport * as utils from './ruleUtils'\nimport {\n\tcomputeTraversedVariableAfterEval,\n\tcomputeTraversedVariableBeforeEval,\n\tisTraversedVariablesBoundary,\n} from './traversedVariables'\n\nconst emptyCache = (): Cache => ({\n\t_meta: {\n\t\tevaluationRuleStack: [],\n\t\tparentRuleStack: [],\n\t},\n\ttraversedVariablesStack: undefined,\n\tnodes: new Map(),\n})\n\ntype Cache = {\n\tinversionFail?: boolean\n\t_meta: {\n\t\tevaluationRuleStack: Array\n\t\tparentRuleStack: Array\n\t\tcurrentContexteSituation?: string\n\t}\n\t/**\n\t * Every time we encounter a reference to a rule in an expression we add it\n\t * to the current Set of traversed variables. Because we evaluate the\n\t * expression graph “top to bottom” (ie. we start by the high-level goal and\n\t * recursively evaluate its dependencies), we need to handle rule\n\t * “boundaries”, so that when we “enter” in the evaluation of a dependency,\n\t * we start with a clear empty set of traversed variables. Then, when we go\n\t * back to the referencer rule, we need to add all to merge the two sets :\n\t * rules already traversed in the current expression and the one from the\n\t * reference.\n\t */\n\ttraversedVariablesStack?: Array>\n\tnodes: Map\n}\n\nexport {\n\treduceAST,\n\tmakeASTTransformer as transformAST,\n\ttraverseASTNode,\n} from './AST/index'\nexport { type Evaluation, type Unit } from './AST/types'\nexport { PublicodesError, isPublicodesError } from './error'\nexport { capitalise0, formatValue } from './format'\nexport { simplifyNodeUnit } from './nodeUnits'\nexport { parseExpression, type ExprAST } from './parseExpression'\nexport { default as serializeEvaluation } from './serializeEvaluation'\nexport { parseUnit, serializeUnit } from './units'\nexport { parsePublicodes, utils }\n\nexport { type ASTNode, type EvaluatedNode, type Rule, type RuleNode }\n\nexport type PublicodesExpression = string | Record | number\n\nexport type Logger = {\n\tlog(message: string): void\n\twarn(message: string): void\n\terror(message: string): void\n}\n\ntype Options = Partial<\n\tPick\n>\n\nexport type EvaluationFunction = (\n\tthis: Engine,\n\tnode: ASTNode & { nodeKind: Kind },\n) => { nodeKind: Kind } & EvaluatedNode\n\nexport type ParsedRules = Record>\n\nexport default class Engine {\n\tbaseContext: Context\n\tcontext: Context\n\tpublicParsedRules: ParsedRules\n\n\tcache: Cache = emptyCache()\n\n\t// The subEngines attribute is used to get an outside reference to the\n\t// `contexte` intermediate calculations. The `contexte` mechanism uses\n\t// `shallowCopy` to instanciate a new engine, and we want to keep a reference\n\t// to it for the documentation.\n\t//\n\t// TODO: A better implementation would to remove the \"runtime\" concept of\n\t// \"subEngines\" and instead duplicate all rules names in the scope of the\n\t// `contexte` as described in\n\t// https://github.com/publicodes/publicodes/discussions/92\n\tsubEngines: Array> = []\n\tsubEngineId: number | undefined\n\n\tconstructor(rules: RawPublicodes = {}, options: Options = {}) {\n\t\tconst initialContext = {\n\t\t\tdottedName: '' as const,\n\t\t\t...options,\n\t\t}\n\t\tthis.baseContext = createContext({\n\t\t\t...initialContext,\n\t\t\t...parsePublicodes(rules, initialContext),\n\t\t})\n\t\tthis.context = this.baseContext\n\n\t\tthis.publicParsedRules = {} as ParsedRules\n\t\tfor (const name in this.baseContext.parsedRules) {\n\t\t\tconst rule = this.baseContext.parsedRules[name]\n\t\t\tif (\n\t\t\t\t!(rule as RuleNode).private &&\n\t\t\t\tutils.isAccessible(this.baseContext.parsedRules, '', name)\n\t\t\t) {\n\t\t\t\tthis.publicParsedRules[name] = rule as RuleNode\n\t\t\t}\n\t\t}\n\t}\n\n\tresetCache() {\n\t\tthis.cache = emptyCache()\n\t}\n\n\tsetSituation(\n\t\tsituation: Partial> = {},\n\t\toptions: { keepPreviousSituation?: boolean } = {},\n\t) {\n\t\tthis.resetCache()\n\n\t\tconst keepPreviousSituation = options.keepPreviousSituation ?? false\n\n\t\tObject.keys(situation).forEach((name) => {\n\t\t\tif (!(name in this.baseContext.parsedRules)) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'EvaluationError',\n\t\t\t\t\t`Erreur lors de la mise à jour de la situation : ${name} n'existe pas dans la base de règle.`,\n\t\t\t\t\t{ dottedName: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (this.baseContext.parsedRules[name].private) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'EvaluationError',\n\t\t\t\t\t`Erreur lors de la mise à jour de la situation : ${name} est une règle privée (il n'est pas possible de modifier une règle privée).`,\n\t\t\t\t\t{ dottedName: name },\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\n\t\t// The situation is implemented as a special sub namespace `$SITUATION`,\n\t\t// present on each non-private rules\n\t\tconst situationToParse = Object.fromEntries(\n\t\t\tObject.entries(situation).map(([nom, value]) => [\n\t\t\t\t`[privé] ${nom} . $SITUATION`,\n\t\t\t\tvalue && typeof value === 'object' && 'nodeKind' in value ?\n\t\t\t\t\t{ valeur: value }\n\t\t\t\t:\tvalue,\n\t\t\t]),\n\t\t)\n\n\t\tconst savedBaseContext = copyContext(this.baseContext)\n\n\t\ttry {\n\t\t\tthis.context = {\n\t\t\t\t...this.baseContext,\n\t\t\t\t...parsePublicodes(\n\t\t\t\t\tsituationToParse as RawPublicodes,\n\t\t\t\t\tkeepPreviousSituation ? this.context : this.baseContext,\n\t\t\t\t),\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.baseContext = savedBaseContext\n\n\t\t\tthrow error\n\t\t}\n\t\tthis.baseContext = savedBaseContext\n\n\t\tObject.keys(situation).forEach((nom) => {\n\t\t\tif (utils.isExperimental(this.context.parsedRules, nom)) {\n\t\t\t\texperimentalRuleWarning(this.baseContext.logger, nom)\n\t\t\t}\n\t\t\tthis.checkExperimentalRule(\n\t\t\t\tthis.context.parsedRules[`${nom} . $SITUATION`],\n\t\t\t)\n\t\t})\n\t\treturn this\n\t}\n\n\tinversionFail(): boolean {\n\t\treturn !!this.cache.inversionFail\n\t}\n\n\tgetRule(dottedName: Name): ParsedRules[Name] {\n\t\tif (!(dottedName in this.baseContext.parsedRules)) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'UnknownRule',\n\t\t\t\t`La règle '${dottedName}' n'existe pas`,\n\t\t\t\t{ dottedName },\n\t\t\t)\n\t\t}\n\n\t\tif (!(dottedName in this.publicParsedRules)) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'PrivateRule',\n\t\t\t\t`La règle ${dottedName} est une règle privée.`,\n\t\t\t\t{ dottedName },\n\t\t\t)\n\t\t}\n\n\t\treturn this.publicParsedRules[dottedName]\n\t}\n\n\tgetParsedRules(): ParsedRules {\n\t\treturn this.publicParsedRules\n\t}\n\n\tevaluate(value: PublicodesExpression): EvaluatedNode {\n\t\tconst cachedNode = this.cache.nodes.get(value)\n\t\tif (cachedNode) {\n\t\t\treturn cachedNode\n\t\t}\n\t\tthis.context = Object.assign(\n\t\t\tthis.context,\n\t\t\tparsePublicodes(\n\t\t\t\t{\n\t\t\t\t\t'[privé] $EVALUATION':\n\t\t\t\t\t\tvalue && typeof value === 'object' && 'nodeKind' in value ?\n\t\t\t\t\t\t\t{ valeur: value }\n\t\t\t\t\t\t:\tvalue,\n\t\t\t\t},\n\t\t\t\tthis.context,\n\t\t\t),\n\t\t)\n\t\tthis.checkExperimentalRule(this.context.parsedRules['$EVALUATION'])\n\t\tthis.cache._meta = emptyCache()._meta\n\n\t\tconst evaluation = this.evaluateNode(\n\t\t\tthis.context.parsedRules['$EVALUATION'].explanation.valeur,\n\t\t)\n\t\tthis.cache.nodes.set(value, evaluation)\n\t\treturn evaluation\n\t}\n\n\tevaluateNode(parsedNode: T): EvaluatedNode & T {\n\t\tconst cachedNode = this.cache.nodes.get(parsedNode)\n\t\tlet traversedVariableBoundary: boolean = false\n\t\tif (this.cache.traversedVariablesStack) {\n\t\t\ttraversedVariableBoundary = isTraversedVariablesBoundary(\n\t\t\t\tthis.cache.traversedVariablesStack,\n\t\t\t\tparsedNode,\n\t\t\t)\n\t\t\tcomputeTraversedVariableBeforeEval(\n\t\t\t\tthis.cache.traversedVariablesStack,\n\t\t\t\tparsedNode,\n\t\t\t\tcachedNode,\n\t\t\t\tthis.publicParsedRules,\n\t\t\t\ttraversedVariableBoundary,\n\t\t\t)\n\t\t}\n\n\t\tif (cachedNode !== undefined) {\n\t\t\treturn cachedNode\n\t\t}\n\n\t\tif (!evaluationFunctions[parsedNode.nodeKind]) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'EvaluationError',\n\t\t\t\t`Unknown \"nodeKind\": ${parsedNode.nodeKind}`,\n\t\t\t\t{ dottedName: '' },\n\t\t\t)\n\t\t}\n\n\t\tconst evaluatedNode = evaluationFunctions[parsedNode.nodeKind].call(\n\t\t\tthis,\n\t\t\tparsedNode,\n\t\t)\n\t\tif (this.cache.traversedVariablesStack) {\n\t\t\tcomputeTraversedVariableAfterEval(\n\t\t\t\tthis.cache.traversedVariablesStack,\n\t\t\t\tevaluatedNode,\n\t\t\t\ttraversedVariableBoundary,\n\t\t\t)\n\t\t}\n\n\t\tthis.cache.nodes.set(parsedNode, evaluatedNode)\n\t\treturn evaluatedNode\n\t}\n\n\t/**\n\t * Shallow Engine instance copy. Keeps references to the original Engine instance attributes.\n\t */\n\tshallowCopy(): Engine {\n\t\tconst newEngine = new Engine()\n\t\tnewEngine.baseContext = copyContext(this.baseContext)\n\t\tnewEngine.context = copyContext(this.context)\n\t\tnewEngine.publicParsedRules = this.publicParsedRules\n\t\tnewEngine.cache = {\n\t\t\t...emptyCache(),\n\n\t\t\tnodes: new Map(this.cache.nodes),\n\t\t}\n\t\treturn newEngine\n\t}\n\n\tprivate checkExperimentalRule = makeASTVisitor((node) => {\n\t\tif (\n\t\t\tnode.nodeKind === 'reference' &&\n\t\t\tutils.isExperimental(this.context.parsedRules, node.dottedName as string)\n\t\t) {\n\t\t\texperimentalRuleWarning(\n\t\t\t\tthis.baseContext.logger,\n\t\t\t\tnode.dottedName as string,\n\t\t\t)\n\t\t}\n\t\treturn 'continue'\n\t})\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA,KAAC,SAAS,MAAM,SAAS;AACrB,UAAI,OAAO,WAAW,YAAY,OAAO,SAAS;AAC9C,eAAO,UAAU,QAAQ;AAAA,MAC7B,OAAO;AACH,aAAK,UAAU,QAAQ;AAAA,MAC3B;AAAA,IACJ,GAAE,SAAM,WAAW;AAEf,eAASA,MAAK,MAAM,SAAS,aAAa;AACtC,aAAK,KAAK,EAAEA,MAAK;AACjB,aAAK,OAAO;AACZ,aAAK,UAAU;AACf,aAAK,cAAc;AACnB,eAAO;AAAA,MACX;AACA,MAAAA,MAAK,YAAY;AAEjB,MAAAA,MAAK,UAAU,WAAW,SAAS,cAAc;AAC7C,YAAI,iBAAkB,OAAO,iBAAiB,cACvB,KAAK,QAAQ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,GAAG,WAAW;AAAA,MAEd,OAAO,IAAI,IAAI,KAAK,MAAM,KAAK;AAAA,IAChC;AACA,WAAO;AAAA,EACR;AAAA,EAEQ,wBAAwB,eAAe,CAAC,SAAS;AACxD,QACC,KAAK,aAAa,eACZ,eAAe,KAAK,QAAQ,aAAa,KAAK,UAAoB,GACvE;AACD;AAAA,QACC,KAAK,YAAY;AAAA,QACjB,KAAK;AAAA,MACN;AAAA,IACD;AACA,WAAO;AAAA,EACR,CAAC;AACF;","names":["Rule","dot","Parser","Grammar","lexer","pad","pad","string","word","Lexer","lexer","node","name","string","formatUnit","factor","convertTable","unitClasses","formatUnit","context","name","evaluate","evaluate","nodeValue","evaluate","date","date","evaluate","evaluate","evaluate","evaluate","evaluate","evaluate","nodeValue","evaluate","evaluate","evaluate","evaluate","unit","moo","arrpush","nearley","disambiguateReference","disambiguateReferencesAndCollectDependencies","isTraversedVariablesBoundary"]} \ No newline at end of file diff --git a/publicodes/package.json b/publicodes/package.json new file mode 100644 index 000000000..e0fb0f271 --- /dev/null +++ b/publicodes/package.json @@ -0,0 +1,58 @@ +{ + "name": "publicodes", + "version": "1.2.1", + "description": "A declarative language for encoding public algorithm", + "types": "dist/index.d.ts", + "type": "module", + "main": "dist/index.cjs", + "module": "dist/index.js", + "exports": { + ".": { + "require": "./dist/index.cjs", + "import": "./dist/index.js", + "types": "./dist/index.d.ts" + } + }, + "repository": { + "type": "git", + "url": "https://github.com/publicodes/publicodes.git", + "directory": "packages/core" + }, + "bugs": "https://github.com/publicodes/publicodes/issues", + "homepage": "https://publi.codes/", + "license": "MIT", + "files": [ + "dist/" + ], + "devDependencies": { + "@rushstack/package-deps-hash": "^3.2.67", + "@types/chai": "^4.3.6", + "@types/mocha": "^9.1.1", + "@types/sinon-chai": "^3.2.10", + "chai": "^4.3.8", + "dedent-js": "1.0.1", + "intl": "^1.2.5", + "mitata": "^0.1.6", + "mocha": "^9.2.2", + "modele-social": "^2.0.0", + "moo": "^0.5.2", + "nearley": "^2.20.1", + "sinon": "^12.0.1", + "sinon-chai": "^3.7.0", + "ts-node": "^10.9.1", + "tsup": "^7.2.0", + "typescript": "^5.2.2", + "yaml": "^2.3.2" + }, + "scripts": { + "codegen": "nearleyc ./src/grammar.ne -o ./src/grammar.codegen.js", + "build": "tsup", + "dev": "tsup --watch", + "test:type": "tsc --noEmit", + "test": "mocha \"./test/**/*.test.{js,ts}\"", + "bench": "tsup --entry.bench ./bench/index.ts && node ./dist/bench.js" + }, + "peerDependencies": { + "@types/mocha": "^9.0.0" + } +} diff --git a/site/package.json b/site/package.json index fee8f6bee..89f3e2d76 100644 --- a/site/package.json +++ b/site/package.json @@ -74,7 +74,7 @@ "markdown-to-jsx": "^7.3.2", "modele-social": "workspace:^", "piano-analytics-js": "^6.13.0", - "publicodes": "^1.2.0", + "publicodes": "file:../publicodes", "react": "^18.2.0", "react-aria": "^3.24.0", "react-day-picker": "^8.8.2", diff --git a/yarn.lock b/yarn.lock index b59675151..40317e5be 100644 --- a/yarn.lock +++ b/yarn.lock @@ -26926,6 +26926,24 @@ __metadata: languageName: node linkType: hard +"publicodes@file:../publicodes::locator=site%40workspace%3Asite": + version: 1.2.1 + resolution: "publicodes@file:../publicodes#../publicodes::hash=7d6a6c&locator=site%40workspace%3Asite" + peerDependencies: + "@types/mocha": ^9.0.0 + checksum: 3785b3864b10ef292c3a23d7b1a8358a73dd3b423e8e96c3d357e8e99a0a674ca634c34a606eec3ed252a1ebc82d61d08fa51c876527a91f6beb6bc71f2ede80 + languageName: node + linkType: hard + +"publicodes@file:./publicodes::locator=root%40workspace%3A.": + version: 1.2.1 + resolution: "publicodes@file:./publicodes#./publicodes::hash=7d6a6c&locator=root%40workspace%3A." + peerDependencies: + "@types/mocha": ^9.0.0 + checksum: 3785b3864b10ef292c3a23d7b1a8358a73dd3b423e8e96c3d357e8e99a0a674ca634c34a606eec3ed252a1ebc82d61d08fa51c876527a91f6beb6bc71f2ede80 + languageName: node + linkType: hard + "publicodes@npm:^1.1.1, publicodes@npm:^1.2.0": version: 1.2.0 resolution: "publicodes@npm:1.2.0" @@ -28642,7 +28660,7 @@ __metadata: eslint-plugin-vitest: ^0.3.22 optics-ts: ^2.4.1 prettier: ^3.0.3 - publicodes: ^1.2.0 + publicodes: "file:./publicodes" rimraf: ^5.0.1 languageName: unknown linkType: soft @@ -29272,7 +29290,7 @@ __metadata: modele-social: "workspace:^" netlify-cli: ^17.10.1 piano-analytics-js: ^6.13.0 - publicodes: ^1.2.0 + publicodes: "file:../publicodes" react: ^18.2.0 react-aria: ^3.24.0 react-day-picker: ^8.8.2