@formancy/report-runtime 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["refused","extreme"],"sources":["../src/document.ts","../src/input.ts","../src/values.ts","../src/data-errors.ts","../src/data.ts","../src/parameters.ts","../src/decimal.ts","../src/format.ts","../src/sort-group.ts","../src/evaluate.ts","../src/resolve-errors.ts","../src/render-context.ts","../src/images.ts","../src/inlines.ts","../src/styles.ts","../src/lower-table.ts","../src/lower.ts","../src/report-check.ts","../src/totals.ts","../src/resolve.ts"],"sourcesContent":["/**\n * The resolved document: a report after the runtime has read its data,\n * evaluated its expressions and conditions, grouped, sorted, totalled and\n * formatted it, with nothing left to decide but where each line falls on a\n * page. The runtime lowers a report definition to it, and\n * `@formancy/report-render-pdf` draws it\n * ([0005](../../../docs/decisions/0005-pdfmake-renders-reports-behind-one-adapter.md)).\n *\n * It names no engine and holds no engine's options. It is plain data, every\n * part of it serialisable but an image's bytes, which are a `Uint8Array`.\n * Every length is in PDF points. Every value is already the string that\n * prints: an exact number stays a string all the way to the page, and an\n * engine never formats, rounds or converts one.\n *\n * It holds everything version 0 of the definition can print: the columns,\n * sections, rule weights and colours, fonts and colours, image fits and\n * group headers across a table that\n * [0007](../../../docs/decisions/0007-a-report-definition-is-its-own-versioned-document.md)\n * found the renderer trial's document without. Its vocabularies -- font\n * tokens, alignments, fits, page sizes, colours -- are report-spec's own\n * types, so the definition and the document cannot name different ones. An\n * absent style property is the renderer's default, as report-spec's print\n * styles say.\n *\n * Where a block may stand -- a table or a page break never inside columns or\n * a keep-together block, page fields only in the page regions -- is the\n * definition's to validate and the renderer's to refuse. These types do not\n * hold it.\n */\nimport type { Alignment, AssetMediaType, Border, FontFamily, ImageFit, Margins, Orientation, PageSizeName, Width } from '@formancy/report-spec'\n\n/**\n * A run of text, or a number only the engine knows when it lays out the\n * page, which prints only in the page header and footer. A run in bold\n * inside a paragraph that is not was the trial's; version 0 of the\n * definition sets weight per paragraph.\n */\nexport type Inline = { readonly text: string; readonly bold?: boolean } | { readonly field: 'pageNumber' } | { readonly field: 'pageCount' }\n\n/**\n * How text prints: report-spec's `PrintStyle`, resolved. The runtime lays\n * each conditional style that held over the base one, a later rule's\n * property winning, and hands the engine the result; an engine never merges\n * styles itself.\n */\nexport interface TextStyle {\n /** A font token, never a font's name: the renderer maps each to a font it embeds. */\n readonly font?: FontFamily\n /** Points. */\n readonly size?: number\n readonly bold?: boolean\n readonly italic?: boolean\n /** Lower-case `#rrggbb`. */\n readonly color?: string\n readonly align?: Alignment\n}\n\n/** Text that wraps at the width it is given. A word wider than that width still prints whole, broken across lines. */\nexport interface Paragraph {\n readonly kind: 'paragraph'\n readonly runs: readonly Inline[]\n readonly style?: TextStyle\n /** Never the last thing on a page when something follows it: a heading moves with what it heads. */\n readonly keepWithNext?: boolean\n}\n\nexport interface TableColumn {\n /** Points, or `'fill'` for an equal share of the width the fixed columns leave. */\n readonly width: Width\n /** How each cell in the column is aligned, unless the cell's style says otherwise. */\n readonly align: Alignment\n}\n\n/**\n * One row of a table, its cells in column order, each aligned to the top of\n * the row, so that a row's first line holds its first cell.\n *\n * A `groupHeader` is never the last row on a page: it moves to the next page\n * with the row it heads. A `detail` row may be taller than a page; the engine\n * then continues it on the next one, or refuses with `content-too-large`, and\n * never clips it.\n */\nexport interface TableRow {\n readonly kind: 'detail' | 'groupHeader' | 'groupFooter' | 'total'\n /** One per column; exactly one when the row runs `across` the table. */\n readonly cells: readonly string[]\n /**\n * The row is one cell across every column: a group header, which version\n * 0 prints as one line across the table rather than in its first column.\n */\n readonly across?: true\n /** Every cell's style; absent, the renderer's for a row of its kind. */\n readonly style?: TextStyle\n /**\n * A cell's own style, one entry per cell, `null` where the cell has the\n * row's. A cell's own is its whole style, the row's already laid under it\n * by the runtime, never merged again by the engine: a column's print\n * style, or one of its conditional styles that held for this row.\n */\n readonly cellStyles?: readonly (TextStyle | null)[]\n}\n\nexport interface Table {\n readonly kind: 'table'\n readonly id: string\n readonly columns: readonly TableColumn[]\n /** The one header row, repeated at the top of every page the table spans. */\n readonly header: readonly string[]\n /** The header row's style; absent, the renderer's. */\n readonly headerStyle?: TextStyle\n readonly rows: readonly TableRow[]\n /** Printed under the header, in place of detail rows, when there are none. Group and total rows still print. */\n readonly emptyText: string\n}\n\n/**\n * The most bytes one image asset may have: 20 MB, the renderer trial's\n * limit, the plan's \"enforced limits\" made a number to test. The runtime\n * refuses an answer past it before copying it, and the renderer before\n * decoding it, from this one constant.\n */\nexport const MAX_ASSET_BYTES = 20 * 1024 * 1024\n\n/**\n * An approved asset's bytes, already fetched by the host: an engine never\n * resolves an address. Every image that draws the same asset shares one\n * object, which an engine embeds once.\n */\nexport interface ImageAsset {\n readonly id: string\n readonly mediaType: AssetMediaType\n readonly bytes: Uint8Array\n}\n\n/**\n * An image in a box of fixed size, which the layout reserves whole whatever\n * the image holds. `contain` draws all of the image at its own proportions,\n * as large as the box allows; `cover` fills the box at the image's\n * proportions and crops what falls outside it. Either way the image is\n * centred in its box, as CSS's `object-fit` centres one by default, and\n * nothing of it is drawn outside the box. For an image of the box's own\n * proportions the two are the same drawing. Bytes the engine cannot decode\n * are refused as `invalid-asset`, naming the asset.\n */\nexport interface Image {\n readonly kind: 'image'\n readonly asset: ImageAsset\n readonly width: number\n readonly height: number\n readonly fit: ImageFit\n}\n\n/** A horizontal line across the width it is given: the printable area's, or its column's. */\nexport interface Rule {\n readonly kind: 'rule'\n /** Points. */\n readonly thickness: number\n /** Lower-case `#rrggbb`. */\n readonly color?: string\n}\n\n/** A box of fixed size: filled, outlined, both, or neither, when it is only space. */\nexport interface Rectangle {\n readonly kind: 'rectangle'\n readonly width: number\n readonly height: number\n /** Lower-case `#rrggbb`. */\n readonly fill?: string\n /** The outline's colour, lower-case `#rrggbb`, drawn at the renderer's weight. */\n readonly stroke?: string\n}\n\nexport interface Spacer {\n readonly kind: 'spacer'\n readonly height: number\n}\n\n/** Starts a new page. */\nexport interface PageBreak {\n readonly kind: 'pageBreak'\n}\n\n/**\n * Blocks that are printed on one page, such as a report's summary. When they\n * do not fit in what is left of the page they move whole to the next one;\n * when they are taller than a whole page the engine refuses with\n * `content-too-large` rather than splitting them.\n */\nexport interface KeepTogether {\n readonly kind: 'keepTogether'\n readonly blocks: readonly Block[]\n}\n\n/** One column of a columns block, as distinct from a table's column. */\nexport interface ColumnSlot {\n /** Points, or `'fill'` for an equal share of the width the fixed columns leave. */\n readonly width: Width\n readonly blocks: readonly Block[]\n}\n\n/**\n * Two to four columns side by side, each laying its blocks out down its own\n * width, with no gap between them but what their widths leave. The block is\n * as tall as its tallest column. When it does not fit on what is left of the\n * page, the engine continues its columns on the next page or refuses with\n * `content-too-large`, and never clips them.\n */\nexport interface Columns {\n readonly kind: 'columns'\n readonly columns: readonly ColumnSlot[]\n}\n\n/**\n * Blocks in a frame: the border drawn around them, the fill behind them, and\n * the padding between the border and them. A section adds no layout rule:\n * its blocks flow as though they stood in its place, across pages too, and\n * the frame is drawn around the part on each page. Without a border, a fill\n * or padding it is its blocks and nothing more.\n */\nexport interface Section {\n readonly kind: 'section'\n readonly blocks: readonly Block[]\n readonly border?: Border\n /** Lower-case `#rrggbb`. */\n readonly fill?: string\n /** Points, on every side. */\n readonly padding?: number\n}\n\nexport type Block = Paragraph | Table | Image | Rule | Rectangle | Spacer | PageBreak | KeepTogether | Columns | Section\n\nexport interface PageSetup {\n readonly size: PageSizeName\n readonly orientation: Orientation\n /**\n * From each edge of the paper to the printable area. Everything prints\n * inside it: the page header at its top, the page footer at its bottom, and\n * the body between them.\n */\n readonly margins: Margins\n}\n\nexport interface ResolvedDocument {\n readonly info: {\n readonly title: string\n /** An ISO instant, fixed by the caller, so that the same document renders to the same PDF. */\n readonly creationDate: string\n }\n readonly page: PageSetup\n /** Repeated on every page, at the top of the printable area. */\n readonly pageHeader: readonly Block[]\n /** Repeated on every page, at the bottom of the printable area. */\n readonly pageFooter: readonly Block[]\n /**\n * What prints once, in order. A definition's report header is simply the\n * start of the body, and its summary the end: each prints once, before or\n * after everything else, so neither needs a block kind of its own. A\n * summary that must stay on one page is a keep-together block.\n */\n readonly body: readonly Block[]\n}\n\nexport const REFUSAL_CODES = ['too-many-pages', 'content-too-large', 'invalid-asset', 'cancelled', 'unsupported'] as const\nexport type RefusalCode = (typeof REFUSAL_CODES)[number]\n\n/**\n * Why an engine produced no PDF. An engine refuses rather than truncates: a\n * report that cannot be printed whole is not printed, and the caller is told\n * what stopped it. `subject` names the asset, table or block concerned, when\n * the refusal is about one.\n */\nexport class RenderRefusal extends Error {\n readonly code: RefusalCode\n readonly subject: string | undefined\n\n constructor(code: RefusalCode, message: string, subject?: string) {\n super(message)\n this.name = 'RenderRefusal'\n this.code = code\n this.subject = subject\n }\n}\n","/**\n * Reading the data a host hands over, once, without running any of it.\n *\n * Datasets and parameters are untrusted input, even from the host's own\n * provider. A JSON-parsed object is plain data, but a host may hand over\n * anything JavaScript can hold: a getter that answers differently each time\n * it is asked, a proxy whose traps throw, a sparse array. So every object\n * and list is read through its property descriptors into a copy, as\n * report-spec reads a report: a getter is refused unrun, an exception from a\n * trap becomes a refusal, and what is checked afterwards is the copy, which\n * cannot change under the check.\n */\n\n/** Why a container could not be read at all. */\nexport type ContainerCode = 'wrong-type' | 'not-data' | 'too-many'\n\n/** A property of a record that could not be read, with the key it has when it has a string one. */\nexport interface PropertyProblem {\n readonly key?: string\n readonly message: string\n}\n\nexport type RecordRead =\n | { readonly ok: true; readonly entries: ReadonlyMap<string, unknown>; readonly problems: readonly PropertyProblem[] }\n | { readonly ok: false; readonly code: Exclude<ContainerCode, 'too-many'>; readonly message: string }\n\n/** An item of a list that could not be read, by its index. */\nexport interface ItemProblem {\n readonly index: number\n readonly message: string\n}\n\n/** Stands in a read list where an item could not be read; its problem says why. */\nexport const UNREADABLE: unique symbol = Symbol('unreadable')\n\nexport type ListRead =\n | { readonly ok: true; readonly items: readonly unknown[]; readonly problems: readonly ItemProblem[] }\n | { readonly ok: false; readonly code: ContainerCode; readonly message: string }\n\nconst ACCESSOR = 'a getter or setter is not data, and is not run'\n\n/** Whether `value` is a plain object: made by a literal, JSON.parse or Object.create(null), not a class instance, an array or a Map. */\nfunction isPlainObject(value: unknown): value is object {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const prototype: unknown = Object.getPrototypeOf(value)\n return prototype === Object.prototype || prototype === null\n}\n\n/**\n * A plain object's own enumerable string-keyed data properties, each read\n * once, in the object's own order. A property that is not data -- a getter,\n * a symbol key, a hidden property -- is a problem of the record and left\n * out; anything else about the object refuses it whole.\n */\nexport function readRecord(value: unknown): RecordRead {\n try {\n if (!isPlainObject(value)) return { ok: false, code: 'wrong-type', message: 'expected an object of named values' }\n const entries = new Map<string, unknown>()\n const problems: PropertyProblem[] = []\n let symbols = false\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key === 'symbol') {\n symbols = true\n continue\n }\n const descriptor = Object.getOwnPropertyDescriptor(value, key) as PropertyDescriptor\n if (!('value' in descriptor)) problems.push({ key, message: ACCESSOR })\n else if (descriptor.enumerable !== true) problems.push({ key, message: 'a property that is not enumerable is not data' })\n else entries.set(key, descriptor.value)\n }\n if (symbols) problems.push({ message: 'a property named by a symbol is not data' })\n return { ok: true, entries, problems }\n } catch {\n return { ok: false, code: 'not-data', message: 'an object that throws when read is not data' }\n }\n}\n\n/**\n * A list's items, each read once, after its length is checked against\n * `max`: a list longer than that is refused before any item is read. A hole\n * or a getter is a problem at its index, and `UNREADABLE` stands in its\n * place.\n */\nexport function readList(value: unknown, max: number): ListRead {\n try {\n if (!Array.isArray(value)) return { ok: false, code: 'wrong-type', message: 'expected a list' }\n // A proxy describes its length as it likes: an object whose valueOf\n // answers the bound one number and the loop another, or Infinity. Only a\n // whole number is a length, and it is compared and looped to as read.\n const length: unknown = (Object.getOwnPropertyDescriptor(value, 'length') as PropertyDescriptor).value\n if (typeof length !== 'number' || !Number.isSafeInteger(length) || length < 0) return { ok: false, code: 'not-data', message: 'a list whose length is not a whole number is not data' }\n if (length > max) return { ok: false, code: 'too-many', message: `a list of ${length} items, more than the ${max} allowed` }\n const items: unknown[] = []\n const problems: ItemProblem[] = []\n for (let index = 0; index < length; index++) {\n const descriptor = Object.getOwnPropertyDescriptor(value, index)\n if (descriptor !== undefined && 'value' in descriptor) {\n items.push(descriptor.value)\n continue\n }\n items.push(UNREADABLE)\n problems.push({ index, message: descriptor === undefined ? 'a hole in a list is not data' : ACCESSOR })\n }\n return { ok: true, items, problems }\n } catch {\n return { ok: false, code: 'not-data', message: 'a list that throws when read is not data' }\n }\n}\n","/**\n * One value read as the type a dataset field or a parameter declares, and\n * held as the runtime computes with it.\n *\n * Exact values travel as strings with their type and are never converted\n * through a JavaScript number (0007; formancy.ai-data 0008). So:\n * - an integer is a string of its digits, or a JSON number only where a\n * number is still exact, below 2^53; it is held as a `bigint`;\n * - a decimal is only ever the string of its exact digits, held as\n * `@formancy/expressions`' `Decimal` with its scale;\n * - a date and a local date-time have no zone and are held as their ISO\n * strings, which sort in calendar order;\n * - an instant has a zone, and is held in UTC, so that two spellings of one\n * moment are one value;\n * - an image is an approved asset's id and digest, never an address.\n *\n * Each type has one spelling of each value, the one report-spec writes a\n * parameter default in. Its patterns are restated here because report-spec\n * does not export them; `values.test.ts` puts candidates to both, so the two\n * cannot drift apart unnoticed. A refusal says what was expected and never\n * repeats what was found: the data is the customer's.\n */\nimport { DEFAULT_VALUE_LIMITS, Decimal, decimalFromString } from '@formancy/expressions'\nimport { isIdentifier, MAX_SCALE } from '@formancy/report-spec'\nimport type { FieldType } from '@formancy/report-spec'\nimport { readRecord } from './input.js'\n\n/**\n * The longest string a value may be, in UTF-16 code units. Not chosen: it is\n * the longest string `@formancy/expressions` lets an expression be handed\n * (`DEFAULT_VALUE_LIMITS.maxStringLength`), so every string the data check\n * accepts is one an expression can read, and a longer one is refused where\n * the check can name its field rather than when an expression first reads\n * it.\n */\nexport const MAX_STRING_LENGTH = DEFAULT_VALUE_LIMITS.maxStringLength\n\nexport const VALUE_ERROR_CODES = [\n /** A value of another JavaScript type than the field's: a number for a string, a bigint, a Date. */\n 'wrong-type',\n 'string-too-long',\n /** A string with half a surrogate pair, which is not text and would print as something nobody wrote. */\n 'ill-formed-string',\n /** Not an integer's one spelling, or a number with a fraction. */\n 'invalid-integer',\n /** A JSON number past 2^53, which has already lost digits. */\n 'unsafe-integer',\n /** A decimal as a JSON number, which has already lost digits. */\n 'decimal-as-number',\n 'invalid-decimal',\n /** A decimal with more places than its field declares, or than a decimal holds. */\n 'decimal-scale',\n 'invalid-date',\n 'invalid-datetime',\n 'invalid-instant',\n 'invalid-image',\n] as const\nexport type ValueErrorCode = (typeof VALUE_ERROR_CODES)[number]\n\n/** An image field's value: an approved asset the host resolves to bytes by its id, pinned by its digest. */\nexport interface ImageValue {\n /** An identifier, as report-spec writes an asset's id. */\n readonly asset: string\n /** `sha256:` and 64 lower-case hex digits. */\n readonly digest: string\n}\n\n/** What a value of each field type is held as once read. */\nexport interface FieldValues {\n readonly string: string\n readonly integer: bigint\n readonly decimal: Decimal\n readonly boolean: boolean\n /** `YYYY-MM-DD`. */\n readonly date: string\n /** `YYYY-MM-DDTHH:mm:ss`, and a fraction of a second without trailing zeros when it has one. */\n readonly datetime: string\n /** As a date-time, in UTC, with a final `Z`. */\n readonly instant: string\n readonly image: ImageValue\n}\n\n/** A value of any field type, read. Null is not one: whether a field may be null is its contract's, and checked before its type. */\nexport type CheckedValue = FieldValues[FieldType]\n\nexport type ValueRead<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly code: ValueErrorCode; readonly message: string }\n\nfunction refused(code: ValueErrorCode, message: string): { readonly ok: false; readonly code: ValueErrorCode; readonly message: string } {\n return { ok: false, code, message }\n}\n\n/** What `raw` is, for a message: its JavaScript type, never its content. */\nfunction kindOf(raw: unknown): string {\n if (raw === null) return 'null'\n if (Array.isArray(raw)) return 'a list'\n if (raw instanceof Date) return 'a Date'\n if (raw instanceof Decimal) return 'a Decimal'\n const type = typeof raw\n return type === 'object' ? 'an object' : `a ${type}`\n}\n\nfunction wrongType(expected: string, raw: unknown): { readonly ok: false; readonly code: ValueErrorCode; readonly message: string } {\n return refused('wrong-type', `expected ${expected}, found ${kindOf(raw)}`)\n}\n\n/** An exact integer: no sign but '-', no leading zero, no '-0' (report-spec's `INTEGER`). */\nconst INTEGER = /^(?:0|-?[1-9]\\d*)$/\n\n/** An exact decimal: an integer, optionally a point and at least one digit; no negative zero (report-spec's `DECIMAL`). */\nconst DECIMAL = /^(?:-?[1-9]\\d*(?:\\.\\d+)?|0(?:\\.\\d+)?|-0\\.\\d*[1-9]\\d*)$/\n\n/** An asset's content digest: SHA-256, lower-case hex (report-spec's `DIGEST`). */\nconst DIGEST = /^sha256:[0-9a-f]{64}$/\n\n/** Half a surrogate pair: a high one not followed by a low one, or a low one not preceded by a high one. */\nconst LONE_SURROGATE = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/\n\nconst DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/\nconst DATETIME = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,9}))?$/\n/** An ISO 8601 date-time with its zone, as `@formancy/expressions` binds a timestamp: seconds optional, a fraction to the nanosecond. */\nconst INSTANT = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{1,9}))?)?(?:Z|([+-])(\\d{2}):(\\d{2}))$/\n\n/**\n * Whether year, month and day name a day on the proleptic Gregorian\n * calendar from the year 1: 2024-02-29 does, 2026-02-29 does not, and no day\n * of the year 0000 does, which Intl shows as the year 1 without its era\n * (report-spec's `isCalendarDate`).\n */\nfunction isCalendarDay(year: number, month: number, day: number): boolean {\n if (year < 1 || month < 1 || month > 12 || day < 1) return false\n const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0\n const days = month === 2 ? (leap ? 29 : 28) : [4, 6, 9, 11].includes(month) ? 30 : 31\n return day <= days\n}\n\n/** Whether hours, minutes and seconds name a time on a clock that has no leap second, as Date has none. */\nfunction isClockTime(hour: number, minute: number, second: number): boolean {\n return hour <= 23 && minute <= 59 && second <= 59\n}\n\n/**\n * `fraction` without trailing zeros, with its point, or nothing when nothing\n * is left. A loop rather than /0+$/: the instant pattern bounds the fraction\n * to nine digits, but an anchored repetition is quadratic on many zeros\n * before a non-zero (CodeQL's js/polynomial-redos), and this needs no bound\n * to stay linear.\n */\nfunction fractionOf(fraction: string | undefined): string {\n if (fraction === undefined) return ''\n let end = fraction.length\n while (end > 0 && fraction[end - 1] === '0') end -= 1\n return end === 0 ? '' : `.${fraction.slice(0, end)}`\n}\n\nfunction readString(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('a string', raw)\n if (raw.length > MAX_STRING_LENGTH) return refused('string-too-long', `a string of ${raw.length} characters, more than the ${MAX_STRING_LENGTH} a value may have`)\n if (LONE_SURROGATE.test(raw)) return refused('ill-formed-string', 'a string with half a surrogate pair is not text, and would print a character nobody wrote')\n return { ok: true, value: raw }\n}\n\nfunction readInteger(raw: unknown): ValueRead<bigint> {\n if (typeof raw === 'string') {\n if (raw.length <= MAX_STRING_LENGTH && INTEGER.test(raw)) return { ok: true, value: BigInt(raw) }\n return refused('invalid-integer', 'an integer is written as its digits, with \"-\" for a negative one, no leading zero and no \"-0\"')\n }\n if (typeof raw === 'number') {\n if (Number.isSafeInteger(raw)) return { ok: true, value: BigInt(raw) }\n if (Number.isInteger(raw)) return refused('unsafe-integer', 'a number past 2^53 has already lost digits; send the integer as a string of its digits')\n return refused('invalid-integer', 'expected a whole number')\n }\n return wrongType('an integer, written as a string of its digits', raw)\n}\n\nfunction readDecimal(raw: unknown, scale: number | undefined): ValueRead<Decimal> {\n if (typeof raw === 'number') return refused('decimal-as-number', 'a decimal is sent as a string of its exact digits, never as a number: floats lose digits')\n if (typeof raw !== 'string') return wrongType('a decimal, written as a string of its exact digits', raw)\n if (raw.length > MAX_STRING_LENGTH || !DECIMAL.test(raw)) {\n return refused('invalid-decimal', 'a decimal is written as its digits, with \".\" before any places, \"-\" for a negative one, no leading zero and no \"-0\"')\n }\n const places = raw.length - raw.indexOf('.') - 1\n const allowed = scale ?? MAX_SCALE\n if (raw.includes('.') && places > allowed) {\n const whose = scale === undefined ? 'a decimal holds' : 'the field declares'\n return refused('decimal-scale', `a decimal with ${places} places, more than the ${allowed} ${whose}; rounding it here would print another number than the source holds`)\n }\n return { ok: true, value: decimalFromString(raw) }\n}\n\nfunction readBoolean(raw: unknown): ValueRead<boolean> {\n return typeof raw === 'boolean' ? { ok: true, value: raw } : wrongType('true or false', raw)\n}\n\nfunction readDate(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('a date, written YYYY-MM-DD', raw)\n const match = DATE.exec(raw)\n if (match !== null && isCalendarDay(Number(match[1]), Number(match[2]), Number(match[3]))) return { ok: true, value: raw }\n return refused('invalid-date', 'a date is a day on the calendar, written YYYY-MM-DD')\n}\n\nfunction readDatetime(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('a date and time, written YYYY-MM-DDTHH:mm:ss', raw)\n const match = DATETIME.exec(raw)\n const [year, month, day, hour, minute, second] = match === null ? [] : match.slice(1, 7).map(Number)\n if (match === null || !isCalendarDay(year as number, month as number, day as number) || !isClockTime(hour as number, minute as number, second as number)) {\n return refused('invalid-datetime', 'a date and time without a zone is written YYYY-MM-DDTHH:mm:ss, with a fraction of a second of up to nine digits if it has one')\n }\n return { ok: true, value: `${raw.slice(0, 19)}${fractionOf(match[7])}` }\n}\n\nconst pad = (value: number, width: number): string => String(value).padStart(width, '0')\n\n/**\n * `text`, an ISO 8601 date-time with its zone, as the moment it names in\n * UTC: `YYYY-MM-DDTHH:mm:ssZ`, with the fraction of a second it has, less\n * trailing zeros. Undefined when it is not one, or the moment falls outside\n * the years 0001 to 9999 in UTC: past them a year has no four-digit\n * spelling, and Intl shows the year 0 as the year 1.\n *\n * What an expression gives back for a timestamp is RFC 3339 in UTC, so this\n * also makes an expression's instant comparable with the data's.\n */\nexport function canonicalInstant(text: string): string | undefined {\n const match = INSTANT.exec(text)\n if (match === null) return undefined\n const [year, month, day, hour, minute, second = 0] = match.slice(1, 7).map((part) => (part === undefined ? undefined : Number(part))) as number[]\n const offsetHours = match[9] === undefined ? 0 : Number(match[9])\n const offsetMinutes = match[10] === undefined ? 0 : Number(match[10])\n if (!isCalendarDay(year as number, month as number, day as number) || !isClockTime(hour as number, minute as number, second) || offsetHours > 23 || offsetMinutes > 59) return undefined\n // Date.UTC reads the years 0 to 99 as 1900 to 1999; setUTCFullYear does not.\n const moment = new Date(0)\n moment.setUTCFullYear(year as number, (month as number) - 1, day as number)\n moment.setUTCHours(hour as number, minute as number, second, 0)\n const offset = (match[8] === '-' ? -1 : 1) * (offsetHours * 60 + offsetMinutes)\n moment.setTime(moment.getTime() - offset * 60_000)\n const utcYear = moment.getUTCFullYear()\n if (utcYear < 1 || utcYear > 9999) return undefined\n const date = `${pad(utcYear, 4)}-${pad(moment.getUTCMonth() + 1, 2)}-${pad(moment.getUTCDate(), 2)}`\n const time = `${pad(moment.getUTCHours(), 2)}:${pad(moment.getUTCMinutes(), 2)}:${pad(moment.getUTCSeconds(), 2)}`\n return `${date}T${time}${fractionOf(match[7])}Z`\n}\n\nfunction readInstant(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('an instant, written as an ISO 8601 date-time with its zone', raw)\n const value = canonicalInstant(raw)\n if (value !== undefined) return { ok: true, value }\n return refused('invalid-instant', 'an instant is an ISO 8601 date-time with its zone, Z or an offset such as +01:00, between the years 0001 and 9999 in UTC')\n}\n\nconst IMAGE_SHAPE = 'an image is an approved asset, { \"asset\": its id, \"digest\": \"sha256:\" and 64 lower-case hex digits }, never an address'\n\nfunction readImage(raw: unknown): ValueRead<ImageValue> {\n const read = readRecord(raw)\n if (!read.ok || read.problems.length > 0) return refused('invalid-image', IMAGE_SHAPE)\n const { entries } = read\n const asset = entries.get('asset')\n const digest = entries.get('digest')\n if (entries.size !== 2 || !isIdentifier(asset) || typeof digest !== 'string' || !DIGEST.test(digest)) return refused('invalid-image', IMAGE_SHAPE)\n return { ok: true, value: Object.freeze({ asset, digest }) }\n}\n\n/**\n * `raw` read as a value of `type`, or why it is not one. `scale` is a\n * decimal field's declared scale: a decimal with more places is refused.\n * Null is refused as every type's wrong type; the caller decides first\n * whether the field may hold it.\n */\nexport function readValue<T extends FieldType>(type: T, raw: unknown, scale?: number): ValueRead<FieldValues[T]> {\n const read = READERS[type] as (raw: unknown, scale: number | undefined) => ValueRead<FieldValues[T]>\n return read(raw, scale)\n}\n\nconst READERS: { readonly [T in FieldType]: (raw: unknown, scale: number | undefined) => ValueRead<FieldValues[T]> } = {\n string: readString,\n integer: readInteger,\n decimal: readDecimal,\n boolean: readBoolean,\n date: readDate,\n datetime: readDatetime,\n instant: readInstant,\n image: readImage,\n}\n","/**\n * What the runtime can say is wrong with the data and parameters it is\n * given, as stable codes, and the bounded list one check collects.\n *\n * A code is for a program and the message for a person. An error's path is\n * a JSON Pointer into what was given -- `/detail/17/amount` -- and neither\n * the path nor the message ever holds a value from it: the data is the\n * customer's, and an error is the kind of thing that ends up in a log.\n */\nimport { MAX_ERRORS, MAX_KEY_LENGTH } from '@formancy/report-spec'\nimport { VALUE_ERROR_CODES } from './values.js'\n\nexport const DATA_ERROR_CODES = [\n ...VALUE_ERROR_CODES,\n /** Something JavaScript can hold and JSON cannot: a getter, a hole, a symbol key, an object that throws when read. */\n 'not-data',\n /** A part of the data envelope the runtime does not know. */\n 'unknown-property',\n /** A dataset the report declares and the data lacks. */\n 'missing-dataset',\n /** Data for a dataset the report does not declare. */\n 'undeclared-dataset',\n /** A field the contract declares and a record lacks, which is not the same as null. */\n 'missing-field',\n /** Null where the contract or the parameter does not allow it. */\n 'unexpected-null',\n /** A field the contract does not declare: a report never carries what it does not print. */\n 'undeclared-field',\n /** More detail rows than `MAX_DETAIL_ROWS`. */\n 'too-many-rows',\n /** Data the provider says is incomplete, in a final render. */\n 'incomplete',\n /** A captured count other than the rows given, or more than the cap. */\n 'completeness-mismatch',\n 'invalid-completeness',\n 'invalid-consistency',\n /** A required parameter with no value and no default. */\n 'missing-parameter',\n /** A value for a parameter the report does not declare. */\n 'undeclared-parameter',\n /** More errors were found than are listed. */\n 'too-many-errors',\n] as const\nexport type DataErrorCode = (typeof DATA_ERROR_CODES)[number]\n\nexport interface DataError {\n /** A JSON Pointer into the data or the parameter values: `/detail/17/amount`, `/from`. */\n readonly path: string\n readonly code: DataErrorCode\n /** For a person: what was expected, never what was found. */\n readonly message: string\n}\n\n/**\n * Errors listed per check: as many as report-spec lists for a report, for\n * the same reasons. Past it, one `too-many-errors` entry says the list was\n * cut short, and the check stops reading.\n */\nexport const MAX_DATA_ERRORS = MAX_ERRORS\n\n/** The errors one check has found, bounded. */\nexport class DataFindings {\n readonly #errors: DataError[] = []\n #overflowed = false\n\n report(path: string, code: DataErrorCode, message: string): void {\n if (this.#errors.length < MAX_DATA_ERRORS) this.#errors.push({ path, code, message })\n else this.#overflowed = true\n }\n\n /** Whether the list is cut short: once it is, nothing more is worth reading. */\n get full(): boolean {\n return this.#overflowed\n }\n\n get empty(): boolean {\n return this.#errors.length === 0\n }\n\n /** The errors in the order found, and a last one when more were found than listed. */\n errors(): DataError[] {\n const errors = [...this.#errors]\n if (this.#overflowed) errors.push({ path: '', code: 'too-many-errors', message: `more than ${MAX_DATA_ERRORS} errors were found; the first ${MAX_DATA_ERRORS} are listed` })\n return errors\n }\n}\n\n/** `path` extended by one key or index, escaped as RFC 6901 says. */\nexport function at(path: string, key: string | number): string {\n if (typeof key === 'number') return `${path}/${key}`\n return `${path}/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`\n}\n\n/** Whether `key` is longer than any id the format allows: such a key is never one the report declares, and never goes into a path or a message. */\nexport function isLongKey(key: string): boolean {\n return key.length > MAX_KEY_LENGTH\n}\n\n/** The path to `key` in the object at `path`; the object's own path for a long key. */\nexport function keyAt(path: string, key: string): string {\n return isLongKey(key) ? path : at(path, key)\n}\n","/**\n * The data a report is rendered from, and the check that admits it.\n *\n * A host hands over one envelope (plan 13.2): one header record and one\n * primary detail list for version 0, with what the provider says about\n * them -- how many rows it captured against what cap, and how consistent\n * the capture is. `checkData` holds every value to the report's dataset\n * contracts before anything reads it, and refuses rather than repairs:\n *\n * - **Types are the contract's.** Each value is read as its field's type\n * (`values.ts`), exact numbers as strings and never through a JavaScript\n * number, and held as the runtime computes with it.\n * - **Null is not missing.** Null is a value where the contract allows it,\n * and prints as nothing. A field the data lacks altogether is an error in\n * a final render, never an empty cell (0007); a preview, which may run on\n * a sample, warns once per field and leaves it missing.\n * - **Data minimisation.** A field, or a dataset, the report does not\n * declare is refused: a report never carries what it does not print, so\n * nothing it was not written to read rides along into a render, a cache\n * or a log.\n * - **No silent truncation.** A final render prints every row or none: data\n * the provider calls incomplete is refused, and so is a captured count\n * that disagrees with the rows given.\n * - **Bounded.** The rows and every string are bounded before they are\n * read, and so is the error list; once it is full, nothing more is read.\n *\n * What is held afterwards is a frozen copy, read once from the host's\n * objects, which no later change to them reaches.\n */\nimport { MAX_KEY_LENGTH } from '@formancy/report-spec'\nimport type { DatasetContract, DatasetRole, ReportDefinition } from '@formancy/report-spec'\nimport { at, DataFindings, isLongKey, keyAt } from './data-errors.js'\nimport type { DataError, DataErrorCode } from './data-errors.js'\nimport { readList, readRecord, UNREADABLE } from './input.js'\nimport type { ContainerCode } from './input.js'\nimport { readValue } from './values.js'\nimport type { CheckedValue } from './values.js'\n\n/**\n * How consistent the provider's capture is (plan 13.2): captured by the\n * host, read in one database snapshot, or explicitly neither -- the label\n * Formancy Data 0.1.0's records carry, read at different moments.\n */\nexport const CONSISTENCY_MODES = ['host-captured', 'transaction-snapshot', 'best-effort'] as const\nexport type Consistency = (typeof CONSISTENCY_MODES)[number]\n\n/** A final render prints the report; a preview shows an author a sample while they work, and says what it lacks. */\nexport const DATA_MODES = ['final', 'preview'] as const\nexport type DataMode = (typeof DATA_MODES)[number]\n\n/**\n * Detail rows in one render. Chosen, not derived: a report is read by a\n * person, and at the renderer trial's 48 rows a page (`docs/renderer-trial.md`,\n * 15 October 2026) this is over 2,000 pages, which pdfmake took more than 35\n * seconds to lay out at the 1,829 ms per hundred pages measured there. The\n * PDF's page bound refuses most such reports first; this bounds the\n * runtime's own work -- checking, sorting, totalling -- before a page is\n * laid out. At the bound, checking rows of the test sample report's nine\n * fields took a median of 1.5 seconds, and ordering them by site and SKU 0.5\n * (five warm runs under vitest, Node 24.21, an Intel i9-10900K, 15 October\n * 2026).\n */\nexport const MAX_DETAIL_ROWS = 100_000\n\n/** What the provider says about the rows it handed over. */\nexport interface Completeness {\n /** False when the provider stopped before the end: at its cap, or sampling. */\n readonly complete: boolean\n /** How many detail rows it captured: exactly the rows given. */\n readonly captured: number\n /** The most rows it would capture, when it has a cap. */\n readonly cap?: number\n}\n\n/** The envelope a host renders a report from. Untrusted: `checkData` reads it as data, whatever its type says. */\nexport interface ReportData {\n /** The header dataset's one record, by field id. */\n readonly header?: Readonly<Record<string, unknown>>\n /** The detail dataset's rows, in the provider's order. */\n readonly detail?: readonly Readonly<Record<string, unknown>>[]\n readonly completeness: Completeness\n readonly consistency: Consistency\n}\n\n/**\n * One record, checked: each declared field's value as its type holds it, or\n * null. A field a preview's data lacks is absent, not null. The record has\n * no prototype, so a field named `constructor` is the record's own or\n * absent, never inherited.\n */\nexport type CheckedRecord = { readonly [field: string]: CheckedValue | null }\n\nexport interface CheckedData {\n readonly mode: DataMode\n /** The header record; absent when the report declares no header dataset. */\n readonly header?: CheckedRecord\n /** The detail rows, in the provider's order; empty when the report declares no detail dataset. */\n readonly detail: readonly CheckedRecord[]\n readonly completeness: Completeness\n readonly consistency: Consistency\n}\n\nexport type DataCheck =\n | { readonly ok: true; readonly data: CheckedData; /** What a preview lacks; always empty in a final render, which refuses it. */ readonly warnings: readonly DataError[] }\n | { readonly ok: false; readonly errors: readonly DataError[] }\n\nexport interface DataCheckOptions {\n readonly mode: DataMode\n}\n\nconst ENVELOPE: readonly string[] = ['header', 'detail', 'completeness', 'consistency']\nconst COMPLETENESS: readonly string[] = ['complete', 'captured', 'cap']\n\nconst MINIMISATION = 'a report never carries what it does not print, so data it does not read is refused rather than carried along'\n\n/** What one check carries through: its errors, its warnings, and its mode. */\ninterface Check {\n readonly errors: DataFindings\n readonly warnings: DataError[]\n readonly final: boolean\n}\n\n/** A container's code as a data error's: a list too long is a dataset with too many rows. */\nconst CONTAINER: { readonly [C in ContainerCode]: DataErrorCode } = { 'wrong-type': 'wrong-type', 'not-data': 'not-data', 'too-many': 'too-many-rows' }\n\n/** Reports what a record holds that is not data, by key; returns those keys. */\nfunction reportProblems(c: Check, path: string, problems: readonly { readonly key?: string; readonly message: string }[]): ReadonlySet<string> {\n const keys = new Set<string>()\n for (const problem of problems) {\n if (problem.key !== undefined) keys.add(problem.key)\n c.errors.report(problem.key === undefined ? path : keyAt(path, problem.key), 'not-data', problem.message)\n }\n return keys\n}\n\n/** How many records lacked a field, and where it was first missed. */\ninterface Missing {\n first: string\n count: number\n}\n\n/** One record held to `contract`, or undefined when it cannot be read at all. Fields it lacks are tallied in `missing`. */\nfunction checkRecord(c: Check, contract: DatasetContract, declared: ReadonlySet<string>, raw: unknown, path: string, missing: Map<string, Missing>): CheckedRecord | undefined {\n const read = readRecord(raw)\n if (!read.ok) {\n c.errors.report(path, read.code, read.message)\n return undefined\n }\n const unreadable = reportProblems(c, path, read.problems)\n const record = Object.create(null) as Record<string, CheckedValue | null>\n for (const field of contract.fields) {\n const where = at(path, field.id)\n if (unreadable.has(field.id)) continue\n if (!read.entries.has(field.id)) {\n const tally = missing.get(field.id)\n if (c.final) c.errors.report(where, 'missing-field', `${field.id}: the contract declares this field and the data lacks it; a missing field is not null, and a final render refuses it`)\n else if (tally === undefined) missing.set(field.id, { first: where, count: 1 })\n else tally.count++\n continue\n }\n const value = read.entries.get(field.id)\n if (value === null) {\n if (field.nullable) record[field.id] = null\n else c.errors.report(where, 'unexpected-null', `${field.id}: the contract says this field is never null`)\n continue\n }\n const checked = readValue(field.type, value, field.scale)\n if (checked.ok) record[field.id] = checked.value\n else c.errors.report(where, checked.code, `${field.id}: ${checked.message}`)\n }\n for (const key of read.entries.keys()) {\n if (declared.has(key)) continue\n const what = isLongKey(key) ? `a property name longer than ${MAX_KEY_LENGTH} characters, which no field has` : 'the contract declares no such field'\n c.errors.report(keyAt(path, key), 'undeclared-field', `${what}; ${MINIMISATION}`)\n }\n return Object.freeze(record)\n}\n\n/** A warning for each field a preview's records lacked, once per field. */\nfunction warnMissing(c: Check, missing: ReadonlyMap<string, Missing>, records: number, role: DatasetRole): void {\n for (const [field, { first, count }] of missing) {\n const where = role === 'header' ? 'the header record' : `${count} of ${records} rows`\n c.warnings.push({ path: first, code: 'missing-field', message: `${field}: missing from ${where}; a final render refuses data without it` })\n }\n}\n\n/** The report does not declare `role`, and the data holds it. */\nfunction undeclaredDataset(c: Check, role: DatasetRole): void {\n c.errors.report(`/${role}`, 'undeclared-dataset', `the report declares no ${role} dataset; ${MINIMISATION}`)\n}\n\n/** The report declares `role`, and the data lacks it: an error in a final render, a warning in a preview. */\nfunction missingDataset(c: Check, role: DatasetRole): void {\n const message = `the report declares a ${role} dataset and the data has none`\n if (c.final) c.errors.report(`/${role}`, 'missing-dataset', message)\n else c.warnings.push({ path: `/${role}`, code: 'missing-dataset', message: `${message}; every field of it is missing` })\n}\n\nconst EMPTY: CheckedRecord = Object.freeze(Object.create(null) as CheckedRecord)\n\nfunction checkHeader(c: Check, contract: DatasetContract | undefined, entries: ReadonlyMap<string, unknown>): CheckedRecord | undefined {\n const present = entries.has('header')\n if (contract === undefined) {\n if (present) undeclaredDataset(c, 'header')\n return undefined\n }\n if (!present) {\n missingDataset(c, 'header')\n return EMPTY\n }\n const missing = new Map<string, Missing>()\n const record = checkRecord(c, contract, new Set(contract.fields.map(({ id }) => id)), entries.get('header'), '/header', missing)\n warnMissing(c, missing, 1, 'header')\n return record\n}\n\n/** The detail rows checked, and how many were given when that could be counted. */\nfunction checkDetail(c: Check, contract: DatasetContract | undefined, entries: ReadonlyMap<string, unknown>): { readonly rows: CheckedRecord[]; readonly given: number | undefined } {\n const present = entries.has('detail')\n if (contract === undefined || !present) {\n if (contract === undefined && present) undeclaredDataset(c, 'detail')\n if (contract !== undefined) missingDataset(c, 'detail')\n return { rows: [], given: contract === undefined && !present ? 0 : undefined }\n }\n const list = readList(entries.get('detail'), MAX_DETAIL_ROWS)\n if (!list.ok) {\n const message = list.code === 'too-many' ? `${list.message}: a render reads at most ${MAX_DETAIL_ROWS} detail rows` : list.message\n c.errors.report('/detail', CONTAINER[list.code], message)\n return { rows: [], given: undefined }\n }\n const unreadable = new Map(list.problems.map(({ index, message }) => [index, message]))\n const declared = new Set(contract.fields.map(({ id }) => id))\n const missing = new Map<string, Missing>()\n const rows: CheckedRecord[] = []\n for (const [index, item] of list.items.entries()) {\n if (c.errors.full) break\n if (item === UNREADABLE) {\n c.errors.report(at('/detail', index), 'not-data', unreadable.get(index) as string)\n continue\n }\n const record = checkRecord(c, contract, declared, item, at('/detail', index), missing)\n if (record !== undefined) rows.push(record)\n }\n warnMissing(c, missing, list.items.length, 'detail')\n return { rows, given: list.items.length }\n}\n\nconst isCount = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n\nfunction checkCompleteness(c: Check, raw: unknown, given: number | undefined): Completeness | undefined {\n const read = readRecord(raw)\n const shape = 'completeness is { \"complete\": true or false, \"captured\": the rows given, \"cap\": the most rows the provider would capture, if it has a cap }'\n if (!read.ok) {\n c.errors.report('/completeness', 'invalid-completeness', shape)\n return undefined\n }\n reportProblems(c, '/completeness', read.problems)\n for (const key of read.entries.keys()) {\n if (!COMPLETENESS.includes(key)) c.errors.report(keyAt('/completeness', key), 'invalid-completeness', `${shape}; nothing else`)\n }\n const { complete, captured, cap } = Object.fromEntries(COMPLETENESS.map((key) => [key, read.entries.get(key)]))\n const valid = typeof complete === 'boolean' && isCount(captured) && (cap === undefined || isCount(cap))\n if (typeof complete !== 'boolean') c.errors.report('/completeness/complete', 'invalid-completeness', 'complete is true or false')\n if (!isCount(captured)) c.errors.report('/completeness/captured', 'invalid-completeness', 'captured is a count of rows: a whole number, 0 or more')\n if (cap !== undefined && !isCount(cap)) c.errors.report('/completeness/cap', 'invalid-completeness', 'cap is a count of rows: a whole number, 0 or more')\n if (!valid) return undefined\n if (given !== undefined && captured !== given) {\n c.errors.report('/completeness/captured', 'completeness-mismatch', `the provider says it captured ${captured} rows and gave ${given}; rows lost or added on the way are never papered over`)\n }\n if (cap !== undefined && captured > cap) c.errors.report('/completeness/cap', 'completeness-mismatch', `the provider says it captured ${captured} rows, more than its cap of ${cap}`)\n if (!complete) {\n const message = 'the provider says the data is incomplete'\n if (c.final) c.errors.report('/completeness/complete', 'incomplete', `${message}; a final render prints every row or none, and never a silently truncated report`)\n else c.warnings.push({ path: '/completeness/complete', code: 'incomplete', message: `${message}; this preview shows only what was captured` })\n }\n return Object.freeze({ complete, captured, ...(cap === undefined ? {} : { cap }) })\n}\n\nfunction checkConsistency(c: Check, raw: unknown): Consistency | undefined {\n if (CONSISTENCY_MODES.includes(raw as Consistency)) return raw as Consistency\n c.errors.report('/consistency', 'invalid-consistency', `consistency is one of ${CONSISTENCY_MODES.map((mode) => `\"${mode}\"`).join(', ')}`)\n return undefined\n}\n\n/**\n * `data` held to `report`'s dataset contracts, or every reason it is\n * refused, up to `MAX_DATA_ERRORS`. `report` is one the validator accepts.\n * Any mode but `preview` is held as final: the stricter of the two.\n */\nexport function checkData(report: ReportDefinition, data: ReportData, options: DataCheckOptions): DataCheck {\n const c: Check = { errors: new DataFindings(), warnings: [], final: options.mode !== 'preview' }\n const top = readRecord(data)\n if (!top.ok) return { ok: false, errors: [{ path: '', code: top.code, message: top.message }] }\n reportProblems(c, '', top.problems)\n for (const key of top.entries.keys()) {\n if (!ENVELOPE.includes(key)) c.errors.report(keyAt('', key), 'unknown-property', `the data holds ${ENVELOPE.join(', ')}, and nothing the runtime does not know`)\n }\n const header = checkHeader(c, report.datasets.header, top.entries)\n const detail = checkDetail(c, report.datasets.detail, top.entries)\n const completeness = checkCompleteness(c, top.entries.get('completeness'), detail.given)\n const consistency = checkConsistency(c, top.entries.get('consistency'))\n if (!c.errors.empty || completeness === undefined || consistency === undefined) return { ok: false, errors: c.errors.errors() }\n const checked: CheckedData = {\n mode: c.final ? 'final' : 'preview',\n ...(header === undefined ? {} : { header }),\n detail: Object.freeze(detail.rows),\n completeness,\n consistency,\n }\n return { ok: true, data: Object.freeze(checked), warnings: c.warnings }\n}\n","/**\n * The values a person supplies before rendering, held to the report's\n * parameters.\n *\n * A parameter is read by exactly the rules a dataset field of its type is\n * (`values.ts`), so `params.copies` is an integer however it reached the\n * report: from a parameter form, an API call or a default. Then:\n *\n * - **Defaults apply** to a parameter left out. A default is written as the\n * format writes it -- an exact string, or a boolean -- and read by the\n * same rules as a value.\n * - **Required is enforced.** A required parameter with neither a value nor\n * a default is refused.\n * - **Null only where there may be none.** A parameter that is neither\n * required nor defaulted may be null; any other is never null when an\n * expression reads it (0009), so null for it is refused, not read as its\n * default.\n * - **Nothing undeclared.** A value for a parameter the report does not\n * declare is refused.\n *\n * The values are checked again here even when a parameter form checked\n * them already (plan 12.4): what reaches a render is decided by the\n * runtime, never by the browser that sent it.\n */\nimport { MAX_KEY_LENGTH } from '@formancy/report-spec'\nimport type { ParameterDef, ReportDefinition } from '@formancy/report-spec'\nimport { at, DataFindings, isLongKey, keyAt } from './data-errors.js'\nimport type { DataError } from './data-errors.js'\nimport { readRecord } from './input.js'\nimport { readValue } from './values.js'\nimport type { CheckedValue } from './values.js'\n\n/** The parameters' values by id, each read as its type or null. It has no prototype, so a parameter named `constructor` is its own value. */\nexport type CheckedParameters = { readonly [parameter: string]: CheckedValue | null }\n\nexport type ParameterCheck = { readonly ok: true; readonly values: CheckedParameters } | { readonly ok: false; readonly errors: readonly DataError[] }\n\n/** The value `parameter` takes when nobody supplied one; undefined when it must be supplied. */\nfunction absent(errors: DataFindings, parameter: ParameterDef, path: string): CheckedValue | null | undefined {\n if (parameter.default !== undefined) {\n const read = readValue(parameter.type, parameter.default)\n if (read.ok) return read.value\n errors.report(path, read.code, `${parameter.id}: its default is not a ${parameter.type}: ${read.message}`)\n return undefined\n }\n if (!parameter.required) return null\n errors.report(path, 'missing-parameter', `${parameter.id}: the report requires this parameter, and it has no value and no default`)\n return undefined\n}\n\n/**\n * `values` held to `report`'s parameters, with defaults applied, or every\n * reason they are refused. `report` is one the validator accepts. A path is\n * a JSON Pointer into `values`: `/copies`.\n */\nexport function checkParameters(report: ReportDefinition, values: Readonly<Record<string, unknown>>): ParameterCheck {\n const errors = new DataFindings()\n const read = readRecord(values)\n if (!read.ok) return { ok: false, errors: [{ path: '', code: read.code, message: `parameters are ${read.message}` }] }\n const unreadable = new Set<string>()\n for (const problem of read.problems) {\n if (problem.key !== undefined) unreadable.add(problem.key)\n errors.report(problem.key === undefined ? '' : keyAt('', problem.key), 'not-data', problem.message)\n }\n const checked = Object.create(null) as Record<string, CheckedValue | null>\n for (const parameter of report.parameters) {\n const path = at('', parameter.id)\n if (unreadable.has(parameter.id)) continue\n if (!read.entries.has(parameter.id)) {\n const value = absent(errors, parameter, path)\n if (value !== undefined) checked[parameter.id] = value\n continue\n }\n const raw = read.entries.get(parameter.id)\n if (raw === null) {\n if (!parameter.required && parameter.default === undefined) checked[parameter.id] = null\n else {\n const why = parameter.default === undefined ? 'the report requires it' : 'it has a default; leave it out to use the default'\n errors.report(path, 'unexpected-null', `${parameter.id}: never null, because ${why}`)\n }\n continue\n }\n const value = readValue(parameter.type, raw)\n if (value.ok) checked[parameter.id] = value.value\n else errors.report(path, value.code, `${parameter.id}: ${value.message}`)\n }\n const declared = new Set(report.parameters.map(({ id }) => id))\n for (const key of read.entries.keys()) {\n if (declared.has(key)) continue\n const what = isLongKey(key) ? `a name longer than ${MAX_KEY_LENGTH} characters, which no parameter has` : 'the report declares no such parameter'\n errors.report(keyAt('', key), 'undeclared-parameter', `${what}; a report reads nothing it was not written to read`)\n }\n if (!errors.empty) return { ok: false, errors: errors.errors() }\n return { ok: true, values: Object.freeze(checked) }\n}\n","/**\n * Exact totals and declared rounding, over `@formancy/expressions`'\n * `Decimal`: a value as an integer of units at a scale, so that nothing here\n * ever passes through a JavaScript number.\n *\n * Totals are decided once, here (0007): a sum is exact at the largest scale\n * it meets, a minimum or maximum compares by value, and an average is the\n * exact quotient rounded once, by the rule the aggregate declares. Rounding\n * follows report-spec's `Rounding`: to a multiple of `increment` when one is\n * given -- 0.05 for Swiss cash rounding -- and otherwise to `scale` places,\n * ties going by `mode` either way, and the result at exactly `scale` places.\n *\n * Upstream's own `roundDecimal` rounds half away from zero to a number of\n * places and nothing else; a declared rounding also has half to even and an\n * increment, so it is worked here, on integers, once for every case.\n * `decimal.test.ts` holds it against a reference written independently.\n */\nimport { addDecimal, compareDecimal, Decimal, decimalFromString } from '@formancy/expressions'\nimport type { Rounding, RoundingMode } from '@formancy/report-spec'\n\n/**\n * `numerator / denominator` (denominator more than 0) rounded to a whole\n * number, ties by `mode`. Division truncates towards zero; what it left\n * decides whether to step away from zero.\n */\nfunction roundQuotient(numerator: bigint, denominator: bigint, mode: RoundingMode): bigint {\n const quotient = numerator / denominator\n const remainder = numerator % denominator\n const twice = 2n * (remainder < 0n ? -remainder : remainder)\n if (twice < denominator) return quotient\n const away = numerator < 0n ? quotient - 1n : quotient + 1n\n if (twice > denominator) return away\n return mode === 'half-away-from-zero' || quotient % 2n !== 0n ? away : quotient\n}\n\n/** The step a rounding rounds to: its increment, or one unit at its scale. Throws for a step report-spec refuses. */\nfunction stepOf(rounding: Rounding): Decimal {\n if (rounding.increment === undefined) return new Decimal(1n, rounding.scale)\n const step = decimalFromString(rounding.increment)\n if (step.units <= 0n || step.scale > rounding.scale) {\n throw new RangeError(`an increment is more than 0 and has no more places than the ${rounding.scale} its rounding keeps`)\n }\n return step\n}\n\n/** The exact quotient `numerator / denominator` rounded as `rounding` declares. */\nfunction roundRatio(numerator: bigint, denominator: bigint, rounding: Rounding): Decimal {\n const step = stepOf(rounding)\n const steps = roundQuotient(numerator * 10n ** BigInt(step.scale), denominator * step.units, rounding.mode)\n return new Decimal(steps * step.units * 10n ** BigInt(rounding.scale - step.scale), rounding.scale)\n}\n\n/**\n * `value` rounded as `rounding` declares, at exactly its scale. A negative\n * value that rounds to nothing is zero, never minus zero. Throws a\n * RangeError for an increment report-spec refuses: of zero or less, or with\n * more places than the scale.\n */\nexport function roundDecimalAs(value: Decimal, rounding: Rounding): Decimal {\n return roundRatio(value.units, 10n ** BigInt(value.scale), rounding)\n}\n\n/** The exact sum, at the largest scale among the values; 0 over none (0007). */\nexport function sumDecimals(values: Iterable<Decimal>): Decimal {\n let total = new Decimal(0n, 0)\n for (const value of values) total = addDecimal(total, value)\n return total\n}\n\n/** The value `keep` prefers over each other, compared by value; the first of equals is kept, as written. */\nfunction extreme(values: Iterable<Decimal>, keep: (order: -1 | 0 | 1) => boolean): Decimal | null {\n let found: Decimal | null = null\n for (const value of values) if (found === null || keep(compareDecimal(value, found))) found = value\n return found\n}\n\n/** The least value, as written; null over none (0007). */\nexport function minDecimal(values: Iterable<Decimal>): Decimal | null {\n return extreme(values, (order) => order < 0)\n}\n\n/** The greatest value, as written; null over none (0007). */\nexport function maxDecimal(values: Iterable<Decimal>): Decimal | null {\n return extreme(values, (order) => order > 0)\n}\n\n/**\n * The exact average, rounded once as `rounding` declares: the exact sum\n * over the count, never a quotient rounded and then rounded again. Null\n * over no values (0007).\n */\nexport function averageDecimals(values: Iterable<Decimal>, rounding: Rounding): Decimal | null {\n let count = 0n\n let total = new Decimal(0n, 0)\n for (const value of values) {\n total = addDecimal(total, value)\n count++\n }\n return count === 0n ? null : roundRatio(total.units, count * 10n ** BigInt(total.scale), rounding)\n}\n","/**\n * A value as the text a report prints, for the report's locale: report-spec's\n * number, currency, date and text formats, through Intl.\n *\n * - **Exact to the last digit.** A number reaches Intl as the string of its\n * digits, already rounded here to exactly the places it prints, half away\n * from zero as a person rounds by hand. An ES2023 engine formats such a\n * string exactly, and `format.test.ts` holds that it does; Intl is never\n * handed a double and never rounds. Up to a bound: ECMA-402 reads a\n * string whose double would be infinite as infinity, and prints '∞'. A\n * number with more than `MAX_FORMATTED_DIGITS` integer digits is refused\n * instead; printed without a format, it prints whole.\n * - **The locale's conventions.** Grouping, separators, currency symbols,\n * month names and case are the locale's, as the engine's ICU has them.\n * ICU versions can differ -- which mark Swiss German groups digits with is\n * one such difference, and `format.test.ts` reads it from the engine -- so\n * the same report can print differently on two engines. That is the cost\n * of not carrying a locale database here.\n * - **Dates have no zone.** A date, and a date and time without a zone, are\n * formatted in UTC from their own fields, so 2026-01-01 is the first of\n * January wherever the report renders. Only an instant is shown in a zone,\n * and that zone is the host's to name: the machine's is never used.\n * - **Nothing is guessed.** A locale or zone the engine lacks is refused\n * rather than replaced by a default, and a format that cannot show a value\n * is an error rather than a blank.\n *\n * Null prints as nothing (0007), under every format.\n */\nimport { Decimal, decimalToString } from '@formancy/expressions'\nimport type { CurrencyFormat, CurrencySource, DateStyle, FieldType, Format, NumberFormat, TextTransform } from '@formancy/report-spec'\nimport type { CheckedRecord } from './data.js'\nimport { roundDecimalAs } from './decimal.js'\nimport type { CheckedParameters } from './parameters.js'\nimport { readValue } from './values.js'\nimport type { FieldValues } from './values.js'\n\n/** The types a value printed can have: every field type but an image, which is drawn. */\nexport type PrintableType = Exclude<FieldType, 'image'>\n\n/** A value with its type, as the runtime holds it (`values.ts`). */\nexport type TypedValue = { readonly [T in PrintableType]: { readonly type: T; readonly value: FieldValues[T] } }[PrintableType]\n\nexport const FORMAT_ERROR_CODES = [\n /** A locale the engine's Intl does not have, which it would silently replace with the host's. */\n 'unsupported-locale',\n /** A time zone the engine's Intl does not know. */\n 'unsupported-time-zone',\n /** A format that cannot show the value it is given: a number format over text, a date format over a number. */\n 'format-type-mismatch',\n /** An amount whose currency field or parameter has no value. */\n 'no-currency',\n /** A currency that is not an ISO 4217 code in capitals. */\n 'invalid-currency',\n /** A number with more integer digits than `MAX_FORMATTED_DIGITS`, which Intl would print as '∞'. */\n 'number-too-large',\n] as const\n\n/**\n * The most integer digits a number or currency format prints: 308. A double\n * holds up to about 1.8 × 10^308, and ECMA-402's ToIntlMathematicalValue\n * reads a string whose double would be infinite as infinity, so every\n * number of 308 digits or fewer prints exactly and one of 309 may not.\n */\nexport const MAX_FORMATTED_DIGITS = 308\nexport type FormatErrorCode = (typeof FORMAT_ERROR_CODES)[number]\n\nexport type Formatted = { readonly ok: true; readonly text: string } | { readonly ok: false; readonly code: FormatErrorCode; readonly message: string }\n\n/** What a render is formatted for: the report's locale, and the zone its instants are shown in. */\nexport interface FormatContext {\n /** A BCP 47 tag, as a report's `locale` is. */\n readonly locale: string\n /** An IANA time zone, such as `Europe/Zurich`, named by the host. */\n readonly timeZone: string\n}\n\n/** Where a currency format finds a currency read from a field or a parameter. */\nexport interface CurrencyScope {\n readonly params?: CheckedParameters\n readonly header?: CheckedRecord\n /** The current detail row, in a table's cells. */\n readonly row?: CheckedRecord\n}\n\nexport interface Formatter {\n readonly locale: string\n readonly timeZone: string\n /** `value` as `format` shows it, or as it prints plainly without one. */\n format(value: TypedValue | null, format: Format | undefined, scope?: CurrencyScope): Formatted\n}\n\nfunction refused(code: FormatErrorCode, message: string): Formatted {\n return { ok: false, code, message }\n}\n\n/**\n * A value printed with no format: as the format writes it. Exact digits\n * with their scale, ISO dates, an instant in UTC; nothing is interpreted.\n */\nexport function plainText(value: TypedValue | null): string {\n if (value === null) return ''\n if (value.type === 'integer' || value.type === 'boolean') return String(value.value)\n if (value.type === 'decimal') return decimalToString(value.value)\n return value.value\n}\n\n/**\n * Whether the engine has `locale`, in its number and date formats and its\n * collation, by the lookup a tag like `de-CH` falls back from region to\n * language with. A tag it cannot read is not one it has.\n */\nexport function supportedLocale(locale: string): boolean {\n try {\n const options = { localeMatcher: 'lookup' } as const\n return (\n Intl.NumberFormat.supportedLocalesOf([locale], options).length === 1 &&\n Intl.DateTimeFormat.supportedLocalesOf([locale], options).length === 1 &&\n Intl.Collator.supportedLocalesOf([locale], options).length === 1\n )\n } catch {\n return false\n }\n}\n\n/** Whether Intl knows `timeZone`. */\nfunction knownTimeZone(timeZone: string): boolean {\n try {\n new Intl.DateTimeFormat('en', { timeZone })\n return true\n } catch {\n return false\n }\n}\n\n/** The time a date-and-time format shows with each date style: no seconds for short, seconds otherwise; never the zone's name, which a local time does not have. */\nconst TIME_STYLE: { readonly [S in DateStyle]: 'short' | 'medium' } = { short: 'short', medium: 'medium', long: 'medium' }\n\n/** A moment to show: when, whether it has a time of day, and whether it is shown in the render's zone or, having none, in UTC. */\ninterface Moment {\n readonly epochMs: number\n readonly time: boolean\n readonly zoned: boolean\n}\n\n/** Epoch milliseconds of a calendar date and time in UTC; Date.UTC would read the years 0 to 99 as 1900 to 1999. */\nfunction utc(year: number, month: number, day: number, hour = 0, minute = 0, second = 0): number {\n const moment = new Date(0)\n moment.setUTCFullYear(year, month - 1, day)\n moment.setUTCHours(hour, minute, second, 0)\n return moment.getTime()\n}\n\n/** The numbers in `text`, a date or a date and time `readValue` accepted, in order. */\nconst fieldsOf = (text: string): number[] => (text.match(/\\d+/g) as RegExpMatchArray).map(Number)\n\n/** `value` as a `type` spells it: a value of that type, or a string an expression gave that spells one, as `readValue` holds it. */\nfunction spelledAs(value: TypedValue, type: 'date' | 'datetime' | 'instant'): string | undefined {\n if (value.type === type) return value.value as string\n if (value.type !== 'string') return undefined\n const read = readValue(type, value.value)\n return read.ok ? read.value : undefined\n}\n\n/** The moment a value spells: a date, a date and time, or an instant, by its type or, for a string an expression gave, by its syntax. */\nfunction momentOf(value: TypedValue): Moment | undefined {\n const date = spelledAs(value, 'date')\n if (date !== undefined) {\n const [year, month, day] = fieldsOf(date) as [number, number, number]\n return { epochMs: utc(year, month, day), time: false, zoned: false }\n }\n const local = spelledAs(value, 'datetime')\n if (local !== undefined) {\n const [year, month, day, hour, minute, second] = fieldsOf(local) as [number, number, number, number, number, number]\n return { epochMs: utc(year, month, day, hour, minute, second), time: true, zoned: false }\n }\n const instant = spelledAs(value, 'instant')\n return instant === undefined ? undefined : { epochMs: new Date(instant).getTime(), time: true, zoned: true }\n}\n\n/** The exact number a value holds, or undefined when it holds none. */\nfunction exactNumber(value: TypedValue): Decimal | undefined {\n if (value.type === 'integer') return new Decimal(value.value, 0)\n return value.type === 'decimal' ? value.value : undefined\n}\n\n/** The currency code an amount is in, from the format, a field or a parameter, or why there is none. */\nfunction currencyOf(source: CurrencySource, scope: CurrencyScope | undefined): string | Formatted {\n if (source.kind === 'code') return source.code\n const [name, raw] =\n source.kind === 'parameter'\n ? [`parameter ${source.parameter}`, scope?.params?.[source.parameter]]\n : [`field ${source.field.field}`, (source.field.dataset === 'header' ? scope?.header : scope?.row)?.[source.field.field]]\n if (raw === null || raw === undefined) return refused('no-currency', `the amount's currency, ${name}, has no value, and an amount without one reads as some other currency`)\n if (typeof raw === 'string' && /^[A-Z]{3}$/.test(raw)) return raw\n return refused('invalid-currency', `the amount's currency, ${name}, is not an ISO 4217 code in capitals, such as CHF`)\n}\n\n/** The Intl formatter `cache` keeps for `options`, made by `make` the first time they are asked for: a table formats a column with one. */\nfunction kept<T>(cache: Map<string, T>, options: object, make: () => T): T {\n const key = JSON.stringify(options)\n const found = cache.get(key)\n if (found !== undefined) return found\n const made = make()\n cache.set(key, made)\n return made\n}\n\n/** A formatter for one locale and time zone, which builds each Intl formatter it needs once and keeps it. */\nclass LocaleFormatter implements Formatter {\n readonly locale: string\n readonly timeZone: string\n readonly #numbers = new Map<string, Intl.NumberFormat>()\n readonly #dates = new Map<string, Intl.DateTimeFormat>()\n\n constructor(context: FormatContext) {\n this.locale = context.locale\n this.timeZone = context.timeZone\n }\n\n format(value: TypedValue | null, format: Format | undefined, scope?: CurrencyScope): Formatted {\n if (value === null) return { ok: true, text: '' }\n if (format === undefined) return { ok: true, text: plainText(value) }\n switch (format.kind) {\n case 'text':\n return { ok: true, text: this.#transformed(plainText(value), format.transform) }\n case 'date':\n return this.#date(value, format.style)\n default:\n return this.#number(value, format, scope)\n }\n }\n\n #transformed(text: string, transform: TextTransform | undefined): string {\n if (transform === 'upper') return text.toLocaleUpperCase(this.locale)\n return transform === 'lower' ? text.toLocaleLowerCase(this.locale) : text\n }\n\n #number(value: TypedValue, format: NumberFormat | CurrencyFormat, scope: CurrencyScope | undefined): Formatted {\n const exact = exactNumber(value)\n if (exact === undefined) return refused('format-type-mismatch', `a ${format.kind} format shows integers and decimals, and this value is a ${value.type}`)\n const currency = format.kind === 'currency' ? currencyOf(format.currency, scope) : undefined\n if (typeof currency === 'object') return currency\n const rounded = decimalToString(roundDecimalAs(exact, { scale: format.scale, mode: 'half-away-from-zero' })) as Intl.StringNumericLiteral\n if (rounded.replace(/^-/, '').split('.')[0]!.length > MAX_FORMATTED_DIGITS) {\n return refused('number-too-large', `a number of more than ${MAX_FORMATTED_DIGITS} digits, which Intl would print as infinity; printed without a format, it prints whole`)\n }\n const options: Intl.NumberFormatOptions = {\n minimumFractionDigits: format.scale,\n maximumFractionDigits: format.scale,\n ...(currency === undefined ? { useGrouping: format.kind === 'number' && !format.grouping ? false : 'auto' } : { style: 'currency', currency }),\n }\n return { ok: true, text: kept(this.#numbers, options, () => new Intl.NumberFormat(this.locale, options)).format(rounded) }\n }\n\n #date(value: TypedValue, style: DateStyle): Formatted {\n const moment = momentOf(value)\n if (moment === undefined) return refused('format-type-mismatch', `a date format shows dates, dates and times, and instants, and this value is a ${value.type} that spells none`)\n const options: Intl.DateTimeFormatOptions = {\n dateStyle: style,\n ...(moment.time ? { timeStyle: TIME_STYLE[style] } : {}),\n timeZone: moment.zoned ? this.timeZone : 'UTC',\n }\n return { ok: true, text: kept(this.#dates, options, () => new Intl.DateTimeFormat(this.locale, options)).format(moment.epochMs) }\n }\n}\n\n/** A formatter for `context`, or why its locale or time zone is refused. */\nexport function createFormatter(context: FormatContext): { readonly ok: true; readonly formatter: Formatter } | { readonly ok: false; readonly code: FormatErrorCode; readonly message: string } {\n if (!supportedLocale(context.locale)) {\n return { ok: false, code: 'unsupported-locale', message: \"the engine's Intl does not have this locale, and would print the host's instead\" }\n }\n if (!knownTimeZone(context.timeZone)) return { ok: false, code: 'unsupported-time-zone', message: \"the engine's Intl does not know this time zone\" }\n return { ok: true, formatter: new LocaleFormatter(context) }\n}\n","/**\n * The order of a table's rows and its groups, decided once, here (0007).\n *\n * Rows are ordered by the group's key first, in its direction, then by each\n * sort key, each compared as its type: decimals by value, integers as\n * BigInt, dates and times in calendar order, text as the report's language\n * sorts it, false before true. Nulls -- and a field a preview lacks -- go\n * last whichever way a key runs, so an empty cell never lands among the\n * values. Rows whose keys are all equal keep the provider's order: the\n * row's index is the last key, so the comparator is a total order and the\n * result rests on it alone. `Array.prototype.sort` has been stable since\n * ES2019, which by itself keeps that order too, so no test can tell the two\n * apart; the index is there so that nothing depends on the algorithm.\n *\n * Text the collator holds equal but spelled differently -- é composed and\n * decomposed -- is ordered by code unit after the collator, so that rows\n * with identical keys always stand together and a group never splits around\n * another spelling. Collation is the engine's ICU's, and differs between\n * ICU versions as formatting does.\n */\nimport { compareDecimal } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport type { ReportDefinition, SortDirection, TableComponent } from '@formancy/report-spec'\nimport type { CheckedRecord } from './data.js'\nimport type { PrintableType } from './format.js'\nimport type { CheckedValue } from './values.js'\n\n/** One key rows are ordered by: a detail field, its type, and its direction. */\nexport interface OrderKey {\n readonly field: string\n readonly type: PrintableType\n readonly direction: SortDirection\n}\n\n/** A detail row in its place: the record, and its index in the order the provider gave the rows. */\nexport interface OrderedRow {\n readonly index: number\n readonly record: CheckedRecord\n}\n\n/** One group: its key, as its first row spells it, or null; then its rows, in order. */\nexport interface RowGroup {\n readonly key: CheckedValue | null\n readonly rows: readonly OrderedRow[]\n}\n\n/** A table's rows in order and, when it groups, its groups in order. */\nexport interface OrderedTable {\n readonly rows: readonly OrderedRow[]\n readonly groups?: readonly RowGroup[]\n}\n\n/** A value made comparable with `<` -- or, for text, with the collator -- for one key column. */\ntype Comparable = string | bigint | boolean\n\n/**\n * A date and time with its fraction of a second at nine digits, without a\n * zone: held without trailing zeros, '10:00:00.5' and '10:00:00' differ in\n * length, and as they stand '10:00:00.5Z' sorts before '10:00:00Z'.\n */\nexport function fixedWidth(value: string): string {\n const local = value.endsWith('Z') ? value.slice(0, -1) : value\n return `${local.slice(0, 19)}.${local.slice(20).padEnd(9, '0')}`\n}\n\n/** The values of `key` in every row, made comparable once; null for a null or missing one. */\nfunction column(rows: readonly CheckedRecord[], key: OrderKey): (Comparable | null)[] {\n const values = rows.map((record) => record[key.field] ?? null)\n switch (key.type) {\n case 'decimal': {\n // Every decimal of the column at one scale, so each comparison is one of integers.\n const decimals = values as (Decimal | null)[]\n const scale = Math.max(0, ...decimals.map((value) => value?.scale ?? 0))\n return decimals.map((value) => (value === null ? null : value.units * 10n ** BigInt(scale - value.scale)))\n }\n case 'datetime':\n case 'instant':\n return (values as (string | null)[]).map((value) => (value === null ? null : fixedWidth(value)))\n default:\n return values as (Comparable | null)[]\n }\n}\n\n/** -1, 0 or 1 for two values of one comparable column. */\nfunction compared(type: PrintableType, a: Comparable, b: Comparable, collator: Intl.Collator): number {\n if (type === 'string') {\n const order = collator.compare(a as string, b as string)\n if (order !== 0) return order\n }\n return a < b ? -1 : a > b ? 1 : 0\n}\n\n/**\n * `rows` in the order `keys` give, each key applied only among rows the keys\n * before it hold equal, with text compared as `locale` sorts it -- a locale\n * `supportedLocale` accepts. Ties keep the provider's order.\n */\nexport function orderRows(rows: readonly CheckedRecord[], keys: readonly OrderKey[], locale: string): OrderedRow[] {\n const collator = new Intl.Collator(locale, { usage: 'sort' })\n const columns = keys.map((key) => column(rows, key))\n const order = rows.map((_, index) => index)\n order.sort((left, right) => {\n for (const [at, key] of keys.entries()) {\n const values = columns[at] as (Comparable | null)[]\n const [a, b] = [values[left] as Comparable | null, values[right] as Comparable | null]\n if (a === null || b === null) {\n if (a !== b) return a === null ? 1 : -1\n continue\n }\n const found = compared(key.type, a, b, collator)\n if (found !== 0) return key.direction === 'asc' ? found : -found\n }\n return left - right\n })\n return order.map((index) => Object.freeze({ index, record: rows[index] as CheckedRecord }))\n}\n\n/** Whether two group keys are one: decimals by value, everything else as held, and null with null. */\nfunction sameKey(type: PrintableType, a: CheckedValue | null, b: CheckedValue | null): boolean {\n if (a === null || b === null) return a === b\n return type === 'decimal' ? compareDecimal(a as Decimal, b as Decimal) === 0 : a === b\n}\n\n/**\n * Rows already in order, as consecutive groups of equal keys: the groups in\n * the order of their rows, each keyed by its first row's value. A missing\n * value groups with null.\n */\nexport function groupRows(rows: readonly OrderedRow[], by: { readonly field: string; readonly type: PrintableType }): RowGroup[] {\n const groups: { key: CheckedValue | null; rows: OrderedRow[] }[] = []\n for (const row of rows) {\n const value = row.record[by.field] ?? null\n const last = groups.at(-1)\n if (last !== undefined && sameKey(by.type, last.key, value)) last.rows.push(row)\n else groups.push({ key: value, rows: [row] })\n }\n return groups.map((group) => Object.freeze({ key: group.key, rows: Object.freeze(group.rows) }))\n}\n\n/**\n * The keys `table` orders its rows by: its group's key first, then its sort\n * keys (0007), each typed by the report's detail contract. Throws a\n * RangeError for a key on a field that has no order -- an image, or one the\n * contract lacks -- which report-spec refuses.\n */\nexport function orderKeys(report: ReportDefinition, table: TableComponent): OrderKey[] {\n const types = new Map((report.datasets.detail?.fields ?? []).map(({ id, type }) => [id, type]))\n const typed = (field: string, direction: SortDirection): OrderKey => {\n const type = types.get(field)\n if (type === undefined || type === 'image') throw new RangeError(`detail field ${field} has no order to sort or group by`)\n return { field, type, direction }\n }\n const group = table.group === undefined ? [] : [typed(table.group.by.field, table.group.direction)]\n return [...group, ...(table.sort ?? []).map(({ field, direction }) => typed(field.field, direction))]\n}\n\n/** `detail` -- the report's checked detail rows -- in `table`'s order, and in its groups when it has one. */\nexport function orderTable(report: ReportDefinition, table: TableComponent, detail: readonly CheckedRecord[]): OrderedTable {\n const keys = orderKeys(report, table)\n const rows = orderRows(detail, keys, report.locale)\n if (table.group === undefined) return { rows }\n return { rows, groups: groupRows(rows, keys[0] as OrderKey) }\n}\n","/**\n * A report's expressions, compiled once and evaluated against checked data,\n * within a budget, each failure an error that says where.\n *\n * - **One compilation.** `@formancy/report-core`'s `compileReport` compiles\n * every expression where it stands, and the editor's diagnostics come\n * from the same function (0009). A report its diagnostics give an error\n * for is refused before anything is evaluated, so the runtime never runs\n * what the editor refuses. Each expression is compiled once per render,\n * never once per row -- twice, in fact, since `diagnose` does not hand\n * back the compilation it made.\n * - **One binding.** Each program's values are made by report-core's\n * `expressionValues`: an integer as a BigInt, a decimal as a `Decimal`,\n * an instant as a moment, a date as its ISO string. A value missing, or of\n * another type, fails the evaluation, naming the member and never quoting\n * the value.\n * - **Nothing differs between renders.** The diagnostics refuse `now()`,\n * `today()` and `random()`; the capabilities an evaluation is handed are\n * fixed besides, so that one reached anyway would answer the same in every\n * render.\n * - **Bounded.** Each evaluation has a budget of steps, and a render has one\n * for all its evaluations together. Past either, the evaluation is refused.\n * - **A failure is an error, never a blank.** It names the component, the\n * table column or the aggregate, and the detail row, and gives upstream's\n * code for what went wrong, never upstream's message, which can quote the\n * values it was computing with.\n *\n * What an expression gives is handed back typed as the runtime holds values:\n * an integer as a BigInt, an instant in UTC. A list or a map, which has no\n * text, is refused. A double never arrives: the diagnostics refuse every\n * double literal, every `double()` and every `/` before anything is\n * evaluated (report-core's `exactness.ts`), since upstream hands an integer\n * and a double back alike, as a JavaScript number, and `int()` of a double\n * would otherwise print as an exact integer. A number that is not a safe\n * integer is still refused here, rather than printed.\n */\nimport { DEFAULT_BUDGET, Decimal, evaluate, fixedCapabilities } from '@formancy/expressions'\nimport type { Capabilities, ExpressionValue } from '@formancy/expressions'\nimport { compileReport, diagnose, expressionValues } from '@formancy/report-core'\nimport type { CompiledExpression, Diagnostic, ExpressionValues, ReportCompilation } from '@formancy/report-core'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport type { TypedValue } from './format.js'\nimport { canonicalInstant } from './values.js'\n\n/**\n * Steps one evaluation may take: upstream's default for a formancy form's\n * expression (`DEFAULT_BUDGET`). A report expression reads single values, so\n * the only way to spend many steps is a comprehension over a list literal;\n * the deepest the structural limits allow, 64 by 64, measured 8,385 steps,\n * and `evaluate.test.ts` holds that it fits while one reading three values\n * in each turn (28,865 steps) does not.\n */\nexport const EXPRESSION_STEP_BUDGET = DEFAULT_BUDGET.maxSteps\n\n/**\n * Steps every evaluation of one render may take together, each charged its\n * steps and one more for itself. Measured as a render spends them, through\n * `condition()` with each evaluation's binding included, on 15 October\n * 2026, on an Intel i9-10900K under Node 24.21 with `@formancy/expressions`\n * 0.5.0: ten million steps of `row.urgent` took 10.0 seconds (1.00\n * microseconds a step) and of `row.amount * dec(\"1.081\") > dec(\"10\")` 13.0\n * (1.30). An earlier measurement, of upstream's `evaluate` alone, had put\n * that budget at 8.5 seconds and missed the binding. So the budget is five\n * million: about 5 to 6.5 seconds of evaluation on that machine, against\n * the plan's investigation target of ten seconds in all for a hundred-page\n * report. A report of `MAX_DETAIL_ROWS` rows evaluating ten one-read\n * expressions per row spends 2,000,000.\n */\nexport const RENDER_STEP_BUDGET = 5_000_000\n\n/**\n * What `now()`, `today()` and `random()` would give: nothing a report may\n * read (0009), fixed so that one reached anyway gives the same answer in\n * every render.\n */\nexport const CAPABILITIES: Capabilities = fixedCapabilities({ nowMs: 0, today: '1970-01-01', random: 0 })\n\nexport const EVALUATION_ERROR_CODES = [\n /** A path at which the report has no compiled expression: the caller's defect. */\n 'unknown-expression',\n /** A member the expression reads has no value: a field a preview's data lacks, or a total not yet computed. */\n 'missing-value',\n /** A value of another type than its member's, which the data check admits none of. */\n 'unbound-value',\n /** Upstream refused the evaluation: a division by zero, an overflow, a result too large to hand back. */\n 'expression-failed',\n /** The evaluation took more than `EXPRESSION_STEP_BUDGET` steps. */\n 'expression-budget',\n /** The render has spent `RENDER_STEP_BUDGET` steps. */\n 'render-budget',\n /** A number that is not a safe integer: a double, which the diagnostics refuse before anything is evaluated. */\n 'inexact-value',\n /** A list, a map or anything else without text. */\n 'unprintable-value',\n /** A condition that gave something other than a boolean. */\n 'not-a-condition',\n] as const\nexport type EvaluationErrorCode = (typeof EVALUATION_ERROR_CODES)[number]\n\n/** Why an evaluation gave no value, and where. */\nexport interface EvaluationError {\n readonly code: EvaluationErrorCode\n /** For a person: where and what, never a value. */\n readonly message: string\n /** The JSON Pointer to the expression's `cel` in the report. */\n readonly path: string\n readonly componentId?: string\n readonly columnId?: string\n /** The aggregate whose expression this is, for one read from each row. */\n readonly aggregateId?: string\n /** The detail row's index in the data, when the expression read one. */\n readonly row?: number\n}\n\nexport type Evaluation = { readonly ok: true; readonly value: TypedValue | null } | { readonly ok: false; readonly error: EvaluationError }\n\nexport type ConditionEvaluation = { readonly ok: true; readonly value: boolean } | { readonly ok: false; readonly error: EvaluationError }\n\nexport interface ReportExpressions {\n /** What compiled: the programs by path, the members, and the order aggregates are computed in. */\n readonly compilation: ReportCompilation\n /** Steps this render has spent, each evaluation charged its steps and one more. */\n readonly spent: number\n /** The expression at `path` evaluated over `values`; `row` is the detail row's index, for an error to name. */\n evaluate(path: string, values: ExpressionValues, row?: number): Evaluation\n /** The condition at `path` -- a `visibleWhen` or a style rule's `when` -- evaluated over `values`. */\n condition(path: string, values: ExpressionValues, row?: number): ConditionEvaluation\n}\n\nexport type ExpressionsPreparation = { readonly ok: true; readonly expressions: ReportExpressions } | { readonly ok: false; readonly diagnostics: readonly Diagnostic[] }\n\n/** The typed value an expression's result is, or why it is not one. Exported for its test alone. */\nexport function typed(result: ExpressionValue, resultType: string): TypedValue | null | { readonly code: EvaluationErrorCode; readonly what: string } {\n if (result === null) return null\n if (result instanceof Decimal) return { type: 'decimal', value: result }\n switch (typeof result) {\n case 'boolean':\n return { type: 'boolean', value: result }\n case 'string': {\n const instant = resultType === 'timestamp' ? canonicalInstant(result) : undefined\n return instant === undefined ? { type: 'string', value: result } : { type: 'instant', value: instant }\n }\n case 'number':\n // Upstream hands an integer back as a number, and refuses one it cannot hold exactly.\n if (Number.isSafeInteger(result)) return { type: 'integer', value: BigInt(result) }\n return { code: 'inexact-value', what: 'the expression gives a double, which is not exact; dec() keeps a number exact' }\n default:\n return { code: 'unprintable-value', what: 'the expression gives a list or a map, which has no text' }\n }\n}\n\n/** One render's evaluations of a report's expressions. */\nclass Evaluator implements ReportExpressions {\n readonly compilation: ReportCompilation\n readonly #aggregates: readonly string[]\n #spent = 0\n\n constructor(report: ReportDefinition, compilation: ReportCompilation) {\n this.compilation = compilation\n this.#aggregates = report.aggregates.map(({ id }) => id)\n }\n\n get spent(): number {\n return this.#spent\n }\n\n evaluate(path: string, values: ExpressionValues, row?: number): Evaluation {\n const compiled = this.compilation.expressions.get(path)\n if (compiled === undefined) return { ok: false, error: { code: 'unknown-expression', message: `the report has no expression at ${path}`, path } }\n const fail = (code: EvaluationErrorCode, what: string): Evaluation => ({ ok: false, error: this.#error(compiled, code, what, row) })\n for (const read of compiled.reads) {\n const scope = values[read.name]\n if (scope === undefined || !Object.hasOwn(scope, read.member)) return fail('missing-value', `${read.name}.${read.member} has no value: it is missing, which is not null`)\n }\n let bound: Record<string, unknown>\n try {\n bound = expressionValues(compiled, values)\n } catch (error) {\n // report-core's refusal names the member and its type, and never quotes the value.\n return fail('unbound-value', (error as TypeError).message)\n }\n if (this.#spent >= RENDER_STEP_BUDGET) return fail('render-budget', `the render has spent its budget of ${RENDER_STEP_BUDGET} steps`)\n const maxSteps = Math.min(EXPRESSION_STEP_BUDGET, RENDER_STEP_BUDGET - this.#spent - 1)\n const outcome = evaluate(compiled.program, bound, { capabilities: CAPABILITIES, budget: { maxSteps } })\n if (!outcome.ok) {\n const exhausted = outcome.error.kind === 'budget'\n this.#spent += (exhausted ? maxSteps : 0) + 1\n if (!exhausted) return fail('expression-failed', `the expression failed (${outcome.error.code})`)\n if (maxSteps < EXPRESSION_STEP_BUDGET) return fail('render-budget', `the render has spent its budget of ${RENDER_STEP_BUDGET} steps`)\n return fail('expression-budget', `the expression took more than its budget of ${EXPRESSION_STEP_BUDGET} steps`)\n }\n this.#spent += outcome.steps + 1\n const value = typed(outcome.value, compiled.program.resultType)\n return value !== null && 'code' in value ? fail(value.code, value.what) : { ok: true, value }\n }\n\n condition(path: string, values: ExpressionValues, row?: number): ConditionEvaluation {\n const outcome = this.evaluate(path, values, row)\n if (!outcome.ok) return outcome\n if (outcome.value?.type === 'boolean') return { ok: true, value: outcome.value.value }\n const compiled = this.compilation.expressions.get(path) as CompiledExpression\n return { ok: false, error: this.#error(compiled, 'not-a-condition', 'a condition gives true or false, and this expression gives something else', row) }\n }\n\n /** An error about `compiled`, naming where it stands and the row it read. */\n #error(compiled: CompiledExpression, code: EvaluationErrorCode, what: string, row: number | undefined): EvaluationError {\n const { site } = compiled\n const aggregateId = site.path.startsWith('/aggregates/') ? this.#aggregates[Number(site.path.split('/')[2])] : undefined\n const place = [\n site.componentId === undefined ? undefined : `component ${site.componentId}`,\n site.columnId === undefined ? undefined : `column ${site.columnId}`,\n aggregateId === undefined ? undefined : `aggregate ${aggregateId}`,\n row === undefined ? undefined : `detail row ${row}`,\n ].filter((part) => part !== undefined)\n return {\n code,\n message: `${place.join(', ')}: ${what}`,\n path: site.path,\n ...(site.componentId === undefined ? {} : { componentId: site.componentId }),\n ...(site.columnId === undefined ? {} : { columnId: site.columnId }),\n ...(aggregateId === undefined ? {} : { aggregateId }),\n ...(row === undefined ? {} : { row }),\n }\n }\n}\n\n/**\n * `report`'s expressions compiled for one render, or the diagnostics that\n * refuse it: every error `diagnose` gives, which the editor shows too.\n * `report` is one the validator accepts. The evaluations of one render\n * share one budget, so a render prepares its own.\n */\nexport function prepareExpressions(report: ReportDefinition): ExpressionsPreparation {\n const errors = diagnose(report).filter(({ severity }) => severity === 'error')\n if (errors.length > 0) return { ok: false, diagnostics: errors }\n return { ok: true, expressions: new Evaluator(report, compileReport(report)) }\n}\n","/**\n * Why a report did not resolve, as one list a caller reads whatever stage\n * found the problem: the report itself, its expressions, the parameters, the\n * data, the options, an evaluation, a format, an image or a total.\n *\n * Each stage keeps the codes it already has -- report-spec's for structure,\n * report-core's diagnostics for expressions, the data check's for data and\n * parameters, the evaluator's and the formatter's -- so a code means one\n * thing wherever it appears. `stage` says which list a code is from. Like\n * every error the runtime gives, none holds a value from the data.\n */\nimport type { Diagnostic, DiagnosticCode } from '@formancy/report-core'\nimport type { ReportError, ReportErrorCode } from '@formancy/report-spec'\nimport type { DataError, DataErrorCode } from './data-errors.js'\nimport { MAX_DATA_ERRORS } from './data-errors.js'\nimport type { EvaluationError, EvaluationErrorCode } from './evaluate.js'\nimport type { FormatErrorCode } from './format.js'\n\n/** What lowering a report can find wrong besides what each earlier stage finds. */\nexport const RESOLVE_ERROR_CODES = [\n /** A creation date that is not an ISO 8601 instant with its zone. */\n 'invalid-creation-date',\n /** An image whose bytes the host does not have, or a report with images and no way to fetch them. */\n 'missing-asset',\n /** Bytes for an image that are not a `Uint8Array`, or of another media type than the asset declares or a report may draw. */\n 'invalid-asset',\n /** The host's image lookup threw. */\n 'asset-lookup-failed',\n /** A declared rounding on a total that is not a decimal: an integer, a date or an instant has no places to round. */\n 'rounding-not-decimal',\n /** A total over values that cannot be totalled together: a sum of text, a minimum of a number and a date. */\n 'aggregate-value-type',\n /** More errors were found than are listed. */\n 'too-many-errors',\n] as const\nexport type ResolveErrorCode = (typeof RESOLVE_ERROR_CODES)[number]\n\n/** Where in the report an error is, when it is in a component, a table column or a row. */\ninterface Place {\n readonly componentId?: string\n readonly columnId?: string\n /** The detail row's index in the data as the provider gave it. */\n readonly row?: number\n}\n\n/** One error, from the stage that found it, with that stage's code. Its path is a JSON Pointer into what the stage read: the report, the data, the parameters, or '' for the options. */\nexport type RuntimeError =\n | ({ readonly stage: 'report'; readonly code: ReportErrorCode; readonly path: string; readonly message: string } & Place)\n | ({ readonly stage: 'expressions'; readonly code: DiagnosticCode; readonly path: string; readonly message: string } & Place)\n | { readonly stage: 'parameters' | 'data'; readonly code: DataErrorCode; readonly path: string; readonly message: string }\n | ({ readonly stage: 'evaluation'; readonly code: EvaluationErrorCode; readonly path: string; readonly message: string; readonly aggregateId?: string } & Place)\n | ({ readonly stage: 'format'; readonly code: FormatErrorCode; readonly path: string; readonly message: string } & Place)\n | ({ readonly stage: 'resolve'; readonly code: ResolveErrorCode; readonly path: string; readonly message: string } & Place)\n\nexport type RuntimeStage = RuntimeError['stage']\n\n/** The optional parts of a place, written only when present, as exactOptionalPropertyTypes asks. */\nexport function placed(place: { readonly componentId?: string | undefined; readonly columnId?: string | undefined; readonly row?: number | undefined }): Place {\n return {\n ...(place.componentId === undefined ? {} : { componentId: place.componentId }),\n ...(place.columnId === undefined ? {} : { columnId: place.columnId }),\n ...(place.row === undefined ? {} : { row: place.row }),\n }\n}\n\nexport function fromReport(error: ReportError): RuntimeError {\n return { stage: 'report', code: error.code, path: error.path, message: error.message, ...placed(error) }\n}\n\nexport function fromDiagnostic(diagnostic: Diagnostic): RuntimeError {\n return { stage: 'expressions', code: diagnostic.code, path: diagnostic.path, message: diagnostic.message, ...placed(diagnostic) }\n}\n\nexport function fromData(stage: 'parameters' | 'data', error: DataError): RuntimeError {\n return { stage, code: error.code, path: error.path, message: error.message }\n}\n\nexport function fromEvaluation(error: EvaluationError): RuntimeError {\n return {\n stage: 'evaluation',\n code: error.code,\n path: error.path,\n message: error.message,\n ...placed(error),\n ...(error.aggregateId === undefined ? {} : { aggregateId: error.aggregateId }),\n }\n}\n\n/**\n * The errors and warnings one resolution collects. Errors are bounded as the\n * data check bounds its own: past `MAX_DATA_ERRORS`, one `too-many-errors`\n * says the list was cut short, and `full` tells a long loop to stop. A\n * warning is said once per path: a preview that lacks a field a thousand\n * rows read warns once for it.\n */\nexport class Problems {\n readonly #errors: RuntimeError[] = []\n readonly #warnings = new Map<string, RuntimeError>()\n #overflowed = false\n\n error(error: RuntimeError): void {\n if (this.#errors.length < MAX_DATA_ERRORS) this.#errors.push(error)\n else this.#overflowed = true\n }\n\n warn(warning: RuntimeError): void {\n const key = `${warning.stage} ${warning.code} ${warning.path}`\n if (!this.#warnings.has(key)) this.#warnings.set(key, warning)\n }\n\n /** Whether the error list is cut short: nothing more is worth computing. */\n get full(): boolean {\n return this.#overflowed\n }\n\n get failed(): boolean {\n return this.#errors.length > 0\n }\n\n errors(): RuntimeError[] {\n const errors = [...this.#errors]\n if (this.#overflowed) errors.push({ stage: 'resolve', code: 'too-many-errors', path: '', message: `more than ${MAX_DATA_ERRORS} errors were found; the first ${MAX_DATA_ERRORS} are listed` })\n return errors\n }\n\n warnings(): RuntimeError[] {\n return [...this.#warnings.values()]\n }\n}\n","/**\n * What one resolution knows while it lowers a report, and the three scopes\n * a value is read in (0007): the report, a group of rows, one detail row.\n *\n * A scope is the values an expression is handed -- `params`, `header`,\n * `totals`, and `group` or `row` where there is one -- and where a currency\n * format finds a currency. Every expression is evaluated through `valueOf`\n * or `holds`, so an evaluation that fails is an error in one place, and a\n * preview that lacks a field degrades in one place: what reads it prints\n * nothing, and a condition over it does not hold, each said once as a\n * warning. In a final render a missing field never gets this far: the data\n * check refuses it.\n */\nimport type { ExpressionValues } from '@formancy/report-core'\nimport type { FieldRef, FieldType, ParameterType, ReportDefinition } from '@formancy/report-spec'\nimport type { CheckedData, CheckedRecord } from './data.js'\nimport type { TextStyle } from './document.js'\nimport type { ReportExpressions } from './evaluate.js'\nimport type { CurrencyScope, Formatter, TypedValue } from './format.js'\nimport type { CheckedParameters } from './parameters.js'\nimport { fromEvaluation } from './resolve-errors.js'\nimport type { Problems } from './resolve-errors.js'\nimport type { OrderedRow, RowGroup } from './sort-group.js'\nimport type { ImageValue } from './values.js'\n\n/** An approved asset, named as report-spec names one: by id, pinned by digest. */\nexport interface ImageRef {\n readonly asset: string\n readonly digest: string\n}\n\n/** What the host holds for an approved asset: its bytes, already fetched, and their media type. */\nexport interface ImageBytes {\n readonly mediaType: string\n readonly bytes: Uint8Array\n}\n\n/**\n * The host's lookup of an approved asset's bytes by its id and digest, or\n * undefined when it has none. Never an address: the runtime fetches nothing.\n */\nexport type ImageResolver = (ref: ImageRef) => ImageBytes | undefined\n\n/** Each aggregate's value over some rows, by id: a typed value, or null where it has none. */\nexport type AggregateValues = ReadonlyMap<string, TypedValue | null>\n\n/** The totals of one render: each aggregate over every row, and the same over any group of them. */\nexport interface Totals {\n readonly report: AggregateValues\n over(rows: readonly OrderedRow[]): AggregateValues\n}\n\n/** One resolution's inputs, checked, and what it collects. */\nexport interface Render {\n /** The copy validation read. */\n readonly report: ReportDefinition\n readonly expressions: ReportExpressions\n readonly formatter: Formatter\n readonly params: CheckedParameters\n readonly data: CheckedData\n readonly problems: Problems\n readonly preview: boolean\n readonly images: ImageResolver | undefined\n /** Each print style, by id, as the document's style. */\n readonly styles: ReadonlyMap<string, TextStyle>\n readonly totals: Totals\n}\n\n/** Where a value is read: what its expressions are handed, where its currency comes from, and what an error there names. */\nexport interface Scope {\n readonly values: ExpressionValues\n readonly currency: CurrencyScope\n /** The current group's aggregates, in a group's header and footer. */\n readonly group?: AggregateValues\n /** The record a detail field is read from: the current row, or a group's first row, whose key every row of the group shares. */\n readonly record?: CheckedRecord\n /** The current row's index in the data as the provider gave it, for an error to name. */\n readonly row?: number\n}\n\n/** Each aggregate's value as an expression is handed it: the typed value's own, or null. */\nfunction raw(values: AggregateValues): Record<string, unknown> {\n return Object.fromEntries([...values].map(([id, value]) => [id, value === null ? null : value.value]))\n}\n\n/** The header record, or none when the report declares no header dataset. */\nfunction headerOf(render: Pick<Render, 'data'>): CheckedRecord {\n return render.data.header ?? {}\n}\n\nexport function reportScope(render: Pick<Render, 'params' | 'data'>, totals: AggregateValues): Scope {\n const header = headerOf(render)\n return { values: { params: render.params, header, totals: raw(totals) }, currency: { params: render.params, header } }\n}\n\n/**\n * A group's header and footer: the report's values, and the group's\n * aggregates and key as `group`. `by` is the field grouped by; where a\n * preview's rows lack it the key is missing, as the field is, not null.\n */\nexport function groupScope(render: Render, group: RowGroup, aggregates: AggregateValues, by: string): Scope {\n const record = (group.rows[0] as OrderedRow).record\n const header = headerOf(render)\n const key = Object.hasOwn(record, by) ? { key: group.key } : {}\n return {\n values: { params: render.params, header, totals: raw(render.totals.report), group: { ...raw(aggregates), ...key } },\n currency: { params: render.params, header, row: record },\n group: aggregates,\n record,\n }\n}\n\n/** One detail row: the report's values, and the row's as `row`. */\nexport function rowScope(render: Pick<Render, 'params' | 'data'>, totals: AggregateValues, row: OrderedRow): Scope {\n const header = headerOf(render)\n return {\n values: { params: render.params, header, totals: raw(totals), row: row.record },\n currency: { params: render.params, header, row: row.record },\n record: row.record,\n row: row.index,\n }\n}\n\n/** A failed evaluation: an error, or in a preview a value the data lacks, which is a warning. Returns whether it was only a warning. */\nfunction failed(render: Pick<Render, 'problems' | 'preview'>, outcome: { readonly error: Parameters<typeof fromEvaluation>[0] }): boolean {\n if (render.preview && outcome.error.code === 'missing-value') {\n // Said once for the expression, naming the first row, not once per row: the data check has already said which field is missing.\n const error = fromEvaluation(outcome.error)\n render.problems.warn({ ...error, message: `${error.message}; this preview prints nothing for it` })\n return true\n }\n render.problems.error(fromEvaluation(outcome.error))\n return false\n}\n\n/** The value of the expression whose `cel` is at `path`, read in `scope`; null for none, undefined when it failed and the failure is recorded. */\nexport function valueOf(render: Pick<Render, 'expressions' | 'problems' | 'preview'>, scope: Scope, path: string): TypedValue | null | undefined {\n const outcome = render.expressions.evaluate(path, scope.values, scope.row)\n if (outcome.ok) return outcome.value\n return failed(render, outcome) ? null : undefined\n}\n\n/** Whether the condition whose `cel` is at `path` holds in `scope`; undefined when it failed and the failure is recorded as an error. */\nexport function holds(render: Pick<Render, 'expressions' | 'problems' | 'preview'>, scope: Scope, path: string): boolean | undefined {\n const outcome = render.expressions.condition(path, scope.values, scope.row)\n if (outcome.ok) return outcome.value\n return failed(render, outcome) ? false : undefined\n}\n\n/** The type the report's contract gives `ref`'s field; the validator has checked that it declares one. */\nexport function fieldType(report: ReportDefinition, ref: FieldRef): FieldType {\n return report.datasets[ref.dataset]?.fields.find(({ id }) => id === ref.field)?.type as FieldType\n}\n\nexport function parameterType(report: ReportDefinition, parameter: string): ParameterType {\n return report.parameters.find(({ id }) => id === parameter)?.type as ParameterType\n}\n\n/**\n * The value of `ref`, typed by its contract: a header field's from the\n * header, a detail field's from `record`. Null where it is null, and where\n * a preview's data lacks it, which the data check has already warned of. An\n * image field is drawn, never printed (0007), and reads as null here.\n */\nexport function fieldValue(render: Pick<Render, 'report' | 'data'>, record: CheckedRecord | undefined, ref: FieldRef): TypedValue | null {\n const value = (ref.dataset === 'header' ? render.data.header : record)?.[ref.field] ?? null\n const type = fieldType(render.report, ref)\n if (value === null || type === 'image') return null\n return { type, value } as TypedValue\n}\n\n/** An image field's value in the header: an approved asset, or null when there is none to draw. */\nexport function imageValue(render: Pick<Render, 'data'>, ref: FieldRef): ImageValue | null {\n return (render.data.header?.[ref.field] as ImageValue | null | undefined) ?? null\n}\n","/**\n * An image component lowered to the bytes it draws.\n *\n * An image shows an asset the template pins, or an image field of the\n * header dataset (0007). Either way it names an approved asset by its id\n * and digest, and the host's lookup hands over the bytes: the runtime never\n * follows an address and fetches nothing. What comes back is checked here --\n * bytes, and a media type a report may draw, the one the template declares\n * for its own asset -- and copied, so that nothing the host changes\n * afterwards reaches the document. Whether the bytes are a picture is the\n * renderer's to say (`invalid-asset`).\n *\n * The lookup is trusted to return the bytes the digest pins: the runtime has\n * no hash function of its own, being free of Node and of the DOM, and does\n * not check them against it.\n *\n * An image field with no value draws nothing, and its box is kept as space,\n * so that what follows it stands where it would with a picture: null prints\n * as nothing (0007), and nothing moves.\n *\n * Each approved asset is asked for once per render, and every image that\n * draws it shares the one copy, so that a logo on every page header, or a\n * photo drawn by forty components, is held and embedded once. An answer\n * past `MAX_ASSET_BYTES` is refused before it is copied.\n */\nimport { ASSET_MEDIA_TYPES } from '@formancy/report-spec'\nimport type { AssetMediaType, ImageComponent } from '@formancy/report-spec'\nimport { MAX_ASSET_BYTES } from './document.js'\nimport type { Image, ImageAsset, Spacer } from './document.js'\nimport { imageValue } from './render-context.js'\nimport type { ImageBytes, ImageRef, Render } from './render-context.js'\nimport type { ResolveErrorCode } from './resolve-errors.js'\n\n/** Why an asset's bytes could not be had: the code, and what to say after the component's id. */\ninterface Refusal {\n readonly code: ResolveErrorCode\n readonly message: string\n}\n\n/** What the host handed over, if it is bytes of a media type a report draws, within the limit: copied. A string says why it is not. */\nfunction checkedBytes(found: unknown, declared: AssetMediaType | undefined): { readonly mediaType: AssetMediaType; readonly bytes: Uint8Array } | string {\n const media = `is not bytes of ${declared === undefined ? ASSET_MEDIA_TYPES.join(' or ') : declared}`\n if (typeof found !== 'object' || found === null) return media\n const { mediaType, bytes } = found as Partial<ImageBytes>\n if (!(bytes instanceof Uint8Array) || !ASSET_MEDIA_TYPES.includes(mediaType as AssetMediaType)) return media\n if (declared !== undefined && mediaType !== declared) return media\n if (bytes.length > MAX_ASSET_BYTES) return `is ${bytes.length} bytes; an asset may have ${MAX_ASSET_BYTES} (20 MB)`\n return { mediaType: mediaType as AssetMediaType, bytes: new Uint8Array(bytes) }\n}\n\n/** The bytes of `ref`, asked of the host and checked, or why they could not be had. */\nfunction fetched(render: Render, ref: ImageRef, declared: AssetMediaType | undefined): ImageAsset | Refusal {\n if (render.images === undefined) return { code: 'missing-asset', message: 'the report draws an image, and the host gave no way to fetch approved assets' }\n let found: unknown\n let bytes: ReturnType<typeof checkedBytes>\n try {\n // The answer is read inside the guard too: a getter on it is the host's code, and may throw.\n found = render.images(ref)\n bytes = checkedBytes(found, declared)\n } catch {\n return { code: 'asset-lookup-failed', message: `fetching the approved asset ${ref.asset} failed` }\n }\n if (found === undefined) return { code: 'missing-asset', message: `the host has no bytes for the approved asset ${ref.asset} at its digest` }\n if (typeof bytes === 'string') return { code: 'invalid-asset', message: `the host's answer for the approved asset ${ref.asset} ${bytes}` }\n return { id: ref.asset, ...bytes }\n}\n\n/** Each render's assets, by id, digest and the type declared for them: asked for once, and shared. */\nconst ASSETS = new WeakMap<Render, Map<string, ImageAsset | Refusal>>()\n\nfunction assetOf(render: Render, ref: ImageRef, declared: AssetMediaType | undefined): ImageAsset | Refusal {\n const cache = ASSETS.get(render) ?? new Map<string, ImageAsset | Refusal>()\n ASSETS.set(render, cache)\n const key = JSON.stringify([ref.asset, ref.digest, declared ?? null])\n const known = cache.get(key)\n if (known !== undefined) return known\n const asset = fetched(render, ref, declared)\n cache.set(key, asset)\n return asset\n}\n\n/** `component`, at `path`, as the image it draws, the space it keeps when its field is null, or undefined when its bytes could not be had, which is recorded. */\nexport function imageBlock(render: Render, component: ImageComponent, path: string): Image | Spacer | undefined {\n const { source } = component\n let ref: ImageRef\n let declared: AssetMediaType | undefined\n if (source.kind === 'asset') {\n // report-spec refuses an image of an asset the report does not declare.\n const asset = render.report.assets.find(({ id }) => id === source.asset) as { readonly id: string; readonly mediaType: AssetMediaType; readonly digest: string }\n ref = { asset: asset.id, digest: asset.digest }\n declared = asset.mediaType\n } else {\n const value = imageValue(render, source.field)\n if (value === null) return { kind: 'spacer', height: component.height }\n ref = { asset: value.asset, digest: value.digest }\n }\n const asset = assetOf(render, ref, declared)\n if ('code' in asset) {\n render.problems.error({ stage: 'resolve', code: asset.code, path: `${path}/source`, message: `component ${component.id}: ${asset.message}`, componentId: component.id })\n return undefined\n }\n return { kind: 'image', asset, width: component.width, height: component.height, fit: component.fit }\n}\n","/**\n * A run of a report -- literal, bound, computed, totalled or a page counter\n * -- lowered to the text it prints, formatted for the report's locale.\n *\n * The one place each kind of inline gets its value: a field from the header\n * or the current record, a parameter from the checked parameters, an\n * expression from its evaluation in the scope it stands in, an aggregate\n * from the report's totals or the current group's. Every value is formatted\n * by `format.ts` with the inline's format, or printed plainly without one,\n * and null prints as nothing (0007). A page counter stays a field the\n * engine fills in, since only it knows the pages.\n */\nimport type { Inline as ReportInline } from '@formancy/report-spec'\nimport type { Inline } from './document.js'\nimport type { TypedValue } from './format.js'\nimport { fieldValue, parameterType, valueOf } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\nimport { placed } from './resolve-errors.js'\n\n/** What an error names besides the inline's path: the component, and in a table the column. */\nexport interface Owner {\n readonly componentId?: string\n readonly columnId?: string\n}\n\n/** The value `inline` prints, read in `scope`; undefined when its evaluation failed, which is recorded. */\nfunction valueAt(render: Render, scope: Scope, inline: Exclude<ReportInline, { kind: 'text' | 'pageNumber' | 'pageCount' }>, path: string): TypedValue | null | undefined {\n switch (inline.kind) {\n case 'field':\n return fieldValue(render, scope.record, inline.field)\n case 'parameter': {\n const value = render.params[inline.parameter] ?? null\n return value === null ? null : ({ type: parameterType(render.report, inline.parameter), value } as TypedValue)\n }\n case 'expression':\n return valueOf(render, scope, `${path}/expression/cel`)\n case 'aggregate':\n // report-spec allows a group's aggregate only where there is a group.\n return (inline.over === 'group' ? scope.group : render.totals.report)?.get(inline.aggregate) ?? null\n }\n}\n\n/** `inline`, at `path` in the report, as the run it prints in `scope`; undefined when it could not be, which is recorded. */\nexport function runOf(render: Render, scope: Scope, inline: ReportInline, path: string, owner: Owner): Inline | undefined {\n if (inline.kind === 'text') return { text: inline.text }\n if (inline.kind === 'pageNumber' || inline.kind === 'pageCount') return { field: inline.kind }\n const value = valueAt(render, scope, inline, path)\n if (value === undefined) return undefined\n const formatted = render.formatter.format(value, inline.format, scope.currency)\n if (formatted.ok) return { text: formatted.text }\n const where = [owner.componentId && `component ${owner.componentId}`, owner.columnId && `column ${owner.columnId}`, scope.row !== undefined && `detail row ${scope.row}`].filter(Boolean).join(', ')\n render.problems.error({ stage: 'format', code: formatted.code, path, message: `${where}: ${formatted.message}`, ...placed({ ...owner, row: scope.row }) })\n return undefined\n}\n\n/** The text of runs that hold no page counter: what a table cell or a group header prints. */\nexport function textOfRuns(runs: readonly Inline[]): string {\n return runs.map((run) => ('text' in run ? run.text : '')).join('')\n}\n","/**\n * Print styles resolved to the one style each piece of text prints in.\n *\n * report-spec's styles are tokens (0007); here they are laid over each other\n * once, and the document carries the result, so an engine never merges\n * styles (`TextStyle`). The order, each later one's property winning:\n *\n * 1. what the component stands in passes down: a section's, a columns\n * block's or a keep-together block's style is the base of the text\n * inside it;\n * 2. the component's own `style`;\n * 3. each of its `styleWhen` rules that holds, in order.\n *\n * In a table, the table's resolved style is the base of every row: the\n * header's `headerStyle`, a group header's, a footer row's own, and each\n * column's style and rules over a detail cell. An image, a line, a\n * rectangle, a spacer and a page break print no text; a style on one is\n * read for its rules' conditions, and changes nothing.\n */\nimport type { PrintStyle, StyleRule } from '@formancy/report-spec'\nimport type { TextStyle } from './document.js'\nimport { holds } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\n\n/** Each print style as the document's: the same tokens without the id. */\nexport function documentStyles(styles: readonly PrintStyle[]): ReadonlyMap<string, TextStyle> {\n return new Map(styles.map(({ id, ...style }) => [id, style]))\n}\n\n/** `styles` laid over each other, a later one's property winning; undefined when none sets anything. */\nexport function layered(...styles: readonly (TextStyle | undefined)[]): TextStyle | undefined {\n const merged: TextStyle = Object.assign({}, ...styles.filter((style) => style !== undefined)) as TextStyle\n return Object.keys(merged).length === 0 ? undefined : merged\n}\n\n/**\n * `base`, then the print style `style` names, then each rule at\n * `<path>/<index>` whose condition holds in `scope`. Undefined when nothing\n * sets anything, or when a condition failed, which is recorded.\n */\nexport function styled(render: Render, scope: Scope, base: TextStyle | undefined, style: string | undefined, rules: readonly StyleRule[] | undefined, path: string): TextStyle | undefined {\n const held: TextStyle[] = []\n for (const [index, rule] of (rules ?? []).entries()) {\n if (holds(render, scope, `${path}/${index}/when/cel`) === true) held.push(render.styles.get(rule.style) as TextStyle)\n }\n return layered(base, style === undefined ? undefined : render.styles.get(style), ...held)\n}\n","/**\n * The table over the detail dataset, lowered to the rows it prints.\n *\n * Its rows are ordered and grouped by `sort-group.ts` (0007): the group's\n * key first, then the sort keys, ties in the provider's order. Then, in\n * that order:\n *\n * - for each group, one line across the table read in the group's scope,\n * its rows, and its footer rows, whose aggregates are the group's;\n * - the totals rows, whose aggregates are over every row;\n * - with no detail rows, the table's empty text in their place, and its\n * totals still printed: a count and a sum of nothing are 0.\n *\n * A column whose condition does not hold is left out, read once per report:\n * its header, every cell under it and its footer cells, and the fill columns\n * share its width. A table every column of which is hidden prints nothing.\n * Each detail cell is read in its row's scope, its column's style rules too;\n * every other row has one style.\n */\nimport type { TableColumn as ReportColumn, TableComponent, TableFooterRow } from '@formancy/report-spec'\nimport type { Table, TableRow, TextStyle } from './document.js'\nimport { runOf, textOfRuns } from './inlines.js'\nimport { groupScope, holds, reportScope, rowScope } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\nimport { orderTable } from './sort-group.js'\nimport type { OrderedRow } from './sort-group.js'\nimport { layered, styled } from './styles.js'\n\n/** A column that prints, and where it stands in the report's list of the table's columns. */\ninterface Shown {\n readonly column: ReportColumn\n readonly index: number\n}\n\n/** What every row of one table is read with. */\ninterface Lowering {\n readonly render: Render\n readonly table: TableComponent\n readonly path: string\n readonly shown: readonly Shown[]\n /** The table's own style, laid under every row's. */\n readonly base: TextStyle | undefined\n}\n\n/** `style` as a row's: the table's under the named print style; absent when neither sets anything. */\nfunction rowStyle(lowering: Lowering, style: string | undefined): { readonly style?: TextStyle } {\n const resolved = layered(lowering.base, style === undefined ? undefined : lowering.render.styles.get(style))\n return resolved === undefined ? {} : { style: resolved }\n}\n\n/** One detail row: each shown column's value and own style, read in the row's scope. */\nfunction detailRow(lowering: Lowering, row: OrderedRow): TableRow {\n const { render, table, path } = lowering\n const scope = rowScope(render, render.totals.report, row)\n const cells = lowering.shown.map(({ column, index }) => {\n const run = runOf(render, scope, column.value, `${path}/columns/${index}/value`, { componentId: table.id, columnId: column.id })\n return run === undefined ? '' : textOfRuns([run])\n })\n const own = lowering.shown.map(({ column, index }) => styled(render, scope, undefined, column.style, column.styleWhen, `${path}/columns/${index}/styleWhen`))\n const cellStyles = own.some((style) => style !== undefined) ? { cellStyles: own.map((style) => (style === undefined ? null : (layered(lowering.base, style) as TextStyle))) } : {}\n return { kind: 'detail', cells, ...(lowering.base === undefined ? {} : { style: lowering.base }), ...cellStyles }\n}\n\n/** Footer rows read in `scope`: under a group, or under the table. A shown column without a cell in a row prints nothing there. */\nfunction footerRows(lowering: Lowering, rows: readonly TableFooterRow[] | undefined, at: string, kind: 'groupFooter' | 'total', scope: Scope): TableRow[] {\n const { render, table } = lowering\n return (rows ?? []).map((row, rowIndex) => {\n const cells = lowering.shown.map(({ column }) => {\n const cellIndex = row.cells.findIndex((cell) => cell.column === column.id)\n const cell = row.cells[cellIndex]\n if (cell === undefined) return ''\n const run = runOf(render, scope, cell.value, `${at}/${rowIndex}/cells/${cellIndex}/value`, { componentId: table.id, columnId: column.id })\n return run === undefined ? '' : textOfRuns([run])\n })\n return { kind, cells, ...rowStyle(lowering, row.style) }\n })\n}\n\n/** The rows of a table that groups: per group, its header line, its rows and its footer. */\nfunction groupedRows(lowering: Lowering, groups: NonNullable<ReturnType<typeof orderTable>['groups']>): TableRow[] {\n const { render, table, path } = lowering\n const group = table.group as NonNullable<TableComponent['group']>\n const rows: TableRow[] = []\n for (const each of groups) {\n if (render.problems.full) break\n const scope = groupScope(render, each, render.totals.over(each.rows), group.by.field)\n const runs = group.header.map((inline, index) => runOf(render, scope, inline, `${path}/group/header/${index}`, { componentId: table.id }))\n rows.push({ kind: 'groupHeader', cells: [textOfRuns(runs.filter((run) => run !== undefined))], across: true, ...rowStyle(lowering, group.headerStyle) })\n for (const row of each.rows) rows.push(detailRow(lowering, row))\n rows.push(...footerRows(lowering, group.footer, `${path}/group/footer`, 'groupFooter', scope))\n }\n return rows\n}\n\n/**\n * `table`, at `path`, as the document's table, `base` its own resolved\n * style; undefined when every column is hidden. A value that could not be\n * read prints nothing here, and is recorded as an error, so the report is\n * refused.\n */\nexport function tableBlock(render: Render, table: TableComponent, path: string, base: TextStyle | undefined): Table | undefined {\n const scope = reportScope(render, render.totals.report)\n const shown = table.columns\n .map((column, index) => ({ column, index }))\n .filter(({ column, index }) => column.visibleWhen === undefined || holds(render, scope, `${path}/columns/${index}/visibleWhen/cel`) === true)\n if (shown.length === 0) return undefined\n const lowering: Lowering = { render, table, path, shown, base }\n const ordered = orderTable(render.report, table, render.data.detail)\n const rows: TableRow[] = []\n if (ordered.groups !== undefined) rows.push(...groupedRows(lowering, ordered.groups))\n else {\n for (const row of ordered.rows) {\n if (render.problems.full) break\n rows.push(detailRow(lowering, row))\n }\n }\n rows.push(...footerRows(lowering, table.totals, `${path}/totals`, 'total', scope))\n const headerStyle = layered(base, table.headerStyle === undefined ? undefined : render.styles.get(table.headerStyle))\n return {\n kind: 'table',\n id: table.id,\n columns: shown.map(({ column }) => ({ width: column.width, align: column.align })),\n header: shown.map(({ column }) => column.header),\n ...(headerStyle === undefined ? {} : { headerStyle }),\n rows,\n emptyText: table.emptyText,\n }\n}\n","/**\n * A report's components lowered to the document's blocks, region by region.\n *\n * Every component is read in the report's scope: its condition first, and a\n * component whose condition does not hold prints nothing, nor does anything\n * inside it. Then its style (`styles.ts`), and then what it is. A kind maps\n * to a block through a table over every kind, so a kind added to the format\n * without a way down does not compile.\n *\n * The report header is the start of the body and the summary its end, so\n * the document has three regions: the page header and footer, repeated on\n * every page, and the body.\n */\nimport type { Component, ComponentKind, RegionName } from '@formancy/report-spec'\nimport type { Block, TextStyle } from './document.js'\nimport { imageBlock } from './images.js'\nimport { runOf } from './inlines.js'\nimport { tableBlock } from './lower-table.js'\nimport { holds, reportScope } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\nimport { styled } from './styles.js'\n\n/** The document's regions, lowered. */\nexport interface LoweredRegions {\n readonly pageHeader: readonly Block[]\n readonly pageFooter: readonly Block[]\n readonly body: readonly Block[]\n}\n\n/** What one component is lowered with: where it is, the report scope, and its resolved style. */\ninterface At {\n readonly render: Render\n readonly scope: Scope\n readonly path: string\n readonly style: TextStyle | undefined\n}\n\ntype Lowerer<K extends ComponentKind> = (component: Extract<Component, { kind: K }>, at: At) => Block | undefined\n\n/** `value` under `key` when it is defined: the document writes only what is set. */\nconst optional = <K extends string, V>(key: K, value: V | undefined): { [P in K]?: V } => (value === undefined ? {} : ({ [key]: value } as { [P in K]: V }))\n\nconst LOWER: { readonly [K in ComponentKind]: Lowerer<K> } = {\n text: (text, { render, scope, path, style }) => {\n const runs = text.content.flatMap((inline, index) => runOf(render, scope, inline, `${path}/content/${index}`, { componentId: text.id }) ?? [])\n return { kind: 'paragraph', runs, ...optional('style', style), ...(text.keepWithNext === true ? { keepWithNext: true } : {}) }\n },\n image: (image, { render, path }) => imageBlock(render, image, path),\n line: (line) => ({ kind: 'rule', thickness: line.thickness, ...optional('color', line.color) }),\n rectangle: (rectangle) => ({ kind: 'rectangle', width: rectangle.width, height: rectangle.height, ...optional('fill', rectangle.fill), ...optional('stroke', rectangle.stroke) }),\n spacer: (spacer) => ({ kind: 'spacer', height: spacer.height }),\n columns: (columns, { render, path, style }) => ({\n kind: 'columns',\n columns: columns.columns.map((slot, index) => ({ width: slot.width, blocks: blocksOf(render, slot.components, `${path}/columns/${index}/components`, style) })),\n }),\n section: (section, { render, path, style }) => ({\n kind: 'section',\n blocks: blocksOf(render, section.components, `${path}/components`, style),\n ...optional('border', section.border),\n ...optional('fill', section.fill),\n ...optional('padding', section.padding),\n }),\n table: (table, { render, path, style }) => tableBlock(render, table, path, style),\n pageBreak: () => ({ kind: 'pageBreak' }),\n keepTogether: (kept, { render, path, style }) => ({ kind: 'keepTogether', blocks: blocksOf(render, kept.components, `${path}/components`, style) }),\n}\n\n/** `component`, at `path`, as the block it prints; undefined when it prints nothing, or could not be lowered, which is recorded. */\nfunction blockOf(render: Render, component: Component, path: string, inherited: TextStyle | undefined): Block | undefined {\n const scope = reportScope(render, render.totals.report)\n if (component.visibleWhen !== undefined && holds(render, scope, `${path}/visibleWhen/cel`) !== true) return undefined\n const style = styled(render, scope, inherited, component.style, component.styleWhen, `${path}/styleWhen`)\n return (LOWER[component.kind] as Lowerer<ComponentKind>)(component as never, { render, scope, path, style })\n}\n\n/** The components of the list at `path`, in order, as the blocks they print. */\nfunction blocksOf(render: Render, components: readonly Component[], path: string, inherited: TextStyle | undefined): Block[] {\n return components.flatMap((component, index) => blockOf(render, component, `${path}/${index}`, inherited) ?? [])\n}\n\nfunction region(render: Render, name: RegionName): Block[] {\n return blocksOf(render, render.report.regions[name], `/regions/${name}`, undefined)\n}\n\n/** Every region of `render`'s report, lowered: the report header, body and summary as the one body. */\nexport function lowerRegions(render: Render): LoweredRegions {\n return {\n pageHeader: region(render, 'pageHeader'),\n pageFooter: region(render, 'pageFooter'),\n body: [...region(render, 'reportHeader'), ...region(render, 'body'), ...region(render, 'summary')],\n }\n}\n","/**\n * Whether a report can be rendered at all, before any data is read: the\n * first two levels of plan 15, structure and bindings.\n *\n * A report reaches the runtime as untrusted input, whatever its type says --\n * parsed from storage, posted by a browser. So it is validated again here,\n * with report-spec's `validateReport`, and what the runtime goes on to read\n * is the copy validation made, which no later change to the caller's object\n * reaches. Then its expressions are compiled with report-core, and a report\n * the editor's diagnostics give an error for is refused (0009): the runtime\n * never renders what the editor refuses.\n */\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { validateReport } from '@formancy/report-spec'\nimport { prepareExpressions } from './evaluate.js'\nimport type { ReportExpressions } from './evaluate.js'\nimport { fromDiagnostic, fromReport } from './resolve-errors.js'\nimport type { RuntimeError } from './resolve-errors.js'\n\nexport type ReportCheck =\n | { readonly ok: true; /** The copy validation read. */ readonly report: ReportDefinition; readonly expressions: ReportExpressions }\n | { readonly ok: false; readonly errors: readonly RuntimeError[] }\n\n/**\n * `report` validated and its expressions compiled for one render, or every\n * reason it is refused: each structural error, or, for a report that is\n * structurally valid, each diagnostic of severity error.\n */\nexport function checkReport(report: unknown): ReportCheck {\n const validation = validateReport(report)\n if (!validation.valid) return { ok: false, errors: validation.errors.map(fromReport) }\n const prepared = prepareExpressions(validation.report)\n if (!prepared.ok) return { ok: false, errors: prepared.diagnostics.map(fromDiagnostic) }\n return { ok: true, report: validation.report, expressions: prepared.expressions }\n}\n","/**\n * The report's aggregates, computed exactly, once, here (0007): over every\n * detail row for `totals`, and over a group's rows for `group`.\n *\n * - **In report-core's order.** An aggregate's expression may read another\n * aggregate's total, so each is computed after every one it reads, in the\n * order `compileReport` gives (0009); an aggregate that could never be\n * computed has already refused the report.\n * - **Each row read once.** What an aggregate reads from a row is read once\n * per render, with the report's totals, and kept by the row's index; a\n * group's aggregate is the same function over its rows' values. So a\n * group's subtotal and the report's total are totals of the same values,\n * and the subtotals of a sum that declares no rounding add up to the\n * total. A declared rounding is applied to each group's exact sum and to\n * the report's, once each, so rounded subtotals need not add up to the\n * rounded total: two groups of 0.02, rounded to 0.05, print 0.00 and 0.00\n * over 0.05.\n * - **Exact, and of one kind.** Integers as BigInt, decimals as `Decimal`,\n * through `decimal.ts`; nothing passes through a JavaScript number. A\n * total report-core compiled as a decimal is a decimal, its 0 too, and so\n * is one whose kind the compiler could not tell (`dyn`) once it declares a\n * rounding or meets a decimal; a group's total is of the report total's\n * kind, so an expression reading `group.<id>` meets one type.\n * - **Nulls are skipped**, and so is a value a preview's data lacks. Over no\n * values a count and a sum are 0 and the rest null (0007).\n * - **Declared rounding is applied once**, to the exact result: an average\n * always declares one, and a sum, a minimum or a maximum of decimals may.\n * A rounding on a total that is an integer or a moment is refused, never\n * ignored.\n */\nimport { compareDecimal, Decimal } from '@formancy/expressions'\nimport type { AggregateDef, Rounding } from '@formancy/report-spec'\nimport { averageDecimals, roundDecimalAs, sumDecimals } from './decimal.js'\nimport type { TypedValue } from './format.js'\nimport { fieldValue, rowScope, valueOf } from './render-context.js'\nimport type { AggregateValues, Render, Totals } from './render-context.js'\nimport type { ResolveErrorCode } from './resolve-errors.js'\nimport type { OrderedRow } from './sort-group.js'\nimport { fixedWidth } from './sort-group.js'\n\n/** Why a total has no value: its code and what to say. */\ninterface Refusal {\n readonly code: ResolveErrorCode\n readonly message: string\n}\n\ntype Total = TypedValue | null | Refusal\n\nconst isRefusal = (value: Total): value is Refusal => value !== null && 'code' in value\n\nconst integer = (value: bigint): TypedValue => ({ type: 'integer', value })\nconst decimal = (value: Decimal): TypedValue => ({ type: 'decimal', value })\nconst asDecimal = (value: TypedValue): Decimal => (value.type === 'integer' ? new Decimal(value.value, 0) : (value.value as Decimal))\n\n/** How one aggregate is totalled: its definition, whether its numbers are decimals whatever they hold, and the text order. */\ninterface Totalling {\n readonly aggregate: AggregateDef\n readonly decimals: boolean\n readonly collator: Intl.Collator\n}\n\n/** Values as numbers of one kind: integers while every one is and decimals are not asked for, else decimals; undefined when one is not a number. */\nfunction numbers(values: readonly TypedValue[], decimals: boolean): { readonly integers: readonly bigint[] } | { readonly decimals: readonly Decimal[] } | undefined {\n if (!decimals && values.every((value) => value.type === 'integer')) return { integers: values.map((value) => value.value as bigint) }\n if (!values.every((value) => value.type === 'integer' || value.type === 'decimal')) return undefined\n return { decimals: values.map(asDecimal) }\n}\n\nconst NOT_NUMBERS: Refusal = { code: 'aggregate-value-type', message: 'totals integers and decimals, and a value it read is neither' }\n\nfunction sum(values: readonly TypedValue[], decimals: boolean): Total {\n const read = numbers(values, decimals)\n if (read === undefined) return NOT_NUMBERS\n return 'integers' in read ? integer(read.integers.reduce((total, value) => total + value, 0n)) : decimal(sumDecimals(read.decimals))\n}\n\nfunction average(values: readonly TypedValue[], rounding: Rounding): Total {\n const read = numbers(values, true) as { readonly decimals: readonly Decimal[] } | undefined\n if (read === undefined) return NOT_NUMBERS\n const result = averageDecimals(read.decimals, rounding)\n return result === null ? null : decimal(result)\n}\n\nconst ordered = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0)\n\n/** -1, 0 or 1 for two values of one kind: numbers by value, text as the report's language sorts it, dates as days, moments in time order. */\nfunction comparator(values: readonly TypedValue[], collator: Intl.Collator): ((a: TypedValue, b: TypedValue) => number) | undefined {\n const types = new Set(values.map(({ type }) => type))\n if ([...types].every((type) => type === 'integer' || type === 'decimal')) return (a, b) => compareDecimal(asDecimal(a), asDecimal(b))\n const only = types.size === 1 ? [...types][0] : undefined\n if (only === 'string') return (a, b) => collator.compare(a.value as string, b.value as string)\n if (only === 'date') return (a, b) => ordered(a.value as string, b.value as string)\n if (only === 'datetime' || only === 'instant') return (a, b) => ordered(fixedWidth(a.value as string), fixedWidth(b.value as string))\n return undefined\n}\n\n/** The least (`sign` -1) or greatest (1) value, the first of equals as written; null over none. */\nfunction extreme(values: readonly TypedValue[], sign: -1 | 1, totalling: Totalling): Total {\n const compare = comparator(values, totalling.collator)\n if (compare === undefined) return { code: 'aggregate-value-type', message: 'takes the least or greatest of values of one kind, and the values it read are of several' }\n const found = values.reduce<TypedValue | null>((kept, value) => (kept === null || Math.sign(compare(value, kept)) === sign ? value : kept), null)\n return found?.type === 'integer' && totalling.decimals ? decimal(asDecimal(found)) : found\n}\n\n/** `total` rounded as `rounding` declares: a decimal at the rounding's scale. */\nfunction rounded(total: Total, rounding: Rounding | undefined): Total {\n if (rounding === undefined || total === null || isRefusal(total)) return total\n if (total.type === 'decimal') return decimal(roundDecimalAs(total.value, rounding))\n return { code: 'rounding-not-decimal', message: `declares a rounding, and its total is ${total.type === 'integer' ? 'an integer' : `a ${total.type}`}, which has no places to round` }\n}\n\n/** The aggregate over the values read from some rows -- each null or typed -- or over `rows` rows when it reads nothing. */\nfunction reduce(totalling: Totalling, read: readonly (TypedValue | null)[] | undefined, rows: number): Total {\n const { aggregate, decimals } = totalling\n const values = (read ?? []).filter((value): value is TypedValue => value !== null)\n switch (aggregate.fn) {\n case 'count':\n return integer(BigInt(read === undefined ? rows : values.length))\n case 'avg':\n // report-spec requires an average to declare its rounding.\n return values.length === 0 ? null : average(values, aggregate.rounding as Rounding)\n case 'sum':\n return rounded(sum(values, decimals), aggregate.rounding)\n case 'min':\n return rounded(extreme(values, -1, totalling), aggregate.rounding)\n case 'max':\n return rounded(extreme(values, 1, totalling), aggregate.rounding)\n }\n}\n\n/**\n * Every aggregate of `render`'s report, over its detail rows and, through\n * `over`, over any of them; or undefined when one could not be computed,\n * each reason recorded. `render` has every input but the totals.\n */\nexport function computeTotals(render: Omit<Render, 'totals'>): Totals | undefined {\n const { report, expressions, data, problems } = render\n const collator = new Intl.Collator(report.locale, { usage: 'sort' })\n const rows: readonly OrderedRow[] = data.detail.map((record, index) => ({ index, record }))\n const read = new Map<string, readonly (TypedValue | null)[]>()\n const totals = new Map<string, TypedValue | null>()\n const totallings = new Map<string, Totalling>()\n const refuse = (index: number, refusal: Refusal): void => {\n problems.error({ stage: 'resolve', code: refusal.code, path: `/aggregates/${index}`, message: `aggregate ${report.aggregates[index]?.id} ${refusal.message}` })\n }\n let computed = true\n\n for (const id of expressions.compilation.aggregateOrder) {\n const index = report.aggregates.findIndex((aggregate) => aggregate.id === id)\n const aggregate = report.aggregates[index] as AggregateDef\n const compiled = expressions.compilation.members.totals.get(id)?.type\n const decimals = compiled === 'decimal' || (compiled === 'dyn' && aggregate.rounding !== undefined)\n const of = aggregate.of\n if (of !== undefined) {\n const path = `/aggregates/${index}/of/expression/cel`\n const values = rows.map((row) => (of.kind === 'field' ? fieldValue(render, row.record, of.field) : valueOf(render, rowScope(render, totals, row), path)))\n if (values.some((value) => value === undefined)) {\n computed = false\n continue\n }\n read.set(id, values as (TypedValue | null)[])\n }\n const totalling: Totalling = { aggregate, decimals, collator }\n const total = reduce(totalling, read.get(id), rows.length)\n if (isRefusal(total)) {\n computed = false\n refuse(index, total)\n continue\n }\n totals.set(id, total)\n // A group's total is of its report total's kind: one that met a decimal is a decimal in every group.\n totallings.set(id, total?.type === 'decimal' ? { ...totalling, decimals: true } : totalling)\n }\n if (!computed) return undefined\n\n return {\n report: totals,\n over(group: readonly OrderedRow[]): AggregateValues {\n const values = new Map<string, TypedValue | null>()\n for (const aggregate of report.aggregates) {\n const each = read.get(aggregate.id)\n // Never refused: a group's values are some of those the report's\n // total took, of the kinds it took, totalled as the same kind and\n // rounded as it was. Every refusal `reduce` has is about the kinds\n // of values, and a share of values has no kind the whole lacks.\n values.set(aggregate.id, reduce(totallings.get(aggregate.id) as Totalling, each && group.map((row) => each[row.index] as TypedValue | null), group.length) as TypedValue | null)\n }\n return values\n },\n }\n}\n","/**\n * A report resolved against its data: the renderer-neutral document it\n * prints, and the manifest that says what it was printed from (plan 14).\n *\n * The composition of the runtime's stages, each decided in its own module:\n *\n * 1. the report, validated again and its expressions compiled; one the\n * editor's diagnostics give an error for is refused (`report-check.ts`);\n * 2. the options, the parameters and the data, each checked, and every\n * error of the three listed together (`parameters.ts`, `data.ts`);\n * 3. the aggregates, exactly, over every row (`totals.ts`);\n * 4. the regions, lowered component by component (`lower.ts`), tables row\n * by row (`lower-table.ts`), images through the host's lookup\n * (`images.ts`).\n *\n * It refuses rather than prints a wrong report: any error at any stage, and\n * the result is the errors, never a partial document. A preview may run on\n * data the provider calls incomplete or that lacks a field; it says so in\n * the manifest and in its warnings, and its every page carries\n * `PREVIEW_LABEL`, so that a preview printed or passed on is never taken for\n * the report. A final render refuses such data.\n */\nimport { decimalToString } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport { reportHash } from '@formancy/report-spec'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { checkData } from './data.js'\nimport type { Completeness, Consistency, DataMode, ReportData } from './data.js'\nimport type { Paragraph, ResolvedDocument } from './document.js'\nimport { createFormatter } from './format.js'\nimport { lowerRegions } from './lower.js'\nimport { checkParameters } from './parameters.js'\nimport type { CheckedParameters } from './parameters.js'\nimport type { ImageResolver } from './render-context.js'\nimport { checkReport } from './report-check.js'\nimport { fromData, Problems } from './resolve-errors.js'\nimport type { RuntimeError } from './resolve-errors.js'\nimport { documentStyles } from './styles.js'\nimport { computeTotals } from './totals.js'\nimport { canonicalInstant } from './values.js'\n\nexport interface ResolveOptions {\n /** A final render prints the report; a preview shows a sample and says what it lacks. */\n readonly mode: DataMode\n /** The values a person supplied, by parameter id; defaults apply to those left out. */\n readonly parameters?: Readonly<Record<string, unknown>>\n /** The host's lookup of approved assets' bytes; a report that draws an image is refused without one. */\n readonly images?: ImageResolver\n /** An ISO 8601 instant with its zone, fixed by the caller, so that the same inputs print the same PDF. */\n readonly creationDate: string\n /** The IANA zone instants are shown in, named by the host: UTC when absent, never the machine's. */\n readonly timeZone?: string\n}\n\n/** What a document was resolved from, to keep beside the PDF (plan 14). Nothing in it is the data's. */\nexport interface RenderManifest {\n /** report-spec's hash of the report as validated. */\n readonly reportHash: string\n readonly reportSpecVersion: ReportDefinition['reportSpecVersion']\n readonly locale: string\n readonly timeZone: string\n readonly mode: DataMode\n readonly consistency: Consistency\n readonly completeness: Completeness\n /** Each parameter's value as the format writes one -- an exact number or a date as a string, a boolean -- or null. */\n readonly parameters: Readonly<Record<string, string | boolean | null>>\n}\n\nexport type Resolution =\n | { readonly ok: true; readonly document: ResolvedDocument; readonly manifest: RenderManifest; /** What a preview lacks; empty in a final render, which refuses it. */ readonly warnings: readonly RuntimeError[] }\n | { readonly ok: false; readonly errors: readonly RuntimeError[] }\n\n/** What every page of a preview that lacks data says, at the top of its page header. */\nexport const PREVIEW_LABEL = 'Preview of incomplete data: not a final report'\n\nconst LABEL: Paragraph = { kind: 'paragraph', runs: [{ text: PREVIEW_LABEL }], style: { size: 8, bold: true, color: '#b00020' } }\n\n/** Each parameter's value as the format writes one. */\nfunction writtenParameters(values: CheckedParameters): Record<string, string | boolean | null> {\n return Object.fromEntries(\n Object.entries(values).map(([id, value]) => {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return [id, value]\n if (typeof value === 'bigint') return [id, String(value)]\n // A parameter is never an image (report-spec), so what is left is a decimal.\n return [id, decimalToString(value as Decimal)]\n }),\n )\n}\n\n/**\n * `report` resolved against `data`: the document to render and its\n * manifest, or every reason it is refused, up to a bound. Nothing is read\n * from `report`, `data` or the parameters but through the checks, and\n * nothing in the result is shared with them.\n */\nexport function resolveReport(report: ReportDefinition, data: ReportData, options: ResolveOptions): Resolution {\n const checked = checkReport(report)\n if (!checked.ok) return { ok: false, errors: checked.errors }\n const valid = checked.report\n const timeZone = options.timeZone ?? 'UTC'\n const errors: RuntimeError[] = []\n const creationDate = canonicalInstant(String(options.creationDate))\n if (creationDate === undefined) errors.push({ stage: 'resolve', code: 'invalid-creation-date', path: '', message: 'the creation date is an ISO 8601 instant with its zone' })\n const formatter = createFormatter({ locale: valid.locale, timeZone })\n if (!formatter.ok) errors.push({ stage: 'format', code: formatter.code, path: formatter.code === 'unsupported-locale' ? '/locale' : '', message: formatter.message })\n const parameters = checkParameters(valid, options.parameters ?? {})\n if (!parameters.ok) errors.push(...parameters.errors.map((error) => fromData('parameters', error)))\n const checkedData = checkData(valid, data, { mode: options.mode })\n if (!checkedData.ok) errors.push(...checkedData.errors.map((error) => fromData('data', error)))\n if (errors.length > 0 || creationDate === undefined || !formatter.ok || !parameters.ok || !checkedData.ok) return { ok: false, errors }\n\n const problems = new Problems()\n for (const warning of checkedData.warnings) problems.warn(fromData('data', warning))\n const preview = checkedData.data.mode === 'preview'\n const inputs = {\n report: valid,\n expressions: checked.expressions,\n formatter: formatter.formatter,\n params: parameters.values,\n data: checkedData.data,\n problems,\n preview,\n images: options.images,\n styles: documentStyles(valid.styles),\n }\n const totals = computeTotals(inputs)\n if (totals === undefined) return { ok: false, errors: problems.errors() }\n const regions = lowerRegions({ ...inputs, totals })\n if (problems.failed) return { ok: false, errors: problems.errors() }\n\n const { completeness, consistency } = checkedData.data\n const warnings = problems.warnings()\n const labelled = preview && (!completeness.complete || warnings.length > 0)\n const document: ResolvedDocument = {\n info: { title: valid.title, creationDate },\n page: valid.page,\n pageHeader: labelled ? [LABEL, ...regions.pageHeader] : regions.pageHeader,\n pageFooter: regions.pageFooter,\n body: regions.body,\n }\n const manifest: RenderManifest = {\n reportHash: reportHash(valid),\n reportSpecVersion: valid.reportSpecVersion,\n locale: valid.locale,\n timeZone,\n mode: checkedData.data.mode,\n consistency,\n completeness,\n parameters: writtenParameters(parameters.values),\n }\n return { ok: true, document, manifest, warnings }\n}\n"],"mappings":";;;;;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,MAAM;GACzB,QAAQ,MAAM;GACd;GACA,MAAM,YAAY,KAAK;GACvB;GACA;GACA,YAAY,kBAAkB,WAAW,MAAM;EAEb;EAAG;CAAS;AAClD"}
1
+ {"version":3,"file":"index.mjs","names":["refused","extreme","kept","text","optional","amount","optional","FACTUR_X_PROFILES","sum","invoiceNames","refuse","checked","refuse","address","party","invoiceNames","FACTUR_X_PROFILES","FACTUR_X","ADDRESS_PARTS","refuse","checked","amount","checkQrBillAmount","MAX_SVG_BYTES","MAX_ASSET_BYTES"],"sources":["../src/document.ts","../src/input.ts","../src/values.ts","../src/data-errors.ts","../src/data.ts","../src/parameters.ts","../src/decimal.ts","../src/format.ts","../src/sort-group.ts","../src/evaluate.ts","../src/xml.ts","../src/cii-parties.ts","../src/cii.ts","../src/e-invoice-totals.ts","../src/resolve-errors.ts","../src/render-context.ts","../src/inlines.ts","../src/e-invoice-lines.ts","../src/e-invoice-terms.ts","../src/lower-e-invoice.ts","../src/e-invoice-payable.ts","../src/qr-bill.ts","../src/lower-payment-part.ts","../src/images.ts","../src/lower-epc-qr-code.ts","../src/styles.ts","../src/lower-table.ts","../src/lower.ts","../src/report-check.ts","../src/totals.ts","../src/resolve.ts"],"sourcesContent":["/**\n * The resolved document: a report after the runtime has read its data,\n * evaluated its expressions and conditions, grouped, sorted, totalled and\n * formatted it, with nothing left to decide but where each line falls on a\n * page. The runtime lowers a report definition to it, and\n * `@formancy/report-render-pdf` draws it\n * ([0005](../../../docs/decisions/0005-pdfmake-renders-reports-behind-one-adapter.md)).\n *\n * It names no engine and holds no engine's options. It is plain data, every\n * part of it serialisable but an image's bytes, which are a `Uint8Array`.\n * Every length is in PDF points. Every value is already the string that\n * prints: an exact number stays a string all the way to the page, and an\n * engine never formats, rounds or converts one.\n *\n * It holds everything version 0 of the definition can print: the columns,\n * sections, rule weights and colours, fonts and colours, image fits and\n * group headers across a table that\n * [0007](../../../docs/decisions/0007-a-report-definition-is-its-own-versioned-document.md)\n * found the renderer trial's document without. Its vocabularies -- font\n * tokens, alignments, fits, page sizes, colours -- are report-spec's own\n * types, so the definition and the document cannot name different ones. An\n * absent style property is the renderer's default, as report-spec's print\n * styles say.\n *\n * Where a block may stand -- a table or a page break never inside columns or\n * a keep-together block, page fields only in the page regions -- is the\n * definition's to validate and the renderer's to refuse. These types do not\n * hold it.\n */\nimport type { Alignment, AssetMediaType, Border, EpcCaption, FacturXProfileTerms, FontFamily, ImageFit, Margins, Orientation, PageSizeName, QrBillCurrency, QrErrorCorrection, Width } from '@formancy/report-spec'\n\n/**\n * A run of text, or a number only the engine knows when it lays out the\n * page, which prints only in the page header and footer. A run in bold\n * inside a paragraph that is not was the trial's; version 0 of the\n * definition sets weight per paragraph.\n */\nexport type Inline = { readonly text: string; readonly bold?: boolean } | { readonly field: 'pageNumber' } | { readonly field: 'pageCount' }\n\n/**\n * How text prints: report-spec's `PrintStyle`, resolved. The runtime lays\n * each conditional style that held over the base one, a later rule's\n * property winning, and hands the engine the result; an engine never merges\n * styles itself.\n */\nexport interface TextStyle {\n /** A font token, never a font's name: the renderer maps each to a font it embeds. */\n readonly font?: FontFamily\n /** Points. */\n readonly size?: number\n readonly bold?: boolean\n readonly italic?: boolean\n /** Lower-case `#rrggbb`. */\n readonly color?: string\n readonly align?: Alignment\n}\n\n/** Text that wraps at the width it is given. A word wider than that width still prints whole, broken across lines. */\nexport interface Paragraph {\n readonly kind: 'paragraph'\n readonly runs: readonly Inline[]\n readonly style?: TextStyle\n /** Never the last thing on a page when something follows it: a heading moves with what it heads. */\n readonly keepWithNext?: boolean\n}\n\nexport interface TableColumn {\n /** Points, or `'fill'` for an equal share of the width the fixed columns leave. */\n readonly width: Width\n /** How each cell in the column is aligned, unless the cell's style says otherwise. */\n readonly align: Alignment\n}\n\n/**\n * One row of a table, its cells in column order, each aligned to the top of\n * the row, so that a row's first line holds its first cell.\n *\n * A `groupHeader` is never the last row on a page: it moves to the next page\n * with the row it heads. A `detail` row may be taller than a page; the engine\n * then continues it on the next one, or refuses with `content-too-large`, and\n * never clips it.\n */\nexport interface TableRow {\n readonly kind: 'detail' | 'groupHeader' | 'groupFooter' | 'total'\n /** One per column; exactly one when the row runs `across` the table. */\n readonly cells: readonly string[]\n /**\n * The row is one cell across every column: a group header, which version\n * 0 prints as one line across the table rather than in its first column.\n */\n readonly across?: true\n /** Every cell's style; absent, the renderer's for a row of its kind. */\n readonly style?: TextStyle\n /**\n * A cell's own style, one entry per cell, `null` where the cell has the\n * row's. A cell's own is its whole style, the row's already laid under it\n * by the runtime, never merged again by the engine: a column's print\n * style, or one of its conditional styles that held for this row.\n */\n readonly cellStyles?: readonly (TextStyle | null)[]\n}\n\nexport interface Table {\n readonly kind: 'table'\n readonly id: string\n readonly columns: readonly TableColumn[]\n /** The one header row, repeated at the top of every page the table spans. */\n readonly header: readonly string[]\n /** The header row's style; absent, the renderer's. */\n readonly headerStyle?: TextStyle\n readonly rows: readonly TableRow[]\n /** Printed under the header, in place of detail rows, when there are none. Group and total rows still print. */\n readonly emptyText: string\n}\n\n/**\n * An approved asset's bytes, already fetched by the host: an engine never\n * resolves an address. Every image that draws the same asset shares one\n * object, which an engine embeds once for a PNG or a JPEG, and draws again\n * wherever an SVG prints (0030).\n */\nexport interface ImageAsset {\n readonly id: string\n readonly mediaType: AssetMediaType\n readonly bytes: Uint8Array\n}\n\n/**\n * An image in a box of fixed size, which the layout reserves whole whatever\n * the image holds. `contain` draws all of the image at its own proportions,\n * as large as the box allows; `cover` fills the box at the image's\n * proportions and crops what falls outside it. Either way the image is\n * centred in its box, as CSS's `object-fit` centres one by default, and\n * nothing of it is drawn outside the box. For an image of the box's own\n * proportions the two are the same drawing. Bytes the engine cannot decode\n * are refused as `invalid-asset`, naming the asset.\n */\nexport interface Image {\n readonly kind: 'image'\n readonly asset: ImageAsset\n readonly width: number\n readonly height: number\n readonly fit: ImageFit\n}\n\n/**\n * A QR code (ISO/IEC 18004): `text`, encoded as UTF-8 at the error\n * correction level asked for, drawn dark on white in a square `size` points\n * a side, whose quiet zone of four modules lies inside that square. `text`\n * is what the component's content prints, formatted as a paragraph's runs\n * are; it never holds a page number or count, which report-spec refuses in\n * a QR code. In a final render it holds every value its content reads and\n * is never empty: the runtime refuses a run whose value is null, and\n * content that prints nothing, as `no-qr-value` and `empty-qr-code`. In a\n * preview it is what the content resolves to, a value that is null as\n * nothing, and it can be empty, which an engine draws as a symbol of no\n * data. Which version of the symbol holds the text, and so how large a\n * module is, is the engine's to work out: text no version holds at the\n * level, or modules too small to print, are refused as `content-too-large`,\n * naming the code by `id`, never drawn as a code that does not scan.\n */\nexport interface QrCode {\n readonly kind: 'qrCode'\n /** The component's id, which a refusal names as its subject. */\n readonly id: string\n readonly text: string\n /** Points: the side of the square, quiet zone included. */\n readonly size: number\n readonly errorCorrection: QrErrorCorrection\n}\n\n/**\n * An EPC QR code (EPC069-12 v3.1): the code a SEPA credit transfer is\n * initiated from, drawn dark on white in a square `size` points a side.\n * `payload` is its text, every element resolved and held to the EPC's\n * rules (report-spec's `epc-payload.ts`): the engine encodes it as UTF-8\n * at level M, in a symbol of version 13 at most (EPC069-12 2.1), and\n * formats, checks and changes nothing of it. A payload no such symbol\n * holds, or modules too small to print, are refused as\n * `content-too-large`, naming the code by `id`, never drawn at another\n * level or in a larger version, which a bank's app need not read.\n *\n * Without a caption the code is drawn as a QR code is, its quiet zone of\n * four modules inside its square. With one, Austria's frame and the words\n * \"Zahlen mit Code\" are drawn inside the square too (PSA v3.0 5), as\n * report-spec's `epc-print.ts` lays them out and bounds the modules'\n * width; the engine, which knows the version, refuses a code whose\n * modules are outside those bounds.\n */\nexport interface EpcQrCode {\n readonly kind: 'epcQrCode'\n /** The component's id, which a refusal names as its subject. */\n readonly id: string\n /** The EPC's elements in EPC069-12 2.2's order, each on its own line, separated by a line feed and not ended by one: at most 331 bytes in UTF-8. */\n readonly payload: string\n /** Points: the side of the square, the quiet zone, and the frame and caption when there are any, inside it. */\n readonly size: number\n /** Austria's frame and caption; absent, the code is drawn alone. */\n readonly caption?: EpcCaption\n}\n\n/** A horizontal line across the width it is given: the printable area's, or its column's. */\nexport interface Rule {\n readonly kind: 'rule'\n /** Points. */\n readonly thickness: number\n /** Lower-case `#rrggbb`. */\n readonly color?: string\n}\n\n/** A box of fixed size: filled, outlined, both, or neither, when it is only space. */\nexport interface Rectangle {\n readonly kind: 'rectangle'\n readonly width: number\n readonly height: number\n /** Lower-case `#rrggbb`. */\n readonly fill?: string\n /** The outline's colour, lower-case `#rrggbb`, drawn at the renderer's weight. */\n readonly stroke?: string\n}\n\nexport interface Spacer {\n readonly kind: 'spacer'\n readonly height: number\n}\n\n/** Starts a new page. */\nexport interface PageBreak {\n readonly kind: 'pageBreak'\n}\n\n/**\n * Blocks that are printed on one page, such as a report's summary. When they\n * do not fit in what is left of the page they move whole to the next one;\n * when they are taller than a whole page the engine refuses with\n * `content-too-large` rather than splitting them.\n */\nexport interface KeepTogether {\n readonly kind: 'keepTogether'\n readonly blocks: readonly Block[]\n}\n\n/** One column of a columns block, as distinct from a table's column. */\nexport interface ColumnSlot {\n /** Points, or `'fill'` for an equal share of the width the fixed columns leave. */\n readonly width: Width\n readonly blocks: readonly Block[]\n}\n\n/**\n * Two to four columns side by side, each laying its blocks out down its own\n * width, with no gap between them but what their widths leave. The block is\n * as tall as its tallest column. When it does not fit on what is left of the\n * page, the engine continues its columns on the next page or refuses with\n * `content-too-large`, and never clips them.\n */\nexport interface Columns {\n readonly kind: 'columns'\n readonly columns: readonly ColumnSlot[]\n}\n\n/**\n * Blocks in a frame: the border drawn around them, the fill behind them, and\n * the padding between the border and them. A section adds no layout rule:\n * its blocks flow as though they stood in its place, across pages too, and\n * the frame is drawn around the part on each page. Without a border, a fill\n * or padding it is its blocks and nothing more.\n */\nexport interface Section {\n readonly kind: 'section'\n readonly blocks: readonly Block[]\n readonly border?: Border\n /** Lower-case `#rrggbb`. */\n readonly fill?: string\n /** Points, on every side. */\n readonly padding?: number\n}\n\nexport type Block = Paragraph | Table | Image | QrCode | EpcQrCode | Rule | Rectangle | Spacer | PageBreak | KeepTogether | Columns | Section\n\nexport interface PageSetup {\n readonly size: PageSizeName\n readonly orientation: Orientation\n /**\n * From each edge of the paper to the printable area. Everything prints\n * inside it: the page header at its top, the page footer at its bottom, and\n * the body between them.\n */\n readonly margins: Margins\n}\n\n/**\n * The headings a QR-bill's slip prints, in its language: SIX's own words\n * (IG Annex C), which \"must not be changed\".\n */\nexport interface QrBillHeadings {\n readonly paymentPart: string\n readonly receipt: string\n /** \"Account / Payable to\". */\n readonly account: string\n readonly reference: string\n readonly additionalInformation: string\n /** \"Payable by\", or, for a bill without a debtor, \"Payable by (name/address)\" over the blank field. */\n readonly payableBy: string\n readonly currency: string\n readonly amount: string\n readonly acceptancePoint: string\n /** \"Separate before paying in\": the instruction above the line a PDF's slip is cut along. */\n readonly separate: string\n}\n\n/**\n * A Swiss QR-bill: its receipt and its payment part, 210 by 105 mm across\n * the foot of an A4 page, the report's last (report-spec's `QR_BILL_SIZE`).\n * Where it falls, and a page of its own when the body leaves no room for\n * it, is the engine's to lay out.\n *\n * Everything in it is resolved and checked by SIX's rules (report-spec's\n * `qr-bill.ts`): `payload` is the Swiss QR Code's text, which the engine\n * encodes at level M, and every other text is what the slip prints, exactly\n * as it prints, the values grouped as SIX groups them. An engine formats,\n * groups, translates and checks nothing of it; it draws the headings, the\n * values, the blank fields where a value is null, the code and the cross.\n * The engine draws the receipt's texts from the same values, but for\n * `additionalInformation`, which a receipt never prints (IG 3.6).\n */\nexport interface QrBill {\n readonly kind: 'swissQrBill'\n /** The Swiss QR Code's elements in IG Table 8's order, each on its own line, separated by a line feed and not ended by one: at most 997 characters. */\n readonly payload: string\n readonly headings: QrBillHeadings\n /** The IBAN in blocks of four: \"CH44 3199 9123 0008 8901 2\". */\n readonly account: string\n /** The creditor's address, line by line: the name, the street and building number, the postal code and town. */\n readonly creditor: readonly string[]\n /** The QR reference or creditor reference in SIX's blocks, or null for a bill without one. */\n readonly reference: string | null\n /** The message, then the billing information, each that is there, on a line of its own; empty prints no heading. */\n readonly additionalInformation: readonly string[]\n /** The debtor's address, line by line; null prints the blank field for the payer to write in. */\n readonly debtor: readonly string[] | null\n readonly currency: QrBillCurrency\n /** The amount with a space between thousands and two decimals: \"1 949.75\"; null prints the blank field for the payer to write in. */\n readonly amount: string | null\n}\n\n/**\n * The e-invoice a PDF carries: its XML, which the runtime wrote from the\n * very values the page prints (0027), and what the renderer embeds it as\n * [S] -- the file's name, its `/AFRelationship` and the XMP's\n * `fx:ConformanceLevel`. The values are report-spec's `FACTUR_X` and\n * `FACTUR_X_PROFILES`, handed on so an engine reads the one decision; one\n * an engine does not know it refuses as `unsupported`, never embedded\n * under another name. Only a final render writes one: a preview is not the\n * invoice. An engine encodes the XML as UTF-8 and changes nothing of it.\n */\nexport interface EInvoiceFile {\n /** The CII XML, with its declaration: the invoice itself. */\n readonly xml: string\n /** The embedded file's name: `factur-x.xml`. */\n readonly fileName: string\n readonly relationship: FacturXProfileTerms['relationship']\n /** `EN 16931`. */\n readonly conformanceLevel: string\n}\n\nexport interface ResolvedDocument {\n readonly info: {\n readonly title: string\n /** An ISO instant, fixed by the caller, so that the same document renders to the same PDF. */\n readonly creationDate: string\n }\n readonly page: PageSetup\n /** Repeated on every page, at the top of the printable area. */\n readonly pageHeader: readonly Block[]\n /** Repeated on every page, at the bottom of the printable area. */\n readonly pageFooter: readonly Block[]\n /**\n * What prints once, in order. A definition's report header is simply the\n * start of the body, and its summary the end: each prints once, before or\n * after everything else, so neither needs a block kind of its own. A\n * summary that must stay on one page is a keep-together block.\n */\n readonly body: readonly Block[]\n /** The slip the report is paid by, at the foot of its last page; absent, it has none. Never a block: it stands at a place SIX fixes, outside the printable area. */\n readonly paymentPart?: QrBill\n /** The e-invoice the PDF embeds, in a final render of a report that is one; absent, the PDF carries none. */\n readonly eInvoice?: EInvoiceFile\n}\n\nexport const REFUSAL_CODES = ['too-many-pages', 'content-too-large', 'invalid-asset', 'cancelled', 'unsupported'] as const\nexport type RefusalCode = (typeof REFUSAL_CODES)[number]\n\n/**\n * Why an engine produced no PDF. An engine refuses rather than truncates: a\n * report that cannot be printed whole is not printed, and the caller is told\n * what stopped it. `subject` names the asset, table or block concerned, when\n * the refusal is about one.\n */\nexport class RenderRefusal extends Error {\n readonly code: RefusalCode\n readonly subject: string | undefined\n\n constructor(code: RefusalCode, message: string, subject?: string) {\n super(message)\n this.name = 'RenderRefusal'\n this.code = code\n this.subject = subject\n }\n}\n","/**\n * Reading the data a host hands over, once, without running any of it.\n *\n * Datasets and parameters are untrusted input, even from the host's own\n * provider. A JSON-parsed object is plain data, but a host may hand over\n * anything JavaScript can hold: a getter that answers differently each time\n * it is asked, a proxy whose traps throw, a sparse array. So every object\n * and list is read through its property descriptors into a copy, as\n * report-spec reads a report: a getter is refused unrun, an exception from a\n * trap becomes a refusal, and what is checked afterwards is the copy, which\n * cannot change under the check.\n */\n\n/** Why a container could not be read at all. */\nexport type ContainerCode = 'wrong-type' | 'not-data' | 'too-many'\n\n/** A property of a record that could not be read, with the key it has when it has a string one. */\nexport interface PropertyProblem {\n readonly key?: string\n readonly message: string\n}\n\nexport type RecordRead =\n | { readonly ok: true; readonly entries: ReadonlyMap<string, unknown>; readonly problems: readonly PropertyProblem[] }\n | { readonly ok: false; readonly code: Exclude<ContainerCode, 'too-many'>; readonly message: string }\n\n/** An item of a list that could not be read, by its index. */\nexport interface ItemProblem {\n readonly index: number\n readonly message: string\n}\n\n/** Stands in a read list where an item could not be read; its problem says why. */\nexport const UNREADABLE: unique symbol = Symbol('unreadable')\n\nexport type ListRead =\n | { readonly ok: true; readonly items: readonly unknown[]; readonly problems: readonly ItemProblem[] }\n | { readonly ok: false; readonly code: ContainerCode; readonly message: string }\n\nconst ACCESSOR = 'a getter or setter is not data, and is not run'\n\n/** Whether `value` is a plain object: made by a literal, JSON.parse or Object.create(null), not a class instance, an array or a Map. */\nfunction isPlainObject(value: unknown): value is object {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const prototype: unknown = Object.getPrototypeOf(value)\n return prototype === Object.prototype || prototype === null\n}\n\n/**\n * A plain object's own enumerable string-keyed data properties, each read\n * once, in the object's own order. A property that is not data -- a getter,\n * a symbol key, a hidden property -- is a problem of the record and left\n * out; anything else about the object refuses it whole.\n */\nexport function readRecord(value: unknown): RecordRead {\n try {\n if (!isPlainObject(value)) return { ok: false, code: 'wrong-type', message: 'expected an object of named values' }\n const entries = new Map<string, unknown>()\n const problems: PropertyProblem[] = []\n let symbols = false\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key === 'symbol') {\n symbols = true\n continue\n }\n const descriptor = Object.getOwnPropertyDescriptor(value, key) as PropertyDescriptor\n if (!('value' in descriptor)) problems.push({ key, message: ACCESSOR })\n else if (descriptor.enumerable !== true) problems.push({ key, message: 'a property that is not enumerable is not data' })\n else entries.set(key, descriptor.value)\n }\n if (symbols) problems.push({ message: 'a property named by a symbol is not data' })\n return { ok: true, entries, problems }\n } catch {\n return { ok: false, code: 'not-data', message: 'an object that throws when read is not data' }\n }\n}\n\n/**\n * A list's items, each read once, after its length is checked against\n * `max`: a list longer than that is refused before any item is read. A hole\n * or a getter is a problem at its index, and `UNREADABLE` stands in its\n * place.\n */\nexport function readList(value: unknown, max: number): ListRead {\n try {\n if (!Array.isArray(value)) return { ok: false, code: 'wrong-type', message: 'expected a list' }\n // A proxy describes its length as it likes: an object whose valueOf\n // answers the bound one number and the loop another, or Infinity. Only a\n // whole number is a length, and it is compared and looped to as read.\n const length: unknown = (Object.getOwnPropertyDescriptor(value, 'length') as PropertyDescriptor).value\n if (typeof length !== 'number' || !Number.isSafeInteger(length) || length < 0) return { ok: false, code: 'not-data', message: 'a list whose length is not a whole number is not data' }\n if (length > max) return { ok: false, code: 'too-many', message: `a list of ${length} items, more than the ${max} allowed` }\n const items: unknown[] = []\n const problems: ItemProblem[] = []\n for (let index = 0; index < length; index++) {\n const descriptor = Object.getOwnPropertyDescriptor(value, index)\n if (descriptor !== undefined && 'value' in descriptor) {\n items.push(descriptor.value)\n continue\n }\n items.push(UNREADABLE)\n problems.push({ index, message: descriptor === undefined ? 'a hole in a list is not data' : ACCESSOR })\n }\n return { ok: true, items, problems }\n } catch {\n return { ok: false, code: 'not-data', message: 'a list that throws when read is not data' }\n }\n}\n","/**\n * One value read as the type a dataset field or a parameter declares, and\n * held as the runtime computes with it.\n *\n * Exact values travel as strings with their type and are never converted\n * through a JavaScript number (0007; formancy.ai-data 0008). So:\n * - an integer is a string of its digits, or a JSON number only where a\n * number is still exact, below 2^53; it is held as a `bigint`;\n * - a decimal is only ever the string of its exact digits, held as\n * `@formancy/expressions`' `Decimal` with its scale;\n * - a date and a local date-time have no zone and are held as their ISO\n * strings, which sort in calendar order;\n * - an instant has a zone, and is held in UTC, so that two spellings of one\n * moment are one value;\n * - an image is an approved asset's id and digest, never an address.\n *\n * Each type has one spelling of each value, the one report-spec writes a\n * parameter default in. Its patterns are restated here because report-spec\n * does not export them; `values.test.ts` puts candidates to both, so the two\n * cannot drift apart unnoticed. A refusal says what was expected and never\n * repeats what was found: the data is the customer's.\n */\nimport { DEFAULT_VALUE_LIMITS, Decimal, decimalFromString } from '@formancy/expressions'\nimport { isIdentifier, MAX_SCALE } from '@formancy/report-spec'\nimport type { FieldType } from '@formancy/report-spec'\nimport { readRecord } from './input.js'\n\n/**\n * The longest string a value may be, in UTF-16 code units. Not chosen: it is\n * the longest string `@formancy/expressions` lets an expression be handed\n * (`DEFAULT_VALUE_LIMITS.maxStringLength`), so every string the data check\n * accepts is one an expression can read, and a longer one is refused where\n * the check can name its field rather than when an expression first reads\n * it.\n */\nexport const MAX_STRING_LENGTH = DEFAULT_VALUE_LIMITS.maxStringLength\n\nexport const VALUE_ERROR_CODES = [\n /** A value of another JavaScript type than the field's: a number for a string, a bigint, a Date. */\n 'wrong-type',\n 'string-too-long',\n /** A string with half a surrogate pair, which is not text and would print as something nobody wrote. */\n 'ill-formed-string',\n /** Not an integer's one spelling, or a number with a fraction. */\n 'invalid-integer',\n /** A JSON number past 2^53, which has already lost digits. */\n 'unsafe-integer',\n /** A decimal as a JSON number, which has already lost digits. */\n 'decimal-as-number',\n 'invalid-decimal',\n /** A decimal with more places than its field declares, or than a decimal holds. */\n 'decimal-scale',\n 'invalid-date',\n 'invalid-datetime',\n 'invalid-instant',\n 'invalid-image',\n] as const\nexport type ValueErrorCode = (typeof VALUE_ERROR_CODES)[number]\n\n/** An image field's value: an approved asset the host resolves to bytes by its id, pinned by its digest. */\nexport interface ImageValue {\n /** An identifier, as report-spec writes an asset's id. */\n readonly asset: string\n /** `sha256:` and 64 lower-case hex digits. */\n readonly digest: string\n}\n\n/** What a value of each field type is held as once read. */\nexport interface FieldValues {\n readonly string: string\n readonly integer: bigint\n readonly decimal: Decimal\n readonly boolean: boolean\n /** `YYYY-MM-DD`. */\n readonly date: string\n /** `YYYY-MM-DDTHH:mm:ss`, and a fraction of a second without trailing zeros when it has one. */\n readonly datetime: string\n /** As a date-time, in UTC, with a final `Z`. */\n readonly instant: string\n readonly image: ImageValue\n}\n\n/** A value of any field type, read. Null is not one: whether a field may be null is its contract's, and checked before its type. */\nexport type CheckedValue = FieldValues[FieldType]\n\nexport type ValueRead<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly code: ValueErrorCode; readonly message: string }\n\nfunction refused(code: ValueErrorCode, message: string): { readonly ok: false; readonly code: ValueErrorCode; readonly message: string } {\n return { ok: false, code, message }\n}\n\n/** What `raw` is, for a message: its JavaScript type, never its content. */\nfunction kindOf(raw: unknown): string {\n if (raw === null) return 'null'\n if (Array.isArray(raw)) return 'a list'\n if (raw instanceof Date) return 'a Date'\n if (raw instanceof Decimal) return 'a Decimal'\n const type = typeof raw\n return type === 'object' ? 'an object' : `a ${type}`\n}\n\nfunction wrongType(expected: string, raw: unknown): { readonly ok: false; readonly code: ValueErrorCode; readonly message: string } {\n return refused('wrong-type', `expected ${expected}, found ${kindOf(raw)}`)\n}\n\n/** An exact integer: no sign but '-', no leading zero, no '-0' (report-spec's `INTEGER`). */\nconst INTEGER = /^(?:0|-?[1-9]\\d*)$/\n\n/** An exact decimal: an integer, optionally a point and at least one digit; no negative zero (report-spec's `DECIMAL`). */\nconst DECIMAL = /^(?:-?[1-9]\\d*(?:\\.\\d+)?|0(?:\\.\\d+)?|-0\\.0*[1-9]\\d*)$/\n\n/** An asset's content digest: SHA-256, lower-case hex (report-spec's `DIGEST`). */\nconst DIGEST = /^sha256:[0-9a-f]{64}$/\n\n/** Half a surrogate pair: a high one not followed by a low one, or a low one not preceded by a high one. */\nconst LONE_SURROGATE = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/\n\nconst DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/\nconst DATETIME = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,9}))?$/\n/** An ISO 8601 date-time with its zone, as `@formancy/expressions` binds a timestamp: seconds optional, a fraction to the nanosecond. */\nconst INSTANT = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{1,9}))?)?(?:Z|([+-])(\\d{2}):(\\d{2}))$/\n\n/**\n * Whether year, month and day name a day on the proleptic Gregorian\n * calendar from the year 1: 2024-02-29 does, 2026-02-29 does not, and no day\n * of the year 0000 does, which Intl shows as the year 1 without its era\n * (report-spec's `isCalendarDate`).\n */\nfunction isCalendarDay(year: number, month: number, day: number): boolean {\n if (year < 1 || month < 1 || month > 12 || day < 1) return false\n const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0\n const days = month === 2 ? (leap ? 29 : 28) : [4, 6, 9, 11].includes(month) ? 30 : 31\n return day <= days\n}\n\n/** Whether hours, minutes and seconds name a time on a clock that has no leap second, as Date has none. */\nfunction isClockTime(hour: number, minute: number, second: number): boolean {\n return hour <= 23 && minute <= 59 && second <= 59\n}\n\n/**\n * `fraction` without trailing zeros, with its point, or nothing when nothing\n * is left. A loop rather than /0+$/: the instant pattern bounds the fraction\n * to nine digits, but an anchored repetition is quadratic on many zeros\n * before a non-zero (CodeQL's js/polynomial-redos), and this needs no bound\n * to stay linear.\n */\nfunction fractionOf(fraction: string | undefined): string {\n if (fraction === undefined) return ''\n let end = fraction.length\n while (end > 0 && fraction[end - 1] === '0') end -= 1\n return end === 0 ? '' : `.${fraction.slice(0, end)}`\n}\n\nfunction readString(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('a string', raw)\n if (raw.length > MAX_STRING_LENGTH) return refused('string-too-long', `a string of ${raw.length} characters, more than the ${MAX_STRING_LENGTH} a value may have`)\n if (LONE_SURROGATE.test(raw)) return refused('ill-formed-string', 'a string with half a surrogate pair is not text, and would print a character nobody wrote')\n return { ok: true, value: raw }\n}\n\nfunction readInteger(raw: unknown): ValueRead<bigint> {\n if (typeof raw === 'string') {\n if (raw.length <= MAX_STRING_LENGTH && INTEGER.test(raw)) return { ok: true, value: BigInt(raw) }\n return refused('invalid-integer', 'an integer is written as its digits, with \"-\" for a negative one, no leading zero and no \"-0\"')\n }\n if (typeof raw === 'number') {\n if (Number.isSafeInteger(raw)) return { ok: true, value: BigInt(raw) }\n if (Number.isInteger(raw)) return refused('unsafe-integer', 'a number past 2^53 has already lost digits; send the integer as a string of its digits')\n return refused('invalid-integer', 'expected a whole number')\n }\n return wrongType('an integer, written as a string of its digits', raw)\n}\n\nfunction readDecimal(raw: unknown, scale: number | undefined): ValueRead<Decimal> {\n if (typeof raw === 'number') return refused('decimal-as-number', 'a decimal is sent as a string of its exact digits, never as a number: floats lose digits')\n if (typeof raw !== 'string') return wrongType('a decimal, written as a string of its exact digits', raw)\n if (raw.length > MAX_STRING_LENGTH || !DECIMAL.test(raw)) {\n return refused('invalid-decimal', 'a decimal is written as its digits, with \".\" before any places, \"-\" for a negative one, no leading zero and no \"-0\"')\n }\n const places = raw.length - raw.indexOf('.') - 1\n const allowed = scale ?? MAX_SCALE\n if (raw.includes('.') && places > allowed) {\n const whose = scale === undefined ? 'a decimal holds' : 'the field declares'\n return refused('decimal-scale', `a decimal with ${places} places, more than the ${allowed} ${whose}; rounding it here would print another number than the source holds`)\n }\n return { ok: true, value: decimalFromString(raw) }\n}\n\nfunction readBoolean(raw: unknown): ValueRead<boolean> {\n return typeof raw === 'boolean' ? { ok: true, value: raw } : wrongType('true or false', raw)\n}\n\nfunction readDate(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('a date, written YYYY-MM-DD', raw)\n const match = DATE.exec(raw)\n if (match !== null && isCalendarDay(Number(match[1]), Number(match[2]), Number(match[3]))) return { ok: true, value: raw }\n return refused('invalid-date', 'a date is a day on the calendar, written YYYY-MM-DD')\n}\n\nfunction readDatetime(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('a date and time, written YYYY-MM-DDTHH:mm:ss', raw)\n const match = DATETIME.exec(raw)\n const [year, month, day, hour, minute, second] = match === null ? [] : match.slice(1, 7).map(Number)\n if (match === null || !isCalendarDay(year as number, month as number, day as number) || !isClockTime(hour as number, minute as number, second as number)) {\n return refused('invalid-datetime', 'a date and time without a zone is written YYYY-MM-DDTHH:mm:ss, with a fraction of a second of up to nine digits if it has one')\n }\n return { ok: true, value: `${raw.slice(0, 19)}${fractionOf(match[7])}` }\n}\n\nconst pad = (value: number, width: number): string => String(value).padStart(width, '0')\n\n/**\n * `text`, an ISO 8601 date-time with its zone, as the moment it names in\n * UTC: `YYYY-MM-DDTHH:mm:ssZ`, with the fraction of a second it has, less\n * trailing zeros. Undefined when it is not one, or the moment falls outside\n * the years 0001 to 9999 in UTC: past them a year has no four-digit\n * spelling, and Intl shows the year 0 as the year 1.\n *\n * What an expression gives back for a timestamp is RFC 3339 in UTC, so this\n * also makes an expression's instant comparable with the data's.\n */\nexport function canonicalInstant(text: string): string | undefined {\n const match = INSTANT.exec(text)\n if (match === null) return undefined\n const [year, month, day, hour, minute, second = 0] = match.slice(1, 7).map((part) => (part === undefined ? undefined : Number(part))) as number[]\n const offsetHours = match[9] === undefined ? 0 : Number(match[9])\n const offsetMinutes = match[10] === undefined ? 0 : Number(match[10])\n if (!isCalendarDay(year as number, month as number, day as number) || !isClockTime(hour as number, minute as number, second) || offsetHours > 23 || offsetMinutes > 59) return undefined\n // Date.UTC reads the years 0 to 99 as 1900 to 1999; setUTCFullYear does not.\n const moment = new Date(0)\n moment.setUTCFullYear(year as number, (month as number) - 1, day as number)\n moment.setUTCHours(hour as number, minute as number, second, 0)\n const offset = (match[8] === '-' ? -1 : 1) * (offsetHours * 60 + offsetMinutes)\n moment.setTime(moment.getTime() - offset * 60_000)\n const utcYear = moment.getUTCFullYear()\n if (utcYear < 1 || utcYear > 9999) return undefined\n const date = `${pad(utcYear, 4)}-${pad(moment.getUTCMonth() + 1, 2)}-${pad(moment.getUTCDate(), 2)}`\n const time = `${pad(moment.getUTCHours(), 2)}:${pad(moment.getUTCMinutes(), 2)}:${pad(moment.getUTCSeconds(), 2)}`\n return `${date}T${time}${fractionOf(match[7])}Z`\n}\n\nfunction readInstant(raw: unknown): ValueRead<string> {\n if (typeof raw !== 'string') return wrongType('an instant, written as an ISO 8601 date-time with its zone', raw)\n const value = canonicalInstant(raw)\n if (value !== undefined) return { ok: true, value }\n return refused('invalid-instant', 'an instant is an ISO 8601 date-time with its zone, Z or an offset such as +01:00, between the years 0001 and 9999 in UTC')\n}\n\nconst IMAGE_SHAPE = 'an image is an approved asset, { \"asset\": its id, \"digest\": \"sha256:\" and 64 lower-case hex digits }, never an address'\n\nfunction readImage(raw: unknown): ValueRead<ImageValue> {\n const read = readRecord(raw)\n if (!read.ok || read.problems.length > 0) return refused('invalid-image', IMAGE_SHAPE)\n const { entries } = read\n const asset = entries.get('asset')\n const digest = entries.get('digest')\n if (entries.size !== 2 || !isIdentifier(asset) || typeof digest !== 'string' || !DIGEST.test(digest)) return refused('invalid-image', IMAGE_SHAPE)\n return { ok: true, value: Object.freeze({ asset, digest }) }\n}\n\n/**\n * `raw` read as a value of `type`, or why it is not one. `scale` is a\n * decimal field's declared scale: a decimal with more places is refused.\n * Null is refused as every type's wrong type; the caller decides first\n * whether the field may hold it.\n */\nexport function readValue<T extends FieldType>(type: T, raw: unknown, scale?: number): ValueRead<FieldValues[T]> {\n const read = READERS[type] as (raw: unknown, scale: number | undefined) => ValueRead<FieldValues[T]>\n return read(raw, scale)\n}\n\nconst READERS: { readonly [T in FieldType]: (raw: unknown, scale: number | undefined) => ValueRead<FieldValues[T]> } = {\n string: readString,\n integer: readInteger,\n decimal: readDecimal,\n boolean: readBoolean,\n date: readDate,\n datetime: readDatetime,\n instant: readInstant,\n image: readImage,\n}\n","/**\n * What the runtime can say is wrong with the data and parameters it is\n * given, as stable codes, and the bounded list one check collects.\n *\n * A code is for a program and the message for a person. An error's path is\n * a JSON Pointer into what was given -- `/detail/17/amount` -- and neither\n * the path nor the message ever holds a value from it: the data is the\n * customer's, and an error is the kind of thing that ends up in a log.\n */\nimport { MAX_ERRORS, MAX_KEY_LENGTH } from '@formancy/report-spec'\nimport { VALUE_ERROR_CODES } from './values.js'\n\nexport const DATA_ERROR_CODES = [\n ...VALUE_ERROR_CODES,\n /** Something JavaScript can hold and JSON cannot: a getter, a hole, a symbol key, an object that throws when read. */\n 'not-data',\n /** A part of the data envelope the runtime does not know. */\n 'unknown-property',\n /** A dataset the report declares and the data lacks. */\n 'missing-dataset',\n /** Data for a dataset the report does not declare. */\n 'undeclared-dataset',\n /** A field the contract declares and a record lacks, which is not the same as null. */\n 'missing-field',\n /** Null where the contract or the parameter does not allow it. */\n 'unexpected-null',\n /** A field the contract does not declare: a report never carries what it does not print. */\n 'undeclared-field',\n /** More detail rows than `MAX_DETAIL_ROWS`. */\n 'too-many-rows',\n /** Data the provider says is incomplete, in a final render. */\n 'incomplete',\n /** A captured count other than the rows given, or more than the cap. */\n 'completeness-mismatch',\n 'invalid-completeness',\n 'invalid-consistency',\n /** A required parameter with no value and no default. */\n 'missing-parameter',\n /** A value for a parameter the report does not declare. */\n 'undeclared-parameter',\n /** More errors were found than are listed. */\n 'too-many-errors',\n] as const\nexport type DataErrorCode = (typeof DATA_ERROR_CODES)[number]\n\nexport interface DataError {\n /** A JSON Pointer into the data or the parameter values: `/detail/17/amount`, `/from`. */\n readonly path: string\n readonly code: DataErrorCode\n /** For a person: what was expected, never what was found. */\n readonly message: string\n}\n\n/**\n * Errors listed per check: as many as report-spec lists for a report, for\n * the same reasons. Past it, one `too-many-errors` entry says the list was\n * cut short, and the check stops reading.\n */\nexport const MAX_DATA_ERRORS = MAX_ERRORS\n\n/** The errors one check has found, bounded. */\nexport class DataFindings {\n readonly #errors: DataError[] = []\n #overflowed = false\n\n report(path: string, code: DataErrorCode, message: string): void {\n if (this.#errors.length < MAX_DATA_ERRORS) this.#errors.push({ path, code, message })\n else this.#overflowed = true\n }\n\n /** Whether the list is cut short: once it is, nothing more is worth reading. */\n get full(): boolean {\n return this.#overflowed\n }\n\n get empty(): boolean {\n return this.#errors.length === 0\n }\n\n /** The errors in the order found, and a last one when more were found than listed. */\n errors(): DataError[] {\n const errors = [...this.#errors]\n if (this.#overflowed) errors.push({ path: '', code: 'too-many-errors', message: `more than ${MAX_DATA_ERRORS} errors were found; the first ${MAX_DATA_ERRORS} are listed` })\n return errors\n }\n}\n\n/** `path` extended by one key or index, escaped as RFC 6901 says. */\nexport function at(path: string, key: string | number): string {\n if (typeof key === 'number') return `${path}/${key}`\n return `${path}/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`\n}\n\n/** Whether `key` is longer than any id the format allows: such a key is never one the report declares, and never goes into a path or a message. */\nexport function isLongKey(key: string): boolean {\n return key.length > MAX_KEY_LENGTH\n}\n\n/** The path to `key` in the object at `path`; the object's own path for a long key. */\nexport function keyAt(path: string, key: string): string {\n return isLongKey(key) ? path : at(path, key)\n}\n","/**\n * The data a report is rendered from, and the check that admits it.\n *\n * A host hands over one envelope (plan 13.2): one header record and one\n * primary detail list for version 0, with what the provider says about\n * them -- how many rows it captured against what cap, and how consistent\n * the capture is. `checkData` holds every value to the report's dataset\n * contracts before anything reads it, and refuses rather than repairs:\n *\n * - **Types are the contract's.** Each value is read as its field's type\n * (`values.ts`), exact numbers as strings and never through a JavaScript\n * number, and held as the runtime computes with it.\n * - **Null is not missing.** Null is a value where the contract allows it,\n * and prints as nothing. A field the data lacks altogether is an error in\n * a final render, never an empty cell (0007); a preview, which may run on\n * a sample, warns once per field and leaves it missing.\n * - **Data minimisation.** A field, or a dataset, the report does not\n * declare is refused: a report never carries what it does not print, so\n * nothing it was not written to read rides along into a render, a cache\n * or a log.\n * - **No silent truncation.** A final render prints every row or none: data\n * the provider calls incomplete is refused, and so is a captured count\n * that disagrees with the rows given.\n * - **Bounded.** The rows and every string are bounded before they are\n * read, and so is the error list; once it is full, nothing more is read.\n *\n * What is held afterwards is a frozen copy, read once from the host's\n * objects, which no later change to them reaches.\n */\nimport { MAX_KEY_LENGTH } from '@formancy/report-spec'\nimport type { DatasetContract, DatasetRole, ReportDefinition } from '@formancy/report-spec'\nimport { at, DataFindings, isLongKey, keyAt } from './data-errors.js'\nimport type { DataError, DataErrorCode } from './data-errors.js'\nimport { readList, readRecord, UNREADABLE } from './input.js'\nimport type { ContainerCode } from './input.js'\nimport { readValue } from './values.js'\nimport type { CheckedValue } from './values.js'\n\n/**\n * How consistent the provider's capture is (plan 13.2): captured by the\n * host, read in one database snapshot, or explicitly neither -- the label\n * Formancy Data 0.1.0's records carry, read at different moments.\n */\nexport const CONSISTENCY_MODES = ['host-captured', 'transaction-snapshot', 'best-effort'] as const\nexport type Consistency = (typeof CONSISTENCY_MODES)[number]\n\n/** A final render prints the report; a preview shows an author a sample while they work, and says what it lacks. */\nexport const DATA_MODES = ['final', 'preview'] as const\nexport type DataMode = (typeof DATA_MODES)[number]\n\n/**\n * Detail rows in one render. Chosen, not derived: a report is read by a\n * person, and at the renderer trial's 48 rows a page (`docs/renderer-trial.md`,\n * 15 October 2026) this is over 2,000 pages, which pdfmake took more than 35\n * seconds to lay out at the 1,829 ms per hundred pages measured there. The\n * PDF's page bound refuses most such reports first; this bounds the\n * runtime's own work -- checking, sorting, totalling -- before a page is\n * laid out. At the bound, checking rows of the test sample report's nine\n * fields took a median of 1.5 seconds, and ordering them by site and SKU 0.5\n * (five warm runs under vitest, Node 24.21, an Intel i9-10900K, 15 October\n * 2026).\n */\nexport const MAX_DETAIL_ROWS = 100_000\n\n/** What the provider says about the rows it handed over. */\nexport interface Completeness {\n /** False when the provider stopped before the end: at its cap, or sampling. */\n readonly complete: boolean\n /** How many detail rows it captured: exactly the rows given. */\n readonly captured: number\n /** The most rows it would capture, when it has a cap. */\n readonly cap?: number\n}\n\n/** The envelope a host renders a report from. Untrusted: `checkData` reads it as data, whatever its type says. */\nexport interface ReportData {\n /** The header dataset's one record, by field id. */\n readonly header?: Readonly<Record<string, unknown>>\n /** The detail dataset's rows, in the provider's order. */\n readonly detail?: readonly Readonly<Record<string, unknown>>[]\n readonly completeness: Completeness\n readonly consistency: Consistency\n}\n\n/**\n * One record, checked: each declared field's value as its type holds it, or\n * null. A field a preview's data lacks is absent, not null. The record has\n * no prototype, so a field named `constructor` is the record's own or\n * absent, never inherited.\n */\nexport type CheckedRecord = { readonly [field: string]: CheckedValue | null }\n\nexport interface CheckedData {\n readonly mode: DataMode\n /** The header record; absent when the report declares no header dataset. */\n readonly header?: CheckedRecord\n /** The detail rows, in the provider's order; empty when the report declares no detail dataset. */\n readonly detail: readonly CheckedRecord[]\n readonly completeness: Completeness\n readonly consistency: Consistency\n}\n\nexport type DataCheck =\n | { readonly ok: true; readonly data: CheckedData; /** What a preview lacks; always empty in a final render, which refuses it. */ readonly warnings: readonly DataError[] }\n | { readonly ok: false; readonly errors: readonly DataError[] }\n\nexport interface DataCheckOptions {\n readonly mode: DataMode\n}\n\nconst ENVELOPE: readonly string[] = ['header', 'detail', 'completeness', 'consistency']\nconst COMPLETENESS: readonly string[] = ['complete', 'captured', 'cap']\n\nconst MINIMISATION = 'a report never carries what it does not print, so data it does not read is refused rather than carried along'\n\n/** What one check carries through: its errors, its warnings, and its mode. */\ninterface Check {\n readonly errors: DataFindings\n readonly warnings: DataError[]\n readonly final: boolean\n}\n\n/** A container's code as a data error's: a list too long is a dataset with too many rows. */\nconst CONTAINER: { readonly [C in ContainerCode]: DataErrorCode } = { 'wrong-type': 'wrong-type', 'not-data': 'not-data', 'too-many': 'too-many-rows' }\n\n/** Reports what a record holds that is not data, by key; returns those keys. */\nfunction reportProblems(c: Check, path: string, problems: readonly { readonly key?: string; readonly message: string }[]): ReadonlySet<string> {\n const keys = new Set<string>()\n for (const problem of problems) {\n if (problem.key !== undefined) keys.add(problem.key)\n c.errors.report(problem.key === undefined ? path : keyAt(path, problem.key), 'not-data', problem.message)\n }\n return keys\n}\n\n/** How many records lacked a field, and where it was first missed. */\ninterface Missing {\n first: string\n count: number\n}\n\n/** One record held to `contract`, or undefined when it cannot be read at all. Fields it lacks are tallied in `missing`. */\nfunction checkRecord(c: Check, contract: DatasetContract, declared: ReadonlySet<string>, raw: unknown, path: string, missing: Map<string, Missing>): CheckedRecord | undefined {\n const read = readRecord(raw)\n if (!read.ok) {\n c.errors.report(path, read.code, read.message)\n return undefined\n }\n const unreadable = reportProblems(c, path, read.problems)\n const record = Object.create(null) as Record<string, CheckedValue | null>\n for (const field of contract.fields) {\n const where = at(path, field.id)\n if (unreadable.has(field.id)) continue\n if (!read.entries.has(field.id)) {\n const tally = missing.get(field.id)\n if (c.final) c.errors.report(where, 'missing-field', `${field.id}: the contract declares this field and the data lacks it; a missing field is not null, and a final render refuses it`)\n else if (tally === undefined) missing.set(field.id, { first: where, count: 1 })\n else tally.count++\n continue\n }\n const value = read.entries.get(field.id)\n if (value === null) {\n if (field.nullable) record[field.id] = null\n else c.errors.report(where, 'unexpected-null', `${field.id}: the contract says this field is never null`)\n continue\n }\n const checked = readValue(field.type, value, field.scale)\n if (checked.ok) record[field.id] = checked.value\n else c.errors.report(where, checked.code, `${field.id}: ${checked.message}`)\n }\n for (const key of read.entries.keys()) {\n if (declared.has(key)) continue\n const what = isLongKey(key) ? `a property name longer than ${MAX_KEY_LENGTH} characters, which no field has` : 'the contract declares no such field'\n c.errors.report(keyAt(path, key), 'undeclared-field', `${what}; ${MINIMISATION}`)\n }\n return Object.freeze(record)\n}\n\n/** A warning for each field a preview's records lacked, once per field. */\nfunction warnMissing(c: Check, missing: ReadonlyMap<string, Missing>, records: number, role: DatasetRole): void {\n for (const [field, { first, count }] of missing) {\n const where = role === 'header' ? 'the header record' : `${count} of ${records} rows`\n c.warnings.push({ path: first, code: 'missing-field', message: `${field}: missing from ${where}; a final render refuses data without it` })\n }\n}\n\n/** The report does not declare `role`, and the data holds it. */\nfunction undeclaredDataset(c: Check, role: DatasetRole): void {\n c.errors.report(`/${role}`, 'undeclared-dataset', `the report declares no ${role} dataset; ${MINIMISATION}`)\n}\n\n/** The report declares `role`, and the data lacks it: an error in a final render, a warning in a preview. */\nfunction missingDataset(c: Check, role: DatasetRole): void {\n const message = `the report declares a ${role} dataset and the data has none`\n if (c.final) c.errors.report(`/${role}`, 'missing-dataset', message)\n else c.warnings.push({ path: `/${role}`, code: 'missing-dataset', message: `${message}; every field of it is missing` })\n}\n\nconst EMPTY: CheckedRecord = Object.freeze(Object.create(null) as CheckedRecord)\n\nfunction checkHeader(c: Check, contract: DatasetContract | undefined, entries: ReadonlyMap<string, unknown>): CheckedRecord | undefined {\n const present = entries.has('header')\n if (contract === undefined) {\n if (present) undeclaredDataset(c, 'header')\n return undefined\n }\n if (!present) {\n missingDataset(c, 'header')\n return EMPTY\n }\n const missing = new Map<string, Missing>()\n const record = checkRecord(c, contract, new Set(contract.fields.map(({ id }) => id)), entries.get('header'), '/header', missing)\n warnMissing(c, missing, 1, 'header')\n return record\n}\n\n/** The detail rows checked, and how many were given when that could be counted. */\nfunction checkDetail(c: Check, contract: DatasetContract | undefined, entries: ReadonlyMap<string, unknown>): { readonly rows: CheckedRecord[]; readonly given: number | undefined } {\n const present = entries.has('detail')\n if (contract === undefined || !present) {\n if (contract === undefined && present) undeclaredDataset(c, 'detail')\n if (contract !== undefined) missingDataset(c, 'detail')\n return { rows: [], given: contract === undefined && !present ? 0 : undefined }\n }\n const list = readList(entries.get('detail'), MAX_DETAIL_ROWS)\n if (!list.ok) {\n const message = list.code === 'too-many' ? `${list.message}: a render reads at most ${MAX_DETAIL_ROWS} detail rows` : list.message\n c.errors.report('/detail', CONTAINER[list.code], message)\n return { rows: [], given: undefined }\n }\n const unreadable = new Map(list.problems.map(({ index, message }) => [index, message]))\n const declared = new Set(contract.fields.map(({ id }) => id))\n const missing = new Map<string, Missing>()\n const rows: CheckedRecord[] = []\n for (const [index, item] of list.items.entries()) {\n if (c.errors.full) break\n if (item === UNREADABLE) {\n c.errors.report(at('/detail', index), 'not-data', unreadable.get(index) as string)\n continue\n }\n const record = checkRecord(c, contract, declared, item, at('/detail', index), missing)\n if (record !== undefined) rows.push(record)\n }\n warnMissing(c, missing, list.items.length, 'detail')\n return { rows, given: list.items.length }\n}\n\nconst isCount = (value: unknown): value is number => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n\nfunction checkCompleteness(c: Check, raw: unknown, given: number | undefined): Completeness | undefined {\n const read = readRecord(raw)\n const shape = 'completeness is { \"complete\": true or false, \"captured\": the rows given, \"cap\": the most rows the provider would capture, if it has a cap }'\n if (!read.ok) {\n c.errors.report('/completeness', 'invalid-completeness', shape)\n return undefined\n }\n reportProblems(c, '/completeness', read.problems)\n for (const key of read.entries.keys()) {\n if (!COMPLETENESS.includes(key)) c.errors.report(keyAt('/completeness', key), 'invalid-completeness', `${shape}; nothing else`)\n }\n const { complete, captured, cap } = Object.fromEntries(COMPLETENESS.map((key) => [key, read.entries.get(key)]))\n const valid = typeof complete === 'boolean' && isCount(captured) && (cap === undefined || isCount(cap))\n if (typeof complete !== 'boolean') c.errors.report('/completeness/complete', 'invalid-completeness', 'complete is true or false')\n if (!isCount(captured)) c.errors.report('/completeness/captured', 'invalid-completeness', 'captured is a count of rows: a whole number, 0 or more')\n if (cap !== undefined && !isCount(cap)) c.errors.report('/completeness/cap', 'invalid-completeness', 'cap is a count of rows: a whole number, 0 or more')\n if (!valid) return undefined\n if (given !== undefined && captured !== given) {\n c.errors.report('/completeness/captured', 'completeness-mismatch', `the provider says it captured ${captured} rows and gave ${given}; rows lost or added on the way are never papered over`)\n }\n if (cap !== undefined && captured > cap) c.errors.report('/completeness/cap', 'completeness-mismatch', `the provider says it captured ${captured} rows, more than its cap of ${cap}`)\n if (!complete) {\n const message = 'the provider says the data is incomplete'\n if (c.final) c.errors.report('/completeness/complete', 'incomplete', `${message}; a final render prints every row or none, and never a silently truncated report`)\n else c.warnings.push({ path: '/completeness/complete', code: 'incomplete', message: `${message}; this preview shows only what was captured` })\n }\n return Object.freeze({ complete, captured, ...(cap === undefined ? {} : { cap }) })\n}\n\nfunction checkConsistency(c: Check, raw: unknown): Consistency | undefined {\n if (CONSISTENCY_MODES.includes(raw as Consistency)) return raw as Consistency\n c.errors.report('/consistency', 'invalid-consistency', `consistency is one of ${CONSISTENCY_MODES.map((mode) => `\"${mode}\"`).join(', ')}`)\n return undefined\n}\n\n/**\n * `data` held to `report`'s dataset contracts, or every reason it is\n * refused, up to `MAX_DATA_ERRORS`. `report` is one the validator accepts.\n * Any mode but `preview` is held as final: the stricter of the two.\n */\nexport function checkData(report: ReportDefinition, data: ReportData, options: DataCheckOptions): DataCheck {\n const c: Check = { errors: new DataFindings(), warnings: [], final: options.mode !== 'preview' }\n const top = readRecord(data)\n if (!top.ok) return { ok: false, errors: [{ path: '', code: top.code, message: top.message }] }\n reportProblems(c, '', top.problems)\n for (const key of top.entries.keys()) {\n if (!ENVELOPE.includes(key)) c.errors.report(keyAt('', key), 'unknown-property', `the data holds ${ENVELOPE.join(', ')}, and nothing the runtime does not know`)\n }\n const header = checkHeader(c, report.datasets.header, top.entries)\n const detail = checkDetail(c, report.datasets.detail, top.entries)\n const completeness = checkCompleteness(c, top.entries.get('completeness'), detail.given)\n const consistency = checkConsistency(c, top.entries.get('consistency'))\n if (!c.errors.empty || completeness === undefined || consistency === undefined) return { ok: false, errors: c.errors.errors() }\n const checked: CheckedData = {\n mode: c.final ? 'final' : 'preview',\n ...(header === undefined ? {} : { header }),\n detail: Object.freeze(detail.rows),\n completeness,\n consistency,\n }\n return { ok: true, data: Object.freeze(checked), warnings: c.warnings }\n}\n","/**\n * The values a person supplies before rendering, held to the report's\n * parameters.\n *\n * A parameter is read by exactly the rules a dataset field of its type is\n * (`values.ts`), so `params.copies` is an integer however it reached the\n * report: from a parameter form, an API call or a default. Then:\n *\n * - **Defaults apply** to a parameter left out. A default is written as the\n * format writes it -- an exact string, or a boolean -- and read by the\n * same rules as a value.\n * - **Required is enforced.** A required parameter with neither a value nor\n * a default is refused.\n * - **Null only where there may be none.** A parameter that is neither\n * required nor defaulted may be null; any other is never null when an\n * expression reads it (0009), so null for it is refused, not read as its\n * default.\n * - **Nothing undeclared.** A value for a parameter the report does not\n * declare is refused.\n *\n * The values are checked again here even when a parameter form checked\n * them already (plan 12.4): what reaches a render is decided by the\n * runtime, never by the browser that sent it.\n */\nimport { MAX_KEY_LENGTH } from '@formancy/report-spec'\nimport type { ParameterDef, ReportDefinition } from '@formancy/report-spec'\nimport { at, DataFindings, isLongKey, keyAt } from './data-errors.js'\nimport type { DataError } from './data-errors.js'\nimport { readRecord } from './input.js'\nimport { readValue } from './values.js'\nimport type { CheckedValue } from './values.js'\n\n/** The parameters' values by id, each read as its type or null. It has no prototype, so a parameter named `constructor` is its own value. */\nexport type CheckedParameters = { readonly [parameter: string]: CheckedValue | null }\n\nexport type ParameterCheck = { readonly ok: true; readonly values: CheckedParameters } | { readonly ok: false; readonly errors: readonly DataError[] }\n\n/** The value `parameter` takes when nobody supplied one; undefined when it must be supplied. */\nfunction absent(errors: DataFindings, parameter: ParameterDef, path: string): CheckedValue | null | undefined {\n if (parameter.default !== undefined) {\n const read = readValue(parameter.type, parameter.default)\n if (read.ok) return read.value\n errors.report(path, read.code, `${parameter.id}: its default is not a ${parameter.type}: ${read.message}`)\n return undefined\n }\n if (!parameter.required) return null\n errors.report(path, 'missing-parameter', `${parameter.id}: the report requires this parameter, and it has no value and no default`)\n return undefined\n}\n\n/**\n * `values` held to `report`'s parameters, with defaults applied, or every\n * reason they are refused. `report` is one the validator accepts. A path is\n * a JSON Pointer into `values`: `/copies`.\n */\nexport function checkParameters(report: ReportDefinition, values: Readonly<Record<string, unknown>>): ParameterCheck {\n const errors = new DataFindings()\n const read = readRecord(values)\n if (!read.ok) return { ok: false, errors: [{ path: '', code: read.code, message: `parameters are ${read.message}` }] }\n const unreadable = new Set<string>()\n for (const problem of read.problems) {\n if (problem.key !== undefined) unreadable.add(problem.key)\n errors.report(problem.key === undefined ? '' : keyAt('', problem.key), 'not-data', problem.message)\n }\n const checked = Object.create(null) as Record<string, CheckedValue | null>\n for (const parameter of report.parameters) {\n const path = at('', parameter.id)\n if (unreadable.has(parameter.id)) continue\n if (!read.entries.has(parameter.id)) {\n const value = absent(errors, parameter, path)\n if (value !== undefined) checked[parameter.id] = value\n continue\n }\n const raw = read.entries.get(parameter.id)\n if (raw === null) {\n if (!parameter.required && parameter.default === undefined) checked[parameter.id] = null\n else {\n const why = parameter.default === undefined ? 'the report requires it' : 'it has a default; leave it out to use the default'\n errors.report(path, 'unexpected-null', `${parameter.id}: never null, because ${why}`)\n }\n continue\n }\n const value = readValue(parameter.type, raw)\n if (value.ok) checked[parameter.id] = value.value\n else errors.report(path, value.code, `${parameter.id}: ${value.message}`)\n }\n const declared = new Set(report.parameters.map(({ id }) => id))\n for (const key of read.entries.keys()) {\n if (declared.has(key)) continue\n const what = isLongKey(key) ? `a name longer than ${MAX_KEY_LENGTH} characters, which no parameter has` : 'the report declares no such parameter'\n errors.report(keyAt('', key), 'undeclared-parameter', `${what}; a report reads nothing it was not written to read`)\n }\n if (!errors.empty) return { ok: false, errors: errors.errors() }\n return { ok: true, values: Object.freeze(checked) }\n}\n","/**\n * Exact totals and declared rounding, over `@formancy/expressions`'\n * `Decimal`: a value as an integer of units at a scale, so that nothing here\n * ever passes through a JavaScript number.\n *\n * Totals are decided once, here (0007): a sum is exact at the largest scale\n * it meets, a minimum or maximum compares by value, and an average is the\n * exact quotient rounded once, by the rule the aggregate declares. Rounding\n * follows report-spec's `Rounding`: to a multiple of `increment` when one is\n * given -- 0.05 for Swiss cash rounding -- and otherwise to `scale` places,\n * ties going by `mode` either way, and the result at exactly `scale` places.\n *\n * Upstream's own `roundDecimal` rounds half away from zero to a number of\n * places and nothing else; a declared rounding also has half to even and an\n * increment, so it is worked here, on integers, once for every case.\n * `decimal.test.ts` holds it against a reference written independently.\n */\nimport { addDecimal, compareDecimal, Decimal, decimalFromString } from '@formancy/expressions'\nimport type { Rounding, RoundingMode } from '@formancy/report-spec'\n\n/**\n * `numerator / denominator` (denominator more than 0) rounded to a whole\n * number, ties by `mode`. Division truncates towards zero; what it left\n * decides whether to step away from zero.\n */\nfunction roundQuotient(numerator: bigint, denominator: bigint, mode: RoundingMode): bigint {\n const quotient = numerator / denominator\n const remainder = numerator % denominator\n const twice = 2n * (remainder < 0n ? -remainder : remainder)\n if (twice < denominator) return quotient\n const away = numerator < 0n ? quotient - 1n : quotient + 1n\n if (twice > denominator) return away\n return mode === 'half-away-from-zero' || quotient % 2n !== 0n ? away : quotient\n}\n\n/** The step a rounding rounds to: its increment, or one unit at its scale. Throws for a step report-spec refuses. */\nfunction stepOf(rounding: Rounding): Decimal {\n if (rounding.increment === undefined) return new Decimal(1n, rounding.scale)\n const step = decimalFromString(rounding.increment)\n if (step.units <= 0n || step.scale > rounding.scale) {\n throw new RangeError(`an increment is more than 0 and has no more places than the ${rounding.scale} its rounding keeps`)\n }\n return step\n}\n\n/** The exact quotient `numerator / denominator` rounded as `rounding` declares. */\nfunction roundRatio(numerator: bigint, denominator: bigint, rounding: Rounding): Decimal {\n const step = stepOf(rounding)\n const steps = roundQuotient(numerator * 10n ** BigInt(step.scale), denominator * step.units, rounding.mode)\n return new Decimal(steps * step.units * 10n ** BigInt(rounding.scale - step.scale), rounding.scale)\n}\n\n/**\n * `value` rounded as `rounding` declares, at exactly its scale. A negative\n * value that rounds to nothing is zero, never minus zero. Throws a\n * RangeError for an increment report-spec refuses: of zero or less, or with\n * more places than the scale.\n */\nexport function roundDecimalAs(value: Decimal, rounding: Rounding): Decimal {\n return roundRatio(value.units, 10n ** BigInt(value.scale), rounding)\n}\n\n/** The exact sum, at the largest scale among the values; 0 over none (0007). */\nexport function sumDecimals(values: Iterable<Decimal>): Decimal {\n let total = new Decimal(0n, 0)\n for (const value of values) total = addDecimal(total, value)\n return total\n}\n\n/** The value `keep` prefers over each other, compared by value; the first of equals is kept, as written. */\nfunction extreme(values: Iterable<Decimal>, keep: (order: -1 | 0 | 1) => boolean): Decimal | null {\n let found: Decimal | null = null\n for (const value of values) if (found === null || keep(compareDecimal(value, found))) found = value\n return found\n}\n\n/** The least value, as written; null over none (0007). */\nexport function minDecimal(values: Iterable<Decimal>): Decimal | null {\n return extreme(values, (order) => order < 0)\n}\n\n/** The greatest value, as written; null over none (0007). */\nexport function maxDecimal(values: Iterable<Decimal>): Decimal | null {\n return extreme(values, (order) => order > 0)\n}\n\n/**\n * The exact average, rounded once as `rounding` declares: the exact sum\n * over the count, never a quotient rounded and then rounded again. Null\n * over no values (0007).\n */\nexport function averageDecimals(values: Iterable<Decimal>, rounding: Rounding): Decimal | null {\n let count = 0n\n let total = new Decimal(0n, 0)\n for (const value of values) {\n total = addDecimal(total, value)\n count++\n }\n return count === 0n ? null : roundRatio(total.units, count * 10n ** BigInt(total.scale), rounding)\n}\n","/**\n * A value as the text a report prints, for the report's locale: report-spec's\n * number, currency, date and text formats, through Intl.\n *\n * - **Exact to the last digit.** A number reaches Intl as the string of its\n * digits, already rounded here to exactly the places it prints, half away\n * from zero as a person rounds by hand. An ES2023 engine formats such a\n * string exactly, and `format.test.ts` holds that it does; Intl is never\n * handed a double and never rounds. Up to a bound: ECMA-402 reads a\n * string whose double would be infinite as infinity, and prints '∞'. A\n * number with more than `MAX_FORMATTED_DIGITS` integer digits is refused\n * instead; printed without a format, it prints whole.\n * - **The locale's conventions.** Grouping, separators, currency symbols,\n * month names and case are the locale's, as the engine's ICU has them.\n * ICU versions can differ -- which mark Swiss German groups digits with is\n * one such difference, and `format.test.ts` reads it from the engine -- so\n * the same report can print differently on two engines. That is the cost\n * of not carrying a locale database here.\n * - **Dates have no zone.** A date, and a date and time without a zone, are\n * formatted in UTC from their own fields, so 2026-01-01 is the first of\n * January wherever the report renders. Only an instant is shown in a zone,\n * and that zone is the host's to name: the machine's is never used.\n * - **Nothing is guessed.** A locale or zone the engine lacks is refused\n * rather than replaced by a default, and a format that cannot show a value\n * is an error rather than a blank.\n *\n * Null prints as nothing (0007), under every format.\n */\nimport { Decimal, decimalToString } from '@formancy/expressions'\nimport type { CurrencyFormat, CurrencySource, DateStyle, FieldType, Format, NumberFormat, TextTransform } from '@formancy/report-spec'\nimport type { CheckedRecord } from './data.js'\nimport { roundDecimalAs } from './decimal.js'\nimport type { CheckedParameters } from './parameters.js'\nimport { readValue } from './values.js'\nimport type { FieldValues } from './values.js'\n\n/** The types a value printed can have: every field type but an image, which is drawn. */\nexport type PrintableType = Exclude<FieldType, 'image'>\n\n/** A value with its type, as the runtime holds it (`values.ts`). */\nexport type TypedValue = { readonly [T in PrintableType]: { readonly type: T; readonly value: FieldValues[T] } }[PrintableType]\n\nexport const FORMAT_ERROR_CODES = [\n /** A locale the engine's Intl does not have, which it would silently replace with the host's. */\n 'unsupported-locale',\n /** A time zone the engine's Intl does not know. */\n 'unsupported-time-zone',\n /** A format that cannot show the value it is given: a number format over text, a date format over a number. */\n 'format-type-mismatch',\n /** An amount whose currency field or parameter has no value. */\n 'no-currency',\n /** A currency that is not an ISO 4217 code in capitals. */\n 'invalid-currency',\n /** A number with more integer digits than `MAX_FORMATTED_DIGITS`, which Intl would print as '∞'. */\n 'number-too-large',\n] as const\n\n/**\n * The most integer digits a number or currency format prints: 308. A double\n * holds up to about 1.8 × 10^308, and ECMA-402's ToIntlMathematicalValue\n * reads a string whose double would be infinite as infinity, so every\n * number of 308 digits or fewer prints exactly and one of 309 may not.\n */\nexport const MAX_FORMATTED_DIGITS = 308\nexport type FormatErrorCode = (typeof FORMAT_ERROR_CODES)[number]\n\nexport type Formatted = { readonly ok: true; readonly text: string } | { readonly ok: false; readonly code: FormatErrorCode; readonly message: string }\n\n/** What a render is formatted for: the report's locale, and the zone its instants are shown in. */\nexport interface FormatContext {\n /** A BCP 47 tag, as a report's `locale` is. */\n readonly locale: string\n /** An IANA time zone, such as `Europe/Zurich`, named by the host. */\n readonly timeZone: string\n}\n\n/** Where a currency format finds a currency read from a field or a parameter. */\nexport interface CurrencyScope {\n readonly params?: CheckedParameters\n readonly header?: CheckedRecord\n /** The current detail row, in a table's cells. */\n readonly row?: CheckedRecord\n}\n\nexport interface Formatter {\n readonly locale: string\n readonly timeZone: string\n /** `value` as `format` shows it, or as it prints plainly without one. */\n format(value: TypedValue | null, format: Format | undefined, scope?: CurrencyScope): Formatted\n}\n\nfunction refused(code: FormatErrorCode, message: string): Formatted {\n return { ok: false, code, message }\n}\n\n/**\n * A value printed with no format: as the format writes it. Exact digits\n * with their scale, ISO dates, an instant in UTC; nothing is interpreted.\n */\nexport function plainText(value: TypedValue | null): string {\n if (value === null) return ''\n if (value.type === 'integer' || value.type === 'boolean') return String(value.value)\n if (value.type === 'decimal') return decimalToString(value.value)\n return value.value\n}\n\n/**\n * Whether the engine has `locale`, in its number and date formats and its\n * collation, by the lookup a tag like `de-CH` falls back from region to\n * language with. A tag it cannot read is not one it has.\n */\nexport function supportedLocale(locale: string): boolean {\n try {\n const options = { localeMatcher: 'lookup' } as const\n return (\n Intl.NumberFormat.supportedLocalesOf([locale], options).length === 1 &&\n Intl.DateTimeFormat.supportedLocalesOf([locale], options).length === 1 &&\n Intl.Collator.supportedLocalesOf([locale], options).length === 1\n )\n } catch {\n return false\n }\n}\n\n/** Whether Intl knows `timeZone`. */\nfunction knownTimeZone(timeZone: string): boolean {\n try {\n new Intl.DateTimeFormat('en', { timeZone })\n return true\n } catch {\n return false\n }\n}\n\n/** The time a date-and-time format shows with each date style: no seconds for short, seconds otherwise; never the zone's name, which a local time does not have. */\nconst TIME_STYLE: { readonly [S in DateStyle]: 'short' | 'medium' } = { short: 'short', medium: 'medium', long: 'medium' }\n\n/** A moment to show: when, whether it has a time of day, and whether it is shown in the render's zone or, having none, in UTC. */\ninterface Moment {\n readonly epochMs: number\n readonly time: boolean\n readonly zoned: boolean\n}\n\n/** Epoch milliseconds of a calendar date and time in UTC; Date.UTC would read the years 0 to 99 as 1900 to 1999. */\nfunction utc(year: number, month: number, day: number, hour = 0, minute = 0, second = 0): number {\n const moment = new Date(0)\n moment.setUTCFullYear(year, month - 1, day)\n moment.setUTCHours(hour, minute, second, 0)\n return moment.getTime()\n}\n\n/** The numbers in `text`, a date or a date and time `readValue` accepted, in order. */\nconst fieldsOf = (text: string): number[] => (text.match(/\\d+/g) as RegExpMatchArray).map(Number)\n\n/** `value` as a `type` spells it: a value of that type, or a string an expression gave that spells one, as `readValue` holds it. */\nfunction spelledAs(value: TypedValue, type: 'date' | 'datetime' | 'instant'): string | undefined {\n if (value.type === type) return value.value as string\n if (value.type !== 'string') return undefined\n const read = readValue(type, value.value)\n return read.ok ? read.value : undefined\n}\n\n/** The moment a value spells: a date, a date and time, or an instant, by its type or, for a string an expression gave, by its syntax. */\nfunction momentOf(value: TypedValue): Moment | undefined {\n const date = spelledAs(value, 'date')\n if (date !== undefined) {\n const [year, month, day] = fieldsOf(date) as [number, number, number]\n return { epochMs: utc(year, month, day), time: false, zoned: false }\n }\n const local = spelledAs(value, 'datetime')\n if (local !== undefined) {\n const [year, month, day, hour, minute, second] = fieldsOf(local) as [number, number, number, number, number, number]\n return { epochMs: utc(year, month, day, hour, minute, second), time: true, zoned: false }\n }\n const instant = spelledAs(value, 'instant')\n return instant === undefined ? undefined : { epochMs: new Date(instant).getTime(), time: true, zoned: true }\n}\n\n/** The exact number a value holds, or undefined when it holds none. */\nfunction exactNumber(value: TypedValue): Decimal | undefined {\n if (value.type === 'integer') return new Decimal(value.value, 0)\n return value.type === 'decimal' ? value.value : undefined\n}\n\n/** The currency code an amount is in, from the format, a field or a parameter, or why there is none. */\nfunction currencyOf(source: CurrencySource, scope: CurrencyScope | undefined): string | Formatted {\n if (source.kind === 'code') return source.code\n const [name, raw] =\n source.kind === 'parameter'\n ? [`parameter ${source.parameter}`, scope?.params?.[source.parameter]]\n : [`field ${source.field.field}`, (source.field.dataset === 'header' ? scope?.header : scope?.row)?.[source.field.field]]\n if (raw === null || raw === undefined) return refused('no-currency', `the amount's currency, ${name}, has no value, and an amount without one reads as some other currency`)\n if (typeof raw === 'string' && /^[A-Z]{3}$/.test(raw)) return raw\n return refused('invalid-currency', `the amount's currency, ${name}, is not an ISO 4217 code in capitals, such as CHF`)\n}\n\n/** The Intl formatter `cache` keeps for `options`, made by `make` the first time they are asked for: a table formats a column with one. */\nfunction kept<T>(cache: Map<string, T>, options: object, make: () => T): T {\n const key = JSON.stringify(options)\n const found = cache.get(key)\n if (found !== undefined) return found\n const made = make()\n cache.set(key, made)\n return made\n}\n\n/** A formatter for one locale and time zone, which builds each Intl formatter it needs once and keeps it. */\nclass LocaleFormatter implements Formatter {\n readonly locale: string\n readonly timeZone: string\n readonly #numbers = new Map<string, Intl.NumberFormat>()\n readonly #dates = new Map<string, Intl.DateTimeFormat>()\n\n constructor(context: FormatContext) {\n this.locale = context.locale\n this.timeZone = context.timeZone\n }\n\n format(value: TypedValue | null, format: Format | undefined, scope?: CurrencyScope): Formatted {\n if (value === null) return { ok: true, text: '' }\n if (format === undefined) return { ok: true, text: plainText(value) }\n switch (format.kind) {\n case 'text':\n return { ok: true, text: this.#transformed(plainText(value), format.transform) }\n case 'date':\n return this.#date(value, format.style)\n default:\n return this.#number(value, format, scope)\n }\n }\n\n #transformed(text: string, transform: TextTransform | undefined): string {\n if (transform === 'upper') return text.toLocaleUpperCase(this.locale)\n return transform === 'lower' ? text.toLocaleLowerCase(this.locale) : text\n }\n\n #number(value: TypedValue, format: NumberFormat | CurrencyFormat, scope: CurrencyScope | undefined): Formatted {\n const exact = exactNumber(value)\n if (exact === undefined) return refused('format-type-mismatch', `a ${format.kind} format shows integers and decimals, and this value is a ${value.type}`)\n const currency = format.kind === 'currency' ? currencyOf(format.currency, scope) : undefined\n if (typeof currency === 'object') return currency\n const rounded = decimalToString(roundDecimalAs(exact, { scale: format.scale, mode: 'half-away-from-zero' })) as Intl.StringNumericLiteral\n if (rounded.replace(/^-/, '').split('.')[0]!.length > MAX_FORMATTED_DIGITS) {\n return refused('number-too-large', `a number of more than ${MAX_FORMATTED_DIGITS} digits, which Intl would print as infinity; printed without a format, it prints whole`)\n }\n const options: Intl.NumberFormatOptions = {\n minimumFractionDigits: format.scale,\n maximumFractionDigits: format.scale,\n ...(currency === undefined ? { useGrouping: format.kind === 'number' && !format.grouping ? false : 'auto' } : { style: 'currency', currency }),\n }\n return { ok: true, text: kept(this.#numbers, options, () => new Intl.NumberFormat(this.locale, options)).format(rounded) }\n }\n\n #date(value: TypedValue, style: DateStyle): Formatted {\n const moment = momentOf(value)\n if (moment === undefined) return refused('format-type-mismatch', `a date format shows dates, dates and times, and instants, and this value is a ${value.type} that spells none`)\n const options: Intl.DateTimeFormatOptions = {\n dateStyle: style,\n ...(moment.time ? { timeStyle: TIME_STYLE[style] } : {}),\n timeZone: moment.zoned ? this.timeZone : 'UTC',\n }\n return { ok: true, text: kept(this.#dates, options, () => new Intl.DateTimeFormat(this.locale, options)).format(moment.epochMs) }\n }\n}\n\n/** A formatter for `context`, or why its locale or time zone is refused. */\nexport function createFormatter(context: FormatContext): { readonly ok: true; readonly formatter: Formatter } | { readonly ok: false; readonly code: FormatErrorCode; readonly message: string } {\n if (!supportedLocale(context.locale)) {\n return { ok: false, code: 'unsupported-locale', message: \"the engine's Intl does not have this locale, and would print the host's instead\" }\n }\n if (!knownTimeZone(context.timeZone)) return { ok: false, code: 'unsupported-time-zone', message: \"the engine's Intl does not know this time zone\" }\n return { ok: true, formatter: new LocaleFormatter(context) }\n}\n","/**\n * The order of a table's rows and its groups, decided once, here (0007).\n *\n * Rows are ordered by the group's key first, in its direction, then by each\n * sort key, each compared as its type: decimals by value, integers as\n * BigInt, dates and times in calendar order, text as the report's language\n * sorts it, false before true. Nulls -- and a field a preview lacks -- go\n * last whichever way a key runs, so an empty cell never lands among the\n * values. Rows whose keys are all equal keep the provider's order: the\n * row's index is the last key, so the comparator is a total order and the\n * result rests on it alone. `Array.prototype.sort` has been stable since\n * ES2019, which by itself keeps that order too, so no test can tell the two\n * apart; the index is there so that nothing depends on the algorithm.\n *\n * Text the collator holds equal but spelled differently -- é composed and\n * decomposed -- is ordered by code unit after the collator, so that rows\n * with identical keys always stand together and a group never splits around\n * another spelling. Collation is the engine's ICU's, and differs between\n * ICU versions as formatting does.\n */\nimport { compareDecimal } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport type { ReportDefinition, SortDirection, TableComponent } from '@formancy/report-spec'\nimport type { CheckedRecord } from './data.js'\nimport type { PrintableType } from './format.js'\nimport type { CheckedValue } from './values.js'\n\n/** One key rows are ordered by: a detail field, its type, and its direction. */\nexport interface OrderKey {\n readonly field: string\n readonly type: PrintableType\n readonly direction: SortDirection\n}\n\n/** A detail row in its place: the record, and its index in the order the provider gave the rows. */\nexport interface OrderedRow {\n readonly index: number\n readonly record: CheckedRecord\n}\n\n/** One group: its key, as its first row spells it, or null; then its rows, in order. */\nexport interface RowGroup {\n readonly key: CheckedValue | null\n readonly rows: readonly OrderedRow[]\n}\n\n/** A table's rows in order and, when it groups, its groups in order. */\nexport interface OrderedTable {\n readonly rows: readonly OrderedRow[]\n readonly groups?: readonly RowGroup[]\n}\n\n/** A value made comparable with `<` -- or, for text, with the collator -- for one key column. */\ntype Comparable = string | bigint | boolean\n\n/**\n * A date and time with its fraction of a second at nine digits, without a\n * zone: held without trailing zeros, '10:00:00.5' and '10:00:00' differ in\n * length, and as they stand '10:00:00.5Z' sorts before '10:00:00Z'.\n */\nexport function fixedWidth(value: string): string {\n const local = value.endsWith('Z') ? value.slice(0, -1) : value\n return `${local.slice(0, 19)}.${local.slice(20).padEnd(9, '0')}`\n}\n\n/** The values of `key` in every row, made comparable once; null for a null or missing one. */\nfunction column(rows: readonly CheckedRecord[], key: OrderKey): (Comparable | null)[] {\n const values = rows.map((record) => record[key.field] ?? null)\n switch (key.type) {\n case 'decimal': {\n // Every decimal of the column at one scale, so each comparison is one of integers.\n const decimals = values as (Decimal | null)[]\n const scale = Math.max(0, ...decimals.map((value) => value?.scale ?? 0))\n return decimals.map((value) => (value === null ? null : value.units * 10n ** BigInt(scale - value.scale)))\n }\n case 'datetime':\n case 'instant':\n return (values as (string | null)[]).map((value) => (value === null ? null : fixedWidth(value)))\n default:\n return values as (Comparable | null)[]\n }\n}\n\n/** -1, 0 or 1 for two values of one comparable column. */\nfunction compared(type: PrintableType, a: Comparable, b: Comparable, collator: Intl.Collator): number {\n if (type === 'string') {\n const order = collator.compare(a as string, b as string)\n if (order !== 0) return order\n }\n return a < b ? -1 : a > b ? 1 : 0\n}\n\n/**\n * `rows` in the order `keys` give, each key applied only among rows the keys\n * before it hold equal, with text compared as `locale` sorts it -- a locale\n * `supportedLocale` accepts. Ties keep the provider's order.\n */\nexport function orderRows(rows: readonly CheckedRecord[], keys: readonly OrderKey[], locale: string): OrderedRow[] {\n const collator = new Intl.Collator(locale, { usage: 'sort' })\n const columns = keys.map((key) => column(rows, key))\n const order = rows.map((_, index) => index)\n order.sort((left, right) => {\n for (const [at, key] of keys.entries()) {\n const values = columns[at] as (Comparable | null)[]\n const [a, b] = [values[left] as Comparable | null, values[right] as Comparable | null]\n if (a === null || b === null) {\n if (a !== b) return a === null ? 1 : -1\n continue\n }\n const found = compared(key.type, a, b, collator)\n if (found !== 0) return key.direction === 'asc' ? found : -found\n }\n return left - right\n })\n return order.map((index) => Object.freeze({ index, record: rows[index] as CheckedRecord }))\n}\n\n/** Whether two group keys are one: decimals by value, everything else as held, and null with null. */\nfunction sameKey(type: PrintableType, a: CheckedValue | null, b: CheckedValue | null): boolean {\n if (a === null || b === null) return a === b\n return type === 'decimal' ? compareDecimal(a as Decimal, b as Decimal) === 0 : a === b\n}\n\n/**\n * Rows already in order, as consecutive groups of equal keys: the groups in\n * the order of their rows, each keyed by its first row's value. A missing\n * value groups with null.\n */\nexport function groupRows(rows: readonly OrderedRow[], by: { readonly field: string; readonly type: PrintableType }): RowGroup[] {\n const groups: { key: CheckedValue | null; rows: OrderedRow[] }[] = []\n for (const row of rows) {\n const value = row.record[by.field] ?? null\n const last = groups.at(-1)\n if (last !== undefined && sameKey(by.type, last.key, value)) last.rows.push(row)\n else groups.push({ key: value, rows: [row] })\n }\n return groups.map((group) => Object.freeze({ key: group.key, rows: Object.freeze(group.rows) }))\n}\n\n/**\n * The keys `table` orders its rows by: its group's key first, then its sort\n * keys (0007), each typed by the report's detail contract. Throws a\n * RangeError for a key on a field that has no order -- an image, or one the\n * contract lacks -- which report-spec refuses.\n */\nexport function orderKeys(report: ReportDefinition, table: TableComponent): OrderKey[] {\n const types = new Map((report.datasets.detail?.fields ?? []).map(({ id, type }) => [id, type]))\n const typed = (field: string, direction: SortDirection): OrderKey => {\n const type = types.get(field)\n if (type === undefined || type === 'image') throw new RangeError(`detail field ${field} has no order to sort or group by`)\n return { field, type, direction }\n }\n const group = table.group === undefined ? [] : [typed(table.group.by.field, table.group.direction)]\n return [...group, ...(table.sort ?? []).map(({ field, direction }) => typed(field.field, direction))]\n}\n\n/** `detail` -- the report's checked detail rows -- in `table`'s order, and in its groups when it has one. */\nexport function orderTable(report: ReportDefinition, table: TableComponent, detail: readonly CheckedRecord[]): OrderedTable {\n const keys = orderKeys(report, table)\n const rows = orderRows(detail, keys, report.locale)\n if (table.group === undefined) return { rows }\n return { rows, groups: groupRows(rows, keys[0] as OrderKey) }\n}\n","/**\n * A report's expressions, compiled once and evaluated against checked data,\n * within a budget, each failure an error that says where.\n *\n * - **One compilation.** `@formancy/report-core`'s `compileReport` compiles\n * every expression where it stands, and the editor's diagnostics come\n * from the same function (0009). A report its diagnostics give an error\n * for is refused before anything is evaluated, so the runtime never runs\n * what the editor refuses. Each expression is compiled once per render,\n * never once per row -- twice, in fact, since `diagnose` does not hand\n * back the compilation it made.\n * - **One binding.** Each program's values are made by report-core's\n * `expressionValues`: an integer as a BigInt, a decimal as a `Decimal`,\n * an instant as a moment, a date as its ISO string. A value missing, or of\n * another type, fails the evaluation, naming the member and never quoting\n * the value.\n * - **Nothing differs between renders.** The diagnostics refuse `now()`,\n * `today()` and `random()`; the capabilities an evaluation is handed are\n * fixed besides, so that one reached anyway would answer the same in every\n * render.\n * - **Bounded.** Each evaluation has a budget of steps, and a render has one\n * for all its evaluations together. Past either, the evaluation is refused.\n * - **A failure is an error, never a blank.** It names the component, the\n * table column or the aggregate, and the detail row, and gives upstream's\n * code for what went wrong, never upstream's message, which can quote the\n * values it was computing with.\n *\n * What an expression gives is handed back typed as the runtime holds values:\n * an integer as a BigInt, an instant in UTC. A list or a map, which has no\n * text, is refused. A double never arrives: the diagnostics refuse every\n * double literal, every `double()` and every `/` before anything is\n * evaluated (report-core's `exactness.ts`), since upstream hands an integer\n * and a double back alike, as a JavaScript number, and `int()` of a double\n * would otherwise print as an exact integer. A number that is not a safe\n * integer is still refused here, rather than printed.\n */\nimport { DEFAULT_BUDGET, Decimal, evaluate, fixedCapabilities } from '@formancy/expressions'\nimport type { Capabilities, ExpressionValue } from '@formancy/expressions'\nimport { compileReport, diagnose, expressionValues } from '@formancy/report-core'\nimport type { CompiledExpression, Diagnostic, ExpressionValues, ReportCompilation } from '@formancy/report-core'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport type { TypedValue } from './format.js'\nimport { canonicalInstant } from './values.js'\n\n/**\n * Steps one evaluation may take: upstream's default for a formancy form's\n * expression (`DEFAULT_BUDGET`). A report expression reads single values, so\n * the only way to spend many steps is a comprehension over a list literal;\n * the deepest the structural limits allow, 64 by 64, measured 8,385 steps,\n * and `evaluate.test.ts` holds that it fits while one reading three values\n * in each turn (28,865 steps) does not.\n */\nexport const EXPRESSION_STEP_BUDGET = DEFAULT_BUDGET.maxSteps\n\n/**\n * Steps every evaluation of one render may take together, each charged its\n * steps and one more for itself. Measured as a render spends them, through\n * `condition()` with each evaluation's binding included, on 15 October\n * 2026, on an Intel i9-10900K under Node 24.21 with `@formancy/expressions`\n * 0.5.0: ten million steps of `row.urgent` took 10.0 seconds (1.00\n * microseconds a step) and of `row.amount * dec(\"1.081\") > dec(\"10\")` 13.0\n * (1.30). An earlier measurement, of upstream's `evaluate` alone, had put\n * that budget at 8.5 seconds and missed the binding. So the budget is five\n * million: about 5 to 6.5 seconds of evaluation on that machine, against\n * the plan's investigation target of ten seconds in all for a hundred-page\n * report. A report of `MAX_DETAIL_ROWS` rows evaluating ten one-read\n * expressions per row spends 2,000,000.\n */\nexport const RENDER_STEP_BUDGET = 5_000_000\n\n/**\n * What `now()`, `today()` and `random()` would give: nothing a report may\n * read (0009), fixed so that one reached anyway gives the same answer in\n * every render.\n */\nexport const CAPABILITIES: Capabilities = fixedCapabilities({ nowMs: 0, today: '1970-01-01', random: 0 })\n\nexport const EVALUATION_ERROR_CODES = [\n /** A path at which the report has no compiled expression: the caller's defect. */\n 'unknown-expression',\n /** A member the expression reads has no value: a field a preview's data lacks, or a total not yet computed. */\n 'missing-value',\n /** A value of another type than its member's, which the data check admits none of. */\n 'unbound-value',\n /** Upstream refused the evaluation: a division by zero, an overflow, a result too large to hand back. */\n 'expression-failed',\n /** The evaluation took more than `EXPRESSION_STEP_BUDGET` steps. */\n 'expression-budget',\n /** The render has spent `RENDER_STEP_BUDGET` steps. */\n 'render-budget',\n /** A number that is not a safe integer: a double, which the diagnostics refuse before anything is evaluated. */\n 'inexact-value',\n /** A list, a map or anything else without text. */\n 'unprintable-value',\n /** A condition that gave something other than a boolean. */\n 'not-a-condition',\n] as const\nexport type EvaluationErrorCode = (typeof EVALUATION_ERROR_CODES)[number]\n\n/** Why an evaluation gave no value, and where. */\nexport interface EvaluationError {\n readonly code: EvaluationErrorCode\n /** For a person: where and what, never a value. */\n readonly message: string\n /** The JSON Pointer to the expression's `cel` in the report. */\n readonly path: string\n readonly componentId?: string\n readonly columnId?: string\n /** The aggregate whose expression this is, for one read from each row. */\n readonly aggregateId?: string\n /** The detail row's index in the data, when the expression read one. */\n readonly row?: number\n}\n\nexport type Evaluation = { readonly ok: true; readonly value: TypedValue | null } | { readonly ok: false; readonly error: EvaluationError }\n\nexport type ConditionEvaluation = { readonly ok: true; readonly value: boolean } | { readonly ok: false; readonly error: EvaluationError }\n\nexport interface ReportExpressions {\n /** What compiled: the programs by path, the members, and the order aggregates are computed in. */\n readonly compilation: ReportCompilation\n /** Steps this render has spent, each evaluation charged its steps and one more. */\n readonly spent: number\n /** The expression at `path` evaluated over `values`; `row` is the detail row's index, for an error to name. */\n evaluate(path: string, values: ExpressionValues, row?: number): Evaluation\n /** The condition at `path` -- a `visibleWhen` or a style rule's `when` -- evaluated over `values`. */\n condition(path: string, values: ExpressionValues, row?: number): ConditionEvaluation\n}\n\nexport type ExpressionsPreparation = { readonly ok: true; readonly expressions: ReportExpressions } | { readonly ok: false; readonly diagnostics: readonly Diagnostic[] }\n\n/** The typed value an expression's result is, or why it is not one. Exported for its test alone. */\nexport function typed(result: ExpressionValue, resultType: string): TypedValue | null | { readonly code: EvaluationErrorCode; readonly what: string } {\n if (result === null) return null\n if (result instanceof Decimal) return { type: 'decimal', value: result }\n switch (typeof result) {\n case 'boolean':\n return { type: 'boolean', value: result }\n case 'string': {\n const instant = resultType === 'timestamp' ? canonicalInstant(result) : undefined\n return instant === undefined ? { type: 'string', value: result } : { type: 'instant', value: instant }\n }\n case 'number':\n // Upstream hands an integer back as a number, and refuses one it cannot hold exactly.\n if (Number.isSafeInteger(result)) return { type: 'integer', value: BigInt(result) }\n return { code: 'inexact-value', what: 'the expression gives a double, which is not exact; dec() keeps a number exact' }\n default:\n return { code: 'unprintable-value', what: 'the expression gives a list or a map, which has no text' }\n }\n}\n\n/** One render's evaluations of a report's expressions. */\nclass Evaluator implements ReportExpressions {\n readonly compilation: ReportCompilation\n readonly #aggregates: readonly string[]\n #spent = 0\n\n constructor(report: ReportDefinition, compilation: ReportCompilation) {\n this.compilation = compilation\n this.#aggregates = report.aggregates.map(({ id }) => id)\n }\n\n get spent(): number {\n return this.#spent\n }\n\n evaluate(path: string, values: ExpressionValues, row?: number): Evaluation {\n const compiled = this.compilation.expressions.get(path)\n if (compiled === undefined) return { ok: false, error: { code: 'unknown-expression', message: `the report has no expression at ${path}`, path } }\n const fail = (code: EvaluationErrorCode, what: string): Evaluation => ({ ok: false, error: this.#error(compiled, code, what, row) })\n for (const read of compiled.reads) {\n const scope = values[read.name]\n if (scope === undefined || !Object.hasOwn(scope, read.member)) return fail('missing-value', `${read.name}.${read.member} has no value: it is missing, which is not null`)\n }\n let bound: Record<string, unknown>\n try {\n bound = expressionValues(compiled, values)\n } catch (error) {\n // report-core's refusal names the member and its type, and never quotes the value.\n return fail('unbound-value', (error as TypeError).message)\n }\n if (this.#spent >= RENDER_STEP_BUDGET) return fail('render-budget', `the render has spent its budget of ${RENDER_STEP_BUDGET} steps`)\n const maxSteps = Math.min(EXPRESSION_STEP_BUDGET, RENDER_STEP_BUDGET - this.#spent - 1)\n const outcome = evaluate(compiled.program, bound, { capabilities: CAPABILITIES, budget: { maxSteps } })\n if (!outcome.ok) {\n const exhausted = outcome.error.kind === 'budget'\n this.#spent += (exhausted ? maxSteps : 0) + 1\n if (!exhausted) return fail('expression-failed', `the expression failed (${outcome.error.code})`)\n if (maxSteps < EXPRESSION_STEP_BUDGET) return fail('render-budget', `the render has spent its budget of ${RENDER_STEP_BUDGET} steps`)\n return fail('expression-budget', `the expression took more than its budget of ${EXPRESSION_STEP_BUDGET} steps`)\n }\n this.#spent += outcome.steps + 1\n const value = typed(outcome.value, compiled.program.resultType)\n return value !== null && 'code' in value ? fail(value.code, value.what) : { ok: true, value }\n }\n\n condition(path: string, values: ExpressionValues, row?: number): ConditionEvaluation {\n const outcome = this.evaluate(path, values, row)\n if (!outcome.ok) return outcome\n if (outcome.value?.type === 'boolean') return { ok: true, value: outcome.value.value }\n const compiled = this.compilation.expressions.get(path) as CompiledExpression\n return { ok: false, error: this.#error(compiled, 'not-a-condition', 'a condition gives true or false, and this expression gives something else', row) }\n }\n\n /** An error about `compiled`, naming where it stands and the row it read. */\n #error(compiled: CompiledExpression, code: EvaluationErrorCode, what: string, row: number | undefined): EvaluationError {\n const { site } = compiled\n const aggregateId = site.path.startsWith('/aggregates/') ? this.#aggregates[Number(site.path.split('/')[2])] : undefined\n const place = [\n // The payment part and the e-invoice stand in no component, and are named as one would be.\n site.path.startsWith('/paymentPart/') ? 'the payment part' : site.path.startsWith('/eInvoice/') ? 'the e-invoice' : undefined,\n site.componentId === undefined ? undefined : `component ${site.componentId}`,\n site.columnId === undefined ? undefined : `column ${site.columnId}`,\n aggregateId === undefined ? undefined : `aggregate ${aggregateId}`,\n row === undefined ? undefined : `detail row ${row}`,\n ].filter((part) => part !== undefined)\n return {\n code,\n message: `${place.join(', ')}: ${what}`,\n path: site.path,\n ...(site.componentId === undefined ? {} : { componentId: site.componentId }),\n ...(site.columnId === undefined ? {} : { columnId: site.columnId }),\n ...(aggregateId === undefined ? {} : { aggregateId }),\n ...(row === undefined ? {} : { row }),\n }\n }\n}\n\n/**\n * `report`'s expressions compiled for one render, or the diagnostics that\n * refuse it: every error `diagnose` gives, which the editor shows too.\n * `report` is one the validator accepts. The evaluations of one render\n * share one budget, so a render prepares its own.\n */\nexport function prepareExpressions(report: ReportDefinition): ExpressionsPreparation {\n const errors = diagnose(report).filter(({ severity }) => severity === 'error')\n if (errors.length > 0) return { ok: false, diagnostics: errors }\n return { ok: true, expressions: new Evaluator(report, compileReport(report)) }\n}\n","/**\n * XML, written one way: a tree of elements serialised with the same bytes\n * for the same tree, every text escaped so that a parser gives back exactly\n * what was written. The e-invoice's CII is built as such a tree\n * (`cii.ts`), and this is the one place it becomes text.\n *\n * Exactly, to a parser: a reader that applies the schema reads an element\n * the XSD types as xs:token -- an identifier, a code -- with its white\n * space collapsed. report-spec's rules refuse such a text that holds any\n * (`token` in `en16931.ts`), so what such a reader reads is what was\n * written too.\n *\n * - **Deterministic.** `<?xml version=\"1.0\" encoding=\"UTF-8\"?>`, no byte\n * order mark, a line feed after every line, two spaces a level, an empty\n * element closed at once, attributes in the order given. Nothing reads a\n * clock or the machine.\n * - **Escaped.** In text `&`, `<` and `>`, and a carriage return as\n * `&#13;`, which a parser would otherwise read as a line feed (XML 1.0,\n * 2.11). In an attribute the double quote too, and a tab, a line feed and\n * a carriage return as references, which a parser would otherwise read\n * as spaces (3.3.3).\n * - **Never a character XML 1.0 cannot hold.** report-spec's\n * `xmlCharacterBreak` decides which: the e-invoice's rules refuse a text\n * that holds one where it is read, naming its term. One that reaches the\n * writer anyway is a defect, thrown as a RangeError, never dropped, since\n * dropping it would change what the invoice says.\n */\nimport { xmlCharacterBreak } from '@formancy/report-spec'\n\n/** An attribute: its qualified name and its value. */\nexport type XmlAttribute = readonly [name: string, value: string]\n\n/** An element: its qualified name, its attributes, and either its text or the elements it holds. */\nexport interface XmlElement {\n readonly name: string\n readonly attributes: readonly XmlAttribute[]\n readonly content: string | readonly XmlElement[]\n}\n\n/** An element holding `children`, in order; an undefined child is a term the document leaves out. */\nexport function element(name: string, children: readonly (XmlElement | undefined)[], attributes: readonly XmlAttribute[] = []): XmlElement {\n return { name, attributes, content: children.filter((child): child is XmlElement => child !== undefined) }\n}\n\n/** An element holding the text `text`. */\nexport function leaf(name: string, text: string, attributes: readonly XmlAttribute[] = []): XmlElement {\n return { name, attributes, content: text }\n}\n\n/** `text` with no character XML 1.0 cannot write; a RangeError when it holds one, which the rules refuse before. */\nfunction writable(text: string): string {\n const broken = xmlCharacterBreak(text)\n if (broken !== undefined) throw new RangeError(`a text ${broken}; the e-invoice's rules refuse it where it is read`)\n return text\n}\n\nconst TEXT = /[&<>\\r]/g\nconst ATTRIBUTE = /[&<>\"\\t\\n\\r]/g\nconst REFERENCES: { readonly [character: string]: string } = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;', '\\t': '&#9;', '\\n': '&#10;', '\\r': '&#13;' }\n\nconst escaped = (pattern: RegExp) => (text: string): string => writable(text).replace(pattern, (character) => REFERENCES[character] as string)\nconst text = escaped(TEXT)\nconst attribute = escaped(ATTRIBUTE)\n\n/** `node` written into `lines`, at `depth` levels. */\nfunction write(node: XmlElement, depth: number, lines: string[]): void {\n const indent = ' '.repeat(depth)\n const open = `${indent}<${node.name}${node.attributes.map(([name, value]) => ` ${name}=\"${attribute(value)}\"`).join('')}`\n if (typeof node.content === 'string') {\n lines.push(`${open}>${text(node.content)}</${node.name}>`)\n return\n }\n if (node.content.length === 0) {\n lines.push(`${open}/>`)\n return\n }\n lines.push(`${open}>`)\n for (const child of node.content) write(child, depth + 1, lines)\n lines.push(`${indent}</${node.name}>`)\n}\n\n/** The document whose root is `root`, as UTF-8 XML text: its declaration first, a line feed after every line. */\nexport function xmlDocument(root: XmlElement): string {\n const lines = ['<?xml version=\"1.0\" encoding=\"UTF-8\"?>']\n write(root, 0, lines)\n return `${lines.join('\\n')}\\n`\n}\n","/**\n * The parties of a CII invoice and how it is paid: the seller (BG-4) and\n * the buyer (BG-7) with their addresses (BG-5, BG-8), and the payment\n * instructions (BG-16), each in the order the Factur-X EN 16931 XSD's\n * `xs:sequence` gives its elements and at the path CEN/TC 434's CII binding\n * gives each business term. `cii.ts` places them in the document.\n *\n * A trade party is `Name`, `SpecifiedLegalOrganization`,\n * `PostalTradeAddress` and `SpecifiedTaxRegistration`, in that order, the\n * VAT identifier under scheme `VA` and the seller's tax number under `FC`;\n * an address is `PostcodeCode`, `LineOne`, `LineTwo`, `CityName`,\n * `CountryID`. Only elements D16B shares with D22B are written, since the\n * validators run the D16B schema.\n */\nimport type { AddressTerms, PartyTerms, PaymentTerms } from './e-invoice-terms.js'\nimport { element, leaf } from './xml.js'\nimport type { XmlElement } from './xml.js'\n\n/** `make` of `value` where there is one; nothing where the term is left out. */\nexport function optional(value: string | undefined, make: (value: string) => XmlElement): XmlElement | undefined {\n return value === undefined ? undefined : make(value)\n}\n\n/** BG-5 or BG-8: the post code, the lines, the city and the country (BT-38, 35, 36, 37, 40; BT-53, 50, 51, 52, 55). */\nfunction postalAddress(address: AddressTerms): XmlElement {\n return element('ram:PostalTradeAddress', [\n leaf('ram:PostcodeCode', address.postalCode),\n leaf('ram:LineOne', address.line1),\n optional(address.line2, (line) => leaf('ram:LineTwo', line)),\n leaf('ram:CityName', address.city),\n leaf('ram:CountryID', address.country),\n ])\n}\n\n/**\n * The seller or the buyer: its name (BT-27, BT-44), its legal registration\n * and its scheme (BT-30, BT-47), its address, its VAT identifier (BT-31,\n * BT-48) and, the seller's, its tax number (BT-32).\n */\nexport function tradeParty(name: 'ram:SellerTradeParty' | 'ram:BuyerTradeParty', party: PartyTerms): XmlElement {\n const registration = party.legalId\n return element(name, [\n leaf('ram:Name', party.name),\n registration === undefined ? undefined : element('ram:SpecifiedLegalOrganization', [leaf('ram:ID', registration.id, registration.scheme === undefined ? [] : [['schemeID', registration.scheme]])]),\n postalAddress(party.address),\n optional(party.vatId, (id) => element('ram:SpecifiedTaxRegistration', [leaf('ram:ID', id, [['schemeID', 'VA']])])),\n optional(party.taxNumber, (id) => element('ram:SpecifiedTaxRegistration', [leaf('ram:ID', id, [['schemeID', 'FC']])])),\n ])\n}\n\n/**\n * BG-16: the means (BT-81), the account by its IBAN (BT-84) and its name\n * (BT-85), and the BIC of its bank (BT-86). The remittance information\n * (BT-83) is the settlement's `PaymentReference`, which `cii.ts` writes.\n */\nexport function paymentMeans(payment: PaymentTerms): XmlElement {\n return element('ram:SpecifiedTradeSettlementPaymentMeans', [\n leaf('ram:TypeCode', payment.means),\n element('ram:PayeePartyCreditorFinancialAccount', [leaf('ram:IBANID', payment.account), optional(payment.accountName, (name) => leaf('ram:AccountName', name))]),\n optional(payment.bic, (bic) => element('ram:PayeeSpecifiedCreditorFinancialInstitution', [leaf('ram:BICID', bic)])),\n ])\n}\n","/**\n * An e-invoice written as UN/CEFACT Cross Industry Invoice XML in the\n * Factur-X 1.09.2 / ZUGFeRD 2.5.2 EN 16931 profile (0027): the runtime's,\n * as the QR-bill's payload is, since the XML is the invoice's payload and\n * the renderer decides none of it.\n *\n * - **Its shape.** The root `rsm:CrossIndustryInvoice` with the four\n * namespaces of CEN/TC 434's binding; its context (BT-24), its document\n * (BT-1, BT-3, BT-2) and its transaction: the lines, then the\n * agreement, the delivery and the settlement, each element in the order\n * the profile's XSD `xs:sequence` gives it, at the path CEN's binding\n * gives each business term. Only elements D16B shares with D22B are\n * written, since the validators run the D16B schema.\n * - **Dates** are `udt:DateTimeString` of format 102, YYYYMMDD.\n * - **The delivery**, which the XSD needs once, is written empty where the\n * invoice gives an invoicing period and no delivery date: it has nothing\n * else to hold. Mustang 2.26.0's Factur-X schematron warns of that empty\n * element (PEPPOL-EN16931-R008, \"still status warning\"), and KoSIT's\n * EN 16931 scenario does not, measured by hand on 17 October 2026.\n * - **Amounts** are written from their own digits with exactly two places;\n * only `TaxTotalAmount` names its currency (CII-DT-031). A quantity and\n * a net price, which CEN does not hold to two places, are written as the\n * template's columns resolved them; a rate by value, `19`, `7`, `0`.\n * - **Its order** is the template's and the table's: categories as\n * declared, lines as the table prints them. The same invoice is the same\n * bytes (`xml.ts`).\n *\n * Every value is one the rules have already held (`e-invoice-lines.ts`,\n * `e-invoice-terms.ts`) and every total one `e-invoice-totals.ts`\n * computed: nothing here decides, rounds or checks.\n */\nimport { decimalToString } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport { FACTUR_X_PROFILES } from '@formancy/report-spec'\nimport type { EInvoiceCurrency, EInvoiceProfile, InvoiceTypeCode } from '@formancy/report-spec'\nimport { optional, paymentMeans, tradeParty } from './cii-parties.js'\nimport type { LineTerms } from './e-invoice-lines.js'\nimport type { InvoiceTerms } from './e-invoice-terms.js'\nimport type { InvoiceTotals, VatBreakdown } from './e-invoice-totals.js'\nimport { element, leaf, xmlDocument } from './xml.js'\nimport type { XmlAttribute, XmlElement } from './xml.js'\n\n/** What the XML is written from: the profile, the type and the currency, every term, the lines in the table's order, and the totals. */\nexport interface CiiInvoice {\n readonly profile: EInvoiceProfile\n readonly type: InvoiceTypeCode\n readonly currency: EInvoiceCurrency\n readonly terms: InvoiceTerms\n readonly lines: readonly LineTerms[]\n readonly totals: InvoiceTotals\n}\n\n/** CEN/TC 434's CII namespaces, as its schematron declares them. */\nconst NAMESPACES: readonly XmlAttribute[] = [\n ['xmlns:rsm', 'urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100'],\n ['xmlns:qdt', 'urn:un:unece:uncefact:data:standard:QualifiedDataType:100'],\n ['xmlns:ram', 'urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100'],\n ['xmlns:udt', 'urn:un:unece:uncefact:data:standard:UnqualifiedDataType:100'],\n]\n\n/** A date, YYYY-MM-DD as the runtime holds one, as CII writes it: format 102, YYYYMMDD. */\nfunction dateTime(name: string, date: string): XmlElement {\n return element(name, [leaf('udt:DateTimeString', date.replaceAll('-', ''), [['format', '102']])])\n}\n\n/** An amount, from its own digits; a RangeError for one not at the two places every total and line amount is computed at. */\nfunction amount(name: string, value: Decimal, attributes: readonly XmlAttribute[] = []): XmlElement {\n if (value.scale !== 2) throw new RangeError(`${name} is at ${value.scale} places, and an e-invoice's amounts are computed at two`)\n return leaf(name, decimalToString(value), attributes)\n}\n\n/** A tax (BT-118, BT-119; at a line BT-151, BT-152): `VAT`, its category and its rate, and its reason, basis and amount where a breakdown has them. */\nfunction tradeTax(breakdown: VatBreakdown, totals?: { readonly reason: string | undefined }): XmlElement {\n return element('ram:ApplicableTradeTax', [\n totals === undefined ? undefined : amount('ram:CalculatedAmount', breakdown.amount),\n leaf('ram:TypeCode', 'VAT'),\n optional(totals?.reason, (reason) => leaf('ram:ExemptionReason', reason)),\n totals === undefined ? undefined : amount('ram:BasisAmount', breakdown.basis),\n leaf('ram:CategoryCode', breakdown.category.code),\n leaf('ram:RateApplicablePercent', breakdown.rate),\n ])\n}\n\n/** A line (BG-25): its identifier (BT-126), its item (BT-153), its net price (BT-146), its quantity and unit (BT-129, BT-130), its tax and its net amount (BT-131). */\nfunction line(each: LineTerms, breakdown: VatBreakdown): XmlElement {\n return element('ram:IncludedSupplyChainTradeLineItem', [\n element('ram:AssociatedDocumentLineDocument', [leaf('ram:LineID', each.id)]),\n element('ram:SpecifiedTradeProduct', [leaf('ram:Name', each.name)]),\n element('ram:SpecifiedLineTradeAgreement', [element('ram:NetPriceProductTradePrice', [leaf('ram:ChargeAmount', each.netPrice)])]),\n element('ram:SpecifiedLineTradeDelivery', [leaf('ram:BilledQuantity', each.quantity, [['unitCode', each.unit]])]),\n element('ram:SpecifiedLineTradeSettlement', [tradeTax(breakdown), element('ram:SpecifiedTradeSettlementLineMonetarySummation', [amount('ram:LineTotalAmount', each.netAmount)])]),\n ])\n}\n\n/** The settlement: the remittance (BT-83), the currency (BT-5), the payment, the breakdown, the period (BG-14), the terms (BT-20, BT-9) and the totals (BG-22). */\nfunction settlement(invoice: CiiInvoice): XmlElement {\n const { terms, totals, currency } = invoice\n const period = terms.period\n return element('ram:ApplicableHeaderTradeSettlement', [\n optional(terms.payment?.remittance, (remittance) => leaf('ram:PaymentReference', remittance)),\n leaf('ram:InvoiceCurrencyCode', currency),\n terms.payment === undefined ? undefined : paymentMeans(terms.payment),\n ...totals.breakdown.map((breakdown) => tradeTax(breakdown, { reason: terms.reasons.get(breakdown.category.id) })),\n period === undefined ? undefined : element('ram:BillingSpecifiedPeriod', [optional(period.start, (start) => dateTime('ram:StartDateTime', start)), optional(period.end, (end) => dateTime('ram:EndDateTime', end))]),\n terms.terms === undefined && terms.due === undefined\n ? undefined\n : element('ram:SpecifiedTradePaymentTerms', [optional(terms.terms, (text) => leaf('ram:Description', text)), optional(terms.due, (due) => dateTime('ram:DueDateDateTime', due))]),\n element('ram:SpecifiedTradeSettlementHeaderMonetarySummation', [\n amount('ram:LineTotalAmount', totals.lineTotal),\n amount('ram:TaxBasisTotalAmount', totals.taxBasisTotal),\n amount('ram:TaxTotalAmount', totals.taxTotal, [['currencyID', currency]]),\n amount('ram:GrandTotalAmount', totals.grandTotal),\n totals.paid === null ? undefined : amount('ram:TotalPrepaidAmount', totals.paid),\n amount('ram:DuePayableAmount', totals.duePayable),\n ]),\n ])\n}\n\n/** `invoice` as CII XML, UTF-8 text with its declaration, the same bytes for the same invoice. */\nexport function ciiXml(invoice: CiiInvoice): string {\n const { terms, totals } = invoice\n const breakdowns = new Map(totals.breakdown.map((breakdown) => [breakdown.category.id, breakdown]))\n const root = element(\n 'rsm:CrossIndustryInvoice',\n [\n element('rsm:ExchangedDocumentContext', [element('ram:GuidelineSpecifiedDocumentContextParameter', [leaf('ram:ID', FACTUR_X_PROFILES[invoice.profile].guideline)])]),\n element('rsm:ExchangedDocument', [leaf('ram:ID', terms.number), leaf('ram:TypeCode', invoice.type), dateTime('ram:IssueDateTime', terms.issued)]),\n element('rsm:SupplyChainTradeTransaction', [\n // Every line's category has a breakdown: the totals are computed from these lines.\n ...invoice.lines.map((each) => line(each, breakdowns.get(each.category.id) as VatBreakdown)),\n element('ram:ApplicableHeaderTradeAgreement', [optional(terms.buyerReference, (reference) => leaf('ram:BuyerReference', reference)), tradeParty('ram:SellerTradeParty', terms.seller), tradeParty('ram:BuyerTradeParty', terms.buyer)]),\n element('ram:ApplicableHeaderTradeDelivery', [optional(terms.delivered, (delivered) => element('ram:ActualDeliverySupplyChainEvent', [dateTime('ram:OccurrenceDateTime', delivered)]))]),\n settlement(invoice),\n ]),\n ],\n NAMESPACES,\n )\n return xmlDocument(root)\n}\n","/**\n * An e-invoice's totals and VAT breakdown, computed once, here, from its\n * lines (0027): the page prints them through `invoice`, `vatBasis` and\n * `vatAmount`, and the XML is written from the very same values, so the\n * two cannot part. The rules are CEN/TC 434's CII artefacts 1.3.17's, by\n * number.\n *\n * | Value | Computed as | Rule |\n * |---|---|---|\n * | BT-131 | BT-129 × BT-146, rounded once to two places: held, not written from it | EN 16931's definition; PEPPOL-EN16931-R120 |\n * | BT-106 | Σ BT-131, each a whole number of cents | BR-CO-10 |\n * | BT-109 | BT-106: there are no allowances or charges | BR-CO-13 |\n * | BT-116 | Σ BT-131 of the category's lines | BR-S-08, BR-E-08, BR-AE-08 |\n * | BT-117 | BT-116 × BT-119 / 100, rounded once to two places, half away from zero | BR-CO-17, BR-E-09, BR-AE-09 |\n * | BT-110 | Σ BT-117 | BR-CO-14 |\n * | BT-112 | BT-109 + BT-110 | BR-CO-15 |\n * | BT-115 | BT-112 − BT-113; there is no BT-114 | BR-CO-16 |\n *\n * - **Exact.** In `@formancy/expressions`' `Decimal`, a value as an integer\n * of units at a scale; nothing passes through a JavaScript number.\n * Dividing by 100 moves the point and loses nothing, so a category's tax\n * is the exact product rounded once. CEN tests BR-CO-17 and BR-S-09\n * within one unit of the currency either way, a euro, and the exact\n * product rounded once lies inside.\n * - **Per category, once.** VAT is rounded per category, never per line:\n * an ERP that rounds each line can differ by up to half a cent a line,\n * which is said where the costs are.\n * - **Half away from zero**, as upstream's `roundDecimal` rounds and as a\n * person rounds by hand. CEN's tests round the absolute value, where half\n * away from zero and XPath's `round` agree.\n * - **A breakdown for each category a line is in**, in the order the\n * invoice declares them: BR-E-01 and BR-AE-01 refuse one for a category\n * no line has, and one invoice is one XML.\n */\nimport { addDecimal, Decimal, decimalFromString, multiplyDecimal, roundDecimal, subtractDecimal } from '@formancy/expressions'\nimport type { ExpressionValues } from '@formancy/report-core'\nimport { checkVatRate } from '@formancy/report-spec'\nimport type { FacturXInvoice, VatCategory } from '@formancy/report-spec'\n\n/** A line as its totals read it: its net amount (BT-131) at exactly two places, and the category it is in (BT-151). */\nexport interface TotalledLine {\n readonly netAmount: Decimal\n readonly category: VatCategory\n}\n\n/** One VAT breakdown (BG-23): a category a line is in, its rate as the XML writes it, its taxable amount and its tax. */\nexport interface VatBreakdown {\n readonly category: VatCategory\n /** BT-119 by value, as report-spec's `checkVatRate` gives it: `19`, `7`, `0`. */\n readonly rate: string\n /** BT-116. */\n readonly basis: Decimal\n /** BT-117. */\n readonly amount: Decimal\n}\n\n/** The document's totals (BG-22) and its VAT breakdown (BG-23), every amount at exactly two places. */\nexport interface InvoiceTotals {\n /** BT-106. */\n readonly lineTotal: Decimal\n /** BT-109. */\n readonly taxBasisTotal: Decimal\n /** BT-110. */\n readonly taxTotal: Decimal\n /** BT-112. */\n readonly grandTotal: Decimal\n /** BT-113, or null where none was paid. */\n readonly paid: Decimal | null\n /** BT-115. */\n readonly duePayable: Decimal\n /** Each category a line is in, in the order the invoice declares them. */\n readonly breakdown: readonly VatBreakdown[]\n}\n\nconst ZERO = new Decimal(0n, 2)\n\n/** `amount`, which a defect of the caller's would have written at another scale than the two places the XML writes. */\nfunction cents(amount: Decimal, what: string): Decimal {\n if (amount.scale !== 2) throw new RangeError(`${what} is at ${amount.scale} places, and the e-invoice's lines are read at two`)\n return amount\n}\n\nconst sum = (amounts: Iterable<Decimal>): Decimal => {\n let total = ZERO\n for (const amount of amounts) total = addDecimal(total, amount)\n return total\n}\n\n/**\n * A line's net amount (BT-131) as EN 16931 makes it, which the lines'\n * reader holds each line's to: its quantity (BT-129) times its net price\n * (BT-146), each as the XML writes it, rounded once to two places, half\n * away from zero, as BT-117 is. This version writes no line allowance or\n * charge and no base quantity (BT-149), which would enter it.\n */\nexport function lineNetAmount(quantity: string, netPrice: string): Decimal {\n return roundDecimal(multiplyDecimal(decimalFromString(quantity), decimalFromString(netPrice)), 2)\n}\n\n/** BT-117 of a category of `rate` over `basis`: the exact product over 100, rounded once to two places, half away from zero. */\nfunction tax(basis: Decimal, rate: string): Decimal {\n const product = multiplyDecimal(basis, decimalFromString(rate))\n return roundDecimal(new Decimal(product.units, product.scale + 2), 2)\n}\n\n/**\n * The totals of `lines`, each in one of `categories`, as declared; `paid`\n * the amount already paid (BT-113), or null. Every amount it is handed is\n * at exactly two places, as the lines' reader writes it, and a RangeError\n * says a caller handed one that is not.\n */\nexport function invoiceTotals(categories: readonly VatCategory[], lines: readonly TotalledLine[], paid: Decimal | null): InvoiceTotals {\n const amounts = lines.map((line, index) => cents(line.netAmount, `line ${index}'s net amount`))\n const breakdown = categories.flatMap((category): VatBreakdown[] => {\n const own = lines.flatMap((line, index) => (line.category === category ? [amounts[index] as Decimal] : []))\n if (own.length === 0) return []\n const basis = sum(own)\n // report-spec's validator took the rate by this very check, so it takes it again.\n const rate = (checkVatRate(category.code, category.rate) as { readonly value: string }).value\n return [{ category, rate, basis, amount: tax(basis, category.rate) }]\n })\n const lineTotal = sum(amounts)\n const taxTotal = sum(breakdown.map(({ amount }) => amount))\n const grandTotal = addDecimal(lineTotal, taxTotal)\n const prepaid = paid === null ? null : cents(paid, 'the paid amount')\n return {\n lineTotal,\n taxBasisTotal: lineTotal,\n taxTotal,\n grandTotal,\n paid: prepaid,\n duePayable: prepaid === null ? grandTotal : subtractDecimal(grandTotal, prepaid),\n breakdown,\n }\n}\n\n/**\n * What the e-invoice's names hold, as an expression is handed them (0027,\n * beside 0009): `invoice` each document total, `paid` only where the\n * invoice declares a paid amount, as report-core binds it; `vatBasis` and\n * `vatAmount` each declared category's basis and tax by its id, null where\n * no line is in it, which prints as nothing (0007). The very values the\n * XML is written from.\n */\nexport function invoiceNames(invoice: Pick<FacturXInvoice, 'vat' | 'paid'>, totals: InvoiceTotals): ExpressionValues {\n const of = (category: VatCategory): VatBreakdown | undefined => totals.breakdown.find((each) => each.category.id === category.id)\n return {\n invoice: {\n lineTotal: totals.lineTotal,\n taxBasisTotal: totals.taxBasisTotal,\n taxTotal: totals.taxTotal,\n grandTotal: totals.grandTotal,\n ...(invoice.paid === undefined ? {} : { paid: totals.paid }),\n duePayable: totals.duePayable,\n },\n vatBasis: Object.fromEntries(invoice.vat.map((category) => [category.id, of(category)?.basis ?? null])),\n vatAmount: Object.fromEntries(invoice.vat.map((category) => [category.id, of(category)?.amount ?? null])),\n }\n}\n","/**\n * Why a report did not resolve, as one list a caller reads whatever stage\n * found the problem: the report itself, its expressions, the parameters, the\n * data, the options, an evaluation, a format, an image or a total.\n *\n * Each stage keeps the codes it already has -- report-spec's for structure,\n * report-core's diagnostics for expressions, the data check's for data and\n * parameters, the evaluator's and the formatter's -- so a code means one\n * thing wherever it appears. `stage` says which list a code is from. Like\n * every error the runtime gives, none holds a value from the data.\n */\nimport type { Diagnostic, DiagnosticCode } from '@formancy/report-core'\nimport type { ReportError, ReportErrorCode } from '@formancy/report-spec'\nimport type { DataError, DataErrorCode } from './data-errors.js'\nimport { MAX_DATA_ERRORS } from './data-errors.js'\nimport type { EvaluationError, EvaluationErrorCode } from './evaluate.js'\nimport type { FormatErrorCode } from './format.js'\n\n/** What lowering a report can find wrong besides what each earlier stage finds. */\nexport const RESOLVE_ERROR_CODES = [\n /** A creation date that is not an ISO 8601 instant with its zone. */\n 'invalid-creation-date',\n /** An image whose bytes the host does not have, or a report with images and no way to fetch them. */\n 'missing-asset',\n /** Bytes for an image that are not a `Uint8Array`, or of another media type than the asset declares or a report may draw. */\n 'invalid-asset',\n /** The host's image lookup threw. */\n 'asset-lookup-failed',\n /** A declared rounding on a total that is not a decimal: an integer, a date or an instant has no places to round. */\n 'rounding-not-decimal',\n /** A total over values that cannot be totalled together: a sum of text, a minimum of a number and a date. */\n 'aggregate-value-type',\n /** In a final render, a run of a QR code's content, or of a QR-bill's or an EPC QR code's text, whose value is null: the code would scan as less than its content, and nothing on the page would say so. */\n 'no-qr-value',\n /** In a final render, a QR code whose content prints nothing: a symbol of no data, which a scanner reads as no code. */\n 'empty-qr-code',\n /**\n * A QR-bill a rule of SIX's breaks once its data has resolved it: an\n * account, a reference, an address part, a message or an amount. The\n * code report-spec gives a literal that breaks it, from the same rules.\n */\n 'invalid-qr-bill',\n /**\n * An EPC QR code a rule of the EPC's breaks once its data has resolved\n * it: an IBAN, a BIC, a name, a reference, a text, an amount, or a\n * payload past its bytes. The code report-spec gives a literal that\n * breaks it, from the same rules.\n */\n 'invalid-epc-qr-code',\n /**\n * An e-invoice a rule of EN 16931's breaks once its data has resolved it\n * -- a text, a date, a line's term, a row with none -- or a payment code\n * that asks for another amount or account than it names. The code\n * report-spec gives a literal that breaks it, from the same rules.\n */\n 'invalid-e-invoice',\n /** A warning, never an error: a preview of an e-invoice, which writes no XML and is not the invoice. */\n 'e-invoice-preview',\n /** More errors were found than are listed. */\n 'too-many-errors',\n] as const\nexport type ResolveErrorCode = (typeof RESOLVE_ERROR_CODES)[number]\n\n/** Where in the report an error is, when it is in a component, a table column or a row. */\ninterface Place {\n readonly componentId?: string\n readonly columnId?: string\n /** The detail row's index in the data as the provider gave it. */\n readonly row?: number\n}\n\n/** One error, from the stage that found it, with that stage's code. Its path is a JSON Pointer into what the stage read: the report, the data, the parameters, or '' for the options. */\nexport type RuntimeError =\n | ({ readonly stage: 'report'; readonly code: ReportErrorCode; readonly path: string; readonly message: string } & Place)\n | ({ readonly stage: 'expressions'; readonly code: DiagnosticCode; readonly path: string; readonly message: string } & Place)\n | { readonly stage: 'parameters' | 'data'; readonly code: DataErrorCode; readonly path: string; readonly message: string }\n | ({ readonly stage: 'evaluation'; readonly code: EvaluationErrorCode; readonly path: string; readonly message: string; readonly aggregateId?: string } & Place)\n | ({ readonly stage: 'format'; readonly code: FormatErrorCode; readonly path: string; readonly message: string } & Place)\n | ({ readonly stage: 'resolve'; readonly code: ResolveErrorCode; readonly path: string; readonly message: string } & Place)\n\nexport type RuntimeStage = RuntimeError['stage']\n\n/** The optional parts of a place, written only when present, as exactOptionalPropertyTypes asks. */\nexport function placed(place: { readonly componentId?: string | undefined; readonly columnId?: string | undefined; readonly row?: number | undefined }): Place {\n return {\n ...(place.componentId === undefined ? {} : { componentId: place.componentId }),\n ...(place.columnId === undefined ? {} : { columnId: place.columnId }),\n ...(place.row === undefined ? {} : { row: place.row }),\n }\n}\n\n/** A type as a message says what a value is: \"a decimal\", \"an integer\". */\nexport function aType(type: string): string {\n return `${/^[aeiou]/.test(type) ? 'an' : 'a'} ${type}`\n}\n\nexport function fromReport(error: ReportError): RuntimeError {\n return { stage: 'report', code: error.code, path: error.path, message: error.message, ...placed(error) }\n}\n\nexport function fromDiagnostic(diagnostic: Diagnostic): RuntimeError {\n return { stage: 'expressions', code: diagnostic.code, path: diagnostic.path, message: diagnostic.message, ...placed(diagnostic) }\n}\n\nexport function fromData(stage: 'parameters' | 'data', error: DataError): RuntimeError {\n return { stage, code: error.code, path: error.path, message: error.message }\n}\n\nexport function fromEvaluation(error: EvaluationError): RuntimeError {\n return {\n stage: 'evaluation',\n code: error.code,\n path: error.path,\n message: error.message,\n ...placed(error),\n ...(error.aggregateId === undefined ? {} : { aggregateId: error.aggregateId }),\n }\n}\n\n/**\n * The errors and warnings one resolution collects. Errors are bounded as the\n * data check bounds its own: past `MAX_DATA_ERRORS`, one `too-many-errors`\n * says the list was cut short, and `full` tells a long loop to stop. A\n * warning is said once per path: a preview that lacks a field a thousand\n * rows read warns once for it.\n */\nexport class Problems {\n readonly #errors: RuntimeError[] = []\n readonly #warnings = new Map<string, RuntimeError>()\n #overflowed = false\n\n error(error: RuntimeError): void {\n if (this.#errors.length < MAX_DATA_ERRORS) this.#errors.push(error)\n else this.#overflowed = true\n }\n\n warn(warning: RuntimeError): void {\n const key = `${warning.stage} ${warning.code} ${warning.path}`\n if (!this.#warnings.has(key)) this.#warnings.set(key, warning)\n }\n\n /** Whether the error list is cut short: nothing more is worth computing. */\n get full(): boolean {\n return this.#overflowed\n }\n\n get failed(): boolean {\n return this.#errors.length > 0\n }\n\n errors(): RuntimeError[] {\n const errors = [...this.#errors]\n if (this.#overflowed) errors.push({ stage: 'resolve', code: 'too-many-errors', path: '', message: `more than ${MAX_DATA_ERRORS} errors were found; the first ${MAX_DATA_ERRORS} are listed` })\n return errors\n }\n\n warnings(): RuntimeError[] {\n return [...this.#warnings.values()]\n }\n}\n","/**\n * What one resolution knows while it lowers a report, and the three scopes\n * a value is read in (0007): the report, a group of rows, one detail row.\n *\n * A scope is the values an expression is handed -- `params`, `header`,\n * `totals`, and `group` or `row` where there is one -- and where a currency\n * format finds a currency. Every expression is evaluated through `valueOf`\n * or `holds`, so an evaluation that fails is an error in one place, and a\n * preview that lacks a field degrades in one place: what reads it prints\n * nothing, and a condition over it does not hold, each said once as a\n * warning. In a final render a missing field never gets this far: the data\n * check refuses it.\n *\n * A code is the one place a value that prints as nothing is refused: in a\n * final render, a run whose value is null in a QR code's content or a\n * QR-bill's or an EPC QR code's text (`joinedText` in `inlines.ts`), and a\n * QR code's content that prints nothing at all. A preview encodes them as they resolve, as a\n * paragraph prints them.\n *\n * A report that is an e-invoice reads three more names wherever `totals`\n * is read -- `invoice`, `vatBasis` and `vatAmount` -- once its totals are\n * computed (`lower-e-invoice.ts`), before anything is lowered.\n */\nimport type { Decimal } from '@formancy/expressions'\nimport type { ExpressionValues } from '@formancy/report-core'\nimport type { FieldRef, FieldType, ParameterType, ReportDefinition } from '@formancy/report-spec'\nimport type { CheckedData, CheckedRecord } from './data.js'\nimport type { TextStyle } from './document.js'\nimport type { ReportExpressions } from './evaluate.js'\nimport type { CurrencyScope, Formatter, TypedValue } from './format.js'\nimport type { CheckedParameters } from './parameters.js'\nimport { fromEvaluation } from './resolve-errors.js'\nimport type { Problems } from './resolve-errors.js'\nimport type { OrderedRow, RowGroup } from './sort-group.js'\nimport type { ImageValue } from './values.js'\n\n/** An approved asset, named as report-spec names one: by id, pinned by digest. */\nexport interface ImageRef {\n readonly asset: string\n readonly digest: string\n}\n\n/** What the host holds for an approved asset: its bytes, already fetched, and their media type. */\nexport interface ImageBytes {\n readonly mediaType: string\n readonly bytes: Uint8Array\n}\n\n/**\n * The host's lookup of an approved asset's bytes by its id and digest, or\n * undefined when it has none. Never an address: the runtime fetches nothing.\n */\nexport type ImageResolver = (ref: ImageRef) => ImageBytes | undefined\n\n/** Each aggregate's value over some rows, by id: a typed value, or null where it has none. */\nexport type AggregateValues = ReadonlyMap<string, TypedValue | null>\n\n/** The totals of one render: each aggregate over every row, and the same over any group of them. */\nexport interface Totals {\n readonly report: AggregateValues\n over(rows: readonly OrderedRow[]): AggregateValues\n}\n\n/**\n * What a render that is an e-invoice computed before it lowered anything\n * (`lower-e-invoice.ts`), for lowering to read.\n */\nexport interface InvoiceReads {\n /** What `invoice`, `vatBasis` and `vatAmount` hold. */\n readonly names: ExpressionValues\n /**\n * Each value a column that prints a term of each line gave, by the path\n * of the column's value, one for each detail row by its index in the\n * data: what the table prints, so that it prints what the XML holds.\n */\n readonly columns: ReadonlyMap<string, readonly (TypedValue | null)[]>\n /** What a payment code printed with the e-invoice may ask for: the amount due (BT-115), and the payment account (BT-84) once its rule took it, undefined where none did. */\n readonly payable: { readonly amount: Decimal; readonly account: string | undefined }\n}\n\n/** One resolution's inputs, checked, and what it collects. */\nexport interface Render {\n /** The copy validation read. */\n readonly report: ReportDefinition\n readonly expressions: ReportExpressions\n readonly formatter: Formatter\n readonly params: CheckedParameters\n readonly data: CheckedData\n readonly problems: Problems\n readonly preview: boolean\n readonly images: ImageResolver | undefined\n /** Each print style, by id, as the document's style. */\n readonly styles: ReadonlyMap<string, TextStyle>\n readonly totals: Totals\n /** What the e-invoice computed before lowering, where the report is one. */\n readonly invoice?: InvoiceReads\n}\n\n/** Where a value is read: what its expressions are handed, where its currency comes from, and what an error there names. */\nexport interface Scope {\n readonly values: ExpressionValues\n readonly currency: CurrencyScope\n /** The current group's aggregates, in a group's header and footer. */\n readonly group?: AggregateValues\n /** The record a detail field is read from: the current row, or a group's first row, whose key every row of the group shares. */\n readonly record?: CheckedRecord\n /** The current row's index in the data as the provider gave it, for an error to name. */\n readonly row?: number\n}\n\n/** Each aggregate's value as an expression is handed it: the typed value's own, or null. */\nfunction raw(values: AggregateValues): Record<string, unknown> {\n return Object.fromEntries([...values].map(([id, value]) => [id, value === null ? null : value.value]))\n}\n\n/** The header record, or none when the report declares no header dataset. */\nfunction headerOf(render: Pick<Render, 'data'>): CheckedRecord {\n return render.data.header ?? {}\n}\n\n/** The e-invoice's names, read wherever `totals` is, once they are computed; none in a report that is no e-invoice. */\nfunction invoiceNames(render: Pick<Render, 'invoice'>): ExpressionValues {\n return render.invoice?.names ?? {}\n}\n\nexport function reportScope(render: Pick<Render, 'params' | 'data' | 'invoice'>, totals: AggregateValues): Scope {\n const header = headerOf(render)\n return { values: { params: render.params, header, totals: raw(totals), ...invoiceNames(render) }, currency: { params: render.params, header } }\n}\n\n/**\n * A group's header and footer: the report's values, and the group's\n * aggregates and key as `group`. `by` is the field grouped by; where a\n * preview's rows lack it the key is missing, as the field is, not null.\n */\nexport function groupScope(render: Render, group: RowGroup, aggregates: AggregateValues, by: string): Scope {\n const record = (group.rows[0] as OrderedRow).record\n const header = headerOf(render)\n const key = Object.hasOwn(record, by) ? { key: group.key } : {}\n return {\n values: { params: render.params, header, totals: raw(render.totals.report), group: { ...raw(aggregates), ...key }, ...invoiceNames(render) },\n currency: { params: render.params, header, row: record },\n group: aggregates,\n record,\n }\n}\n\n/** One detail row: the report's values, and the row's as `row`. */\nexport function rowScope(render: Pick<Render, 'params' | 'data' | 'invoice'>, totals: AggregateValues, row: OrderedRow): Scope {\n const header = headerOf(render)\n return {\n values: { params: render.params, header, totals: raw(totals), row: row.record, ...invoiceNames(render) },\n currency: { params: render.params, header, row: row.record },\n record: row.record,\n row: row.index,\n }\n}\n\n/** A failed evaluation: an error, or in a preview a value the data lacks, which is a warning. Returns whether it was only a warning. */\nfunction failed(render: Pick<Render, 'problems' | 'preview'>, outcome: { readonly error: Parameters<typeof fromEvaluation>[0] }): boolean {\n if (render.preview && outcome.error.code === 'missing-value') {\n // Said once for the expression, naming the first row, not once per row: the data check has already said which field is missing.\n const error = fromEvaluation(outcome.error)\n render.problems.warn({ ...error, message: `${error.message}; this preview prints nothing for it` })\n return true\n }\n render.problems.error(fromEvaluation(outcome.error))\n return false\n}\n\n/** The value of the expression whose `cel` is at `path`, read in `scope`; null for none, undefined when it failed and the failure is recorded. */\nexport function valueOf(render: Pick<Render, 'expressions' | 'problems' | 'preview'>, scope: Scope, path: string): TypedValue | null | undefined {\n const outcome = render.expressions.evaluate(path, scope.values, scope.row)\n if (outcome.ok) return outcome.value\n return failed(render, outcome) ? null : undefined\n}\n\n/** Whether the condition whose `cel` is at `path` holds in `scope`; undefined when it failed and the failure is recorded as an error. */\nexport function holds(render: Pick<Render, 'expressions' | 'problems' | 'preview'>, scope: Scope, path: string): boolean | undefined {\n const outcome = render.expressions.condition(path, scope.values, scope.row)\n if (outcome.ok) return outcome.value\n return failed(render, outcome) ? false : undefined\n}\n\n/** The type the report's contract gives `ref`'s field; the validator has checked that it declares one. */\nexport function fieldType(report: ReportDefinition, ref: FieldRef): FieldType {\n return report.datasets[ref.dataset]?.fields.find(({ id }) => id === ref.field)?.type as FieldType\n}\n\nexport function parameterType(report: ReportDefinition, parameter: string): ParameterType {\n return report.parameters.find(({ id }) => id === parameter)?.type as ParameterType\n}\n\n/**\n * The value of `ref`, typed by its contract: a header field's from the\n * header, a detail field's from `record`. Null where it is null, and where\n * a preview's data lacks it, which the data check has already warned of. An\n * image field is drawn, never printed (0007), and reads as null here.\n */\nexport function fieldValue(render: Pick<Render, 'report' | 'data'>, record: CheckedRecord | undefined, ref: FieldRef): TypedValue | null {\n const value = (ref.dataset === 'header' ? render.data.header : record)?.[ref.field] ?? null\n const type = fieldType(render.report, ref)\n if (value === null || type === 'image') return null\n return { type, value } as TypedValue\n}\n\n/** An image field's value in the header: an approved asset, or null when there is none to draw. */\nexport function imageValue(render: Pick<Render, 'data'>, ref: FieldRef): ImageValue | null {\n return (render.data.header?.[ref.field] as ImageValue | null | undefined) ?? null\n}\n","/**\n * A run of a report -- literal, bound, computed, totalled or a page counter\n * -- lowered to the text it prints, formatted for the report's locale.\n *\n * The one place each kind of inline gets its value: a field from the header\n * or the current record, a parameter from the checked parameters, an\n * expression from its evaluation in the scope it stands in, an aggregate\n * from the report's totals or the current group's. Every value is formatted\n * by `format.ts` with the inline's format, or printed plainly without one,\n * and null prints as nothing (0007). A page counter stays a field the\n * engine fills in, since only it knows the pages.\n *\n * A QR code's content, and each text of a QR-bill or an EPC QR code, is\n * read run by run as a paragraph's is, and joined into the one text the\n * code encodes (`joinedText`), where a value that prints as nothing is\n * refused in a final render. An e-invoice's texts are read the same way\n * (`readRuns`), and held to its own rules.\n *\n * A column that prints a term of an e-invoice's lines is read once for\n * every row before anything is lowered, since the totals are computed from\n * it (`e-invoice-lines.ts`); the table prints the value kept then, never\n * one read again, so that the page and the XML hold one evaluation.\n */\nimport type { Inline as ReportInline } from '@formancy/report-spec'\nimport type { Inline } from './document.js'\nimport type { TypedValue } from './format.js'\nimport { fieldValue, parameterType, valueOf } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\nimport { placed } from './resolve-errors.js'\n\n/** What an error names besides the inline's path: the component, and in a table the column, or what holds it outside any component. */\nexport interface Owner {\n /** What holds the inline where no component does, by name: \"the payment part\". A component is named by its id. */\n readonly said?: string\n readonly componentId?: string\n readonly columnId?: string\n}\n\n/** A run whose value is read: anything but literal text and a page counter. */\nexport type BoundInline = Exclude<ReportInline, { kind: 'text' | 'pageNumber' | 'pageCount' }>\n\n/** The value `inline`, at `path`, reads in `scope`, unformatted; undefined when its evaluation failed, which is recorded. */\nexport function inlineValue(render: Pick<Render, 'report' | 'data' | 'params' | 'expressions' | 'problems' | 'preview' | 'totals'>, scope: Scope, inline: BoundInline, path: string): TypedValue | null | undefined {\n switch (inline.kind) {\n case 'field':\n return fieldValue(render, scope.record, inline.field)\n case 'parameter': {\n const value = render.params[inline.parameter] ?? null\n return value === null ? null : ({ type: parameterType(render.report, inline.parameter), value } as TypedValue)\n }\n case 'expression':\n return valueOf(render, scope, `${path}/expression/cel`)\n case 'aggregate':\n // report-spec allows a group's aggregate only where there is a group.\n return (inline.over === 'group' ? scope.group : render.totals.report)?.get(inline.aggregate) ?? null\n }\n}\n\n/** What the e-invoice kept of the detail row `row` for the column value at `path`: the value, null among them; or undefined where it kept nothing. */\nfunction kept(render: Render, path: string, row: number | undefined): { readonly value: TypedValue | null } | undefined {\n const column = row === undefined ? undefined : render.invoice?.columns.get(path)\n // Every row was read: one that could not be has refused the render before anything is lowered.\n return column === undefined ? undefined : { value: column[row as number] as TypedValue | null }\n}\n\n/** The value `inline` reads in `scope`, and the text it prints; undefined when either could not be had, which is recorded. */\nfunction printed(render: Render, scope: Scope, inline: BoundInline, path: string, owner: Owner): { readonly value: TypedValue | null; readonly text: string } | undefined {\n const read = kept(render, path, scope.row)\n const value = read === undefined ? inlineValue(render, scope, inline, path) : read.value\n if (value === undefined) return undefined\n const formatted = render.formatter.format(value, inline.format, scope.currency)\n if (formatted.ok) return { value, text: formatted.text }\n const where = [owner.componentId === undefined ? owner.said : `component ${owner.componentId}`, owner.columnId && `column ${owner.columnId}`, scope.row !== undefined && `detail row ${scope.row}`].filter(Boolean).join(', ')\n render.problems.error({ stage: 'format', code: formatted.code, path, message: `${where}: ${formatted.message}`, ...placed({ componentId: owner.componentId, columnId: owner.columnId, row: scope.row }) })\n return undefined\n}\n\n/** `inline`, at `path` in the report, as the run it prints in `scope`; undefined when it could not be, which is recorded. */\nexport function runOf(render: Render, scope: Scope, inline: ReportInline, path: string, owner: Owner): Inline | undefined {\n if (inline.kind === 'text') return { text: inline.text }\n if (inline.kind === 'pageNumber' || inline.kind === 'pageCount') return { field: inline.kind }\n const run = printed(render, scope, inline, path, owner)\n return run && { text: run.text }\n}\n\n/** What holds runs a code encodes, as an error names it: a QR code's or an EPC QR code's component, or the payment part. */\nexport interface Encoder {\n /** How an error's message names it: \"component pay-code\", \"the payment part\". */\n readonly said: string\n /** The component, for a code that is one. */\n readonly componentId?: string\n /** What the runs are encoded in. */\n readonly code: keyof typeof SCANNED_AS\n}\n\n/** What a code of less than its runs would scan as, by what they are encoded in. */\nconst SCANNED_AS = {\n 'a QR code': 'some other text',\n 'a QR-bill': 'some other bill',\n 'an EPC QR code': 'some other transfer',\n} as const\n\n/** What runs encoded in a code join to, and whether a run of them had a value that is null, which a preview prints as nothing. */\nexport interface Encoded {\n readonly text: string\n readonly lacking: boolean\n}\n\n/** What runs print, read as a paragraph's: their text, the paths of those whose value is null, and whether one could not be read, which is recorded. */\nexport interface ReadRuns {\n readonly text: string\n readonly nulls: readonly string[]\n readonly refused: boolean\n}\n\n/**\n * The runs at `path`, read in `scope` run by run as a paragraph's are, so\n * that what a code or an e-invoice holds and what a paragraph prints never\n * format a value apart. A page counter has no value before there are\n * pages, and report-spec refuses one wherever runs are read so; one that\n * reaches here all the same throws, naming what holds it, never read as\n * nothing.\n */\nexport function readRuns(render: Render, scope: Scope, runs: readonly ReportInline[], path: string, owner: Owner & { readonly said: string }): ReadRuns {\n const texts: string[] = []\n const nulls: string[] = []\n let refused = false\n for (const [index, inline] of runs.entries()) {\n const at = `${path}/${index}`\n if (inline.kind === 'pageNumber' || inline.kind === 'pageCount') {\n throw new RangeError(`${owner.said} holds a ${inline.kind} at ${at}, which has no value before there are pages; report-spec refuses it`)\n }\n const run = inline.kind === 'text' ? { value: undefined, text: inline.text } : printed(render, scope, inline, at, owner)\n if (run === undefined) refused = true\n else {\n if (run.value === null) nulls.push(at)\n texts.push(run.text)\n }\n }\n return { text: texts.join(''), nulls, refused }\n}\n\n/**\n * The text `runs`, at `path`, join to when they are encoded in a code,\n * read as `readRuns` reads them. Undefined when a run is refused, which is\n * recorded, naming `encoder`.\n *\n * A final render refuses a run whose value is null: a code of less than\n * its content scans as some other text, and the page does not say so. A\n * preview encodes it as nothing, as a paragraph prints it, and says it\n * did.\n *\n * `unused` is given for a text its code may leave out, and says whether\n * the text the runs print leaves its element unused. A text that does,\n * nulls and all -- a nullable field's way of saying \"none\" -- is no text\n * rather than one cut short, and a final render takes it as a preview\n * does; one whose other runs print something is still refused.\n */\nexport function joinedText(render: Render, scope: Scope, runs: readonly ReportInline[], path: string, encoder: Encoder, unused?: (text: string) => boolean): Encoded | undefined {\n const { text, nulls, refused } = readRuns(render, scope, runs, path, encoder)\n if (!render.preview && nulls.length > 0 && unused?.(text) !== true) {\n for (const at of nulls) {\n render.problems.error({ stage: 'resolve', code: 'no-qr-value', path: at, message: `${encoder.said}: this run has no value, and ${encoder.code} without it would scan as ${SCANNED_AS[encoder.code]}`, ...placed(encoder) })\n }\n return undefined\n }\n return refused ? undefined : { text, lacking: render.preview && nulls.length > 0 }\n}\n\n/**\n * The text the QR code `id` encodes: its `content`, at `path`, joined as\n * `joinedText` joins it. Undefined when it is refused, which is recorded,\n * naming the code. A final render refuses content that prints nothing at\n * all, a code of nothing, which scans as no code; a preview encodes it.\n */\nexport function encodedText(render: Render, scope: Scope, content: readonly ReportInline[], path: string, id: string): string | undefined {\n const joined = joinedText(render, scope, content, `${path}/content`, { said: `component ${id}`, componentId: id, code: 'a QR code' })\n if (joined === undefined) return undefined\n if (joined.text !== '' || render.preview) return joined.text\n render.problems.error({ stage: 'resolve', code: 'empty-qr-code', path: `${path}/content`, message: `component ${id}: its content prints nothing, and a QR code of nothing scans as no code`, componentId: id })\n return undefined\n}\n\n/** The text of runs that hold no page counter: what a table cell or a group header prints. */\nexport function textOfRuns(runs: readonly Inline[]): string {\n return runs.map((run) => ('text' in run ? run.text : '')).join('')\n}\n","/**\n * An e-invoice's lines (BG-25): one for each row of the table that prints\n * them, read once, before the totals, for the page and the XML alike\n * (0027).\n *\n * - **One evaluation.** The four columns the e-invoice names -- the item\n * name (BT-153), the invoiced quantity (BT-129), the net price (BT-146)\n * and the net amount (BT-131) -- are read here for every row, as the\n * table reads a cell, and kept by the path of each column's value and the\n * row's index: the table prints the very value kept (`inlines.ts`). So\n * the page and the XML cannot each read a line, and part. The line's\n * identifier (BT-126), its unit (BT-130) and its VAT category (BT-151)\n * are codes a page need not print, read from each row as an aggregate\n * reads it.\n * - **In the table's order** (`orderTable`, 0007), which the XML holds\n * them in.\n * - **Held to EN 16931's rules**, report-spec's functions over text, the\n * ones its validator applies to a literal (`en16931.ts`): a code from a\n * closed list, a net price that is not negative, a net amount that is a\n * whole number of cents, never rounded, a category the invoice declares.\n * And to what EN 16931 defines and no rule of CEN's tests: a net amount\n * that is the quantity times the net price, rounded once to the cent\n * (`lineNetAmount`), and a line identifier no other line has. A rule\n * broken is `invalid-e-invoice`, naming the row and the column or the\n * code, the term and the rule, never the value.\n * - **Printed as the XML holds it.** A quantity or a net price whose\n * column's format shows fewer places than it has is refused: the page\n * would round it, and the XML would not.\n * - **A preview holds what it has.** A final render refuses a term that\n * has no value (BR-21 to BR-26, BR-CO-04) and a table of no rows\n * (BR-16). A preview takes a term with no value as one it lacks, and\n * leaves a line whose net amount or category it lacks out of every\n * total, as an aggregate skips a null; what the data does hold it holds\n * to the same rules.\n */\nimport { compareDecimal, decimalFromString, decimalToString } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport { checkEInvoiceDecimal, checkEInvoiceText, checkLineCategory, E_INVOICE_DECIMALS, E_INVOICE_LINE_CODES, E_INVOICE_LINE_COLUMNS, E_INVOICE_TEXTS, eInvoiceBlank, en16931Rule, walkComponents } from '@formancy/report-spec'\nimport type { EInvoiceDecimalTerm, EInvoiceLineCode, EInvoiceLineColumn, EInvoiceLineTerm, EInvoiceTextTerm, En16931Rule, FacturXInvoice, FieldType, TableComponent, VatCategory } from '@formancy/report-spec'\nimport { roundDecimalAs } from './decimal.js'\nimport { lineNetAmount } from './e-invoice-totals.js'\nimport type { TypedValue } from './format.js'\nimport { inlineValue } from './inlines.js'\nimport type { BoundInline } from './inlines.js'\nimport { fieldValue, rowScope, valueOf } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\nimport { aType, placed } from './resolve-errors.js'\nimport { orderTable } from './sort-group.js'\nimport type { OrderedRow } from './sort-group.js'\n\n/** A line's terms as the XML writes them. */\nexport interface LineTerms {\n /** BT-126. */\n readonly id: string\n /** BT-153. */\n readonly name: string\n /** BT-129, as written. */\n readonly quantity: string\n /** BT-130, a code of report-spec's `UNIT_CODES`. */\n readonly unit: string\n /** BT-146, as written. */\n readonly netPrice: string\n /** BT-131, at exactly two places. */\n readonly netAmount: Decimal\n /** The category the line names (BT-151), and so its rate (BT-152). */\n readonly category: VatCategory\n}\n\ntype LineKey = EInvoiceLineColumn | EInvoiceLineCode\n\n/** The key of each term of `LineTerms` the e-invoice names a column or a code by. */\nconst TERM_OF: { readonly [K in LineKey]: keyof LineTerms } = { name: 'name', quantity: 'quantity', netPrice: 'netPrice', netAmount: 'netAmount', id: 'id', unit: 'unit', vat: 'category' }\n\n/** A line as a render read it from its row: each term, null where a preview has no value for it, and the row's index in the data. */\nexport type ReadLine = { readonly [K in keyof LineTerms]: LineTerms[K] | null } & { readonly row: number }\n\n/** The lines in the table's order, and what the named columns printed of each row, by the path of each column's value. */\nexport interface ReadLines {\n readonly lines: readonly ReadLine[]\n readonly columns: ReadonlyMap<string, readonly (TypedValue | null)[]>\n}\n\n/** What the lines are read with: every input but what the e-invoice adds. */\ntype Reading = Omit<Render, 'invoice'>\n\n/** Where a term of a line is read, as a refusal names it. */\ninterface Place {\n readonly path: string\n readonly said: string\n readonly componentId?: string\n readonly columnId?: string\n readonly row: number\n}\n\nfunction refuse(render: Reading, place: Place, message: string): undefined {\n render.problems.error({ stage: 'resolve', code: 'invalid-e-invoice', path: place.path, message: `${place.said}, detail row ${place.row}: ${message}`, ...placed(place) })\n return undefined\n}\n\n/** The rule a term with no value breaks: every line term is needed. */\nfunction required(term: EInvoiceLineTerm): string {\n const rule = term.term in E_INVOICE_DECIMALS ? E_INVOICE_DECIMALS[term.term as EInvoiceDecimalTerm].required : E_INVOICE_TEXTS[term.term as EInvoiceTextTerm].required\n // Every term of a line has the rule of CEN's its absence breaks (`en16931.test.ts`).\n return en16931Rule(rule as En16931Rule, 'has no value, and every line of an e-invoice has one')\n}\n\n/** A value as its term's text: a decimal and an integer by their own digits, a text as it is. */\nfunction written(value: TypedValue): string {\n return value.type === 'decimal' ? decimalToString(value.value) : String(value.value)\n}\n\n/**\n * The term `term` of a line, read as `value`, held to its rule: what the\n * XML writes, null where a preview has no value for it, or undefined when\n * it is refused, which is recorded at `place`.\n */\nfunction checked(render: Reading, term: EInvoiceLineTerm, value: TypedValue | null, place: Place): string | null | undefined {\n if (value === null || (render.preview && value.type === 'string' && eInvoiceBlank(value.value))) {\n return render.preview ? null : refuse(render, place, `${term.what} ${required(term)}`)\n }\n if (!term.types.includes(value.type as FieldType)) return refuse(render, place, `${term.what} is read from ${term.types.map(aType).join(' or ')}, and this gives ${aType(value.type)}`)\n const text = written(value)\n const outcome = term.term in E_INVOICE_DECIMALS ? checkEInvoiceDecimal(term.term as EInvoiceDecimalTerm, text) : checkEInvoiceText(term.term as EInvoiceTextTerm, text)\n return outcome.ok ? outcome.value : refuse(render, place, `${term.what} ${outcome.rule}`)\n}\n\n/** A column the e-invoice names: its key, its value, where that stands, and what it printed of each row. */\ninterface NamedColumn {\n readonly key: EInvoiceLineColumn\n readonly id: string\n readonly value: BoundInline\n readonly path: string\n readonly printed: (TypedValue | null)[]\n}\n\n/** The table the lines are the rows of, and the columns that print their terms. */\nfunction namedColumns(render: Reading, invoice: FacturXInvoice): { readonly table: TableComponent; readonly columns: readonly NamedColumn[] } {\n // report-spec's validator holds the lines to this table, and each named column to it: shown, and a detail field or an expression.\n const located = walkComponents(render.report).find(({ component }) => component.kind === 'table' && component.id === invoice.lines.table) as { readonly component: TableComponent; readonly path: string }\n const table = located.component\n const columns = (Object.keys(E_INVOICE_LINE_COLUMNS) as EInvoiceLineColumn[]).map((key): NamedColumn => {\n const index = table.columns.findIndex((column) => column.id === invoice.lines[key])\n const column = table.columns[index] as TableComponent['columns'][number]\n return { key, id: column.id, value: column.value as BoundInline, path: `${located.path}/columns/${index}/value`, printed: new Array<TypedValue | null>(render.data.detail.length).fill(null) }\n })\n return { table, columns }\n}\n\n/**\n * The columns whose term the XML writes with the data's own places, which\n * their format may not round: the quantity and the net price. The net\n * amount and every total are amounts the XML writes at two places, which\n * the editing core holds a format to where the template is written.\n */\nconst AS_WRITTEN: ReadonlySet<EInvoiceLineColumn> = new Set(['quantity', 'netPrice'])\n\n/** The places `column` prints `value` at, where printing it there would round it, by value; undefined where it prints it as it is. */\nfunction roundingPlaces(column: NamedColumn, value: TypedValue): number | undefined {\n const format = column.value.format\n if (!AS_WRITTEN.has(column.key) || value.type !== 'decimal' || (format?.kind !== 'number' && format?.kind !== 'currency')) return undefined\n const shown = roundDecimalAs(value.value, { scale: format.scale, mode: 'half-away-from-zero' })\n return compareDecimal(shown, value.value) === 0 ? undefined : format.scale\n}\n\n/** The term of `column` in `row`, read and held to its rule, and to the places its column prints; `undefined` when it could not be, which is recorded. */\nfunction readColumn(render: Reading, scope: Scope, column: NamedColumn, place: Place): string | null | undefined {\n const value = inlineValue(render, scope, column.value, column.path)\n if (value === undefined) return undefined\n column.printed[place.row] = value\n const term = E_INVOICE_LINE_COLUMNS[column.key]\n const text = checked(render, term, value, place)\n const places = typeof text === 'string' ? roundingPlaces(column, value as TypedValue) : undefined\n if (places === undefined) return text\n return refuse(render, place, `${term.what} has more places than its column prints, ${places}, so the page would print another than the XML holds: the column prints the places the data gives`)\n}\n\n/** The line of `row`, every term read and held to its rule; undefined when a term is refused or could not be read, which is recorded. */\nfunction readLine(render: Reading, invoice: FacturXInvoice, table: TableComponent, columns: readonly NamedColumn[], row: OrderedRow): ReadLine | undefined {\n const scope = rowScope(render, render.totals.report, row)\n const terms: Partial<Record<keyof LineTerms, string | VatCategory | Decimal | null>> = {}\n let whole = true\n const keep = (key: LineKey, value: string | VatCategory | Decimal | null | undefined): void => {\n if (value === undefined) whole = false\n else terms[TERM_OF[key]] = value\n }\n const placeOf = (column: NamedColumn): Place => ({ path: column.path, said: `component ${table.id}, column ${column.id}`, componentId: table.id, columnId: column.id, row: row.index })\n for (const column of columns) {\n const text = readColumn(render, scope, column, placeOf(column))\n keep(column.key, column.key === 'netAmount' && typeof text === 'string' ? decimalFromString(text) : text)\n }\n const { quantity, netPrice, netAmount } = terms as Partial<Record<'quantity' | 'netPrice', string | null>> & { readonly netAmount?: Decimal | null }\n if (typeof quantity === 'string' && typeof netPrice === 'string' && netAmount !== undefined && netAmount !== null && compareDecimal(lineNetAmount(quantity, netPrice), netAmount) !== 0) {\n const amount = columns.find(({ key }) => key === 'netAmount') as NamedColumn\n keep('netAmount', refuse(render, placeOf(amount), `${E_INVOICE_LINE_COLUMNS.netAmount.what} is not ${E_INVOICE_LINE_COLUMNS.quantity.what} times ${E_INVOICE_LINE_COLUMNS.netPrice.what}, rounded once to the cent: a receiver that multiplies them reads another amount`))\n }\n for (const key of Object.keys(E_INVOICE_LINE_CODES) as EInvoiceLineCode[]) {\n const code = invoice.lines[key]\n const path = `/eInvoice/lines/${key}`\n const value = code.kind === 'field' ? fieldValue(render, row.record, code.field) : valueOf(render, scope, `${path}/expression/cel`)\n if (value === undefined) {\n whole = false\n continue\n }\n const place = { path, said: 'the e-invoice', row: row.index }\n const text = checked(render, E_INVOICE_LINE_CODES[key], value, place)\n if (key !== 'vat' || typeof text !== 'string') keep(key, text)\n else {\n const category = checkLineCategory(text, invoice.vat)\n keep(key, category.ok ? category.value : refuse(render, place, `${E_INVOICE_LINE_CODES.vat.what} ${category.rule}`))\n }\n }\n return whole ? ({ ...terms, row: row.index } as ReadLine) : undefined\n}\n\n/**\n * `invoice`'s lines in the table's order, each term read once and held to\n * its rule, and what the named columns printed of each row; undefined when\n * a line is refused, or could not be read, which is recorded. A final\n * render refuses a table of no rows (BR-16).\n */\nexport function readLines(render: Reading, invoice: FacturXInvoice): ReadLines | undefined {\n const { table, columns } = namedColumns(render, invoice)\n const lines: ReadLine[] = []\n const ids = new Set<string>()\n let whole = true\n for (const row of orderTable(render.report, table, render.data.detail).rows) {\n if (render.problems.full) return undefined\n const line = readLine(render, invoice, table, columns, row)\n if (line === undefined) whole = false\n else if (line.id !== null && ids.has(line.id)) {\n // BT-126 is the line's own (EN 16931, as XRechnung 3.0.2 gives its model): the later of two is refused.\n refuse(render, { path: '/eInvoice/lines/id', said: 'the e-invoice', row: row.index }, `${E_INVOICE_LINE_CODES.id.what} is an earlier line's, and each line of an e-invoice has its own`)\n whole = false\n } else {\n if (line.id !== null) ids.add(line.id)\n lines.push(line)\n }\n }\n if (!render.preview && render.data.detail.length === 0) {\n render.problems.error({\n stage: 'resolve',\n code: 'invalid-e-invoice',\n path: '/eInvoice/lines/table',\n message: `the e-invoice: ${en16931Rule('BR-16', `an e-invoice has one line at least, a row of the table ${table.id}, and the data has no rows`)}`,\n componentId: table.id,\n })\n return undefined\n }\n return whole ? { lines, columns: new Map(columns.map(({ path, printed }) => [path, printed])) } : undefined\n}\n\n/** The lines a final render writes: every term of each read, which a final render refuses a line without. */\nexport function writtenLines(lines: readonly ReadLine[]): readonly LineTerms[] | undefined {\n return lines.every((line) => Object.values(line).every((term) => term !== null)) ? (lines as readonly LineTerms[]) : undefined\n}\n","/**\n * An e-invoice's terms but its lines -- its number, its dates, its seller\n * and its buyer, its categories' reasons, its payment instructions, its\n * paid amount -- each read in the report's scope once the data has\n * resolved it, and held to EN 16931's rules: report-spec's `en16931.ts`,\n * the very functions its validator applies to a literal, named by the same\n * tables.\n *\n * - **Read as a paragraph.** Each text is its runs, read as a paragraph's\n * in the report's scope (`readRuns`), so the XML holds what the same runs\n * would print. A literal passes again; a value from data is held where\n * the validator could not see it.\n * - **What may be left out is.** An optional text the data resolves to\n * blank, nulls and all, is a term the XML leaves out, as an EPC QR code's\n * optional texts are: a nullable field's null is how data says \"none\".\n * A needed one that prints nothing breaks its rule (BR-02, BR-06 ...);\n * one whose runs print something around a null is refused as a text cut\n * short.\n * - **What only the whole says** -- the identifiers the lines' categories\n * need of the seller and the buyer (BR-CO-26, BR-S-02, BR-E-02,\n * BR-AE-02), the time of supply (§ 14 UStG), a category's reason (BR-E-10,\n * BR-AE-10) -- is said of the categories the lines are in, once every\n * part has resolved; an invoicing period's order (BR-29) once both its\n * dates have.\n * - **A preview holds what it has**: a term it has no value for is one it\n * lacks, and what only an absence breaks it does not say. What the data\n * holds it holds to the same rules.\n *\n * A rule broken is `invalid-e-invoice` at the term, naming its business\n * term and the rule, never the value, which may be a person's name,\n * account or VAT identifier.\n */\nimport { decimalFromString, decimalToString } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport {\n buyerIdentificationBreak,\n checkEInvoiceDate,\n checkEInvoiceDecimal,\n checkEInvoiceText,\n checkInvoicingPeriod,\n E_INVOICE_DATES,\n E_INVOICE_DECIMALS,\n E_INVOICE_TEXT_TERMS,\n E_INVOICE_TEXTS,\n eInvoiceBlank,\n en16931Rule,\n sellerIdentificationBreaks,\n supplyBreak,\n vatReasonBreak,\n} from '@formancy/report-spec'\nimport type { EInvoiceAddress, EInvoiceBuyer, EInvoiceDateTerm, EInvoiceSeller, EInvoiceTextTerm, Expression, FacturXInvoice, Inline, PaymentMeansCode, SchemeId, VatCategory } from '@formancy/report-spec'\nimport { readRuns } from './inlines.js'\nimport { reportScope, valueOf } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\nimport { aType } from './resolve-errors.js'\n\n/** A postal address (BG-5, BG-8) as the XML writes it. */\nexport interface AddressTerms {\n readonly line1: string\n readonly line2?: string\n readonly postalCode: string\n readonly city: string\n /** A code of report-spec's `COUNTRY_CODES`. */\n readonly country: string\n}\n\n/** A seller (BG-4) or a buyer (BG-7) as the XML writes it; a buyer has no tax number. */\nexport interface PartyTerms {\n readonly name: string\n /** Its spaces dropped. */\n readonly vatId?: string\n readonly taxNumber?: string\n readonly legalId?: { readonly id: string; readonly scheme?: SchemeId }\n readonly address: AddressTerms\n}\n\n/** The payment instructions (BG-16) as the XML writes them. */\nexport interface PaymentTerms {\n readonly means: PaymentMeansCode\n /** BT-84, as the EPC QR code's account rule writes it: its spaces dropped, its letters capitals. */\n readonly account: string\n readonly bic?: string\n readonly accountName?: string\n readonly remittance?: string\n}\n\n/** Every term of an e-invoice but its lines and its totals, as the XML writes it; each date YYYY-MM-DD. */\nexport interface InvoiceTerms {\n readonly number: string\n readonly issued: string\n readonly seller: PartyTerms\n readonly buyer: PartyTerms\n readonly buyerReference?: string\n readonly delivered?: string\n readonly period?: { readonly start?: string; readonly end?: string }\n /** The exemption reason (BT-120) of each category a line is in that gives one, by the category's id. */\n readonly reasons: ReadonlyMap<string, string>\n readonly payment?: PaymentTerms\n readonly due?: string\n readonly terms?: string\n}\n\n/** What is read with: every input but what the e-invoice adds, and the report's scope. */\ninterface Reader {\n readonly render: Omit<Render, 'invoice'>\n readonly scope: Scope\n}\n\n/** What an error names the e-invoice by: it stands in no component. */\nconst OWNER = { said: 'the e-invoice' } as const\n\nfunction refuse({ render }: Pick<Reader, 'render'>, path: string, message: string): undefined {\n render.problems.error({ stage: 'resolve', code: 'invalid-e-invoice', path, message: `the e-invoice: ${message}` })\n return undefined\n}\n\n/**\n * A read term: its value, null where it is none -- left out, or one a\n * preview has no value for -- or undefined where it was refused or could\n * not be read, which is recorded.\n */\ntype Read<T> = T | null | undefined\n\n/** The text of `term`, its runs at `path`, held to its rule. */\nfunction text(reader: Reader, term: EInvoiceTextTerm, runs: readonly Inline[] | undefined, path: string): Read<string> {\n if (runs === undefined) return null\n const read = readRuns(reader.render, reader.scope, runs, path, OWNER)\n if (read.refused) return undefined\n const rule = E_INVOICE_TEXTS[term]\n const blank = eInvoiceBlank(read.text)\n if (reader.render.preview && (blank || read.nulls.length > 0)) return null\n if (blank && rule.required === undefined) return null\n if (!blank && read.nulls.length > 0) return refuse(reader, path, `${rule.what} has a run with no value, and written without it the e-invoice would hold less than its runs print`)\n const checked = checkEInvoiceText(term, read.text)\n return checked.ok ? checked.value : refuse(reader, path, `${rule.what} ${checked.rule}`)\n}\n\n/** The date of `term`, its expression at `path`: a day on the calendar, YYYY-MM-DD. */\nfunction date(reader: Reader, term: EInvoiceDateTerm, expression: Expression | undefined, path: string): Read<string> {\n if (expression === undefined) return null\n const value = valueOf(reader.render, reader.scope, `${path}/cel`)\n if (value === undefined) return undefined\n const rule = E_INVOICE_DATES[term]\n if (value === null) return rule.required === undefined || reader.render.preview ? null : refuse(reader, path, `${rule.what} ${en16931Rule(rule.required, 'has no value, and an e-invoice needs it')}`)\n if (value.type !== 'date' && value.type !== 'string') return refuse(reader, path, `${rule.what} is a date, and this gives ${aType(value.type)}`)\n const checked = checkEInvoiceDate(value.value)\n return checked.ok ? checked.value : refuse(reader, path, `${rule.what} ${checked.rule}`)\n}\n\n/** `value` under `key` where it is a value; nothing where it is none or was refused. */\nconst term = <K extends string, V>(key: K, value: Read<V>): { [P in K]?: V } => (value === null || value === undefined ? {} : ({ [key]: value } as { [P in K]: V }))\n\n/** Whether every one of `values` was read and is there: what a term needs of each of its parts. */\nconst all = (...values: readonly Read<unknown>[]): boolean => values.every((value) => value !== null && value !== undefined)\n\nfunction address(reader: Reader, held: EInvoiceAddress, path: string, which: 'seller' | 'buyer'): Read<AddressTerms> {\n const terms = E_INVOICE_TEXT_TERMS[which].address\n const line1 = text(reader, terms.line1, held.line1, `${path}/line1`)\n const line2 = text(reader, terms.line2, held.line2, `${path}/line2`)\n const postalCode = text(reader, terms.postalCode, held.postalCode, `${path}/postalCode`)\n const city = text(reader, terms.city, held.city, `${path}/city`)\n const country = text(reader, terms.country, held.country, `${path}/country`)\n if (line2 === undefined || !all(line1, postalCode, city, country)) return undefined\n return { line1: line1 as string, ...term('line2', line2), postalCode: postalCode as string, city: city as string, country: country as string }\n}\n\n/** A party as read, and which of its identifiers are there: one refused is there, as the validator says of one written. */\ninterface ReadParty {\n readonly party: Read<PartyTerms>\n readonly has: { readonly vatId: boolean; readonly taxNumber: boolean; readonly legalId: boolean }\n}\n\nfunction party(reader: Reader, held: EInvoiceSeller | EInvoiceBuyer, path: string, which: 'seller' | 'buyer'): ReadParty {\n const terms = E_INVOICE_TEXT_TERMS[which]\n const name = text(reader, terms.name, held.name, `${path}/name`)\n const vatId = text(reader, terms.vatId, held.vatId, `${path}/vatId`)\n // A buyer has no tax registration identifier (BT-32 is the seller's).\n const taxNumber = which === 'seller' ? text(reader, E_INVOICE_TEXT_TERMS.seller.taxNumber, (held as EInvoiceSeller).taxNumber, `${path}/taxNumber`) : null\n const legalId = text(reader, terms.legalId, held.legalId?.id, `${path}/legalId/id`)\n const where = address(reader, held.address, `${path}/address`, which)\n const has = { vatId: vatId !== null, taxNumber: taxNumber !== null, legalId: legalId !== null }\n if (vatId === undefined || taxNumber === undefined || legalId === undefined || !all(name, where)) return { party: undefined, has }\n const scheme = held.legalId?.scheme\n const registration = legalId === null ? {} : { legalId: { id: legalId, ...(scheme === undefined ? {} : { scheme }) } }\n return { party: { name: name as string, ...term('vatId', vatId), ...term('taxNumber', taxNumber), ...registration, address: where as AddressTerms }, has }\n}\n\nfunction payment(reader: Reader, invoice: FacturXInvoice): { readonly payment: Read<PaymentTerms>; readonly account: string | undefined } {\n const held = invoice.payment\n if (held === undefined) return { payment: null, account: undefined }\n const terms = E_INVOICE_TEXT_TERMS.payment\n const account = text(reader, terms.iban, held.iban, '/eInvoice/payment/iban')\n const bic = text(reader, terms.bic, held.bic, '/eInvoice/payment/bic')\n const accountName = text(reader, terms.accountName, held.accountName, '/eInvoice/payment/accountName')\n const remittance = text(reader, terms.remittance, held.remittance, '/eInvoice/payment/remittance')\n const known = account ?? undefined\n if (bic === undefined || accountName === undefined || remittance === undefined || !all(account)) return { payment: undefined, account: known }\n return { payment: { means: held.means, account: account as string, ...term('bic', bic), ...term('accountName', accountName), ...term('remittance', remittance) }, account: known }\n}\n\n/** The paid amount (BT-113), read in the report's scope: a whole number of cents, at two places, or null where none is paid. */\nexport function paidAmount(render: Omit<Render, 'invoice'>, invoice: FacturXInvoice): Read<Decimal> {\n if (invoice.paid === undefined) return null\n const path = '/eInvoice/paid'\n const value = valueOf(render, reportScope(render, render.totals.report), `${path}/cel`)\n if (value === undefined || value === null) return value\n const what = E_INVOICE_DECIMALS['BT-113'].what\n if (value.type !== 'decimal') return refuse({ render }, path, `${what} is a decimal, and this gives ${aType(value.type)}`)\n const checked = checkEInvoiceDecimal('BT-113', decimalToString(value.value))\n return checked.ok ? decimalFromString(checked.value) : refuse({ render }, path, `${what} ${checked.rule}`)\n}\n\n/** What reading the terms gives: the terms, where every one is there; and the payment account, where its rule took it, for a payment code to be held to. */\nexport interface ReadTerms {\n readonly terms: InvoiceTerms | undefined\n readonly account: string | undefined\n}\n\n/**\n * Every term of `invoice` but its lines and its totals, each read in the\n * report's scope and held to its rule, and what the whole breaks said of\n * `used`, the categories the lines are in. `terms` is undefined where a\n * term was refused, which is recorded, or a preview lacks one.\n */\nexport function readTerms(render: Omit<Render, 'invoice'>, invoice: FacturXInvoice, used: readonly VatCategory[]): ReadTerms {\n const reader: Reader = { render, scope: reportScope(render, render.totals.report) }\n const number = text(reader, E_INVOICE_TEXT_TERMS.number, invoice.number, '/eInvoice/number')\n const issued = date(reader, 'BT-2', invoice.issued, '/eInvoice/issued')\n const seller = party(reader, invoice.seller, '/eInvoice/seller', 'seller')\n const buyer = party(reader, invoice.buyer, '/eInvoice/buyer', 'buyer')\n const buyerReference = text(reader, E_INVOICE_TEXT_TERMS.buyerReference, invoice.buyerReference, '/eInvoice/buyerReference')\n const delivered = date(reader, 'BT-72', invoice.delivered, '/eInvoice/delivered')\n const start = date(reader, 'BT-73', invoice.period?.start, '/eInvoice/period/start')\n const end = date(reader, 'BT-74', invoice.period?.end, '/eInvoice/period/end')\n const reasons = used.map((category) => [category, text(reader, E_INVOICE_TEXT_TERMS.reason, category.reason, `/eInvoice/vat/${invoice.vat.indexOf(category)}/reason`)] as const)\n const paying = payment(reader, invoice)\n const due = date(reader, 'BT-9', invoice.due, '/eInvoice/due')\n const terms = text(reader, E_INVOICE_TEXT_TERMS.terms, invoice.terms, '/eInvoice/terms')\n\n const ordered = typeof start === 'string' && typeof end === 'string' ? checkInvoicingPeriod(start, end) : undefined\n if (ordered !== undefined) refuse(reader, '/eInvoice/period', ordered)\n if (!render.preview) {\n const codes = used.map(({ code }) => code)\n for (const rule of sellerIdentificationBreaks(seller.has, codes)) refuse(reader, '/eInvoice/seller', rule)\n const unidentified = buyerIdentificationBreak(buyer.has, codes)\n if (unidentified !== undefined) refuse(reader, '/eInvoice/buyer', unidentified)\n const unsupplied = supplyBreak(delivered !== null, start !== null || end !== null)\n if (unsupplied !== undefined) refuse(reader, '/eInvoice/delivered', unsupplied)\n for (const [category, reason] of reasons) {\n const unreasoned = vatReasonBreak(category.code, reason !== null)\n if (unreasoned !== undefined) refuse(reader, `/eInvoice/vat/${invoice.vat.indexOf(category)}/reason`, unreasoned)\n }\n }\n const read = [number, issued, seller.party, buyer.party, buyerReference, delivered, start, end, paying.payment, due, terms, ...reasons.map(([, reason]) => reason)]\n if (render.problems.failed || read.includes(undefined) || !all(number, issued, seller.party, buyer.party)) return { terms: undefined, account: paying.account }\n return {\n terms: {\n number: number as string,\n issued: issued as string,\n seller: seller.party as PartyTerms,\n buyer: buyer.party as PartyTerms,\n ...term('buyerReference', buyerReference),\n ...term('delivered', delivered),\n ...(start === null && end === null ? {} : { period: { ...term('start', start), ...term('end', end) } }),\n reasons: new Map(reasons.flatMap(([category, reason]) => (typeof reason === 'string' ? [[category.id, reason] as const] : []))),\n ...term('payment', paying.payment),\n ...term('due', due),\n ...term('terms', terms),\n },\n account: paying.account,\n }\n}\n","/**\n * A report's e-invoice resolved (0027): its lines and its totals before\n * anything is lowered, since the page prints them; and after the page is\n * lowered, in a final render, the XML the PDF embeds.\n *\n * 1. **The lines**, read once from the rows of the table that prints them\n * (`e-invoice-lines.ts`), each column's value kept for the table to\n * print.\n * 2. **The paid amount and the totals**, computed once from the lines\n * (`e-invoice-totals.ts`) and bound as `invoice`, `vatBasis` and\n * `vatAmount` for every scope that reads them.\n * 3. **The other terms**, read in the report's scope and held to EN\n * 16931's rules (`e-invoice-terms.ts`); a payment code is held to the\n * amount due and the account they give (`e-invoice-payable.ts`).\n * 4. **The XML** (`cii.ts`), written from those very values.\n *\n * **A preview is not the invoice.** In Germany the XML a hybrid invoice\n * embeds is the invoice, so a preview writes none and the PDF that leaves\n * it is no e-invoice; it prints the totals of what it has, and warns\n * `e-invoice-preview` whatever data it has, so that every page carries a\n * preview label, complete data or not. A final render writes the XML or\n * refuses.\n */\nimport { FACTUR_X, FACTUR_X_PROFILES } from '@formancy/report-spec'\nimport type { EInvoice, EInvoiceKind, FacturXInvoice } from '@formancy/report-spec'\nimport { ciiXml } from './cii.js'\nimport type { CiiInvoice } from './cii.js'\nimport type { EInvoiceFile } from './document.js'\nimport { readLines, writtenLines } from './e-invoice-lines.js'\nimport { paidAmount, readTerms } from './e-invoice-terms.js'\nimport { invoiceNames, invoiceTotals } from './e-invoice-totals.js'\nimport type { InvoiceReads, Render } from './render-context.js'\n\n/** An e-invoice resolved before lowering: what lowering reads, and what a final render writes its XML from. */\nexport interface ResolvedInvoice {\n readonly reads: InvoiceReads\n /** In a final render whose every term resolved, what the XML is written from; undefined in a preview, or where a term was refused, which is recorded. */\n readonly written: CiiInvoice | undefined\n}\n\ntype Resolver<E extends EInvoice> = (render: Omit<Render, 'invoice'>, invoice: E) => ResolvedInvoice | undefined\n\nfunction facturX(render: Omit<Render, 'invoice'>, invoice: FacturXInvoice): ResolvedInvoice | undefined {\n const read = readLines(render, invoice)\n const paid = paidAmount(render, invoice)\n if (read === undefined || paid === undefined) return undefined\n // A line a preview cannot place, its amount or its category lacking, is in no total.\n const placed = read.lines.flatMap(({ netAmount, category }) => (netAmount === null || category === null ? [] : [{ netAmount, category }]))\n const totals = invoiceTotals(invoice.vat, placed, paid)\n const { terms, account } = readTerms(\n render,\n invoice,\n totals.breakdown.map(({ category }) => category),\n )\n const lines = writtenLines(read.lines)\n const written = render.preview || terms === undefined || lines === undefined ? undefined : { profile: invoice.profile, type: invoice.type, currency: invoice.currency, terms, lines, totals }\n return { reads: { names: invoiceNames(invoice, totals), columns: read.columns, payable: { amount: totals.duePayable, account } }, written }\n}\n\n/** How each kind of e-invoice is resolved. A table over every kind, so a kind added to report-spec without a way down does not compile. */\nconst RESOLVERS: { readonly [K in EInvoiceKind]: Resolver<Extract<EInvoice, { kind: K }>> } = {\n facturX,\n}\n\n/**\n * `invoice`, `render`'s e-invoice, resolved before anything is lowered:\n * its lines, its totals and its terms. Undefined when its lines or its\n * totals could not be, which is recorded: nothing that prints them can be\n * lowered. A term refused is recorded, and leaves nothing to write.\n */\nexport function resolveEInvoice(render: Omit<Render, 'invoice'>, invoice: EInvoice): ResolvedInvoice | undefined {\n return RESOLVERS[invoice.kind](render, invoice)\n}\n\n/** What a preview of an e-invoice warns, whatever data it has. */\nconst PREVIEWED = 'this is a preview, which writes no e-invoice: a final render alone writes its XML, and this PDF is not the invoice'\n\n/**\n * The file the PDF of `render` embeds, once its page is lowered: in a\n * final render the XML, named as report-spec names it; in a preview none,\n * and the warning that says so. Undefined too where anything was refused,\n * which refuses the document.\n *\n * A final render with nothing to write and nothing recorded would hand on\n * a document without its XML, which a renderer draws as a plain PDF: a\n * picture of an invoice handed over as though it were one. Every way to\n * nothing records an error first, so that is a defect, and throws.\n */\nexport function eInvoiceFile(render: Render, resolved: ResolvedInvoice, invoice: EInvoice): EInvoiceFile | undefined {\n if (render.preview) {\n render.problems.warn({ stage: 'resolve', code: 'e-invoice-preview', path: '/eInvoice', message: `the e-invoice: ${PREVIEWED}` })\n return undefined\n }\n if (render.problems.failed) return undefined\n if (resolved.written === undefined) throw new RangeError('a final render of an e-invoice wrote no XML and recorded no reason: a defect, refused rather than drawn as a plain PDF')\n const profile = FACTUR_X_PROFILES[invoice.profile]\n return { xml: ciiXml(resolved.written), fileName: FACTUR_X.fileName, relationship: profile.relationship, conformanceLevel: profile.conformanceLevel }\n}\n","/**\n * A payment code printed with an e-invoice -- the QR-bill, an EPC QR code\n * -- held to it once both have resolved: it asks for the amount due for\n * payment (BT-115), or leaves the amount to the payer, and to be paid to\n * the e-invoice's payment account (BT-84).\n *\n * The page and the XML are one invoice, or the page is a second one: a\n * picture that asks for another amount or another account than its\n * structured part says may count as a further invoice under § 14c UStG\n * (BMF, 15 October 2025, UStAE 14c.1 (4a)). report-spec refuses what a\n * template's literals break, its currency among them; what only the data\n * decides -- an amount is always an expression, an account may be read\n * from a field -- is compared here, by value, the account as each code's\n * own rule wrote it: its spaces dropped and its letters capitals. A code\n * whose amount or account its own rules refused is not compared again.\n */\nimport { compareDecimal } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport type { Render } from './render-context.js'\n\n/** A payment code, as a refusal names it, and where its amount and its account stand. */\nexport interface PayingCode {\n /** \"the payment part\", \"component pay-code\". */\n readonly said: string\n /** \"the QR-bill\", \"the EPC QR code\". */\n readonly code: string\n readonly componentId?: string\n readonly amountPath: string\n readonly accountPath: string\n}\n\n/**\n * Records what `code`, which asks for `amount` -- null to leave it to the\n * payer -- to `account`, asks for that the e-invoice does not name; nothing\n * in a report that is no e-invoice, or where the e-invoice's account was\n * refused or a preview lacks it.\n */\nexport function checkPayable(render: Render, code: PayingCode, amount: Decimal | null, account: string): void {\n const payable = render.invoice?.payable\n if (payable === undefined) return\n const refuse = (path: string, message: string): void =>\n render.problems.error({ stage: 'resolve', code: 'invalid-e-invoice', path, message: `${code.said}: ${message}`, ...(code.componentId === undefined ? {} : { componentId: code.componentId }) })\n if (amount !== null && compareDecimal(amount, payable.amount) !== 0) {\n refuse(code.amountPath, `${code.code} asks for another amount than the e-invoice's amount due for payment (BT-115): a page and its XML ask for one amount`)\n }\n if (payable.account !== undefined && account !== payable.account) {\n refuse(code.accountPath, `${code.code} asks to be paid to another account than the e-invoice's payment account (BT-84): a page and its XML name one account`)\n }\n}\n","/**\n * A Swiss QR-bill made from values SIX's rules have accepted: the Swiss QR\n * Code's payload, and every text its slip prints.\n *\n * The rules a value is held to are report-spec's (`qr-bill.ts` there), one\n * set for a literal at validation and for a value from data here. What is\n * the runtime's alone is what a checked bill becomes:\n *\n * - **The payload**, in the order of IG Table 8, each element on its line.\n * - **The printed values**, grouped as the slip prints them (IG 3.5, 3.6).\n * - **The headings**, in the slip's language (IG Annex C).\n *\n * Nothing here reads a value as a number: an amount's digits are grouped\n * as text. \"IG\" is SIX's Swiss Implementation Guidelines for the QR-bill,\n * version 2.4 of 24 February 2026, whose payload, printing rules and\n * headings are version 2.3's, but for the Romansh headings it adds.\n */\nimport { QR_BILL_ADDRESS_RULES } from '@formancy/report-spec'\nimport type { QrBillAccount, QrBillAddress, QrBillCurrency, QrBillLanguage, QrBillReference } from '@formancy/report-spec'\nimport type { QrBill, QrBillHeadings } from './document.js'\n\n/** A party's address as SIX's rules accepted it: each part without the blanks around it, a part absent as ''. */\nexport type CheckedAddress = { readonly [P in keyof QrBillAddress]-?: string }\n\n/** A bill whose every text SIX's rules accepted, each as the code holds it. */\nexport interface CheckedQrBill {\n readonly language: QrBillLanguage\n readonly account: QrBillAccount\n readonly creditor: CheckedAddress\n readonly currency: QrBillCurrency\n /** As the code writes it: \"1949.75\"; null leaves it to the payer. */\n readonly amount: string | null\n /** Null leaves the field for the payer's name and address. */\n readonly debtor: CheckedAddress | null\n /** Null is a bill without one: NON. */\n readonly reference: QrBillReference | null\n /** '' for none. */\n readonly message: string\n /** '' for none. */\n readonly billingInformation: string\n}\n\n/** What the slip's headings say, before the payer's heading is chosen by whether the bill has a debtor. */\ntype Words = Omit<QrBillHeadings, 'payableBy'> & { readonly payableBy: string; readonly payableByBlank: string }\n\n/**\n * IG Annex C, Table 23, version 2.4, read in its PDF's text. Version 2.3's\n * English table printed Italian's currency as \"Value date\" and two French\n * words wrongly, which version 2.4 and the French edition correct; and\n * version 2.4 adds Romansh, in force since 1 January 2026.\n */\nconst HEADINGS: { readonly [L in QrBillLanguage]: Words } = {\n de: {\n paymentPart: 'Zahlteil',\n receipt: 'Empfangsschein',\n account: 'Konto / Zahlbar an',\n reference: 'Referenz',\n additionalInformation: 'Zusätzliche Informationen',\n payableBy: 'Zahlbar durch',\n payableByBlank: 'Zahlbar durch (Name/Adresse)',\n currency: 'Währung',\n amount: 'Betrag',\n acceptancePoint: 'Annahmestelle',\n separate: 'Vor der Einzahlung abzutrennen',\n },\n fr: {\n paymentPart: 'Section paiement',\n receipt: 'Récépissé',\n account: 'Compte / Payable à',\n reference: 'Référence',\n additionalInformation: 'Informations supplémentaires',\n payableBy: 'Payable par',\n payableByBlank: 'Payable par (nom/adresse)',\n currency: 'Monnaie',\n amount: 'Montant',\n acceptancePoint: 'Point de dépôt',\n separate: 'A détacher avant le versement',\n },\n it: {\n paymentPart: 'Sezione pagamento',\n receipt: 'Ricevuta',\n account: 'Conto / Pagabile a',\n reference: 'Riferimento',\n additionalInformation: 'Informazioni supplementari',\n payableBy: 'Pagabile da',\n payableByBlank: 'Pagabile da (nome/indirizzo)',\n currency: 'Valuta',\n amount: 'Importo',\n acceptancePoint: 'Punto di accettazione',\n separate: 'Da staccare prima del versamento',\n },\n en: {\n paymentPart: 'Payment part',\n receipt: 'Receipt',\n account: 'Account / Payable to',\n reference: 'Reference',\n additionalInformation: 'Additional information',\n payableBy: 'Payable by',\n payableByBlank: 'Payable by (name/address)',\n currency: 'Currency',\n amount: 'Amount',\n acceptancePoint: 'Acceptance point',\n separate: 'Separate before paying in',\n },\n rm: {\n paymentPart: 'Part da pajament',\n receipt: 'Quittanza',\n account: 'Conto / Da pajar a',\n reference: 'Referenza',\n additionalInformation: 'Infurmaziuns supplementaras',\n payableBy: 'Da pajar da',\n payableByBlank: 'Da pajar da (num/adressa)',\n currency: 'Valuta',\n amount: 'Import',\n acceptancePoint: 'Post da recepziun',\n separate: 'Da distatgar avant che pajar',\n },\n}\n\n/** An address's parts in the order the code holds them, which report-spec's table of their rules is in. */\nconst ADDRESS_PARTS = Object.keys(QR_BILL_ADDRESS_RULES) as readonly (keyof QrBillAddress)[]\n\n/** A party's seven lines (IG Table 8): the structured address type, S, and its parts; none at all, seven empty lines. */\nfunction party(address: CheckedAddress | null): string[] {\n return address === null ? ['', ...ADDRESS_PARTS.map(() => '')] : ['S', ...ADDRESS_PARTS.map((part) => address[part])]\n}\n\n/**\n * The Swiss QR Code's text (IG 4.1.4, Table 8). Every element is on its\n * line, an empty one as an empty line, and the lines are separated by a\n * line feed, with none after the last. The ultimate creditor's lines are\n * empty: SIX keeps them for later use and they \"must not be filled in\".\n * Billing information, of status A, is left out when the bill has none:\n * nothing after it is ever used, since this format has no alternative\n * procedure. Version 0200 is the only one SIX allows in master version 02,\n * and coding 1 is UTF-8 restricted to the characters of IG 4.1.1.\n */\nfunction payload(bill: CheckedQrBill): string {\n return [\n 'SPC',\n '0200',\n '1',\n bill.account.iban,\n ...party(bill.creditor),\n ...party(null),\n bill.amount ?? '',\n bill.currency,\n ...party(bill.debtor),\n bill.reference?.type ?? 'NON',\n bill.reference?.reference ?? '',\n bill.message,\n 'EPD',\n ...(bill.billingInformation === '' ? [] : [bill.billingInformation]),\n ].join('\\n')\n}\n\n/** `text` in blocks of `size` characters from its start, the last block shorter. */\nfunction blocks(text: string, size: number): string {\n const parts: string[] = []\n for (let start = 0; start < text.length; start += size) parts.push(text.slice(start, start + size))\n return parts.join(' ')\n}\n\n/** A QR reference in two digits and five blocks of five; a creditor reference in blocks of four (IG 3.5.4). */\nfunction printedReference(reference: QrBillReference): string {\n const { type, reference: text } = reference\n return type === 'QRR' ? `${text.slice(0, 2)} ${blocks(text.slice(2), 5)}` : blocks(text, 4)\n}\n\n/** The amount with a space between each three digits before the point (IG 3.5.3: \"CHF 1 590.00\"), grouped as text. */\nfunction printedAmount(amount: string): string {\n const [whole = '', cents = ''] = amount.split('.')\n const groups: string[] = []\n for (let end = whole.length; end > 0; end -= 3) groups.unshift(whole.slice(Math.max(0, end - 3), end))\n return `${groups.join(' ')}.${cents}`\n}\n\n/**\n * An address as the slip prints it, as IG 3.5.4 and SIX's style guide show\n * it: the name; the street and building number, on one line; the postal\n * code and the town. The country is printed for a party outside\n * Switzerland, Liechtenstein one of them; the guidelines do not say how,\n * and it goes before the postal code, as in \"LI-9490 Vaduz\".\n */\nfunction printedAddress(address: CheckedAddress): string[] {\n const street = [address.street, address.buildingNumber].filter((part) => part !== '').join(' ')\n const country = address.country === 'CH' ? '' : `${address.country}-`\n return [address.name, ...(street === '' ? [] : [street]), `${country}${address.postalCode} ${address.town}`]\n}\n\n/** The document's bill: `bill`'s payload, and every text its slip prints, in its language. */\nexport function qrBillPart(bill: CheckedQrBill): QrBill {\n const { payableByBlank, payableBy, ...words } = HEADINGS[bill.language]\n return {\n kind: 'swissQrBill',\n payload: payload(bill),\n headings: { ...words, payableBy: bill.debtor === null ? payableByBlank : payableBy },\n account: blocks(bill.account.iban, 4),\n creditor: printedAddress(bill.creditor),\n reference: bill.reference === null ? null : printedReference(bill.reference),\n additionalInformation: [bill.message, bill.billingInformation].filter((text) => text !== ''),\n debtor: bill.debtor === null ? null : printedAddress(bill.debtor),\n currency: bill.currency,\n amount: bill.amount === null ? null : printedAmount(bill.amount),\n }\n}\n","/**\n * A report's payment part lowered to the document's: each text read in the\n * report's scope, held to SIX's rules, and made into the bill\n * (`qr-bill.ts`).\n *\n * - **Read as a paragraph.** Every text is its runs, read as a paragraph's\n * in the report's scope and joined as a QR code's content is\n * (`joinedText`): a final render refuses a run whose value is null, as\n * `no-qr-value`, since the bill's code would say less than its texts.\n * - **Held to SIX's rules.** report-spec's checks, the very functions its\n * validator applies to a literal, are applied to every text once it has\n * resolved: a literal passes again, and a value from data is held where\n * the validator could not see it. A rule broken is `invalid-qr-bill` on\n * the field, naming the rule and never the value, which may be a\n * person's name or account.\n * - **The same in a preview.** A preview prints a value that is null, or\n * one its data lacks, as nothing, as a paragraph does; the bill that\n * leaves is held to the same rules, and refused where it breaks one,\n * saying the preview had no value for it. A bill SIX refuses cannot be\n * drawn as one: its code would scan as a bill no bank pays.\n * - **The amount** is a decimal, or null for the payer to fill in. Any\n * other value is refused by its type, and a decimal is written with its\n * own digits, never rounded: one with more than two places is refused.\n * - **Printed with an e-invoice**, it asks for the amount due and to be\n * paid to the e-invoice's account (`e-invoice-payable.ts`).\n */\nimport { decimalFromString, decimalToString } from '@formancy/expressions'\nimport {\n checkQrBillAccount,\n checkQrBillAdditionalInformation,\n checkQrBillAmount,\n checkQrBillReference,\n checkQrBillText,\n QR_BILL_ADDRESS_RULES,\n QR_BILL_BILLING_RULE,\n QR_BILL_MESSAGE_RULE,\n qrBillPairing,\n} from '@formancy/report-spec'\nimport type { Expression, Inline, PaymentPart, PaymentPartKind, QrBillAddress, QrBillCheck, QrBillTextRule, SwissQrBill } from '@formancy/report-spec'\nimport type { QrBill } from './document.js'\nimport { checkPayable } from './e-invoice-payable.js'\nimport { joinedText } from './inlines.js'\nimport type { Encoder } from './inlines.js'\nimport { qrBillPart } from './qr-bill.js'\nimport type { CheckedAddress } from './qr-bill.js'\nimport { reportScope, valueOf } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\n\nconst PATH = '/paymentPart'\n\n/** What an error in the payment part names it by: it stands in no component. */\nconst PART: Encoder = { said: 'the payment part', code: 'a QR-bill' }\n\n/** What lowering one bill reads, and records its errors in. */\ninterface Lowering {\n readonly render: Render\n readonly scope: Scope\n}\n\nfunction refuse({ render }: Lowering, path: string, message: string): undefined {\n render.problems.error({ stage: 'resolve', code: 'invalid-qr-bill', path, message })\n return undefined\n}\n\n/**\n * The text the runs at `path` print, held to `check`, as `what` names it in\n * an error: what the check made of it, or undefined when a run or the rule\n * refused it, which is recorded. Absent runs print nothing, which the rule\n * judges: an optional text, nothing; a required one, empty.\n */\nfunction checked<T>(lowering: Lowering, runs: readonly Inline[] | undefined, path: string, what: string, check: (text: string) => QrBillCheck<T>): T | undefined {\n const joined = joinedText(lowering.render, lowering.scope, runs ?? [], path, PART)\n if (joined === undefined) return undefined\n const outcome = check(joined.text)\n if (outcome.ok) return outcome.value\n return refuse(lowering, path, `${what} ${outcome.rule}${joined.lacking ? '; this preview has no value for a run of it' : ''}`)\n}\n\nconst ADDRESS_PARTS = Object.entries(QR_BILL_ADDRESS_RULES) as readonly (readonly [keyof QrBillAddress, QrBillTextRule])[]\n\n/** A party's address, each part held to its rule; undefined when a part is refused, which is recorded. */\nfunction address(lowering: Lowering, value: QrBillAddress, path: string, party: 'creditor' | 'debtor'): CheckedAddress | undefined {\n const parts: Partial<Record<keyof QrBillAddress, string>> = {}\n let whole = true\n for (const [part, rule] of ADDRESS_PARTS) {\n const text = checked(lowering, value[part], `${path}/${part}`, `the ${party}'s ${rule.said}`, (each) => checkQrBillText(each, rule))\n if (text === undefined) whole = false\n else parts[part] = text\n }\n return whole ? (parts as CheckedAddress) : undefined\n}\n\n/** The amount as the code writes it, null for the payer to fill in, or undefined when it is refused, which is recorded. */\nfunction amount(lowering: Lowering, expression: Expression | undefined): string | null | undefined {\n if (expression === undefined) return null\n const path = `${PATH}/amount`\n const value = valueOf(lowering.render, lowering.scope, `${path}/cel`)\n if (value === undefined || value === null) return value\n if (value.type !== 'decimal') return refuse(lowering, path, `the amount gives ${value.type}, and a QR-bill's amount is a decimal, or null to leave it for the payer`)\n const outcome = checkQrBillAmount(decimalToString(value.value))\n return outcome.ok ? outcome.value : refuse(lowering, path, `the amount ${outcome.rule}`)\n}\n\n/** `bill`, resolved and held to SIX's rules; undefined when anything of it is refused, which is recorded. */\nfunction swissQrBill(lowering: Lowering, bill: SwissQrBill): QrBill | undefined {\n const account = checked(lowering, bill.account, `${PATH}/account`, 'the account', checkQrBillAccount)\n const creditor = address(lowering, bill.creditor, `${PATH}/creditor`, 'creditor')\n const sum = amount(lowering, bill.amount)\n const debtor = bill.debtor === undefined ? null : address(lowering, bill.debtor, `${PATH}/debtor`, 'debtor')\n const reference = bill.reference === undefined ? null : checked(lowering, bill.reference, `${PATH}/reference`, 'the reference', checkQrBillReference)\n const message = checked(lowering, bill.message, `${PATH}/message`, 'the message', (text) => checkQrBillText(text, QR_BILL_MESSAGE_RULE))\n const billing = checked(lowering, bill.billingInformation, `${PATH}/billingInformation`, 'the billing information', (text) => checkQrBillText(text, QR_BILL_BILLING_RULE))\n // What two texts break together, each already held to its own rules.\n const together = message === undefined || billing === undefined ? undefined : checkQrBillAdditionalInformation(message, billing)\n if (together !== undefined) refuse(lowering, `${PATH}/message`, together)\n if (account !== undefined && sum !== undefined) {\n const asked = { said: PART.said, code: 'the QR-bill', amountPath: `${PATH}/amount`, accountPath: `${PATH}/account` }\n checkPayable(lowering.render, asked, sum === null ? null : decimalFromString(sum), account.iban)\n }\n const pairing = account === undefined || reference === undefined ? [] : qrBillPairing(account.qrIban ? 'qrIban' : 'iban', reference?.type ?? 'NON', bill.currency)\n for (const { field, rule } of pairing) refuse(lowering, `${PATH}/${field}`, rule)\n if (together !== undefined || pairing.length > 0) return undefined\n if (account === undefined || creditor === undefined || sum === undefined || debtor === undefined || reference === undefined || message === undefined || billing === undefined) return undefined\n return qrBillPart({ language: bill.language, account, creditor, currency: bill.currency, amount: sum, debtor, reference, message, billingInformation: billing })\n}\n\ntype PartLowerer<K extends PaymentPartKind> = (lowering: Lowering, part: Extract<PaymentPart, { kind: K }>) => QrBill | undefined\n\n/** How each kind of payment part is lowered. A table over every kind, so a kind added to report-spec without a way down does not compile. */\nconst PARTS: { readonly [K in PaymentPartKind]: PartLowerer<K> } = {\n swissQrBill,\n}\n\n/** `render`'s payment part, lowered; undefined when the report has none, or when it is refused, which is recorded. */\nexport function lowerPaymentPart(render: Render): QrBill | undefined {\n const part = render.report.paymentPart\n if (part === undefined) return undefined\n return PARTS[part.kind]({ render, scope: reportScope(render, render.totals.report) }, part)\n}\n","/**\n * An image component lowered to the bytes it draws.\n *\n * An image shows an asset the template pins, or an image field of the\n * header dataset (0007). Either way it names an approved asset by its id\n * and digest, and the host's lookup hands over the bytes: the runtime never\n * follows an address and fetches nothing. What comes back is checked here --\n * bytes, and a media type a report may draw, the one the template declares\n * for its own asset -- and copied, so that nothing the host changes\n * afterwards reaches the document. Whether the bytes are a picture is the\n * renderer's to say (`invalid-asset`): for an SVG, whether they are exactly\n * the drawing report-spec's `cleanSvg` writes, by report-spec's `checkSvg`,\n * which the renderer applies (0030).\n *\n * The lookup is trusted to return the bytes the digest pins, and they are\n * not checked against it. Not for want of a hash: a pure SHA-256 reaches the\n * runtime through `@formancy/spec`, and checking digests is a decision of\n * its own, since it changes what every host's resolver must satisfy (0030).\n *\n * An image field with no value draws nothing, and its box is kept as space,\n * so that what follows it stands where it would with a picture: null prints\n * as nothing (0007), and nothing moves.\n *\n * Each approved asset is asked for once per render, and every image that\n * draws it shares the one copy, so that a logo on every page header, or a\n * photo drawn by forty components, is held once: a PNG or a JPEG is\n * embedded once, and an SVG is drawn again wherever it prints, on every\n * page of a page region (0030). An answer past its type's limit --\n * `MAX_ASSET_BYTES`, or `MAX_SVG_BYTES` for an SVG -- is refused before it\n * is copied.\n */\nimport { ASSET_MEDIA_TYPES, MAX_ASSET_BYTES, MAX_SVG_BYTES } from '@formancy/report-spec'\nimport type { AssetMediaType, ImageComponent } from '@formancy/report-spec'\nimport type { Image, ImageAsset, Spacer } from './document.js'\nimport { imageValue } from './render-context.js'\nimport type { ImageBytes, ImageRef, Render } from './render-context.js'\nimport type { ResolveErrorCode } from './resolve-errors.js'\n\n/** Why an asset's bytes could not be had: the code, and what to say after the component's id. */\ninterface Refusal {\n readonly code: ResolveErrorCode\n readonly message: string\n}\n\n/** What the host handed over, if it is bytes of a media type a report draws, within the limit: copied. A string says why it is not. */\nfunction checkedBytes(found: unknown, declared: AssetMediaType | undefined): { readonly mediaType: AssetMediaType; readonly bytes: Uint8Array } | string {\n const media = `is not bytes of ${declared === undefined ? ASSET_MEDIA_TYPES.join(' or ') : declared}`\n if (typeof found !== 'object' || found === null) return media\n const { mediaType, bytes } = found as Partial<ImageBytes>\n if (!(bytes instanceof Uint8Array) || !ASSET_MEDIA_TYPES.includes(mediaType as AssetMediaType)) return media\n if (declared !== undefined && mediaType !== declared) return media\n if (mediaType === 'image/svg+xml' && bytes.length > MAX_SVG_BYTES) return `is ${bytes.length} bytes; an SVG asset may have ${MAX_SVG_BYTES} (1 MiB)`\n if (bytes.length > MAX_ASSET_BYTES) return `is ${bytes.length} bytes; an asset may have ${MAX_ASSET_BYTES} (20 MB)`\n return { mediaType: mediaType as AssetMediaType, bytes: new Uint8Array(bytes) }\n}\n\n/** The bytes of `ref`, asked of the host and checked, or why they could not be had. */\nfunction fetched(render: Render, ref: ImageRef, declared: AssetMediaType | undefined): ImageAsset | Refusal {\n if (render.images === undefined) return { code: 'missing-asset', message: 'the report draws an image, and the host gave no way to fetch approved assets' }\n let found: unknown\n let bytes: ReturnType<typeof checkedBytes>\n try {\n // The answer is read inside the guard too: a getter on it is the host's code, and may throw.\n found = render.images(ref)\n bytes = checkedBytes(found, declared)\n } catch {\n return { code: 'asset-lookup-failed', message: `fetching the approved asset ${ref.asset} failed` }\n }\n if (found === undefined) return { code: 'missing-asset', message: `the host has no bytes for the approved asset ${ref.asset} at its digest` }\n if (typeof bytes === 'string') return { code: 'invalid-asset', message: `the host's answer for the approved asset ${ref.asset} ${bytes}` }\n return { id: ref.asset, ...bytes }\n}\n\n/** Each render's assets, by id, digest and the type declared for them: asked for once, and shared. */\nconst ASSETS = new WeakMap<Render, Map<string, ImageAsset | Refusal>>()\n\nfunction assetOf(render: Render, ref: ImageRef, declared: AssetMediaType | undefined): ImageAsset | Refusal {\n const cache = ASSETS.get(render) ?? new Map<string, ImageAsset | Refusal>()\n ASSETS.set(render, cache)\n const key = JSON.stringify([ref.asset, ref.digest, declared ?? null])\n const known = cache.get(key)\n if (known !== undefined) return known\n const asset = fetched(render, ref, declared)\n cache.set(key, asset)\n return asset\n}\n\n/** `component`, at `path`, as the image it draws, the space it keeps when its field is null, or undefined when its bytes could not be had, which is recorded. */\nexport function imageBlock(render: Render, component: ImageComponent, path: string): Image | Spacer | undefined {\n const { source } = component\n let ref: ImageRef\n let declared: AssetMediaType | undefined\n if (source.kind === 'asset') {\n // report-spec refuses an image of an asset the report does not declare.\n const asset = render.report.assets.find(({ id }) => id === source.asset) as { readonly id: string; readonly mediaType: AssetMediaType; readonly digest: string }\n ref = { asset: asset.id, digest: asset.digest }\n declared = asset.mediaType\n } else {\n const value = imageValue(render, source.field)\n if (value === null) return { kind: 'spacer', height: component.height }\n ref = { asset: value.asset, digest: value.digest }\n }\n const asset = assetOf(render, ref, declared)\n if ('code' in asset) {\n render.problems.error({ stage: 'resolve', code: asset.code, path: `${path}/source`, message: `component ${component.id}: ${asset.message}`, componentId: component.id })\n return undefined\n }\n return { kind: 'image', asset, width: component.width, height: component.height, fit: component.fit }\n}\n","/**\n * An EPC QR code lowered to the document's block: each text read in the\n * report's scope, held to the EPC's rules, and written into the payload the\n * renderer encodes. \"EPC\" is EPC069-12, version 3.1, by its section.\n *\n * - **Read as a paragraph.** Every text is its runs, read as a paragraph's\n * in the report's scope and joined as a QR code's content is\n * (`joinedText`): a final render refuses a run whose value is null, as\n * `no-qr-value`, since the transfer would say less than the invoice --\n * unless the text is optional and prints nothing else.\n * - **Held to the EPC's rules.** report-spec's checks (`epc-payload.ts`),\n * the very functions its validator applies to a literal, are applied to\n * every text once it has resolved: a literal passes again, and a value\n * from data is held where the validator could not see it -- the IBAN's\n * spaces dropped and its letters made capitals, its country's, its\n * length and its check digits; the BIC, and whether the account needs\n * one; the creditor reference; each text's characters and length. A rule\n * broken is `invalid-epc-qr-code` on the field, naming the code and the\n * rule and never the value, which may be a person's name or account.\n * - **An optional text that prints nothing is unused.** A BIC, a\n * reference, a text or information the data gives empty, blank or null\n * is an element the code leaves empty, as one the template does not\n * have, in a final render as in a preview: a customer with no BIC on\n * record is paid by version 002, never refused for a BIC that is no BIC.\n * The validator refuses a blank literal instead, a second spelling of an\n * element left out.\n * - **The same in a preview.** A preview prints a value that is null, or\n * one its data lacks, as nothing, as a paragraph does; the code that\n * leaves is held to the same rules, and refused where it breaks one,\n * saying the preview had no value for it. A code the EPC refuses cannot\n * be drawn as one: it would scan as a transfer no bank makes.\n * - **The amount** is a decimal, or null for the payer to fill in. Any\n * other value is refused by its type, and a decimal is written with its\n * own digits, as short as it can be, never rounded: one with more than\n * two places is refused.\n * - **The payload** is report-spec's `epcPayload` of the checked texts,\n * held to the EPC's 331 bytes in UTF-8, which only the whole can break.\n * - **Printed with an e-invoice**, it asks for the amount due and to be\n * paid to the e-invoice's account (`e-invoice-payable.ts`).\n */\nimport { decimalFromString, decimalToString } from '@formancy/expressions'\nimport { checkEpcAmount, checkEpcField, checkEpcPayload, EPC_TEXT_FIELDS, epcBlank, epcPairing, epcPayload } from '@formancy/report-spec'\nimport type { EpcQrCodeComponent, EpcTextField } from '@formancy/report-spec'\nimport type { EpcQrCode } from './document.js'\nimport { checkPayable } from './e-invoice-payable.js'\nimport { joinedText } from './inlines.js'\nimport type { Encoder } from './inlines.js'\nimport { valueOf } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\n\n/** What a refusal adds when a preview had no value for a run of the text it refuses. */\nconst LACKED = '; this preview has no value for a run of it'\n\n/** What lowering one code reads, and records its errors in. */\ninterface Lowering {\n readonly render: Render\n readonly scope: Scope\n readonly code: EpcQrCodeComponent\n readonly path: string\n readonly encoder: Encoder\n}\n\nfunction refuse({ render, code, encoder }: Lowering, path: string, message: string): undefined {\n render.problems.error({ stage: 'resolve', code: 'invalid-epc-qr-code', path, message: `${encoder.said}: ${message}`, componentId: code.id })\n return undefined\n}\n\n/** A text as its rule made it, '' for an element the code leaves unused, and whether a preview lacked a value for a run of it. */\ninterface Checked {\n readonly text: string\n readonly lacking: boolean\n}\n\n/**\n * The text `key` of the code, resolved and held to its field's rule\n * (report-spec's `EPC_TEXT_FIELDS`); undefined when a run or the rule\n * refused it, which is recorded. An optional text that prints nothing a\n * payer reads (`epcBlank`), nulls and all, is its element unused, and no\n * rule is asked.\n */\nfunction checked(lowering: Lowering, key: EpcTextField): Checked | undefined {\n const runs = lowering.code[key]\n if (runs === undefined) return { text: '', lacking: false }\n const path = `${lowering.path}/${key}`\n const { what, optional } = EPC_TEXT_FIELDS[key]\n const joined = joinedText(lowering.render, lowering.scope, runs, path, lowering.encoder, optional ? epcBlank : undefined)\n if (joined === undefined) return undefined\n if (optional && epcBlank(joined.text)) return { text: '', lacking: joined.lacking }\n const outcome = checkEpcField(key, joined.text)\n if (outcome.ok) return { text: outcome.value, lacking: joined.lacking }\n return refuse(lowering, path, `${what} ${outcome.rule}${joined.lacking ? LACKED : ''}`)\n}\n\n/** The amount as the code writes it after `EUR`, '' for the payer to fill in, or undefined when it is refused, which is recorded. */\nfunction amount(lowering: Lowering): string | undefined {\n if (lowering.code.amount === undefined) return ''\n const path = `${lowering.path}/amount`\n const value = valueOf(lowering.render, lowering.scope, `${path}/cel`)\n if (value === undefined) return undefined\n if (value === null) return ''\n if (value.type !== 'decimal') return refuse(lowering, path, `the amount gives ${value.type}, and an EPC QR code's amount is a decimal in euro, or null to leave it for the payer`)\n const outcome = checkEpcAmount(decimalToString(value.value))\n return outcome.ok ? outcome.value : refuse(lowering, path, `the amount ${outcome.rule}`)\n}\n\n/**\n * The block the EPC QR code `code`, at `path`, prints, read in `scope`;\n * undefined when anything of it is refused, which is recorded. Every text\n * is read and every rule broken said, not the first alone.\n */\nexport function epcQrCodeBlock(render: Render, scope: Scope, code: EpcQrCodeComponent, path: string): EpcQrCode | undefined {\n const lowering: Lowering = { render, scope, code, path, encoder: { said: `component ${code.id}`, componentId: code.id, code: 'an EPC QR code' } }\n const bic = checked(lowering, 'bic')\n const beneficiary = checked(lowering, 'beneficiary')\n const iban = checked(lowering, 'iban')\n const sum = amount(lowering)\n const reference = checked(lowering, 'reference')\n const text = checked(lowering, 'text')\n const information = checked(lowering, 'information')\n // What the IBAN and the BIC break together, each already held to its own rules: a BIC that prints nothing is none.\n const pairing = epcPairing(iban?.text, bic === undefined ? undefined : bic.text === '' ? null : bic.text)\n for (const { field, rule } of pairing) refuse(lowering, `${path}/${field}`, `${rule}${bic?.lacking === true ? LACKED : ''}`)\n if (iban !== undefined && sum !== undefined) {\n const asked = { said: lowering.encoder.said, code: 'the EPC QR code', componentId: code.id, amountPath: `${path}/amount`, accountPath: `${path}/iban` }\n checkPayable(render, asked, sum === '' ? null : decimalFromString(sum), iban.text)\n }\n if (pairing.length > 0 || bic === undefined || beneficiary === undefined || iban === undefined || sum === undefined || reference === undefined || text === undefined || information === undefined) return undefined\n const payload = epcPayload({\n bic: bic.text,\n beneficiary: beneficiary.text,\n iban: iban.text,\n amount: sum,\n purpose: code.purpose,\n reference: reference.text,\n text: text.text,\n information: information.text,\n })\n const bytes = checkEpcPayload(payload)\n if (!bytes.ok) return refuse(lowering, path, `its payload ${bytes.rule}`)\n return { kind: 'epcQrCode', id: code.id, payload, size: code.size, ...(code.caption === undefined ? {} : { caption: code.caption }) }\n}\n","/**\n * Print styles resolved to the one style each piece of text prints in.\n *\n * report-spec's styles are tokens (0007); here they are laid over each other\n * once, and the document carries the result, so an engine never merges\n * styles (`TextStyle`). The order, each later one's property winning:\n *\n * 1. what the component stands in passes down: a section's, a columns\n * block's or a keep-together block's style is the base of the text\n * inside it;\n * 2. the component's own `style`;\n * 3. each of its `styleWhen` rules that holds, in order.\n *\n * In a table, the table's resolved style is the base of every row: the\n * header's `headerStyle`, a group header's, a footer row's own, and each\n * column's style and rules over a detail cell. An image, a QR code, a line,\n * a rectangle, a spacer and a page break print no text; a style on one is\n * read for its rules' conditions, and changes nothing.\n */\nimport type { PrintStyle, StyleRule } from '@formancy/report-spec'\nimport type { TextStyle } from './document.js'\nimport { holds } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\n\n/** Each print style as the document's: the same tokens without the id. */\nexport function documentStyles(styles: readonly PrintStyle[]): ReadonlyMap<string, TextStyle> {\n return new Map(styles.map(({ id, ...style }) => [id, style]))\n}\n\n/** `styles` laid over each other, a later one's property winning; undefined when none sets anything. */\nexport function layered(...styles: readonly (TextStyle | undefined)[]): TextStyle | undefined {\n const merged: TextStyle = Object.assign({}, ...styles.filter((style) => style !== undefined)) as TextStyle\n return Object.keys(merged).length === 0 ? undefined : merged\n}\n\n/**\n * `base`, then the print style `style` names, then each rule at\n * `<path>/<index>` whose condition holds in `scope`. Undefined when nothing\n * sets anything, or when a condition failed, which is recorded.\n */\nexport function styled(render: Render, scope: Scope, base: TextStyle | undefined, style: string | undefined, rules: readonly StyleRule[] | undefined, path: string): TextStyle | undefined {\n const held: TextStyle[] = []\n for (const [index, rule] of (rules ?? []).entries()) {\n if (holds(render, scope, `${path}/${index}/when/cel`) === true) held.push(render.styles.get(rule.style) as TextStyle)\n }\n return layered(base, style === undefined ? undefined : render.styles.get(style), ...held)\n}\n","/**\n * The table over the detail dataset, lowered to the rows it prints.\n *\n * Its rows are ordered and grouped by `sort-group.ts` (0007): the group's\n * key first, then the sort keys, ties in the provider's order. Then, in\n * that order:\n *\n * - for each group, one line across the table read in the group's scope,\n * its rows, and its footer rows, whose aggregates are the group's;\n * - the totals rows, whose aggregates are over every row;\n * - with no detail rows, the table's empty text in their place, and its\n * totals still printed: a count and a sum of nothing are 0.\n *\n * A column whose condition does not hold is left out, read once per report:\n * its header, every cell under it and its footer cells, and the fill columns\n * share its width. A table every column of which is hidden prints nothing.\n * Each detail cell is read in its row's scope, its column's style rules too;\n * every other row has one style.\n */\nimport type { TableColumn as ReportColumn, TableComponent, TableFooterRow } from '@formancy/report-spec'\nimport type { Table, TableRow, TextStyle } from './document.js'\nimport { runOf, textOfRuns } from './inlines.js'\nimport { groupScope, holds, reportScope, rowScope } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\nimport { orderTable } from './sort-group.js'\nimport type { OrderedRow } from './sort-group.js'\nimport { layered, styled } from './styles.js'\n\n/** A column that prints, and where it stands in the report's list of the table's columns. */\ninterface Shown {\n readonly column: ReportColumn\n readonly index: number\n}\n\n/** What every row of one table is read with. */\ninterface Lowering {\n readonly render: Render\n readonly table: TableComponent\n readonly path: string\n readonly shown: readonly Shown[]\n /** The table's own style, laid under every row's. */\n readonly base: TextStyle | undefined\n}\n\n/** `style` as a row's: the table's under the named print style; absent when neither sets anything. */\nfunction rowStyle(lowering: Lowering, style: string | undefined): { readonly style?: TextStyle } {\n const resolved = layered(lowering.base, style === undefined ? undefined : lowering.render.styles.get(style))\n return resolved === undefined ? {} : { style: resolved }\n}\n\n/** One detail row: each shown column's value and own style, read in the row's scope. */\nfunction detailRow(lowering: Lowering, row: OrderedRow): TableRow {\n const { render, table, path } = lowering\n const scope = rowScope(render, render.totals.report, row)\n const cells = lowering.shown.map(({ column, index }) => {\n const run = runOf(render, scope, column.value, `${path}/columns/${index}/value`, { componentId: table.id, columnId: column.id })\n return run === undefined ? '' : textOfRuns([run])\n })\n const own = lowering.shown.map(({ column, index }) => styled(render, scope, undefined, column.style, column.styleWhen, `${path}/columns/${index}/styleWhen`))\n const cellStyles = own.some((style) => style !== undefined) ? { cellStyles: own.map((style) => (style === undefined ? null : (layered(lowering.base, style) as TextStyle))) } : {}\n return { kind: 'detail', cells, ...(lowering.base === undefined ? {} : { style: lowering.base }), ...cellStyles }\n}\n\n/** Footer rows read in `scope`: under a group, or under the table. A shown column without a cell in a row prints nothing there. */\nfunction footerRows(lowering: Lowering, rows: readonly TableFooterRow[] | undefined, at: string, kind: 'groupFooter' | 'total', scope: Scope): TableRow[] {\n const { render, table } = lowering\n return (rows ?? []).map((row, rowIndex) => {\n const cells = lowering.shown.map(({ column }) => {\n const cellIndex = row.cells.findIndex((cell) => cell.column === column.id)\n const cell = row.cells[cellIndex]\n if (cell === undefined) return ''\n const run = runOf(render, scope, cell.value, `${at}/${rowIndex}/cells/${cellIndex}/value`, { componentId: table.id, columnId: column.id })\n return run === undefined ? '' : textOfRuns([run])\n })\n return { kind, cells, ...rowStyle(lowering, row.style) }\n })\n}\n\n/** The rows of a table that groups: per group, its header line, its rows and its footer. */\nfunction groupedRows(lowering: Lowering, groups: NonNullable<ReturnType<typeof orderTable>['groups']>): TableRow[] {\n const { render, table, path } = lowering\n const group = table.group as NonNullable<TableComponent['group']>\n const rows: TableRow[] = []\n for (const each of groups) {\n if (render.problems.full) break\n const scope = groupScope(render, each, render.totals.over(each.rows), group.by.field)\n const runs = group.header.map((inline, index) => runOf(render, scope, inline, `${path}/group/header/${index}`, { componentId: table.id }))\n rows.push({ kind: 'groupHeader', cells: [textOfRuns(runs.filter((run) => run !== undefined))], across: true, ...rowStyle(lowering, group.headerStyle) })\n for (const row of each.rows) rows.push(detailRow(lowering, row))\n rows.push(...footerRows(lowering, group.footer, `${path}/group/footer`, 'groupFooter', scope))\n }\n return rows\n}\n\n/**\n * `table`, at `path`, as the document's table, `base` its own resolved\n * style; undefined when every column is hidden. A value that could not be\n * read prints nothing here, and is recorded as an error, so the report is\n * refused.\n */\nexport function tableBlock(render: Render, table: TableComponent, path: string, base: TextStyle | undefined): Table | undefined {\n const scope = reportScope(render, render.totals.report)\n const shown = table.columns\n .map((column, index) => ({ column, index }))\n .filter(({ column, index }) => column.visibleWhen === undefined || holds(render, scope, `${path}/columns/${index}/visibleWhen/cel`) === true)\n if (shown.length === 0) return undefined\n const lowering: Lowering = { render, table, path, shown, base }\n const ordered = orderTable(render.report, table, render.data.detail)\n const rows: TableRow[] = []\n if (ordered.groups !== undefined) rows.push(...groupedRows(lowering, ordered.groups))\n else {\n for (const row of ordered.rows) {\n if (render.problems.full) break\n rows.push(detailRow(lowering, row))\n }\n }\n rows.push(...footerRows(lowering, table.totals, `${path}/totals`, 'total', scope))\n const headerStyle = layered(base, table.headerStyle === undefined ? undefined : render.styles.get(table.headerStyle))\n return {\n kind: 'table',\n id: table.id,\n columns: shown.map(({ column }) => ({ width: column.width, align: column.align })),\n header: shown.map(({ column }) => column.header),\n ...(headerStyle === undefined ? {} : { headerStyle }),\n rows,\n emptyText: table.emptyText,\n }\n}\n","/**\n * A report's components lowered to the document's blocks, region by region.\n *\n * Every component is read in the report's scope: its condition first, and a\n * component whose condition does not hold prints nothing, nor does anything\n * inside it. Then its style (`styles.ts`), and then what it is. A kind maps\n * to a block through a table over every kind, so a kind added to the format\n * without a way down does not compile.\n *\n * The report header is the start of the body and the summary its end, so\n * the document has three regions: the page header and footer, repeated on\n * every page, and the body.\n */\nimport type { Component, ComponentKind, RegionName } from '@formancy/report-spec'\nimport type { Block, TextStyle } from './document.js'\nimport { imageBlock } from './images.js'\nimport { encodedText, runOf } from './inlines.js'\nimport { epcQrCodeBlock } from './lower-epc-qr-code.js'\nimport { tableBlock } from './lower-table.js'\nimport { holds, reportScope } from './render-context.js'\nimport type { Render, Scope } from './render-context.js'\nimport { styled } from './styles.js'\n\n/** The document's regions, lowered. */\nexport interface LoweredRegions {\n readonly pageHeader: readonly Block[]\n readonly pageFooter: readonly Block[]\n readonly body: readonly Block[]\n}\n\n/** What one component is lowered with: where it is, the report scope, and its resolved style. */\ninterface At {\n readonly render: Render\n readonly scope: Scope\n readonly path: string\n readonly style: TextStyle | undefined\n}\n\ntype Lowerer<K extends ComponentKind> = (component: Extract<Component, { kind: K }>, at: At) => Block | undefined\n\n/** `value` under `key` when it is defined: the document writes only what is set. */\nconst optional = <K extends string, V>(key: K, value: V | undefined): { [P in K]?: V } => (value === undefined ? {} : ({ [key]: value } as { [P in K]: V }))\n\nconst LOWER: { readonly [K in ComponentKind]: Lowerer<K> } = {\n text: (text, { render, scope, path, style }) => {\n const runs = text.content.flatMap((inline, index) => runOf(render, scope, inline, `${path}/content/${index}`, { componentId: text.id }) ?? [])\n return { kind: 'paragraph', runs, ...optional('style', style), ...(text.keepWithNext === true ? { keepWithNext: true } : {}) }\n },\n image: (image, { render, path }) => imageBlock(render, image, path),\n qrCode: (code, { render, scope, path }) => {\n const text = encodedText(render, scope, code.content, path, code.id)\n return text === undefined ? undefined : { kind: 'qrCode', id: code.id, text, size: code.size, errorCorrection: code.errorCorrection }\n },\n epcQrCode: (code, { render, scope, path }) => epcQrCodeBlock(render, scope, code, path),\n line: (line) => ({ kind: 'rule', thickness: line.thickness, ...optional('color', line.color) }),\n rectangle: (rectangle) => ({ kind: 'rectangle', width: rectangle.width, height: rectangle.height, ...optional('fill', rectangle.fill), ...optional('stroke', rectangle.stroke) }),\n spacer: (spacer) => ({ kind: 'spacer', height: spacer.height }),\n columns: (columns, { render, path, style }) => ({\n kind: 'columns',\n columns: columns.columns.map((slot, index) => ({ width: slot.width, blocks: blocksOf(render, slot.components, `${path}/columns/${index}/components`, style) })),\n }),\n section: (section, { render, path, style }) => ({\n kind: 'section',\n blocks: blocksOf(render, section.components, `${path}/components`, style),\n ...optional('border', section.border),\n ...optional('fill', section.fill),\n ...optional('padding', section.padding),\n }),\n table: (table, { render, path, style }) => tableBlock(render, table, path, style),\n pageBreak: () => ({ kind: 'pageBreak' }),\n keepTogether: (kept, { render, path, style }) => ({ kind: 'keepTogether', blocks: blocksOf(render, kept.components, `${path}/components`, style) }),\n}\n\n/** `component`, at `path`, as the block it prints; undefined when it prints nothing, or could not be lowered, which is recorded. */\nfunction blockOf(render: Render, component: Component, path: string, inherited: TextStyle | undefined): Block | undefined {\n const scope = reportScope(render, render.totals.report)\n if (component.visibleWhen !== undefined && holds(render, scope, `${path}/visibleWhen/cel`) !== true) return undefined\n const style = styled(render, scope, inherited, component.style, component.styleWhen, `${path}/styleWhen`)\n return (LOWER[component.kind] as Lowerer<ComponentKind>)(component as never, { render, scope, path, style })\n}\n\n/** The components of the list at `path`, in order, as the blocks they print. */\nfunction blocksOf(render: Render, components: readonly Component[], path: string, inherited: TextStyle | undefined): Block[] {\n return components.flatMap((component, index) => blockOf(render, component, `${path}/${index}`, inherited) ?? [])\n}\n\nfunction region(render: Render, name: RegionName): Block[] {\n return blocksOf(render, render.report.regions[name], `/regions/${name}`, undefined)\n}\n\n/** Every region of `render`'s report, lowered: the report header, body and summary as the one body. */\nexport function lowerRegions(render: Render): LoweredRegions {\n return {\n pageHeader: region(render, 'pageHeader'),\n pageFooter: region(render, 'pageFooter'),\n body: [...region(render, 'reportHeader'), ...region(render, 'body'), ...region(render, 'summary')],\n }\n}\n","/**\n * Whether a report can be rendered at all, before any data is read: the\n * first two levels of plan 15, structure and bindings.\n *\n * A report reaches the runtime as untrusted input, whatever its type says --\n * parsed from storage, posted by a browser. So it is validated again here,\n * with report-spec's `validateReport`, and what the runtime goes on to read\n * is the copy validation made, which no later change to the caller's object\n * reaches. Then its expressions are compiled with report-core, and a report\n * the editor's diagnostics give an error for is refused (0009): the runtime\n * never renders what the editor refuses.\n */\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { validateReport } from '@formancy/report-spec'\nimport { prepareExpressions } from './evaluate.js'\nimport type { ReportExpressions } from './evaluate.js'\nimport { fromDiagnostic, fromReport } from './resolve-errors.js'\nimport type { RuntimeError } from './resolve-errors.js'\n\nexport type ReportCheck =\n | { readonly ok: true; /** The copy validation read. */ readonly report: ReportDefinition; readonly expressions: ReportExpressions }\n | { readonly ok: false; readonly errors: readonly RuntimeError[] }\n\n/**\n * `report` validated and its expressions compiled for one render, or every\n * reason it is refused: each structural error, or, for a report that is\n * structurally valid, each diagnostic of severity error.\n */\nexport function checkReport(report: unknown): ReportCheck {\n const validation = validateReport(report)\n if (!validation.valid) return { ok: false, errors: validation.errors.map(fromReport) }\n const prepared = prepareExpressions(validation.report)\n if (!prepared.ok) return { ok: false, errors: prepared.diagnostics.map(fromDiagnostic) }\n return { ok: true, report: validation.report, expressions: prepared.expressions }\n}\n","/**\n * The report's aggregates, computed exactly, once, here (0007): over every\n * detail row for `totals`, and over a group's rows for `group`.\n *\n * - **In report-core's order.** An aggregate's expression may read another\n * aggregate's total, so each is computed after every one it reads, in the\n * order `compileReport` gives (0009); an aggregate that could never be\n * computed has already refused the report.\n * - **Each row read once.** What an aggregate reads from a row is read once\n * per render, with the report's totals, and kept by the row's index; a\n * group's aggregate is the same function over its rows' values. So a\n * group's subtotal and the report's total are totals of the same values,\n * and the subtotals of a sum that declares no rounding add up to the\n * total. A declared rounding is applied to each group's exact sum and to\n * the report's, once each, so rounded subtotals need not add up to the\n * rounded total: two groups of 0.02, rounded to 0.05, print 0.00 and 0.00\n * over 0.05.\n * - **Exact, and of one kind.** Integers as BigInt, decimals as `Decimal`,\n * through `decimal.ts`; nothing passes through a JavaScript number. A\n * total report-core compiled as a decimal is a decimal, its 0 too, and so\n * is one whose kind the compiler could not tell (`dyn`) once it declares a\n * rounding or meets a decimal; a group's total is of the report total's\n * kind, so an expression reading `group.<id>` meets one type.\n * - **Nulls are skipped**, and so is a value a preview's data lacks. Over no\n * values a count and a sum are 0 and the rest null (0007).\n * - **Declared rounding is applied once**, to the exact result: an average\n * always declares one, and a sum, a minimum or a maximum of decimals may.\n * A rounding on a total that is an integer or a moment is refused, never\n * ignored.\n */\nimport { compareDecimal, Decimal } from '@formancy/expressions'\nimport type { AggregateDef, Rounding } from '@formancy/report-spec'\nimport { averageDecimals, roundDecimalAs, sumDecimals } from './decimal.js'\nimport type { TypedValue } from './format.js'\nimport { fieldValue, rowScope, valueOf } from './render-context.js'\nimport type { AggregateValues, Render, Totals } from './render-context.js'\nimport type { ResolveErrorCode } from './resolve-errors.js'\nimport type { OrderedRow } from './sort-group.js'\nimport { fixedWidth } from './sort-group.js'\n\n/** Why a total has no value: its code and what to say. */\ninterface Refusal {\n readonly code: ResolveErrorCode\n readonly message: string\n}\n\ntype Total = TypedValue | null | Refusal\n\nconst isRefusal = (value: Total): value is Refusal => value !== null && 'code' in value\n\nconst integer = (value: bigint): TypedValue => ({ type: 'integer', value })\nconst decimal = (value: Decimal): TypedValue => ({ type: 'decimal', value })\nconst asDecimal = (value: TypedValue): Decimal => (value.type === 'integer' ? new Decimal(value.value, 0) : (value.value as Decimal))\n\n/** How one aggregate is totalled: its definition, whether its numbers are decimals whatever they hold, and the text order. */\ninterface Totalling {\n readonly aggregate: AggregateDef\n readonly decimals: boolean\n readonly collator: Intl.Collator\n}\n\n/** Values as numbers of one kind: integers while every one is and decimals are not asked for, else decimals; undefined when one is not a number. */\nfunction numbers(values: readonly TypedValue[], decimals: boolean): { readonly integers: readonly bigint[] } | { readonly decimals: readonly Decimal[] } | undefined {\n if (!decimals && values.every((value) => value.type === 'integer')) return { integers: values.map((value) => value.value as bigint) }\n if (!values.every((value) => value.type === 'integer' || value.type === 'decimal')) return undefined\n return { decimals: values.map(asDecimal) }\n}\n\nconst NOT_NUMBERS: Refusal = { code: 'aggregate-value-type', message: 'totals integers and decimals, and a value it read is neither' }\n\nfunction sum(values: readonly TypedValue[], decimals: boolean): Total {\n const read = numbers(values, decimals)\n if (read === undefined) return NOT_NUMBERS\n return 'integers' in read ? integer(read.integers.reduce((total, value) => total + value, 0n)) : decimal(sumDecimals(read.decimals))\n}\n\nfunction average(values: readonly TypedValue[], rounding: Rounding): Total {\n const read = numbers(values, true) as { readonly decimals: readonly Decimal[] } | undefined\n if (read === undefined) return NOT_NUMBERS\n const result = averageDecimals(read.decimals, rounding)\n return result === null ? null : decimal(result)\n}\n\nconst ordered = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0)\n\n/** -1, 0 or 1 for two values of one kind: numbers by value, text as the report's language sorts it, dates as days, moments in time order. */\nfunction comparator(values: readonly TypedValue[], collator: Intl.Collator): ((a: TypedValue, b: TypedValue) => number) | undefined {\n const types = new Set(values.map(({ type }) => type))\n if ([...types].every((type) => type === 'integer' || type === 'decimal')) return (a, b) => compareDecimal(asDecimal(a), asDecimal(b))\n const only = types.size === 1 ? [...types][0] : undefined\n if (only === 'string') return (a, b) => collator.compare(a.value as string, b.value as string)\n if (only === 'date') return (a, b) => ordered(a.value as string, b.value as string)\n if (only === 'datetime' || only === 'instant') return (a, b) => ordered(fixedWidth(a.value as string), fixedWidth(b.value as string))\n return undefined\n}\n\n/** The least (`sign` -1) or greatest (1) value, the first of equals as written; null over none. */\nfunction extreme(values: readonly TypedValue[], sign: -1 | 1, totalling: Totalling): Total {\n const compare = comparator(values, totalling.collator)\n if (compare === undefined) return { code: 'aggregate-value-type', message: 'takes the least or greatest of values of one kind, and the values it read are of several' }\n const found = values.reduce<TypedValue | null>((kept, value) => (kept === null || Math.sign(compare(value, kept)) === sign ? value : kept), null)\n return found?.type === 'integer' && totalling.decimals ? decimal(asDecimal(found)) : found\n}\n\n/** `total` rounded as `rounding` declares: a decimal at the rounding's scale. */\nfunction rounded(total: Total, rounding: Rounding | undefined): Total {\n if (rounding === undefined || total === null || isRefusal(total)) return total\n if (total.type === 'decimal') return decimal(roundDecimalAs(total.value, rounding))\n return { code: 'rounding-not-decimal', message: `declares a rounding, and its total is ${total.type === 'integer' ? 'an integer' : `a ${total.type}`}, which has no places to round` }\n}\n\n/** The aggregate over the values read from some rows -- each null or typed -- or over `rows` rows when it reads nothing. */\nfunction reduce(totalling: Totalling, read: readonly (TypedValue | null)[] | undefined, rows: number): Total {\n const { aggregate, decimals } = totalling\n const values = (read ?? []).filter((value): value is TypedValue => value !== null)\n switch (aggregate.fn) {\n case 'count':\n return integer(BigInt(read === undefined ? rows : values.length))\n case 'avg':\n // report-spec requires an average to declare its rounding.\n return values.length === 0 ? null : average(values, aggregate.rounding as Rounding)\n case 'sum':\n return rounded(sum(values, decimals), aggregate.rounding)\n case 'min':\n return rounded(extreme(values, -1, totalling), aggregate.rounding)\n case 'max':\n return rounded(extreme(values, 1, totalling), aggregate.rounding)\n }\n}\n\n/**\n * Every aggregate of `render`'s report, over its detail rows and, through\n * `over`, over any of them; or undefined when one could not be computed,\n * each reason recorded. `render` has every input but the totals.\n */\nexport function computeTotals(render: Omit<Render, 'totals'>): Totals | undefined {\n const { report, expressions, data, problems } = render\n const collator = new Intl.Collator(report.locale, { usage: 'sort' })\n const rows: readonly OrderedRow[] = data.detail.map((record, index) => ({ index, record }))\n const read = new Map<string, readonly (TypedValue | null)[]>()\n const totals = new Map<string, TypedValue | null>()\n const totallings = new Map<string, Totalling>()\n const refuse = (index: number, refusal: Refusal): void => {\n problems.error({ stage: 'resolve', code: refusal.code, path: `/aggregates/${index}`, message: `aggregate ${report.aggregates[index]?.id} ${refusal.message}` })\n }\n let computed = true\n\n for (const id of expressions.compilation.aggregateOrder) {\n const index = report.aggregates.findIndex((aggregate) => aggregate.id === id)\n const aggregate = report.aggregates[index] as AggregateDef\n const compiled = expressions.compilation.members.totals.get(id)?.type\n const decimals = compiled === 'decimal' || (compiled === 'dyn' && aggregate.rounding !== undefined)\n const of = aggregate.of\n if (of !== undefined) {\n const path = `/aggregates/${index}/of/expression/cel`\n const values = rows.map((row) => (of.kind === 'field' ? fieldValue(render, row.record, of.field) : valueOf(render, rowScope(render, totals, row), path)))\n if (values.some((value) => value === undefined)) {\n computed = false\n continue\n }\n read.set(id, values as (TypedValue | null)[])\n }\n const totalling: Totalling = { aggregate, decimals, collator }\n const total = reduce(totalling, read.get(id), rows.length)\n if (isRefusal(total)) {\n computed = false\n refuse(index, total)\n continue\n }\n totals.set(id, total)\n // A group's total is of its report total's kind: one that met a decimal is a decimal in every group.\n totallings.set(id, total?.type === 'decimal' ? { ...totalling, decimals: true } : totalling)\n }\n if (!computed) return undefined\n\n return {\n report: totals,\n over(group: readonly OrderedRow[]): AggregateValues {\n const values = new Map<string, TypedValue | null>()\n for (const aggregate of report.aggregates) {\n const each = read.get(aggregate.id)\n // Never refused: a group's values are some of those the report's\n // total took, of the kinds it took, totalled as the same kind and\n // rounded as it was. Every refusal `reduce` has is about the kinds\n // of values, and a share of values has no kind the whole lacks.\n values.set(aggregate.id, reduce(totallings.get(aggregate.id) as Totalling, each && group.map((row) => each[row.index] as TypedValue | null), group.length) as TypedValue | null)\n }\n return values\n },\n }\n}\n","/**\n * A report resolved against its data: the renderer-neutral document it\n * prints, and the manifest that says what it was printed from (plan 14).\n *\n * The composition of the runtime's stages, each decided in its own module:\n *\n * 1. the report, validated again and its expressions compiled; one the\n * editor's diagnostics give an error for is refused (`report-check.ts`);\n * 2. the options, the parameters and the data, each checked, and every\n * error of the three listed together (`parameters.ts`, `data.ts`);\n * 3. the aggregates, exactly, over every row (`totals.ts`);\n * 4. the e-invoice's lines, read once, and its totals and its terms, where\n * the report is one (`lower-e-invoice.ts`);\n * 5. the regions, lowered component by component (`lower.ts`), tables row\n * by row (`lower-table.ts`), images through the host's lookup\n * (`images.ts`), an EPC QR code's every text held to the EPC's rules\n * (`lower-epc-qr-code.ts`);\n * 6. the payment part, its every text held to SIX's rules\n * (`lower-payment-part.ts`);\n * 7. the e-invoice's XML, in a final render (`cii.ts`).\n *\n * It refuses rather than prints a wrong report: any error at any stage, and\n * the result is the errors, never a partial document. A preview may run on\n * data the provider calls incomplete or that lacks a field; it says so in\n * the manifest and in its warnings, and its every page carries\n * `PREVIEW_LABEL`, so that a preview printed or passed on is never taken for\n * the report. A final render refuses such data. A preview of an e-invoice\n * writes no XML, and is labelled whatever its data:\n * `E_INVOICE_PREVIEW_LABEL` where nothing else is lacking.\n */\nimport { decimalToString } from '@formancy/expressions'\nimport type { Decimal } from '@formancy/expressions'\nimport { reportHash } from '@formancy/report-spec'\nimport type { ReportDefinition } from '@formancy/report-spec'\nimport { checkData } from './data.js'\nimport type { Completeness, Consistency, DataMode, ReportData } from './data.js'\nimport type { Paragraph, ResolvedDocument } from './document.js'\nimport { createFormatter } from './format.js'\nimport { eInvoiceFile, resolveEInvoice } from './lower-e-invoice.js'\nimport { lowerPaymentPart } from './lower-payment-part.js'\nimport { lowerRegions } from './lower.js'\nimport { checkParameters } from './parameters.js'\nimport type { CheckedParameters } from './parameters.js'\nimport type { ImageResolver } from './render-context.js'\nimport { checkReport } from './report-check.js'\nimport { fromData, Problems } from './resolve-errors.js'\nimport type { RuntimeError } from './resolve-errors.js'\nimport { documentStyles } from './styles.js'\nimport { computeTotals } from './totals.js'\nimport { canonicalInstant } from './values.js'\n\nexport interface ResolveOptions {\n /** A final render prints the report; a preview shows a sample and says what it lacks. */\n readonly mode: DataMode\n /** The values a person supplied, by parameter id; defaults apply to those left out. */\n readonly parameters?: Readonly<Record<string, unknown>>\n /** The host's lookup of approved assets' bytes; a report that draws an image is refused without one. */\n readonly images?: ImageResolver\n /** An ISO 8601 instant with its zone, fixed by the caller, so that the same inputs print the same PDF. */\n readonly creationDate: string\n /** The IANA zone instants are shown in, named by the host: UTC when absent, never the machine's. */\n readonly timeZone?: string\n}\n\n/** What a document was resolved from, to keep beside the PDF (plan 14). Nothing in it is the data's. */\nexport interface RenderManifest {\n /** report-spec's hash of the report as validated. */\n readonly reportHash: string\n readonly reportSpecVersion: ReportDefinition['reportSpecVersion']\n readonly locale: string\n readonly timeZone: string\n readonly mode: DataMode\n readonly consistency: Consistency\n readonly completeness: Completeness\n /** Each parameter's value as the format writes one -- an exact number or a date as a string, a boolean -- or null. */\n readonly parameters: Readonly<Record<string, string | boolean | null>>\n}\n\nexport type Resolution =\n | { readonly ok: true; readonly document: ResolvedDocument; readonly manifest: RenderManifest; /** What a preview lacks; empty in a final render, which refuses it. */ readonly warnings: readonly RuntimeError[] }\n | { readonly ok: false; readonly errors: readonly RuntimeError[] }\n\n/** What every page of a preview that lacks data says, at the top of its page header. */\nexport const PREVIEW_LABEL = 'Preview of incomplete data: not a final report'\n\n/** What every page of a preview of an e-invoice says when it lacks nothing else: it writes no XML, and is not the invoice. */\nexport const E_INVOICE_PREVIEW_LABEL = 'Preview: not an e-invoice, and not a final report'\n\nconst label = (text: string): Paragraph => ({ kind: 'paragraph', runs: [{ text }], style: { size: 8, bold: true, color: '#b00020' } })\n\n/** Each parameter's value as the format writes one. */\nfunction writtenParameters(values: CheckedParameters): Record<string, string | boolean | null> {\n return Object.fromEntries(\n Object.entries(values).map(([id, value]) => {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return [id, value]\n if (typeof value === 'bigint') return [id, String(value)]\n // A parameter is never an image (report-spec), so what is left is a decimal.\n return [id, decimalToString(value as Decimal)]\n }),\n )\n}\n\n/**\n * `report` resolved against `data`: the document to render and its\n * manifest, or every reason it is refused, up to a bound. Nothing is read\n * from `report`, `data` or the parameters but through the checks, and\n * nothing in the result is shared with them.\n */\nexport function resolveReport(report: ReportDefinition, data: ReportData, options: ResolveOptions): Resolution {\n const checked = checkReport(report)\n if (!checked.ok) return { ok: false, errors: checked.errors }\n const valid = checked.report\n const timeZone = options.timeZone ?? 'UTC'\n const errors: RuntimeError[] = []\n const creationDate = canonicalInstant(String(options.creationDate))\n if (creationDate === undefined) errors.push({ stage: 'resolve', code: 'invalid-creation-date', path: '', message: 'the creation date is an ISO 8601 instant with its zone' })\n const formatter = createFormatter({ locale: valid.locale, timeZone })\n if (!formatter.ok) errors.push({ stage: 'format', code: formatter.code, path: formatter.code === 'unsupported-locale' ? '/locale' : '', message: formatter.message })\n const parameters = checkParameters(valid, options.parameters ?? {})\n if (!parameters.ok) errors.push(...parameters.errors.map((error) => fromData('parameters', error)))\n const checkedData = checkData(valid, data, { mode: options.mode })\n if (!checkedData.ok) errors.push(...checkedData.errors.map((error) => fromData('data', error)))\n if (errors.length > 0 || creationDate === undefined || !formatter.ok || !parameters.ok || !checkedData.ok) return { ok: false, errors }\n\n const problems = new Problems()\n for (const warning of checkedData.warnings) problems.warn(fromData('data', warning))\n const preview = checkedData.data.mode === 'preview'\n const inputs = {\n report: valid,\n expressions: checked.expressions,\n formatter: formatter.formatter,\n params: parameters.values,\n data: checkedData.data,\n problems,\n preview,\n images: options.images,\n styles: documentStyles(valid.styles),\n }\n const totals = computeTotals(inputs)\n if (totals === undefined) return { ok: false, errors: problems.errors() }\n const invoice = valid.eInvoice === undefined ? undefined : resolveEInvoice({ ...inputs, totals }, valid.eInvoice)\n if (valid.eInvoice !== undefined && invoice === undefined) return { ok: false, errors: problems.errors() }\n const render = { ...inputs, totals, ...(invoice === undefined ? {} : { invoice: invoice.reads }) }\n const regions = lowerRegions(render)\n const paymentPart = lowerPaymentPart(render)\n const eInvoice = invoice === undefined || valid.eInvoice === undefined ? undefined : eInvoiceFile(render, invoice, valid.eInvoice)\n if (problems.failed) return { ok: false, errors: problems.errors() }\n\n const { completeness, consistency } = checkedData.data\n const warnings = problems.warnings()\n const lacking = !completeness.complete || warnings.some(({ code }) => code !== 'e-invoice-preview')\n const labelled = !preview ? undefined : lacking ? PREVIEW_LABEL : invoice === undefined ? undefined : E_INVOICE_PREVIEW_LABEL\n const document: ResolvedDocument = {\n info: { title: valid.title, creationDate },\n page: valid.page,\n pageHeader: labelled === undefined ? regions.pageHeader : [label(labelled), ...regions.pageHeader],\n pageFooter: regions.pageFooter,\n body: regions.body,\n ...(paymentPart === undefined ? {} : { paymentPart }),\n ...(eInvoice === undefined ? {} : { eInvoice }),\n }\n const manifest: RenderManifest = {\n reportHash: reportHash(valid),\n reportSpecVersion: valid.reportSpecVersion,\n locale: valid.locale,\n timeZone,\n mode: checkedData.data.mode,\n consistency,\n completeness,\n parameters: writtenParameters(parameters.values),\n }\n return { ok: true, document, manifest, warnings }\n}\n"],"mappings":";;;;AAsYA,MAAa,gBAAgB;CAAC;CAAkB;CAAqB;CAAiB;CAAa;AAAa;;;;;;;AAShH,IAAa,gBAAb,cAAmC,MAAM;CACvC;CACA;CAEA,YAAY,MAAmB,SAAiB,SAAkB;EAChE,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,UAAU;CACjB;AACF;;;;ACxXA,MAAa,aAA4B,OAAO,YAAY;AAM5D,MAAM,WAAW;;AAGjB,SAAS,cAAc,OAAiC;CACtD,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG,OAAO;CAChF,MAAM,YAAqB,OAAO,eAAe,KAAK;CACtD,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;;;;;;;AAQA,SAAgB,WAAW,OAA4B;CACrD,IAAI;EACF,IAAI,CAAC,cAAc,KAAK,GAAG,OAAO;GAAE,IAAI;GAAO,MAAM;GAAc,SAAS;EAAqC;EACjH,MAAM,0BAAU,IAAI,IAAqB;EACzC,MAAM,WAA8B,CAAC;EACrC,IAAI,UAAU;EACd,KAAK,MAAM,OAAO,QAAQ,QAAQ,KAAK,GAAG;GACxC,IAAI,OAAO,QAAQ,UAAU;IAC3B,UAAU;IACV;GACF;GACA,MAAM,aAAa,OAAO,yBAAyB,OAAO,GAAG;GAC7D,IAAI,EAAE,WAAW,aAAa,SAAS,KAAK;IAAE;IAAK,SAAS;GAAS,CAAC;QACjE,IAAI,WAAW,eAAe,MAAM,SAAS,KAAK;IAAE;IAAK,SAAS;GAAgD,CAAC;QACnH,QAAQ,IAAI,KAAK,WAAW,KAAK;EACxC;EACA,IAAI,SAAS,SAAS,KAAK,EAAE,SAAS,2CAA2C,CAAC;EAClF,OAAO;GAAE,IAAI;GAAM;GAAS;EAAS;C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