@financica/ubl 0.15.1 → 0.17.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.js","names":[],"sources":["../../src/build/ubl/constants.ts","../../src/build/xml.ts","../../src/build/ubl/serialize.ts","../../src/build/utils.ts","../../src/build/address.ts","../../src/build/identifiers.ts","../../src/build/party.ts","../../src/build/attachment.ts","../../src/build/numeric.ts","../../src/build/tax-category.ts","../../src/build/tax-totals.ts"],"sourcesContent":["/** Peppol BIS Billing 3.0 / EN 16931 identifiers and fixed code values. */\n\n/** EN 16931 + Peppol BIS Billing 3.0 customization (BT-24). */\nexport const UBL_CUSTOMIZATION_ID =\n\t\"urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0\";\n\n/** Peppol BIS Billing 3.0 process (BT-23). */\nexport const UBL_PROFILE_ID = \"urn:fdc:peppol.eu:2017:poacc:billing:01:1.0\";\n\n/** UNTDID 1001 — commercial invoice. */\nexport const INVOICE_TYPE_CODE = \"380\";\n/** UNTDID 1001 — credit note. */\nexport const CREDIT_NOTE_TYPE_CODE = \"381\";\n\n/** UN/ECE Recommendation 20 — \"one / piece\" (the default line unit). */\nexport const DEFAULT_UNIT_CODE = \"C62\";\n\n/** UNCL5153 — the VAT tax scheme identifier. */\nexport const VAT_TAX_SCHEME_ID = \"VAT\";\n\n/** ISO 3166-1 alpha-2 list identifier for `cbc:IdentificationCode`. */\nexport const COUNTRY_CODE_LIST_ID = \"ISO3166-1:Alpha2\";\n\nexport const NS_INVOICE = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\";\nexport const NS_CREDIT_NOTE =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2\";\nexport const NS_CAC =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\nexport const NS_CBC =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\n","/**\n * Minimal, dependency-free XML builder + serializer.\n *\n * UBL is order-sensitive (every element sequence is fixed by the schema), so\n * children are always explicit, ordered arrays. There is no attribute or text\n * coercion magic beyond escaping — the UBL layer is responsible for emitting\n * elements in the right order.\n */\n\nexport type XmlAttrs = Record<string, string | number | null | undefined>;\n\nexport interface XmlElement {\n\tname: string;\n\tattrs?: XmlAttrs;\n\t/** Leaf text content. Mutually exclusive with `children`. */\n\ttext?: string | number | null;\n\t/** Child elements. Mutually exclusive with `text`. */\n\tchildren?: XmlElement[];\n}\n\n/** Falsy children are dropped, so callers can write `cond && el(...)`. */\ntype ChildSpec = XmlElement | null | undefined | false;\n\n/**\n * Build an XML element.\n *\n * el(\"cbc:ID\", null, \"INV-1\") → <cbc:ID>INV-1</cbc:ID>\n * el(\"cbc:Amount\", { currencyID: \"EUR\" }, \"10.00\") → <cbc:Amount currencyID=\"EUR\">10.00</cbc:Amount>\n * el(\"cac:Party\", null, [child, cond && child2]) → nested element\n */\nexport const el = (\n\tname: string,\n\tattrs?: XmlAttrs | null,\n\tcontent?: string | number | null | ChildSpec[],\n): XmlElement => {\n\tif (Array.isArray(content)) {\n\t\treturn {\n\t\t\tname,\n\t\t\tattrs: attrs ?? undefined,\n\t\t\tchildren: content.filter((c): c is XmlElement => Boolean(c)),\n\t\t};\n\t}\n\treturn { name, attrs: attrs ?? undefined, text: content ?? undefined };\n};\n\nconst escapeText = (value: string): string =>\n\tvalue.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n\nconst escapeAttr = (value: string): string => escapeText(value).replace(/\"/g, \"&quot;\");\n\nconst serializeAttrs = (attrs: XmlAttrs | undefined): string => {\n\tif (!attrs) return \"\";\n\treturn Object.entries(attrs)\n\t\t.filter(([, value]) => value !== null && value !== undefined)\n\t\t.map(([key, value]) => ` ${key}=\"${escapeAttr(String(value))}\"`)\n\t\t.join(\"\");\n};\n\nconst serializeElement = (node: XmlElement, indentLevel: number): string => {\n\tconst pad = \" \".repeat(indentLevel);\n\tconst attrs = serializeAttrs(node.attrs);\n\n\tif (node.text !== undefined && node.text !== null) {\n\t\treturn `${pad}<${node.name}${attrs}>${escapeText(String(node.text))}</${node.name}>`;\n\t}\n\n\tconst children = node.children ?? [];\n\tif (children.length === 0) {\n\t\treturn `${pad}<${node.name}${attrs}/>`;\n\t}\n\n\tconst inner = children\n\t\t.map((child) => serializeElement(child, indentLevel + 1))\n\t\t.join(\"\\n\");\n\treturn `${pad}<${node.name}${attrs}>\\n${inner}\\n${pad}</${node.name}>`;\n};\n\n/** Serialize a root element into a UTF-8 XML document string. */\nexport const serializeDocument = (root: XmlElement): string =>\n\t`<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n${serializeElement(root, 0)}\\n`;\n","import { el, serializeDocument, type XmlElement } from \"../xml\";\nimport {\n\tCOUNTRY_CODE_LIST_ID,\n\tCREDIT_NOTE_TYPE_CODE,\n\tINVOICE_TYPE_CODE,\n\tNS_CAC,\n\tNS_CBC,\n\tNS_CREDIT_NOTE,\n\tNS_INVOICE,\n\tUBL_CUSTOMIZATION_ID,\n\tUBL_PROFILE_ID,\n\tVAT_TAX_SCHEME_ID,\n} from \"./constants\";\nimport type {\n\tUblAddress,\n\tUblAttachment,\n\tUblDocument,\n\tUblLine,\n\tUblParty,\n\tUblPeriod,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n} from \"./types\";\n\n/** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */\nconst amount = (value: number): string => value.toFixed(2);\n\n/** Format a VAT percentage. Trims to at most 2 decimals without forcing them. */\nconst percent = (value: number): string => {\n\tconst rounded = Math.round(value * 100) / 100;\n\treturn Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);\n};\n\nconst money = (name: string, value: number, currency: string): XmlElement =>\n\tel(name, { currencyID: currency }, amount(value));\n\nconst vatTaxScheme = (): XmlElement =>\n\tel(\"cac:TaxScheme\", null, [el(\"cbc:ID\", null, VAT_TAX_SCHEME_ID)]);\n\n/**\n * Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)\n * and `cac:TaxCategory` (in the VAT breakdown). EN 16931 requires an exemption\n * reason for the non-charging categories (E/AE/O/K/G).\n */\nconst taxCategory = (name: string, category: UblTaxCategory): XmlElement =>\n\tel(name, null, [\n\t\tel(\"cbc:ID\", null, category.id),\n\t\tel(\"cbc:Percent\", null, percent(category.percent)),\n\t\tcategory.exemptionReason\n\t\t\t? el(\"cbc:TaxExemptionReason\", null, category.exemptionReason)\n\t\t\t: null,\n\t\tvatTaxScheme(),\n\t]);\n\nconst postalAddress = (address: UblAddress): XmlElement =>\n\tel(\"cac:PostalAddress\", null, [\n\t\taddress.street ? el(\"cbc:StreetName\", null, address.street) : null,\n\t\taddress.additionalStreet\n\t\t\t? el(\"cbc:AdditionalStreetName\", null, address.additionalStreet)\n\t\t\t: null,\n\t\taddress.city ? el(\"cbc:CityName\", null, address.city) : null,\n\t\taddress.postalZone ? el(\"cbc:PostalZone\", null, address.postalZone) : null,\n\t\taddress.countrySubentity\n\t\t\t? el(\"cbc:CountrySubentity\", null, address.countrySubentity)\n\t\t\t: null,\n\t\taddress.countryCode\n\t\t\t? el(\"cac:Country\", null, [\n\t\t\t\t\tel(\n\t\t\t\t\t\t\"cbc:IdentificationCode\",\n\t\t\t\t\t\t{ listID: COUNTRY_CODE_LIST_ID },\n\t\t\t\t\t\taddress.countryCode,\n\t\t\t\t\t),\n\t\t\t\t])\n\t\t\t: null,\n\t]);\n\nconst party = (source: UblParty): XmlElement =>\n\tel(\"cac:Party\", null, [\n\t\tsource.endpoint\n\t\t\t? el(\n\t\t\t\t\t\"cbc:EndpointID\",\n\t\t\t\t\t{ schemeID: source.endpoint.scheme },\n\t\t\t\t\tsource.endpoint.value,\n\t\t\t\t)\n\t\t\t: null,\n\t\tel(\"cac:PartyName\", null, [el(\"cbc:Name\", null, source.name)]),\n\t\tpostalAddress(source.address),\n\t\tsource.vatNumber\n\t\t\t? el(\"cac:PartyTaxScheme\", null, [\n\t\t\t\t\tel(\"cbc:CompanyID\", null, source.vatNumber),\n\t\t\t\t\tvatTaxScheme(),\n\t\t\t\t])\n\t\t\t: null,\n\t\tel(\"cac:PartyLegalEntity\", null, [\n\t\t\tel(\"cbc:RegistrationName\", null, source.legalName ?? source.name),\n\t\t\tsource.companyId\n\t\t\t\t? el(\n\t\t\t\t\t\t\"cbc:CompanyID\",\n\t\t\t\t\t\tsource.companyId.scheme\n\t\t\t\t\t\t\t? { schemeID: source.companyId.scheme }\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\tsource.companyId.value,\n\t\t\t\t\t)\n\t\t\t\t: null,\n\t\t]),\n\t]);\n\nconst taxSubtotal = (subtotal: UblTaxSubtotal, currency: string): XmlElement =>\n\tel(\"cac:TaxSubtotal\", null, [\n\t\tmoney(\"cbc:TaxableAmount\", subtotal.taxableAmount, currency),\n\t\tmoney(\"cbc:TaxAmount\", subtotal.taxAmount, currency),\n\t\ttaxCategory(\"cac:TaxCategory\", subtotal.category),\n\t]);\n\n/**\n * `cac:LegalMonetaryTotal` children, in UBL sequence order. `cbc:PrepaidAmount`\n * (BT-113) and `cbc:PayableRoundingAmount` (BT-114) precede `cbc:PayableAmount`\n * — emitting them after it produces schema-invalid XML.\n */\nconst legalMonetaryTotalChildren = (doc: UblDocument): XmlElement[] => {\n\tconst { currency, monetaryTotal: total } = doc;\n\tconst children: (XmlElement | null)[] = [\n\t\tmoney(\"cbc:LineExtensionAmount\", total.lineExtensionAmount, currency),\n\t\tmoney(\"cbc:TaxExclusiveAmount\", total.taxExclusiveAmount, currency),\n\t\tmoney(\"cbc:TaxInclusiveAmount\", total.taxInclusiveAmount, currency),\n\t\ttotal.prepaidAmount\n\t\t\t? money(\"cbc:PrepaidAmount\", total.prepaidAmount, currency)\n\t\t\t: null,\n\t\ttotal.payableRoundingAmount\n\t\t\t? money(\"cbc:PayableRoundingAmount\", total.payableRoundingAmount, currency)\n\t\t\t: null,\n\t\tmoney(\"cbc:PayableAmount\", total.payableAmount, currency),\n\t];\n\treturn children.filter((child): child is XmlElement => Boolean(child));\n};\n\n/**\n * `cac:InvoicePeriod`. Null when neither bound is set — an empty period element\n * fails BR-CO-19, which requires at least one of the two dates.\n */\nconst invoicePeriod = (period: UblPeriod | null | undefined): XmlElement | null => {\n\tif (!period || (!period.startDate && !period.endDate)) return null;\n\treturn el(\n\t\t\"cac:InvoicePeriod\",\n\t\tnull,\n\t\t[\n\t\t\tperiod.startDate ? el(\"cbc:StartDate\", null, period.startDate) : null,\n\t\t\tperiod.endDate ? el(\"cbc:EndDate\", null, period.endDate) : null,\n\t\t].filter((child): child is XmlElement => Boolean(child)),\n\t);\n};\n\nconst line = (\n\tsource: UblLine,\n\tcurrency: string,\n\tdocumentType: UblDocument[\"documentType\"],\n): XmlElement => {\n\tconst lineElementName =\n\t\tdocumentType === \"creditNote\" ? \"cac:CreditNoteLine\" : \"cac:InvoiceLine\";\n\tconst quantityElementName =\n\t\tdocumentType === \"creditNote\" ? \"cbc:CreditedQuantity\" : \"cbc:InvoicedQuantity\";\n\n\treturn el(lineElementName, null, [\n\t\tel(\"cbc:ID\", null, source.id),\n\t\tel(quantityElementName, { unitCode: source.unitCode }, String(source.quantity)),\n\t\tmoney(\"cbc:LineExtensionAmount\", source.lineExtensionAmount, currency),\n\t\tinvoicePeriod(source.invoicePeriod),\n\t\tel(\"cac:Item\", null, [\n\t\t\tel(\"cbc:Name\", null, source.name),\n\t\t\ttaxCategory(\"cac:ClassifiedTaxCategory\", source.taxCategory),\n\t\t]),\n\t\t// BT-149's unit code must match the invoiced/credited quantity's\n\t\t// (PEPPOL-EN16931-R130).\n\t\tel(\"cac:Price\", null, [\n\t\t\tmoney(\"cbc:PriceAmount\", source.priceAmount, currency),\n\t\t\tsource.baseQuantity != null\n\t\t\t\t? el(\n\t\t\t\t\t\t\"cbc:BaseQuantity\",\n\t\t\t\t\t\t{ unitCode: source.unitCode },\n\t\t\t\t\t\tString(source.baseQuantity),\n\t\t\t\t\t)\n\t\t\t\t: null,\n\t\t]),\n\t]);\n};\n\nconst attachmentReference = (attachment: UblAttachment): XmlElement =>\n\tel(\"cac:AdditionalDocumentReference\", null, [\n\t\tel(\"cbc:ID\", null, attachment.id),\n\t\tel(\"cac:Attachment\", null, [\n\t\t\tel(\n\t\t\t\t\"cbc:EmbeddedDocumentBinaryObject\",\n\t\t\t\t{ mimeCode: attachment.mimeCode, filename: attachment.filename },\n\t\t\t\tattachment.base64,\n\t\t\t),\n\t\t]),\n\t]);\n\nconst billingReference = (precedingInvoiceId: string): XmlElement =>\n\tel(\"cac:BillingReference\", null, [\n\t\tel(\"cac:InvoiceDocumentReference\", null, [\n\t\t\tel(\"cbc:ID\", null, precedingInvoiceId),\n\t\t]),\n\t]);\n\n/** Serialize a {@link UblDocument} into a Peppol BIS Billing 3.0 XML string. */\nexport const serializeUblDocument = (doc: UblDocument): string => {\n\tconst isCreditNote = doc.documentType === \"creditNote\";\n\tconst rootName = isCreditNote ? \"CreditNote\" : \"Invoice\";\n\tconst rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;\n\tconst typeCodeElement = isCreditNote\n\t\t? el(\"cbc:CreditNoteTypeCode\", null, CREDIT_NOTE_TYPE_CODE)\n\t\t: el(\"cbc:InvoiceTypeCode\", null, INVOICE_TYPE_CODE);\n\n\tconst children: (XmlElement | null | false)[] = [\n\t\tel(\"cbc:CustomizationID\", null, UBL_CUSTOMIZATION_ID),\n\t\tel(\"cbc:ProfileID\", null, UBL_PROFILE_ID),\n\t\tel(\"cbc:ID\", null, doc.id),\n\t\tel(\"cbc:IssueDate\", null, doc.issueDate),\n\t\t// CreditNote has no DueDate element in the UBL sequence.\n\t\t!isCreditNote && doc.dueDate ? el(\"cbc:DueDate\", null, doc.dueDate) : null,\n\t\ttypeCodeElement,\n\t\tdoc.note ? el(\"cbc:Note\", null, doc.note) : null,\n\t\tel(\"cbc:DocumentCurrencyCode\", null, doc.currency),\n\t\tdoc.buyerReference ? el(\"cbc:BuyerReference\", null, doc.buyerReference) : null,\n\t\tinvoicePeriod(doc.invoicePeriod),\n\t\tdoc.precedingInvoiceId ? billingReference(doc.precedingInvoiceId) : null,\n\t\t...doc.attachments.map(attachmentReference),\n\t\tel(\"cac:AccountingSupplierParty\", null, [party(doc.supplier)]),\n\t\tel(\"cac:AccountingCustomerParty\", null, [party(doc.customer)]),\n\t\t// BT-20. In both the Invoice and CreditNote sequences PaymentTerms sits\n\t\t// after the parties (and PaymentMeans, which we do not emit) and before\n\t\t// TaxTotal.\n\t\tdoc.paymentTermsNote\n\t\t\t? el(\"cac:PaymentTerms\", null, [el(\"cbc:Note\", null, doc.paymentTermsNote)])\n\t\t\t: null,\n\t\tel(\"cac:TaxTotal\", null, [\n\t\t\tmoney(\"cbc:TaxAmount\", doc.taxTotal.taxAmount, doc.currency),\n\t\t\t...doc.taxTotal.subtotals.map((subtotal) =>\n\t\t\t\ttaxSubtotal(subtotal, doc.currency),\n\t\t\t),\n\t\t]),\n\t\tel(\"cac:LegalMonetaryTotal\", null, legalMonetaryTotalChildren(doc)),\n\t\t...doc.lines.map((source) => line(source, doc.currency, doc.documentType)),\n\t];\n\n\tconst root = el(\n\t\trootName,\n\t\t{\n\t\t\txmlns: rootNamespace,\n\t\t\t\"xmlns:cac\": NS_CAC,\n\t\t\t\"xmlns:cbc\": NS_CBC,\n\t\t},\n\t\tchildren.filter((child): child is XmlElement => Boolean(child)),\n\t);\n\n\treturn serializeDocument(root);\n};\n","export const isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport const normalizeString = (value: unknown): string | null => {\n\tif (typeof value !== \"string\") return null;\n\tconst normalized = value.trim();\n\treturn normalized.length > 0 ? normalized : null;\n};\n\nexport const toNumber = (value: unknown): number => {\n\tif (typeof value === \"number\" && Number.isFinite(value)) return value;\n\tif (typeof value === \"string\") {\n\t\tconst parsed = Number(value);\n\t\tif (Number.isFinite(parsed)) return parsed;\n\t}\n\treturn 0;\n};\n","import type { UblAddress } from \"./ubl/types\";\nimport { isRecord, normalizeString } from \"./utils\";\n\nconst normalizeCountryCode = (value: string | null | undefined): string | null => {\n\tconst trimmed = normalizeString(value);\n\tif (!trimmed) return null;\n\treturn trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : null;\n};\n\n/**\n * Normalize a free-form address (Stripe shape, custom shape, or an internal\n * shape) into a {@link UblAddress}.\n *\n * Accepts both `line1`/`postal_code`/`country` (Stripe) and `street`/`zip_code`\n * (legacy/internal) keys. Falls back to `fallbackCountryCode` when the address\n * has no country, but never silently substitutes a caller's country — pass\n * `null` when \"no country\" is the right answer.\n */\nexport const normalizeAddress = (\n\taddress: unknown,\n\tfallbackCountryCode: string | null,\n\tfallbackLine?: string | null,\n): UblAddress => {\n\tconst record = isRecord(address) ? address : {};\n\tconst countryCode =\n\t\tnormalizeCountryCode(normalizeString(record.country)) ??\n\t\tnormalizeCountryCode(normalizeString(record.country_code)) ??\n\t\tnormalizeCountryCode(fallbackCountryCode);\n\treturn {\n\t\tstreet:\n\t\t\tnormalizeString(record.line1) ??\n\t\t\tnormalizeString(record.street) ??\n\t\t\tfallbackLine ??\n\t\t\tnull,\n\t\tadditionalStreet: normalizeString(record.line2),\n\t\tcity: normalizeString(record.city),\n\t\tpostalZone:\n\t\t\tnormalizeString(record.postal_code) ?? normalizeString(record.zip_code),\n\t\tcountrySubentity:\n\t\t\tnormalizeString(record.state) ?? normalizeString(record.country_subentity),\n\t\tcountryCode,\n\t};\n};\n","import { normalizeParticipantValue } from \"@financica/peppol/identifiers\";\nimport type { UblCompanyId, UblEndpoint } from \"./ubl/types\";\nimport { isRecord, normalizeString } from \"./utils\";\n\nconst normalizeBelgianCompanyNumber = (value: string | null | undefined) => {\n\tif (!value) return \"\";\n\t// EAS 0208 (BE:EN) is 10 bare digits, so the printed dots are decoration.\n\treturn normalizeParticipantValue(\"0208\", value).toUpperCase().replace(/^BE/, \"\");\n};\n\n/**\n * Strip whitespace/punctuation from a country-specific company number.\n * For Belgium, also strips an optional `BE` prefix.\n */\nexport const normalizeCompanyNumberForCountry = (\n\tcountryCode: string | null | undefined,\n\tcompanyNumber: string | null | undefined,\n) => {\n\tif (!companyNumber) return \"\";\n\tconst upper = countryCode?.trim().toUpperCase() ?? \"\";\n\tif (upper === \"BE\") return normalizeBelgianCompanyNumber(companyNumber);\n\treturn companyNumber.trim();\n};\n\n/**\n * Country code → Peppol/ISO 6523 ICD scheme for a legal registration number\n * (`cac:PartyLegalEntity/cbc:CompanyID/@schemeID`).\n *\n * BE → 0208 (Belgian enterprise number, CBE/KBO/BCE)\n * NL → 0106 (Netherlands KvK)\n * FR → 0002 (France SIRENE)\n *\n * Falls back to inspecting the number's country prefix (e.g. `BE0793904121`).\n * Returns `null` when the scheme can't be determined, in which case the\n * CompanyID is emitted without a `schemeID` attribute.\n */\nexport const resolveCompanyIdScheme = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): string | null => {\n\tconst companyNumber = normalizeString(params.companyNumber);\n\tif (!companyNumber) return null;\n\n\tconst TABLE: Record<string, string> = {\n\t\tBE: \"0208\",\n\t\tNL: \"0106\",\n\t\tFR: \"0002\",\n\t};\n\n\tconst normalizedCountry =\n\t\tnormalizeString(params.countryCode)?.toUpperCase() ?? null;\n\tif (normalizedCountry && normalizedCountry in TABLE) {\n\t\treturn TABLE[normalizedCountry] ?? null;\n\t}\n\n\t// Only sniffing the country prefix, e.g. `BE0793904121` → `BE`.\n\tconst countryPrefix = companyNumber\n\t\t.replace(/[^A-Za-z]/g, \"\")\n\t\t.toUpperCase()\n\t\t.slice(0, 2);\n\treturn countryPrefix in TABLE ? (TABLE[countryPrefix] ?? null) : null;\n};\n\n/**\n * Build the `cac:PartyLegalEntity/cbc:CompanyID` value for a party, with the\n * country-appropriate ICD scheme when known. Returns `null` when there is no\n * company number.\n */\nexport const buildCompanyId = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): UblCompanyId | null => {\n\tconst normalized = normalizeString(\n\t\tnormalizeCompanyNumberForCountry(params.countryCode, params.companyNumber),\n\t);\n\tif (!normalized) return null;\n\treturn {\n\t\tvalue: normalized,\n\t\tscheme: resolveCompanyIdScheme({\n\t\t\tcountryCode: params.countryCode,\n\t\t\tcompanyNumber: normalized,\n\t\t}),\n\t};\n};\n\n/**\n * Country code → Peppol EAS scheme for a *VAT* identifier, keyed by ISO 3166-1\n * alpha-2. Source: Peppol Code Lists – Participant Identifier Schemes (EAS),\n * Peppol BIS Billing 3.0 (November 2025 release).\n *\n * Only countries that publish a VAT-based EAS scheme appear here. Some (e.g.\n * SE/DK/NO) address Peppol participants by organisation number rather than VAT\n * and are intentionally absent — see {@link resolveCompanyIdScheme}.\n */\nconst VAT_SCHEME_BY_COUNTRY: Record<string, string> = {\n\tAD: \"9922\", // Andorra\n\tAL: \"9923\", // Albania\n\tAT: \"9914\", // Austria\n\tBA: \"9924\", // Bosnia and Herzegovina\n\tBE: \"9925\", // Belgium\n\tBG: \"9926\", // Bulgaria\n\tCH: \"9927\", // Switzerland\n\tCY: \"9928\", // Cyprus\n\tCZ: \"9929\", // Czech Republic\n\tDE: \"9930\", // Germany\n\tEE: \"9931\", // Estonia\n\tES: \"9920\", // Spain (Spanish Tax Administration)\n\tFI: \"0213\", // Finland (Finnish VAT Identifier)\n\tFR: \"9957\", // France\n\tGB: \"9932\", // United Kingdom\n\tGR: \"9933\", // Greece (VAT prefix \"EL\")\n\tHR: \"9934\", // Croatia\n\tHU: \"9910\", // Hungary\n\tIE: \"9935\", // Ireland\n\tLI: \"9936\", // Liechtenstein\n\tLT: \"9937\", // Lithuania\n\tLU: \"9938\", // Luxembourg\n\tLV: \"9939\", // Latvia\n\tMC: \"9940\", // Monaco\n\tME: \"9941\", // Montenegro\n\tMK: \"9942\", // North Macedonia\n\tMT: \"9943\", // Malta\n\tNL: \"9944\", // Netherlands\n\tPL: \"9945\", // Poland\n\tPT: \"9946\", // Portugal\n\tRO: \"9947\", // Romania\n\tRS: \"9948\", // Serbia\n\tSI: \"9949\", // Slovenia\n\tSK: \"9950\", // Slovakia\n\tSM: \"9951\", // San Marino\n\tTR: \"9952\", // Turkey\n\tVA: \"9953\", // Holy See / Vatican City\n};\n\n/**\n * VAT registration prefixes that differ from the ISO 3166-1 alpha-2 country\n * code, so a VAT number's leading two letters still resolve to the right scheme.\n */\nconst VAT_PREFIX_TO_COUNTRY: Record<string, string> = {\n\tEL: \"GR\", // Greece issues VAT numbers with the \"EL\" prefix\n\tXI: \"GB\", // Northern Ireland VAT is issued under the UK scheme\n};\n\n/**\n * Resolve the Peppol participant identifier for a VAT number, deriving the EAS\n * scheme from the number's own country prefix (falling back to `countryCode`).\n *\n * `BE0206582284` → `{ scheme: \"9925\", value: \"BE0206582284\" }`\n *\n * The value keeps its country prefix, matching how participants register (the\n * Peppol directory lists this party as `9925:be0206582284`). Returns `null`\n * when the country has no VAT EAS scheme or the input is empty.\n */\nexport const resolveVatEndpoint = (params: {\n\tvatNumber: string | null | undefined;\n\tcountryCode?: string | null;\n}): UblEndpoint | null => {\n\tconst value = normalizeString(params.vatNumber);\n\tif (!value) return null;\n\n\tconst prefix = value\n\t\t.replace(/[^A-Za-z0-9]/g, \"\")\n\t\t.toUpperCase()\n\t\t.slice(0, 2);\n\tconst fromPrefix = /^[A-Z]{2}$/.test(prefix)\n\t\t? (VAT_PREFIX_TO_COUNTRY[prefix] ?? prefix)\n\t\t: null;\n\tconst fromCountry = normalizeString(params.countryCode)?.toUpperCase() ?? null;\n\n\tconst country =\n\t\tfromPrefix && fromPrefix in VAT_SCHEME_BY_COUNTRY ? fromPrefix : fromCountry;\n\tconst scheme = country ? VAT_SCHEME_BY_COUNTRY[country] : undefined;\n\tif (!scheme) return null;\n\n\t// Every scheme in the table is a VAT scheme, whose value carries no\n\t// separator, so the printed dots/spaces are dropped.\n\tconst cleaned = normalizeParticipantValue(scheme, value).toUpperCase();\n\tif (!cleaned) return null;\n\n\treturn { scheme, value: cleaned };\n};\n\n/**\n * Parse a Peppol participant identifier into a {@link UblEndpoint}.\n *\n * Accepts the canonical `scheme:value` form (e.g. `0208:0800279001`). Returns\n * `null` for values without an explicit scheme, since `cbc:EndpointID` requires\n * a `schemeID` and guessing one would mis-route the document.\n */\nexport const parsePeppolEndpoint = (\n\tpeppolId: string | null | undefined,\n): UblEndpoint | null => {\n\tconst normalized = normalizeString(peppolId);\n\tif (!normalized) return null;\n\tconst separatorIndex = normalized.indexOf(\":\");\n\tif (separatorIndex <= 0) return null;\n\tconst scheme = normalized.slice(0, separatorIndex).trim();\n\tconst value = normalized.slice(separatorIndex + 1).trim();\n\tif (!scheme || !value) return null;\n\treturn { scheme, value };\n};\n\nexport interface CustomerTaxIdentifiers {\n\tpeppolID: string | null;\n\tglnNumber: string | null;\n\ttaxNumber: string | null;\n\tvatNumber: string | null;\n}\n\nconst normalizeIdentifierType = (value: string | null) =>\n\tvalue?.toLowerCase().replace(/[^a-z0-9]+/g, \"_\") ?? null;\n\n/**\n * Pick the first usable Peppol identifier, GLN, VAT number, and tax number\n * from a Stripe-style `customer_tax_ids` array (`[{type, value}, …]`).\n *\n * Stripe stores VAT numbers under types like `eu_vat`, `gb_vat`, etc.\n * Peppol IDs are typically stored as a custom `peppol_id` type.\n */\nexport const extractCustomerTaxIdentifiers = (\n\ttaxIds: unknown,\n): CustomerTaxIdentifiers => {\n\tlet peppolID: string | null = null;\n\tlet glnNumber: string | null = null;\n\tlet taxNumber: string | null = null;\n\tlet vatNumber: string | null = null;\n\n\tif (!Array.isArray(taxIds)) {\n\t\treturn { peppolID, glnNumber, taxNumber, vatNumber };\n\t}\n\n\tfor (const entry of taxIds) {\n\t\tif (!isRecord(entry)) continue;\n\n\t\tconst type = normalizeIdentifierType(normalizeString(entry.type));\n\t\tconst value = normalizeString(entry.value);\n\t\tif (!type || !value) continue;\n\n\t\tif (!peppolID && type.includes(\"peppol\")) {\n\t\t\tpeppolID = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!glnNumber && type.includes(\"gln\")) {\n\t\t\tglnNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!vatNumber && type.includes(\"vat\")) {\n\t\t\tvatNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\t// Any other typed id (ca_gst_hst, au_abn, us_ein, ...) is a registration\n\t\t// number: it goes to BT-30, not BT-31.\n\t\tif (!taxNumber) taxNumber = value;\n\t}\n\n\treturn { peppolID, glnNumber, taxNumber, vatNumber };\n};\n\n/**\n * Build the fully-qualified Peppol participant identifiers (`scheme:value`) a\n * receiver lookup will accept, in priority order, de-duplicated.\n *\n * Stripe stores a customer's VAT number without a Peppol scheme (e.g.\n * `BE0206582284`), but a participant lookup needs the qualified identifier\n * (`9925:BE0206582284`). This attaches the right scheme:\n *\n * 1. an explicit Peppol ID (already `scheme:value`) — passed through as-is;\n * 2. a GLN under EAS `0088`;\n * 3. the VAT number under its country's VAT EAS scheme (see\n * {@link resolveVatEndpoint});\n * 4. for Belgium, the enterprise number (VAT digits without the `BE` prefix)\n * under EAS `0208` — many Belgian entities register only under that;\n * 5. a generic tax/registration number under its country's company-ID scheme.\n *\n * `countryCode` (the customer's country, when known) disambiguates schemes for\n * identifiers that don't carry a country prefix (GLN, plain tax numbers).\n */\nexport const listPeppolReceiverIdentifierCandidates = (\n\tcustomer: {\n\t\tpeppolID?: string | null;\n\t\tglnNumber?: string | null;\n\t\ttaxNumber?: string | null;\n\t\tvatNumber?: string | null;\n\t},\n\tcountryCode?: string | null,\n): string[] => {\n\tconst candidates: string[] = [];\n\tconst add = (id: { scheme?: string | null; value: string } | null) => {\n\t\tif (id?.scheme && id.value) candidates.push(`${id.scheme}:${id.value}`);\n\t};\n\n\t// 1. An explicit Peppol ID already carries its own scheme.\n\tconst peppol = normalizeString(customer.peppolID);\n\tif (peppol) candidates.push(peppol);\n\n\t// 2. GLN → EAS 0088 (Global Location Number).\n\tconst gln = normalizeString(customer.glnNumber);\n\tif (gln) add({ scheme: \"0088\", value: normalizeParticipantValue(\"0088\", gln) });\n\n\t// 3. VAT number → the country's VAT EAS scheme (e.g. BE → 9925).\n\tconst vat = resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });\n\tadd(vat);\n\n\t// 4. Belgium also reaches parties by enterprise number under EAS 0208; it is\n\t// the VAT digits without the `BE` prefix, and some entities register only so.\n\tif (vat?.scheme === \"9925\") {\n\t\tadd(\n\t\t\tbuildCompanyId({\n\t\t\t\tcountryCode: \"BE\",\n\t\t\t\tcompanyNumber: customer.vatNumber ?? null,\n\t\t\t}),\n\t\t);\n\t}\n\n\t// 5. A generic tax/registration number → its country's company-ID scheme.\n\tconst tax = normalizeString(customer.taxNumber);\n\tif (tax)\n\t\tadd(buildCompanyId({ countryCode: countryCode ?? null, companyNumber: tax }));\n\n\treturn Array.from(new Set(candidates));\n};\n","import { normalizeAddress } from \"./address\";\nimport { buildCompanyId, parsePeppolEndpoint, resolveVatEndpoint } from \"./identifiers\";\nimport type { UblAddress, UblEndpoint, UblParty } from \"./ubl/types\";\nimport { normalizeString } from \"./utils\";\n\n/**\n * Supplier (seller) VAT status. Drives how zero-VAT lines are reported when the\n * seller does not charge VAT:\n *\n * 1 — Subject to VAT (the normal case): line categories come from the data.\n * 2 — Not subject to VAT.\n * 3 — Small business / franchise exemption (e.g. Belgian Article 56bis).\n *\n * For statuses 2 and 3, {@link ../build.ts} coerces all line categories to a\n * non-charging exempt category so no VAT is reported.\n */\nexport type SupplierVatStatus = 1 | 2 | 3;\n\n/**\n * Caller-provided supplier data, normalized into a stable shape.\n *\n * Each consumer builds this from its own data store. Once a `UblSupplier`\n * exists, the party builder no longer needs to know where it came from.\n */\nexport interface UblSupplier {\n\t/** Display + legal name shown on the invoice. */\n\tname: string;\n\t/** ISO 3166-1 alpha-2 country code (e.g. `\"BE\"`). */\n\tcountryCode: string;\n\t/**\n\t * Free-form address. Stripe-style fields (`line1`, `postal_code`, `country`)\n\t * and legacy/internal fields (`street`, `zip_code`) are both accepted.\n\t */\n\taddress: unknown;\n\t/** Country-specific company/registration number (e.g. BE enterprise number). */\n\tcompanyNumber?: string | null;\n\t/** VAT number with country prefix (e.g. `\"BE0793904121\"`). */\n\tvatNumber?: string | null;\n\t/** Whether the supplier charges VAT. See {@link SupplierVatStatus}. */\n\tvatStatus: SupplierVatStatus;\n\t/** Peppol participant identifier in `scheme:value` form (e.g. `\"0208:0793904121\"`). */\n\tpeppolID?: string | null;\n}\n\n/** Convert a {@link UblSupplier} into the supplier (seller) party. */\nexport const buildSupplierParty = (supplier: UblSupplier): UblParty => {\n\tconst address = normalizeAddress(supplier.address, supplier.countryCode);\n\treturn {\n\t\tendpoint: parsePeppolEndpoint(supplier.peppolID),\n\t\tname: supplier.name,\n\t\taddress,\n\t\tvatNumber: normalizeString(supplier.vatNumber),\n\t\tlegalName: supplier.name,\n\t\tcompanyId: buildCompanyId({\n\t\t\tcountryCode: supplier.countryCode,\n\t\t\tcompanyNumber: supplier.companyNumber ?? null,\n\t\t}),\n\t};\n};\n\n/**\n * Caller-provided customer (buyer) data, normalized into a stable shape.\n *\n * Each consumer (the Stripe adapter, app-specific row builders) resolves its\n * own identifiers and address, then hands this generic shape to\n * {@link buildCustomerParty}, so the Peppol routing logic lives in one place.\n */\nexport interface UblCustomer {\n\t/** Display + legal name shown on the invoice. */\n\tname: string;\n\t/** Customer address, already normalized by the caller. */\n\taddress: UblAddress;\n\t/**\n\t * The customer's ISO 3166-1 alpha-2 country, used to resolve VAT/registration\n\t * schemes for identifiers that don't carry a country prefix. Pass the\n\t * customer's *own* country (never the supplier's) so the document is not\n\t * mis-routed; falls back to the address country when omitted.\n\t */\n\tcountryCode?: string | null;\n\t/** Peppol participant identifier in `scheme:value` form (e.g. `\"0208:0793904121\"`). */\n\tpeppolID?: string | null;\n\t/** Global Location Number (resolved under EAS `0088`). */\n\tglnNumber?: string | null;\n\t/** Generic tax/registration number (no VAT prefix). */\n\ttaxNumber?: string | null;\n\t/** VAT number with country prefix (e.g. `\"BE0793904121\"`). */\n\tvatNumber?: string | null;\n}\n\n/**\n * Convert a {@link UblCustomer} into the customer (buyer) party.\n *\n * The Peppol `EndpointID` (BT-49) — which routes the document — is resolved in\n * priority order: an explicit `endpointOverride` (e.g. a confirmed-registered\n * identifier), then an explicit Peppol ID, then a GLN (scheme `0088`), then the\n * VAT number mapped to its country's VAT EAS scheme (e.g. BE → `9925`). That\n * last step matters because most data stores hold a customer's VAT without a\n * scheme, so without it a VAT-only customer would have no endpoint and the\n * document would be unroutable.\n */\nexport const buildCustomerParty = (\n\tcustomer: UblCustomer,\n\tendpointOverride?: UblEndpoint | null,\n): UblParty => {\n\tconst countryCode =\n\t\tnormalizeString(customer.countryCode) ?? customer.address.countryCode;\n\tconst endpoint =\n\t\tendpointOverride ??\n\t\tparsePeppolEndpoint(customer.peppolID) ??\n\t\t(customer.glnNumber ? { scheme: \"0088\", value: customer.glnNumber } : null) ??\n\t\tresolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });\n\n\treturn {\n\t\tendpoint,\n\t\tname: customer.name,\n\t\taddress: customer.address,\n\t\tvatNumber: normalizeString(customer.vatNumber),\n\t\tlegalName: customer.name,\n\t\tcompanyId: buildCompanyId({\n\t\t\tcountryCode,\n\t\t\tcompanyNumber: customer.taxNumber ?? null,\n\t\t}),\n\t};\n};\n","import type { UblAttachment, UblDocument } from \"./ubl/types\";\n\n/**\n * Build a UBL embedded-document attachment (BG-24) from raw bytes — e.g. the\n * rendered PDF of the invoice. Emitted as a `cac:AdditionalDocumentReference`\n * with an inline base64 `cbc:EmbeddedDocumentBinaryObject`.\n */\nexport const buildPdfAttachment = (params: {\n\tfilename: string;\n\tbytes: Uint8Array;\n\t/** Document reference ID (BT-122). Defaults to the filename. */\n\tid?: string;\n}): UblAttachment => ({\n\tid: params.id ?? params.filename,\n\tfilename: params.filename,\n\tmimeCode: \"application/pdf\",\n\tbase64: Buffer.from(params.bytes).toString(\"base64\"),\n});\n\n/**\n * Replace each attachment's base64 payload with `[omitted]` plus a length, so a\n * {@link UblDocument} is safe to log or persist for audit.\n */\nexport const sanitizeUblDocumentForAudit = (doc: UblDocument): UblDocument => {\n\tif (doc.attachments.length === 0) return doc;\n\treturn {\n\t\t...doc,\n\t\tattachments: doc.attachments.map((attachment) => ({\n\t\t\t...attachment,\n\t\t\tbase64: `[omitted ${attachment.base64.length} chars]`,\n\t\t})),\n\t};\n};\n","/** Round a number to 2 decimal places (cents). */\nexport const roundCurrency = (value: number) =>\n\tMath.round((value + Number.EPSILON) * 100) / 100;\n\n/** Convert an integer cent amount into a 2-decimal currency value. */\nexport const centsToDecimal = (cents: number) => roundCurrency(cents / 100);\n\n/** The `cac:Price` pair for a line: BT-146 and the optional BT-149. */\nexport interface UnitPrice {\n\t/** `cbc:PriceAmount` (BT-146). */\n\tpriceAmount: number;\n\t/** `cbc:BaseQuantity` (BT-149) — the units `priceAmount` covers. Omitted = 1. */\n\tbaseQuantity?: number;\n}\n\n/**\n * Derive the `cac:Price` for a line whose net total is authoritative.\n *\n * Peppol rule PEPPOL-EN16931-R120 checks\n * `quantity × (priceAmount ÷ baseQuantity)` against the line net amount within\n * a 0.02 tolerance. Naively rounding `net ÷ quantity` to cents breaks that\n * whenever the division doesn't land on a cent: 940.00 over 14 units gives\n * 67.142857…, which rounds to 67.14, and 14 × 67.14 = 939.96 — off by 0.04 and\n * rejected as a fatal validation error.\n *\n * So the cent-rounded unit price is only used when it reproduces the net\n * exactly. Otherwise the line is priced as a whole via BT-149 (`priceAmount` =\n * the net, `baseQuantity` = the quantity), which is exact at any magnitude\n * instead of merely within tolerance — the residual of a rounded unit price\n * grows with quantity and would eventually breach 0.02 at any fixed precision.\n */\nexport const deriveUnitPrice = (netTotal: number, quantity: number): UnitPrice => {\n\t// A zero or fractional-to-zero quantity still has to price something; BT-149\n\t// must be a positive number (PEPPOL-EN16931-R121), so floor the divisor at 1.\n\tconst units = quantity > 0 ? quantity : 1;\n\tconst perUnit = roundCurrency(netTotal / units);\n\tif (roundCurrency(perUnit * units) === roundCurrency(netTotal)) {\n\t\treturn { priceAmount: perUnit };\n\t}\n\treturn { priceAmount: roundCurrency(netTotal), baseQuantity: units };\n};\n","import type { UblTaxCategory } from \"./ubl/types\";\n\n/**\n * Stripe Tax `taxability_reason` values that map to a VAT-exempt UBL category\n * (`E`). Reverse charge is handled separately (category `AE`).\n */\nexport const EXEMPT_TAXABILITY_REASONS = new Set([\n\t\"customer_exempt\",\n\t\"product_exempt\",\n\t\"not_subject_to_tax\",\n\t\"not_collecting\",\n\t\"not_supported\",\n\t\"portion_product_exempt\",\n]);\n\n/** Human-readable EN 16931 exemption reasons (BR-E-10 / BR-AE-10 / …). */\nconst EXEMPTION_REASON_TEXT: Record<string, string> = {\n\treverse_charge: \"Reverse charge\",\n\tintra_community: \"Intra-community supply\",\n\texport: \"Export outside the EU\",\n\tcustomer_exempt: \"Exempt based on customer status\",\n\tproduct_exempt: \"Exempt based on the supplied goods or services\",\n\tportion_product_exempt: \"Exempt based on the supplied goods or services\",\n\tnot_subject_to_tax: \"Not subject to VAT\",\n\tnot_collecting: \"VAT not collected\",\n\tnot_supported: \"VAT not applicable\",\n};\n\nexport interface TaxAmountInfo {\n\tamount: number;\n\ttaxability_reason?: string | null;\n\ttax_rate_percentage?: number | null;\n}\n\nconst normalizeTaxCategoryId = (value: unknown) => {\n\tif (typeof value !== \"string\") return null;\n\tconst normalized = value.trim().toUpperCase();\n\treturn normalized.length > 0 ? normalized : null;\n};\n\n/**\n * Map an explicit UBL category hint, a Stripe `taxability_reason`, and/or a\n * numeric rate into a {@link UblTaxCategory}.\n *\n * - Reverse charge → `AE` (0%, with exemption reason)\n * - Intra-community supply → `K` (0%, with exemption reason)\n * - Export outside the EU → `G` (0%, with exemption reason)\n * - Any other exempt reason → `E` (0%, with exemption reason)\n * - Category `Z` / rate ≤ 0 → `Z` (zero-rated, 0%)\n * - Otherwise → `S` (standard, the line's rate)\n */\nexport const taxCategoryFromReasonOrRate = (params: {\n\ttaxCategoryId?: string | null;\n\ttaxabilityReason: string | null;\n\trate: number;\n}): UblTaxCategory => {\n\tconst categoryHint = normalizeTaxCategoryId(params.taxCategoryId);\n\tconst reason = params.taxabilityReason;\n\n\tif (categoryHint === \"AE\" || reason === \"reverse_charge\") {\n\t\treturn {\n\t\t\tid: \"AE\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT.reverse_charge,\n\t\t};\n\t}\n\tif (categoryHint === \"K\" || reason === \"intra_community\") {\n\t\treturn {\n\t\t\tid: \"K\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT.intra_community,\n\t\t};\n\t}\n\tif (categoryHint === \"G\" || reason === \"export\") {\n\t\treturn {\n\t\t\tid: \"G\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT.export,\n\t\t};\n\t}\n\tif (categoryHint === \"E\" || (reason && EXEMPT_TAXABILITY_REASONS.has(reason))) {\n\t\treturn {\n\t\t\tid: \"E\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason:\n\t\t\t\t(reason ? EXEMPTION_REASON_TEXT[reason] : null) ?? \"Exempt from VAT\",\n\t\t};\n\t}\n\tif (categoryHint === \"Z\" || reason === \"zero_rated\" || params.rate <= 0) {\n\t\treturn { id: \"Z\", percent: 0 };\n\t}\n\treturn { id: \"S\", percent: params.rate };\n};\n\n/**\n * Resolve a {@link UblTaxCategory} from a line's Stripe tax info.\n *\n * Exempt / reverse-charge / zero-rated reasons take precedence over the rate;\n * otherwise the rate decides standard (`S`) vs zero-rated (`Z`).\n */\nexport const resolveTaxCategoryFromTaxAmounts = (\n\ttaxAmounts: TaxAmountInfo[],\n\trate: number,\n): UblTaxCategory => {\n\tfor (const ta of taxAmounts) {\n\t\tif (!ta.taxability_reason) continue;\n\t\tif (ta.taxability_reason === \"reverse_charge\") {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: \"reverse_charge\",\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t\tif (EXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)) {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: ta.taxability_reason,\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t\tif (ta.taxability_reason === \"zero_rated\") {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: \"zero_rated\",\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t}\n\treturn taxCategoryFromReasonOrRate({ taxabilityReason: null, rate });\n};\n","import { deriveUnitPrice, roundCurrency } from \"./numeric\";\nimport type {\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n\tUblTaxTotal,\n} from \"./ubl/types\";\n\n/**\n * Adjust the largest line's net amount so the line nets sum to the\n * authoritative document total (e.g. Stripe's `invoice.total_excluding_tax`).\n *\n * Reconciling at the *line* level — rather than directly on the VAT breakdown —\n * keeps the document consistent bottom-up: the VAT category taxable amounts\n * (BR-S-08) and the line-extension total (BR-CO-13) both still derive from the\n * lines. Discrepancies here are sub-cent rounding or a distributed invoice-level\n * coupon; larger ones indicate a real upstream data problem.\n */\nexport const reconcileLinesToExclTotal = (\n\tlines: UblLine[],\n\tauthoritativeTotalExclVat: number,\n): UblLine[] => {\n\tif (lines.length === 0) return lines;\n\tconst computed = roundCurrency(\n\t\tlines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),\n\t);\n\tconst diff = roundCurrency(authoritativeTotalExclVat - computed);\n\tif (diff === 0) return lines;\n\n\tconst largestIdx = lines.reduce(\n\t\t(maxIdx, line, idx, arr) =>\n\t\t\tline.lineExtensionAmount > (arr[maxIdx]?.lineExtensionAmount ?? 0)\n\t\t\t\t? idx\n\t\t\t\t: maxIdx,\n\t\t0,\n\t);\n\n\treturn lines.map((line, idx) => {\n\t\tif (idx !== largestIdx) return line;\n\t\tconst adjusted = roundCurrency(line.lineExtensionAmount + diff);\n\t\t// Re-derive the price from the adjusted net through the shared helper —\n\t\t// nudging the net without re-deriving BT-146/BT-149 to match is exactly\n\t\t// what PEPPOL-EN16931-R120 rejects. Assign `baseQuantity` unconditionally\n\t\t// so a line that no longer needs one doesn't keep a stale value.\n\t\tconst { priceAmount, baseQuantity } = deriveUnitPrice(adjusted, line.quantity);\n\t\treturn {\n\t\t\t...line,\n\t\t\tlineExtensionAmount: adjusted,\n\t\t\tpriceAmount,\n\t\t\tbaseQuantity,\n\t\t};\n\t});\n};\n\nconst categoryKey = (category: UblTaxCategory): string =>\n\t`${category.id}:${category.percent}`;\n\nexport interface BuildTaxTotalsResult {\n\ttaxTotal: UblTaxTotal;\n\tmonetaryTotal: UblMonetaryTotal;\n}\n\nexport interface BuildTaxTotalsOptions {\n\t/**\n\t * BT-113 — amount already paid, **gross (VAT-inclusive)**. Subtracted from\n\t * BT-112 to derive the outstanding `payableAmount` (BR-CO-16). Pass the full\n\t * gross total for a settled document so it reports a payable amount of 0.\n\t */\n\tprepaidAmount?: number;\n\t/** BT-114 — rounding applied to the payable amount. */\n\tpayableRoundingAmount?: number;\n}\n\n/**\n * Group lines by `(category, percent)` into a VAT breakdown and compute the\n * document monetary totals.\n *\n * Each VAT category's tax amount is **derived** as `taxable × percent / 100`,\n * rounded to two decimals (EN 16931 BR-CO-17), rather than summed from the\n * upstream per-line tax cents. This guarantees the breakdown is internally\n * consistent and passes validation; it can differ by a cent from the figure a\n * payment processor reported, which is an unavoidable artifact of representing\n * a cents-rounded system as a rate-based VAT breakdown.\n *\n * `payableAmount` is derived per BR-CO-16 (`BT-112 − BT-113 + BT-114`) so the\n * invariant holds by construction. The result is *not* clamped: a prepayment\n * exceeding the total yields a negative payable amount, surfacing the upstream\n * overpayment rather than hiding it.\n */\nexport const buildTaxTotals = (\n\tlines: UblLine[],\n\toptions?: BuildTaxTotalsOptions,\n): BuildTaxTotalsResult => {\n\tconst groups = new Map<\n\t\tstring,\n\t\t{ category: UblTaxCategory; taxableAmount: number }\n\t>();\n\n\tfor (const line of lines) {\n\t\tconst key = categoryKey(line.taxCategory);\n\t\tconst current = groups.get(key) ?? {\n\t\t\tcategory: line.taxCategory,\n\t\t\ttaxableAmount: 0,\n\t\t};\n\t\tcurrent.taxableAmount = roundCurrency(\n\t\t\tcurrent.taxableAmount + line.lineExtensionAmount,\n\t\t);\n\t\tgroups.set(key, current);\n\t}\n\n\tconst subtotals: UblTaxSubtotal[] = Array.from(groups.values()).map((group) => ({\n\t\ttaxableAmount: group.taxableAmount,\n\t\ttaxAmount: roundCurrency((group.taxableAmount * group.category.percent) / 100),\n\t\tcategory: group.category,\n\t}));\n\n\tconst lineExtensionAmount = roundCurrency(\n\t\tlines.reduce((sum, line) => sum + line.lineExtensionAmount, 0),\n\t);\n\tconst taxAmount = roundCurrency(\n\t\tsubtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0),\n\t);\n\tconst taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);\n\n\tconst prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);\n\tconst payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);\n\tconst payableAmount = roundCurrency(\n\t\ttaxInclusiveAmount - prepaidAmount + payableRoundingAmount,\n\t);\n\n\treturn {\n\t\ttaxTotal: { taxAmount, subtotals },\n\t\tmonetaryTotal: {\n\t\t\tlineExtensionAmount,\n\t\t\ttaxExclusiveAmount: lineExtensionAmount,\n\t\t\ttaxInclusiveAmount,\n\t\t\t...(prepaidAmount ? { prepaidAmount } : {}),\n\t\t\t...(payableRoundingAmount ? { payableRoundingAmount } : {}),\n\t\t\tpayableAmount,\n\t\t},\n\t};\n};\n"],"mappings":";;;;AAGA,MAAa,uBACZ;;AAGD,MAAa,iBAAiB;;AAG9B,MAAa,oBAAoB;;AAEjC,MAAa,wBAAwB;;AAGrC,MAAa,oBAAoB;;AAGjC,MAAa,oBAAoB;;AAGjC,MAAa,uBAAuB;AAEpC,MAAa,aAAa;AAC1B,MAA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GAAG,GAAG,SAAS;;;;;;;;;;;;;;;;;AAkC5B,MAAa,kBACZ,OACA,YAC0B;CAC1B,MAAM,yBAAS,IAAI,IAGjB;CAEF,KAAK,MAAM,QAAQ,OAAO;EACzB,MAAM,MAAM,YAAY,KAAK,WAAW;EACxC,MAAM,UAAU,OAAO,IAAI,GAAG,KAAK;GAClC,UAAU,KAAK;GACf,eAAe;EAChB;EACA,QAAQ,gBAAgB,cACvB,QAAQ,gBAAgB,KAAK,mBAC9B;EACA,OAAO,IAAI,KAAK,OAAO;CACxB;CAEA,MAAM,YAA8B,MAAM,KAAK,OAAO,OAAO,CAAC,CAAC,CAAC,KAAK,WAAW;EAC/E,eAAe,MAAM;EACrB,WAAW,cAAe,MAAM,gBAAgB,MAAM,SAAS,UAAW,GAAG;EAC7E,UAAU,MAAM;CACjB,EAAE;CAEF,MAAM,sBAAsB,cAC3B,MAAM,QAAQ,KAAK,SAAS,MAAM,KAAK,qBAAqB,CAAC,CAC9D;CACA,MAAM,YAAY,cACjB,UAAU,QAAQ,KAAK,aAAa,MAAM,SAAS,WAAW,CAAC,CAChE;CACA,MAAM,qBAAqB,cAAc,sBAAsB,SAAS;CAExE,MAAM,gBAAgB,cAAc,SAAS,iBAAiB,CAAC;CAC/D,MAAM,wBAAwB,cAAc,SAAS,yBAAyB,CAAC;CAC/E,MAAM,gBAAgB,cACrB,qBAAqB,gBAAgB,qBACtC;CAEA,OAAO;EACN,UAAU;GAAE;GAAW;EAAU;EACjC,eAAe;GACd;GACA,oBAAoB;GACpB;GACA,GAAI,gBAAgB,EAAE,cAAc,IAAI,CAAC;GACzC,GAAI,wBAAwB,EAAE,sBAAsB,IAAI,CAAC;GACzD;EACD;CACD;AACD"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/build/ubl/constants.ts","../../src/build/xml.ts","../../src/build/ubl/serialize.ts","../../src/build/utils.ts","../../src/build/address.ts","../../src/build/identifiers.ts","../../src/build/party.ts","../../src/build/attachment.ts","../../src/build/numeric.ts","../../src/build/tax-category.ts","../../src/build/tax-totals.ts"],"sourcesContent":["/** Peppol BIS Billing 3.0 / EN 16931 identifiers and fixed code values. */\n\n/** EN 16931 + Peppol BIS Billing 3.0 customization (BT-24). */\nexport const UBL_CUSTOMIZATION_ID =\n\t\"urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0\";\n\n/** Peppol BIS Billing 3.0 process (BT-23). */\nexport const UBL_PROFILE_ID = \"urn:fdc:peppol.eu:2017:poacc:billing:01:1.0\";\n\n/** UNTDID 1001 — commercial invoice. */\nexport const INVOICE_TYPE_CODE = \"380\";\n/** UNTDID 1001 — credit note. */\nexport const CREDIT_NOTE_TYPE_CODE = \"381\";\n\n/** UN/ECE Recommendation 20 — \"one / piece\" (the default line unit). */\nexport const DEFAULT_UNIT_CODE = \"C62\";\n\n/** UNCL5153 — the VAT tax scheme identifier. */\nexport const VAT_TAX_SCHEME_ID = \"VAT\";\n\n/** ISO 3166-1 alpha-2 list identifier for `cbc:IdentificationCode`. */\nexport const COUNTRY_CODE_LIST_ID = \"ISO3166-1:Alpha2\";\n\nexport const NS_INVOICE = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\";\nexport const NS_CREDIT_NOTE =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2\";\nexport const NS_CAC =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\nexport const NS_CBC =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\n","/**\n * Minimal, dependency-free XML builder + serializer.\n *\n * UBL is order-sensitive (every element sequence is fixed by the schema), so\n * children are always explicit, ordered arrays. There is no attribute or text\n * coercion magic beyond escaping — the UBL layer is responsible for emitting\n * elements in the right order.\n */\n\nexport type XmlAttrs = Record<string, string | number | null | undefined>;\n\nexport interface XmlElement {\n\tname: string;\n\tattrs?: XmlAttrs;\n\t/** Leaf text content. Mutually exclusive with `children`. */\n\ttext?: string | number | null;\n\t/** Child elements. Mutually exclusive with `text`. */\n\tchildren?: XmlElement[];\n}\n\n/** Falsy children are dropped, so callers can write `cond && el(...)`. */\ntype ChildSpec = XmlElement | null | undefined | false;\n\n/**\n * Build an XML element.\n *\n * el(\"cbc:ID\", null, \"INV-1\") → <cbc:ID>INV-1</cbc:ID>\n * el(\"cbc:Amount\", { currencyID: \"EUR\" }, \"10.00\") → <cbc:Amount currencyID=\"EUR\">10.00</cbc:Amount>\n * el(\"cac:Party\", null, [child, cond && child2]) → nested element\n */\nexport const el = (\n\tname: string,\n\tattrs?: XmlAttrs | null,\n\tcontent?: string | number | null | ChildSpec[],\n): XmlElement => {\n\tif (Array.isArray(content)) {\n\t\treturn {\n\t\t\tname,\n\t\t\t...(attrs ? { attrs } : {}),\n\t\t\tchildren: content.filter((c): c is XmlElement => Boolean(c)),\n\t\t};\n\t}\n\treturn {\n\t\tname,\n\t\t...(attrs ? { attrs } : {}),\n\t\t...(content !== undefined ? { text: content } : {}),\n\t};\n};\n\nconst escapeText = (value: string): string =>\n\tvalue.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n\nconst escapeAttr = (value: string): string => escapeText(value).replace(/\"/g, \"&quot;\");\n\nconst serializeAttrs = (attrs: XmlAttrs | undefined): string => {\n\tif (!attrs) return \"\";\n\treturn Object.entries(attrs)\n\t\t.filter(([, value]) => value !== null && value !== undefined)\n\t\t.map(([key, value]) => ` ${key}=\"${escapeAttr(String(value))}\"`)\n\t\t.join(\"\");\n};\n\nconst serializeElement = (node: XmlElement, indentLevel: number): string => {\n\tconst pad = \" \".repeat(indentLevel);\n\tconst attrs = serializeAttrs(node.attrs);\n\n\tif (node.text !== undefined && node.text !== null) {\n\t\treturn `${pad}<${node.name}${attrs}>${escapeText(String(node.text))}</${node.name}>`;\n\t}\n\n\tconst children = node.children ?? [];\n\tif (children.length === 0) {\n\t\treturn `${pad}<${node.name}${attrs}/>`;\n\t}\n\n\tconst inner = children\n\t\t.map((child) => serializeElement(child, indentLevel + 1))\n\t\t.join(\"\\n\");\n\treturn `${pad}<${node.name}${attrs}>\\n${inner}\\n${pad}</${node.name}>`;\n};\n\n/** Serialize a root element into a UTF-8 XML document string. */\nexport const serializeDocument = (root: XmlElement): string =>\n\t`<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n${serializeElement(root, 0)}\\n`;\n","import { UblBuildError } from \"../../errors\";\nimport type {\n\tUblAddress,\n\tUblAttachment,\n\tUblBillingReference,\n\tUblInvoice,\n\tUblInvoicePeriod,\n\tUblLine,\n\tUblParty,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n} from \"../../types\";\nimport { el, serializeDocument, type XmlElement } from \"../xml\";\nimport {\n\tCOUNTRY_CODE_LIST_ID,\n\tCREDIT_NOTE_TYPE_CODE,\n\tINVOICE_TYPE_CODE,\n\tNS_CAC,\n\tNS_CBC,\n\tNS_CREDIT_NOTE,\n\tNS_INVOICE,\n\tUBL_CUSTOMIZATION_ID,\n\tUBL_PROFILE_ID,\n\tVAT_TAX_SCHEME_ID,\n} from \"./constants\";\n\n// ── Validation ─────────────────────────────────────────────────────────\n//\n// The model is permissive (the parser reads whatever a document states); the\n// serializer is where EN 16931 / Peppol BIS Billing 3.0 mandatory fields are\n// enforced. Each check names the BT and the model path in its message.\n\nconst missing = (what: string, path: string): UblBuildError =>\n\tnew UblBuildError(`Missing ${what} (${path})`);\n\nfunction required<T>(value: T | undefined, what: string, path: string): NonNullable<T> {\n\tif (value === undefined || value === null || value === \"\") {\n\t\tthrow missing(what, path);\n\t}\n\treturn value as NonNullable<T>;\n}\n\n/** Category `O` (outside scope) is the one category BR-O-05 forbids a percent on. */\nconst requiresPercent = (categoryId: string): boolean => categoryId !== \"O\";\n\nconst validateTaxCategory = (\n\tcategory: UblTaxCategory | undefined,\n\tpath: string,\n): UblTaxCategory & { id: string } => {\n\tconst present = required(category, \"VAT category (BT-151/BT-118)\", path);\n\tconst id = required(present.id, \"VAT category code (BT-151/BT-118)\", `${path}.id`);\n\tif (requiresPercent(id) && present.percent === undefined) {\n\t\tthrow missing(`VAT rate (BT-152/BT-119) for category ${id}`, `${path}.percent`);\n\t}\n\treturn { ...present, id };\n};\n\nconst validateLine = (line: UblLine, index: number): void => {\n\tconst path = `lines[${index}]`;\n\trequired(line.id, \"line identifier (BT-126)\", `${path}.id`);\n\trequired(line.quantity, \"invoiced quantity (BT-129)\", `${path}.quantity`);\n\trequired(line.unitCode, \"unit code (BT-130)\", `${path}.unitCode`);\n\trequired(line.unitPrice, \"net unit price (BT-146)\", `${path}.unitPrice`);\n\trequired(\n\t\tline.lineExtensionAmount,\n\t\t\"line net amount (BT-131)\",\n\t\t`${path}.lineExtensionAmount`,\n\t);\n\tvalidateTaxCategory(line.taxCategory, `${path}.taxCategory`);\n};\n\nconst isExternalOnly = (attachment: UblAttachment): boolean =>\n\tattachment.externalUri !== undefined && attachment.base64Content === undefined;\n\nconst validateAttachment = (attachment: UblAttachment, index: number): void => {\n\tif (isExternalOnly(attachment)) return;\n\tconst path = `attachments[${index}]`;\n\trequired(attachment.filename, \"attachment filename (BT-125-2)\", `${path}.filename`);\n\trequired(\n\t\tattachment.mimeCode,\n\t\t\"attachment MIME code (BT-125-1)\",\n\t\t`${path}.mimeCode`,\n\t);\n\trequired(\n\t\tattachment.base64Content,\n\t\t\"attachment content (BT-125)\",\n\t\t`${path}.base64Content`,\n\t);\n};\n\nconst validateInvoice = (doc: UblInvoice): void => {\n\trequired(doc.id, \"document identifier (BT-1)\", \"id\");\n\trequired(doc.issueDate, \"issue date (BT-2)\", \"issueDate\");\n\trequired(doc.currency, \"document currency (BT-5)\", \"currency\");\n\trequired(doc.seller.name, \"seller name (BT-27)\", \"seller.name\");\n\trequired(doc.buyer.name, \"buyer name (BT-44)\", \"buyer.name\");\n\tif (doc.seller.endpoint && doc.seller.endpoint.scheme === undefined) {\n\t\tthrow missing(\"seller endpoint scheme (BT-34-1)\", \"seller.endpoint.scheme\");\n\t}\n\tif (doc.buyer.endpoint && doc.buyer.endpoint.scheme === undefined) {\n\t\tthrow missing(\"buyer endpoint scheme (BT-49-1)\", \"buyer.endpoint.scheme\");\n\t}\n\tif (doc.lines.length === 0) {\n\t\tthrow new UblBuildError(\"A document needs at least one line (BG-25, lines)\");\n\t}\n\tdoc.lines.forEach(validateLine);\n\trequired(doc.taxTotal.taxAmount, \"total VAT amount (BT-110)\", \"taxTotal.taxAmount\");\n\tconst total = doc.monetaryTotal;\n\trequired(\n\t\ttotal.lineExtensionAmount,\n\t\t\"sum of line net amounts (BT-106)\",\n\t\t\"monetaryTotal.lineExtensionAmount\",\n\t);\n\trequired(\n\t\ttotal.taxExclusiveAmount,\n\t\t\"total without VAT (BT-109)\",\n\t\t\"monetaryTotal.taxExclusiveAmount\",\n\t);\n\trequired(\n\t\ttotal.taxInclusiveAmount,\n\t\t\"total with VAT (BT-112)\",\n\t\t\"monetaryTotal.taxInclusiveAmount\",\n\t);\n\trequired(total.payableAmount, \"amount due (BT-115)\", \"monetaryTotal.payableAmount\");\n\t(doc.attachments ?? []).forEach(validateAttachment);\n};\n\n// ── Formatting ─────────────────────────────────────────────────────────\n\n/** Format a monetary value as a 2-decimal string (UBL amounts are fixed-scale). */\nconst amount = (value: number): string => value.toFixed(2);\n\n/** Format a VAT percentage. Trims to at most 2 decimals without forcing them. */\nconst percent = (value: number): string => {\n\tconst rounded = Math.round(value * 100) / 100;\n\treturn Number.isInteger(rounded) ? rounded.toFixed(2) : String(rounded);\n};\n\nconst money = (name: string, value: number, currency: string): XmlElement =>\n\tel(name, { currencyID: currency }, amount(value));\n\nconst text = (name: string, value: string | undefined): XmlElement | null =>\n\tvalue !== undefined ? el(name, null, value) : null;\n\nconst taxScheme = (schemeId: string | undefined): XmlElement =>\n\tel(\"cac:TaxScheme\", null, [el(\"cbc:ID\", null, schemeId ?? VAT_TAX_SCHEME_ID)]);\n\n/**\n * Render a tax category, shared between `cac:ClassifiedTaxCategory` (on lines)\n * and `cac:TaxCategory` (in the VAT breakdown). EN 16931 requires an exemption\n * reason for the non-charging categories (E/AE/O/K/G).\n */\nconst taxCategory = (\n\tname: string,\n\tcategory: UblTaxCategory,\n\tpath: string,\n): XmlElement => {\n\tconst valid = validateTaxCategory(category, path);\n\treturn el(name, null, [\n\t\tel(\"cbc:ID\", null, valid.id),\n\t\tvalid.percent !== undefined\n\t\t\t? el(\"cbc:Percent\", null, percent(valid.percent))\n\t\t\t: null,\n\t\ttext(\"cbc:TaxExemptionReason\", valid.exemptionReason),\n\t\ttaxScheme(valid.schemeId),\n\t]);\n};\n\nconst postalAddress = (address: UblAddress): XmlElement =>\n\tel(\"cac:PostalAddress\", null, [\n\t\ttext(\"cbc:StreetName\", address.street),\n\t\ttext(\"cbc:AdditionalStreetName\", address.additionalStreet),\n\t\ttext(\"cbc:CityName\", address.city),\n\t\ttext(\"cbc:PostalZone\", address.postalZone),\n\t\ttext(\"cbc:CountrySubentity\", address.countrySubentity),\n\t\taddress.countryCode !== undefined\n\t\t\t? el(\"cac:Country\", null, [\n\t\t\t\t\tel(\n\t\t\t\t\t\t\"cbc:IdentificationCode\",\n\t\t\t\t\t\t{ listID: COUNTRY_CODE_LIST_ID },\n\t\t\t\t\t\taddress.countryCode,\n\t\t\t\t\t),\n\t\t\t\t])\n\t\t\t: null,\n\t]);\n\nconst party = (source: UblParty, name: string): XmlElement =>\n\tel(\"cac:Party\", null, [\n\t\tsource.endpoint\n\t\t\t? el(\n\t\t\t\t\t\"cbc:EndpointID\",\n\t\t\t\t\t{ schemeID: source.endpoint.scheme ?? \"\" },\n\t\t\t\t\tsource.endpoint.value,\n\t\t\t\t)\n\t\t\t: null,\n\t\tel(\"cac:PartyName\", null, [el(\"cbc:Name\", null, name)]),\n\t\tsource.address ? postalAddress(source.address) : null,\n\t\tsource.vatId !== undefined\n\t\t\t? el(\"cac:PartyTaxScheme\", null, [\n\t\t\t\t\tel(\"cbc:CompanyID\", null, source.vatId),\n\t\t\t\t\ttaxScheme(source.taxSchemeId),\n\t\t\t\t])\n\t\t\t: null,\n\t\tel(\"cac:PartyLegalEntity\", null, [\n\t\t\tel(\"cbc:RegistrationName\", null, source.registrationName ?? name),\n\t\t\tsource.companyId\n\t\t\t\t? el(\n\t\t\t\t\t\t\"cbc:CompanyID\",\n\t\t\t\t\t\tsource.companyId.scheme !== undefined\n\t\t\t\t\t\t\t? { schemeID: source.companyId.scheme }\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\tsource.companyId.value,\n\t\t\t\t\t)\n\t\t\t\t: null,\n\t\t]),\n\t]);\n\nconst taxSubtotal = (\n\tsubtotal: UblTaxSubtotal,\n\tcurrency: string,\n\tindex: number,\n): XmlElement => {\n\tconst path = `taxTotal.subtotals[${index}]`;\n\treturn el(\"cac:TaxSubtotal\", null, [\n\t\tmoney(\n\t\t\t\"cbc:TaxableAmount\",\n\t\t\trequired(\n\t\t\t\tsubtotal.taxableAmount,\n\t\t\t\t\"taxable amount (BT-116)\",\n\t\t\t\t`${path}.taxableAmount`,\n\t\t\t),\n\t\t\tcurrency,\n\t\t),\n\t\tmoney(\n\t\t\t\"cbc:TaxAmount\",\n\t\t\trequired(subtotal.taxAmount, \"VAT amount (BT-117)\", `${path}.taxAmount`),\n\t\t\tcurrency,\n\t\t),\n\t\ttaxCategory(\n\t\t\t\"cac:TaxCategory\",\n\t\t\trequired(subtotal.category, \"VAT category (BT-118)\", `${path}.category`),\n\t\t\t`${path}.category`,\n\t\t),\n\t]);\n};\n\n/**\n * `cac:LegalMonetaryTotal` children, in UBL sequence order. `cbc:PrepaidAmount`\n * (BT-113) and `cbc:PayableRoundingAmount` (BT-114) precede `cbc:PayableAmount`\n * — emitting them after it produces schema-invalid XML. BT-113/BT-114 are\n * omitted when absent or zero.\n */\nconst legalMonetaryTotalChildren = (doc: UblInvoice): XmlElement[] => {\n\tconst { currency, monetaryTotal: total } = doc;\n\tconst children: (XmlElement | null)[] = [\n\t\tmoney(\"cbc:LineExtensionAmount\", total.lineExtensionAmount ?? 0, currency),\n\t\tmoney(\"cbc:TaxExclusiveAmount\", total.taxExclusiveAmount ?? 0, currency),\n\t\tmoney(\"cbc:TaxInclusiveAmount\", total.taxInclusiveAmount ?? 0, currency),\n\t\ttotal.prepaidAmount\n\t\t\t? money(\"cbc:PrepaidAmount\", total.prepaidAmount, currency)\n\t\t\t: null,\n\t\ttotal.payableRoundingAmount\n\t\t\t? money(\"cbc:PayableRoundingAmount\", total.payableRoundingAmount, currency)\n\t\t\t: null,\n\t\tmoney(\"cbc:PayableAmount\", total.payableAmount ?? 0, currency),\n\t];\n\treturn children.filter((child): child is XmlElement => Boolean(child));\n};\n\n/**\n * `cac:InvoicePeriod`. Null when neither bound is set — an empty period element\n * fails BR-CO-19, which requires at least one of the two dates.\n */\nconst invoicePeriod = (period: UblInvoicePeriod | undefined): XmlElement | null => {\n\tif (!period || (period.startDate === undefined && period.endDate === undefined)) {\n\t\treturn null;\n\t}\n\treturn el(\"cac:InvoicePeriod\", null, [\n\t\ttext(\"cbc:StartDate\", period.startDate),\n\t\ttext(\"cbc:EndDate\", period.endDate),\n\t]);\n};\n\nconst line = (\n\tsource: UblLine,\n\tcurrency: string,\n\tdocumentType: UblInvoice[\"documentType\"],\n): XmlElement => {\n\tconst isCreditNote = documentType === \"CreditNote\";\n\tconst lineElementName = isCreditNote ? \"cac:CreditNoteLine\" : \"cac:InvoiceLine\";\n\tconst quantityElementName = isCreditNote\n\t\t? \"cbc:CreditedQuantity\"\n\t\t: \"cbc:InvoicedQuantity\";\n\tconst unitCode = source.unitCode ?? \"\";\n\t// BT-146 covers BT-149 units; the model holds the per-unit price.\n\tconst priceAmount = (source.unitPrice ?? 0) * (source.baseQuantity ?? 1);\n\n\treturn el(lineElementName, null, [\n\t\tel(\"cbc:ID\", null, source.id),\n\t\tel(quantityElementName, { unitCode }, String(source.quantity ?? 0)),\n\t\tmoney(\"cbc:LineExtensionAmount\", source.lineExtensionAmount ?? 0, currency),\n\t\tinvoicePeriod(source.invoicePeriod),\n\t\tel(\"cac:Item\", null, [\n\t\t\ttext(\"cbc:Description\", source.description),\n\t\t\t// BT-153 is mandatory; BT-154 stands in when the line has no name.\n\t\t\tel(\"cbc:Name\", null, source.itemName ?? source.description ?? source.id),\n\t\t\ttaxCategory(\n\t\t\t\t\"cac:ClassifiedTaxCategory\",\n\t\t\t\tsource.taxCategory ?? {},\n\t\t\t\t`lines[${source.id}].taxCategory`,\n\t\t\t),\n\t\t]),\n\t\t// BT-149's unit code must match the invoiced/credited quantity's\n\t\t// (PEPPOL-EN16931-R130).\n\t\tel(\"cac:Price\", null, [\n\t\t\tmoney(\"cbc:PriceAmount\", priceAmount, currency),\n\t\t\tsource.baseQuantity !== undefined\n\t\t\t\t? el(\"cbc:BaseQuantity\", { unitCode }, String(source.baseQuantity))\n\t\t\t\t: null,\n\t\t]),\n\t]);\n};\n\nconst attachmentReference = (attachment: UblAttachment): XmlElement =>\n\tel(\"cac:AdditionalDocumentReference\", null, [\n\t\tel(\n\t\t\t\"cbc:ID\",\n\t\t\tnull,\n\t\t\tattachment.id ?? attachment.filename ?? attachment.externalUri ?? \"\",\n\t\t),\n\t\tel(\"cac:Attachment\", null, [\n\t\t\tisExternalOnly(attachment)\n\t\t\t\t? el(\"cac:ExternalReference\", null, [\n\t\t\t\t\t\tel(\"cbc:URI\", null, attachment.externalUri ?? \"\"),\n\t\t\t\t\t])\n\t\t\t\t: el(\n\t\t\t\t\t\t\"cbc:EmbeddedDocumentBinaryObject\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmimeCode: attachment.mimeCode ?? \"\",\n\t\t\t\t\t\t\tfilename: attachment.filename ?? \"\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tattachment.base64Content ?? \"\",\n\t\t\t\t\t),\n\t\t]),\n\t]);\n\nconst billingReference = (reference: UblBillingReference): XmlElement | null => {\n\tif (reference.invoiceId === undefined) return null;\n\treturn el(\"cac:BillingReference\", null, [\n\t\tel(\"cac:InvoiceDocumentReference\", null, [\n\t\t\tel(\"cbc:ID\", null, reference.invoiceId),\n\t\t]),\n\t]);\n};\n\n/**\n * Serialize a {@link UblInvoice} into a Peppol BIS Billing 3.0 XML string.\n *\n * Emits the subset of the model a Peppol BIS Billing 3.0 document needs:\n * header (`customizationId`, `profileId` and `invoiceTypeCode` default to the\n * BIS values), note, buyer reference, invoice period, billing reference,\n * attachments, parties, payment terms, VAT breakdown, monetary totals and\n * lines with their price and classified VAT category. Payment means,\n * allowances/charges, delivery and the document references are not emitted.\n *\n * @throws {UblBuildError} when a field EN 16931 / Peppol BIS makes mandatory is\n * missing: document id, issue date, currency, seller and buyer name, an\n * endpoint without a scheme, at least one line, per line the quantity, unit\n * code, unit price, net amount and VAT category (id, plus the rate unless the\n * category is `O`), the total VAT amount, the four monetary totals, and for an\n * embedded attachment its filename, MIME code and content.\n */\nexport const serializeUblInvoice = (doc: UblInvoice): string => {\n\tvalidateInvoice(doc);\n\n\tconst isCreditNote = doc.documentType === \"CreditNote\";\n\tconst rootName = isCreditNote ? \"CreditNote\" : \"Invoice\";\n\tconst rootNamespace = isCreditNote ? NS_CREDIT_NOTE : NS_INVOICE;\n\tconst typeCodeElement = isCreditNote\n\t\t? el(\n\t\t\t\t\"cbc:CreditNoteTypeCode\",\n\t\t\t\tnull,\n\t\t\t\tdoc.invoiceTypeCode ?? CREDIT_NOTE_TYPE_CODE,\n\t\t\t)\n\t\t: el(\"cbc:InvoiceTypeCode\", null, doc.invoiceTypeCode ?? INVOICE_TYPE_CODE);\n\n\tconst children: (XmlElement | null | false)[] = [\n\t\tel(\"cbc:CustomizationID\", null, doc.customizationId ?? UBL_CUSTOMIZATION_ID),\n\t\tel(\"cbc:ProfileID\", null, doc.profileId ?? UBL_PROFILE_ID),\n\t\tel(\"cbc:ID\", null, doc.id),\n\t\tel(\"cbc:IssueDate\", null, doc.issueDate),\n\t\t// CreditNote has no DueDate element in the UBL sequence.\n\t\t!isCreditNote ? text(\"cbc:DueDate\", doc.dueDate) : null,\n\t\ttypeCodeElement,\n\t\ttext(\"cbc:Note\", doc.note),\n\t\tel(\"cbc:DocumentCurrencyCode\", null, doc.currency),\n\t\ttext(\"cbc:BuyerReference\", doc.buyerReference),\n\t\tinvoicePeriod(doc.invoicePeriod),\n\t\tdoc.billingReference ? billingReference(doc.billingReference) : null,\n\t\t...(doc.attachments ?? []).map(attachmentReference),\n\t\tel(\"cac:AccountingSupplierParty\", null, [\n\t\t\tparty(doc.seller, doc.seller.name ?? \"\"),\n\t\t]),\n\t\tel(\"cac:AccountingCustomerParty\", null, [\n\t\t\tparty(doc.buyer, doc.buyer.name ?? \"\"),\n\t\t]),\n\t\t// BT-20. In both the Invoice and CreditNote sequences PaymentTerms sits\n\t\t// after the parties (and PaymentMeans, which we do not emit) and before\n\t\t// TaxTotal.\n\t\tdoc.paymentTermsNote !== undefined\n\t\t\t? el(\"cac:PaymentTerms\", null, [el(\"cbc:Note\", null, doc.paymentTermsNote)])\n\t\t\t: null,\n\t\tel(\"cac:TaxTotal\", null, [\n\t\t\tmoney(\"cbc:TaxAmount\", doc.taxTotal.taxAmount ?? 0, doc.currency),\n\t\t\t...doc.taxTotal.subtotals.map((subtotal, index) =>\n\t\t\t\ttaxSubtotal(subtotal, doc.currency, index),\n\t\t\t),\n\t\t]),\n\t\tel(\"cac:LegalMonetaryTotal\", null, legalMonetaryTotalChildren(doc)),\n\t\t...doc.lines.map((source) => line(source, doc.currency, doc.documentType)),\n\t];\n\n\tconst root = el(\n\t\trootName,\n\t\t{\n\t\t\txmlns: rootNamespace,\n\t\t\t\"xmlns:cac\": NS_CAC,\n\t\t\t\"xmlns:cbc\": NS_CBC,\n\t\t},\n\t\tchildren.filter((child): child is XmlElement => Boolean(child)),\n\t);\n\n\treturn serializeDocument(root);\n};\n\n/** Alias of {@link serializeUblInvoice}, kept under the historical name. */\nexport const serializeUblDocument = serializeUblInvoice;\n","/** Trim a string; `undefined` when missing or blank. */\nexport const normalizeString = (\n\tvalue: string | null | undefined,\n): string | undefined => {\n\tif (typeof value !== \"string\") return undefined;\n\tconst normalized = value.trim();\n\treturn normalized.length > 0 ? normalized : undefined;\n};\n\n/** Drop `undefined`-valued keys so an absent field is an absent key. */\nexport const compact = <T extends object>(value: T): T =>\n\tObject.fromEntries(\n\t\tObject.entries(value).filter(([, entry]) => entry !== undefined),\n\t) as T;\n","import type { UblAddress } from \"../types\";\nimport { compact, normalizeString } from \"./utils\";\n\nconst normalizeCountryCode = (value: string | null | undefined): string | undefined => {\n\tconst trimmed = normalizeString(value);\n\tif (!trimmed) return undefined;\n\treturn trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : undefined;\n};\n\n/**\n * A free-form postal address as accepted by {@link normalizeAddress}.\n *\n * Both the Stripe shape (`line1`, `postal_code`, `country`, `state`) and the\n * legacy/internal shape (`street`, `zip_code`, `country_code`,\n * `country_subentity`) are accepted; when both keys are present the Stripe\n * one wins.\n */\nexport interface AddressInput {\n\tline1?: string | null;\n\tline2?: string | null;\n\tstreet?: string | null;\n\tcity?: string | null;\n\tpostal_code?: string | null;\n\tzip_code?: string | null;\n\tstate?: string | null;\n\tcountry_subentity?: string | null;\n\tcountry?: string | null;\n\tcountry_code?: string | null;\n}\n\n/**\n * Normalize a free-form address (Stripe shape, custom shape, or an internal\n * shape) into a {@link UblAddress}. An absent part is an absent key.\n *\n * Accepts both `line1`/`postal_code`/`country` (Stripe) and `street`/`zip_code`\n * (legacy/internal) keys. Falls back to `fallbackCountryCode` when the address\n * has no country, but never silently substitutes a caller's country — pass\n * `null` when \"no country\" is the right answer.\n */\nexport const normalizeAddress = (\n\taddress: AddressInput | null | undefined,\n\tfallbackCountryCode: string | null,\n\tfallbackLine?: string | null,\n): UblAddress => {\n\tconst record: AddressInput = address ?? {};\n\tconst countryCode =\n\t\tnormalizeCountryCode(normalizeString(record.country)) ??\n\t\tnormalizeCountryCode(normalizeString(record.country_code)) ??\n\t\tnormalizeCountryCode(fallbackCountryCode);\n\treturn compact({\n\t\tstreet:\n\t\t\tnormalizeString(record.line1) ??\n\t\t\tnormalizeString(record.street) ??\n\t\t\tnormalizeString(fallbackLine),\n\t\tadditionalStreet: normalizeString(record.line2),\n\t\tcity: normalizeString(record.city),\n\t\tpostalZone:\n\t\t\tnormalizeString(record.postal_code) ?? normalizeString(record.zip_code),\n\t\tcountrySubentity:\n\t\t\tnormalizeString(record.state) ?? normalizeString(record.country_subentity),\n\t\tcountryCode,\n\t});\n};\n","import { getPeppolIdentifierSchemes } from \"@financica/peppol/countries\";\nimport {\n\tcountryFromVatNumber,\n\tnormalizeParticipantValue,\n} from \"@financica/peppol/identifiers\";\nimport type { UblCompanyId, UblEndpoint } from \"../types\";\nimport { compact, normalizeString } from \"./utils\";\n\nconst normalizeBelgianCompanyNumber = (value: string | null | undefined) => {\n\tif (!value) return \"\";\n\t// EAS 0208 (BE:EN) is 10 bare digits, so the printed dots are decoration.\n\treturn normalizeParticipantValue(\"0208\", value).toUpperCase().replace(/^BE/, \"\");\n};\n\n/**\n * Strip whitespace/punctuation from a country-specific company number.\n * For Belgium, also strips an optional `BE` prefix.\n */\nexport const normalizeCompanyNumberForCountry = (\n\tcountryCode: string | null | undefined,\n\tcompanyNumber: string | null | undefined,\n) => {\n\tif (!companyNumber) return \"\";\n\tconst upper = countryCode?.trim().toUpperCase() ?? \"\";\n\tif (upper === \"BE\") return normalizeBelgianCompanyNumber(companyNumber);\n\treturn companyNumber.trim();\n};\n\n/**\n * Peppol/ISO 6523 ICD scheme for a legal registration number\n * (`cac:PartyLegalEntity/cbc:CompanyID/@schemeID`), e.g. BE → `0208`\n * (enterprise number), NL → `0106` (KvK), FR → `0002` (SIRENE). The table is\n * `@financica/peppol`'s country profiles.\n *\n * Falls back to inspecting the number's country prefix (e.g. `BE0793904121`).\n * Returns `undefined` when the scheme can't be determined, in which case the\n * CompanyID is emitted without a `schemeID` attribute.\n */\nexport const resolveCompanyIdScheme = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): string | undefined => {\n\tconst companyNumber = normalizeString(params.companyNumber);\n\tif (!companyNumber) return undefined;\n\n\tconst fromCountry =\n\t\tgetPeppolIdentifierSchemes(params.countryCode)?.companyIdentifierScheme ??\n\t\tundefined;\n\tif (fromCountry) return fromCountry;\n\n\t// Only sniffing the country prefix, e.g. `BE0793904121` → `BE`.\n\tconst prefix = companyNumber\n\t\t.replace(/[^A-Za-z]/g, \"\")\n\t\t.toUpperCase()\n\t\t.slice(0, 2);\n\treturn getPeppolIdentifierSchemes(prefix)?.companyIdentifierScheme ?? undefined;\n};\n\n/**\n * Build the `cac:PartyLegalEntity/cbc:CompanyID` value for a party, with the\n * country-appropriate ICD scheme when known. Returns `undefined` when there is no\n * company number.\n */\nexport const buildCompanyId = (params: {\n\tcountryCode: string | null;\n\tcompanyNumber: string | null;\n}): UblCompanyId | undefined => {\n\tconst normalized = normalizeString(\n\t\tnormalizeCompanyNumberForCountry(params.countryCode, params.companyNumber),\n\t);\n\tif (!normalized) return undefined;\n\treturn compact({\n\t\tvalue: normalized,\n\t\tscheme: resolveCompanyIdScheme({\n\t\t\tcountryCode: params.countryCode,\n\t\t\tcompanyNumber: normalized,\n\t\t}),\n\t});\n};\n\n/**\n * Resolve the Peppol participant identifier for a VAT number, deriving the EAS\n * scheme from the number's own country prefix (falling back to `countryCode`).\n *\n * `BE0206582284` → `{ scheme: \"9925\", value: \"BE0206582284\" }`\n *\n * The scheme comes from `@financica/peppol`'s country resolution, so countries\n * that route on their registry number alone (Norway, Denmark) yield `undefined`\n * here — their VAT number is not a Peppol participant identifier.\n *\n * The value keeps its country prefix, matching how participants register (the\n * Peppol directory lists this party as `9925:be0206582284`). Returns `undefined`\n * when the country has no VAT EAS scheme or the input is empty.\n */\nexport const resolveVatEndpoint = (params: {\n\tvatNumber: string | null | undefined;\n\tcountryCode?: string | null | undefined;\n}): UblEndpoint | undefined => {\n\tconst value = normalizeString(params.vatNumber);\n\tif (!value) return undefined;\n\n\tconst fromPrefix = countryFromVatNumber(value);\n\tconst scheme =\n\t\tgetPeppolIdentifierSchemes(fromPrefix)?.vatIdentifierScheme ??\n\t\tgetPeppolIdentifierSchemes(params.countryCode)?.vatIdentifierScheme;\n\tif (!scheme) return undefined;\n\n\t// Every scheme in the table is a VAT scheme, whose value carries no\n\t// separator, so the printed dots/spaces are dropped.\n\tconst cleaned = normalizeParticipantValue(scheme, value).toUpperCase();\n\tif (!cleaned) return undefined;\n\n\treturn { scheme, value: cleaned };\n};\n\n/**\n * Parse a Peppol participant identifier into a {@link UblEndpoint}.\n *\n * Accepts the canonical `scheme:value` form (e.g. `0208:0800279001`). Returns\n * `undefined` for values without an explicit scheme, since `cbc:EndpointID` requires\n * a `schemeID` and guessing one would mis-route the document.\n */\nexport const parsePeppolEndpoint = (\n\tpeppolId: string | null | undefined,\n): UblEndpoint | undefined => {\n\tconst normalized = normalizeString(peppolId);\n\tif (!normalized) return undefined;\n\tconst separatorIndex = normalized.indexOf(\":\");\n\tif (separatorIndex <= 0) return undefined;\n\tconst scheme = normalized.slice(0, separatorIndex).trim();\n\tconst value = normalized.slice(separatorIndex + 1).trim();\n\tif (!scheme || !value) return undefined;\n\treturn { scheme, value };\n};\n\nexport interface CustomerTaxIdentifiers {\n\tpeppolID: string | null;\n\tglnNumber: string | null;\n\ttaxNumber: string | null;\n\tvatNumber: string | null;\n}\n\n/**\n * One customer tax identifier as stored by Stripe (`customer_tax_ids[]`) or an\n * equivalent `{type, value}` pair. `type` is a Stripe tax-ID type such as\n * `eu_vat`, or a custom type such as `peppol_id`; blank entries are skipped.\n */\nexport interface CustomerTaxIdInput {\n\ttype: string | null | undefined;\n\tvalue: string | null | undefined;\n}\n\nconst normalizeIdentifierType = (value: string | undefined) =>\n\tvalue?.toLowerCase().replace(/[^a-z0-9]+/g, \"_\");\n\n/**\n * Pick the first usable Peppol identifier, GLN, VAT number, and tax number\n * from a Stripe-style `customer_tax_ids` array (`[{type, value}, …]`).\n *\n * Stripe stores VAT numbers under types like `eu_vat`, `gb_vat`, etc.\n * Peppol IDs are typically stored as a custom `peppol_id` type.\n */\nexport const extractCustomerTaxIdentifiers = (\n\ttaxIds: readonly CustomerTaxIdInput[] | null | undefined,\n): CustomerTaxIdentifiers => {\n\tlet peppolID: string | null = null;\n\tlet glnNumber: string | null = null;\n\tlet taxNumber: string | null = null;\n\tlet vatNumber: string | null = null;\n\n\tfor (const entry of taxIds ?? []) {\n\t\tconst type = normalizeIdentifierType(normalizeString(entry.type));\n\t\tconst value = normalizeString(entry.value);\n\t\tif (!type || !value) continue;\n\n\t\tif (!peppolID && type.includes(\"peppol\")) {\n\t\t\tpeppolID = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!glnNumber && type.includes(\"gln\")) {\n\t\t\tglnNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!vatNumber && type.includes(\"vat\")) {\n\t\t\tvatNumber = value;\n\t\t\tcontinue;\n\t\t}\n\t\t// Any other typed id (ca_gst_hst, au_abn, us_ein, ...) is a registration\n\t\t// number: it goes to BT-30, not BT-31.\n\t\tif (!taxNumber) taxNumber = value;\n\t}\n\n\treturn { peppolID, glnNumber, taxNumber, vatNumber };\n};\n\n/**\n * Build the fully-qualified Peppol participant identifiers (`scheme:value`) a\n * receiver lookup will accept, in priority order, de-duplicated.\n *\n * Stripe stores a customer's VAT number without a Peppol scheme (e.g.\n * `BE0206582284`), but a participant lookup needs the qualified identifier\n * (`9925:BE0206582284`). This attaches the right scheme:\n *\n * 1. an explicit Peppol ID (already `scheme:value`) — passed through as-is;\n * 2. a GLN under EAS `0088`;\n * 3. the VAT number under its country's VAT EAS scheme (see\n * {@link resolveVatEndpoint});\n * 4. for Belgium, the enterprise number (VAT digits without the `BE` prefix)\n * under EAS `0208` — many Belgian entities register only under that;\n * 5. a generic tax/registration number under its country's company-ID scheme.\n *\n * `countryCode` (the customer's country, when known) disambiguates schemes for\n * identifiers that don't carry a country prefix (GLN, plain tax numbers).\n */\nexport const listPeppolReceiverIdentifierCandidates = (\n\tcustomer: Partial<CustomerTaxIdentifiers>,\n\tcountryCode?: string | null,\n): string[] => {\n\tconst candidates: string[] = [];\n\tconst add = (id: { scheme?: string | undefined; value: string } | undefined) => {\n\t\tif (id?.scheme && id.value) candidates.push(`${id.scheme}:${id.value}`);\n\t};\n\n\t// 1. An explicit Peppol ID already carries its own scheme.\n\tconst peppol = normalizeString(customer.peppolID);\n\tif (peppol) candidates.push(peppol);\n\n\t// 2. GLN → EAS 0088 (Global Location Number).\n\tconst gln = normalizeString(customer.glnNumber);\n\tif (gln) add({ scheme: \"0088\", value: normalizeParticipantValue(\"0088\", gln) });\n\n\t// 3. VAT number → the country's VAT EAS scheme (e.g. BE → 9925).\n\tconst vat = resolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });\n\tadd(vat);\n\n\t// 4. Belgium also reaches parties by enterprise number under EAS 0208; it is\n\t// the VAT digits without the `BE` prefix, and some entities register only so.\n\tif (vat?.scheme === \"9925\") {\n\t\tadd(\n\t\t\tbuildCompanyId({\n\t\t\t\tcountryCode: \"BE\",\n\t\t\t\tcompanyNumber: customer.vatNumber ?? null,\n\t\t\t}),\n\t\t);\n\t}\n\n\t// 5. A generic tax/registration number → its country's company-ID scheme.\n\tconst tax = normalizeString(customer.taxNumber);\n\tif (tax)\n\t\tadd(buildCompanyId({ countryCode: countryCode ?? null, companyNumber: tax }));\n\n\treturn Array.from(new Set(candidates));\n};\n","import { type AddressInput, normalizeAddress } from \"./address\";\nimport { buildCompanyId, parsePeppolEndpoint, resolveVatEndpoint } from \"./identifiers\";\nimport type { UblAddress, UblEndpoint, UblParty } from \"../types\";\nimport { compact, normalizeString } from \"./utils\";\n\n/**\n * Supplier (seller) VAT status. Drives how zero-VAT lines are reported when the\n * seller does not charge VAT:\n *\n * - `subject` — subject to VAT (the normal case): line categories come from\n * the data.\n * - `not_subject` — not subject to VAT.\n * - `small_business` — small business / franchise exemption (e.g. Belgian\n * Article 56bis).\n *\n * For the last two, `coerceLinesForSupplierVatStatus` (tax-category.ts) turns\n * every line into a non-charging exempt category so no VAT is reported.\n * Providers that encode this numerically (Scrada: 1/2/3) map at their boundary.\n */\nexport type SupplierVatStatus = \"subject\" | \"not_subject\" | \"small_business\";\n\n/**\n * Caller-provided supplier data, normalized into a stable shape.\n *\n * Each consumer builds this from its own data store. Once a `UblSupplier`\n * exists, the party builder no longer needs to know where it came from.\n */\nexport interface UblSupplier {\n\t/** Display + legal name shown on the invoice. */\n\tname: string;\n\t/** ISO 3166-1 alpha-2 country code (e.g. `\"BE\"`). */\n\tcountryCode: string;\n\t/**\n\t * Free-form address. Stripe-style fields (`line1`, `postal_code`, `country`)\n\t * and legacy/internal fields (`street`, `zip_code`) are both accepted.\n\t */\n\taddress: AddressInput | null;\n\t/** Country-specific company/registration number (e.g. BE enterprise number). */\n\tcompanyNumber?: string | null;\n\t/** VAT number with country prefix (e.g. `\"BE0793904121\"`). */\n\tvatNumber?: string | null;\n\t/** Whether the supplier charges VAT. See {@link SupplierVatStatus}. */\n\tvatStatus: SupplierVatStatus;\n\t/** Peppol participant identifier in `scheme:value` form (e.g. `\"0208:0793904121\"`). */\n\tpeppolID?: string | null;\n}\n\n/** Convert a {@link UblSupplier} into the seller party (`cac:AccountingSupplierParty`). */\nexport const buildSupplierParty = (supplier: UblSupplier): UblParty => {\n\tconst address = normalizeAddress(supplier.address, supplier.countryCode);\n\treturn compact({\n\t\tendpoint: parsePeppolEndpoint(supplier.peppolID),\n\t\tname: supplier.name,\n\t\tregistrationName: supplier.name,\n\t\taddress,\n\t\tvatId: normalizeString(supplier.vatNumber),\n\t\tcompanyId: buildCompanyId({\n\t\t\tcountryCode: supplier.countryCode,\n\t\t\tcompanyNumber: supplier.companyNumber ?? null,\n\t\t}),\n\t});\n};\n\n/**\n * Caller-provided customer (buyer) data, normalized into a stable shape.\n *\n * Each consumer (the Stripe adapter, app-specific row builders) resolves its\n * own identifiers and address, then hands this generic shape to\n * {@link buildCustomerParty}, so the Peppol routing logic lives in one place.\n */\nexport interface UblCustomer {\n\t/** Display + legal name shown on the invoice. */\n\tname: string;\n\t/** Customer address, already normalized by the caller. */\n\taddress: UblAddress;\n\t/**\n\t * The customer's ISO 3166-1 alpha-2 country, used to resolve VAT/registration\n\t * schemes for identifiers that don't carry a country prefix. Pass the\n\t * customer's *own* country (never the supplier's) so the document is not\n\t * mis-routed; falls back to the address country when omitted.\n\t */\n\tcountryCode?: string | null;\n\t/** Peppol participant identifier in `scheme:value` form (e.g. `\"0208:0793904121\"`). */\n\tpeppolID?: string | null;\n\t/** Global Location Number (resolved under EAS `0088`). */\n\tglnNumber?: string | null;\n\t/** Generic tax/registration number (no VAT prefix). */\n\ttaxNumber?: string | null;\n\t/** VAT number with country prefix (e.g. `\"BE0793904121\"`). */\n\tvatNumber?: string | null;\n}\n\n/**\n * Convert a {@link UblCustomer} into the buyer party (`cac:AccountingCustomerParty`).\n *\n * The Peppol `EndpointID` (BT-49) — which routes the document — is resolved in\n * priority order: an explicit `endpointOverride` (e.g. a confirmed-registered\n * identifier), then an explicit Peppol ID, then a GLN (scheme `0088`), then the\n * VAT number mapped to its country's VAT EAS scheme (e.g. BE → `9925`). That\n * last step matters because most data stores hold a customer's VAT without a\n * scheme, so without it a VAT-only customer would have no endpoint and the\n * document would be unroutable.\n */\nexport const buildCustomerParty = (\n\tcustomer: UblCustomer,\n\tendpointOverride?: UblEndpoint | null,\n): UblParty => {\n\tconst countryCode =\n\t\tnormalizeString(customer.countryCode) ?? customer.address.countryCode ?? null;\n\tconst endpoint =\n\t\tendpointOverride ??\n\t\tparsePeppolEndpoint(customer.peppolID) ??\n\t\t(customer.glnNumber\n\t\t\t? { scheme: \"0088\", value: customer.glnNumber }\n\t\t\t: undefined) ??\n\t\tresolveVatEndpoint({ vatNumber: customer.vatNumber, countryCode });\n\n\treturn compact({\n\t\tendpoint,\n\t\tname: customer.name,\n\t\tregistrationName: customer.name,\n\t\taddress: customer.address,\n\t\tvatId: normalizeString(customer.vatNumber),\n\t\tcompanyId: buildCompanyId({\n\t\t\tcountryCode,\n\t\t\tcompanyNumber: customer.taxNumber ?? null,\n\t\t}),\n\t});\n};\n","import type { UblAttachment, UblInvoice } from \"../types\";\n\n/**\n * Build a UBL embedded-document attachment (BG-24) from raw bytes — e.g. the\n * rendered PDF of the invoice. Emitted as a `cac:AdditionalDocumentReference`\n * with an inline base64 `cbc:EmbeddedDocumentBinaryObject`.\n */\nexport const buildPdfAttachment = (params: {\n\tfilename: string;\n\tbytes: Uint8Array;\n\t/** Document reference ID (BT-122). Defaults to the filename. */\n\tid?: string;\n}): UblAttachment => ({\n\tid: params.id ?? params.filename,\n\tfilename: params.filename,\n\tmimeCode: \"application/pdf\",\n\tbase64Content: Buffer.from(params.bytes).toString(\"base64\"),\n});\n\n/**\n * Replace each attachment's base64 payload with `[omitted]` plus a length, so a\n * {@link UblInvoice} is safe to log or persist for audit.\n */\nexport const sanitizeUblDocumentForAudit = (doc: UblInvoice): UblInvoice => {\n\tif (!doc.attachments?.length) return doc;\n\treturn {\n\t\t...doc,\n\t\tattachments: doc.attachments.map((attachment) =>\n\t\t\tattachment.base64Content === undefined\n\t\t\t\t? attachment\n\t\t\t\t: {\n\t\t\t\t\t\t...attachment,\n\t\t\t\t\t\tbase64Content: `[omitted ${attachment.base64Content.length} chars]`,\n\t\t\t\t\t},\n\t\t),\n\t};\n};\n","/** Round a number to 2 decimal places (cents). */\nexport const roundCurrency = (value: number) =>\n\tMath.round((value + Number.EPSILON) * 100) / 100;\n\n/** Convert an integer cent amount into a 2-decimal currency value. */\nexport const centsToDecimal = (cents: number) => roundCurrency(cents / 100);\n\n/** The `cac:Price` pair for a line: the per-unit price and the optional BT-149. */\nexport interface UnitPrice {\n\t/** Net price of one unit (`UblLine.unitPrice`). */\n\tunitPrice: number;\n\t/**\n\t * `cbc:BaseQuantity` (BT-149) — set when the per-unit price is not exact in\n\t * cents; the serializer then emits `PriceAmount = unitPrice × baseQuantity`\n\t * (the line net). Omitted = 1.\n\t */\n\tbaseQuantity?: number | undefined;\n}\n\n/**\n * Derive the `cac:Price` for a line whose net total is authoritative.\n *\n * Peppol rule PEPPOL-EN16931-R120 checks\n * `quantity × (PriceAmount ÷ BaseQuantity)` against the line net amount within\n * a 0.02 tolerance. Naively rounding `net ÷ quantity` to cents breaks that\n * whenever the division doesn't land on a cent: 940.00 over 14 units gives\n * 67.142857…, which rounds to 67.14, and 14 × 67.14 = 939.96 — off by 0.04 and\n * rejected as a fatal validation error.\n *\n * So the cent-rounded unit price is only used when it reproduces the net\n * exactly. Otherwise the line is priced as a whole via BT-149: `unitPrice` is\n * the exact (unrounded) `net ÷ quantity` and `baseQuantity` = the quantity, so\n * the serializer writes `PriceAmount` = the net and `BaseQuantity` = the\n * quantity, which is exact at any magnitude instead of merely within tolerance\n * — the residual of a rounded unit price grows with quantity and would\n * eventually breach 0.02 at any fixed precision.\n */\nexport const deriveUnitPrice = (netTotal: number, quantity: number): UnitPrice => {\n\t// A zero or fractional-to-zero quantity still has to price something; BT-149\n\t// must be a positive number (PEPPOL-EN16931-R121), so floor the divisor at 1.\n\tconst units = quantity > 0 ? quantity : 1;\n\tconst perUnit = roundCurrency(netTotal / units);\n\tif (roundCurrency(perUnit * units) === roundCurrency(netTotal)) {\n\t\treturn { unitPrice: perUnit };\n\t}\n\treturn { unitPrice: roundCurrency(netTotal) / units, baseQuantity: units };\n};\n","import type { SupplierVatStatus } from \"./party\";\nimport type { UblLine, UblTaxCategory } from \"../types\";\nimport { normalizeString } from \"./utils\";\n\n/**\n * Stripe Tax `taxability_reason` values that map to a VAT-exempt UBL category\n * (`E`). Reverse charge is handled separately (category `AE`).\n */\nexport const EXEMPT_TAXABILITY_REASONS = new Set([\n\t\"customer_exempt\",\n\t\"product_exempt\",\n\t\"not_subject_to_tax\",\n\t\"not_collecting\",\n\t\"not_supported\",\n\t\"portion_product_exempt\",\n]);\n\n/** Human-readable EN 16931 exemption reasons (BR-E-10 / BR-AE-10 / …). */\nconst EXEMPTION_REASON_TEXT: Record<string, string> = {\n\treverse_charge: \"Reverse charge\",\n\tintra_community: \"Intra-community supply\",\n\texport: \"Export outside the EU\",\n\tcustomer_exempt: \"Exempt based on customer status\",\n\tproduct_exempt: \"Exempt based on the supplied goods or services\",\n\tportion_product_exempt: \"Exempt based on the supplied goods or services\",\n\tnot_subject_to_tax: \"Not subject to VAT\",\n\tnot_collecting: \"VAT not collected\",\n\tnot_supported: \"VAT not applicable\",\n};\n\nexport interface TaxAmountInfo {\n\tamount: number;\n\ttaxability_reason?: string | null;\n\ttax_rate_percentage?: number | null;\n}\n\nconst normalizeTaxCategoryId = (value: string | null | undefined): string | undefined =>\n\tnormalizeString(value)?.toUpperCase();\n\n/**\n * Map an explicit UBL category hint, a Stripe `taxability_reason`, and/or a\n * numeric rate into a {@link UblTaxCategory}.\n *\n * - Reverse charge → `AE` (0%, with exemption reason)\n * - Intra-community supply → `K` (0%, with exemption reason)\n * - Export outside the EU → `G` (0%, with exemption reason)\n * - Any other exempt reason → `E` (0%, with exemption reason)\n * - Category `Z` / rate ≤ 0 → `Z` (zero-rated, 0%)\n * - Otherwise → `S` (standard, the line's rate)\n */\nexport const taxCategoryFromReasonOrRate = (params: {\n\ttaxCategoryId?: string | null;\n\ttaxabilityReason: string | null;\n\trate: number;\n}): UblTaxCategory => {\n\tconst categoryHint = normalizeTaxCategoryId(params.taxCategoryId);\n\tconst reason = params.taxabilityReason;\n\n\tif (categoryHint === \"AE\" || reason === \"reverse_charge\") {\n\t\treturn {\n\t\t\tid: \"AE\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT[\"reverse_charge\"],\n\t\t};\n\t}\n\tif (categoryHint === \"K\" || reason === \"intra_community\") {\n\t\treturn {\n\t\t\tid: \"K\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT[\"intra_community\"],\n\t\t};\n\t}\n\tif (categoryHint === \"G\" || reason === \"export\") {\n\t\treturn {\n\t\t\tid: \"G\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason: EXEMPTION_REASON_TEXT[\"export\"],\n\t\t};\n\t}\n\tif (categoryHint === \"E\" || (reason && EXEMPT_TAXABILITY_REASONS.has(reason))) {\n\t\treturn {\n\t\t\tid: \"E\",\n\t\t\tpercent: 0,\n\t\t\texemptionReason:\n\t\t\t\t(reason ? EXEMPTION_REASON_TEXT[reason] : undefined) ??\n\t\t\t\t\"Exempt from VAT\",\n\t\t};\n\t}\n\tif (categoryHint === \"Z\" || reason === \"zero_rated\" || params.rate <= 0) {\n\t\treturn { id: \"Z\", percent: 0 };\n\t}\n\treturn { id: \"S\", percent: params.rate };\n};\n\n/**\n * Resolve a {@link UblTaxCategory} from a line's Stripe tax info.\n *\n * Exempt / reverse-charge / zero-rated reasons take precedence over the rate;\n * otherwise the rate decides standard (`S`) vs zero-rated (`Z`).\n */\nexport const resolveTaxCategoryFromTaxAmounts = (\n\ttaxAmounts: TaxAmountInfo[],\n\trate: number,\n): UblTaxCategory => {\n\tfor (const ta of taxAmounts) {\n\t\tif (!ta.taxability_reason) continue;\n\t\tif (\n\t\t\tta.taxability_reason === \"reverse_charge\" ||\n\t\t\tta.taxability_reason === \"zero_rated\" ||\n\t\t\tEXEMPT_TAXABILITY_REASONS.has(ta.taxability_reason)\n\t\t) {\n\t\t\treturn taxCategoryFromReasonOrRate({\n\t\t\t\ttaxabilityReason: ta.taxability_reason,\n\t\t\t\trate,\n\t\t\t});\n\t\t}\n\t}\n\treturn taxCategoryFromReasonOrRate({ taxabilityReason: null, rate });\n};\n\n/**\n * BT-120 text for a small-business/franchise exemption, by supplier country.\n * Countries without a specific legal reference fall back to the generic text.\n */\nconst SMALL_BUSINESS_EXEMPTION_REASON_BY_COUNTRY: Record<string, string> = {\n\tBE: \"Exempt — small business scheme (Article 56bis)\",\n};\nconst SMALL_BUSINESS_EXEMPTION_REASON = \"Exempt — small business scheme\";\nconst NOT_SUBJECT_EXEMPTION_REASON = \"Seller not subject to VAT\";\n\n/**\n * When the supplier does not charge VAT, coerce every line to a non-charging\n * exempt category (`E`, 0%) with the appropriate BT-120 reason, so the document\n * reports no VAT regardless of what the upstream line tax data implied. Lines\n * are returned untouched for a `subject` supplier.\n */\nexport const coerceLinesForSupplierVatStatus = (\n\tlines: UblLine[],\n\tvatStatus: SupplierVatStatus,\n\tsupplierCountryCode?: string | null,\n): UblLine[] => {\n\tif (vatStatus === \"subject\") return lines;\n\tconst country = normalizeString(supplierCountryCode)?.toUpperCase();\n\tconst exemptionReason =\n\t\tvatStatus === \"small_business\"\n\t\t\t? ((country && SMALL_BUSINESS_EXEMPTION_REASON_BY_COUNTRY[country]) ??\n\t\t\t\tSMALL_BUSINESS_EXEMPTION_REASON)\n\t\t\t: NOT_SUBJECT_EXEMPTION_REASON;\n\treturn lines.map((line) => ({\n\t\t...line,\n\t\ttaxCategory: { id: \"E\", percent: 0, exemptionReason },\n\t}));\n};\n","import { UblBuildError } from \"../errors\";\nimport type {\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n\tUblTaxTotal,\n} from \"../types\";\nimport { deriveUnitPrice, roundCurrency } from \"./numeric\";\nimport { compact } from \"./utils\";\n\nconst lineNet = (line: UblLine): number => line.lineExtensionAmount ?? 0;\n\n/**\n * Adjust the largest line's net amount so the line nets sum to the\n * authoritative document total (e.g. Stripe's `invoice.total_excluding_tax`).\n *\n * Reconciling at the *line* level — rather than directly on the VAT breakdown —\n * keeps the document consistent bottom-up: the VAT category taxable amounts\n * (BR-S-08) and the line-extension total (BR-CO-13) both still derive from the\n * lines. Discrepancies here are sub-cent rounding or a distributed invoice-level\n * coupon; larger ones indicate a real upstream data problem.\n */\nexport const reconcileLinesToExclTotal = (\n\tlines: UblLine[],\n\tauthoritativeTotalExclVat: number,\n): UblLine[] => {\n\tif (lines.length === 0) return lines;\n\tconst computed = roundCurrency(lines.reduce((sum, line) => sum + lineNet(line), 0));\n\tconst diff = roundCurrency(authoritativeTotalExclVat - computed);\n\tif (diff === 0) return lines;\n\n\tconst largestIdx = lines.reduce(\n\t\t(maxIdx, line, idx, arr) =>\n\t\t\tlineNet(line) > lineNet(arr[maxIdx] ?? line) ? idx : maxIdx,\n\t\t0,\n\t);\n\n\treturn lines.map((line, idx) => {\n\t\tif (idx !== largestIdx) return line;\n\t\tconst adjusted = roundCurrency(lineNet(line) + diff);\n\t\t// Re-derive the price from the adjusted net through the shared helper —\n\t\t// nudging the net without re-deriving BT-146/BT-149 to match is exactly\n\t\t// what PEPPOL-EN16931-R120 rejects. Assign `baseQuantity` unconditionally\n\t\t// so a line that no longer needs one doesn't keep a stale value.\n\t\tconst { unitPrice, baseQuantity } = deriveUnitPrice(\n\t\t\tadjusted,\n\t\t\tline.quantity ?? 0,\n\t\t);\n\t\treturn compact({\n\t\t\t...line,\n\t\t\tlineExtensionAmount: adjusted,\n\t\t\tunitPrice,\n\t\t\tbaseQuantity,\n\t\t});\n\t});\n};\n\nconst categoryKey = (category: UblTaxCategory): string =>\n\t`${category.id ?? \"\"}:${category.percent ?? \"\"}`;\n\nexport interface BuildTaxTotalsResult {\n\ttaxTotal: UblTaxTotal;\n\tmonetaryTotal: UblMonetaryTotal;\n}\n\nexport interface BuildTaxTotalsOptions {\n\t/**\n\t * BT-113 — amount already paid, **gross (VAT-inclusive)**. Subtracted from\n\t * BT-112 to derive the outstanding `payableAmount` (BR-CO-16). Pass the full\n\t * gross total for a settled document so it reports a payable amount of 0.\n\t */\n\tprepaidAmount?: number;\n\t/** BT-114 — rounding applied to the payable amount. */\n\tpayableRoundingAmount?: number;\n}\n\n/**\n * Group lines by `(category, percent)` into a VAT breakdown and compute the\n * document monetary totals.\n *\n * Each VAT category's tax amount is **derived** as `taxable × percent / 100`,\n * rounded to two decimals (EN 16931 BR-CO-17), rather than summed from the\n * upstream per-line tax cents. This guarantees the breakdown is internally\n * consistent and passes validation; it can differ by a cent from the figure a\n * payment processor reported, which is an unavoidable artifact of representing\n * a cents-rounded system as a rate-based VAT breakdown.\n *\n * `payableAmount` is derived per BR-CO-16 (`BT-112 − BT-113 + BT-114`) so the\n * invariant holds by construction. The result is *not* clamped: a prepayment\n * exceeding the total yields a negative payable amount, surfacing the upstream\n * overpayment rather than hiding it.\n *\n * @throws {UblBuildError} for a line without a `taxCategory` — there is no\n * VAT breakdown to put it in.\n */\nexport const buildTaxTotals = (\n\tlines: UblLine[],\n\toptions?: BuildTaxTotalsOptions,\n): BuildTaxTotalsResult => {\n\tconst groups = new Map<\n\t\tstring,\n\t\t{ category: UblTaxCategory; taxableAmount: number }\n\t>();\n\n\tfor (const line of lines) {\n\t\tif (!line.taxCategory) {\n\t\t\tthrow new UblBuildError(\n\t\t\t\t`Line ${line.id} has no taxCategory (BT-151); cannot build the VAT breakdown`,\n\t\t\t);\n\t\t}\n\t\tconst key = categoryKey(line.taxCategory);\n\t\tconst current = groups.get(key) ?? {\n\t\t\tcategory: line.taxCategory,\n\t\t\ttaxableAmount: 0,\n\t\t};\n\t\tcurrent.taxableAmount = roundCurrency(current.taxableAmount + lineNet(line));\n\t\tgroups.set(key, current);\n\t}\n\n\tconst subtotals: UblTaxSubtotal[] = Array.from(groups.values()).map((group) => ({\n\t\ttaxableAmount: group.taxableAmount,\n\t\ttaxAmount: roundCurrency(\n\t\t\t(group.taxableAmount * (group.category.percent ?? 0)) / 100,\n\t\t),\n\t\tcategory: group.category,\n\t}));\n\n\tconst lineExtensionAmount = roundCurrency(\n\t\tlines.reduce((sum, line) => sum + lineNet(line), 0),\n\t);\n\tconst taxAmount = roundCurrency(\n\t\tsubtotals.reduce((sum, subtotal) => sum + (subtotal.taxAmount ?? 0), 0),\n\t);\n\tconst taxInclusiveAmount = roundCurrency(lineExtensionAmount + taxAmount);\n\n\tconst prepaidAmount = roundCurrency(options?.prepaidAmount ?? 0);\n\tconst payableRoundingAmount = roundCurrency(options?.payableRoundingAmount ?? 0);\n\tconst payableAmount = roundCurrency(\n\t\ttaxInclusiveAmount - prepaidAmount + payableRoundingAmount,\n\t);\n\n\treturn {\n\t\ttaxTotal: { taxAmount, subtotals },\n\t\tmonetaryTotal: {\n\t\t\tlineExtensionAmount,\n\t\t\ttaxExclusiveAmount: lineExtensionAmount,\n\t\t\ttaxInclusiveAmount,\n\t\t\t...(prepaidAmount ? { prepaidAmount } : {}),\n\t\t\t...(payableRoundingAmount ? { payableRoundingAmount } : {}),\n\t\t\tpayableAmount,\n\t\t},\n\t};\n};\n"],"mappings":";;;;;;AAGA,MAAa,uBACZ;;AAGD,MAAa,iBAAiB;;AAG9B,MAAa,oBAAoB;;AAEjC,MAAa,wBAAwB;;AAGrC,MAAa,oBAAoB;;AAGjC,MAAa,oBAAoB;;AAGjC,MAAa,uBAAuB;AAEpC,MAAa,aAAa;AAC1B,MAAa,iBACZ;AACD,MAAa,SACZ;AACD,MAAa,SACZ;;;;;;;;;;ACCD,MAAa,MACZ,MACA,OACA,YACgB;CAChB,IAAI,MAAM,QAAQ,OAAO,GACxB,OAAO;EACN;EACA,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;EACzB,UAAU,QAAQ,QAAQ,MAAuB,QAAQ,CAAC,CAAC;CAC5D;CAED,OAAO;EACN;EACA,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;EACzB,GAAI,YAAY,KAAA,IAAY,EAAE,MAAM,QAAQ,IAAI,CAAC;CAClD;AACD;AAEA,MAAM,cAAc,UACnB,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,MAAM,CAAC,CAAC,QAAQ,MAAM,MAAM;AAExE,MAAM,cAAc,UAA0B,WAAW,KAAK,CAAC,CAAC,QAAQ,MAAM,QAAQ;AAEtF,MAAM,kBAAkB,UAAwC;CAC/D,IAAI,CAAC,OAAO,OAAO;CACnB,OAAO,OAAO,QAAQ,KAAK,CAAC,CAC1B,QAAQ,GAAG,WAAW,UAAU,QAAQ,UAAU,KAAA,CAAS,CAAC,CAC5D,KAAK,CAAC,KAAK,WAAW,IAAI,IAAI,IAAI,WAAW,OAAO,KAAK,CAAC,EAAE,EAAE,CAAC,CAC/D,KAAK,EAAE;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gB,cACrB,qBAAqB,gBAAgB,qBACtC;CAEA,OAAO;EACN,UAAU;GAAE;GAAW;EAAU;EACjC,eAAe;GACd;GACA,oBAAoB;GACpB;GACA,GAAI,gBAAgB,EAAE,cAAc,IAAI,CAAC;GACzC,GAAI,wBAAwB,EAAE,sBAAsB,IAAI,CAAC;GACzD;EACD;CACD;AACD"}
@@ -0,0 +1,33 @@
1
+ //#region src/errors.ts
2
+ /**
3
+ * Thrown by the parse side of this package when input is broken: malformed
4
+ * XML, or a UBL document missing an element EN 16931 makes mandatory. A parser
5
+ * returns `null` instead when the input is well-formed but not the document
6
+ * type it parses.
7
+ */
8
+ var UblParseError = class extends Error {
9
+ cause;
10
+ constructor(message, options) {
11
+ super(message);
12
+ this.name = "UblParseError";
13
+ if (options && "cause" in options) this.cause = options.cause;
14
+ }
15
+ };
16
+ /**
17
+ * Thrown by the build side when a model cannot be serialized: a field EN 16931
18
+ * / Peppol BIS Billing 3.0 makes mandatory on the wire is missing, or a build
19
+ * helper is handed input it cannot turn into one. The message names the BT /
20
+ * model field.
21
+ */
22
+ var UblBuildError = class extends Error {
23
+ cause;
24
+ constructor(message, options) {
25
+ super(message);
26
+ this.name = "UblBuildError";
27
+ if (options && "cause" in options) this.cause = options.cause;
28
+ }
29
+ };
30
+ //#endregion
31
+ export { UblParseError as n, UblBuildError as t };
32
+
33
+ //# sourceMappingURL=errors-C9YYJ1xR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-C9YYJ1xR.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Thrown by the parse side of this package when input is broken: malformed\n * XML, or a UBL document missing an element EN 16931 makes mandatory. A parser\n * returns `null` instead when the input is well-formed but not the document\n * type it parses.\n */\nexport class UblParseError extends Error {\n\toverride readonly cause?: unknown;\n\n\tconstructor(message: string, options?: { cause?: unknown }) {\n\t\tsuper(message);\n\t\tthis.name = \"UblParseError\";\n\t\tif (options && \"cause\" in options) this.cause = options.cause;\n\t}\n}\n\n/**\n * Thrown by the build side when a model cannot be serialized: a field EN 16931\n * / Peppol BIS Billing 3.0 makes mandatory on the wire is missing, or a build\n * helper is handed input it cannot turn into one. The message names the BT /\n * model field.\n */\nexport class UblBuildError extends Error {\n\toverride readonly cause?: unknown;\n\n\tconstructor(message: string, options?: { cause?: unknown }) {\n\t\tsuper(message);\n\t\tthis.name = \"UblBuildError\";\n\t\tif (options && \"cause\" in options) this.cause = options.cause;\n\t}\n}\n"],"mappings":";;;;;;;AAMA,IAAa,gBAAb,cAAmC,MAAM;CACxC;CAEA,YAAY,SAAiB,SAA+B;EAC3D,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,IAAI,WAAW,WAAW,SAAS,KAAK,QAAQ,QAAQ;CACzD;AACD;;;;;;;AAQA,IAAa,gBAAb,cAAmC,MAAM;CACxC;CAEA,YAAY,SAAiB,SAA+B;EAC3D,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,IAAI,WAAW,WAAW,SAAS,KAAK,QAAQ,QAAQ;CACzD;AACD"}