@formancy/report-spec 0.1.0 → 0.3.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":[],"sources":["../src/limits.ts","../src/pointer.ts","../src/syntax.ts","../src/units.ts","../src/check.ts","../src/version.ts","../src/types.ts","../src/validate-context.ts","../src/validate-inline.ts","../src/validate-aggregates.ts","../src/validate-table.ts","../src/validate-components.ts","../src/page.ts","../src/validate-declarations.ts","../src/validate.ts","../src/errors.ts","../src/hash.ts","../src/empty.ts","../src/walk.ts"],"sourcesContent":["/**\n * The bounds a report definition is held to, and why each exists.\n *\n * A template is untrusted input, even when an administrator wrote it. Every\n * array, string and number in it is bounded, so that validating, hashing,\n * editing and later laying one out costs work that does not grow with\n * whatever a broken or hostile document holds. An array is measured before\n * any element of it is read.\n *\n * The numbers are chosen, not measured: each sits well above what the three\n * starter reports need (plan 7) and low enough to keep that work small. Two\n * are not chosen, and say where they come from. Raising a bound is safe;\n * lowering one refuses reports that were valid, which once the format is\n * frozen means a new reportSpecVersion.\n */\n\n/**\n * Errors listed per validation. Past it, one `too-many-errors` entry says\n * the list was cut short, so a caller never mistakes a partial list for a\n * whole one. Enough to fix a broken template in one pass; not so many that\n * a document of junk produces megabytes of messages.\n */\nexport const MAX_ERRORS = 100\n\n/**\n * Components in one region, counting those inside containers, so wrapping\n * components in a container does not get round it. A printed page holds a\n * few dozen blocks; a region of five hundred is a document that should be\n * two.\n */\nexport const MAX_REGION_COMPONENTS = 500\n\n/**\n * How deep containers (columns, keep-together blocks) nest. A container\n * inside four others is refused. Every stage that walks the tree --\n * validation, the core's commands, the runtime, the layout -- recurses this\n * deep and no deeper, and nesting past it is a layout no reader follows.\n */\nexport const MAX_NESTING_DEPTH = 4\n\n/** Columns in a columns block: fewer than two is not columns; more than four on A4 is too narrow to read. */\nexport const MIN_COLUMNS = 2\nexport const MAX_COLUMNS = 4\n\n/** Columns in a table: wider than a landscape page can show legibly, and a bound on per-row work. */\nexport const MAX_TABLE_COLUMNS = 32\n\n/** Sort keys on a table. Each one costs a comparison per row pair; a longer sort is usually a missing key. */\nexport const MAX_SORT_KEYS = 8\n\n/** Rows under a group or under the table: a subtotal, a discount, two tax lines and a total fit with room to spare. */\nexport const MAX_FOOTER_ROWS = 8\n\n/** Fields in one dataset contract: a report prints a fraction of any source table's columns. */\nexport const MAX_DATASET_FIELDS = 64\n\n/** Print styles in one report. A report's look is a handful of tokens; this is many handfuls. */\nexport const MAX_STYLES = 64\n\n/** Conditional style rules on one component or column. Each is an expression evaluated per render or per row. */\nexport const MAX_STYLE_RULES = 8\n\n/** Parameters: each is a field on the parameter form a person fills in before rendering. */\nexport const MAX_PARAMETERS = 32\n\n/** Asset references: each is a lookup and a byte budget at render time. */\nexport const MAX_ASSETS = 64\n\n/** Aggregates: each is a pass over the detail rows, per group and once overall. */\nexport const MAX_AGGREGATES = 32\n\n/** Inline runs in one paragraph or group header. A paragraph with more bindings than this is a table. */\nexport const MAX_INLINES = 64\n\n/**\n * Characters in a property name. The format's own names are short and its\n * ids are at most 64 characters, so a longer name is never one it knows. It\n * is refused before a path is built from it, so that no path and no message\n * grows with what a document holds.\n */\nexport const MAX_KEY_LENGTH = 64\n\n/** Characters (UTF-16 code units, as JavaScript counts) in a literal run of text: several pages of prose. */\nexport const MAX_TEXT_LENGTH = 10_000\n\n/** Characters in a title, label, column header, empty-state text or parameter default: one line, generously. */\nexport const MAX_LABEL_LENGTH = 200\n\n/** Characters in a CEL expression. An expression is a formula, not a program; the runtime bounds its evaluation too. */\nexport const MAX_EXPRESSION_LENGTH = 1024\n\n/** Digits after the decimal point, for fields, formats and rounding. Covers every currency's minor unit and unit prices to many places. */\nexport const MAX_SCALE = 20\n\n/** Font sizes in points: below 4 is not legible print, above 96 is a poster. */\nexport const MIN_FONT_SIZE = 4\nexport const MAX_FONT_SIZE = 96\n\n/**\n * The longest length anything in a report may have, in points. Not chosen:\n * 14,400 units (200 inches) is the largest page dimension PDF readers\n * implement (ISO 32000-1, Annex C), so nothing longer can appear on a page.\n */\nexport const MAX_LENGTH_PT = 14_400\n\n/**\n * The smallest printable area the margins may leave, each way: one inch,\n * 72 points. Not chosen so much as named: less than an inch of width does\n * not hold a word of body text.\n */\nexport const MIN_PRINTABLE_PT = 72\n","/**\n * JSON Pointers (RFC 6901), the one way this package says where something\n * is: validation errors and `walkComponents` use the same paths, so an\n * error can be matched to the component it is about.\n */\n\n/**\n * `path` extended by one key or index, escaped as RFC 6901 says.\n *\n * Validation builds a path for every property it reads, so the common case\n * -- an index, or a key with nothing to escape -- is a concatenation; the\n * two replacements took half of validation's time when they ran on every\n * key (measured with --cpu-prof on a 40-component report, 14 October 2026).\n */\nexport function at(path: string, key: string | number): string {\n if (typeof key === 'number' || !(key.includes('~') || key.includes('/'))) return `${path}/${key}`\n return `${path}/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`\n}\n","/**\n * What a valid string looks like, for each string in a report that has a\n * syntax. One pattern per thing, so the validator and an editor checking a\n * value as it is typed cannot disagree.\n *\n * Each accepts one spelling of each value -- lower-case hex, canonical\n * locale case, no negative zero -- so that one value has one canonical hash.\n */\n\n/**\n * Identifiers: lower-case letters, digits and hyphens, starting with a\n * letter, at most 64 characters. The names a deployment resolves -- a\n * dataset, an asset -- are written this way, as formancy writes a named\n * options source (formancy.ai 0077), and so are the format's structural\n * names: components, styles, table columns.\n */\nconst IDENTIFIER = /^[a-z][a-z0-9-]{0,63}$/\n\n/** Whether `value` is an identifier a report can use for a component, style, dataset, asset or table column. */\nexport function isIdentifier(value: unknown): value is string {\n return typeof value === 'string' && IDENTIFIER.test(value)\n}\n\n/**\n * Field keys: formancy's `fieldKey` exactly -- letters, digits and\n * underscores, starting with a letter or an underscore, at most 64\n * characters, the case part of the key. The names an expression reads are\n * written this way: a dataset field, a parameter, an aggregate. So a form's\n * or a dataset's key is the report's key unrenamed, and CEL reads it with a\n * dot, `row.unitPrice`, where a hyphen would read as a subtraction.\n */\nconst FIELD_KEY = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/\n\n/** Whether `value` is a field key: the id of a dataset field, a parameter or an aggregate. */\nexport function isFieldKey(value: unknown): value is string {\n return typeof value === 'string' && FIELD_KEY.test(value)\n}\n\n/** A formancy form's id, as its schema writes one (`formId`): at most 128 characters. */\nexport const FORM_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/\n\n/**\n * The BCP 47 subset a report's locale may be: a language (2-3 letters), an\n * optional script (4 letters, title case) and an optional region (2 letters\n * upper case, or 3 digits) -- 'en', 'de-CH', 'zh-Hans-CN', 'es-419'.\n * Variants, extensions and private use are refused rather than half-read,\n * and a regular expression rather than Intl decides, because Intl's\n * canonicalisation differs between ICU versions and a template must\n * validate the same in every runtime.\n */\nexport const LOCALE = /^[a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-(?:[A-Z]{2}|\\d{3}))?$/\n\n/** A colour: `#rrggbb`, lower case. */\nexport const COLOR = /^#[0-9a-f]{6}$/\n\n/** An ISO 4217 currency code, upper case. */\nexport const CURRENCY = /^[A-Z]{3}$/\n\n/** An asset's content digest: SHA-256, lower-case hex. */\nexport const DIGEST = /^sha256:[0-9a-f]{64}$/\n\n/** A form version's hash, as `@formancy/spec`'s `schemaHash` writes it: 64 lower-case hex digits. */\nexport const SCHEMA_HASH = /^[0-9a-f]{64}$/\n\n/** An exact integer as a string: no sign but '-', no leading zeros, no exponent, and no '-0'. */\nexport const INTEGER = /^(?:0|-?[1-9]\\d*)$/\n\n/**\n * An exact decimal as a string: an integer, optionally a point and at least\n * one digit. Trailing zeros are kept, because they say the scale ('1.50' has\n * two places); a negative zero ('-0', '-0.00') is refused.\n */\nexport const DECIMAL = /^(?:-?[1-9]\\d*(?:\\.\\d+)?|0(?:\\.\\d+)?|-0\\.\\d*[1-9]\\d*)$/\n\nconst DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/\n\n/**\n * Whether `value` is a calendar date written YYYY-MM-DD: 2024-02-29 is one,\n * 2026-02-29 is not, and neither is any day of the year 0000, which Intl\n * shows as the year 1 -- 1 BC without its era -- a year nobody wrote.\n */\nexport function isCalendarDate(value: string): boolean {\n const match = DATE.exec(value)\n if (match === null) return false\n const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])]\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 * Lengths: the one conversion between points and millimetres, and the one\n * rounding every stored length goes through (plan 9).\n *\n * A report stores points, the PDF unit. Millimetres are what an author in\n * Switzerland or Germany types and reads, so the builder converts at its\n * edge, here and nowhere else.\n */\n\n/** Points per inch: the default PDF user-space unit is 1/72 inch. */\nexport const POINTS_PER_INCH = 72\n\n/** Millimetres per inch, exactly. */\nexport const MILLIMETRES_PER_INCH = 25.4\n\n/**\n * To the nearest hundredth, ties away from zero, and never -0.\n *\n * Ties are decided on the binary value JavaScript computed, which for a\n * product like `mm * 72 / 25.4` is already a little either side of any\n * exact tie. Symmetric about zero, so a length and its negation round to\n * the same magnitude.\n */\nfunction toHundredths(value: number): number {\n return (Math.sign(value) * Math.round(Math.abs(value) * 100)) / 100 + 0\n}\n\n/**\n * A length in points rounded to the 0.01 pt a report stores. A hundredth of\n * a point is under four thousandths of a millimetre: finer than any printer\n * places ink, coarse enough that one length has one stored value.\n */\nexport function roundPt(points: number): number {\n return toHundredths(points)\n}\n\n/** Millimetres to points, rounded to 0.01 pt. */\nexport function mmToPt(millimetres: number): number {\n return roundPt((millimetres * POINTS_PER_INCH) / MILLIMETRES_PER_INCH)\n}\n\n/**\n * Points to millimetres, rounded to 0.01 mm, for display. A value typed in\n * millimetres to two decimals, stored with `mmToPt`, comes back as typed:\n * the stored point value is within 0.005 pt (0.0018 mm) of the exact one,\n * well inside the 0.005 mm that would change the displayed hundredth.\n */\nexport function ptToMm(points: number): number {\n return toHundredths((points * MILLIMETRES_PER_INCH) / POINTS_PER_INCH)\n}\n","/**\n * Reading untrusted input once, and checking the values in it: the\n * vocabulary every part of validation is written in.\n *\n * Every object and array is read once, through its property descriptors,\n * into a copy; validation then works on the copy and builds the report it\n * returns from what it checked. A getter is refused, never run, and a value\n * read once cannot answer differently later.\n *\n * One convention holds throughout: `undefined` means absent, or present but\n * unreadable -- and in that case already reported. Every function here\n * handed `undefined` returns `undefined` and says nothing, so a missing or\n * unreadable value is reported once, where it is, and not again by every\n * check that wanted it.\n *\n * And one more: no message and no path grows with what a document holds.\n * A string is quoted to 40 characters, and a property name longer than any\n * the format has is refused before a path is built from it.\n */\nimport type { ReportError, ReportErrorCode } from './errors.js'\nimport { MAX_ERRORS, MAX_FONT_SIZE, MAX_KEY_LENGTH, MAX_LENGTH_PT, MIN_FONT_SIZE } from './limits.js'\nimport { at } from './pointer.js'\nimport { isFieldKey, isIdentifier } from './syntax.js'\nimport type { Width } from './types.js'\nimport { roundPt } from './units.js'\n\n/** The errors one validation has found, bounded, and the components they can be attributed to. */\nexport class Findings {\n readonly #errors: ReportError[] = []\n readonly #components = new Map<string, string>()\n #overflowed = false\n\n report(path: string, code: ReportErrorCode, message: string): void {\n if (this.#errors.length < MAX_ERRORS) this.#errors.push({ path, code, message })\n else this.#overflowed = true\n }\n\n /** Records that the component at `path` has `id`, so that errors under it name it. */\n component(path: string, id: string): void {\n this.#components.set(path, id)\n }\n\n /** The errors in the order found, each naming the innermost component it is inside, and a last one when more were found than listed. */\n errors(): ReportError[] {\n const errors = this.#errors.map((error) => {\n const componentId = this.#owner(error.path)\n return componentId === undefined ? error : { ...error, componentId }\n })\n if (this.#overflowed) {\n errors.push({ path: '', code: 'too-many-errors', message: `more than ${MAX_ERRORS} errors were found; the first ${MAX_ERRORS} are listed` })\n }\n return errors\n }\n\n /** The id of the component whose path is the longest prefix of `path`. */\n #owner(path: string): string | undefined {\n for (let prefix = path; ; prefix = prefix.slice(0, prefix.lastIndexOf('/'))) {\n const id = this.#components.get(prefix)\n if (id !== undefined || prefix === '') return id\n }\n }\n}\n\n/** A value as a message can quote it: strings shortened and quoted, objects named, never stringified. */\nexport function describe(value: unknown): string {\n if (value === null) return 'null'\n if (typeof value === 'string') return `the string ${quote(value)}`\n if (typeof value === 'number' || typeof value === 'boolean') return `${typeof value} ${String(value)}`\n if (typeof value !== 'object') return `a ${typeof value}`\n try {\n return Array.isArray(value) ? 'an array' : 'an object'\n } catch {\n return 'an object that cannot be read'\n }\n}\n\n/** A string as a message quotes it: at most 40 characters of it. Every string from a document passes through here before a message holds it. */\nexport function quote(text: string): string {\n return JSON.stringify(text.length > 40 ? `${text.slice(0, 40)}...` : text)\n}\n\n/** Allowed values as a message lists them. */\nexport function list(values: readonly (string | boolean)[]): string {\n return values.map((value) => (typeof value === 'string' ? `\"${value}\"` : String(value))).join(', ')\n}\n\n/** A property's value as JSON data, or undefined after reporting why it is not. */\nfunction readProperty(f: Findings, owner: object, key: string | number, path: string): unknown {\n const descriptor = Object.getOwnPropertyDescriptor(owner, key)\n if (descriptor === undefined) {\n f.report(path, 'not-json', 'a hole in an array is not JSON data')\n return undefined\n }\n if (!('value' in descriptor)) {\n f.report(path, 'not-json', 'a getter or setter is not JSON data, and is not run')\n return undefined\n }\n const value: unknown = descriptor.value\n switch (typeof value) {\n case 'string':\n case 'boolean':\n case 'object':\n return value\n case 'number':\n if (Number.isFinite(value)) return value + 0 // -0 is read as 0, as JSON writes it\n f.report(path, 'not-json', 'a number that is not finite is not JSON data')\n return undefined\n default:\n f.report(path, 'not-json', `${describe(value)} is not JSON data`)\n return undefined\n }\n}\n\n/** A plain object's own enumerable data properties, copied, or undefined after reporting why not. */\nexport function readObject(f: Findings, value: unknown, path: string): Record<string, unknown> | undefined {\n if (value === undefined) return undefined\n try {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n f.report(path, 'wrong-type', `expected an object, found ${describe(value)}`)\n return undefined\n }\n // A plain object's prototype is Object.prototype, from this realm or\n // another, or null. Anything else -- a Map, a Date, a class -- would be\n // read as an object of its own properties, which is not what it holds.\n const prototype: unknown = Object.getPrototypeOf(value)\n if (prototype !== null && Object.getPrototypeOf(prototype as object) !== null) {\n f.report(path, 'wrong-type', 'expected a plain object, found an instance of a class')\n return undefined\n }\n const copy: Record<string, unknown> = Object.create(null) as Record<string, unknown>\n for (const key of Object.keys(value)) {\n // Reported where its object is and left out of the copy, so no path is\n // built from it; the error alone keeps the report from being valid.\n if (key.length > MAX_KEY_LENGTH) f.report(path, 'too-long', `holds a property name ${key.length} characters long, ${quote(key)}; no name in the format is longer than ${MAX_KEY_LENGTH}`)\n else copy[key] = readProperty(f, value, key, at(path, key))\n }\n return copy\n } catch {\n f.report(path, 'not-json', 'this value threw when it was read')\n return undefined\n }\n}\n\n/**\n * An array's elements, copied, or undefined after reporting why not. Its\n * length is read once, as a number, and checked before any element is\n * read: a proxy's length that answered differently when asked again would\n * otherwise pass the bound and then be read past it.\n */\nexport function readArray(f: Findings, value: unknown, path: string, max: number): unknown[] | undefined {\n if (value === undefined) return undefined\n try {\n if (!Array.isArray(value)) {\n f.report(path, 'wrong-type', `expected an array, found ${describe(value)}`)\n return undefined\n }\n const length: unknown = value.length\n if (typeof length !== 'number' || !Number.isSafeInteger(length) || length < 0) {\n f.report(path, 'not-json', 'an array whose length is not a whole number is not JSON data')\n return undefined\n }\n if (length > max) {\n f.report(path, 'too-many', `holds ${length} entries; at most ${max} are allowed`)\n return undefined\n }\n const copy: unknown[] = []\n for (let index = 0; index < length; index += 1) copy.push(readProperty(f, value, index, at(path, index)))\n return copy\n } catch {\n f.report(path, 'not-json', 'this value threw when it was read')\n return undefined\n }\n}\n\n/** An array with at least `min` and at most `max` elements. One with too few is still returned, so its elements are checked too. */\nexport function readList(f: Findings, value: unknown, path: string, min: number, max: number): unknown[] | undefined {\n const items = readArray(f, value, path, max)\n if (items !== undefined && items.length < min) f.report(path, 'too-few', `holds ${items.length} entries; at least ${min} are needed`)\n return items\n}\n\n/** Reports every property a shape does not have, and every required one that is absent. */\nexport function strictKeys(f: Findings, o: Record<string, unknown>, path: string, required: readonly string[], optional: readonly string[] = []): void {\n for (const key of Object.keys(o)) {\n if (!required.includes(key) && !optional.includes(key)) {\n f.report(at(path, key), 'unknown-property', `${quote(key)} is not a property this version of the format has here`)\n }\n }\n for (const key of required) if (!Object.hasOwn(o, key)) f.report(at(path, key), 'missing-property', `${quote(key)} is required here`)\n}\n\n/** An object with exactly the properties a shape allows. */\nexport function shape(f: Findings, value: unknown, path: string, required: readonly string[], optional: readonly string[] = []): Record<string, unknown> | undefined {\n const o = readObject(f, value, path)\n if (o !== undefined) strictKeys(f, o, path, required, optional)\n return o\n}\n\n/** The `kind` of an object that has one, among `kinds`. */\nexport function kindOf<K extends string>(f: Findings, o: Record<string, unknown>, path: string, kinds: readonly K[]): K | undefined {\n const where = at(path, 'kind')\n if (!Object.hasOwn(o, 'kind')) {\n f.report(where, 'missing-property', `\"kind\" is required: it says which of ${list(kinds)} this is`)\n return undefined\n }\n const kind = reference(f, o.kind, where)\n if (kind === undefined) return undefined\n if ((kinds as readonly string[]).includes(kind)) return kind as K\n f.report(where, 'unknown-kind', `${quote(kind)} is not a kind this version knows; it knows ${list(kinds)}`)\n return undefined\n}\n\nexport function text(f: Findings, value: unknown, path: string, max: number): string | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'string') {\n f.report(path, 'wrong-type', `expected a string, found ${describe(value)}`)\n return undefined\n }\n if (value.length > max) {\n f.report(path, 'too-long', `is ${value.length} characters long; at most ${max} are allowed`)\n return undefined\n }\n return value\n}\n\n/** A string naming something declared elsewhere; whether it is declared is the caller's question. */\nexport function reference(f: Findings, value: unknown, path: string): string | undefined {\n return text(f, value, path, Number.POSITIVE_INFINITY)\n}\n\nexport function flag(f: Findings, value: unknown, path: string): boolean | undefined {\n if (value === undefined || typeof value === 'boolean') return value\n f.report(path, 'wrong-type', `expected true or false, found ${describe(value)}`)\n return undefined\n}\n\nexport function oneOf<const T extends string | boolean>(f: Findings, value: unknown, path: string, allowed: readonly T[]): T | undefined {\n if (value === undefined) return undefined\n if ((allowed as readonly unknown[]).includes(value)) return value as T\n f.report(path, 'not-one-of', `expected ${allowed.length === 1 ? '' : 'one of '}${list(allowed)}, found ${describe(value)}`)\n return undefined\n}\n\n/** A finite number from `min` to `max`. */\nexport function number(f: Findings, value: unknown, path: string, min: number, max: number): number | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'number') {\n f.report(path, 'wrong-type', `expected a number, found ${describe(value)}`)\n return undefined\n }\n if (value < min || value > max) {\n f.report(path, 'out-of-range', `${value} is outside the range allowed here, ${min} to ${max}`)\n return undefined\n }\n return value\n}\n\n/** A whole number from `min` to `max`. */\nexport function integer(f: Findings, value: unknown, path: string, min: number, max: number): number | undefined {\n if (typeof value === 'number' && !Number.isInteger(value)) {\n f.report(path, 'not-an-integer', `${value} is not a whole number`)\n return undefined\n }\n return number(f, value, path, min, max)\n}\n\n/**\n * A number of points from `min` to `max`, on the hundredth of a point that\n * lengths are stored to. A finer one is refused rather than rounded: two\n * spellings of one stored length would hash differently, and a length that\n * rounds to 0 would pass as more than 0.\n */\nfunction measure(f: Findings, value: unknown, path: string, min: number, max: number): number | undefined {\n const length = number(f, value, path, min, max)\n if (length === undefined || roundPt(length) === length) return length\n f.report(path, 'too-precise', `${length} has more than two decimal places; lengths are stored to the hundredth of a point`)\n return undefined\n}\n\n/** A length in points: from 0, or more than 0, up to MAX_LENGTH_PT. */\nexport function points(f: Findings, value: unknown, path: string, least: 'zero' | 'positive'): number | undefined {\n const length = measure(f, value, path, 0, MAX_LENGTH_PT)\n if (length === 0 && least === 'positive') {\n f.report(path, 'out-of-range', 'a length of 0 points draws nothing; it must be more than 0')\n return undefined\n }\n return length\n}\n\n/** A font size in points, from MIN_FONT_SIZE to MAX_FONT_SIZE. */\nexport function fontSize(f: Findings, value: unknown, path: string): number | undefined {\n return measure(f, value, path, MIN_FONT_SIZE, MAX_FONT_SIZE)\n}\n\n/** A width: a length in points, or \"fill\" for a share of what fixed widths leave. */\nexport function width(f: Findings, value: unknown, path: string): Width | undefined {\n if (value === 'fill') return value\n if (typeof value === 'string') {\n f.report(path, 'wrong-type', `expected a width in points or \"fill\", found ${describe(value)}`)\n return undefined\n }\n return points(f, value, path, 'positive')\n}\n\n/** A string matching `pattern`; `expected` says in words what it should look like. */\nexport function matches(f: Findings, value: unknown, path: string, pattern: RegExp, code: ReportErrorCode, expected: string): string | undefined {\n const string = reference(f, value, path)\n if (string === undefined || pattern.test(string)) return string\n f.report(path, code, `expected ${expected}, found ${quote(string)}`)\n return undefined\n}\n\nconst IDENTIFIER_RULE = 'lower-case letters, digits and hyphens, starting with a letter, at most 64 characters'\n\nexport function identifier(f: Findings, value: unknown, path: string): string | undefined {\n const id = reference(f, value, path)\n if (id === undefined || isIdentifier(id)) return id\n f.report(path, 'invalid-id', `${quote(id)} is not an identifier: ${IDENTIFIER_RULE}`)\n return undefined\n}\n\nconst FIELD_KEY_RULE = 'letters, digits and underscores, starting with a letter or an underscore, at most 64 characters, as a formancy form writes a field key'\n\n/** A name an expression reads: a field, a parameter or an aggregate. */\nexport function fieldKey(f: Findings, value: unknown, path: string): string | undefined {\n const key = reference(f, value, path)\n if (key === undefined || isFieldKey(key)) return key\n f.report(path, 'invalid-id', `${quote(key)} is not a field key: ${FIELD_KEY_RULE}`)\n return undefined\n}\n\n/** Every value, or undefined when any of them is. */\nexport function all<T>(values: readonly (T | undefined)[]): T[] | undefined {\n const present: T[] = []\n for (const value of values) {\n if (value === undefined) return undefined\n present.push(value)\n }\n return present\n}\n\n/** `{ [key]: value }`, or `{}` when value is absent: an optional property spread into a result. */\nexport function optional<K extends string, V>(key: K, value: V | undefined): { readonly [P in K]?: V } {\n return (value === undefined ? {} : { [key]: value }) as { readonly [P in K]?: V }\n}\n","/**\n * What a Formancy Report definition is, before anything about what it holds.\n *\n * A report is its own document, not a formancy form with pages added: it has\n * its own version line, independent of formancy's `specVersion`, of Formancy\n * Data's generated form spec and bindings versions, and of this package's npm\n * version. Package versions alone cannot say whether two documents are\n * compatible; this can.\n *\n * A message here quotes what the document holds, shortened: a version string\n * is the document's to choose, and a message that echoed it whole would grow\n * with it.\n */\nimport { quote } from './check.js'\n\n/**\n * The format's name. A canonical hash of a report is taken over an envelope\n * that names it, so a report and a form whose JSON bodies happen to be equal\n * can never share a hash.\n */\nexport const REPORT_FORMAT = 'formancy-report'\n\n/**\n * The version of the report definition this package reads. A string of\n * digits, as formancy writes `specVersion`.\n *\n * Version 0 is the draft: the format is being designed, and no document\n * written under it is promised to be read by a later release. The release\n * that first freezes the format makes it 1, and from then a frozen version\n * keeps its meaning.\n */\nexport const REPORT_SPEC_VERSION = '0'\n\n/** Whether a document is a report of the version this package reads, and why not when it is not. */\nexport type SpecVersionCheck =\n | { readonly ok: true }\n | { readonly ok: false; readonly code: 'not-a-report' | 'unsupported-version'; readonly message: string }\n\n/** The field that holds a value, when `value` is an object that has it. */\nfunction field(value: unknown, name: string): unknown {\n return typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>)[name] : undefined\n}\n\n/**\n * Whether `document` is a report definition of `REPORT_SPEC_VERSION`.\n *\n * Refuses rather than guesses. A document with no `reportSpecVersion` string\n * is not a report, and a formancy form -- the document most likely to arrive\n * here by mistake -- is named as one. A report of another version is refused,\n * never partly read: a field this version does not know could be the one that\n * hides a row or changes a total.\n */\nexport function checkSpecVersion(document: unknown): SpecVersionCheck {\n const version = field(document, 'reportSpecVersion')\n if (typeof version !== 'string') {\n const form = field(document, 'specVersion')\n const message =\n typeof form === 'string'\n ? `this is a formancy form (specVersion ${quote(form)}), not a report definition`\n : 'this is not a report definition: it has no reportSpecVersion string'\n return { ok: false, code: 'not-a-report', message }\n }\n if (version !== REPORT_SPEC_VERSION) {\n return { ok: false, code: 'unsupported-version', message: `reportSpecVersion ${quote(version)} is not one this package reads; it reads ${quote(REPORT_SPEC_VERSION)}` }\n }\n return { ok: true }\n}\n","/**\n * The report definition, version 0: what a Formancy Report template is.\n *\n * A report is its own document, with its own version line\n * ([0007](../../../docs/decisions/0007-a-report-definition-is-its-own-versioned-document.md)).\n * Lengths are PDF points (1/72 inch), stored to the hundredth. Nothing here\n * holds customer data, credentials, asset bytes or rendered output: a\n * template names a dataset contract, an asset digest and a parameter, and\n * the deployment supplies what each resolves to.\n *\n * Four conventions hold throughout, so that one editor command, one binding\n * picker and one walk serve every part of the format:\n * - every shape that comes in kinds says which with `kind`;\n * - every declaration is a list of objects with an `id`, unique in its list;\n * - every reference to a dataset field is a `FieldRef`;\n * - a name an expression reads -- a field, a parameter, an aggregate -- is a\n * field key, as formancy's form spec writes one (`isFieldKey`); every other\n * id is an identifier (`isIdentifier`).\n *\n * The vocabularies are `const` lists, and each union type is derived from\n * its list, so the type and the validator's list cannot disagree.\n */\nimport type { REPORT_SPEC_VERSION } from './version.js'\n\nexport const PAGE_SIZE_NAMES = ['A4', 'Letter'] as const\nexport type PageSizeName = (typeof PAGE_SIZE_NAMES)[number]\n\nexport const ORIENTATIONS = ['portrait', 'landscape'] as const\nexport type Orientation = (typeof ORIENTATIONS)[number]\n\nexport interface Margins {\n readonly top: number\n readonly right: number\n readonly bottom: number\n readonly left: number\n}\n\nexport interface PageSettings {\n readonly size: PageSizeName\n readonly orientation: Orientation\n readonly margins: Margins\n}\n\nexport const FONT_FAMILIES = ['sans', 'serif', 'mono'] as const\nexport type FontFamily = (typeof FONT_FAMILIES)[number]\n\nexport const ALIGNMENTS = ['left', 'center', 'right'] as const\nexport type Alignment = (typeof ALIGNMENTS)[number]\n\n/**\n * A print style: serialisable report tokens, never CSS. Nothing from the\n * editor's or the host's stylesheet reaches a printed page; what prints is\n * what these say (plan 11.4). An absent property is the renderer's default.\n */\nexport interface PrintStyle {\n readonly id: string\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\nexport const FIELD_TYPES = ['string', 'integer', 'decimal', 'boolean', 'date', 'datetime', 'instant', 'image'] as const\nexport type FieldType = (typeof FIELD_TYPES)[number]\n\n/**\n * A field a dataset contract promises.\n *\n * Values of exact types arrive as strings, never as JavaScript numbers. An\n * `image` field's value is an approved asset -- its id and its `sha256:`\n * digest -- which the host resolves to bytes, never an address: a photo or\n * a signature captured with a form arrives this way, and prints only as an\n * image. A field that is not nullable never holds null; one that is prints\n * null as nothing. A field the data lacks altogether is the runtime's error,\n * never an empty string.\n */\nexport interface FieldContract {\n /** A field key: what an expression reads it as, `header.<id>` or `row.<id>`. */\n readonly id: string\n readonly type: FieldType\n readonly label: string\n readonly nullable: boolean\n /** Digits after the decimal point; decimal fields only. */\n readonly scale?: number\n}\n\n/**\n * A dataset the report reads, by the logical id a deployment's binding set\n * maps to a provider. The fields are the contract the template was written\n * against, so the template itself records which revision of the contract it\n * expects.\n */\nexport interface DatasetContract {\n readonly id: string\n readonly fields: readonly FieldContract[]\n}\n\n/** The two datasets a version-0 report can read: one row of header data, and the one primary detail dataset. */\nexport const DATASET_ROLES = ['header', 'detail'] as const\nexport type DatasetRole = (typeof DATASET_ROLES)[number]\n\nexport interface Datasets {\n readonly header?: DatasetContract\n readonly detail?: DatasetContract\n}\n\nexport const PARAMETER_TYPES = ['string', 'integer', 'decimal', 'boolean', 'date'] as const\nexport type ParameterType = (typeof PARAMETER_TYPES)[number]\n\n/** A value a person supplies before rendering, on a formancy form whose field key is the parameter's id (plan 12.4). */\nexport interface ParameterDef {\n /** A field key: what an expression reads it as, `params.<id>`. */\n readonly id: string\n readonly type: ParameterType\n readonly label: string\n readonly required: boolean\n /** A boolean for a boolean parameter; for every other type, the exact value as a string. */\n readonly default?: string | boolean\n}\n\nexport const ASSET_MEDIA_TYPES = ['image/png', 'image/jpeg'] as const\nexport type AssetMediaType = (typeof ASSET_MEDIA_TYPES)[number]\n\n/**\n * An approved asset, named by id and pinned by digest. The bytes never live\n * in the definition, and rendering never follows a mutable \"latest\" asset\n * (plan 17): a new logo is a new digest and a new template release.\n */\nexport interface AssetRef {\n readonly id: string\n readonly mediaType: AssetMediaType\n /** `sha256:` and 64 lower-case hex digits. */\n readonly digest: string\n}\n\n/** A CEL expression, compiled and bounded by the runtime, not here. */\nexport interface Expression {\n readonly cel: string\n}\n\n/**\n * Where a value is read, which decides what it can name (plan 15's \"current\n * row, group or report\"): `row` in a table cell, once per detail row;\n * `group` in a group header or footer, once per group; `report` everywhere\n * else, the table's total rows included.\n */\nexport const VALUE_SCOPES = ['report', 'group', 'row'] as const\nexport type ValueScope = (typeof VALUE_SCOPES)[number]\n\n/**\n * The names an expression reads in each scope, and nothing else: the\n * runtime binds exactly these. `params` maps parameter ids to values,\n * `header` the header dataset's fields, `row` the current detail row's,\n * `totals` each aggregate over every detail row, and `group` each aggregate\n * over the current group's rows and, as `GROUP_KEY`, the value the group\n * is keyed by.\n *\n * Whether an expression names only these is checked when the runtime\n * compiles it (plan 15's second level), not here: a second, partial CEL\n * parser would be a second place to disagree with the real one.\n */\nexport const EXPRESSION_NAMES: { readonly [S in ValueScope]: readonly string[] } = {\n report: ['params', 'header', 'totals'],\n group: ['params', 'header', 'totals', 'group'],\n row: ['params', 'header', 'totals', 'row'],\n}\n\n/**\n * The member of `group` that is the value the group is keyed by: in a group\n * header, `group.key` is the site a group of rows by site is for, of the\n * type of the field grouped by, and null for the group of rows without one.\n * An aggregate may not take the name (`reserved-id`), so `group.key` never\n * reads one.\n */\nexport const GROUP_KEY = 'key'\n\n/** A field of the header or the detail dataset: the one way the format refers to one. */\nexport interface FieldRef {\n readonly dataset: DatasetRole\n readonly field: string\n}\n\nexport const FORMAT_KINDS = ['number', 'currency', 'date', 'text'] as const\nexport type FormatKind = (typeof FORMAT_KINDS)[number]\n\nexport const DATE_STYLES = ['short', 'medium', 'long'] as const\nexport type DateStyle = (typeof DATE_STYLES)[number]\n\nexport const TEXT_TRANSFORMS = ['upper', 'lower'] as const\nexport type TextTransform = (typeof TEXT_TRANSFORMS)[number]\n\nexport interface NumberFormat {\n readonly kind: 'number'\n readonly scale: number\n readonly grouping: boolean\n}\n\nexport const CURRENCY_SOURCE_KINDS = ['code', 'field', 'parameter'] as const\nexport type CurrencySourceKind = (typeof CURRENCY_SOURCE_KINDS)[number]\n\n/** Which currency an amount is in: a code the template fixes, or a string field or parameter that supplies one per report or per row. */\nexport type CurrencySource =\n | { readonly kind: 'code'; /** ISO 4217, upper case. */ readonly code: string }\n | { readonly kind: 'field'; readonly field: FieldRef }\n | { readonly kind: 'parameter'; readonly parameter: string }\n\nexport interface CurrencyFormat {\n readonly kind: 'currency'\n readonly currency: CurrencySource\n readonly scale: number\n}\nexport interface DateFormat {\n readonly kind: 'date'\n readonly style: DateStyle\n}\nexport interface TextFormat {\n readonly kind: 'text'\n readonly transform?: TextTransform\n}\n/** How a value is displayed. Display only: calculation precision is the runtime's, with its declared rounding. */\nexport type Format = NumberFormat | CurrencyFormat | DateFormat | TextFormat\n\nexport interface TextInline {\n readonly kind: 'text'\n readonly text: string\n}\nexport interface FieldInline {\n readonly kind: 'field'\n readonly field: FieldRef\n readonly format?: Format\n}\nexport interface ParameterInline {\n readonly kind: 'parameter'\n readonly parameter: string\n readonly format?: Format\n}\nexport interface ExpressionInline {\n readonly kind: 'expression'\n readonly expression: Expression\n readonly format?: Format\n}\n\n/** Whose rows an aggregate is taken over where it is printed: the current group's, or every detail row. */\nexport const AGGREGATE_SCOPES = ['group', 'report'] as const\nexport type AggregateScope = (typeof AGGREGATE_SCOPES)[number]\n\nexport interface AggregateInline {\n readonly kind: 'aggregate'\n /** An `AggregateDef` id. */\n readonly aggregate: string\n readonly over: AggregateScope\n readonly format?: Format\n}\nexport interface PageNumberInline {\n readonly kind: 'pageNumber'\n}\nexport interface PageCountInline {\n readonly kind: 'pageCount'\n}\n\nexport const INLINE_KINDS = ['text', 'field', 'parameter', 'expression', 'aggregate', 'pageNumber', 'pageCount'] as const\nexport type InlineKind = (typeof INLINE_KINDS)[number]\n\n/**\n * A run of text: literal, bound, computed, totalled or a page counter. The\n * one shape for a paragraph's runs, a table cell, a footer cell and a group\n * header. Null prints as nothing.\n */\nexport type Inline = TextInline | FieldInline | ParameterInline | ExpressionInline | AggregateInline | PageNumberInline | PageCountInline\n\n/** What an aggregate reads from each detail row: a detail field, or an expression over the row. */\nexport type RowValue = { readonly kind: 'field'; readonly field: FieldRef } | { readonly kind: 'expression'; readonly expression: Expression }\n\nexport const AGGREGATE_FUNCTIONS = ['sum', 'count', 'min', 'max', 'avg'] as const\nexport type AggregateFunction = (typeof AGGREGATE_FUNCTIONS)[number]\n\nexport const ROUNDING_MODES = ['half-away-from-zero', 'half-even'] as const\nexport type RoundingMode = (typeof ROUNDING_MODES)[number]\n\n/**\n * Declared rounding: an exact decimal is rounded once, by a named rule,\n * never by a float. To a multiple of `increment` when it is given -- '0.05'\n * for Swiss cash rounding -- and otherwise to `scale` places; ties go by\n * `mode` either way.\n */\nexport interface Rounding {\n readonly scale: number\n readonly mode: RoundingMode\n /** An exact decimal more than 0, with no more than `scale` places. */\n readonly increment?: string\n}\n\n/**\n * A total the report computes over the detail dataset, exactly, once, in\n * the runtime. Declared once and printed by id, over the current group in a\n * group header or footer and over every detail row anywhere else.\n *\n * - `count` without `of` counts rows; with it, the rows where it is not null.\n * - `sum` and `avg` take integers and decimals; `min` and `max` those and\n * the three temporal types. Each skips nulls.\n * - Over no values, `count` and `sum` are 0, and `min`, `max` and `avg` are\n * null, which prints as nothing.\n * - `avg` is rarely exact, so it declares its rounding.\n */\nexport interface AggregateDef {\n /** A field key: what an expression reads it as, `totals.<id>` or `group.<id>`. Never `GROUP_KEY`, which `group` holds already. */\n readonly id: string\n readonly fn: AggregateFunction\n /** Absent only for count. */\n readonly of?: RowValue\n readonly rounding?: Rounding\n}\n\n/** A style applied when a condition holds: each rule that holds applies its style over the base one, in order, a later rule's property winning. */\nexport interface StyleRule {\n readonly when: Expression\n /** A `PrintStyle` id. */\n readonly style: string\n}\n\n/** What every component has: a stable id, and optionally a condition and print styles. */\nexport interface ComponentBase {\n readonly id: string\n readonly visibleWhen?: Expression\n /** A `PrintStyle` id. */\n readonly style?: string\n readonly styleWhen?: readonly StyleRule[]\n}\n\nexport interface TextComponent extends ComponentBase {\n readonly kind: 'text'\n readonly content: readonly Inline[]\n /** Never the last block on a page when something follows it: a heading moves with what it heads. */\n readonly keepWithNext?: boolean\n}\n\nexport const IMAGE_FITS = ['contain', 'cover'] as const\nexport type ImageFit = (typeof IMAGE_FITS)[number]\n\nexport const IMAGE_SOURCE_KINDS = ['asset', 'field'] as const\nexport type ImageSourceKind = (typeof IMAGE_SOURCE_KINDS)[number]\n\n/** What an image shows: an asset the template pins, the same in every render, or an image field of the header dataset, one per render. */\nexport type ImageSource = { readonly kind: 'asset'; /** An `AssetRef` id. */ readonly asset: string } | { readonly kind: 'field'; readonly field: FieldRef }\n\n/** An image drawn in a box of fixed size; the width and the height bound it whatever its source holds. */\nexport interface ImageComponent extends ComponentBase {\n readonly kind: 'image'\n readonly source: ImageSource\n readonly width: number\n readonly height: number\n readonly fit: ImageFit\n}\n\nexport interface LineComponent extends ComponentBase {\n readonly kind: 'line'\n readonly thickness: number\n readonly color?: string\n}\n\nexport interface RectangleComponent extends ComponentBase {\n readonly kind: 'rectangle'\n readonly width: number\n readonly height: number\n readonly fill?: string\n readonly stroke?: string\n}\n\nexport interface SpacerComponent extends ComponentBase {\n readonly kind: 'spacer'\n readonly height: number\n}\n\n/** A width in points, or a share of what fixed widths leave. */\nexport type Width = number | 'fill'\n\n/** One column of a columns block, as distinct from a table's column. */\nexport interface ColumnSlot {\n readonly width: Width\n readonly components: readonly Component[]\n}\n\nexport interface ColumnsComponent extends ComponentBase {\n readonly kind: 'columns'\n readonly columns: readonly ColumnSlot[]\n}\n\nexport interface Border {\n readonly thickness: number\n readonly color: string\n}\n\n/**\n * Components that belong together and nothing more: they flow as though\n * they stood where the section does, so one condition shows or hides them\n * all, and a border, a fill and padding can frame them. Unlike columns and\n * keep-together blocks, a section adds no layout rule.\n */\nexport interface SectionComponent extends ComponentBase {\n readonly kind: 'section'\n readonly components: readonly Component[]\n readonly border?: Border\n readonly fill?: string\n /** Points between the border and the content. */\n readonly padding?: number\n}\n\nexport const SORT_DIRECTIONS = ['asc', 'desc'] as const\nexport type SortDirection = (typeof SORT_DIRECTIONS)[number]\n\nexport interface SortKey {\n /** A detail field. */\n readonly field: FieldRef\n readonly direction: SortDirection\n}\n\nexport interface TableColumn {\n /** Unique within its table. */\n readonly id: string\n readonly header: string\n readonly width: Width\n readonly align: Alignment\n /** Read once per detail row. */\n readonly value: Inline\n /** Read once per report: a hidden column gives its width to the fill columns, and its footer cells hide with it. */\n readonly visibleWhen?: Expression\n readonly style?: string\n /** Read once per detail row. */\n readonly styleWhen?: readonly StyleRule[]\n}\n\nexport interface TableFooterCell {\n /** A column id of the same table. */\n readonly column: string\n readonly value: Inline\n}\n\n/** A row under a group or under the table: a subtotal, a tax line, a total. */\nexport interface TableFooterRow {\n readonly cells: readonly TableFooterCell[]\n readonly style?: string\n}\n\n/**\n * One grouping level, the only one version 0 has. Rows are ordered by the\n * group's key first, then by the table's sort keys; rows whose keys are all\n * equal keep the order the provider gave them.\n */\nexport interface TableGroup {\n /** A detail field. */\n readonly by: FieldRef\n readonly direction: SortDirection\n /** One line across the table, read once per group. */\n readonly header: readonly Inline[]\n readonly headerStyle?: string\n readonly footer: readonly TableFooterRow[]\n}\n\n/** The table over the report's one detail dataset. Its header repeats on every page; version 0 has no other choice. */\nexport interface TableComponent extends ComponentBase {\n readonly kind: 'table'\n readonly dataset: 'detail'\n readonly columns: readonly TableColumn[]\n readonly headerStyle?: string\n readonly sort?: readonly SortKey[]\n readonly group?: TableGroup\n readonly totals?: readonly TableFooterRow[]\n readonly emptyText: string\n readonly repeatHeader: true\n}\n\nexport interface PageBreakComponent extends ComponentBase {\n readonly kind: 'pageBreak'\n}\n\nexport interface KeepTogetherComponent extends ComponentBase {\n readonly kind: 'keepTogether'\n readonly components: readonly Component[]\n}\n\nexport const COMPONENT_KINDS = ['text', 'image', 'line', 'rectangle', 'spacer', 'columns', 'section', 'table', 'pageBreak', 'keepTogether'] as const\nexport type ComponentKind = (typeof COMPONENT_KINDS)[number]\n\nexport type Component =\n | TextComponent\n | ImageComponent\n | LineComponent\n | RectangleComponent\n | SpacerComponent\n | ColumnsComponent\n | SectionComponent\n | TableComponent\n | PageBreakComponent\n | KeepTogetherComponent\n\n/**\n * The report's regions, in the order a reader meets them. The body is flow\n * only in version 0: ordered blocks, so a growing table pushes what follows\n * down. Positioned elements in the page regions are deferred.\n */\nexport const REGION_NAMES = ['reportHeader', 'pageHeader', 'body', 'pageFooter', 'summary'] as const\nexport type RegionName = (typeof REGION_NAMES)[number]\n\nexport type Regions = { readonly [R in RegionName]: readonly Component[] }\n\nexport const PROVENANCE_KINDS = ['blank', 'form', 'dataset'] as const\nexport type ProvenanceKind = (typeof PROVENANCE_KINDS)[number]\n\n/**\n * Where a report was started from, so a reviewer can find the exact form\n * version or the dataset a generated report came from.\n */\nexport type Provenance =\n | { readonly kind: 'blank' }\n | {\n readonly kind: 'form'\n /** The form's id, as formancy writes one. */\n readonly form: string\n /** `schemaHash` of the exact form version: 64 lower-case hex digits. */\n readonly formHash: string\n }\n | { readonly kind: 'dataset'; /** The dataset's id in the deployment's catalogue. */ readonly dataset: string }\n\nexport interface ReportDefinition {\n readonly reportSpecVersion: typeof REPORT_SPEC_VERSION\n readonly id: string\n readonly title: string\n /** A BCP 47 tag: language, optional script, optional region. */\n readonly locale: string\n readonly page: PageSettings\n readonly styles: readonly PrintStyle[]\n readonly datasets: Datasets\n readonly parameters: readonly ParameterDef[]\n readonly assets: readonly AssetRef[]\n readonly aggregates: readonly AggregateDef[]\n readonly regions: Regions\n readonly provenance?: Provenance\n}\n","/**\n * What one validation knows while it reads a report: what the report\n * declares, which component ids it has seen, where its detail table is and\n * how much of the page its margins leave.\n */\nimport { Findings, quote } from './check.js'\nimport type { ReportErrorCode } from './errors.js'\nimport type { PageDimensions } from './page.js'\nimport type { FieldType, ParameterType } from './types.js'\n\n/**\n * Declared names and what each declares. `undefined` when the declarations\n * could not all be read: that was reported where they are, and a reference\n * that matches none of the rest could be the one that was unreadable, so\n * references into them are not reported again, one by one, as unknown.\n */\nexport type Declarations<T> = ReadonlyMap<string, T> | undefined\n\nexport interface Declared {\n styles: Declarations<true>\n /** By role; a role's fields are `undefined` when its contract could not be read. A field's type is `undefined` when its contract could not. */\n datasets: Declarations<Declarations<FieldType | undefined>>\n parameters: Declarations<ParameterType | undefined>\n assets: Declarations<true>\n /** What each aggregate computes, when that is known: what an expression computes is not. */\n aggregates: Declarations<FieldType | undefined>\n}\n\nexport interface Ctx {\n readonly f: Findings\n readonly declared: Declared\n /** Component ids seen so far, and the path of the first component with each. */\n readonly componentIds: Map<string, string>\n /** Where the table over the detail dataset is, once one has been read. */\n detailTable: string | undefined\n /** What the margins leave of the page, once they are known to leave enough; fixed sizes are measured against it. */\n printable: PageDimensions | undefined\n}\n\nexport function newContext(): Ctx {\n return {\n f: new Findings(),\n declared: { styles: undefined, datasets: undefined, parameters: undefined, assets: undefined, aggregates: undefined },\n componentIds: new Map(),\n detailTable: undefined,\n printable: undefined,\n }\n}\n\n/** What `name` declares, after reporting `code` when it is not declared. Nothing is checked when either is unknown. */\nexport function resolve<T>(f: Findings, names: Declarations<T>, name: string | undefined, path: string, code: ReportErrorCode, what: string): T | undefined {\n if (names === undefined || name === undefined) return undefined\n if (names.has(name)) return names.get(name)\n f.report(path, code, `${quote(name)} is not a ${what} this report declares`)\n return undefined\n}\n\n/** One entry of a list of declarations: its id when it could be read, where the id is, and what it declares. */\nexport interface Declaration<T> {\n readonly id: string | undefined\n readonly path: string\n readonly value: T\n}\n\n/**\n * The names a list declares, each id after the first reported as a\n * duplicate, with `code` and what `again` says of it. `undefined` when an id\n * could not be read.\n *\n * One rule for every list whose entries are named -- declarations, a\n * table's columns, a footer row's cells, the keys that order a table -- so\n * that a second entry with one name is refused the same way everywhere.\n */\nexport function declare<T>(f: Findings, entries: readonly Declaration<T>[], code: ReportErrorCode, again: (id: string) => string): Map<string, T> | undefined {\n const declared = new Map<string, T>()\n let complete = true\n for (const { id, path, value } of entries) {\n if (id === undefined) complete = false\n else if (declared.has(id)) f.report(path, code, again(quote(id)))\n else declared.set(id, value)\n }\n return complete ? declared : undefined\n}\n\n/**\n * Reports a fixed length the page cannot hold. The page and its margins are\n * in the same document, so a size that can never fit is refused while the\n * author edits; what fits inside a container is the layout's question.\n */\nexport function withinPage(c: Ctx, length: number | undefined, path: string, side: 'width' | 'height', what: string): void {\n const room = c.printable?.[side]\n if (length === undefined || room === undefined || length <= room) return\n c.f.report(path, 'exceeds-printable-area', `${length} points of ${side} for ${what}, and the margins leave ${room}`)\n}\n","/**\n * Values: what a paragraph, a table cell or a footer is made of, where each\n * kind of value has one, and how it is displayed.\n *\n * Kinds are tables, not switches, as components are: an inline, format or\n * currency source added to its list without a reader here does not compile.\n */\nimport { all, flag, integer, kindOf, matches, oneOf, optional, quote, readArray, readObject, reference, shape, strictKeys, text } from './check.js'\nimport type { Findings } from './check.js'\nimport { MAX_EXPRESSION_LENGTH, MAX_INLINES, MAX_SCALE, MAX_STYLE_RULES, MAX_TEXT_LENGTH } from './limits.js'\nimport { at } from './pointer.js'\nimport { CURRENCY } from './syntax.js'\nimport { AGGREGATE_SCOPES, CURRENCY_SOURCE_KINDS, DATASET_ROLES, DATE_STYLES, FORMAT_KINDS, INLINE_KINDS, TEXT_TRANSFORMS } from './types.js'\nimport type {\n CurrencySource,\n CurrencySourceKind,\n Expression,\n FieldRef,\n FieldType,\n Format,\n FormatKind,\n Inline,\n InlineKind,\n RegionName,\n RowValue,\n StyleRule,\n ValueScope,\n} from './types.js'\nimport { resolve } from './validate-context.js'\nimport type { Ctx } from './validate-context.js'\n\n/** Where a value is read: the region decides page counters, the scope decides detail fields and a group's aggregates. */\nexport interface InlineScope {\n readonly region: RegionName\n readonly reads: ValueScope\n /** In a group header or footer, the detail field grouped by, when the dataset declares it. */\n readonly groupBy?: string | undefined\n}\n\n/** The regions drawn once per page, the only ones in which a page number or count has a value. */\nconst PAGE_REGIONS: readonly RegionName[] = ['pageHeader', 'pageFooter']\n\nexport function readExpression(f: Findings, value: unknown, path: string): Expression | undefined {\n const o = shape(f, value, path, ['cel'])\n const cel = text(f, o?.cel, at(path, 'cel'), MAX_EXPRESSION_LENGTH)\n if (cel === undefined) return undefined\n if (cel.trim() !== '') return { cel }\n f.report(at(path, 'cel'), 'empty-expression', 'an expression needs something to evaluate, and this one is empty')\n return undefined\n}\n\n/** A reference to a print style the report declares. */\nexport function readStyleRef(c: Ctx, value: unknown, path: string): string | undefined {\n const style = reference(c.f, value, path)\n resolve(c.f, c.declared.styles, style, path, 'unknown-style', 'style')\n return style\n}\n\n/** Conditional styles: each a condition and the style it applies. */\nexport function readStyleRules(c: Ctx, value: unknown, path: string): readonly StyleRule[] | undefined {\n const items = readArray(c.f, value, path, MAX_STYLE_RULES)\n const rules = items?.map((item, index): StyleRule | undefined => {\n const where = at(path, index)\n const o = shape(c.f, item, where, ['when', 'style'])\n const when = readExpression(c.f, o?.when, at(where, 'when'))\n const style = readStyleRef(c, o?.style, at(where, 'style'))\n return when === undefined || style === undefined ? undefined : { when, style }\n })\n return rules && all(rules)\n}\n\n/** A field reference, its field's type when known, and whether the dataset declares the field. */\nexport interface FieldBinding {\n readonly ref: FieldRef\n readonly type: FieldType | undefined\n readonly declared: boolean\n}\n\n/** Reports a detail field read where there is no current row. */\nfunction placeDetailField(c: Ctx, field: string, path: string, scope: InlineScope): void {\n if (scope.reads === 'row') return\n if (scope.reads === 'report') {\n c.f.report(path, 'misplaced-detail-field', 'a detail field has a current row only in the cells of the table over the detail dataset')\n } else if (scope.groupBy !== undefined && field !== scope.groupBy) {\n c.f.report(path, 'misplaced-detail-field', `in a group header or footer, the one detail field with a single value is the one grouped by, ${quote(scope.groupBy)}`)\n }\n}\n\n/**\n * A FieldRef read in `scope`, or, where only a detail field can be named --\n * a sort key, a group key, what an aggregate reads -- with `scope` 'detail'.\n */\nexport function readFieldRef(c: Ctx, value: unknown, path: string, scope: InlineScope | 'detail'): FieldBinding | undefined {\n const o = shape(c.f, value, path, ['dataset', 'field'])\n const dataset = oneOf(c.f, o?.dataset, at(path, 'dataset'), scope === 'detail' ? (['detail'] as const) : DATASET_ROLES)\n const field = reference(c.f, o?.field, at(path, 'field'))\n if (scope !== 'detail' && dataset === 'detail' && field !== undefined) placeDetailField(c, field, path, scope)\n const fields = resolve(c.f, c.declared.datasets, dataset, at(path, 'dataset'), 'unknown-dataset', 'dataset')\n const type = resolve(c.f, fields, field, at(path, 'field'), 'unknown-field', `field of the ${String(dataset)} dataset`)\n if (dataset === undefined || field === undefined) return undefined\n return { ref: { dataset, field }, type, declared: fields?.has(field) === true }\n}\n\n/** Reports a field or parameter whose type is not `wanted`, where it is bound. */\nfunction expectType(c: Ctx, type: FieldType | undefined, wanted: FieldType, path: string, where: string): void {\n if (type !== undefined && type !== wanted) c.f.report(path, 'binding-type-mismatch', `${where} reads a ${wanted}, and this is a ${type}`)\n}\n\ntype CurrencyReader = (c: Ctx, o: Record<string, unknown>, path: string, scope: InlineScope) => CurrencySource | undefined\n\nconst CURRENCIES: { readonly [K in CurrencySourceKind]: { readonly required: readonly string[]; readonly read: CurrencyReader } } = {\n code: {\n required: ['code'],\n read: (c, o, path) => {\n const code = matches(c.f, o.code, at(path, 'code'), CURRENCY, 'invalid-currency', 'an ISO 4217 code in capitals, such as CHF')\n return code === undefined ? undefined : { kind: 'code', code }\n },\n },\n field: {\n required: ['field'],\n read: (c, o, path, scope) => {\n const field = readFieldRef(c, o.field, at(path, 'field'), scope)\n expectType(c, field?.type, 'string', at(path, 'field'), 'a currency')\n return field && { kind: 'field', field: field.ref }\n },\n },\n parameter: {\n required: ['parameter'],\n read: (c, o, path) => {\n const parameter = reference(c.f, o.parameter, at(path, 'parameter'))\n const type = resolve(c.f, c.declared.parameters, parameter, at(path, 'parameter'), 'unknown-parameter', 'parameter')\n expectType(c, type, 'string', at(path, 'parameter'), 'a currency')\n return parameter === undefined ? undefined : { kind: 'parameter', parameter }\n },\n },\n}\n\nfunction readCurrency(c: Ctx, value: unknown, path: string, scope: InlineScope): CurrencySource | undefined {\n const o = readObject(c.f, value, path)\n const kind = o && kindOf(c.f, o, path, CURRENCY_SOURCE_KINDS)\n if (o === undefined || kind === undefined) return undefined\n strictKeys(c.f, o, path, ['kind', ...CURRENCIES[kind].required])\n return CURRENCIES[kind].read(c, o, path, scope)\n}\n\ntype FormatReader = (c: Ctx, o: Record<string, unknown>, path: string, scope: InlineScope) => Format | undefined\n\nconst FORMATS: { readonly [K in FormatKind]: FormatReader } = {\n number: (c, o, path) => {\n strictKeys(c.f, o, path, ['kind', 'scale', 'grouping'])\n const scale = integer(c.f, o.scale, at(path, 'scale'), 0, MAX_SCALE)\n const grouping = flag(c.f, o.grouping, at(path, 'grouping'))\n return scale === undefined || grouping === undefined ? undefined : { kind: 'number', scale, grouping }\n },\n currency: (c, o, path, scope) => {\n strictKeys(c.f, o, path, ['kind', 'currency', 'scale'])\n const currency = readCurrency(c, o.currency, at(path, 'currency'), scope)\n const scale = integer(c.f, o.scale, at(path, 'scale'), 0, MAX_SCALE)\n return currency === undefined || scale === undefined ? undefined : { kind: 'currency', currency, scale }\n },\n date: (c, o, path) => {\n strictKeys(c.f, o, path, ['kind', 'style'])\n const style = oneOf(c.f, o.style, at(path, 'style'), DATE_STYLES)\n return style === undefined ? undefined : { kind: 'date', style }\n },\n text: (c, o, path) => {\n strictKeys(c.f, o, path, ['kind'], ['transform'])\n return { kind: 'text', ...optional('transform', oneOf(c.f, o.transform, at(path, 'transform'), TEXT_TRANSFORMS)) }\n },\n}\n\nfunction readFormat(c: Ctx, value: unknown, path: string, scope: InlineScope): Format | undefined {\n const o = readObject(c.f, value, path)\n const kind = o && kindOf(c.f, o, path, FORMAT_KINDS)\n return o && kind && FORMATS[kind](c, o, path, scope)\n}\n\n/** The types each format displays. Text displays anything that prints. */\nconst FORMATTED: { readonly [K in FormatKind]: readonly FieldType[] | 'any' } = {\n number: ['integer', 'decimal'],\n currency: ['integer', 'decimal'],\n date: ['date', 'datetime', 'instant'],\n text: 'any',\n}\n\n/**\n * The format at `path` read, and reported when it does not display a value\n * of `type`. An expression's type is known only when the runtime compiles\n * it, so its format is not checked here: `type` is then undefined.\n */\nfunction readCheckedFormat(c: Ctx, value: unknown, path: string, scope: InlineScope, type: FieldType | undefined): Format | undefined {\n const format = readFormat(c, value, path, scope)\n const formatted = format && FORMATTED[format.kind]\n if (format !== undefined && type !== undefined && formatted !== 'any' && formatted?.includes(type) === false) {\n c.f.report(path, 'format-type-mismatch', `a ${format.kind} format displays ${formatted.join(', ')} values, and this value is a ${type}`)\n }\n return format\n}\n\n/** A page number or count, and whether it stands where it has a value. A table never stands in a page region, so its cells are refused by region too. */\nfunction readCounter(c: Ctx, path: string, scope: InlineScope, kind: 'pageNumber' | 'pageCount'): Inline {\n if (!PAGE_REGIONS.includes(scope.region)) {\n c.f.report(path, 'misplaced-page-counter', `page numbers and counts have a value only in the page header and footer, not in the ${scope.region}`)\n }\n return { kind }\n}\n\ninterface InlineRule {\n readonly required: readonly string[]\n readonly optional?: readonly string[]\n readonly read: (c: Ctx, o: Record<string, unknown>, path: string, scope: InlineScope) => Inline | undefined\n}\n\nconst INLINES: { readonly [K in InlineKind]: InlineRule } = {\n text: {\n required: ['text'],\n read: (c, o, path) => {\n const literal = text(c.f, o.text, at(path, 'text'), MAX_TEXT_LENGTH)\n return literal === undefined ? undefined : { kind: 'text', text: literal }\n },\n },\n field: {\n required: ['field'],\n optional: ['format'],\n read: (c, o, path, scope) => {\n const field = readFieldRef(c, o.field, at(path, 'field'), scope)\n // An image is drawn by an image component; printed, it would be an asset id.\n if (field?.type === 'image') c.f.report(at(path, 'field'), 'binding-type-mismatch', 'an image field is drawn by an image, never printed as text')\n const format = readCheckedFormat(c, o.format, at(path, 'format'), scope, field?.type === 'image' ? undefined : field?.type)\n return field && { kind: 'field', field: field.ref, ...optional('format', format) }\n },\n },\n parameter: {\n required: ['parameter'],\n optional: ['format'],\n read: (c, o, path, scope) => {\n const parameter = reference(c.f, o.parameter, at(path, 'parameter'))\n const type = resolve(c.f, c.declared.parameters, parameter, at(path, 'parameter'), 'unknown-parameter', 'parameter')\n const format = readCheckedFormat(c, o.format, at(path, 'format'), scope, type)\n return parameter === undefined ? undefined : { kind: 'parameter', parameter, ...optional('format', format) }\n },\n },\n expression: {\n required: ['expression'],\n optional: ['format'],\n read: (c, o, path, scope) => {\n const expression = readExpression(c.f, o.expression, at(path, 'expression'))\n const format = readCheckedFormat(c, o.format, at(path, 'format'), scope, undefined)\n return expression && { kind: 'expression', expression, ...optional('format', format) }\n },\n },\n aggregate: {\n required: ['aggregate', 'over'],\n optional: ['format'],\n read: (c, o, path, scope) => {\n const aggregate = reference(c.f, o.aggregate, at(path, 'aggregate'))\n const type = resolve(c.f, c.declared.aggregates, aggregate, at(path, 'aggregate'), 'unknown-aggregate', 'aggregate')\n const over = oneOf(c.f, o.over, at(path, 'over'), AGGREGATE_SCOPES)\n if (over === 'group' && scope.reads !== 'group') {\n c.f.report(at(path, 'over'), 'misplaced-group-aggregate', 'an aggregate over a group has a value only in that group\\'s header and footer; over \"report\", it is taken over every row')\n }\n const format = readCheckedFormat(c, o.format, at(path, 'format'), scope, type)\n return aggregate === undefined || over === undefined ? undefined : { kind: 'aggregate', aggregate, over, ...optional('format', format) }\n },\n },\n pageNumber: { required: [], read: (c, _o, path, scope) => readCounter(c, path, scope, 'pageNumber') },\n pageCount: { required: [], read: (c, _o, path, scope) => readCounter(c, path, scope, 'pageCount') },\n}\n\nexport function readInline(c: Ctx, value: unknown, path: string, scope: InlineScope): Inline | undefined {\n const o = readObject(c.f, value, path)\n const kind = o && kindOf(c.f, o, path, INLINE_KINDS)\n if (o === undefined || kind === undefined) return undefined\n const rule = INLINES[kind]\n strictKeys(c.f, o, path, ['kind', ...rule.required], rule.optional)\n return rule.read(c, o, path, scope)\n}\n\nexport function readInlines(c: Ctx, value: unknown, path: string, scope: InlineScope): readonly Inline[] | undefined {\n const items = readArray(c.f, value, path, MAX_INLINES)\n return items && all(items.map((item, index) => readInline(c, item, at(path, index), scope)))\n}\n\n/** What an aggregate reads from each row, and that value's type when it is a field's. */\nexport function readRowValue(c: Ctx, value: unknown, path: string): { value: RowValue; type: FieldType | undefined } | undefined {\n const o = readObject(c.f, value, path)\n const kind = o && kindOf(c.f, o, path, ['field', 'expression'] as const)\n if (o === undefined || kind === undefined) return undefined\n strictKeys(c.f, o, path, ['kind', kind])\n if (kind === 'expression') {\n const expression = readExpression(c.f, o.expression, at(path, 'expression'))\n return expression && { value: { kind, expression }, type: undefined }\n }\n const field = readFieldRef(c, o.field, at(path, 'field'), 'detail')\n return field && { value: { kind, field: field.ref }, type: field.type }\n}\n","/**\n * Aggregates: the totals a report computes over its detail rows, declared\n * once and printed by id, and the rounding each declares.\n */\nimport type { Findings } from './check.js'\nimport { all, fieldKey, integer, matches, oneOf, optional, readArray, shape } from './check.js'\nimport { MAX_AGGREGATES, MAX_SCALE } from './limits.js'\nimport { at } from './pointer.js'\nimport { DECIMAL } from './syntax.js'\nimport { AGGREGATE_FUNCTIONS, GROUP_KEY, ROUNDING_MODES } from './types.js'\nimport type { AggregateDef, AggregateFunction, FieldType, Rounding } from './types.js'\nimport { declare } from './validate-context.js'\nimport type { Ctx } from './validate-context.js'\nimport { readRowValue } from './validate-inline.js'\n\nconst NUMERIC: readonly FieldType[] = ['integer', 'decimal']\nconst ORDERED: readonly FieldType[] = [...NUMERIC, 'date', 'datetime', 'instant']\n\n/**\n * What each function reads, and what it computes from a value of a type:\n * a count is an integer, an average a decimal, and a sum, minimum or\n * maximum the type it read. Unknown when what it read is an expression.\n */\nconst FUNCTIONS: { readonly [F in AggregateFunction]: { readonly takes: readonly FieldType[] | 'any'; readonly gives: (of: FieldType | undefined) => FieldType | undefined } } = {\n sum: { takes: NUMERIC, gives: (of) => of },\n avg: { takes: NUMERIC, gives: () => 'decimal' },\n min: { takes: ORDERED, gives: (of) => of },\n max: { takes: ORDERED, gives: (of) => of },\n count: { takes: 'any', gives: () => 'integer' },\n}\n\n/** A rounding increment: an exact decimal more than 0, with no more places than `scale`. */\nfunction readIncrement(f: Findings, value: unknown, path: string, scale: number | undefined): string | undefined {\n const increment = matches(f, value, path, DECIMAL, 'invalid-decimal', 'an exact decimal such as \"0.05\"')\n if (increment === undefined) return undefined\n if (increment.startsWith('-') || /^0(?:\\.0+)?$/.test(increment)) {\n f.report(path, 'out-of-range', `an increment of ${increment} rounds to nothing; it must be more than 0`)\n return undefined\n }\n const places = increment.split('.')[1]?.length ?? 0\n if (scale !== undefined && places > scale) {\n f.report(path, 'out-of-range', `an increment of ${increment} has ${places} decimal places, more than the ${scale} this rounding keeps`)\n return undefined\n }\n return increment\n}\n\nfunction readRounding(f: Findings, value: unknown, path: string): Rounding | undefined {\n const o = shape(f, value, path, ['scale', 'mode'], ['increment'])\n const scale = integer(f, o?.scale, at(path, 'scale'), 0, MAX_SCALE)\n const mode = oneOf(f, o?.mode, at(path, 'mode'), ROUNDING_MODES)\n const increment = readIncrement(f, o?.increment, at(path, 'increment'), scale)\n return scale === undefined || mode === undefined ? undefined : { scale, mode, ...optional('increment', increment) }\n}\n\nfunction readAggregate(c: Ctx, value: unknown, path: string): { id: string | undefined; gives: FieldType | undefined; aggregate: AggregateDef | undefined } {\n const o = shape(c.f, value, path, ['id', 'fn'], ['of', 'rounding'])\n const id = fieldKey(c.f, o?.id, at(path, 'id'))\n // group.key is the value a group is keyed by; an aggregate of that name would be read there as one or the other.\n if (id === GROUP_KEY) c.f.report(at(path, 'id'), 'reserved-id', `an aggregate cannot be called ${GROUP_KEY}: in a group's header and footer, group.${GROUP_KEY} is the value the group is keyed by`)\n const fn = oneOf(c.f, o?.fn, at(path, 'fn'), AGGREGATE_FUNCTIONS)\n const of = readRowValue(c, o?.of, at(path, 'of'))\n if (o !== undefined && fn !== undefined && fn !== 'count' && !Object.hasOwn(o, 'of')) {\n c.f.report(at(path, 'of'), 'missing-property', `a ${fn} needs a value from each row; only a count may leave it out, to count rows`)\n }\n const takes = fn && FUNCTIONS[fn].takes\n const mismatch = takes !== undefined && takes !== 'any' && of?.type !== undefined && !takes.includes(of.type)\n if (mismatch) c.f.report(at(at(path, 'of'), 'field'), 'aggregate-type-mismatch', `${fn} takes ${takes.join(', ')} values, and this field is a ${of.type}`)\n const rounding = readRounding(c.f, o?.rounding, at(path, 'rounding'))\n // An exact average is rarely a terminating decimal: 1, 1 and 2 average 1.333...\n if (o !== undefined && fn === 'avg' && !Object.hasOwn(o, 'rounding')) {\n c.f.report(at(path, 'rounding'), 'missing-property', 'an average is rarely exact, so it says how it is rounded')\n }\n // A refused aggregate computes nothing known, so what prints it is not refused again for that.\n const gives = mismatch ? undefined : fn && FUNCTIONS[fn].gives(of?.type)\n if (id === undefined || fn === undefined || (o?.of !== undefined && of === undefined)) return { id, gives, aggregate: undefined }\n return { id, gives, aggregate: { id, fn, ...optional('of', of?.value), ...optional('rounding', rounding) } }\n}\n\nexport function readAggregates(c: Ctx, value: unknown, path: string): readonly AggregateDef[] | undefined {\n const items = readArray(c.f, value, path, MAX_AGGREGATES)\n if (items === undefined) return undefined\n const read = items.map((item, index) => ({ index, ...readAggregate(c, item, at(path, index)) }))\n c.declared.aggregates = declare(\n c.f,\n read.map(({ id, index, gives }) => ({ id, path: at(at(path, index), 'id'), value: gives })),\n 'duplicate-id',\n (duplicate) => `another aggregate is already ${duplicate}`,\n )\n return all(read.map(({ aggregate }) => aggregate))\n}\n","/**\n * The table over the detail dataset: its columns, single grouping level,\n * sort and footer rows, and the references each makes into the detail\n * dataset and into the table's own columns.\n */\nimport { all, identifier, oneOf, optional, quote, readArray, readList, reference, shape, text, width } from './check.js'\nimport { MAX_FOOTER_ROWS, MAX_LABEL_LENGTH, MAX_SORT_KEYS, MAX_TABLE_COLUMNS } from './limits.js'\nimport { at } from './pointer.js'\nimport { ALIGNMENTS, SORT_DIRECTIONS } from './types.js'\nimport type { ComponentBase, RegionName, SortKey, TableColumn, TableComponent, TableFooterCell, TableFooterRow, TableGroup, Width } from './types.js'\nimport { declare, resolve, withinPage } from './validate-context.js'\nimport type { Ctx, Declarations } from './validate-context.js'\nimport { readExpression, readFieldRef, readInline, readInlines, readStyleRef, readStyleRules } from './validate-inline.js'\nimport type { FieldBinding, InlineScope } from './validate-inline.js'\nimport { roundPt } from './units.js'\n\nexport const TABLE_REQUIRED = ['dataset', 'columns', 'emptyText', 'repeatHeader']\nexport const TABLE_OPTIONAL = ['headerStyle', 'sort', 'group', 'totals']\n\n/** Reports a sort or group key whose field is an image: an image has no order. */\nfunction orderable(c: Ctx, key: FieldBinding | undefined, path: string): void {\n if (key?.type === 'image') c.f.report(path, 'binding-type-mismatch', 'an image field has no order to sort or group by')\n}\n\n/** Reports fixed widths that add up to more than the printable width; fill columns share what is left. */\nexport function checkFixedWidths(c: Ctx, widths: readonly (Width | undefined)[], path: string): void {\n const fixed = all(widths)?.reduce<number>((total, columnWidth) => total + (columnWidth === 'fill' ? 0 : columnWidth), 0)\n withinPage(c, fixed === undefined ? undefined : roundPt(fixed), path, 'width', 'the fixed widths of these columns')\n}\n\nfunction readTableColumn(c: Ctx, value: unknown, path: string, region: RegionName): { id: string | undefined; width: Width | undefined; column: TableColumn | undefined } {\n const o = shape(c.f, value, path, ['id', 'header', 'width', 'align', 'value'], ['visibleWhen', 'style', 'styleWhen'])\n const id = identifier(c.f, o?.id, at(path, 'id'))\n const header = text(c.f, o?.header, at(path, 'header'), MAX_LABEL_LENGTH)\n const columnWidth = width(c.f, o?.width, at(path, 'width'))\n const align = oneOf(c.f, o?.align, at(path, 'align'), ALIGNMENTS)\n const cell = readInline(c, o?.value, at(path, 'value'), { region, reads: 'row' })\n const visibleWhen = readExpression(c.f, o?.visibleWhen, at(path, 'visibleWhen'))\n const style = readStyleRef(c, o?.style, at(path, 'style'))\n const styleWhen = readStyleRules(c, o?.styleWhen, at(path, 'styleWhen'))\n if (id === undefined || header === undefined || columnWidth === undefined || align === undefined || cell === undefined) return { id, width: columnWidth, column: undefined }\n const column = { id, header, width: columnWidth, align, value: cell, ...optional('visibleWhen', visibleWhen), ...optional('style', style), ...optional('styleWhen', styleWhen) }\n return { id, width: columnWidth, column }\n}\n\n/** A footer cell, and the column it names when that could be read. */\nfunction readFooterCell(c: Ctx, value: unknown, path: string, scope: InlineScope, columns: Declarations<true>): { column: string | undefined; cell: TableFooterCell | undefined } {\n const o = shape(c.f, value, path, ['column', 'value'])\n const column = reference(c.f, o?.column, at(path, 'column'))\n if (column !== undefined && columns !== undefined && !columns.has(column)) {\n c.f.report(at(path, 'column'), 'unknown-column', `this table has no column ${quote(column)}`)\n }\n const cellValue = readInline(c, o?.value, at(path, 'value'), scope)\n return { column, cell: column === undefined || cellValue === undefined ? undefined : { column, value: cellValue } }\n}\n\n/** A footer row: at most one cell per column, each under a column the table has. */\nfunction readFooterRow(c: Ctx, value: unknown, path: string, scope: InlineScope, columns: Declarations<true>): TableFooterRow | undefined {\n const o = shape(c.f, value, path, ['cells'], ['style'])\n const where = at(path, 'cells')\n const cells = readArray(c.f, o?.cells, where, MAX_TABLE_COLUMNS)?.map((item, index) => readFooterCell(c, item, at(where, index), scope, columns))\n const named = (cells ?? []).map(({ column }, index) => ({ id: column, path: at(at(where, index), 'column'), value: true }))\n declare(c.f, named, 'duplicate-footer-cell', (column) => `column ${column} already has a cell in this row`)\n const style = readStyleRef(c, o?.style, at(path, 'style'))\n const read = cells && all(cells.map(({ cell }) => cell))\n return read && { cells: read, ...optional('style', style) }\n}\n\nfunction readFooterRows(c: Ctx, value: unknown, path: string, scope: InlineScope, columns: Declarations<true>): readonly TableFooterRow[] | undefined {\n const rows = readArray(c.f, value, path, MAX_FOOTER_ROWS)?.map((row, index) => readFooterRow(c, row, at(path, index), scope, columns))\n return rows && all(rows)\n}\n\nfunction readGroup(c: Ctx, value: unknown, path: string, region: RegionName, columns: Declarations<true>): { group: TableGroup | undefined; by: string | undefined } {\n const o = shape(c.f, value, path, ['by', 'direction', 'header', 'footer'], ['headerStyle'])\n const by = readFieldRef(c, o?.by, at(path, 'by'), 'detail')\n orderable(c, by, at(path, 'by'))\n // Only a field the dataset declares can be checked against: with an\n // unknown one, the header's detail fields are not refused for not being it.\n const scope: InlineScope = { region, reads: 'group', groupBy: by?.declared === true ? by.ref.field : undefined }\n const direction = oneOf(c.f, o?.direction, at(path, 'direction'), SORT_DIRECTIONS)\n const header = readInlines(c, o?.header, at(path, 'header'), scope)\n const headerStyle = readStyleRef(c, o?.headerStyle, at(path, 'headerStyle'))\n const footer = readFooterRows(c, o?.footer, at(path, 'footer'), scope, columns)\n if (by === undefined || direction === undefined || header === undefined || footer === undefined) return { group: undefined, by: by?.ref.field }\n return { group: { by: by.ref, direction, header, ...optional('headerStyle', headerStyle), footer }, by: by.ref.field }\n}\n\n/** Sort keys, after the group's key: rows are ordered by the group's key first, so a key on that field, or on one already sorted by, orders nothing. */\nfunction readSort(c: Ctx, value: unknown, path: string, groupBy: string | undefined): readonly SortKey[] | undefined {\n const keys = readArray(c.f, value, path, MAX_SORT_KEYS)?.map((item, index) => {\n const where = at(path, index)\n const o = shape(c.f, item, where, ['field', 'direction'])\n const field = readFieldRef(c, o?.field, at(where, 'field'), 'detail')\n orderable(c, field, at(where, 'field'))\n const direction = oneOf(c.f, o?.direction, at(where, 'direction'), SORT_DIRECTIONS)\n return { field, direction, path: at(where, 'field') }\n })\n // The group's key orders first, so it is declared before the sort keys.\n const group = groupBy === undefined ? [] : [{ id: groupBy, path, value: true }]\n const sorted = (keys ?? []).map(({ field, path: fieldPath }) => ({ id: field?.ref.field, path: fieldPath, value: true }))\n declare(c.f, [...group, ...sorted], 'duplicate-sort-key', (field) => `${field} already orders these rows, as the group's key or an earlier sort key; a second key on it orders nothing`)\n return keys && all(keys.map(({ field, direction }) => (field === undefined || direction === undefined ? undefined : { field: field.ref, direction })))\n}\n\n/**\n * The table, after refusing a second one: version 0 has one primary detail\n * dataset (plan 10) and one table over it.\n */\nexport function readTable(c: Ctx, o: Record<string, unknown>, path: string, region: RegionName, base: ComponentBase | undefined): TableComponent | undefined {\n if (c.detailTable === undefined) c.detailTable = path\n else c.f.report(path, 'second-detail-table', `a report has one table over the detail dataset in version 0, and this one's is at ${c.detailTable}`)\n const dataset = oneOf(c.f, o.dataset, at(path, 'dataset'), ['detail'])\n resolve(c.f, c.declared.datasets, dataset, at(path, 'dataset'), 'unknown-dataset', 'dataset')\n const read = readList(c.f, o.columns, at(path, 'columns'), 1, MAX_TABLE_COLUMNS)?.map((item, index) => readTableColumn(c, item, at(at(path, 'columns'), index), region))\n const columnIds =\n read &&\n declare(\n c.f,\n read.map(({ id }, index) => ({ id, path: at(at(at(path, 'columns'), index), 'id'), value: true as const })),\n 'duplicate-column-id',\n (id) => `this table already has a column ${id}`,\n )\n if (read !== undefined) checkFixedWidths(c, read.map(({ width: columnWidth }) => columnWidth), at(path, 'columns'))\n const headerStyle = readStyleRef(c, o.headerStyle, at(path, 'headerStyle'))\n const group = readGroup(c, o.group, at(path, 'group'), region, columnIds)\n const sort = readSort(c, o.sort, at(path, 'sort'), group.by)\n const totals = readFooterRows(c, o.totals, at(path, 'totals'), { region, reads: 'report' }, columnIds)\n const emptyText = text(c.f, o.emptyText, at(path, 'emptyText'), MAX_LABEL_LENGTH)\n const repeatHeader = oneOf(c.f, o.repeatHeader, at(path, 'repeatHeader'), [true])\n const columns = read && all(read.map(({ column }) => column))\n if (base === undefined || dataset === undefined || columns === undefined || emptyText === undefined || repeatHeader === undefined) return undefined\n return {\n ...base,\n kind: 'table',\n dataset,\n columns,\n ...optional('headerStyle', headerStyle),\n ...optional('sort', sort),\n ...optional('group', group.group),\n ...optional('totals', totals),\n emptyText,\n repeatHeader,\n }\n}\n","/**\n * Components: the shape of each kind, and where each may stand.\n *\n * Kinds are a table, not a switch: each entry says which properties its\n * kind has, whether and how it holds other components, where it may stand,\n * and how to read what is particular to it. A kind added to COMPONENT_KINDS\n * without an entry here does not compile.\n */\nimport { all, flag, identifier, kindOf, matches, oneOf, optional, points, readArray, readList, readObject, reference, shape, strictKeys, width } from './check.js'\nimport { MAX_COLUMNS, MAX_NESTING_DEPTH, MAX_REGION_COMPONENTS, MIN_COLUMNS } from './limits.js'\nimport { at } from './pointer.js'\nimport { COLOR } from './syntax.js'\nimport { COMPONENT_KINDS, IMAGE_FITS, IMAGE_SOURCE_KINDS } from './types.js'\nimport type { Border, ColumnSlot, Component, ComponentBase, ComponentKind, ImageSource, ImageSourceKind, RegionName, Width } from './types.js'\nimport { resolve, withinPage } from './validate-context.js'\nimport type { Ctx } from './validate-context.js'\nimport { readExpression, readFieldRef, readInlines, readStyleRef, readStyleRules } from './validate-inline.js'\nimport { checkFixedWidths, readTable, TABLE_OPTIONAL, TABLE_REQUIRED } from './validate-table.js'\n\nexport interface ComponentScope {\n readonly region: RegionName\n /** Where the region is, for the error when its budget runs out. */\n readonly regionPath: string\n /** How many containers enclose the components being read: 0 at a region's top level. */\n readonly depth: number\n /** The innermost columns or keep-together block around the components being read, if any: no table or page break stands in one. */\n readonly layout: ComponentKind | undefined\n /** How many more components the region may hold; one budget for every list in the region. */\n readonly budget: { left: number }\n}\n\n/** The regions content flows through; the others are drawn at a fixed place on a page. */\nconst FLOW_REGIONS: readonly RegionName[] = ['body', 'summary']\n\nconst COLOR_RULE = 'a colour written #rrggbb in lower case'\n\ninterface KindRule<C extends Component> {\n readonly required: readonly string[]\n readonly optional?: readonly string[]\n /**\n * Holds components of its own: 'layout' when it lays them out (columns,\n * keep-together), 'flow' when they flow as though it were not there (a\n * section). Either counts toward the nesting depth.\n */\n readonly holds?: 'layout' | 'flow'\n /** May stand only in a region content flows through. */\n readonly flowOnly?: true\n /** Is part of the flow itself, so never inside a columns or keep-together block. */\n readonly inFlow?: true\n /**\n * What is particular to the kind. `scope` is the scope of what a\n * container holds, and the component's own for any other kind; the\n * region is the same either way. `base` is undefined when the\n * component's id could not be read.\n */\n readonly read: (c: Ctx, o: Record<string, unknown>, path: string, scope: ComponentScope, base: ComponentBase | undefined) => C | undefined\n}\n\n/** The scope a component of `kind` passes to what it holds: one level deeper, and inside it when it lays them out. */\nfunction inside(scope: ComponentScope, kind: ComponentKind, holds: 'layout' | 'flow' | undefined): ComponentScope {\n if (holds === undefined) return scope\n return { ...scope, depth: scope.depth + 1, layout: holds === 'layout' ? kind : scope.layout }\n}\n\nfunction readSlot(c: Ctx, value: unknown, path: string, scope: ComponentScope): { width: Width | undefined; slot: ColumnSlot | undefined } {\n const o = shape(c.f, value, path, ['width', 'components'])\n const slotWidth = width(c.f, o?.width, at(path, 'width'))\n const components = readComponents(c, o?.components, at(path, 'components'), scope)\n return { width: slotWidth, slot: slotWidth === undefined || components === undefined ? undefined : { width: slotWidth, components } }\n}\n\n/** A length checked against the page, as `what` measures it. */\nfunction sized(c: Ctx, value: unknown, path: string, side: 'width' | 'height', what: string): number | undefined {\n const length = points(c.f, value, path, 'positive')\n withinPage(c, length, path, side, what)\n return length\n}\n\ntype SourceReader = (c: Ctx, o: Record<string, unknown>, path: string, region: RegionName) => ImageSource | undefined\n\nconst SOURCES: { readonly [K in ImageSourceKind]: { readonly required: readonly string[]; readonly read: SourceReader } } = {\n asset: {\n required: ['asset'],\n read: (c, o, path) => {\n const asset = reference(c.f, o.asset, at(path, 'asset'))\n resolve(c.f, c.declared.assets, asset, at(path, 'asset'), 'unknown-asset', 'asset')\n return asset === undefined ? undefined : { kind: 'asset', asset }\n },\n },\n field: {\n required: ['field'],\n read: (c, o, path, region) => {\n const field = readFieldRef(c, o.field, at(path, 'field'), { region, reads: 'report' })\n if (field?.type !== undefined && field.type !== 'image') {\n c.f.report(at(path, 'field'), 'binding-type-mismatch', `an image draws an image field, and this is a ${field.type}`)\n }\n return field && { kind: 'field', field: field.ref }\n },\n },\n}\n\nfunction readImageSource(c: Ctx, value: unknown, path: string, region: RegionName): ImageSource | undefined {\n const o = readObject(c.f, value, path)\n const kind = o && kindOf(c.f, o, path, IMAGE_SOURCE_KINDS)\n if (o === undefined || kind === undefined) return undefined\n strictKeys(c.f, o, path, ['kind', ...SOURCES[kind].required])\n return SOURCES[kind].read(c, o, path, region)\n}\n\nfunction readBorder(c: Ctx, value: unknown, path: string): Border | undefined {\n const o = shape(c.f, value, path, ['thickness', 'color'])\n const thickness = points(c.f, o?.thickness, at(path, 'thickness'), 'positive')\n const color = matches(c.f, o?.color, at(path, 'color'), COLOR, 'invalid-color', COLOR_RULE)\n return thickness === undefined || color === undefined ? undefined : { thickness, color }\n}\n\nconst KINDS: { readonly [K in ComponentKind]: KindRule<Extract<Component, { kind: K }>> } = {\n text: {\n required: ['content'],\n optional: ['keepWithNext'],\n read: (c, o, path, scope, base) => {\n const content = readInlines(c, o.content, at(path, 'content'), { region: scope.region, reads: 'report' })\n const keepWithNext = flag(c.f, o.keepWithNext, at(path, 'keepWithNext'))\n return base && content && { ...base, kind: 'text', content, ...optional('keepWithNext', keepWithNext) }\n },\n },\n image: {\n required: ['source', 'width', 'height', 'fit'],\n read: (c, o, path, scope, base) => {\n const source = readImageSource(c, o.source, at(path, 'source'), scope.region)\n const imageWidth = sized(c, o.width, at(path, 'width'), 'width', 'this image')\n const height = sized(c, o.height, at(path, 'height'), 'height', 'this image')\n const fit = oneOf(c.f, o.fit, at(path, 'fit'), IMAGE_FITS)\n if (base === undefined || source === undefined || imageWidth === undefined || height === undefined || fit === undefined) return undefined\n return { ...base, kind: 'image', source, width: imageWidth, height, fit }\n },\n },\n line: {\n required: ['thickness'],\n optional: ['color'],\n read: (c, o, path, _scope, base) => {\n const thickness = points(c.f, o.thickness, at(path, 'thickness'), 'positive')\n const color = matches(c.f, o.color, at(path, 'color'), COLOR, 'invalid-color', COLOR_RULE)\n return base && thickness !== undefined ? { ...base, kind: 'line', thickness, ...optional('color', color) } : undefined\n },\n },\n rectangle: {\n required: ['width', 'height'],\n optional: ['fill', 'stroke'],\n read: (c, o, path, _scope, base) => {\n const boxWidth = sized(c, o.width, at(path, 'width'), 'width', 'this rectangle')\n const height = sized(c, o.height, at(path, 'height'), 'height', 'this rectangle')\n const fill = matches(c.f, o.fill, at(path, 'fill'), COLOR, 'invalid-color', COLOR_RULE)\n const stroke = matches(c.f, o.stroke, at(path, 'stroke'), COLOR, 'invalid-color', COLOR_RULE)\n if (base === undefined || boxWidth === undefined || height === undefined) return undefined\n return { ...base, kind: 'rectangle', width: boxWidth, height, ...optional('fill', fill), ...optional('stroke', stroke) }\n },\n },\n spacer: {\n required: ['height'],\n read: (c, o, path, _scope, base) => {\n const height = sized(c, o.height, at(path, 'height'), 'height', 'this spacer')\n return base && height !== undefined ? { ...base, kind: 'spacer', height } : undefined\n },\n },\n columns: {\n required: ['columns'],\n holds: 'layout',\n read: (c, o, path, scope, base) => {\n const where = at(path, 'columns')\n const read = readList(c.f, o.columns, where, MIN_COLUMNS, MAX_COLUMNS)?.map((item, index) => readSlot(c, item, at(where, index), scope))\n if (read !== undefined) checkFixedWidths(c, read.map(({ width: slotWidth }) => slotWidth), where)\n const columns = read && all(read.map(({ slot }) => slot))\n return base && columns && { ...base, kind: 'columns', columns }\n },\n },\n section: {\n required: ['components'],\n optional: ['border', 'fill', 'padding'],\n holds: 'flow',\n read: (c, o, path, scope, base) => {\n const components = readComponents(c, o.components, at(path, 'components'), scope)\n const border = readBorder(c, o.border, at(path, 'border'))\n const fill = matches(c.f, o.fill, at(path, 'fill'), COLOR, 'invalid-color', COLOR_RULE)\n const padding = points(c.f, o.padding, at(path, 'padding'), 'zero')\n return base && components && { ...base, kind: 'section', components, ...optional('border', border), ...optional('fill', fill), ...optional('padding', padding) }\n },\n },\n table: {\n required: TABLE_REQUIRED,\n optional: TABLE_OPTIONAL,\n flowOnly: true,\n inFlow: true,\n read: (c, o, path, scope, base) => readTable(c, o, path, scope.region, base),\n },\n pageBreak: {\n required: [],\n flowOnly: true,\n inFlow: true,\n read: (_c, _o, _path, _scope, base) => base && { ...base, kind: 'pageBreak' },\n },\n keepTogether: {\n required: ['components'],\n holds: 'layout',\n flowOnly: true,\n read: (c, o, path, scope, base) => {\n const components = readComponents(c, o.components, at(path, 'components'), scope)\n return base && components && { ...base, kind: 'keepTogether', components }\n },\n },\n}\n\n/** Records a component's id, refusing it when another component already has it. */\nfunction claim(c: Ctx, id: string, path: string): void {\n c.f.component(path, id)\n const first = c.componentIds.get(id)\n if (first === undefined) c.componentIds.set(id, path)\n else c.f.report(at(path, 'id'), 'duplicate-component-id', `\"${id}\" is already the id of the component at ${first}; component ids are unique across the whole report`)\n}\n\n/** Reports a component of `kind` standing where it may not. */\nfunction place(c: Ctx, rule: KindRule<Component>, kind: ComponentKind, path: string, scope: ComponentScope): void {\n if (rule.flowOnly && !FLOW_REGIONS.includes(scope.region)) {\n c.f.report(path, 'misplaced-flow-component', `a ${kind} stands only in the body or the summary, where content flows, not in the ${scope.region}`)\n }\n if (rule.inFlow && scope.layout !== undefined) {\n c.f.report(path, 'nested-flow-component', `a ${kind} is part of the flow, and cannot stand inside a ${scope.layout} block; a section can hold it`)\n }\n}\n\nfunction readComponent(c: Ctx, value: unknown, path: string, scope: ComponentScope): Component | undefined {\n const o = readObject(c.f, value, path)\n const kind = o && kindOf(c.f, o, path, COMPONENT_KINDS)\n if (o === undefined || kind === undefined) return undefined\n const rule: KindRule<Component> = KINDS[kind]\n strictKeys(c.f, o, path, ['id', 'kind', ...rule.required], ['visibleWhen', 'style', 'styleWhen', ...(rule.optional ?? [])])\n const id = identifier(c.f, o.id, at(path, 'id'))\n if (id !== undefined) claim(c, id, path)\n place(c, rule, kind, path, scope)\n if (rule.holds !== undefined && scope.depth >= MAX_NESTING_DEPTH) {\n c.f.report(path, 'nesting-too-deep', `this ${kind} is inside ${scope.depth} containers; containers nest at most ${MAX_NESTING_DEPTH} deep`)\n return undefined\n }\n const visibleWhen = readExpression(c.f, o.visibleWhen, at(path, 'visibleWhen'))\n const style = readStyleRef(c, o.style, at(path, 'style'))\n const styleWhen = readStyleRules(c, o.styleWhen, at(path, 'styleWhen'))\n const base = id === undefined ? undefined : { id, ...optional('visibleWhen', visibleWhen), ...optional('style', style), ...optional('styleWhen', styleWhen) }\n return rule.read(c, o, path, inside(scope, kind, rule.holds), base)\n}\n\n/** Takes one component from the region's budget, reporting once when it is spent. */\nfunction spend(c: Ctx, scope: ComponentScope): boolean {\n if (scope.budget.left > 0) {\n scope.budget.left -= 1\n return true\n }\n if (scope.budget.left === 0) {\n c.f.report(scope.regionPath, 'too-many', `a region holds at most ${MAX_REGION_COMPONENTS} components, counting those inside containers`)\n scope.budget.left = -1\n }\n return false\n}\n\nexport function readComponents(c: Ctx, value: unknown, path: string, scope: ComponentScope): readonly Component[] | undefined {\n const items = readArray(c.f, value, path, MAX_REGION_COMPONENTS)\n if (items === undefined) return undefined\n const components: (Component | undefined)[] = []\n for (const [index, item] of items.entries()) {\n if (!spend(c, scope)) return undefined\n components.push(readComponent(c, item, at(path, index), scope))\n }\n return all(components)\n}\n","/**\n * Page geometry: the size of each page the format names, and the area its\n * margins leave. The validator's margin check, the builder's rulers and the\n * renderer read the same numbers from here.\n */\nimport type { Orientation, PageSettings, PageSizeName } from './types.js'\nimport { mmToPt, POINTS_PER_INCH, roundPt } from './units.js'\n\nexport interface PageDimensions {\n readonly width: number\n readonly height: number\n}\n\n/**\n * Portrait sizes in points. A4 is ISO 216's 210 x 297 mm, converted and\n * rounded like any other length (595.28 x 841.89, the values PDF engines\n * use); Letter is 8.5 x 11 inches, exactly 612 x 792.\n */\nexport const PAGE_SIZES: { readonly [S in PageSizeName]: PageDimensions } = {\n A4: { width: mmToPt(210), height: mmToPt(297) },\n Letter: { width: 8.5 * POINTS_PER_INCH, height: 11 * POINTS_PER_INCH },\n}\n\n/** The page's width and height as oriented: landscape swaps the sides. */\nexport function pageDimensions(page: { readonly size: PageSizeName; readonly orientation: Orientation }): PageDimensions {\n const { width, height } = PAGE_SIZES[page.size]\n return page.orientation === 'portrait' ? { width, height } : { width: height, height: width }\n}\n\n/** What the margins leave of the oriented page, to the hundredth of a point that lengths are stored at. */\nexport function printableArea(page: PageSettings): PageDimensions {\n const { width, height } = pageDimensions(page)\n const { top, right, bottom, left } = page.margins\n return { width: roundPt(width - left - right), height: roundPt(height - top - bottom) }\n}\n","/**\n * What a report declares before it lays anything out: its page, its print\n * styles, the datasets and parameters it reads, the assets it shows and\n * where it came from. Each list records the ids it declares, so components\n * can be checked against them.\n */\nimport type { Findings } from './check.js'\nimport { all, describe, fieldKey, flag, fontSize, identifier, integer, kindOf, matches, oneOf, optional, points, readArray, readObject, shape, strictKeys, text } from './check.js'\nimport { MAX_ASSETS, MAX_DATASET_FIELDS, MAX_LABEL_LENGTH, MAX_PARAMETERS, MAX_SCALE, MAX_STYLES, MIN_PRINTABLE_PT } from './limits.js'\nimport { printableArea } from './page.js'\nimport { at } from './pointer.js'\nimport { COLOR, DECIMAL, DIGEST, FORM_ID, INTEGER, isCalendarDate, SCHEMA_HASH } from './syntax.js'\nimport {\n ALIGNMENTS,\n ASSET_MEDIA_TYPES,\n DATASET_ROLES,\n FIELD_TYPES,\n FONT_FAMILIES,\n ORIENTATIONS,\n PAGE_SIZE_NAMES,\n PARAMETER_TYPES,\n PROVENANCE_KINDS,\n} from './types.js'\nimport type {\n AssetRef,\n DatasetContract,\n DatasetRole,\n Datasets,\n FieldContract,\n FieldType,\n Margins,\n PageSettings,\n ParameterDef,\n ParameterType,\n PrintStyle,\n Provenance,\n ProvenanceKind,\n} from './types.js'\nimport { declare } from './validate-context.js'\nimport type { Ctx, Declarations, Declaration } from './validate-context.js'\n\nfunction readMargins(f: Findings, value: unknown, path: string): Margins | undefined {\n const o = shape(f, value, path, ['top', 'right', 'bottom', 'left'])\n const [top, right, bottom, left] = (['top', 'right', 'bottom', 'left'] as const).map((side) => points(f, o?.[side], at(path, side), 'zero'))\n return top === undefined || right === undefined || bottom === undefined || left === undefined ? undefined : { top, right, bottom, left }\n}\n\n/** The page, recording what its margins leave when that is enough to measure content against. */\nexport function readPage(c: Ctx, value: unknown, path: string): PageSettings | undefined {\n const o = shape(c.f, value, path, ['size', 'orientation', 'margins'])\n const size = oneOf(c.f, o?.size, at(path, 'size'), PAGE_SIZE_NAMES)\n const orientation = oneOf(c.f, o?.orientation, at(path, 'orientation'), ORIENTATIONS)\n const margins = readMargins(c.f, o?.margins, at(path, 'margins'))\n if (size === undefined || orientation === undefined || margins === undefined) return undefined\n const page = { size, orientation, margins }\n const area = printableArea(page)\n if (area.width >= MIN_PRINTABLE_PT && area.height >= MIN_PRINTABLE_PT) c.printable = area\n else {\n c.f.report(\n at(path, 'margins'),\n 'printable-area-too-small',\n `the margins leave ${area.width} x ${area.height} points of the page; at least ${MIN_PRINTABLE_PT} each way is needed`,\n )\n }\n return page\n}\n\n/** A declaration read: its id, what it declares, and the declaration itself when every part of it could be read. */\ninterface Read<T, D> {\n readonly entry: Declaration<D>\n readonly item: T | undefined\n}\n\n/** A list of declarations, each with an id unique in the list. */\nfunction readDeclarations<T, D>(\n c: Ctx,\n value: unknown,\n path: string,\n max: number,\n what: string,\n read: (item: unknown, where: string) => Read<T, D>,\n): { items: T[] | undefined; declared: Map<string, D> | undefined } {\n const items = readArray(c.f, value, path, max)\n if (items === undefined) return { items: undefined, declared: undefined }\n const entries = items.map((item, index) => read(item, at(path, index)))\n const declared = declare(\n c.f,\n entries.map(({ entry }) => entry),\n 'duplicate-id',\n (id) => `another ${what} is already ${id}`,\n )\n return { items: all(entries.map(({ item }) => item)), declared }\n}\n\nfunction readStyle(f: Findings, value: unknown, path: string): Read<PrintStyle, true> {\n const o = shape(f, value, path, ['id'], ['font', 'size', 'bold', 'italic', 'color', 'align'])\n const id = identifier(f, o?.id, at(path, 'id'))\n const entry = { id, path: at(path, 'id'), value: true as const }\n if (o === undefined || id === undefined) return { entry, item: undefined }\n return {\n entry,\n item: {\n id,\n ...optional('font', oneOf(f, o.font, at(path, 'font'), FONT_FAMILIES)),\n ...optional('size', fontSize(f, o.size, at(path, 'size'))),\n ...optional('bold', flag(f, o.bold, at(path, 'bold'))),\n ...optional('italic', flag(f, o.italic, at(path, 'italic'))),\n ...optional('color', matches(f, o.color, at(path, 'color'), COLOR, 'invalid-color', 'a colour written #rrggbb in lower case')),\n ...optional('align', oneOf(f, o.align, at(path, 'align'), ALIGNMENTS)),\n },\n }\n}\n\nexport function readStyles(c: Ctx, value: unknown, path: string): readonly PrintStyle[] | undefined {\n const { items, declared } = readDeclarations(c, value, path, MAX_STYLES, 'style', (item, where) => readStyle(c.f, item, where))\n c.declared.styles = declared\n return items\n}\n\nfunction readFieldContract(f: Findings, value: unknown, path: string): Read<FieldContract, FieldType | undefined> {\n const o = shape(f, value, path, ['id', 'type', 'label', 'nullable'], ['scale'])\n const id = fieldKey(f, o?.id, at(path, 'id'))\n const type = oneOf(f, o?.type, at(path, 'type'), FIELD_TYPES)\n const label = text(f, o?.label, at(path, 'label'), MAX_LABEL_LENGTH)\n const nullable = flag(f, o?.nullable, at(path, 'nullable'))\n const scale = integer(f, o?.scale, at(path, 'scale'), 0, MAX_SCALE)\n if (scale !== undefined && type !== undefined && type !== 'decimal') {\n f.report(at(path, 'scale'), 'scale-on-non-decimal', `a scale says how many decimal places a decimal field has, and this field is a ${type}`)\n }\n const entry = { id, path: at(path, 'id'), value: type }\n if (id === undefined || type === undefined || label === undefined || nullable === undefined) return { entry, item: undefined }\n return { entry, item: { id, type, label, nullable, ...optional('scale', scale) } }\n}\n\n/** A dataset contract, recording its fields under its role. */\nfunction readDataset(c: Ctx, value: unknown, path: string, role: DatasetRole, declared: Map<string, Declarations<FieldType | undefined>>): DatasetContract | undefined {\n if (value === undefined) return undefined\n const o = shape(c.f, value, path, ['id', 'fields'])\n const id = identifier(c.f, o?.id, at(path, 'id'))\n const fields = readDeclarations(c, o?.fields, at(path, 'fields'), MAX_DATASET_FIELDS, 'field of this dataset', (item, where) => readFieldContract(c.f, item, where))\n declared.set(role, fields.declared)\n return id === undefined || fields.items === undefined ? undefined : { id, fields: fields.items }\n}\n\nexport function readDatasets(c: Ctx, value: unknown, path: string): Datasets | undefined {\n const o = shape(c.f, value, path, [], DATASET_ROLES)\n if (o === undefined) return undefined\n const declared = new Map<string, Declarations<FieldType | undefined>>()\n c.declared.datasets = declared\n const header = readDataset(c, o.header, at(path, 'header'), 'header', declared)\n const detail = readDataset(c, o.detail, at(path, 'detail'), 'detail', declared)\n if (header !== undefined && detail !== undefined && header.id === detail.id) {\n c.f.report(at(at(path, 'detail'), 'id'), 'duplicate-id', `the header dataset is already \"${detail.id}\"; each dataset is bound to a provider by its own id`)\n }\n return { ...optional('header', header), ...optional('detail', detail) }\n}\n\n/** What a default looks like for each parameter type, and how to tell. Exact values are strings. */\nconst DEFAULTS: { readonly [T in ParameterType]: { readonly accepts: (value: unknown) => boolean; readonly shape: string } } = {\n string: { accepts: (value) => typeof value === 'string', shape: 'a string' },\n integer: { accepts: (value) => typeof value === 'string' && INTEGER.test(value), shape: 'an integer written as a string, such as \"12\"' },\n decimal: { accepts: (value) => typeof value === 'string' && DECIMAL.test(value), shape: 'a decimal written as a string, such as \"12.50\"' },\n boolean: { accepts: (value) => typeof value === 'boolean', shape: 'true or false' },\n date: { accepts: (value) => typeof value === 'string' && isCalendarDate(value), shape: 'a calendar date written YYYY-MM-DD' },\n}\n\nfunction readDefault(f: Findings, value: unknown, path: string, type: ParameterType | undefined): string | boolean | undefined {\n if (value === undefined || type === undefined) return undefined\n if (typeof value === 'string' && text(f, value, path, MAX_LABEL_LENGTH) === undefined) return undefined\n if (DEFAULTS[type].accepts(value)) return value as string | boolean\n f.report(path, 'invalid-default', `a default for a ${type} parameter is ${DEFAULTS[type].shape}; this is ${describe(value)}`)\n return undefined\n}\n\nfunction readParameter(f: Findings, value: unknown, path: string): Read<ParameterDef, ParameterType | undefined> {\n const o = shape(f, value, path, ['id', 'type', 'label', 'required'], ['default'])\n const id = fieldKey(f, o?.id, at(path, 'id'))\n const type = oneOf(f, o?.type, at(path, 'type'), PARAMETER_TYPES)\n const label = text(f, o?.label, at(path, 'label'), MAX_LABEL_LENGTH)\n const required = flag(f, o?.required, at(path, 'required'))\n const fallback = readDefault(f, o?.default, at(path, 'default'), type)\n const entry = { id, path: at(path, 'id'), value: type }\n if (id === undefined || type === undefined || label === undefined || required === undefined) return { entry, item: undefined }\n return { entry, item: { id, type, label, required, ...optional('default', fallback) } }\n}\n\nexport function readParameters(c: Ctx, value: unknown, path: string): readonly ParameterDef[] | undefined {\n const { items, declared } = readDeclarations(c, value, path, MAX_PARAMETERS, 'parameter', (item, where) => readParameter(c.f, item, where))\n c.declared.parameters = declared\n return items\n}\n\nfunction readAsset(f: Findings, value: unknown, path: string): Read<AssetRef, true> {\n const o = shape(f, value, path, ['id', 'mediaType', 'digest'])\n const id = identifier(f, o?.id, at(path, 'id'))\n const mediaType = oneOf(f, o?.mediaType, at(path, 'mediaType'), ASSET_MEDIA_TYPES)\n const digest = matches(f, o?.digest, at(path, 'digest'), DIGEST, 'invalid-digest', '\"sha256:\" and 64 lower-case hex digits')\n const entry = { id, path: at(path, 'id'), value: true as const }\n return { entry, item: id === undefined || mediaType === undefined || digest === undefined ? undefined : { id, mediaType, digest } }\n}\n\nexport function readAssets(c: Ctx, value: unknown, path: string): readonly AssetRef[] | undefined {\n const { items, declared } = readDeclarations(c, value, path, MAX_ASSETS, 'asset', (item, where) => readAsset(c.f, item, where))\n c.declared.assets = declared\n return items\n}\n\n/** Each kind of provenance: what it names, and how to read it. */\nconst PROVENANCE: { readonly [K in ProvenanceKind]: { readonly required: readonly string[]; readonly read: (f: Findings, o: Record<string, unknown>, path: string) => Provenance | undefined } } = {\n blank: { required: [], read: () => ({ kind: 'blank' }) },\n form: {\n required: ['form', 'formHash'],\n read: (f, o, path) => {\n const form = matches(f, o.form, at(path, 'form'), FORM_ID, 'invalid-id', \"a form's id as formancy writes one: letters, digits, '.', '_' and '-', starting with a letter or digit\")\n const formHash = matches(f, o.formHash, at(path, 'formHash'), SCHEMA_HASH, 'invalid-digest', \"the form version's schemaHash: 64 lower-case hex digits\")\n return form === undefined || formHash === undefined ? undefined : { kind: 'form', form, formHash }\n },\n },\n dataset: {\n required: ['dataset'],\n read: (f, o, path) => {\n const dataset = identifier(f, o.dataset, at(path, 'dataset'))\n return dataset === undefined ? undefined : { kind: 'dataset', dataset }\n },\n },\n}\n\nexport function readProvenance(f: Findings, value: unknown, path: string): Provenance | undefined {\n const o = readObject(f, value, path)\n const kind = o && kindOf(f, o, path, PROVENANCE_KINDS)\n if (o === undefined || kind === undefined) return undefined\n strictKeys(f, o, path, ['kind', ...PROVENANCE[kind].required])\n return PROVENANCE[kind].read(f, o, path)\n}\n","/**\n * Structural validation: whether a document is a report definition this\n * package reads, and every way in which it is not.\n *\n * This is the first of the four levels of plan 15 -- structure, with the\n * references a definition makes into its own declarations and the sizes its\n * own page allows. Whether a declared dataset exists in a deployment,\n * whether an expression compiles against the names `EXPRESSION_NAMES` binds,\n * and whether the rendered output fits are later levels, owned elsewhere.\n */\nimport { identifier, matches, optional, readObject, shape, strictKeys, text } from './check.js'\nimport type { ReportError } from './errors.js'\nimport { MAX_LABEL_LENGTH, MAX_REGION_COMPONENTS } from './limits.js'\nimport { at } from './pointer.js'\nimport { LOCALE } from './syntax.js'\nimport { REGION_NAMES } from './types.js'\nimport type { ReportDefinition, Regions } from './types.js'\nimport { readAggregates } from './validate-aggregates.js'\nimport { newContext } from './validate-context.js'\nimport type { Ctx } from './validate-context.js'\nimport { readComponents } from './validate-components.js'\nimport { readAssets, readDatasets, readPage, readParameters, readProvenance, readStyles } from './validate-declarations.js'\nimport { checkSpecVersion, REPORT_SPEC_VERSION } from './version.js'\n\nexport type ReportValidation = { readonly valid: true; readonly report: ReportDefinition } | { readonly valid: false; readonly errors: readonly ReportError[] }\n\nfunction readRegions(c: Ctx, value: unknown, path: string): Regions | undefined {\n const o = shape(c.f, value, path, REGION_NAMES)\n const [reportHeader, pageHeader, body, pageFooter, summary] = REGION_NAMES.map((region) => {\n const where = at(path, region)\n return readComponents(c, o?.[region], where, { region, regionPath: where, depth: 0, layout: undefined, budget: { left: MAX_REGION_COMPONENTS } })\n })\n if (reportHeader === undefined || pageHeader === undefined || body === undefined || pageFooter === undefined || summary === undefined) return undefined\n return { reportHeader, pageHeader, body, pageFooter, summary }\n}\n\n/** The report in `o`, a copy of the document's top level whose version has been checked. */\nfunction readReport(c: Ctx, o: Record<string, unknown>): ReportDefinition | undefined {\n strictKeys(c.f, o, '', ['reportSpecVersion', 'id', 'title', 'locale', 'page', 'styles', 'datasets', 'parameters', 'assets', 'aggregates', 'regions'], ['provenance'])\n const id = identifier(c.f, o.id, '/id')\n const title = text(c.f, o.title, '/title', MAX_LABEL_LENGTH)\n const locale = matches(c.f, o.locale, '/locale', LOCALE, 'invalid-locale', 'a BCP 47 language tag such as en, de-CH or zh-Hans-CN')\n // The page first, then the declarations: the regions are measured\n // against the one and checked against the others.\n const page = readPage(c, o.page, '/page')\n const styles = readStyles(c, o.styles, '/styles')\n const datasets = readDatasets(c, o.datasets, '/datasets')\n const parameters = readParameters(c, o.parameters, '/parameters')\n const assets = readAssets(c, o.assets, '/assets')\n const aggregates = readAggregates(c, o.aggregates, '/aggregates')\n const regions = readRegions(c, o.regions, '/regions')\n const provenance = readProvenance(c.f, o.provenance, '/provenance')\n if (\n id === undefined ||\n title === undefined ||\n locale === undefined ||\n page === undefined ||\n styles === undefined ||\n datasets === undefined ||\n parameters === undefined ||\n assets === undefined ||\n aggregates === undefined ||\n regions === undefined\n ) {\n return undefined\n }\n const reportSpecVersion = REPORT_SPEC_VERSION\n return { reportSpecVersion, id, title, locale, page, styles, datasets, parameters, assets, aggregates, regions, ...optional('provenance', provenance) }\n}\n\n/**\n * Whether `document` is a valid report definition, and if not, every reason\n * why -- up to MAX_ERRORS of them, each with a JSON Pointer, a code, a\n * message for a person and the component it is inside.\n *\n * The version is checked first, with `checkSpecVersion`: a formancy form or\n * a later version's report is refused as what it is, with one error, rather\n * than with every way its shape differs.\n *\n * Never throws, whatever it is handed. Every object and array is read once,\n * through its property descriptors, into a copy; a getter is refused and\n * never run, and the report returned is built from what was checked and\n * shares no object with `document`. The work is bounded by the limits in\n * `limits.ts`: an array past its bound is refused before it is read. No\n * message and no path grows with what the document holds.\n */\nexport function validateReport(document: unknown): ReportValidation {\n const c = newContext()\n const top = readObject(c.f, document, '')\n const version = checkSpecVersion(top)\n if (!version.ok) {\n return { valid: false, errors: [{ path: version.code === 'unsupported-version' ? '/reportSpecVersion' : '', code: version.code, message: version.message }] }\n }\n // checkSpecVersion reads a version only from an object, so `top` is one.\n const report = readReport(c, top as Record<string, unknown>)\n const errors = c.f.errors()\n return report !== undefined && errors.length === 0 ? { valid: true, report } : { valid: false, errors }\n}\n","/**\n * What validation can say is wrong with a report, as stable codes.\n *\n * A code is for a program -- the builder links it to a property editor, a\n * test asserts it -- and the message is for a person. Codes are never\n * reworded once released; a new rule gets a new code. Each has a refusal\n * test in `validate.test.ts`, which does not compile while one is missing.\n */\nexport const REPORT_ERROR_CODES = [\n // The document as a whole.\n /** Not a report definition at all; a formancy form is named as one. */\n 'not-a-report',\n /** A report of a version this package does not read. */\n 'unsupported-version',\n /** A value JSON cannot hold: undefined, NaN, a function, an accessor, an array hole, an object that throws when read. */\n 'not-json',\n /** More errors were found than are listed. */\n 'too-many-errors',\n\n // Shape: what a property must be.\n 'wrong-type',\n 'missing-property',\n /** A property this version does not know; shapes are strict. */\n 'unknown-property',\n /** A component, inline, format or value of a kind this version does not know. */\n 'unknown-kind',\n 'not-one-of',\n 'out-of-range',\n 'not-an-integer',\n /** A length finer than the hundredth of a point lengths are stored to. */\n 'too-precise',\n /** A string, or a property name, past its bound. */\n 'too-long',\n /** An array past its bound, or a region past its component budget. */\n 'too-many',\n 'too-few',\n /** A CEL expression that is empty or only whitespace. */\n 'empty-expression',\n\n // Strings with a syntax.\n 'invalid-id',\n 'invalid-locale',\n 'invalid-color',\n 'invalid-currency',\n 'invalid-digest',\n /** A parameter default its own type would refuse. */\n 'invalid-default',\n /** A string that should hold an exact decimal and does not. */\n 'invalid-decimal',\n\n // Declarations.\n /** Margins that leave less than MIN_PRINTABLE_PT either way. */\n 'printable-area-too-small',\n 'scale-on-non-decimal',\n /** Two declarations with one id in one list: styles, fields, parameters, assets, aggregates, or the two datasets. */\n 'duplicate-id',\n /** An id the format gives a meaning of its own: an aggregate called `key`, which `group.key` reads as the value grouped by. */\n 'reserved-id',\n\n // References to what the report declares.\n 'unknown-style',\n 'unknown-dataset',\n 'unknown-field',\n 'unknown-parameter',\n 'unknown-asset',\n 'unknown-aggregate',\n 'unknown-column',\n\n // Placement and structure.\n /** A table, page break or keep-together block outside the body and the summary. */\n 'misplaced-flow-component',\n /** A table or page break inside a columns or keep-together block. */\n 'nested-flow-component',\n /** A page number or count outside the page header and footer. */\n 'misplaced-page-counter',\n /** A detail field where there is no current row: outside the table's cells, or in a group header or footer when it is not the field grouped by. */\n 'misplaced-detail-field',\n /** A group's aggregate outside a group header or footer. */\n 'misplaced-group-aggregate',\n /** A second table over the detail dataset. */\n 'second-detail-table',\n 'nesting-too-deep',\n /** Two components with one id, anywhere in the report. */\n 'duplicate-component-id',\n /** Two columns with one id in one table. */\n 'duplicate-column-id',\n /** Two cells for one column in one footer row. */\n 'duplicate-footer-cell',\n /** A field sorted by twice, or sorted by and grouped by: the second key orders nothing. */\n 'duplicate-sort-key',\n /** A fixed size larger than the page's printable area: an image, a rectangle, a spacer, or the fixed widths of a table or a columns block. */\n 'exceeds-printable-area',\n\n // Types meeting.\n /** An aggregate over a field of a type it cannot take. */\n 'aggregate-type-mismatch',\n /** A number, currency or date format over a value of a type it does not format. */\n 'format-type-mismatch',\n /** A field or parameter bound where its type does not fit: an image field printed, sorted or grouped by; a field that is not an image drawn as one; a currency that is not a string. */\n 'binding-type-mismatch',\n] as const\n\nexport type ReportErrorCode = (typeof REPORT_ERROR_CODES)[number]\n\nexport interface ReportError {\n /** A JSON Pointer (RFC 6901) to what is wrong; '' is the whole document. */\n readonly path: string\n readonly code: ReportErrorCode\n readonly message: string\n /** The innermost component the error is inside, when it is inside one whose id could be read. */\n readonly componentId?: string\n}\n\n/** Errors as one line of text, for an exception that has to carry them: each its code, path and message. */\nexport function describeErrors(errors: readonly ReportError[]): string {\n return errors.map((error) => `${error.code} ${error.path}: ${error.message}`).join('; ')\n}\n","/**\n * The content hash that names a report definition.\n */\nimport { schemaHash } from '@formancy/spec'\nimport { describeErrors } from './errors.js'\nimport type { ReportDefinition } from './types.js'\nimport { validateReport } from './validate.js'\nimport { REPORT_FORMAT } from './version.js'\n\n/**\n * A 64-character lower-case hex SHA-256 of the report's canonical JSON,\n * taken over an envelope that names the format and its version, so a\n * formancy form and a report whose bodies are equal never share a hash.\n *\n * Only a valid report has a hash. The report is validated first, and a\n * RangeError naming every error is thrown for one the validator refuses,\n * whatever its type says: a hash is what publication pins, and pinning a\n * report the runtime would refuse helps nobody. What is hashed is the copy\n * validation read, so a getter never runs and the hash is of what was\n * checked.\n *\n * Canonicalisation is formancy's (`@formancy/spec`), not a second one: keys\n * sorted, so key order never changes the hash. It builds each object by\n * assignment, so an own `__proto__` key would vanish from it; the validator\n * refuses such a key first.\n */\nexport function reportHash(report: ReportDefinition): string {\n const outcome = validateReport(report)\n if (!outcome.valid) throw new RangeError(`only a valid report has a hash, and this one is not: ${describeErrors(outcome.errors)}`)\n return schemaHash({ format: REPORT_FORMAT, reportSpecVersion: outcome.report.reportSpecVersion, report: outcome.report })\n}\n","/**\n * The report an author starts from when they start from nothing.\n */\nimport { describeErrors } from './errors.js'\nimport type { ReportDefinition } from './types.js'\nimport { mmToPt } from './units.js'\nimport { validateReport } from './validate.js'\nimport { REPORT_SPEC_VERSION } from './version.js'\n\n/** The default margin: 20 mm, a common default for A4 business documents. */\nconst MARGIN_MM = 20\n\n/**\n * A valid, empty A4 portrait report with 20 mm margins, nothing declared and\n * nothing in any region, recorded as started blank.\n *\n * Throws a RangeError naming the property when `id`, `title` or `locale` is\n * one the format refuses, rather than returning a report every later step\n * would refuse.\n */\nexport function emptyReport(id: string, title: string, locale: string): ReportDefinition {\n const margin = mmToPt(MARGIN_MM)\n const outcome = validateReport({\n reportSpecVersion: REPORT_SPEC_VERSION,\n id,\n title,\n locale,\n page: { size: 'A4', orientation: 'portrait', margins: { top: margin, right: margin, bottom: margin, left: margin } },\n styles: [],\n datasets: {},\n parameters: [],\n assets: [],\n aggregates: [],\n regions: { reportHeader: [], pageHeader: [], body: [], pageFooter: [], summary: [] },\n provenance: { kind: 'blank' },\n })\n if (outcome.valid) return outcome.report\n throw new RangeError(`not a valid empty report: ${describeErrors(outcome.errors)}`)\n}\n","/**\n * Finding components in a report: the walk the core's commands, the\n * builder's outline and the runtime share, so they visit components in one\n * order and name them by one path.\n */\nimport { at } from './pointer.js'\nimport { REGION_NAMES } from './types.js'\nimport type { Component, ComponentKind, RegionName, ReportDefinition } from './types.js'\n\nexport interface ComponentLocation {\n readonly component: Component\n readonly region: RegionName\n /** A JSON Pointer from the report's root: the path validation errors use. */\n readonly path: string\n /** How many containers enclose the component: 0 at a region's top level. */\n readonly depth: number\n}\n\ntype ChildLists = readonly (readonly [string, readonly Component[]])[]\n\nconst NONE: ChildLists = []\n\n/**\n * The component lists each kind holds, each with its path relative to the\n * component. A table over every kind, so a container added to the format\n * without saying where it keeps its children does not compile, and the walk\n * cannot quietly skip what the validator checked.\n */\nconst CHILDREN: { readonly [K in ComponentKind]: (component: Extract<Component, { kind: K }>) => ChildLists } = {\n text: () => NONE,\n image: () => NONE,\n line: () => NONE,\n rectangle: () => NONE,\n spacer: () => NONE,\n columns: (component) => component.columns.map((column, index) => [`/columns/${index}/components`, column.components] as const),\n section: (component) => [['/components', component.components]],\n table: () => NONE,\n pageBreak: () => NONE,\n keepTogether: (component) => [['/components', component.components]],\n}\n\nfunction childLists(component: Component): ChildLists {\n return (CHILDREN[component.kind] as (component: Component) => ChildLists)(component)\n}\n\n/** Every component in the report: regions in the order a reader meets them, each depth-first, a container before what it holds. */\nexport function walkComponents(report: ReportDefinition): readonly ComponentLocation[] {\n const found: ComponentLocation[] = []\n const visit = (components: readonly Component[], region: RegionName, path: string, depth: number): void => {\n for (const [index, component] of components.entries()) {\n const where = at(path, index)\n found.push({ component, region, path: where, depth })\n for (const [suffix, children] of childLists(component)) visit(children, region, `${where}${suffix}`, depth + 1)\n }\n }\n for (const region of REGION_NAMES) visit(report.regions[region], region, at('/regions', region), 0)\n return found\n}\n\n/** The component with `id`, where it is, or undefined when the report has none. Ids are unique in a valid report. */\nexport function componentAt(report: ReportDefinition, id: string): ComponentLocation | undefined {\n return walkComponents(report).find(({ component }) => component.id === id)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsBA,MAAa,aAAa;;;;;;;AAQ1B,MAAa,wBAAwB;;;;;;;AAQrC,MAAa,oBAAoB;;AAGjC,MAAa,cAAc;AAC3B,MAAa,cAAc;;AAG3B,MAAa,oBAAoB;;AAGjC,MAAa,gBAAgB;;AAG7B,MAAa,kBAAkB;;AAG/B,MAAa,qBAAqB;;AAGlC,MAAa,aAAa;;AAG1B,MAAa,kBAAkB;;AAG/B,MAAa,iBAAiB;;AAG9B,MAAa,aAAa;;AAG1B,MAAa,iBAAiB;;AAG9B,MAAa,cAAc;;;;;;;AAQ3B,MAAa,iBAAiB;;AAG9B,MAAa,kBAAkB;;AAG/B,MAAa,mBAAmB;;AAGhC,MAAa,wBAAwB;;AAGrC,MAAa,YAAY;;AAGzB,MAAa,gBAAgB;AAC7B,MAAa,gBAAgB;;;;;;AAO7B,MAAa,gBAAgB;;;;;;AAO7B,MAAa,mBAAmB;;;;;;;;;;;;;;;;AChGhC,SAAgB,GAAG,MAAc,KAA8B;CAC7D,IAAI,OAAO,QAAQ,YAAY,EAAE,IAAI,SAAS,GAAG,KAAK,IAAI,SAAS,GAAG,IAAI,OAAO,GAAG,KAAK,GAAG;CAC5F,OAAO,GAAG,KAAK,GAAG,IAAI,WAAW,KAAK,IAAI,CAAC,CAAC,WAAW,KAAK,IAAI;AAClE;;;;;;;;;;;;;;;;;;ACDA,MAAM,aAAa;;AAGnB,SAAgB,aAAa,OAAiC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AAkC,QAAoB,MAAc,UAAwB;EACzG,KAAK,MAAM,CAAC,OAAO,cAAc,WAAW,QAAQ,GAAG;GACrD,MAAM,QAAQ,GAAG,MAAM,KAAK;GAC5B,MAAM,KAAK;IAAE;IAAW;IAAQ,MAAM;IAAO;GAAM,CAAC;GACpD,KAAK,MAAM,CAAC,QAAQ,aAAa,WAAW,SAAS,GAAG,MAAM,UAAU,QAAQ,GAAG,QAAQ,UAAU,QAAQ,CAAC;EAChH;CACF;CACA,KAAK,MAAM,UAAU,cAAc,MAAM,OAAO,QAAQ,SAAS,QAAQ,GAAG,YAAY,MAAM,GAAG,CAAC;CAClG,OAAO;AACT;;AAGA,SAAgB,YAAY,QAA0B,IAA2C;CAC/F,OAAO,eAAe,MAAM,CAAC,CAAC,MAAM,EAAE,gBAAgB,UAAU,OAAO,EAAE;AAC3E"}
1
+ {"version":3,"file":"index.mjs","names":["IDENTIFIER","readProperty","measure","points","IBAN","MAX_WHOLE_DIGITS","points","read","inside","points","points","readDeclarations","NONE","CHILDREN","read","readAddress","read","refuse","refuse","refuse","UNITS","refuse","arc"],"sources":["../src/chart.ts","../src/limits.ts","../src/pointer.ts","../src/syntax.ts","../src/units.ts","../src/check.ts","../src/version.ts","../src/page.ts","../src/styles.ts","../src/data.ts","../src/assets.ts","../src/font-map.ts","../src/font-scripts.ts","../src/values.ts","../src/aggregates.ts","../src/components.ts","../src/table.ts","../src/definition.ts","../src/payment-part.ts","../src/payment-reference.ts","../src/qr-bill.ts","../src/epc-qr-code.ts","../src/sepa.ts","../src/epc-payload.ts","../src/epc-print.ts","../src/e-invoice.ts","../src/xrechnung.ts","../src/en16931.ts","../src/en16931-texts.ts","../src/en16931-decimals.ts","../src/en16931-dates.ts","../src/en16931-lines.ts","../src/en16931-vat.ts","../src/validate-context.ts","../src/validate-inline.ts","../src/validate-aggregates.ts","../src/validate-chart.ts","../src/validate-payment-text.ts","../src/validate-epc-qr-code.ts","../src/validate-table.ts","../src/validate-components.ts","../src/validate-form-binding.ts","../src/validate-declarations.ts","../src/walk.ts","../src/validate-e-invoice-report.ts","../src/validate-e-invoice.ts","../src/validate-font-map.ts","../src/validate-payment-part.ts","../src/translation.ts","../src/report-in.ts","../src/validate-translations.ts","../src/validate.ts","../src/errors.ts","../src/digest.ts","../src/image-header.ts","../src/svg-allow.ts","../src/svg-refusal.ts","../src/svg-number.ts","../src/svg-syntax.ts","../src/svg-tree.ts","../src/svg-colours.ts","../src/svg-values.ts","../src/svg-style.ts","../src/svg-computed.ts","../src/svg-transform.ts","../src/svg-extent.ts","../src/svg-cost.ts","../src/svg-gradient.ts","../src/svg-path.ts","../src/svg-shapes.ts","../src/svg-drawing.ts","../src/svg-write.ts","../src/svg.ts","../src/font-refusal.ts","../src/font-file.ts","../src/font-cmap.ts","../src/font-names.ts","../src/font-outlines.ts","../src/font-tables.ts","../src/font.ts","../src/hash.ts","../src/empty.ts"],"sourcesContent":["/**\n * The chart component: a bar, line or pie chart of the detail rows, drawn\n * as vectors from the numbers the runtime totals, never from a picture.\n *\n * What a chart groups by and what it totals is written here; the\n * validator (`validate-chart.ts`) holds a chart to its fields' types, the\n * runtime totals each series exactly, once, and the renderer draws the\n * resolved numbers and refuses what it cannot draw whole.\n */\nimport type { AggregateFunction, Rounding } from './aggregates.js'\nimport type { ComponentBase } from './components.js'\nimport type { FieldRef, FieldType } from './data.js'\nimport type { CurrencyFormat, Format, NumberFormat } from './values.js'\n\nexport const CHART_KINDS = ['bar', 'line', 'pie'] as const\nexport type ChartKind = (typeof CHART_KINDS)[number]\n\n/** The order a chart lists its categories in: as the rows first have them, or sorted by the category, least or greatest first. */\nexport const CHART_ORDERS = ['data', 'asc', 'desc'] as const\nexport type ChartOrder = (typeof CHART_ORDERS)[number]\n\n/** The types a category may be: text, a date, or a number. A boolean, a moment or an image names no group a reader would look for. Held by the validator. */\nexport const CHART_CATEGORY_TYPES: readonly FieldType[] = ['string', 'date', 'integer', 'decimal']\n\n/** What a pie may total: a share of an average, a minimum or a maximum is no share of a whole. Held by the validator. */\nexport const PIE_FUNCTIONS: readonly AggregateFunction[] = ['sum', 'count']\n\n/**\n * The colours a series is drawn in, by its place in the chart (a pie's\n * slices by the category's): eight, each at least 3:1 against white paper\n * (WCAG 2.2 1.4.11), the least `#1b9e77` at 3.39. A chart's own `palette`\n * overrides them. Held by `chart.test.ts`.\n */\nexport const CHART_PALETTE = ['#1f77b4', '#d95f02', '#1b9e77', '#7570b3', '#e7298a', '#5a8f1a', '#a6761d', '#666666'] as const\n\n/** What the chart groups the detail rows by: one group, one category, for each value the field takes. */\nexport interface ChartCategory {\n readonly field: FieldRef\n readonly order: ChartOrder\n /** How the category prints; it must display the field's type. */\n readonly format?: Format\n /** The label of the rows whose category is null, never blank; asked of a field that may be null. */\n readonly nullLabel?: string\n}\n\n/** One thing a chart totals for each category: a function over a detail field, as an aggregate's, with `avg` declaring its rounding. */\nexport interface ChartSeries {\n /** Unique in the chart. */\n readonly id: string\n /** The legend's entry. */\n readonly label: string\n readonly fn: AggregateFunction\n /** Absent only for `count`, which then counts rows. */\n readonly of?: FieldRef\n readonly rounding?: Rounding\n}\n\n/** A chart drawn in a box of fixed size; the width and the height bound it whatever its data holds. */\nexport interface ChartComponent extends ComponentBase {\n readonly kind: 'chart'\n readonly chart: ChartKind\n readonly dataset: 'detail'\n readonly width: number\n readonly height: number\n readonly category: ChartCategory\n readonly series: readonly ChartSeries[]\n /**\n * How every value prints: each tick, each value label, and a pie's values.\n * A pie's shares, printed beside its values where it labels them, are not\n * this format's: each is the exact ratio rounded once, half away from zero,\n * to a percentage of one place, written as the locale writes one (the\n * runtime's `SHARE_PLACES`).\n */\n readonly valueFormat: NumberFormat | CurrencyFormat\n /** What prints in place of a chart with nothing to draw. */\n readonly emptyText: string\n readonly title?: string\n readonly categoryTitle?: string\n readonly valueTitle?: string\n readonly valueLabels?: boolean\n /** Replaces `CHART_PALETTE`: one to eight distinct colours, and in a bar or a line chart at least one for each series. */\n readonly palette?: readonly string[]\n}\n","/**\n * The bounds a report definition is held to, and why each exists.\n *\n * A template is untrusted input, even when an administrator wrote it. Every\n * array, string and number in it is bounded, so that validating, hashing,\n * editing and later laying one out costs work that does not grow with\n * whatever a broken or hostile document holds. An array is measured before\n * any element of it is read.\n *\n * The numbers are chosen, not measured: each sits well above what the three\n * starter reports need (plan 7) and low enough to keep that work small. Two\n * are not chosen, and say where they come from. Raising a bound is safe;\n * lowering one refuses reports that were valid, which once the format is\n * frozen means a new reportSpecVersion.\n *\n * The bounds of an SVG asset and of a font, at the end, are the\n * exception: each but `MAX_SVG_REMOVED_NAMES` was measured, and says how,\n * on what and when (0030, 0040). `MAX_REPORT_BYTES` is a multiple of a\n * measured size and says so.\n */\nimport { CHART_PALETTE } from './chart.js'\n\n/**\n * Errors listed per validation. Past it, one `too-many-errors` entry says\n * the list was cut short, so a caller never mistakes a partial list for a\n * whole one. Enough to fix a broken template in one pass; not so many that\n * a document of junk produces megabytes of messages.\n */\nexport const MAX_ERRORS = 100\n\n/**\n * Components in one region, counting those inside containers, so wrapping\n * components in a container does not get round it. A printed page holds a\n * few dozen blocks; a region of five hundred is a document that should be\n * two.\n */\nexport const MAX_REGION_COMPONENTS = 500\n\n/**\n * How deep containers (columns, keep-together blocks) nest. A container\n * inside four others is refused. Every stage that walks the tree --\n * validation, the core's commands, the runtime, the layout -- recurses this\n * deep and no deeper, and nesting past it is a layout no reader follows.\n */\nexport const MAX_NESTING_DEPTH = 4\n\n/** Columns in a columns block: fewer than two is not columns; more than four on A4 is too narrow to read. */\nexport const MIN_COLUMNS = 2\nexport const MAX_COLUMNS = 4\n\n/** Columns in a table: wider than a landscape page can show legibly, and a bound on per-row work. */\nexport const MAX_TABLE_COLUMNS = 32\n\n/**\n * Tables in a report, counting those inside containers (0062). Chosen, not\n * measured: each table orders the rows its condition selects, work no step\n * budget counts, and reads its condition once per detail row, which the\n * render's budget does; a report of more lists than eight is several\n * reports. Ordering the runtime's `MAX_DETAIL_ROWS` once, by two keys,\n * took a median of 0.5 seconds (Node 24.21, an Intel i9-10900K, 15 October\n * 2026, as measured beside that bound). What eight cost at that bound was\n * measured on the same machine and Node on 15 November 2026, the median of\n * five runs of the built runtime's `resolveReport` after one that warmed\n * it, each table of two columns grouped by one field, sorted by another\n * and totalling one sum over its rows: one table without a condition\n * resolved in 1.4 seconds, eight each selecting an eighth of the rows by a\n * condition of one read in 4.0, and eight each selecting every row,\n * 800,000 rows lowered, in 12.2. A condition of one read is charged two\n * steps, so eight read over every row spend 1,600,000 of the runtime's\n * `RENDER_STEP_BUDGET`.\n */\nexport const MAX_TABLES = 8\n\n/** Sort keys on a table. Each one costs a comparison per row pair; a longer sort is usually a missing key. */\nexport const MAX_SORT_KEYS = 8\n\n/** Rows under a group or under the table: a subtotal, a discount, two tax lines and a total fit with room to spare. */\nexport const MAX_FOOTER_ROWS = 8\n\n/**\n * The most of its group's first rows a group header may be kept on its\n * page with (0059). Chosen, not measured: well above the two or three rows\n * that keep a group from starting at the foot of a page. A count past what\n * a page holds keeps what fits, so the bound protects no page: it refuses\n * a count nobody means, and bounds what the renderer adds up for each\n * group header.\n */\nexport const MAX_KEEP_WITH_ROWS = 32\n\n/** Fields in one dataset contract: a report prints a fraction of any source table's columns. */\nexport const MAX_DATASET_FIELDS = 64\n\n/** Print styles in one report. A report's look is a handful of tokens; this is many handfuls. */\nexport const MAX_STYLES = 64\n\n/** Conditional style rules on one component or column. Each is an expression evaluated per render or per row. */\nexport const MAX_STYLE_RULES = 8\n\n/** Parameters: each is a field on the parameter form a person fills in before rendering. */\nexport const MAX_PARAMETERS = 32\n\n/** Asset references: each is a lookup and a byte budget at render time. */\nexport const MAX_ASSETS = 64\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, and chosen, not\n * measured. A builder refuses a file past it before reading it, the runtime\n * a host's answer past it before copying it, and the renderer bytes past it\n * before decoding them, from this one constant; an SVG is held to\n * `MAX_SVG_BYTES` besides.\n */\nexport const MAX_ASSET_BYTES = 20 * 1024 * 1024\n\n/**\n * The most bytes a report may have as a draft: the UTF-8 length of its\n * JSON, which is what a client sends and a server can count before it\n * parses anything, so a route can bound its body by this one constant.\n * 256 KiB, the least power of two that is at least sixteen times the\n * largest report definition the corpus exports, starters, samples and the\n * site visit's report among them. That is the XRechnung sample, 16,254\n * bytes, an e-invoice being the report with the most terms to state; the\n * next is 16,027 and the smallest 3,956 (measured on 2026-10-28 on an\n * Apple M2 under Node 22.23.3, as\n * `new TextEncoder().encode(JSON.stringify(report)).byteLength`). A\n * report sixteen times the richest one is a document that should be\n * several, and the limit is a quarter of the mebibyte Fastify reads by\n * default, which a draft's request should not need to exceed.\n *\n * The factor is chosen, and the bounds above allow far more: one region of\n * `MAX_REGION_COMPONENTS` text components that each hold `MAX_TEXT_LENGTH`\n * characters holds five million characters. A report of that kind\n * validates and is not kept as a draft. Raising the limit is safe;\n * lowering it refuses reports that were kept. The corpus's\n * `report-size.test.ts` holds every report there to the limit, and the\n * limit to this factor.\n */\nexport const MAX_REPORT_BYTES = 262_144\n\n/**\n * Pixels a side of a PNG or a JPEG asset: the renderer trial's limit too,\n * and as chosen. What pictures of this size cost the renderer to embed is\n * measured beside report-render-pdf's `MAX_IMAGE_DATA`, which bounds a\n * render by them. `imageHeader` holds a picture to it, where a person adds\n * one and where it prints.\n */\nexport const MAX_ASSET_SIDE = 4096\n\n/** Series in a chart: a colour each from the palette, so that the legend tells every one apart. Derived, not chosen. */\nexport const MAX_CHART_SERIES = CHART_PALETTE.length\n\n/** The least a chart's side: under an inch (72 points) holds no plot beneath its title and its labels. Chosen, not measured. */\nexport const MIN_CHART_SIDE = 72\n\n/** Aggregates: each is a pass over the detail rows, per group, once per table that selects its rows (0062), and once overall. */\nexport const MAX_AGGREGATES = 32\n\n/**\n * VAT categories an e-invoice declares, each a VAT breakdown (BG-23) its\n * XML writes and a basis and an amount its page reads. Germany's two rates,\n * an exempt category and a reverse-charged one take four; eight is twice\n * that, and a list of breakdowns no invoice prints is refused unread.\n */\nexport const MAX_VAT_CATEGORIES = 8\n\n/** Inline runs in one paragraph or group header. A paragraph with more bindings than this is a table. */\nexport const MAX_INLINES = 64\n\n/**\n * Characters in a property name. The format's own names are short and its\n * ids are at most 64 characters, so a longer name is never one it knows. It\n * is refused before a path is built from it, so that no path and no message\n * grows with what a document holds.\n */\nexport const MAX_KEY_LENGTH = 64\n\n/** Characters (UTF-16 code units, as JavaScript counts) in a literal run of text: several pages of prose. */\nexport const MAX_TEXT_LENGTH = 10_000\n\n/** Characters in a title, label, column header, empty-state text or parameter default: one line, generously. */\nexport const MAX_LABEL_LENGTH = 200\n\n/**\n * Keys in a formancy data path a dataset field is read from (0042): a\n * field in a group in a group, sixteen deep. Chosen, not measured: formancy\n * bounds no nesting, and a person filling in a form does not follow one\n * deeper than a few groups. It bounds a path to 1,039 characters, so no\n * path a message names grows with what a document holds.\n */\nexport const MAX_FORM_PATH_KEYS = 16\n\n/**\n * Characters in a member a dataset field is read from: a matrix row's\n * value or a selectboxes option's (0042). Not chosen: formancy's schema\n * writes both from 1 to 200 characters, so a longer one names nothing a\n * form could hold.\n */\nexport const MAX_FORM_MEMBER_LENGTH = 200\n\n/**\n * Form versions one binding is read differently in (0048): the overrides\n * a review writes on a field, or on the detail's repeater, one for each\n * version that moved or removed it. Chosen, not measured: a field moved\n * by 64 versions of its form is read from a form that has become another\n * one, and a report better started again from it (0045). It bounds a\n * binding to 64 hashes, so no binding grows with what a document holds.\n */\nexport const MAX_FORM_OVERRIDES = 64\n\n/**\n * Languages a report is written in, its own among them (0063). Chosen, not\n * measured: the European Union's official languages are twenty-four, and a\n * report is validated once for each language it declares.\n */\nexport const MAX_LANGUAGES = 24\n\n/**\n * Words one translation holds, and expressions that print words: each list\n * bounded by it (0063). 1,024, the least power of two that is at least\n * sixteen times the most a report the corpus exports holds of both: the\n * XRechnung sample, 36 distinct words and 13 expression runs where words\n * stand, 49 (measured on 2026-11-15 on an Intel i9-10900K under Windows 11\n * and Node 24.21.0, as the distinct texts `reportWords` gives and the\n * distinct sources `wordExpressionSites` gives). That sample written in\n * `MAX_LANGUAGES` languages, each translation as long as its word, is\n * 91,113 bytes, inside `MAX_REPORT_BYTES`.\n *\n * The format admits far more words than this: every region may hold\n * `MAX_REGION_COMPONENTS` texts of `MAX_INLINES` runs. Such a report\n * validates and cannot be translated whole: each word past the bound stays\n * missing in that language, said as report-core's `word-missing`, and a\n * render in it is refused. The corpus's `report-size.test.ts` holds the\n * bound to this factor.\n */\nexport const MAX_WORDS = 1024\n\n/** Characters in a CEL expression. An expression is a formula, not a program; the runtime bounds its evaluation too. */\nexport const MAX_EXPRESSION_LENGTH = 1024\n\n/** Digits after the decimal point, for fields, formats and rounding. Covers every currency's minor unit and unit prices to many places. */\nexport const MAX_SCALE = 20\n\n/** Font sizes in points: below 4 is not legible print, above 96 is a poster. */\nexport const MIN_FONT_SIZE = 4\nexport const MAX_FONT_SIZE = 96\n\n/**\n * The longest length anything in a report may have, in points. Not chosen:\n * 14,400 units (200 inches) is the largest page dimension PDF readers\n * implement (ISO 32000-1, Annex C), so nothing longer can appear on a page.\n */\nexport const MAX_LENGTH_PT = 14_400\n\n/**\n * The smallest printable area the margins may leave, each way: one inch,\n * 72 points. Not chosen so much as named: less than an inch of width does\n * not hold a word of body text.\n */\nexport const MIN_PRINTABLE_PT = 72\n\n/*\n * The bounds of an SVG asset (0030). Each is held by report-spec's\n * `cleanSvg` when an asset is approved and by `checkSvg` when it prints, so\n * that an approved drawing costs a bounded amount to clean, to draw and to\n * read back, wherever it is drawn. A `source.js:N` below is a line of\n * pdfmake 0.3.11's `src/3rd-party/svg-to-pdfkit/source.js`, of which Node\n * runs a transpiled copy under `js/`.\n *\n * Measured on 2026-10-18 on an Intel i9-10900K under Node 24.21.0 with\n * pdfmake 0.3.11, and in Chromium 156.0.8078.4 (Playwright 1.64.1's headless\n * shell, drawing in software) with pdfjs-dist 6.4.299, as the Studio's\n * Preview draws a page. A starter page costs 63-89 ms to pixels there. The\n * aim the per-drawing bounds were set by is that the worst logo they\n * accept, at the starters' 15 mm, costs about what one more starter page\n * costs; what they give is more, two to six starter pages at 15 mm and\n * three to eight page-wide (`MAX_SVG_SEGMENTS`), since a bound low enough\n * to keep the aim against a rasteriser's worst would refuse detailed\n * logos. The machine was shared, so a time below is a median, and a range\n * where repeated runs differed.\n */\n\n/**\n * Bytes in an SVG asset, both as the file comes and as `cleanSvg` writes it:\n * the written form can be several times its input -- a relative path written\n * as absolute coordinates, a colour name as `#rrggbb` -- so a drawing whose\n * cleaned form would pass this is refused when it is approved, not at every\n * print after. A logo is kilobytes; the exporters' invented samples were\n * 545-2,520 bytes in and 483-994 out. At the bound the cleaner itself took\n * at most 179 ms in Node on the costliest it accepts (`MAX_SVG_CASCADE`'s\n * worst; 3,000 moves, each styled with every property and turned, written\n * to 1.04 MB, 141-162 ms), 35-120 ms on a mebibyte of each shape of value\n * `svg-threats.test.ts` holds it to, and 292-331 ms to refuse a mebibyte of\n * path past MAX_SVG_SEGMENTS (Node alone, on the day these were measured\n * again); a page of rectangles of that size takes the renderer 0.94 s to\n * draw.\n */\nexport const MAX_SVG_BYTES = 1_048_576\n\n/**\n * Element levels in a drawing, the root's included, as the file nests them\n * and as `cleanSvg` writes them; also the longest chain of gradients that\n * name each other. pdfmake's XML reader and svg-to-pdfkit both recurse once\n * per level, and 5,000 levels overflowed the stack in a probe. 32 and 64\n * levels with a transform each cost the same as none (122 ms to render, 59-65\n * ms to pixels), so this bounds recursion, not time. The deepest exporter\n * sample nests four.\n */\nexport const MAX_SVG_DEPTH = 32\n\n/**\n * Elements in a cleaned drawing. svg-to-pdfkit re-reads and draws every one\n * on every page it is drawn on, at about 34 microseconds an element: 10,000\n * one-unit rectangles took 545 ms of the renderer's final pass against 55\n * without them, and 234 ms (DPR 1) and 198 ms (DPR 2) to pixels.\n */\nexport const MAX_SVG_ELEMENTS = 10_000\n\n/**\n * What one drawing costs a reader to paint, in weighted segments. Each\n * command the converter draws counts: a move, a line or a close 1, a curve\n * 3 (10,000 short crossing cubics cost about what 30,000 such lines do, in\n * Node and in Chromium; a cubic spanning the box costs less than three\n * lines that do, 10,000 of them 238 ms against 933 ms for 30,000 lines,\n * as review measured the same day), an arc 3 for each curve svg-to-pdfkit splits it\n * into (one per 60 degrees, `source.js:1054` at its default precision), and\n * an arc that ends where it starts, which draws nothing, 1. A stroked shape\n * counts its commands twice more, three times in all when it is also filled\n * (10,000 lines filled and stroked cost about what 30,000 filled do). A clip\n * path's commands count once for every element it clips, a gradient's stops\n * once for every shape painted with it, and a dashed stroke one more for\n * each dash it could draw.\n *\n * A rasteriser's worst is a path whose every segment crosses the whole\n * box: it pays for each segment on every row of pixels the segment spans,\n * so the cost grows faster than the count. A zigzag of such lines took 121\n * ms to pixels at DPR 1 and 132 ms at DPR 2 in a 15 mm box at this bound,\n * 268-276 ms at 15,000, 490-500 ms at 20,000 and 1.15-1.27 s at 30,000; the\n * worst accepted -- that zigzag in a clipped group, with three more clipped\n * shapes, every group the bounds allow -- took 190 and 392 ms at 15 mm and\n * 269 and 550 ms page-wide, against 63 to 89 ms for a starter page (on\n * 2026-10-18, in the Chromium and pdfjs-dist above, medians of five). The\n * same count of 30,000 in paths whose segments were a seventh of the box\n * long took 184-295 ms, and spanning the box 1.15 to 1.84 s. A logo whose\n * curves are short costs far less than its count says, and one of more\n * than this is refused, to be simplified in the drawing program.\n */\nexport const MAX_SVG_SEGMENTS = 10_000\n\n/**\n * Transparency groups in one drawing, in units: a clip-path reference 1, a\n * group with an opacity under 1 1, and a shape painted with a gradient\n * whose stops come out translucent 2. svg-to-pdfkit makes every one a\n * group the size of the whole page, whatever the size of the logo, and a\n * translucent gradient two page-sized objects, so the cost is the page's\n * pixels: about 15 ms a clip at DPR 1 and 59 ms at DPR 2, 30 ms and 117 ms\n * a translucent gradient, 1.4 ms and 5.2 ms a group opacity. Four units keep\n * the worst accepted at about 60 ms more than a starter page at DPR 1 and\n * 240 ms at DPR 2, and admit every exporter sample: Figma's clipped frame is\n * 1, Figma's fade with a layer at 80 % is 3, Canva's two shapes 2. A\n * translucent stop is kept because a bound this small admits them; a Canva\n * logo of five shapes or more, each clipped, is refused.\n */\nexport const MAX_SVG_GROUPS = 4\n\n/**\n * Stops in one gradient. Each use of a 64-stop gradient writes 10.9 kB into\n * the PDF and costs a reader about half a millisecond; `MAX_SVG_SEGMENTS`\n * bounds the uses, counting a gradient's stops once each. A logo's\n * gradients have two to five.\n */\nexport const MAX_SVG_STOPS = 64\n\n/**\n * Entries in a stroke's dash array, after an odd list is doubled as SVG\n * doubles it. Every dash it draws counts against `MAX_SVG_SEGMENTS` too: a\n * spiral of 4,096 segments dashed at a period of 0.01 units, about 900,000\n * dashes, cost 219-265 ms to pixels against 70-102 ms dashed at a period of\n * one unit. Skia gives up at a count of its own; another reader may not.\n */\nexport const MAX_SVG_DASHES = 32\n\n/**\n * The largest magnitude of any number in a drawing; of every entry of the\n * transform composed from the root down to each element, and of its\n * inverse, which svg-to-pdfkit computes for every clip and group opacity;\n * and of the matrix a gradient is drawn under, its shape's and its box's\n * composed with its own. With a point and a matrix both at it in a viewBox\n * one unit wide, the renderer drew in 115 ms with no warning, and the\n * device coordinates stayed near 10^13 points, far below the 10^21 at\n * which PDFKit throws; past it, two groups shrinking a millionfold each\n * under a clip, or a gradient composed to a million cubed, threw from\n * inside PDFKit. An e-invoice's PDF/A-3 keeps none of PDF/A-1's 32,767 for\n * a real: veraPDF 1.30.3's PDF/A-3b profile holds a real to 3.403 × 10^38\n * (its rule 6.1.13-2), past PDFKit's 10^21, and an integer to 2,147,483,647\n * (6.1.13-1), which the numbers the converter computes from these bounds can\n * pass -- a group's box under a shrink of 10^6 in a box of a point reached\n * 7.85 × 10^10 -- so the renderer holds an SVG in an e-invoice to that by\n * the extent `cleanSvg` measures (`svg-extent.ts`; report-render-pdf's\n * `svg-pdfa.ts`), and no bound here is lowered for it.\n */\nexport const MAX_SVG_COORDINATE = 1_000_000\n\n/**\n * Simple selectors -- a type, a class or an id -- in all of a drawing's\n * stylesheets together, after comma lists are split. Indexing the rules by\n * id, class and type makes matching linear in the rules that could match,\n * but rules that all match every element cannot be shortened that way, so\n * the work is this bound times the combinations of classes elements hold.\n * The rules one combination matches are merged once: 256 one-class rules,\n * each declaring every kept property, all matching 10,000 elements, took\n * the cleaner 85-102 ms in Node and 63-81 ms in Chromium, against 1.9 s\n * when every element read every rule. Elements of combinations of their\n * own are bounded by `MAX_SVG_CASCADE`. Illustrator's samples hold three.\n */\nexport const MAX_SVG_RULES = 256\n\n/**\n * The cascade's work, in all: each rule compared with a combination of\n * type, id and classes an element holds, and each declaration merged for it.\n * Merging once per combination makes ten thousand elements of one class one\n * merge, but elements that each hold a combination of their own are one\n * merge each: 9,990 elements, each of its own set of fourteen classes, under\n * 242 type rules declaring every kept property took the cleaner 1.8 s in\n * Node. At this bound the costliest shape measured -- 5,000 elements each\n * of its own pair of 101 classes, under 98 type rules of one declaration --\n * took 179 ms (158-271), within what the worst file `MAX_SVG_BYTES` admits\n * costs, and that shape of 9,990 elements is refused in 136 ms. An\n * Illustrator export, one class an element from a few dozen, merges a few\n * hundred times. Measured on 2026-10-18 under Node 24.21.0, medians of five,\n * on the machine and the terms above.\n */\nexport const MAX_SVG_CASCADE = 1_000_000\n\n/**\n * Distinct names `cleanSvg` lists among what it removed; removals of every\n * further name are counted, not named, so that the list a person is shown\n * does not grow with what a file holds. Chosen, not measured: the Inkscape\n * sample, the most any exporter's sample removes, lists 26 names -- its\n * editor's attributes, namespaces, layers and text properties -- and a\n * bound of 16 would have cut it short.\n */\nexport const MAX_SVG_REMOVED_NAMES = 32\n\n/**\n * The bounds of a font asset (0040), each measured on 21 October 2026 on\n * an Intel i9-10900K under Windows 11 and Node 24.21.0, shared with another\n * workflow's builds (8 to 11 % load), medians of seven reads: on the\n * costliest font these three admit, made in code; on the 447 `.ttf` and\n * `.ttc` files of the machine's Windows fonts directory, never copied into\n * the repository; and on the faces the renderer ships. The reads, and the\n * tally of the machine's fonts, were measured again on 22 October 2026, on\n * the reader as review left it, at 1 to 12 % load.\n */\n\n/**\n * Bytes in a font: an image asset's 20 MB (`MAX_ASSET_BYTES`), which a\n * builder, the runtime and the renderer already hold an asset to. The\n * costliest font it admits -- 65,534 glyphs each walked flag by flag, a\n * format 12 map of 131,066 characters -- read in 60 ms (57-65); Malgun\n * Gothic, 13.5 MB and 28,215 glyphs, in 16 to 17 ms, Liberation Sans in\n * 0.8.\n * What subsetting a large font costs a render is bounded by the outlines'\n * points and work together (`MAX_FONT_POINTS`, `MAX_FONT_OUTLINE_WORK`),\n * not by its bytes; of the machine's fonts, two collections and\n * SimSun-ExtB, 21.9 MB, are past it.\n */\nexport const MAX_FONT_BYTES = MAX_ASSET_BYTES\n\n/**\n * Characters one font may map: 131,072, twice the BMP. A kilobyte of\n * format 12 can map every code point there is, a Set of 1,114,112 entries\n * that took 150 ms and 60 to 80 MiB of heap to build; at this bound the Set\n * takes 8 ms and 5 MiB. Of the 412 fonts on the machine the reader\n * accepts, the most a font maps is 28,530 (HP Simplified Hans); Roboto maps\n * 927, Liberation Sans 2,327. Chosen, at more than four times the most\n * measured.\n */\nexport const MAX_FONT_CHARACTERS = 0x20000\n\n/**\n * A simple glyph's points times its contours. fontkit, through which\n * PDFKit subsets a font, looks every point up among the glyph's contour\n * ends: one glyph of 32,767 contours and 65,534 points, 66 KB of a font\n * the reader otherwise accepts, took PDFKit 1.6 s to embed, and 16,000\n * contours of 32,000 points 0.4 s, four times as long for each doubling.\n * At this bound a glyph costs it under a millisecond: 200 such glyphs\n * embedded in 168 ms. The most of any glyph in the machine's fonts is\n * 160,000 (200 contours of 800 points, Lucida Sans Unicode); Liberation\n * Sans's is 28,224, Roboto's 3,549.\n */\nexport const MAX_FONT_GLYPH_WORK = 1_048_576\n\n/**\n * The points of every simple glyph of a font, together: 2,097,152 (2^21).\n * A subset holds every glyph a printed character reaches -- a composite's\n * components among them, which may be every glyph the font has -- and\n * fontkit decodes each point of each into an object of its own when PDFKit\n * subsets. A font this reader accepted under the bounds above, one 'A'\n * composed of 36,733 glyphs of 16 contours and 65,536 points, took PDFKit\n * 162 s to embed (0043). Of the 412 fonts on the machine the reader\n * accepts, the most points a font holds is 1,886,654 (Malgun Gothic Bold,\n * a Hangul font whose script no report prints), Noto Sans 65,560 and\n * Liberation Sans 35,285. Chosen just past the most measured, since the\n * cost is what a render waits for, and the fonts that come near it hold\n * Hangul, Han or a dozen scripts, which no report prints. At this bound\n * and the next, the costliest subset found -- 31 glyphs of 8 contours and\n * 65,536 points of one-byte coordinates and 65,500 glyphs of one point,\n * one composite made of them all -- took PDFKit 1.3 to 1.4 s to embed,\n * over three runs.\n * Measured on 22 October 2026 on an Intel i9-10900K under Windows 11 and\n * Node 24.21.0, shared with two other workflows' builds.\n */\nexport const MAX_FONT_POINTS = 2_097_152\n\n/**\n * Every simple glyph's points times its contours, together: 16,777,216\n * (2^24), sixteen glyphs at `MAX_FONT_GLYPH_WORK`. fontkit looks each point\n * up among its glyph's contour ends, so a font of fewer points than the\n * bound above can still cost a subset this much; sixteen glyphs at the\n * bound took PDFKit 44 ms to embed. The most of the machine's fonts is\n * 12,342,110 (Malgun Gothic), Liberation Sans's 123,704. Chosen past the\n * most measured, as above. Measured as above.\n */\nexport const MAX_FONT_OUTLINE_WORK = 16_777_216\n\n/**\n * The components of every composite glyph of a font, together: 262,144\n * (2^18). PDFKit's subset decodes a composite's components into a list,\n * however many of them name the same glyph: one composite of 3,490,000\n * components, what 20 MiB holds, took PDFKit 1.0 s and 431 MiB of heap to\n * embed for one 'A'. The most of the machine's fonts is 68,743 (HP\n * Simplified Hans Light), and the most in one glyph 15; Liberation Sans\n * holds 2,131, Roboto 1,321. Chosen at nearly four times the most measured.\n * Measured as above.\n */\nexport const MAX_FONT_COMPONENTS = 262_144\n\n/**\n * A font's line, in ems: its horizontal header's ascender less its\n * descender, over its units to the em, which is how tall pdfmake lays out\n * each line of it (PDFKit's `lineHeight`, from fontkit's `hhea.ascent`,\n * `hhea.descent` and `head.unitsPerEm`; the line gap unread), its\n * baseline the ascender below the line's top. The renderer counts a line\n * of text as its size times this when it refuses a report too long for its\n * page limit before laying it out (`bound.ts`), so the floor bounds how\n * many lines a limit admits: at 0.5, 2.3 times what Roboto's 1.172 does.\n * Unbounded, a face of a line of nothing printed a report of 20,000 lines,\n * limited to one page, on one spot of that page, in 921 ms, and one of 4\n * units to the em 2,000 lines within 35 points, each over the last (0040).\n * The ceiling refuses metrics no font measured comes near; a line too tall\n * for the page is refused at print besides.\n * Measured on 22 October 2026 on the machine above, over the 425 fonts the\n * reader accepts of Roboto 3.014's four faces, Liberation Sans, Serif and\n * Mono 2.1.5's eight, Noto Sans Regular (0043's Sources) and the 447 files\n * of the machine's Windows fonts directory: the shortest line is Ink\n * Free's, 0.864, then Footlight MT Light's, 0.915 and Palace Script MT's,\n * 0.926; the tallest Sans Serif Collection's, 2.651, then Javanese Text's,\n * 2.271 and Myanmar Text Bold's, 1.904; Liberation's are 1.107 to 1.133,\n * Roboto's 1.172 and Noto Sans's 1.362. fontkit read every one's ascender,\n * descender and units as the reader does. Chosen with a margin: the floor\n * half the shortest line, rounded up to half an em, 42 % below it; the\n * ceiling one and a half times the tallest, rounded to a whole em, 51 %\n * above it.\n */\nexport const MIN_FONT_LINE = 0.5\nexport const MAX_FONT_LINE = 4\n","/**\n * JSON Pointers (RFC 6901), the one way this package says where something\n * is: validation errors and `walkComponents` use the same paths, so an\n * error can be matched to the component it is about.\n */\n\n/**\n * `path` extended by one key or index, escaped as RFC 6901 says.\n *\n * Validation builds a path for every property it reads, so the common case\n * -- an index, or a key with nothing to escape -- is a concatenation; the\n * two replacements took half of validation's time when they ran on every\n * key (measured with --cpu-prof on a 40-component report, 14 October 2026).\n */\nexport function at(path: string, key: string | number): string {\n if (typeof key === 'number' || !(key.includes('~') || key.includes('/'))) return `${path}/${key}`\n return `${path}/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`\n}\n","/**\n * What a valid string looks like, for each string in a report that has a\n * syntax. One pattern per thing, so the validator and an editor checking a\n * value as it is typed cannot disagree.\n *\n * Each accepts one spelling of each value -- lower-case hex, canonical\n * locale case, no negative zero -- so that one value has one canonical hash.\n */\nimport { MAX_FORM_PATH_KEYS } from './limits.js'\n\n/**\n * Identifiers: lower-case letters, digits and hyphens, starting with a\n * letter, at most 64 characters. The names a deployment resolves -- a\n * dataset, an asset -- are written this way, as formancy writes a named\n * options source (formancy.ai 0077), and so are the format's structural\n * names: components, styles, table columns.\n */\nconst IDENTIFIER = /^[a-z][a-z0-9-]{0,63}$/\n\n/** Whether `value` is an identifier a report can use for a component, style, dataset, asset or table column. */\nexport function isIdentifier(value: unknown): value is string {\n return typeof value === 'string' && IDENTIFIER.test(value)\n}\n\n/**\n * Field keys: formancy's `fieldKey` exactly -- letters, digits and\n * underscores, starting with a letter or an underscore, at most 64\n * characters, the case part of the key. The names an expression reads are\n * written this way: a dataset field, a parameter, an aggregate. So a form's\n * or a dataset's key is the report's key unrenamed, and CEL reads it with a\n * dot, `row.unitPrice`, where a hyphen would read as a subtraction.\n */\nconst FIELD_KEY = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/\n\n/** Whether `value` is a field key: the id of a dataset field, a parameter or an aggregate. */\nexport function isFieldKey(value: unknown): value is string {\n return typeof value === 'string' && FIELD_KEY.test(value)\n}\n\n/**\n * Whether `value` is a formancy data path in one scope, as a dataset field\n * is read from a submission (0042): field keys joined by dots, as\n * `modelDataPaths` writes a group's child, `address.street`, and at most\n * `MAX_FORM_PATH_KEYS` of them. A repeater's `[]` is not in it, since a\n * path is read in the submission's scope or a row's, never across both.\n */\nexport function isFormPath(value: unknown): value is string {\n // Measured before it is split: no key is longer than 64 characters.\n if (typeof value !== 'string' || value.length > MAX_FORM_PATH_KEYS * 65 - 1) return false\n const keys = value.split('.')\n return keys.length <= MAX_FORM_PATH_KEYS && keys.every((key) => FIELD_KEY.test(key))\n}\n\n/** A formancy form's id, as its schema writes one (`formId`): at most 128 characters. */\nexport const FORM_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/\n\n/** Whether `value` is a formancy form's id: what a report's provenance names, and the runtime's data source (0041). */\nexport function isFormId(value: unknown): value is string {\n return typeof value === 'string' && FORM_ID.test(value)\n}\n\n/**\n * The BCP 47 subset a report's locale may be: a language (2-3 letters), an\n * optional script (4 letters, title case) and an optional region (2 letters\n * upper case, or 3 digits) -- 'en', 'de-CH', 'zh-Hans-CN', 'es-419'.\n * Variants, extensions and private use are refused rather than half-read,\n * and a regular expression rather than Intl decides, because Intl's\n * canonicalisation differs between ICU versions and a template must\n * validate the same in every runtime.\n */\nexport const LOCALE = /^[a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-(?:[A-Z]{2}|\\d{3}))?$/\n\n/** Whether `value` is a locale as a report writes one: what the runtime holds the locale a form source's labels were read in to (0063), so that the two cannot read a locale differently. */\nexport function isLocale(value: unknown): value is string {\n return typeof value === 'string' && LOCALE.test(value)\n}\n\n/** A colour: `#rrggbb`, lower case. */\nexport const COLOR = /^#[0-9a-f]{6}$/\n\n/** An ISO 4217 currency code, upper case. */\nexport const CURRENCY = /^[A-Z]{3}$/\n\n/** An asset's content digest: SHA-256, lower-case hex. */\nexport const DIGEST = /^sha256:[0-9a-f]{64}$/\n\n/**\n * Whether `value` is an asset's digest as a report declares one, `sha256:`\n * and 64 lower-case hex digits: the one rule for it, which the report\n * server judges a path's digest by, with `sha256:` before it, and its store\n * names a file by (0049).\n */\nexport function isDigest(value: unknown): value is string {\n return typeof value === 'string' && DIGEST.test(value)\n}\n\n/** A form version's hash, as `@formancy/spec`'s `schemaHash` writes it: 64 lower-case hex digits. */\nexport const SCHEMA_HASH = /^[0-9a-f]{64}$/\n\n/** Whether `value` is a form version's hash as `schemaHash` writes one: what a report's provenance pins, and the runtime's data source (0041). */\nexport function isSchemaHash(value: unknown): value is string {\n return typeof value === 'string' && SCHEMA_HASH.test(value)\n}\n\n/** An exact integer as a string: no sign but '-', no leading zeros, no exponent, and no '-0'. */\nexport const INTEGER = /^(?:0|-?[1-9]\\d*)$/\n\n/**\n * An exact decimal as a string: an integer, optionally a point and at least\n * one digit. Trailing zeros are kept, because they say the scale ('1.50' has\n * two places); a negative zero ('-0', '-0.00') is refused. A negative\n * value under one is its zeros, then the digit that is not one, then any:\n * one way to read each string, so a long one that fails is refused in time\n * linear in its length, where `\\d*[1-9]\\d*` tried every split of its digits.\n */\nexport const DECIMAL = /^(?:-?[1-9]\\d*(?:\\.\\d+)?|0(?:\\.\\d+)?|-0\\.0*[1-9]\\d*)$/\n\nconst DATE = /^(\\d{4})-(\\d{2})-(\\d{2})$/\n\n/**\n * Whether `value` is a calendar date written YYYY-MM-DD: 2024-02-29 is one,\n * 2026-02-29 is not, and neither is any day of the year 0000, which Intl\n * shows as the year 1 -- 1 BC without its era -- a year nobody wrote.\n */\nexport function isCalendarDate(value: string): boolean {\n const match = DATE.exec(value)\n if (match === null) return false\n const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])]\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 * Lengths: the one conversion between points and millimetres, and the one\n * rounding every stored length goes through (plan 9).\n *\n * A report stores points, the PDF unit. Millimetres are what an author in\n * Switzerland or Germany types and reads, so the builder converts at its\n * edge, here and nowhere else.\n */\n\n/** Points per inch: the default PDF user-space unit is 1/72 inch. */\nexport const POINTS_PER_INCH = 72\n\n/** Millimetres per inch, exactly. */\nexport const MILLIMETRES_PER_INCH = 25.4\n\n/**\n * To the nearest hundredth, ties away from zero, and never -0.\n *\n * Ties are decided on the binary value JavaScript computed, which for a\n * product like `mm * 72 / 25.4` is already a little either side of any\n * exact tie. Symmetric about zero, so a length and its negation round to\n * the same magnitude.\n */\nfunction toHundredths(value: number): number {\n return (Math.sign(value) * Math.round(Math.abs(value) * 100)) / 100 + 0\n}\n\n/**\n * A length in points rounded to the 0.01 pt a report stores. A hundredth of\n * a point is under four thousandths of a millimetre: finer than any printer\n * places ink, coarse enough that one length has one stored value.\n */\nexport function roundPt(points: number): number {\n return toHundredths(points)\n}\n\n/** Millimetres to points, rounded to 0.01 pt. */\nexport function mmToPt(millimetres: number): number {\n return roundPt((millimetres * POINTS_PER_INCH) / MILLIMETRES_PER_INCH)\n}\n\n/**\n * Points to millimetres, rounded to 0.01 mm, for display. A value typed in\n * millimetres to two decimals, stored with `mmToPt`, comes back as typed:\n * the stored point value is within 0.005 pt (0.0018 mm) of the exact one,\n * well inside the 0.005 mm that would change the displayed hundredth.\n */\nexport function ptToMm(points: number): number {\n return toHundredths((points * MILLIMETRES_PER_INCH) / POINTS_PER_INCH)\n}\n","/**\n * Reading untrusted input once, and checking the values in it: the\n * vocabulary every part of validation is written in.\n *\n * Every object and array is read once, through its property descriptors,\n * into a copy; validation then works on the copy and builds the report it\n * returns from what it checked. A getter is refused, never run, and a value\n * read once cannot answer differently later.\n *\n * One convention holds throughout: `undefined` means absent, or present but\n * unreadable -- and in that case already reported. Every function here\n * handed `undefined` returns `undefined` and says nothing, so a missing or\n * unreadable value is reported once, where it is, and not again by every\n * check that wanted it.\n *\n * And one more: no message and no path grows with what a document holds.\n * A string is quoted to 40 characters, and a property name longer than any\n * the format has is refused before a path is built from it.\n */\nimport type { Width } from './components.js'\nimport type { ReportError, ReportErrorCode } from './errors.js'\nimport { MAX_ERRORS, MAX_FONT_SIZE, MAX_KEY_LENGTH, MAX_LENGTH_PT, MIN_FONT_SIZE } from './limits.js'\nimport { at } from './pointer.js'\nimport { isFieldKey, isIdentifier } from './syntax.js'\nimport { roundPt } from './units.js'\n\n/** The errors one validation has found, bounded, and the components they can be attributed to. */\nexport class Findings {\n readonly #errors: ReportError[] = []\n readonly #components = new Map<string, string>()\n #overflowed = false\n\n report(path: string, code: ReportErrorCode, message: string): void {\n if (this.#errors.length < MAX_ERRORS) this.#errors.push({ path, code, message })\n else this.#overflowed = true\n }\n\n /** Records that the component at `path` has `id`, so that errors under it name it. */\n component(path: string, id: string): void {\n this.#components.set(path, id)\n }\n\n /** The errors in the order found, each naming the innermost component it is inside, and a last one when more were found than listed. */\n errors(): ReportError[] {\n const errors = this.#errors.map((error) => {\n const componentId = this.#owner(error.path)\n return componentId === undefined ? error : { ...error, componentId }\n })\n if (this.#overflowed) {\n errors.push({ path: '', code: 'too-many-errors', message: `more than ${MAX_ERRORS} errors were found; the first ${MAX_ERRORS} are listed` })\n }\n return errors\n }\n\n /** The id of the component whose path is the longest prefix of `path`. */\n #owner(path: string): string | undefined {\n for (let prefix = path; ; prefix = prefix.slice(0, prefix.lastIndexOf('/'))) {\n const id = this.#components.get(prefix)\n if (id !== undefined || prefix === '') return id\n }\n }\n}\n\n/** A value as a message can quote it: strings shortened and quoted, objects named, never stringified. */\nexport function describe(value: unknown): string {\n if (value === null) return 'null'\n if (typeof value === 'string') return `the string ${quote(value)}`\n if (typeof value === 'number' || typeof value === 'boolean') return `${typeof value} ${String(value)}`\n if (typeof value !== 'object') return `a ${typeof value}`\n try {\n return Array.isArray(value) ? 'an array' : 'an object'\n } catch {\n return 'an object that cannot be read'\n }\n}\n\n/** A string as a message quotes it: at most 40 characters of it. Every string from a document passes through here before a message holds it. */\nexport function quote(text: string): string {\n return JSON.stringify(text.length > 40 ? `${text.slice(0, 40)}...` : text)\n}\n\n/** Allowed values as a message lists them. */\nexport function list(values: readonly (string | boolean)[]): string {\n return values.map((value) => (typeof value === 'string' ? `\"${value}\"` : String(value))).join(', ')\n}\n\n/** A property's value as JSON data, or undefined after reporting why it is not. */\nfunction readProperty(f: Findings, owner: object, key: string | number, path: string): unknown {\n const descriptor = Object.getOwnPropertyDescriptor(owner, key)\n if (descriptor === undefined) {\n f.report(path, 'not-json', 'a hole in an array is not JSON data')\n return undefined\n }\n if (!('value' in descriptor)) {\n f.report(path, 'not-json', 'a getter or setter is not JSON data, and is not run')\n return undefined\n }\n const value: unknown = descriptor.value\n switch (typeof value) {\n case 'string':\n case 'boolean':\n case 'object':\n return value\n case 'number':\n if (Number.isFinite(value)) return value + 0 // -0 is read as 0, as JSON writes it\n f.report(path, 'not-json', 'a number that is not finite is not JSON data')\n return undefined\n default:\n f.report(path, 'not-json', `${describe(value)} is not JSON data`)\n return undefined\n }\n}\n\n/** A plain object's own enumerable data properties, copied, or undefined after reporting why not. */\nexport function readObject(f: Findings, value: unknown, path: string): Record<string, unknown> | undefined {\n if (value === undefined) return undefined\n try {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n f.report(path, 'wrong-type', `expected an object, found ${describe(value)}`)\n return undefined\n }\n // A plain object's prototype is Object.prototype, from this realm or\n // another, or null. Anything else -- a Map, a Date, a class -- would be\n // read as an object of its own properties, which is not what it holds.\n const prototype: unknown = Object.getPrototypeOf(value)\n if (prototype !== null && Object.getPrototypeOf(prototype) !== null) {\n f.report(path, 'wrong-type', 'expected a plain object, found an instance of a class')\n return undefined\n }\n const copy: Record<string, unknown> = Object.create(null) as Record<string, unknown>\n for (const key of Object.keys(value)) {\n // Reported where its object is and left out of the copy, so no path is\n // built from it; the error alone keeps the report from being valid.\n if (key.length > MAX_KEY_LENGTH)\n f.report(path, 'too-long', `holds a property name ${key.length} characters long, ${quote(key)}; no name in the format is longer than ${MAX_KEY_LENGTH}`)\n else copy[key] = readProperty(f, value, key, at(path, key))\n }\n return copy\n } catch {\n f.report(path, 'not-json', 'this value threw when it was read')\n return undefined\n }\n}\n\n/**\n * An array's elements, copied, or undefined after reporting why not. Its\n * length is read once, as a number, and checked before any element is\n * read: a proxy's length that answered differently when asked again would\n * otherwise pass the bound and then be read past it.\n */\nexport function readArray(f: Findings, value: unknown, path: string, max: number): unknown[] | undefined {\n if (value === undefined) return undefined\n try {\n if (!Array.isArray(value)) {\n f.report(path, 'wrong-type', `expected an array, found ${describe(value)}`)\n return undefined\n }\n const length: unknown = value.length\n if (typeof length !== 'number' || !Number.isSafeInteger(length) || length < 0) {\n f.report(path, 'not-json', 'an array whose length is not a whole number is not JSON data')\n return undefined\n }\n if (length > max) {\n f.report(path, 'too-many', `holds ${length} entries; at most ${max} are allowed`)\n return undefined\n }\n const copy: unknown[] = []\n for (let index = 0; index < length; index += 1) copy.push(readProperty(f, value, index, at(path, index)))\n return copy\n } catch {\n f.report(path, 'not-json', 'this value threw when it was read')\n return undefined\n }\n}\n\n/** An array with at least `min` and at most `max` elements. One with too few is still returned, so its elements are checked too. */\nexport function readList(f: Findings, value: unknown, path: string, min: number, max: number): unknown[] | undefined {\n const items = readArray(f, value, path, max)\n if (items !== undefined && items.length < min) f.report(path, 'too-few', `holds ${items.length} entries; at least ${min} are needed`)\n return items\n}\n\n/** Reports every property a shape does not have, and every required one that is absent. */\nexport function strictKeys(f: Findings, o: Record<string, unknown>, path: string, required: readonly string[], optional: readonly string[] = []): void {\n for (const key of Object.keys(o)) {\n if (!required.includes(key) && !optional.includes(key)) {\n f.report(at(path, key), 'unknown-property', `${quote(key)} is not a property this version of the format has here`)\n }\n }\n for (const key of required) if (!Object.hasOwn(o, key)) f.report(at(path, key), 'missing-property', `${quote(key)} is required here`)\n}\n\n/** An object with exactly the properties a shape allows. */\nexport function shape(\n f: Findings,\n value: unknown,\n path: string,\n required: readonly string[],\n optional: readonly string[] = [],\n): Record<string, unknown> | undefined {\n const o = readObject(f, value, path)\n if (o !== undefined) strictKeys(f, o, path, required, optional)\n return o\n}\n\n/** The `kind` of an object that has one, among `kinds`. */\nexport function kindOf<K extends string>(f: Findings, o: Record<string, unknown>, path: string, kinds: readonly K[]): K | undefined {\n const where = at(path, 'kind')\n if (!Object.hasOwn(o, 'kind')) {\n f.report(where, 'missing-property', `\"kind\" is required: it says which of ${list(kinds)} this is`)\n return undefined\n }\n const kind = reference(f, o.kind, where)\n if (kind === undefined) return undefined\n if ((kinds as readonly string[]).includes(kind)) return kind as K\n f.report(where, 'unknown-kind', `${quote(kind)} is not a kind this version knows; it knows ${list(kinds)}`)\n return undefined\n}\n\nexport function text(f: Findings, value: unknown, path: string, max: number): string | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'string') {\n f.report(path, 'wrong-type', `expected a string, found ${describe(value)}`)\n return undefined\n }\n if (value.length > max) {\n f.report(path, 'too-long', `is ${value.length} characters long; at most ${max} are allowed`)\n return undefined\n }\n return value\n}\n\n/** A string naming something declared elsewhere; whether it is declared is the caller's question. */\nexport function reference(f: Findings, value: unknown, path: string): string | undefined {\n return text(f, value, path, Number.POSITIVE_INFINITY)\n}\n\nexport function flag(f: Findings, value: unknown, path: string): boolean | undefined {\n if (value === undefined || typeof value === 'boolean') return value\n f.report(path, 'wrong-type', `expected true or false, found ${describe(value)}`)\n return undefined\n}\n\nexport function oneOf<const T extends string | boolean>(f: Findings, value: unknown, path: string, allowed: readonly T[]): T | undefined {\n if (value === undefined) return undefined\n if ((allowed as readonly unknown[]).includes(value)) return value as T\n f.report(path, 'not-one-of', `expected ${allowed.length === 1 ? '' : 'one of '}${list(allowed)}, found ${describe(value)}`)\n return undefined\n}\n\n/** A finite number from `min` to `max`. */\nexport function number(f: Findings, value: unknown, path: string, min: number, max: number): number | undefined {\n if (value === undefined) return undefined\n if (typeof value !== 'number') {\n f.report(path, 'wrong-type', `expected a number, found ${describe(value)}`)\n return undefined\n }\n if (value < min || value > max) {\n f.report(path, 'out-of-range', `${value} is outside the range allowed here, ${min} to ${max}`)\n return undefined\n }\n return value\n}\n\n/** A whole number from `min` to `max`. */\nexport function integer(f: Findings, value: unknown, path: string, min: number, max: number): number | undefined {\n if (typeof value === 'number' && !Number.isInteger(value)) {\n f.report(path, 'not-an-integer', `${value} is not a whole number`)\n return undefined\n }\n return number(f, value, path, min, max)\n}\n\n/**\n * A number of points from `min` to `max`, on the hundredth of a point that\n * lengths are stored to. A finer one is refused rather than rounded: two\n * spellings of one stored length would hash differently, and a length that\n * rounds to 0 would pass as more than 0.\n */\nfunction measure(f: Findings, value: unknown, path: string, min: number, max: number): number | undefined {\n const length = number(f, value, path, min, max)\n if (length === undefined || roundPt(length) === length) return length\n f.report(path, 'too-precise', `${length} has more than two decimal places; lengths are stored to the hundredth of a point`)\n return undefined\n}\n\n/** A length in points: from 0, or more than 0, up to MAX_LENGTH_PT. */\nexport function points(f: Findings, value: unknown, path: string, least: 'zero' | 'positive'): number | undefined {\n const length = measure(f, value, path, 0, MAX_LENGTH_PT)\n if (length === 0 && least === 'positive') {\n f.report(path, 'out-of-range', 'a length of 0 points draws nothing; it must be more than 0')\n return undefined\n }\n return length\n}\n\n/** A font size in points, from MIN_FONT_SIZE to MAX_FONT_SIZE. */\nexport function fontSize(f: Findings, value: unknown, path: string): number | undefined {\n return measure(f, value, path, MIN_FONT_SIZE, MAX_FONT_SIZE)\n}\n\n/** A width: a length in points, or \"fill\" for a share of what fixed widths leave. */\nexport function width(f: Findings, value: unknown, path: string): Width | undefined {\n if (value === 'fill') return value\n if (typeof value === 'string') {\n f.report(path, 'wrong-type', `expected a width in points or \"fill\", found ${describe(value)}`)\n return undefined\n }\n return points(f, value, path, 'positive')\n}\n\n/** A string matching `pattern`; `expected` says in words what it should look like. */\nexport function matches(f: Findings, value: unknown, path: string, pattern: RegExp, code: ReportErrorCode, expected: string): string | undefined {\n const string = reference(f, value, path)\n if (string === undefined || pattern.test(string)) return string\n f.report(path, code, `expected ${expected}, found ${quote(string)}`)\n return undefined\n}\n\nconst IDENTIFIER_RULE = 'lower-case letters, digits and hyphens, starting with a letter, at most 64 characters'\n\nexport function identifier(f: Findings, value: unknown, path: string): string | undefined {\n const id = reference(f, value, path)\n if (id === undefined || isIdentifier(id)) return id\n f.report(path, 'invalid-id', `${quote(id)} is not an identifier: ${IDENTIFIER_RULE}`)\n return undefined\n}\n\nconst FIELD_KEY_RULE = 'letters, digits and underscores, starting with a letter or an underscore, at most 64 characters, as a formancy form writes a field key'\n\n/** A name an expression reads: a field, a parameter or an aggregate. */\nexport function fieldKey(f: Findings, value: unknown, path: string): string | undefined {\n const key = reference(f, value, path)\n if (key === undefined || isFieldKey(key)) return key\n f.report(path, 'invalid-id', `${quote(key)} is not a field key: ${FIELD_KEY_RULE}`)\n return undefined\n}\n\n/** Every value, or undefined when any of them is. */\nexport function all<T>(values: readonly (T | undefined)[]): T[] | undefined {\n const present: T[] = []\n for (const value of values) {\n if (value === undefined) return undefined\n present.push(value)\n }\n return present\n}\n\n/** `{ [key]: value }`, or `{}` when value is absent: an optional property spread into a result. */\nexport function optional<K extends string, V>(key: K, value: V | undefined): { readonly [P in K]?: V } {\n return (value === undefined ? {} : { [key]: value }) as { readonly [P in K]?: V }\n}\n","/**\n * What a Formancy Report definition is, before anything about what it holds.\n *\n * A report is its own document, not a formancy form with pages added: it has\n * its own version line, independent of formancy's `specVersion`, of Formancy\n * Data's generated form spec and bindings versions, and of this package's npm\n * version. Package versions alone cannot say whether two documents are\n * compatible; this can.\n *\n * A message here quotes what the document holds, shortened: a version string\n * is the document's to choose, and a message that echoed it whole would grow\n * with it.\n */\nimport { quote } from './check.js'\n\n/**\n * The format's name. A canonical hash of a report is taken over an envelope\n * that names it, so a report and a form whose JSON bodies happen to be equal\n * can never share a hash.\n */\nexport const REPORT_FORMAT = 'formancy-report'\n\n/**\n * The version of the report definition this package reads. A string of\n * digits, as formancy writes `specVersion`.\n *\n * Version 0 is the draft: the format is being designed, and no document\n * written under it is promised to be read by a later release. The release\n * that first freezes the format makes it 1, and from then a frozen version\n * keeps its meaning.\n */\nexport const REPORT_SPEC_VERSION = '0'\n\n/** Whether a document is a report of the version this package reads, and why not when it is not. */\nexport type SpecVersionCheck = { readonly ok: true } | { readonly ok: false; readonly code: 'not-a-report' | 'unsupported-version'; readonly message: string }\n\n/** The field that holds a value, when `value` is an object that has it. */\nfunction field(value: unknown, name: string): unknown {\n return typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>)[name] : undefined\n}\n\n/**\n * Whether `document` is a report definition of `REPORT_SPEC_VERSION`.\n *\n * Refuses rather than guesses. A document with no `reportSpecVersion` string\n * is not a report, and a formancy form -- the document most likely to arrive\n * here by mistake -- is named as one. A report of another version is refused,\n * never partly read: a field this version does not know could be the one that\n * hides a row or changes a total.\n */\nexport function checkSpecVersion(document: unknown): SpecVersionCheck {\n const version = field(document, 'reportSpecVersion')\n if (typeof version !== 'string') {\n const form = field(document, 'specVersion')\n const message =\n typeof form === 'string'\n ? `this is a formancy form (specVersion ${quote(form)}), not a report definition`\n : 'this is not a report definition: it has no reportSpecVersion string'\n return { ok: false, code: 'not-a-report', message }\n }\n if (version !== REPORT_SPEC_VERSION) {\n return {\n ok: false,\n code: 'unsupported-version',\n message: `reportSpecVersion ${quote(version)} is not one this package reads; it reads ${quote(REPORT_SPEC_VERSION)}`,\n }\n }\n return { ok: true }\n}\n","/**\n * The page: the sizes and orientations the format names, a report's page\n * settings, and their geometry -- the size of each page, the area its\n * margins leave, and the largest square that area holds. A size is named\n * beside its dimensions, so the two are added together. The validator's\n * margin check, the builder's rulers and the renderer read the same\n * numbers from here.\n */\nimport { mmToPt, POINTS_PER_INCH, roundPt } from './units.js'\n\nexport const PAGE_SIZE_NAMES = ['A4', 'Letter'] as const\nexport type PageSizeName = (typeof PAGE_SIZE_NAMES)[number]\n\nexport const ORIENTATIONS = ['portrait', 'landscape'] as const\nexport type Orientation = (typeof ORIENTATIONS)[number]\n\nexport interface Margins {\n readonly top: number\n readonly right: number\n readonly bottom: number\n readonly left: number\n}\n\nexport interface PageSettings {\n readonly size: PageSizeName\n readonly orientation: Orientation\n readonly margins: Margins\n}\n\nexport interface PageDimensions {\n readonly width: number\n readonly height: number\n}\n\n/**\n * Portrait sizes in points. A4 is ISO 216's 210 x 297 mm, converted and\n * rounded like any other length (595.28 x 841.89, the values PDF engines\n * use); Letter is 8.5 x 11 inches, exactly 612 x 792.\n */\nexport const PAGE_SIZES: { readonly [S in PageSizeName]: PageDimensions } = {\n A4: { width: mmToPt(210), height: mmToPt(297) },\n Letter: { width: 8.5 * POINTS_PER_INCH, height: 11 * POINTS_PER_INCH },\n}\n\n/** The page's width and height as oriented: landscape swaps the sides. */\nexport function pageDimensions(page: { readonly size: PageSizeName; readonly orientation: Orientation }): PageDimensions {\n const { width, height } = PAGE_SIZES[page.size]\n return page.orientation === 'portrait' ? { width, height } : { width: height, height: width }\n}\n\n/** What the margins leave of the oriented page, to the hundredth of a point that lengths are stored at. */\nexport function printableArea(page: PageSettings): PageDimensions {\n const { width, height } = pageDimensions(page)\n const { top, right, bottom, left } = page.margins\n return { width: roundPt(width - left - right), height: roundPt(height - top - bottom) }\n}\n\n/**\n * The largest square `area` holds: the length of its shorter side, and\n * which side that is, the width when the two are equal. The validator\n * measures a QR code's square against it and refuses one that overruns it\n * on that side; the builders size a new code by it and name it as the room\n * a refused size lacks.\n */\nexport function squareRoom(area: PageDimensions): { readonly side: 'width' | 'height'; readonly length: number } {\n return area.height < area.width ? { side: 'height', length: area.height } : { side: 'width', length: area.width }\n}\n","/**\n * Print styles: the report's own serialisable tokens for how its text\n * prints, never CSS -- the font families and alignments the format names,\n * a style, and a style applied when a condition holds.\n */\nimport type { Expression } from './values.js'\n\nexport const FONT_FAMILIES = ['sans', 'serif', 'mono'] as const\nexport type FontFamily = (typeof FONT_FAMILIES)[number]\n\nexport const ALIGNMENTS = ['left', 'center', 'right'] as const\nexport type Alignment = (typeof ALIGNMENTS)[number]\n\n/**\n * A print style: serialisable report tokens, never CSS. Nothing from the\n * editor's or the host's stylesheet reaches a printed page; what prints is\n * what these say (plan 11.4). An absent property is the renderer's default.\n */\nexport interface PrintStyle {\n readonly id: string\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/** A style applied when a condition holds: each rule that holds applies its style over the base one, in order, a later rule's property winning. */\nexport interface StyleRule {\n readonly when: Expression\n /** A `PrintStyle` id. */\n readonly style: string\n}\n","/**\n * The data a report reads: the datasets it names by the contract each\n * promises, the one way the format refers to one of their fields, and the\n * parameters a person supplies before it renders. The template names them;\n * the deployment supplies what each resolves to.\n */\n\nexport const FIELD_TYPES = ['string', 'integer', 'decimal', 'boolean', 'date', 'datetime', 'instant', 'image'] as const\nexport type FieldType = (typeof FIELD_TYPES)[number]\n\n/**\n * How a choice's answer prints, where it does not print its label (0042):\n * the value the submission stores. Its label -- the one its option has in\n * the form version that collected it, in the locale the render names, the\n * report's own when it names none (0063) -- is what it prints when `read`\n * is left out, and has no spelling of its own, so that one binding has\n * one hash.\n */\nexport const FORM_READS = ['value'] as const\nexport type FormRead = (typeof FORM_READS)[number]\n\n/**\n * Where a formancy form's submission holds a field's answer (0042): its\n * data path in the dataset's scope, as formancy writes one -- field keys\n * joined by dots, a group's child `address.street`; a page scopes nothing\n * and has no key in it. The header's scope and one row per submission's is\n * the submission's; a repeater's rows' is the row's.\n */\nexport interface FieldFormBinding {\n readonly path: string\n /** A matrix row's value, whose chosen column the field prints, or a selectboxes option's value, whether it is ticked. */\n readonly member?: string\n /** How a choice prints -- a select, a radio, a matrix row's column: `value`, its stored value; absent, its label. Only a string field reads a choice. */\n readonly read?: FormRead\n /**\n * What a review decided for a form version (0048), keyed by the\n * version's `schemaHash`: where that version holds the field -- `path`\n * itself, for the version a followed rename moved `path` to -- or that\n * the report prints nothing of it from that version. Every version not\n * named is read at `path`.\n */\n readonly overrides?: Readonly<Record<string, FieldFormOverride>>\n}\n\n/**\n * How one form version's submissions fill a field, where it is not as the\n * binding says (0048): from another data path in the same scope, the\n * member and the reading kept; or not at all, null in every submission of\n * that version, which only a field that may be null takes.\n */\nexport type FieldFormOverride = { readonly path: string } | { readonly omit: true }\n\n/**\n * What of a formancy form's submissions a dataset reads (0042): the header\n * one submission's answers; the detail one of its repeater's rows, or one\n * row for each submission of a report of many, which has no header. Which\n * version of which form is the render's input, never the report's: each\n * submission is read against the version that collected it.\n */\nexport const DATASET_FORM_KINDS = ['submission', 'repeater', 'submissions'] as const\nexport type DatasetFormKind = (typeof DATASET_FORM_KINDS)[number]\n\nexport type DatasetFormBinding =\n | { readonly kind: 'submission' }\n | {\n readonly kind: 'repeater'\n /** The repeater's data path in the submission's scope. */\n readonly repeater: string\n /** Where a form version holds the rows, keyed by its `schemaHash`, as a review decided (0048) -- `repeater` itself, for the version a followed rename moved it to; its rows' fields are read at their own paths in them. Every version not named reads `repeater`. */\n readonly overrides?: Readonly<Record<string, { readonly repeater: string }>>\n }\n | { readonly kind: 'submissions' }\n\n/**\n * A field a dataset contract promises.\n *\n * Values of exact types arrive as strings, never as JavaScript numbers. An\n * `image` field's value is an approved asset -- its id and its `sha256:`\n * digest -- which the host resolves to bytes, never an address: a photo or\n * a signature captured with a form arrives this way, and prints only as an\n * image. A field that is not nullable never holds null; one that is prints\n * null as nothing. A field the data lacks altogether is the runtime's error,\n * never an empty string.\n */\nexport interface FieldContract {\n /** A field key: what an expression reads it as, `header.<id>` or `row.<id>`. */\n readonly id: string\n readonly type: FieldType\n readonly label: string\n readonly nullable: boolean\n /** Digits after the decimal point; decimal fields only. */\n readonly scale?: number\n /** Where a formancy form's submission holds it, in a dataset read from one; absent in any other. */\n readonly form?: FieldFormBinding\n}\n\n/**\n * A dataset the report reads, by the logical id a deployment's binding set\n * maps to a provider. The fields are the contract the template was written\n * against, so the template itself records which revision of the contract it\n * expects.\n */\nexport interface DatasetContract {\n readonly id: string\n readonly fields: readonly FieldContract[]\n /** What of a formancy form's submissions it reads; absent, the host hands its data over as it captured it. */\n readonly form?: DatasetFormBinding\n}\n\n/** The two datasets a version-0 report can read: one row of header data, and the one primary detail dataset. */\nexport const DATASET_ROLES = ['header', 'detail'] as const\nexport type DatasetRole = (typeof DATASET_ROLES)[number]\n\nexport interface Datasets {\n readonly header?: DatasetContract\n readonly detail?: DatasetContract\n}\n\n/** A field of the header or the detail dataset: the one way the format refers to one. */\nexport interface FieldRef {\n readonly dataset: DatasetRole\n readonly field: string\n}\n\nexport const PARAMETER_TYPES = ['string', 'integer', 'decimal', 'boolean', 'date'] as const\nexport type ParameterType = (typeof PARAMETER_TYPES)[number]\n\n/** A value a person supplies before rendering, on a formancy form whose field key is the parameter's id (plan 12.4). */\nexport interface ParameterDef {\n /** A field key: what an expression reads it as, `params.<id>`. */\n readonly id: string\n readonly type: ParameterType\n readonly label: string\n readonly required: boolean\n /** A boolean for a boolean parameter; for every other type, the exact value as a string. */\n readonly default?: string | boolean\n}\n","/**\n * The assets a report shows or prints in, each named by its id and pinned\n * by its digest; the bytes are the deployment's. What a PNG's or a JPEG's\n * bytes may be, `image-header.ts` reads, an SVG's, `svg.ts`, and a font's,\n * `font.ts` (0040, 0043).\n */\n\n/** An image asset's bytes are a PNG, a JPEG, or an SVG in the form report-spec's `cleanSvg` writes (0030). */\nexport const ASSET_MEDIA_TYPES = ['image/png', 'image/jpeg', 'image/svg+xml'] as const\nexport type AssetMediaType = (typeof ASSET_MEDIA_TYPES)[number]\n\n/**\n * A font asset's bytes are a TrueType font (`font/ttf`, RFC 8081), read by\n * `readFont` (0040). An OpenType CFF font (`font/otf`) is not admitted:\n * `readFont` reads no CFF outlines and refuses `OTTO` bytes, and the\n * e-invoice gate has not proved a CFF face embeds in a PDF/A-3b (FT-Q15,\n * 0043).\n */\nexport const FONT_MEDIA_TYPES = ['font/ttf'] as const\nexport type FontMediaType = (typeof FONT_MEDIA_TYPES)[number]\n\n/** Every media type an asset may declare: an image's, or a font's. */\nexport const ASSET_AND_FONT_MEDIA_TYPES = [...ASSET_MEDIA_TYPES, ...FONT_MEDIA_TYPES] as const\nexport type AnyAssetMediaType = AssetMediaType | FontMediaType\n\n/** Whether `mediaType` is a font's, not an image's. */\nexport function isFontMediaType(mediaType: string): mediaType is FontMediaType {\n return (FONT_MEDIA_TYPES as readonly string[]).includes(mediaType)\n}\n\n/**\n * An approved asset, named by id and pinned by digest. The bytes never live\n * in the definition, and rendering never follows a mutable \"latest\" asset\n * (plan 17): a new logo, or a new typeface, is a new digest and a new\n * template release.\n */\nexport interface AssetRef {\n readonly id: string\n readonly mediaType: AnyAssetMediaType\n /** `sha256:` and 64 lower-case hex digits. */\n readonly digest: string\n}\n","/**\n * How a report maps its three font tokens to the fonts a host approved\n * (0043). A print style names a token -- `sans`, `serif` or `mono`\n * ([styles.ts](styles.js)) -- and this says which approved font assets each\n * token prints in, face by face. A token a report leaves unmapped prints in\n * the renderer's own face, as it did before a report could name a host's\n * font: `sans` is the renderer's Roboto, and `serif` and `mono` are refused\n * at print, exactly as today.\n *\n * A face is an approved asset, named by id and pinned by digest in\n * `assets`, whose media type is a font's (`FONT_MEDIA_TYPES`); the host's\n * lookup hands over its bytes, which report-spec's `readFont` reads and the\n * renderer embeds (0040). The mapping is part of the definition, so the\n * report's hash covers which font a token prints in: a firm swaps its\n * typeface as it swaps its logo, with a new digest and a new template\n * version, and \"the same report renders the same PDF\" survives (0007).\n *\n * Nothing here holds a font's bytes: a face is a reference, resolved by the\n * deployment, as every asset is.\n */\nimport type { FontFamily } from './styles.js'\n\n/**\n * The faces of one family a report may map, as pdfmake draws text in each\n * weight and slant: `normal` always, and `bold`, `italic` and `boldItalic`\n * where the report prints text in them. A face is never synthesised from\n * another -- pdfmake's own faux bold and oblique are a substitution nobody\n * sees until the PDF is read (plan 20) -- so a report that prints bold text\n * in a mapped family maps that family's bold face, or the renderer refuses\n * it.\n */\nexport const FONT_FACE_KEYS = ['normal', 'bold', 'italic', 'boldItalic'] as const\nexport type FontFaceKey = (typeof FONT_FACE_KEYS)[number]\n\n/** The approved font assets a family's faces print in, each named by its asset id; `normal` is required, the rest are mapped where the report prints them. */\nexport interface FontFaces {\n readonly normal: string\n readonly bold?: string\n readonly italic?: string\n readonly boldItalic?: string\n}\n\n/** A report's font map: the token-to-faces mapping for whichever of the three families it maps. Absent, or a token left out, the renderer prints that token in its own face. */\nexport type FontMap = { readonly [F in FontFamily]?: FontFaces }\n\n/** The face a run of text in this weight and slant prints in. */\nexport function faceKey(bold: boolean, italic: boolean): FontFaceKey {\n return bold ? (italic ? 'boldItalic' : 'bold') : italic ? 'italic' : 'normal'\n}\n","/**\n * The characters a report prints, by code point (0043, FT-Q16).\n *\n * pdfmake lays text out left to right and reorders nothing, and the\n * renderer removes a host face's layout tables before it embeds it\n * (report-render-pdf's `strip-layout.ts`), so fontkit substitutes and\n * positions nothing at print either: each character prints as the glyph\n * its face maps it to. That prints Latin, Greek and Cyrillic, and the\n * punctuation, symbols and combining marks written with them, which the\n * corpus proves on the PDF. It does not print a right-to-left script, a\n * script whose letters join or reorder, or CJK, and nothing here has proved\n * any other. So the list is of what prints, not of what is refused: a\n * character prints only where it lies in one of `PRINTED_BLOCKS` and is not\n * one of `BIDI_CONTROLS`, and every other is refused, in any face, Roboto's\n * included, until a fixture proves its script.\n *\n * The bounds are Unicode's blocks, read from `Blocks.txt` 18.0.0, and the\n * controls are its `PropList.txt`'s Bidi_Control; 0043 gives both files'\n * addresses and digests. Seven entries take part of a block and say so in\n * their names: Spacing Modifier Letters and Greek and Coptic each in two,\n * around the Bopomofo tone marks and the Coptic letters they hold; the\n * Latin ligatures of Alphabetic Presentation Forms, whose rest is Armenian\n * and Hebrew; the byte-order mark alone of Arabic Presentation Forms-B; and\n * the two replacement characters of Specials.\n * `font-scripts.test.ts` holds each entry's bounds and order, and\n * report-render-pdf's `scripts.test.ts` every character of every entry to\n * the script fontkit's own Unicode data gives it; that the bounds are\n * Blocks.txt's is review-held.\n */\n\n/** The Unicode version the blocks and the controls were read from. */\nexport const UNICODE_VERSION = '18.0.0'\n\n/** A run of code points that prints: a block, or the named part of one, with its inclusive bounds. */\nexport interface PrintedBlock {\n readonly block: string\n readonly from: number\n readonly to: number\n}\n\n/** What prints, in code-point order, every entry in the Basic Multilingual Plane. */\nexport const PRINTED_BLOCKS: readonly PrintedBlock[] = [\n // Latin, Greek and Cyrillic, and the marks and modifiers written with them.\n { block: 'Basic Latin', from: 0x0000, to: 0x007f },\n { block: 'Latin-1 Supplement', from: 0x0080, to: 0x00ff },\n { block: 'Latin Extended-A', from: 0x0100, to: 0x017f },\n { block: 'Latin Extended-B', from: 0x0180, to: 0x024f },\n { block: 'IPA Extensions', from: 0x0250, to: 0x02af },\n { block: 'Spacing Modifier Letters (before the Bopomofo tone marks)', from: 0x02b0, to: 0x02e9 },\n { block: 'Spacing Modifier Letters (after the Bopomofo tone marks)', from: 0x02ec, to: 0x02ff },\n { block: 'Combining Diacritical Marks', from: 0x0300, to: 0x036f },\n { block: 'Greek and Coptic (before the Coptic letters)', from: 0x0370, to: 0x03e1 },\n { block: 'Greek and Coptic (after the Coptic letters)', from: 0x03f0, to: 0x03ff },\n { block: 'Cyrillic', from: 0x0400, to: 0x04ff },\n { block: 'Cyrillic Supplement', from: 0x0500, to: 0x052f },\n { block: 'Combining Diacritical Marks Extended', from: 0x1ab0, to: 0x1aff },\n { block: 'Cyrillic Extended-C', from: 0x1c80, to: 0x1c8f },\n { block: 'Phonetic Extensions', from: 0x1d00, to: 0x1d7f },\n { block: 'Phonetic Extensions Supplement', from: 0x1d80, to: 0x1dbf },\n { block: 'Combining Diacritical Marks Supplement', from: 0x1dc0, to: 0x1dff },\n { block: 'Latin Extended Additional', from: 0x1e00, to: 0x1eff },\n { block: 'Greek Extended', from: 0x1f00, to: 0x1fff },\n // Punctuation and symbols, none of a script of its own.\n { block: 'General Punctuation', from: 0x2000, to: 0x206f },\n { block: 'Superscripts and Subscripts', from: 0x2070, to: 0x209f },\n { block: 'Currency Symbols', from: 0x20a0, to: 0x20cf },\n { block: 'Combining Diacritical Marks for Symbols', from: 0x20d0, to: 0x20ff },\n { block: 'Letterlike Symbols', from: 0x2100, to: 0x214f },\n { block: 'Number Forms', from: 0x2150, to: 0x218f },\n { block: 'Arrows', from: 0x2190, to: 0x21ff },\n { block: 'Mathematical Operators', from: 0x2200, to: 0x22ff },\n { block: 'Miscellaneous Technical', from: 0x2300, to: 0x23ff },\n { block: 'Control Pictures', from: 0x2400, to: 0x243f },\n { block: 'Optical Character Recognition', from: 0x2440, to: 0x245f },\n { block: 'Enclosed Alphanumerics', from: 0x2460, to: 0x24ff },\n { block: 'Box Drawing', from: 0x2500, to: 0x257f },\n { block: 'Block Elements', from: 0x2580, to: 0x259f },\n { block: 'Geometric Shapes', from: 0x25a0, to: 0x25ff },\n { block: 'Miscellaneous Symbols', from: 0x2600, to: 0x26ff },\n { block: 'Dingbats', from: 0x2700, to: 0x27bf },\n { block: 'Miscellaneous Mathematical Symbols-A', from: 0x27c0, to: 0x27ef },\n { block: 'Supplemental Arrows-A', from: 0x27f0, to: 0x27ff },\n { block: 'Supplemental Arrows-B', from: 0x2900, to: 0x297f },\n { block: 'Miscellaneous Mathematical Symbols-B', from: 0x2980, to: 0x29ff },\n { block: 'Supplemental Mathematical Operators', from: 0x2a00, to: 0x2aff },\n { block: 'Miscellaneous Symbols and Arrows', from: 0x2b00, to: 0x2bff },\n // Latin and Cyrillic past the symbols, and the punctuation beside them.\n { block: 'Latin Extended-C', from: 0x2c60, to: 0x2c7f },\n { block: 'Cyrillic Extended-A', from: 0x2de0, to: 0x2dff },\n { block: 'Supplemental Punctuation', from: 0x2e00, to: 0x2e7f },\n { block: 'Cyrillic Extended-B', from: 0xa640, to: 0xa69f },\n { block: 'Modifier Tone Letters', from: 0xa700, to: 0xa71f },\n { block: 'Latin Extended-D', from: 0xa720, to: 0xa7ff },\n { block: 'Latin Extended-E', from: 0xab30, to: 0xab6f },\n // A face's own glyphs, and the parts of three blocks that print alone.\n { block: 'Private Use Area', from: 0xe000, to: 0xf8ff },\n { block: 'Alphabetic Presentation Forms (the Latin ligatures)', from: 0xfb00, to: 0xfb06 },\n { block: 'Combining Half Marks', from: 0xfe20, to: 0xfe2f },\n { block: 'Arabic Presentation Forms-B (the byte-order mark)', from: 0xfeff, to: 0xfeff },\n { block: 'Specials (the object replacement and replacement characters)', from: 0xfffc, to: 0xfffd },\n]\n\n/**\n * The bidirectional controls in the blocks that print, PropList.txt's\n * Bidi_Control but for U+061C, the Arabic letter mark, which is in no\n * printed block. pdfmake reorders nothing and fontkit draws a control as a\n * space, so each is refused rather than printed as one.\n */\nexport const BIDI_CONTROLS: ReadonlySet<number> = new Set([0x200e, 0x200f, 0x202a, 0x202b, 0x202c, 0x202d, 0x202e, 0x2066, 0x2067, 0x2068, 0x2069])\n\n/** Why a report does not print a character: its script is one nothing here prints, or it is a bidirectional control. */\nexport type CharacterRefusal = 'script' | 'bidi-control'\n\n/** Why `point` does not print, or undefined where it does; a binary search of `PRINTED_BLOCKS`. */\nexport function refusedCharacter(point: number): CharacterRefusal | undefined {\n let low = 0\n let high = PRINTED_BLOCKS.length - 1\n while (low <= high) {\n const middle = (low + high) >>> 1\n const entry = PRINTED_BLOCKS[middle]!\n if (point < entry.from) high = middle - 1\n else if (point > entry.to) low = middle + 1\n else return BIDI_CONTROLS.has(point) ? 'bidi-control' : undefined\n }\n return 'script'\n}\n","/**\n * Values: an expression, the scopes it is read in and the names it reads in\n * each; how a value is displayed; and the runs of text a paragraph, a table\n * cell, a footer cell and a group header are made of.\n */\nimport type { FieldRef } from './data.js'\n\n/** A CEL expression, compiled and bounded by the runtime, not here. */\nexport interface Expression {\n readonly cel: string\n}\n\n/**\n * Where a value is read, which decides what it can name (plan 15's \"current\n * row, group or report\"): `row` in a table cell and a table's row\n * condition, once per detail row; `group` in a group header or footer,\n * once per group; `table` in a table's total rows, once per table (0062);\n * `report` everywhere else.\n */\nexport const VALUE_SCOPES = ['report', 'table', 'group', 'row'] as const\nexport type ValueScope = (typeof VALUE_SCOPES)[number]\n\n/**\n * The names an expression reads in each scope, and nothing else: the\n * runtime binds exactly these. `params` maps parameter ids to values,\n * `header` the header dataset's fields, `row` the current detail row's,\n * `totals` each aggregate over every detail row, `table` each aggregate\n * over the rows the table prints (0062), and `group` each aggregate over\n * the current group's rows and, as `GROUP_KEY`, the value the group is\n * keyed by. A table's row condition is read in the row's scope, so it\n * reads neither `table` nor `group`, which are totalled and made from the\n * rows it selects.\n *\n * Whether an expression names only these is checked when the runtime\n * compiles it (plan 15's second level), not here: a second, partial CEL\n * parser would be a second place to disagree with the real one.\n */\nexport const EXPRESSION_NAMES: { readonly [S in ValueScope]: readonly string[] } = {\n report: ['params', 'header', 'totals'],\n table: ['params', 'header', 'totals', 'table'],\n group: ['params', 'header', 'totals', 'table', 'group'],\n row: ['params', 'header', 'totals', 'row'],\n}\n\n/**\n * The member of `group` that is the value the group is keyed by: in a group\n * header, `group.key` is the site a group of rows by site is for, of the\n * type of the field the group's own table groups by, and null for the\n * group of rows without one.\n * An aggregate may not take the name (`reserved-id`), so `group.key` never\n * reads one.\n */\nexport const GROUP_KEY = 'key'\n\nexport const FORMAT_KINDS = ['number', 'currency', 'date', 'text'] as const\nexport type FormatKind = (typeof FORMAT_KINDS)[number]\n\nexport const DATE_STYLES = ['short', 'medium', 'long'] as const\nexport type DateStyle = (typeof DATE_STYLES)[number]\n\nexport const TEXT_TRANSFORMS = ['upper', 'lower'] as const\nexport type TextTransform = (typeof TEXT_TRANSFORMS)[number]\n\nexport interface NumberFormat {\n readonly kind: 'number'\n readonly scale: number\n readonly grouping: boolean\n}\n\nexport const CURRENCY_SOURCE_KINDS = ['code', 'field', 'parameter'] as const\nexport type CurrencySourceKind = (typeof CURRENCY_SOURCE_KINDS)[number]\n\n/** Which currency an amount is in: a code the template fixes, or a string field or parameter that supplies one per report or per row. */\nexport type CurrencySource =\n | { readonly kind: 'code'; /** ISO 4217, upper case. */ readonly code: string }\n | { readonly kind: 'field'; readonly field: FieldRef }\n | { readonly kind: 'parameter'; readonly parameter: string }\n\nexport interface CurrencyFormat {\n readonly kind: 'currency'\n readonly currency: CurrencySource\n readonly scale: number\n}\nexport interface DateFormat {\n readonly kind: 'date'\n readonly style: DateStyle\n}\nexport interface TextFormat {\n readonly kind: 'text'\n readonly transform?: TextTransform\n}\n/** How a value is displayed. Display only: calculation precision is the runtime's, with its declared rounding. */\nexport type Format = NumberFormat | CurrencyFormat | DateFormat | TextFormat\n\n/**\n * Where a run of a paragraph stands against its line (0061): set below it,\n * a formula's digit, or above it, a unit's power, an exponent or a\n * footnote's mark, smaller than the paragraph's text and moved, in any\n * character its face draws. Absent, the run stands on the line. Only a\n * text component's runs take one; a page counter takes none, and what a\n * code encodes and a table's cells refuse one as `misplaced-baseline`.\n */\nexport const BASELINE_SHIFTS = ['subscript', 'superscript'] as const\nexport type BaselineShift = (typeof BASELINE_SHIFTS)[number]\n\nexport interface TextInline {\n readonly kind: 'text'\n readonly text: string\n readonly baseline?: BaselineShift\n}\nexport interface FieldInline {\n readonly kind: 'field'\n readonly field: FieldRef\n readonly format?: Format\n readonly baseline?: BaselineShift\n}\nexport interface ParameterInline {\n readonly kind: 'parameter'\n readonly parameter: string\n readonly format?: Format\n readonly baseline?: BaselineShift\n}\nexport interface ExpressionInline {\n readonly kind: 'expression'\n readonly expression: Expression\n readonly format?: Format\n readonly baseline?: BaselineShift\n}\n\n/**\n * Whose rows an aggregate is taken over where it is printed: the current\n * group's, the rows its table prints (0062), or every detail row.\n */\nexport const AGGREGATE_SCOPES = ['group', 'table', 'report'] as const\nexport type AggregateScope = (typeof AGGREGATE_SCOPES)[number]\n\nexport interface AggregateInline {\n readonly kind: 'aggregate'\n /** An `AggregateDef` id. */\n readonly aggregate: string\n readonly over: AggregateScope\n readonly format?: Format\n readonly baseline?: BaselineShift\n}\n/** The page's number, which the engine fills on each page; it takes no baseline. */\nexport interface PageNumberInline {\n readonly kind: 'pageNumber'\n}\n/** How many pages the document has, which the engine fills; it takes no baseline. */\nexport interface PageCountInline {\n readonly kind: 'pageCount'\n}\n\nexport const INLINE_KINDS = ['text', 'field', 'parameter', 'expression', 'aggregate', 'pageNumber', 'pageCount'] as const\nexport type InlineKind = (typeof INLINE_KINDS)[number]\n\n/**\n * A run of text: literal, bound, computed, totalled or a page counter. The\n * one shape for a paragraph's runs, a table cell, a footer cell and a group\n * header. Null prints as nothing.\n */\nexport type Inline = TextInline | FieldInline | ParameterInline | ExpressionInline | AggregateInline | PageNumberInline | PageCountInline\n","/**\n * The totals a report declares over its detail dataset: what each reads\n * from a row, its function and its declared rounding. The runtime computes\n * each exactly, once.\n */\nimport type { FieldRef } from './data.js'\nimport type { Expression } from './values.js'\n\n/** What an aggregate reads from each detail row: a detail field, or an expression over the row. */\nexport type RowValue = { readonly kind: 'field'; readonly field: FieldRef } | { readonly kind: 'expression'; readonly expression: Expression }\n\nexport const AGGREGATE_FUNCTIONS = ['sum', 'count', 'min', 'max', 'avg'] as const\nexport type AggregateFunction = (typeof AGGREGATE_FUNCTIONS)[number]\n\nexport const ROUNDING_MODES = ['half-away-from-zero', 'half-even'] as const\nexport type RoundingMode = (typeof ROUNDING_MODES)[number]\n\n/**\n * Declared rounding: an exact decimal is rounded once, by a named rule,\n * never by a float. To a multiple of `increment` when it is given -- '0.05'\n * for Swiss cash rounding -- and otherwise to `scale` places; ties go by\n * `mode` either way.\n */\nexport interface Rounding {\n readonly scale: number\n readonly mode: RoundingMode\n /** An exact decimal more than 0, with no more than `scale` places. */\n readonly increment?: string\n}\n\n/**\n * A total the report computes over the detail dataset, exactly, once, in\n * the runtime. Declared once and printed by id, over the current group in a\n * group header or footer and over every detail row anywhere else.\n *\n * - `count` without `of` counts rows; with it, the rows where it is not null.\n * - `sum` and `avg` take integers and decimals; `min` and `max` those and\n * the three temporal types. Each skips nulls.\n * - Over no values, `count` and `sum` are 0, and `min`, `max` and `avg` are\n * null, which prints as nothing.\n * - `avg` is rarely exact, so it declares its rounding.\n */\nexport interface AggregateDef {\n /** A field key: what an expression reads it as, `totals.<id>` or `group.<id>`. Never `GROUP_KEY`, which `group` holds already. */\n readonly id: string\n readonly fn: AggregateFunction\n /** Absent only for count. */\n readonly of?: RowValue\n readonly rounding?: Rounding\n}\n","/**\n * The components a region holds: what every one has, each kind, and the\n * kinds as one list and one union. The table, whose rows, groups and\n * totals change for reasons of their own, is `table.ts`'s; the EPC QR code\n * is `epc-qr-code.ts`'s.\n */\nimport type { ChartComponent } from './chart.js'\nimport type { FieldRef } from './data.js'\nimport type { EpcQrCodeComponent } from './epc-qr-code.js'\nimport type { StyleRule } from './styles.js'\nimport type { TableComponent } from './table.js'\nimport type { Expression, Inline } from './values.js'\n\n/** What every component has: a stable id, and optionally a condition and print styles. */\nexport interface ComponentBase {\n readonly id: string\n readonly visibleWhen?: Expression\n /** A `PrintStyle` id. */\n readonly style?: string\n readonly styleWhen?: readonly StyleRule[]\n}\n\nexport interface TextComponent extends ComponentBase {\n readonly kind: 'text'\n readonly content: readonly Inline[]\n /** Never the last block on a page when something follows it: a heading moves with what it heads. */\n readonly keepWithNext?: boolean\n}\n\nexport const IMAGE_FITS = ['contain', 'cover'] as const\nexport type ImageFit = (typeof IMAGE_FITS)[number]\n\nexport const IMAGE_SOURCE_KINDS = ['asset', 'field'] as const\nexport type ImageSourceKind = (typeof IMAGE_SOURCE_KINDS)[number]\n\n/** What an image shows: an asset the template pins, the same in every render, or an image field of the header dataset, one per render. */\nexport type ImageSource = { readonly kind: 'asset'; /** An `AssetRef` id. */ readonly asset: string } | { readonly kind: 'field'; readonly field: FieldRef }\n\n/** An image drawn in a box of fixed size; the width and the height bound it whatever its source holds. */\nexport interface ImageComponent extends ComponentBase {\n readonly kind: 'image'\n readonly source: ImageSource\n readonly width: number\n readonly height: number\n readonly fit: ImageFit\n}\n\n/**\n * How much of a QR code may be lost and its content still read: ISO/IEC\n * 18004's four levels, which restore about 7, 15, 25 and 30 % of the\n * codewords. A higher level holds less content in the same square.\n */\nexport const QR_ERROR_CORRECTION = ['L', 'M', 'Q', 'H'] as const\nexport type QrErrorCorrection = (typeof QR_ERROR_CORRECTION)[number]\n\n/**\n * A QR code of the text its content prints, drawn as a square of fixed\n * size. The content is read once, as a paragraph's in the same place is,\n * and resolved whole before there are pages: it never holds a page number\n * or count, in any region.\n */\nexport interface QrCodeComponent extends ComponentBase {\n readonly kind: 'qrCode'\n readonly content: readonly Inline[]\n /** The side of the square in points, the quiet zone around the modules included. */\n readonly size: number\n readonly errorCorrection: QrErrorCorrection\n}\n\nexport interface LineComponent extends ComponentBase {\n readonly kind: 'line'\n readonly thickness: number\n readonly color?: string\n}\n\nexport interface RectangleComponent extends ComponentBase {\n readonly kind: 'rectangle'\n readonly width: number\n readonly height: number\n readonly fill?: string\n readonly stroke?: string\n}\n\nexport interface SpacerComponent extends ComponentBase {\n readonly kind: 'spacer'\n readonly height: number\n}\n\n/** A width in points, or a share of what fixed widths leave. */\nexport type Width = number | 'fill'\n\n/** One column of a columns block, as distinct from a table's column. */\nexport interface ColumnSlot {\n readonly width: Width\n readonly components: readonly Component[]\n}\n\nexport interface ColumnsComponent extends ComponentBase {\n readonly kind: 'columns'\n readonly columns: readonly ColumnSlot[]\n}\n\nexport interface Border {\n readonly thickness: number\n readonly color: string\n}\n\n/**\n * Components that belong together and nothing more: they flow as though\n * they stood where the section does, so one condition shows or hides them\n * all, and a border, a fill and padding can frame them. Unlike columns and\n * keep-together blocks, a section adds no layout rule.\n */\nexport interface SectionComponent extends ComponentBase {\n readonly kind: 'section'\n readonly components: readonly Component[]\n readonly border?: Border\n readonly fill?: string\n /** Points between the border and the content. */\n readonly padding?: number\n}\n\nexport interface PageBreakComponent extends ComponentBase {\n readonly kind: 'pageBreak'\n}\n\nexport interface KeepTogetherComponent extends ComponentBase {\n readonly kind: 'keepTogether'\n readonly components: readonly Component[]\n}\n\nexport const COMPONENT_KINDS = [\n 'text',\n 'image',\n 'qrCode',\n 'epcQrCode',\n 'line',\n 'rectangle',\n 'spacer',\n 'columns',\n 'section',\n 'table',\n 'chart',\n 'pageBreak',\n 'keepTogether',\n] as const\nexport type ComponentKind = (typeof COMPONENT_KINDS)[number]\n\nexport type Component =\n | TextComponent\n | ImageComponent\n | QrCodeComponent\n | EpcQrCodeComponent\n | LineComponent\n | RectangleComponent\n | SpacerComponent\n | ColumnsComponent\n | SectionComponent\n | TableComponent\n | ChartComponent\n | PageBreakComponent\n | KeepTogetherComponent\n","/**\n * A table over the report's one detail dataset: the rows it prints, its\n * columns, the keys it sorts by, its one level of grouping and the rows\n * under a group or the table that total them. A report may hold several,\n * each printing the rows its own condition selects (0062).\n */\nimport type { ComponentBase, Width } from './components.js'\nimport type { FieldRef } from './data.js'\nimport type { Alignment, StyleRule } from './styles.js'\nimport type { Expression, Inline } from './values.js'\n\nexport const SORT_DIRECTIONS = ['asc', 'desc'] as const\nexport type SortDirection = (typeof SORT_DIRECTIONS)[number]\n\nexport interface SortKey {\n /** A detail field. */\n readonly field: FieldRef\n readonly direction: SortDirection\n}\n\nexport interface TableColumn {\n /** Unique within its table. */\n readonly id: string\n /** Its title in the header row, a literal; where every shown column's is empty or white space, the table has no header row (0078). */\n readonly header: string\n readonly width: Width\n readonly align: Alignment\n /** Read once per detail row. */\n readonly value: Inline\n /** Read once per report: a hidden column gives its width to the fill columns, and its footer cells hide with it. */\n readonly visibleWhen?: Expression\n readonly style?: string\n /** Read once per detail row. */\n readonly styleWhen?: readonly StyleRule[]\n}\n\nexport interface TableFooterCell {\n /** A column id of the same table. */\n readonly column: string\n readonly value: Inline\n}\n\n/** A row under a group or under the table: a subtotal, a tax line, a total. One under the table is read in the `table` scope, where `table` totals the rows the table prints. */\nexport interface TableFooterRow {\n readonly cells: readonly TableFooterCell[]\n readonly style?: string\n}\n\n/**\n * One grouping level, the only one version 0 has. Rows are ordered by the\n * group's key first, then by the table's sort keys; rows whose keys are all\n * equal keep the order the provider gave them.\n */\nexport interface TableGroup {\n /** A detail field. */\n readonly by: FieldRef\n readonly direction: SortDirection\n /** One line across the table, read once per group. */\n readonly header: readonly Inline[]\n readonly headerStyle?: string\n /**\n * How many of the group's first rows its header is kept on its page\n * with, from 1 to `MAX_KEEP_WITH_ROWS`; absent, one, the rule every group\n * header has had. The group's own, so that each level of a later nesting\n * states its own (0059).\n */\n readonly keepWithRows?: number\n readonly footer: readonly TableFooterRow[]\n}\n\n/**\n * A table over the report's one detail dataset. Its header repeats on every\n * page it reaches; version 0 has no other choice. A table none of whose\n * shown columns' titles prints anything has no header row (0078).\n */\nexport interface TableComponent extends ComponentBase {\n readonly kind: 'table'\n readonly dataset: 'detail'\n /**\n * Read once per detail row, in its scope, in the provider's order and\n * before anything is ordered: the table prints, orders, groups and\n * totals the rows for which it holds. Absent, every row (0062).\n */\n readonly rowsWhen?: Expression\n readonly columns: readonly TableColumn[]\n readonly headerStyle?: string\n readonly sort?: readonly SortKey[]\n readonly group?: TableGroup\n readonly totals?: readonly TableFooterRow[]\n readonly emptyText: string\n readonly repeatHeader: true\n}\n","/**\n * The report definition, version 0: what a Formancy Report template is.\n *\n * A report is its own document, with its own version line\n * ([0007](../../../docs/decisions/0007-a-report-definition-is-its-own-versioned-document.md)).\n * Lengths are PDF points (1/72 inch), stored to the hundredth. Nothing here\n * holds customer data, credentials, asset bytes or rendered output: a\n * template names a dataset contract, an asset digest and a parameter, and\n * the deployment supplies what each resolves to.\n *\n * Four conventions hold throughout, so that one editor command, one binding\n * picker and one walk serve every part of the format:\n * - every shape that comes in kinds says which with `kind`;\n * - every declaration is a list of objects with an `id`, unique in its list;\n * - every reference to a dataset field is a `FieldRef`;\n * - a name an expression reads -- a field, a parameter, an aggregate -- is a\n * field key, as formancy's form spec writes one (`isFieldKey`); every other\n * id is an identifier (`isIdentifier`).\n *\n * The vocabularies are `const` lists, and each union type is derived from\n * its list, so the type and the validator's list cannot disagree.\n *\n * This module holds the definition, its regions and its provenance. Each\n * part it declares stands in a module of its own, named for what it\n * holds: the page (`page.ts`), print styles (`styles.ts`), the data it\n * reads (`data.ts`), assets (`assets.ts`), values (`values.ts`),\n * aggregates (`aggregates.ts`), components (`components.ts`) and the\n * table (`table.ts`).\n */\nimport type { AggregateDef } from './aggregates.js'\nimport type { AssetRef } from './assets.js'\nimport type { Component } from './components.js'\nimport type { Datasets, ParameterDef } from './data.js'\nimport type { EInvoice } from './e-invoice.js'\nimport type { FontMap } from './font-map.js'\nimport type { PageSettings } from './page.js'\nimport type { PaymentPart } from './payment-part.js'\nimport type { PrintStyle } from './styles.js'\nimport type { Translation } from './translation.js'\nimport type { REPORT_SPEC_VERSION } from './version.js'\n\n/**\n * The report's regions, in the order a reader meets them. The body is flow\n * only in version 0: ordered blocks, so a growing table pushes what follows\n * down. Positioned elements in the page regions are deferred.\n *\n * The first page header stands beside the header it replaces: page 1\n * prints it in place of the page header, which then prints from page 2 on\n * ([0060](../../../docs/decisions/0060-a-reports-first-page-may-print-a-header-of-its-own-or-none-in-place-of-the-page-header.md)).\n */\nexport const REGION_NAMES = ['reportHeader', 'firstPageHeader', 'pageHeader', 'body', 'pageFooter', 'summary'] as const\nexport type RegionName = (typeof REGION_NAMES)[number]\n\n/**\n * The regions a report may leave out, and what leaving one out means: the\n * first page header absent, page 1 prints the page header as every page\n * does; present and empty, page 1 prints no header (0060). Every other\n * region every report holds.\n */\nexport const OPTIONAL_REGIONS = ['firstPageHeader'] as const satisfies readonly RegionName[]\nexport type OptionalRegionName = (typeof OPTIONAL_REGIONS)[number]\n\nexport type Regions = { readonly [R in Exclude<RegionName, OptionalRegionName>]: readonly Component[] } & {\n readonly [R in OptionalRegionName]?: readonly Component[]\n}\n\nexport const PROVENANCE_KINDS = ['blank', 'form', 'dataset'] as const\nexport type ProvenanceKind = (typeof PROVENANCE_KINDS)[number]\n\n/**\n * Where a report was started from, so a reviewer can find the exact form\n * version or the dataset a generated report came from.\n */\nexport type Provenance =\n | { readonly kind: 'blank' }\n | {\n readonly kind: 'form'\n /** The form's id, as formancy writes one. */\n readonly form: string\n /** `schemaHash` of the exact form version: 64 lower-case hex digits. */\n readonly formHash: string\n }\n | { readonly kind: 'dataset'; /** The dataset's id in the deployment's catalogue. */ readonly dataset: string }\n\nexport interface ReportDefinition {\n readonly reportSpecVersion: typeof REPORT_SPEC_VERSION\n readonly id: string\n readonly title: string\n /** A BCP 47 tag: language, optional script, optional region. The report's own language: the one its words are written in, and the one a render that names none prints in (0063). */\n readonly locale: string\n readonly page: PageSettings\n readonly styles: readonly PrintStyle[]\n readonly datasets: Datasets\n readonly parameters: readonly ParameterDef[]\n readonly assets: readonly AssetRef[]\n readonly aggregates: readonly AggregateDef[]\n /** Which font assets each font token prints in, face by face; absent, and a token left out, the renderer prints that token in its own face (0043). */\n readonly fonts?: FontMap\n readonly regions: Regions\n /** A slip to pay the report by, printed at the foot of its last page: a Swiss QR-bill. Absent, the report has none. */\n readonly paymentPart?: PaymentPart\n /** The EN 16931 invoice the report is, written as Factur-X from what its page prints. Absent, the report is none. */\n readonly eInvoice?: EInvoice\n readonly provenance?: Provenance\n /**\n * The report's words in each language besides its own, one translation\n * a language, each word looked up by its exact text in the report's own\n * (0063). Absent, the report is written in its own language alone; never\n * an empty list.\n */\n readonly translations?: readonly Translation[]\n}\n","/**\n * The payment part a report may print: one Swiss QR-bill, its receipt and\n * its payment part, at the foot of the report's last page.\n *\n * It belongs to the report, not to a region: a bill is printed once, at a\n * place SIX fixes, whatever the regions hold. Its texts are runs, read as\n * a paragraph's in the report's scope, and resolved whole before there are\n * pages, since every one of them is encoded in the bill's QR code: none\n * holds a page number or count. What each must hold, SIX's Swiss\n * Implementation Guidelines for the QR-bill say; `qr-bill.ts` holds their\n * rules, and the validator applies them to a text no data can change.\n */\nimport type { Expression, Inline } from './values.js'\n\n/**\n * The languages a QR-bill's headings may be printed in: German, French,\n * Italian, English, and Romansh since 1 January 2026 (IG 2.4, Annex C). A\n * report in any other language prints its slip in one of these.\n */\nexport const QR_BILL_LANGUAGES = ['de', 'fr', 'it', 'en', 'rm'] as const\nexport type QrBillLanguage = (typeof QR_BILL_LANGUAGES)[number]\n\n/** The currencies a QR-bill pays in, and the only ones (IG Table 8, Ccy). */\nexport const QR_BILL_CURRENCIES = ['CHF', 'EUR'] as const\nexport type QrBillCurrency = (typeof QR_BILL_CURRENCIES)[number]\n\n/**\n * A party's address, structured: the one address type SIX has taken since\n * version 2.3 removed the combined one. Each part is runs of text; what\n * each may hold is `QR_BILL_ADDRESS_RULES`.\n */\nexport interface QrBillAddress {\n /** A person's first and last name, or a company's: 70 characters. */\n readonly name: readonly Inline[]\n /** The street or post office box, without the building number: 70 characters. */\n readonly street?: readonly Inline[]\n readonly buildingNumber?: readonly Inline[]\n /** Without a country prefix. */\n readonly postalCode: readonly Inline[]\n readonly town: readonly Inline[]\n /** ISO 3166-1's two capital letters: CH. */\n readonly country: readonly Inline[]\n}\n\n/**\n * A Swiss QR-bill. Each text is runs, one at least where it is present; an\n * optional one absent is a field the bill leaves empty, never an empty\n * list of runs, so that one bill has one spelling and one hash.\n */\nexport interface SwissQrBill {\n readonly kind: 'swissQrBill'\n /** The language of the slip's headings, which may differ from the report's. */\n readonly language: QrBillLanguage\n /** The creditor's IBAN or QR-IBAN, of Switzerland or Liechtenstein. Spaces are for reading, and are dropped. */\n readonly account: readonly Inline[]\n readonly creditor: QrBillAddress\n readonly currency: QrBillCurrency\n /** A decimal of at most two places. Absent, or null, leaves the amount for the payer to fill in. */\n readonly amount?: Expression\n /** Who pays. Absent leaves a field for the payer's name and address. */\n readonly debtor?: QrBillAddress\n /** A QR reference, with a QR-IBAN, or a creditor reference, with an IBAN. Absent, the bill has none. */\n readonly reference?: readonly Inline[]\n /** The unstructured message: what the payment is for. */\n readonly message?: readonly Inline[]\n /** Coded information for the payer's software, beginning with `//`. */\n readonly billingInformation?: readonly Inline[]\n}\n\n/** The kinds of payment part. A kind this version does not know is refused, never skipped. */\nexport const PAYMENT_PART_KINDS = ['swissQrBill'] as const\nexport type PaymentPartKind = (typeof PAYMENT_PART_KINDS)[number]\n\nexport type PaymentPart = SwissQrBill\n","/**\n * What every payment code a report prints shares: ISO 7064's check modulo\n * 97, which ISO 13616 checks an IBAN with and ISO 11649 a creditor\n * reference, and a Leitweg-ID's check digits are computed by; the\n * creditor reference itself; and what a check says.\n *\n * One check, read by the QR-bill's rules (`qr-bill.ts`) and the EPC QR\n * code's (`epc-payload.ts`): two copies could disagree about which account\n * is typed right, and nobody would find out until a bank refused a payment.\n * What only one code allows -- the QR-bill's accounts of Switzerland and\n * Liechtenstein, its QR reference, the EPC's countries of SEPA -- stays\n * with that code's rules.\n *\n * A rule broken is said without the value that broke it: an IBAN or a\n * reference may be a person's.\n */\n\n/** What a check made of a text it accepts, or the rule the text breaks. */\nexport type PaymentCheck<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly rule: string }\n\nexport function ok<T>(value: T): PaymentCheck<T> {\n return { ok: true, value }\n}\n\nexport function no(rule: string): PaymentCheck<never> {\n return { ok: false, rule }\n}\n\n/** Every gap a person writes into an IBAN or a reference to read it, and which a code never holds. */\nconst SPACES = /\\s+/g\n\nexport function withoutSpaces(text: string): string {\n return text.replace(SPACES, '')\n}\n\n/**\n * A text's remainder modulo 97, each letter read as the two digits ISO\n * 7064 gives it (A is 10, Z is 35), in either case, digit by digit: never\n * as one number, which a 27-character IBAN is too long to be exactly. The\n * Leitweg-ID's check digits are ISO 7064's MOD 97-10 too, and read it\n * (`xrechnung.ts`, 0038).\n */\nexport function mod97(text: string): number {\n let remainder = 0\n for (const character of text) {\n const value = Number.parseInt(character, 36)\n remainder = (remainder * (value < 10 ? 10 : 100) + value) % 97\n }\n return remainder\n}\n\n/** ISO 13616 and ISO 11649 check the same way: the first four characters moved to the end, and the remainder modulo 97 is 1. */\nfunction checksOut(text: string): boolean {\n return mod97(`${text.slice(4)}${text.slice(0, 4)}`) === 1\n}\n\n/**\n * An IBAN its code's own rule has already shaped -- its country, its\n * length, its characters -- checked by its check digits (ISO 13616).\n */\nexport function checkIbanCheckDigits(iban: string): PaymentCheck<string> {\n return checksOut(iban) ? ok(iban) : no('has check digits that do not match the rest of it (ISO 13616: the IBAN modulo 97 is 1)')\n}\n\n/** A creditor reference: RF, two check digits and from one to 21 letters or digits (ISO 11649), in any case. */\nconst CREDITOR_REFERENCE = /^RF\\d{2}[0-9A-Z]{1,21}$/i\n\n/**\n * A creditor reference (ISO 11649), its spaces dropped and its case kept as\n * written: the check reads a letter the same in either case, and which\n * case a code holds is that code's rule -- a QR-bill's as written, since\n * \"the banks draw no distinction between lower and upper case\" (SIX's\n * guidelines, Table 8, Ref); an EPC QR code's in capitals\n * (`epc-payload.ts`). A text that is not shaped as one breaks `shape`, the\n * caller's words for what its code takes instead.\n */\nexport function checkCreditorReference(text: string, shape: string): PaymentCheck<string> {\n const reference = withoutSpaces(text)\n if (!CREDITOR_REFERENCE.test(reference)) return no(shape)\n return checksOut(reference) ? ok(reference) : no('has check digits that do not match the rest of it (ISO 11649: the reference modulo 97 is 1)')\n}\n","/**\n * What SIX's Swiss Implementation Guidelines for the QR-bill allow a bill\n * to hold, as checks over text: the account, the reference, each address\n * part, the message, the billing information and the amount; and the\n * slip's size, where it stands on its page, and the room it needs there.\n *\n * One set of rules, read twice. The validator applies them to a text no\n * data can change -- a field of literal runs -- so that the editor refuses\n * a mistyped IBAN where it is written; the runtime applies them to every\n * text once the data has resolved it. Two copies could disagree about\n * which bills are valid, and nobody would find out until a bank refused\n * one. An IBAN's check digits and a creditor reference are every payment\n * code's (`payment-reference.ts`): an EPC QR code's are checked by the same\n * functions, and what stays here is the QR-bill's own -- its accounts of\n * Switzerland and Liechtenstein, its QR reference.\n *\n * The rules are version 2.3's, in force since 21 November 2025, and one of\n * version 2.4's, valid from 14 November 2026: a QR-IBAN and a QR reference\n * only in CHF. Version 2.4 changes nothing else a bill holds, so a bill\n * these accept is valid under both. \"IG\" below is the guidelines, Table 8\n * their table of the code's elements.\n *\n * A rule broken is said without the value that broke it: an IBAN, a name\n * or a town may be a person's, and a message reaches logs and screens.\n * Lengths and positions are said; characters are not.\n */\nimport { mmToPt, roundPt } from './units.js'\nimport { PAGE_SIZES, type PageDimensions, type PageSettings } from './page.js'\nimport type { QrBillAddress, QrBillCurrency } from './payment-part.js'\nimport { checkCreditorReference, checkIbanCheckDigits, no, ok, withoutSpaces } from './payment-reference.js'\nimport type { PaymentCheck } from './payment-reference.js'\nimport { DECIMAL } from './syntax.js'\n\n/** What a check made of a text it accepts, or the rule the text breaks: every payment code's `PaymentCheck`. */\nexport type QrBillCheck<T> = PaymentCheck<T>\n\n/**\n * The slip: the receipt and the payment part, 210 by 105 mm (IG 3.1),\n * across the foot of an A4 page in portrait. The builders' band and the\n * renderer's slip are this size.\n */\nexport const QR_BILL_SIZE: PageDimensions = { width: mmToPt(210), height: mmToPt(105) }\n\n/**\n * How far down its page the slip starts, in points from the paper's top:\n * 105 mm above the foot of the A4 page (IG 3.1), stored as every length\n * is. The renderer draws the slip from here, and `qrBillPageBreak` keeps\n * what the page prints above it out of it.\n */\nexport const QR_BILL_TOP = roundPt(PAGE_SIZES.A4.height - QR_BILL_SIZE.height)\n\n/** A rule a page breaks by carrying a QR-bill, and what it is said of: the page's size and orientation, or its top margin. */\nexport interface QrBillPageBreak {\n readonly field: 'page' | 'topMargin'\n readonly rule: string\n}\n\n/**\n * The rule `page` breaks by carrying a QR-bill's slip, or undefined. The\n * slip is printed across the foot of an A4 page in portrait (IG 3.1), and\n * what the page prints above it ends at its top, `QR_BILL_TOP`: the page\n * header and the body, which start at the top margin. The page footer\n * never meets it: the slip stands in its place on the last page, and the\n * footers of the pages before it are on pages of their own.\n *\n * `above` is what stands between the top margin and the slip that only a\n * render measures: the page header's height, and the instruction to\n * separate that a PDF prints over the slip's top line (IG 3.7). The\n * validator knows neither and passes none, so it refuses what the top\n * margin alone decides; the renderer passes both, and the same rule\n * refuses the rest. One rule, so that where the slip starts and what\n * reaching into it is are decided once.\n */\nexport function qrBillPageBreak(page: PageSettings, above = 0): QrBillPageBreak | undefined {\n if (page.size !== 'A4' || page.orientation !== 'portrait') {\n return { field: 'page', rule: `a QR-bill is printed across the foot of an A4 page in portrait, and this page is ${page.size} in ${page.orientation}` }\n }\n const reach = page.margins.top + above\n if (reach <= QR_BILL_TOP) return undefined\n // Said to the hundredth above, so that a reach past the top by less than a hundredth never reads as the top itself.\n const said = (Math.ceil(reach * 100 - 1e-6) / 100).toFixed(2)\n const what = above === 0 ? 'the top margin reaches' : 'the top margin, with the page header and the instruction to separate printed above the slip, reaches'\n return {\n field: 'topMargin',\n rule: `${what} ${said} pt down the page, past the top of the QR-bill's slip at ${QR_BILL_TOP.toFixed(2)} pt, 105 mm above the paper's foot`,\n }\n}\n\n/** An IBAN of Switzerland or Liechtenstein: the country, two check digits, the five-digit institution and twelve digits or capitals. */\nconst IBAN = /^(?:CH|LI)\\d{2}(\\d{5})[0-9A-Z]{12}$/\n\n/** The institutions whose IBANs are QR-IBANs (IG 2.8). */\nconst QR_IID = { first: 30000, last: 31999 }\n\n/**\n * Whether `iban`, an IBAN without spaces, is a QR-IBAN: of Switzerland or\n * Liechtenstein, its institution a QR-IID, \"used only for the procedure\n * with a QR reference in the QR-bill\" (IG 2.8). The EPC QR code's rules\n * refuse one by this range (`epc-payload.ts`), which is SIX's and stays\n * here.\n */\nexport function isQrIban(iban: string): boolean {\n const institution = IBAN.exec(iban)?.[1]\n return institution !== undefined && Number(institution) >= QR_IID.first && Number(institution) <= QR_IID.last\n}\n\nexport interface QrBillAccount {\n /** The IBAN as the code holds it: 21 characters, no spaces. */\n readonly iban: string\n /** Whether its institution is a QR-IID, so that it is paid to with a QR reference. */\n readonly qrIban: boolean\n}\n\n/** The account: an IBAN or a QR-IBAN of Switzerland or Liechtenstein (IG Table 8, IBAN), its spaces dropped. */\nexport function checkQrBillAccount(text: string): QrBillCheck<QrBillAccount> {\n const iban = withoutSpaces(text)\n if (!IBAN.test(iban))\n return no('is not an IBAN of Switzerland or Liechtenstein: CH or LI, two check digits and 17 digits or capitals, 21 characters without spaces')\n const checked = checkIbanCheckDigits(iban)\n if (!checked.ok) return checked\n return ok({ iban, qrIban: isQrIban(iban) })\n}\n\n/**\n * The accounts of SIX's examples (IG 2.4, Annex A: examples 1, 2 and 3,\n * and 4, 5 and 6, which share one), as the code holds them: two QR-IBANs\n * and two IBANs. SIX publishes them to test with, and they are no\n * creditor's: a bill that pays one never reaches the creditor it names. A\n * new bill in a builder starts from example 3's, and report-core warns of\n * a bill whose account, written in the report, is one of these (0039).\n */\nexport const QR_BILL_EXAMPLE_ACCOUNTS = ['CH6431961000004421557', 'CH4431999123000889012', 'CH5204835012345671000', 'CH5800791123000889012'] as const\n\n/** A party of SIX's examples, part by part, as plain text. */\ntype ExampleParty = { readonly [P in keyof QrBillAddress]?: string }\n\n/**\n * What a builder starts a bill from, SIX's own example values (IG 2.4,\n * Annex A), as SIX prints them: example 3's account and creditor (Table\n * 19), the bill a builder adds, with no amount, debtor or reference;\n * example 1's debtor (Table 17), the debtor it adds; and example 1's QR\n * reference, which it gives a bill whose account is made a QR-IBAN, as a\n * QR-IBAN is paid to with nothing else. They are no one's, and\n * report-core warns of a bill that holds one of them, written in the\n * report, as it warns of an example account (0039): one list, so that\n * what a builder puts in and what is warned of cannot drift apart.\n */\nexport const QR_BILL_EXAMPLE = {\n account: 'CH52 0483 5012 3456 7100 0',\n creditor: { name: 'Muster Stiftung (sample foundation)', street: 'P.O. box', postalCode: '3001', town: 'Bern', country: 'CH' },\n debtor: { name: 'Simon Muster', street: 'Musterstrasse', buildingNumber: '1', postalCode: '8000', town: 'Seldwyla', country: 'CH' },\n reference: '00 00082 07791 22585 74212 86694',\n} as const satisfies { readonly account: string; readonly creditor: ExampleParty; readonly debtor: ExampleParty; readonly reference: string }\n\n/** The recursive modulo 10 of IG Annex B, row by row: the carry after each digit. */\nconst CARRY = [0, 9, 4, 6, 8, 2, 7, 1, 3, 5]\n\n/** The check digit of a QR reference's first 26 digits. */\nfunction qrCheckDigit(digits: string): number {\n let carry = 0\n for (const digit of digits) carry = CARRY[(carry + Number(digit)) % 10] as number\n return (10 - carry) % 10\n}\n\n/** The kinds of reference a bill holds (IG Table 8, Tp): a QR reference, a creditor reference, or none. */\nexport type QrBillReferenceType = 'QRR' | 'SCOR' | 'NON'\n\nexport interface QrBillReference {\n readonly type: 'QRR' | 'SCOR'\n /** The reference as the code holds it: no spaces, in the case it was written. */\n readonly reference: string\n}\n\nconst QR_REFERENCE_LENGTH = 27\n\n/**\n * The reference: a QR reference of 27 digits, the last its check digit\n * (IG 2.12.1, Annex B), or a creditor reference (IG Table 8, Ref), its\n * spaces dropped.\n */\nexport function checkQrBillReference(text: string): QrBillCheck<QrBillReference> {\n const reference = withoutSpaces(text)\n if (/^\\d+$/.test(reference)) {\n if (reference.length !== QR_REFERENCE_LENGTH) return no(`is a QR reference of ${reference.length} digits; a QR reference has ${QR_REFERENCE_LENGTH}`)\n if (/^0+$/.test(reference)) return no('is a QR reference of zeros only, which SIX does not allow (IG 2.12.1)')\n if (qrCheckDigit(reference.slice(0, -1)) !== Number(reference.at(-1)))\n return no('ends in a digit that is not its check digit (IG Annex B: modulo 10, recursive)')\n return ok({ type: 'QRR', reference })\n }\n const creditor = checkCreditorReference(\n reference,\n 'is neither a QR reference, 27 digits, nor a creditor reference, RF, two check digits and up to 21 letters or digits',\n )\n return creditor.ok ? ok({ type: 'SCOR', reference: creditor.value }) : creditor\n}\n\n/** What a text of the bill may hold: whether it must, how many characters, and a syntax it must have when it is not empty. */\nexport interface QrBillTextRule {\n /** What a person calls it, for a message: \"postal code\". */\n readonly said: string\n readonly required: boolean\n /** Characters, as SIX counts them: every character it allows is one UTF-16 unit. */\n readonly max: number\n readonly syntax?: { readonly pattern: RegExp; readonly rule: string }\n}\n\n/**\n * Each part of an address, in the order the code holds them, with what it\n * may hold (IG Table 8, Cdtr and UltmtDbtr). The name, the postal code,\n * the town and the country \"must be filled in\" (IG 4.3.1). A table over\n * every part, so a part added to `QrBillAddress` without its rule does not\n * compile, and what reads an address reads it in this order.\n */\nexport const QR_BILL_ADDRESS_RULES: { readonly [P in keyof QrBillAddress]-?: QrBillTextRule } = {\n name: { said: 'name', required: true, max: 70 },\n street: { said: 'street', required: false, max: 70 },\n buildingNumber: { said: 'building number', required: false, max: 16 },\n postalCode: { said: 'postal code', required: true, max: 16 },\n town: { said: 'town', required: true, max: 35 },\n country: {\n said: 'country',\n required: true,\n max: 2,\n syntax: { pattern: /^[A-Z]{2}$/, rule: 'is not a country code: two capital letters, as ISO 3166-1 writes one, such as CH' },\n },\n}\n\n/** The most characters the message and the billing information hold together (IG Table 8, AddInf). */\nexport const MAX_QR_BILL_ADDITIONAL_INFORMATION = 140\n\n/** The unstructured message (IG Table 8, Ustrd). */\nexport const QR_BILL_MESSAGE_RULE: QrBillTextRule = { said: 'message', required: false, max: MAX_QR_BILL_ADDITIONAL_INFORMATION }\n\n/**\n * The billing information (IG Table 8, StrdBkgInf; 4.3.3): it begins with\n * `//` and the two letters or digits that name its syntax, as SIX's own,\n * `S1`. What follows is the syntax's, which SIX does not standardise.\n */\nexport const QR_BILL_BILLING_RULE: QrBillTextRule = {\n said: 'billing information',\n required: false,\n max: MAX_QR_BILL_ADDITIONAL_INFORMATION,\n syntax: { pattern: /^\\/\\/[0-9A-Za-z]{2}/, rule: 'does not begin with //, then the two characters that name its syntax (IG 4.3.3)' },\n}\n\n/**\n * Whether a character is one SIX allows (IG 4.1.1): Basic Latin, Latin-1\n * Supplement and Latin Extended-A, Ș ș Ț ț, and the euro sign. A line\n * break is not one, so no text can end its line of the code early.\n */\nfunction allowed(codePoint: number): boolean {\n return (\n (codePoint >= 0x20 && codePoint <= 0x7e) || (codePoint >= 0xa0 && codePoint <= 0x17f) || (codePoint >= 0x218 && codePoint <= 0x21b) || codePoint === 0x20ac\n )\n}\n\n/**\n * A text of the bill, without the blanks around it, which SIX never sends\n * (IG 4.1.3), checked against `rule` and the characters SIX allows. The\n * first character outside them is named by its position in the text as\n * written, counted in characters from 1, and never quoted.\n */\nexport function checkQrBillText(text: string, rule: QrBillTextRule): QrBillCheck<string> {\n const value = text.trim()\n const outside = [...value].findIndex((character) => !allowed(character.codePointAt(0) as number))\n if (outside !== -1) {\n // Every blank trimmed is one UTF-16 unit, so the units before the text are as many characters.\n const position = text.length - text.trimStart().length + outside + 1\n return no(`is not written in the characters SIX allows (IG 4.1.1): character ${position} is outside them`)\n }\n if (value === '') return rule.required ? no('is empty, and a QR-bill needs it') : ok(value)\n if (rule.syntax !== undefined && !rule.syntax.pattern.test(value)) return no(rule.syntax.rule)\n if (value.length > rule.max) return no(`is ${value.length} characters long; SIX allows at most ${rule.max}`)\n return ok(value)\n}\n\n/** The rule the message and the billing information break together, each already checked on its own, or undefined. */\nexport function checkQrBillAdditionalInformation(message: string, billingInformation: string): string | undefined {\n const length = message.length + billingInformation.length\n if (length <= MAX_QR_BILL_ADDITIONAL_INFORMATION) return undefined\n return `the message and the billing information are ${length} characters long together; SIX allows at most ${MAX_QR_BILL_ADDITIONAL_INFORMATION}`\n}\n\n/** A rule an account, a reference and a currency break together, and the field it is reported on. */\nexport interface QrBillPairingBreak {\n readonly field: 'reference' | 'currency'\n readonly rule: string\n}\n\n/**\n * The rules an account, a reference and a currency break together. A\n * QR-IBAN is paid to with a QR reference and nothing else; a QR reference\n * only to a QR-IBAN (IG Table 8, Tp); and from version 2.4 both are for\n * CHF only (IG 2.4, 2.10). An account or a reference that is not known --\n * read from data, before a render -- is undefined, and nothing is said of\n * it.\n */\nexport function qrBillPairing(\n account: 'iban' | 'qrIban' | undefined,\n reference: QrBillReferenceType | undefined,\n currency: QrBillCurrency,\n): readonly QrBillPairingBreak[] {\n const breaks: QrBillPairingBreak[] = []\n if (account === 'qrIban' && reference !== undefined && reference !== 'QRR') {\n const has = reference === 'NON' ? 'this bill has none' : 'this is a creditor reference'\n breaks.push({ field: 'reference', rule: `a QR-IBAN is paid to with a QR reference, and ${has}` })\n }\n if (account === 'iban' && reference === 'QRR') breaks.push({ field: 'reference', rule: 'a QR reference is paid to a QR-IBAN, and the account is an IBAN' })\n if (currency !== 'CHF' && (account === 'qrIban' || reference === 'QRR')) {\n breaks.push({\n field: 'currency',\n rule: 'a QR-IBAN and a QR reference are for invoices in CHF only, from version 2.4 of the guidelines, valid from 14 November 2026',\n })\n }\n return breaks\n}\n\n/** The most digits before the point: 999 999 999.99 is the largest amount (IG Table 8, Amt). */\nconst MAX_WHOLE_DIGITS = 9\n\n/**\n * The amount as the code writes it: the exact decimal's own digits, a\n * point and two decimals (IG Table 8, Amt), from 0.01 to 999 999 999.99.\n * `DECIMAL` admits no leading zero, so none is written. Never rounded: an\n * amount written with more than two decimals is refused, a third decimal\n * of zero among them, so that a template that does not round is refused\n * on its first render.\n */\nexport function checkQrBillAmount(decimal: string): QrBillCheck<string> {\n if (!DECIMAL.test(decimal)) return no('is not a decimal')\n const [whole = '', fraction = ''] = decimal.replace(/^-/, '').split('.')\n if (fraction.length > 2) return no('has more than two decimals; a QR-bill pays whole cents, so the amount is rounded where it is computed')\n const cents = fraction.padEnd(2, '0')\n if (decimal.startsWith('-') || whole.length > MAX_WHOLE_DIGITS || (whole === '0' && cents === '00'))\n return no('is not from 0.01 to 999 999 999.99, the amounts a QR-bill pays')\n return ok(`${whole}.${cents}`)\n}\n","/**\n * The EPC QR code: the code a SEPA credit transfer is initiated from, as\n * the European Payments Council's guidelines define it (EPC069-12 v3.1),\n * printed on an invoice beside the payment details it holds.\n *\n * It is a component in a region, as a QR code is, and not a payment part:\n * the EPC prescribes no slip and no place for it. Austria's PSA asks for\n * \"the right most or left most lower edge of the page\" (PSA v3.0 5), and\n * the author puts it there. Its texts are runs, read as a paragraph's in\n * the report's scope and resolved whole before there are pages, since all\n * are encoded: none holds a page number or count. What each may hold,\n * `epc-payload.ts` says; how it is printed, `epc-print.ts`.\n *\n * It pays SEPA credit transfers (`SCT`) in euro, and nothing else: no\n * instant transfer, no other currency, and no structured reference but a\n * creditor reference (ISO 11649).\n */\nimport type { ComponentBase } from './components.js'\nimport type { Expression, Inline } from './values.js'\n\n/**\n * What a code may be framed and captioned with: Austria's frame and the\n * words \"Zahlen mit Code\" (PSA v3.0 5), drawn inside the code's square.\n * Absent, the code is printed alone, as a QR code is.\n */\nexport const EPC_CAPTIONS = ['zahlenMitCode'] as const\nexport type EpcCaption = (typeof EPC_CAPTIONS)[number]\n\n/**\n * An EPC QR code. Each text is runs, one at least where it is present; an\n * optional one absent is an element the code leaves empty, never an empty\n * list of runs, so that one code has one spelling and one hash.\n */\nexport interface EpcQrCodeComponent extends ComponentBase {\n readonly kind: 'epcQrCode'\n /** The side of the square in points: the quiet zone, and the frame and caption when there are any, inside it. */\n readonly size: number\n /** The beneficiary's name (AT-E001): at most 70 characters. */\n readonly beneficiary: readonly Inline[]\n /** The beneficiary's IBAN (AT-C001), of a country of SEPA. Spaces are for reading, and are dropped. */\n readonly iban: readonly Inline[]\n /** The BIC of the beneficiary's bank (AT-C002): needed for an account outside the EEA, and may be left out for one inside it. */\n readonly bic?: readonly Inline[]\n /** The amount in euro, a decimal of at most two places. Absent, or null, leaves the amount for the payer to fill in. */\n readonly amount?: Expression\n /** The purpose code (AT-T007): four capital letters, written into the template. */\n readonly purpose?: string\n /** A creditor reference (AT-T009, structured): RF and its check digits. Never with `text`. */\n readonly reference?: readonly Inline[]\n /** The remittance text (AT-T009, unstructured): at most 140 characters. Never with `reference`. */\n readonly text?: readonly Inline[]\n /** Information for the payer, shown by the banking app and not sent with the transfer: at most 70 characters. */\n readonly information?: readonly Inline[]\n readonly caption?: EpcCaption\n}\n","/**\n * The countries and territories a SEPA credit transfer reaches, and what\n * their accounts and their banks are written with: the length of each\n * country's IBAN, whether it is in the EEA, and the country code each\n * territory's BICs carry.\n *\n * Recorded from, on 17 October 2026:\n * - **EPC409-09**, \"EPC List of Countries in the SEPA Schemes' Geographical\n * Scope\", version 8.0, issued 24 December 2025. Section 5 gives every\n * country and territory with the code its BICs and its IBANs carry;\n * section 2 says which are in the EU or the EEA. Gibraltar is in section\n * 5's table and in neither of section 2's lists, and is outside the EU\n * and the EEA: it is recorded as outside the EEA.\n * - **SWIFT's IBAN Registry**, release 101, for each country's length.\n * swift.com refused the download that day (HTTP 403, \"SWIFT site\n * off-line\"), so the lengths were read from python-stdnum's `iban.dat`,\n * which says it was generated from `iban-registry-v101.txt` (commit\n * 6070c60af5d4, 4 January 2026), and agree with php-iban's\n * `registry.txt` for every country here. `epc-payload.test.ts` holds\n * each to the registry's example IBAN for its country.\n *\n * A country joining SEPA, or a registry release changing a length, is a\n * change here and nowhere else.\n */\n\n/** What a country's accounts are: its IBAN's length, and whether it is in the EEA. */\nexport interface SepaCountry {\n readonly length: number\n readonly eea: boolean\n}\n\n/** Each country code an IBAN of SEPA begins with (EPC409-09 v8.0, 5), its length (IBAN Registry 101) and whether it is in the EEA (2). */\nconst IBAN_COUNTRIES: { readonly [country: string]: SepaCountry } = {\n AD: { length: 24, eea: false }, // Andorra\n AL: { length: 28, eea: false }, // Albania\n AT: { length: 20, eea: true }, // Austria\n BE: { length: 16, eea: true }, // Belgium\n BG: { length: 22, eea: true }, // Bulgaria\n CH: { length: 21, eea: false }, // Switzerland\n CY: { length: 28, eea: true }, // Cyprus\n CZ: { length: 24, eea: true }, // Czech Republic\n DE: { length: 22, eea: true }, // Germany\n DK: { length: 18, eea: true }, // Denmark\n EE: { length: 20, eea: true }, // Estonia\n ES: { length: 24, eea: true }, // Spain, the Canary Islands\n FI: { length: 18, eea: true }, // Finland, the Åland Islands\n // France, French Guiana, Guadeloupe, Martinique, Mayotte, Réunion, Saint\n // Barthélemy, Saint Martin; and Saint Pierre and Miquelon, which is\n // outside the EEA and whose accounts no IBAN tells apart.\n FR: { length: 27, eea: true },\n GB: { length: 22, eea: false }, // the United Kingdom, Guernsey, the Isle of Man, Jersey\n GI: { length: 23, eea: false }, // Gibraltar\n GR: { length: 27, eea: true }, // Greece\n HR: { length: 21, eea: true }, // Croatia\n HU: { length: 28, eea: true }, // Hungary\n IE: { length: 22, eea: true }, // Ireland\n IS: { length: 26, eea: true }, // Iceland\n IT: { length: 27, eea: true }, // Italy\n LI: { length: 21, eea: true }, // Liechtenstein\n LT: { length: 20, eea: true }, // Lithuania\n LU: { length: 20, eea: true }, // Luxembourg\n LV: { length: 21, eea: true }, // Latvia\n MC: { length: 27, eea: false }, // Monaco\n MD: { length: 24, eea: false }, // Moldova\n ME: { length: 22, eea: false }, // Montenegro\n MK: { length: 19, eea: false }, // North Macedonia\n MT: { length: 31, eea: true }, // Malta\n NL: { length: 18, eea: true }, // the Netherlands\n NO: { length: 15, eea: true }, // Norway\n PL: { length: 28, eea: true }, // Poland\n PT: { length: 25, eea: true }, // Portugal, the Azores, Madeira\n RO: { length: 24, eea: true }, // Romania\n RS: { length: 22, eea: false }, // Serbia\n SE: { length: 24, eea: true }, // Sweden\n SI: { length: 19, eea: true }, // Slovenia\n SK: { length: 24, eea: true }, // Slovakia\n SM: { length: 27, eea: false }, // San Marino\n VA: { length: 22, eea: false }, // Vatican City State\n}\n\n/**\n * The territories whose BICs carry a country code of their own and whose\n * IBANs another's (EPC409-09 v8.0, 5). Every other country of SEPA writes\n * its BICs with its IBANs' code.\n */\nconst BIC_TERRITORIES: { readonly [bicCountry: string]: string } = {\n BL: 'FR', // Saint Barthélemy\n GF: 'FR', // French Guiana\n GG: 'GB', // Guernsey\n GP: 'FR', // Guadeloupe\n IM: 'GB', // the Isle of Man\n JE: 'GB', // Jersey\n MF: 'FR', // Saint Martin (French part)\n MQ: 'FR', // Martinique\n PM: 'FR', // Saint Pierre and Miquelon\n RE: 'FR', // Réunion\n YT: 'FR', // Mayotte\n}\n\n/** The country of SEPA whose IBANs begin with `country`, or undefined when it is none. */\nexport function sepaCountry(country: string): SepaCountry | undefined {\n return Object.hasOwn(IBAN_COUNTRIES, country) ? IBAN_COUNTRIES[country] : undefined\n}\n\n/** The code the IBANs carry of the territory whose BICs carry `bicCountry`, or undefined when no territory of SEPA's BICs carry it. */\nexport function sepaIbanCountryOfBic(bicCountry: string): string | undefined {\n if (Object.hasOwn(BIC_TERRITORIES, bicCountry)) return BIC_TERRITORIES[bicCountry]\n return Object.hasOwn(IBAN_COUNTRIES, bicCountry) ? bicCountry : undefined\n}\n\n/** Every country code an IBAN of SEPA begins with, in alphabetical order. */\nexport const SEPA_IBAN_COUNTRIES: readonly string[] = Object.keys(IBAN_COUNTRIES).sort()\n","/**\n * What an EPC QR code may hold, as checks over text, and the payload it\n * encodes: the European Payments Council's \"Quick Response Code --\n * Guidelines to Enable the Data Capture for the Initiation of a SEPA Credit\n * Transfer\", EPC069-12 version 3.1 of 19 March 2024 (\"EPC\" below, by its\n * section). Where Austria's \"QR-Code und BCD Definition\", PSA version 3.0\n * of 1 May 2021, is stricter and the EPC allows its rule, the PSA's is\n * taken: an amount as short as it can be written (PSA 3, note 5).\n *\n * One set of rules, read twice, as the QR-bill's are (`qr-bill.ts`): the\n * validator applies them to a text no data can change, so that the editor\n * refuses a mistyped IBAN where it is written, and the runtime to every\n * text once the data has resolved it. The IBAN's check digits and the\n * creditor reference are the checks a QR-bill's are\n * (`payment-reference.ts`); which countries' accounts this code reaches is\n * `sepa.ts`'s table.\n *\n * What the code is: SEPA credit transfers, `SCT`, in euro, written in\n * UTF-8, character set 1. A rule broken is said without the value that\n * broke it: an IBAN, a name or a reference may be a person's. Lengths and\n * positions are said; characters are not.\n */\nimport { checkCreditorReference, checkIbanCheckDigits, no, ok, withoutSpaces } from './payment-reference.js'\nimport type { PaymentCheck } from './payment-reference.js'\nimport { isQrIban } from './qr-bill.js'\nimport { sepaCountry, sepaIbanCountryOfBic } from './sepa.js'\nimport { DECIMAL } from './syntax.js'\n\n/** The most bytes the whole payload may take (EPC 2.2): what a version 13 code holds at level M (EPC 2.1). */\nexport const EPC_MAX_BYTES = 331\n\n/** An IBAN as a person may write one: two letters for its country, two check digits, then letters or digits, in either case. */\nconst IBAN = /^[A-Za-z]{2}\\d{2}[A-Za-z0-9]+$/\n\n/**\n * The account (EPC 2.2, AT-C001: \"Only IBAN is allowed\"): an IBAN of a\n * country of SEPA, of that country's length, its check digits right. Its\n * spaces are dropped and its letters made capitals, as the electronic form\n * writes it -- after its letters are known to be A to Z, so that no letter\n * becomes two.\n *\n * And no QR-IBAN, which SIX keeps for a QR-bill in francs paid with a QR\n * reference (SIX's QR-bill guidelines 2.8, 2.10): a transfer in euro with\n * a creditor reference or none is not one it is credited by. That rule is\n * SIX's, not the EPC's, and its range is the QR-bill's (`isQrIban`).\n *\n * An e-invoice's payment account (BT-84) is held by this rule too\n * (`en16931.ts`): every credit transfer it writes is paid in euro, and an\n * invoice that prints an EPC QR code beside it names one account.\n */\nexport function checkEpcIban(text: string): PaymentCheck<string> {\n const written = withoutSpaces(text)\n if (!IBAN.test(written)) return no('is not an IBAN: two letters for its country, two check digits, then letters or digits')\n const iban = written.toUpperCase()\n const country = sepaCountry(iban.slice(0, 2))\n if (country === undefined) return no('is not the IBAN of an account in SEPA: its country is not one EPC409-09 lists')\n if (iban.length !== country.length) return no(`is ${iban.length} characters long, and an IBAN of its country has ${country.length} (SWIFT's IBAN Registry)`)\n const checked = checkIbanCheckDigits(iban)\n if (checked.ok && isQrIban(iban)) {\n return no(\n \"is a QR-IBAN, which SIX keeps for QR-bills in francs paid with a QR reference (SIX's QR-bill guidelines 2.8, 2.10), and a SEPA credit transfer in euro carries none\",\n )\n }\n return checked\n}\n\n/**\n * A BIC (ISO 9362): four letters or digits for the bank, two letters for\n * its country, two letters or digits for its place, and three for a branch\n * or none. The EPC types the element as 8 or 11 alphanumeric characters\n * (2.2, \"8/11an\"), so a digit is taken in the bank's four, where\n * Wikipedia's article on ISO 9362 gives four letters; SWIFT's own text,\n * which would decide it, could not be read (17 October 2026).\n */\nconst BIC = /^[A-Z0-9]{4}[A-Z]{2}[A-Z0-9]{2}(?:[A-Z0-9]{3})?$/\n\n/** The BIC of the beneficiary's bank (EPC 2.2, AT-C002), of a bank in SEPA. */\nexport function checkEpcBic(text: string): PaymentCheck<string> {\n if (!BIC.test(text)) {\n return no(\n 'is not a BIC: four letters or digits for the bank, two letters for its country, two letters or digits for its place, and three for a branch or none (ISO 9362)',\n )\n }\n if (sepaIbanCountryOfBic(text.slice(4, 6)) === undefined) return no('is not the BIC of a bank in SEPA: its country is not one EPC409-09 lists')\n return ok(text)\n}\n\n/** A rule an IBAN and a BIC break together, reported on the BIC. */\nexport interface EpcPairingBreak {\n readonly field: 'bic'\n readonly rule: string\n}\n\n/**\n * The rules an IBAN and a BIC break together. An account outside the EEA\n * is paid to with its bank's BIC: version 002 lets a code leave the BIC\n * out, and \"the BIC will continue to be mandatory for SEPA payment\n * transactions involving SCT scheme participants from non-EEA countries\"\n * (EPC 2.2). Those participants are the payer's bank as well as the\n * beneficiary's, and the payer is not known here: only the account's side\n * is held.\n *\n * And a BIC is of the account's country, by the territory codes EPC409-09\n * gives each country's BICs and IBANs (5). That pairing is this module's\n * inference, so that a BIC typed for the wrong country is refused: neither\n * EPC document says an account's bank has a BIC of the account's country,\n * and one whose bank's BIC is another country's is refused too. `bic` is\n * null when the code has none; an IBAN or a BIC that is not known -- read\n * from data, before a render, or already refused -- is undefined, and\n * nothing is said of it.\n */\nexport function epcPairing(iban: string | undefined, bic: string | null | undefined): readonly EpcPairingBreak[] {\n if (iban === undefined) return []\n const country = iban.slice(0, 2)\n if (bic === null) {\n if (sepaCountry(country)?.eea !== false) return []\n return [\n {\n field: 'bic',\n rule: \"an account outside the EEA is paid to with its bank's BIC: EPC069-12 2.2 keeps the BIC mandatory where SCT scheme participants from non-EEA countries take part\",\n },\n ]\n }\n if (bic === undefined || sepaIbanCountryOfBic(bic.slice(4, 6)) === country) return []\n return [{ field: 'bic', rule: \"the BIC is of a bank in another country than the IBAN's account (EPC409-09 5 gives each country's BICs and IBANs)\" }]\n}\n\n/**\n * The structured remittance information (EPC 2.2, AT-T009): \"ISO 11649 RF\n * Creditor Reference may be used\", and it is the one structured reference\n * this code takes. Checked as a QR-bill's creditor reference is, and then\n * made capitals, as the IBAN's letters are -- after they are known to be A\n * to Z. The EPC marks the reference as one the payer should not change\n * (2.2, \"Fixed\") and says nothing of its case, so it is written in one\n * case, not left to each banking app; a QR-bill keeps the case it was\n * written in, as SIX says banks draw no distinction.\n */\nexport function checkEpcReference(text: string): PaymentCheck<string> {\n const checked = checkCreditorReference(\n text,\n 'is not a creditor reference: RF, two check digits and up to 21 letters or digits (ISO 11649), the one structured reference this code holds',\n )\n return checked.ok ? ok(checked.value.toUpperCase()) : checked\n}\n\n/** What a free text of the code may hold: how many characters. */\nexport interface EpcTextRule {\n /** Characters, as the EPC counts them: code points, whatever their bytes. */\n readonly max: number\n}\n\n/** The beneficiary's name (EPC 2.2, AT-E001): at most 70 characters. */\nexport const EPC_BENEFICIARY_RULE: EpcTextRule = { max: 70 }\n\n/** The unstructured remittance information (EPC 2.2, AT-T009): at most 140 characters. */\nexport const EPC_TEXT_RULE: EpcTextRule = { max: 140 }\n\n/** The beneficiary to originator information (EPC 2.2): at most 70 characters, shown to the payer and not sent on (PSA 3, note 8). */\nexport const EPC_INFORMATION_RULE: EpcTextRule = { max: 70 }\n\n/**\n * Whether a code point is one no text may hold: a control character -- C0,\n * DEL or C1, the line feed and carriage return that separate the code's\n * elements among them (EPC 2.2) -- or the line or paragraph separator a\n * reader may break a line at.\n */\nfunction breaksLine(codePoint: number): boolean {\n return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) || codePoint === 0x2028 || codePoint === 0x2029\n}\n\n/** Whether a code point is half of a surrogate pair, which UTF-8 cannot write. */\nfunction half(codePoint: number): boolean {\n return codePoint >= 0xd800 && codePoint <= 0xdfff\n}\n\n/**\n * A free text of the code, checked against `rule`: its characters and its\n * length. The EPC names character sets (2.1) and no narrower one, so in\n * UTF-8 any character is taken but a control character, a line break or\n * half of one: any of them would end the text's element early, or be\n * written as something else. The first is named by its position, counted\n * in characters from 1, and never quoted. A text is not trimmed: the EPC\n * asks for nothing of the kind. Whether it may be blank is its field's\n * question (`checkEpcField`).\n */\nexport function checkEpcText(text: string, rule: EpcTextRule): PaymentCheck<string> {\n const characters = [...text]\n for (const [index, character] of characters.entries()) {\n const codePoint = character.codePointAt(0) as number\n if (breaksLine(codePoint)) return no(`holds a control character or a line break at character ${index + 1}, which would end its line of the code early`)\n if (half(codePoint)) return no(`holds half of a character at character ${index + 1}, which UTF-8 cannot write`)\n }\n if (characters.length > rule.max) return no(`is ${characters.length} characters long; the EPC allows at most ${rule.max}`)\n return ok(text)\n}\n\n/** The texts a code holds, by their names in its component, in the order its payload holds them. */\nexport type EpcTextField = 'bic' | 'beneficiary' | 'iban' | 'reference' | 'text' | 'information'\n\n/** How a text of the code is held: what a refusal calls it, whether the code may leave its element unused, and the rule it is held to when it holds one. */\nexport interface EpcTextFieldRule {\n readonly what: string\n readonly optional: boolean\n readonly check: (text: string) => PaymentCheck<string>\n}\n\n/**\n * Each text of the code (EPC 2.2): the name and the IBAN mandatory, the\n * BIC, the reference, the text and the information optional. One table,\n * which the validator reads for a literal text and the runtime for one the\n * data resolved: two could call a field two things, or disagree about\n * which one a code may leave out, and nobody would find out.\n */\nexport const EPC_TEXT_FIELDS: { readonly [K in EpcTextField]: EpcTextFieldRule } = {\n bic: { what: 'the BIC', optional: true, check: checkEpcBic },\n beneficiary: { what: \"the beneficiary's name\", optional: false, check: (text) => checkEpcText(text, EPC_BENEFICIARY_RULE) },\n iban: { what: 'the IBAN', optional: false, check: checkEpcIban },\n reference: { what: 'the reference', optional: true, check: checkEpcReference },\n text: { what: 'the text', optional: true, check: (text) => checkEpcText(text, EPC_TEXT_RULE) },\n information: { what: 'the information', optional: true, check: (text) => checkEpcText(text, EPC_INFORMATION_RULE) },\n}\n\n/** Whether a text prints nothing a payer reads: empty, or white space alone. */\nexport function epcBlank(text: string): boolean {\n return text.trim() === ''\n}\n\n/**\n * The text of `field`, held to its rule. An element the code holds has one\n * character at least (EPC 2.2: \"1..70an\", \"1..140an\"), so a blank text is\n * refused: a required one as needed, an optional one as the element left\n * out, written a second way. That is what the validator says of a literal;\n * an optional text the data resolves to blank is its element unused\n * instead, which the runtime decides by `epcBlank` before it asks here.\n */\nexport function checkEpcField(field: EpcTextField, text: string): PaymentCheck<string> {\n const { optional, check } = EPC_TEXT_FIELDS[field]\n if (!epcBlank(text)) return check(text)\n return no(\n optional\n ? 'is blank, and an element the code holds has one character at least (EPC069-12 2.2): a text the code does not hold is left out'\n : 'is empty, and an EPC QR code needs it',\n )\n}\n\n/**\n * The purpose of the transfer (EPC 2.2, AT-T007): a purpose code, four\n * capital letters, as ISO 20022 writes one and the EPC's sample, GDDS, is.\n */\nexport function checkEpcPurpose(code: string): PaymentCheck<string> {\n return /^[A-Z]{4}$/.test(code) ? ok(code) : no('is not a purpose code: four capital letters, as ISO 20022 writes one, such as GDDS')\n}\n\n/** The most digits before the point: 999999999.99 is the largest amount (EPC 2.2). */\nconst MAX_WHOLE_DIGITS = 9\n\n/**\n * The amount in euro (EPC 2.2, AT-T002), as the code writes it after `EUR`:\n * from 0.01 to 999999999.99, a point and at most two decimals, and \"as\n * short as possible\" (PSA 3, note 5) -- no trailing zero after the point,\n * no point without a decimal after it, and no leading zero, which `DECIMAL`\n * admits none of. Written from the exact decimal's own digits, never a\n * JavaScript number. Never rounded: an amount written with more than two\n * decimals is refused, a third decimal of zero among them, so that a\n * template that does not round is refused on its first render.\n */\nexport function checkEpcAmount(decimal: string): PaymentCheck<string> {\n if (!DECIMAL.test(decimal)) return no('is not a decimal')\n const [whole = '', fraction = ''] = decimal.replace(/^-/, '').split('.')\n if (fraction.length > 2) return no('has more than two decimals; a SEPA credit transfer pays whole cents, so the amount is rounded where it is computed')\n const decimals = fraction.replace(/0+$/, '')\n if (decimal.startsWith('-') || whole.length > MAX_WHOLE_DIGITS || (whole === '0' && decimals === '')) {\n return no('is not from 0.01 to 999999999.99, the amounts an EPC QR code pays (EPC069-12 2.2)')\n }\n return ok(decimals === '' ? whole : `${whole}.${decimals}`)\n}\n\n/**\n * What a payload holds, each already checked: absent, undefined or empty is\n * an element the code leaves unused. A reference and a text are never both\n * given: only one of the two may be populated (EPC 2.2, {Or}), which the\n * validator holds a code to.\n */\nexport interface EpcPayloadFields {\n readonly bic?: string | undefined\n readonly beneficiary: string\n readonly iban: string\n /** As `checkEpcAmount` writes it, without `EUR`. */\n readonly amount?: string | undefined\n readonly purpose?: string | undefined\n readonly reference?: string | undefined\n readonly text?: string | undefined\n readonly information?: string | undefined\n}\n\n/**\n * The text the code encodes (EPC 2.2): the service tag `BCD`, the version,\n * the character set `1` for UTF-8, the identification `SCT`, then the\n * BIC, the name, the IBAN, the amount in euro, the purpose, the reference,\n * the text and the information, each on its own line, separated by a line\n * feed. Every element up to the last the code holds is a line, empty when\n * it is unused, and \"the last populated element is not followed by any\n * character or element separator\" (EPC 2.2; PSA 3).\n *\n * A code with a BIC is written as version 001, as the EPC's first sample\n * is, and one without as 002, the version that lets the BIC be left empty.\n * That a reader of either version takes 001 is a reading of the two\n * versions (0025), not something a test here shows.\n */\nexport function epcPayload(fields: EpcPayloadFields): string {\n const bic = fields.bic ?? ''\n const amount = fields.amount === undefined || fields.amount === '' ? '' : `EUR${fields.amount}`\n const elements = [\n 'BCD',\n bic === '' ? '002' : '001',\n '1',\n 'SCT',\n bic,\n fields.beneficiary,\n fields.iban,\n amount,\n fields.purpose ?? '',\n fields.reference ?? '',\n fields.text ?? '',\n fields.information ?? '',\n ]\n let last = elements.length\n while (last > 0 && elements[last - 1] === '') last -= 1\n return elements.slice(0, last).join('\\n')\n}\n\n/** How many bytes UTF-8 writes `text` in: one to four for each code point. */\nexport function utf8Length(text: string): number {\n let bytes = 0\n for (const character of text) {\n const codePoint = character.codePointAt(0) as number\n bytes += codePoint < 0x80 ? 1 : codePoint < 0x800 ? 2 : codePoint < 0x10000 ? 3 : 4\n }\n return bytes\n}\n\n/** A whole payload, held to the 331 bytes the EPC allows (2.2), counted in UTF-8's bytes and not in characters. */\nexport function checkEpcPayload(payload: string): PaymentCheck<string> {\n const bytes = utf8Length(payload)\n if (bytes <= EPC_MAX_BYTES) return ok(payload)\n return no(`is ${bytes} bytes long in UTF-8; the EPC allows at most ${EPC_MAX_BYTES} (EPC069-12 2.2), what a version 13 code holds at level M`)\n}\n","/**\n * How an EPC QR code is printed: the side of its modules in the square it\n * stands in, and, with Austria's caption, the frame and the words around\n * it and the modules' widths the PSA allows (\"QR-Code und BCD Definition\",\n * PSA version 3.0, section 5, and its figure there).\n *\n * The EPC gives no size and no caption (EPC069-12 v3.1): a code without\n * the caption is drawn as a QR code is (0020), its quiet zone of four\n * modules inside its square, and held by the renderer to the same 0.4 mm\n * floor. The caption brings the PSA's rules with it, and they are decided\n * here once: the validator applies them to a size, which no data changes,\n * for every version a code may have; the renderer to the version the\n * encoder chose. Two copies could disagree about which sizes print, and\n * nobody would find out until a bank's app could not read one.\n */\nimport type { EpcCaption } from './epc-qr-code.js'\nimport { MILLIMETRES_PER_INCH, POINTS_PER_INCH } from './units.js'\n\n/** The largest version a code may have: 69 modules a side, which holds 331 bytes at level M (EPC069-12 2.1). */\nexport const EPC_MAX_VERSION = 13\n\n/** The modules a side of a symbol of `version` has: \"QR-Code Version*4+17\" (PSA 2; ISO/IEC 18004). */\nexport function qrSymbolModules(version: number): number {\n return 4 * version + 17\n}\n\n/**\n * The frame around a captioned code, in modules (PSA 5's figure): four\n * between the symbol and the frame -- \"Distance = 4 * m\" -- and between\n * the symbol and the caption, which the figure asks \"min. 3 * m\" of: four\n * meets both, and keeps ISO/IEC 18004's quiet zone of four clear of the\n * caption. The corner's radius is \"r = 2 * m\". The line is at most \"0,8 *\n * m\" wide; half a module is drawn, clearly within it.\n */\nexport const EPC_FRAME = { distance: 4, radius: 2, line: 0.5 } as const\n\n/**\n * The caption (PSA 5): \"Zahlen mit Code\", \"to the right from bottom to\n * top\", at \"Font size min. 7pt\" in \"Arial o.s. non-serifs\" -- Liberation\n * Sans, the QR-bill's face, here. Its band, in points, is the room to the\n * right of the symbol's distance, to the square's edge: one em of the\n * caption's size. It holds the caption's letters, which reach 0.725 em\n * above their baseline and 0.01 em below it in Liberation Sans 2.1.5, and\n * the frame's right line, which runs along the caption's baseline and is\n * broken where the caption stands, as in the PSA's figure.\n *\n * Its advance, in ems, is its fifteen glyphs' in Liberation Sans 2.1.5:\n * 15026 of the face's 2048 units per em, as fontkit lays them out for\n * PDFKit, with no kerning between these letters -- 51.36 pt at 7 pt,\n * measured on 17 October 2026, and held to the PDF the renderer draws by\n * report-render-pdf's `epc-qr-code.test.ts`. The caption stands beside the\n * symbol, centred on it, and no longer than the symbol is tall, as in the\n * figure, so that the frame's right line is drawn above and below it.\n */\nexport const EPC_CAPTION = { words: 'Zahlen mit Code', size: 7, band: 7, advance: 15026 / 2048 } as const\n\n/**\n * The modules' widths the PSA prints, in millimetres: \"minimal ... 15 mil\",\n * \"shall not exceed 20 mil\" (PSA 5), a mil 0.0254 mm (PSA 2). They are\n * 1.08 and 1.44 points exactly, `MODULE_HUNDREDTHS`.\n */\nexport const EPC_CAPTION_MODULE = { least: 0.381, most: 0.508 } as const\n\n/** The PSA's modules in hundredths of a point: 15 and 20 mil, a mil 0.072 pt. */\nconst MODULE_HUNDREDTHS = { least: 108, most: 144 } as const\n\n/**\n * The side, in points, of one module of a code of `version` in a square of\n * `size`. Without a caption, the square holds the symbol and its quiet zone\n * of four modules a side, as a QR code's does (0020). With one, it holds,\n * from the left, the frame's line, the distance, the symbol, the distance\n * and the caption's band; down, the frame and the distance alone, which\n * take less room than the band does across.\n */\nexport function epcModule(size: number, version: number, caption: EpcCaption | undefined): number {\n const symbol = qrSymbolModules(version)\n if (caption === undefined) return size / (symbol + 8)\n return (size - EPC_CAPTION.band) / (EPC_FRAME.line + 2 * EPC_FRAME.distance + symbol)\n}\n\n/** Twice the modules across a captioned code of `version`, its frame's line and distances counted: a whole number, so that the bounds compare exactly. */\nfunction twiceAcross(version: number): number {\n return 2 * (EPC_FRAME.line + 2 * EPC_FRAME.distance + qrSymbolModules(version))\n}\n\n/** A size in the whole hundredths of a point it is stored in. */\nconst hundredths = (size: number): number => Math.round(size * 100)\n\n/** The caption's band in hundredths of a point. */\nconst BAND = EPC_CAPTION.band * 100\n\n/** Whether a captioned code of `version` in a square of `size` has modules of at least 15 mil, or at most 20, compared in whole hundredths. */\nfunction modulesAre(size: number, version: number, bound: 'least' | 'most'): boolean {\n const room = 2 * (hundredths(size) - BAND)\n const limit = MODULE_HUNDREDTHS[bound] * twiceAcross(version)\n return bound === 'least' ? room >= limit : room <= limit\n}\n\n/** The caption's length in hundredths of a point: its advance at its size, exact, as every multiple of a 2048th is in binary. */\nconst CAPTION_HUNDREDTHS = EPC_CAPTION.advance * EPC_CAPTION.size * 100\n\n/**\n * Whether the symbol of a captioned code of `version` in a square of\n * `size` is as tall as the caption beside it. The symbol is its modules\n * times a module, `2 * symbol * (size - band) / twiceAcross`; compared\n * with the caption's length without the division, exactly.\n */\nfunction captionBeside(size: number, version: number): boolean {\n return CAPTION_HUNDREDTHS * twiceAcross(version) <= 2 * qrSymbolModules(version) * (hundredths(size) - BAND)\n}\n\n/** Whether a captioned code of `version` prints in a square of `size`: its modules from 15 to 20 mil, and its symbol as tall as its caption. */\nfunction prints(size: number, version: number): boolean {\n return modulesAre(size, version, 'least') && modulesAre(size, version, 'most') && captionBeside(size, version)\n}\n\n/** Every version a code may have, from the smallest. */\nconst VERSIONS: readonly number[] = Array.from({ length: EPC_MAX_VERSION }, (_, index) => index + 1)\n\n/**\n * The squares some version prints a captioned code in, in hundredths of a\n * point. Each version prints from where its modules are 15 mil and its\n * symbol as tall as the caption, to where its modules are 20 mil; a\n * version whose symbol is shorter than the caption even at 20 mil starts\n * past where it ends, and above where a larger version starts. The runs\n * of the versions from 1 to 13 overlap into one, from the least start to\n * version 13's end, which `epc-print.test.ts` holds for every size: a size\n * outside it is refused, and none inside.\n */\nconst CAPTION_SQUARES = {\n least: Math.min(\n ...VERSIONS.map((version) => {\n const across = twiceAcross(version)\n return Math.max(BAND + (MODULE_HUNDREDTHS.least * across) / 2, BAND + Math.ceil((CAPTION_HUNDREDTHS * across) / (2 * qrSymbolModules(version))))\n }),\n ),\n most: BAND + (MODULE_HUNDREDTHS.most * twiceAcross(EPC_MAX_VERSION)) / 2,\n} as const\n\n/**\n * The least version a code is drawn at in a square of `size`. Without the\n * caption, 1: the encoder takes the smallest that holds the payload, as\n * for a QR code. With it, the least whose modules are at most 20 mil and\n * whose symbol is as tall as the caption, so that a payload too short for\n * the square is drawn in a larger version of itself, at the same level,\n * rather than refused; none where even version 13's modules are over 20\n * mil. Whether the version the payload then needs has modules of 15 mil\n * or more is `epcCaptionBreak`'s to say.\n */\nexport function epcLeastVersion(size: number, caption: EpcCaption | undefined): number | undefined {\n if (caption === undefined) return 1\n return VERSIONS.find((version) => modulesAre(size, version, 'most') && captionBeside(size, version))\n}\n\n/**\n * A module's width in millimetres, said to the thousandth on the side of\n * the bound it breaks, so that one past a bound never reads as the bound;\n * none at all where the square is narrower than the caption's band.\n */\nfunction said(size: number, version: number, past: 'under' | 'over'): string {\n const width = Math.max(0, (epcModule(size, version, 'zahlenMitCode') * MILLIMETRES_PER_INCH) / POINTS_PER_INCH)\n const rounded = past === 'under' ? Math.floor(width * 1000 + 1e-9) : Math.ceil(width * 1000 - 1e-9)\n return (rounded / 1000).toFixed(3)\n}\n\n/** Hundredths of a point as points, to the hundredth. */\nconst points = (value: number): string => (value / 100).toFixed(2)\n\n/** The caption, its size and its length, rounded up, as a refusal names it. */\nconst CAPTION_SAID = `\"${EPC_CAPTION.words}\" at ${EPC_CAPTION.size} pt, ${points(Math.ceil(CAPTION_HUNDREDTHS))} pt long`\n\n/**\n * The rule a captioned code in a square of `size` breaks, or undefined. A\n * render passes the version the encoder chose, and the rules are that\n * version's: modules from 15 to 20 mil, and a symbol as tall as the\n * caption. The validator knows no version and passes none, and refuses\n * only a size in which no version from 1 to 13 prints, naming the run of\n * sizes some version does. Sizes are compared in the hundredths of a point\n * they are stored in, exactly.\n */\nexport function epcCaptionBreak(size: number, version?: number): string | undefined {\n const square = `in a square of ${size} pt`\n if (version === undefined) {\n if (VERSIONS.some((each) => prints(size, each))) return undefined\n return hundredths(size) < CAPTION_SQUARES.least\n ? `with the caption, a code needs a square of at least ${points(CAPTION_SQUARES.least)} pt, and this one is ${size} pt: in a smaller one, no symbol with modules of 0.381 mm (15 mil) or more is as tall as the caption beside it, ${CAPTION_SAID}`\n : `with the caption, a code needs a square of at most ${points(CAPTION_SQUARES.most)} pt, and this one is ${size} pt: in a larger one, even a version ${EPC_MAX_VERSION} code, the largest the EPC allows, has modules over 0.508 mm (20 mil), the widest the PSA prints`\n }\n if (!modulesAre(size, version, 'least') || !modulesAre(size, version, 'most')) {\n const past = modulesAre(size, version, 'least') ? 'over' : 'under'\n return `with the caption, this version ${version} code has modules of ${said(size, version, past)} mm ${square}; the PSA prints them from 0.381 to 0.508 mm (15 to 20 mil) wide`\n }\n if (!captionBeside(size, version)) {\n const tall = Math.floor(qrSymbolModules(version) * epcModule(size, version, 'zahlenMitCode') * 100 + 1e-9)\n return `with the caption, this version ${version} code's symbol is ${points(tall)} pt tall ${square}, shorter than the caption beside it, ${CAPTION_SAID}`\n }\n return undefined\n}\n","/**\n * The e-invoice a report may carry: one EN 16931 invoice, written by the\n * runtime as CII from the very values the page prints (0027), of one of two\n * kinds: Factur-X 1.09.2 / ZUGFeRD 2.5.2 in the EN 16931 profile, the\n * hybrid a PDF/A-3b embeds (0031); or XRechnung 3.0, KoSIT's CIUS of EN\n * 16931 a German public buyer asks for, whose XML is the invoice and whose\n * PDF a copy (0038).\n *\n * It belongs to the report, not to a region, as a payment part does (0022):\n * one invoice per PDF. Its texts are runs, read as a paragraph's in the\n * report's scope and resolved whole before there are pages, since the XML\n * holds every one of them: none holds a page number or count. Its lines are\n * the rows of the report's table over the detail dataset: four of the\n * table's columns print each line's name, quantity, net price and net\n * amount, and the XML is written from what they resolved to, so the page and\n * the file read one evaluation of each line. The line's identifier, its unit\n * and its VAT category are codes a page need not print, read from each row.\n *\n * What each text may hold, and which of EN 16931's rules a value breaks,\n * `en16931.ts` says; the validator applies those rules to a text no data can\n * change, the runtime to every text once the data has resolved it.\n *\n * \"BT\" and \"BG\" are EN 16931's business terms and groups, \"BR\" its business\n * rules, as CEN/TC 434's CII artefacts 1.3.17 name them. Where a value\n * below is marked [S], it rests on phax/kaltblut's transcription of the\n * Factur-X 1.09.2 specification, which was not itself read: it is behind a\n * registration that has not been made.\n */\nimport type { RowValue } from './aggregates.js'\nimport type { Expression, Inline } from './values.js'\n\n/** The kinds of e-invoice. A kind this version does not know is refused, never skipped. */\nexport const E_INVOICE_KINDS = ['facturX', 'xrechnung'] as const\nexport type EInvoiceKind = (typeof E_INVOICE_KINDS)[number]\n\n/** The XRechnung versions this version writes: 3.0, the major and minor version its BT-24 names, of which KoSIT's 3.0.2 is the release the e-invoice gate's configuration pins. 4.0 is not backward compatible, and waits. */\nexport const XRECHNUNG_VERSIONS = ['3.0'] as const\nexport type XRechnungVersion = (typeof XRECHNUNG_VERSIONS)[number]\n\n/** What names each XRechnung version: its specification identifier (BT-24), the release of KoSIT's it is read from, and the syntax it is written in. */\nexport interface XRechnungTerms {\n /** BT-24: `XR-CIUS-ID` of KoSIT's XRechnung schematron, which its scenario `EN16931 XRechnung (CII)` matches the XML by. */\n readonly guideline: string\n /** The release of KoSIT's XRechnung the gate's configuration pins (`docs/release/e-invoice-tools.json`), which the e-invoice gate holds it to on every run. */\n readonly release: string\n /** CII, the one syntax the runtime writes: UBL, which KoSIT takes too, would be a second writer of one invoice (0027, 0038). */\n readonly syntax: 'cii'\n}\n\n/**\n * Each version's names. A table over every version, so a version added to\n * `XRECHNUNG_VERSIONS` without them does not compile. BT-24 is\n * `XR-CIUS-ID` as `resources/xrechnung/3.0.2/xsl/XRechnung-CII-validation.xsl`\n * of KoSIT's configuration of 2026-08-31 builds it, read on 21 October\n * 2026; the e-invoice gate holds it to that file on every run, and KoSIT\n * matches the XRechnung sample to its scenario by it.\n */\nexport const XRECHNUNG: { readonly [V in XRechnungVersion]: XRechnungTerms } = {\n '3.0': { guideline: 'urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0', release: '3.0.2', syntax: 'cii' },\n}\n\n/** The Factur-X profiles this version writes: EN 16931 alone, which Germany counts as an e-invoice and FeRD recommends. */\nexport const E_INVOICE_PROFILES = ['en16931'] as const\nexport type EInvoiceProfile = (typeof E_INVOICE_PROFILES)[number]\n\n/** The invoice type codes (BT-3, UNTDID 1001) this version writes: 380, a commercial invoice. No credit note yet. */\nexport const INVOICE_TYPE_CODES = ['380'] as const\nexport type InvoiceTypeCode = (typeof INVOICE_TYPE_CODES)[number]\n\n/** The currencies (BT-5, ISO 4217) this version writes: EUR. A second would bring BT-6 and BT-111 with it. */\nexport const E_INVOICE_CURRENCIES = ['EUR'] as const\nexport type EInvoiceCurrency = (typeof E_INVOICE_CURRENCIES)[number]\n\n/**\n * The VAT categories (BT-118, BT-151; UNCL 5305) this version writes:\n * standard rated, exempt from VAT, and reverse charge. CEN's BR-CL-17 and\n * BR-CL-18 take seven more, Z, K, G, O, L, M and B, which wait.\n */\nexport const VAT_CATEGORY_CODES = ['S', 'E', 'AE'] as const\nexport type VatCategoryCode = (typeof VAT_CATEGORY_CODES)[number]\n\n/** The payment means (BT-81, UNTDID 4461) this version writes: 58, a SEPA credit transfer, and 30, a credit transfer. */\nexport const PAYMENT_MEANS_CODES = ['58', '30'] as const\nexport type PaymentMeansCode = (typeof PAYMENT_MEANS_CODES)[number]\n\n/*\n * The closed lists. CEN's code-list rules are fatal, so a code outside its\n * list makes a file every validator refuses. Each list here is chosen and\n * narrower than CEN's: only a code someone chose is written. Every code was\n * found, on 17 October 2026, in the list of CEN/TC 434's CII artefacts\n * 1.3.17 (`schematron/codelist/EN16931-CII-codes.sch` in its\n * `en16931-cii-1.3.17.zip`)\n * and in that of the 1.3.16 artefacts KoSIT's XRechnung configuration of\n * 2026-08-31 runs; the e-invoice gate holds each list to its pinned\n * schematron's on every run. The meanings are UN/ECE's and ISO's, as\n * Peppol BIS Billing 3.0's code lists (May 2026 release) print them, read\n * the same day. Which codes to take, and whether copying them out of CEN's\n * artefact, which is EUPL-1.2, is acceptable under 0006, are the owner's\n * questions (0027).\n */\n\n/**\n * The units of measure (BT-130; UN/ECE Recommendation 20, revision 11e) a\n * line's quantity may be in, and no other (BR-CL-23): the counted, time,\n * mass, length, area, volume and energy units a German invoice is written\n * in. CEN takes 2,162; the packaging codes of Recommendation 21 among them\n * wait.\n */\nexport const UNIT_CODES = [\n 'C62', // one (synonym: unit)\n 'H87', // piece\n 'SET', // set\n 'PR', // pair\n 'LS', // lump sum\n 'MIN', // minute\n 'HUR', // hour\n 'DAY', // day\n 'WEE', // week\n 'MON', // month\n 'ANN', // year\n 'GRM', // gram\n 'KGM', // kilogram\n 'TNE', // tonne (metric ton)\n 'MTR', // metre\n 'KMT', // kilometre\n 'MTK', // square metre\n 'MTQ', // cubic metre\n 'MLT', // millilitre\n 'LTR', // litre\n 'KWH', // kilowatt hour\n] as const\nexport type UnitCode = (typeof UNIT_CODES)[number]\n\n/**\n * The countries (BT-40, BT-55; ISO 3166-1 alpha-2) a seller or a buyer may\n * be in, and no other (BR-CL-14): the 27 member states of the EU, the EEA's\n * Iceland, Liechtenstein and Norway, Switzerland, and the United Kingdom.\n * CEN takes 251. Greece is GR here, and EL only as a VAT prefix.\n */\nexport const COUNTRY_CODES = [\n 'AT', // Austria\n 'BE', // Belgium\n 'BG', // Bulgaria\n 'CY', // Cyprus\n 'CZ', // Czechia\n 'DE', // Germany\n 'DK', // Denmark\n 'EE', // Estonia\n 'ES', // Spain\n 'FI', // Finland\n 'FR', // France\n 'GR', // Greece\n 'HR', // Croatia\n 'HU', // Hungary\n 'IE', // Ireland\n 'IT', // Italy\n 'LT', // Lithuania\n 'LU', // Luxembourg\n 'LV', // Latvia\n 'MT', // Malta\n 'NL', // Netherlands\n 'PL', // Poland\n 'PT', // Portugal\n 'RO', // Romania\n 'SE', // Sweden\n 'SI', // Slovenia\n 'SK', // Slovakia\n 'IS', // Iceland\n 'LI', // Liechtenstein\n 'NO', // Norway\n 'CH', // Switzerland\n 'GB', // United Kingdom\n] as const\nexport type CountryCode = (typeof COUNTRY_CODES)[number]\n\n/**\n * The prefixes a VAT identifier (BT-31, BT-48) may begin with (BR-CO-09):\n * a country of `COUNTRY_CODES`, or EL, which Greece writes its VAT\n * identifiers with. BR-CO-09's message allows EL in both releases, but only\n * 1.3.16's test, which the pinned validators run, holds it; 1.3.17's does\n * not. EL is taken while the pinned oracle takes it, and the gate fails on\n * the release that does not.\n */\nexport const VAT_PREFIXES: readonly string[] = [...COUNTRY_CODES, 'EL']\n\n/**\n * The schemes (BT-30-1, BT-47-1; ISO 6523 ICD) a legal registration\n * identifier may be given in, and no other (BR-CL-11). An identifier may be\n * given without one, as a German commercial register number is. France's\n * SIREN and SIRET, since a French buyer's SIREN is the one detail of\n * France's the XML holds; and the two that name a company anywhere. CEN\n * takes 246. The Leitweg-ID, 0204, which routes an invoice to a German\n * public buyer, is no legal registration: an XRechnung names it as the\n * buyer's reference (BT-10) and as an electronic address\n * (`ADDRESS_SCHEMES`, 0038).\n */\nexport const SCHEME_IDS = [\n '0002', // System Information et Repertoire des Entreprise et des Etablissements: SIRENE\n '0009', // SIRET-CODE\n '0060', // Data Universal Numbering System (D-U-N-S Number)\n '0088', // EAN Location Code (GS1's Global Location Number)\n] as const\nexport type SchemeId = (typeof SCHEME_IDS)[number]\n\n/**\n * The schemes (BT-34-1, BT-49-1; the CEF's Electronic Address Scheme code\n * list) an electronic address may be given in, and no other (BR-CL-25),\n * each code found on 20 October 2026 in BR-CL-25's list of the CEN 1.3.16\n * schematron KoSIT's configuration of 2026-08-31 runs and in list 17 of\n * FeRD's code database in Mustang 2.26.0, which the e-invoice gate holds\n * them to on every run (0037). CEN's list holds 104 codes and FeRD's 102,\n * counted that day; these are the five a German or a French invoice is\n * addressed by, their meanings as Peppol's EAS code list gives them:\n */\nexport const ADDRESS_SCHEMES = [\n 'EM', // an email address\n '0204', // the Leitweg-ID, which a German public buyer is reached by\n '0225', // France's electronic addressing scheme (FRCTC ELECTRONIC ADDRESS)\n '9930', // a German VAT identifier\n '0088', // EAN Location Code (GS1's Global Location Number)\n] as const\nexport type AddressScheme = (typeof ADDRESS_SCHEMES)[number]\n\n/** What names each profile, in the XML and in the PDF that carries it. */\nexport interface FacturXProfileTerms {\n /** The specification identifier (BT-24), which the XML opens with. */\n readonly guideline: string\n /** The XMP's `fx:ConformanceLevel` [S]. */\n readonly conformanceLevel: string\n /** The embedded file's `/AFRelationship` [S]. */\n readonly relationship: 'Alternative'\n}\n\n/**\n * Each profile's names. A table over every profile, so a profile added to\n * `E_INVOICE_PROFILES` without them does not compile.\n * - BT-24 is the EN 16931 profile's identifier as the Factur-X 1.09.2\n * schematron's code list 1 gives it (`FACTUR-X_EN16931_codedb.xml`, read\n * in akretion's copy). Mustang refuses the old `urn:factur-x.eu:1p0:en16931`.\n * - `Alternative` is Germany's relationship for EN 16931, and one of the\n * three France allows [S].\n */\nexport const FACTUR_X_PROFILES: { readonly [P in EInvoiceProfile]: FacturXProfileTerms } = {\n en16931: { guideline: 'urn:cen.eu:en16931:2017', conformanceLevel: 'EN 16931', relationship: 'Alternative' },\n}\n\n/**\n * The file a Factur-X PDF embeds, and the XMP that describes it [S]: the\n * name, the media type, the fx extension's namespace (its trailing `#`\n * required) and prefix, and the document type and the version it states.\n * The namespace is the transcription's section 6.3.1; its BR-HYBRID-04\n * gives it without `:invoice`, an inconsistency the transcription resolves\n * for section 6.3.1, as akretion's generator and PDFlib's sample do (0031).\n * No validator checks the namespace: Mustang reads the four properties by\n * local name, and veraPDF checks only that the extension schema describes\n * them. The renderer embeds what these say (0031), and its test holds the\n * PDF to the transcription's values, written there and not read from here;\n * the official package's XMP example, which would hold them to more, waits\n * for a registration with FeRD nobody here has made.\n */\nexport const FACTUR_X = {\n fileName: 'factur-x.xml',\n mediaType: 'text/xml',\n xmpNamespace: 'urn:factur-x:pdfa:CrossIndustryDocument:invoice:1p0#',\n xmpPrefix: 'fx',\n documentType: 'INVOICE',\n version: '1.0',\n} as const\n\n/**\n * The names an expression reads in a report that is an e-invoice, beside\n * `EXPRESSION_NAMES`'s, and in no other report (0027, an addition to\n * 0007's names): `invoice` holds the document's totals (BG-22), and\n * `vatBasis` and `vatAmount` each declared VAT category's taxable and tax\n * amount (BG-23) by the category's id, null when no line is in it. The\n * runtime computes each once, from the lines, for the page and the XML\n * alike. They are read wherever `totals` is, except where they are\n * computed from: an aggregate's expression, the e-invoice's own, and the\n * columns that print a line's terms. The editing core refuses a read\n * there, and in any other report.\n */\nexport const E_INVOICE_NAMES = ['invoice', 'vatBasis', 'vatAmount'] as const\nexport type EInvoiceName = (typeof E_INVOICE_NAMES)[number]\n\n/**\n * The members of `invoice`, each one of the document's totals (BG-22), as a\n * refusal names it: every one a decimal of two places in the invoice's\n * currency. With no allowances and no charges, the total without VAT is\n * the sum of the lines. `paid` is a member only of an invoice that\n * declares a paid amount, and is what that gives; with none, the amount\n * due is the total with VAT.\n */\nexport const INVOICE_TOTALS = {\n lineTotal: 'the sum of the invoice line net amounts (BT-106)',\n taxBasisTotal: 'the invoice total amount without VAT (BT-109)',\n taxTotal: 'the invoice total VAT amount (BT-110)',\n grandTotal: 'the invoice total amount with VAT (BT-112)',\n paid: 'the paid amount (BT-113)',\n duePayable: 'the amount due for payment (BT-115)',\n} as const\nexport type InvoiceTotal = keyof typeof INVOICE_TOTALS\n\n/** What `vatBasis` and `vatAmount` hold of each declared category, as a refusal names it. */\nexport const VAT_BREAKDOWN: { readonly [N in Exclude<EInvoiceName, 'invoice'>]: string } = {\n vatBasis: 'the VAT category taxable amount (BT-116)',\n vatAmount: 'the VAT category tax amount (BT-117)',\n}\n\n/**\n * A postal address (BG-5, BG-8): the first line, the post code, the city\n * and the country are needed, the second line may be left out. Each is\n * runs; the country is a code of `COUNTRY_CODES`.\n */\nexport interface EInvoiceAddress {\n readonly line1: readonly Inline[]\n readonly line2?: readonly Inline[]\n readonly postalCode: readonly Inline[]\n readonly city: readonly Inline[]\n readonly country: readonly Inline[]\n}\n\n/** A legal registration identifier (BT-30, BT-47), and the scheme it is given in, if one. */\nexport interface LegalIdentifier {\n readonly id: readonly Inline[]\n readonly scheme?: SchemeId\n}\n\n/**\n * An electronic address (BT-34, BT-49), where the party is sent the\n * invoice, and the scheme it is given in (BT-34-1, BT-49-1), which EN\n * 16931 needs with it (BR-62, BR-63): a code of `ADDRESS_SCHEMES`.\n */\nexport interface ElectronicAddress {\n readonly id: readonly Inline[]\n readonly scheme: AddressScheme\n}\n\n/**\n * The seller's contact (BG-6): its contact point (BT-41), a person or a\n * department, its telephone number (BT-42) and its email address (BT-43).\n * EN 16931 lets each be left out; a contact here gives all three, as\n * XRechnung asks (BR-DE-5, -6, -7), so that one contact serves either.\n */\nexport interface SellerContact {\n readonly name: readonly Inline[]\n readonly telephone: readonly Inline[]\n readonly email: readonly Inline[]\n}\n\n/** The seller (BG-4): its name (BT-27), its VAT identifier (BT-31), its tax number (BT-32), its legal registration (BT-30), its electronic address (BT-34), its contact (BG-6) and its address (BG-5). */\nexport interface EInvoiceSeller {\n readonly name: readonly Inline[]\n readonly vatId?: readonly Inline[]\n readonly taxNumber?: readonly Inline[]\n readonly legalId?: LegalIdentifier\n readonly electronicAddress?: ElectronicAddress\n readonly contact?: SellerContact\n readonly address: EInvoiceAddress\n}\n\n/** The buyer (BG-7): its name (BT-44), its VAT identifier (BT-48), its legal registration (BT-47), its electronic address (BT-49) and its address (BG-8). A buyer has no BT-32, and its contact (BG-9) is not written. */\nexport interface EInvoiceBuyer {\n readonly name: readonly Inline[]\n readonly vatId?: readonly Inline[]\n readonly legalId?: LegalIdentifier\n readonly electronicAddress?: ElectronicAddress\n readonly address: EInvoiceAddress\n}\n\n/**\n * A VAT category the invoice's lines are in, one VAT breakdown (BG-23) each\n * when a line uses it.\n */\nexport interface VatCategory {\n /** A field key: what the page reads its basis and its amount as, `vatBasis.<id>` and `vatAmount.<id>`, and what a line names it by. */\n readonly id: string\n readonly code: VatCategoryCode\n /** The rate in per cent (BT-119, BT-152), an exact decimal: more than 0 when standard rated, 0 otherwise. */\n readonly rate: string\n /** The exemption reason (BT-120): needed for E and AE, never for S. */\n readonly reason?: readonly Inline[]\n}\n\n/** The invoicing period (BG-14): its start (BT-73), its end (BT-74), or both. */\nexport interface InvoicingPeriod {\n readonly start?: Expression\n readonly end?: Expression\n}\n\n/**\n * The lines (BG-25), one per row of the table over the detail dataset. The\n * name, the quantity, the net price and the net amount are column ids of\n * that table: what each column prints, once per row, is what the line\n * holds. The identifier, the unit and the VAT category are read from each\n * row, as an aggregate reads it.\n */\nexport interface EInvoiceLines {\n /** The id of the table over the detail dataset. */\n readonly table: string\n /** The column that prints the item name (BT-153). */\n readonly name: string\n /** The column that prints the invoiced quantity (BT-129). */\n readonly quantity: string\n /** The column that prints the item net price (BT-146). */\n readonly netPrice: string\n /** The column that prints the line net amount (BT-131), a whole number of cents. */\n readonly netAmount: string\n /** The line identifier (BT-126). */\n readonly id: RowValue\n /** The unit of measure (BT-130), a code of `UNIT_CODES`. */\n readonly unit: RowValue\n /** The id of the line's VAT category (BT-151, BT-152): one the invoice declares. */\n readonly vat: RowValue\n}\n\n/** The payment instructions (BG-16): how the invoice is paid, and to which account. */\nexport interface PaymentInstructions {\n /** BT-81. */\n readonly means: PaymentMeansCode\n /** The payment account (BT-84): an IBAN. Spaces are for reading, and are dropped. */\n readonly iban: readonly Inline[]\n /** The BIC of the account's bank (BT-86). */\n readonly bic?: readonly Inline[]\n /** The account's name (BT-85). */\n readonly accountName?: readonly Inline[]\n /** The remittance information (BT-83): what a payer writes on the transfer. */\n readonly remittance?: readonly Inline[]\n}\n\n/**\n * What an invoice of either kind holds: EN 16931's terms, as 0027 and 0037\n * give them. Each text is runs, one at least where it is present; an\n * optional one absent is a term the XML leaves out, never an empty list of\n * runs, so that one invoice has one spelling and one hash. Each expression\n * is compiled and typed by the editing core: the dates are dates, the paid\n * amount a decimal.\n */\nexport interface EInvoiceTerms {\n /** BT-3. */\n readonly type: InvoiceTypeCode\n /** BT-5. */\n readonly currency: EInvoiceCurrency\n /** The invoice number (BT-1). */\n readonly number: readonly Inline[]\n /** The issue date (BT-2). */\n readonly issued: Expression\n /** The business process (BT-23): the context the buyer's system routes the invoice in, an identifier such as Peppol's `urn:fdc:peppol.eu:2017:poacc:billing:01:1.0`. */\n readonly businessProcess?: readonly Inline[]\n readonly seller: EInvoiceSeller\n readonly buyer: EInvoiceBuyer\n /** The buyer's reference (BT-10). */\n readonly buyerReference?: readonly Inline[]\n /** The actual delivery date (BT-72). A delivery date, a period or both: a German invoice says when it was supplied. */\n readonly delivered?: Expression\n readonly period?: InvoicingPeriod\n /** The VAT categories its lines may be in, one at least. */\n readonly vat: readonly VatCategory[]\n readonly lines: EInvoiceLines\n readonly payment?: PaymentInstructions\n /** The payment due date (BT-9). */\n readonly due?: Expression\n /** The payment terms (BT-20), where a Skonto is written. */\n readonly terms?: readonly Inline[]\n /** The amount already paid (BT-113), a whole number of cents. */\n readonly paid?: Expression\n}\n\n/** A Factur-X invoice in the EN 16931 profile: the hybrid whose XML a PDF/A-3b embeds (0031). */\nexport interface FacturXInvoice extends EInvoiceTerms {\n readonly kind: 'facturX'\n readonly profile: EInvoiceProfile\n}\n\n/**\n * An XRechnung (0038): EN 16931's terms in KoSIT's CIUS, written as CII,\n * with what its schematron needs past EN 16931 -- the business process\n * (PEPPOL-EN16931-R001), the buyer's reference (BR-DE-15), the payment\n * instructions (BR-DE-1), the seller's contact (BR-DE-2) and both\n * electronic addresses (PEPPOL-EN16931-R020, -R010) -- each needed here.\n * Its XML is the invoice; a PDF of it is a copy, and says so on every page.\n */\nexport interface XRechnungInvoice extends EInvoiceTerms {\n readonly kind: 'xrechnung'\n readonly version: XRechnungVersion\n readonly businessProcess: readonly Inline[]\n readonly seller: EInvoiceSeller & { readonly electronicAddress: ElectronicAddress; readonly contact: SellerContact }\n readonly buyer: EInvoiceBuyer & { readonly electronicAddress: ElectronicAddress }\n /** A public buyer's Leitweg-ID, or the reference a business buyer asks for. */\n readonly buyerReference: readonly Inline[]\n readonly payment: PaymentInstructions\n}\n\nexport type EInvoice = FacturXInvoice | XRechnungInvoice\n","/**\n * What KoSIT's XRechnung 3.0.2 asks of an e-invoice past EN 16931, as\n * report-spec holds it: of either kind, the shapes of the seller's contact\n * telephone number (BT-42) and email address (BT-43), each a warning of\n * KoSIT's XRechnung scenario, BR-DE-27 and BR-DE-28, which a file of either\n * kind is held to so that none earns it (0037); of an XRechnung (0038), the\n * terms its schematron needs that EN 16931 lets an invoice leave out\n * (`XRECHNUNG_NEEDS`, `XRECHNUNG_TEXT_NEEDS`) and the payment terms that\n * hold no Skonto line (`skontoBreak`, BR-DE-18); and of an electronic\n * address under 0204 in either, the Leitweg-ID's shape and check digits\n * (`leitwegIdBreak`), which no rule of XRechnung's checks. The rules the\n * plan names that nothing the format can say breaks are listed apart, with\n * what holds each (`XRECHNUNG_HELD`).\n *\n * Each shape is the pinned schematron's own expression, written here as\n * its variable writes it -- `XR-TELEPHONE-REGEX` and `XR-EMAIL-REGEX` in\n * `resources/xrechnung/3.0.2/xsl/XRechnung-CII-validation.xsl` of KoSIT's\n * configuration of 2026-08-31, read on 20 October 2026 -- and read as\n * XPath 2.0 reads it (`xpathRegExp`), after `normalize-space`, as the\n * rule's test reads it. The e-invoice gate holds each string, and the test\n * that reads it, to that file, and each id of `XRECHNUNG_RULES` to a rule\n * of it, on every run. The telephone number's expression is not run as\n * written: its digits are counted, which is what it asks, in time in\n * proportion to the text's length (`telephoneBreak`).\n */\n\nimport type { EInvoiceTextTerm } from './en16931-texts.js'\nimport { mod97 } from './payment-reference.js'\n\n/**\n * Every rule of XRechnung's a refusal of report-spec names, and no other:\n * Peppol's three that KoSIT's XRechnung schematron runs among them. The\n * gate reads this list and holds each id to a rule of the pinned XRechnung\n * schematron; `en16931.test.ts` and `xrechnung.test.ts` hold it to the ids\n * the rules say.\n */\nexport const XRECHNUNG_RULES = [\n 'BR-DE-1',\n 'BR-DE-2',\n 'BR-DE-5',\n 'BR-DE-6',\n 'BR-DE-7',\n 'BR-DE-15',\n 'BR-DE-18',\n 'BR-DE-27',\n 'BR-DE-28',\n 'PEPPOL-EN16931-R001',\n 'PEPPOL-EN16931-R010',\n 'PEPPOL-EN16931-R020',\n] as const\nexport type XRechnungRule = (typeof XRECHNUNG_RULES)[number]\n\n/** A rule of XRechnung's that needs a term, and what a refusal says of the term when it is not given. */\nexport interface XRechnungNeed {\n readonly rule: XRechnungRule\n readonly said: string\n}\n\n/**\n * What an XRechnung needs that EN 16931 lets an invoice leave out, by the\n * place it stands in under the e-invoice, each fatal in the pinned\n * XRechnung schematron: the validator refuses an XRechnung without it,\n * where it is missing. The gate holds each rule's test to the element the\n * runtime writes the term as.\n */\nexport const XRECHNUNG_NEEDS = {\n businessProcess: { rule: 'PEPPOL-EN16931-R001', said: 'the business process (BT-23) is not given, and an XRechnung needs it' },\n buyerReference: { rule: 'BR-DE-15', said: \"the buyer's reference (BT-10), a public buyer's Leitweg-ID, is not given, and an XRechnung needs it\" },\n payment: { rule: 'BR-DE-1', said: 'the payment instructions (BG-16) are not given, and an XRechnung needs them' },\n 'seller/contact': { rule: 'BR-DE-2', said: \"the seller's contact (BG-6) is not given, and an XRechnung needs it\" },\n 'seller/electronicAddress': { rule: 'PEPPOL-EN16931-R020', said: \"the seller's electronic address (BT-34) is not given, and an XRechnung needs it\" },\n 'buyer/electronicAddress': { rule: 'PEPPOL-EN16931-R010', said: \"the buyer's electronic address (BT-49) is not given, and an XRechnung needs it\" },\n} as const satisfies { readonly [at: string]: XRechnungNeed }\n\n/**\n * The texts an XRechnung needs to say something, by business term, and the\n * rule of XRechnung's that needs each: those of `XRECHNUNG_NEEDS`, and the\n * contact's three, which BR-DE-5 to -7 read through normalize-space. An\n * XRechnung's texts are EN 16931's with these needed\n * (`E_INVOICE_KIND_TEXTS`), so that a blank one is refused by its rule, a\n * literal where it is written and one from data at the render.\n */\nexport const XRECHNUNG_TEXT_NEEDS = {\n 'BT-10': 'BR-DE-15',\n 'BT-23': 'PEPPOL-EN16931-R001',\n 'BT-34': 'PEPPOL-EN16931-R020',\n 'BT-41': 'BR-DE-5',\n 'BT-42': 'BR-DE-6',\n 'BT-43': 'BR-DE-7',\n 'BT-49': 'PEPPOL-EN16931-R010',\n} as const satisfies { readonly [T in EInvoiceTextTerm]?: XRechnungRule }\n\n/**\n * The rules of XRechnung's the plan for 0.3.0 names, or that hold the terms\n * it does, that nothing the format can say breaks, so that no refusal of\n * report-spec names them: each is held by another rule or by what the\n * format and the writer leave out, as said. The gate holds each id to a\n * rule of the pinned XRechnung schematron, and the rule's context and test,\n * white space aside, to the ones the reason was read against\n * (`XRECHNUNG_HELD_RULES` in `scripts/e-invoice/oracle.mjs`), so that a\n * rule KoSIT renames, drops or rewrites is seen; that each holds of a file\n * is the XRechnung sample's, which KoSIT's XRechnung scenario judges.\n */\nexport const XRECHNUNG_HELD: { readonly [id: string]: string } = {\n 'BR-DE-3': \"the seller's city: the UStG's full address needs it in every e-invoice (`FULL_ADDRESS`)\",\n 'BR-DE-4': \"the seller's post code: the UStG's full address needs it in every e-invoice (`FULL_ADDRESS`)\",\n 'BR-DE-8': \"the buyer's city: the UStG's full address needs it in every e-invoice (`FULL_ADDRESS`)\",\n 'BR-DE-9': \"the buyer's post code: the UStG's full address needs it in every e-invoice (`FULL_ADDRESS`)\",\n 'BR-DE-14': 'the VAT category rate: every category declares its rate, and the writer writes it, by value, in each breakdown',\n 'BR-DE-16':\n \"the seller's VAT identifier or tax number where a line is in S, E or AE: BR-S-02, BR-E-02 and BR-AE-02 ask the same of the three categories this release writes, and it writes no tax representative\",\n 'BR-DE-17': 'the invoice type: 380, the one code `INVOICE_TYPE_CODES` holds, is of the codes it lists',\n 'BR-DE-19': \"the IBAN of a SEPA credit transfer: the payment account is the EPC QR code's account rule, check digits and all (`checkEpcIban`)\",\n 'BR-DE-21': \"BT-24: the writer writes the version's `XRECHNUNG` guideline, KoSIT's `XR-CIUS-ID`\",\n 'BR-DE-23-a': \"the payee's account (BG-17) of a credit transfer, 58 or 30: payment instructions need the account (BR-61), and the writer writes it\",\n 'BR-DE-23-b': 'no card (BG-18) and no direct debit (BG-19) beside a credit transfer: the format writes neither',\n}\n\n/** What a rule of XRechnung's says, with its id: the one way a message names one, so that every id is a listed one. */\nexport function xrechnungRule(id: XRechnungRule, said: string): string {\n return `${said} (XRechnung's ${id})`\n}\n\n/** Whether a rule id is one of XRechnung's, rather than CEN's or the UStG's. */\nexport function isXRechnungRule(id: string): id is XRechnungRule {\n return (XRECHNUNG_RULES as readonly string[]).includes(id)\n}\n\n/** A shape XRechnung holds a term to: the rule that holds it, and its XPath regular expression as the pinned schematron writes it. */\nexport interface XRechnungPattern {\n readonly rule: XRechnungRule\n readonly pattern: string\n}\n\n/** The shapes, by what they shape. */\nexport const XRECHNUNG_PATTERNS: { readonly telephone: XRechnungPattern; readonly email: XRechnungPattern } = {\n telephone: { rule: 'BR-DE-27', pattern: '.*([0-9].*){3,}.*' },\n email: { rule: 'BR-DE-28', pattern: String.raw`^[^@\\s]+@([^@.\\s]+\\.)+[^@.\\s]+$` },\n}\n\n/** XPath's \\s: a space, a tab, a line feed, a carriage return (XML Schema Part 2, F.1.1), and no other white space. */\nconst SPACE = String.raw` \\t\\n\\r`\n\n/** The escapes XPath and JavaScript read alike: a tab, a line feed, a carriage return, or a character XPath's syntax would otherwise read, written as itself; and in a class, a hyphen. */\nconst LITERAL = /^[nrt.\\\\?*+{}()[\\]^$|]$/\n\n/**\n * `pattern`, an XPath 2.0 regular expression, as a JavaScript one that\n * matches the very strings it matches, `matches()` being unanchored as\n * `test` is: `\\s` as XPath's four characters, `.` outside a class as any\n * character but a line feed and a carriage return, and the rest as\n * written. An escape the two read otherwise -- `\\d`, `\\w`, a category,\n * XPath's own `\\i` and `\\c`, `\\S` -- and a class subtracted, which\n * JavaScript has not, are refused rather than translated; so is what\n * JavaScript reads and XPath 2.0 refuses: a group that begins `(?`, an\n * escape XPath has not, `\\/` among them, and a `[` inside a class. The\n * package does not export it: the two expressions here are what it reads.\n */\nexport function xpathRegExp(pattern: string): RegExp {\n const refused = (what: string): never => {\n throw new RangeError(`${what} is read otherwise by XPath than by JavaScript, and is not translated`)\n }\n let source = ''\n let inClass = false\n for (let at = 0; at < pattern.length; at += 1) {\n const character = pattern[at] as string\n if (character === '\\\\') {\n const escaped = pattern[at + 1] ?? ''\n at += 1\n if (escaped === 's') source += inClass ? SPACE : `[${SPACE}]`\n else if (LITERAL.test(escaped) || (inClass && escaped === '-')) source += `\\\\${escaped}`\n else refused(`the escape \\\\${escaped}`)\n } else if (inClass && character === '-' && pattern[at + 1] === '[') refused('a class subtracted')\n else if (character === '[') {\n if (inClass) refused('a [ inside a class')\n inClass = true\n source += character\n } else if (character === ']') {\n inClass = false\n source += character\n } else if (character === '(' && !inClass && pattern[at + 1] === '?') refused('a group that begins (?')\n else if (character === '.' && !inClass) source += String.raw`[^\\n\\r]`\n else source += character\n }\n return new RegExp(source, 'u')\n}\n\n/** `text` as XPath's `normalize-space` gives it: its runs of XPath's white space one space each, and none at either end. */\nexport function normalizeSpace(text: string): string {\n return text.replace(/[ \\t\\n\\r]+/g, ' ').replace(/^ | $/g, '')\n}\n\nconst EMAIL = xpathRegExp(XRECHNUNG_PATTERNS.email.pattern)\n\n/**\n * The rule a contact's telephone number (BT-42) breaks, or undefined:\n * three ASCII digits at least, as BR-DE-27 reads one. Its expression,\n * `.*([0-9].*){3,}.*`, matches what `normalize-space` leaves of a text --\n * no line feed and no carriage return, the two characters XPath's `.`\n * does not match -- exactly where three of `[0-9]` stand in it, so the\n * digits are counted. Run as written by a backtracking engine it takes\n * time that grows with the square of the text's length, and a text may be\n * long; `xrechnung.test.ts` holds the count to the expression.\n */\nexport function telephoneBreak(text: string): string | undefined {\n let digits = 0\n for (let at = 0; at < text.length; at += 1) {\n const code = text.charCodeAt(at)\n if (code >= 0x30 && code <= 0x39 && (digits += 1) === 3) return undefined\n }\n return xrechnungRule('BR-DE-27', 'has fewer than three digits, which a telephone number has at least')\n}\n\n/** The rule a contact's email address (BT-43) breaks, or undefined: the shape BR-DE-28 reads an address in. */\nexport function emailBreak(text: string): string | undefined {\n return EMAIL.test(normalizeSpace(text))\n ? undefined\n : xrechnungRule(\n 'BR-DE-28',\n 'is not an email address of the shape XRechnung reads one in: no white space, one @ with something before it, and after it two names at least, each joined to the next by one dot',\n )\n}\n\n/** What BR-DE-18 says of a line led by #, as a refusal says it. */\nconst SKONTO = xrechnungRule(\n 'BR-DE-18',\n 'hold a line that begins with #, which XRechnung reads as a Skonto line of its own syntax, and this release writes none: a discount is said in words',\n)\n\n/**\n * The rule an XRechnung's payment terms (BT-20) break, or undefined: no\n * line led by # (0038, Q4). BR-DE-18 reads every line of the terms --\n * `tokenize(. , '(\\r?\\n)')`, so a line ends at a line feed, a carriage\n * return before it going with it -- whose `normalize-space` begins with #,\n * as a Skonto line of XRechnung's own syntax, fatal where it is not one;\n * this release writes no Skonto, and refuses every such line, a\n * well-formed one too. The white space normalize-space drops before the #\n * is XPath's four characters. Found in one pass over the text.\n */\nexport function skontoBreak(text: string): string | undefined {\n let lineStart = true\n for (let at = 0; at < text.length; at += 1) {\n const character = text[at]\n if (character === '\\n') lineStart = true\n else if (lineStart && character === '#') return SKONTO\n else if (character !== ' ' && character !== '\\t' && character !== '\\r') lineStart = false\n }\n return undefined\n}\n\n/**\n * A Leitweg-ID's parts: a coarse address of 2 to 12 digits, a fine address\n * of 1 to 30 letters and digits where it has one, and two check digits,\n * joined by hyphens. Anchored at both ends, every repeat bounded, it\n * matches no text past the longest Leitweg-ID's 46 characters, and decides\n * a text of any length within its first 46: no backtracking grows with an\n * address's length.\n */\nconst LEITWEG_ID = /^([0-9]{2,12})(?:-([0-9A-Za-z]{1,30}))?-([0-9]{2})$/\n\n/** What an address under 0204 breaks by its shape, as a refusal says it. */\nconst LEITWEG_SHAPE =\n 'is under 0204, a Leitweg-ID, and is not shaped as one: a coarse address of 2 to 12 digits, a fine address of up to 30 letters and digits where it has one, and two check digits, joined by hyphens'\n\n/**\n * The rule an electronic address under scheme 0204 breaks as a Leitweg-ID,\n * or undefined (0038, Q3): its shape, and check digits that are 98 less\n * the remainder modulo 97 of its coarse and fine addresses with 00 after\n * them, each letter, in either case, the two digits ISO/IEC 7064 gives it\n * (MOD 97-10, as an IBAN's). The format specification itself, KoSIT's\n * Leitweg-ID-Formatspezifikation 2.0.2, could not be read here; the shape\n * and the computation are as FeRD's data sheet describes them, and every\n * Leitweg-ID of KoSIT's XRechnung 3.0.2 test suite with right digits\n * passes it, and every one with wrong digits is refused\n * (`xrechnung.test.ts`). No rule of XRechnung's or CEN's checks one, so\n * this names none.\n */\nexport function leitwegIdBreak(text: string): string | undefined {\n const parts = LEITWEG_ID.exec(text)\n if (parts === null) return LEITWEG_SHAPE\n const [, coarse = '', fine = '', check] = parts\n const digits = String(98 - mod97(`${coarse}${fine}00`)).padStart(2, '0')\n return digits === check\n ? undefined\n : \"is under 0204, a Leitweg-ID, and has check digits that do not match the rest of it (the Leitweg-ID's check digits, ISO/IEC 7064 MOD 97-10)\"\n}\n","/**\n * EN 16931's rules for what an e-invoice holds, as checks over text: each\n * answers the value the XML is written with, or the rule the text breaks,\n * named by its business term (BT) and its business rule (BR) and never by\n * the value, which may be a person's name, account or VAT identifier.\n *\n * One set of rules, read twice, as the QR-bill's are (0022): the validator\n * applies them to a text no data can change, so that the editor refuses a\n * country written UK where it is written; the runtime applies the same\n * functions to every text once the data has resolved it. Two copies could\n * disagree about which invoices are valid, and nobody would find out until\n * a buyer's system refused one. The arithmetic -- the totals and the VAT\n * breakdown -- is not here: the runtime computes it once\n * (`e-invoice-totals.ts`), so it is right by construction and not checked.\n *\n * The rules are CEN/TC 434's CII artefacts 1.3.17, each fatal there and in\n * the 1.3.16 the pinned validators run; the e-invoice gate holds every id\n * `EN16931_RULES` lists to a fatal rule of its pinned schematron. The one\n * that is not CEN's, the time of supply, is the UStG's, and says so. Which\n * release each check follows where they differ, 0027 says: EL as a VAT\n * prefix only.\n *\n * This module holds the rules' ids and how a refusal names one; the\n * checks stand beside it, by the kind of term each holds: the texts\n * (`en16931-texts.ts`), the decimals (`en16931-decimals.ts`), the dates\n * (`en16931-dates.ts`), the terms of a line (`en16931-lines.ts`) and the\n * VAT categories (`en16931-vat.ts`). The two shapes XRechnung asks of the\n * seller's contact, which no rule of CEN's does, are XRechnung's own, with\n * their own list of ids (`xrechnung.ts`, 0037), and so are the terms an\n * XRechnung needs past EN 16931 (0038).\n */\nimport { isXRechnungRule, xrechnungRule } from './xrechnung.js'\nimport type { XRechnungRule } from './xrechnung.js'\n\n/**\n * Every rule of EN 16931 a refusal of these checks names, and no other.\n * The gate reads this list; `en16931.test.ts` holds it to the ids the\n * rules say.\n */\nexport const EN16931_RULES = [\n 'BR-02',\n 'BR-03',\n 'BR-06',\n 'BR-07',\n 'BR-09',\n 'BR-11',\n 'BR-16',\n 'BR-21',\n 'BR-22',\n 'BR-23',\n 'BR-24',\n 'BR-25',\n 'BR-26',\n 'BR-27',\n 'BR-29',\n 'BR-61',\n 'BR-CL-11',\n 'BR-CL-14',\n 'BR-CL-23',\n 'BR-CL-25',\n 'BR-CO-04',\n 'BR-CO-09',\n 'BR-CO-17',\n 'BR-CO-18',\n 'BR-CO-19',\n 'BR-CO-26',\n 'BR-DEC-16',\n 'BR-DEC-23',\n 'BR-S-02',\n 'BR-S-05',\n 'BR-S-08',\n 'BR-S-10',\n 'BR-E-01',\n 'BR-E-02',\n 'BR-E-05',\n 'BR-E-10',\n 'BR-AE-01',\n 'BR-AE-02',\n 'BR-AE-05',\n 'BR-AE-10',\n] as const\nexport type En16931Rule = (typeof EN16931_RULES)[number]\n\n/** What a rule says, with the ids of the rules it is: the one way a message of these checks names one, so that every id is a listed one. */\nexport function en16931Rule(id: En16931Rule | readonly En16931Rule[], said: string): string {\n return `${said} (${typeof id === 'string' ? id : id.join(', ')})`\n}\n\n/**\n * The section of the UStG that asks a German invoice for \"die vollständige\n * Anschrift\" of the seller and of the buyer (§ 14 Abs. 4 Satz 1 Nr. 1,\n * read on gesetze-im-internet.de on 17 October 2026): their street, post\n * code and city, which no rule of CEN's asks for. BR-08 and BR-10 need\n * only that each party has a postal address (BG-5, BG-8), and BR-09 and\n * BR-11 its country. It is the law's, not one of CEN's rules, and so not\n * in `EN16931_RULES`.\n */\nexport const FULL_ADDRESS = '§ 14 Abs. 4 Satz 1 Nr. 1 UStG'\n\n/** What asks for a term an e-invoice cannot leave out: one of EN 16931's rules, the UStG's full address, or, in an XRechnung, one of XRechnung's rules (0038). */\nexport type EInvoiceNeed = En16931Rule | typeof FULL_ADDRESS | XRechnungRule\n\n/** What a refusal says of a term `need` asks for that is `said` -- empty, or without a value -- and what asks for it: a rule of CEN's or XRechnung's by its id, the UStG by its section and what it asks. */\nexport function neededBy(need: EInvoiceNeed, said: string): string {\n if (need === FULL_ADDRESS) return `${said}, and a German invoice gives the full address of the seller and the buyer (${FULL_ADDRESS})`\n return isXRechnungRule(need) ? xrechnungRule(need, `${said}, and an XRechnung needs it`) : en16931Rule(need, `${said}, and an e-invoice needs it`)\n}\n","/**\n * Each text term of the e-invoice held to EN 16931: what a refusal calls\n * it, whether the invoice may leave it out, whether the XML writes it as a\n * token, and its own rule -- a code from a closed list, a VAT identifier,\n * the EPC QR code's account and BIC, XRechnung's shape of a telephone\n * number and of an email address -- in one table, and which term each\n * text of the format is, by where it stands. What a text may hold at all,\n * XML 1.0 decides. An XRechnung's texts are the same terms, with what\n * XRechnung needs past EN 16931 needed and its payment terms held to\n * BR-DE-18 (`E_INVOICE_KIND_TEXTS`, 0038).\n */\nimport { checkEpcBic, checkEpcIban } from './epc-payload.js'\nimport { ADDRESS_SCHEMES, COUNTRY_CODES, SCHEME_IDS, UNIT_CODES, VAT_PREFIXES } from './e-invoice.js'\nimport type {\n AddressScheme,\n CountryCode,\n EInvoiceAddress,\n EInvoiceBuyer,\n EInvoiceKind,\n EInvoiceSeller,\n PaymentInstructions,\n SchemeId,\n SellerContact,\n UnitCode,\n} from './e-invoice.js'\nimport { en16931Rule, FULL_ADDRESS, neededBy } from './en16931.js'\nimport type { EInvoiceNeed } from './en16931.js'\nimport { no, ok, withoutSpaces } from './payment-reference.js'\nimport type { PaymentCheck } from './payment-reference.js'\nimport { emailBreak, leitwegIdBreak, skontoBreak, telephoneBreak, XRECHNUNG_TEXT_NEEDS } from './xrechnung.js'\n\n/** Whether a text says nothing: empty, or white space alone. */\nexport function eInvoiceBlank(text: string): boolean {\n return text.trim() === ''\n}\n\n/**\n * Whether a code point is one XML 1.0 cannot write (2.2, Char): a C0\n * control but tab, line feed and carriage return; half of a surrogate\n * pair; U+FFFE or U+FFFF. DEL and the C1 controls it allows.\n */\nfunction unwritable(codePoint: number): boolean {\n if (codePoint < 0x20) return codePoint !== 0x09 && codePoint !== 0x0a && codePoint !== 0x0d\n return (codePoint >= 0xd800 && codePoint <= 0xdfff) || codePoint === 0xfffe || codePoint === 0xffff\n}\n\n/**\n * The rule a text breaks by holding a character XML 1.0 cannot write, or\n * undefined. A file that held one would not be XML, and dropping it would\n * change what the invoice says, so it is refused, named by its position,\n * counted in characters from 1, never quoted.\n */\nexport function xmlCharacterBreak(text: string): string | undefined {\n let position = 0\n for (const character of text) {\n position += 1\n if (unwritable(character.codePointAt(0) as number)) return `holds a character at character ${position} that XML 1.0 cannot write`\n }\n return undefined\n}\n\n/** A country (BT-40, BT-55) of `COUNTRY_CODES`, its blanks dropped. */\nexport function checkCountryCode(text: string): PaymentCheck<CountryCode> {\n const code = text.trim()\n if ((COUNTRY_CODES as readonly string[]).includes(code)) return ok(code as CountryCode)\n return no(en16931Rule('BR-CL-14', \"is not a country code of those this release takes, a list narrower than ISO 3166-1's\"))\n}\n\n/** A unit of measure (BT-130) of `UNIT_CODES`, its blanks dropped. */\nexport function checkUnitCode(text: string): PaymentCheck<UnitCode> {\n const code = text.trim()\n if ((UNIT_CODES as readonly string[]).includes(code)) return ok(code as UnitCode)\n return no(en16931Rule('BR-CL-23', 'is not a unit of measure of those this release takes, a list narrower than UN/ECE Recommendation 20'))\n}\n\n/** A scheme (BT-30-1, BT-47-1) of `SCHEME_IDS`: a literal the template writes, taken as written. */\nexport function checkSchemeId(code: string): PaymentCheck<SchemeId> {\n if ((SCHEME_IDS as readonly string[]).includes(code)) return ok(code as SchemeId)\n return no(en16931Rule('BR-CL-11', \"is not a scheme of those this release takes, a list narrower than ISO 6523's\"))\n}\n\n/** An electronic address's scheme (BT-34-1, BT-49-1) of `ADDRESS_SCHEMES`: a literal the template writes, taken as written. */\nexport function checkAddressScheme(code: string): PaymentCheck<AddressScheme> {\n if ((ADDRESS_SCHEMES as readonly string[]).includes(code)) return ok(code as AddressScheme)\n return no(en16931Rule('BR-CL-25', \"is not an electronic address scheme of those this release takes, a list narrower than the CEF's EAS code list\"))\n}\n\n/** A check of `breaks`: the text as written where it breaks nothing, and the rule it breaks where it does. */\nconst held =\n (breaks: (text: string) => string | undefined) =>\n (text: string): PaymentCheck<string> => {\n const rule = breaks(text)\n return rule === undefined ? ok(text) : no(rule)\n }\n\n/**\n * A VAT identifier (BT-31, BT-48): a prefix of `VAT_PREFIXES`, which names\n * the country that issued it (BR-CO-09), and then the number it gives. The\n * spaces a person writes to read one are dropped, as an IBAN's are; what\n * follows the prefix is the issuing country's to define, and not checked.\n */\nexport function checkVatIdentifier(text: string): PaymentCheck<string> {\n const id = withoutSpaces(text)\n if (id.length > 2 && VAT_PREFIXES.includes(id.slice(0, 2))) return ok(id)\n return no(en16931Rule('BR-CO-09', 'does not begin with a country code this release takes as a VAT prefix, then the number it gives'))\n}\n\n/** How a text term of the e-invoice is held: what a refusal calls it, the rule its absence breaks, and its own rule. */\nexport interface EInvoiceTextRule {\n /** What a refusal calls it, its business term named: \"the seller's name (BT-27)\". */\n readonly what: string\n /** What an empty one breaks, when the e-invoice needs it; absent, it may be left out. */\n readonly required?: EInvoiceNeed\n /**\n * Whether the XML writes it as a token: the Factur-X EN 16931 XSD types\n * an identifier and a code (udt:IDType, udt:CodeType) as xs:token, which\n * a schema-aware reader collapses -- each tab and line break a space, two\n * spaces one, none at either end. Such a text holds none of that, or a\n * reader would read another identifier than the page prints.\n */\n readonly token?: true\n /** What it holds when it holds something, past its characters: the value the XML writes, or the rule it breaks. */\n readonly check?: (text: string) => PaymentCheck<string>\n}\n\n/**\n * Each text term of the e-invoice, by its business term. One table, which\n * the validator reads for a literal text and the runtime for one the data\n * resolved: two could call a term two things, or disagree about which an\n * invoice may leave out, and nobody would find out.\n *\n * - The address lines, post codes and cities are needed by the UStG's\n * full address (`FULL_ADDRESS`), past EN 16931, which asks only for the\n * country.\n * - An identifier or a code the XML writes as a token holds no white\n * space a token collapses (`token`).\n * - The payment account (BT-84) is held by the one rule an EPC QR code's\n * account is (`checkEpcIban`): an IBAN of a country of SEPA, of its\n * length, its check digits right (`payment-reference.ts`), and no\n * QR-IBAN; and its BIC (BT-86) by the EPC QR code's BIC rule\n * (`checkEpcBic`). Every credit transfer this version writes is paid in\n * euro, and an invoice that prints both cannot hold two rules for one\n * account or one bank.\n * - The exemption reason (BT-120) is needed by its category's code\n * (`vatReasonBreak`); a line's VAT category (BT-151) is one the invoice\n * declares (`checkLineCategory`).\n * - The business process (BT-23), the electronic addresses (BT-34, BT-49)\n * and the seller's contact (BT-41 to BT-43) are needed by no rule a\n * German B2B invoice is held to (0037). The telephone number and the\n * email address are held to the shapes XRechnung's KoSIT warns of\n * (`xrechnung.ts`), so that no file earns the warning; the business\n * process and an address, identifiers of no shape CEN or XRechnung asks,\n * are tokens alone.\n */\nexport type EInvoiceTextTerm =\n | 'BT-1'\n | 'BT-10'\n | 'BT-20'\n | 'BT-23'\n | 'BT-27'\n | 'BT-30'\n | 'BT-31'\n | 'BT-32'\n | 'BT-34'\n | 'BT-35'\n | 'BT-36'\n | 'BT-37'\n | 'BT-38'\n | 'BT-40'\n | 'BT-41'\n | 'BT-42'\n | 'BT-43'\n | 'BT-44'\n | 'BT-47'\n | 'BT-48'\n | 'BT-49'\n | 'BT-50'\n | 'BT-51'\n | 'BT-52'\n | 'BT-53'\n | 'BT-55'\n | 'BT-83'\n | 'BT-84'\n | 'BT-85'\n | 'BT-86'\n | 'BT-120'\n | 'BT-126'\n | 'BT-130'\n | 'BT-151'\n | 'BT-153'\n\nexport const E_INVOICE_TEXTS: { readonly [T in EInvoiceTextTerm]: EInvoiceTextRule } = {\n 'BT-1': { what: 'the invoice number (BT-1)', required: 'BR-02', token: true },\n 'BT-10': { what: \"the buyer's reference (BT-10)\" },\n 'BT-20': { what: 'the payment terms (BT-20)' },\n 'BT-23': { what: 'the business process (BT-23)', token: true },\n 'BT-27': { what: \"the seller's name (BT-27)\", required: 'BR-06' },\n 'BT-30': { what: \"the seller's legal registration identifier (BT-30)\", token: true },\n 'BT-31': { what: \"the seller's VAT identifier (BT-31)\", check: checkVatIdentifier },\n 'BT-32': { what: \"the seller's tax registration identifier (BT-32)\", token: true },\n 'BT-34': { what: \"the seller's electronic address (BT-34)\", token: true },\n 'BT-35': { what: \"the seller's address line (BT-35)\", required: FULL_ADDRESS },\n 'BT-36': { what: \"the seller's second address line (BT-36)\" },\n 'BT-37': { what: \"the seller's city (BT-37)\", required: FULL_ADDRESS },\n 'BT-38': { what: \"the seller's post code (BT-38)\", required: FULL_ADDRESS, token: true },\n 'BT-40': { what: \"the seller's country code (BT-40)\", required: 'BR-09', check: checkCountryCode },\n 'BT-41': { what: \"the seller's contact point (BT-41)\" },\n 'BT-42': { what: \"the seller's contact telephone number (BT-42)\", check: held(telephoneBreak) },\n 'BT-43': { what: \"the seller's contact email address (BT-43)\", token: true, check: held(emailBreak) },\n 'BT-44': { what: \"the buyer's name (BT-44)\", required: 'BR-07' },\n 'BT-47': { what: \"the buyer's legal registration identifier (BT-47)\", token: true },\n 'BT-48': { what: \"the buyer's VAT identifier (BT-48)\", check: checkVatIdentifier },\n 'BT-49': { what: \"the buyer's electronic address (BT-49)\", token: true },\n 'BT-50': { what: \"the buyer's address line (BT-50)\", required: FULL_ADDRESS },\n 'BT-51': { what: \"the buyer's second address line (BT-51)\" },\n 'BT-52': { what: \"the buyer's city (BT-52)\", required: FULL_ADDRESS },\n 'BT-53': { what: \"the buyer's post code (BT-53)\", required: FULL_ADDRESS, token: true },\n 'BT-55': { what: \"the buyer's country code (BT-55)\", required: 'BR-11', check: checkCountryCode },\n 'BT-83': { what: 'the remittance information (BT-83)' },\n 'BT-84': { what: 'the payment account (BT-84)', required: 'BR-61', check: checkEpcIban },\n 'BT-85': { what: \"the payment account's name (BT-85)\" },\n 'BT-86': { what: \"the payment account's BIC (BT-86)\", token: true, check: checkEpcBic },\n 'BT-120': { what: 'the VAT exemption reason (BT-120)' },\n 'BT-126': { what: 'the line identifier (BT-126)', required: 'BR-21', token: true },\n 'BT-130': { what: 'the unit of measure (BT-130)', required: 'BR-23', check: checkUnitCode },\n 'BT-151': { what: \"the line's VAT category (BT-151)\", required: 'BR-CO-04' },\n 'BT-153': { what: 'the item name (BT-153)', required: 'BR-25' },\n}\n\n/** How each text term is held, by its business term: a table over every term. */\nexport type EInvoiceTextRules = { readonly [T in EInvoiceTextTerm]: EInvoiceTextRule }\n\n/** An XRechnung's text rules: EN 16931's, with each term XRechnung needs needed by its rule, and its payment terms holding no Skonto line. */\nfunction xrechnungTexts(): EInvoiceTextRules {\n const rules: Record<string, EInvoiceTextRule> = { ...E_INVOICE_TEXTS }\n for (const [term, rule] of Object.entries(XRECHNUNG_TEXT_NEEDS)) rules[term] = { ...E_INVOICE_TEXTS[term as EInvoiceTextTerm], required: rule }\n rules['BT-20'] = { ...E_INVOICE_TEXTS['BT-20'], check: held(skontoBreak) }\n return rules as EInvoiceTextRules\n}\n\n/**\n * Each kind's text rules, one table per kind over every term (0038): the\n * validator reads a literal by its kind's, the runtime what the data\n * resolved, so the two cannot hold one term of one kind to two rules. A\n * kind without a table does not compile.\n */\nexport const E_INVOICE_KIND_TEXTS: { readonly [K in EInvoiceKind]: EInvoiceTextRules } = {\n facturX: E_INVOICE_TEXTS,\n xrechnung: xrechnungTexts(),\n}\n\n/** Each part of an address, by its business term. */\ntype AddressTerms = { readonly [A in keyof EInvoiceAddress]-?: EInvoiceTextTerm }\n\n/** Each part of the seller's contact, by its business term. */\ntype ContactTerms = { readonly [C in keyof SellerContact]-?: EInvoiceTextTerm }\n\n/**\n * Which term each text of an e-invoice is, by where it stands in it: the\n * type of `E_INVOICE_TEXT_TERMS`, over every text the format has. A legal\n * registration and an electronic address are named by their identifier's\n * term; their schemes are codes, not texts.\n */\nexport interface EInvoiceTextTerms {\n readonly number: EInvoiceTextTerm\n readonly businessProcess: EInvoiceTextTerm\n readonly buyerReference: EInvoiceTextTerm\n readonly terms: EInvoiceTextTerm\n readonly seller: { readonly [K in Exclude<keyof EInvoiceSeller, 'address' | 'contact'>]-?: EInvoiceTextTerm } & {\n readonly contact: ContactTerms\n readonly address: AddressTerms\n }\n readonly buyer: { readonly [K in Exclude<keyof EInvoiceBuyer, 'address'>]-?: EInvoiceTextTerm } & { readonly address: AddressTerms }\n /** A VAT category's exemption reason. */\n readonly reason: EInvoiceTextTerm\n readonly payment: { readonly [K in Exclude<keyof PaymentInstructions, 'means'>]-?: EInvoiceTextTerm }\n}\n\n/**\n * Which business term each text of an e-invoice is, by where it stands:\n * the validator reads a literal by it and the runtime what the data\n * resolved, so the two cannot call one text two terms. A line's texts are\n * not here: the columns and the row that give them are `E_INVOICE_LINE_COLUMNS`'\n * and `E_INVOICE_LINE_CODES`'.\n */\nexport const E_INVOICE_TEXT_TERMS: EInvoiceTextTerms = {\n number: 'BT-1',\n businessProcess: 'BT-23',\n buyerReference: 'BT-10',\n terms: 'BT-20',\n seller: {\n name: 'BT-27',\n vatId: 'BT-31',\n taxNumber: 'BT-32',\n legalId: 'BT-30',\n electronicAddress: 'BT-34',\n contact: { name: 'BT-41', telephone: 'BT-42', email: 'BT-43' },\n address: { line1: 'BT-35', line2: 'BT-36', postalCode: 'BT-38', city: 'BT-37', country: 'BT-40' },\n },\n buyer: {\n name: 'BT-44',\n vatId: 'BT-48',\n legalId: 'BT-47',\n electronicAddress: 'BT-49',\n address: { line1: 'BT-50', line2: 'BT-51', postalCode: 'BT-53', city: 'BT-52', country: 'BT-55' },\n },\n reason: 'BT-120',\n payment: { iban: 'BT-84', bic: 'BT-86', accountName: 'BT-85', remittance: 'BT-83' },\n}\n\n/** Whether `text` is what xs:token's white space facet, collapse, leaves it: no tab, line feed or carriage return, no space at either end, and no two in a row. */\nfunction collapsed(text: string): boolean {\n return !/[\\t\\n\\r]|^ | $| {2}/.test(text)\n}\n\n/**\n * The text of `term`, held to its rule: one that says nothing is refused,\n * as needed where the e-invoice needs it and as the term left out where it\n * may be, a second spelling of one absent; then its characters, which XML\n * 1.0 must be able to write; then, for a term the XML writes as a token,\n * its white space; then its own rule. That is what the validator says of a\n * literal; an optional term the data resolves to blank is left out of the\n * XML instead, which the runtime decides by `eInvoiceBlank` before it asks\n * here. `kind` is the e-invoice's, whose rules the term is held to.\n */\nexport function checkEInvoiceText(term: EInvoiceTextTerm, text: string, kind: EInvoiceKind = 'facturX'): PaymentCheck<string> {\n const rule = E_INVOICE_KIND_TEXTS[kind][term]\n if (eInvoiceBlank(text))\n return no(rule.required === undefined ? 'is blank: a term the e-invoice does not hold is left out of it' : neededBy(rule.required, 'is empty'))\n const characters = xmlCharacterBreak(text)\n if (characters !== undefined) return no(characters)\n if (rule.token === true && !collapsed(text)) {\n return no(\n 'holds white space the XML would not keep: its schema types the term as a token, read with each tab and line break as a space, two spaces as one, and none at either end',\n )\n }\n return rule.check === undefined ? ok(text) : rule.check(text)\n}\n\n/**\n * The identifier of an electronic address (BT-34, BT-49), `term`, given in\n * `scheme`: held to its term's rule, and, under 0204, which says it is a\n * Leitweg-ID, to a Leitweg-ID's shape and check digits (`leitwegIdBreak`,\n * 0038), in an e-invoice of either kind. What a value under another\n * scheme must be is not checked (0037).\n */\nexport function checkElectronicAddress(term: EInvoiceTextTerm, scheme: AddressScheme, text: string, kind: EInvoiceKind = 'facturX'): PaymentCheck<string> {\n const checked = checkEInvoiceText(term, text, kind)\n if (!checked.ok || scheme !== '0204') return checked\n const broken = leitwegIdBreak(checked.value)\n return broken === undefined ? checked : no(broken)\n}\n","/**\n * Each decimal term the runtime reads from data -- a line's quantity, net\n * price and net amount, and the paid amount -- held to EN 16931, and\n * written as the XML writes it: an amount with two decimals, never\n * rounded here.\n */\nimport { en16931Rule } from './en16931.js'\nimport type { En16931Rule } from './en16931.js'\nimport { no, ok } from './payment-reference.js'\nimport type { PaymentCheck } from './payment-reference.js'\nimport { DECIMAL } from './syntax.js'\n\n/** How a decimal term of the e-invoice is held: what a refusal calls it, the rule a null breaks, and what it may be. */\nexport interface EInvoiceDecimalRule {\n readonly what: string\n /** The rule a final render's null breaks; absent, the term may be left out. */\n readonly required?: En16931Rule\n /** The rule more than two decimals break, for a term the XML writes as an amount with two. */\n readonly cents?: En16931Rule\n /** The rule a negative value breaks, for a term that may not be one. */\n readonly least?: En16931Rule\n}\n\n/**\n * Each decimal term the runtime reads from data, by its business term:\n * the line's quantity, net price and net amount, and the paid amount. The\n * totals and the breakdown are not here: the runtime computes them.\n */\nexport type EInvoiceDecimalTerm = 'BT-129' | 'BT-146' | 'BT-131' | 'BT-113'\n\nexport const E_INVOICE_DECIMALS: { readonly [T in EInvoiceDecimalTerm]: EInvoiceDecimalRule } = {\n 'BT-129': { what: 'the invoiced quantity (BT-129)', required: 'BR-22' },\n 'BT-146': { what: 'the item net price (BT-146)', required: 'BR-26', least: 'BR-27' },\n 'BT-131': { what: 'the line net amount (BT-131)', required: 'BR-24', cents: 'BR-DEC-23' },\n 'BT-113': { what: 'the paid amount (BT-113)', cents: 'BR-DEC-16' },\n}\n\n/**\n * The decimal of `term`, an exact decimal as a string, as the XML writes\n * it: an amount with exactly two decimals, from its own digits; a quantity\n * or a price as written. Never rounded, and never read through a\n * JavaScript number: an amount of 10.505 is refused, so that a template\n * that does not round where it computes a line is refused on its first\n * render, rather than writing another amount than its page prints. 10.500\n * is the same number of cents, and is written 10.50.\n */\nexport function checkEInvoiceDecimal(term: EInvoiceDecimalTerm, decimal: string): PaymentCheck<string> {\n if (!DECIMAL.test(decimal)) return no('is not a decimal')\n const rule = E_INVOICE_DECIMALS[term]\n const negative = decimal.startsWith('-')\n if (negative && rule.least !== undefined)\n return no(en16931Rule(rule.least, 'is negative, and a net price never is: a discount is a line of negative quantity at a positive price'))\n if (rule.cents === undefined) return ok(decimal)\n const [whole = '', fraction = ''] = decimal.replace(/^-/, '').split('.')\n if (/[1-9]/.test(fraction.slice(2))) {\n return no(\n en16931Rule(rule.cents, 'is not a whole number of cents, and the XML writes it with two decimals at most: it is rounded where the template computes it'),\n )\n }\n return ok(`${negative ? '-' : ''}${whole}.${fraction.slice(0, 2).padEnd(2, '0')}`)\n}\n","/**\n * When: each date term of the e-invoice, held to a day on the calendar,\n * the invoicing period, which ends no earlier than it starts, and the\n * time of supply a German invoice states.\n */\nimport { en16931Rule } from './en16931.js'\nimport type { En16931Rule } from './en16931.js'\nimport { no, ok } from './payment-reference.js'\nimport type { PaymentCheck } from './payment-reference.js'\nimport { isCalendarDate } from './syntax.js'\n\n/** A date term of the e-invoice: what a refusal calls it, and the rule a final render's null breaks where the e-invoice needs it. */\nexport interface EInvoiceDateRule {\n readonly what: string\n readonly required?: En16931Rule\n}\n\nexport type EInvoiceDateTerm = 'BT-2' | 'BT-9' | 'BT-72' | 'BT-73' | 'BT-74'\n\n/** Each date term, by its business term. */\nexport const E_INVOICE_DATES: { readonly [T in EInvoiceDateTerm]: EInvoiceDateRule } = {\n 'BT-2': { what: 'the issue date (BT-2)', required: 'BR-03' },\n 'BT-9': { what: 'the payment due date (BT-9)' },\n 'BT-72': { what: 'the delivery date (BT-72)' },\n 'BT-73': { what: \"the invoicing period's start (BT-73)\" },\n 'BT-74': { what: \"the invoicing period's end (BT-74)\" },\n}\n\n/**\n * A date term the data resolved, held to a day on the calendar written\n * YYYY-MM-DD, as the runtime holds a date. The editing core types a date\n * term as the ISO string a date field is read as, so any text passes it;\n * one that is not a day -- a name, 2026-02-29, a moment with its time --\n * would be written as a date no validator reads as one.\n */\nexport function checkEInvoiceDate(text: string): PaymentCheck<string> {\n return isCalendarDate(text) ? ok(text) : no('is not a day on the calendar written YYYY-MM-DD')\n}\n\n/**\n * The rule an invoicing period breaks whose dates the data resolved, or\n * undefined: it ends no earlier than it starts (BR-29). Both are calendar\n * dates written YYYY-MM-DD, as the runtime's dates are, so they compare as\n * text.\n */\nexport function checkInvoicingPeriod(start: string, end: string): string | undefined {\n if (!isCalendarDate(start) || !isCalendarDate(end)) return 'the invoicing period is not two dates written YYYY-MM-DD'\n return end < start ? en16931Rule('BR-29', 'the invoicing period ends (BT-74) before it starts (BT-73)') : undefined\n}\n\n/** The rule an invoicing period breaks by holding neither date (BR-CO-19), or undefined: `start` and `end` say which it holds. */\nexport function periodBreak(start: boolean, end: boolean): string | undefined {\n return start || end ? undefined : en16931Rule('BR-CO-19', 'an invoicing period has a start (BT-73), an end (BT-74), or both')\n}\n\n/**\n * The rule an invoice breaks that says nothing of when it was supplied, or\n * undefined: § 14 (4) 1 no. 6 UStG asks a German invoice for the time of\n * supply, which the XML gives as a delivery date or an invoicing period.\n * Not one of CEN's rules: FeRD's BR-FX-DE-04, as the specification is\n * transcribed [S], only warns of an invoice without one.\n */\nexport function supplyBreak(delivered: boolean, period: boolean): string | undefined {\n return delivered || period\n ? undefined\n : 'a German invoice says when it was supplied: a delivery date (BT-72), an invoicing period (BG-14), or both (§ 14 Abs. 4 Satz 1 Nr. 6 UStG)'\n}\n","/**\n * A line's terms: which term each column of the lines' table prints, which\n * codes are read from a line's row, and the types of field that can give\n * each. The rules that hold them are the texts' and the decimals'.\n */\nimport type { FieldType } from './data.js'\nimport { E_INVOICE_DECIMALS } from './en16931-decimals.js'\nimport type { EInvoiceDecimalTerm } from './en16931-decimals.js'\nimport { E_INVOICE_TEXTS } from './en16931-texts.js'\nimport type { EInvoiceTextTerm } from './en16931-texts.js'\n\n/** What a line's term is read from: its business term, whose rule holds it, what a refusal calls it, and the types of field that can give it. */\nexport interface EInvoiceLineTerm {\n readonly term: EInvoiceTextTerm | EInvoiceDecimalTerm\n readonly what: string\n readonly types: readonly FieldType[]\n}\n\nexport type EInvoiceLineColumn = 'name' | 'quantity' | 'netPrice' | 'netAmount'\nexport type EInvoiceLineCode = 'id' | 'unit' | 'vat'\n\n/**\n * Each term a column of the lines' table prints, in the order the XML\n * holds a line's. A column prints a detail field of one of these types, or\n * an expression the editing core holds to what it reads them as: one\n * table, so the validator and the core cannot take a column for two\n * things.\n */\nexport const E_INVOICE_LINE_COLUMNS: { readonly [K in EInvoiceLineColumn]: EInvoiceLineTerm } = {\n name: { term: 'BT-153', what: E_INVOICE_TEXTS['BT-153'].what, types: ['string'] },\n quantity: { term: 'BT-129', what: E_INVOICE_DECIMALS['BT-129'].what, types: ['integer', 'decimal'] },\n netPrice: { term: 'BT-146', what: E_INVOICE_DECIMALS['BT-146'].what, types: ['integer', 'decimal'] },\n netAmount: { term: 'BT-131', what: E_INVOICE_DECIMALS['BT-131'].what, types: ['integer', 'decimal'] },\n}\n\n/** Each code read from a line's row, a detail field of one of these types or an expression held to them in the same way. */\nexport const E_INVOICE_LINE_CODES: { readonly [K in EInvoiceLineCode]: EInvoiceLineTerm } = {\n id: { term: 'BT-126', what: E_INVOICE_TEXTS['BT-126'].what, types: ['string', 'integer'] },\n unit: { term: 'BT-130', what: E_INVOICE_TEXTS['BT-130'].what, types: ['string'] },\n vat: { term: 'BT-151', what: E_INVOICE_TEXTS['BT-151'].what, types: ['string'] },\n}\n","/**\n * VAT: the identifiers a category's lines need of the seller and the\n * buyer, the rate and the exemption reason each category takes, the\n * breakdowns a list of categories makes, and the category a line names.\n */\nimport type { VatCategory, VatCategoryCode } from './e-invoice.js'\nimport { en16931Rule } from './en16931.js'\nimport type { En16931Rule } from './en16931.js'\nimport { no, ok } from './payment-reference.js'\nimport type { PaymentCheck } from './payment-reference.js'\n\n/** The rules of the seller's identifiers each VAT category's lines need, in the order the categories are listed. */\nconst SELLER_VAT_RULES: { readonly [C in VatCategoryCode]: En16931Rule } = { S: 'BR-S-02', E: 'BR-E-02', AE: 'BR-AE-02' }\n\n/**\n * The rules the seller's identifiers break, `has` saying which it holds,\n * for an invoice whose lines are in categories of `codes`:\n * - BR-CO-26: a buyer identifies a seller by its VAT identifier or its\n * legal registration (BT-29, the third way, this version does not write);\n * - BR-S-02, BR-E-02, BR-AE-02: a line in any of the three categories needs\n * the seller's VAT identifier or its tax number.\n *\n * The validator passes what the template declares: every line is in a\n * category the invoice declares, and every invoice has a line, so a rule\n * of a declared category is one some render breaks. The runtime passes\n * the categories its lines use and the identifiers that print.\n */\nexport function sellerIdentificationBreaks(\n has: { readonly vatId: boolean; readonly taxNumber: boolean; readonly legalId: boolean },\n codes: readonly VatCategoryCode[],\n): readonly string[] {\n const breaks: string[] = []\n if (!has.vatId && !has.legalId) {\n breaks.push(\n en16931Rule(\n 'BR-CO-26',\n 'the seller has neither a VAT identifier (BT-31) nor a legal registration identifier (BT-30), one of which a buyer identifies a seller by',\n ),\n )\n }\n const rules = (Object.keys(SELLER_VAT_RULES) as VatCategoryCode[]).filter((code) => codes.includes(code)).map((code) => SELLER_VAT_RULES[code])\n if (!has.vatId && !has.taxNumber && rules.length > 0) {\n breaks.push(\n en16931Rule(\n rules,\n 'the seller has neither a VAT identifier (BT-31) nor a tax registration identifier (BT-32), one of which a line of these VAT categories needs',\n ),\n )\n }\n return breaks\n}\n\n/**\n * The rule the buyer's identifiers break, or undefined: a reverse-charged\n * line moves the tax to the buyer, and needs it named by its VAT identifier\n * or its legal registration (BR-AE-02).\n */\nexport function buyerIdentificationBreak(has: { readonly vatId: boolean; readonly legalId: boolean }, codes: readonly VatCategoryCode[]): string | undefined {\n if (!codes.includes('AE') || has.vatId || has.legalId) return undefined\n return en16931Rule(\n 'BR-AE-02',\n \"a reverse-charged line needs the buyer's VAT identifier (BT-48) or its legal registration identifier (BT-47), and the buyer has neither\",\n )\n}\n\n/**\n * A rate in per cent (BT-119, BT-152), as this version takes one: from 0 to\n * below 100, an exact decimal with two places at most. Chosen, not\n * measured, as `limits.ts`'s bounds are: Germany's 19 and 7 need none, and\n * a rate past the bound is a typo, or a rate in hundredths.\n */\nconst RATE = /^(?:0|[1-9]\\d?)(?:\\.\\d{1,2})?$/\n\n/** A rate without the trailing zeros that do not change its value: 19.00 is 19, 5.50 is 5.5. */\nfunction byValue(rate: string): string {\n return rate.includes('.') ? rate.replace(/\\.?0+$/, '') : rate\n}\n\n/** A rate below 0.5 by value: XPath's `round` makes it 0, which BR-CO-17 reads as a breakdown whose tax rounds to 0. */\nconst BELOW_HALF = /^0\\.[0-4]/\n\n/** What a rate must be for each code, and the rule a rate that is not breaks. */\nconst RATE_RULES: { readonly [C in VatCategoryCode]: { readonly zero: boolean; readonly rule: string } } = {\n S: { zero: false, rule: en16931Rule('BR-S-05', \"is 0, and a standard rated category's rate is more than 0\") },\n E: { zero: true, rule: en16931Rule('BR-E-05', \"is not 0, and an exempt category's rate is 0\") },\n AE: { zero: true, rule: en16931Rule('BR-AE-05', \"is not 0, and a reverse-charged category's rate is 0\") },\n}\n\n/**\n * The rate of a category of `code`, by value, without the trailing zeros\n * that do not change it: more than 0 when standard rated (BR-S-05), 0 when\n * exempt or reverse-charged (BR-E-05, BR-AE-05). Compared as text, never\n * as a JavaScript number: report-spec has no decimal, and needs none.\n *\n * And a standard rate of 0.5 or more (BR-CO-17). CEN's rule rounds the\n * rate first, and XPath's round(0.4) is 0: a breakdown whose rate rounds\n * to 0 must then hold a tax that rounds to 0, which a standard rated\n * category's tax does not past a small basis -- at 0.4, one of 125 or\n * more. No rate of the EU's is that low.\n */\nexport function checkVatRate(code: VatCategoryCode, rate: string): PaymentCheck<string> {\n if (!RATE.test(rate)) return no('is not a rate this release takes: a percentage from 0 to below 100, an exact decimal of two places at most')\n const value = byValue(rate)\n if ((value === '0') !== RATE_RULES[code].zero) return no(RATE_RULES[code].rule)\n if (code === 'S' && BELOW_HALF.test(value)) {\n return no(\n en16931Rule(\n 'BR-CO-17',\n \"is below 0.5, which BR-CO-17 rounds to 0, and a breakdown whose rate rounds to 0 holds a tax that rounds to 0 too: a standard rated category's tax would not, past a small basis\",\n ),\n )\n }\n return ok(value)\n}\n\n/**\n * The rule a category's exemption reason (BT-120) breaks, or undefined:\n * exempt and reverse-charged categories say why (BR-E-10, BR-AE-10), and a\n * standard rated one has no reason to give (BR-S-10).\n */\nexport function vatReasonBreak(code: VatCategoryCode, hasReason: boolean): string | undefined {\n if (code === 'S') return hasReason ? en16931Rule('BR-S-10', 'a standard rated category gives no exemption reason') : undefined\n if (hasReason) return undefined\n return code === 'E'\n ? en16931Rule('BR-E-10', 'an exempt category gives its exemption reason')\n : en16931Rule('BR-AE-10', 'a reverse-charged category gives its reason, \"Reverse charge\" or its words in the invoice\\'s language')\n}\n\n/** A rule a list of categories breaks, and the category and field it is said of. */\nexport interface VatCategoryBreak {\n readonly index: number\n readonly field: 'code' | 'rate'\n readonly rule: string\n}\n\n/** For each code but S, the rule a second category of it breaks: an invoice with a line of the code holds exactly one breakdown of it. */\nconst ONE_BREAKDOWN: { readonly [C in Exclude<VatCategoryCode, 'S'>]: string } = {\n E: en16931Rule('BR-E-01', 'is a second exempt category, and the exempt lines have exactly one breakdown'),\n AE: en16931Rule('BR-AE-01', 'is a second reverse-charged category, and the reverse-charged lines have exactly one breakdown'),\n}\n\n/**\n * The rules a list of categories, each with a rate `checkVatRate` took,\n * breaks together: each is one VAT breakdown (BG-23), so standard rated\n * categories have distinct rates by value (BR-S-08), and there is one\n * exempt and one reverse-charged category at most (BR-E-01, BR-AE-01). Two\n * that would be one breakdown would each claim every one of its lines, and\n * the XML would fail. The later of the two is refused.\n */\nexport function vatCategoryBreaks(categories: readonly { readonly code: VatCategoryCode; readonly rate: string }[]): readonly VatCategoryBreak[] {\n const seen = new Set<string>()\n const breaks: VatCategoryBreak[] = []\n for (const [index, { code, rate }] of categories.entries()) {\n const breakdown = code === 'S' ? `S ${byValue(rate)}` : code\n if (!seen.has(breakdown)) seen.add(breakdown)\n else if (code === 'S')\n breaks.push({\n index,\n field: 'rate',\n rule: en16931Rule('BR-S-08', 'is the rate of an earlier standard rated category, and the standard rated lines have one breakdown for each rate'),\n })\n else breaks.push({ index, field: 'code', rule: ONE_BREAKDOWN[code] })\n }\n return breaks\n}\n\n/** The category a line names by `id`, a category the invoice declares (BR-CO-04). */\nexport function checkLineCategory(id: string, categories: readonly VatCategory[]): PaymentCheck<VatCategory> {\n const category = categories.find((declared) => declared.id === id)\n return category === undefined ? no(en16931Rule('BR-CO-04', 'is not the id of a VAT category this invoice declares, and every line is in one')) : ok(category)\n}\n","/**\n * What one validation knows while it reads a report: what the report\n * declares, which component ids it has seen, where its tables are and how\n * much of the page its margins leave.\n */\nimport type { AnyAssetMediaType } from './assets.js'\nimport { Findings, quote } from './check.js'\nimport type { FieldType, ParameterType } from './data.js'\nimport type { ReportErrorCode } from './errors.js'\nimport type { PageDimensions } from './page.js'\n\n/**\n * Declared names and what each declares. `undefined` when the declarations\n * could not all be read: that was reported where they are, and a reference\n * that matches none of the rest could be the one that was unreadable, so\n * references into them are not reported again, one by one, as unknown.\n */\nexport type Declarations<T> = ReadonlyMap<string, T> | undefined\n\nexport interface Declared {\n styles: Declarations<true>\n /** By role; a role's fields are `undefined` when its contract could not be read. A field's type is `undefined` when its contract could not. */\n datasets: Declarations<Declarations<FieldType | undefined>>\n parameters: Declarations<ParameterType | undefined>\n /** Each asset's media type, so a reference can be held to being an image or a font (0043); `undefined` where the type could not be read. */\n assets: Declarations<AnyAssetMediaType | undefined>\n /** What each aggregate computes, when that is known: what an expression computes is not. */\n aggregates: Declarations<FieldType | undefined>\n /** The fields each dataset role declares that may be null, when its contract could be read; a chart asks the label its null rows print under. */\n nullable: Map<string, ReadonlySet<string>>\n}\n\nexport interface Ctx {\n readonly f: Findings\n readonly declared: Declared\n /** Component ids seen so far, and the path of the first component with each. */\n readonly componentIds: Map<string, string>\n /** Where each table over the detail dataset is, in the order they were read: the bound counts them, and an e-invoice holds one (0062). */\n readonly tables: string[]\n /** What the margins leave of the page, once they are known to leave enough; fixed sizes are measured against it. */\n printable: PageDimensions | undefined\n}\n\nexport function newContext(): Ctx {\n return {\n f: new Findings(),\n declared: { styles: undefined, datasets: undefined, parameters: undefined, assets: undefined, aggregates: undefined, nullable: new Map() },\n componentIds: new Map(),\n tables: [],\n printable: undefined,\n }\n}\n\n/** What `name` declares, after reporting `code` when it is not declared. Nothing is checked when either is unknown. */\nexport function resolve<T>(f: Findings, names: Declarations<T>, name: string | undefined, path: string, code: ReportErrorCode, what: string): T | undefined {\n if (names === undefined || name === undefined) return undefined\n if (names.has(name)) return names.get(name)\n f.report(path, code, `${quote(name)} is not a ${what} this report declares`)\n return undefined\n}\n\n/** One entry of a list of declarations: its id when it could be read, where the id is, and what it declares. */\nexport interface Declaration<T> {\n readonly id: string | undefined\n readonly path: string\n readonly value: T\n}\n\n/**\n * The names a list declares, each id after the first reported as a\n * duplicate, with `code` and what `again` says of it. `undefined` when an id\n * could not be read.\n *\n * One rule for every list whose entries are named -- declarations, a\n * table's columns, a footer row's cells, the keys that order a table -- so\n * that a second entry with one name is refused the same way everywhere.\n */\nexport function declare<T>(f: Findings, entries: readonly Declaration<T>[], code: ReportErrorCode, again: (id: string) => string): Map<string, T> | undefined {\n const declared = new Map<string, T>()\n let complete = true\n for (const { id, path, value } of entries) {\n if (id === undefined) complete = false\n else if (declared.has(id)) f.report(path, code, again(quote(id)))\n else declared.set(id, value)\n }\n return complete ? declared : undefined\n}\n\n/**\n * Reports a fixed length the page cannot hold. The page and its margins are\n * in the same document, so a size that can never fit is refused while the\n * author edits; what fits inside a container is the layout's question.\n */\nexport function withinPage(c: Ctx, length: number | undefined, path: string, side: 'width' | 'height', what: string): void {\n const room = c.printable?.[side]\n if (length === undefined || room === undefined || length <= room) return\n c.f.report(path, 'exceeds-printable-area', `${length} points of ${side} for ${what}, and the margins leave ${room}`)\n}\n","/**\n * Values: what a paragraph, a table cell or a footer is made of, where each\n * kind of value has one, how it is displayed, and where a run may be set\n * below or above the line.\n *\n * Kinds are tables, not switches, as components are: an inline, format or\n * currency source added to its list without a reader here does not compile.\n */\nimport type { RowValue } from './aggregates.js'\nimport { all, flag, integer, kindOf, matches, oneOf, optional, quote, readArray, readList, readObject, reference, shape, strictKeys, text } from './check.js'\nimport type { Findings } from './check.js'\nimport { DATASET_ROLES } from './data.js'\nimport type { FieldRef, FieldType } from './data.js'\nimport type { RegionName } from './definition.js'\nimport { MAX_EXPRESSION_LENGTH, MAX_INLINES, MAX_SCALE, MAX_STYLE_RULES, MAX_TEXT_LENGTH } from './limits.js'\nimport { at } from './pointer.js'\nimport type { StyleRule } from './styles.js'\nimport { CURRENCY } from './syntax.js'\nimport { resolve } from './validate-context.js'\nimport type { Ctx } from './validate-context.js'\nimport { AGGREGATE_SCOPES, BASELINE_SHIFTS, CURRENCY_SOURCE_KINDS, DATE_STYLES, FORMAT_KINDS, INLINE_KINDS, TEXT_TRANSFORMS } from './values.js'\nimport type { BaselineShift, CurrencySource, CurrencySourceKind, Expression, Format, FormatKind, Inline, InlineKind, ValueScope } from './values.js'\n\n/** Where a value is read: the region decides page counters, the scope decides detail fields and a group's aggregates. */\nexport interface InlineScope {\n /** The region the runs stand in, or the payment part or the e-invoice, which stand in none. */\n readonly region: RegionName | 'paymentPart' | 'eInvoice'\n readonly reads: ValueScope\n /** In a group header or footer, the detail field grouped by, when the dataset declares it. */\n readonly groupBy?: string | undefined\n /** What the runs are encoded in, when they are: resolved whole, once, before there are pages to count. */\n readonly encoded?: 'a QR code' | 'an EPC QR code' | 'a QR-bill' | 'an e-invoice'\n /** Whether the runs are a paragraph's, a text component's content: the one place a run may be set below or above the line (0061). */\n readonly paragraph?: true\n}\n\n/** The regions drawn once per page, the only ones in which a page number or count has a value. */\nconst PAGE_REGIONS: readonly InlineScope['region'][] = ['pageHeader', 'pageFooter']\n\nexport function readExpression(f: Findings, value: unknown, path: string): Expression | undefined {\n const o = shape(f, value, path, ['cel'])\n const cel = text(f, o?.cel, at(path, 'cel'), MAX_EXPRESSION_LENGTH)\n if (cel === undefined) return undefined\n if (cel.trim() !== '') return { cel }\n f.report(at(path, 'cel'), 'empty-expression', 'an expression needs something to evaluate, and this one is empty')\n return undefined\n}\n\n/** A reference to a print style the report declares. */\nexport function readStyleRef(c: Ctx, value: unknown, path: string): string | undefined {\n const style = reference(c.f, value, path)\n resolve(c.f, c.declared.styles, style, path, 'unknown-style', 'style')\n return style\n}\n\n/** Conditional styles: each a condition and the style it applies. */\nexport function readStyleRules(c: Ctx, value: unknown, path: string): readonly StyleRule[] | undefined {\n const items = readArray(c.f, value, path, MAX_STYLE_RULES)\n const rules = items?.map((item, index): StyleRule | undefined => {\n const where = at(path, index)\n const o = shape(c.f, item, where, ['when', 'style'])\n const when = readExpression(c.f, o?.when, at(where, 'when'))\n const style = readStyleRef(c, o?.style, at(where, 'style'))\n return when === undefined || style === undefined ? undefined : { when, style }\n })\n return rules && all(rules)\n}\n\n/** A field reference, its field's type when known, and whether the dataset declares the field. */\nexport interface FieldBinding {\n readonly ref: FieldRef\n readonly type: FieldType | undefined\n readonly declared: boolean\n}\n\n/** Reports a detail field read where there is no current row: in the report's scope, and under a table, in its total rows. */\nfunction placeDetailField(c: Ctx, field: string, path: string, scope: InlineScope): void {\n if (scope.reads === 'row') return\n if (scope.reads === 'report' || scope.reads === 'table') {\n c.f.report(path, 'misplaced-detail-field', 'a detail field has a current row only in the cells of the table over the detail dataset')\n } else if (scope.groupBy !== undefined && field !== scope.groupBy) {\n c.f.report(\n path,\n 'misplaced-detail-field',\n `in a group header or footer, the one detail field with a single value is the one grouped by, ${quote(scope.groupBy)}`,\n )\n }\n}\n\n/**\n * A FieldRef read in `scope`, or, where only a detail field can be named --\n * a sort key, a group key, what an aggregate reads -- with `scope` 'detail'.\n */\nexport function readFieldRef(c: Ctx, value: unknown, path: string, scope: InlineScope | 'detail'): FieldBinding | undefined {\n const o = shape(c.f, value, path, ['dataset', 'field'])\n const dataset = oneOf(c.f, o?.dataset, at(path, 'dataset'), scope === 'detail' ? (['detail'] as const) : DATASET_ROLES)\n const field = reference(c.f, o?.field, at(path, 'field'))\n if (scope !== 'detail' && dataset === 'detail' && field !== undefined) placeDetailField(c, field, path, scope)\n const fields = resolve(c.f, c.declared.datasets, dataset, at(path, 'dataset'), 'unknown-dataset', 'dataset')\n const type = resolve(c.f, fields, field, at(path, 'field'), 'unknown-field', `field of the ${String(dataset)} dataset`)\n if (dataset === undefined || field === undefined) return undefined\n return { ref: { dataset, field }, type, declared: fields?.has(field) === true }\n}\n\n/** Reports a field or parameter whose type is not `wanted`, where it is bound. */\nfunction expectType(c: Ctx, type: FieldType | undefined, wanted: FieldType, path: string, where: string): void {\n if (type !== undefined && type !== wanted) c.f.report(path, 'binding-type-mismatch', `${where} reads a ${wanted}, and this is a ${type}`)\n}\n\ntype CurrencyReader = (c: Ctx, o: Record<string, unknown>, path: string, scope: InlineScope) => CurrencySource | undefined\n\nconst CURRENCIES: { readonly [K in CurrencySourceKind]: { readonly required: readonly string[]; readonly read: CurrencyReader } } = {\n code: {\n required: ['code'],\n read: (c, o, path) => {\n const code = matches(c.f, o.code, at(path, 'code'), CURRENCY, 'invalid-currency', 'an ISO 4217 code in capitals, such as CHF')\n return code === undefined ? undefined : { kind: 'code', code }\n },\n },\n field: {\n required: ['field'],\n read: (c, o, path, scope) => {\n const field = readFieldRef(c, o.field, at(path, 'field'), scope)\n expectType(c, field?.type, 'string', at(path, 'field'), 'a currency')\n return field && { kind: 'field', field: field.ref }\n },\n },\n parameter: {\n required: ['parameter'],\n read: (c, o, path) => {\n const parameter = reference(c.f, o.parameter, at(path, 'parameter'))\n const type = resolve(c.f, c.declared.parameters, parameter, at(path, 'parameter'), 'unknown-parameter', 'parameter')\n expectType(c, type, 'string', at(path, 'parameter'), 'a currency')\n return parameter === undefined ? undefined : { kind: 'parameter', parameter }\n },\n },\n}\n\nfunction readCurrency(c: Ctx, value: unknown, path: string, scope: InlineScope): CurrencySource | undefined {\n const o = readObject(c.f, value, path)\n const kind = o && kindOf(c.f, o, path, CURRENCY_SOURCE_KINDS)\n if (o === undefined || kind === undefined) return undefined\n strictKeys(c.f, o, path, ['kind', ...CURRENCIES[kind].required])\n return CURRENCIES[kind].read(c, o, path, scope)\n}\n\ntype FormatReader = (c: Ctx, o: Record<string, unknown>, path: string, scope: InlineScope) => Format | undefined\n\nconst FORMATS: { readonly [K in FormatKind]: FormatReader } = {\n number: (c, o, path) => {\n strictKeys(c.f, o, path, ['kind', 'scale', 'grouping'])\n const scale = integer(c.f, o.scale, at(path, 'scale'), 0, MAX_SCALE)\n const grouping = flag(c.f, o.grouping, at(path, 'grouping'))\n return scale === undefined || grouping === undefined ? undefined : { kind: 'number', scale, grouping }\n },\n currency: (c, o, path, scope) => {\n strictKeys(c.f, o, path, ['kind', 'currency', 'scale'])\n const currency = readCurrency(c, o.currency, at(path, 'currency'), scope)\n const scale = integer(c.f, o.scale, at(path, 'scale'), 0, MAX_SCALE)\n return currency === undefined || scale === undefined ? undefined : { kind: 'currency', currency, scale }\n },\n date: (c, o, path) => {\n strictKeys(c.f, o, path, ['kind', 'style'])\n const style = oneOf(c.f, o.style, at(path, 'style'), DATE_STYLES)\n return style === undefined ? undefined : { kind: 'date', style }\n },\n text: (c, o, path) => {\n strictKeys(c.f, o, path, ['kind'], ['transform'])\n return { kind: 'text', ...optional('transform', oneOf(c.f, o.transform, at(path, 'transform'), TEXT_TRANSFORMS)) }\n },\n}\n\nexport function readFormat(c: Ctx, value: unknown, path: string, scope: InlineScope): Format | undefined {\n const o = readObject(c.f, value, path)\n const kind = o && kindOf(c.f, o, path, FORMAT_KINDS)\n return o && kind && FORMATS[kind](c, o, path, scope)\n}\n\n/** The types each format displays. Text displays anything that prints. */\nconst FORMATTED: { readonly [K in FormatKind]: readonly FieldType[] | 'any' } = {\n number: ['integer', 'decimal'],\n currency: ['integer', 'decimal'],\n date: ['date', 'datetime', 'instant'],\n text: 'any',\n}\n\n/**\n * The format at `path` read, and reported when it does not display a value\n * of `type`. An expression's type is known only when the runtime compiles\n * it, so its format is not checked here: `type` is then undefined.\n */\nexport function readCheckedFormat(c: Ctx, value: unknown, path: string, scope: InlineScope, type: FieldType | undefined): Format | undefined {\n const format = readFormat(c, value, path, scope)\n const formatted = format && FORMATTED[format.kind]\n if (format !== undefined && type !== undefined && formatted !== 'any' && formatted?.includes(type) === false) {\n c.f.report(path, 'format-type-mismatch', `a ${format.kind} format displays ${formatted.join(', ')} values, and this value is a ${type}`)\n }\n return format\n}\n\n/**\n * A page number or count, and whether it stands where it has a value: in\n * the page header and footer, printed. A table never stands in a page\n * region, so its cells are refused by region too; what a QR code, an EPC\n * QR code, a QR-bill or an e-invoice encodes is resolved before there are\n * pages, so it is refused in every region. The first page's own header is\n * drawn on page 1 alone, when page 1 is laid out and before the pages are\n * counted (0060): a count there has no value, and a number that is always\n * 1 is text.\n */\nfunction readCounter(c: Ctx, path: string, scope: InlineScope, kind: 'pageNumber' | 'pageCount'): Inline {\n if (scope.encoded !== undefined) {\n c.f.report(\n path,\n 'misplaced-page-counter',\n `what ${scope.encoded} encodes is resolved once, before pages are counted, so a page number or count has no value in it`,\n )\n } else if (scope.region === 'firstPageHeader') {\n c.f.report(\n path,\n 'misplaced-page-counter',\n \"the first page's own header is drawn before pages are counted, so a page number or count has no value in it; the page footer prints page 1's\",\n )\n } else if (!PAGE_REGIONS.includes(scope.region)) {\n c.f.report(path, 'misplaced-page-counter', `page numbers and counts have a value only in the page header and footer, not in the ${scope.region}`)\n }\n return { kind }\n}\n\n/**\n * A run's baseline (0061), read where a paragraph is. Anywhere else a run\n * is read, the property is refused whatever its value: what a code encodes\n * is its text alone, and a table's cell prints one string at one size.\n */\nfunction readBaseline(c: Ctx, value: unknown, path: string, scope: InlineScope): BaselineShift | undefined {\n if (value === undefined) return undefined\n if (scope.paragraph === true) return oneOf(c.f, value, path, BASELINE_SHIFTS)\n const said =\n scope.encoded === undefined\n ? \"a table's cell, footer cell or group header prints one string at one size; a run is set below or above the line only in a text's paragraph\"\n : `what ${scope.encoded} encodes is its text alone, and a run's place below or above the line is no part of it`\n c.f.report(path, 'misplaced-baseline', said)\n return undefined\n}\n\ninterface InlineRule {\n readonly required: readonly string[]\n readonly optional?: readonly string[]\n /** Whether a run of the kind may be set below or above the line: every kind that prints a value, and no page counter, which the engine fills. */\n readonly shifts: boolean\n readonly read: (c: Ctx, o: Record<string, unknown>, path: string, scope: InlineScope) => Inline | undefined\n}\n\n/** Whether the type of a run of kind `K` has a baseline, which its rule must say: the table and the types cannot disagree. */\ntype Shifts<K extends InlineKind> = 'baseline' extends keyof Extract<Inline, { readonly kind: K }> ? true : false\n\nconst INLINES: { readonly [K in InlineKind]: InlineRule & { readonly shifts: Shifts<K> } } = {\n text: {\n required: ['text'],\n shifts: true,\n read: (c, o, path) => {\n const literal = text(c.f, o.text, at(path, 'text'), MAX_TEXT_LENGTH)\n return literal === undefined ? undefined : { kind: 'text', text: literal }\n },\n },\n field: {\n required: ['field'],\n optional: ['format'],\n shifts: true,\n read: (c, o, path, scope) => {\n const field = readFieldRef(c, o.field, at(path, 'field'), scope)\n // An image is drawn by an image component; printed, it would be an asset id.\n if (field?.type === 'image') c.f.report(at(path, 'field'), 'binding-type-mismatch', 'an image field is drawn by an image, never printed as text')\n const format = readCheckedFormat(c, o.format, at(path, 'format'), scope, field?.type === 'image' ? undefined : field?.type)\n return field && { kind: 'field', field: field.ref, ...optional('format', format) }\n },\n },\n parameter: {\n required: ['parameter'],\n optional: ['format'],\n shifts: true,\n read: (c, o, path, scope) => {\n const parameter = reference(c.f, o.parameter, at(path, 'parameter'))\n const type = resolve(c.f, c.declared.parameters, parameter, at(path, 'parameter'), 'unknown-parameter', 'parameter')\n const format = readCheckedFormat(c, o.format, at(path, 'format'), scope, type)\n return parameter === undefined ? undefined : { kind: 'parameter', parameter, ...optional('format', format) }\n },\n },\n expression: {\n required: ['expression'],\n optional: ['format'],\n shifts: true,\n read: (c, o, path, scope) => {\n const expression = readExpression(c.f, o.expression, at(path, 'expression'))\n const format = readCheckedFormat(c, o.format, at(path, 'format'), scope, undefined)\n return expression && { kind: 'expression', expression, ...optional('format', format) }\n },\n },\n aggregate: {\n required: ['aggregate', 'over'],\n optional: ['format'],\n shifts: true,\n read: (c, o, path, scope) => {\n const aggregate = reference(c.f, o.aggregate, at(path, 'aggregate'))\n const type = resolve(c.f, c.declared.aggregates, aggregate, at(path, 'aggregate'), 'unknown-aggregate', 'aggregate')\n const over = oneOf(c.f, o.over, at(path, 'over'), AGGREGATE_SCOPES)\n if (over === 'group' && scope.reads !== 'group') {\n c.f.report(\n at(path, 'over'),\n 'misplaced-group-aggregate',\n 'an aggregate over a group has a value only in that group\\'s header and footer; over \"report\", it is taken over every row',\n )\n }\n // A group's header and footer stand under a table too, and read its totals (0062).\n if (over === 'table' && scope.reads !== 'table' && scope.reads !== 'group') {\n c.f.report(\n at(path, 'over'),\n 'misplaced-table-aggregate',\n 'an aggregate over a table has a value only in its total rows and its group\\'s header and footer; over \"report\", it is taken over every row',\n )\n }\n const format = readCheckedFormat(c, o.format, at(path, 'format'), scope, type)\n return aggregate === undefined || over === undefined ? undefined : { kind: 'aggregate', aggregate, over, ...optional('format', format) }\n },\n },\n pageNumber: { required: [], shifts: false, read: (c, _o, path, scope) => readCounter(c, path, scope, 'pageNumber') },\n pageCount: { required: [], shifts: false, read: (c, _o, path, scope) => readCounter(c, path, scope, 'pageCount') },\n}\n\nexport function readInline(c: Ctx, value: unknown, path: string, scope: InlineScope): Inline | undefined {\n const o = readObject(c.f, value, path)\n const kind = o && kindOf(c.f, o, path, INLINE_KINDS)\n if (o === undefined || kind === undefined) return undefined\n const rule = INLINES[kind]\n strictKeys(c.f, o, path, ['kind', ...rule.required], [...(rule.optional ?? []), ...(rule.shifts ? ['baseline'] : [])])\n const inline = rule.read(c, o, path, scope)\n if (!rule.shifts) return inline\n const baseline = readBaseline(c, o.baseline, at(path, 'baseline'), scope)\n return inline && { ...inline, ...optional('baseline', baseline) }\n}\n\n/** Runs, at least `min` of them: none is an empty line in a paragraph, and nothing at all in a QR code. */\nexport function readInlines(c: Ctx, value: unknown, path: string, scope: InlineScope, min = 0): readonly Inline[] | undefined {\n const items = readList(c.f, value, path, min, MAX_INLINES)\n return items && all(items.map((item, index) => readInline(c, item, at(path, index), scope)))\n}\n\n/** What an aggregate reads from each row, and that value's type when it is a field's. */\nexport function readRowValue(c: Ctx, value: unknown, path: string): { value: RowValue; type: FieldType | undefined } | undefined {\n const o = readObject(c.f, value, path)\n const kind = o && kindOf(c.f, o, path, ['field', 'expression'] as const)\n if (o === undefined || kind === undefined) return undefined\n strictKeys(c.f, o, path, ['kind', kind])\n if (kind === 'expression') {\n const expression = readExpression(c.f, o.expression, at(path, 'expression'))\n return expression && { value: { kind, expression }, type: undefined }\n }\n const field = readFieldRef(c, o.field, at(path, 'field'), 'detail')\n return field && { value: { kind, field: field.ref }, type: field.type }\n}\n","/**\n * Aggregates: the totals a report computes over its detail rows, declared\n * once and printed by id, and the rounding each declares.\n */\nimport { AGGREGATE_FUNCTIONS, ROUNDING_MODES } from './aggregates.js'\nimport type { AggregateDef, AggregateFunction, Rounding } from './aggregates.js'\nimport type { Findings } from './check.js'\nimport { all, fieldKey, integer, matches, oneOf, optional, readArray, shape } from './check.js'\nimport type { FieldType } from './data.js'\nimport { MAX_AGGREGATES, MAX_SCALE } from './limits.js'\nimport { at } from './pointer.js'\nimport { DECIMAL } from './syntax.js'\nimport { declare } from './validate-context.js'\nimport type { Ctx } from './validate-context.js'\nimport { readRowValue } from './validate-inline.js'\nimport { GROUP_KEY } from './values.js'\n\nconst NUMERIC: readonly FieldType[] = ['integer', 'decimal']\nconst ORDERED: readonly FieldType[] = [...NUMERIC, 'date', 'datetime', 'instant']\n\n/**\n * What each function reads, and what it computes from a value of a type:\n * a count is an integer, an average a decimal, and a sum, minimum or\n * maximum the type it read. Unknown when what it read is an expression.\n */\nconst FUNCTIONS: {\n readonly [F in AggregateFunction]: { readonly takes: readonly FieldType[] | 'any'; readonly gives: (of: FieldType | undefined) => FieldType | undefined }\n} = {\n sum: { takes: NUMERIC, gives: (of) => of },\n avg: { takes: NUMERIC, gives: () => 'decimal' },\n min: { takes: ORDERED, gives: (of) => of },\n max: { takes: ORDERED, gives: (of) => of },\n count: { takes: 'any', gives: () => 'integer' },\n}\n\n/** A rounding increment: an exact decimal more than 0, with no more places than `scale`. */\nfunction readIncrement(f: Findings, value: unknown, path: string, scale: number | undefined): string | undefined {\n const increment = matches(f, value, path, DECIMAL, 'invalid-decimal', 'an exact decimal such as \"0.05\"')\n if (increment === undefined) return undefined\n if (increment.startsWith('-') || /^0(?:\\.0+)?$/.test(increment)) {\n f.report(path, 'out-of-range', `an increment of ${increment} rounds to nothing; it must be more than 0`)\n return undefined\n }\n const places = increment.split('.')[1]?.length ?? 0\n if (scale !== undefined && places > scale) {\n f.report(path, 'out-of-range', `an increment of ${increment} has ${places} decimal places, more than the ${scale} this rounding keeps`)\n return undefined\n }\n return increment\n}\n\nexport function readRounding(f: Findings, value: unknown, path: string): Rounding | undefined {\n const o = shape(f, value, path, ['scale', 'mode'], ['increment'])\n const scale = integer(f, o?.scale, at(path, 'scale'), 0, MAX_SCALE)\n const mode = oneOf(f, o?.mode, at(path, 'mode'), ROUNDING_MODES)\n const increment = readIncrement(f, o?.increment, at(path, 'increment'), scale)\n return scale === undefined || mode === undefined ? undefined : { scale, mode, ...optional('increment', increment) }\n}\n\nfunction readAggregate(c: Ctx, value: unknown, path: string): { id: string | undefined; gives: FieldType | undefined; aggregate: AggregateDef | undefined } {\n const o = shape(c.f, value, path, ['id', 'fn'], ['of', 'rounding'])\n const id = fieldKey(c.f, o?.id, at(path, 'id'))\n // group.key is the value a group is keyed by; an aggregate of that name would be read there as one or the other.\n if (id === GROUP_KEY)\n c.f.report(\n at(path, 'id'),\n 'reserved-id',\n `an aggregate cannot be called ${GROUP_KEY}: in a group's header and footer, group.${GROUP_KEY} is the value the group is keyed by`,\n )\n const fn = oneOf(c.f, o?.fn, at(path, 'fn'), AGGREGATE_FUNCTIONS)\n const of = readRowValue(c, o?.of, at(path, 'of'))\n if (o !== undefined && fn !== undefined && fn !== 'count' && !Object.hasOwn(o, 'of')) {\n c.f.report(at(path, 'of'), 'missing-property', `a ${fn} needs a value from each row; only a count may leave it out, to count rows`)\n }\n const takes = fn && FUNCTIONS[fn].takes\n const mismatch = takes !== undefined && takes !== 'any' && of?.type !== undefined && !takes.includes(of.type)\n if (mismatch) c.f.report(at(at(path, 'of'), 'field'), 'aggregate-type-mismatch', `${fn} takes ${takes.join(', ')} values, and this field is a ${of.type}`)\n const rounding = readRounding(c.f, o?.rounding, at(path, 'rounding'))\n // An exact average is rarely a terminating decimal: 1, 1 and 2 average 1.333...\n if (o !== undefined && fn === 'avg' && !Object.hasOwn(o, 'rounding')) {\n c.f.report(at(path, 'rounding'), 'missing-property', 'an average is rarely exact, so it says how it is rounded')\n }\n // A refused aggregate computes nothing known, so what prints it is not refused again for that.\n const gives = mismatch ? undefined : fn && FUNCTIONS[fn].gives(of?.type)\n if (id === undefined || fn === undefined || (o?.of !== undefined && of === undefined)) return { id, gives, aggregate: undefined }\n return { id, gives, aggregate: { id, fn, ...optional('of', of?.value), ...optional('rounding', rounding) } }\n}\n\nexport function readAggregates(c: Ctx, value: unknown, path: string): readonly AggregateDef[] | undefined {\n const items = readArray(c.f, value, path, MAX_AGGREGATES)\n if (items === undefined) return undefined\n const read = items.map((item, index) => ({ index, ...readAggregate(c, item, at(path, index)) }))\n c.declared.aggregates = declare(\n c.f,\n read.map(({ id, index, gives }) => ({ id, path: at(at(path, index), 'id'), value: gives })),\n 'duplicate-id',\n (duplicate) => `another aggregate is already ${duplicate}`,\n )\n return all(read.map(({ aggregate }) => aggregate))\n}\n","/**\n * A chart: its shape, and the rules that make what it draws a chart of\n * something. Its category and its series read detail fields and nothing\n * else (a chart holds no expression), so their types are checked here,\n * statically; the runtime totals each series exactly, once, with the\n * function an aggregate is totalled with.\n *\n * A chart is held to what a reader could use: a series told apart in the\n * legend, a category that has a word for its null rows, a pie that is a\n * share of a whole. What only the data can say -- whether the categories\n * fit the box, whether every value is zero -- is the runtime's and the\n * renderer's, and is refused there, never cut to fit.\n */\nimport { AGGREGATE_FUNCTIONS } from './aggregates.js'\nimport type { AggregateFunction, Rounding } from './aggregates.js'\nimport { all, flag, identifier, matches, oneOf, optional, points, readList, shape, text } from './check.js'\nimport { CHART_CATEGORY_TYPES, CHART_KINDS, CHART_ORDERS, CHART_PALETTE, PIE_FUNCTIONS } from './chart.js'\nimport type { ChartCategory, ChartComponent, ChartKind, ChartSeries } from './chart.js'\nimport type { ComponentBase } from './components.js'\nimport type { FieldType } from './data.js'\nimport type { RegionName } from './definition.js'\nimport { MAX_CHART_SERIES, MAX_LABEL_LENGTH, MIN_CHART_SIDE } from './limits.js'\nimport { at } from './pointer.js'\nimport { COLOR } from './syntax.js'\nimport { readRounding } from './validate-aggregates.js'\nimport { declare, withinPage } from './validate-context.js'\nimport type { Ctx } from './validate-context.js'\nimport { readCheckedFormat, readFieldRef, readFormat } from './validate-inline.js'\nimport type { InlineScope } from './validate-inline.js'\n\nexport const CHART_REQUIRED = ['chart', 'dataset', 'width', 'height', 'category', 'series', 'valueFormat', 'emptyText']\nexport const CHART_OPTIONAL = ['title', 'categoryTitle', 'valueTitle', 'valueLabels', 'palette']\n\n/** What a series totals: a sum, an average, a minimum or a maximum of text or of a date has no number to print. A count takes any field. */\nconst TOTALLED: readonly FieldType[] = ['integer', 'decimal']\n\n/** A side of the box, held to what a plot needs and to the printable area, as an image's box is held to the page. */\nfunction side(c: Ctx, value: unknown, path: string, which: 'width' | 'height'): number | undefined {\n const length = points(c.f, value, path, 'positive')\n if (length === undefined) return undefined\n if (length < MIN_CHART_SIDE) {\n c.f.report(path, 'out-of-range', `${length} points of ${which} leaves a chart no plot beneath its words; at least ${MIN_CHART_SIDE} are needed`)\n return undefined\n }\n withinPage(c, length, path, which, 'this chart')\n return length\n}\n\n/** A label, title or text, and whether it is blank where a reader needs words. */\nfunction words(c: Ctx, value: unknown, path: string, needed: string | undefined): string | undefined {\n const read = text(c.f, value, path, MAX_LABEL_LENGTH)\n if (read !== undefined && needed !== undefined && read.trim() === '') c.f.report(path, 'invalid-chart', `${needed} cannot be blank`)\n return read\n}\n\nfunction readCategory(c: Ctx, value: unknown, path: string, scope: InlineScope): ChartCategory | undefined {\n const o = shape(c.f, value, path, ['field', 'order'], ['format', 'nullLabel'])\n if (o === undefined) return undefined\n const field = readFieldRef(c, o.field, at(path, 'field'), 'detail')\n const order = oneOf(c.f, o.order, at(path, 'order'), CHART_ORDERS)\n if (field?.type !== undefined && !CHART_CATEGORY_TYPES.includes(field.type)) {\n c.f.report(at(path, 'field'), 'binding-type-mismatch', `a chart groups by ${CHART_CATEGORY_TYPES.join(', ')} values, and this field is a ${field.type}`)\n }\n const format = readCheckedFormat(c, o.format, at(path, 'format'), scope, field?.type)\n const nullLabel = words(c, o.nullLabel, at(path, 'nullLabel'), 'the label of the rows without a category')\n // Rows without a category would be drawn under no word, or dropped.\n if (field !== undefined && !Object.hasOwn(o, 'nullLabel') && c.declared.nullable.get(field.ref.dataset)?.has(field.ref.field) === true) {\n c.f.report(at(path, 'nullLabel'), 'missing-property', 'this field may be null, so the chart says what its rows without a value are called')\n }\n return field === undefined || order === undefined\n ? undefined\n : { field: field.ref, order, ...optional('format', format), ...optional('nullLabel', nullLabel) }\n}\n\n/** A series, and its function when that could be read: a pie is held to it. */\nfunction readSeries(c: Ctx, value: unknown, path: string): { series: ChartSeries | undefined; fn: AggregateFunction | undefined } {\n const o = shape(c.f, value, path, ['id', 'label', 'fn'], ['of', 'rounding'])\n if (o === undefined) return { series: undefined, fn: undefined }\n const id = identifier(c.f, o.id, at(path, 'id'))\n const label = words(c, o.label, at(path, 'label'), \"the label of a series, the legend's entry for it,\")\n const fn = oneOf(c.f, o.fn, at(path, 'fn'), AGGREGATE_FUNCTIONS)\n const of = o.of === undefined ? undefined : readFieldRef(c, o.of, at(path, 'of'), 'detail')\n if (fn !== undefined && fn !== 'count' && o.of === undefined) {\n c.f.report(at(path, 'of'), 'missing-property', `a ${fn} needs a field to total; only a count may leave it out, to count rows`)\n }\n const mismatch = fn !== undefined && fn !== 'count' && of?.type !== undefined && !TOTALLED.includes(of.type)\n if (mismatch) c.f.report(at(path, 'of'), 'aggregate-type-mismatch', `${fn} takes ${TOTALLED.join(' or ')} values, and this field is a ${of.type}`)\n const rounding: Rounding | undefined = readRounding(c.f, o.rounding, at(path, 'rounding'))\n // An exact average is rarely a terminating decimal: 1, 1 and 2 average 1.333...\n if (fn === 'avg' && o.rounding === undefined) c.f.report(at(path, 'rounding'), 'missing-property', 'an average is rarely exact, so it says how it is rounded')\n if (id === undefined || label === undefined || fn === undefined || (o.of !== undefined && of === undefined)) return { series: undefined, fn }\n return { series: { id, label, fn, ...optional('of', of?.ref), ...optional('rounding', rounding) }, fn }\n}\n\nfunction readPalette(c: Ctx, value: unknown, path: string): readonly string[] | undefined {\n const items = readList(c.f, value, path, 1, CHART_PALETTE.length)\n // A palette of nothing is refused as too few, and is no palette to hold to the series.\n if (items === undefined || items.length === 0) return undefined\n const colors = items.map((item, index) => matches(c.f, item, at(path, index), COLOR, 'invalid-color', 'a colour written #rrggbb in lower case'))\n // Two series of one colour are told apart by nothing.\n colors.forEach((color, index) => {\n if (color !== undefined && colors.indexOf(color) < index) c.f.report(at(path, index), 'invalid-chart', `the palette already has ${color}`)\n })\n return all(colors)\n}\n\n/**\n * What each kind of chart refuses, as `invalid-chart`, once its series and\n * its palette are read: a pie is the shares of one sum or count and has no\n * axis; a line of several series has no value labels; a bar or a line has\n * a colour for each series. A pie's colours go to its categories, which\n * only the data counts.\n */\nfunction kindRules(\n c: Ctx,\n o: Record<string, unknown>,\n path: string,\n chart: ChartKind | undefined,\n fns: readonly (AggregateFunction | undefined)[] | undefined,\n palette: readonly string[] | undefined,\n): void {\n if (chart === 'pie') {\n for (const key of ['categoryTitle', 'valueTitle'] as const) {\n if (o[key] !== undefined) c.f.report(at(path, key), 'invalid-chart', `a pie has no axis to title`)\n }\n }\n if (chart === undefined || fns === undefined) return\n const where = at(path, 'series')\n if (chart === 'pie') {\n if (fns.length > 1) c.f.report(where, 'invalid-chart', `a pie is the shares of one series, and this chart has ${fns.length}`)\n for (const [index, fn] of fns.entries()) {\n if (fn !== undefined && !PIE_FUNCTIONS.includes(fn)) {\n c.f.report(\n at(at(where, index), 'fn'),\n 'invalid-chart',\n `a pie shows shares of a whole, which only ${PIE_FUNCTIONS.join(' or ')} give; a ${fn} is no share`,\n )\n }\n }\n return\n }\n if (chart === 'line' && o.valueLabels === true && fns.length > 1) {\n c.f.report(at(path, 'valueLabels'), 'invalid-chart', 'value labels on a line of several series would be printed over one another at a category')\n }\n // A series past the palette's end would be drawn in a colour nobody chose, or in none.\n if (palette !== undefined && palette.length < fns.length) {\n const said = `this chart has ${fns.length} series, and its palette colours ${palette.length} of them; each series is drawn in a colour of its own`\n c.f.report(at(path, 'palette'), 'invalid-chart', said)\n }\n}\n\nexport function readChart(c: Ctx, o: Record<string, unknown>, path: string, region: RegionName, base: ComponentBase | undefined): ChartComponent | undefined {\n const scope: InlineScope = { region, reads: 'report' }\n const chart = oneOf(c.f, o.chart, at(path, 'chart'), CHART_KINDS)\n const dataset = oneOf(c.f, o.dataset, at(path, 'dataset'), ['detail'] as const)\n const chartWidth = side(c, o.width, at(path, 'width'), 'width')\n const height = side(c, o.height, at(path, 'height'), 'height')\n const category = readCategory(c, o.category, at(path, 'category'), scope)\n\n const where = at(path, 'series')\n const items = readList(c.f, o.series, where, 1, MAX_CHART_SERIES)\n const read = items?.map((item, index) => readSeries(c, item, at(where, index)))\n if (read !== undefined && items !== undefined) {\n declare(\n c.f,\n read.map(({ series }, index) => ({ id: series?.id, path: at(at(where, index), 'id'), value: true as const })),\n 'duplicate-id',\n (duplicate) => `another series of this chart is already ${duplicate}`,\n )\n }\n const series = read && all(read.map((entry) => entry.series))\n\n // The values print in a number or a currency, read where the report is: a chart has no current row.\n const valueFormat = readFormat(c, o.valueFormat, at(path, 'valueFormat'), scope)\n if (valueFormat !== undefined && valueFormat.kind !== 'number' && valueFormat.kind !== 'currency') {\n c.f.report(\n at(path, 'valueFormat'),\n 'format-type-mismatch',\n `a chart prints totals, in a number or a currency format, and this is a ${valueFormat.kind} format`,\n )\n }\n const emptyText = words(c, o.emptyText, at(path, 'emptyText'), 'the text a chart with nothing to draw prints')\n const title = text(c.f, o.title, at(path, 'title'), MAX_LABEL_LENGTH)\n const categoryTitle = text(c.f, o.categoryTitle, at(path, 'categoryTitle'), MAX_LABEL_LENGTH)\n const valueTitle = text(c.f, o.valueTitle, at(path, 'valueTitle'), MAX_LABEL_LENGTH)\n const valueLabels = flag(c.f, o.valueLabels, at(path, 'valueLabels'))\n const palette = readPalette(c, o.palette, at(path, 'palette'))\n // The kinds' own rules last: each needs the series read.\n const fns = read?.map(({ fn }) => fn)\n kindRules(c, o, path, chart, fns, palette)\n\n if (base === undefined || chart === undefined || dataset === undefined || chartWidth === undefined || height === undefined) return undefined\n if (category === undefined || series === undefined || valueFormat === undefined || emptyText === undefined) return undefined\n if (valueFormat.kind !== 'number' && valueFormat.kind !== 'currency') return undefined\n if (o.palette !== undefined && palette === undefined) return undefined\n return {\n ...base,\n kind: 'chart',\n chart,\n dataset,\n width: chartWidth,\n height,\n category,\n series,\n valueFormat,\n emptyText,\n ...optional('title', title),\n ...optional('categoryTitle', categoryTitle),\n ...optional('valueTitle', valueTitle),\n ...optional('valueLabels', valueLabels),\n ...optional('palette', palette),\n }\n}\n","/**\n * The texts a payment code holds, read one way for every code -- a\n * QR-bill's, an EPC QR code's, and an e-invoice's, the XML a payment is\n * made from: runs, one at least, read as a paragraph's in the report's\n * scope, but for a baseline, which has no place in a code (0061), and\n * encoded in the code; and, when every run is literal, the text they make\n * held to the code's own rule where it is written.\n *\n * A text of literal runs prints the same in every render, so its code's\n * rule is applied to it here; any other is checked by the runtime with the\n * same rule, once the data has resolved it.\n */\nimport { readArray } from './check.js'\nimport type { ReportErrorCode } from './errors.js'\nimport { MAX_INLINES } from './limits.js'\nimport type { PaymentCheck } from './payment-reference.js'\nimport { at } from './pointer.js'\nimport type { Ctx } from './validate-context.js'\nimport { readInlines } from './validate-inline.js'\nimport type { InlineScope } from './validate-inline.js'\nimport type { Inline } from './values.js'\n\n/** Where a payment code's runs are read: in the report's scope, encoded in the code it names. */\nexport type PaymentScope = InlineScope & { readonly reads: 'report'; readonly encoded: 'a QR-bill' | 'an EPC QR code' | 'an e-invoice' }\n\n/** The text runs make when every one is literal; undefined when any is read from data, or there are none, which is refused as too few. */\nexport function literal(runs: readonly Inline[]): string | undefined {\n if (runs.length === 0) return undefined\n let text = ''\n for (const run of runs) {\n if (run.kind !== 'text') return undefined\n text += run.text\n }\n return text\n}\n\n/**\n * A string where a code expects runs, a run or an address, refused as the\n * wrong type without the quote the shared readers give a string they find:\n * written out, it is an IBAN, a name or a street, which may be a person's.\n */\nexport function unquoted(c: Ctx, path: string, expected: string, scope: PaymentScope): undefined {\n c.f.report(path, 'wrong-type', `expected ${expected}, found a string, which is not quoted: what ${scope.encoded} holds may be a person's`)\n return undefined\n}\n\n/** The runs at `path`, one at least, read as a paragraph's are; a string in their place, or in a run's, refused unquoted. */\nfunction readRuns(c: Ctx, value: unknown, path: string, scope: PaymentScope): readonly Inline[] | undefined {\n const items = typeof value === 'string' ? unquoted(c, path, 'an array', scope) : readArray(c.f, value, path, MAX_INLINES)\n const strings = items?.flatMap((item, index) => (typeof item === 'string' ? [index] : [])) ?? []\n for (const index of strings) unquoted(c, at(path, index), 'an object', scope)\n return items === undefined || strings.length > 0 ? undefined : readInlines(c, items, path, scope, 1)\n}\n\n/** A text of a code: its runs, and what its rule made of them when they are literal and it accepted them. */\nexport interface PaymentText<T> {\n readonly runs: readonly Inline[] | undefined\n readonly checked: T | undefined\n}\n\n/**\n * The runs at `path`, one at least, and the rule `check` applied to them\n * when they are literal, refused as `code`, `what` breaking it. Absent,\n * nothing is said: whether it may be is the shape's question.\n */\nexport function readPaymentText<T>(\n c: Ctx,\n value: unknown,\n path: string,\n scope: PaymentScope,\n code: ReportErrorCode,\n what: string,\n check: (text: string) => PaymentCheck<T>,\n): PaymentText<T> {\n const runs = readRuns(c, value, path, scope)\n const text = runs && literal(runs)\n if (text === undefined) return { runs, checked: undefined }\n const outcome = check(text)\n if (!outcome.ok) c.f.report(path, code, `${what} ${outcome.rule}`)\n return { runs, checked: outcome.ok ? outcome.value : undefined }\n}\n","/**\n * An EPC QR code: its shape, and the EPC's rules applied to every text no\n * data can change.\n *\n * Its texts are runs read in the report's scope and encoded in the code,\n * so they read what a paragraph in its place reads and never a page number\n * or count, as `validate-payment-text.ts` reads every payment code's. A\n * text of literal runs prints the same in every render, so\n * `epc-payload.ts`'s rules are applied to it here, where it is written; any\n * other is checked by the runtime with the same rules, once the data has\n * resolved it. A literal optional text that is blank is refused as the\n * text left out, so that a code has one spelling (`checkEpcField`). What\n * only literal texts can say together is said too: a BIC the IBAN does not\n * go with, and a payload already past its bytes before any data is read.\n */\nimport { oneOf, optional, reference } from './check.js'\nimport type { ComponentBase } from './components.js'\nimport type { RegionName } from './definition.js'\nimport { checkEpcField, checkEpcPayload, checkEpcPurpose, EPC_TEXT_FIELDS, epcPairing, epcPayload } from './epc-payload.js'\nimport type { EpcTextField } from './epc-payload.js'\nimport { epcCaptionBreak } from './epc-print.js'\nimport { EPC_CAPTIONS } from './epc-qr-code.js'\nimport type { EpcQrCodeComponent } from './epc-qr-code.js'\nimport { at } from './pointer.js'\nimport type { Ctx } from './validate-context.js'\nimport { readExpression } from './validate-inline.js'\nimport { readPaymentText } from './validate-payment-text.js'\nimport type { PaymentScope, PaymentText } from './validate-payment-text.js'\n\nexport const EPC_QR_CODE_REQUIRED = ['size', 'beneficiary', 'iban']\nexport const EPC_QR_CODE_OPTIONAL = ['bic', 'amount', 'purpose', 'reference', 'text', 'information', 'caption']\n\n/** Whether a property that is present was read: absent is read, as nothing. */\nconst read = (o: Record<string, unknown>, key: string, value: unknown): boolean => o[key] === undefined || value !== undefined\n\n/** The purpose, a literal string the template writes, held to its rule. */\nfunction readPurpose(c: Ctx, value: unknown, path: string): string | undefined {\n const code = reference(c.f, value, path)\n if (code === undefined) return undefined\n const checked = checkEpcPurpose(code)\n if (checked.ok) return code\n c.f.report(path, 'invalid-epc-qr-code', `the purpose ${checked.rule}`)\n return undefined\n}\n\n/**\n * The rules only literal texts can break together: a reference and a text\n * both present (EPC069-12 2.2, {Or}), whatever reads them; a BIC the IBAN\n * does not go with, or none where one is needed; and a payload past its\n * bytes on what the literal texts write alone. A text read from data\n * writes nothing here, and the amount nothing: each can only add bytes,\n * so what is left is the least the code holds.\n */\nfunction readTogether(\n c: Ctx,\n o: Record<string, unknown>,\n path: string,\n texts: Readonly<Record<EpcTextField, PaymentText<string>>>,\n purpose: string | undefined,\n): void {\n if (o.reference !== undefined && o.text !== undefined) {\n c.f.report(\n at(path, 'text'),\n 'invalid-epc-qr-code',\n 'a code holds a creditor reference or a text, never both: only one of the two may be populated (EPC069-12 2.2)',\n )\n }\n const bic = o.bic === undefined ? null : texts.bic.checked\n for (const { field, rule } of epcPairing(texts.iban.checked, bic)) c.f.report(at(path, field), 'invalid-epc-qr-code', rule)\n const least = epcPayload({\n bic: texts.bic.checked,\n beneficiary: texts.beneficiary.checked ?? '',\n iban: texts.iban.checked ?? '',\n purpose,\n reference: texts.reference.checked,\n text: texts.text.checked,\n information: texts.information.checked,\n })\n const bytes = checkEpcPayload(least)\n if (!bytes.ok) c.f.report(path, 'invalid-epc-qr-code', `its literal texts alone make a payload that ${bytes.rule}`)\n}\n\n/**\n * The EPC QR code at `path`, standing in `region`, its square `size`\n * already read; undefined when anything in it could not be.\n */\nexport function readEpcQrCode(\n c: Ctx,\n o: Record<string, unknown>,\n path: string,\n region: RegionName,\n base: ComponentBase | undefined,\n size: number | undefined,\n): EpcQrCodeComponent | undefined {\n const scope: PaymentScope = { region, reads: 'report', encoded: 'an EPC QR code' }\n const field = (key: EpcTextField): PaymentText<string> =>\n readPaymentText(c, o[key], at(path, key), scope, 'invalid-epc-qr-code', EPC_TEXT_FIELDS[key].what, (written) => checkEpcField(key, written))\n const texts = {\n beneficiary: field('beneficiary'),\n iban: field('iban'),\n bic: field('bic'),\n reference: field('reference'),\n text: field('text'),\n information: field('information'),\n }\n const amount = readExpression(c.f, o.amount, at(path, 'amount'))\n const purpose = readPurpose(c, o.purpose, at(path, 'purpose'))\n const caption = oneOf(c.f, o.caption, at(path, 'caption'), EPC_CAPTIONS)\n readTogether(c, o, path, texts, purpose)\n const small = caption === undefined || size === undefined ? undefined : epcCaptionBreak(size)\n if (small !== undefined) c.f.report(at(path, 'size'), 'invalid-epc-qr-code', small)\n if (\n base === undefined ||\n size === undefined ||\n texts.beneficiary.runs === undefined ||\n texts.iban.runs === undefined ||\n !read(o, 'bic', texts.bic.runs) ||\n !read(o, 'amount', amount) ||\n !read(o, 'purpose', purpose) ||\n !read(o, 'reference', texts.reference.runs) ||\n !read(o, 'text', texts.text.runs) ||\n !read(o, 'information', texts.information.runs) ||\n !read(o, 'caption', caption)\n ) {\n return undefined\n }\n return {\n ...base,\n kind: 'epcQrCode',\n size,\n beneficiary: texts.beneficiary.runs,\n iban: texts.iban.runs,\n ...optional('bic', texts.bic.runs),\n ...optional('amount', amount),\n ...optional('purpose', purpose),\n ...optional('reference', texts.reference.runs),\n ...optional('text', texts.text.runs),\n ...optional('information', texts.information.runs),\n ...optional('caption', caption),\n }\n}\n","/**\n * A table over the detail dataset: the rows it selects, its columns,\n * single grouping level, sort and footer rows, and the references each\n * makes into the detail dataset and into the table's own columns. A\n * report holds up to `MAX_TABLES` of them (0062).\n */\nimport { all, identifier, integer, oneOf, optional, quote, readArray, readList, reference, shape, text, width } from './check.js'\nimport type { ComponentBase, Width } from './components.js'\nimport type { RegionName } from './definition.js'\nimport { MAX_FOOTER_ROWS, MAX_KEEP_WITH_ROWS, MAX_LABEL_LENGTH, MAX_SORT_KEYS, MAX_TABLE_COLUMNS, MAX_TABLES } from './limits.js'\nimport { at } from './pointer.js'\nimport { ALIGNMENTS } from './styles.js'\nimport { SORT_DIRECTIONS } from './table.js'\nimport type { SortKey, TableColumn, TableComponent, TableFooterCell, TableFooterRow, TableGroup } from './table.js'\nimport { declare, resolve, withinPage } from './validate-context.js'\nimport type { Ctx, Declarations } from './validate-context.js'\nimport { readExpression, readFieldRef, readInline, readInlines, readStyleRef, readStyleRules } from './validate-inline.js'\nimport type { FieldBinding, InlineScope } from './validate-inline.js'\nimport { roundPt } from './units.js'\n\nexport const TABLE_REQUIRED = ['dataset', 'columns', 'emptyText', 'repeatHeader']\nexport const TABLE_OPTIONAL = ['rowsWhen', 'headerStyle', 'sort', 'group', 'totals']\n\n/** Reports a sort or group key whose field is an image: an image has no order. */\nfunction orderable(c: Ctx, key: FieldBinding | undefined, path: string): void {\n if (key?.type === 'image') c.f.report(path, 'binding-type-mismatch', 'an image field has no order to sort or group by')\n}\n\n/** Reports fixed widths that add up to more than the printable width; fill columns share what is left. */\nexport function checkFixedWidths(c: Ctx, widths: readonly (Width | undefined)[], path: string): void {\n const fixed = all(widths)?.reduce<number>((total, columnWidth) => total + (columnWidth === 'fill' ? 0 : columnWidth), 0)\n withinPage(c, fixed === undefined ? undefined : roundPt(fixed), path, 'width', 'the fixed widths of these columns')\n}\n\nfunction readTableColumn(\n c: Ctx,\n value: unknown,\n path: string,\n region: RegionName,\n): { id: string | undefined; width: Width | undefined; column: TableColumn | undefined } {\n const o = shape(c.f, value, path, ['id', 'header', 'width', 'align', 'value'], ['visibleWhen', 'style', 'styleWhen'])\n const id = identifier(c.f, o?.id, at(path, 'id'))\n const header = text(c.f, o?.header, at(path, 'header'), MAX_LABEL_LENGTH)\n const columnWidth = width(c.f, o?.width, at(path, 'width'))\n const align = oneOf(c.f, o?.align, at(path, 'align'), ALIGNMENTS)\n const cell = readInline(c, o?.value, at(path, 'value'), { region, reads: 'row' })\n const visibleWhen = readExpression(c.f, o?.visibleWhen, at(path, 'visibleWhen'))\n const style = readStyleRef(c, o?.style, at(path, 'style'))\n const styleWhen = readStyleRules(c, o?.styleWhen, at(path, 'styleWhen'))\n if (id === undefined || header === undefined || columnWidth === undefined || align === undefined || cell === undefined)\n return { id, width: columnWidth, column: undefined }\n const column = {\n id,\n header,\n width: columnWidth,\n align,\n value: cell,\n ...optional('visibleWhen', visibleWhen),\n ...optional('style', style),\n ...optional('styleWhen', styleWhen),\n }\n return { id, width: columnWidth, column }\n}\n\n/** A footer cell, and the column it names when that could be read. */\nfunction readFooterCell(\n c: Ctx,\n value: unknown,\n path: string,\n scope: InlineScope,\n columns: Declarations<true>,\n): { column: string | undefined; cell: TableFooterCell | undefined } {\n const o = shape(c.f, value, path, ['column', 'value'])\n const column = reference(c.f, o?.column, at(path, 'column'))\n if (column !== undefined && columns !== undefined && !columns.has(column)) {\n c.f.report(at(path, 'column'), 'unknown-column', `this table has no column ${quote(column)}`)\n }\n const cellValue = readInline(c, o?.value, at(path, 'value'), scope)\n return { column, cell: column === undefined || cellValue === undefined ? undefined : { column, value: cellValue } }\n}\n\n/** A footer row: at most one cell per column, each under a column the table has. */\nfunction readFooterRow(c: Ctx, value: unknown, path: string, scope: InlineScope, columns: Declarations<true>): TableFooterRow | undefined {\n const o = shape(c.f, value, path, ['cells'], ['style'])\n const where = at(path, 'cells')\n const cells = readArray(c.f, o?.cells, where, MAX_TABLE_COLUMNS)?.map((item, index) => readFooterCell(c, item, at(where, index), scope, columns))\n const named = (cells ?? []).map(({ column }, index) => ({ id: column, path: at(at(where, index), 'column'), value: true }))\n declare(c.f, named, 'duplicate-footer-cell', (column) => `column ${column} already has a cell in this row`)\n const style = readStyleRef(c, o?.style, at(path, 'style'))\n const read = cells && all(cells.map(({ cell }) => cell))\n return read && { cells: read, ...optional('style', style) }\n}\n\nfunction readFooterRows(c: Ctx, value: unknown, path: string, scope: InlineScope, columns: Declarations<true>): readonly TableFooterRow[] | undefined {\n const rows = readArray(c.f, value, path, MAX_FOOTER_ROWS)?.map((row, index) => readFooterRow(c, row, at(path, index), scope, columns))\n return rows && all(rows)\n}\n\nfunction readGroup(\n c: Ctx,\n value: unknown,\n path: string,\n region: RegionName,\n columns: Declarations<true>,\n): { group: TableGroup | undefined; by: string | undefined } {\n const o = shape(c.f, value, path, ['by', 'direction', 'header', 'footer'], ['headerStyle', 'keepWithRows'])\n const by = readFieldRef(c, o?.by, at(path, 'by'), 'detail')\n orderable(c, by, at(path, 'by'))\n // Only a field the dataset declares can be checked against: with an\n // unknown one, the header's detail fields are not refused for not being it.\n const scope: InlineScope = { region, reads: 'group', groupBy: by?.declared === true ? by.ref.field : undefined }\n const direction = oneOf(c.f, o?.direction, at(path, 'direction'), SORT_DIRECTIONS)\n const header = readInlines(c, o?.header, at(path, 'header'), scope)\n const headerStyle = readStyleRef(c, o?.headerStyle, at(path, 'headerStyle'))\n const keepWithRows = integer(c.f, o?.keepWithRows, at(path, 'keepWithRows'), 1, MAX_KEEP_WITH_ROWS)\n const footer = readFooterRows(c, o?.footer, at(path, 'footer'), scope, columns)\n if (by === undefined || direction === undefined || header === undefined || footer === undefined) return { group: undefined, by: by?.ref.field }\n return {\n group: { by: by.ref, direction, header, ...optional('headerStyle', headerStyle), ...optional('keepWithRows', keepWithRows), footer },\n by: by.ref.field,\n }\n}\n\n/** Sort keys, after the group's key: rows are ordered by the group's key first, so a key on that field, or on one already sorted by, orders nothing. */\nfunction readSort(c: Ctx, value: unknown, path: string, groupBy: string | undefined): readonly SortKey[] | undefined {\n const keys = readArray(c.f, value, path, MAX_SORT_KEYS)?.map((item, index) => {\n const where = at(path, index)\n const o = shape(c.f, item, where, ['field', 'direction'])\n const field = readFieldRef(c, o?.field, at(where, 'field'), 'detail')\n orderable(c, field, at(where, 'field'))\n const direction = oneOf(c.f, o?.direction, at(where, 'direction'), SORT_DIRECTIONS)\n return { field, direction, path: at(where, 'field') }\n })\n // The group's key orders first, so it is declared before the sort keys.\n const group = groupBy === undefined ? [] : [{ id: groupBy, path, value: true }]\n const sorted = (keys ?? []).map(({ field, path: fieldPath }) => ({ id: field?.ref.field, path: fieldPath, value: true }))\n declare(\n c.f,\n [...group, ...sorted],\n 'duplicate-sort-key',\n (field) => `${field} already orders these rows, as the group's key or an earlier sort key; a second key on it orders nothing`,\n )\n return keys && all(keys.map(({ field, direction }) => (field === undefined || direction === undefined ? undefined : { field: field.ref, direction })))\n}\n\n/**\n * A table, counted against `MAX_TABLES`: version 0 has one primary detail\n * dataset (plan 10), and each table prints the rows of it that its\n * condition selects (0062). Whether a report that is an e-invoice holds a\n * second is the e-invoice's to say, once it is read.\n */\nexport function readTable(c: Ctx, o: Record<string, unknown>, path: string, region: RegionName, base: ComponentBase | undefined): TableComponent | undefined {\n c.tables.push(path)\n if (c.tables.length > MAX_TABLES)\n c.f.report(path, 'too-many', `a report holds at most ${MAX_TABLES} tables, counting those inside containers, and this is table ${c.tables.length}`)\n const dataset = oneOf(c.f, o.dataset, at(path, 'dataset'), ['detail'])\n resolve(c.f, c.declared.datasets, dataset, at(path, 'dataset'), 'unknown-dataset', 'dataset')\n const rowsWhen = readExpression(c.f, o.rowsWhen, at(path, 'rowsWhen'))\n const read = readList(c.f, o.columns, at(path, 'columns'), 1, MAX_TABLE_COLUMNS)?.map((item, index) =>\n readTableColumn(c, item, at(at(path, 'columns'), index), region),\n )\n const columnIds =\n read &&\n declare(\n c.f,\n read.map(({ id }, index) => ({ id, path: at(at(at(path, 'columns'), index), 'id'), value: true as const })),\n 'duplicate-column-id',\n (id) => `this table already has a column ${id}`,\n )\n if (read !== undefined)\n checkFixedWidths(\n c,\n read.map(({ width: columnWidth }) => columnWidth),\n at(path, 'columns'),\n )\n const headerStyle = readStyleRef(c, o.headerStyle, at(path, 'headerStyle'))\n const group = readGroup(c, o.group, at(path, 'group'), region, columnIds)\n const sort = readSort(c, o.sort, at(path, 'sort'), group.by)\n const totals = readFooterRows(c, o.totals, at(path, 'totals'), { region, reads: 'table' }, columnIds)\n const emptyText = text(c.f, o.emptyText, at(path, 'emptyText'), MAX_LABEL_LENGTH)\n const repeatHeader = oneOf(c.f, o.repeatHeader, at(path, 'repeatHeader'), [true])\n const columns = read && all(read.map(({ column }) => column))\n if (base === undefined || dataset === undefined || columns === undefined || emptyText === undefined || repeatHeader === undefined) return undefined\n return {\n ...base,\n kind: 'table',\n dataset,\n ...optional('rowsWhen', rowsWhen),\n columns,\n ...optional('headerStyle', headerStyle),\n ...optional('sort', sort),\n ...optional('group', group.group),\n ...optional('totals', totals),\n emptyText,\n repeatHeader,\n }\n}\n","/**\n * Components: the shape of each kind, and where each may stand.\n *\n * Kinds are a table, not a switch: each entry says which properties its\n * kind has, whether and how it holds other components, where it may stand,\n * and how to read what is particular to it. A kind added to COMPONENT_KINDS\n * without an entry here does not compile.\n */\nimport { isFontMediaType } from './assets.js'\nimport {\n all,\n flag,\n identifier,\n kindOf,\n matches,\n oneOf,\n optional,\n points,\n quote,\n readArray,\n readList,\n readObject,\n reference,\n shape,\n strictKeys,\n width,\n} from './check.js'\nimport { COMPONENT_KINDS, IMAGE_FITS, IMAGE_SOURCE_KINDS, QR_ERROR_CORRECTION } from './components.js'\nimport type { Border, ColumnSlot, Component, ComponentBase, ComponentKind, ImageSource, ImageSourceKind, Width } from './components.js'\nimport type { RegionName } from './definition.js'\nimport { MAX_COLUMNS, MAX_NESTING_DEPTH, MAX_REGION_COMPONENTS, MIN_COLUMNS } from './limits.js'\nimport { squareRoom } from './page.js'\nimport { at } from './pointer.js'\nimport { COLOR } from './syntax.js'\nimport { CHART_OPTIONAL, CHART_REQUIRED, readChart } from './validate-chart.js'\nimport { resolve, withinPage } from './validate-context.js'\nimport { EPC_QR_CODE_OPTIONAL, EPC_QR_CODE_REQUIRED, readEpcQrCode } from './validate-epc-qr-code.js'\nimport type { Ctx } from './validate-context.js'\nimport { readExpression, readFieldRef, readInlines, readStyleRef, readStyleRules } from './validate-inline.js'\nimport { checkFixedWidths, readTable, TABLE_OPTIONAL, TABLE_REQUIRED } from './validate-table.js'\n\nexport interface ComponentScope {\n readonly region: RegionName\n /** Where the region is, for the error when its budget runs out. */\n readonly regionPath: string\n /** How many containers enclose the components being read: 0 at a region's top level. */\n readonly depth: number\n /** The innermost columns or keep-together block around the components being read, if any: no table or page break stands in one. */\n readonly layout: ComponentKind | undefined\n /** How many more components the region may hold; one budget for every list in the region. */\n readonly budget: { left: number }\n}\n\n/** The regions content flows through; the others are drawn at a fixed place on a page. */\nconst FLOW_REGIONS: readonly RegionName[] = ['body', 'summary']\n\nconst COLOR_RULE = 'a colour written #rrggbb in lower case'\n\ninterface KindRule<C extends Component> {\n readonly required: readonly string[]\n readonly optional?: readonly string[]\n /**\n * Holds components of its own: 'layout' when it lays them out (columns,\n * keep-together), 'flow' when they flow as though it were not there (a\n * section). Either counts toward the nesting depth.\n */\n readonly holds?: 'layout' | 'flow'\n /** May stand only in a region content flows through. */\n readonly flowOnly?: true\n /** Is part of the flow itself, so never inside a columns or keep-together block. */\n readonly inFlow?: true\n /**\n * What is particular to the kind. `scope` is the scope of what a\n * container holds, and the component's own for any other kind; the\n * region is the same either way. `base` is undefined when the\n * component's id could not be read.\n */\n readonly read: (c: Ctx, o: Record<string, unknown>, path: string, scope: ComponentScope, base: ComponentBase | undefined) => C | undefined\n}\n\n/** The scope a component of `kind` passes to what it holds: one level deeper, and inside it when it lays them out. */\nfunction inside(scope: ComponentScope, kind: ComponentKind, holds: 'layout' | 'flow' | undefined): ComponentScope {\n if (holds === undefined) return scope\n return { ...scope, depth: scope.depth + 1, layout: holds === 'layout' ? kind : scope.layout }\n}\n\nfunction readSlot(c: Ctx, value: unknown, path: string, scope: ComponentScope): { width: Width | undefined; slot: ColumnSlot | undefined } {\n const o = shape(c.f, value, path, ['width', 'components'])\n const slotWidth = width(c.f, o?.width, at(path, 'width'))\n const components = readComponents(c, o?.components, at(path, 'components'), scope)\n return { width: slotWidth, slot: slotWidth === undefined || components === undefined ? undefined : { width: slotWidth, components } }\n}\n\n/** A length checked against the page, as `what` measures it. */\nfunction sized(c: Ctx, value: unknown, path: string, side: 'width' | 'height', what: string): number | undefined {\n const length = points(c.f, value, path, 'positive')\n withinPage(c, length, path, side, what)\n return length\n}\n\n/**\n * A square's side, checked against the shorter side of the printable area\n * (`squareRoom`): a square that fits that way fits the other, and one that\n * fits neither is reported once, on the side that is short.\n */\nfunction square(c: Ctx, value: unknown, path: string, what: string): number | undefined {\n return sized(c, value, path, c.printable === undefined ? 'width' : squareRoom(c.printable).side, what)\n}\n\ntype SourceReader = (c: Ctx, o: Record<string, unknown>, path: string, region: RegionName) => ImageSource | undefined\n\nconst SOURCES: { readonly [K in ImageSourceKind]: { readonly required: readonly string[]; readonly read: SourceReader } } = {\n asset: {\n required: ['asset'],\n read: (c, o, path) => {\n const asset = reference(c.f, o.asset, at(path, 'asset'))\n const mediaType = resolve(c.f, c.declared.assets, asset, at(path, 'asset'), 'unknown-asset', 'asset')\n // A font asset is not a picture: an image that drew one would print nothing, or fail at the first byte the renderer read.\n if (mediaType !== undefined && isFontMediaType(mediaType))\n c.f.report(at(path, 'asset'), 'asset-not-an-image', `the asset ${quote(asset as string)} is a font, which an image cannot draw`)\n return asset === undefined ? undefined : { kind: 'asset', asset }\n },\n },\n field: {\n required: ['field'],\n read: (c, o, path, region) => {\n const field = readFieldRef(c, o.field, at(path, 'field'), { region, reads: 'report' })\n if (field?.type !== undefined && field.type !== 'image') {\n c.f.report(at(path, 'field'), 'binding-type-mismatch', `an image draws an image field, and this is a ${field.type}`)\n }\n return field && { kind: 'field', field: field.ref }\n },\n },\n}\n\nfunction readImageSource(c: Ctx, value: unknown, path: string, region: RegionName): ImageSource | undefined {\n const o = readObject(c.f, value, path)\n const kind = o && kindOf(c.f, o, path, IMAGE_SOURCE_KINDS)\n if (o === undefined || kind === undefined) return undefined\n strictKeys(c.f, o, path, ['kind', ...SOURCES[kind].required])\n return SOURCES[kind].read(c, o, path, region)\n}\n\nfunction readBorder(c: Ctx, value: unknown, path: string): Border | undefined {\n const o = shape(c.f, value, path, ['thickness', 'color'])\n const thickness = points(c.f, o?.thickness, at(path, 'thickness'), 'positive')\n const color = matches(c.f, o?.color, at(path, 'color'), COLOR, 'invalid-color', COLOR_RULE)\n return thickness === undefined || color === undefined ? undefined : { thickness, color }\n}\n\nconst KINDS: { readonly [K in ComponentKind]: KindRule<Extract<Component, { kind: K }>> } = {\n text: {\n required: ['content'],\n optional: ['keepWithNext'],\n read: (c, o, path, scope, base) => {\n const content = readInlines(c, o.content, at(path, 'content'), { region: scope.region, reads: 'report', paragraph: true })\n const keepWithNext = flag(c.f, o.keepWithNext, at(path, 'keepWithNext'))\n return base && content && { ...base, kind: 'text', content, ...optional('keepWithNext', keepWithNext) }\n },\n },\n image: {\n required: ['source', 'width', 'height', 'fit'],\n read: (c, o, path, scope, base) => {\n const source = readImageSource(c, o.source, at(path, 'source'), scope.region)\n const imageWidth = sized(c, o.width, at(path, 'width'), 'width', 'this image')\n const height = sized(c, o.height, at(path, 'height'), 'height', 'this image')\n const fit = oneOf(c.f, o.fit, at(path, 'fit'), IMAGE_FITS)\n if (base === undefined || source === undefined || imageWidth === undefined || height === undefined || fit === undefined) return undefined\n return { ...base, kind: 'image', source, width: imageWidth, height, fit }\n },\n },\n qrCode: {\n required: ['content', 'size', 'errorCorrection'],\n read: (c, o, path, scope, base) => {\n const content = readInlines(c, o.content, at(path, 'content'), { region: scope.region, reads: 'report', encoded: 'a QR code' }, 1)\n const size = square(c, o.size, at(path, 'size'), 'this QR code')\n const errorCorrection = oneOf(c.f, o.errorCorrection, at(path, 'errorCorrection'), QR_ERROR_CORRECTION)\n if (base === undefined || content === undefined || size === undefined || errorCorrection === undefined) return undefined\n return { ...base, kind: 'qrCode', content, size, errorCorrection }\n },\n },\n epcQrCode: {\n required: EPC_QR_CODE_REQUIRED,\n optional: EPC_QR_CODE_OPTIONAL,\n read: (c, o, path, scope, base) => readEpcQrCode(c, o, path, scope.region, base, square(c, o.size, at(path, 'size'), 'this EPC QR code')),\n },\n line: {\n required: ['thickness'],\n optional: ['color'],\n read: (c, o, path, _scope, base) => {\n const thickness = points(c.f, o.thickness, at(path, 'thickness'), 'positive')\n const color = matches(c.f, o.color, at(path, 'color'), COLOR, 'invalid-color', COLOR_RULE)\n return base && thickness !== undefined ? { ...base, kind: 'line', thickness, ...optional('color', color) } : undefined\n },\n },\n rectangle: {\n required: ['width', 'height'],\n optional: ['fill', 'stroke'],\n read: (c, o, path, _scope, base) => {\n const boxWidth = sized(c, o.width, at(path, 'width'), 'width', 'this rectangle')\n const height = sized(c, o.height, at(path, 'height'), 'height', 'this rectangle')\n const fill = matches(c.f, o.fill, at(path, 'fill'), COLOR, 'invalid-color', COLOR_RULE)\n const stroke = matches(c.f, o.stroke, at(path, 'stroke'), COLOR, 'invalid-color', COLOR_RULE)\n if (base === undefined || boxWidth === undefined || height === undefined) return undefined\n return { ...base, kind: 'rectangle', width: boxWidth, height, ...optional('fill', fill), ...optional('stroke', stroke) }\n },\n },\n spacer: {\n required: ['height'],\n read: (c, o, path, _scope, base) => {\n const height = sized(c, o.height, at(path, 'height'), 'height', 'this spacer')\n return base && height !== undefined ? { ...base, kind: 'spacer', height } : undefined\n },\n },\n columns: {\n required: ['columns'],\n holds: 'layout',\n read: (c, o, path, scope, base) => {\n const where = at(path, 'columns')\n const read = readList(c.f, o.columns, where, MIN_COLUMNS, MAX_COLUMNS)?.map((item, index) => readSlot(c, item, at(where, index), scope))\n if (read !== undefined)\n checkFixedWidths(\n c,\n read.map(({ width: slotWidth }) => slotWidth),\n where,\n )\n const columns = read && all(read.map(({ slot }) => slot))\n return base && columns && { ...base, kind: 'columns', columns }\n },\n },\n section: {\n required: ['components'],\n optional: ['border', 'fill', 'padding'],\n holds: 'flow',\n read: (c, o, path, scope, base) => {\n const components = readComponents(c, o.components, at(path, 'components'), scope)\n const border = readBorder(c, o.border, at(path, 'border'))\n const fill = matches(c.f, o.fill, at(path, 'fill'), COLOR, 'invalid-color', COLOR_RULE)\n const padding = points(c.f, o.padding, at(path, 'padding'), 'zero')\n return (\n base &&\n components && { ...base, kind: 'section', components, ...optional('border', border), ...optional('fill', fill), ...optional('padding', padding) }\n )\n },\n },\n table: {\n required: TABLE_REQUIRED,\n optional: TABLE_OPTIONAL,\n flowOnly: true,\n inFlow: true,\n read: (c, o, path, scope, base) => readTable(c, o, path, scope.region, base),\n },\n chart: {\n required: CHART_REQUIRED,\n optional: CHART_OPTIONAL,\n flowOnly: true,\n read: (c, o, path, scope, base) => readChart(c, o, path, scope.region, base),\n },\n pageBreak: {\n required: [],\n flowOnly: true,\n inFlow: true,\n read: (_c, _o, _path, _scope, base) => base && { ...base, kind: 'pageBreak' },\n },\n keepTogether: {\n required: ['components'],\n holds: 'layout',\n flowOnly: true,\n read: (c, o, path, scope, base) => {\n const components = readComponents(c, o.components, at(path, 'components'), scope)\n return base && components && { ...base, kind: 'keepTogether', components }\n },\n },\n}\n\n/** Records a component's id, refusing it when another component already has it. */\nfunction claim(c: Ctx, id: string, path: string): void {\n c.f.component(path, id)\n const first = c.componentIds.get(id)\n if (first === undefined) c.componentIds.set(id, path)\n else\n c.f.report(\n at(path, 'id'),\n 'duplicate-component-id',\n `\"${id}\" is already the id of the component at ${first}; component ids are unique across the whole report`,\n )\n}\n\n/** Reports a component of `kind` standing where it may not. */\nfunction place(c: Ctx, rule: KindRule<Component>, kind: ComponentKind, path: string, scope: ComponentScope): void {\n if (rule.flowOnly && !FLOW_REGIONS.includes(scope.region)) {\n c.f.report(path, 'misplaced-flow-component', `a ${kind} stands only in the body or the summary, where content flows, not in the ${scope.region}`)\n }\n if (rule.inFlow && scope.layout !== undefined) {\n c.f.report(path, 'nested-flow-component', `a ${kind} is part of the flow, and cannot stand inside a ${scope.layout} block; a section can hold it`)\n }\n}\n\nfunction readComponent(c: Ctx, value: unknown, path: string, scope: ComponentScope): Component | undefined {\n const o = readObject(c.f, value, path)\n const kind = o && kindOf(c.f, o, path, COMPONENT_KINDS)\n if (o === undefined || kind === undefined) return undefined\n const rule: KindRule<Component> = KINDS[kind]\n strictKeys(c.f, o, path, ['id', 'kind', ...rule.required], ['visibleWhen', 'style', 'styleWhen', ...(rule.optional ?? [])])\n const id = identifier(c.f, o.id, at(path, 'id'))\n if (id !== undefined) claim(c, id, path)\n place(c, rule, kind, path, scope)\n if (rule.holds !== undefined && scope.depth >= MAX_NESTING_DEPTH) {\n c.f.report(path, 'nesting-too-deep', `this ${kind} is inside ${scope.depth} containers; containers nest at most ${MAX_NESTING_DEPTH} deep`)\n return undefined\n }\n const visibleWhen = readExpression(c.f, o.visibleWhen, at(path, 'visibleWhen'))\n const style = readStyleRef(c, o.style, at(path, 'style'))\n const styleWhen = readStyleRules(c, o.styleWhen, at(path, 'styleWhen'))\n const base = id === undefined ? undefined : { id, ...optional('visibleWhen', visibleWhen), ...optional('style', style), ...optional('styleWhen', styleWhen) }\n return rule.read(c, o, path, inside(scope, kind, rule.holds), base)\n}\n\n/** Takes one component from the region's budget, reporting once when it is spent. */\nfunction spend(c: Ctx, scope: ComponentScope): boolean {\n if (scope.budget.left > 0) {\n scope.budget.left -= 1\n return true\n }\n if (scope.budget.left === 0) {\n c.f.report(scope.regionPath, 'too-many', `a region holds at most ${MAX_REGION_COMPONENTS} components, counting those inside containers`)\n scope.budget.left = -1\n }\n return false\n}\n\nexport function readComponents(c: Ctx, value: unknown, path: string, scope: ComponentScope): readonly Component[] | undefined {\n const items = readArray(c.f, value, path, MAX_REGION_COMPONENTS)\n if (items === undefined) return undefined\n const components: (Component | undefined)[] = []\n for (const [index, item] of items.entries()) {\n if (!spend(c, scope)) return undefined\n components.push(readComponent(c, item, at(path, index), scope))\n }\n return all(components)\n}\n","/**\n * Where a report's datasets are read from a formancy form's submissions\n * (0042): what of the submissions each dataset reads, and where each of its\n * fields is. The structure alone, which the report holds: whether a version\n * of a form has a field at a path, of a kind the field's type reads, is\n * report-forms' to say, per render, against the version that collected each\n * submission. A dataset is read from a form whole, and both datasets are,\n * or neither, because a submission is read into the whole envelope at once.\n *\n * A binding may say, one form version at a time, where that version holds\n * what the binding reads, or that the report prints nothing of a field\n * from it (0048): what a review of a version decided, keyed by the\n * version's `schemaHash`, so that every version it does not name reads the\n * binding's own path. An override may read that own path too: a review\n * that followed a rename moved the own path to where the version it\n * reviewed holds the field, and names that version so, for the next\n * review to compare with.\n */\nimport type { Findings } from './check.js'\nimport { kindOf, oneOf, optional, quote, readObject, reference, shape, strictKeys, text } from './check.js'\nimport { DATASET_FORM_KINDS, FORM_READS } from './data.js'\nimport type { DatasetFormBinding, DatasetFormKind, DatasetRole, FieldFormBinding, FieldFormOverride, FieldType } from './data.js'\nimport { MAX_FORM_MEMBER_LENGTH, MAX_FORM_OVERRIDES, MAX_FORM_PATH_KEYS } from './limits.js'\nimport { at } from './pointer.js'\nimport { isFormPath, isSchemaHash } from './syntax.js'\n\nconst PATH_RULE = `field keys joined by dots, as formancy writes a data path in one scope: at most ${MAX_FORM_PATH_KEYS} keys, each letters, digits and underscores, and no repeater's []`\n\n/** A data path in one scope, or a repeater's. */\nfunction formPath(f: Findings, value: unknown, path: string): string | undefined {\n const string = reference(f, value, path)\n if (string === undefined || isFormPath(string)) return string\n f.report(path, 'invalid-form-path', `expected ${PATH_RULE}, found ${quote(string)}`)\n return undefined\n}\n\n/**\n * Overrides keyed by a form version's hash, each read by `read`, or\n * undefined when they could not all be read. At least one, since none is\n * the binding without them spelled otherwise; at most\n * `MAX_FORM_OVERRIDES`, refused before any is read.\n */\nfunction readOverrides<T>(\n f: Findings,\n value: unknown,\n path: string,\n read: (item: unknown, where: string) => T | undefined,\n): Readonly<Record<string, T>> | undefined {\n const o = readObject(f, value, path)\n if (o === undefined) return undefined\n const versions = Object.keys(o)\n if (versions.length === 0)\n f.report(path, 'too-few', 'overrides name at least one form version: none is the binding without them, and one reading has one hash')\n if (versions.length > MAX_FORM_OVERRIDES) {\n f.report(path, 'too-many', `name ${versions.length} form versions; at most ${MAX_FORM_OVERRIDES} are allowed`)\n return undefined\n }\n const items = versions.map((version) => {\n if (isSchemaHash(version)) return read(o[version], at(path, version))\n f.report(at(path, version), 'invalid-digest', 'a form version is named by its schemaHash: 64 lower-case hex digits')\n return undefined\n })\n return versions.length > 0 && items.every((item) => item !== undefined)\n ? Object.fromEntries(versions.map((version, index) => [version, items[index] as T]))\n : undefined\n}\n\n/**\n * One version's override of a field's binding, or undefined after\n * reporting why it is none: a path, the binding's own among them, or\n * nothing printed, of a field that may be null.\n */\nfunction readFieldOverride(f: Findings, value: unknown, path: string, nullable: boolean | undefined): FieldFormOverride | undefined {\n const o = shape(f, value, path, [], ['path', 'omit'])\n if (o === undefined) return undefined\n if (Object.hasOwn(o, 'path') === Object.hasOwn(o, 'omit')) {\n f.report(\n path,\n 'invalid-form-override',\n 'an override reads the field from another path in that version, { path }, or prints nothing of it from that version, { omit: true }: one of the two',\n )\n return undefined\n }\n if (Object.hasOwn(o, 'omit')) {\n if (oneOf(f, o.omit, at(path, 'omit'), [true] as const) === undefined) return undefined\n if (nullable !== false) return { omit: true }\n f.report(\n path,\n 'invalid-form-override',\n \"printing nothing of a field from a version hands it null in each of that version's submissions, and this field is never null: a final render would refuse every one\",\n )\n return undefined\n }\n const where = formPath(f, o.path, at(path, 'path'))\n return where === undefined ? undefined : { path: where }\n}\n\n/**\n * Where a field of `type` is read from a submission, when it says; undefined\n * when it does not, or when what it says could not all be read. A choice\n * prints text, so only a string field says how one prints; and only a\n * field that may be null, as `nullable` says, has nothing printed of it\n * from a version.\n */\nexport function readFieldForm(\n f: Findings,\n value: unknown,\n path: string,\n type: FieldType | undefined,\n nullable: boolean | undefined,\n): FieldFormBinding | undefined {\n const o = shape(f, value, path, ['path'], ['member', 'read', 'overrides'])\n if (o === undefined) return undefined\n const where = formPath(f, o.path, at(path, 'path'))\n const member = text(f, o.member, at(path, 'member'), MAX_FORM_MEMBER_LENGTH)\n if (member === '')\n f.report(\n at(path, 'member'),\n 'invalid-form-path',\n \"a member is a matrix row's value or a selectboxes option's, which formancy writes as one character at least\",\n )\n // The label is the default, and spelled out it would hash apart from the binding that leaves it out.\n const read = o.read === 'label' ? undefined : oneOf(f, o.read, at(path, 'read'), FORM_READS)\n if (o.read === 'label')\n f.report(at(path, 'read'), 'not-one-of', 'a choice prints its label when read is left out, so leave it out: one binding has one spelling, and one hash')\n if (read !== undefined && type !== undefined && type !== 'string') {\n f.report(at(path, 'read'), 'binding-type-mismatch', `a choice prints its label or its stored value, both text, and this field is a ${type}`)\n }\n const overrides =\n o.overrides === undefined\n ? undefined\n : readOverrides(f, o.overrides, at(path, 'overrides'), (item, version) => readFieldOverride(f, item, version, nullable))\n const whole =\n where !== undefined &&\n (o.member === undefined || (member !== undefined && member !== '')) &&\n (o.read === undefined || read !== undefined) &&\n (o.overrides === undefined || overrides !== undefined)\n return whole ? { path: where, ...optional('member', member), ...optional('read', read), ...optional('overrides', overrides) } : undefined\n}\n\n/** One version's override of the detail's repeater -- a repeater, the binding's own among them -- or undefined after reporting why it is none. */\nfunction readRepeaterOverride(f: Findings, value: unknown, path: string): { readonly repeater: string } | undefined {\n const o = shape(f, value, path, ['repeater'])\n const where = o === undefined ? undefined : formPath(f, o.repeater, at(path, 'repeater'))\n return where === undefined ? undefined : { repeater: where }\n}\n\n/** What a dataset says of a form: the binding when it could be read whole, and its kind where that could be read. */\nexport interface DatasetFormRead {\n readonly binding: DatasetFormBinding | undefined\n readonly kind: DatasetFormKind | undefined\n}\n\n/** What of the submissions a dataset reads. */\nexport function readDatasetForm(f: Findings, value: unknown, path: string): DatasetFormRead {\n const o = readObject(f, value, path)\n const kind = o && kindOf(f, o, path, DATASET_FORM_KINDS)\n if (o === undefined || kind === undefined) return { binding: undefined, kind: undefined }\n if (kind !== 'repeater') {\n strictKeys(f, o, path, ['kind'])\n return { binding: { kind }, kind }\n }\n strictKeys(f, o, path, ['kind', 'repeater'], ['overrides'])\n const repeater = formPath(f, o.repeater, at(path, 'repeater'))\n const overrides =\n o.overrides === undefined ? undefined : readOverrides(f, o.overrides, at(path, 'overrides'), (item, version) => readRepeaterOverride(f, item, version))\n const whole = repeater !== undefined && (o.overrides === undefined || overrides !== undefined)\n return { binding: whole ? { kind, repeater, ...optional('overrides', overrides) } : undefined, kind }\n}\n\n/**\n * Refuses a field of a dataset read from a form that says nowhere it is\n * read, and one that says where in a dataset read from none. `bound` says,\n * field by field, whether each says where, as it was written.\n */\nexport function checkFieldsBound(f: Findings, path: string, read: boolean, bound: readonly boolean[]): void {\n bound.forEach((says, index) => {\n if (says === read) return\n const field = at(at(path, 'fields'), index)\n if (read)\n f.report(\n field,\n 'incomplete-form-binding',\n 'the dataset is read from a form, and this field says nowhere it is read: it would be missing from every render, which a final render refuses',\n )\n else f.report(at(field, 'form'), 'incomplete-form-binding', 'the dataset is read from no form, so nothing reads where this field says a form holds it')\n })\n}\n\n/** What a declared dataset says of a form: whether it reads one, and its kind where that could be read. */\nexport interface DatasetForm {\n readonly read: boolean\n readonly kind: DatasetFormKind | undefined\n}\n\nconst ROLE_KINDS: { readonly [R in DatasetRole]: { readonly kinds: readonly DatasetFormKind[]; readonly is: string; readonly not: string } } = {\n header: { kinds: ['submission'], is: \"the header is one record, a submission's answers\", not: 'rows' },\n detail: { kinds: ['repeater', 'submissions'], is: \"the detail is rows, a repeater's or one for each submission\", not: 'one record' },\n}\n\n/**\n * Refuses datasets that read what they are not, and a report with one\n * dataset read from a form beside one that is not: the header is one\n * submission's answers, the detail rows; and a report of one row per\n * submission has no one record to head it.\n */\nexport function checkDatasetForms(f: Findings, path: string, forms: { readonly [R in DatasetRole]?: DatasetForm }): void {\n for (const role of ['header', 'detail'] as const) {\n const kind = forms[role]?.kind\n const { kinds, is, not } = ROLE_KINDS[role]\n if (kind !== undefined && !kinds.includes(kind))\n f.report(at(at(at(path, role), 'form'), 'kind'), 'misplaced-form-binding', `${is}, and ${quote(kind)} reads ${not}`)\n }\n const { header, detail } = forms\n if (detail?.kind === 'submissions' && header !== undefined) {\n f.report(\n at(path, 'header'),\n 'misplaced-form-binding',\n 'a report of one row per submission has no one record to head it: which submission would the header read? What it prints is read in the rows',\n )\n } else if (header !== undefined && detail !== undefined && header.read !== detail.read) {\n f.report(\n at(path, header.read ? 'detail' : 'header'),\n 'incomplete-form-binding',\n 'the other dataset is read from a form, and a submission is read into both at once: this one would have nothing to read',\n )\n }\n}\n","/**\n * What a report declares before it lays anything out: its page, its print\n * styles, the datasets and parameters it reads, the assets it shows and\n * where it came from. Each list records the ids it declares, so components\n * can be checked against them.\n */\nimport { ASSET_AND_FONT_MEDIA_TYPES } from './assets.js'\nimport type { AnyAssetMediaType, AssetRef } from './assets.js'\nimport type { Findings } from './check.js'\nimport {\n all,\n describe,\n fieldKey,\n flag,\n fontSize,\n identifier,\n integer,\n kindOf,\n matches,\n oneOf,\n optional,\n points,\n readArray,\n readObject,\n shape,\n strictKeys,\n text,\n} from './check.js'\nimport { DATASET_ROLES, FIELD_TYPES, PARAMETER_TYPES } from './data.js'\nimport type { DatasetContract, DatasetRole, Datasets, FieldContract, FieldType, ParameterDef, ParameterType } from './data.js'\nimport { PROVENANCE_KINDS } from './definition.js'\nimport type { Provenance, ProvenanceKind } from './definition.js'\nimport { MAX_ASSETS, MAX_DATASET_FIELDS, MAX_LABEL_LENGTH, MAX_PARAMETERS, MAX_SCALE, MAX_STYLES, MIN_PRINTABLE_PT } from './limits.js'\nimport { ORIENTATIONS, PAGE_SIZE_NAMES, printableArea } from './page.js'\nimport type { Margins, PageSettings } from './page.js'\nimport { at } from './pointer.js'\nimport { ALIGNMENTS, FONT_FAMILIES } from './styles.js'\nimport type { PrintStyle } from './styles.js'\nimport { COLOR, DECIMAL, DIGEST, FORM_ID, INTEGER, isCalendarDate, SCHEMA_HASH } from './syntax.js'\nimport { declare } from './validate-context.js'\nimport type { Ctx, Declarations, Declaration } from './validate-context.js'\nimport { checkDatasetForms, checkFieldsBound, readDatasetForm, readFieldForm } from './validate-form-binding.js'\nimport type { DatasetForm } from './validate-form-binding.js'\n\nfunction readMargins(f: Findings, value: unknown, path: string): Margins | undefined {\n const o = shape(f, value, path, ['top', 'right', 'bottom', 'left'])\n const [top, right, bottom, left] = (['top', 'right', 'bottom', 'left'] as const).map((side) => points(f, o?.[side], at(path, side), 'zero'))\n return top === undefined || right === undefined || bottom === undefined || left === undefined ? undefined : { top, right, bottom, left }\n}\n\n/** The page, recording what its margins leave when that is enough to measure content against. */\nexport function readPage(c: Ctx, value: unknown, path: string): PageSettings | undefined {\n const o = shape(c.f, value, path, ['size', 'orientation', 'margins'])\n const size = oneOf(c.f, o?.size, at(path, 'size'), PAGE_SIZE_NAMES)\n const orientation = oneOf(c.f, o?.orientation, at(path, 'orientation'), ORIENTATIONS)\n const margins = readMargins(c.f, o?.margins, at(path, 'margins'))\n if (size === undefined || orientation === undefined || margins === undefined) return undefined\n const page = { size, orientation, margins }\n const area = printableArea(page)\n if (area.width >= MIN_PRINTABLE_PT && area.height >= MIN_PRINTABLE_PT) c.printable = area\n else {\n c.f.report(\n at(path, 'margins'),\n 'printable-area-too-small',\n `the margins leave ${area.width} x ${area.height} points of the page; at least ${MIN_PRINTABLE_PT} each way is needed`,\n )\n }\n return page\n}\n\n/** A declaration read: its id, what it declares, and the declaration itself when every part of it could be read. */\ninterface Read<T, D> {\n readonly entry: Declaration<D>\n readonly item: T | undefined\n}\n\n/** A list of declarations, each with an id unique in the list. */\nfunction readDeclarations<T, D>(\n c: Ctx,\n value: unknown,\n path: string,\n max: number,\n what: string,\n read: (item: unknown, where: string) => Read<T, D>,\n): { items: T[] | undefined; declared: Map<string, D> | undefined } {\n const items = readArray(c.f, value, path, max)\n if (items === undefined) return { items: undefined, declared: undefined }\n const entries = items.map((item, index) => read(item, at(path, index)))\n const declared = declare(\n c.f,\n entries.map(({ entry }) => entry),\n 'duplicate-id',\n (id) => `another ${what} is already ${id}`,\n )\n return { items: all(entries.map(({ item }) => item)), declared }\n}\n\nfunction readStyle(f: Findings, value: unknown, path: string): Read<PrintStyle, true> {\n const o = shape(f, value, path, ['id'], ['font', 'size', 'bold', 'italic', 'color', 'align'])\n const id = identifier(f, o?.id, at(path, 'id'))\n const entry = { id, path: at(path, 'id'), value: true as const }\n if (o === undefined || id === undefined) return { entry, item: undefined }\n return {\n entry,\n item: {\n id,\n ...optional('font', oneOf(f, o.font, at(path, 'font'), FONT_FAMILIES)),\n ...optional('size', fontSize(f, o.size, at(path, 'size'))),\n ...optional('bold', flag(f, o.bold, at(path, 'bold'))),\n ...optional('italic', flag(f, o.italic, at(path, 'italic'))),\n ...optional('color', matches(f, o.color, at(path, 'color'), COLOR, 'invalid-color', 'a colour written #rrggbb in lower case')),\n ...optional('align', oneOf(f, o.align, at(path, 'align'), ALIGNMENTS)),\n },\n }\n}\n\nexport function readStyles(c: Ctx, value: unknown, path: string): readonly PrintStyle[] | undefined {\n const { items, declared } = readDeclarations(c, value, path, MAX_STYLES, 'style', (item, where) => readStyle(c.f, item, where))\n c.declared.styles = declared\n return items\n}\n\n/** A field contract, and whether it says where a form holds it, as written: the dataset holds that to whether it reads a form. */\nfunction readFieldContract(f: Findings, value: unknown, path: string): Read<FieldContract, FieldType | undefined> & { readonly formed: boolean } {\n const o = shape(f, value, path, ['id', 'type', 'label', 'nullable'], ['scale', 'form'])\n const id = fieldKey(f, o?.id, at(path, 'id'))\n const type = oneOf(f, o?.type, at(path, 'type'), FIELD_TYPES)\n const label = text(f, o?.label, at(path, 'label'), MAX_LABEL_LENGTH)\n const nullable = flag(f, o?.nullable, at(path, 'nullable'))\n const scale = integer(f, o?.scale, at(path, 'scale'), 0, MAX_SCALE)\n if (scale !== undefined && type !== undefined && type !== 'decimal') {\n f.report(at(path, 'scale'), 'scale-on-non-decimal', `a scale says how many decimal places a decimal field has, and this field is a ${type}`)\n }\n const formed = o?.form !== undefined\n const form = formed ? readFieldForm(f, o?.form, at(path, 'form'), type, nullable) : undefined\n const entry = { id, path: at(path, 'id'), value: type }\n if (id === undefined || type === undefined || label === undefined || nullable === undefined || (formed && form === undefined))\n return { entry, item: undefined, formed }\n return { entry, item: { id, type, label, nullable, ...optional('scale', scale), ...optional('form', form) }, formed }\n}\n\n/** A dataset contract, recording its fields under its role, and what it says of a form. */\nfunction readDataset(\n c: Ctx,\n value: unknown,\n path: string,\n role: DatasetRole,\n declared: Map<string, Declarations<FieldType | undefined>>,\n): { readonly contract: DatasetContract | undefined; readonly form: DatasetForm } {\n const o = shape(c.f, value, path, ['id', 'fields'], ['form'])\n const id = identifier(c.f, o?.id, at(path, 'id'))\n const formed: boolean[] = []\n const fields = readDeclarations(c, o?.fields, at(path, 'fields'), MAX_DATASET_FIELDS, 'field of this dataset', (item, where) => {\n const read = readFieldContract(c.f, item, where)\n formed.push(read.formed)\n return read\n })\n declared.set(role, fields.declared)\n if (fields.items !== undefined) c.declared.nullable.set(role, new Set(fields.items.filter(({ nullable }) => nullable).map(({ id }) => id)))\n const read = o?.form !== undefined\n const { binding, kind } = read ? readDatasetForm(c.f, o?.form, at(path, 'form')) : { binding: undefined, kind: undefined }\n checkFieldsBound(c.f, path, read, formed)\n const contract =\n id === undefined || fields.items === undefined || (read && binding === undefined) ? undefined : { id, fields: fields.items, ...optional('form', binding) }\n return { contract, form: { read, kind } }\n}\n\nexport function readDatasets(c: Ctx, value: unknown, path: string): Datasets | undefined {\n const o = shape(c.f, value, path, [], DATASET_ROLES)\n if (o === undefined) return undefined\n const declared = new Map<string, Declarations<FieldType | undefined>>()\n c.declared.datasets = declared\n const header = o.header === undefined ? undefined : readDataset(c, o.header, at(path, 'header'), 'header', declared)\n const detail = o.detail === undefined ? undefined : readDataset(c, o.detail, at(path, 'detail'), 'detail', declared)\n if (header?.contract !== undefined && detail?.contract !== undefined && header.contract.id === detail.contract.id) {\n c.f.report(\n at(at(path, 'detail'), 'id'),\n 'duplicate-id',\n `the header dataset is already \"${detail.contract.id}\"; each dataset is bound to a provider by its own id`,\n )\n }\n checkDatasetForms(c.f, path, { ...optional('header', header?.form), ...optional('detail', detail?.form) })\n return { ...optional('header', header?.contract), ...optional('detail', detail?.contract) }\n}\n\n/** What a default looks like for each parameter type, and how to tell. Exact values are strings. */\nconst DEFAULTS: { readonly [T in ParameterType]: { readonly accepts: (value: unknown) => boolean; readonly shape: string } } = {\n string: { accepts: (value) => typeof value === 'string', shape: 'a string' },\n integer: { accepts: (value) => typeof value === 'string' && INTEGER.test(value), shape: 'an integer written as a string, such as \"12\"' },\n decimal: { accepts: (value) => typeof value === 'string' && DECIMAL.test(value), shape: 'a decimal written as a string, such as \"12.50\"' },\n boolean: { accepts: (value) => typeof value === 'boolean', shape: 'true or false' },\n date: { accepts: (value) => typeof value === 'string' && isCalendarDate(value), shape: 'a calendar date written YYYY-MM-DD' },\n}\n\nfunction readDefault(f: Findings, value: unknown, path: string, type: ParameterType | undefined): string | boolean | undefined {\n if (value === undefined || type === undefined) return undefined\n if (typeof value === 'string' && text(f, value, path, MAX_LABEL_LENGTH) === undefined) return undefined\n if (DEFAULTS[type].accepts(value)) return value as string | boolean\n f.report(path, 'invalid-default', `a default for a ${type} parameter is ${DEFAULTS[type].shape}; this is ${describe(value)}`)\n return undefined\n}\n\nfunction readParameter(f: Findings, value: unknown, path: string): Read<ParameterDef, ParameterType | undefined> {\n const o = shape(f, value, path, ['id', 'type', 'label', 'required'], ['default'])\n const id = fieldKey(f, o?.id, at(path, 'id'))\n const type = oneOf(f, o?.type, at(path, 'type'), PARAMETER_TYPES)\n const label = text(f, o?.label, at(path, 'label'), MAX_LABEL_LENGTH)\n const required = flag(f, o?.required, at(path, 'required'))\n const fallback = readDefault(f, o?.default, at(path, 'default'), type)\n const entry = { id, path: at(path, 'id'), value: type }\n if (id === undefined || type === undefined || label === undefined || required === undefined) return { entry, item: undefined }\n return { entry, item: { id, type, label, required, ...optional('default', fallback) } }\n}\n\nexport function readParameters(c: Ctx, value: unknown, path: string): readonly ParameterDef[] | undefined {\n const { items, declared } = readDeclarations(c, value, path, MAX_PARAMETERS, 'parameter', (item, where) => readParameter(c.f, item, where))\n c.declared.parameters = declared\n return items\n}\n\nfunction readAsset(f: Findings, value: unknown, path: string): Read<AssetRef, AnyAssetMediaType | undefined> {\n const o = shape(f, value, path, ['id', 'mediaType', 'digest'])\n const id = identifier(f, o?.id, at(path, 'id'))\n const mediaType = oneOf(f, o?.mediaType, at(path, 'mediaType'), ASSET_AND_FONT_MEDIA_TYPES)\n const digest = matches(f, o?.digest, at(path, 'digest'), DIGEST, 'invalid-digest', '\"sha256:\" and 64 lower-case hex digits')\n const entry = { id, path: at(path, 'id'), value: mediaType }\n return { entry, item: id === undefined || mediaType === undefined || digest === undefined ? undefined : { id, mediaType, digest } }\n}\n\nexport function readAssets(c: Ctx, value: unknown, path: string): readonly AssetRef[] | undefined {\n const { items, declared } = readDeclarations(c, value, path, MAX_ASSETS, 'asset', (item, where) => readAsset(c.f, item, where))\n c.declared.assets = declared\n return items\n}\n\n/** Each kind of provenance: what it names, and how to read it. */\nconst PROVENANCE: {\n readonly [K in ProvenanceKind]: {\n readonly required: readonly string[]\n readonly read: (f: Findings, o: Record<string, unknown>, path: string) => Provenance | undefined\n }\n} = {\n blank: { required: [], read: () => ({ kind: 'blank' }) },\n form: {\n required: ['form', 'formHash'],\n read: (f, o, path) => {\n const form = matches(\n f,\n o.form,\n at(path, 'form'),\n FORM_ID,\n 'invalid-id',\n \"a form's id as formancy writes one: letters, digits, '.', '_' and '-', starting with a letter or digit\",\n )\n const formHash = matches(f, o.formHash, at(path, 'formHash'), SCHEMA_HASH, 'invalid-digest', \"the form version's schemaHash: 64 lower-case hex digits\")\n return form === undefined || formHash === undefined ? undefined : { kind: 'form', form, formHash }\n },\n },\n dataset: {\n required: ['dataset'],\n read: (f, o, path) => {\n const dataset = identifier(f, o.dataset, at(path, 'dataset'))\n return dataset === undefined ? undefined : { kind: 'dataset', dataset }\n },\n },\n}\n\nexport function readProvenance(f: Findings, value: unknown, path: string): Provenance | undefined {\n const o = readObject(f, value, path)\n const kind = o && kindOf(f, o, path, PROVENANCE_KINDS)\n if (o === undefined || kind === undefined) return undefined\n strictKeys(f, o, path, ['kind', ...PROVENANCE[kind].required])\n return PROVENANCE[kind].read(f, o, path)\n}\n","/**\n * Finding components in a report: the walk the core's commands, the\n * builder's outline and the runtime share, so they visit components in one\n * order and name them by one path.\n */\nimport type { Component, ComponentKind } from './components.js'\nimport { REGION_NAMES } from './definition.js'\nimport type { RegionName, Regions, ReportDefinition } from './definition.js'\nimport { at } from './pointer.js'\n\nexport interface ComponentLocation {\n readonly component: Component\n readonly region: RegionName\n /** A JSON Pointer from the report's root: the path validation errors use. */\n readonly path: string\n /** How many containers enclose the component: 0 at a region's top level. */\n readonly depth: number\n}\n\ntype ChildLists = readonly (readonly [string, readonly Component[]])[]\n\nconst NONE: ChildLists = []\n\n/**\n * The component lists each kind holds, each with its path relative to the\n * component. A table over every kind, so a container added to the format\n * without saying where it keeps its children does not compile, and the walk\n * cannot quietly skip what the validator checked.\n */\nconst CHILDREN: { readonly [K in ComponentKind]: (component: Extract<Component, { kind: K }>) => ChildLists } = {\n text: () => NONE,\n image: () => NONE,\n qrCode: () => NONE,\n epcQrCode: () => NONE,\n line: () => NONE,\n rectangle: () => NONE,\n spacer: () => NONE,\n columns: (component) => component.columns.map((column, index) => [`/columns/${index}/components`, column.components] as const),\n section: (component) => [['/components', component.components]],\n table: () => NONE,\n chart: () => NONE,\n pageBreak: () => NONE,\n keepTogether: (component) => [['/components', component.components]],\n}\n\nfunction childLists(component: Component): ChildLists {\n return (CHILDREN[component.kind] as (component: Component) => ChildLists)(component)\n}\n\n/** Every component in the report: regions in the order a reader meets them, each depth-first, a container before what it holds. */\nexport function walkComponents(report: ReportDefinition): readonly ComponentLocation[] {\n return walkRegions(report.regions)\n}\n\n/**\n * The regions `regions` holds, each with its components, in the order a\n * reader meets them: every region but an optional one the report leaves\n * out, which holds nothing to visit or put a component in (0060).\n */\nexport function heldRegions(regions: Regions): readonly (readonly [RegionName, readonly Component[]])[] {\n return REGION_NAMES.flatMap((region) => {\n const components = regions[region]\n return components === undefined ? [] : [[region, components] as const]\n })\n}\n\n/** Every component in `regions`, as `walkComponents` finds them: for a validation that has read the regions and not yet the whole report. */\nexport function walkRegions(regions: Regions): readonly ComponentLocation[] {\n const found: ComponentLocation[] = []\n const visit = (components: readonly Component[], region: RegionName, path: string, depth: number): void => {\n for (const [index, component] of components.entries()) {\n const where = at(path, index)\n found.push({ component, region, path: where, depth })\n for (const [suffix, children] of childLists(component)) visit(children, region, `${where}${suffix}`, depth + 1)\n }\n }\n for (const [region, components] of heldRegions(regions)) visit(components, region, at('/regions', region), 0)\n return found\n}\n\n/** The component with `id`, where it is, or undefined when the report has none. Ids are unique in a valid report. */\nexport function componentAt(report: ReportDefinition, id: string): ComponentLocation | undefined {\n return walkComponents(report).find(({ component }) => component.id === id)\n}\n","/**\n * What an e-invoice says of the report around it, held where the report\n * can be read: that its lines are what the report's one table over the\n * detail dataset prints, every row of it (0062), that a payment code\n * printed with it asks for its account and its currency, and that a\n * Factur-X invoice's title can stand in the PDF/A's metadata.\n *\n * The page and the XML are one invoice, or the page is a second one: a\n * picture that differs from the structured part in what the invoice says\n * \"may be a further invoice\" under § 14c UStG (BMF, 15 October 2025, UStAE\n * 14c.1 (4a), which names \"eine andere Leistungsbeschreibung\"). So a line\n * is read from the columns the table prints it with, once per row, and no\n * column, table or container that prints one may be hidden; and a payment\n * code that names another account than the XML's is refused where both are\n * literal. What only a render knows -- an account read from the data, the\n * amount a code asks for, which is an expression -- the runtime compares.\n */\nimport type { RowValue } from './aggregates.js'\nimport { identifier, quote, shape } from './check.js'\nimport type { Regions } from './definition.js'\nimport { E_INVOICE_LINE_CODES, E_INVOICE_LINE_COLUMNS } from './en16931-lines.js'\nimport type { EInvoiceLineCode, EInvoiceLineColumn } from './en16931-lines.js'\nimport { xmlCharacterBreak } from './en16931-texts.js'\nimport { en16931Rule } from './en16931.js'\nimport { checkEpcIban } from './epc-payload.js'\nimport { E_INVOICE_CURRENCIES } from './e-invoice.js'\nimport type { EInvoiceKind, EInvoiceLines } from './e-invoice.js'\nimport type { PaymentPart } from './payment-part.js'\nimport { at } from './pointer.js'\nimport { checkQrBillAccount } from './qr-bill.js'\nimport type { TableComponent } from './table.js'\nimport type { Ctx } from './validate-context.js'\nimport { readRowValue } from './validate-inline.js'\nimport { literal } from './validate-payment-text.js'\nimport type { InlineKind } from './values.js'\nimport { walkRegions } from './walk.js'\nimport type { ComponentLocation } from './walk.js'\n\n/** The parts of the report an e-invoice is held against, each as far as it could be read. */\nexport interface EInvoiceSurroundings {\n readonly title: string | undefined\n readonly regions: Regions | undefined\n readonly paymentPart: PaymentPart | undefined\n}\n\n/** The ids the lines name, each when it could be read: the table, and the column of each term. */\nexport type NamedColumns = { readonly [K in EInvoiceLineColumn | 'table']?: string }\n\n/**\n * The lines: the table and the columns they are printed by, ids checked\n * against the table once the report's regions are read, and each code read\n * from the row as an aggregate reads it, a detail field of the code's type\n * or an expression the core types.\n */\nexport function readLines(c: Ctx, value: unknown, path: string): { readonly lines: EInvoiceLines | undefined; readonly named: NamedColumns } {\n const o = shape(c.f, value, path, ['table', 'name', 'quantity', 'netPrice', 'netAmount', 'id', 'unit', 'vat'])\n const named: Record<string, string> = {}\n for (const key of ['table', ...(Object.keys(E_INVOICE_LINE_COLUMNS) as EInvoiceLineColumn[])]) {\n const id = identifier(c.f, o?.[key], at(path, key))\n if (id !== undefined) named[key] = id\n }\n const codes: Partial<Record<EInvoiceLineCode, RowValue>> = {}\n for (const [key, { what, types }] of Object.entries(E_INVOICE_LINE_CODES) as [EInvoiceLineCode, (typeof E_INVOICE_LINE_CODES)[EInvoiceLineCode]][]) {\n const read = readRowValue(c, o?.[key], at(path, key))\n if (read?.type !== undefined && !types.includes(read.type)) {\n c.f.report(at(at(path, key), 'field'), 'binding-type-mismatch', `${what} is read from a ${types.join(' or ')} field, and this is a ${read.type}`)\n } else if (read !== undefined) codes[key] = read.value\n }\n const { table, name, quantity, netPrice, netAmount } = named\n const { id, unit, vat } = codes\n if (\n table === undefined ||\n name === undefined ||\n quantity === undefined ||\n netPrice === undefined ||\n netAmount === undefined ||\n id === undefined ||\n unit === undefined ||\n vat === undefined\n ) {\n return { lines: undefined, named }\n }\n return { lines: { table, name, quantity, netPrice, netAmount, id, unit, vat }, named }\n}\n\n/** What a column prints that is not read from the row, as a refusal says it. */\nconst UNROWED: { readonly [K in Exclude<InlineKind, 'field' | 'expression'>]: string } = {\n text: 'a literal text',\n parameter: 'a parameter',\n aggregate: 'a total',\n pageNumber: 'a page number',\n pageCount: 'a page count',\n}\n\n/** Reports what a line's term breaks in the column `id` of `table`, which another term may already print. */\nfunction checkColumn(c: Ctx, table: TableComponent, key: EInvoiceLineColumn, id: string, path: string, printedBy: Map<string, EInvoiceLineColumn>): void {\n const { what, types } = E_INVOICE_LINE_COLUMNS[key]\n const column = table.columns.find((candidate) => candidate.id === id)\n if (column === undefined) {\n c.f.report(path, 'unknown-column', `the table ${quote(table.id)} has no column ${quote(id)} to print ${what}`)\n return\n }\n const other = printedBy.get(id)\n if (other !== undefined)\n c.f.report(\n path,\n 'invalid-e-invoice',\n `${what} is printed by the column that prints ${E_INVOICE_LINE_COLUMNS[other].what}: a column prints one term of a line`,\n )\n else printedBy.set(id, key)\n if (column.visibleWhen !== undefined)\n c.f.report(path, 'invalid-e-invoice', `${what} is printed by a column that may be hidden, and every line the XML holds prints it`)\n const cell = column.value\n if (cell.kind === 'expression') return\n if (cell.kind !== 'field') {\n c.f.report(\n path,\n 'invalid-e-invoice',\n `${what} is read from each row, and its column prints ${UNROWED[cell.kind]}: it prints a detail field or an expression`,\n )\n return\n }\n if (cell.field.dataset !== 'detail') {\n c.f.report(\n path,\n 'invalid-e-invoice',\n `${what} is read from each row, and its column prints a header field, the same in every row: it prints a detail field or an expression`,\n )\n return\n }\n const type = c.declared.datasets?.get('detail')?.get(cell.field.field)\n if (type !== undefined && !types.includes(type))\n c.f.report(path, 'binding-type-mismatch', `${what} is a ${types.join(' or ')}, and its column prints a ${type} field`)\n}\n\n/**\n * The lines held to the table over the detail dataset (BR-16 where there is\n * none): its id, and each term's column, printed in every render.\n */\nfunction checkLines(c: Ctx, path: string, locations: readonly ComponentLocation[], named: NamedColumns): void {\n // The first table is the lines' because a report that is an e-invoice\n // holds one (`checkOneTable`, 0062). A version that allows a second\n // there must find the table the lines name instead.\n const found = locations.find(({ component }) => component.kind === 'table')\n if (found === undefined) {\n c.f.report(\n at(path, 'table'),\n 'invalid-e-invoice',\n en16931Rule('BR-16', 'an e-invoice has one line at least, a row of the table over the detail dataset, and this report has no such table'),\n )\n return\n }\n const table = found.component as TableComponent\n if (named.table !== undefined && named.table !== table.id) {\n c.f.report(\n at(path, 'table'),\n 'invalid-e-invoice',\n `the lines are the rows of the table over the detail dataset, ${quote(table.id)}, and this names another`,\n )\n return\n }\n // The table and every container it stands in: a condition on any hides the lines.\n if (locations.some(({ component, path: where }) => component.visibleWhen !== undefined && (where === found.path || found.path.startsWith(`${where}/`)))) {\n c.f.report(\n at(path, 'table'),\n 'invalid-e-invoice',\n 'the lines are printed by a table that may be hidden, or that stands in a component that may be: every line the XML holds is printed',\n )\n }\n if (table.rowsWhen !== undefined) {\n c.f.report(\n at(path, 'table'),\n 'invalid-e-invoice',\n 'the lines are printed by a table that prints only the rows its condition selects: every detail row is a line the XML holds, and is printed',\n )\n }\n const printedBy = new Map<string, EInvoiceLineColumn>()\n for (const key of Object.keys(E_INVOICE_LINE_COLUMNS) as EInvoiceLineColumn[]) {\n const id = named[key]\n if (id !== undefined) checkColumn(c, table, key, id, at(path, key), printedBy)\n }\n}\n\n/**\n * Reports every table after the first, each where it stands: the lines are\n * every row of the report's one table, and a second would print lines, or\n * a part of them, that the XML does not hold as printed (0062). Read from\n * where the validation found each table, so it is said even where the\n * regions could not be read whole.\n */\nfunction checkOneTable(c: Ctx): void {\n const [first, ...others] = c.tables\n for (const other of others) {\n c.f.report(\n other,\n 'second-detail-table',\n `an e-invoice's lines are every row of the report's one table, at ${String(first)}, and a report that is an e-invoice holds no other`,\n )\n }\n}\n\n/**\n * Reports a payment code's account, `written` when it is literal and its\n * own rule took it, at `path`: the e-invoice names an account (BT-84) for\n * every code to ask for, `account` when it is literal and its rule took it,\n * and a code that asks for another is refused. An account not known on\n * either side is the render's to compare.\n */\nfunction checkAccount(c: Ctx, path: string, code: string, written: string | undefined, pays: boolean, account: string | undefined): void {\n if (!pays) {\n c.f.report(\n path,\n 'invalid-e-invoice',\n `${code} asks to be paid to an account, and the e-invoice names none: its payment instructions (BG-16) give the account (BT-84)`,\n )\n } else if (written !== undefined && account !== undefined && written !== account) {\n c.f.report(\n path,\n 'invalid-e-invoice',\n `${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\n/** Every payment code the report prints, the QR-bill and each EPC QR code, held to the e-invoice's currency and account, shown or hidden. */\nfunction checkPaymentCodes(\n c: Ctx,\n around: EInvoiceSurroundings,\n locations: readonly ComponentLocation[] | undefined,\n pays: boolean,\n account: string | undefined,\n): void {\n const bill = around.paymentPart\n if (bill !== undefined) {\n if (!(E_INVOICE_CURRENCIES as readonly string[]).includes(bill.currency)) {\n c.f.report(\n '/paymentPart/currency',\n 'invalid-e-invoice',\n `a QR-bill printed with an e-invoice asks for the e-invoice's currency, ${E_INVOICE_CURRENCIES.join(', ')} (BT-5)`,\n )\n }\n const text = literal(bill.account)\n const checked = text === undefined ? undefined : checkQrBillAccount(text)\n checkAccount(c, '/paymentPart/account', 'the QR-bill', checked?.ok === true ? checked.value.iban : undefined, pays, account)\n }\n for (const { component, path } of locations ?? []) {\n if (component.kind !== 'epcQrCode') continue\n const text = literal(component.iban)\n const checked = text === undefined ? undefined : checkEpcIban(text)\n checkAccount(c, at(path, 'iban'), 'the EPC QR code', checked?.ok === true ? checked.value : undefined, pays, account)\n }\n}\n\n/**\n * The rule a Factur-X invoice's title breaks, or undefined. The renderer\n * writes the title into the PDF/A's XMP, and its engine writes it there\n * unescaped (`_addInfo` in pdfkit 0.19.1's `js/pdfkit.js`): \"Müller & Söhne\n * <AG>\" makes metadata that is not XML, and a PDF that is not PDF/A. The\n * title is the template's own string, never data, so it is refused where\n * it is written; the page may print the three characters. An XRechnung's\n * copy is a plain PDF with no XMP, and its XML holds no title (0038).\n */\nfunction titleBreak(title: string): string | undefined {\n const characters = xmlCharacterBreak(title)\n if (characters !== undefined) return `an e-invoice's title ${characters}`\n return /[&<>]/.test(title)\n ? \"an e-invoice's title is written into its PDF/A's metadata, where &, < and > cannot stand as written: this one holds one\"\n : undefined\n}\n\n/**\n * Everything the e-invoice at `path` says of the report around it: a\n * Factur-X invoice's title, the one table, the lines' columns, and every\n * payment code. `pays` says whether it gives payment instructions,\n * `account` is their account when it is literal and its rule took it, and\n * `kind` is the e-invoice's.\n */\nexport function checkEInvoiceReport(\n c: Ctx,\n path: string,\n around: EInvoiceSurroundings,\n invoice: { readonly named: NamedColumns; readonly pays: boolean; readonly account: string | undefined; readonly kind: EInvoiceKind },\n): void {\n const broken = around.title === undefined || invoice.kind !== 'facturX' ? undefined : titleBreak(around.title)\n if (broken !== undefined) c.f.report('/title', 'invalid-e-invoice', broken)\n checkOneTable(c)\n const locations = around.regions && walkRegions(around.regions)\n if (locations !== undefined) checkLines(c, at(path, 'lines'), locations, invoice.named)\n checkPaymentCodes(c, around, locations, invoice.pays, invoice.account)\n}\n","/**\n * The e-invoice: its shape, and EN 16931's rules applied to every text no\n * data can change.\n *\n * Its texts are runs read in the report's scope and written into the XML,\n * so they read what a paragraph in the summary reads and never a page\n * number or count, as `validate-payment-text.ts` reads every payment\n * code's. A text of literal runs is written the same into every invoice, so\n * `en16931.ts`'s rules are applied to it here, where it is written; any\n * other is checked by the runtime with the same rules, once the data has\n * resolved it. What only the template's declarations decide is decided\n * here too: the seller's and the buyer's identifiers a category needs, the\n * time of supply, and one breakdown for each category.\n *\n * An XRechnung (0038) is read as a Factur-X invoice is, by the same\n * readers, its texts held to its kind's rules (`E_INVOICE_KIND_TEXTS`),\n * and then held to what XRechnung needs past EN 16931 (`XRECHNUNG_NEEDS`),\n * each missing part refused where it is missing, naming its rule.\n *\n * What the e-invoice says of the rest of the report -- that its lines are\n * what the table prints, that a payment code asks for its account, that\n * its title can stand in a PDF/A's metadata -- is\n * `validate-e-invoice-report.ts`'s.\n */\nimport { fieldKey, kindOf, oneOf, optional, readArray, readObject, reference, shape, strictKeys } from './check.js'\nimport {\n E_INVOICE_CURRENCIES,\n E_INVOICE_KINDS,\n E_INVOICE_PROFILES,\n INVOICE_TYPE_CODES,\n PAYMENT_MEANS_CODES,\n VAT_CATEGORY_CODES,\n XRECHNUNG_VERSIONS,\n} from './e-invoice.js'\nimport type {\n AddressScheme,\n EInvoice,\n EInvoiceAddress,\n EInvoiceBuyer,\n EInvoiceKind,\n EInvoiceSeller,\n EInvoiceTerms,\n ElectronicAddress,\n FacturXInvoice,\n InvoicingPeriod,\n LegalIdentifier,\n PaymentInstructions,\n SchemeId,\n SellerContact,\n VatCategory,\n VatCategoryCode,\n XRechnungInvoice,\n} from './e-invoice.js'\nimport { periodBreak, supplyBreak } from './en16931-dates.js'\nimport { checkAddressScheme, checkEInvoiceText, checkElectronicAddress, checkSchemeId, E_INVOICE_KIND_TEXTS, E_INVOICE_TEXT_TERMS } from './en16931-texts.js'\nimport type { EInvoiceTextTerm } from './en16931-texts.js'\nimport { buyerIdentificationBreak, checkVatRate, sellerIdentificationBreaks, vatCategoryBreaks, vatReasonBreak } from './en16931-vat.js'\nimport { en16931Rule } from './en16931.js'\nimport { MAX_VAT_CATEGORIES } from './limits.js'\nimport { at } from './pointer.js'\nimport type { Ctx } from './validate-context.js'\nimport { declare } from './validate-context.js'\nimport { checkEInvoiceReport, readLines } from './validate-e-invoice-report.js'\nimport type { EInvoiceSurroundings } from './validate-e-invoice-report.js'\nimport { readExpression } from './validate-inline.js'\nimport { readPaymentText, unquoted } from './validate-payment-text.js'\nimport type { PaymentScope, PaymentText } from './validate-payment-text.js'\nimport { XRECHNUNG_NEEDS, xrechnungRule } from './xrechnung.js'\n\n/** Where an e-invoice's runs are read: in the report's scope, written into its XML. */\nexport const E_INVOICE_SCOPE: PaymentScope = { region: 'eInvoice', reads: 'report', encoded: 'an e-invoice' }\n\n/** A text of an e-invoice of `kind`, read as every payment code's is, and refused as `invalid-e-invoice` when its term's rule of that kind refuses it, or `check` where it is given. */\nfunction readTerm(\n c: Ctx,\n value: unknown,\n path: string,\n term: EInvoiceTextTerm,\n kind: EInvoiceKind,\n check = (text: string) => checkEInvoiceText(term, text, kind),\n): PaymentText<string> {\n return readPaymentText(c, value, path, E_INVOICE_SCOPE, 'invalid-e-invoice', E_INVOICE_KIND_TEXTS[kind][term].what, check)\n}\n\n/** A part of the e-invoice that holds others, read with exactly its properties: written as a string, it is refused unquoted, since it is a party's name, address or account. */\nfunction readPart(\n c: Ctx,\n value: unknown,\n path: string,\n required: readonly string[],\n optionalKeys: readonly string[] = [],\n): Record<string, unknown> | undefined {\n return typeof value === 'string' ? unquoted(c, path, 'an object', E_INVOICE_SCOPE) : shape(c.f, value, path, required, optionalKeys)\n}\n\n/** Whether a property that is present was read: absent is read, as nothing. */\nconst read = (o: Record<string, unknown>, key: string, value: unknown): boolean => o[key] === undefined || value !== undefined\n\ntype Party = 'seller' | 'buyer'\n\nfunction readAddress(c: Ctx, value: unknown, path: string, party: Party, kind: EInvoiceKind): EInvoiceAddress | undefined {\n const o = readPart(c, value, path, ['line1', 'postalCode', 'city', 'country'], ['line2'])\n if (o === undefined) return undefined\n const address: Partial<Record<keyof EInvoiceAddress, PaymentText<string>['runs']>> = {}\n let whole = true\n for (const [part, term] of Object.entries(E_INVOICE_TEXT_TERMS[party].address) as [keyof EInvoiceAddress, EInvoiceTextTerm][]) {\n const { runs } = readTerm(c, o[part], at(path, part), term, kind)\n if (runs !== undefined) address[part] = runs\n else if (o[part] !== undefined || part !== 'line2') whole = false\n }\n return whole ? (address as EInvoiceAddress) : undefined\n}\n\n/** What a refusal calls a legal registration's scheme. */\nconst SCHEMES: { readonly [P in Party]: string } = {\n seller: \"the scheme of the seller's legal registration identifier (BT-30-1)\",\n buyer: \"the scheme of the buyer's legal registration identifier (BT-47-1)\",\n}\n\nfunction readLegalId(c: Ctx, value: unknown, path: string, party: Party, kind: EInvoiceKind): LegalIdentifier | undefined {\n const o = readPart(c, value, path, ['id'], ['scheme'])\n if (o === undefined) return undefined\n const id = readTerm(c, o.id, at(path, 'id'), E_INVOICE_TEXT_TERMS[party].legalId, kind)\n const code = reference(c.f, o.scheme, at(path, 'scheme'))\n const checked = code === undefined ? undefined : checkSchemeId(code)\n if (checked?.ok === false) c.f.report(at(path, 'scheme'), 'invalid-e-invoice', `${SCHEMES[party]} ${checked.rule}`)\n const scheme: SchemeId | undefined = checked?.ok === true ? checked.value : undefined\n return id.runs === undefined || !read(o, 'scheme', scheme) ? undefined : { id: id.runs, ...optional('scheme', scheme) }\n}\n\n/** What a refusal calls an electronic address's scheme. */\nconst ADDRESS_SCHEME_TERMS: { readonly [P in Party]: string } = {\n seller: \"the scheme of the seller's electronic address (BT-34-1)\",\n buyer: \"the scheme of the buyer's electronic address (BT-49-1)\",\n}\n\n/**\n * An electronic address: its scheme, a code of the list, which EN 16931\n * needs with it (BR-62, BR-63), and its identifier, a text held to its\n * term's rule and, under 0204, to a Leitweg-ID's (0038).\n */\nfunction readElectronicAddress(c: Ctx, value: unknown, path: string, party: Party, kind: EInvoiceKind): ElectronicAddress | undefined {\n const o = readPart(c, value, path, ['id', 'scheme'])\n if (o === undefined) return undefined\n const code = reference(c.f, o.scheme, at(path, 'scheme'))\n const checked = code === undefined ? undefined : checkAddressScheme(code)\n if (checked?.ok === false) c.f.report(at(path, 'scheme'), 'invalid-e-invoice', `${ADDRESS_SCHEME_TERMS[party]} ${checked.rule}`)\n const scheme: AddressScheme | undefined = checked?.ok === true ? checked.value : undefined\n const term = E_INVOICE_TEXT_TERMS[party].electronicAddress\n const id = readTerm(c, o.id, at(path, 'id'), term, kind, (text) =>\n scheme === undefined ? checkEInvoiceText(term, text, kind) : checkElectronicAddress(term, scheme, text, kind),\n )\n return id.runs === undefined || scheme === undefined ? undefined : { id: id.runs, scheme }\n}\n\n/** The seller's contact: its name, its telephone number and its email address, each a text, all three given. */\nfunction readContact(c: Ctx, value: unknown, path: string, kind: EInvoiceKind): SellerContact | undefined {\n const o = readPart(c, value, path, ['name', 'telephone', 'email'])\n if (o === undefined) return undefined\n const terms = E_INVOICE_TEXT_TERMS.seller.contact\n const name = readTerm(c, o.name, at(path, 'name'), terms.name, kind)\n const telephone = readTerm(c, o.telephone, at(path, 'telephone'), terms.telephone, kind)\n const email = readTerm(c, o.email, at(path, 'email'), terms.email, kind)\n return name.runs === undefined || telephone.runs === undefined || email.runs === undefined\n ? undefined\n : { name: name.runs, telephone: telephone.runs, email: email.runs }\n}\n\n/** The seller, its identifiers held to what the categories it declares need when those could be read. */\nfunction readSeller(c: Ctx, value: unknown, path: string, codes: readonly VatCategoryCode[] | undefined, kind: EInvoiceKind): EInvoiceSeller | undefined {\n const o = readPart(c, value, path, ['name', 'address'], ['vatId', 'taxNumber', 'legalId', 'electronicAddress', 'contact'])\n if (o === undefined) return undefined\n const terms = E_INVOICE_TEXT_TERMS.seller\n const name = readTerm(c, o.name, at(path, 'name'), terms.name, kind)\n const vatId = readTerm(c, o.vatId, at(path, 'vatId'), terms.vatId, kind)\n const taxNumber = readTerm(c, o.taxNumber, at(path, 'taxNumber'), terms.taxNumber, kind)\n const legalId = readLegalId(c, o.legalId, at(path, 'legalId'), 'seller', kind)\n const electronicAddress = readElectronicAddress(c, o.electronicAddress, at(path, 'electronicAddress'), 'seller', kind)\n const contact = readContact(c, o.contact, at(path, 'contact'), kind)\n const address = readAddress(c, o.address, at(path, 'address'), 'seller', kind)\n // Said of what is written, read or not: an identifier refused is there.\n const has = { vatId: o.vatId !== undefined, taxNumber: o.taxNumber !== undefined, legalId: o.legalId !== undefined }\n for (const rule of codes === undefined ? [] : sellerIdentificationBreaks(has, codes)) c.f.report(path, 'invalid-e-invoice', rule)\n if (\n name.runs === undefined ||\n address === undefined ||\n !read(o, 'vatId', vatId.runs) ||\n !read(o, 'taxNumber', taxNumber.runs) ||\n !read(o, 'legalId', legalId) ||\n !read(o, 'electronicAddress', electronicAddress) ||\n !read(o, 'contact', contact)\n ) {\n return undefined\n }\n return {\n name: name.runs,\n ...optional('vatId', vatId.runs),\n ...optional('taxNumber', taxNumber.runs),\n ...optional('legalId', legalId),\n ...optional('electronicAddress', electronicAddress),\n ...optional('contact', contact),\n address,\n }\n}\n\n/** The buyer, its identifiers held to what a reverse-charged category needs. */\nfunction readBuyer(c: Ctx, value: unknown, path: string, codes: readonly VatCategoryCode[] | undefined, kind: EInvoiceKind): EInvoiceBuyer | undefined {\n const o = readPart(c, value, path, ['name', 'address'], ['vatId', 'legalId', 'electronicAddress'])\n if (o === undefined) return undefined\n const terms = E_INVOICE_TEXT_TERMS.buyer\n const name = readTerm(c, o.name, at(path, 'name'), terms.name, kind)\n const vatId = readTerm(c, o.vatId, at(path, 'vatId'), terms.vatId, kind)\n const legalId = readLegalId(c, o.legalId, at(path, 'legalId'), 'buyer', kind)\n const electronicAddress = readElectronicAddress(c, o.electronicAddress, at(path, 'electronicAddress'), 'buyer', kind)\n const address = readAddress(c, o.address, at(path, 'address'), 'buyer', kind)\n const broken = codes && buyerIdentificationBreak({ vatId: o.vatId !== undefined, legalId: o.legalId !== undefined }, codes)\n if (broken !== undefined) c.f.report(path, 'invalid-e-invoice', broken)\n if (\n name.runs === undefined ||\n address === undefined ||\n !read(o, 'vatId', vatId.runs) ||\n !read(o, 'legalId', legalId) ||\n !read(o, 'electronicAddress', electronicAddress)\n )\n return undefined\n return { name: name.runs, ...optional('vatId', vatId.runs), ...optional('legalId', legalId), ...optional('electronicAddress', electronicAddress), address }\n}\n\n/** A category as read: the category when all of it was, and the code and the rate by value when each was. */\ninterface ReadCategory {\n readonly category: VatCategory | undefined\n readonly id: string | undefined\n readonly code: VatCategoryCode | undefined\n readonly rate: string | undefined\n}\n\nfunction readVatCategory(c: Ctx, value: unknown, path: string, kind: EInvoiceKind): ReadCategory {\n const o = shape(c.f, value, path, ['id', 'code', 'rate'], ['reason'])\n const id = fieldKey(c.f, o?.id, at(path, 'id'))\n const code = oneOf(c.f, o?.code, at(path, 'code'), VAT_CATEGORY_CODES)\n const written = reference(c.f, o?.rate, at(path, 'rate'))\n const checked = written === undefined || code === undefined ? undefined : checkVatRate(code, written)\n if (checked?.ok === false) c.f.report(at(path, 'rate'), 'invalid-e-invoice', `the VAT category's rate (BT-119) ${checked.rule}`)\n const reason = readTerm(c, o?.reason, at(path, 'reason'), E_INVOICE_TEXT_TERMS.reason, kind)\n const unreasoned = o && code && vatReasonBreak(code, o.reason !== undefined)\n if (unreasoned !== undefined) c.f.report(at(path, 'reason'), 'invalid-e-invoice', unreasoned)\n const rate = checked?.ok === true ? checked.value : undefined\n if (o === undefined || id === undefined || code === undefined || rate === undefined || written === undefined || !read(o, 'reason', reason.runs)) {\n return { category: undefined, id, code, rate }\n }\n return { category: { id, code, rate: written, ...optional('reason', reason.runs) }, id, code, rate }\n}\n\n/** What a breakdown's refusal is said of: its rate, or the category itself. */\nconst BREAKDOWN_FIELDS = { rate: \"the VAT category's rate (BT-119)\", code: 'the VAT category (BT-118)' } as const\n\n/**\n * The categories, one at least (BR-CO-18), each id once, each one breakdown\n * (`vatCategoryBreaks`); and their codes, when every one could be read, for\n * what the parties' identifiers must be.\n */\nfunction readVatCategories(\n c: Ctx,\n value: unknown,\n path: string,\n kind: EInvoiceKind,\n): { categories: readonly VatCategory[] | undefined; codes: readonly VatCategoryCode[] | undefined } {\n const items = readArray(c.f, value, path, MAX_VAT_CATEGORIES)\n if (items === undefined) return { categories: undefined, codes: undefined }\n if (items.length === 0)\n c.f.report(\n path,\n 'invalid-e-invoice',\n en16931Rule('BR-CO-18', 'an e-invoice declares one VAT category at least, the VAT breakdown (BG-23) its lines are in'),\n )\n const read = items.map((item, index) => readVatCategory(c, item, at(path, index), kind))\n declare(\n c.f,\n read.map(({ id }, index) => ({ id, path: at(at(path, index), 'id'), value: true })),\n 'duplicate-id',\n (id) => `${id} is already the id of a VAT category of this invoice`,\n )\n const rated = read.flatMap(({ code, rate }, index) => (code === undefined || rate === undefined ? [] : [{ index, code, rate }]))\n for (const { index, field, rule } of vatCategoryBreaks(rated)) {\n c.f.report(at(at(path, (rated[index] as { index: number }).index), field), 'invalid-e-invoice', `${BREAKDOWN_FIELDS[field]} ${rule}`)\n }\n const codes = read.map(({ code }) => code)\n const categories = read.map(({ category }) => category)\n return {\n categories: categories.every((category) => category !== undefined) ? categories : undefined,\n codes: codes.every((code) => code !== undefined) ? codes : undefined,\n }\n}\n\n/** The invoicing period: a start, an end or both (BR-CO-19), each an expression. */\nfunction readPeriod(c: Ctx, value: unknown, path: string): InvoicingPeriod | undefined {\n const o = shape(c.f, value, path, [], ['start', 'end'])\n if (o === undefined) return undefined\n const broken = periodBreak(o.start !== undefined, o.end !== undefined)\n if (broken !== undefined) c.f.report(path, 'invalid-e-invoice', broken)\n const start = readExpression(c.f, o.start, at(path, 'start'))\n const end = readExpression(c.f, o.end, at(path, 'end'))\n if (broken !== undefined || !read(o, 'start', start) || !read(o, 'end', end)) return undefined\n return { ...optional('start', start), ...optional('end', end) }\n}\n\n/** The payment instructions, and the account as the XML writes it when it is literal and its rule took it. */\nfunction readPayment(c: Ctx, value: unknown, path: string, kind: EInvoiceKind): { payment: PaymentInstructions | undefined; account: string | undefined } {\n const o = readPart(c, value, path, ['means', 'iban'], ['bic', 'accountName', 'remittance'])\n const means = oneOf(c.f, o?.means, at(path, 'means'), PAYMENT_MEANS_CODES)\n const terms = E_INVOICE_TEXT_TERMS.payment\n const iban = readTerm(c, o?.iban, at(path, 'iban'), terms.iban, kind)\n const bic = readTerm(c, o?.bic, at(path, 'bic'), terms.bic, kind)\n const accountName = readTerm(c, o?.accountName, at(path, 'accountName'), terms.accountName, kind)\n const remittance = readTerm(c, o?.remittance, at(path, 'remittance'), terms.remittance, kind)\n if (\n o === undefined ||\n means === undefined ||\n iban.runs === undefined ||\n !read(o, 'bic', bic.runs) ||\n !read(o, 'accountName', accountName.runs) ||\n !read(o, 'remittance', remittance.runs)\n ) {\n return { payment: undefined, account: iban.checked }\n }\n const payment = {\n means,\n iban: iban.runs,\n ...optional('bic', bic.runs),\n ...optional('accountName', accountName.runs),\n ...optional('remittance', remittance.runs),\n }\n return { payment, account: iban.checked }\n}\n\n/** The properties both kinds have, beside each kind's own: its profile, or its version. */\nconst TERMS_REQUIRED = ['kind', 'type', 'currency', 'number', 'issued', 'seller', 'buyer', 'vat', 'lines']\nconst TERMS_OPTIONAL = ['businessProcess', 'buyerReference', 'delivered', 'period', 'payment', 'due', 'terms', 'paid']\n\n/**\n * EN 16931's terms of an e-invoice of `kind`, each held to that kind's\n * rules, and what they say of the report around it: the terms when every\n * one could be read, undefined otherwise, every fault reported. Which keys\n * the e-invoice may have is its kind's reader's to say.\n */\nfunction readTerms(c: Ctx, o: Record<string, unknown>, path: string, around: EInvoiceSurroundings, kind: EInvoiceKind): EInvoiceTerms | undefined {\n const type = oneOf(c.f, o.type, at(path, 'type'), INVOICE_TYPE_CODES)\n const currency = oneOf(c.f, o.currency, at(path, 'currency'), E_INVOICE_CURRENCIES)\n const number = readTerm(c, o.number, at(path, 'number'), E_INVOICE_TEXT_TERMS.number, kind)\n const issued = readExpression(c.f, o.issued, at(path, 'issued'))\n const businessProcess = readTerm(c, o.businessProcess, at(path, 'businessProcess'), E_INVOICE_TEXT_TERMS.businessProcess, kind)\n // The categories first: what the parties' identifiers must be depends on their codes.\n const { categories, codes } = readVatCategories(c, o.vat, at(path, 'vat'), kind)\n const seller = readSeller(c, o.seller, at(path, 'seller'), codes, kind)\n const buyer = readBuyer(c, o.buyer, at(path, 'buyer'), codes, kind)\n const buyerReference = readTerm(c, o.buyerReference, at(path, 'buyerReference'), E_INVOICE_TEXT_TERMS.buyerReference, kind)\n const unsupplied = supplyBreak(o.delivered !== undefined, o.period !== undefined)\n if (unsupplied !== undefined) c.f.report(at(path, 'delivered'), 'invalid-e-invoice', unsupplied)\n const delivered = readExpression(c.f, o.delivered, at(path, 'delivered'))\n const period = readPeriod(c, o.period, at(path, 'period'))\n const { lines, named } = readLines(c, o.lines, at(path, 'lines'))\n const { payment, account } = readPayment(c, o.payment, at(path, 'payment'), kind)\n const due = readExpression(c.f, o.due, at(path, 'due'))\n const terms = readTerm(c, o.terms, at(path, 'terms'), E_INVOICE_TEXT_TERMS.terms, kind)\n const paid = readExpression(c.f, o.paid, at(path, 'paid'))\n checkEInvoiceReport(c, path, around, { named, pays: o.payment !== undefined, account, kind })\n if (\n type === undefined ||\n currency === undefined ||\n number.runs === undefined ||\n issued === undefined ||\n seller === undefined ||\n buyer === undefined ||\n categories === undefined ||\n lines === undefined ||\n !read(o, 'businessProcess', businessProcess.runs) ||\n !read(o, 'buyerReference', buyerReference.runs) ||\n !read(o, 'delivered', delivered) ||\n !read(o, 'period', period) ||\n !read(o, 'payment', payment) ||\n !read(o, 'due', due) ||\n !read(o, 'terms', terms.runs) ||\n !read(o, 'paid', paid)\n ) {\n return undefined\n }\n return {\n type,\n currency,\n number: number.runs,\n issued,\n ...optional('businessProcess', businessProcess.runs),\n seller,\n buyer,\n ...optional('buyerReference', buyerReference.runs),\n ...optional('delivered', delivered),\n ...optional('period', period),\n vat: categories,\n lines,\n ...optional('payment', payment),\n ...optional('due', due),\n ...optional('terms', terms.runs),\n ...optional('paid', paid),\n }\n}\n\nfunction readFacturX(c: Ctx, o: Record<string, unknown>, path: string, around: EInvoiceSurroundings): FacturXInvoice | undefined {\n strictKeys(c.f, o, path, [...TERMS_REQUIRED, 'profile'], TERMS_OPTIONAL)\n const profile = oneOf(c.f, o.profile, at(path, 'profile'), E_INVOICE_PROFILES)\n const terms = readTerms(c, o, path, around, 'facturX')\n return profile === undefined || terms === undefined ? undefined : { kind: 'facturX', profile, ...terms }\n}\n\n/** `value` where it is an object of properties, as a part of the format is; undefined where it is anything else, a list among it. */\nconst partOf = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined\n\n/**\n * An XRechnung: EN 16931's terms held to its kind's rules, its version, and\n * each part XRechnung needs past EN 16931, refused where it is missing,\n * naming the rule. A part whose parent is missing or is no object is that\n * parent's fault, said where the parent is read.\n */\nfunction readXRechnung(c: Ctx, o: Record<string, unknown>, path: string, around: EInvoiceSurroundings): XRechnungInvoice | undefined {\n strictKeys(c.f, o, path, [...TERMS_REQUIRED, 'version'], TERMS_OPTIONAL)\n const version = oneOf(c.f, o.version, at(path, 'version'), XRECHNUNG_VERSIONS)\n const terms = readTerms(c, o, path, around, 'xrechnung')\n let needed = true\n for (const [pointer, need] of Object.entries(XRECHNUNG_NEEDS)) {\n const keys = pointer.split('/')\n const parent = keys.slice(0, -1).reduce<Record<string, unknown> | undefined>((part, key) => partOf(part?.[key]), o)\n if (parent === undefined || parent[keys.at(-1) as string] !== undefined) continue\n c.f.report(`${path}/${pointer}`, 'invalid-e-invoice', xrechnungRule(need.rule, need.said))\n needed = false\n }\n // Every part XRechnung needs is there and was read: the terms carry them.\n return version === undefined || terms === undefined || !needed ? undefined : ({ kind: 'xrechnung', version, ...terms } as XRechnungInvoice)\n}\n\ntype EInvoiceReader<E extends EInvoice> = (c: Ctx, o: Record<string, unknown>, path: string, around: EInvoiceSurroundings) => E | undefined\n\n/** How each kind of e-invoice is read. A table over every kind, so a kind added to E_INVOICE_KINDS without a reader does not compile. */\nconst READERS: { readonly [K in EInvoiceKind]: EInvoiceReader<Extract<EInvoice, { kind: K }>> } = {\n facturX: readFacturX,\n xrechnung: readXRechnung,\n}\n\n/**\n * The e-invoice at `path`, read with what it says of the report around it:\n * its title, its regions and its payment part, as far as each could be\n * read. Absent, the report is none.\n */\nexport function readEInvoice(c: Ctx, value: unknown, path: string, around: EInvoiceSurroundings): EInvoice | undefined {\n const o = typeof value === 'string' ? unquoted(c, path, 'an object', E_INVOICE_SCOPE) : readObject(c.f, value, path)\n const kind = o && kindOf(c.f, o, path, E_INVOICE_KINDS)\n if (o === undefined || kind === undefined) return undefined\n return READERS[kind](c, o, path, around)\n}\n","/**\n * The report's font map, validated (0043): which approved font assets each\n * font token prints in, face by face, and whether the faces a report's own\n * styles ask for are mapped.\n *\n * A face names an asset the report declares, whose media type is a font's:\n * an undeclared id is `unknown-asset`, and an image asset mapped as a face\n * is `asset-not-a-font`. Nothing here reads a font's bytes -- a face is a\n * reference, resolved by the deployment -- so what is checked is the\n * mapping's shape and its references, as for every asset a report names.\n *\n * `missing-face` is the one rule that reads a style against the map: a\n * print style that sets `bold` or `italic` for a mapped family without that\n * family's bold, italic or bold-italic face. A face is never synthesised\n * (plan 20), so a report whose heading is bold in a mapped family that has\n * no bold face could not print, and the author hears so while editing. What\n * the renderer prints bold of its own -- a table's header and total rows --\n * it holds to the map at print, where the data decides which faces a run\n * needs.\n */\nimport { isFontMediaType } from './assets.js'\nimport { optional, quote, reference, shape } from './check.js'\nimport { faceKey } from './font-map.js'\nimport type { FontFaceKey, FontFaces, FontMap } from './font-map.js'\nimport { at } from './pointer.js'\nimport { FONT_FAMILIES } from './styles.js'\nimport type { PrintStyle } from './styles.js'\nimport { resolve } from './validate-context.js'\nimport type { Ctx } from './validate-context.js'\n\n/** The faces of a family a report may map, `normal` required and the rest optional, read in `FONT_FACE_KEYS`' order. */\nfunction readFaces(c: Ctx, value: unknown, path: string): FontFaces | undefined {\n const o = shape(c.f, value, path, ['normal'], ['bold', 'italic', 'boldItalic'])\n const face = (key: FontFaceKey): string | undefined => {\n const asset = reference(c.f, o?.[key], at(path, key))\n if (asset === undefined) return undefined\n const mediaType = resolve(c.f, c.declared.assets, asset, at(path, key), 'unknown-asset', 'asset')\n if (mediaType !== undefined && !isFontMediaType(mediaType))\n c.f.report(at(path, key), 'asset-not-a-font', `the asset ${quote(asset)} is an image, not a font`)\n return asset\n }\n const normal = face('normal')\n const bold = face('bold')\n const italic = face('italic')\n const boldItalic = face('boldItalic')\n if (o === undefined || normal === undefined) return undefined\n return { normal, ...optional('bold', bold), ...optional('italic', italic), ...optional('boldItalic', boldItalic) }\n}\n\n/** The font map in `value`, its families read in `FONT_FAMILIES`' order; absent is no map. */\nexport function readFontMap(c: Ctx, value: unknown, path: string): FontMap | undefined {\n if (value === undefined) return undefined\n const o = shape(c.f, value, path, [], FONT_FAMILIES)\n if (o === undefined) return undefined\n const map: { -readonly [F in keyof FontMap]: FontFaces } = {}\n let complete = true\n for (const family of FONT_FAMILIES) {\n if (o[family] === undefined) continue\n const faces = readFaces(c, o[family], at(path, family))\n if (faces === undefined) complete = false\n else map[family] = faces\n }\n return complete ? map : undefined\n}\n\n/**\n * Reports a `missing-face` for each print style that sets a weight or a\n * slant its mapped family has no face for: the style names the family and\n * the face, the face is read from the style's own `bold` and `italic`, and\n * `boldItalic` is the face a style that is both needs.\n */\nexport function checkMissingFaces(c: Ctx, styles: readonly PrintStyle[] | undefined, fonts: FontMap | undefined, path: string): void {\n if (styles === undefined || fonts === undefined) return\n styles.forEach((style, index) => {\n if (style.font === undefined) return\n const faces = fonts[style.font]\n if (faces === undefined) return\n const key = faceKey(style.bold === true, style.italic === true)\n if (key === 'normal' || faces[key] !== undefined) return\n c.f.report(at(path, index), 'missing-face', `the style ${quote(style.id)} prints ${WHICH[key]} in the ${style.font} font, which maps no ${key} face`)\n })\n}\n\n/** What a style asks for, for a message a person reads. */\nconst WHICH: { readonly [K in Exclude<FontFaceKey, 'normal'>]: string } = { bold: 'bold text', italic: 'italic text', boldItalic: 'bold italic text' }\n","/**\n * The payment part: its shape, the page it is printed on, and SIX's rules\n * applied to every text no data can change.\n *\n * Its texts are runs read in the report's scope and encoded in the bill's\n * QR code, so they read what a paragraph in the summary reads and never a\n * page number or count. A text of literal runs prints the same in every\n * render, so `qr-bill.ts`'s rules are applied to it here, where it is\n * written, as `validate-payment-text.ts` reads every payment code's texts;\n * any other is checked by the runtime with the same rules, once the data\n * has resolved it.\n */\nimport { kindOf, oneOf, optional, readObject, shape, strictKeys } from './check.js'\nimport type { PageSettings } from './page.js'\nimport { PAYMENT_PART_KINDS, QR_BILL_CURRENCIES, QR_BILL_LANGUAGES } from './payment-part.js'\nimport type { PaymentPart, PaymentPartKind, QrBillAddress, SwissQrBill } from './payment-part.js'\nimport { at } from './pointer.js'\nimport {\n checkQrBillAccount,\n checkQrBillAdditionalInformation,\n checkQrBillReference,\n checkQrBillText,\n QR_BILL_ADDRESS_RULES,\n QR_BILL_BILLING_RULE,\n QR_BILL_MESSAGE_RULE,\n qrBillPageBreak,\n qrBillPairing,\n} from './qr-bill.js'\nimport type { QrBillCheck, QrBillPageBreak, QrBillTextRule } from './qr-bill.js'\nimport type { Ctx } from './validate-context.js'\nimport { readExpression } from './validate-inline.js'\nimport { readPaymentText, unquoted } from './validate-payment-text.js'\nimport type { PaymentScope, PaymentText } from './validate-payment-text.js'\nimport type { Inline } from './values.js'\n\n/** Where a bill's runs are read: in the report's scope, encoded in its QR code. */\nconst SCOPE: PaymentScope = { region: 'paymentPart', reads: 'report', encoded: 'a QR-bill' }\n\n/**\n * Where each rule of the page is reported: the A4 rule on the page, whose\n * size and orientation are what the author changes, and the slip's room on\n * the top margin.\n */\nconst PAGE_FIELDS: { readonly [F in QrBillPageBreak['field']]: string } = { page: '/page', topMargin: '/page/margins/top' }\n\n/** A text of the bill, read as every payment code's is, and refused as `invalid-qr-bill` when SIX's rule refuses it. */\nfunction readText<T>(c: Ctx, value: unknown, path: string, what: string, check: (text: string) => QrBillCheck<T>): PaymentText<T> {\n return readPaymentText(c, value, path, SCOPE, 'invalid-qr-bill', what, check)\n}\n\ntype AddressPart = keyof QrBillAddress\n\nconst ADDRESS_PARTS = Object.entries(QR_BILL_ADDRESS_RULES) as readonly (readonly [AddressPart, QrBillTextRule])[]\nconst REQUIRED_PARTS = ADDRESS_PARTS.filter(([, rule]) => rule.required).map(([part]) => part)\nconst OPTIONAL_PARTS = ADDRESS_PARTS.filter(([, rule]) => !rule.required).map(([part]) => part)\n\n/** A party's address, each part read in the order the code holds them and held to its rule. */\nfunction readAddress(c: Ctx, value: unknown, path: string, party: 'creditor' | 'debtor'): QrBillAddress | undefined {\n const o = typeof value === 'string' ? unquoted(c, path, 'an object', SCOPE) : shape(c.f, value, path, REQUIRED_PARTS, OPTIONAL_PARTS)\n if (o === undefined) return undefined\n const address: Partial<Record<AddressPart, readonly Inline[]>> = {}\n let whole = true\n for (const [part, rule] of ADDRESS_PARTS) {\n const { runs } = readText(c, o[part], at(path, part), `the ${party}'s ${rule.said}`, (text) => checkQrBillText(text, rule))\n if (runs !== undefined) address[part] = runs\n else if (o[part] !== undefined || rule.required) whole = false\n }\n return whole ? (address as QrBillAddress) : undefined\n}\n\nconst BILL_REQUIRED = ['kind', 'language', 'account', 'creditor', 'currency']\nconst BILL_OPTIONAL = ['amount', 'debtor', 'reference', 'message', 'billingInformation']\n\n/** Whether a property that is present was read: absent is read, as nothing. */\nconst read = (o: Record<string, unknown>, key: string, value: unknown): boolean => o[key] === undefined || value !== undefined\n\nfunction readSwissQrBill(c: Ctx, o: Record<string, unknown>, path: string, page: PageSettings | undefined): SwissQrBill | undefined {\n strictKeys(c.f, o, path, BILL_REQUIRED, BILL_OPTIONAL)\n const broken = page && qrBillPageBreak(page)\n if (broken !== undefined) c.f.report(PAGE_FIELDS[broken.field], 'payment-part-page', broken.rule)\n const language = oneOf(c.f, o.language, at(path, 'language'), QR_BILL_LANGUAGES)\n const account = readText(c, o.account, at(path, 'account'), 'the account', checkQrBillAccount)\n const creditor = readAddress(c, o.creditor, at(path, 'creditor'), 'creditor')\n const currency = oneOf(c.f, o.currency, at(path, 'currency'), QR_BILL_CURRENCIES)\n const amount = readExpression(c.f, o.amount, at(path, 'amount'))\n const debtor = readAddress(c, o.debtor, at(path, 'debtor'), 'debtor')\n const reference = readText(c, o.reference, at(path, 'reference'), 'the reference', checkQrBillReference)\n const message = readText(c, o.message, at(path, 'message'), 'the message', (text) => checkQrBillText(text, QR_BILL_MESSAGE_RULE))\n const billing = readText(c, o.billingInformation, at(path, 'billingInformation'), 'the billing information', (text) =>\n checkQrBillText(text, QR_BILL_BILLING_RULE),\n )\n if (message.checked !== undefined && billing.checked !== undefined) {\n const together = checkQrBillAdditionalInformation(message.checked, billing.checked)\n if (together !== undefined) c.f.report(at(path, 'message'), 'invalid-qr-bill', together)\n }\n if (currency !== undefined) {\n // An account or a reference read from data is not known yet, nor is one\n // already refused; an absent reference is known: the bill has none.\n const kind = account.checked === undefined ? undefined : account.checked.qrIban ? 'qrIban' : 'iban'\n const type = o.reference === undefined ? 'NON' : reference.checked?.type\n for (const { field, rule } of qrBillPairing(kind, type, currency)) c.f.report(at(path, field), 'invalid-qr-bill', rule)\n }\n if (\n language === undefined ||\n account.runs === undefined ||\n creditor === undefined ||\n currency === undefined ||\n !read(o, 'amount', amount) ||\n !read(o, 'debtor', debtor) ||\n !read(o, 'reference', reference.runs) ||\n !read(o, 'message', message.runs) ||\n !read(o, 'billingInformation', billing.runs)\n ) {\n return undefined\n }\n return {\n kind: 'swissQrBill',\n language,\n account: account.runs,\n creditor,\n currency,\n ...optional('amount', amount),\n ...optional('debtor', debtor),\n ...optional('reference', reference.runs),\n ...optional('message', message.runs),\n ...optional('billingInformation', billing.runs),\n }\n}\n\ntype PartReader<P extends PaymentPart> = (c: Ctx, o: Record<string, unknown>, path: string, page: PageSettings | undefined) => P | undefined\n\n/** How each kind of payment part is read. A table over every kind, so a kind added to PAYMENT_PART_KINDS without a reader does not compile. */\nconst PARTS: { readonly [K in PaymentPartKind]: PartReader<Extract<PaymentPart, { kind: K }>> } = {\n swissQrBill: readSwissQrBill,\n}\n\n/** The payment part at `path`, read on `page`, the report's page when it could be read. Absent, the report has none. */\nexport function readPaymentPart(c: Ctx, value: unknown, path: string, page: PageSettings | undefined): PaymentPart | undefined {\n const o = readObject(c.f, value, path)\n const kind = o && kindOf(c.f, o, path, PAYMENT_PART_KINDS)\n if (o === undefined || kind === undefined) return undefined\n return PARTS[kind](c, o, path, page)\n}\n","/**\n * A report's own words, and their translations\n * ([0063](../../../docs/decisions/0063-a-reports-own-words-are-written-in-each-language-it-declares-and-a-render-names-the-one-it-prints-in.md)).\n *\n * A report is written in its own `locale`. It may declare `translations`:\n * for each other language, its words written in that language, each\n * looked up by its exact text in the report's own, and each expression\n * that prints words by its exact source. What a word is, is this module's\n * walk, and the places it walks are the only ones: every other string of\n * the format prints as written in every language, and `NOT_WORDS` names\n * each of them, so that a string added to the format is one or the other\n * by a decision. `report-in.ts` writes a report in one of its languages;\n * `validate-translations.ts` holds what a translation may be.\n */\nimport type { ChartComponent } from './chart.js'\nimport type { Component, ComponentKind } from './components.js'\nimport type { ReportDefinition } from './definition.js'\nimport { at } from './pointer.js'\nimport type { TableComponent, TableFooterRow } from './table.js'\nimport type { Expression, Inline } from './values.js'\nimport { walkComponents } from './walk.js'\n\n/** A word of the report, exactly as it stands in the report's own language, and what prints for it in a translation's. */\nexport interface TranslatedWord {\n readonly word: string\n readonly text: string\n}\n\n/** An expression that prints words, by its source exactly, and the expression that prints in its place in a translation's language. */\nexport interface TranslatedExpression {\n readonly cel: string\n readonly expression: Expression\n}\n\n/** The report's words in one language besides its own. */\nexport interface Translation {\n /** A BCP 47 tag, written as the report's `locale` is; never the report's own. */\n readonly locale: string\n /** Each word once; a language just added holds none yet. */\n readonly words: readonly TranslatedWord[]\n readonly expressions: readonly TranslatedExpression[]\n}\n\n/** A literal string where a word stands, and where it is. */\nexport interface WordPlace {\n /** The JSON Pointer to the string: a run's `text`, a column's `header`, the report's `title`. */\n readonly path: string\n readonly text: string\n /** The innermost component it stands in; none for the title or the payment part's message. */\n readonly componentId?: string\n /** For a table column's header and its value, the column's id. */\n readonly columnId?: string\n}\n\n/** An expression run where a word stands: a word where it prints text and its source holds a quote, which only the core can tell (0063). */\nexport interface WordExpressionSite {\n /** The JSON Pointer to the expression's `cel`, as report-core names the site it compiles. */\n readonly path: string\n readonly cel: string\n readonly componentId?: string\n readonly columnId?: string\n}\n\n/** Every place a word may stand: literal strings, whether or not each holds a letter, and expression runs. */\nexport interface WordPlaces {\n readonly literals: readonly WordPlace[]\n readonly expressions: readonly WordExpressionSite[]\n}\n\nconst LETTER = /\\p{L}/u\n\n/** Whether `text` is a word: whether it holds a letter, of any script. A separator, a number or a sign prints as written in every language. */\nexport function isWord(text: string): boolean {\n return LETTER.test(text)\n}\n\n/** Where a word stands: the component and the column, where there is one. */\ninterface Owner {\n readonly componentId?: string\n readonly columnId?: string\n}\n\n/** What one walk collects. */\nclass Places implements WordPlaces {\n readonly literals: WordPlace[] = []\n readonly expressions: WordExpressionSite[] = []\n\n literal(text: string | undefined, path: string, owner: Owner): void {\n if (text !== undefined) this.literals.push({ path, text, ...owner })\n }\n\n run(inline: Inline, path: string, owner: Owner): void {\n if (inline.kind === 'text') this.literal(inline.text, at(path, 'text'), owner)\n if (inline.kind === 'expression') this.expressions.push({ path: `${path}/expression/cel`, cel: inline.expression.cel, ...owner })\n }\n\n runs(inlines: readonly Inline[] | undefined, path: string, owner: Owner): void {\n for (const [index, inline] of (inlines ?? []).entries()) this.run(inline, at(path, index), owner)\n }\n\n footer(rows: readonly TableFooterRow[] | undefined, path: string, owner: Owner): void {\n for (const [index, row] of (rows ?? []).entries()) {\n for (const [cell, { value }] of row.cells.entries()) this.run(value, `${path}/${index}/cells/${cell}/value`, owner)\n }\n }\n}\n\ntype Walker<K extends ComponentKind> = (component: Extract<Component, { kind: K }>, path: string, into: Places) => void\n\nconst NONE = (): void => undefined\n\nconst table: Walker<'table'> = (component: TableComponent, path, into) => {\n const owner = { componentId: component.id }\n for (const [index, column] of component.columns.entries()) {\n const where = `${path}/columns/${index}`\n const inColumn = { ...owner, columnId: column.id }\n into.literal(column.header, `${where}/header`, inColumn)\n into.run(column.value, `${where}/value`, inColumn)\n }\n into.runs(component.group?.header, `${path}/group/header`, owner)\n into.footer(component.group?.footer, `${path}/group/footer`, owner)\n into.footer(component.totals, `${path}/totals`, owner)\n into.literal(component.emptyText, `${path}/emptyText`, owner)\n}\n\n/** A chart's words, in the order its type holds them. */\nconst chart: Walker<'chart'> = (component: ChartComponent, path, into) => {\n const owner = { componentId: component.id }\n into.literal(component.category.nullLabel, `${path}/category/nullLabel`, owner)\n for (const [index, series] of component.series.entries()) into.literal(series.label, `${path}/series/${index}/label`, owner)\n into.literal(component.emptyText, `${path}/emptyText`, owner)\n into.literal(component.title, `${path}/title`, owner)\n into.literal(component.categoryTitle, `${path}/categoryTitle`, owner)\n into.literal(component.valueTitle, `${path}/valueTitle`, owner)\n}\n\n/**\n * The words each kind holds. A table over every kind, so a kind added to\n * the format without saying where its words are does not compile. A QR\n * code's content and an EPC QR code's texts are codes a scanner reads, and\n * hold none; what a container holds is visited by the walk itself.\n */\nconst WALKERS: { readonly [K in ComponentKind]: Walker<K> } = {\n text: (component, path, into) => into.runs(component.content, `${path}/content`, { componentId: component.id }),\n image: NONE,\n qrCode: NONE,\n epcQrCode: NONE,\n line: NONE,\n rectangle: NONE,\n spacer: NONE,\n columns: NONE,\n section: NONE,\n table,\n chart,\n pageBreak: NONE,\n keepTogether: NONE,\n}\n\n/**\n * Every place a word may stand in `report`, in document order: the title,\n * each component's as the walk meets it, and the payment part's message\n * last. Literals whether or not they hold a letter; `reportWords` keeps\n * those that do.\n */\nexport function wordPlaces(report: ReportDefinition): WordPlaces {\n const into = new Places()\n into.literal(report.title, '/title', {})\n for (const { component, path } of walkComponents(report)) (WALKERS[component.kind] as Walker<ComponentKind>)(component, path, into)\n into.runs(report.paymentPart?.message, '/paymentPart/message', {})\n return into\n}\n\n/** Every word of `report`, at each place it stands, in document order: a word in several places is yielded at each. */\nexport function reportWords(report: ReportDefinition): readonly WordPlace[] {\n return wordPlaces(report).literals.filter(({ text }) => isWord(text))\n}\n\n/** Every expression run where a word stands, in document order: report-core says which of them print words. */\nexport function wordExpressionSites(report: ReportDefinition): readonly WordExpressionSite[] {\n return wordPlaces(report).expressions\n}\n\n/**\n * Every string of the format that is not a word, as JSON Pointer\n * patterns: from the report's root, or, after a component's kind and a\n * colon, from that component (`*` for any kind). A segment `*` is any one\n * segment, `**` any number of them. Each prints as written in every\n * language, for the reason given; `words.test.ts` holds every string a\n * report can hold to being a word place or one of these, and never both.\n */\nexport const NOT_WORDS: readonly { readonly why: string; readonly at: readonly string[] }[] = [\n {\n why: 'what names a part of the report, the format or a vocabulary, which no reader reads',\n at: [\n '/reportSpecVersion',\n '**/id',\n '**/kind',\n '**/style',\n '**/headerStyle',\n '**/dataset',\n '**/field',\n '**/parameter',\n '**/aggregate',\n '**/asset',\n '**/column',\n '**/over',\n '**/fn',\n '**/mode',\n '**/increment',\n '**/direction',\n '**/order',\n '**/transform',\n '**/code',\n '**/align',\n '**/baseline',\n '**/width',\n '**/fit',\n '**/errorCorrection',\n '**/color',\n '**/fill',\n '**/stroke',\n '**/palette/*',\n 'chart:/chart',\n ],\n },\n { why: \"the report's own language, and the languages its translations are in\", at: ['/locale', '/translations/**'] },\n {\n why: 'conditions, which print nothing',\n at: ['*:/visibleWhen/cel', '*:/styleWhen/*/when/cel', 'table:/columns/*/visibleWhen/cel', 'table:/columns/*/styleWhen/*/when/cel'],\n },\n {\n why: \"a table's row condition (0062), which prints nothing and selects the rows the table prints: read as written in every language, so that a render selects the same rows in each\",\n at: ['table:/rowsWhen/cel'],\n },\n {\n why: \"declarations the editor and the host show, and the page: a field's and a parameter's label is no word the report prints; a parameter's default is the value the host may replace\",\n at: ['/page/**', '/styles/**', '/datasets/**', '/parameters/**', '/assets/**', '/aggregates/**', '/fonts/**', '/provenance/**'],\n },\n { why: \"a code a scanner reads: a QR code's content and an EPC QR code's texts\", at: ['qrCode:/content/**', 'epcQrCode:/**'] },\n {\n why: \"a QR-bill's account, parties, reference, billing information, amount, currency and the language of its headings, which are identifiers and names; its message is a word\",\n at: [\n '/paymentPart/language',\n '/paymentPart/currency',\n '/paymentPart/amount/cel',\n '/paymentPart/account/**',\n '/paymentPart/creditor/**',\n '/paymentPart/debtor/**',\n '/paymentPart/reference/**',\n '/paymentPart/billingInformation/**',\n ],\n },\n { why: \"an e-invoice's texts, which its XML alone holds\", at: ['/eInvoice/**'] },\n]\n","/**\n * A report written in one of its languages (0063): the locale a render\n * may name, and the report with its words and its word expressions\n * replaced by that language's.\n *\n * One function decides it, so that the validator, the core's diagnostics\n * and the runtime write a report in a language one way: every word place\n * of `translation.ts`'s walk whose word, or whose expression's source,\n * the language translates, replaced whole; `locale` the language's; the\n * QR-bill's headings in that language where SIX has them; and no\n * translations left, so that what reads the result reads a report in one\n * language, as every report was before.\n */\nimport { quote } from './check.js'\nimport type { ReportDefinition } from './definition.js'\nimport { QR_BILL_LANGUAGES } from './payment-part.js'\nimport { at } from './pointer.js'\nimport { isWord, wordPlaces } from './translation.js'\nimport type { Translation } from './translation.js'\n\n/** The locales `report` is written in: its own first, then each translation's, in the order declared. */\nexport function declaredLocales(report: ReportDefinition): readonly string[] {\n return [report.locale, ...(report.translations ?? []).map(({ locale }) => locale)]\n}\n\nexport type LocaleChoice = { readonly ok: true; readonly locale: string } | { readonly ok: false; readonly message: string }\n\n/**\n * The locale a render of `report` prints in: `requested` where the report\n * is written in it, the report's own where nothing is requested. A locale\n * the report does not declare is refused, never matched to a near one:\n * de-DE is not de-CH, and de is neither.\n */\nexport function renderLocale(report: ReportDefinition, requested?: string): LocaleChoice {\n if (requested === undefined) return { ok: true, locale: report.locale }\n const declared = declaredLocales(report)\n if (declared.includes(requested)) return { ok: true, locale: requested }\n return { ok: false, message: `${quote(requested)} is not a locale this report is written in; it is written in ${declared.join(', ')}` }\n}\n\n/** A string a translation replaces: where it stands, what prints there, and the translation's entry it comes from, as JSON Pointers. */\nexport interface Substitution {\n readonly path: string\n readonly text: string\n /** The entry's `text`, for a word, or its expression's `cel`, for an expression. */\n readonly entry: string\n}\n\n/** What the translation at `index` replaces in `report`: each word it translates, at every place it stands, then each word expression, each in document order. */\nexport function substitutions(report: ReportDefinition, index: number): readonly Substitution[] {\n const translation = report.translations?.[index] as Translation\n const base = at('/translations', index)\n const words = new Map(translation.words.map(({ word, text }, entry) => [word, { text, entry: `${base}/words/${entry}/text` }]))\n const expressions = new Map(\n translation.expressions.map(({ cel, expression }, entry) => [cel, { text: expression.cel, entry: `${base}/expressions/${entry}/expression/cel` }]),\n )\n const places = wordPlaces(report)\n return [\n // A translated word holds a letter, which the validator holds, so a literal with none finds no translation.\n ...places.literals.flatMap(({ path, text }) => {\n const found = words.get(text)\n return found === undefined ? [] : [{ path, ...found }]\n }),\n ...places.expressions.flatMap(({ path, cel }) => {\n const found = expressions.get(cel)\n return found === undefined ? [] : [{ path, ...found }]\n }),\n ]\n}\n\n/** `value` copied, each string at a path `replace` names replaced, and `translations` left out at the top. */\nfunction copied(value: unknown, path: string, replace: ReadonlyMap<string, string>): unknown {\n const replacement = replace.get(path)\n if (replacement !== undefined) return replacement\n if (Array.isArray(value)) return value.map((item, index) => copied(item, at(path, index), replace))\n if (typeof value !== 'object' || value === null) return value\n const entries = Object.entries(value).filter(([key]) => path !== '' || key !== 'translations')\n return Object.fromEntries(entries.map(([key, child]) => [key, copied(child, at(path, key), replace)]))\n}\n\n/** The QR-bill's language in a translation's locale: the locale's own where SIX has headings in it, the bill's otherwise. */\nfunction slipLanguage(locale: string): string | undefined {\n const language = locale.split('-')[0] as string\n return (QR_BILL_LANGUAGES as readonly string[]).includes(language) ? language : undefined\n}\n\n/**\n * `report` -- one the validator accepts -- written in `locale` as far as\n * its translations go: each word and each word expression the language\n * translates replaced, every other left in the report's own; what the\n * validator checks each language by, and what the core diagnoses it by.\n * In the report's own locale, the report without its translations.\n * `locale` is one `renderLocale` accepted; another is a caller's mistake,\n * and throws a RangeError.\n */\nexport function writtenIn(report: ReportDefinition, locale: string): ReportDefinition {\n const index = (report.translations ?? []).findIndex((translation) => translation.locale === locale)\n if (locale === report.locale) {\n const { translations: _translations, ...own } = report\n return own\n }\n if (index === -1) throw new RangeError(`${quote(locale)} is not a locale this report is written in`)\n const replace = new Map(substitutions(report, index).map(({ path, text }) => [path, text]))\n replace.set('/locale', locale)\n const language = report.paymentPart === undefined ? undefined : slipLanguage(locale)\n if (language !== undefined) replace.set('/paymentPart/language', language)\n return copied(report, '', replace) as ReportDefinition\n}\n\n/**\n * `report` -- one the validator accepts -- written in `locale`, whole:\n * what a render in that locale prints. A word the language does not\n * translate is never printed in another, so one missing throws a\n * RangeError, as an undeclared locale does: a caller asks `renderLocale`\n * first, and report-core's `languageDiagnostics`, which says each word\n * missing, and each expression that prints words, before anything is\n * written. Neither throw is reached from a check that was made.\n */\nexport function reportIn(report: ReportDefinition, locale: string): ReportDefinition {\n const written = writtenIn(report, locale)\n if (locale === report.locale) return written\n const translated = new Set(substitutions(report, declaredLocales(report).indexOf(locale) - 1).map(({ path }) => path))\n const missing = wordPlaces(report).literals.filter(({ path, text }) => isWord(text) && !translated.has(path))\n if (missing.length > 0)\n throw new RangeError(`${missing.length} of this report's words are not written in ${quote(locale)}, and are never printed in another language`)\n return written\n}\n","/**\n * A report's translations (0063): their shape and bounds, and then the\n * report written in each of its languages, held to the rules every\n * report is held to.\n *\n * A word that stands in several places is translated once, and the\n * translation must hold wherever it stands: a column header's bound, a\n * QR-bill message's characters, a Factur-X title's metadata. Rather than\n * a second copy of each place's rule, the report is written in each\n * language -- missing words left in its own, as `writtenIn` writes it --\n * and read again by the reader that read the report, and each error that\n * reading finds is the translation's: the report in its own language was\n * valid. It is reported at the translation's entry that broke it, the\n * message naming the place and the language.\n */\nimport { all, matches, quote, readList, shape, text } from './check.js'\nimport type { ReportDefinition } from './definition.js'\nimport { MAX_EXPRESSION_LENGTH, MAX_LANGUAGES, MAX_TEXT_LENGTH, MAX_WORDS } from './limits.js'\nimport { at } from './pointer.js'\nimport { substitutions, writtenIn } from './report-in.js'\nimport type { Substitution } from './report-in.js'\nimport { LOCALE } from './syntax.js'\nimport { isWord } from './translation.js'\nimport type { TranslatedExpression, TranslatedWord, Translation } from './translation.js'\nimport { newContext } from './validate-context.js'\nimport type { Ctx } from './validate-context.js'\nimport { readExpression } from './validate-inline.js'\n\n/** One entry of a translation that a language holds once: a word by its text, an expression by its source. */\nfunction once(c: Ctx, key: string | undefined, path: string, seen: Set<string>, what: string): void {\n if (key === undefined) return\n if (seen.has(key)) c.f.report(path, 'duplicate-word', `${what} ${quote(key)} is translated twice in this language; a word has one translation in each`)\n seen.add(key)\n}\n\nfunction readWord(c: Ctx, value: unknown, path: string, seen: Set<string>): TranslatedWord | undefined {\n const o = shape(c.f, value, path, ['word', 'text'])\n const word = text(c.f, o?.word, at(path, 'word'), MAX_TEXT_LENGTH)\n const translation = text(c.f, o?.text, at(path, 'text'), MAX_TEXT_LENGTH)\n if (word !== undefined && !isWord(word)) {\n c.f.report(at(path, 'word'), 'not-a-word', `${quote(word)} holds no letter, so it prints as written in every language and is never translated`)\n } else once(c, word, at(path, 'word'), seen, 'the word')\n if (translation !== undefined && translation.trim() === '') {\n c.f.report(at(path, 'text'), 'blank-translation', \"a translation prints in its word's place, and a blank one prints nothing there\")\n return undefined\n }\n return word === undefined || translation === undefined ? undefined : { word, text: translation }\n}\n\nfunction readTranslatedExpression(c: Ctx, value: unknown, path: string, seen: Set<string>): TranslatedExpression | undefined {\n const o = shape(c.f, value, path, ['cel', 'expression'])\n const where = at(path, 'cel')\n const cel = text(c.f, o?.cel, where, MAX_EXPRESSION_LENGTH)\n if (cel !== undefined && cel.trim() === '') c.f.report(where, 'empty-expression', 'an expression translated is one the report prints, and this one is empty')\n else once(c, cel, where, seen, 'the expression')\n const expression = readExpression(c.f, o?.expression, at(path, 'expression'))\n return cel === undefined || cel.trim() === '' || expression === undefined ? undefined : { cel, expression }\n}\n\nfunction readTranslation(c: Ctx, value: unknown, path: string, languages: Set<string>): Translation | undefined {\n const o = shape(c.f, value, path, ['locale', 'words', 'expressions'])\n const where = at(path, 'locale')\n const locale = matches(c.f, o?.locale, where, LOCALE, 'invalid-locale', 'a BCP 47 language tag such as en, de-CH or zh-Hans-CN')\n if (locale !== undefined && languages.has(locale)) {\n c.f.report(where, 'duplicate-language', `the report is written in ${quote(locale)} already: its own words, or another translation's`)\n }\n if (locale !== undefined) languages.add(locale)\n const words = new Set<string>()\n const wordList = readList(c.f, o?.words, at(path, 'words'), 0, MAX_WORDS)?.map((item, index) => readWord(c, item, at(at(path, 'words'), index), words))\n const sources = new Set<string>()\n const expressionList = readList(c.f, o?.expressions, at(path, 'expressions'), 0, MAX_WORDS)?.map((item, index) =>\n readTranslatedExpression(c, item, at(at(path, 'expressions'), index), sources),\n )\n const read = { words: wordList && all(wordList), expressions: expressionList && all(expressionList) }\n return locale === undefined || read.words === undefined || read.expressions === undefined\n ? undefined\n : { locale, words: read.words, expressions: read.expressions }\n}\n\n/**\n * The translations at `path`, one at least where they are present: each\n * language once, never the report's own (`own`, when it could be read),\n * and with it at most `MAX_LANGUAGES`. Absent, the report has none.\n */\nexport function readTranslations(c: Ctx, value: unknown, path: string, own: string | undefined): readonly Translation[] | undefined {\n const items = readList(c.f, value, path, 1, MAX_LANGUAGES - 1)\n const languages = new Set<string>(own === undefined ? [] : [own])\n const translations = items?.map((item, index) => readTranslation(c, item, at(path, index), languages))\n return translations && all(translations)\n}\n\n/**\n * The translation's entry an error the report written in a language finds\n * is reported at: the one whose string the error is at -- a column header\n * too long -- or else the first whose string it stands over -- a QR-bill's\n * message, judged whole, or the whole report. A translated string is a\n * leaf, so no error stands under one.\n */\nfunction entryOf(path: string, replaced: readonly Substitution[]): Substitution | undefined {\n return replaced.find((substitution) => substitution.path === path) ?? replaced.find((substitution) => substitution.path.startsWith(`${path}/`))\n}\n\n/** A reader of a report's top level, as validate.ts's: what each language is read again by. */\nexport type ReportReader = (c: Ctx, o: Record<string, unknown>) => ReportDefinition | undefined\n\n/**\n * `report` -- read without an error by `read` -- written in each of\n * `translations`, its own, and read again by `read`, each error reported\n * into `c` at the translation that broke it, naming the place and the\n * language. A written report differs from the report only at the strings\n * a translation replaced, its locale and its slip's language, so every\n * error stands at or over a replaced string; one that stands near none is\n * reported at the translation as a whole.\n */\nexport function checkLanguages(c: Ctx, report: ReportDefinition, translations: readonly Translation[], read: ReportReader): void {\n for (const [index, translation] of translations.entries()) {\n const replaced = substitutions(report, index)\n const again = newContext()\n read(again, writtenIn(report, translation.locale) as unknown as Record<string, unknown>)\n for (const error of again.f.errors()) {\n const place = error.path === '' ? 'the report as a whole' : error.path\n const said = `written in ${translation.locale}, where it stands at ${place}, ${error.message}`\n c.f.report(entryOf(error.path, replaced)?.entry ?? at('/translations', index), error.code, said)\n }\n }\n}\n","/**\n * Structural validation: whether a document is a report definition this\n * package reads, and every way in which it is not.\n *\n * This is the first of the four levels of plan 15 -- structure, with the\n * references a definition makes into its own declarations and the sizes its\n * own page allows. Whether a declared dataset exists in a deployment,\n * whether an expression compiles against the names `EXPRESSION_NAMES` binds,\n * and whether the rendered output fits are later levels, owned elsewhere.\n */\nimport { identifier, matches, optional, readObject, shape, strictKeys, text } from './check.js'\nimport type { Component } from './components.js'\nimport { OPTIONAL_REGIONS, REGION_NAMES } from './definition.js'\nimport type { RegionName, Regions, ReportDefinition } from './definition.js'\nimport type { ReportError } from './errors.js'\nimport { MAX_LABEL_LENGTH, MAX_REGION_COMPONENTS } from './limits.js'\nimport { at } from './pointer.js'\nimport { LOCALE } from './syntax.js'\nimport { readAggregates } from './validate-aggregates.js'\nimport { newContext } from './validate-context.js'\nimport type { Ctx } from './validate-context.js'\nimport { readComponents } from './validate-components.js'\nimport { readAssets, readDatasets, readPage, readParameters, readProvenance, readStyles } from './validate-declarations.js'\nimport { readEInvoice } from './validate-e-invoice.js'\nimport { checkMissingFaces, readFontMap } from './validate-font-map.js'\nimport { readPaymentPart } from './validate-payment-part.js'\nimport { checkLanguages, readTranslations } from './validate-translations.js'\nimport { checkSpecVersion, REPORT_SPEC_VERSION } from './version.js'\n\nexport type ReportValidation = { readonly valid: true; readonly report: ReportDefinition } | { readonly valid: false; readonly errors: readonly ReportError[] }\n\n/** The regions every report holds: every one but those it may leave out. */\nconst REQUIRED_REGIONS: readonly RegionName[] = REGION_NAMES.filter((region) => !(OPTIONAL_REGIONS as readonly RegionName[]).includes(region))\n\n/**\n * The regions, each read by its name in the order a reader meets them, so\n * that a component id taken twice is reported where the reader meets it\n * second. An optional region absent is left absent, and one present as an\n * empty list is kept: the two print different first pages (0060).\n */\nfunction readRegions(c: Ctx, value: unknown, path: string): Regions | undefined {\n const o = shape(c.f, value, path, REQUIRED_REGIONS, OPTIONAL_REGIONS)\n const read: Partial<Record<RegionName, readonly Component[]>> = {}\n for (const region of REGION_NAMES) {\n const where = at(path, region)\n const components = readComponents(c, o?.[region], where, {\n region,\n regionPath: where,\n depth: 0,\n layout: undefined,\n budget: { left: MAX_REGION_COMPONENTS },\n })\n if (components !== undefined) read[region] = components\n }\n const { reportHeader, firstPageHeader, pageHeader, body, pageFooter, summary } = read\n if (reportHeader === undefined || pageHeader === undefined || body === undefined || pageFooter === undefined || summary === undefined) return undefined\n if (o?.firstPageHeader !== undefined && firstPageHeader === undefined) return undefined\n return { reportHeader, ...optional('firstPageHeader', firstPageHeader), pageHeader, body, pageFooter, summary }\n}\n\n/** The report in `o`, a copy of the document's top level whose version has been checked. */\nfunction readReport(c: Ctx, o: Record<string, unknown>): ReportDefinition | undefined {\n strictKeys(\n c.f,\n o,\n '',\n ['reportSpecVersion', 'id', 'title', 'locale', 'page', 'styles', 'datasets', 'parameters', 'assets', 'aggregates', 'regions'],\n ['fonts', 'paymentPart', 'eInvoice', 'provenance', 'translations'],\n )\n const id = identifier(c.f, o.id, '/id')\n const title = text(c.f, o.title, '/title', MAX_LABEL_LENGTH)\n const locale = matches(c.f, o.locale, '/locale', LOCALE, 'invalid-locale', 'a BCP 47 language tag such as en, de-CH or zh-Hans-CN')\n // The page first, then the declarations: the regions and the payment\n // part are measured against the one and checked against the others, and\n // the e-invoice is held against all of them.\n const page = readPage(c, o.page, '/page')\n const styles = readStyles(c, o.styles, '/styles')\n const datasets = readDatasets(c, o.datasets, '/datasets')\n const parameters = readParameters(c, o.parameters, '/parameters')\n const assets = readAssets(c, o.assets, '/assets')\n const aggregates = readAggregates(c, o.aggregates, '/aggregates')\n // The font map after the assets it references and the styles it is read against, before the regions, which print in it.\n const fonts = readFontMap(c, o.fonts, '/fonts')\n checkMissingFaces(c, styles, fonts, '/styles')\n const regions = readRegions(c, o.regions, '/regions')\n const paymentPart = readPaymentPart(c, o.paymentPart, '/paymentPart', page)\n const eInvoice = readEInvoice(c, o.eInvoice, '/eInvoice', { title, regions, paymentPart })\n const provenance = readProvenance(c.f, o.provenance, '/provenance')\n // Last: a translation is of words the rest holds, and each language is the rest written again.\n const translations = readTranslations(c, o.translations, '/translations', locale)\n if (\n id === undefined ||\n title === undefined ||\n locale === undefined ||\n page === undefined ||\n styles === undefined ||\n datasets === undefined ||\n parameters === undefined ||\n assets === undefined ||\n aggregates === undefined ||\n regions === undefined ||\n (o.fonts !== undefined && fonts === undefined) ||\n (o.paymentPart !== undefined && paymentPart === undefined) ||\n (o.eInvoice !== undefined && eInvoice === undefined) ||\n (o.translations !== undefined && translations === undefined)\n ) {\n return undefined\n }\n const reportSpecVersion = REPORT_SPEC_VERSION\n return {\n reportSpecVersion,\n id,\n title,\n locale,\n page,\n styles,\n datasets,\n parameters,\n assets,\n aggregates,\n ...optional('fonts', fonts),\n regions,\n ...optional('paymentPart', paymentPart),\n ...optional('eInvoice', eInvoice),\n ...optional('provenance', provenance),\n ...optional('translations', translations),\n }\n}\n\n/**\n * Whether `document` is a valid report definition, and if not, every reason\n * why -- up to MAX_ERRORS of them, each with a JSON Pointer, a code, a\n * message for a person and the component it is inside.\n *\n * The version is checked first, with `checkSpecVersion`: a formancy form or\n * a later version's report is refused as what it is, with one error, rather\n * than with every way its shape differs.\n *\n * Never throws, whatever it is handed. Every object and array is read once,\n * through its property descriptors, into a copy; a getter is refused and\n * never run, and the report returned is built from what was checked and\n * shares no object with `document`. The work is bounded by the limits in\n * `limits.ts`: an array past its bound is refused before it is read. No\n * message and no path grows with what the document holds.\n */\nexport function validateReport(document: unknown): ReportValidation {\n const c = newContext()\n const top = readObject(c.f, document, '')\n const version = checkSpecVersion(top)\n if (!version.ok) {\n return {\n valid: false,\n errors: [{ path: version.code === 'unsupported-version' ? '/reportSpecVersion' : '', code: version.code, message: version.message }],\n }\n }\n // checkSpecVersion reads a version only from an object, so `top` is one.\n const report = readReport(c, top as Record<string, unknown>)\n // Each language only once the report in its own is whole: an error then is the translation's alone.\n if (report?.translations !== undefined && c.f.errors().length === 0) checkLanguages(c, report, report.translations, readReport)\n const errors = c.f.errors()\n return report !== undefined && errors.length === 0 ? { valid: true, report } : { valid: false, errors }\n}\n","/**\n * What validation can say is wrong with a report, as stable codes.\n *\n * A code is for a program -- the builder links it to a property editor, a\n * test asserts it -- and the message is for a person. Codes are never\n * reworded once released; a new rule gets a new code. Each has a refusal\n * test in `validate.test.ts`, which does not compile while one is missing.\n */\nexport const REPORT_ERROR_CODES = [\n // The document as a whole.\n /** Not a report definition at all; a formancy form is named as one. */\n 'not-a-report',\n /** A report of a version this package does not read. */\n 'unsupported-version',\n /** A value JSON cannot hold: undefined, NaN, a function, an accessor, an array hole, an object that throws when read. */\n 'not-json',\n /** More errors were found than are listed. */\n 'too-many-errors',\n\n // Shape: what a property must be.\n 'wrong-type',\n 'missing-property',\n /** A property this version does not know; shapes are strict. */\n 'unknown-property',\n /** A component, inline, format or value of a kind this version does not know. */\n 'unknown-kind',\n 'not-one-of',\n 'out-of-range',\n 'not-an-integer',\n /** A length finer than the hundredth of a point lengths are stored to. */\n 'too-precise',\n /** A string, or a property name, past its bound. */\n 'too-long',\n /** An array past its bound, a region past its component budget, or a table past `MAX_TABLES` (0062). */\n 'too-many',\n 'too-few',\n /** A CEL expression that is empty or only whitespace. */\n 'empty-expression',\n\n // Strings with a syntax.\n 'invalid-id',\n 'invalid-locale',\n 'invalid-color',\n 'invalid-currency',\n 'invalid-digest',\n /** A parameter default its own type would refuse. */\n 'invalid-default',\n /** Where a dataset is read from a formancy form: a data path or a repeater that is not field keys joined by dots, or an empty member (0042). */\n 'invalid-form-path',\n /** A string that should hold an exact decimal and does not. */\n 'invalid-decimal',\n /**\n * A text of a QR-bill that no data can change, which SIX's rules for the\n * QR-bill refuse: an account, a reference, a part of an address, the\n * message or the billing information; or an account, a reference and a\n * currency that do not go together.\n */\n 'invalid-qr-bill',\n /**\n * An EPC QR code the EPC's guidelines refuse where it is written: a\n * literal IBAN, BIC, name, reference, text, information or purpose that\n * breaks its rule; a BIC an IBAN does not go with, or none where one is\n * needed; a reference and a text together; literal texts that pass 331\n * bytes alone; or, with Austria's caption, a size in which no version\n * prints the modules the PSA allows.\n */\n 'invalid-epc-qr-code',\n /**\n * An e-invoice that EN 16931's rules, or this version's narrower ones,\n * refuse where it is written, each refusal naming the business term and\n * the rule: a literal text, code or rate that breaks its rule; a seller,\n * a buyer, a time of supply, a period or VAT categories that cannot make\n * a valid invoice; lines that are not what the table over the detail\n * dataset prints, or a lines' table that selects its rows (0062); a\n * QR-bill or an EPC QR code that asks to be paid\n * otherwise than the e-invoice says; or a title its PDF/A cannot hold.\n */\n 'invalid-e-invoice',\n /**\n * A chart that says what no reader could use: a series label, an empty\n * text or a label for the rows without a category that is blank; a\n * palette that names a colour twice, or that has fewer colours than a\n * bar or a line chart has series; a pie of more than one series, of a\n * function outside `PIE_FUNCTIONS`, or with an axis title; or a line\n * chart with value labels over more than one series.\n */\n 'invalid-chart',\n\n // Declarations.\n /** Margins that leave less than MIN_PRINTABLE_PT either way. */\n 'printable-area-too-small',\n 'scale-on-non-decimal',\n /** Two declarations with one id in one list: styles, fields, parameters, assets, aggregates, or the two datasets. */\n 'duplicate-id',\n /** An id the format gives a meaning of its own: an aggregate called `key`, which `group.key` reads as the value grouped by. */\n 'reserved-id',\n /**\n * A dataset read from a formancy form that is not read whole: a field of\n * one that says nowhere it is read, a field that says where in a dataset\n * read from none, or one dataset read from a form beside one that is not\n * (0042).\n */\n 'incomplete-form-binding',\n /** A dataset that reads what it is not from a form: the header rows, the detail one record, or a header beside a detail of one row per submission (0042). */\n 'misplaced-form-binding',\n /**\n * An override of a binding for one form version (0048) that says both a\n * path and nothing, or neither, or that prints nothing of a field that\n * may not be null.\n */\n 'invalid-form-override',\n\n // References to what the report declares.\n 'unknown-style',\n 'unknown-dataset',\n 'unknown-field',\n 'unknown-parameter',\n 'unknown-asset',\n 'unknown-aggregate',\n 'unknown-column',\n /** A font token mapped to an asset that is an image, not a font. */\n 'asset-not-a-font',\n /** An image that draws a font asset, which is not a picture. */\n 'asset-not-an-image',\n /** A print style that sets bold or italic in a mapped font family that has no bold, italic or bold-italic face; a face is never synthesised. */\n 'missing-face',\n\n // Placement and structure.\n /** A table, page break or keep-together block outside the body and the summary. */\n 'misplaced-flow-component',\n /** A table or page break inside a columns or keep-together block. */\n 'nested-flow-component',\n /** A page number or count outside the page header and footer, or anywhere in what a QR code, an EPC QR code, a QR-bill or an e-invoice encodes. */\n 'misplaced-page-counter',\n /** A detail field where there is no current row: outside the table's cells, or in a group header or footer when it is not the field grouped by. */\n 'misplaced-detail-field',\n /** A group's aggregate outside a group header or footer. */\n 'misplaced-group-aggregate',\n /** A table's aggregate, `over: 'table'`, outside a table's total rows and its group's header and footer (0062). */\n 'misplaced-table-aggregate',\n /** A run set below or above the line outside a text component's runs: in what a QR code, an EPC QR code, a QR-bill or an e-invoice encodes, or in a table's cell, footer cell or group header (0061). */\n 'misplaced-baseline',\n /**\n * A second table in a report that is an e-invoice, whose lines are every\n * row of its one table (0062). Before 0062, a second table in any report.\n */\n 'second-detail-table',\n 'nesting-too-deep',\n /** Two components with one id, anywhere in the report. */\n 'duplicate-component-id',\n /** Two columns with one id in one table. */\n 'duplicate-column-id',\n /** Two cells for one column in one footer row. */\n 'duplicate-footer-cell',\n /** A field sorted by twice, or sorted by and grouped by: the second key orders nothing. */\n 'duplicate-sort-key',\n /** A fixed size larger than the page's printable area: an image, a QR code, a rectangle, a spacer, or the fixed widths of a table or a columns block. */\n 'exceeds-printable-area',\n /** A payment part on a page it is not printed on: a QR-bill is printed across the foot of an A4 page in portrait, below the top margin. */\n 'payment-part-page',\n\n // Types meeting.\n /** An aggregate over a field of a type it cannot take. */\n 'aggregate-type-mismatch',\n /** A number, currency or date format over a value of a type it does not format. */\n 'format-type-mismatch',\n /** A field or parameter bound where its type does not fit: an image field printed, sorted or grouped by; a field that is not an image drawn as one; a currency that is not a string; a choice of a form read into a field that is not a string (0042). */\n 'binding-type-mismatch',\n\n // Translations (0063).\n /** A translation in a language the report is written in already: its own, or one translated before. */\n 'duplicate-language',\n /** A word a translation translates that holds no letter: a separator, a number or a sign prints as written in every language. */\n 'not-a-word',\n /** A word, or an expression that prints words, translated twice in one language. */\n 'duplicate-word',\n /** A translation that is empty or only whitespace: a word a language left out would print nothing in its place. */\n 'blank-translation',\n] as const\n\nexport type ReportErrorCode = (typeof REPORT_ERROR_CODES)[number]\n\nexport interface ReportError {\n /** A JSON Pointer (RFC 6901) to what is wrong; '' is the whole document. */\n readonly path: string\n readonly code: ReportErrorCode\n readonly message: string\n /** The innermost component the error is inside, when it is inside one whose id could be read. */\n readonly componentId?: string\n}\n\n/** Errors as one line of text, for an exception that has to carry them: each its code, path and message. */\nexport function describeErrors(errors: readonly ReportError[]): string {\n return errors.map((error) => `${error.code} ${error.path}: ${error.message}`).join('; ')\n}\n","/**\n * An approved asset's digest, taken where a person adds an image (0033).\n *\n * A report pins an asset by its id and the SHA-256 of its bytes (0007),\n * written as `DIGEST` (`syntax.ts`) says: `sha256:` and 64 lower-case hex\n * digits. The syntax and its computation stand in one package, so that the\n * editor that names an image and the validator that reads the name cannot\n * disagree about what one looks like.\n *\n * The hash is @noble/hashes' SHA-256, which `@formancy/spec` already uses\n * for a form's hash, for the reason it gives: Web Crypto's is asynchronous,\n * is there only in a secure context, and is no part of ES2023's library,\n * and this is a pure function a builder calls in the middle of an add. It\n * runs on the caller's thread.\n */\nimport { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex } from '@noble/hashes/utils.js'\n\n/** `sha256:` and the lower-case hex SHA-256 of exactly `bytes`; @noble/hashes' TypeError for anything that is not a Uint8Array. */\nexport function assetDigest(bytes: Uint8Array): string {\n return `sha256:${bytesToHex(sha256(bytes))}`\n}\n","/**\n * What a PNG's or a JPEG's bytes say of the picture they hold, read once\n * for every reader: a builder, where a person adds an image, and the\n * renderer, where it prints (0033). A picture the renderer would refuse at\n * every print is refused when it is added, in the same words, so that a\n * host never keeps bytes no report could print.\n *\n * What is read: for a PNG, every chunk's length and CRC, the header, a\n * palette where the header needs one, the image data's chunks, the end\n * chunk and nothing after it; for a JPEG, the segment structure up to the\n * scan, one frame header, read where PDFKit reads it, its size and its\n * component count, the first Exif block's orientation, and the end\n * marker. What is not: whether a PNG's image data inflates to exactly the\n * scanlines its header promises, which needs a decompressor ES2023 does not\n * have and the renderer checks at print; and a JPEG's entropy-coded scan,\n * which nothing decodes, so a corrupt scan inside an otherwise well-formed\n * JPEG still reaches the PDF.\n *\n * The size returned is the size the picture is shown at: a JPEG whose Exif\n * orientation turns it a quarter turn is as wide as its frame is tall, as\n * PDFKit draws it. Every read is bounded by the bytes' length, and nothing\n * here throws for what the bytes hold.\n */\nimport type { AssetMediaType } from './assets.js'\nimport { MAX_ASSET_SIDE } from './limits.js'\n\n/** A PNG's header, as the renderer needs it to check the image data: its scanlines follow from the size, the bits a pixel and the interlace. */\nexport interface PngHeader {\n readonly ok: true\n readonly mediaType: 'image/png'\n readonly width: number\n readonly height: number\n readonly bitsPerPixel: number\n /** Adam7, the one interlace method PNG defines. */\n readonly interlaced: boolean\n /** The image data, every IDAT chunk's joined in order: compressed, and not inflated here. */\n readonly data: Uint8Array<ArrayBuffer>\n}\n\n/** A JPEG's frame, as it is shown. */\nexport interface JpegHeader {\n readonly ok: true\n readonly mediaType: 'image/jpeg'\n readonly width: number\n readonly height: number\n /** Grey, RGB or CMYK, as PDFKit draws a JPEG of one, three or four components (pdfkit.js 3808-3812). */\n readonly components: 1 | 3 | 4\n /**\n * How its first Exif block turns or mirrors it, 2 to 8, as PDFKit reads\n * the tag and draws it; absent where the picture is upright -- the block\n * says 1, says nothing, or is not there. `width` and `height` are\n * already the turned picture's. A writer that embeds the bytes as they\n * are and cannot say what its reader does with the tag refuses one that\n * has it (0068).\n */\n readonly orientation?: 2 | 3 | 4 | 5 | 6 | 7 | 8\n}\n\nexport type RasterHeader = PngHeader | JpegHeader\n\n/** Why a PNG's or a JPEG's bytes are refused, each the first thing found wrong with them. */\nexport const IMAGE_REFUSAL_CODES = [\n /** Neither a PNG's signature nor a JPEG's start of image. */\n 'not-raster',\n /** A PNG or a JPEG whose structure is broken, or that PDFKit would read otherwise than this does. */\n 'malformed',\n /** No pixels: a width or a height of 0. */\n 'no-pixels',\n /** Wider or taller than `MAX_ASSET_SIDE` pixels. */\n 'too-large',\n] as const\nexport type ImageRefusalCode = (typeof IMAGE_REFUSAL_CODES)[number]\n\n/** A refusal, said in English after the image's name -- the renderer says `the image asset logo ${message}` -- and, for one of its size, the size, for a person's own language. */\nexport type ImageRefusal =\n | { readonly ok: false; readonly code: 'not-raster' | 'malformed'; readonly message: string }\n | { readonly ok: false; readonly code: 'no-pixels' | 'too-large'; readonly message: string; readonly width: number; readonly height: number }\n\nconst PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] as const\n\n/** A UTF-8 file's byte order mark; and UTF-16's, either way round, and big-endian UTF-32's, little-endian UTF-32's starting as UTF-16's does: the SVG cleaner refuses each as `encoding`. */\nconst UTF8_MARK = [0xef, 0xbb, 0xbf] as const\nconst WIDE_MARKS = [\n [0xfe, 0xff],\n [0xff, 0xfe],\n [0, 0, 0xfe, 0xff],\n] as const\n\n/** XML's white space: space, tab, carriage return, line feed. */\nconst XML_SPACE = new Set([0x20, 0x09, 0x0d, 0x0a])\n\n/**\n * What an image's bytes are, from their first bytes alone, never a file's\n * name or a type a browser guessed: a PNG by its signature, a JPEG by its\n * start of image, and an SVG to be cleaned by `<` after an optional UTF-8\n * byte order mark and white space, or by a UTF-16 or UTF-32 byte order\n * mark, so that a person who saved one so is told to save it as UTF-8.\n * Undefined for anything else. A sniff is no check: the bytes are read\n * whole by `imageHeader` or by `cleanSvg` next.\n */\nexport function sniffImage(bytes: Uint8Array): AssetMediaType | undefined {\n if (startsWith(bytes, PNG_SIGNATURE)) return 'image/png'\n if (bytes[0] === 0xff && bytes[1] === 0xd8) return 'image/jpeg'\n if (WIDE_MARKS.some((mark) => startsWith(bytes, mark))) return 'image/svg+xml'\n let at = startsWith(bytes, UTF8_MARK) ? UTF8_MARK.length : 0\n while (at < bytes.length && XML_SPACE.has(bytes[at]!)) at++\n return bytes[at] === 0x3c ? 'image/svg+xml' : undefined\n}\n\n/** A PNG's or a JPEG's header, read as the renderer reads it, or the first thing wrong with it. */\nexport function imageHeader(bytes: Uint8Array): RasterHeader | ImageRefusal {\n const sniffed = sniffImage(bytes)\n if (sniffed === 'image/png') return readPng(bytes)\n if (sniffed === 'image/jpeg') return readJpeg(bytes)\n return { ok: false, code: 'not-raster', message: 'is neither a PNG nor a JPEG' }\n}\n\nfunction malformed(message: string): ImageRefusal {\n return { ok: false, code: 'malformed', message }\n}\n\nfunction sizeRefusal(width: number, height: number): ImageRefusal | undefined {\n if (width === 0 || height === 0) return { ok: false, code: 'no-pixels', message: `has no pixels (${width} × ${height})`, width, height }\n if (width > MAX_ASSET_SIDE || height > MAX_ASSET_SIDE)\n return { ok: false, code: 'too-large', message: `is ${width} × ${height} pixels; the limit is ${MAX_ASSET_SIDE} pixels a side`, width, height }\n return undefined\n}\n\n/** CRC-32 as PNG and zlib compute it: the reflected polynomial 0xedb88320, every bit inverted before and after. */\nconst CRC_TABLE: readonly number[] = Array.from({ length: 256 }, (_, byte) => {\n let crc = byte\n for (let bit = 0; bit < 8; bit++) crc = crc & 1 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1\n return crc >>> 0\n})\n\n/** The CRC of `bytes` from `start` up to `end`, all of them when neither is given. */\nexport function crc32(bytes: Uint8Array, start = 0, end = bytes.length): number {\n let crc = 0xffffffff\n for (let at = start; at < end; at++) crc = CRC_TABLE[(crc ^ bytes[at]!) & 0xff]! ^ (crc >>> 8)\n return (crc ^ 0xffffffff) >>> 0\n}\n\n/** Channels per pixel for each PNG colour type, and the bit depths it allows. */\nconst PNG_COLOUR_TYPES: ReadonlyMap<number, { channels: number; depths: readonly number[] }> = new Map([\n [0, { channels: 1, depths: [1, 2, 4, 8, 16] }],\n [2, { channels: 3, depths: [8, 16] }],\n [3, { channels: 1, depths: [1, 2, 4, 8] }],\n [4, { channels: 2, depths: [8, 16] }],\n [6, { channels: 4, depths: [8, 16] }],\n])\n\n/** A PNG's header chunk, read. */\ninterface Ihdr {\n readonly width: number\n readonly height: number\n readonly bitsPerPixel: number\n readonly interlaced: boolean\n readonly paletted: boolean\n}\n\n/** The chunk types read, as the four bytes of each read as one big-endian number. */\nconst IHDR = 0x49484452\nconst PLTE = 0x504c5445\nconst IDAT = 0x49444154\nconst IEND = 0x49454e44\n\n/**\n * A PNG's chunks walked once, each CRC checked, and nothing kept of a chunk\n * but what the header chunk says and how long the image data is: a file a\n * person chose may hold over a million chunks in its 20 MiB.\n */\nfunction readPng(bytes: Uint8Array): PngHeader | ImageRefusal {\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n let header: Ihdr | undefined\n let palette = false\n let chunks = 0\n let length = 0\n for (let offset: number = PNG_SIGNATURE.length; ;) {\n // A chunk is its length, its type, its data and its CRC: 12 bytes and the data.\n if (offset + 12 > bytes.length || offset + 12 + view.getUint32(offset) > bytes.length) return malformed(`is cut off at byte ${offset}`)\n const size = view.getUint32(offset)\n const end = offset + 12 + size\n const type = view.getUint32(offset + 4)\n if (crc32(bytes, offset + 4, offset + 8 + size) !== view.getUint32(offset + 8 + size))\n return malformed(`has the wrong CRC on its ${String.fromCharCode(...bytes.subarray(offset + 4, offset + 8))} chunk`)\n if (header === undefined) {\n if (type !== IHDR) return malformed('does not start with its header chunk')\n const parsed = pngHeader(bytes.subarray(offset + 8, offset + 8 + size))\n if ('ok' in parsed) return parsed\n header = parsed\n } else if (type === PLTE) {\n palette = true\n } else if (type === IDAT) {\n chunks += 1\n length += size\n } else if (type === IEND) {\n if (end !== bytes.length) return malformed('has bytes after its end chunk')\n break\n }\n offset = end\n }\n if (header.paletted && !palette) return malformed('is paletted and has no palette')\n if (chunks === 0) return malformed('has no image data')\n const { width, height, bitsPerPixel, interlaced } = header\n return { ok: true, mediaType: 'image/png', width, height, bitsPerPixel, interlaced, data: imageData(bytes, view, length) }\n}\n\n/** The `length` bytes of a PNG's image data, every IDAT chunk's copied in order into one array, of a PNG whose chunks `readPng` has walked. */\nfunction imageData(bytes: Uint8Array, view: DataView, length: number): Uint8Array<ArrayBuffer> {\n const data = new Uint8Array(length)\n for (let offset: number = PNG_SIGNATURE.length, at = 0; at < length;) {\n const size = view.getUint32(offset)\n if (view.getUint32(offset + 4) === IDAT && size > 0) {\n data.set(bytes.subarray(offset + 8, offset + 8 + size), at)\n at += size\n }\n offset += 12 + size\n }\n return data\n}\n\nfunction pngHeader(body: Uint8Array): Ihdr | ImageRefusal {\n if (body.length !== 13) return malformed('has a header chunk of the wrong length')\n const view = new DataView(body.buffer, body.byteOffset, body.byteLength)\n const width = view.getUint32(0)\n const height = view.getUint32(4)\n const size = sizeRefusal(width, height)\n if (size !== undefined) return size\n const [depth = 0, colourType = 0, compression, filter, interlace = 0] = body.subarray(8)\n const colour = PNG_COLOUR_TYPES.get(colourType)\n if (colour === undefined || !colour.depths.includes(depth)) return malformed(`has an invalid colour type and bit depth (${colourType}, ${depth})`)\n if (compression !== 0 || filter !== 0 || interlace > 1) return malformed('has an unknown compression, filter or interlace method')\n return { width, height, bitsPerPixel: colour.channels * depth, interlaced: interlace === 1, paletted: colourType === 3 }\n}\n\n/** Start-of-frame markers: every SOFn, which are C0 to CF but DHT (C4), JPG (C8) and DAC (CC). */\nconst JPEG_FRAMES = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf])\n\n/**\n * The two markers PDFKit takes for a frame header besides the SOFn: it\n * reads the first segment of any of the three as the frame (pdfkit.js 3807,\n * 3822-3843), so one of these before the frame would be read in its place.\n */\nconst READ_AS_FRAMES: ReadonlyMap<number, string> = new Map([\n [0xc8, 'JPG'],\n [0xcc, 'DAC'],\n])\n\n/** The component counts PDFKit gives a colour space: grey, RGB and CMYK (pdfkit.js 3808-3812). */\nconst JPEG_COMPONENTS: ReadonlySet<number> = new Set([1, 3, 4])\n\n/** APP1, where an Exif block lives. */\nconst APP1 = 0xe1\n\n/**\n * The segments before the scan, each a marker and a length, as a baseline or\n * progressive encoder writes them. Fill bytes between segments, which the\n * standard allows and encoders do not write, are refused with the rest of\n * what is malformed: failing closed costs a JPEG that could have been drawn.\n * So does a JPEG PDFKit would read otherwise than this does -- a JPG or DAC\n * segment before the frame header, which it reads as the frame, a second\n * frame header, or a component count it gives no colour space -- since the\n * size and the colour this reads are what the page and an e-invoice's\n * PDF/A rest on: arithmetic coding, which writes a DAC segment, may write\n * it before the frame header, and such a JPEG is refused.\n */\nfunction readJpeg(bytes: Uint8Array): JpegHeader | ImageRefusal {\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n let frame: JpegHeader | undefined\n let orientation: number | undefined\n for (let offset = 2; offset + 4 <= bytes.length;) {\n const marker = bytes[offset + 1]!\n if (bytes[offset] !== 0xff || marker === 0xff) return malformed(`has a malformed segment at byte ${offset}`)\n const length = view.getUint16(offset + 2)\n if (length < 2 || offset + 2 + length > bytes.length) return malformed(`has a segment that runs past its end at byte ${offset}`)\n const readAs = READ_AS_FRAMES.get(marker)\n if (frame === undefined && readAs !== undefined)\n return malformed(`has a ${readAs} segment (FF${marker.toString(16).toUpperCase()}) before its frame header, which PDFKit would read as the frame header`)\n if (JPEG_FRAMES.has(marker)) {\n if (frame !== undefined) return malformed('has two frame headers')\n if (length < 8) return malformed('has a frame header of the wrong length')\n const [width, height] = [view.getUint16(offset + 7), view.getUint16(offset + 5)]\n const size = sizeRefusal(width, height)\n if (size !== undefined) return size\n // The component count follows the size.\n const components = bytes[offset + 9]!\n if (!JPEG_COMPONENTS.has(components)) return malformed(`has a frame header of ${components} components, where PDFKit draws 1, 3 or 4`)\n frame = { ok: true, mediaType: 'image/jpeg', width, height, components: components as JpegHeader['components'] }\n }\n if (marker === APP1 && orientation === undefined && startsWith(bytes.subarray(offset + 4), EXIF))\n orientation = exifOrientation(bytes.subarray(offset + 4 + EXIF.length, offset + 2 + length))\n if (marker === 0xda) {\n if (frame === undefined) return malformed('has image data before its frame header')\n if (bytes[bytes.length - 2] !== 0xff || bytes[bytes.length - 1] !== 0xd9) return malformed('is cut off: it does not end with an end-of-image marker')\n // Upright, or no orientation read: the frame as it is, and nothing said of a turn.\n if (orientation === undefined || orientation < 2) return frame\n const turned = orientation as NonNullable<JpegHeader['orientation']>\n // Orientations 5 to 8 turn the image a quarter turn, as PDFKit draws it.\n return turned > 4 ? { ...frame, width: frame.height, height: frame.width, orientation: turned } : { ...frame, orientation: turned }\n }\n offset += 2 + length\n }\n return malformed('is cut off before its image data')\n}\n\n/** What an APP1 segment that holds Exif data starts with. */\nconst EXIF = [0x45, 0x78, 0x69, 0x66, 0, 0] as const\n\n/**\n * The orientation the first Exif block gives its image, read as PDFKit reads\n * it: the Orientation tag (0x0112) of the first image file directory, from 1\n * to 8. Anything else -- a block cut short, no such tag, a value out of\n * range -- is no orientation, which PDFKit draws as 1, upright. Only the\n * first Exif block counts, for PDFKit and here, so `0` stands for one read\n * without an orientation.\n */\nfunction exifOrientation(block: Uint8Array): number {\n if (block.length < 8) return 0\n const tiff = new DataView(block.buffer, block.byteOffset, block.byteLength)\n const order = tiff.getUint16(0)\n if (order !== 0x4949 && order !== 0x4d4d) return 0\n const little = order === 0x4949\n if (tiff.getUint16(2, little) !== 42) return 0\n const directory = tiff.getUint32(4, little)\n if (directory + 2 > tiff.byteLength) return 0\n const entries = tiff.getUint16(directory, little)\n for (let index = 0; index < entries; index++) {\n const entry = directory + 2 + index * 12\n if (entry + 12 > tiff.byteLength) return 0\n if (tiff.getUint16(entry, little) === 0x0112) {\n const value = tiff.getUint16(entry + 8, little)\n return value >= 1 && value <= 8 ? value : 0\n }\n }\n return 0\n}\n\nfunction startsWith(bytes: Uint8Array, prefix: readonly number[]): boolean {\n return prefix.every((byte, index) => bytes[index] === byte)\n}\n","/**\n * What an approved SVG may hold, as tables: the elements kept and the\n * geometry each is written with, the properties kept and the order they are\n * written in, and what is removed or refused instead (0030).\n *\n * Tables, not switches, so that the tests derive what they check from them:\n * the differential test reads every cleaned drawing back with another\n * parser and finds each element and attribute here, never by searching the\n * output for a phrase. Anything a table does not name is refused, named:\n * an SVG is untrusted input, and a construct this file has not decided\n * about fails closed (formancy.ai 0022).\n *\n * The lists are svg-to-pdfkit's subset, the converter pdfmake 0.3.11\n * vendors, cut down to what it draws as a browser draws it. Where the two\n * disagree -- text in a font pdfmake picks, a filter drawn as nothing -- the\n * construct is refused rather than drawn otherwise than its author saw it.\n * Every `source.js:N` cited in the SVG reader's files is a line of pdfmake\n * 0.3.11's `src/3rd-party/svg-to-pdfkit/source.js`; Node runs a transpiled\n * copy of it under `js/`, and the browser build bundles it.\n */\n\n/** The elements a cleaned drawing is written with. */\nexport const KEPT_ELEMENTS = [\n 'svg',\n 'g',\n 'defs',\n 'path',\n 'rect',\n 'circle',\n 'ellipse',\n 'line',\n 'polyline',\n 'polygon',\n 'linearGradient',\n 'radialGradient',\n 'stop',\n 'clipPath',\n] as const\nexport type KeptElement = (typeof KEPT_ELEMENTS)[number]\n\nconst KEPT_SET: ReadonlySet<string> = new Set(KEPT_ELEMENTS)\n\nexport function isKept(name: string): name is KeptElement {\n return KEPT_SET.has(name)\n}\n\nexport const SHAPES: ReadonlySet<KeptElement> = new Set(['path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon'])\nexport const GRADIENTS: ReadonlySet<KeptElement> = new Set(['linearGradient', 'radialGradient'])\n\n/**\n * Each kept element's geometry, in the order it is written. The root's\n * viewBox is the drawing's own coordinates; every other root attribute is\n * the report's to decide (its box, its fit) and is removed.\n */\nexport const GEOMETRY: { readonly [E in KeptElement]: readonly string[] } = {\n svg: ['viewBox'],\n g: [],\n defs: [],\n path: ['d'],\n rect: ['x', 'y', 'width', 'height', 'rx', 'ry'],\n circle: ['cx', 'cy', 'r'],\n ellipse: ['cx', 'cy', 'rx', 'ry'],\n line: ['x1', 'y1', 'x2', 'y2'],\n polyline: ['points'],\n polygon: ['points'],\n linearGradient: ['x1', 'y1', 'x2', 'y2', 'gradientUnits', 'gradientTransform', 'spreadMethod'],\n radialGradient: ['cx', 'cy', 'r', 'fx', 'fy', 'gradientUnits', 'gradientTransform', 'spreadMethod'],\n stop: ['offset'],\n clipPath: ['clipPathUnits'],\n}\n\n/** The elements that may carry a `transform`, written after the geometry. A gradient's is its gradientTransform. */\nexport const TRANSFORMED: ReadonlySet<KeptElement> = new Set(['g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'clipPath'])\n\nconst CONTAINER_CHILDREN: ReadonlySet<KeptElement> = new Set([\n 'g',\n 'defs',\n 'path',\n 'rect',\n 'circle',\n 'ellipse',\n 'line',\n 'polyline',\n 'polygon',\n 'linearGradient',\n 'radialGradient',\n 'clipPath',\n])\nconst NOTHING: ReadonlySet<KeptElement> = new Set()\n\n/**\n * What each kept element may hold. A clip path holds shapes alone, as SVG\n * says, and a gradient its stops alone; a shape holds nothing that draws.\n * svg-to-pdfkit would draw a group inside a clip path, which a browser\n * ignores, so the table, not the converter, decides.\n */\nexport const CHILDREN: { readonly [E in KeptElement]: ReadonlySet<KeptElement> } = {\n svg: CONTAINER_CHILDREN,\n g: CONTAINER_CHILDREN,\n defs: CONTAINER_CHILDREN,\n path: NOTHING,\n rect: NOTHING,\n circle: NOTHING,\n ellipse: NOTHING,\n line: NOTHING,\n polyline: NOTHING,\n polygon: NOTHING,\n linearGradient: new Set(['stop']),\n radialGradient: new Set(['stop']),\n stop: NOTHING,\n clipPath: SHAPES,\n}\n\n/**\n * Removed with everything inside them, and listed: what describes, scripts\n * or animates a drawing and never draws. The drawing printed is the one\n * before any animation starts, which is what a still page shows.\n */\nexport const REMOVED_ELEMENTS: ReadonlySet<string> = new Set([\n 'title',\n 'desc',\n 'metadata',\n 'script',\n 'animate',\n 'animateMotion',\n 'animateTransform',\n 'animateColor',\n 'set',\n 'mpath',\n 'discard',\n 'cursor',\n 'view',\n])\n\nexport interface RefusedElement {\n readonly code: 'text' | 'raster' | 'reference' | 'unsupported'\n readonly advice: string\n}\n\n/** Refused, with the code and what to do about it. Any SVG element neither kept, removed nor listed here is refused too, named. */\nexport const REFUSED_ELEMENTS: ReadonlyMap<string, RefusedElement> = new Map<string, RefusedElement>([\n ...['text', 'tspan', 'textPath', 'tref', 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'glyphRef'].map((name): [string, RefusedElement] => [\n name,\n { code: 'text', advice: 'convert the text to outlines' },\n ]),\n ['image', { code: 'raster', advice: 'add the picture as a PNG or JPEG asset of its own' }],\n ['use', { code: 'reference', advice: 'a program wrote shapes as references; save it again through a program that expands them' }],\n ['symbol', { code: 'reference', advice: 'a program wrote shapes as references; save it again through a program that expands them' }],\n ['switch', { code: 'unsupported', advice: \"save it without Illustrator's editing capabilities\" }],\n ['foreignObject', { code: 'unsupported', advice: \"save it without Illustrator's editing capabilities\" }],\n ['filter', { code: 'unsupported', advice: 'expand the appearance' }],\n ['mask', { code: 'unsupported', advice: 'flatten the transparency' }],\n ['pattern', { code: 'unsupported', advice: 'expand the pattern into shapes' }],\n ['marker', { code: 'unsupported', advice: 'expand the stroke' }],\n])\n\n/** The root's attributes the report decides instead: its box gives the size, its fit the proportions and the clipping. Removed and listed. */\nexport const ROOT_REMOVED: ReadonlySet<string> = new Set([\n 'width',\n 'height',\n 'x',\n 'y',\n 'version',\n 'baseProfile',\n 'preserveAspectRatio',\n 'zoomAndPan',\n 'contentScriptType',\n 'contentStyleType',\n])\n\n/** Removed from any kept element and listed: what a person, a screen reader or a script reads, never the page. */\nconst REMOVED_ATTRIBUTES: ReadonlySet<string> = new Set(['role', 'tabindex', 'focusable', 'lang'])\n\nexport function isRemovedAttribute(name: string): boolean {\n return REMOVED_ATTRIBUTES.has(name) || name.startsWith('data-') || name.startsWith('aria-') || /^on[a-z]+$/.test(name)\n}\n\n/** A link's own attributes, removed with the link when an `a` is read as the group it draws as. */\nexport const LINK_ATTRIBUTES: ReadonlySet<string> = new Set(['href', 'target', 'download', 'rel', 'hreflang', 'type', 'ping', 'referrerpolicy'])\n\n/**\n * Refused: a browser may hide the element by them, even outside a `switch`\n * (SVG 1.1, 5.8), so removing them would print what the approver never saw.\n */\nexport const CONDITIONAL_ATTRIBUTES: ReadonlySet<string> = new Set([\n 'requiredFeatures',\n 'requiredExtensions',\n 'systemLanguage',\n 'requiredFonts',\n 'requiredFormats',\n])\n\n/** The properties written, in the order they are written: the canonical order. */\nexport const WRITTEN_PROPERTIES = [\n 'fill',\n 'fill-opacity',\n 'fill-rule',\n 'stroke',\n 'stroke-opacity',\n 'stroke-width',\n 'stroke-linecap',\n 'stroke-linejoin',\n 'stroke-miterlimit',\n 'stroke-dasharray',\n 'stroke-dashoffset',\n 'opacity',\n 'clip-path',\n 'clip-rule',\n 'stop-color',\n 'stop-opacity',\n] as const\nexport type WrittenProperty = (typeof WRITTEN_PROPERTIES)[number]\n\n/** What a stop draws with: its colour and its opacity. */\nconst STOP_PAINT: ReadonlySet<WrittenProperty> = new Set(['stop-color', 'stop-opacity'])\n\n/** What a group or a shape draws with, or passes on to what it holds: every written property but a stop's. */\nconst PAINT: ReadonlySet<WrittenProperty> = new Set(WRITTEN_PROPERTIES.filter((property) => !STOP_PAINT.has(property)))\n\nconst NO_PROPERTY: ReadonlySet<WrittenProperty> = new Set()\n\n/**\n * The properties a cleaned drawing writes on each element: what draws there,\n * in a browser and in the converter alike. Anything else is removed from the\n * element and listed, a reference among them, which nothing would follow.\n *\n * - The root holds its namespace and its viewBox alone; its paint is moved\n * onto a group inside it (0030).\n * - A gradient element draws nothing itself, and its stops take nothing\n * from it, in a browser or in the converter.\n * - A clip path's shapes are painted as its clip, in no colour, so of what\n * it could pass on only `clip-rule` matters. They inherit it from what\n * holds the clip path, in a browser and in the converter, which reads a\n * clip path's parents from the document (`source.js:1208`); the cleaner\n * writes the rule a clip path inherits on the clip path itself, so that\n * the clip it makes never rests on `defs`, and what `defs` holds draws\n * nowhere.\n */\nexport const WRITTEN_ON: { readonly [E in KeptElement]: ReadonlySet<WrittenProperty> } = {\n svg: NO_PROPERTY,\n g: PAINT,\n defs: NO_PROPERTY,\n path: PAINT,\n rect: PAINT,\n circle: PAINT,\n ellipse: PAINT,\n line: PAINT,\n polyline: PAINT,\n polygon: PAINT,\n linearGradient: NO_PROPERTY,\n radialGradient: NO_PROPERTY,\n stop: STOP_PAINT,\n clipPath: new Set(['clip-rule']),\n}\n\n/**\n * Read and never written: `display: none` removes the element, `color` is\n * resolved into every `currentColor`, and `visibility` and `vector-effect`\n * are accepted only with the value that draws as though they were absent.\n */\nexport const READ_PROPERTIES = ['display', 'visibility', 'color', 'vector-effect'] as const\nexport type Property = WrittenProperty | (typeof READ_PROPERTIES)[number]\n\nconst PROPERTY_SET: ReadonlySet<string> = new Set([...WRITTEN_PROPERTIES, ...READ_PROPERTIES])\n\nfunction isProperty(name: string): name is Property {\n return PROPERTY_SET.has(name)\n}\n\n/** The kept properties a child takes from its parent when it sets none of its own (SVG 1.1's property index). */\nexport const INHERITED: ReadonlySet<Property> = new Set([\n 'fill',\n 'fill-opacity',\n 'fill-rule',\n 'stroke',\n 'stroke-opacity',\n 'stroke-width',\n 'stroke-linecap',\n 'stroke-linejoin',\n 'stroke-miterlimit',\n 'stroke-dasharray',\n 'stroke-dashoffset',\n 'clip-rule',\n 'color',\n 'visibility',\n])\n\n/**\n * Removed wherever they are written, as an attribute, in `style` or in a\n * stylesheet, and listed: rendering hints a PDF has no use for, the\n * properties of text (refused, so they apply to nothing), and properties\n * nothing kept reads.\n */\nconst REMOVED_PROPERTIES: ReadonlySet<string> = new Set([\n 'shape-rendering',\n 'color-rendering',\n 'color-interpolation',\n 'color-interpolation-filters',\n 'image-rendering',\n 'text-rendering',\n 'buffered-rendering',\n 'color-profile',\n 'enable-background',\n 'isolation',\n 'overflow',\n 'pointer-events',\n 'cursor',\n 'solid-color',\n 'solid-opacity',\n 'flood-color',\n 'flood-opacity',\n 'lighting-color',\n 'font',\n 'font-family',\n 'font-size',\n 'font-size-adjust',\n 'font-stretch',\n 'font-style',\n 'font-variant',\n 'font-variant-caps',\n 'font-variant-east-asian',\n 'font-variant-ligatures',\n 'font-variant-numeric',\n 'font-variant-position',\n 'font-variant-alternates',\n 'font-weight',\n 'font-feature-settings',\n 'font-variation-settings',\n 'font-kerning',\n 'font-optical-sizing',\n 'font-synthesis',\n 'letter-spacing',\n 'word-spacing',\n 'text-anchor',\n 'text-align',\n 'text-align-last',\n 'text-decoration',\n 'text-decoration-line',\n 'text-decoration-style',\n 'text-decoration-color',\n 'text-indent',\n 'text-orientation',\n 'text-transform',\n 'text-overflow',\n 'writing-mode',\n 'direction',\n 'unicode-bidi',\n 'dominant-baseline',\n 'alignment-baseline',\n 'baseline-shift',\n 'line-height',\n 'white-space',\n 'glyph-orientation-vertical',\n 'glyph-orientation-horizontal',\n 'kerning',\n 'inline-size',\n 'shape-inside',\n 'shape-padding',\n 'shape-margin',\n 'shape-subtract',\n])\n\n/**\n * Removed only with the value that does nothing, and refused with any other,\n * with what to do: a filter, a mask, a marker or a blend this format does\n * not draw, a stroke painted under its fill, a transform about another\n * origin.\n */\ninterface Inert {\n readonly inert: (value: string) => boolean\n readonly advice: string\n}\n\nconst INERT: ReadonlyMap<string, Inert> = new Map<string, Inert>([\n ['filter', { inert: (value: string) => value === 'none', advice: 'expand the appearance' }],\n ['mask', { inert: (value: string) => value === 'none', advice: 'flatten the transparency' }],\n ['mix-blend-mode', { inert: (value: string) => value === 'normal', advice: 'flatten the transparency' }],\n ...['marker', 'marker-start', 'marker-mid', 'marker-end'].map((name): [string, Inert] => [\n name,\n { inert: (value: string) => value === 'none', advice: 'expand the stroke' },\n ]),\n ['paint-order', { inert: fillBeforeStroke, advice: 'paint the fill before the stroke' }],\n ['transform-origin', { inert: (value: string) => ORIGINS.has(value), advice: 'apply the transform about the origin' }],\n])\n\n/** `transform-origin` values that are the origin SVG takes anyway. */\nconst ORIGINS: ReadonlySet<string> = new Set(['0', '0 0', '0 0 0', '0px', '0px 0px', '0px 0px 0px', '0% 0%', 'left top', 'top left'])\n\n/** Whether a `paint-order` keeps the fill under the stroke, as SVG paints by default: `normal`, or a list that names stroke after fill or not at all. */\nfunction fillBeforeStroke(value: string): boolean {\n if (value === 'normal') return true\n const order = value.split(/\\s+/)\n const known = ['fill', 'stroke', 'markers']\n if (order.some((part) => !known.includes(part)) || new Set(order).size !== order.length) return false\n for (const part of known) if (!order.includes(part)) order.push(part)\n return order.indexOf('fill') < order.indexOf('stroke')\n}\n\n/** What happens to a property written on a kept element, whose value is its text trimmed and in lower case. */\nexport type PropertyFate =\n { readonly fate: 'kept'; readonly property: Property } | { readonly fate: 'removed' } | { readonly fate: 'refused'; readonly advice: string }\n\nexport function propertyFate(name: string, value: string): PropertyFate | undefined {\n if (isProperty(name)) return { fate: 'kept', property: name }\n if (REMOVED_PROPERTIES.has(name) || (name.startsWith('-') && !name.startsWith('--'))) return { fate: 'removed' }\n const inert = INERT.get(name)\n if (inert !== undefined) return inert.inert(value) ? { fate: 'removed' } : { fate: 'refused', advice: inert.advice }\n return undefined\n}\n","/**\n * How an SVG is refused, what cleaning one removed, and how a name read from\n * one is repeated back: the words every part of the SVG reader shares.\n *\n * A refusal or a removal names what was found, never a value: a link's\n * address, a script's text or a style's content is not repeated back to a\n * person, a log or a test snapshot. A name is repeated only when it is\n * short ASCII (`shown`), so neither a message nor the list of removals grows\n * with what a file holds, and neither carries bytes a reader would decode\n * as something else.\n */\nimport { MAX_KEY_LENGTH, MAX_SVG_REMOVED_NAMES } from './limits.js'\n\n/** Why an SVG is refused, each the first thing found that is wrong with it. */\nexport const SVG_REFUSAL_CODES = [\n /** Not XML whose root is an svg element in the SVG namespace. */\n 'not-svg',\n /** The XML itself: unclosed, mismatched, an attribute twice, data after the root, a character XML forbids. */\n 'not-well-formed',\n /** A UTF-16 or UTF-32 file, a declared encoding other than UTF-8, US-ASCII or ISO-8859-1, or a byte past ASCII in what is kept. */\n 'encoding',\n /** A DOCTYPE with an internal subset, or an entity XML does not predefine. */\n 'doctype',\n /** text, tspan, textPath, or character data where a drawing holds none. */\n 'text',\n /** An embedded picture. */\n 'raster',\n /** use, symbol, an href or url() to anything but a gradient or a clip path in the file, or a cycle. */\n 'reference',\n /** An element, attribute, property, value or CSS construct this format does not draw as a browser draws it. */\n 'unsupported',\n /** A number past MAX_SVG_COORDINATE, a negative size, a viewBox side under 1. */\n 'out-of-range',\n /** Past MAX_SVG_BYTES, MAX_SVG_ELEMENTS, MAX_SVG_SEGMENTS, MAX_SVG_GROUPS, MAX_SVG_STOPS, MAX_SVG_DASHES or MAX_SVG_RULES. */\n 'too-large',\n /** Nesting past MAX_SVG_DEPTH. */\n 'too-deep',\n] as const\nexport type SvgRefusalCode = (typeof SVG_REFUSAL_CODES)[number]\n\nexport interface SvgRefusal {\n readonly ok: false\n readonly code: SvgRefusalCode\n /** English, for a log or a person: what was found and where, by element path (`svg/g[2]/text`), never a value, then what to do (`SVG_ADVICE`). */\n readonly message: string\n}\n\n/**\n * A refusal on its way out of the reader. It is thrown where the problem is\n * found, deep in a value grammar, and caught once, at `cleanSvg`'s edge, so\n * that no partly read drawing is ever returned.\n */\nexport class SvgRefused extends Error {\n readonly code: SvgRefusalCode\n\n constructor(code: SvgRefusalCode, message: string) {\n super(message)\n this.code = code\n }\n}\n\n/**\n * What a person can do about each kind of refusal, said after what was\n * found unless the refusal knows something more particular. Every refusal\n * says one, because a refusal is what a person who uploaded a logo is\n * shown, and \"unsupported\" alone sends them back to the drawing program\n * with nothing to try (0030).\n */\nexport const SVG_ADVICE: { readonly [C in SvgRefusalCode]: string } = {\n 'not-svg': 'save the drawing as an SVG file',\n 'not-well-formed': 'save the drawing again from the program it was made in',\n encoding: 'save it as UTF-8, with every name in ASCII',\n doctype: 'save it as plain SVG',\n text: 'convert the text to outlines',\n raster: 'add the picture as a PNG or JPEG asset of its own',\n reference: 'save it again through a program that expands references, with everything it names inside the file',\n unsupported: 'expand it into plain shapes in the drawing program, or remove it',\n 'out-of-range': 'give the drawing an ordinary size in the drawing program',\n 'too-large': 'simplify the drawing',\n 'too-deep': 'flatten its groups',\n}\n\n/** What a stylesheet is refused with: every program that writes CSS into an SVG can write attributes instead. */\nexport const CSS_ADVICE = 'export it with presentation attributes rather than CSS'\n\n/** Refused, with what was found (`what`) and what to do (`advice`, the code's own when the refusal knows nothing more particular). */\nexport function refuse(code: SvgRefusalCode, what: string, advice: string = SVG_ADVICE[code]): never {\n throw new SvgRefused(code, `${what}; ${advice}`)\n}\n\n/**\n * A name as a message may repeat it: ASCII name characters, a leading hyphen\n * allowed for a vendor's property (`-inkscape-stroke`), and no longer than\n * the format's own longest name (`MAX_KEY_LENGTH`). Anything else is said as\n * `otherwise`: a name past that is never one this format knows, and a byte\n * past ASCII would be read as another character by another reader.\n */\nconst SHOWN = /^-?[A-Za-z_][A-Za-z0-9_.:-]*$/\n\nexport function shown(name: string, otherwise: string): string {\n return name.length <= MAX_KEY_LENGTH && SHOWN.test(name) ? name : otherwise\n}\n\n/** What cleaning removed: names only, never a value. */\nexport interface SvgRemoval {\n readonly kind: SvgRemovalKind\n /** The element, attribute or property name as written (`sodipodi:namedview`, `onclick`, `-inkscape-stroke`); for a comment, a declaration or a DOCTYPE, the kind again. */\n readonly name: string\n readonly count: number\n}\n\nexport type SvgRemovalKind = 'element' | 'attribute' | 'property' | 'comment' | 'declaration' | 'doctype'\n\n/** What stands in for a name `shown` will not repeat, by kind. */\nconst UNSHOWN: { readonly [K in SvgRemovalKind]: string } = {\n element: 'an element in another namespace',\n attribute: 'an attribute with a long or non-ASCII name',\n property: 'a property with a long or non-ASCII name',\n comment: 'comment',\n declaration: 'declaration',\n doctype: 'doctype',\n}\n\n/**\n * The removals of one cleaning, grouped by kind and name with a count. The\n * first `MAX_SVG_REMOVED_NAMES` distinct names are kept; every removal of a\n * name past them is counted in `more`, so that a file of fifty thousand\n * distinctly named attributes reports thirty-two names and a count of the\n * rest, not fifty thousand names.\n */\nexport class Removals {\n private readonly named = new Map<string, { kind: SvgRemovalKind; name: string; count: number }>()\n private further = 0\n\n add(kind: SvgRemovalKind, name: string): void {\n const said = shown(name, UNSHOWN[kind])\n const key = `${kind} ${said}`\n const found = this.named.get(key)\n if (found !== undefined) found.count += 1\n else if (this.named.size < MAX_SVG_REMOVED_NAMES) this.named.set(key, { kind, name: said, count: 1 })\n else this.further += 1\n }\n\n get more(): number {\n return this.further\n }\n\n list(): readonly SvgRemoval[] {\n return [...this.named.values()].map(({ kind, name, count }) => ({ kind, name, count }))\n }\n}\n","/**\n * The numbers of an SVG: read by SVG's number grammar, bounded, and written\n * back in one form every reader reads alike.\n *\n * A number is kept exactly where it can be: as an integer and a count of\n * decimal places, when the file wrote it in nine places or fewer. A\n * coordinate a path reaches by relative steps is then their exact decimal\n * sum, not the float sum -- `l.1.2` twice is at 0.2 0.4, never at\n * 0.20000000000000001 -- so the written form grows no digits the author did\n * not write, and never moves a point the author drew. Past nine places, and\n * for what is computed rather than written (a unit converted, a transform\n * composed), the number is the float, written as JavaScript's shortest\n * round trip. Either way, reading the written form again gives the same\n * number and writes the same text: the fixed point `checkSvg` tests for.\n *\n * A magnitude below 10^-6 is written as 0: no exponent is ever written\n * (JavaScript writes none between 10^-6 and 10^21), and the root's viewBox\n * is at least one unit wide, so a millionth of a unit is below anything a\n * page shows. A magnitude past `MAX_SVG_COORDINATE` is refused.\n */\nimport { MAX_SVG_COORDINATE } from './limits.js'\nimport { refuse } from './svg-refusal.js'\n\nexport interface SvgNumber {\n readonly value: number\n /** The number times 10^`places`, an integer held exactly, when the file wrote it in at most `MAX_PLACES` places; undefined for a float. */\n readonly scaled: number | undefined\n readonly places: number\n}\n\n/** The most decimal places a number is kept exactly in, and then in at most 15 digits, which a double holds exactly, as it does the sum of two. */\nconst MAX_PLACES = 9\nconst POWERS = [1, 10, 100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000, 1_000_000_000] as const\n\nexport const ZERO: SvgNumber = { value: 0, scaled: 0, places: 0 }\nexport const ONE: SvgNumber = { value: 1, scaled: 1, places: 0 }\n\n/** A number computed, not written. */\nexport function float(value: number): SvgNumber {\n return { value, scaled: undefined, places: 0 }\n}\n\nfunction power(places: number): number {\n return POWERS[places] as number\n}\n\nconst DIGIT_0 = 0x30\nconst DIGIT_9 = 0x39\n\nfunction isDigit(code: number): boolean {\n return code >= DIGIT_0 && code <= DIGIT_9\n}\n\n/**\n * Where the number that starts at `at` ends, or -1 when none starts there:\n * a sign, digits with at most one point and at least one digit, and an\n * exponent only when digits follow its `e`. `1.5.5` is two numbers, `1e` a\n * number and a stray letter, as SVG's grammar and svg-to-pdfkit both read\n * them.\n */\nexport function scanNumber(text: string, at: number): number {\n let i = at\n const sign = text.charCodeAt(i)\n if (sign === 0x2b || sign === 0x2d) i += 1\n let digits = 0\n while (isDigit(text.charCodeAt(i))) {\n i += 1\n digits += 1\n }\n if (text.charCodeAt(i) === 0x2e) {\n i += 1\n while (isDigit(text.charCodeAt(i))) {\n i += 1\n digits += 1\n }\n }\n if (digits === 0) return -1\n const e = text.charCodeAt(i)\n if (e === 0x65 || e === 0x45) {\n let j = i + 1\n const exponentSign = text.charCodeAt(j)\n if (exponentSign === 0x2b || exponentSign === 0x2d) j += 1\n if (isDigit(text.charCodeAt(j))) {\n while (isDigit(text.charCodeAt(j))) j += 1\n i = j\n }\n }\n return i\n}\n\n/** The number `text` holds between `start` and `end`, which `scanNumber` found, refused as `out-of-range` past the bound. */\nexport function numberAt(text: string, start: number, end: number, where: string): SvgNumber {\n const written = text.slice(start, end)\n const value = Number(written)\n if (!(Math.abs(value) <= MAX_SVG_COORDINATE)) refuse('out-of-range', `${where} holds a number past ${MAX_SVG_COORDINATE}`)\n return { value, ...exactly(written) }\n}\n\n/** The whole of `text`, which must be one number and nothing else, surrounding whitespace aside. */\nexport function readNumber(text: string, where: string): SvgNumber {\n const trimmed = text.trim()\n const end = scanNumber(trimmed, 0)\n if (end !== trimmed.length || end <= 0) refuse('unsupported', `${where} is not a number`, 'write it as a number')\n return numberAt(trimmed, 0, end, where)\n}\n\n/** The exact form of a number as written, or none when it has more places or digits than a double holds exactly. */\nfunction exactly(written: string): { readonly scaled: number | undefined; readonly places: number } {\n // `scanNumber` admits only what this pattern reads.\n const [, sign = '', whole = '', writtenFraction = '', exponent = '0'] = /^([+-]?)(\\d*)(?:\\.(\\d*))?(?:[eE]([+-]?\\d+))?$/.exec(written) ?? []\n // Trailing zeros dropped by a loop: `/0+$/` tries every start in a run of zeros, which a mebibyte of them makes quadratic.\n let kept = writtenFraction.length\n while (kept > 0 && writtenFraction.charCodeAt(kept - 1) === DIGIT_0) kept -= 1\n const fraction = writtenFraction.slice(0, kept)\n let places = fraction.length - Number(exponent)\n let digits = `${whole}${fraction}`.replace(/^0+/, '')\n if (digits === '') return { scaled: 0, places: 0 }\n if (places < 0) {\n digits += '0'.repeat(-places)\n places = 0\n }\n if (places > MAX_PLACES || digits.length > 15) return { scaled: undefined, places: 0 }\n const scaled = Number(digits)\n return { scaled: sign === '-' ? -scaled : scaled, places }\n}\n\n/** The sum of two numbers, exact when both are; refused as `out-of-range` past the bound, as a relative path that walks off the page is. */\nexport function plus(a: SvgNumber, b: SvgNumber, where: string): SvgNumber {\n let sum: SvgNumber\n if (a.scaled !== undefined && b.scaled !== undefined) {\n const places = Math.max(a.places, b.places)\n const scaled = a.scaled * power(places - a.places) + b.scaled * power(places - b.places)\n sum = { value: scaled / power(places), scaled, places }\n } else sum = float(a.value + b.value)\n if (!(Math.abs(sum.value) <= MAX_SVG_COORDINATE)) refuse('out-of-range', `${where} reaches a point past ${MAX_SVG_COORDINATE}`)\n return sum\n}\n\n/** A hundredth of a number, exact when it is and two more places still fit: what a percentage is. */\nexport function hundredth(n: SvgNumber): SvgNumber {\n if (n.scaled !== undefined && n.places + 2 <= MAX_PLACES) return { value: n.scaled / power(n.places + 2), scaled: n.scaled, places: n.places + 2 }\n return float(n.value / 100)\n}\n\n/** The number clamped between `low` and `high`, as SVG clamps an opacity or an offset. */\nexport function clamp(n: SvgNumber, low: SvgNumber, high: SvgNumber): SvgNumber {\n if (n.value < low.value) return low\n if (n.value > high.value) return high\n return n\n}\n\n/** The number's written form: no exponent, no sign on zero, no trailing zero, nothing below 10^-6. */\nexport function writeNumber(n: SvgNumber): string {\n if (!(Math.abs(n.value) >= 1e-6)) return '0'\n if (n.scaled === undefined) return String(n.value)\n const digits = String(Math.abs(n.scaled)).padStart(n.places + 1, '0')\n const whole = digits.slice(0, digits.length - n.places)\n const fraction = digits.slice(digits.length - n.places).replace(/0+$/, '')\n return `${n.scaled < 0 ? '-' : ''}${whole}${fraction === '' ? '' : `.${fraction}`}`\n}\n","/**\n * The XML an SVG is written in, read from its bytes: markup, attributes,\n * character data and references, checked for well-formedness as it goes.\n *\n * Bytes, not text: report-spec's ES2023 library has no `TextDecoder`, and\n * needs none. Every byte is read as the character of that number (Latin-1),\n * so a name or a value keeps its bytes exactly and a byte past ASCII stays a\n * character past ASCII, which the cleaner refuses wherever it would be kept:\n * a byte past 0x7F must mean the same thing to every reader of the file,\n * and the one way to be sure of that is to keep none. What is removed -- a\n * comment, a title, an editor's label -- may hold any.\n *\n * Iterative, never recursive, so that no nesting reaches the stack, and\n * stopped at the first error: a reference to an entity XML does not\n * predefine (`doctype`, since only a DOCTYPE could declare one), or an\n * unclosed, mismatched or otherwise malformed construct (`not-well-formed`),\n * named by byte offset and by the element path the reader was in.\n */\nimport { MAX_KEY_LENGTH } from './limits.js'\nimport { refuse } from './svg-refusal.js'\n\nexport interface XmlAttribute {\n /** As written, prefix and all. */\n readonly name: string\n /** Where its value's bytes start and end, inside the quotes. */\n readonly start: number\n readonly end: number\n}\n\nexport type XmlToken =\n | { readonly kind: 'declaration'; readonly version: string; readonly encoding: string | undefined }\n | { readonly kind: 'doctype' }\n | { readonly kind: 'comment' }\n | { readonly kind: 'pi'; readonly target: string }\n | { readonly kind: 'cdata'; readonly start: number; readonly end: number }\n | { readonly kind: 'text'; readonly start: number; readonly end: number }\n | { readonly kind: 'start'; readonly name: string; readonly attributes: readonly XmlAttribute[]; readonly empty: boolean }\n | { readonly kind: 'end'; readonly name: string }\n\nconst LT = 0x3c\nconst GT = 0x3e\nconst AMP = 0x26\nconst SLASH = 0x2f\nconst BANG = 0x21\nconst EQUALS = 0x3d\nconst QUOTE = 0x22\nconst APOSTROPHE = 0x27\nconst SEMICOLON = 0x3b\n\nfunction isWhite(byte: number | undefined): boolean {\n return byte === 0x20 || byte === 0x09 || byte === 0x0a || byte === 0x0d\n}\n\nfunction isNameStart(byte: number | undefined): boolean {\n return byte !== undefined && ((byte >= 0x41 && byte <= 0x5a) || (byte >= 0x61 && byte <= 0x7a) || byte === 0x5f || byte === 0x3a || byte >= 0x80)\n}\n\nfunction isNameByte(byte: number | undefined): boolean {\n return isNameStart(byte) || (byte !== undefined && ((byte >= 0x30 && byte <= 0x39) || byte === 0x2d || byte === 0x2e))\n}\n\n/** The bytes from `start` to `end` as characters of their own numbers. */\nexport function latin1(bytes: Uint8Array, start: number, end: number): string {\n let text = ''\n for (let at = start; at < end; at += 8192) text += String.fromCharCode(...bytes.subarray(at, Math.min(end, at + 8192)))\n return text\n}\n\n/** Whether a code point is a character XML 1.0 allows (production 2), which a numeric reference must name. */\nfunction isXmlChar(code: number): boolean {\n return (\n code === 0x9 ||\n code === 0xa ||\n code === 0xd ||\n (code >= 0x20 && code <= 0xd7ff) ||\n (code >= 0xe000 && code <= 0xfffd) ||\n (code >= 0x10000 && code <= 0x10ffff)\n )\n}\n\nconst PREDEFINED: { readonly [name: string]: string } = { lt: '<', gt: '>', amp: '&', quot: '\"', apos: \"'\" }\n\nexport class XmlReader {\n private readonly bytes: Uint8Array\n private at: number\n /** The element path the reader is in, for messages; the tree that reads the tokens keeps it. */\n path = 'the document'\n\n constructor(bytes: Uint8Array) {\n this.bytes = bytes\n this.at = 0\n const [b0, b1, b2] = bytes\n if (b0 === 0xef && b1 === 0xbb && b2 === 0xbf) this.at = 3\n else if ((b0 === 0xfe && b1 === 0xff) || (b0 === 0xff && b1 === 0xfe) || b0 === 0 || b1 === 0)\n refuse('encoding', 'the file is UTF-16 or UTF-32', 'save it as UTF-8')\n for (let i = this.at; i < bytes.length; i += 1) {\n const byte = bytes[i] as number\n if (byte < 0x20 && !isWhite(byte)) this.malformed(i, 'a control character XML forbids')\n }\n }\n\n private malformed(at: number, what: string): never {\n return refuse('not-well-formed', `at byte ${at} in ${this.path}: ${what}`)\n }\n\n private startsWith(text: string, at = this.at): boolean {\n for (let k = 0; k < text.length; k += 1) if (this.bytes[at + k] !== text.charCodeAt(k)) return false\n return true\n }\n\n /** Where `text` first starts between `from` and `to`, or -1. Every search is bounded, so that no construct is searched past its own end and reading stays linear in the bytes. */\n private find(text: string, from: number, to = this.bytes.length): number {\n const first = text.charCodeAt(0)\n for (let i = this.index(first, from, to); i >= 0; i = this.index(first, i + 1, to)) if (this.startsWith(text, i)) return i\n return -1\n }\n\n private index(byte: number, from: number, to: number): number {\n const found = this.bytes.subarray(from, to).indexOf(byte)\n return found < 0 ? -1 : from + found\n }\n\n private name(): string {\n const start = this.at\n if (!isNameStart(this.bytes[this.at])) this.malformed(start, 'markup without a name')\n while (isNameByte(this.bytes[this.at])) this.at += 1\n const name = latin1(this.bytes, start, this.at)\n const colon = name.indexOf(':')\n if (colon === 0 || colon === name.length - 1 || name.indexOf(':', colon + 1) >= 0) this.malformed(start, 'a name with a misplaced colon')\n return name\n }\n\n private skipWhite(): boolean {\n const start = this.at\n while (isWhite(this.bytes[this.at])) this.at += 1\n return this.at > start\n }\n\n /** The next token, or undefined at the end of the bytes. */\n next(): XmlToken | undefined {\n const { bytes } = this\n if (this.at >= bytes.length) return undefined\n const start = this.at\n if (bytes[start] !== LT) {\n const lt = bytes.indexOf(LT, start)\n this.at = lt < 0 ? bytes.length : lt\n this.references(start, this.at)\n const close = this.find(']]>', start, this.at)\n if (close >= 0) this.malformed(close, ']]> in character data')\n return { kind: 'text', start, end: this.at }\n }\n if (this.startsWith('<?')) return this.instruction(start)\n if (this.startsWith('<!--')) {\n const dashes = this.find('--', start + 4)\n if (dashes < 0 || bytes[dashes + 2] !== GT) this.malformed(start, 'a comment that holds -- or is not closed')\n this.at = dashes + 3\n return { kind: 'comment' }\n }\n if (this.startsWith('<![CDATA[')) {\n const close = this.find(']]>', start + 9)\n if (close < 0) this.malformed(start, 'a CDATA section that is not closed')\n this.at = close + 3\n return { kind: 'cdata', start: start + 9, end: close }\n }\n if (this.startsWith('<!DOCTYPE')) return this.doctype(start)\n if (bytes[start + 1] === BANG) this.malformed(start, 'a declaration outside a DOCTYPE')\n if (bytes[start + 1] === SLASH) {\n this.at = start + 2\n const name = this.name()\n this.skipWhite()\n if (bytes[this.at] !== GT) this.malformed(start, 'an end tag that is not closed')\n this.at += 1\n return { kind: 'end', name }\n }\n return this.startTag(start)\n }\n\n private instruction(start: number): XmlToken {\n this.at = start + 2\n const target = this.name()\n const close = this.find('?>', this.at)\n if (close < 0) this.malformed(start, 'a processing instruction that is not closed')\n if (close > this.at && !isWhite(this.bytes[this.at])) this.malformed(start, 'a processing instruction without a space after its target')\n const body = latin1(this.bytes, this.at, close)\n this.at = close + 2\n if (target.toLowerCase() !== 'xml') return { kind: 'pi', target }\n const bom = this.bytes[0] === 0xef ? 3 : 0\n if (target !== 'xml' || start !== bom) this.malformed(start, 'an XML declaration anywhere but at the very start')\n const declaration = /^\\s+version\\s*=\\s*([\"'])([^\"']*)\\1(?:\\s+encoding\\s*=\\s*([\"'])([^\"']*)\\3)?(?:\\s+standalone\\s*=\\s*([\"'])(?:yes|no)\\5)?\\s*$/.exec(body)\n if (declaration === null) this.malformed(start, 'an XML declaration that is not one')\n return { kind: 'declaration', version: declaration[2] ?? '', encoding: declaration[4] }\n }\n\n private doctype(start: number): XmlToken {\n let quote: number | undefined\n for (let i = start + 9; i < this.bytes.length; i += 1) {\n const byte = this.bytes[i]\n if (quote !== undefined) {\n if (byte === quote) quote = undefined\n } else if (byte === QUOTE || byte === APOSTROPHE) quote = byte\n else if (byte === 0x5b)\n refuse(\n 'doctype',\n 'the DOCTYPE declares entities in an internal subset, which this format does not expand',\n \"save it without Illustrator's editing capabilities, or as plain SVG\",\n )\n else if (byte === GT) {\n this.at = i + 1\n return { kind: 'doctype' }\n }\n }\n return this.malformed(start, 'a DOCTYPE that is not closed')\n }\n\n private startTag(start: number): XmlToken {\n this.at = start + 1\n const name = this.name()\n const attributes: XmlAttribute[] = []\n const seen = new Set<string>()\n for (;;) {\n const spaced = this.skipWhite()\n const byte = this.bytes[this.at]\n if (byte === GT) {\n this.at += 1\n return { kind: 'start', name, attributes, empty: false }\n }\n if (byte === SLASH && this.bytes[this.at + 1] === GT) {\n this.at += 2\n return { kind: 'start', name, attributes, empty: true }\n }\n if (byte === undefined) this.malformed(start, 'a start tag that is not closed')\n if (!spaced) this.malformed(this.at, 'attributes not separated by a space')\n const attributeAt = this.at\n const attribute = this.name()\n if (seen.has(attribute)) this.malformed(attributeAt, 'an attribute given twice')\n seen.add(attribute)\n this.skipWhite()\n if (this.bytes[this.at] !== EQUALS) this.malformed(this.at, 'an attribute without a value')\n this.at += 1\n this.skipWhite()\n const quote = this.bytes[this.at]\n if (quote !== QUOTE && quote !== APOSTROPHE) this.malformed(this.at, 'an attribute value without quotes')\n const valueStart = this.at + 1\n const valueEnd = this.bytes.indexOf(quote, valueStart)\n if (valueEnd < 0) this.malformed(this.at, 'an attribute value that is not closed')\n const lt = this.index(LT, valueStart, valueEnd)\n if (lt >= 0) this.malformed(lt, '< in an attribute value')\n this.references(valueStart, valueEnd)\n attributes.push({ name: attribute, start: valueStart, end: valueEnd })\n this.at = valueEnd + 1\n }\n }\n\n /** Every reference between `start` and `end`, checked: XML's five entities, or a number naming a character XML allows. */\n private references(start: number, end: number): void {\n for (let i = this.index(AMP, start, end); i >= 0; i = this.index(AMP, i + 1, end)) this.reference(i, end)\n }\n\n /** The reference at `at`: what it stands for, and where it ends. */\n private reference(at: number, end: number): { readonly text: string; readonly next: number } {\n // A reference longer than the format's longest name is not one this reader follows: `&#x10FFFF;` is ten bytes.\n const semicolon = this.index(SEMICOLON, at, Math.min(end, at + MAX_KEY_LENGTH))\n if (semicolon < 0) this.malformed(at, '& that does not start a reference')\n const body = latin1(this.bytes, at + 1, semicolon)\n const numeric = /^#(?:([0-9]+)|x([0-9a-fA-F]+))$/.exec(body)\n if (numeric !== null) {\n const code = numeric[1] !== undefined ? Number.parseInt(numeric[1], 10) : Number.parseInt(numeric[2] ?? '', 16)\n if (!isXmlChar(code)) this.malformed(at, 'a reference to a character XML forbids')\n return { text: String.fromCodePoint(code), next: semicolon + 1 }\n }\n const predefined = PREDEFINED[body]\n if (predefined === undefined) {\n if (!/^[A-Za-z_:][A-Za-z0-9._:-]*$/.test(body)) this.malformed(at, '& that does not start a reference')\n refuse('doctype', `at byte ${at} in ${this.path}: a reference to an entity XML does not predefine, which only a DOCTYPE could declare`)\n }\n return { text: predefined, next: semicolon + 1 }\n }\n\n /**\n * The characters between `start` and `end`, references replaced by what\n * they stand for, and, in an attribute value, each literal tab, line feed\n * and carriage return by a space, as XML normalises a value (3.3.3).\n */\n decode(start: number, end: number, value: boolean): string {\n let text = ''\n let from = start\n for (let i = this.index(AMP, start, end); i >= 0;) {\n text += latin1(this.bytes, from, i)\n const { text: replaced, next } = this.reference(i, end)\n text += replaced\n from = next\n i = this.index(AMP, next, end)\n }\n text += latin1(this.bytes, from, end)\n return value ? text.replace(/[\\t\\n\\r]/g, ' ') : text\n }\n\n /** The bytes between `start` and `end` as they are, as a CDATA section holds them. */\n raw(start: number, end: number): string {\n return latin1(this.bytes, start, end)\n }\n\n /** Whether the bytes between `start` and `end` are XML whitespace alone. */\n isWhite(start: number, end: number): boolean {\n for (let i = start; i < end; i += 1) if (!isWhite(this.bytes[i])) return false\n return true\n }\n}\n","/**\n * An SVG's tokens read into the tree the cleaner works on: the elements it\n * keeps, each with its geometry, its presentation attributes, its id, its\n * classes and its `style`; the text of its stylesheets; and, as it goes,\n * what it removes and what it refuses (0030).\n *\n * Namespaces are XML's: an element is an SVG one by its namespace, not its\n * prefix, so `svg:rect` is a rect, and an element in any other namespace --\n * an editor's layers, its metadata -- is removed with everything inside it.\n * A prefixed attribute is in its prefix's namespace, never the attribute of\n * the same local name, so `svg:fill` is not `fill` (Namespaces in XML,\n * 6.2) and is removed as a browser ignores it.\n *\n * Inside what is removed nothing is read but well-formedness, with one\n * exception: an SVG `style` there would still style the drawing in a\n * browser, so it is refused rather than skipped.\n */\nimport { MAX_SVG_DEPTH, MAX_SVG_ELEMENTS } from './limits.js'\nimport {\n CHILDREN,\n CONDITIONAL_ATTRIBUTES,\n GEOMETRY,\n GRADIENTS,\n isKept,\n isRemovedAttribute,\n type KeptElement,\n LINK_ATTRIBUTES,\n type Property,\n propertyFate,\n REFUSED_ELEMENTS,\n REMOVED_ELEMENTS,\n ROOT_REMOVED,\n TRANSFORMED,\n} from './svg-allow.js'\nimport { CSS_ADVICE, refuse, Removals, shown } from './svg-refusal.js'\nimport { type XmlAttribute, XmlReader } from './svg-syntax.js'\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'\nconst XLINK_NAMESPACE = 'http://www.w3.org/1999/xlink'\nconst XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'\n\n/** A value as written, and where, for a message about it. */\nexport interface Located {\n readonly value: string\n readonly where: string\n}\n\nexport interface SvgElement {\n readonly name: KeptElement\n /** An `a`, read as the group it draws as: its link removed, its transform and its paint kept (0030). */\n readonly link: boolean\n readonly path: string\n readonly parent: SvgElement | undefined\n readonly children: SvgElement[]\n readonly depth: number\n /** Geometry, `transform` and a gradient's `href`, as written. */\n readonly attributes: Map<string, Located>\n /** The kept properties written as presentation attributes. */\n readonly presentation: Map<Property, Located>\n id: string | undefined\n classes: readonly string[]\n style: Located | undefined\n}\n\nexport interface SvgDocument {\n readonly root: SvgElement\n /** Every stylesheet's text, in document order. */\n readonly styles: readonly Located[]\n /** The root's width and height, which give the viewBox when it has none. */\n readonly width: Located | undefined\n readonly height: Located | undefined\n}\n\n/** Where the reader is: a kept element, inside something removed, or inside a stylesheet. */\ninterface Frame {\n readonly qname: string\n readonly declared: readonly string[]\n readonly kind: 'kept' | 'removed' | 'style'\n readonly element: SvgElement | undefined\n /** The nearest kept element's path, or a stylesheet's own. */\n readonly path: string\n readonly siblings: Map<string, number>\n readonly text: string[]\n}\n\n/** Whether a text holds a character past ASCII: a byte past 0x7F as Latin-1 reads it, or a reference to one. */\nexport function hasNonAscii(text: string): boolean {\n for (let i = 0; i < text.length; i += 1) if (text.charCodeAt(i) > 0x7f) return true\n return false\n}\n\nfunction split(qname: string): { readonly prefix: string; readonly local: string } {\n const colon = qname.indexOf(':')\n return colon < 0 ? { prefix: '', local: qname } : { prefix: qname.slice(0, colon), local: qname.slice(colon + 1) }\n}\n\nexport function readTree(bytes: Uint8Array, removals: Removals): SvgDocument {\n return new TreeReader(bytes, removals).read()\n}\n\nclass TreeReader {\n private readonly reader: XmlReader\n private readonly removals: Removals\n private readonly frames: Frame[] = []\n /** Each prefix's bindings, innermost last; `''` is the default namespace. */\n private readonly namespaces = new Map<string, string[]>([['xml', [XML_NAMESPACE]]])\n private readonly styles: Located[] = []\n private root: SvgElement | undefined\n private closed = false\n private doctype = false\n private elements = 0\n private readonly ids = new Set<string>()\n private width: Located | undefined\n private height: Located | undefined\n\n constructor(bytes: Uint8Array, removals: Removals) {\n this.reader = new XmlReader(bytes)\n this.removals = removals\n }\n\n read(): SvgDocument {\n for (let token = this.reader.next(); token !== undefined; token = this.reader.next()) {\n const top = this.frames.at(-1)\n switch (token.kind) {\n case 'declaration':\n if (token.version !== '1.0') refuse('unsupported', 'the file is XML 1.1, which this format does not read', 'save it as XML 1.0')\n if (token.encoding !== undefined && !/^(utf-8|us-ascii|iso-8859-1)$/i.test(token.encoding))\n refuse('encoding', 'the file declares an encoding other than UTF-8, US-ASCII or ISO-8859-1', 'save it as UTF-8')\n this.removals.add('declaration', 'declaration')\n break\n case 'doctype':\n if (this.doctype || this.root !== undefined) refuse('not-well-formed', 'a DOCTYPE after the root or a second one')\n this.doctype = true\n this.removals.add('doctype', 'doctype')\n break\n case 'comment':\n if (top?.kind !== 'removed') this.removals.add('comment', 'comment')\n break\n case 'pi':\n if (top?.kind !== 'removed')\n refuse(\n 'unsupported',\n `${this.reader.path} holds a processing instruction (${shown(token.target, 'one')}), which this format does not read`,\n 'save it as plain SVG',\n )\n break\n case 'text':\n case 'cdata':\n this.characters(top, token.kind, token.start, token.end)\n break\n case 'start':\n this.start(top, token.name, token.attributes, token.empty)\n break\n default:\n this.end(top, token.name)\n }\n }\n if (this.root === undefined) refuse('not-svg', 'the file holds no svg element')\n if (this.frames.length > 0) refuse('not-well-formed', `${this.reader.path} is not closed`)\n return { root: this.root, styles: this.styles, width: this.width, height: this.height }\n }\n\n private characters(top: Frame | undefined, kind: 'text' | 'cdata', start: number, end: number): void {\n if (top === undefined) {\n if (kind === 'cdata' || !this.reader.isWhite(start, end)) refuse('not-well-formed', 'character data outside the root')\n return\n }\n if (top.kind === 'removed') return\n if (top.kind === 'style') {\n top.text.push(kind === 'cdata' ? this.reader.raw(start, end) : this.reader.decode(start, end, false))\n return\n }\n if (kind === 'cdata') refuse('unsupported', `${this.reader.path} holds a CDATA section, which this format reads in a style alone`, 'save it as plain SVG')\n if (!this.reader.isWhite(start, end)) refuse('text', `${this.reader.path} holds text`)\n }\n\n private lookup(prefix: string): string | undefined {\n return this.namespaces.get(prefix)?.at(-1)\n }\n\n /** The namespaces a start tag declares, bound until its end tag; checked as Namespaces in XML checks them. */\n private declare(attributes: readonly XmlAttribute[]): string[] {\n const declared: string[] = []\n for (const attribute of attributes) {\n if (attribute.name !== 'xmlns' && !attribute.name.startsWith('xmlns:')) continue\n const prefix = attribute.name === 'xmlns' ? '' : attribute.name.slice(6)\n const uri = this.reader.decode(attribute.start, attribute.end, true)\n if (prefix === 'xmlns' || (prefix === 'xml') !== (uri === XML_NAMESPACE) || (prefix !== '' && uri === ''))\n refuse('not-well-formed', `${this.reader.path}: a namespace declaration XML forbids`)\n const bindings = this.namespaces.get(prefix) ?? []\n bindings.push(uri)\n this.namespaces.set(prefix, bindings)\n declared.push(prefix)\n }\n return declared\n }\n\n private start(top: Frame | undefined, qname: string, attributes: readonly XmlAttribute[], empty: boolean): void {\n if (top === undefined && (this.root !== undefined || this.closed)) refuse('not-well-formed', 'a second element after the root')\n const declared = this.declare(attributes)\n const { prefix, local } = split(qname)\n const uri = this.lookup(prefix)\n if (prefix !== '' && uri === undefined) refuse('not-well-formed', `${this.reader.path}: an element of a prefix no namespace is declared for`)\n this.attributesUnique(attributes)\n const frame = (kind: Frame['kind'], path: string, element?: SvgElement): void => {\n const pushed: Frame = { qname, declared, kind, element, path, siblings: new Map(), text: [] }\n if (empty) this.close(pushed)\n else {\n this.frames.push(pushed)\n if (element !== undefined) this.reader.path = element.path\n }\n }\n if (top?.kind === 'removed') {\n if (uri === SVG_NAMESPACE && local === 'style')\n refuse(\n 'unsupported',\n `${this.reader.path} holds a style inside what is removed, which a browser would still apply`,\n 'move the style out of it, or delete the style',\n )\n frame('removed', top.path)\n return\n }\n if (top?.kind === 'style') refuse('unsupported', `${this.reader.path} holds an element inside a style`, CSS_ADVICE)\n if (top === undefined && (local !== 'svg' || uri !== SVG_NAMESPACE)) refuse('not-svg', 'the root is not an svg element in the SVG namespace')\n const path = this.path(top, local)\n if (uri !== SVG_NAMESPACE) {\n this.removals.add('element', qname)\n frame('removed', top?.path ?? path)\n return\n }\n // Unprefixed SVG elements below would be in another namespace, which a browser draws none of.\n if (declared.includes('') && this.lookup('') !== SVG_NAMESPACE)\n refuse('unsupported', `${path} declares another default namespace than SVG's`, 'save it as plain SVG')\n if (REMOVED_ELEMENTS.has(local)) {\n this.removals.add('element', local)\n frame('removed', top?.path ?? path)\n return\n }\n if (local === 'style') {\n this.styleAttributes(attributes, path)\n this.removals.add('element', 'style')\n frame('style', path)\n return\n }\n frame('kept', path, this.keep(top?.element, local, path, attributes))\n }\n\n /** An SVG element neither removed nor a stylesheet: refused, or kept where its parent may hold it, within the bounds. */\n private keep(parent: SvgElement | undefined, local: string, path: string, attributes: readonly XmlAttribute[]): SvgElement {\n const refused = REFUSED_ELEMENTS.get(local)\n if (refused !== undefined) refuse(refused.code, `${path} is ${local}`, refused.advice)\n if (local === 'svg' && parent !== undefined)\n refuse('unsupported', `${path} is an svg inside the drawing, and this format draws one svg alone`, 'ungroup it into the outer drawing')\n const link = local === 'a'\n const name = link ? 'g' : local\n if (!isKept(name)) refuse('unsupported', `${path} is ${shown(local, 'an element')}, which this format does not draw`)\n if (parent !== undefined && !CHILDREN[parent.name].has(name))\n refuse('unsupported', `${path} is not drawn inside a ${parent.name}`, `move it out of the ${parent.name}`)\n const depth = (parent?.depth ?? 0) + 1\n if (depth > MAX_SVG_DEPTH) refuse('too-deep', `${path} nests past ${MAX_SVG_DEPTH} levels`)\n this.elements += 1\n if (this.elements > MAX_SVG_ELEMENTS) refuse('too-large', `the drawing has more than ${MAX_SVG_ELEMENTS} elements`)\n const element: SvgElement = {\n name,\n link,\n path,\n parent,\n children: [],\n depth,\n attributes: new Map(),\n presentation: new Map(),\n id: undefined,\n classes: [],\n style: undefined,\n }\n if (link) this.removals.add('element', 'a')\n this.attributes(element, attributes)\n if (parent === undefined) this.root = element\n else parent.children.push(element)\n return element\n }\n\n private path(top: Frame | undefined, local: string): string {\n if (top?.element === undefined) return local\n // The name as a message may repeat it: an element this format does not know may be named anything.\n const name = shown(local, 'element')\n const count = (top.siblings.get(name) ?? 0) + 1\n top.siblings.set(name, count)\n return `${top.element.path}/${name}${count > 1 ? `[${count}]` : ''}`\n }\n\n /** No two attributes of one element name the same thing, prefixes resolved: `xlink:href` and `x:href` bound to one namespace are one attribute twice. */\n private attributesUnique(attributes: readonly XmlAttribute[]): void {\n const seen = new Set<string>()\n for (const { name } of attributes) {\n const { prefix, local } = split(name)\n if (prefix === '' || prefix === 'xmlns') continue\n const uri = this.lookup(prefix)\n if (uri === undefined) refuse('not-well-formed', `${this.reader.path}: an attribute of a prefix no namespace is declared for`)\n const key = `${uri} ${local}`\n if (seen.has(key)) refuse('not-well-formed', `${this.reader.path}: an attribute given twice under two prefixes`)\n seen.add(key)\n }\n }\n\n /** A stylesheet is read only when it is CSS for every medium, as a browser would apply it to a printed page. */\n private styleAttributes(attributes: readonly XmlAttribute[], path: string): void {\n for (const attribute of attributes) {\n const value = this.reader.decode(attribute.start, attribute.end, true).trim().toLowerCase()\n if (attribute.name === 'type' && value !== '' && value !== 'text/css') refuse('unsupported', `${path} is a stylesheet that is not CSS`, CSS_ADVICE)\n if (attribute.name === 'media' && value !== 'all') refuse('unsupported', `${path} is a stylesheet for some media alone`, CSS_ADVICE)\n }\n }\n\n private attributes(element: SvgElement, attributes: readonly XmlAttribute[]): void {\n const root = element.parent === undefined\n for (const attribute of attributes) {\n const { name: qname } = attribute\n if (qname === 'xmlns' || qname.startsWith('xmlns:')) {\n if (qname !== 'xmlns') this.removals.add('attribute', qname)\n continue\n }\n const where = `${element.path}@${shown(qname, 'an attribute')}`\n const { prefix, local } = split(qname)\n const value = (): string => this.reader.decode(attribute.start, attribute.end, true)\n if (prefix !== '') {\n if (this.lookup(prefix) === XLINK_NAMESPACE && local === 'href') this.href(element, value(), where)\n else if (!element.link || this.lookup(prefix) !== XLINK_NAMESPACE) this.removals.add('attribute', qname)\n continue\n }\n if (root && ROOT_REMOVED.has(local)) {\n if (local === 'width') this.width = { value: value(), where }\n if (local === 'height') this.height = { value: value(), where }\n this.removals.add('attribute', local)\n } else if (local === 'href') this.href(element, value(), where)\n else if (element.link && LINK_ATTRIBUTES.has(local)) continue\n else if (isRemovedAttribute(local)) this.removals.add('attribute', local)\n else if (CONDITIONAL_ATTRIBUTES.has(local))\n refuse('unsupported', `${where} is a conditional-processing attribute, by which a browser may hide the element`, `remove ${local} from it`)\n else if (local === 'id') this.id(element, value(), where)\n else if (local === 'class')\n element.classes = value()\n .split(' ')\n .filter((name) => name !== '')\n else if (local === 'style') element.style = { value: value(), where }\n else if (GEOMETRY[element.name].includes(local) || local === 'transform') this.geometry(element, local, value(), where)\n else this.presentation(element, local, value(), where)\n }\n }\n\n /** An element's id, refused when another element has it: which of the two a reference names, readers decide differently. */\n private id(element: SvgElement, id: string, where: string): void {\n if (this.ids.has(id)) refuse('reference', `${where} is an id another element has too`, 'give each element an id of its own')\n this.ids.add(id)\n element.id = id\n }\n\n private geometry(element: SvgElement, name: string, value: string, where: string): void {\n if (name === 'transform' && !TRANSFORMED.has(element.name) && element.parent !== undefined) {\n // A transform on defs moves nothing: what defs holds is drawn, if at all, in the user space of what refers to it.\n if (element.name === 'defs') this.removals.add('attribute', 'transform')\n else\n refuse(\n 'unsupported',\n `${where} transforms an element this format does not transform`,\n \"move the transform onto a group around it, or onto a gradient's gradientTransform\",\n )\n return\n }\n element.attributes.set(name, { value: ascii(value, where), where })\n }\n\n private presentation(element: SvgElement, name: string, value: string, where: string): void {\n const fate = propertyFate(name, value.trim().toLowerCase().replace(/\\s+/g, ' '))\n if (fate === undefined) refuse('unsupported', `${where} is not an attribute this format draws as a browser draws it`)\n if (fate.fate === 'removed') this.removals.add('attribute', name)\n else if (fate.fate === 'refused') refuse('unsupported', `${where} is not drawn by this format`, fate.advice)\n else element.presentation.set(fate.property, { value: ascii(value, where), where })\n }\n\n /** A gradient's reference to another gradient, the one reference an attribute may hold; a link's is removed with the link. */\n private href(element: SvgElement, value: string, where: string): void {\n if (element.link) return\n if (!GRADIENTS.has(element.name)) refuse('reference', `${where} is a reference this format does not follow`)\n if (element.attributes.has('href')) refuse('reference', `${where}: href and xlink:href both, which readers choose between differently`, 'keep one of them')\n element.attributes.set('href', { value: ascii(value, where), where })\n }\n\n private end(top: Frame | undefined, qname: string): void {\n if (top === undefined || top.qname !== qname) refuse('not-well-formed', `${this.reader.path}: an end tag that does not match its start`)\n this.frames.pop()\n this.close(top)\n this.reader.path = this.frames.at(-1)?.path ?? 'the document'\n }\n\n private close(frame: Frame): void {\n for (const prefix of frame.declared) this.namespaces.get(prefix)?.pop()\n if (frame.kind === 'style') this.styles.push({ value: frame.text.join(''), where: frame.path })\n if (frame.element !== undefined && frame.element.parent === undefined) this.closed = true\n }\n}\n\n/** A kept value, refused when it holds a byte past ASCII: what is kept must read alike in every reader. */\nfunction ascii(value: string, where: string): string {\n if (hasNonAscii(value)) refuse('encoding', `${where} holds a byte past ASCII`, 'write it in ASCII')\n return value\n}\n","/**\n * The named colours an SVG may write, and the `#rrggbb` each is written as.\n *\n * Taken from CSS Color Module Level 4, section 6.1 (\"Named Colors\"), which\n * SVG's colour keywords follow, and not copied from the converter: the\n * renderer's tests hold this table equal to the one svg-to-pdfkit, under\n * pdfmake 0.3.11, reads the names with, so a transcription error in either\n * shows. The cleaner writes every colour as `#rrggbb`, so the converter\n * itself never reads a name. `transparent` and the system colours are not\n * here: a colour with an alpha would have to become an opacity, which is a\n * second decision (0030).\n *\n * Packed as name and hex, two words a colour, so that the 148 entries read\n * as a table and not as 148 lines.\n */\nconst PACKED = `\naliceblue f0f8ff antiquewhite faebd7 aqua 00ffff aquamarine 7fffd4 azure f0ffff\nbeige f5f5dc bisque ffe4c4 black 000000 blanchedalmond ffebcd blue 0000ff\nblueviolet 8a2be2 brown a52a2a burlywood deb887 cadetblue 5f9ea0 chartreuse 7fff00\nchocolate d2691e coral ff7f50 cornflowerblue 6495ed cornsilk fff8dc crimson dc143c\ncyan 00ffff darkblue 00008b darkcyan 008b8b darkgoldenrod b8860b darkgray a9a9a9\ndarkgreen 006400 darkgrey a9a9a9 darkkhaki bdb76b darkmagenta 8b008b\ndarkolivegreen 556b2f darkorange ff8c00 darkorchid 9932cc darkred 8b0000\ndarksalmon e9967a darkseagreen 8fbc8f darkslateblue 483d8b darkslategray 2f4f4f\ndarkslategrey 2f4f4f darkturquoise 00ced1 darkviolet 9400d3 deeppink ff1493\ndeepskyblue 00bfff dimgray 696969 dimgrey 696969 dodgerblue 1e90ff\nfirebrick b22222 floralwhite fffaf0 forestgreen 228b22 fuchsia ff00ff\ngainsboro dcdcdc ghostwhite f8f8ff gold ffd700 goldenrod daa520 gray 808080\ngreen 008000 greenyellow adff2f grey 808080 honeydew f0fff0 hotpink ff69b4\nindianred cd5c5c indigo 4b0082 ivory fffff0 khaki f0e68c lavender e6e6fa\nlavenderblush fff0f5 lawngreen 7cfc00 lemonchiffon fffacd lightblue add8e6\nlightcoral f08080 lightcyan e0ffff lightgoldenrodyellow fafad2 lightgray d3d3d3\nlightgreen 90ee90 lightgrey d3d3d3 lightpink ffb6c1 lightsalmon ffa07a\nlightseagreen 20b2aa lightskyblue 87cefa lightslategray 778899 lightslategrey 778899\nlightsteelblue b0c4de lightyellow ffffe0 lime 00ff00 limegreen 32cd32 linen faf0e6\nmagenta ff00ff maroon 800000 mediumaquamarine 66cdaa mediumblue 0000cd\nmediumorchid ba55d3 mediumpurple 9370db mediumseagreen 3cb371 mediumslateblue 7b68ee\nmediumspringgreen 00fa9a mediumturquoise 48d1cc mediumvioletred c71585\nmidnightblue 191970 mintcream f5fffa mistyrose ffe4e1 moccasin ffe4b5\nnavajowhite ffdead navy 000080 oldlace fdf5e6 olive 808000 olivedrab 6b8e23\norange ffa500 orangered ff4500 orchid da70d6 palegoldenrod eee8aa palegreen 98fb98\npaleturquoise afeeee palevioletred db7093 papayawhip ffefd5 peachpuff ffdab9\nperu cd853f pink ffc0cb plum dda0dd powderblue b0e0e6 purple 800080\nrebeccapurple 663399 red ff0000 rosybrown bc8f8f royalblue 4169e1 saddlebrown 8b4513\nsalmon fa8072 sandybrown f4a460 seagreen 2e8b57 seashell fff5ee sienna a0522d\nsilver c0c0c0 skyblue 87ceeb slateblue 6a5acd slategray 708090 slategrey 708090\nsnow fffafa springgreen 00ff7f steelblue 4682b4 tan d2b48c teal 008080\nthistle d8bfd8 tomato ff6347 turquoise 40e0d0 violet ee82ee wheat f5deb3\nwhite ffffff whitesmoke f5f5f5 yellow ffff00 yellowgreen 9acd32\n`\n\nfunction unpack(packed: string): ReadonlyMap<string, string> {\n const words = packed.trim().split(/\\s+/)\n const colours = new Map<string, string>()\n for (let i = 0; i < words.length; i += 2) colours.set(words[i] as string, `#${words[i + 1] as string}`)\n return colours\n}\n\n/** Each CSS colour name, in lower case, and the `#rrggbb` it is written as. */\nexport const SVG_NAMED_COLOURS: ReadonlyMap<string, string> = unpack(PACKED)\n","/**\n * The values an SVG's kept properties and geometry may take, each read by\n * its own grammar into a typed value, and refused, named, when it is not one\n * the format reads.\n *\n * A value outside its grammar is refused, never ignored as a browser\n * ignores an invalid declaration: ignoring it would print a drawing the\n * author did not write, whose cause nobody would find. Keywords, units and\n * colour names are read in any case, as CSS reads them, and written in one.\n */\nimport { INHERITED, type Property } from './svg-allow.js'\nimport { SVG_NAMED_COLOURS } from './svg-colours.js'\nimport { clamp, float, hundredth, numberAt, ONE, readNumber, scanNumber, type SvgNumber, ZERO } from './svg-number.js'\nimport { MAX_SVG_COORDINATE, MAX_SVG_DASHES } from './limits.js'\nimport { refuse } from './svg-refusal.js'\n\nexport type Colour = { readonly kind: 'colour'; readonly hex: string } | { readonly kind: 'current' }\nexport type Paint =\n { readonly kind: 'none' } | Colour | { readonly kind: 'url'; readonly id: string; readonly fallback: Colour | { readonly kind: 'none' } | undefined }\n\n/** A kept property's value, as its grammar read it. */\nexport type Value =\n | { readonly type: 'paint'; readonly paint: Paint }\n | { readonly type: 'colour'; readonly colour: Colour }\n | { readonly type: 'number'; readonly number: SvgNumber }\n | { readonly type: 'keyword'; readonly keyword: string }\n | { readonly type: 'dashes'; readonly dashes: readonly SvgNumber[] | 'none' }\n | { readonly type: 'clip'; readonly id: string | undefined }\n\n/** `inherit` on a property that inherits anyway: it wins the cascade and writes nothing. */\nexport const INHERIT = 'inherit'\n\nconst KEYWORDS: { readonly [P in Property]?: readonly string[] } = {\n 'fill-rule': ['nonzero', 'evenodd'],\n 'clip-rule': ['nonzero', 'evenodd'],\n 'stroke-linecap': ['butt', 'round', 'square'],\n 'stroke-linejoin': ['miter', 'round', 'bevel'],\n display: ['inline', 'block', 'none'],\n visibility: ['visible'],\n 'vector-effect': ['none'],\n}\n\n/** Why a keyword the format knows of is refused, where it is not merely unknown, and what to do. */\nconst REFUSED_KEYWORDS: { readonly [keyword: string]: { readonly why: string; readonly advice: string } } = {\n arcs: { why: 'a line join svg-to-pdfkit does not draw', advice: 'use miter, round or bevel' },\n 'miter-clip': { why: 'a line join svg-to-pdfkit does not draw', advice: 'use miter, round or bevel' },\n hidden: { why: 'hidden', advice: 'remove what is hidden, or show it' },\n collapse: { why: 'hidden', advice: 'remove what is hidden, or show it' },\n 'non-scaling-stroke': { why: 'a stroke whose width depends on the box it is drawn in', advice: 'expand the stroke' },\n}\n\n/** A property's value, `INHERIT`, or a refusal naming `where`. */\nexport function readProperty(property: Property, text: string, where: string): Value | typeof INHERIT {\n const value = text.trim()\n const lower = value.toLowerCase()\n if (lower === 'inherit') {\n if (!INHERITED.has(property)) refuse('unsupported', `${where} inherits a property that does not inherit`, 'give it its value')\n return INHERIT\n }\n if (['initial', 'unset', 'revert', 'revert-layer'].includes(lower)) refuse('unsupported', `${where} is a CSS-wide keyword`, 'give it its value')\n switch (property) {\n case 'fill':\n case 'stroke':\n return { type: 'paint', paint: readPaint(value, where) }\n case 'stop-color':\n return { type: 'colour', colour: readColour(value, where) }\n case 'color': {\n const colour = readColour(value, where)\n // `color: currentColor` is the colour inherited (CSS Color 4, 6.4).\n return colour.kind === 'current' ? INHERIT : { type: 'colour', colour }\n }\n case 'fill-opacity':\n case 'stroke-opacity':\n case 'opacity':\n case 'stop-opacity':\n return { type: 'number', number: readOpacity(value, where) }\n case 'stroke-width':\n return { type: 'number', number: nonNegative(readLength(value, where, false), where) }\n case 'stroke-dashoffset':\n return { type: 'number', number: readLength(value, where, false) }\n case 'stroke-miterlimit': {\n const limit = readNumber(value, where)\n if (limit.value < 1) refuse('out-of-range', `${where} is under 1`, 'give it 1 or more')\n return { type: 'number', number: limit }\n }\n case 'stroke-dasharray':\n return { type: 'dashes', dashes: readDashes(value, where) }\n case 'clip-path': {\n if (lower === 'none') return { type: 'clip', id: undefined }\n const { id, rest } = readUrl(value, where)\n // A clip path has no fallback: what follows its url is not a clip-path a browser reads.\n if (rest !== '') refuse('unsupported', `${where} is not none or url(#id)`, 'write it as none or url(#id)')\n return { type: 'clip', id }\n }\n default:\n return { type: 'keyword', keyword: readKeyword(property, lower, where) }\n }\n}\n\nfunction readKeyword(property: Property, lower: string, where: string): string {\n if ((KEYWORDS[property] ?? []).includes(lower)) return lower\n const refused = REFUSED_KEYWORDS[lower]\n if (refused !== undefined) refuse('unsupported', `${where} is ${refused.why}`, refused.advice)\n return refuse('unsupported', `${where} is not a value of ${property} this format reads`)\n}\n\nfunction nonNegative(n: SvgNumber, where: string): SvgNumber {\n if (n.value < 0) refuse('out-of-range', `${where} is negative`, 'give it zero or more')\n return n\n}\n\n/** An opacity: a number or a percentage, clamped to 0..1 as SVG clamps it. */\nexport function readOpacity(text: string, where: string): SvgNumber {\n const trimmed = text.trim()\n const n = trimmed.endsWith('%') ? hundredth(readNumber(trimmed.slice(0, -1), where)) : readNumber(trimmed, where)\n return clamp(n, ZERO, ONE)\n}\n\n/** Each unit and the user units it is, at CSS's 96 to the inch, as svg-to-pdfkit converts it. */\nconst UNITS: ReadonlyMap<string, number> = new Map([\n ['', 1],\n ['px', 1],\n ['pt', 96 / 72],\n ['pc', 96 / 6],\n ['mm', 96 / 25.4],\n ['cm', 96 / 2.54],\n ['in', 96],\n])\nconst RELATIVE_UNITS: ReadonlySet<string> = new Set(['em', 'ex', 'rem', 'ch', 'vw', 'vh', 'vmin', 'vmax', 'cap', 'ic', 'lh', 'rlh', 'q'])\n\n/**\n * A length in user units. A percentage is a hundredth where `percent`\n * allows one -- a stop's offset, a gradient's coordinates in its box -- and\n * refused elsewhere; a unit relative to a font or a viewport is refused,\n * since a drawing has neither.\n */\nexport function readLength(text: string, where: string, percent: boolean): SvgNumber {\n const trimmed = text.trim()\n const end = scanNumber(trimmed, 0)\n if (end <= 0) refuse('unsupported', `${where} is not a length`, LENGTH_ADVICE)\n const unit = trimmed.slice(end).toLowerCase()\n const n = numberAt(trimmed, 0, end, where)\n if (unit === '%') {\n if (!percent)\n refuse('unsupported', `${where} is a percentage, which this format reads only for an offset, an opacity and a gradient in its box`, LENGTH_ADVICE)\n return hundredth(n)\n }\n if (RELATIVE_UNITS.has(unit)) refuse('unsupported', `${where} is in a unit relative to a font or a viewport, which a drawing has neither of`, LENGTH_ADVICE)\n const factor = UNITS.get(unit)\n if (factor === undefined) refuse('unsupported', `${where} is not a length`, LENGTH_ADVICE)\n return factor === 1 ? n : checked(float(n.value * factor), where)\n}\n\n/** What to do about a length this format does not read. */\nconst LENGTH_ADVICE = 'write it in user units, px, pt, pc, mm, cm or in'\n/** What to do about a list of numbers this format does not read. */\nconst NUMBERS_ADVICE = 'write it as numbers separated by spaces or commas'\n\n/** A number computed from one read, refused as `out-of-range` when converting its unit took it past the bound. */\nfunction checked(n: SvgNumber, where: string): SvgNumber {\n if (!(Math.abs(n.value) <= MAX_SVG_COORDINATE)) refuse('out-of-range', `${where} holds a number past ${MAX_SVG_COORDINATE}`)\n return n\n}\n\n/**\n * Numbers separated as SVG separates them in a list -- whitespace, or a\n * comma with whitespace around it -- and also by nothing where a sign or a\n * point starts the next (`10-20`). A comma with no number after it is\n * refused, as a leading one is.\n */\nexport function readNumbers(text: string, where: string): SvgNumber[] {\n const numbers: SvgNumber[] = []\n let i = skipSpace(text, 0)\n while (i < text.length) {\n const end = scanNumber(text, i)\n if (end < 0) refuse('unsupported', `${where} is not a list of numbers`, NUMBERS_ADVICE)\n numbers.push(numberAt(text, i, end, where))\n i = skipSpace(text, end)\n if (text.charCodeAt(i) === 0x2c) {\n i = skipSpace(text, i + 1)\n if (i >= text.length || scanNumber(text, i) < 0) refuse('unsupported', `${where} is not a list of numbers`, NUMBERS_ADVICE)\n }\n }\n return numbers\n}\n\nexport function isSpace(code: number): boolean {\n return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d\n}\n\nexport function skipSpace(text: string, at: number): number {\n let i = at\n while (isSpace(text.charCodeAt(i))) i += 1\n return i\n}\n\n/** A dash array: `none`, or up to `MAX_SVG_DASHES` non-negative lengths, an odd list doubled as SVG doubles it, and all zeros the solid line SVG draws for them. */\nfunction readDashes(text: string, where: string): readonly SvgNumber[] | 'none' {\n if (text.toLowerCase() === 'none') return 'none'\n const parts = text.split(/\\s*,\\s*|\\s+/)\n if (parts.some((part) => part === '')) refuse('unsupported', `${where} is not a dash array`, NUMBERS_ADVICE)\n // Counted before a part is read, so that a mebibyte of dashes is not read to be refused.\n if (parts.length * (parts.length % 2 === 1 ? 2 : 1) > MAX_SVG_DASHES)\n refuse('too-large', `${where} has more than ${MAX_SVG_DASHES} dashes`, `give it at most ${MAX_SVG_DASHES} entries`)\n const dashes = parts.map((part) => nonNegative(readLength(part, where, false), where))\n const doubled = dashes.length % 2 === 1 ? [...dashes, ...dashes] : dashes\n return doubled.every((dash) => dash.value === 0) ? 'none' : doubled\n}\n\n/** What may stand between `#` and the end of a reference: an id's own characters, digits first allowed, as Canva writes them. */\nconst ID = /^[A-Za-z0-9_.:-]+$/\n\n/** What a URL written without quotes cannot hold. */\nfunction endsUnquoted(code: number): boolean {\n return isSpace(code) || code === 0x22 || code === 0x27 || code === 0x28 || code === 0x29\n}\n\n/**\n * A `url(#id)`, quoted or not, naming something in the file, and what\n * follows it. Read by hand, one pass, rather than by a pattern whose\n * whitespace on either side of an empty address a regular expression would\n * try every split of.\n */\nfunction readUrl(text: string, where: string): { readonly id: string; readonly rest: string } {\n const notUrl = (): never => refuse('unsupported', `${where} is not none or url(#id)`, 'write it as none or url(#id)')\n if (text.slice(0, 4).toLowerCase() !== 'url(') notUrl()\n let i = skipSpace(text, 4)\n const quote = text.charCodeAt(i)\n let target: string\n if (quote === 0x22 || quote === 0x27) {\n const close = text.indexOf(text.charAt(i), i + 1)\n if (close < 0) notUrl()\n target = text.slice(i + 1, close)\n i = close + 1\n } else {\n const start = i\n while (i < text.length && !endsUnquoted(text.charCodeAt(i))) i += 1\n target = text.slice(start, i)\n }\n i = skipSpace(text, i)\n if (text.charCodeAt(i) !== 0x29) notUrl()\n if (!target.startsWith('#')) refuse('reference', `${where} refers to something outside the file`, 'put what it names into the file')\n const id = target.slice(1)\n if (!ID.test(id)) refuse('reference', `${where} names an id this format does not read`, 'give what it names an id of ASCII letters, digits, _, ., : and -')\n return { id, rest: text.slice(i + 1).trim() }\n}\n\n/** A paint: `none`, a colour, `currentColor`, or a gradient in the file with an optional fallback. */\nfunction readPaint(text: string, where: string): Paint {\n if (text.toLowerCase() === 'none') return { kind: 'none' }\n if (/^url\\(/i.test(text)) {\n const { id, rest } = readUrl(text, where)\n if (rest === '') return { kind: 'url', id, fallback: undefined }\n return { kind: 'url', id, fallback: rest.toLowerCase() === 'none' ? { kind: 'none' } : readColour(rest, where) }\n }\n return readColour(text, where)\n}\n\nconst HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/\nconst RGB = /^rgb\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)$/\n// Each number written one way only: `\\d*\\.?\\d+` splits a run of digits every way it can, and tries them all.\nconst RGB_PERCENT = /^rgb\\(\\s*(\\d+(?:\\.\\d+)?|\\.\\d+)%\\s*,\\s*(\\d+(?:\\.\\d+)?|\\.\\d+)%\\s*,\\s*(\\d+(?:\\.\\d+)?|\\.\\d+)%\\s*\\)$/\n\n/**\n * A colour: `#rgb`, `#rrggbb`, `rgb()` of integers or of percentages, a CSS\n * colour name, or `currentColor`. A colour with an alpha -- `#rgba`,\n * `rgba()`, `hsla()`, `transparent` -- would have to become an opacity,\n * which is a second decision, and is refused with `hsl()` and the system\n * colours (0030).\n */\nfunction readColour(text: string, where: string): Colour {\n const lower = text.trim().toLowerCase()\n if (lower === 'currentcolor') return { kind: 'current' }\n if (HEX.test(lower)) return { kind: 'colour', hex: lower.length === 4 ? `#${[...lower.slice(1)].map((digit) => digit + digit).join('')}` : lower }\n const named = SVG_NAMED_COLOURS.get(lower)\n if (named !== undefined) return { kind: 'colour', hex: named }\n const integers = RGB.exec(lower)\n if (integers !== null) return { kind: 'colour', hex: hexOf(integers.slice(1).map((channel) => Math.min(255, Number(channel)))) }\n const percentages = RGB_PERCENT.exec(lower)\n if (percentages !== null)\n return { kind: 'colour', hex: hexOf(percentages.slice(1).map((channel) => Math.round((Math.min(100, Number(channel)) * 255) / 100))) }\n return refuse(\n 'unsupported',\n `${where} is a colour this format does not read: one with an alpha, hsl(), transparent or a system colour`,\n 'write it as #rrggbb, with fill-opacity, stroke-opacity or stop-opacity for its alpha',\n )\n}\n\nfunction hexOf(channels: readonly number[]): string {\n return `#${channels.map((channel) => channel.toString(16).padStart(2, '0')).join('')}`\n}\n","/**\n * The CSS an SVG may hold, in a `style` attribute or a `<style>`, and the\n * cascade that flattens it into one value per property (0030).\n *\n * The subset is svg-to-pdfkit's and Illustrator's: a type, a class, an id,\n * a compound of those, comma lists of them, and declarations of the kept\n * properties. A combinator, an attribute selector, a pseudo-class, `*`, a\n * namespace, an at-rule, `!important`, an escape or a custom property is\n * refused, never ignored as a browser ignores what it cannot parse: what a\n * browser ignores, and what it does not, is a second grammar this one would\n * have to match exactly. A comment separates, as CSS says, and is never\n * deleted in place: `fi/**\\/ll` is not `fill`.\n *\n * Matching is indexed. Each rule sits in one bucket -- its first id, else\n * its first class, else its type -- so an element looks only at the rules\n * that could match it, and `MAX_SVG_RULES`, counted in simple selectors,\n * bounds what it compares against. A rule's declarations are read once, not\n * once per element it matches, and the rules one combination of type, id\n * and classes matches are merged once for every element of it. Elements\n * that each hold a combination of their own defeat that, so the work of\n * every merge -- each rule compared, each declaration merged -- is counted,\n * and bounded by `MAX_SVG_CASCADE`.\n */\nimport { MAX_SVG_CASCADE, MAX_SVG_RULES } from './limits.js'\nimport { type Property, propertyFate } from './svg-allow.js'\nimport { CSS_ADVICE, refuse, type Removals, shown } from './svg-refusal.js'\nimport { hasNonAscii, type Located, type SvgElement } from './svg-tree.js'\nimport { INHERIT, readProperty, type Value } from './svg-values.js'\n\nexport interface Declared {\n readonly value: Value | typeof INHERIT\n readonly where: string\n}\n\nexport type Declarations = ReadonlyMap<Property, Declared>\n\ninterface Rule {\n readonly type: string | undefined\n readonly classes: ReadonlySet<string>\n readonly ids: ReadonlySet<string>\n readonly specificity: number\n readonly order: number\n rank: number\n readonly declarations: Declarations\n}\n\n/** The geometry SVG 2 lets CSS set, which svg-to-pdfkit reads from attributes alone. */\nconst GEOMETRY_PROPERTIES: ReadonlySet<string> = new Set(['x', 'y', 'width', 'height', 'r', 'rx', 'ry', 'cx', 'cy', 'd', 'transform'])\n\n/** The text with each comment replaced by a space, refused when it holds an escape or an unclosed comment or string. */\nfunction uncommented(text: string, where: string): string {\n if (text.includes('\\\\')) refuse('unsupported', `${where} holds a CSS escape`, CSS_ADVICE)\n let out = ''\n let quote: string | undefined\n for (let i = 0; i < text.length; i += 1) {\n const character = text.charAt(i)\n if (quote !== undefined) {\n if (character === '\\n') refuse('unsupported', `${where} holds a CSS string that is not closed`, CSS_ADVICE)\n if (character === quote) quote = undefined\n out += character\n } else if (character === '/' && text.charAt(i + 1) === '*') {\n const close = text.indexOf('*/', i + 2)\n if (close < 0) refuse('unsupported', `${where} holds a CSS comment that is not closed`, CSS_ADVICE)\n out += ' '\n i = close + 1\n } else {\n if (character === '\"' || character === \"'\") quote = character\n out += character\n }\n }\n if (quote !== undefined) refuse('unsupported', `${where} holds a CSS string that is not closed`, CSS_ADVICE)\n return out\n}\n\n/** Where each `separator` falls outside strings and parentheses, splitting the text there. */\nfunction splitOutside(text: string, separator: string): string[] {\n const parts: string[] = []\n let quote: string | undefined\n let depth = 0\n let from = 0\n for (let i = 0; i < text.length; i += 1) {\n const character = text.charAt(i)\n if (quote !== undefined) {\n if (character === quote) quote = undefined\n } else if (character === '\"' || character === \"'\") quote = character\n else if (character === '(') depth += 1\n else if (character === ')') depth -= 1\n else if (character === separator && depth === 0) {\n parts.push(text.slice(from, i))\n from = i + 1\n }\n }\n parts.push(text.slice(from))\n return parts\n}\n\nconst PROPERTY_NAME = /^-{0,2}[a-z_][a-z0-9_-]*$/\n\n/** A declaration block's kept properties, each read by its grammar; what is removed is listed, what is refused is refused. */\nfunction declarations(block: string, where: string, removals: Removals): Map<Property, Declared> {\n const declared = new Map<Property, Declared>()\n for (const part of splitOutside(block, ';')) {\n if (part.trim() === '') continue\n const colon = part.indexOf(':')\n const name = (colon < 0 ? part : part.slice(0, colon)).trim().toLowerCase()\n const value = colon < 0 ? '' : part.slice(colon + 1).trim()\n if (!PROPERTY_NAME.test(name) || value === '') refuse('unsupported', `${where} holds a CSS declaration this format does not read`, CSS_ADVICE)\n if (value.includes('!')) refuse('unsupported', `${where} holds !important, which this format does not read`, CSS_ADVICE)\n const fate = propertyFate(name, value.toLowerCase().replace(/\\s+/g, ' '))\n const at = `${where}: ${shown(name, 'a property')}`\n if (fate === undefined) {\n if (name.startsWith('--')) refuse('unsupported', `${where} holds a custom property, which this format does not read`, CSS_ADVICE)\n if (GEOMETRY_PROPERTIES.has(name))\n refuse('unsupported', `${at} is geometry in CSS, which this format reads from attributes alone`, 'write it as an attribute')\n refuse('unsupported', `${at} is not a property this format draws as a browser draws it`)\n }\n if (fate.fate === 'removed') removals.add('property', name)\n else if (fate.fate === 'refused') refuse('unsupported', `${at} is not drawn by this format`, fate.advice)\n else {\n if (hasNonAscii(value)) refuse('encoding', `${at} holds a byte past ASCII`)\n declared.set(fate.property, { value: readProperty(fate.property, value, at), where: at })\n }\n }\n return declared\n}\n\n/** An element's `style` attribute, read as a declaration block. */\nexport function readDeclarations(style: Located, removals: Removals): Declarations {\n return declarations(uncommented(style.value, style.where), style.where, removals)\n}\n\nconst IDENTIFIER = '-?[A-Za-z_][A-Za-z0-9_-]*'\nconst COMPOUND = new RegExp(`^(${IDENTIFIER})?((?:[.#]${IDENTIFIER})*)$`)\n\nexport class Stylesheet {\n private readonly byId = new Map<string, Rule[]>()\n private readonly byClass = new Map<string, Rule[]>()\n private readonly byType = new Map<string, Rule[]>()\n /** Every class a rule names, in any part of a compound. */\n private readonly named = new Set<string>()\n\n constructor(styles: readonly Located[], removals: Removals) {\n const rules: Rule[] = []\n let simple = 0\n for (const style of styles) {\n const text = uncommented(style.value, style.where)\n if (text.includes('@')) refuse('unsupported', `${style.where} holds an at-rule, which this format does not read`, CSS_ADVICE)\n if (text.includes('<!--') || text.includes('-->')) refuse('unsupported', `${style.where} holds CSS markup this format does not read`, CSS_ADVICE)\n let at = 0\n for (;;) {\n const open = text.indexOf('{', at)\n if (open < 0) {\n if (text.slice(at).trim() !== '') refuse('unsupported', `${style.where} holds CSS outside a rule`, CSS_ADVICE)\n break\n }\n const close = text.indexOf('}', open)\n if (close < 0 || text.slice(open + 1, close).includes('{')) refuse('unsupported', `${style.where} holds a CSS rule that is not closed`, CSS_ADVICE)\n const block = declarations(text.slice(open + 1, close), style.where, removals)\n for (const selector of text.slice(at, open).split(',')) {\n const rule = this.rule(selector.trim(), style.where, block, rules.length)\n simple += (rule.type === undefined ? 0 : 1) + rule.parts\n if (simple > MAX_SVG_RULES) refuse('too-large', `the stylesheets hold more than ${MAX_SVG_RULES} selectors`, CSS_ADVICE)\n rules.push(rule.rule)\n }\n at = close + 1\n }\n }\n rules.sort((a, b) => a.specificity - b.specificity || a.order - b.order)\n rules.forEach((rule, rank) => {\n rule.rank = rank\n const [id] = rule.ids\n const [name] = rule.classes\n for (const name of rule.classes) this.named.add(name)\n if (id !== undefined) bucket(this.byId, id).push(rule)\n else if (name !== undefined) bucket(this.byClass, name).push(rule)\n else bucket(this.byType, rule.type as string).push(rule)\n })\n }\n\n private rule(\n selector: string,\n where: string,\n declared: Declarations,\n order: number,\n ): { readonly rule: Rule; readonly type: string | undefined; readonly parts: number } {\n if (hasNonAscii(selector)) refuse('encoding', `${where} holds a selector with a byte past ASCII`)\n const match = COMPOUND.exec(selector)\n if (selector === '' || match === null)\n refuse('unsupported', `${where} holds a selector this format does not read: a type, a class, an id or a compound of them alone`, CSS_ADVICE)\n const [, type, rest = ''] = match\n const parts = rest.match(/[.#][^.#]+/g) ?? []\n const classes = parts.filter((part) => part.startsWith('.')).map((part) => part.slice(1))\n const ids = parts.filter((part) => part.startsWith('#')).map((part) => part.slice(1))\n const specificity = ids.length * 1_000_000 + classes.length * 1_000 + (type === undefined ? 0 : 1)\n return {\n rule: { type, classes: new Set(classes), ids: new Set(ids), specificity, order, rank: 0, declarations: declared },\n type,\n parts: parts.length,\n }\n }\n\n /**\n * What every rule that matches the element declares, merged in cascade\n * order. Which rules match depends only on the element's type, on its id\n * when a rule names it and on the classes rules name, so the merge is\n * made once for each such combination: ten thousand elements of one\n * class matched by every rule are merged once, not ten thousand times.\n */\n matches(element: SvgElement): Declarations {\n const type = element.link ? 'a' : element.name\n const id = element.id !== undefined && this.byId.has(element.id) ? element.id : undefined\n const classes = [...new Set(element.classes)].filter((name) => this.named.has(name)).sort()\n const key = `${type} ${id ?? ''} ${classes.join(' ')}`\n const cached = this.merged.get(key)\n if (cached !== undefined) return cached\n const held = new Set(classes)\n const candidates: Rule[] = [\n ...(id === undefined ? [] : (this.byId.get(id) ?? [])),\n ...classes.flatMap((name) => this.byClass.get(name) ?? []),\n ...(this.byType.get(type) ?? []),\n ]\n this.spend(candidates.length)\n const matching = candidates\n .filter(\n (rule) =>\n (rule.type === undefined || rule.type === type) &&\n [...rule.ids].every((ruleId) => ruleId === id) &&\n [...rule.classes].every((name) => held.has(name)),\n )\n .sort((a, b) => a.rank - b.rank)\n this.spend(matching.reduce((sum, rule) => sum + rule.declarations.size, 0))\n const merged = new Map<Property, Declared>()\n for (const rule of matching) for (const [property, value] of rule.declarations) merged.set(property, value)\n this.merged.set(key, merged)\n return merged\n }\n\n private readonly merged = new Map<string, Declarations>()\n /** The rules compared and the declarations merged so far, in all merges. */\n private work = 0\n\n /** `units` more of the work `MAX_SVG_CASCADE` bounds, refused before it is done when it would pass the bound. */\n private spend(units: number): void {\n this.work += units\n if (this.work > MAX_SVG_CASCADE) refuse('too-large', `the stylesheets would be matched against its elements more than ${MAX_SVG_CASCADE} times`, CSS_ADVICE)\n }\n}\n\nfunction bucket(index: Map<string, Rule[]>, key: string): Rule[] {\n let rules = index.get(key)\n if (rules === undefined) {\n rules = []\n index.set(key, rules)\n }\n return rules\n}\n\n/**\n * Each element's kept properties after the cascade, lowest to highest: its\n * presentation attributes, then the stylesheets' rules by specificity and\n * order, then its `style` attribute -- CSS's cascade for SVG. One value per\n * property; `INHERIT` where the winner said to inherit.\n */\nexport function cascade(element: SvgElement, sheet: Stylesheet, removals: Removals): Map<Property, Declared> {\n const specified = new Map<Property, Declared>()\n for (const [property, { value, where }] of element.presentation) specified.set(property, { value: readProperty(property, value, where), where })\n for (const [property, value] of sheet.matches(element)) specified.set(property, value)\n if (element.style !== undefined) for (const [property, value] of readDeclarations(element.style, removals)) specified.set(property, value)\n return specified\n}\n","/**\n * Each element's properties after the cascade and inheritance: what the\n * cleaner writes on it, and what it paints with, which the costs are\n * counted from (0030).\n *\n * The cleaner does not push values down the tree: it writes each element's\n * own values and leaves inheritance to the converter, which inherits as SVG\n * says (`source.js:25-66`). One exception: `currentColor` is written as the\n * colour it stands for, and an inherited `currentColor` is the keyword, not\n * the colour, so a child that sets another `color` paints in its own (CSS\n * Color 4, 6.4). svg-to-pdfkit inherits the colour its parent resolved, as\n * SVG 1.1 did; so where a child's colour differs, the cleaner writes the\n * child's paint on the child, and both readers draw what a browser draws.\n */\nimport { INHERITED, type Property, WRITTEN_PROPERTIES, type WrittenProperty } from './svg-allow.js'\nimport { writeNumber } from './svg-number.js'\nimport { cascade, type Declared, type Stylesheet } from './svg-style.js'\nimport type { SvgElement } from './svg-tree.js'\nimport { type Colour, INHERIT, type Paint, type Value } from './svg-values.js'\nimport type { Removals } from './svg-refusal.js'\n\n/** A reference to a gradient or a clip path, by the id the file gave it. */\nexport interface Reference {\n readonly id: string\n readonly where: string\n}\n\n/** A property as it is written: its text, or a reference written with the id its target is renamed to, and a fallback colour. */\nexport type WrittenValue = string | { readonly reference: Reference; readonly fallback: string | undefined }\n\nexport interface Computed {\n readonly fill: Paint\n readonly fillOpacity: number\n readonly stroke: Paint\n readonly strokeOpacity: number\n readonly strokeWidth: number\n readonly dashes: readonly number[] | 'none'\n /** The colour `currentColor` stands for here. */\n readonly color: string\n /** How a clip path's shapes clip: inherited, and written on a clip path, so that its clip never rests on `defs`. */\n readonly clipRule: string\n /** The colour an inherited `currentColor` fill or stroke is written as above this element, when it is one. */\n readonly fillAs: string | undefined\n readonly strokeAs: string | undefined\n}\n\nexport interface Styled {\n readonly computed: Computed\n /** The kept properties written on the element, in the canonical order. */\n readonly written: ReadonlyArray<readonly [WrittenProperty, WrittenValue]>\n /** `display: none`: the element and everything in it is removed. */\n readonly hidden: boolean\n /** The element's own opacity, which is not inherited. */\n readonly opacity: number\n /** A stop's own opacity, which is not inherited either. */\n readonly stopOpacity: number\n readonly clip: Reference | undefined\n}\n\nconst INITIAL: Computed = {\n fill: { kind: 'colour', hex: '#000000' },\n fillOpacity: 1,\n stroke: { kind: 'none' },\n strokeOpacity: 1,\n strokeWidth: 1,\n dashes: 'none',\n color: '#000000',\n clipRule: 'nonzero',\n fillAs: undefined,\n strokeAs: undefined,\n}\n\n/** Every element's styled properties, the tree walked from the root, its parent's computed values in hand. */\nexport function styleTree(root: SvgElement, sheet: Stylesheet, removals: Removals): Map<SvgElement, Styled> {\n const styled = new Map<SvgElement, Styled>()\n const walk = (element: SvgElement, parent: Computed): void => {\n const own = style(cascade(element, sheet, removals), parent)\n styled.set(element, own)\n for (const child of element.children) walk(child, own.computed)\n }\n walk(root, INITIAL)\n return styled\n}\n\nfunction colourOf(colour: Colour, color: string): string {\n return colour.kind === 'current' ? color : colour.hex\n}\n\nfunction numberOf(value: Value | undefined, otherwise: number): number {\n return value?.type === 'number' ? value.number.value : otherwise\n}\n\nfunction own(specified: ReadonlyMap<Property, Declared>, property: Property): Value | undefined {\n const declared = specified.get(property)\n return declared === undefined || declared.value === INHERIT ? undefined : declared.value\n}\n\nfunction style(specified: ReadonlyMap<Property, Declared>, parent: Computed): Styled {\n const colorValue = own(specified, 'color')\n const color = colorValue?.type === 'colour' ? colourOf(colorValue.colour, parent.color) : parent.color\n const written: Array<readonly [WrittenProperty, WrittenValue]> = []\n const paints = { fill: { paint: parent.fill, as: parent.fillAs }, stroke: { paint: parent.stroke, as: parent.strokeAs } }\n for (const property of WRITTEN_PROPERTIES) {\n const declared = specified.get(property)\n const value = own(specified, property)\n if (property === 'fill' || property === 'stroke') {\n const painted = paints[property]\n if (value?.type === 'paint') {\n painted.paint = value.paint\n painted.as = value.paint.kind === 'current' ? color : undefined\n written.push([property, writePaint(value.paint, color, declared?.where ?? '')])\n } else if (painted.paint.kind === 'current' && painted.as !== color) {\n // An inherited currentColor, under a colour of this element's own.\n painted.as = color\n written.push([property, color])\n }\n } else if (value !== undefined && value.type !== 'paint') written.push([property, writeValue(value, color, declared?.where ?? '')])\n }\n const inherited = (property: Property, from: number): number => (INHERITED.has(property) ? numberOf(own(specified, property), from) : from)\n const dashes = own(specified, 'stroke-dasharray')\n const clip = own(specified, 'clip-path')\n const display = own(specified, 'display')\n const clipRule = own(specified, 'clip-rule')\n return {\n computed: {\n fill: paints.fill.paint,\n fillOpacity: inherited('fill-opacity', parent.fillOpacity),\n stroke: paints.stroke.paint,\n strokeOpacity: inherited('stroke-opacity', parent.strokeOpacity),\n strokeWidth: inherited('stroke-width', parent.strokeWidth),\n dashes: dashes?.type === 'dashes' ? (dashes.dashes === 'none' ? 'none' : dashes.dashes.map((dash) => dash.value)) : parent.dashes,\n color,\n clipRule: clipRule?.type === 'keyword' ? clipRule.keyword : parent.clipRule,\n fillAs: paints.fill.as,\n strokeAs: paints.stroke.as,\n },\n written,\n hidden: display?.type === 'keyword' && display.keyword === 'none',\n opacity: numberOf(own(specified, 'opacity'), 1),\n stopOpacity: numberOf(own(specified, 'stop-opacity'), 1),\n clip: clip?.type === 'clip' && clip.id !== undefined ? { id: clip.id, where: specified.get('clip-path')?.where ?? '' } : undefined,\n }\n}\n\nfunction writePaint(paint: Paint, color: string, where: string): WrittenValue {\n switch (paint.kind) {\n case 'none':\n return 'none'\n case 'url':\n return {\n reference: { id: paint.id, where },\n fallback: paint.fallback === undefined ? undefined : paint.fallback.kind === 'none' ? 'none' : colourOf(paint.fallback, color),\n }\n default:\n return colourOf(paint, color)\n }\n}\n\n/** Every value but a paint, which only fill and stroke take. */\nfunction writeValue(value: Exclude<Value, { readonly type: 'paint' }>, color: string, where: string): WrittenValue {\n switch (value.type) {\n case 'colour':\n return colourOf(value.colour, color)\n case 'number':\n return writeNumber(value.number)\n case 'keyword':\n return value.keyword\n case 'dashes':\n return value.dashes === 'none' ? 'none' : value.dashes.map(writeNumber).join(' ')\n default:\n return value.id === undefined ? 'none' : { reference: { id: value.id, where }, fallback: undefined }\n }\n}\n","/**\n * Transforms: an element's `transform` or a gradient's `gradientTransform`,\n * read by SVG 1.1's transform-list grammar, composed into one matrix and\n * written as `matrix(a b c d e f)`.\n *\n * The cleaner also composes the matrices from the root down to each\n * element and refuses a drawing where any entry of one passes\n * `MAX_SVG_COORDINATE`, or of its inverse: svg-to-pdfkit inverts the matrix\n * an element is drawn under to find the page's box in its user space for\n * every clip and every group opacity (`getPageBBox`, `source.js:536`), so a\n * matrix that shrinks the drawing a millionfold twice over gives that box\n * corners past the 10^21 at which PDFKit throws. With every point under the\n * bound too, every coordinate the converter computes stays far below it\n * (limits.ts says what was measured).\n *\n * CSS's transform functions -- units on the arguments, `rotate(30deg)`,\n * `translateX` -- are not SVG's, and svg-to-pdfkit reads none of them, so\n * they are refused as not a transform.\n */\nimport { MAX_SVG_COORDINATE } from './limits.js'\nimport { float, readNumber, writeNumber } from './svg-number.js'\nimport { refuse } from './svg-refusal.js'\nimport { readNumbers, skipSpace } from './svg-values.js'\n\nexport type Matrix = readonly [number, number, number, number, number, number]\n\n/** What to do about a transform this format does not read. */\nconst TRANSFORM_ADVICE = \"write it with SVG's matrix, translate, scale, rotate, skewX and skewY\"\n\nexport const IDENTITY: Matrix = [1, 0, 0, 1, 0, 0]\n\n/** `a` then `b`: the matrix that maps through `b` first, as SVG composes a transform list left to right. */\nexport function multiply(a: Matrix, b: Matrix): Matrix {\n return [\n a[0] * b[0] + a[2] * b[1],\n a[1] * b[0] + a[3] * b[1],\n a[0] * b[2] + a[2] * b[3],\n a[1] * b[2] + a[3] * b[3],\n a[0] * b[4] + a[2] * b[5] + a[4],\n a[1] * b[4] + a[3] * b[5] + a[5],\n ]\n}\n\nconst FUNCTION = /^(matrix|translate|scale|rotate|skewX|skewY)\\s*\\(([^()]*)\\)/\n\nfunction radians(degrees: number): number {\n return (degrees * Math.PI) / 180\n}\n\n/** One transform function's matrix, from its arguments, or undefined when it has the wrong number of them. */\nfunction functionMatrix(name: string, a: readonly number[]): Matrix | undefined {\n const [p = 0, q = 0, r = 0] = a\n switch (name) {\n case 'matrix':\n return a.length === 6 ? (a as unknown as Matrix) : undefined\n case 'translate':\n return a.length === 1 || a.length === 2 ? [1, 0, 0, 1, p, q] : undefined\n case 'scale':\n return a.length === 1 || a.length === 2 ? [p, 0, 0, a.length === 2 ? q : p, 0, 0] : undefined\n case 'rotate': {\n if (a.length !== 1 && a.length !== 3) return undefined\n const cos = Math.cos(radians(p))\n const sin = Math.sin(radians(p))\n const turn: Matrix = [cos, sin, -sin, cos, 0, 0]\n return a.length === 1 ? turn : multiply(multiply([1, 0, 0, 1, q, r], turn), [1, 0, 0, 1, -q, -r])\n }\n case 'skewX':\n return a.length === 1 ? [1, 0, Math.tan(radians(p)), 1, 0, 0] : undefined\n default:\n return a.length === 1 ? [1, Math.tan(radians(p)), 0, 1, 0, 0] : undefined\n }\n}\n\n/** A transform list composed into one matrix, written back as the cleaner writes it so that reading the written form again gives the same matrix. */\nexport function readTransform(text: string, where: string): Matrix {\n let matrix = IDENTITY\n let i = skipSpace(text, 0)\n while (i < text.length) {\n const match = FUNCTION.exec(text.slice(i))\n if (match === null) refuse('unsupported', `${where} is not a transform this format reads`, TRANSFORM_ADVICE)\n const [whole, name = '', args = ''] = match\n const step = functionMatrix(\n name,\n readNumbers(args, where).map((n) => n.value),\n )\n if (step === undefined) refuse('unsupported', `${where} gives ${name} the wrong number of arguments`, TRANSFORM_ADVICE)\n matrix = multiply(matrix, step)\n i = skipSpace(text, i + whole.length)\n if (text.charCodeAt(i) === 0x2c) {\n i = skipSpace(text, i + 1)\n if (i >= text.length) refuse('unsupported', `${where} is not a transform this format reads`, TRANSFORM_ADVICE)\n }\n }\n return written(matrix, where)\n}\n\n/**\n * The matrix each entry of which is what its written form reads back as,\n * so that a drawing is composed, bounded and counted from what is written.\n * A matrix that flattens the drawing to a line or a point is refused: it\n * draws nothing a reader can see, and a PDF reader may refuse its singular\n * matrix.\n */\nfunction written(matrix: Matrix, where: string): Matrix {\n const entries = matrix.map((entry) => readNumber(writeNumber(float(entry)), where).value) as unknown as Matrix\n if (entries[0] * entries[3] - entries[1] * entries[2] === 0)\n refuse('out-of-range', `${where} flattens what it transforms to nothing`, 'remove what it flattens, or give the transform an area')\n return entries\n}\n\nexport function isIdentity(matrix: Matrix): boolean {\n return matrix.every((entry, i) => entry === IDENTITY[i])\n}\n\n/** The `matrix(…)` an element's transform is written as; the identity is not written. */\nexport function writeMatrix(matrix: Matrix): string {\n return `matrix(${matrix.map((entry) => writeNumber(float(entry))).join(' ')})`\n}\n\n/** A box: left, top, right, bottom. */\nexport type Box = readonly [number, number, number, number]\n\n/** The least and the greatest each entry of a matrix may be. */\nexport interface Spread {\n readonly least: Matrix\n readonly greatest: Matrix\n}\n\n/**\n * The matrix a shape's gradient is drawn under -- the matrix `shape`, the\n * shape's box when the gradient is drawn in it, and the gradient's own\n * transform, composed, which PDFKit writes as the pattern's matrix after\n * its own (`source.js:1863-1866`) -- over every box the converter may\n * draw it in. The converter measures the box on the outline\n * (`source.js:867-890`), which lies inside the box the cleaner holds\n * (`svg-path.ts`), a curve's by its control points, but not at its corner:\n * so `box` stands for every box inside it. Each entry is linear in the\n * box's corner and size, across and down apart, and a box inside spans,\n * across, from a left edge at or right of `box`'s to a right edge at or\n * left of its; an entry is least and greatest, then, at one of nine boxes,\n * the whole width or none at either edge, across, and so down. Without a\n * box -- a gradient in user space -- the one matrix.\n */\nexport function spreadUnder(shape: Matrix, box: Box | undefined, gradient: Matrix): Spread {\n if (box === undefined) {\n const drawn = multiply(shape, gradient)\n return { least: drawn, greatest: drawn }\n }\n const [left, top, right, bottom] = box\n const across = [\n [0, left],\n [right - left, left],\n [0, right],\n ] as const\n const down = [\n [0, top],\n [bottom - top, top],\n [0, bottom],\n ] as const\n const least = [Infinity, Infinity, Infinity, Infinity, Infinity, Infinity]\n const greatest = [-Infinity, -Infinity, -Infinity, -Infinity, -Infinity, -Infinity]\n for (const [width, x] of across)\n for (const [height, y] of down) {\n const drawn = multiply(shape, multiply([width, 0, 0, height, x, y], gradient))\n for (let i = 0; i < 6; i += 1) {\n least[i] = Math.min(least[i] as number, drawn[i] as number)\n greatest[i] = Math.max(greatest[i] as number, drawn[i] as number)\n }\n }\n return { least: least as unknown as Matrix, greatest: greatest as unknown as Matrix }\n}\n\n/**\n * Where a shape's gradient is drawn, from the root (`spreadUnder`).\n * Refused as `out-of-range` when an entry could pass the bound: three\n * matrices each within it compose to a million cubed, and a group turned\n * and scaled a millionfold, painting a shape a million wide with a\n * gradient of the same transform, threw `unsupported number: -1.1e+21`\n * from inside PDFKit, page-wide in a landscape box 550 points wide; and a\n * gradient the cleaner's box of a curve held under the bound wrote 5 ×\n * 10^12 in the converter's.\n */\nexport function gradientUnder(shape: Matrix, box: Box | undefined, gradient: Matrix, where: string): Spread {\n const drawn = spreadUnder(shape, box, gradient)\n if (!bounded(drawn.least) || !bounded(drawn.greatest)) refuse('out-of-range', `${where} paints a gradient transformed past ${MAX_SVG_COORDINATE}`)\n return drawn\n}\n\n/** The inverse of a matrix `compose` has held to an area, as svg-to-pdfkit inverts one (`source.js:545-548`). */\nexport function inverse(matrix: Matrix): Matrix {\n const [a, b, c, d, e, f] = matrix\n const determinant = a * d - b * c\n return [d / determinant, -b / determinant, -c / determinant, a / determinant, (c * f - d * e) / determinant, (b * e - a * f) / determinant]\n}\n\n/** Whether every entry is a number of magnitude at most the bound. */\nfunction bounded(entries: readonly number[]): boolean {\n return entries.every((entry) => Math.abs(entry) <= MAX_SVG_COORDINATE)\n}\n\n/**\n * The composed matrix, refused as `out-of-range` when an entry of it, or of\n * the inverse of its linear part, passes the bound: a matrix that\n * magnifies past it, or shrinks past its reciprocal.\n */\nexport function compose(outer: Matrix, inner: Matrix, where: string): Matrix {\n const composed = multiply(outer, inner)\n if (!bounded(composed)) refuse('out-of-range', `${where} is transformed past ${MAX_SVG_COORDINATE}`)\n const [a, b, c, d] = composed\n const determinant = a * d - b * c\n if (!bounded([d / determinant, b / determinant, c / determinant, a / determinant]))\n refuse('out-of-range', `${where} shrinks what it transforms, or flattens it, past a factor of ${MAX_SVG_COORDINATE}`)\n return composed\n}\n","/**\n * How far the numbers svg-to-pdfkit writes for a cleaned drawing reach,\n * wherever the drawing is placed, and how deep it nests the graphics state\n * (0030): what the renderer holds an image of it to in an e-invoice, whose\n * PDF/A-3 may hold no integer past 2,147,483,647 and nest the graphics\n * state no deeper than 28 (ISO 19005-2's 6.1.13, veraPDF's rules 6.1.13-1\n * and 6.1.13-8). Nothing is refused by it here: a report that is no\n * e-invoice is no PDF/A, and draws such a drawing as it always did.\n *\n * What the converter writes, and what each number grows with -- a\n * `source.js:N` is a line of the converter, as `limits.ts` says:\n *\n * - The drawing's outlines, in their own coordinates: the points of its\n * paths and shapes, and those the converter draws them with, which a\n * quadratic reflected after a quadratic and an arc whose radii it grows\n * to reach its ends (`source.js:1010-1068`) take past every number the\n * file holds; each shape's box in `svg-path.ts` holds them all: `own`.\n * The rest of what it writes of the drawing itself -- each element's own\n * matrix, a stroke's width and dashes, a gradient's ends -- is a number\n * the cleaner holds to `MAX_SVG_COORDINATE`, which the renderer adds.\n * - The viewBox fitted into the image's box, which the renderer finds from\n * the viewBox and the box alone.\n * - Every page-sized transparency group's /BBox (`docBeginGroup`,\n * `source.js:67-90`): the page's corners taken through the inverse of\n * all the element that makes it is drawn under, page and box included\n * (`getPageBBox`, `source.js:536-539`). It grows with the inverse of the\n * drawing's matrix there, and with where that inverse takes the viewBox's\n * origin, and as the box shrinks: `groups`.\n * - Every gradient's /Matrix: PDFKit's matrix where the gradient is\n * painted, times the shape's box and the gradient's own transform\n * (`source.js:1863-1866`, and pdfkit.js's gradient `apply`), taken over\n * every box inside the shape's (`spreadUnder`). A group starts PDFKit's\n * matrix again from the identity (`source.js:83`), so inside one that is\n * the matrices below the group's times the box, the same wherever the\n * drawing is placed: `local`. Outside every group it is the page's and\n * the box's matrix times the drawing's: `patterns`.\n * - The box of what a clip in objectBoundingBox units clips, written as a\n * matrix inside the clip's group (`source.js:2211-2213`): for a group,\n * the boxes of its shapes through the matrices between them, and any box\n * inside that, the converter's being the outlines'; `local` too.\n *\n * Each is an upper bound, since a shape's box is the cleaner's, which holds\n * the converter's. What the page and the box add is the renderer's to\n * find, since only it knows them.\n */\nimport type { ViewBox } from './svg-drawing.js'\nimport { type Box, inverse, type Matrix, type Spread } from './svg-transform.js'\n\nexport interface SvgExtent {\n /** The page-sized groups': the largest row sum of the inverse of the linear part of a matrix one is drawn under, and the largest coordinate that inverse takes the viewBox's origin to. */\n readonly groups: { readonly inverse: number; readonly origin: number }\n /** The gradients' painted outside every group: the largest entry of the linear part of a matrix one may be drawn under, its shape's box and its own transform included, and the largest coordinate of that matrix's translation less the viewBox's origin. */\n readonly patterns: { readonly linear: number; readonly offset: number }\n /** The largest entry of a matrix the converter may write in a group's own coordinates: a gradient's inside a group, and the box of what a clip in objectBoundingBox units clips. */\n readonly local: number\n /** The largest coordinate of a point the converter draws an outline with, in the outline's own coordinates, a clip path's included. */\n readonly own: number\n /** The deepest the converter nests the graphics state in one content stream: once as it starts, once for the svg, once for every group and every shape, a group's own stream starting again. A clip path's stream nests two, its own save and its shape's (`source.js:2207-2219`), below any shape in the svg's. */\n readonly nesting: number\n}\n\nexport type { Box }\n\n/** The extent of a drawing, gathered where the walk that counts its cost decides what the converter draws (`svg-cost.ts`). */\nexport class Extent {\n private readonly origin: readonly [number, number]\n private inverse = 0\n private reach = 0\n private linear = 0\n private offset = 0\n private local = 0\n private own = 0\n private nesting = 0\n\n constructor(viewBox: ViewBox) {\n this.origin = [viewBox.x, viewBox.y]\n }\n\n /** A page-sized group, made by an element drawn under `under`. */\n group(under: Matrix): void {\n const [a, b, c, d, e, f] = inverse(under)\n this.inverse = Math.max(this.inverse, Math.abs(a) + Math.abs(c), Math.abs(b) + Math.abs(d))\n const [x, y] = this.origin\n this.reach = Math.max(this.reach, Math.abs(a * x + c * y + e), Math.abs(b * x + d * y + f))\n }\n\n /** A gradient painted outside every group: the matrices it may be drawn under, from the root. */\n pattern({ least, greatest }: Spread): void {\n const [x, y] = this.origin\n this.linear = Math.max(this.linear, largest([...least.slice(0, 4), ...greatest.slice(0, 4)]))\n this.offset = Math.max(this.offset, Math.abs(least[4] - x), Math.abs(greatest[4] - x), Math.abs(least[5] - y), Math.abs(greatest[5] - y))\n }\n\n /** A gradient painted inside a group: the matrices it may be drawn under, from where the group began. */\n inGroup({ least, greatest }: Spread): void {\n this.local = Math.max(this.local, largest([...least, ...greatest]))\n }\n\n /** The box, in the clipped element's own coordinates, that a clip in objectBoundingBox units draws its shapes in: a matrix of the width, height and corner of a box inside it. */\n clipBox([left, top, right, bottom]: Box): void {\n this.local = Math.max(this.local, right - left, bottom - top, largest([left, top, right, bottom]))\n }\n\n /** An outline the converter draws, inside `box` in its own coordinates. */\n outline(box: Box): void {\n this.own = Math.max(this.own, largest(box))\n }\n\n /** A save `depth` deep in its stream. */\n nest(depth: number): void {\n this.nesting = Math.max(this.nesting, depth)\n }\n\n extent(): SvgExtent {\n return {\n groups: { inverse: this.inverse, origin: this.reach },\n patterns: { linear: this.linear, offset: this.offset },\n local: this.local,\n own: this.own,\n nesting: this.nesting,\n }\n }\n}\n\nfunction largest(entries: readonly number[]): number {\n return Math.max(...entries.map(Math.abs))\n}\n","/**\n * What a cleaned drawing costs to draw, counted on what svg-to-pdfkit will\n * draw for it and what a reader will then paint, and refused past the\n * bounds `limits.ts` measured (0030).\n *\n * The converter does more than the drawing's size says. It draws a clip\n * path again for every element that refers to it, writes a gradient again\n * for every shape painted with it, and makes every clip, every group with\n * an opacity under 1 and every translucent gradient a transparency group\n * the size of the page (`source.js:67-88`, `1493-1537`, `1846-1937`;\n * PDFKit's `pdfkit.js:1026`). So segments count each clip path once per\n * reference and each gradient's stops once per use, and the groups have a\n * bound of their own.\n *\n * The weights are a reader's, measured in limits.ts. `drawn` is what the\n * converter draws each time it draws the drawing, by kind, unweighted: the\n * renderer weights it for its own budget, counting every page a page\n * region draws it on. `extent` is gathered by the same walk, where it\n * decides what the converter draws (`svg-extent.ts`).\n */\nimport { MAX_SVG_DEPTH, MAX_SVG_ELEMENTS, MAX_SVG_GROUPS, MAX_SVG_SEGMENTS } from './limits.js'\nimport { SHAPES } from './svg-allow.js'\nimport type { Drawing, Written } from './svg-drawing.js'\nimport { Extent, type SvgExtent } from './svg-extent.js'\nimport { refuse } from './svg-refusal.js'\nimport { type Box, gradientUnder, IDENTITY, type Matrix, multiply, readTransform, spreadUnder } from './svg-transform.js'\nimport type { Paint } from './svg-values.js'\n\nexport interface Cost {\n /** Weighted segments: what `MAX_SVG_SEGMENTS` bounds. */\n readonly segments: number\n /** Transparency groups, in units: what `MAX_SVG_GROUPS` bounds. */\n readonly groups: number\n /** What the converter draws each time it draws the drawing: moves, lines and closes; curves; elements it reads, a clip path's again for every element it clips; and gradient stops it writes, a gradient's again for every shape painted with it. */\n readonly drawn: { readonly lines: number; readonly curves: number; readonly elements: number; readonly stops: number }\n /** How far the numbers the converter writes for it reach, and how deep it nests the graphics state. */\n readonly extent: SvgExtent\n}\n\n/** A curve costs a reader what three lines do (limits.ts). */\nconst CURVE = 3\n/** A stroke costs a reader what painting its outline twice more does. */\nconst STROKE = 2\n/** A translucent gradient is two page-sized objects, a clip or a group opacity one. */\nconst TRANSLUCENT_GRADIENT = 2\n\ninterface Painted {\n readonly painted: boolean\n readonly stops: number\n readonly translucent: boolean\n}\n\nconst UNPAINTED: Painted = { painted: false, stops: 0, translucent: false }\n\nexport function costOf(drawing: Drawing): Cost {\n const counted = new Counter(drawing)\n counted.visit(drawing.root, 1, false, PAGE, IDENTITY)\n return counted.checked()\n}\n\n/** The content stream an element is drawn into: the page's, or a group's, in which PDFKit's matrix starts again from the identity; and the depth its saves count from. */\ninterface Stream {\n readonly grouped: boolean\n readonly base: number\n}\n\n/** The page's stream, where the converter saves the graphics state once before the svg saves it (`source.js:2727`): the root, one deep, saves at two. */\nconst PAGE: Stream = { grouped: false, base: -1 }\n\nconst NOTHING_DRAWN = { moves: 0, lines: 0, curves: 0, length: 0, box: [0, 0, 0, 0] as [number, number, number, number] }\n\nclass Counter {\n private readonly drawing: Drawing\n private segments = 0\n private groups = 0\n private lines = 0\n private curves = 0\n private elements = 0\n /** Elements the converter reads: every element once, and a clip path's shapes again for each element it clips. */\n private reads = 0\n private stops = 0\n private paints = false\n private readonly extent: Extent\n\n constructor(drawing: Drawing) {\n this.drawing = drawing\n this.extent = new Extent(drawing.viewBox)\n }\n\n /**\n * Every element, each shape and clip counted where it draws; clip paths'\n * and gradients' content only where something uses it. A clip and a\n * group at an opacity are each a page-sized group drawn under the\n * element's matrix, and a group with either draws what it holds into a\n * stream of its own (`source.js:1564-1577`). `outer` is the matrix the\n * element is drawn under in its stream, from where the stream began, its\n * own transform not yet included.\n */\n visit(node: Written, depth: number, inside: boolean, stream: Stream, outer: Matrix): void {\n this.elements += 1\n this.reads += 1\n if (this.elements > MAX_SVG_ELEMENTS) refuse('too-large', `the cleaned drawing has more than ${MAX_SVG_ELEMENTS} elements`)\n if (depth > MAX_SVG_DEPTH) refuse('too-deep', `${node.source.path} is written past ${MAX_SVG_DEPTH} levels`)\n const draws = !inside && (node.name === 'g' || SHAPES.has(node.name))\n const clip = draws ? node.styled.clip : undefined\n const translucent = draws && node.name === 'g' && node.styled.opacity < 1\n const at = draws ? multiply(outer, ownMatrix(node)) : outer\n if (draws) this.extent.nest(depth - stream.base)\n if (clip !== undefined) this.clip(node, clip.id)\n if (translucent) this.groups += 1\n if ((clip !== undefined || translucent) && node.under !== undefined) this.extent.group(node.under)\n if (draws && SHAPES.has(node.name)) this.shape(node, stream, at)\n const grouped = node.name === 'g' && (clip !== undefined || translucent)\n const inner = grouped ? { grouped, base: depth } : stream\n for (const child of node.children) this.visit(child, depth + 1, inside || !(node.name === 'g' || node.name === 'svg'), inner, grouped ? IDENTITY : at)\n }\n\n /** The costs, refused past their bounds, and a drawing that paints nothing refused. */\n checked(): Cost {\n const { segments, groups } = this\n if (!this.paints) refuse('unsupported', 'the drawing paints nothing', 'give what it draws a fill or a stroke')\n if (segments > MAX_SVG_SEGMENTS) refuse('too-large', `the drawing costs ${segments} weighted segments to paint; the limit is ${MAX_SVG_SEGMENTS}`)\n if (groups > MAX_SVG_GROUPS)\n refuse('too-large', `the drawing makes ${groups} units of transparency groups; the limit is ${MAX_SVG_GROUPS}`, 'flatten its clips and its transparency')\n return { segments, groups, drawn: { lines: this.lines, curves: this.curves, elements: this.reads, stops: this.stops }, extent: this.extent.extent() }\n }\n\n /** What a paint draws with, as the converter decides it (`source.js:1505-1528`): nothing at an alpha of 0, a gradient's stops, translucent when one comes out under 1. */\n private painted(paint: Paint, alpha: number): Painted {\n if (paint.kind === 'none' || alpha === 0) return UNPAINTED\n if (paint.kind !== 'url') return { painted: true, stops: 0, translucent: false }\n const stops = this.drawing.targets.get(paint.id)?.children ?? []\n if (stops.length === 0) return UNPAINTED\n return { painted: true, stops: stops.length, translucent: stops.length > 1 && stops.some((stop) => stop.styled.stopOpacity * alpha < 1) }\n }\n\n /** A shape drawn under `at` in its stream: its outline, its paints, and what painting them costs. */\n private shape(node: Written, stream: Stream, at: Matrix): void {\n const { computed, opacity } = node.styled\n const drawn = node.drawn ?? NOTHING_DRAWN\n this.extent.outline(drawn.box)\n const fill = this.painted(computed.fill, computed.fillOpacity * opacity)\n const stroke = computed.strokeWidth > 0 ? this.painted(computed.stroke, computed.strokeOpacity * opacity) : UNPAINTED\n if (fill.stops > 1 && computed.fill.kind === 'url') this.pattern(node, computed.fill.id, stream, at)\n if (stroke.stops > 1 && computed.stroke.kind === 'url') this.pattern(node, computed.stroke.id, stream, at)\n const weight = drawn.moves + drawn.lines + CURVE * drawn.curves\n this.segments += weight * ((fill.painted ? 1 : 0) + (stroke.painted ? STROKE : 0) || 1) + fill.stops + stroke.stops\n this.groups += (fill.translucent ? TRANSLUCENT_GRADIENT : 0) + (stroke.translucent ? TRANSLUCENT_GRADIENT : 0)\n if (stroke.painted && computed.dashes !== 'none') {\n const period = computed.dashes.reduce((sum, dash) => sum + dash, 0)\n this.segments += Math.ceil(((drawn.length / period) * computed.dashes.length) / 2)\n }\n this.lines += drawn.moves + drawn.lines\n this.curves += drawn.curves\n this.stops += fill.stops + stroke.stops\n this.paints ||= fill.painted || stroke.painted\n }\n\n /** A gradient of two stops or more, which the converter writes as a pattern, held where it is drawn from the root for the shape `node` (`gradientUnder`) and measured in the stream it is painted in, under `at` there. */\n private pattern(node: Written, id: string, stream: Stream, at: Matrix): void {\n const pattern = this.drawing.targets.get(id)?.pattern\n if (pattern === undefined || node.under === undefined) return\n const box = pattern.inBox ? (node.drawn ?? NOTHING_DRAWN).box : undefined\n const drawn = gradientUnder(node.under, box, pattern.matrix, node.source.path)\n if (stream.grouped) this.extent.inGroup(spreadUnder(at, box, pattern.matrix))\n else this.extent.pattern(drawn)\n }\n\n /** A clip path, drawn again for the element `node` that refers to it: its shapes' outlines, filled once each, in the box of `node` when its units are that box. */\n private clip(node: Written, id: string): void {\n this.groups += 1\n const target = this.drawing.targets.get(id)\n if (target?.geometry.some(([name, value]) => name === 'clipPathUnits' && value === 'objectBoundingBox') === true) this.extent.clipBox(boxOf(node))\n for (const child of target?.children ?? []) {\n const drawn = child.drawn ?? NOTHING_DRAWN\n this.extent.outline(drawn.box)\n this.segments += drawn.moves + drawn.lines + CURVE * drawn.curves\n this.lines += drawn.moves + drawn.lines\n this.curves += drawn.curves\n this.reads += 1\n }\n }\n}\n\n/** The matrix an element's own transform writes, as the converter reads it from the cleaned drawing; the identity where it has none. */\nfunction ownMatrix(node: Written): Matrix {\n return node.transform === undefined ? IDENTITY : readTransform(node.transform, node.source.path)\n}\n\n/**\n * The box of what a clip in objectBoundingBox units clips, in its own\n * coordinates, as the converter measures one (`source.js:1535-1549`): a\n * shape's own box, or the boxes of a group's shapes through the matrices\n * between it and each -- each element's own, composed down, as the\n * converter transforms each child's outline by its own -- their corners\n * taken, so that it holds the box of any outline inside them.\n */\nfunction boxOf(node: Written): Box {\n if (node.name !== 'g') return (node.drawn ?? NOTHING_DRAWN).box\n const box: [number, number, number, number] = [Infinity, Infinity, -Infinity, -Infinity]\n const walk = (at: Written, outer: Matrix): void => {\n for (const child of at.children) {\n const matrix = multiply(outer, ownMatrix(child))\n if (child.name === 'g') walk(child, matrix)\n if (!SHAPES.has(child.name) || child.drawn === undefined) continue\n const [a, b, c, d, e, f] = matrix\n const [left, top, right, bottom] = child.drawn.box\n for (const [x, y] of [\n [left, top],\n [right, top],\n [right, bottom],\n [left, bottom],\n ] as const) {\n const [u, v] = [a * x + c * y + e, b * x + d * y + f]\n box[0] = Math.min(box[0], u)\n box[1] = Math.min(box[1], v)\n box[2] = Math.max(box[2], u)\n box[3] = Math.max(box[3], v)\n }\n }\n }\n walk(node, IDENTITY)\n return box\n}\n","/**\n * Gradients: the chain of gradients one names through `href` followed and\n * flattened into one, and its geometry read in the units it is drawn in\n * (0030).\n *\n * A gradient takes, from the gradient it names, each of its own attributes\n * it does not set, and the stops when it has none (SVG 1.1, 13.2.2 and\n * 13.2.3); the written gradient has no `href`. A chain that leaves the file,\n * names what is not a gradient, comes back on itself or is longer than\n * `MAX_SVG_DEPTH` is refused: the converter follows a chain with no check\n * for a cycle (`source.js:1825-1836`).\n *\n * `spreadMethod` is read as `pad` alone, until `reflect` and `repeat` are\n * measured against a browser; a radial gradient's focal radius `fr`, which\n * the converter does not read, is refused as an attribute it does not know.\n */\nimport { MAX_SVG_DEPTH, MAX_SVG_STOPS } from './limits.js'\nimport { GEOMETRY, GRADIENTS } from './svg-allow.js'\nimport { writeNumber } from './svg-number.js'\nimport { refuse } from './svg-refusal.js'\nimport { IDENTITY, isIdentity, type Matrix, readTransform, writeMatrix } from './svg-transform.js'\nimport type { Located, SvgElement } from './svg-tree.js'\nimport { readLength } from './svg-values.js'\n\nexport interface FlatGradient {\n readonly geometry: ReadonlyArray<readonly [string, string]>\n /** The stops it is drawn with, which may be another gradient's. */\n readonly stops: readonly SvgElement[]\n /** Its gradientTransform, and whether it is drawn in the box of what it paints. */\n readonly matrix: Matrix\n readonly inBox: boolean\n}\n\n/** The gradients a gradient names, itself first, followed until one names none. */\nfunction chain(gradient: SvgElement, ids: ReadonlyMap<string, SvgElement>): SvgElement[] {\n const chained = [gradient]\n for (let href = gradient.attributes.get('href'); href !== undefined;) {\n const target = href.value.trim()\n if (!target.startsWith('#')) refuse('reference', `${href.where} refers to something outside the file`, 'put the gradient it names into the file')\n const next = ids.get(target.slice(1))\n if (next === undefined || !GRADIENTS.has(next.name)) refuse('reference', `${href.where} names no gradient in the file`, 'name a gradient in the file')\n if (chained.includes(next)) refuse('reference', `${href.where} is a cycle of gradients naming each other`, 'make one of them name none')\n if (chained.length >= MAX_SVG_DEPTH)\n refuse('too-deep', `${href.where} is a chain of more than ${MAX_SVG_DEPTH} gradients`, 'give the gradient its own stops and attributes')\n chained.push(next)\n href = next.attributes.get('href')\n }\n return chained\n}\n\nconst UNITS = ['userSpaceOnUse', 'objectBoundingBox']\n\n/** A gradient with its chain followed: its geometry as written, in table order, and its stops. */\nexport function flattenGradient(gradient: SvgElement, ids: ReadonlyMap<string, SvgElement>): FlatGradient {\n const chained = chain(gradient, ids)\n const taken = (name: string): Located | undefined => {\n for (const link of chained) {\n const attribute = link.attributes.get(name)\n if (attribute !== undefined) return attribute\n }\n return undefined\n }\n const units = taken('gradientUnits')\n if (units !== undefined && !UNITS.includes(units.value)) refuse('unsupported', `${units.where} is not userSpaceOnUse or objectBoundingBox`)\n const inBox = units?.value !== 'userSpaceOnUse'\n const geometry: Array<readonly [string, string]> = []\n let matrix = IDENTITY\n for (const name of GEOMETRY[gradient.name]) {\n const attribute = taken(name)\n if (attribute === undefined) continue\n if (name === 'gradientUnits') geometry.push([name, attribute.value])\n else if (name === 'spreadMethod') {\n if (attribute.value !== 'pad')\n refuse('unsupported', `${attribute.where} is a spread this format draws as pad alone`, 'expand the repeated gradient into shapes, or use pad')\n geometry.push([name, 'pad'])\n } else if (name === 'gradientTransform') {\n matrix = readTransform(attribute.value, attribute.where)\n if (!isIdentity(matrix)) geometry.push([name, writeMatrix(matrix)])\n } else {\n const length = readLength(attribute.value, attribute.where, inBox)\n if (name === 'r' && !(length.value > 0))\n refuse('out-of-range', `${attribute.where} is a radial gradient of no radius`, 'give it a radius, or paint with its last colour')\n geometry.push([name, writeNumber(length)])\n }\n }\n const stops = chained.find((link) => link.children.length > 0)?.children ?? []\n if (stops.length > MAX_SVG_STOPS) refuse('too-large', `${gradient.path} has more than ${MAX_SVG_STOPS} stops`)\n return { geometry, stops, matrix, inBox }\n}\n","/**\n * Path data: read by SVG's path grammar, written back as absolute commands,\n * and measured as svg-to-pdfkit will draw it.\n *\n * Read with implicit repetition and the compact arc flags (`a1 1 0 00 1 1`).\n * Malformed data is refused whole: SVG would draw up to the error, and a\n * path that would draw only partly is not drawn here at all. Written as\n * absolute commands, one letter each, numbers separated by single spaces,\n * with no implicit repetition; `H`, `V`, `S` and `T` stay what they are, and\n * an arc keeps its radii, its rotation and its flags. Relative steps sum\n * exactly (`svg-number.ts`).\n *\n * What a path costs is measured on the commands the converter draws, by\n * the converter's own construction: a move, a line and a close each one\n * command, a curve one, an arc one curve per 60 degrees it sweeps at\n * svg-to-pdfkit's default precision, or a line when a radius is zero or\n * when it ends where it starts, which draws nothing but is still read. The\n * basic shapes are measured as the converter builds them: an arc's split at\n * `source.js:1054`, its precision at `:2628`, the shapes at `:2066-2155`.\n */\nimport { plus, scanNumber, numberAt, type SvgNumber, writeNumber, ZERO } from './svg-number.js'\nimport { refuse } from './svg-refusal.js'\nimport { isSpace, skipSpace } from './svg-values.js'\n\nexport type PathLetter = 'M' | 'L' | 'H' | 'V' | 'C' | 'S' | 'Q' | 'T' | 'A' | 'Z'\n\nexport interface PathCommand {\n readonly letter: PathLetter\n /** Absolute; for an arc, its radii, rotation and end point, the flags apart. */\n readonly numbers: readonly SvgNumber[]\n readonly flags?: readonly [0 | 1, 0 | 1]\n}\n\nconst ARGUMENTS: { readonly [L in PathLetter]: number } = { M: 2, L: 2, H: 1, V: 1, C: 6, S: 4, Q: 4, T: 2, A: 7, Z: 0 }\n\nconst LETTERS: ReadonlySet<string> = new Set(Object.keys(ARGUMENTS))\n\nfunction letterAt(text: string, i: number): PathLetter | undefined {\n const upper = text.charAt(i).toUpperCase()\n return LETTERS.has(upper) ? (upper as PathLetter) : undefined\n}\n\n/** A path's commands, absolute; refused whole when the data is malformed, and empty for data with no command. */\nexport function readPath(d: string, where: string): readonly PathCommand[] {\n const reader = new PathReader(d, where)\n return reader.read()\n}\n\nclass PathReader {\n private readonly text: string\n private readonly where: string\n private i = 0\n private x: SvgNumber = ZERO\n private y: SvgNumber = ZERO\n private startX: SvgNumber = ZERO\n private startY: SvgNumber = ZERO\n private readonly commands: PathCommand[] = []\n\n constructor(text: string, where: string) {\n this.text = text\n this.where = where\n }\n\n read(): readonly PathCommand[] {\n this.i = skipSpace(this.text, 0)\n if (this.i >= this.text.length) return this.commands\n if (letterAt(this.text, this.i) !== 'M') this.malformed()\n while (this.i < this.text.length) {\n const letter = letterAt(this.text, this.i)\n if (letter === undefined) this.malformed()\n const relative = this.text.charAt(this.i) !== letter\n this.i = skipSpace(this.text, this.i + 1)\n if (letter === 'Z') {\n this.commands.push({ letter: 'Z', numbers: [] })\n this.x = this.startX\n this.y = this.startY\n continue\n }\n let repeated: PathLetter = letter\n for (;;) {\n this.group(repeated, relative)\n // After a move, a repeated pair is a line (SVG 1.1, 8.3.2).\n if (repeated === 'M') repeated = 'L'\n this.i = skipSpace(this.text, this.i)\n if (this.text.charCodeAt(this.i) === 0x2c) {\n this.i = skipSpace(this.text, this.i + 1)\n if (scanNumber(this.text, this.i) < 0) this.malformed()\n continue\n }\n // A number straight after the last, with or without a space, repeats the command.\n if (scanNumber(this.text, this.i) < 0) break\n }\n }\n return this.commands\n }\n\n private malformed(): never {\n return refuse('unsupported', `${this.where} is malformed path data`, 'save the drawing again from the program it was made in')\n }\n\n private number(): SvgNumber {\n const end = scanNumber(this.text, this.i)\n if (end < 0) this.malformed()\n const n = numberAt(this.text, this.i, end, this.where)\n this.i = end\n return n\n }\n\n /** A separator between two arguments: optional whitespace, then an optional comma and whitespace. */\n private separator(): void {\n this.i = skipSpace(this.text, this.i)\n if (this.text.charCodeAt(this.i) === 0x2c) this.i = skipSpace(this.text, this.i + 1)\n }\n\n private flag(): 0 | 1 {\n const code = this.text.charCodeAt(this.i)\n if (code !== 0x30 && code !== 0x31) this.malformed()\n this.i += 1\n return code === 0x30 ? 0 : 1\n }\n\n private absolute(n: SvgNumber, from: SvgNumber, relative: boolean): SvgNumber {\n return relative ? plus(from, n, this.where) : n\n }\n\n /** One command's arguments, read, made absolute and pushed. */\n private group(letter: PathLetter, relative: boolean): void {\n const args: SvgNumber[] = []\n let flags: [0 | 1, 0 | 1] | undefined\n for (let k = 0; k < ARGUMENTS[letter]; k += 1) {\n if (k > 0) this.separator()\n if (letter === 'A' && (k === 3 || k === 4)) {\n flags ??= [0, 0]\n flags[k - 3] = this.flag()\n continue\n }\n args.push(this.number())\n }\n const { x, y } = this\n let numbers: SvgNumber[]\n switch (letter) {\n case 'H':\n numbers = [this.absolute(args[0] as SvgNumber, x, relative)]\n this.x = numbers[0] as SvgNumber\n break\n case 'V':\n numbers = [this.absolute(args[0] as SvgNumber, y, relative)]\n this.y = numbers[0] as SvgNumber\n break\n case 'A':\n numbers = [args[0], args[1], args[2], this.absolute(args[3] as SvgNumber, x, relative), this.absolute(args[4] as SvgNumber, y, relative)] as SvgNumber[]\n this.x = numbers[3] as SvgNumber\n this.y = numbers[4] as SvgNumber\n break\n default:\n numbers = args.map((n, k) => this.absolute(n, k % 2 === 0 ? x : y, relative))\n this.x = numbers[numbers.length - 2] as SvgNumber\n this.y = numbers[numbers.length - 1] as SvgNumber\n }\n if (letter === 'M') {\n this.startX = this.x\n this.startY = this.y\n }\n this.commands.push(flags === undefined ? { letter, numbers } : { letter, numbers, flags })\n }\n}\n\n/** The path data a cleaned drawing holds. */\nexport function writePath(commands: readonly PathCommand[]): string {\n return commands\n .map(({ letter, numbers, flags }) => {\n if (letter === 'A' && flags !== undefined) {\n const [rx, ry, rotation, x, y] = numbers.map(writeNumber)\n return `A${rx} ${ry} ${rotation} ${flags[0]} ${flags[1]} ${x} ${y}`\n }\n return `${letter}${numbers.map(writeNumber).join(' ')}`\n })\n .join(' ')\n}\n\n/** What drawing a shape costs: the commands the converter draws, by kind, and a bound on the length of the outline, which dashes are laid along. */\nexport interface Drawn {\n moves: number\n lines: number\n curves: number\n length: number\n /** A box the outline lies inside, in the shape's own coordinates -- left, top, right, bottom -- which its box in a browser's or the converter's sense lies inside too: what a gradient in its box is scaled to. */\n box: [number, number, number, number]\n}\n\nfunction nothingDrawn(): Drawn {\n return { moves: 0, lines: 0, curves: 0, length: 0, box: [Infinity, Infinity, -Infinity, -Infinity] }\n}\n\n/** The box widened to hold the point, or a square of `reach` about it. */\nfunction hold(box: Drawn['box'], x: number, y: number, reach = 0): void {\n box[0] = Math.min(box[0], x - reach)\n box[1] = Math.min(box[1], y - reach)\n box[2] = Math.max(box[2], x + reach)\n box[3] = Math.max(box[3], y + reach)\n}\n\n/** A command as the converter receives it: absolute, in floats; an arc's flags are its fourth and fifth numbers. */\nexport interface FloatCommand {\n readonly letter: PathLetter\n readonly values: readonly number[]\n}\n\nexport function floats(commands: readonly PathCommand[]): FloatCommand[] {\n return commands.map(({ letter, numbers, flags }) => {\n const values = numbers.map((n) => n.value)\n if (letter === 'A' && flags !== undefined) values.splice(3, 0, flags[0], flags[1])\n return { letter, values }\n })\n}\n\nfunction distance(ax: number, ay: number, bx: number, by: number): number {\n return Math.hypot(bx - ax, by - ay)\n}\n\n/**\n * What the converter draws for these commands, replaying its own\n * construction (`SvgShape`, `source.js:925-1100`): `S` reflects the last\n * curve's control point only after a `C` or an `S`, `T` the last quadratic's\n * only after a `Q` or a `T`, and an arc is split as the converter splits it.\n * The length is the control polygon's, which is never shorter than the\n * curve, so a count of dashes laid along it is an upper bound.\n */\nexport function measure(commands: readonly FloatCommand[]): Drawn {\n const drawn = nothingDrawn()\n let x = 0\n let y = 0\n let startX = 0\n let startY = 0\n let last: PathLetter | undefined\n let controlX = 0\n let controlY = 0\n // A curve lies inside the hull of its control points, so the box holds them all.\n const curve = (c1x: number, c1y: number, c2x: number, c2y: number, ex: number, ey: number): void => {\n drawn.curves += 1\n drawn.length += distance(x, y, c1x, c1y) + distance(c1x, c1y, c2x, c2y) + distance(c2x, c2y, ex, ey)\n hold(drawn.box, c1x, c1y)\n hold(drawn.box, c2x, c2y)\n hold(drawn.box, ex, ey)\n x = ex\n y = ey\n }\n const line = (ex: number, ey: number): void => {\n drawn.lines += 1\n drawn.length += distance(x, y, ex, ey)\n hold(drawn.box, ex, ey)\n x = ex\n y = ey\n }\n for (const { letter, values: v } of commands) {\n const [a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0] = v\n switch (letter) {\n case 'M':\n drawn.moves += 1\n x = startX = a\n y = startY = b\n hold(drawn.box, a, b)\n break\n case 'L':\n line(a, b)\n break\n case 'H':\n line(a, y)\n break\n case 'V':\n line(x, a)\n break\n case 'Z':\n line(startX, startY)\n break\n case 'C':\n curve(a, b, c, d, e, f)\n controlX = c\n controlY = d\n break\n case 'S': {\n const reflect = last === 'C' || last === 'S'\n const [c1x, c1y] = reflect ? [2 * x - controlX, 2 * y - controlY] : [x, y]\n curve(c1x, c1y, a, b, c, d)\n controlX = a\n controlY = b\n break\n }\n case 'Q':\n case 'T': {\n const reflect = letter === 'T' && (last === 'Q' || last === 'T')\n const [qx, qy] = letter === 'Q' ? [a, b] : reflect ? [2 * x - controlX, 2 * y - controlY] : [x, y]\n const [ex, ey] = letter === 'Q' ? [c, d] : [a, b]\n curve(x + (2 / 3) * (qx - x), y + (2 / 3) * (qy - y), ex + (2 / 3) * (qx - ex), ey + (2 / 3) * (qy - ey), ex, ey)\n controlX = qx\n controlY = qy\n break\n }\n default:\n arc(drawn, x, y, a, b, c, d, e, f, g)\n x = f\n y = g\n }\n last = letter\n }\n return drawn\n}\n\n/** The converter's precision: one curve per π / 3 of an arc's sweep (`source.js:2628`; pdfmake passes none). */\nconst PRECISION = 3\n\n/**\n * How far from an arc's centre, in its larger radius, the converter's\n * curves for it reach: each curve spans at most π / `PRECISION`, and its\n * control points stand off the ellipse along its tangents by 4/3 of the\n * tangent of a quarter of that (`source.js:1058-1062`), so within\n * hypot(1, 4/3 × tan(π / 12)), 1.0619, of the centre; a curve lies inside\n * the hull of its control points.\n */\nconst CONTROL = Math.hypot(1, (4 / 3) * Math.tan(Math.PI / (4 * PRECISION)))\n\n/**\n * An arc as svg-to-pdfkit splits it (`source.js:1026-1068`), its arithmetic\n * repeated term for term, so that the count is the converter's to the\n * floating-point rounding: a curve per π / 3 swept, a line when a radius is\n * zero. One that ends where it starts draws nothing, and is counted a line\n * all the same: every command is read and written back by every reader of\n * the file, so a path of a mebibyte of arcs that draw nothing is not free.\n * The length bound is the sweep times the larger radius, which the arc is\n * never longer than. The box holds the circle of `CONTROL` times the\n * larger radius about the centre, as the converter grows the radii to\n * reach both ends, which holds every curve it draws: the circle of the\n * ellipse's diameter about its end did not, the curves bulging past the\n * ellipse by a hundred-thousandth of its radius.\n */\nfunction arc(drawn: Drawn, x0: number, y0: number, rxIn: number, ryIn: number, rotation: number, large: number, sweep: number, x: number, y: number): void {\n hold(drawn.box, x, y)\n if (Math.abs(rxIn) < 1e-10 || Math.abs(ryIn) < 1e-10) {\n drawn.lines += 1\n drawn.length += distance(x0, y0, x, y)\n return\n }\n const fi = rotation * (Math.PI / 180)\n let rx = Math.abs(rxIn)\n let ry = Math.abs(ryIn)\n const fa = 1 * Number(!!large)\n const fs = 1 * Number(!!sweep)\n const x1 = (Math.cos(fi) * (x0 - x)) / 2 + (Math.sin(fi) * (y0 - y)) / 2\n const y1 = (Math.cos(fi) * (y0 - y)) / 2 - (Math.sin(fi) * (x0 - x)) / 2\n const lambda = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry)\n if (lambda > 1) {\n rx *= Math.sqrt(lambda)\n ry *= Math.sqrt(lambda)\n }\n const r = Math.sqrt(Math.max(0, rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1) / (rx * rx * y1 * y1 + ry * ry * x1 * x1))\n const x2 = ((fa === fs ? -1 : 1) * r * rx * y1) / ry\n const y2 = ((fa === fs ? 1 : -1) * r * ry * x1) / rx\n const cx = Math.cos(fi) * x2 - Math.sin(fi) * y2 + (x0 + x) / 2\n const cy = Math.sin(fi) * x2 + Math.cos(fi) * y2 + (y0 + y) / 2\n const th1 = Math.atan2((y1 - y2) / ry, (x1 - x2) / rx)\n let th2 = Math.atan2((-y1 - y2) / ry, (-x1 - x2) / rx)\n if (fs === 0 && th2 - th1 > 0) th2 -= 2 * Math.PI\n else if (fs === 1 && th2 - th1 < 0) th2 += 2 * Math.PI\n const curves = Math.ceil(Math.abs(th2 - th1) / (Math.PI / PRECISION))\n // NaN when the arc ends where it starts: the converter's loop draws nothing then, but the arc is read.\n if (!(curves > 0)) {\n drawn.lines += 1\n return\n }\n drawn.curves += curves\n drawn.length += Math.abs(th2 - th1) * Math.max(rx, ry)\n hold(drawn.box, cx, cy, CONTROL * Math.max(rx, ry))\n}\n\n/** Whitespace-only path data draws nothing, as an absent `d` does. */\nexport function isBlank(d: string): boolean {\n for (let i = 0; i < d.length; i += 1) if (!isSpace(d.charCodeAt(i))) return false\n return true\n}\n","/**\n * The shapes an SVG draws with -- path, rect, circle, ellipse, line,\n * polyline, polygon -- their geometry read and written back, and what each\n * costs measured on the commands svg-to-pdfkit builds it from\n * (`source.js:2066-2155`).\n *\n * A shape of no size draws nothing, as SVG says, and is removed: a rect, a\n * circle or an ellipse with a zero side or radius, a path with no data, a\n * polyline of fewer than two points. A negative size is an error SVG does\n * not draw, and is refused. Every length is in user units, its unit\n * converted; a percentage of the viewport is refused, since what the\n * viewport is depends on the report's box.\n */\nimport { GEOMETRY } from './svg-allow.js'\nimport { type SvgNumber, writeNumber, ZERO } from './svg-number.js'\nimport { type Drawn, type FloatCommand, floats, isBlank, measure, readPath, writePath } from './svg-path.js'\nimport { refuse } from './svg-refusal.js'\nimport type { SvgElement } from './svg-tree.js'\nimport { readLength, readNumbers } from './svg-values.js'\n\nexport interface Shape {\n readonly geometry: ReadonlyArray<readonly [string, string]>\n readonly drawn: Drawn\n}\n\n/** The shape's geometry and cost, or undefined when it draws nothing. */\nexport function readShape(element: SvgElement): Shape | undefined {\n const lengths = new Map<string, SvgNumber>()\n const geometry: Array<readonly [string, string]> = []\n for (const name of GEOMETRY[element.name]) {\n const attribute = element.attributes.get(name)\n if (attribute === undefined) continue\n if (name === 'd' || name === 'points') continue\n const length = readLength(attribute.value, attribute.where, false)\n if (['width', 'height', 'r', 'rx', 'ry'].includes(name) && length.value < 0)\n refuse('out-of-range', `${attribute.where} is negative`, 'give it zero or more')\n lengths.set(name, length)\n geometry.push([name, writeNumber(length)])\n }\n const at = (name: string): number => (lengths.get(name) ?? ZERO).value\n const commands = shapeCommands(element, at, lengths)\n if (commands === undefined) return undefined\n if (element.name === 'path') geometry.push(['d', writePath(commands.path ?? [])])\n if (element.name === 'polyline' || element.name === 'polygon') geometry.push(['points', commands.points ?? ''])\n return { geometry, drawn: measure(commands.floats) }\n}\n\ninterface Commands {\n readonly floats: readonly FloatCommand[]\n readonly path?: ReturnType<typeof readPath>\n readonly points?: string\n}\n\nfunction move(x: number, y: number): FloatCommand {\n return { letter: 'M', values: [x, y] }\n}\n\nfunction line(x: number, y: number): FloatCommand {\n return { letter: 'L', values: [x, y] }\n}\n\nfunction arc(rx: number, ry: number, x: number, y: number): FloatCommand {\n return { letter: 'A', values: [rx, ry, 0, 0, 1, x, y] }\n}\n\nconst CLOSE: FloatCommand = { letter: 'Z', values: [] }\n\n/** The commands the converter builds the shape from, or undefined when it draws nothing. */\nfunction shapeCommands(element: SvgElement, at: (name: string) => number, lengths: ReadonlyMap<string, SvgNumber>): Commands | undefined {\n switch (element.name) {\n case 'path': {\n const d = element.attributes.get('d')\n if (d === undefined || isBlank(d.value)) return undefined\n const path = readPath(d.value, d.where)\n return { floats: floats(path), path }\n }\n case 'rect':\n return rect(at('x'), at('y'), at('width'), at('height'), lengths.get('rx')?.value, lengths.get('ry')?.value)\n case 'circle': {\n const [cx, cy, r] = [at('cx'), at('cy'), at('r')]\n return r > 0 ? { floats: [move(cx + r, cy), arc(r, r, cx - r, cy), arc(r, r, cx + r, cy), CLOSE] } : undefined\n }\n case 'ellipse': {\n const [cx, cy, rx, ry] = [at('cx'), at('cy'), at('rx'), at('ry')]\n return rx > 0 && ry > 0 ? { floats: [move(cx + rx, cy), arc(rx, ry, cx - rx, cy), arc(rx, ry, cx + rx, cy), CLOSE] } : undefined\n }\n case 'line':\n return { floats: [move(at('x1'), at('y1')), line(at('x2'), at('y2'))] }\n default:\n return poly(element)\n }\n}\n\n/** A rect as the converter builds it: rounded when it has a radius, one radius standing for both, each at most half its side. */\nfunction rect(x: number, y: number, w: number, h: number, rxIn: number | undefined, ryIn: number | undefined): Commands | undefined {\n if (!(w > 0 && h > 0)) return undefined\n let rx = rxIn ?? ryIn ?? 0\n let ry = ryIn ?? rxIn ?? 0\n if (rx === 0 || ry === 0) return { floats: [move(x, y), line(x + w, y), line(x + w, y + h), line(x, y + h), CLOSE] }\n rx = Math.min(rx, 0.5 * w)\n ry = Math.min(ry, 0.5 * h)\n return {\n floats: [\n move(x + rx, y),\n line(x + w - rx, y),\n arc(rx, ry, x + w, y + ry),\n line(x + w, y + h - ry),\n arc(rx, ry, x + w - rx, y + h),\n line(x + rx, y + h),\n arc(rx, ry, x, y + h - ry),\n line(x, y + ry),\n arc(rx, ry, x + rx, y),\n CLOSE,\n ],\n }\n}\n\n/** A polyline or a polygon: pairs of numbers, a polygon closed; an odd count refused, as the converter would warn of it. */\nfunction poly(element: SvgElement): Commands | undefined {\n const points = element.attributes.get('points')\n if (points === undefined) return undefined\n const numbers = readNumbers(points.value, points.where)\n if (numbers.length % 2 === 1) refuse('unsupported', `${points.where} holds an odd count of coordinates`, 'give every point both of its coordinates')\n if (numbers.length < 4) return undefined\n const commands: FloatCommand[] = []\n for (let i = 0; i < numbers.length; i += 2) {\n const x = (numbers[i] as SvgNumber).value\n const y = (numbers[i + 1] as SvgNumber).value\n commands.push(i === 0 ? move(x, y) : line(x, y))\n }\n if (element.name === 'polygon') commands.push(CLOSE)\n return { floats: commands, points: numbers.map(writeNumber).join(' ') }\n}\n","/**\n * The drawing a cleaned SVG holds, built from the styled tree: what is\n * hidden or of no size removed, every reference checked and its target\n * kept, every gradient flattened, what nothing refers to removed, and the\n * root's own paint and transform moved onto one group inside it (0030).\n *\n * The root is written with its namespace and its viewBox alone. A\n * transform on the root would move the drawing and its clip off the\n * report's box -- over a QR-bill's amount, say -- and paint on it would be\n * dropped, printing a stroke-only logo as black blobs; on a group inside\n * it, both draw as the author drew them, inside the box (0030).\n *\n * References are kept only inside the file: a fill or a stroke may name a\n * gradient, a clip-path a clip path, and nothing else may name anything.\n * One that names nothing, the wrong kind of thing, or something inside\n * what is removed, is refused rather than drawn otherwise.\n */\nimport { GRADIENTS, type KeptElement, SHAPES, WRITTEN_ON, type WrittenProperty } from './svg-allow.js'\nimport type { Styled, WrittenValue } from './svg-computed.js'\nimport { flattenGradient } from './svg-gradient.js'\nimport { float, writeNumber } from './svg-number.js'\nimport { type Drawn } from './svg-path.js'\nimport { refuse, type Removals } from './svg-refusal.js'\nimport { readShape } from './svg-shapes.js'\nimport { compose, IDENTITY, isIdentity, type Matrix, readTransform, writeMatrix } from './svg-transform.js'\nimport type { SvgDocument, SvgElement } from './svg-tree.js'\nimport { readLength, readNumbers, readOpacity } from './svg-values.js'\n\n/** An element of the cleaned drawing, as it is written. */\nexport interface Written {\n readonly name: KeptElement\n readonly source: SvgElement\n geometry: ReadonlyArray<readonly [string, string]>\n readonly transform: string | undefined\n readonly properties: ReadonlyArray<readonly [WrittenProperty, WrittenValue]>\n children: Written[]\n readonly styled: Styled\n /** What a shape draws. */\n readonly drawn: Drawn | undefined\n /** The matrix a shape or a group is drawn under, from the root down, its own transform included. */\n readonly under?: Matrix\n /** A gradient's transform, and whether it is drawn in the box of what it paints, once something refers to it. */\n pattern?: { readonly matrix: Matrix; readonly inBox: boolean }\n /** The id it is written with, when something refers to it. */\n id: string | undefined\n}\n\nexport interface ViewBox {\n readonly x: number\n readonly y: number\n readonly width: number\n readonly height: number\n}\n\nexport interface Drawing {\n readonly root: Written\n readonly viewBox: ViewBox\n /** What each reference's id names, among the gradients and clip paths kept. */\n readonly targets: ReadonlyMap<string, Written>\n}\n\ntype Context = 'draw' | 'defs' | 'clip'\n\nexport function buildDrawing(document: SvgDocument, styled: ReadonlyMap<SvgElement, Styled>, removals: Removals): Drawing {\n return new DrawingBuilder(document, styled, removals).build()\n}\n\nclass DrawingBuilder {\n private readonly document: SvgDocument\n private readonly styled: ReadonlyMap<SvgElement, Styled>\n private readonly removals: Removals\n private readonly ids = new Map<string, SvgElement>()\n /** The gradients and clip paths built, by the element they come from. */\n private readonly built = new Map<SvgElement, Written>()\n private readonly flattened = new Set<Written>()\n\n constructor(document: SvgDocument, styled: ReadonlyMap<SvgElement, Styled>, removals: Removals) {\n this.document = document\n this.styled = styled\n this.removals = removals\n const index = (element: SvgElement): void => {\n if (element.id !== undefined) this.ids.set(element.id, element)\n element.children.forEach(index)\n }\n index(document.root)\n }\n\n private style(element: SvgElement): Styled {\n return this.styled.get(element) as Styled\n }\n\n build(): Drawing {\n const { root } = this.document\n const viewBox = this.viewBox()\n const rootStyled = this.style(root)\n if (rootStyled.hidden) refuse('unsupported', 'svg is hidden: the drawing paints nothing', 'show the drawing')\n const transform = this.transform(root, IDENTITY)\n const children = this.children(root, transform.matrix, 'draw')\n const paint = this.drawable('g', rootStyled.written)\n const moved = paint.length > 0 || transform.written !== undefined\n const group: Written = {\n name: 'g',\n source: root,\n geometry: [],\n transform: transform.written,\n properties: paint,\n children,\n styled: rootStyled,\n drawn: undefined,\n under: transform.matrix,\n id: undefined,\n }\n const svg: Written = {\n name: 'svg',\n source: root,\n geometry: [['viewBox', [viewBox.x, viewBox.y, viewBox.width, viewBox.height].map((n) => writeNumber(float(n))).join(' ')]],\n transform: undefined,\n properties: [],\n children: moved ? [group] : children,\n styled: { ...rootStyled, written: [], opacity: 1, clip: undefined },\n drawn: undefined,\n id: undefined,\n }\n // Every reference is checked where it is made, then what draws is found\n // from the shapes up and everything else removed, in one pass each.\n const kept = this.used(svg, this.references(svg))\n this.prune(svg, kept)\n const targets = new Map([...this.references(svg)].filter(([, target]) => kept.has(target)))\n for (const target of targets.values())\n if (target.name === 'clipPath' && target.children.length === 0)\n refuse(\n 'unsupported',\n `${target.source.path} is a clip path with nothing in it, which hides what it clips`,\n 'put the shape it clips to inside it, or remove the clip',\n )\n this.unwrap(svg)\n this.name(svg, new Set(targets.values()))\n return { root: svg, viewBox, targets }\n }\n\n /** The root's viewBox, or `0 0 width height` from its size when it has none. */\n private viewBox(): ViewBox {\n const { root, width, height } = this.document\n const written = root.attributes.get('viewBox')\n if (written === undefined) {\n if (width === undefined || height === undefined)\n refuse('out-of-range', 'svg has no viewBox, and no width and height to take one from', 'give the svg a viewBox')\n return this.box(0, 0, readLength(width.value, width.where, false).value, readLength(height.value, height.where, false).value, 'svg@width')\n }\n const numbers = readNumbers(written.value, written.where)\n if (numbers.length !== 4) refuse('unsupported', `${written.where} is not four numbers`, 'write it as four numbers: x, y, width and height')\n const [x, y, w, h] = numbers.map((n) => n.value) as [number, number, number, number]\n return this.box(x, y, w, h, written.where)\n }\n\n private box(x: number, y: number, width: number, height: number, where: string): ViewBox {\n if (!(width >= 1 && height >= 1)) refuse('out-of-range', `${where} gives the drawing a side under one unit`, 'scale the drawing up in the drawing program')\n return { x, y, width, height }\n }\n\n private transform(element: SvgElement, outer: Matrix): { readonly matrix: Matrix; readonly written: string | undefined } {\n const attribute = element.attributes.get('transform')\n if (attribute === undefined) return { matrix: outer, written: undefined }\n const own = readTransform(attribute.value, attribute.where)\n return { matrix: compose(outer, own, element.path), written: isIdentity(own) ? undefined : writeMatrix(own) }\n }\n\n private children(element: SvgElement, matrix: Matrix, context: Context): Written[] {\n const children: Written[] = []\n for (const child of element.children) {\n const written = this.element(child, matrix, context)\n if (written !== undefined) children.push(written)\n }\n return children\n }\n\n /** An element as it is written, or undefined when it is removed. */\n private element(element: SvgElement, outer: Matrix, context: Context): Written | undefined {\n const styled = this.style(element)\n const draws = element.name === 'g' || SHAPES.has(element.name)\n if (draws && (styled.hidden || context === 'defs')) {\n this.removals.add('element', element.link ? 'a' : element.name)\n return undefined\n }\n if (styled.clip !== undefined && (context === 'clip' || element.name === 'clipPath'))\n refuse('unsupported', `${element.path} is clipped inside a clip path`, 'clip it once, with one clip path')\n const { matrix, written: transform } = this.transform(element, element.name === 'clipPath' ? IDENTITY : outer)\n const shape = SHAPES.has(element.name) ? readShape(element) : undefined\n if (SHAPES.has(element.name) && shape === undefined) {\n this.removals.add('element', element.name)\n return undefined\n }\n const base = { name: element.name, source: element, transform, properties: this.properties(element, styled), styled, id: undefined }\n if (shape !== undefined) return { ...base, geometry: shape.geometry, children: [], drawn: shape.drawn, under: matrix }\n if (GRADIENTS.has(element.name)) {\n // Its geometry and stops are its chain's, taken when something refers to it.\n const gradient: Written = { ...base, geometry: [], children: [], drawn: undefined }\n this.built.set(element, gradient)\n return gradient\n }\n const geometry: Array<readonly [string, string]> = []\n const units = element.attributes.get('clipPathUnits')\n if (units !== undefined) {\n if (!['userSpaceOnUse', 'objectBoundingBox'].includes(units.value)) refuse('unsupported', `${units.where} is not userSpaceOnUse or objectBoundingBox`)\n geometry.push(['clipPathUnits', units.value])\n }\n const inner: Context = element.name === 'clipPath' ? 'clip' : element.name === 'defs' ? 'defs' : context\n const written: Written = {\n ...base,\n geometry,\n children: this.children(element, matrix, inner),\n drawn: undefined,\n ...(element.name === 'g' ? { under: matrix } : {}),\n }\n if (element.name === 'clipPath') this.built.set(element, written)\n return written\n }\n\n /** A stop as it is written, wherever its gradient is. */\n private stop(element: SvgElement): Written {\n const styled = this.style(element)\n const offset = element.attributes.get('offset')\n const geometry: Array<readonly [string, string]> = offset === undefined ? [] : [['offset', writeNumber(readOpacity(offset.value, offset.where))]]\n return {\n name: 'stop',\n source: element,\n geometry,\n transform: undefined,\n properties: this.drawable('stop', styled.written),\n children: [],\n styled,\n drawn: undefined,\n id: undefined,\n }\n }\n\n /** `written` with only what draws on an element `name`, every other property removed and listed (`WRITTEN_ON`). */\n private drawable(name: KeptElement, written: Styled['written']): Styled['written'] {\n const keeps = WRITTEN_ON[name]\n return written.filter(([property]) => {\n if (keeps.has(property)) return true\n this.removals.add('property', property)\n return false\n })\n }\n\n /** What an element is written with: what draws on it, and on a clip path the clip rule it inherits, which `defs` then need not hold. */\n private properties(element: SvgElement, styled: Styled): Styled['written'] {\n const written = this.drawable(element.name, styled.written)\n if (element.name !== 'clipPath' || written.some(([property]) => property === 'clip-rule') || styled.computed.clipRule === 'nonzero') return written\n return [...written, ['clip-rule', styled.computed.clipRule]]\n }\n\n /** The target of a reference, refused unless it is a kept element of the kind the property names. */\n private target(id: string, where: string, gradient: boolean): Written {\n const element = this.ids.get(id)\n if (element === undefined) refuse('reference', `${where} names nothing in the file`, 'put what it names into the file, or remove the reference')\n const kind = gradient ? GRADIENTS.has(element.name) : element.name === 'clipPath'\n if (!kind)\n refuse(\n 'reference',\n `${where} names a ${element.link ? 'a' : element.name}, not a ${gradient ? 'gradient' : 'clip path'}`,\n `name a ${gradient ? 'gradient' : 'clip path'}`,\n )\n const written = this.built.get(element)\n if (written === undefined)\n refuse('reference', `${where} names a ${gradient ? 'gradient' : 'clip path'} inside what is removed`, 'move what it names into defs')\n return written\n }\n\n /**\n * Every reference the drawing makes, checked, its gradients flattened:\n * first what draws, then what the clip paths it uses hold. What a clip\n * path nothing uses refers to is never followed, since it is removed.\n */\n private references(svg: Written): Map<string, Written> {\n const targets = new Map<string, Written>()\n // Each gradient is flattened once, however many rounds see it.\n const follow = (node: Written, inside: boolean): void => {\n if (node.name === 'clipPath' && !inside) return\n if (GRADIENTS.has(node.name)) return\n for (const [property, value] of node.properties) {\n if (typeof value === 'string') continue\n const gradient = property !== 'clip-path'\n const target = this.target(value.reference.id, value.reference.where, gradient)\n if (targets.has(value.reference.id)) continue\n targets.set(value.reference.id, target)\n if (!gradient) for (const child of target.children) follow(child, true)\n else if (!this.flattened.has(target)) {\n this.flattened.add(target)\n const flat = flattenGradient(target.source, this.ids)\n target.geometry = flat.geometry\n target.pattern = { matrix: flat.matrix, inBox: flat.inBox }\n target.children = flat.stops.map((stop) => this.stop(stop))\n }\n }\n for (const child of node.children) follow(child, inside)\n }\n follow(svg, false)\n return targets\n }\n\n /**\n * What draws, and what it needs, found from the shapes up so that each\n * element is visited once: every shape outside a gradient or a clip path;\n * every group or defs that holds something kept; every gradient and clip\n * path something kept refers to, and what a kept clip path's shapes refer\n * to. Removing what is left in rounds -- an empty group, then what only it\n * referred to, then the group that held that -- took a round for every\n * link of such a chain, and as many passes over the drawing.\n */\n private used(svg: Written, targets: ReadonlyMap<string, Written>): Set<Written> {\n const parents = new Map<Written, Written>()\n const kept = new Set<Written>()\n const pending: Written[] = []\n const keep = (node: Written): void => {\n if (kept.has(node)) return\n kept.add(node)\n pending.push(node)\n }\n const index = (node: Written, inside: boolean): void => {\n for (const child of node.children) {\n parents.set(child, node)\n if (!inside && SHAPES.has(child.name)) keep(child)\n index(child, inside || isDefinition(child))\n }\n }\n index(svg, false)\n const referred = (node: Written): void => {\n for (const [, value] of node.properties) {\n const target = typeof value === 'string' ? undefined : targets.get(value.reference.id)\n if (target !== undefined) keep(target)\n }\n }\n for (let node = pending.pop(); node !== undefined; node = pending.pop()) {\n referred(node)\n if (node.name === 'clipPath') node.children.forEach(referred)\n const parent = parents.get(node)\n if (parent !== undefined && !isDefinition(parent)) keep(parent)\n }\n return kept\n }\n\n /** Every element `kept` does not hold removed and listed, with every group, defs, gradient and clip path inside it. */\n private prune(node: Written, kept: ReadonlySet<Written>): void {\n node.children = node.children.filter((child) => {\n if (!kept.has(child)) {\n this.removed(child)\n return false\n }\n // What a kept gradient or clip path holds -- stops, or shapes -- holds nothing to prune.\n if (!isDefinition(child)) this.prune(child, kept)\n return true\n })\n }\n\n private removed(node: Written): void {\n if (!isDefinition(node)) for (const child of node.children) this.removed(child)\n this.removals.add('element', node.source.link ? 'a' : node.name)\n }\n\n /** Every group with nothing written on it unwrapped: it draws as its children do, and is written as them. */\n private unwrap(node: Written): void {\n for (const child of node.children) this.unwrap(child)\n node.children = node.children.flatMap((child) => {\n if (!this.bare(child)) return [child]\n if (child.source.id !== undefined) this.removals.add('attribute', 'id')\n return child.children\n })\n }\n\n /** A group with nothing written on it draws as its children do, and is written as them. */\n private bare(node: Written): boolean {\n return node.name === 'g' && node.transform === undefined && node.properties.length === 0\n }\n\n /**\n * Each gradient and clip path something refers to, named in document\n * order: g1, g2 … and c1, c2 …. Every other id is removed and listed:\n * nothing kept could refer to it.\n */\n private name(node: Written, used: ReadonlySet<Written>): void {\n let gradients = 0\n let clips = 0\n const walk = (at: Written): void => {\n if (used.has(at)) at.id = at.name === 'clipPath' ? `c${(clips += 1)}` : `g${(gradients += 1)}`\n else if (at.source.id !== undefined && (at.name !== 'g' || at.source.parent !== undefined)) this.removals.add('attribute', 'id')\n at.children.forEach(walk)\n }\n walk(node)\n }\n}\n\n/** A gradient or a clip path: drawn only where something refers to it. */\nfunction isDefinition(node: Written): boolean {\n return GRADIENTS.has(node.name) || node.name === 'clipPath'\n}\n","/**\n * The canonical form a cleaned SVG is written in (0030), from the\n * cleaner's own tree; it never copies a span of the input.\n *\n * ```\n * svg := '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"' n ' ' n ' ' n ' ' n '\">' child* '</svg>'\n * child := '<' name attrs '/>' | '<' name attrs '>' child+ '</' name '>'\n * attrs := (' ' attr '=\"' value '\"')* id, then geometry, transform, paint, each in its table's order\n * id := ('g' | 'c') digits gradients g1, g2 …; clip paths c1, c2 …, in document order\n * ```\n *\n * ASCII alone, no whitespace but the single separators, no text, entity,\n * comment, declaration, namespace prefix or unused id. pdfmake reads the\n * file with xmldoc and sax and svg-to-pdfkit again with its own regexes;\n * with nothing in it but elements and plain attributes, every one of them\n * reads the same tree. Every value is generated from a parsed number or a\n * token, so none of `<>&\"'` can be in one; the writer refuses to write one\n * that holds any rather than escape it.\n */\nimport type { WrittenValue } from './svg-computed.js'\nimport type { Drawing, Written } from './svg-drawing.js'\nimport { SVG_NAMESPACE } from './svg-tree.js'\n\nconst MARKUP = /[<>&\"'\\u0080-￿]/\n\n/** One attribute as written, which no value may break out of. */\nexport function attribute(name: string, value: string): string {\n if (MARKUP.test(value))\n throw new Error(`the SVG writer was handed markup or a byte past ASCII for ${name}; a value is always generated, so this is a bug in the cleaner`)\n return ` ${name}=\"${value}\"`\n}\n\nexport function writeDrawing(drawing: Drawing): string {\n const parts: string[] = []\n const reference = (value: WrittenValue): string => {\n if (typeof value === 'string') return value\n const id = drawing.targets.get(value.reference.id)?.id\n // Every reference kept names a target the drawing writes with an id; one that does not would write `url(#)`, which cleaning would then refuse.\n if (id === undefined)\n throw new Error(\n `the SVG writer was handed a reference to nothing it writes, at ${value.reference.where}; every reference kept names a target, so this is a bug in the cleaner`,\n )\n return `url(#${id})${value.fallback === undefined ? '' : ` ${value.fallback}`}`\n }\n const write = (node: Written): void => {\n let attributes = node.name === 'svg' ? attribute('xmlns', SVG_NAMESPACE) : ''\n if (node.id !== undefined) attributes += attribute('id', node.id)\n for (const [name, value] of node.geometry) attributes += attribute(name, value)\n if (node.transform !== undefined) attributes += attribute('transform', node.transform)\n for (const [name, value] of node.properties) attributes += attribute(name, reference(value))\n if (node.children.length === 0) {\n parts.push(`<${node.name}${attributes}/>`)\n return\n }\n parts.push(`<${node.name}${attributes}>`)\n node.children.forEach(write)\n parts.push(`</${node.name}>`)\n }\n write(drawing.root)\n return parts.join('')\n}\n","/**\n * An SVG asset: cleaned once, when it is approved, into the one form the\n * renderer draws, and refused at print in any other (0030).\n *\n * `cleanSvg` runs where an asset is approved -- a host, and later a\n * builder's upload. It reads the file, removes what never draws and lists\n * it, refuses what would draw unsafely or otherwise than a browser draws\n * it, and writes the rest in the canonical form (`svg-write.ts`). The\n * approved asset is the bytes it returns, and its digest is theirs.\n *\n * `checkSvg` is the renderer's: it accepts bytes only when cleaning them\n * would change nothing -- when they are already exactly what `cleanSvg`\n * writes, and nothing would be removed. Nothing is dropped at print, so\n * what prints is in the approved form.\n *\n * One reader, here, because a host's approval, a builder's upload and the\n * renderer must all apply the same rules, and builder-core may import\n * report-spec alone of the packages that could hold them: a second copy\n * could disagree with the first, and nobody would find out until a logo\n * printed otherwise than it was approved.\n */\nimport { MAX_SVG_BYTES } from './limits.js'\nimport { styleTree } from './svg-computed.js'\nimport { costOf } from './svg-cost.js'\nimport { buildDrawing, type ViewBox } from './svg-drawing.js'\nimport type { SvgExtent } from './svg-extent.js'\nimport { refuse, Removals, type SvgRefusal, SvgRefused, type SvgRemoval } from './svg-refusal.js'\nimport { Stylesheet } from './svg-style.js'\nimport { readTree } from './svg-tree.js'\nimport { writeDrawing } from './svg-write.js'\n\nexport interface CleanSvg {\n readonly ok: true\n /** The canonical drawing: ASCII, what the approved asset holds. */\n readonly bytes: Uint8Array\n /** The drawing's own coordinates: what `contain` and `cover` keep the proportions of. */\n readonly viewBox: ViewBox\n /** What it costs a reader to paint, in the weighted segments `MAX_SVG_SEGMENTS` bounds. */\n readonly segments: number\n /** The transparency groups it makes, in the units `MAX_SVG_GROUPS` bounds. */\n readonly groups: number\n /** What the converter draws each time it draws it -- moves, lines and closes; curves; elements read, a clip path's for every element it clips; gradient stops written, a gradient's for every shape painted with it -- for the renderer's budget across pages. */\n readonly drawn: { readonly lines: number; readonly curves: number; readonly elements: number; readonly stops: number }\n /** How far the numbers svg-to-pdfkit writes for it reach wherever it is placed, and how deep it nests the graphics state: what the renderer holds an image of it to in an e-invoice's PDF/A-3 (`svg-extent.ts`). */\n readonly extent: SvgExtent\n /** What cleaning removed, by kind and name with a count: names only, never a value; the first `MAX_SVG_REMOVED_NAMES` names. */\n readonly removed: readonly SvgRemoval[]\n /** Removals of names past those listed, counted. */\n readonly removedMore: number\n}\n\n/** What `checkSvg` accepts: the drawing, which cleaning would not change. */\nexport type CheckedSvg = Omit<CleanSvg, 'removed' | 'removedMore'>\n\nexport function cleanSvg(bytes: Uint8Array): CleanSvg | SvgRefusal {\n try {\n return clean(bytes)\n } catch (error) {\n if (error instanceof SvgRefused) return { ok: false, code: error.code, message: error.message }\n throw error\n }\n}\n\nfunction clean(bytes: Uint8Array): CleanSvg {\n if (!(bytes instanceof Uint8Array)) refuse('not-svg', 'the asset has no bytes', 'hand it the bytes of the file')\n if (bytes.length > MAX_SVG_BYTES) refuse('too-large', `the file is ${bytes.length} bytes; the limit is ${MAX_SVG_BYTES}`)\n const removals = new Removals()\n const document = readTree(bytes, removals)\n const sheet = new Stylesheet(document.styles, removals)\n const drawing = buildDrawing(document, styleTree(document.root, sheet, removals), removals)\n const { segments, groups, drawn, extent } = costOf(drawing)\n const text = writeDrawing(drawing)\n if (text.length > MAX_SVG_BYTES) refuse('too-large', `the cleaned drawing would be ${text.length} bytes; the limit is ${MAX_SVG_BYTES}`)\n const written = new Uint8Array(text.length)\n for (let i = 0; i < text.length; i += 1) written[i] = text.charCodeAt(i)\n return { ok: true, bytes: written, viewBox: drawing.viewBox, segments, groups, drawn, extent, removed: removals.list(), removedMore: removals.more }\n}\n\n/** The renderer's check: the drawing, when `bytes` are already what `cleanSvg` writes; refused naming the first difference otherwise. */\nexport function checkSvg(bytes: Uint8Array): CheckedSvg | SvgRefusal {\n const cleaned = cleanSvg(bytes)\n if (!cleaned.ok) return cleaned\n const { removed, removedMore: _, ...checked } = cleaned\n const [first] = removed\n if (first !== undefined) {\n const what = first.kind === first.name ? `a ${first.kind}` : `the ${first.kind} ${first.name}`\n return { ok: false, code: 'unsupported', message: `the drawing holds ${what}, which cleaning removes; clean it with cleanSvg first` }\n }\n const length = Math.min(bytes.length, checked.bytes.length)\n let at = 0\n while (at < length && bytes[at] === checked.bytes[at]) at += 1\n if (at < length || bytes.length !== checked.bytes.length)\n return { ok: false, code: 'unsupported', message: `the drawing is not in the form cleanSvg writes, from byte ${at}; clean it with cleanSvg first` }\n return checked\n}\n","/**\n * How a font is refused: the codes, what a person can do about each, and\n * the refusal the reader throws where it finds a fault and catches once, at\n * its edge (0040).\n *\n * A refusal names what was found and where, by the name of a table this\n * reader knows, never a byte of the font: no name string, no tag a font\n * invented, no text of its licence. Numbers the reader decoded -- a\n * version, a format, the offset where a table runs out -- are said in the\n * reader's own digits, so a message holds nothing a font chose but a\n * number.\n */\n\n/** Why a font is refused, each the first thing found that is wrong with it. */\nexport const FONT_REFUSAL_CODES = [\n /** Not a font in any format this recognises. */\n 'not-a-font',\n /** A font in a format other than one TrueType font file: a collection, WOFF, WOFF2, EOT or Type 1 (`FONT_FORMATS`). */\n 'format',\n /** CFF or CFF2 outlines: an OpenType font of `OTTO`, or a 'CFF ' or CFF2 table. */\n 'cff',\n /** A variable font: an fvar table. */\n 'variable',\n /** Colour glyphs, which PDFKit does not draw: a COLR, 'SVG ', CBDT or sbix table. */\n 'colour',\n /** No TrueType outlines: no glyf or loca table, or not one glyph with a contour. */\n 'no-outlines',\n /** An OS/2 fsType that does not allow embedding a subset of the outlines (`FONT_EMBEDDING_REFUSALS`). */\n 'embedding',\n /** No Unicode character map in format 4 or 12 where PDFKit's fontkit looks for one, one that maps nothing, or a last-resort font's. */\n 'character-map',\n /** A table, a record or a field the specification does not allow, or one that runs past the end of the file. */\n 'malformed',\n /** Past `MAX_FONT_BYTES`, mapping more characters than `MAX_FONT_CHARACTERS`, or a glyph whose points times contours are past `MAX_FONT_GLYPH_WORK`. */\n 'too-large',\n] as const\nexport type FontRefusalCode = (typeof FONT_REFUSAL_CODES)[number]\n\n/** The font formats a `format` refusal names. */\nexport const FONT_FORMATS = [\n /** A TrueType or OpenType collection, `ttcf`: several fonts in one file. */\n 'collection',\n /** WOFF 1.0. */\n 'woff',\n /** WOFF 2.0. */\n 'woff2',\n /** Embedded OpenType, Microsoft's web font. */\n 'eot',\n /** A PostScript Type 1 font, as a PFB, a PFA or an sfnt of `typ1`. */\n 'type-1',\n] as const\nexport type FontFormat = (typeof FONT_FORMATS)[number]\n\n/** Why an fsType refuses embedding, each the first found, in this order. */\nexport const FONT_EMBEDDING_REFUSALS = [\n /** A value or an OS/2 version the specification does not define: bit 0, several usage bits in version 3 or later, a version past 5. */\n 'invalid',\n /** Restricted License embedding: the usage bits read as 2. */\n 'restricted',\n /** Bitmap embedding only (bit 9), from version 2: PDFKit embeds outlines. */\n 'bitmap-only',\n /** No subsetting (bit 8), from version 2: PDFKit always embeds a subset. */\n 'no-subsetting',\n] as const\nexport type FontEmbeddingRefusal = (typeof FONT_EMBEDDING_REFUSALS)[number]\n\n/** A refusal, said in English after the font's name -- the renderer says `the font ${message}` -- with, for a format or an embedding, which one, for a person's own language. */\nexport type FontRefusal =\n | { readonly ok: false; readonly code: Exclude<FontRefusalCode, 'format' | 'embedding'>; readonly message: string }\n | { readonly ok: false; readonly code: 'format'; readonly message: string; readonly format: FontFormat }\n | { readonly ok: false; readonly code: 'embedding'; readonly message: string; readonly embedding: FontEmbeddingRefusal }\n\n/**\n * What a person can do about each kind of refusal, said after what was\n * found. A font is what a person who brought their brand's typeface is\n * shown refused, so each one says what to ask for or export instead.\n */\nexport const FONT_ADVICE: { readonly [C in FontRefusalCode]: string } = {\n 'not-a-font': 'add the font as a TrueType file (.ttf)',\n format: 'export the face to use as a TrueType font file (.ttf)',\n cff: 'use the TrueType edition of the font (.ttf), which most foundries ship beside the OpenType CFF one (.otf)',\n variable: 'use a static instance of the font, one .ttf file for each weight and style',\n colour: 'use a font whose glyphs are outlines alone',\n 'no-outlines': 'use a font with TrueType outlines',\n embedding: \"ask the font's vendor for a licence and a file that allow embedding a subset in a PDF\",\n 'character-map': 'use a font that maps Unicode characters to its glyphs',\n malformed: 'save the font again from the program it was made in, or ask its vendor for a sound file',\n 'too-large': 'use a font file that holds fewer scripts',\n}\n\n/**\n * A refusal on its way out of the reader. It is thrown where the fault is\n * found, deep in a table, and caught once, at `readFont`'s or\n * `characterMap`'s edge, so that nothing partly read is ever returned; any\n * other error is the reader's own fault, and is let through for a test to\n * find.\n */\nexport class FontRefused extends Error {\n readonly refusal: FontRefusal\n\n constructor(refusal: FontRefusal) {\n super(refusal.message)\n this.refusal = refusal\n }\n}\n\n/** Refused, with what was found (`what`) and what to do, the code's own advice unless the refusal knows something more particular. */\nexport function refuse(code: Exclude<FontRefusalCode, 'format' | 'embedding'>, what: string, advice: string = FONT_ADVICE[code]): never {\n throw new FontRefused({ ok: false, code, message: `${what}; ${advice}` })\n}\n\n/** Refused as a format this does not read. */\nexport function refuseFormat(format: FontFormat, what: string): never {\n throw new FontRefused({ ok: false, code: 'format', format, message: `${what}; ${FONT_ADVICE.format}` })\n}\n\n/** Refused for what its fsType says of embedding. */\nexport function refuseEmbedding(embedding: FontEmbeddingRefusal, what: string): never {\n throw new FontRefused({ ok: false, code: 'embedding', embedding, message: `${what}; ${FONT_ADVICE.embedding}` })\n}\n\n/** The refusal `read` throws, or what it returns. */\nexport function caught<T>(read: () => T): T | FontRefusal {\n try {\n return read()\n } catch (error) {\n if (error instanceof FontRefused) return error.refusal\n throw error\n }\n}\n","/**\n * A font's bytes as the reader reads them (0040): what format the first\n * bytes say they are, the table directory, and reads that are each checked\n * against the bytes, so that a read past the end is a refusal and never a\n * `RangeError`.\n *\n * A table is read where the directory says it starts, and every read is\n * held inside the file, as fontkit -- the reader PDFKit draws with --\n * reads each table from its offset in the whole file. fontkit reads a\n * table's recorded length for two things, and so does this:\n *\n * - **A table recorded as empty is no table.** fontkit sees a table only\n * where its length is not 0, and PDFKit then reads a property of\n * nothing and throws inside pdfmake; `readFont` refuses every table it\n * reads empty (`seenTable`), the OS/2 table too, whose embedding\n * permissions would otherwise be read from a table that says it holds\n * no byte. `characterMap`, which reads the faces the renderer ships,\n * reads their character map whatever length is recorded for it.\n * - **An array no field counts ends where the length says.** fontkit reads\n * the index to location's offsets and version 2.0's PostScript names to\n * the table's recorded end; `readOutlines` and `readPost` hold them there.\n *\n * Otherwise the length does not cut a read short: fontkit reads a table's\n * fields past a length that understates them, and refusing it would refuse\n * a font PDFKit prints. Where a structure states its own length -- a\n * character map's subtable -- its arrays are held inside that length,\n * which fontkit reads them by.\n */\nimport { refuse, refuseFormat, type FontFormat } from './font-refusal.js'\n\n/** The tables the reader reads, by tag, each with the words a refusal calls it by. A tag the reader does not know is never repeated back. */\nconst TABLE_NAMES = {\n cmap: 'character map',\n head: 'font header',\n hhea: 'horizontal header',\n hmtx: 'horizontal metrics',\n maxp: 'maximum profile',\n name: 'naming',\n 'OS/2': 'OS/2 and Windows metrics',\n post: 'PostScript',\n glyf: 'glyph data',\n loca: 'index to location',\n vhea: 'vertical header',\n vmtx: 'vertical metrics',\n} as const\n\n/** A table the reader reads. */\nexport type TableTag = keyof typeof TABLE_NAMES\n\n/** A table's record: where it starts, how long its record says it is, and what a refusal calls it. */\nexport interface TableRecord {\n readonly offset: number\n readonly length: number\n /** `character map table (cmap)`, or `a table` for one the reader does not know. */\n readonly called: string\n}\n\n/** What the first bytes say a file is: one TrueType font, one CFF font, or a format this does not read. */\nexport type Sniffed = 'truetype' | 'cff' | FontFormat\n\n/** The sfnt versions and signatures, as the four bytes read as one big-endian number. */\nconst SIGNATURES: ReadonlyMap<number, Sniffed> = new Map([\n [0x00010000, 'truetype'],\n // Apple's 'true', which its TrueType Reference Manual allows and fontkit reads as TrueType.\n [0x74727565, 'truetype'],\n [0x4f54544f, 'cff'],\n [0x74746366, 'collection'],\n [0x774f4646, 'woff'],\n [0x774f4632, 'woff2'],\n // Apple's 'typ1', a Type 1 font in an sfnt.\n [0x74797031, 'type-1'],\n])\n\n/** '%!PS-AdobeFont' and '%!FontType1', how a PFA begins. */\nconst PFA = ['%!PS-AdobeFont', '%!FontType1'].map((text) => [...text].map((character) => character.charCodeAt(0)))\n\n/**\n * What a font's bytes are, from their first bytes alone, never a file's\n * name or a type a browser guessed: an sfnt by its version, a collection or\n * a web font by its signature, a Type 1 font as a PFB's segment marker or a\n * PFA's comment, and an EOT by its magic number 0x504C at byte 34 in a\n * header whose first field is the file's own size. Undefined for anything\n * else.\n */\nexport function sniffFont(bytes: Uint8Array): Sniffed | undefined {\n if (bytes.length >= 4) {\n const signature = ((bytes[0]! << 24) | (bytes[1]! << 16) | (bytes[2]! << 8) | bytes[3]!) >>> 0\n const found = SIGNATURES.get(signature)\n if (found !== undefined) return found\n }\n if (bytes[0] === 0x80 && bytes[1] === 0x01) return 'type-1'\n if (PFA.some((prefix) => prefix.every((byte, index) => bytes[index] === byte))) return 'type-1'\n if (bytes.length >= 36 && bytes[34] === 0x4c && bytes[35] === 0x50) {\n const size = (bytes[0]! | (bytes[1]! << 8) | (bytes[2]! << 16) | (bytes[3]! << 24)) >>> 0\n if (size === bytes.length) return 'eot'\n }\n return undefined\n}\n\n/** The words a `format` refusal says each format in. */\nconst FORMAT_WORDS: { readonly [F in FontFormat]: string } = {\n collection: 'is a font collection, which holds several fonts in one file',\n woff: 'is a WOFF web font, whose tables are compressed',\n woff2: 'is a WOFF2 web font, whose tables are compressed and transformed',\n eot: 'is an Embedded OpenType web font',\n 'type-1': 'is a PostScript Type 1 font',\n}\n\n/** Refused as the format `sniffFont` found, which is not one font in an sfnt. */\nexport function refuseSniffed(format: FontFormat): never {\n refuseFormat(format, FORMAT_WORDS[format])\n}\n\n/**\n * A font file: its bytes and its table directory, read once. The\n * directory's records are each held inside the file, and a tag twice is\n * refused, since the specification leaves unsaid which of the two a reader\n * takes and fontkit takes the last. Nothing here reads the sfnt version:\n * `readFont` judges it from `sniffFont` before it opens a file, and\n * `characterMap` reads the character map of any sfnt.\n */\nexport class FontFile {\n readonly bytes: Uint8Array\n readonly length: number\n private readonly view: DataView\n private readonly tables = new Map<string, TableRecord>()\n\n constructor(bytes: Uint8Array) {\n this.bytes = bytes\n this.length = bytes.length\n this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)\n if (this.length < 12) refuse('malformed', 'is cut off in its table directory')\n const count = this.view.getUint16(4)\n if (12 + 16 * count > this.length) refuse('malformed', 'is cut off in its table directory')\n for (let index = 0; index < count; index++) {\n const record = 12 + 16 * index\n const tag = String.fromCharCode(bytes[record]!, bytes[record + 1]!, bytes[record + 2]!, bytes[record + 3]!)\n const offset = this.view.getUint32(record + 8)\n const length = this.view.getUint32(record + 12)\n const known = Object.hasOwn(TABLE_NAMES, tag) ? TABLE_NAMES[tag as TableTag] : undefined\n const called = known === undefined ? 'a table' : `${known} table (${tag})`\n if (offset + length > this.length) refuse('malformed', `has ${called} that runs past the end of the file`)\n if (this.tables.has(tag)) refuse('malformed', known === undefined ? 'has two tables of one tag' : `has two ${known} tables (${tag})`)\n this.tables.set(tag, { offset, length, called })\n }\n }\n\n /** Whether the directory holds `tag`. */\n has(tag: string): boolean {\n return this.tables.has(tag)\n }\n\n /** Whether fontkit sees `tag`: the directory holds it, recorded as more than no byte. */\n seen(tag: TableTag): boolean {\n return (this.tables.get(tag)?.length ?? 0) > 0\n }\n\n /** The table `tag`, refused as missing when the directory has none. */\n table(tag: TableTag): TableRecord {\n const found = this.tables.get(tag)\n if (found === undefined) refuse('malformed', `has no ${TABLE_NAMES[tag]} table (${tag})`)\n return found\n }\n\n /** The table `tag` as fontkit sees it: refused as missing, and as empty where its recorded length is 0, since fontkit then sees no table at all. */\n seenTable(tag: TableTag): TableRecord {\n const found = this.table(tag)\n if (found.length === 0) refuse('malformed', `has an empty ${TABLE_NAMES[tag]} table (${tag})`)\n return found\n }\n\n /** Refused unless `size` bytes at `at` lie inside the file; `table` names where the read was. */\n need(at: number, size: number, table: TableRecord): void {\n if (at < 0 || size < 0 || at + size > this.length) refuse('malformed', `has its ${table.called} cut off at byte ${Math.min(at, this.length)}`)\n }\n\n u8(at: number, table: TableRecord): number {\n this.need(at, 1, table)\n return this.view.getUint8(at)\n }\n\n u16(at: number, table: TableRecord): number {\n this.need(at, 2, table)\n return this.view.getUint16(at)\n }\n\n i16(at: number, table: TableRecord): number {\n this.need(at, 2, table)\n return this.view.getInt16(at)\n }\n\n u32(at: number, table: TableRecord): number {\n this.need(at, 4, table)\n return this.view.getUint32(at)\n }\n}\n","/**\n * Which characters a font draws: the code points its character map maps\n * to a glyph other than glyph 0, read as fontkit, through which PDFKit lays\n * out every run, reads them (0040, extending 0011).\n *\n * pdfmake draws a character its font has no glyph for as glyph 0 and writes\n * U+0000 to the text layer, and the render succeeds (0011). So the renderer\n * holds every character a document prints to this map before anything is\n * laid out, and a character it does not hold is refused. That holds only\n * where this map is the one fontkit reads, so:\n *\n * - **The subtable is fontkit's.** fontkit 2.0.4 takes the first record of\n * Windows full repertoire (3, 10), then Unicode (0, 6), (0, 4), Windows\n * BMP (3, 1) and Unicode (0, 3), (0, 2), (0, 1), (0, 0), in that order,\n * whatever their formats (`CmapProcessor`, `findSubtable`); a font with\n * none it re-encodes from a legacy subtable, which this refuses.\n * - **Formats 4 and 12 alone**, the two the specification recommends for\n * Unicode; the subtable fontkit takes in any other format is refused.\n * - **The search is fontkit's**, a binary search of segments or groups, so\n * a subtable whose segments are not sorted and apart -- where a binary\n * search and a walk would find different glyphs -- is refused, as is an\n * idRangeOffset fontkit would read between two glyph indices.\n * - **A glyph index outside the glyph array** is glyph 0, as fontkit's\n * bounded array reads it.\n * - **The variation sequences are fontkit's too.** fontkit decodes the\n * first Unicode Variation Sequences record, (0, 5), when it first lays\n * text out, and throws on a format it does not know; it decodes every\n * sequence for a character followed by a variation selector. So that\n * subtable is held to format 14, its records and the arrays they point\n * to inside the file, and every glyph a sequence names to the glyph\n * count (`readFont`); a sequence maps no character of its own, since\n * the renderer holds text to the base character's glyph.\n *\n * Every array is held inside the subtable's own length, and the subtable\n * inside the file; segments and groups are counted from what those lengths\n * hold, never allocated from a count first. A format 4 subtable maps at\n * most the 65,536 code points of the BMP; a format 12 subtable's code\n * points are summed from its groups, which are apart, and refused past\n * `MAX_FONT_CHARACTERS` before one is added. The variation sequences'\n * arrays, which records may point to many times, may add up to no more\n * than the font's own size.\n */\nimport { FontFile, type TableRecord } from './font-file.js'\nimport { caught, refuse, type FontRefusal } from './font-refusal.js'\nimport { MAX_FONT_CHARACTERS } from './limits.js'\n\n/** The code points a font maps to a glyph, as `characterMap` reads them. */\nexport interface FontCharacters {\n readonly ok: true\n readonly characters: ReadonlySet<number>\n}\n\n/** What the character map holds: the characters, and the largest glyph index it, or a variation sequence, maps one to, which `readFont` holds to the glyph count. */\nexport interface CharacterMap {\n readonly characters: Set<number>\n readonly largestGlyph: number\n}\n\n/** fontkit's order of the Unicode subtables it looks for, as (platform, encoding). */\nconst PREFERENCE: readonly (readonly [number, number])[] = [\n [3, 10],\n [0, 6],\n [0, 4],\n [3, 1],\n [0, 3],\n [0, 2],\n [0, 1],\n [0, 0],\n]\n\n/** The largest code point Unicode has. */\nconst LAST_CODE_POINT = 0x10ffff\n\n/**\n * The code points a font maps to a glyph other than glyph 0, from the\n * character map alone: the table directory and the 'cmap' table, of any\n * sfnt, and nothing else of the font. `readFont` reads the same map and\n * holds the rest of the font besides; this is what the renderer reads of\n * the faces it ships, whose embedding nothing needs to judge again. It\n * holds no glyph index to the glyph count, which it does not read, and\n * reads the character map whatever length the directory records for it,\n * which fontkit does not: a font a host brings is held to `readFont`'s\n * characters, which hold both.\n */\nexport function characterMap(bytes: Uint8Array): FontCharacters | FontRefusal {\n return caught(() => ({ ok: true, characters: readCharacterMap(new FontFile(bytes)).characters }))\n}\n\n/** The character map of an opened font file, or the refusal thrown from inside it. */\nexport function readCharacterMap(file: FontFile): CharacterMap {\n const table = file.table('cmap')\n if (file.u16(table.offset, table) !== 0) refuse('malformed', 'has a character map of a version the specification does not define')\n const count = file.u16(table.offset + 2, table)\n file.need(table.offset + 4, 8 * count, table)\n const records: { platform: number; encoding: number; at: number }[] = []\n for (let index = 0; index < count; index++) {\n const record = table.offset + 4 + 8 * index\n records.push({ platform: file.u16(record, table), encoding: file.u16(record + 2, table), at: table.offset + file.u32(record + 4, table) })\n }\n const chosen = PREFERENCE.map(([platform, encoding]) => records.find((record) => record.platform === platform && record.encoding === encoding)).find(\n (record) => record !== undefined,\n )\n if (chosen === undefined) refuse('character-map', 'has no Unicode character map in format 4 or 12')\n const format = file.u16(chosen.at, table)\n const read =\n format === 4\n ? format4(file, table, chosen.at)\n : format === 12\n ? format12(file, table, chosen.at)\n : refuse('character-map', `maps Unicode in a subtable of format ${format}, where formats 4 and 12 are read`)\n if (read.characters.size === 0) refuse('character-map', 'maps no character to a glyph')\n const sequences = records.find((record) => record.platform === 0 && record.encoding === 5)\n if (sequences === undefined) return read\n return { characters: read.characters, largestGlyph: Math.max(read.largestGlyph, variationSequences(file, table, sequences.at)) }\n}\n\n/**\n * A Unicode Variation Sequences subtable, format 14: its records inside its\n * own length, each record's default and non-default arrays inside the file\n * and their sizes summed, refused past the font's size before a mapping is\n * walked; the largest glyph a non-default sequence maps to, returned.\n */\nfunction variationSequences(file: FontFile, table: TableRecord, at: number): number {\n if (file.u16(at, table) !== 14) refuse('malformed', 'has a variation sequences subtable in a format other than 14')\n const length = file.u32(at + 2, table)\n const count = file.u32(at + 6, table)\n if (10 + 11 * count > length) refuse('malformed', 'has a variation sequences subtable shorter than its records')\n file.need(at, length, table)\n let bytes = 0\n let largestGlyph = 0\n for (let index = 0; index < count; index++) {\n // A record: the selector, three bytes, then the offsets of its default and non-default arrays from the subtable's start, 0 for none.\n const record = at + 10 + 11 * index\n const defaults = file.u32(record + 3, table)\n const others = file.u32(record + 7, table)\n // Ranges of four bytes, and mappings of five -- a code point and a glyph -- each array after its count.\n const ranges = defaults === 0 ? 0 : file.u32(at + defaults, table)\n const mappings = others === 0 ? 0 : file.u32(at + others, table)\n if (defaults !== 0) file.need(at + defaults + 4, 4 * ranges, table)\n if (others !== 0) file.need(at + others + 4, 5 * mappings, table)\n bytes += (defaults === 0 ? 0 : 4 + 4 * ranges) + (others === 0 ? 0 : 4 + 5 * mappings)\n if (bytes > file.length) refuse('malformed', 'has variation sequences that add up to more bytes than the font holds')\n for (let mapping = 0; mapping < mappings; mapping++) largestGlyph = Math.max(largestGlyph, file.u16(at + others + 7 + 5 * mapping, table))\n }\n return largestGlyph\n}\n\n/**\n * A format 4 subtable: four arrays of segments and the glyph array after\n * them, each code point mapped by its segment's delta or, where its\n * idRangeOffset is not 0, through the glyph array, all modulo 65,536.\n */\nfunction format4(file: FontFile, table: TableRecord, at: number): CharacterMap {\n const length = file.u16(at + 2, table)\n const doubled = file.u16(at + 6, table)\n if (length % 2 !== 0 || doubled % 2 !== 0) refuse('malformed', 'has a character map subtable of format 4 of an odd length')\n const segments = doubled / 2\n // The header's 14 bytes, the four arrays and the pad between the first two.\n const arrays = 16 + 8 * segments\n if (length < arrays) refuse('malformed', 'has a character map subtable of format 4 shorter than its segments')\n file.need(at, length, table)\n const ends = at + 14\n const starts = ends + 2 * segments + 2\n const deltas = starts + 2 * segments\n const offsets = deltas + 2 * segments\n const glyphArray = offsets + 2 * segments\n const entries = (length - arrays) / 2\n const characters = new Set<number>()\n let largestGlyph = 0\n for (let segment = 0, previous = -1; segment < segments; segment++) {\n const end = file.u16(ends + 2 * segment, table)\n const start = file.u16(starts + 2 * segment, table)\n const delta = file.u16(deltas + 2 * segment, table)\n const rangeOffset = file.u16(offsets + 2 * segment, table)\n if (start > end || start <= previous) refuse('malformed', 'has a character map subtable of format 4 whose segments are out of order or overlap')\n if (rangeOffset % 2 !== 0) refuse('malformed', 'has a character map subtable of format 4 with an odd idRangeOffset')\n previous = end\n for (let point = start; point <= end; point++) {\n let glyph: number\n if (rangeOffset === 0) glyph = (point + delta) & 0xffff\n else {\n // The specification's address of the entry, from idRangeOffset[segment], as an index into the glyph array.\n const entry = rangeOffset / 2 + (point - start) - (segments - segment)\n const indexed = entry >= 0 && entry < entries ? file.u16(glyphArray + 2 * entry, table) : 0\n glyph = indexed === 0 ? 0 : (indexed + delta) & 0xffff\n }\n if (glyph === 0) continue\n characters.add(point)\n if (glyph > largestGlyph) largestGlyph = glyph\n }\n }\n return { characters, largestGlyph }\n}\n\n/** A format 12 subtable: groups of consecutive code points, each mapped to consecutive glyphs from its first. */\nfunction format12(file: FontFile, table: TableRecord, at: number): CharacterMap {\n const length = file.u32(at + 4, table)\n const groups = file.u32(at + 12, table)\n if (16 + 12 * groups > length) refuse('malformed', 'has a character map subtable of format 12 shorter than its groups')\n file.need(at, length, table)\n let total = 0\n for (let group = 0, previous = -1; group < groups; group++) {\n const record = at + 16 + 12 * group\n const start = file.u32(record, table)\n const end = file.u32(record + 4, table)\n if (start > end || start <= previous) refuse('malformed', 'has a character map subtable of format 12 whose groups are out of order or overlap')\n if (end > LAST_CODE_POINT) refuse('malformed', 'has a character map subtable of format 12 that maps past the last Unicode code point')\n previous = end\n total += end - start + 1\n }\n if (total > MAX_FONT_CHARACTERS) refuse('too-large', `maps ${total} characters, where the most a font may map is ${MAX_FONT_CHARACTERS}`)\n const characters = new Set<number>()\n let largestGlyph = 0\n for (let group = 0; group < groups; group++) {\n const record = at + 16 + 12 * group\n const start = file.u32(record, table)\n const end = file.u32(record + 4, table)\n const first = file.u32(record + 8, table)\n for (let point = start; point <= end; point++) if (first + (point - start) !== 0) characters.add(point)\n if (first + (end - start) > largestGlyph) largestGlyph = first + (end - start)\n }\n return { characters, largestGlyph }\n}\n","/**\n * A font's names, from its naming table (0040): what an approver reads and\n * a builder shows, and the PostScript name the PDF names the font by.\n *\n * - **Returned, never judged.** The family and subfamily -- the\n * typographic names, IDs 16 and 17, before IDs 1 and 2, with the family\n * of ID 1 beside a typographic one (`legacyFamily`) -- the full name,\n * the version, the copyright and the licence description and its\n * address are handed back for a person to read. A customer's font licence\n * is the customer's; nothing here decides what one says.\n * - **The PostScript name cannot write PDF syntax.** PDFKit writes it into\n * the PDF as a name object as it stands, each space replaced by an\n * underscore and nothing else escaped (`EmbeddedFont.embed`, pdfkit.js\n * 2670; `PDFObject.convert`, 120-122), so a slash, a bracket or a\n * percent sign in it would write PDF syntax the font chose, and a number\n * sign would start an escape. Which record fontkit returns depends on\n * their order and languages, so every record of name ID 6 is held to the\n * specification's rule -- at most 63 characters of printable ASCII, none\n * of `[ ] ( ) { } < > / %` -- with a number sign refused besides and a\n * space admitted, since PDFKit replaces it: Microsoft Himalaya's Windows\n * record is `Microsoft Himalaya`. Each is held as fontkit decodes it, so\n * each must be in an encoding fontkit and this decode alike: UTF-16 on\n * the Unicode platform's encodings 0 to 6 and Windows' 1 and 10, or Mac\n * Roman in English. fontkit reads any other encoding a byte at a time,\n * or not as a string at all: a name of UTF-16 read so is a NUL before\n * every letter in the PDF, and one it cannot decode throws inside PDFKit.\n * The name returned is the best record's, as for every other name:\n * Corbel Light's Unicode record says `Corbel-Light` where its Windows\n * record, which fontkit returns, says `CorbelLight`. Every name the\n * records hold is returned besides, since fontkit returns the last\n * English one, not the best, and PDFKit keeps a document's faces by it\n * (0043).\n * - **The table is one fontkit decodes.** fontkit loses the whole table,\n * and PDFKit names the font `undefined`, where a record is of a platform\n * past the four the specification names for names, or a version 1\n * table's record names a language tag the table does not hold; both are\n * refused.\n * - **Every string fontkit decodes is bounded.** fontkit decodes every\n * record of the table when PDFKit asks for the PostScript name, so records\n * that point many times at one long string would cost it far more than\n * the file: their lengths, with a version 1 table's language tags, may\n * add up to no more than the font's own size.\n *\n * One record is decoded for each name returned, the best of its ID: a\n * Windows Unicode record in English (United States), then any Windows\n * Unicode record, then a Unicode one, then a Macintosh Roman one in\n * English. UTF-16 is decoded here, a lone surrogate as U+FFFD, and Mac\n * Roman from its table below, with no `TextDecoder`, which report-spec's\n * library does not have.\n */\nimport type { FontFile, TableRecord } from './font-file.js'\nimport { refuse } from './font-refusal.js'\n\n/** What a font says it is called, and what it says of its licence, as it says it. */\nexport interface FontNames {\n /** The typographic family (name ID 16), or the family (1). */\n readonly family: string\n /**\n * The family of name ID 1, where the font states a typographic family\n * (16) before it and `family` is that one; absent where `family` is name\n * ID 1 itself. It is the name an application that lists four faces to a\n * family knows the face by -- Word among them, to which \"Probe Sans\n * Light\" is a family and \"Probe Sans\" another -- so a writer that names\n * a face for such a reader names `legacyFamily ?? family` (0068).\n */\n readonly legacyFamily?: string\n /** The typographic subfamily (17), or the subfamily (2). */\n readonly subfamily: string\n /** The PostScript name (6), which the PDF names the font by: PDFKit writes it after a subset tag, each space as an underscore. */\n readonly postScriptName: string\n /**\n * Every PostScript name the font's records of name ID 6 hold, each once,\n * in table order, `postScriptName` among them: fontkit returns one of\n * them, the last English record's, so a renderer that tells one face from\n * another by the name PDFKit keeps it by reads them all (0043).\n */\n readonly postScriptNames: readonly string[]\n /** The full name (4). */\n readonly fullName?: string\n /** The version string (5). */\n readonly version?: string\n /** The copyright notice (0). */\n readonly copyright?: string\n /** The licence description (13), as the font states it. */\n readonly licence?: string\n /** The licence information address (14), as the font states it, never opened. */\n readonly licenceUrl?: string\n}\n\n/** A name record, as the table lists it. */\ninterface NameRecord {\n readonly platform: number\n readonly encoding: number\n readonly language: number\n readonly id: number\n readonly at: number\n readonly length: number\n}\n\n/** Mac Roman's upper half, 0x80 to 0xFF, as Apple's mapping to Unicode gives it; the lower half is ASCII. */\nconst MAC_ROMAN = 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ'\n\n/** The characters a PostScript name may not hold among printable ASCII: the specification's ten, and the number sign, which starts an escape in a PDF name. */\nconst NOT_IN_POSTSCRIPT_NAMES = new Set([...'[](){}<>/%#'].map((character) => character.charCodeAt(0)))\n\n/** The longest PostScript name the specification allows. */\nconst POSTSCRIPT_NAME_LENGTH = 63\n\n/** The last of the Unicode platform's encodings the specification defines, 0 to 6, the ones fontkit decodes as UTF-16. */\nconst LAST_UNICODE_ENCODING = 6\n\n/** How a record `rank` ranks is encoded: Mac Roman on the Macintosh platform, UTF-16 on Unicode's and Windows'. */\nfunction encodingOf(record: NameRecord): 'utf-16' | 'mac-roman' {\n return record.platform === 1 ? 'mac-roman' : 'utf-16'\n}\n\n/**\n * How good a record is as the one name of its ID a person reads, lower\n * better; undefined for one never read. A ranked record is one fontkit\n * decodes as this does: Windows symbol (3, 0) is UTF-16 to the\n * specification and no string to fontkit, and Mac Roman in another\n * language than English is, for fontkit, another Macintosh encoding.\n */\nfunction rank(record: NameRecord): number | undefined {\n if (record.platform === 3 && (record.encoding === 1 || record.encoding === 10)) return record.language === 0x409 ? 0 : 1\n if (record.platform === 0 && record.encoding <= LAST_UNICODE_ENCODING) return 2\n if (record.platform === 1 && record.encoding === 0 && record.language === 0) return 3\n return undefined\n}\n\n/** The last platform fontkit decodes a name of: Unicode, Macintosh, ISO and Windows, 0 to 3. */\nconst LAST_NAME_PLATFORM = 3\n\n/** The first language ID that names a version 1 table's language tag, by its index from here. */\nconst FIRST_LANGUAGE_TAG = 0x8000\n\n/** The naming table's records, each string held inside the file, and their lengths held to the font's size. */\nfunction records(file: FontFile, table: TableRecord): NameRecord[] {\n const version = file.u16(table.offset, table)\n if (version > 1) refuse('malformed', 'has a naming table of a version the specification does not define')\n const count = file.u16(table.offset + 2, table)\n const storage = table.offset + file.u16(table.offset + 4, table)\n file.need(table.offset + 6, 12 * count, table)\n const found: NameRecord[] = []\n let decoded = 0\n for (let index = 0; index < count; index++) {\n const record = table.offset + 6 + 12 * index\n const platform = file.u16(record, table)\n if (platform > LAST_NAME_PLATFORM) refuse('malformed', 'has a name record of a platform other than Unicode, Macintosh, ISO and Windows')\n const length = file.u16(record + 8, table)\n const at = storage + file.u16(record + 10, table)\n file.need(at, length, table)\n decoded += length\n found.push({ platform, encoding: file.u16(record + 2, table), language: file.u16(record + 4, table), id: file.u16(record + 6, table), at, length })\n }\n if (version === 1) {\n const tags = table.offset + 6 + 12 * count\n const tagCount = file.u16(tags, table)\n file.need(tags + 2, 4 * tagCount, table)\n for (let index = 0; index < tagCount; index++) {\n const length = file.u16(tags + 2 + 4 * index, table)\n file.need(storage + file.u16(tags + 4 + 4 * index, table), length, table)\n decoded += length\n }\n // fontkit looks a language from 0x8000 up among the tags, and loses the table where it is not there.\n if (found.some((record) => record.language >= FIRST_LANGUAGE_TAG && record.language - FIRST_LANGUAGE_TAG >= tagCount))\n refuse('malformed', 'has a name record whose language tag the naming table does not hold')\n }\n if (decoded > file.length) refuse('malformed', 'has name strings that add up to more bytes than the font holds')\n return found\n}\n\n/** A record's string, decoded. */\nfunction decode(file: FontFile, record: NameRecord): string {\n const bytes = file.bytes.subarray(record.at, record.at + record.length)\n if (encodingOf(record) === 'mac-roman') {\n let text = ''\n for (const byte of bytes) text += byte < 0x80 ? String.fromCharCode(byte) : MAC_ROMAN[byte - 0x80]!\n return text\n }\n if (bytes.length % 2 !== 0) refuse('malformed', 'has a name in UTF-16 of an odd number of bytes')\n let text = ''\n for (let at = 0; at < bytes.length; at += 2) {\n const unit = (bytes[at]! << 8) | bytes[at + 1]!\n const next = at + 3 < bytes.length ? (bytes[at + 2]! << 8) | bytes[at + 3]! : -1\n if (unit >= 0xd800 && unit <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {\n text += String.fromCharCode(unit, next)\n at += 2\n } else text += unit >= 0xd800 && unit <= 0xdfff ? '�' : String.fromCharCode(unit)\n }\n return text\n}\n\n/** The PostScript name, the best record's, and every name the records of name ID 6 hold, once every one of them is one fontkit decodes alike and holds a name PDFKit writes as one PDF name. */\nfunction postScriptNames(file: FontFile, all: readonly NameRecord[]): { readonly best: string; readonly all: readonly string[] } {\n const names = new Set<string>()\n for (const record of all) {\n if (record.id !== 6) continue\n if (rank(record) === undefined) refuse('malformed', 'has a PostScript name in an encoding this does not read')\n // Read no further than the longest name allowed: a record of 65,535 bytes is refused unread.\n if (record.length > (encodingOf(record) === 'utf-16' ? 2 : 1) * POSTSCRIPT_NAME_LENGTH)\n refuse('malformed', `has a PostScript name longer than ${POSTSCRIPT_NAME_LENGTH} characters`)\n const text = decode(file, record)\n for (const character of text) {\n const point = character.codePointAt(0)!\n if (point !== 0x20 && (point < 33 || point > 126 || NOT_IN_POSTSCRIPT_NAMES.has(point)))\n refuse(\n 'malformed',\n 'has a PostScript name with a character PDFKit would write into the PDF as syntax: a delimiter, a number sign, or one outside printable ASCII',\n )\n }\n if (text.trim().length === 0) refuse('malformed', 'has an empty PostScript name')\n names.add(text)\n }\n // Every record of name ID 6 is ranked by now, so there is a best one wherever there is one.\n const name = best(file, all, 6)\n if (name === undefined) refuse('malformed', 'has no PostScript name (name ID 6)')\n return { best: name, all: [...names] }\n}\n\n/** The best record of name ID `id`, decoded; undefined when none is one this reads. */\nfunction best(file: FontFile, all: readonly NameRecord[], id: number): string | undefined {\n let chosen: NameRecord | undefined\n let chosenRank = Number.POSITIVE_INFINITY\n for (const record of all) {\n const ranked = record.id === id ? rank(record) : undefined\n if (ranked !== undefined && ranked < chosenRank) {\n chosen = record\n chosenRank = ranked\n }\n }\n return chosen === undefined ? undefined : decode(file, chosen)\n}\n\n/** A font's names, read from its naming table. */\nexport function readNames(file: FontFile): FontNames {\n const all = records(file, file.table('name'))\n const postScript = postScriptNames(file, all)\n const [typographic, legacy] = [best(file, all, 16), best(file, all, 1)]\n const family = typographic ?? legacy\n const subfamily = best(file, all, 17) ?? best(file, all, 2)\n if (family === undefined || subfamily === undefined) refuse('malformed', 'has no family and subfamily name (name IDs 1 and 2)')\n const optional = { fullName: 4, version: 5, copyright: 0, licence: 13, licenceUrl: 14 } as const\n const names: { -readonly [K in keyof FontNames]: FontNames[K] } = { family, subfamily, postScriptName: postScript.best, postScriptNames: postScript.all }\n // Said only beside a typographic family: where there is none, `family` is name ID 1 already.\n if (typographic !== undefined && legacy !== undefined) names.legacyFamily = legacy\n for (const [key, id] of Object.entries(optional) as [keyof typeof optional, number][]) {\n const text = best(file, all, id)\n if (text !== undefined) names[key] = text\n }\n return names\n}\n","/**\n * A TrueType font's outlines, walked once for their structure (0040): the\n * index to location's offsets, and every glyph description they point to,\n * as fontkit reads them when PDFKit measures a glyph and subsets the font.\n *\n * fontkit reads a glyph's header for its box whenever it measures the\n * glyph, empty or not, and decodes the whole description when it subsets\n * the font; it reads each from the glyph data table's start, bounded by\n * nothing but the file (`TTFGlyph`, `TTFSubset`). So that a font this\n * accepts is one fontkit reads, every offset is held in order and inside\n * the file and inside the length loca's record gives -- fontkit reads the\n * offsets to there, and draws a glyph past the last it read as nothing --\n * every glyph's header too, and every description is walked to\n * its end inside its own extent: a simple glyph's contour ends, its\n * instructions, its flags and repeats and the coordinates they say follow;\n * a composite's components, each naming a glyph the font has. Nothing is\n * decoded into points, nothing recurses, and the walk is bounded by the\n * glyph data's bytes. A simple glyph's points times its contours is held to\n * `MAX_FONT_GLYPH_WORK`: fontkit looks each point up among the contour\n * ends (`_decodeSimple`), so one glyph of 32,767 contours and 65,534 points,\n * 66 KB of a font, took PDFKit 1.6 s to subset. And every glyph's points,\n * and its points times its contours, are held together to\n * `MAX_FONT_POINTS` and `MAX_FONT_OUTLINE_WORK`: a composite may reach\n * every glyph the font has, so one printed character can put them all in\n * the subset, which took PDFKit 162 s for one 'A' before the bound (0043);\n * and so are the composites' components, `MAX_FONT_COMPONENTS`, which the\n * subset decodes into a list however many name one glyph.\n *\n * What is not judged: what an outline looks like, whether its points make\n * sense, its instructions, which no PDF reader runs, and whether a\n * component names its own glyph, which fontkit's subset includes once.\n */\nimport type { FontFile, TableRecord } from './font-file.js'\nimport { refuse } from './font-refusal.js'\nimport { MAX_FONT_COMPONENTS, MAX_FONT_GLYPH_WORK, MAX_FONT_OUTLINE_WORK, MAX_FONT_POINTS } from './limits.js'\n\n/** A glyph header: the contour count and the box, ten bytes. */\nconst HEADER = 10\n\n/** Simple glyph flags (glyf, \"Simple Glyph Description\"). */\nconst X_SHORT = 0x02\nconst Y_SHORT = 0x04\nconst REPEAT = 0x08\nconst X_SAME_OR_POSITIVE = 0x10\nconst Y_SAME_OR_POSITIVE = 0x20\n\n/** Composite glyph flags (glyf, \"Composite Glyph Description\"). */\nconst ARGS_ARE_WORDS = 0x0001\nconst A_SCALE = 0x0008\nconst MORE_COMPONENTS = 0x0020\nconst AN_X_AND_Y_SCALE = 0x0040\nconst A_TWO_BY_TWO = 0x0080\n\n/**\n * The outlines of a font of `glyphs` glyphs whose index to location is in\n * `locFormat`, walked; refused as `no-outlines` when not one glyph has a\n * contour, as a font of bitmaps alone has.\n */\nexport function readOutlines(file: FontFile, glyphs: number, locFormat: 0 | 1): void {\n const loca = file.table('loca')\n const glyf = file.table('glyf')\n const size = locFormat === 0 ? 2 : 4\n file.need(loca.offset, size * (glyphs + 1), loca)\n if (loca.length < size * (glyphs + 1))\n refuse('malformed', `has an index to location table (loca) whose recorded length holds fewer offsets than its ${glyphs} glyphs need`)\n const offsetOf = (glyph: number): number => (locFormat === 0 ? 2 * file.u16(loca.offset + 2 * glyph, loca) : file.u32(loca.offset + 4 * glyph, loca))\n let drawn = 0\n const tally: Tally = { points: 0, work: 0, components: 0 }\n let start = offsetOf(0)\n for (let glyph = 0; glyph < glyphs; glyph++) {\n const end = offsetOf(glyph + 1)\n if (end < start) refuse('malformed', 'has glyph offsets out of order in its index to location table (loca)')\n // fontkit reads the header for the glyph's box even where the glyph is empty.\n file.need(glyf.offset + start, HEADER, glyf)\n file.need(glyf.offset + start, end - start, glyf)\n if (end > start) {\n if (end - start < HEADER) refuse('malformed', 'has a glyph description shorter than its header')\n if (walk(file, glyf, glyf.offset + start, glyf.offset + end, glyphs, tally)) drawn += 1\n }\n start = end\n }\n if (drawn === 0) refuse('no-outlines', 'has no glyph with an outline')\n}\n\n/** What the glyphs walked so far hold together: the simple glyphs' points, and their points times their contours, and the composites' components. */\ninterface Tally {\n points: number\n work: number\n components: number\n}\n\n/** One glyph description from `at` to `end`, walked; whether it has a contour or a component. */\nfunction walk(file: FontFile, glyf: TableRecord, at: number, end: number, glyphs: number, tally: Tally): boolean {\n const contours = file.i16(at, glyf)\n if (contours > 0) simple(file, glyf, at + HEADER, end, contours, tally)\n else if (contours < 0) compound(file, glyf, at + HEADER, end, glyphs, tally)\n return contours !== 0\n}\n\n/** Refused unless `at` lies inside the description, which ends at `end`. */\nfunction inside(at: number, end: number): void {\n if (at > end) refuse('malformed', 'has a glyph description that runs past its end')\n}\n\n/** A simple glyph: its contour ends, its instructions, its flags and the coordinates they say follow, inside its extent, its points and work added to `tally`. */\nfunction simple(file: FontFile, glyf: TableRecord, from: number, end: number, contours: number, tally: Tally): void {\n let at = from + 2 * contours\n inside(at + 2, end)\n const points = file.u16(at - 2, glyf) + 1\n if (points * contours > MAX_FONT_GLYPH_WORK)\n refuse(\n 'too-large',\n `has a glyph of ${contours} contours and ${points} points, past the ${MAX_FONT_GLYPH_WORK} of the two multiplied that a glyph may be`,\n \"simplify the glyph's outline in a font editor, or use another font\",\n )\n tally.points += points\n tally.work += points * contours\n if (tally.points > MAX_FONT_POINTS)\n refuse(\n 'too-large',\n `has glyphs of more than ${MAX_FONT_POINTS} points together, the most a font's glyphs may have`,\n 'use a font file that holds fewer scripts',\n )\n if (tally.work > MAX_FONT_OUTLINE_WORK)\n refuse(\n 'too-large',\n `has glyphs whose points times contours come to more than ${MAX_FONT_OUTLINE_WORK} together, the most a font's glyphs may`,\n 'use a font file that holds fewer scripts',\n )\n const instructions = file.u16(at, glyf)\n at += 2 + instructions\n let flags = 0\n let coordinates = 0\n // fontkit reads a repeat whole, even past the last point, and the coordinates of every flag it read.\n while (flags < points) {\n inside(at + 1, end)\n const flag = file.u8(at, glyf)\n at += 1\n let times = 1\n if ((flag & REPEAT) !== 0) {\n inside(at + 1, end)\n times += file.u8(at, glyf)\n at += 1\n }\n flags += times\n const x = (flag & X_SHORT) !== 0 ? 1 : (flag & X_SAME_OR_POSITIVE) !== 0 ? 0 : 2\n const y = (flag & Y_SHORT) !== 0 ? 1 : (flag & Y_SAME_OR_POSITIVE) !== 0 ? 0 : 2\n coordinates += times * (x + y)\n }\n inside(at + coordinates, end)\n}\n\n/** A composite glyph: its components, each a flag word, a glyph index the font has, its offsets and its transform, inside its extent, counted in `tally`. */\nfunction compound(file: FontFile, glyf: TableRecord, from: number, end: number, glyphs: number, tally: Tally): void {\n let at = from\n let flags = MORE_COMPONENTS\n while ((flags & MORE_COMPONENTS) !== 0) {\n tally.components += 1\n if (tally.components > MAX_FONT_COMPONENTS)\n refuse(\n 'too-large',\n `has composite glyphs of more than ${MAX_FONT_COMPONENTS} components together, the most a font's glyphs may have`,\n 'use a font file that holds fewer scripts',\n )\n inside(at + 4, end)\n flags = file.u16(at, glyf)\n if (file.u16(at + 2, glyf) >= glyphs) refuse('malformed', 'has a composite glyph made of a glyph the font does not have')\n at += 4 + ((flags & ARGS_ARE_WORDS) !== 0 ? 4 : 2)\n at += (flags & A_SCALE) !== 0 ? 2 : (flags & AN_X_AND_Y_SCALE) !== 0 ? 4 : (flags & A_TWO_BY_TWO) !== 0 ? 8 : 0\n inside(at, end)\n }\n}\n","/**\n * A TrueType font's fixed tables, read and held to the OpenType\n * specification (OpenType 1.9.1, read 21 October 2026): the font header,\n * the maximum profile, the horizontal header and metrics, the OS/2 table's\n * embedding permissions, weight and style, and the PostScript table\n * (0040). Each read is checked against the file (`FontFile`); each field a\n * reader acts on is held to the values the specification defines, and a\n * version it does not define is refused rather than read as another; the\n * line the horizontal header makes, which the specification does not\n * bound, is held to what pdfmake can lay a page out by (0040).\n *\n * What PDFKit reads of these when it embeds a face is read here too, so\n * that a font this accepts is one fontkit decodes: it names the font by\n * its PostScript name, scales by `unitsPerEm`, measures a line by the\n * horizontal header, sets the descriptor's flags from the PostScript\n * table's `isFixedPitch` and the header's `macStyle`, and takes each\n * glyph's advance from the metrics (`EmbeddedFont`, pdfkit.js 2551-2690),\n * and fontkit each glyph's height from the vertical metrics where a font\n * has them (`Glyph._getMetrics`). fontkit decodes each of these tables\n * whole, and finds none where its bytes run past the file.\n */\nimport type { FontFile } from './font-file.js'\nimport { refuse, refuseEmbedding } from './font-refusal.js'\nimport { MAX_FONT_LINE, MIN_FONT_LINE } from './limits.js'\n\n/** What the font header says the rest of the font is read by. */\nexport interface FontHeader {\n readonly unitsPerEm: number\n /** loca's offsets: 0 for 16-bit halves, 1 for 32-bit bytes. */\n readonly locFormat: 0 | 1\n}\n\n/** The font header: version 1, the magic number, a unit square of 16 to 16,384, one of loca's two formats, glyph data in its one format, and no last-resort font. */\nexport function readHead(file: FontFile): FontHeader {\n const table = file.table('head')\n const at = table.offset\n file.need(at, 54, table)\n if (file.u16(at, table) !== 1) refuse('malformed', 'has a font header of a version the specification does not define')\n if (file.u32(at + 12, table) !== 0x5f0f3cf5) refuse('malformed', 'has a font header without its magic number')\n const unitsPerEm = file.u16(at + 18, table)\n if (unitsPerEm < 16 || unitsPerEm > 16384) refuse('malformed', `has ${unitsPerEm} units to the em, where the specification allows 16 to 16384`)\n const locFormat = file.i16(at + 50, table)\n if (locFormat !== 0 && locFormat !== 1) refuse('malformed', 'has an index to location format the specification does not define')\n if (file.i16(at + 52, table) !== 0) refuse('malformed', 'has glyph data in a format the specification does not define')\n // Bit 14: the Last Resort font, whose glyphs stand for ranges of code points rather than drawing them.\n if ((file.u16(at + 16, table) & 0x4000) !== 0)\n refuse('character-map', 'is a last-resort font, whose glyphs stand for ranges of characters rather than draw them')\n return { unitsPerEm, locFormat }\n}\n\n/** The glyph count, from a version 1.0 maximum profile, the version TrueType outlines carry, whose 32 bytes fontkit decodes whole; a font of no glyph has no .notdef. */\nexport function readGlyphCount(file: FontFile): number {\n const table = file.table('maxp')\n file.need(table.offset, 32, table)\n if (file.u32(table.offset, table) !== 0x00010000) refuse('malformed', 'has a maximum profile of another version than the 1.0 TrueType outlines need')\n const glyphs = file.u16(table.offset + 4, table)\n if (glyphs === 0) refuse('malformed', 'has no glyph, not even the .notdef glyph 0')\n return glyphs\n}\n\n/** A line, in font units, as PDFKit measures one: the horizontal header's ascender, descender and line gap. */\nexport interface FontLine {\n readonly ascender: number\n readonly descender: number\n readonly lineGap: number\n}\n\n/**\n * The horizontal header, version 1, and the metrics it counts: between one\n * and `glyphs` advances, and a side bearing for every glyph after them,\n * inside the file. And the line it makes at `unitsPerEm`, which pdfmake\n * lays every line of the face out by -- the ascender less the descender,\n * the baseline the ascender below the line's top -- held to rise above its\n * baseline, to reach down to it or below, and to be from `MIN_FONT_LINE`\n * to `MAX_FONT_LINE` ems tall. The specification bounds none of them; a\n * line of nothing printed every line of a report on one spot (0040).\n */\nexport function readHorizontal(file: FontFile, glyphs: number, unitsPerEm: number): FontLine {\n const table = file.table('hhea')\n const at = table.offset\n file.need(at, 36, table)\n if (file.u16(at, table) !== 1) refuse('malformed', 'has a horizontal header of a version the specification does not define')\n if (file.i16(at + 32, table) !== 0) refuse('malformed', 'has horizontal metrics in a format the specification does not define')\n const metrics = file.u16(at + 34, table)\n if (metrics === 0 || metrics > glyphs) refuse('malformed', `counts ${metrics} horizontal metrics for ${glyphs} glyphs`)\n const widths = file.table('hmtx')\n file.need(widths.offset, 4 * metrics + 2 * (glyphs - metrics), widths)\n const line = { ascender: file.i16(at + 4, table), descender: file.i16(at + 6, table), lineGap: file.i16(at + 8, table) }\n if (line.ascender <= 0) refuse('malformed', `has an ascender of ${line.ascender} units, at or below its baseline, where a line must rise above it`)\n if (line.descender > 0) refuse('malformed', `has a descender of ${line.descender} units, above its baseline, where a line must reach down to it or below`)\n const tall = line.ascender - line.descender\n if (tall < MIN_FONT_LINE * unitsPerEm || tall > MAX_FONT_LINE * unitsPerEm) {\n refuse(\n 'malformed',\n `has a line ${tall} units tall, its ascender less its descender, at ${unitsPerEm} units to the em, where a line may be ${MIN_FONT_LINE} to ${MAX_FONT_LINE} ems tall`,\n )\n }\n return line\n}\n\n/**\n * The vertical metrics, where fontkit reads them: where it sees both a\n * vertical header and its metrics, it measures every glyph by them, and\n * otherwise by the OS/2 table and the horizontal header. It reads the\n * header's count of metrics two bytes early -- the version as 16 bits,\n * where the specification gives it 32 -- from the field the specification\n * calls metricDataFormat, which is 0 in a sound font, and so takes every\n * glyph's top side bearing from the start of the table. The bytes held\n * inside the file are the ones fontkit reads; the specification's count is\n * not judged, since fontkit never reads by it.\n */\nexport function readVertical(file: FontFile, glyphs: number): void {\n if (!file.seen('vhea') || !file.seen('vmtx')) return\n const header = file.table('vhea')\n file.need(header.offset, 36, header)\n const counted = file.u16(header.offset + 32, header)\n const metrics = file.table('vmtx')\n file.need(metrics.offset, counted >= glyphs ? 4 * glyphs : 4 * counted + 2 * (glyphs - counted), metrics)\n}\n\n/** What a font's fsType allows, where it allows embedding a subset of its outlines. */\nexport type FontEmbedding = 'installable' | 'preview-print' | 'editable'\n\n/** The OS/2 table's say on embedding, and on the face's weight and style, for a person to choose its face by. */\nexport interface FontOs2 {\n readonly embedding: FontEmbedding\n readonly fsType: number\n /** usWeightClass, 100 thin to 900 black, as the font states it. */\n readonly weight: number\n /** fsSelection's bits 0, 5 and 6: italic, bold, regular. Roboto Medium, which pdfmake prints bold, says regular. */\n readonly italic: boolean\n readonly bold: boolean\n readonly regular: boolean\n}\n\n/** The OS/2 versions the specification defines. */\nconst LAST_OS2_VERSION = 5\n\n/** The usage bits' values, from Restricted License to Editable. */\nconst USAGE = { restricted: 0x0002, previewPrint: 0x0004, editable: 0x0008 } as const\n\n/**\n * What an fsType of an OS/2 table of `version` allows, or its refusal\n * (OS/2, fsType, and its version differences):\n *\n * - bit 0 is reserved and must be zero in every version, and is refused;\n * - in versions 0 to 2 several of bits 1 to 3 mean the least restrictive,\n * as those versions said; from version 3 they are exclusive, and several\n * are refused;\n * - Restricted License alone (2) is refused: the font \"must not be ...\n * embedded ... without first obtaining explicit permission\";\n * - Preview & Print (4) is accepted, since a PDF is opened read-only, and\n * Editable (8) and Installable (0);\n * - from version 2, Bitmap embedding only (bit 9) and No subsetting (bit 8)\n * are refused, since PDFKit embeds outlines and always a subset;\n * versions 0 and 1 assigned no bit past 3, and the specification says to\n * ignore them there;\n * - every other bit is reserved, which the specification says a reader can\n * ignore; a version past 5, whose bits nothing here knows, is refused.\n */\nexport function embeddingOf(version: number, fsType: number): FontEmbedding {\n const hex = `0x${fsType.toString(16).padStart(4, '0')}`\n if (version > LAST_OS2_VERSION)\n refuseEmbedding('invalid', `states its embedding permissions in an OS/2 table of version ${version}, which the specification does not define`)\n if ((fsType & 0x0001) !== 0) refuseEmbedding('invalid', `sets bit 0 of its embedding permissions (fsType ${hex}), which the specification reserves`)\n const usage = fsType & 0x000e\n const several = usage !== 0 && (usage & (usage - 1)) !== 0\n if (several && version >= 3)\n refuseEmbedding('invalid', `sets more than one usage permission (fsType ${hex}), which an OS/2 table of version ${version} may not`)\n const permitted = (usage & USAGE.editable) !== 0 ? 'editable' : (usage & USAGE.previewPrint) !== 0 ? 'preview-print' : usage === 0 ? 'installable' : undefined\n if (permitted === undefined)\n refuseEmbedding('restricted', `allows Restricted License embedding alone (fsType ${hex}), which forbids embedding the font without its owner's permission`)\n if (version >= 2 && (fsType & 0x0200) !== 0)\n refuseEmbedding('bitmap-only', `allows its bitmaps alone to be embedded (fsType ${hex}), where a PDF embeds outlines`)\n if (version >= 2 && (fsType & 0x0100) !== 0)\n refuseEmbedding('no-subsetting', `forbids embedding a subset of it (fsType ${hex}), where the PDF embeds only the glyphs it prints`)\n return permitted\n}\n\n/** The OS/2 table: its version, the embedding its fsType allows, its weight and its style bits. */\nexport function readOs2(file: FontFile): FontOs2 {\n const table = file.table('OS/2')\n const at = table.offset\n const version = file.u16(at, table)\n const fsType = file.u16(at + 8, table)\n const embedding = embeddingOf(version, fsType)\n const selection = file.u16(at + 62, table)\n return {\n embedding,\n fsType,\n weight: file.u16(at + 4, table),\n italic: (selection & 0x01) !== 0,\n bold: (selection & 0x20) !== 0,\n regular: (selection & 0x40) !== 0,\n }\n}\n\n/**\n * The PostScript table, in a version the specification defines -- 1.0,\n * 2.0, the deprecated 2.5, or 3.0 -- whose glyph names fontkit decodes in\n * whole when PDFKit reads `isFixedPitch`: version 2.0's name indices and\n * its Pascal strings to the end of the table, version 2.5's offsets, each\n * inside the file. A table fontkit could not decode would leave PDFKit\n * reading a property of nothing.\n */\nexport function readPost(file: FontFile): void {\n const table = file.table('post')\n const at = table.offset\n file.need(at, 32, table)\n const version = file.u32(at, table)\n if (version === 0x00010000 || version === 0x00030000) return\n if (version === 0x00025000) {\n file.need(at + 34, file.u16(at + 32, table), table)\n return\n }\n if (version !== 0x00020000) refuse('malformed', 'has a PostScript table of a version the specification does not define')\n // fontkit reads the table's own count of name indices, which the specification says should be the glyph count, and never holds it to that.\n const named = file.u16(at + 32, table)\n file.need(at + 34, 2 * named, table)\n // fontkit reads Pascal strings from after the indices to the table's recorded end, each a length and its characters.\n const end = table.offset + table.length\n for (let string = at + 34 + 2 * named; string < end;) {\n file.need(string, 1 + file.u8(string, table), table)\n string += 1 + file.u8(string, table)\n }\n}\n","/**\n * What a font's bytes are, read once by report-spec for every reader (0040):\n * today the renderer, which reads the character maps of the faces it ships\n * through it, and, once they take a font, a builder, where a person adds\n * one, and a host's approval. A font is untrusted input, even when an\n * administrator approved it: every table's offset and length is held to the\n * bytes, every loop is bounded by them, nothing recurses on what a font\n * holds, nothing is allocated from a count before the bytes it counts are\n * known to be there, and a refusal repeats nothing a font chose but a\n * number the reader decoded (`font-refusal.ts`).\n *\n * Accepted: one static TrueType font -- an sfnt of version 0x00010000 or\n * Apple's 'true' -- with TrueType outlines, the eight tables every OpenType\n * font needs, a Unicode character map fontkit reads in format 4 or 12, a\n * line pdfmake can lay out, its ascender above the baseline, its descender\n * at or below it and the two `MIN_FONT_LINE` to `MAX_FONT_LINE` ems apart,\n * and an OS/2 fsType that allows embedding a subset of its outlines. Refused,\n * each with what to do: a collection, WOFF, WOFF2, EOT and Type 1; CFF and\n * CFF2 outlines, until the e-invoice gate has proved a CFF face in a\n * PDF/A-3b; a variable font; colour glyphs, which PDFKit prints as their\n * outlines alone, where a colour font may leave them empty; a font of\n * bitmaps alone; and Restricted License, No subsetting and Bitmap only\n * fonts, with no override on a host's word.\n *\n * The reader says what a font is and which characters it draws. Which\n * scripts a report may print in it, and whether a face is mapped, are the\n * renderer's and the format's, once a report can name a host's font.\n */\nimport { readCharacterMap } from './font-cmap.js'\nimport { FontFile, refuseSniffed, sniffFont } from './font-file.js'\nimport { readNames, type FontNames } from './font-names.js'\nimport { readOutlines } from './font-outlines.js'\nimport { caught, refuse, type FontRefusal } from './font-refusal.js'\nimport { readGlyphCount, readHead, readHorizontal, readOs2, readPost, readVertical, type FontEmbedding } from './font-tables.js'\nimport { MAX_FONT_BYTES } from './limits.js'\n\n/** The metrics PDFKit lays a line out by, in font units: `unitsPerEm`, and the horizontal header's ascender, descender and line gap. A line is `ascender - descender` units, as `style.ts` says of Roboto's: in a font this accepts, the ascender above 0, the descender at or below 0, and the line `MIN_FONT_LINE` to `MAX_FONT_LINE` ems. */\nexport interface FontMetrics {\n readonly unitsPerEm: number\n readonly ascender: number\n readonly descender: number\n readonly lineGap: number\n}\n\n/** What the OS/2 table says of the face, for a person to choose which face it is: a builder proposes, and the person decides, since Roboto Medium, which pdfmake prints as bold, says it is regular. */\nexport interface FontStyle {\n readonly weight: number\n readonly italic: boolean\n readonly bold: boolean\n readonly regular: boolean\n}\n\n/** A font this reader accepts. */\nexport interface Font {\n readonly ok: true\n readonly names: FontNames\n /** What its fsType allows: installable, preview and print, or editable embedding. */\n readonly embedding: FontEmbedding\n /** The OS/2 fsType as the font states it, for a record of what was read. */\n readonly fsType: number\n readonly metrics: FontMetrics\n readonly style: FontStyle\n /** The glyph count, glyph 0 among them. */\n readonly glyphs: number\n /** The code points it maps to a glyph other than glyph 0, as fontkit maps them (`characterMap`). */\n readonly characters: ReadonlySet<number>\n}\n\n/** The tables whose presence makes a font one this does not read, in the order they are looked for, each with its refusal. */\nconst REFUSED_TABLES: readonly (readonly [string, () => never])[] = [\n ['CFF ', () => refuse('cff', 'has CFF outlines')],\n ['CFF2', () => refuse('cff', 'has CFF2 outlines')],\n ['fvar', () => refuse('variable', 'is a variable font')],\n ['COLR', () => refuse('colour', 'has colour glyphs (COLR)')],\n ['SVG ', () => refuse('colour', 'has colour glyphs (SVG)')],\n ['CBDT', () => refuse('colour', 'has colour bitmap glyphs (CBDT)')],\n ['sbix', () => refuse('colour', 'has colour bitmap glyphs (sbix)')],\n]\n\n/** The tables every OpenType font needs, and the two its TrueType outlines are, each of which the reader reads. */\nconst READ_TABLES = ['cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'post', 'glyf', 'loca'] as const\n\n/** A font's bytes, read whole, or the first thing that is wrong with them. */\nexport function readFont(bytes: Uint8Array): Font | FontRefusal {\n return caught(() => read(bytes))\n}\n\nfunction read(bytes: Uint8Array): Font {\n // What the file is comes first: a collection past the size is told what to export, not only that it is large.\n const sniffed = sniffFont(bytes)\n if (sniffed === undefined) refuse('not-a-font', 'is not a font')\n if (sniffed === 'cff') refuse('cff', 'is an OpenType font with CFF outlines')\n if (sniffed !== 'truetype') refuseSniffed(sniffed)\n if (bytes.length > MAX_FONT_BYTES) refuse('too-large', `is ${bytes.length} bytes, where the most a font may have is ${MAX_FONT_BYTES}`)\n const file = new FontFile(bytes)\n for (const [tag, refused] of REFUSED_TABLES) if (file.has(tag)) refused()\n if (!file.has('glyf') || !file.has('loca')) refuse('no-outlines', 'has no TrueType outlines (glyf and loca)')\n // Each as fontkit sees it: one recorded as empty fontkit does not see at all, and PDFKit then reads a property of nothing.\n for (const tag of READ_TABLES) file.seenTable(tag)\n // A restricted font is refused for its restriction, whatever else is wrong with it.\n const os2 = readOs2(file)\n const header = readHead(file)\n const glyphs = readGlyphCount(file)\n const line = readHorizontal(file, glyphs, header.unitsPerEm)\n readVertical(file, glyphs)\n readOutlines(file, glyphs, header.locFormat)\n readPost(file)\n const map = readCharacterMap(file)\n if (map.largestGlyph >= glyphs) refuse('malformed', 'maps a character to a glyph the font does not have')\n return {\n ok: true,\n names: readNames(file),\n embedding: os2.embedding,\n fsType: os2.fsType,\n metrics: { unitsPerEm: header.unitsPerEm, ...line },\n style: { weight: os2.weight, italic: os2.italic, bold: os2.bold, regular: os2.regular },\n glyphs,\n characters: map.characters,\n }\n}\n","/**\n * The content hash that names a report definition.\n */\nimport { schemaHash } from '@formancy/spec'\nimport type { ReportDefinition } from './definition.js'\nimport { describeErrors } from './errors.js'\nimport { validateReport } from './validate.js'\nimport { REPORT_FORMAT } from './version.js'\n\n/**\n * A 64-character lower-case hex SHA-256 of the report's canonical JSON,\n * taken over an envelope that names the format and its version, so a\n * formancy form and a report whose bodies are equal never share a hash.\n *\n * Only a valid report has a hash. The report is validated first, and a\n * RangeError naming every error is thrown for one the validator refuses,\n * whatever its type says: a hash is what publication pins, and pinning a\n * report the runtime would refuse helps nobody. What is hashed is the copy\n * validation read, so a getter never runs and the hash is of what was\n * checked.\n *\n * Canonicalisation is formancy's (`@formancy/spec`), not a second one: keys\n * sorted, so key order never changes the hash. It builds each object by\n * assignment, so an own `__proto__` key would vanish from it; the validator\n * refuses such a key first.\n */\nexport function reportHash(report: ReportDefinition): string {\n const outcome = validateReport(report)\n if (!outcome.valid) throw new RangeError(`only a valid report has a hash, and this one is not: ${describeErrors(outcome.errors)}`)\n return schemaHash({ format: REPORT_FORMAT, reportSpecVersion: outcome.report.reportSpecVersion, report: outcome.report })\n}\n","/**\n * The report an author starts from when they start from nothing.\n */\nimport type { ReportDefinition } from './definition.js'\nimport { describeErrors } from './errors.js'\nimport { mmToPt } from './units.js'\nimport { validateReport } from './validate.js'\nimport { REPORT_SPEC_VERSION } from './version.js'\n\n/** The default margin: 20 mm, a common default for A4 business documents. */\nconst MARGIN_MM = 20\n\n/**\n * A valid, empty A4 portrait report with 20 mm margins, nothing declared and\n * nothing in any region, recorded as started blank.\n *\n * Throws a RangeError naming the property when `id`, `title` or `locale` is\n * one the format refuses, rather than returning a report every later step\n * would refuse.\n */\nexport function emptyReport(id: string, title: string, locale: string): ReportDefinition {\n const margin = mmToPt(MARGIN_MM)\n const outcome = validateReport({\n reportSpecVersion: REPORT_SPEC_VERSION,\n id,\n title,\n locale,\n page: { size: 'A4', orientation: 'portrait', margins: { top: margin, right: margin, bottom: margin, left: margin } },\n styles: [],\n datasets: {},\n parameters: [],\n assets: [],\n aggregates: [],\n regions: { reportHeader: [], pageHeader: [], body: [], pageFooter: [], summary: [] },\n provenance: { kind: 'blank' },\n })\n if (outcome.valid) return outcome.report\n throw new RangeError(`not a valid empty report: ${describeErrors(outcome.errors)}`)\n}\n"],"mappings":";;;;AAcA,MAAa,cAAc;CAAC;CAAO;CAAQ;AAAK;;AAIhD,MAAa,eAAe;CAAC;CAAQ;CAAO;AAAM;;AAIlD,MAAa,uBAA6C;CAAC;CAAU;CAAQ;CAAW;AAAS;;AAGjG,MAAa,gBAA8C,CAAC,OAAO,OAAO;;;;;;;AAQ1E,MAAa,gBAAgB;CAAC;CAAW;CAAW;CAAW;CAAW;CAAW;CAAW;CAAW;AAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACLpH,MAAa,aAAa;;;;;;;AAQ1B,MAAa,wBAAwB;;;;;;;AAQrC,MAAa,oBAAoB;;AAGjC,MAAa,cAAc;AAC3B,MAAa,cAAc;;AAG3B,MAAa,oBAAoB;;;;;;;;;;;;;;;;;;;AAoBjC,MAAa,aAAa;;AAG1B,MAAa,gBAAgB;;AAG7B,MAAa,kBAAkB;;;;;;;;;AAU/B,MAAa,qBAAqB;;AAGlC,MAAa,qBAAqB;;AAGlC,MAAa,aAAa;;AAG1B,MAAa,kBAAkB;;AAG/B,MAAa,iBAAiB;;AAG9B,MAAa,aAAa;;;;;;;;;AAU1B,MAAa,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;AAyB/B,MAAa,mBAAmB;;;;;;;;AAShC,MAAa,iBAAiB;;AAG9B,MAAa,mBAAmB,cAAc;;AAG9C,MAAa,iBAAiB;;AAG9B,MAAa,i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