@financica/ubl 0.18.1 → 0.19.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.
package/dist/index.js CHANGED
@@ -512,21 +512,51 @@ function omitUndefined(value) {
512
512
  }
513
513
  const INVOICE_NS = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2";
514
514
  const CREDIT_NOTE_NS = "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2";
515
+ const SBDH_NS = "http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader";
516
+ const ublDocumentType = (el) => {
517
+ if (el.localName === "Invoice" && el.namespaceURI === INVOICE_NS) return "Invoice";
518
+ if (el.localName === "CreditNote" && el.namespaceURI === CREDIT_NOTE_NS) return "CreditNote";
519
+ return null;
520
+ };
515
521
  /**
516
- * Parse a UBL 2.1 Invoice or CreditNote.
522
+ * The UBL document element: the root itself, or, when the root is a Peppol
523
+ * `StandardBusinessDocument` envelope (as an access point delivers it), its
524
+ * Invoice/CreditNote child.
525
+ */
526
+ const findUblRoot = (root) => {
527
+ const rootType = ublDocumentType(root);
528
+ if (rootType) return {
529
+ root,
530
+ documentType: rootType
531
+ };
532
+ if (root.localName !== "StandardBusinessDocument" || root.namespaceURI !== SBDH_NS) return null;
533
+ for (let i = 0; i < root.childNodes.length; i++) {
534
+ const child = root.childNodes[i];
535
+ if (!child || child.nodeType !== 1) continue;
536
+ const el = child;
537
+ const documentType = ublDocumentType(el);
538
+ if (documentType) return {
539
+ root: el,
540
+ documentType
541
+ };
542
+ }
543
+ return null;
544
+ };
545
+ /**
546
+ * Parse a UBL 2.1 Invoice or CreditNote, bare or wrapped in a Peppol
547
+ * `StandardBusinessDocument` envelope.
517
548
  *
518
- * Returns `null` when the XML is well-formed but its root is not a UBL
519
- * `Invoice`/`CreditNote`. Throws {@link UblParseError} when the XML is
520
- * malformed or the document lacks an element EN 16931 makes mandatory
521
- * (document id, issue date, currency, line id).
549
+ * Returns `null` when the XML is well-formed but neither its root nor the
550
+ * envelope's payload is a UBL `Invoice`/`CreditNote`. Throws
551
+ * {@link UblParseError} when the XML is malformed or the document lacks an
552
+ * element EN 16931 makes mandatory (document id, issue date, currency, line id).
522
553
  */
523
554
  function parseUblInvoice(xml) {
524
- const root = parseXmlDocument(xml).documentElement;
525
- if (!root) return null;
526
- let documentType;
527
- if (root.localName === "Invoice" && root.namespaceURI === INVOICE_NS) documentType = "Invoice";
528
- else if (root.localName === "CreditNote" && root.namespaceURI === CREDIT_NOTE_NS) documentType = "CreditNote";
529
- else return null;
555
+ const doc = parseXmlDocument(xml);
556
+ if (!doc.documentElement) return null;
557
+ const found = findUblRoot(doc.documentElement);
558
+ if (!found) return null;
559
+ const { root, documentType } = found;
530
560
  const isCreditNote = documentType === "CreditNote";
531
561
  const id = requiredCbcText(root, "ID", "document identifier");
532
562
  const issueDate = requiredCbcText(root, "IssueDate", "issue date");
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["XmlDomParser","trimmed","cbcText","cacElement","cbcDirectText"],"sources":["../src/xml-dom.ts","../src/parser.ts","../src/attachments.ts","../src/mlr.ts","../src/normalize.ts"],"sourcesContent":["import { type Document, DOMParser as XmlDomParser } from \"@xmldom/xmldom\";\nimport { UblParseError } from \"./errors.js\";\n\nexport const CBC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\nexport const CAC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\n\n/**\n * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.\n * @xmldom/xmldom resolves external entities by default, so we remove DOCTYPE\n * blocks (including inline DTD subsets) before parsing.\n */\nexport const stripDoctype = (xml: string): string =>\n\txml.replace(/<!DOCTYPE\\s[^>[]*(?:\\[[^\\]]*\\])?>/gi, \"\");\n\n/**\n * Parse XML into a DOM, preferring the host's `DOMParser` (browsers) and\n * falling back to @xmldom/xmldom. Throws {@link UblParseError} when the XML\n * is malformed.\n */\nexport const parseXmlDocument = (xml: string): Document => {\n\tconst safeXml = stripDoctype(xml);\n\tconst BrowserDomParser = (globalThis as { DOMParser?: typeof XmlDomParser })\n\t\t.DOMParser;\n\tconst parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();\n\tlet doc: Document;\n\ttry {\n\t\tdoc = parser.parseFromString(safeXml, \"text/xml\");\n\t} catch (cause) {\n\t\tthrow new UblParseError(\"Malformed XML\", { cause });\n\t}\n\tif (doc.getElementsByTagName(\"parsererror\").length > 0 || !doc.documentElement) {\n\t\tthrow new UblParseError(\"Malformed XML\");\n\t}\n\treturn doc;\n};\n","import type { Element } from \"@xmldom/xmldom\";\nimport type {\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblBillingReference,\n\tUblCommodityClassification,\n\tUblContact,\n\tUblDelivery,\n\tUblDocumentReference,\n\tUblInvoice,\n\tUblInvoicePeriod,\n\tUblItemProperty,\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblParty,\n\tUblPartyIdentification,\n\tUblPaymentMeans,\n\tUblSchemedId,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n\tUblTaxTotal,\n} from \"./types.js\";\nimport { UblParseError } from \"./errors.js\";\nimport { CAC_NS, CBC_NS, parseXmlDocument } from \"./xml-dom.js\";\n\n// --- DOM helpers ---\n\nconst trimmed = (value: string | null | undefined): string | undefined => {\n\tconst text = value?.trim();\n\treturn text ? text : undefined;\n};\n\n/** First descendant CBC element's trimmed text; absent or blank is `undefined`. */\nfunction cbcText(parent: Element, tag: string): string | undefined {\n\treturn trimmed(parent.getElementsByTagNameNS(CBC_NS, tag)[0]?.textContent);\n}\n\n/** Like {@link cbcText} but throws: the element is mandatory in EN 16931. */\nfunction requiredCbcText(parent: Element, tag: string, what: string): string {\n\tconst value = cbcText(parent, tag);\n\tif (value === undefined) throw new UblParseError(`Missing ${what} (cbc:${tag})`);\n\treturn value;\n}\n\nconst toNumber = (value: string | undefined): number | undefined => {\n\tif (value === undefined) return undefined;\n\tconst parsed = Number.parseFloat(value);\n\treturn Number.isNaN(parsed) ? undefined : parsed;\n};\n\nfunction cacElement(parent: Element, tag: string): Element | null {\n\treturn parent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;\n}\n\nfunction cacElements(parent: Element, tag: string): Element[] {\n\treturn Array.from(parent.getElementsByTagNameNS(CAC_NS, tag));\n}\n\n/** First descendant CBC element as a number; absent or non-numeric is `undefined`. */\nfunction cbcNumber(parent: Element, tag: string): number | undefined {\n\treturn toNumber(cbcText(parent, tag));\n}\n\nfunction childElementsByTagNs(\n\tparent: Element,\n\tnamespace: string,\n\ttag: string,\n): Element[] {\n\tconst elements: Element[] = [];\n\tfor (let i = 0; i < parent.childNodes.length; i++) {\n\t\tconst node = parent.childNodes[i];\n\t\tif (!node || node.nodeType !== 1) continue;\n\t\tconst element = node as Element;\n\t\tif (element.namespaceURI === namespace && element.localName === tag) {\n\t\t\telements.push(element);\n\t\t}\n\t}\n\treturn elements;\n}\n\nfunction cbcDirectText(parent: Element, tag: string): string | undefined {\n\treturn trimmed(childElementsByTagNs(parent, CBC_NS, tag)[0]?.textContent);\n}\n\nfunction cbcDirectNumber(parent: Element, tag: string): number | undefined {\n\treturn toNumber(cbcDirectText(parent, tag));\n}\n\nconst attribute = (el: Element | null | undefined, name: string): string | undefined =>\n\ttrimmed(el?.getAttribute(name));\n\n/** A direct `cbc:<tag>` child with its `@schemeID`. */\nfunction cbcDirectSchemedId(parent: Element, tag: string): UblSchemedId | undefined {\n\tconst element = childElementsByTagNs(parent, CBC_NS, tag)[0];\n\tconst value = trimmed(element?.textContent);\n\treturn value !== undefined\n\t\t? { value, scheme: attribute(element, \"schemeID\") }\n\t\t: undefined;\n}\n\nfunction cacDirectElement(parent: Element, tag: string): Element | null {\n\treturn childElementsByTagNs(parent, CAC_NS, tag)[0] ?? null;\n}\n\nfunction cacDirectElements(parent: Element, tag: string): Element[] {\n\treturn childElementsByTagNs(parent, CAC_NS, tag);\n}\n\n// --- Section parsers ---\n\nfunction parseAddressFromElement(address: Element | null): UblAddress | undefined {\n\tif (!address) return undefined;\n\tconst country = cacElement(address, \"Country\");\n\treturn {\n\t\tstreet: cbcText(address, \"StreetName\"),\n\t\tadditionalStreet: cbcText(address, \"AdditionalStreetName\"),\n\t\tcity: cbcText(address, \"CityName\"),\n\t\tpostalZone: cbcText(address, \"PostalZone\"),\n\t\tcountrySubentity: cbcText(address, \"CountrySubentity\"),\n\t\tcountryCode: country ? cbcText(country, \"IdentificationCode\") : undefined,\n\t};\n}\n\nfunction parseAddress(party: Element): UblAddress | undefined {\n\tconst postal = cacElement(party, \"PostalAddress\");\n\treturn parseAddressFromElement(postal);\n}\n\nfunction parseTaxSchemeId(parent: Element | null): string | undefined {\n\tif (!parent) return undefined;\n\tconst taxScheme = cacElement(parent, \"TaxScheme\");\n\tif (!taxScheme) return undefined;\n\treturn cbcText(taxScheme, \"ID\");\n}\n\nfunction parseContact(party: Element): UblContact | undefined {\n\tconst contact = cacElement(party, \"Contact\");\n\tif (!contact) return undefined;\n\tconst name = cbcText(contact, \"Name\");\n\tconst phone = cbcText(contact, \"Telephone\");\n\tconst email = cbcText(contact, \"ElectronicMail\");\n\tif (!name && !phone && !email) return undefined;\n\treturn { name, phone, email };\n}\n\nfunction parsePartyIdentifications(party: Element): UblPartyIdentification[] {\n\tconst ids = cacElements(party, \"PartyIdentification\");\n\tconst result: UblPartyIdentification[] = [];\n\tfor (const idEl of ids) {\n\t\tconst idValue = cbcText(idEl, \"ID\");\n\t\tif (!idValue) continue;\n\t\tresult.push({\n\t\t\tid: idValue,\n\t\t\tschemeId: attribute(\n\t\t\t\tidEl.getElementsByTagNameNS(CBC_NS, \"ID\")[0],\n\t\t\t\t\"schemeID\",\n\t\t\t),\n\t\t});\n\t}\n\treturn result;\n}\n\nfunction parseParty(root: Element, role: string): UblParty {\n\tconst wrapper = cacDirectElement(root, role);\n\tconst party = wrapper ? cacElement(wrapper, \"Party\") : null;\n\treturn party ? parsePartyElement(party) : {};\n}\n\n/**\n * `cac:PayeeParty` (BG-10) and `cac:TaxRepresentativeParty` (BG-11) carry the\n * party children directly, without a `cac:Party` wrapper.\n */\nfunction parseUnwrappedParty(root: Element, tag: string): UblParty | undefined {\n\tconst party = cacDirectElement(root, tag);\n\tif (!party) return undefined;\n\tconst parsed = parsePartyElement(party);\n\treturn Object.values(parsed).some((value) => value !== undefined)\n\t\t? parsed\n\t\t: undefined;\n}\n\nfunction parsePartyElement(party: Element): UblParty {\n\tconst partyName = cacElement(party, \"PartyName\");\n\tconst legalEntity = cacElement(party, \"PartyLegalEntity\");\n\tconst taxScheme = cacElement(party, \"PartyTaxScheme\");\n\tconst partyId = cacElement(party, \"PartyIdentification\");\n\tconst endpointEl = party.getElementsByTagNameNS(CBC_NS, \"EndpointID\")[0];\n\tconst partyIdentifications = parsePartyIdentifications(party);\n\tconst companyIdEl = legalEntity\n\t\t? legalEntity.getElementsByTagNameNS(CBC_NS, \"CompanyID\")[0]\n\t\t: null;\n\n\tconst endpointValue = trimmed(endpointEl?.textContent);\n\tconst companyIdValue = companyIdEl\n\t\t? trimmed(companyIdEl.textContent)\n\t\t: partyId\n\t\t\t? cbcText(partyId, \"ID\")\n\t\t\t: undefined;\n\n\treturn {\n\t\tname: partyName ? cbcText(partyName, \"Name\") : undefined,\n\t\tregistrationName: legalEntity\n\t\t\t? cbcText(legalEntity, \"RegistrationName\")\n\t\t\t: undefined,\n\t\tcompanyLegalForm: legalEntity\n\t\t\t? cbcText(legalEntity, \"CompanyLegalForm\")\n\t\t\t: undefined,\n\t\tvatId: taxScheme ? cbcText(taxScheme, \"CompanyID\") : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(taxScheme),\n\t\tcompanyId:\n\t\t\tcompanyIdValue !== undefined\n\t\t\t\t? { value: companyIdValue, scheme: attribute(companyIdEl, \"schemeID\") }\n\t\t\t\t: undefined,\n\t\tendpoint:\n\t\t\tendpointValue !== undefined\n\t\t\t\t? { value: endpointValue, scheme: attribute(endpointEl, \"schemeID\") }\n\t\t\t\t: undefined,\n\t\tpartyIdentifications:\n\t\t\tpartyIdentifications.length > 0 ? partyIdentifications : undefined,\n\t\taddress: parseAddress(party),\n\t\tcontact: parseContact(party),\n\t};\n}\n\n/**\n * `cac:TaxCategory` / `cac:ClassifiedTaxCategory`. Emitted whenever the\n * element states anything; `percentFallback` covers the E-FFF habit of putting\n * `cbc:Percent` on the subtotal instead of inside the category.\n */\nfunction parseTaxCategory(\n\tcat: Element | null,\n\tpercentFallback?: Element,\n): UblTaxCategory | undefined {\n\tconst percentFromParent = percentFallback\n\t\t? cbcDirectNumber(percentFallback, \"Percent\")\n\t\t: undefined;\n\tif (!cat) {\n\t\treturn percentFromParent !== undefined\n\t\t\t? { percent: percentFromParent }\n\t\t\t: undefined;\n\t}\n\tconst category: UblTaxCategory = {\n\t\tid: cbcText(cat, \"ID\"),\n\t\tpercent: cbcNumber(cat, \"Percent\") ?? percentFromParent,\n\t\tschemeId: parseTaxSchemeId(cat),\n\t\texemptionReason: cbcText(cat, \"TaxExemptionReason\"),\n\t\texemptionReasonCode: cbcText(cat, \"TaxExemptionReasonCode\"),\n\t};\n\treturn Object.values(category).some((value) => value !== undefined)\n\t\t? category\n\t\t: undefined;\n}\n\nfunction parseTaxSubtotal(sub: Element): UblTaxSubtotal {\n\treturn {\n\t\ttaxableAmount: cbcNumber(sub, \"TaxableAmount\"),\n\t\ttaxAmount: cbcNumber(sub, \"TaxAmount\"),\n\t\tcategory: parseTaxCategory(cacElement(sub, \"TaxCategory\"), sub),\n\t};\n}\n\nfunction parseTaxSubtotalsFromTaxTotal(taxTotal: Element): UblTaxSubtotal[] {\n\treturn cacDirectElements(taxTotal, \"TaxSubtotal\").map(parseTaxSubtotal);\n}\n\n/**\n * `cac:TaxTotal` (BG-22). BT-110 is read from the first `cac:TaxTotal` as\n * stated, never summed from the subtotals; the subtotals of every `TaxTotal`\n * (a second one carries the accounting-currency figure) are concatenated.\n */\nfunction parseTaxTotal(root: Element): UblTaxTotal {\n\tconst taxTotals = cacDirectElements(root, \"TaxTotal\");\n\tconst first = taxTotals[0];\n\tconst second = taxTotals[1];\n\treturn {\n\t\ttaxAmount: first ? cbcDirectNumber(first, \"TaxAmount\") : undefined,\n\t\tsubtotals: taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal),\n\t\ttaxAmountInTaxCurrency: second\n\t\t\t? cbcDirectNumber(second, \"TaxAmount\")\n\t\t\t: undefined,\n\t};\n}\n\nfunction parseAllowanceCharge(charge: Element): UblAllowanceCharge {\n\tconst taxCategory = cacElement(charge, \"TaxCategory\");\n\tconst indicatorRaw = cbcDirectText(charge, \"ChargeIndicator\")?.toLowerCase();\n\tconst chargeIndicator = indicatorRaw === \"true\" || indicatorRaw === \"1\";\n\treturn {\n\t\tchargeIndicator,\n\t\tamount: cbcNumber(charge, \"Amount\"),\n\t\tbaseAmount: cbcDirectNumber(charge, \"BaseAmount\"),\n\t\tmultiplierFactorNumeric: cbcDirectNumber(charge, \"MultiplierFactorNumeric\"),\n\t\treason: cbcText(charge, \"AllowanceChargeReason\"),\n\t\treasonCode: cbcText(charge, \"AllowanceChargeReasonCode\"),\n\t\ttaxCategory: parseTaxCategory(taxCategory),\n\t};\n}\n\nfunction parseAllowanceCharges(parent: Element): UblAllowanceCharge[] {\n\treturn cacDirectElements(parent, \"AllowanceCharge\").map(parseAllowanceCharge);\n}\n\nfunction mergeTaxCategories(\n\tpreferred: UblTaxCategory | undefined,\n\tfallback: UblTaxCategory | undefined,\n): UblTaxCategory | undefined {\n\tif (!preferred) return fallback;\n\tif (!fallback) return preferred;\n\treturn {\n\t\tid: preferred.id ?? fallback.id,\n\t\tpercent: preferred.percent ?? fallback.percent,\n\t\tschemeId: preferred.schemeId ?? fallback.schemeId,\n\t\texemptionReason: preferred.exemptionReason ?? fallback.exemptionReason,\n\t\texemptionReasonCode:\n\t\t\tpreferred.exemptionReasonCode ?? fallback.exemptionReasonCode,\n\t};\n}\n\nfunction parseLines(root: Element, isCreditNote: boolean): UblLine[] {\n\tconst qtyTag = isCreditNote ? \"CreditedQuantity\" : \"InvoicedQuantity\";\n\tconst lineTag = isCreditNote ? \"CreditNoteLine\" : \"InvoiceLine\";\n\n\treturn cacElements(root, lineTag).map((line) => {\n\t\tconst item = cacElement(line, \"Item\");\n\t\tconst price = cacElement(line, \"Price\");\n\t\tconst classifiedCategory = parseTaxCategory(\n\t\t\titem ? cacElement(item, \"ClassifiedTaxCategory\") : null,\n\t\t);\n\t\tconst sellersId = item ? cacElement(item, \"SellersItemIdentification\") : null;\n\t\tconst buyersId = item ? cacElement(item, \"BuyersItemIdentification\") : null;\n\t\tconst qtyEl = line.getElementsByTagNameNS(CBC_NS, qtyTag)[0];\n\t\tconst lineExtensionAmount = cbcNumber(line, \"LineExtensionAmount\");\n\t\tconst lineTaxTotal = cacDirectElement(line, \"TaxTotal\");\n\t\tconst lineTaxSubtotals = lineTaxTotal\n\t\t\t? parseTaxSubtotalsFromTaxTotal(lineTaxTotal)\n\t\t\t: [];\n\t\tconst taxAmountFromSubtotals = lineTaxSubtotals.reduce(\n\t\t\t(sum, subtotal) => sum + (subtotal.taxAmount ?? 0),\n\t\t\t0,\n\t\t);\n\t\tconst taxAmountFromLineTotal = lineTaxTotal\n\t\t\t? cbcDirectNumber(lineTaxTotal, \"TaxAmount\")\n\t\t\t: undefined;\n\t\t// A line-level TaxSubtotal (E-FFF) wins over the classified category,\n\t\t// field by field.\n\t\tconst subtotalCategory = lineTaxSubtotals[0]?.category;\n\t\tconst taxCategory = mergeTaxCategories(subtotalCategory, classifiedCategory);\n\t\tconst taxPercent = taxCategory?.percent;\n\t\tconst computedTaxAmount =\n\t\t\ttaxPercent !== undefined && lineExtensionAmount !== undefined\n\t\t\t\t? Number(((lineExtensionAmount * taxPercent) / 100).toFixed(2))\n\t\t\t\t: undefined;\n\t\tconst allowanceCharges = parseAllowanceCharges(line);\n\t\t// BT-147/BT-148: the one allowance UBL permits under cac:Price.\n\t\tconst priceAllowanceElement = price\n\t\t\t? parseAllowanceCharges(price).find((charge) => !charge.chargeIndicator)\n\t\t\t: undefined;\n\t\tconst priceAllowance = priceAllowanceElement\n\t\t\t? {\n\t\t\t\t\tamount: priceAllowanceElement.amount,\n\t\t\t\t\tbaseAmount: priceAllowanceElement.baseAmount,\n\t\t\t\t\treason: priceAllowanceElement.reason,\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tconst discountAmount =\n\t\t\tallowanceCharges.reduce(\n\t\t\t\t(sum, charge) =>\n\t\t\t\t\tcharge.chargeIndicator ? sum : sum + Math.abs(charge.amount ?? 0),\n\t\t\t\t0,\n\t\t\t) + Math.abs(priceAllowance?.amount ?? 0);\n\t\tconst chargeAmount = allowanceCharges.reduce(\n\t\t\t(sum, charge) =>\n\t\t\t\tcharge.chargeIndicator ? sum + Math.abs(charge.amount ?? 0) : sum,\n\t\t\t0,\n\t\t);\n\n\t\tconst additionalItemProperties: UblItemProperty[] = [];\n\t\tif (item) {\n\t\t\tfor (const prop of cacElements(item, \"AdditionalItemProperty\")) {\n\t\t\t\tconst propName = cbcText(prop, \"Name\");\n\t\t\t\tconst propValue = cbcText(prop, \"Value\");\n\t\t\t\tif (propName) {\n\t\t\t\t\tadditionalItemProperties.push({\n\t\t\t\t\t\tname: propName,\n\t\t\t\t\t\tvalue: propValue,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// EN16931 BT-146 (PriceAmount) is the price for BT-149 (BaseQuantity) units\n\t\t// of the item, not necessarily for one unit. Effective unit price is\n\t\t// PriceAmount / BaseQuantity, with BaseQuantity defaulting to 1 when absent.\n\t\tconst priceAmount = price ? cbcNumber(price, \"PriceAmount\") : undefined;\n\t\tconst priceBaseQuantity = price\n\t\t\t? cbcDirectNumber(price, \"BaseQuantity\")\n\t\t\t: undefined;\n\t\tconst unitPrice =\n\t\t\tpriceAmount !== undefined && priceBaseQuantity && priceBaseQuantity > 0\n\t\t\t\t? priceAmount / priceBaseQuantity\n\t\t\t\t: priceAmount;\n\n\t\tconst orderLineReference = cacDirectElement(line, \"OrderLineReference\");\n\t\tconst lineDocumentReference = cacDirectElements(line, \"DocumentReference\").find(\n\t\t\t(reference) => cbcDirectText(reference, \"DocumentTypeCode\") === \"130\",\n\t\t);\n\t\tconst standardId = item\n\t\t\t? cacDirectElement(item, \"StandardItemIdentification\")\n\t\t\t: null;\n\t\tconst originCountry = item ? cacDirectElement(item, \"OriginCountry\") : null;\n\t\tconst commodityClassifications: UblCommodityClassification[] = [];\n\t\tfor (const classification of item\n\t\t\t? cacDirectElements(item, \"CommodityClassification\")\n\t\t\t: []) {\n\t\t\tconst codeElement = childElementsByTagNs(\n\t\t\t\tclassification,\n\t\t\t\tCBC_NS,\n\t\t\t\t\"ItemClassificationCode\",\n\t\t\t)[0];\n\t\t\tconst value = trimmed(codeElement?.textContent);\n\t\t\tif (value === undefined) continue;\n\t\t\tcommodityClassifications.push({\n\t\t\t\tvalue,\n\t\t\t\tlistId: attribute(codeElement, \"listID\"),\n\t\t\t\tlistVersionId: attribute(codeElement, \"listVersionID\"),\n\t\t\t});\n\t\t}\n\n\t\treturn {\n\t\t\tid: requiredCbcText(line, \"ID\", `${lineTag} identifier`),\n\t\t\tnote: cbcDirectText(line, \"Note\"),\n\t\t\tobjectIdentifier: lineDocumentReference\n\t\t\t\t? cbcDirectSchemedId(lineDocumentReference, \"ID\")\n\t\t\t\t: undefined,\n\t\t\torderLineReference: orderLineReference\n\t\t\t\t? cbcDirectText(orderLineReference, \"LineID\")\n\t\t\t\t: undefined,\n\t\t\taccountingCost: cbcDirectText(line, \"AccountingCost\"),\n\t\t\tdescription: item ? cbcText(item, \"Description\") : undefined,\n\t\t\tquantity: cbcNumber(line, qtyTag),\n\t\t\tunitCode: attribute(qtyEl, \"unitCode\"),\n\t\t\tunitPrice,\n\t\t\tlineExtensionAmount,\n\t\t\tbaseQuantity: priceBaseQuantity,\n\t\t\ttaxCategory,\n\t\t\ttaxAmount:\n\t\t\t\ttaxAmountFromLineTotal ??\n\t\t\t\t(lineTaxSubtotals.length > 0\n\t\t\t\t\t? taxAmountFromSubtotals\n\t\t\t\t\t: computedTaxAmount),\n\t\t\ttaxSubtotals: lineTaxSubtotals.length > 0 ? lineTaxSubtotals : undefined,\n\t\t\tallowanceCharges:\n\t\t\t\tallowanceCharges.length > 0 ? allowanceCharges : undefined,\n\t\t\tpriceAllowance,\n\t\t\tdiscountAmount: discountAmount > 0 ? discountAmount : undefined,\n\t\t\tchargeAmount: chargeAmount > 0 ? chargeAmount : undefined,\n\t\t\titemName: item ? cbcText(item, \"Name\") : undefined,\n\t\t\tsellersItemId: sellersId ? cbcText(sellersId, \"ID\") : undefined,\n\t\t\tbuyersItemId: buyersId ? cbcText(buyersId, \"ID\") : undefined,\n\t\t\tstandardItemId: standardId\n\t\t\t\t? cbcDirectSchemedId(standardId, \"ID\")\n\t\t\t\t: undefined,\n\t\t\tcommodityClassifications:\n\t\t\t\tcommodityClassifications.length > 0\n\t\t\t\t\t? commodityClassifications\n\t\t\t\t\t: undefined,\n\t\t\toriginCountryCode: originCountry\n\t\t\t\t? cbcDirectText(originCountry, \"IdentificationCode\")\n\t\t\t\t: undefined,\n\t\t\tadditionalItemProperties:\n\t\t\t\tadditionalItemProperties.length > 0\n\t\t\t\t\t? additionalItemProperties\n\t\t\t\t\t: undefined,\n\t\t\tinvoicePeriod: parseInvoicePeriod(line),\n\t\t};\n\t});\n}\n\nfunction parseMonetaryTotal(root: Element): UblMonetaryTotal {\n\tconst total = cacDirectElement(root, \"LegalMonetaryTotal\");\n\tif (!total) return {};\n\treturn {\n\t\tlineExtensionAmount: cbcNumber(total, \"LineExtensionAmount\"),\n\t\ttaxExclusiveAmount: cbcNumber(total, \"TaxExclusiveAmount\"),\n\t\ttaxInclusiveAmount: cbcNumber(total, \"TaxInclusiveAmount\"),\n\t\tallowanceTotalAmount: cbcNumber(total, \"AllowanceTotalAmount\"),\n\t\tchargeTotalAmount: cbcNumber(total, \"ChargeTotalAmount\"),\n\t\tprepaidAmount: cbcNumber(total, \"PrepaidAmount\"),\n\t\tpayableRoundingAmount: cbcNumber(total, \"PayableRoundingAmount\"),\n\t\tpayableAmount: cbcNumber(total, \"PayableAmount\"),\n\t};\n}\n\nfunction parsePaymentMeansElement(pm: Element): UblPaymentMeans {\n\tconst account = cacElement(pm, \"PayeeFinancialAccount\");\n\tconst branch = account ? cacElement(account, \"FinancialInstitutionBranch\") : null;\n\tconst paymentMeansCodeEl = pm.getElementsByTagNameNS(CBC_NS, \"PaymentMeansCode\")[0];\n\tconst mandate = cacElement(pm, \"PaymentMandate\");\n\tconst debitedAccount = mandate\n\t\t? cacElement(mandate, \"PayerFinancialAccount\")\n\t\t: null;\n\tconst card = cacElement(pm, \"CardAccount\");\n\n\treturn {\n\t\tcode: cbcText(pm, \"PaymentMeansCode\"),\n\t\tcodeName: attribute(paymentMeansCodeEl, \"name\"),\n\t\tpaymentId: cbcText(pm, \"PaymentID\"),\n\t\tiban: account ? cbcText(account, \"ID\") : undefined,\n\t\tbic: branch ? cbcText(branch, \"ID\") : undefined,\n\t\taccountName: account ? cbcText(account, \"Name\") : undefined,\n\t\tmandateId: mandate ? cbcDirectText(mandate, \"ID\") : undefined,\n\t\tdebitedAccount: debitedAccount ? cbcText(debitedAccount, \"ID\") : undefined,\n\t\tcardNumber: card ? cbcText(card, \"PrimaryAccountNumberID\") : undefined,\n\t\tcardHolder: card ? cbcText(card, \"HolderName\") : undefined,\n\t};\n}\n\nfunction parsePaymentMeansList(root: Element): UblPaymentMeans[] | undefined {\n\tconst list = cacElements(root, \"PaymentMeans\").map(parsePaymentMeansElement);\n\treturn list.length > 0 ? list : undefined;\n}\n\n/**\n * BT-73/BT-74 on a document, BT-134/BT-135 on a line. Direct children only:\n * a descendant search on the document root would report the first line's\n * period as the document's whenever the document states none of its own.\n */\nfunction parseInvoicePeriod(parent: Element): UblInvoicePeriod | undefined {\n\tconst period = cacDirectElement(parent, \"InvoicePeriod\");\n\tif (!period) return undefined;\n\n\tconst start = cbcText(period, \"StartDate\");\n\tconst end = cbcText(period, \"EndDate\");\n\tif (!start && !end) return undefined;\n\n\treturn {\n\t\tstartDate: start,\n\t\tendDate: end,\n\t\tdescriptionCode: cbcText(period, \"DescriptionCode\"),\n\t};\n}\n\nfunction parseDelivery(root: Element): UblDelivery | undefined {\n\tconst delivery = cacElement(root, \"Delivery\");\n\tif (!delivery) return undefined;\n\tconst actualDeliveryDate = cbcText(delivery, \"ActualDeliveryDate\");\n\tconst deliveryLocation = cacElement(delivery, \"DeliveryLocation\");\n\tconst locationId = deliveryLocation\n\t\t? cbcDirectSchemedId(deliveryLocation, \"ID\")\n\t\t: undefined;\n\tconst address = parseAddressFromElement(\n\t\tdeliveryLocation ? cacElement(deliveryLocation, \"Address\") : null,\n\t);\n\tconst deliveryParty = cacElement(delivery, \"DeliveryParty\");\n\tconst partyName = deliveryParty ? cbcText(deliveryParty, \"Name\") : undefined;\n\tif (!actualDeliveryDate && !locationId && !address && !partyName) return undefined;\n\treturn {\n\t\tactualDeliveryDate,\n\t\tlocationId,\n\t\taddress,\n\t\tpartyName,\n\t};\n}\n\nfunction parsePaymentTermsNote(root: Element): string | undefined {\n\tconst paymentTerms = cacElement(root, \"PaymentTerms\");\n\tif (!paymentTerms) return undefined;\n\treturn cbcText(paymentTerms, \"Note\");\n}\n\nfunction parseNotes(root: Element): string | undefined {\n\tconst noteEls = root.getElementsByTagNameNS(CBC_NS, \"Note\");\n\tconst notes: string[] = [];\n\tfor (let i = 0; i < noteEls.length; i++) {\n\t\tconst el = noteEls[i];\n\t\tif (!el) continue;\n\t\tif (el.parentElement === root || el.parentNode === root) {\n\t\t\tconst text = el.textContent?.trim();\n\t\t\tif (text) notes.push(text);\n\t\t}\n\t}\n\treturn notes.length > 0 ? notes.join(\"\\n\") : undefined;\n}\n\n/**\n * `cac:AdditionalDocumentReference` (BG-24), plus the two references EN 16931\n * types by `cbc:DocumentTypeCode`: 130 is the invoiced object (BT-18) and 50\n * is the tender or lot (BT-17), which on a credit note stands in for the\n * project reference (BT-11) UBL's CreditNote has no element for.\n */\nfunction parseAttachments(root: Element): {\n\tattachments: UblAttachment[] | undefined;\n\tdocumentReferences: UblDocumentReference[] | undefined;\n\tinvoicedObjectId: UblSchemedId | undefined;\n\ttypeCode50Reference: string | undefined;\n} {\n\tconst refs = cacDirectElements(root, \"AdditionalDocumentReference\");\n\tconst attachments: UblAttachment[] = [];\n\tconst documentReferences: UblDocumentReference[] = [];\n\tlet invoicedObjectId: UblSchemedId | undefined;\n\tlet typeCode50Reference: string | undefined;\n\n\tfor (const ref of refs) {\n\t\tconst attachment = cacElement(ref, \"Attachment\");\n\t\tconst refId = cbcText(ref, \"ID\");\n\t\tconst description = cbcText(ref, \"DocumentDescription\");\n\t\tconst typeCode = cbcDirectText(ref, \"DocumentTypeCode\");\n\n\t\tif (typeCode === \"130\" && !attachment) {\n\t\t\tinvoicedObjectId ??= cbcDirectSchemedId(ref, \"ID\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeCode === \"50\" && !attachment) {\n\t\t\ttypeCode50Reference ??= refId;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!attachment) {\n\t\t\t// Text-only document reference (e.g. terms & conditions, notices)\n\t\t\tif (refId || description) {\n\t\t\t\tdocumentReferences.push({ id: refId, description });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst binaryEl = attachment.getElementsByTagNameNS(\n\t\t\tCBC_NS,\n\t\t\t\"EmbeddedDocumentBinaryObject\",\n\t\t)[0];\n\t\tconst externalRef = cacElement(attachment, \"ExternalReference\");\n\n\t\tif (binaryEl) {\n\t\t\tconst content = binaryEl.textContent?.trim();\n\t\t\tif (content) {\n\t\t\t\tattachments.push({\n\t\t\t\t\tid: refId,\n\t\t\t\t\tfilename: attribute(binaryEl, \"filename\"),\n\t\t\t\t\tmimeCode: attribute(binaryEl, \"mimeCode\"),\n\t\t\t\t\tdescription,\n\t\t\t\t\tbase64Content: content,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (externalRef) {\n\t\t\tconst uri = cbcText(externalRef, \"URI\");\n\t\t\tif (uri) {\n\t\t\t\tattachments.push({\n\t\t\t\t\tid: refId,\n\t\t\t\t\tdescription,\n\t\t\t\t\texternalUri: uri,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tattachments: attachments.length > 0 ? attachments : undefined,\n\t\tdocumentReferences:\n\t\t\tdocumentReferences.length > 0 ? documentReferences : undefined,\n\t\tinvoicedObjectId,\n\t\ttypeCode50Reference,\n\t};\n}\n\nfunction parseBillingReference(root: Element): UblBillingReference | undefined {\n\tconst billingRef = cacElement(root, \"BillingReference\");\n\tif (!billingRef) return undefined;\n\tconst invoiceRef = cacElement(billingRef, \"InvoiceDocumentReference\");\n\tif (!invoiceRef) return undefined;\n\tconst invoiceId = cbcText(invoiceRef, \"ID\");\n\tconst invoiceIssueDate = cbcText(invoiceRef, \"IssueDate\");\n\tif (!invoiceId && !invoiceIssueDate) return undefined;\n\treturn { invoiceId, invoiceIssueDate };\n}\n\n// --- Main parser ---\n\n/**\n * Drop `undefined`-valued keys recursively so an absent field is an absent\n * key, not a key holding `undefined`. Arrays keep their order and length.\n */\nfunction omitUndefined<T>(value: T): T {\n\tif (Array.isArray(value)) {\n\t\treturn value.map(omitUndefined) as T;\n\t}\n\tif (value !== null && typeof value === \"object\") {\n\t\tconst out: Record<string, unknown> = {};\n\t\tfor (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n\t\t\tif (entry !== undefined) out[key] = omitUndefined(entry);\n\t\t}\n\t\treturn out as T;\n\t}\n\treturn value;\n}\n\nconst INVOICE_NS = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\";\nconst CREDIT_NOTE_NS = \"urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2\";\n\n/**\n * Parse a UBL 2.1 Invoice or CreditNote.\n *\n * Returns `null` when the XML is well-formed but its root is not a UBL\n * `Invoice`/`CreditNote`. Throws {@link UblParseError} when the XML is\n * malformed or the document lacks an element EN 16931 makes mandatory\n * (document id, issue date, currency, line id).\n */\nexport function parseUblInvoice(xml: string): UblInvoice | null {\n\tconst doc = parseXmlDocument(xml);\n\tconst root = doc.documentElement;\n\tif (!root) return null;\n\n\tlet documentType: \"Invoice\" | \"CreditNote\";\n\tif (root.localName === \"Invoice\" && root.namespaceURI === INVOICE_NS) {\n\t\tdocumentType = \"Invoice\";\n\t} else if (\n\t\troot.localName === \"CreditNote\" &&\n\t\troot.namespaceURI === CREDIT_NOTE_NS\n\t) {\n\t\tdocumentType = \"CreditNote\";\n\t} else {\n\t\treturn null;\n\t}\n\n\tconst isCreditNote = documentType === \"CreditNote\";\n\tconst id = requiredCbcText(root, \"ID\", \"document identifier\");\n\tconst issueDate = requiredCbcText(root, \"IssueDate\", \"issue date\");\n\tconst currency = requiredCbcText(root, \"DocumentCurrencyCode\", \"currency code\");\n\tconst paymentMeansList = parsePaymentMeansList(root);\n\tconst orderReference = cacElement(root, \"OrderReference\");\n\tconst contractReference = cacDirectElement(root, \"ContractDocumentReference\");\n\tconst projectReference = cacDirectElement(root, \"ProjectReference\");\n\tconst despatchReference = cacDirectElement(root, \"DespatchDocumentReference\");\n\tconst receiptReference = cacDirectElement(root, \"ReceiptDocumentReference\");\n\tconst { attachments, documentReferences, invoicedObjectId, typeCode50Reference } =\n\t\tparseAttachments(root);\n\t// A credit note has no cbc:DueDate; BT-9 travels in the first PaymentMeans.\n\tconst paymentDueDate = (() => {\n\t\tconst first = cacDirectElements(root, \"PaymentMeans\")[0];\n\t\treturn first ? cbcDirectText(first, \"PaymentDueDate\") : undefined;\n\t})();\n\n\treturn omitUndefined<UblInvoice>({\n\t\tdocumentType,\n\t\tcustomizationId: cbcText(root, \"CustomizationID\"),\n\t\tprofileId: cbcText(root, \"ProfileID\"),\n\t\tid,\n\t\tinvoiceTypeCode:\n\t\t\tcbcText(root, \"InvoiceTypeCode\") ?? cbcText(root, \"CreditNoteTypeCode\"),\n\t\tissueDate,\n\t\tdueDate: cbcDirectText(root, \"DueDate\") ?? paymentDueDate,\n\t\ttaxPointDate: cbcDirectText(root, \"TaxPointDate\"),\n\t\tcurrency,\n\t\ttaxCurrency: cbcDirectText(root, \"TaxCurrencyCode\"),\n\t\taccountingCost: cbcDirectText(root, \"AccountingCost\"),\n\t\tbuyerReference: cbcText(root, \"BuyerReference\"),\n\t\torderReference: orderReference ? cbcText(orderReference, \"ID\") : undefined,\n\t\tsalesOrderId: orderReference\n\t\t\t? cbcText(orderReference, \"SalesOrderID\")\n\t\t\t: undefined,\n\t\tcontractReference: contractReference\n\t\t\t? cbcText(contractReference, \"ID\")\n\t\t\t: undefined,\n\t\tprojectReference: projectReference\n\t\t\t? cbcText(projectReference, \"ID\")\n\t\t\t: isCreditNote\n\t\t\t\t? typeCode50Reference\n\t\t\t\t: undefined,\n\t\treceivingAdviceReference: receiptReference\n\t\t\t? cbcDirectText(receiptReference, \"ID\")\n\t\t\t: undefined,\n\t\tdespatchReference: despatchReference\n\t\t\t? cbcDirectText(despatchReference, \"ID\")\n\t\t\t: undefined,\n\t\ttenderReference: isCreditNote ? undefined : typeCode50Reference,\n\t\tinvoicedObjectId,\n\t\tbillingReference: parseBillingReference(root),\n\t\tseller: parseParty(root, \"AccountingSupplierParty\"),\n\t\tbuyer: parseParty(root, \"AccountingCustomerParty\"),\n\t\tpayee: parseUnwrappedParty(root, \"PayeeParty\"),\n\t\ttaxRepresentative: parseUnwrappedParty(root, \"TaxRepresentativeParty\"),\n\t\tdelivery: parseDelivery(root),\n\t\tlines: parseLines(root, isCreditNote),\n\t\ttaxTotal: parseTaxTotal(root),\n\t\tmonetaryTotal: parseMonetaryTotal(root),\n\t\tpaymentMeansList,\n\t\tpaymentMeans: paymentMeansList?.[0],\n\t\tinvoicePeriod: parseInvoicePeriod(root),\n\t\tnote: parseNotes(root),\n\t\tpaymentTermsNote: parsePaymentTermsNote(root),\n\t\tattachments,\n\t\tdocumentReferences,\n\t\tallowanceCharges: parseAllowanceCharges(root),\n\t});\n}\n","import { UblParseError } from \"./errors.js\";\nimport { parseUblInvoice } from \"./parser.js\";\nimport type { UblAttachment } from \"./types.js\";\n\n/**\n * An embedded attachment extracted from a UBL document's\n * `AdditionalDocumentReference` entries, with its binary content still\n * base64-encoded. `sizeBytes` is the decoded size.\n */\nexport interface UblEmbeddedAttachment {\n\tid?: string | undefined;\n\tfilename: string;\n\tmimeCode: string;\n\tsizeBytes: number;\n\t/** Zero-based position among the document's embedded attachments. */\n\tlineOrder: number;\n\tbase64Content: string;\n}\n\n/** Decoded byte length of a base64 string, accounting for `=` padding. */\nexport const base64DecodedSize = (base64: string): number => {\n\tconst sanitized = base64.replace(/\\s+/g, \"\");\n\tif (!sanitized) return 0;\n\tconst padding = sanitized.endsWith(\"==\") ? 2 : sanitized.endsWith(\"=\") ? 1 : 0;\n\treturn Math.floor((sanitized.length * 3) / 4) - padding;\n};\n\n/**\n * Extract the embedded attachments (typically the human-readable PDF) from a\n * UBL invoice or credit note XML. Attachments referenced only by external URI\n * (no `EmbeddedDocumentBinaryObject`) are skipped; use {@link parseUblInvoice}\n * directly when those matter.\n *\n * @throws {UblParseError} when the XML is malformed or not a UBL invoice.\n */\nexport const extractUblEmbeddedAttachments = (xml: string): UblEmbeddedAttachment[] => {\n\tconst parsed = parseUblInvoice(xml);\n\tif (!parsed) throw new UblParseError(\"Document is not a UBL Invoice or CreditNote\");\n\tif (!parsed.attachments || parsed.attachments.length === 0) return [];\n\n\treturn parsed.attachments\n\t\t.map((attachment, index): UblEmbeddedAttachment | null => {\n\t\t\tconst base64Content = attachment.base64Content?.trim();\n\t\t\tif (!base64Content) return null;\n\t\t\treturn {\n\t\t\t\tid: attachment.id,\n\t\t\t\tfilename: attachment.filename ?? `attachment-${index + 1}`,\n\t\t\t\tmimeCode: attachment.mimeCode ?? \"application/octet-stream\",\n\t\t\t\tsizeBytes: base64DecodedSize(base64Content),\n\t\t\t\tlineOrder: index,\n\t\t\t\tbase64Content,\n\t\t\t};\n\t\t})\n\t\t.filter((entry): entry is UblEmbeddedAttachment => entry !== null);\n};\n\n/**\n * Whether an attachment looks like a PDF, by MIME type first and filename\n * extension as a fallback.\n */\nexport const isPdfLikeAttachment = (\n\tattachment: Pick<UblAttachment, \"filename\" | \"mimeCode\">,\n): boolean => {\n\tconst mimeCode = attachment.mimeCode?.toLowerCase() ?? \"\";\n\tif (mimeCode === \"application/pdf\" || mimeCode.endsWith(\"/pdf\")) return true;\n\treturn attachment.filename?.toLowerCase().endsWith(\".pdf\") ?? false;\n};\n","import type { Element } from \"@xmldom/xmldom\";\nimport { UblParseError } from \"./errors.js\";\nimport { CAC_NS, CBC_NS, parseXmlDocument } from \"./xml-dom.js\";\n\n/**\n * Peppol BIS MLR (Message Level Response) document-type identifier value\n * (Peppol `busdox-docid-qns` scheme).\n */\nexport const PEPPOL_MLR_DOCUMENT_TYPE_VALUE =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2::ApplicationResponse##urn:fdc:peppol.eu:poacc:trns:mlr:3::2.1\";\n\n/** Peppol BIS MLR process identifier value. */\nexport const PEPPOL_MLR_PROCESS_VALUE = \"urn:fdc:peppol.eu:poacc:bis:mlr:3\";\n\n/**\n * A parsed Peppol Message Level Response (a UBL `ApplicationResponse`). Every\n * field is optional: a given MLR may omit any of them, and an omitted field is\n * an absent key.\n */\nexport interface PeppolMessageLevelResponse {\n\tcustomizationId?: string | undefined;\n\tprofileId?: string | undefined;\n\tresponseId?: string | undefined;\n\tissueDate?: string | undefined;\n\tissueTime?: string | undefined;\n\treferencedDocumentId?: string | undefined;\n\tresponseCode?: string | undefined;\n\tdescription?: string | undefined;\n\t/** Sender participant id as `schemeID:value` (e.g. `0208:0793904121`). */\n\tsenderIdentifier?: string | undefined;\n\t/** Receiver participant id as `schemeID:value`. */\n\treceiverIdentifier?: string | undefined;\n}\n\nconst trimmed = (value: string | null | undefined): string | undefined => {\n\tconst text = value?.trim();\n\treturn text ? text : undefined;\n};\n\n/** First descendant CBC element's trimmed text, or undefined. */\nconst cbcText = (parent: Element, tag: string): string | undefined =>\n\ttrimmed(parent.getElementsByTagNameNS(CBC_NS, tag)[0]?.textContent);\n\n/**\n * First direct-child CBC element's trimmed text, or null. Used for the\n * top-level scalars so a nested `cbc:ID` (e.g. inside DocumentReference) cannot\n * shadow the ApplicationResponse's own id.\n */\nconst cbcDirectText = (parent: Element, tag: string): string | undefined => {\n\tfor (let i = 0; i < parent.childNodes.length; i++) {\n\t\tconst node = parent.childNodes[i];\n\t\tif (!node || node.nodeType !== 1) continue;\n\t\tconst el = node as Element;\n\t\tif (el.namespaceURI === CBC_NS && el.localName === tag) {\n\t\t\treturn trimmed(el.textContent);\n\t\t}\n\t}\n\treturn undefined;\n};\n\n/** First descendant CAC element, or null. */\nconst cacElement = (parent: Element, tag: string): Element | null =>\n\tparent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;\n\n/**\n * The Peppol participant identifier of a SenderParty / ReceiverParty, rendered\n * as `schemeID:value` when the EndpointID carries a scheme and the value does\n * not already include one, otherwise the raw value.\n */\nconst endpointIdentifier = (party: Element | null): string | undefined => {\n\tif (!party) return undefined;\n\tconst endpoint = party.getElementsByTagNameNS(CBC_NS, \"EndpointID\")[0];\n\tif (!endpoint) return undefined;\n\tconst id = trimmed(endpoint.textContent);\n\tconst scheme = endpoint.getAttribute(\"schemeID\");\n\tif (scheme && id && !id.includes(\":\")) return `${scheme}:${id}`;\n\treturn id;\n};\n\n/**\n * Locate the `ApplicationResponse` element, unwrapping a Standard Business\n * Document (SBDH) envelope when present. Returns null when the XML contains no\n * ApplicationResponse; throws {@link UblParseError} when it is malformed.\n */\nconst findApplicationResponse = (xml: string): Element | null => {\n\tconst doc = parseXmlDocument(xml);\n\tconst root = doc.documentElement;\n\tif (!root) return null;\n\tif (root.localName === \"ApplicationResponse\") return root;\n\tconst candidates = root.getElementsByTagName(\"*\");\n\tfor (let i = 0; i < candidates.length; i++) {\n\t\tconst el = candidates[i];\n\t\tif (el?.localName === \"ApplicationResponse\") return el;\n\t}\n\treturn null;\n};\n\n/**\n * Whether an inbound document is a Peppol Message Level Response, identified by\n * its document-type value, its process value, or by parsing the XML and finding\n * an `ApplicationResponse` root (SBDH-wrapped or not).\n */\nexport const isPeppolMessageLevelResponse = (params: {\n\tdocumentTypeValue?: string | null;\n\tprocessValue?: string | null;\n\txml?: string | null;\n}): boolean => {\n\tif (trimmed(params.documentTypeValue) === PEPPOL_MLR_DOCUMENT_TYPE_VALUE) {\n\t\treturn true;\n\t}\n\tif (trimmed(params.processValue) === PEPPOL_MLR_PROCESS_VALUE) return true;\n\tconst xml = trimmed(params.xml);\n\tif (!xml) return false;\n\ttry {\n\t\treturn findApplicationResponse(xml) !== null;\n\t} catch (error) {\n\t\t// A sniff answers \"is this an MLR?\"; malformed XML is simply \"no\".\n\t\tif (error instanceof UblParseError) return false;\n\t\tthrow error;\n\t}\n};\n\n/**\n * Parse a Peppol Message Level Response (UBL `ApplicationResponse`), unwrapping\n * an SBDH envelope when present. Throws {@link UblParseError} when the XML is\n * malformed or is not an ApplicationResponse.\n */\nexport const parsePeppolMessageLevelResponse = (\n\txml: string,\n): PeppolMessageLevelResponse => {\n\tconst root = findApplicationResponse(xml);\n\tif (!root) {\n\t\tthrow new UblParseError(\"Document is not a Peppol Message Level Response\");\n\t}\n\n\tconst documentResponse = cacElement(root, \"DocumentResponse\");\n\tconst response = documentResponse ? cacElement(documentResponse, \"Response\") : null;\n\tconst documentReference = documentResponse\n\t\t? cacElement(documentResponse, \"DocumentReference\")\n\t\t: null;\n\n\treturn {\n\t\tcustomizationId: cbcDirectText(root, \"CustomizationID\"),\n\t\tprofileId: cbcDirectText(root, \"ProfileID\"),\n\t\tresponseId: cbcDirectText(root, \"ID\"),\n\t\tissueDate: cbcDirectText(root, \"IssueDate\"),\n\t\tissueTime: cbcDirectText(root, \"IssueTime\"),\n\t\treferencedDocumentId: documentReference\n\t\t\t? cbcText(documentReference, \"ID\")\n\t\t\t: undefined,\n\t\tresponseCode: response ? cbcText(response, \"ResponseCode\") : undefined,\n\t\tdescription: response ? cbcText(response, \"Description\") : undefined,\n\t\tsenderIdentifier: endpointIdentifier(cacElement(root, \"SenderParty\")),\n\t\treceiverIdentifier: endpointIdentifier(cacElement(root, \"ReceiverParty\")),\n\t};\n};\n","import { base64DecodedSize } from \"./attachments.js\";\nimport { UblParseError } from \"./errors.js\";\nimport { parseUblInvoice } from \"./parser.js\";\nimport type {\n\tInvoiceExtractionDTO,\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblInvoice,\n\tUblPaymentMeans,\n} from \"./types.js\";\n\n// --- Utility helpers ---\n\nconst UTF8_BOM = 0xfeff;\n\n/** `null` for an absent value or an \"N/A\" placeholder written by the sender. */\nconst normalizeText = (value: string | undefined): string | null => {\n\tif (value === undefined) return null;\n\tconst upper = value.toUpperCase();\n\tif (upper === \"NA\" || upper === \"N/A\") return null;\n\treturn value;\n};\n\nconst toNumberOrNull = (value: number | undefined): number | null =>\n\tvalue !== undefined && Number.isFinite(value) ? value : null;\n\nconst roundToCents = (value: number): number => Math.round(value * 100) / 100;\n\nexport const normalizeCurrency = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\treturn trimmed.toUpperCase();\n};\n\nexport const parseDate = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\tconst timestamp = Date.parse(trimmed);\n\tif (Number.isNaN(timestamp)) return null;\n\tconst iso = new Date(timestamp).toISOString();\n\treturn iso.slice(0, 10);\n};\n\nconst sanitizePaymentMeans = (pm: UblPaymentMeans) => ({\n\tcode: normalizeText(pm.code),\n\tcode_name: normalizeText(pm.codeName),\n\tpayment_id: normalizeText(pm.paymentId),\n\tiban: normalizeText(pm.iban),\n\tbic: normalizeText(pm.bic),\n\taccount_name: normalizeText(pm.accountName),\n\tmandate_id: normalizeText(pm.mandateId),\n});\n\n// --- Address helpers ---\n\nconst present = (part: string | undefined): part is string => part !== undefined;\n\nconst joinStreet = (address: UblAddress): string =>\n\t[address.street, address.additionalStreet].filter(present).join(\" \");\n\nconst addressToString = (address?: UblAddress): string | null => {\n\tif (!address) return null;\n\tconst street = joinStreet(address);\n\tconst cityLine = [address.postalZone, address.city].filter(present).join(\" \");\n\tconst countryLine = [address.countrySubentity, address.countryCode]\n\t\t.filter(present)\n\t\t.join(\" \");\n\tconst lines = [street, cityLine, countryLine].filter((line) => line.length > 0);\n\treturn lines.length > 0 ? lines.join(\"\\n\") : null;\n};\n\nconst addressToStructured = (address?: UblAddress) => {\n\tif (!address) return null;\n\tconst line1 = joinStreet(address);\n\tconst result = {\n\t\tline1: line1 ? normalizeText(line1) : null,\n\t\tline2: null as string | null,\n\t\tcity: normalizeText(address.city),\n\t\tstate: normalizeText(address.countrySubentity),\n\t\tpostal_code: normalizeText(address.postalZone),\n\t\tcountry: normalizeText(address.countryCode),\n\t};\n\tconst hasValue = Object.values(result).some((value) => value);\n\treturn hasValue ? result : null;\n};\n\n// --- Attachment & charge sanitizers ---\n\nconst sanitizeAttachments = (attachments?: UblAttachment[]) =>\n\t(attachments ?? []).map((attachment) => ({\n\t\tid: normalizeText(attachment.id),\n\t\tfilename: normalizeText(attachment.filename),\n\t\tmime_code: normalizeText(attachment.mimeCode),\n\t\tdescription: normalizeText(attachment.description),\n\t\tsize_bytes:\n\t\t\tattachment.base64Content !== undefined\n\t\t\t\t? base64DecodedSize(attachment.base64Content)\n\t\t\t\t: null,\n\t\texternal_uri: normalizeText(attachment.externalUri),\n\t}));\n\nconst sanitizeAllowanceCharges = (charges?: UblAllowanceCharge[]) =>\n\t(charges ?? []).map((charge) => ({\n\t\tcharge_indicator: charge.chargeIndicator,\n\t\tamount: toNumberOrNull(charge.amount),\n\t\tbase_amount: toNumberOrNull(charge.baseAmount),\n\t\tmultiplier_factor_numeric: toNumberOrNull(charge.multiplierFactorNumeric),\n\t\treason: normalizeText(charge.reason),\n\t\treason_code: normalizeText(charge.reasonCode),\n\t\ttax_percent: toNumberOrNull(charge.taxCategory?.percent),\n\t\ttax_category_id: normalizeText(charge.taxCategory?.id),\n\t\ttax_scheme_id: normalizeText(charge.taxCategory?.schemeId),\n\t}));\n\nconst sanitizeRawUbl = (ubl: UblInvoice) => ({\n\t...ubl,\n\tattachments: sanitizeAttachments(ubl.attachments),\n\tdocumentReferences: ubl.documentReferences ?? [],\n});\n\n// --- Summation helpers ---\n\nconst sumTaxTotal = (ubl: UblInvoice): number | null => {\n\tconst { subtotals } = ubl.taxTotal;\n\tconst subtotalSum = subtotals.reduce(\n\t\t(sum, subtotal) => sum + (subtotal.taxAmount ?? 0),\n\t\t0,\n\t);\n\tif (subtotals.length > 0 && Number.isFinite(subtotalSum)) {\n\t\treturn subtotalSum;\n\t}\n\tconst { taxInclusiveAmount, taxExclusiveAmount } = ubl.monetaryTotal;\n\tif (taxInclusiveAmount === undefined || taxExclusiveAmount === undefined) {\n\t\treturn null;\n\t}\n\treturn taxInclusiveAmount - taxExclusiveAmount;\n};\n\nconst sumAllowanceChargesByType = (\n\tcharges: UblAllowanceCharge[] | undefined,\n\tchargeIndicator: boolean,\n) =>\n\t(charges ?? []).reduce((sum, charge) => {\n\t\tif (charge.chargeIndicator !== chargeIndicator) return sum;\n\t\treturn sum + Math.abs(charge.amount ?? 0);\n\t}, 0);\n\n// --- Public API ---\n\n/**\n * Decode raw XML bytes, stripping an optional UTF-8 BOM.\n */\nexport const decodeXmlBytes = (bytes: Uint8Array): string => {\n\tconst text = new TextDecoder(\"utf-8\").decode(bytes);\n\treturn text.charCodeAt(0) === UTF8_BOM ? text.slice(1) : text;\n};\n\n/**\n * Parse a UBL XML string and normalize it into a flat DTO suitable for\n * database storage or API responses.\n *\n * @throws {UblParseError} when the XML is malformed, not a UBL invoice, or\n * lacks a mandatory element.\n */\nexport const normalizeUblResponse = (\n\txml: string,\n\tdocumentId: string,\n): {\n\textracted: InvoiceExtractionDTO;\n\trawPayload: Record<string, unknown>;\n} => {\n\tconst ubl = parseUblInvoice(xml);\n\tif (!ubl) {\n\t\tthrow new UblParseError(\"Document is not a UBL Invoice or CreditNote\");\n\t}\n\n\tconst subtotal =\n\t\ttoNumberOrNull(ubl.monetaryTotal.taxExclusiveAmount) ??\n\t\ttoNumberOrNull(ubl.monetaryTotal.lineExtensionAmount);\n\tconst total =\n\t\ttoNumberOrNull(ubl.monetaryTotal.taxInclusiveAmount) ??\n\t\ttoNumberOrNull(ubl.monetaryTotal.payableAmount);\n\tconst amountDue = toNumberOrNull(ubl.monetaryTotal.payableAmount);\n\tconst prepaidAmount = toNumberOrNull(ubl.monetaryTotal.prepaidAmount);\n\tconst roundingAmount = toNumberOrNull(ubl.monetaryTotal.payableRoundingAmount) ?? 0;\n\t// BR-CO-16: payable = total - prepaid + rounding. With no declared\n\t// PrepaidAmount we invert that to infer what was paid, but the rounding\n\t// term has to come out first — a cash-rounded payable (BT-114) is a\n\t// total-vs-payable gap by design, and reading it as a prepayment reports\n\t// an unpaid invoice as partially settled. Rounded before the sign test so\n\t// the float residue of undoing it cannot pass as a sub-cent prepayment.\n\tconst inferredPaid =\n\t\ttotal !== null && amountDue !== null\n\t\t\t? roundToCents(total - (amountDue - roundingAmount))\n\t\t\t: null;\n\tconst amountPaid =\n\t\tprepaidAmount ??\n\t\t(inferredPaid !== null && inferredPaid > 0 ? inferredPaid : null);\n\tconst taxTotal = toNumberOrNull(sumTaxTotal(ubl) ?? undefined);\n\tconst hasHeaderAllowanceCharges = (ubl.allowanceCharges?.length ?? 0) > 0;\n\tconst headerDiscountTotal = sumAllowanceChargesByType(ubl.allowanceCharges, false);\n\tconst headerChargeTotal = sumAllowanceChargesByType(ubl.allowanceCharges, true);\n\tconst currency = normalizeCurrency(ubl.currency);\n\tconst paymentTerms = normalizeText(ubl.paymentTermsNote);\n\tconst poNumber =\n\t\tnormalizeText(ubl.orderReference) ?? normalizeText(ubl.salesOrderId);\n\n\tconst lineItems = ubl.lines.map((line) => ({\n\t\tdescription:\n\t\t\tnormalizeText(line.description) ??\n\t\t\tnormalizeText(line.itemName) ??\n\t\t\t\"Line item\",\n\t\tquantity: toNumberOrNull(line.quantity),\n\t\tunit: normalizeText(line.unitCode),\n\t\tunit_price: toNumberOrNull(line.unitPrice),\n\t\tamount: toNumberOrNull(line.lineExtensionAmount),\n\t\ttax_amount: toNumberOrNull(line.taxAmount),\n\t\ttax_rate: toNumberOrNull(line.taxCategory?.percent),\n\t\tproduct_code:\n\t\t\tnormalizeText(line.sellersItemId) ?? normalizeText(line.buyersItemId),\n\t\tdiscount_amount: toNumberOrNull(line.discountAmount),\n\t\tperiod_start: parseDate(line.invoicePeriod?.startDate),\n\t\tperiod_end: parseDate(line.invoicePeriod?.endDate),\n\t\textra: {\n\t\t\tubl_line_id: normalizeText(line.id),\n\t\t\titem_name: normalizeText(line.itemName),\n\t\t\tsellers_item_id: normalizeText(line.sellersItemId),\n\t\t\tbuyers_item_id: normalizeText(line.buyersItemId),\n\t\t\ttax_category_id: normalizeText(line.taxCategory?.id),\n\t\t\ttax_scheme_id: normalizeText(line.taxCategory?.schemeId),\n\t\t\ttax_subtotals: line.taxSubtotals ?? [],\n\t\t\tallowance_charges: sanitizeAllowanceCharges([\n\t\t\t\t...(line.allowanceCharges ?? []),\n\t\t\t\t...(line.priceAllowance\n\t\t\t\t\t? [{ chargeIndicator: false, ...line.priceAllowance }]\n\t\t\t\t\t: []),\n\t\t\t]),\n\t\t\tcharge_amount: toNumberOrNull(line.chargeAmount),\n\t\t\tmetadata: line.additionalItemProperties\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tline.additionalItemProperties.map((p) => [p.name, p.value]),\n\t\t\t\t\t)\n\t\t\t\t: null,\n\t\t},\n\t}));\n\n\tconst supplierAddress = addressToString(ubl.seller.address);\n\tconst receiverAddress = addressToString(ubl.buyer.address);\n\tconst supplierAddressStructured = addressToStructured(ubl.seller.address);\n\tconst receiverAddressStructured = addressToStructured(ubl.buyer.address);\n\tconst attachmentMetadata = sanitizeAttachments(ubl.attachments);\n\tconst paymentMeansList =\n\t\tubl.paymentMeansList && ubl.paymentMeansList.length > 0\n\t\t\t? ubl.paymentMeansList\n\t\t\t: ubl.paymentMeans\n\t\t\t\t? [ubl.paymentMeans]\n\t\t\t\t: [];\n\n\tconst extracted: InvoiceExtractionDTO = {\n\t\tprovider: \"ubl_xml\",\n\t\tdocument_id: documentId,\n\t\tinvoice: {\n\t\t\tinvoice_number: normalizeText(ubl.id),\n\t\t\tinvoice_date: parseDate(ubl.issueDate),\n\t\t\tdue_date: parseDate(ubl.dueDate),\n\t\t\tperiod_start: parseDate(ubl.invoicePeriod?.startDate),\n\t\t\tperiod_end: parseDate(ubl.invoicePeriod?.endDate),\n\t\t\tcurrency,\n\t\t\tsubtotal,\n\t\t\ttax_total: taxTotal,\n\t\t\ttotal,\n\t\t\tamount_due: amountDue,\n\t\t\tamount_paid: amountPaid,\n\t\t\tdiscount_total:\n\t\t\t\ttoNumberOrNull(ubl.monetaryTotal.allowanceTotalAmount) ??\n\t\t\t\t(hasHeaderAllowanceCharges\n\t\t\t\t\t? toNumberOrNull(headerDiscountTotal)\n\t\t\t\t\t: null),\n\t\t\tshipping_total:\n\t\t\t\ttoNumberOrNull(ubl.monetaryTotal.chargeTotalAmount) ??\n\t\t\t\t(hasHeaderAllowanceCharges ? toNumberOrNull(headerChargeTotal) : null),\n\t\t\trounding_total: toNumberOrNull(ubl.monetaryTotal.payableRoundingAmount),\n\t\t\tpayment_terms: paymentTerms,\n\t\t\tpo_number: poNumber,\n\t\t\tsupplier: {\n\t\t\t\tname:\n\t\t\t\t\tnormalizeText(ubl.seller.name) ??\n\t\t\t\t\tnormalizeText(ubl.seller.registrationName),\n\t\t\t\taddress: supplierAddress,\n\t\t\t\ttax_id:\n\t\t\t\t\tnormalizeText(ubl.seller.vatId) ??\n\t\t\t\t\tnormalizeText(ubl.seller.companyId?.value),\n\t\t\t\tiban: normalizeText(ubl.paymentMeans?.iban),\n\t\t\t\tbic: normalizeText(ubl.paymentMeans?.bic),\n\t\t\t},\n\t\t\treceiver: {\n\t\t\t\tname:\n\t\t\t\t\tnormalizeText(ubl.buyer.name) ??\n\t\t\t\t\tnormalizeText(ubl.buyer.registrationName),\n\t\t\t\taddress: receiverAddress,\n\t\t\t\ttax_id:\n\t\t\t\t\tnormalizeText(ubl.buyer.vatId) ??\n\t\t\t\t\tnormalizeText(ubl.buyer.companyId?.value),\n\t\t\t},\n\t\t\textra: {\n\t\t\t\tdocument_type: ubl.documentType,\n\t\t\t\tcustomization_id: normalizeText(ubl.customizationId),\n\t\t\t\tprofile_id: normalizeText(ubl.profileId),\n\t\t\t\tinvoice_type_code: normalizeText(ubl.invoiceTypeCode),\n\t\t\t\tbuyer_reference: normalizeText(ubl.buyerReference),\n\t\t\t\torder_reference_id: normalizeText(ubl.orderReference),\n\t\t\t\tsales_order_id: normalizeText(ubl.salesOrderId),\n\t\t\t\tcontract_reference: normalizeText(ubl.contractReference),\n\t\t\t\tproject_reference: normalizeText(ubl.projectReference),\n\t\t\t\tbilling_reference: ubl.billingReference\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tinvoice_id: normalizeText(ubl.billingReference.invoiceId),\n\t\t\t\t\t\t\tinvoice_issue_date: parseDate(\n\t\t\t\t\t\t\t\tubl.billingReference.invoiceIssueDate,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\ttax_point_date: parseDate(ubl.taxPointDate),\n\t\t\t\tinvoice_period: ubl.invoicePeriod ?? null,\n\t\t\t\tnote: normalizeText(ubl.note),\n\t\t\t\tpayment_means: ubl.paymentMeans\n\t\t\t\t\t? sanitizePaymentMeans(ubl.paymentMeans)\n\t\t\t\t\t: null,\n\t\t\t\tpayment_means_list: paymentMeansList.map(sanitizePaymentMeans),\n\t\t\t\tdelivery: ubl.delivery\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tactual_delivery_date: parseDate(\n\t\t\t\t\t\t\t\tubl.delivery.actualDeliveryDate,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\taddress: addressToStructured(ubl.delivery.address),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\tsupplier: {\n\t\t\t\t\tendpoint_id: normalizeText(ubl.seller.endpoint?.value),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.seller.endpoint?.scheme),\n\t\t\t\t\tregistration_name: normalizeText(ubl.seller.registrationName),\n\t\t\t\t\tcompany_legal_form: normalizeText(ubl.seller.companyLegalForm),\n\t\t\t\t\tcompany_id_scheme_id: normalizeText(ubl.seller.companyId?.scheme),\n\t\t\t\t\ttax_scheme_id: normalizeText(ubl.seller.taxSchemeId),\n\t\t\t\t\tparty_identifications: ubl.seller.partyIdentifications ?? [],\n\t\t\t\t\tcontact_name: normalizeText(ubl.seller.contact?.name),\n\t\t\t\t\tcontact_phone: normalizeText(ubl.seller.contact?.phone),\n\t\t\t\t\tcontact_email: normalizeText(ubl.seller.contact?.email),\n\t\t\t\t},\n\t\t\t\treceiver: {\n\t\t\t\t\tendpoint_id: normalizeText(ubl.buyer.endpoint?.value),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.buyer.endpoint?.scheme),\n\t\t\t\t\tregistration_name: normalizeText(ubl.buyer.registrationName),\n\t\t\t\t\tcompany_legal_form: normalizeText(ubl.buyer.companyLegalForm),\n\t\t\t\t\tcompany_id_scheme_id: normalizeText(ubl.buyer.companyId?.scheme),\n\t\t\t\t\ttax_scheme_id: normalizeText(ubl.buyer.taxSchemeId),\n\t\t\t\t\tparty_identifications: ubl.buyer.partyIdentifications ?? [],\n\t\t\t\t\tcontact_name: normalizeText(ubl.buyer.contact?.name),\n\t\t\t\t\tcontact_phone: normalizeText(ubl.buyer.contact?.phone),\n\t\t\t\t\tcontact_email: normalizeText(ubl.buyer.contact?.email),\n\t\t\t\t},\n\t\t\t\tsupplier_address_structured: supplierAddressStructured,\n\t\t\t\treceiver_address_structured: receiverAddressStructured,\n\t\t\t\ttax_subtotals: ubl.taxTotal.subtotals,\n\t\t\t\tallowance_charges: sanitizeAllowanceCharges(ubl.allowanceCharges),\n\t\t\t\tattachments: attachmentMetadata,\n\t\t\t\tdocument_references: ubl.documentReferences ?? [],\n\t\t\t},\n\t\t},\n\t\tline_items: lineItems,\n\t\tconfidence: {\n\t\t\toverall: 1,\n\t\t\tfields: {\n\t\t\t\tinvoice_id: 1,\n\t\t\t\tinvoice_date: 1,\n\t\t\t\tdue_date: 1,\n\t\t\t\ttotal_amount: 1,\n\t\t\t\tsupplier_name: 1,\n\t\t\t},\n\t\t},\n\t};\n\n\treturn {\n\t\textracted,\n\t\trawPayload: {\n\t\t\tformat: \"ubl_xml\",\n\t\t\tinvoice: sanitizeRawUbl(ubl),\n\t\t},\n\t};\n};\n\n/**\n * Parse a UBL invoice from raw bytes and normalize it into a DTO.\n */\nexport const parseUblInvoiceDocument = (params: {\n\tbytes: Uint8Array;\n\tdocumentId: string;\n\tmimeType: string;\n}) => {\n\tconst xml = decodeXmlBytes(params.bytes);\n\tconst { extracted, rawPayload } = normalizeUblResponse(xml, params.documentId);\n\treturn {\n\t\trawPayload: {\n\t\t\t...rawPayload,\n\t\t\tmime_type: params.mimeType,\n\t\t},\n\t\textracted,\n\t\tproviderJobId: null as string | null,\n\t};\n};\n"],"mappings":";;;AAGA,MAAa,SACZ;AACD,MAAa,SACZ;;;;;;AAOD,MAAa,gBAAgB,QAC5B,IAAI,QAAQ,uCAAuC,EAAE;;;;;;AAOtD,MAAa,oBAAoB,QAA0B;CAC1D,MAAM,UAAU,aAAa,GAAG;CAChC,MAAM,mBAAoB,WACxB;CACF,MAAM,SAAS,mBAAmB,IAAI,iBAAiB,IAAI,IAAIA,UAAa;CAC5E,IAAI;CACJ,IAAI;EACH,MAAM,OAAO,gBAAgB,SAAS,UAAU;CACjD,SAAS,OAAO;EACf,MAAM,IAAI,cAAc,iBAAiB,E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}
1
+ {"version":3,"file":"index.js","names":["XmlDomParser","trimmed","cbcText","cacElement","cbcDirectText"],"sources":["../src/xml-dom.ts","../src/parser.ts","../src/attachments.ts","../src/mlr.ts","../src/normalize.ts"],"sourcesContent":["import { type Document, DOMParser as XmlDomParser } from \"@xmldom/xmldom\";\nimport { UblParseError } from \"./errors.js\";\n\nexport const CBC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\nexport const CAC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\n\n/**\n * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.\n * @xmldom/xmldom resolves external entities by default, so we remove DOCTYPE\n * blocks (including inline DTD subsets) before parsing.\n */\nexport const stripDoctype = (xml: string): string =>\n\txml.replace(/<!DOCTYPE\\s[^>[]*(?:\\[[^\\]]*\\])?>/gi, \"\");\n\n/**\n * Parse XML into a DOM, preferring the host's `DOMParser` (browsers) and\n * falling back to @xmldom/xmldom. Throws {@link UblParseError} when the XML\n * is malformed.\n */\nexport const parseXmlDocument = (xml: string): Document => {\n\tconst safeXml = stripDoctype(xml);\n\tconst BrowserDomParser = (globalThis as { DOMParser?: typeof XmlDomParser })\n\t\t.DOMParser;\n\tconst parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();\n\tlet doc: Document;\n\ttry {\n\t\tdoc = parser.parseFromString(safeXml, \"text/xml\");\n\t} catch (cause) {\n\t\tthrow new UblParseError(\"Malformed XML\", { cause });\n\t}\n\tif (doc.getElementsByTagName(\"parsererror\").length > 0 || !doc.documentElement) {\n\t\tthrow new UblParseError(\"Malformed XML\");\n\t}\n\treturn doc;\n};\n","import type { Element } from \"@xmldom/xmldom\";\nimport type {\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblBillingReference,\n\tUblCommodityClassification,\n\tUblContact,\n\tUblDelivery,\n\tUblDocumentReference,\n\tUblInvoice,\n\tUblInvoicePeriod,\n\tUblItemProperty,\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblParty,\n\tUblPartyIdentification,\n\tUblPaymentMeans,\n\tUblSchemedId,\n\tUblTaxCategory,\n\tUblTaxSubtotal,\n\tUblTaxTotal,\n} from \"./types.js\";\nimport { UblParseError } from \"./errors.js\";\nimport { CAC_NS, CBC_NS, parseXmlDocument } from \"./xml-dom.js\";\n\n// --- DOM helpers ---\n\nconst trimmed = (value: string | null | undefined): string | undefined => {\n\tconst text = value?.trim();\n\treturn text ? text : undefined;\n};\n\n/** First descendant CBC element's trimmed text; absent or blank is `undefined`. */\nfunction cbcText(parent: Element, tag: string): string | undefined {\n\treturn trimmed(parent.getElementsByTagNameNS(CBC_NS, tag)[0]?.textContent);\n}\n\n/** Like {@link cbcText} but throws: the element is mandatory in EN 16931. */\nfunction requiredCbcText(parent: Element, tag: string, what: string): string {\n\tconst value = cbcText(parent, tag);\n\tif (value === undefined) throw new UblParseError(`Missing ${what} (cbc:${tag})`);\n\treturn value;\n}\n\nconst toNumber = (value: string | undefined): number | undefined => {\n\tif (value === undefined) return undefined;\n\tconst parsed = Number.parseFloat(value);\n\treturn Number.isNaN(parsed) ? undefined : parsed;\n};\n\nfunction cacElement(parent: Element, tag: string): Element | null {\n\treturn parent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;\n}\n\nfunction cacElements(parent: Element, tag: string): Element[] {\n\treturn Array.from(parent.getElementsByTagNameNS(CAC_NS, tag));\n}\n\n/** First descendant CBC element as a number; absent or non-numeric is `undefined`. */\nfunction cbcNumber(parent: Element, tag: string): number | undefined {\n\treturn toNumber(cbcText(parent, tag));\n}\n\nfunction childElementsByTagNs(\n\tparent: Element,\n\tnamespace: string,\n\ttag: string,\n): Element[] {\n\tconst elements: Element[] = [];\n\tfor (let i = 0; i < parent.childNodes.length; i++) {\n\t\tconst node = parent.childNodes[i];\n\t\tif (!node || node.nodeType !== 1) continue;\n\t\tconst element = node as Element;\n\t\tif (element.namespaceURI === namespace && element.localName === tag) {\n\t\t\telements.push(element);\n\t\t}\n\t}\n\treturn elements;\n}\n\nfunction cbcDirectText(parent: Element, tag: string): string | undefined {\n\treturn trimmed(childElementsByTagNs(parent, CBC_NS, tag)[0]?.textContent);\n}\n\nfunction cbcDirectNumber(parent: Element, tag: string): number | undefined {\n\treturn toNumber(cbcDirectText(parent, tag));\n}\n\nconst attribute = (el: Element | null | undefined, name: string): string | undefined =>\n\ttrimmed(el?.getAttribute(name));\n\n/** A direct `cbc:<tag>` child with its `@schemeID`. */\nfunction cbcDirectSchemedId(parent: Element, tag: string): UblSchemedId | undefined {\n\tconst element = childElementsByTagNs(parent, CBC_NS, tag)[0];\n\tconst value = trimmed(element?.textContent);\n\treturn value !== undefined\n\t\t? { value, scheme: attribute(element, \"schemeID\") }\n\t\t: undefined;\n}\n\nfunction cacDirectElement(parent: Element, tag: string): Element | null {\n\treturn childElementsByTagNs(parent, CAC_NS, tag)[0] ?? null;\n}\n\nfunction cacDirectElements(parent: Element, tag: string): Element[] {\n\treturn childElementsByTagNs(parent, CAC_NS, tag);\n}\n\n// --- Section parsers ---\n\nfunction parseAddressFromElement(address: Element | null): UblAddress | undefined {\n\tif (!address) return undefined;\n\tconst country = cacElement(address, \"Country\");\n\treturn {\n\t\tstreet: cbcText(address, \"StreetName\"),\n\t\tadditionalStreet: cbcText(address, \"AdditionalStreetName\"),\n\t\tcity: cbcText(address, \"CityName\"),\n\t\tpostalZone: cbcText(address, \"PostalZone\"),\n\t\tcountrySubentity: cbcText(address, \"CountrySubentity\"),\n\t\tcountryCode: country ? cbcText(country, \"IdentificationCode\") : undefined,\n\t};\n}\n\nfunction parseAddress(party: Element): UblAddress | undefined {\n\tconst postal = cacElement(party, \"PostalAddress\");\n\treturn parseAddressFromElement(postal);\n}\n\nfunction parseTaxSchemeId(parent: Element | null): string | undefined {\n\tif (!parent) return undefined;\n\tconst taxScheme = cacElement(parent, \"TaxScheme\");\n\tif (!taxScheme) return undefined;\n\treturn cbcText(taxScheme, \"ID\");\n}\n\nfunction parseContact(party: Element): UblContact | undefined {\n\tconst contact = cacElement(party, \"Contact\");\n\tif (!contact) return undefined;\n\tconst name = cbcText(contact, \"Name\");\n\tconst phone = cbcText(contact, \"Telephone\");\n\tconst email = cbcText(contact, \"ElectronicMail\");\n\tif (!name && !phone && !email) return undefined;\n\treturn { name, phone, email };\n}\n\nfunction parsePartyIdentifications(party: Element): UblPartyIdentification[] {\n\tconst ids = cacElements(party, \"PartyIdentification\");\n\tconst result: UblPartyIdentification[] = [];\n\tfor (const idEl of ids) {\n\t\tconst idValue = cbcText(idEl, \"ID\");\n\t\tif (!idValue) continue;\n\t\tresult.push({\n\t\t\tid: idValue,\n\t\t\tschemeId: attribute(\n\t\t\t\tidEl.getElementsByTagNameNS(CBC_NS, \"ID\")[0],\n\t\t\t\t\"schemeID\",\n\t\t\t),\n\t\t});\n\t}\n\treturn result;\n}\n\nfunction parseParty(root: Element, role: string): UblParty {\n\tconst wrapper = cacDirectElement(root, role);\n\tconst party = wrapper ? cacElement(wrapper, \"Party\") : null;\n\treturn party ? parsePartyElement(party) : {};\n}\n\n/**\n * `cac:PayeeParty` (BG-10) and `cac:TaxRepresentativeParty` (BG-11) carry the\n * party children directly, without a `cac:Party` wrapper.\n */\nfunction parseUnwrappedParty(root: Element, tag: string): UblParty | undefined {\n\tconst party = cacDirectElement(root, tag);\n\tif (!party) return undefined;\n\tconst parsed = parsePartyElement(party);\n\treturn Object.values(parsed).some((value) => value !== undefined)\n\t\t? parsed\n\t\t: undefined;\n}\n\nfunction parsePartyElement(party: Element): UblParty {\n\tconst partyName = cacElement(party, \"PartyName\");\n\tconst legalEntity = cacElement(party, \"PartyLegalEntity\");\n\tconst taxScheme = cacElement(party, \"PartyTaxScheme\");\n\tconst partyId = cacElement(party, \"PartyIdentification\");\n\tconst endpointEl = party.getElementsByTagNameNS(CBC_NS, \"EndpointID\")[0];\n\tconst partyIdentifications = parsePartyIdentifications(party);\n\tconst companyIdEl = legalEntity\n\t\t? legalEntity.getElementsByTagNameNS(CBC_NS, \"CompanyID\")[0]\n\t\t: null;\n\n\tconst endpointValue = trimmed(endpointEl?.textContent);\n\tconst companyIdValue = companyIdEl\n\t\t? trimmed(companyIdEl.textContent)\n\t\t: partyId\n\t\t\t? cbcText(partyId, \"ID\")\n\t\t\t: undefined;\n\n\treturn {\n\t\tname: partyName ? cbcText(partyName, \"Name\") : undefined,\n\t\tregistrationName: legalEntity\n\t\t\t? cbcText(legalEntity, \"RegistrationName\")\n\t\t\t: undefined,\n\t\tcompanyLegalForm: legalEntity\n\t\t\t? cbcText(legalEntity, \"CompanyLegalForm\")\n\t\t\t: undefined,\n\t\tvatId: taxScheme ? cbcText(taxScheme, \"CompanyID\") : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(taxScheme),\n\t\tcompanyId:\n\t\t\tcompanyIdValue !== undefined\n\t\t\t\t? { value: companyIdValue, scheme: attribute(companyIdEl, \"schemeID\") }\n\t\t\t\t: undefined,\n\t\tendpoint:\n\t\t\tendpointValue !== undefined\n\t\t\t\t? { value: endpointValue, scheme: attribute(endpointEl, \"schemeID\") }\n\t\t\t\t: undefined,\n\t\tpartyIdentifications:\n\t\t\tpartyIdentifications.length > 0 ? partyIdentifications : undefined,\n\t\taddress: parseAddress(party),\n\t\tcontact: parseContact(party),\n\t};\n}\n\n/**\n * `cac:TaxCategory` / `cac:ClassifiedTaxCategory`. Emitted whenever the\n * element states anything; `percentFallback` covers the E-FFF habit of putting\n * `cbc:Percent` on the subtotal instead of inside the category.\n */\nfunction parseTaxCategory(\n\tcat: Element | null,\n\tpercentFallback?: Element,\n): UblTaxCategory | undefined {\n\tconst percentFromParent = percentFallback\n\t\t? cbcDirectNumber(percentFallback, \"Percent\")\n\t\t: undefined;\n\tif (!cat) {\n\t\treturn percentFromParent !== undefined\n\t\t\t? { percent: percentFromParent }\n\t\t\t: undefined;\n\t}\n\tconst category: UblTaxCategory = {\n\t\tid: cbcText(cat, \"ID\"),\n\t\tpercent: cbcNumber(cat, \"Percent\") ?? percentFromParent,\n\t\tschemeId: parseTaxSchemeId(cat),\n\t\texemptionReason: cbcText(cat, \"TaxExemptionReason\"),\n\t\texemptionReasonCode: cbcText(cat, \"TaxExemptionReasonCode\"),\n\t};\n\treturn Object.values(category).some((value) => value !== undefined)\n\t\t? category\n\t\t: undefined;\n}\n\nfunction parseTaxSubtotal(sub: Element): UblTaxSubtotal {\n\treturn {\n\t\ttaxableAmount: cbcNumber(sub, \"TaxableAmount\"),\n\t\ttaxAmount: cbcNumber(sub, \"TaxAmount\"),\n\t\tcategory: parseTaxCategory(cacElement(sub, \"TaxCategory\"), sub),\n\t};\n}\n\nfunction parseTaxSubtotalsFromTaxTotal(taxTotal: Element): UblTaxSubtotal[] {\n\treturn cacDirectElements(taxTotal, \"TaxSubtotal\").map(parseTaxSubtotal);\n}\n\n/**\n * `cac:TaxTotal` (BG-22). BT-110 is read from the first `cac:TaxTotal` as\n * stated, never summed from the subtotals; the subtotals of every `TaxTotal`\n * (a second one carries the accounting-currency figure) are concatenated.\n */\nfunction parseTaxTotal(root: Element): UblTaxTotal {\n\tconst taxTotals = cacDirectElements(root, \"TaxTotal\");\n\tconst first = taxTotals[0];\n\tconst second = taxTotals[1];\n\treturn {\n\t\ttaxAmount: first ? cbcDirectNumber(first, \"TaxAmount\") : undefined,\n\t\tsubtotals: taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal),\n\t\ttaxAmountInTaxCurrency: second\n\t\t\t? cbcDirectNumber(second, \"TaxAmount\")\n\t\t\t: undefined,\n\t};\n}\n\nfunction parseAllowanceCharge(charge: Element): UblAllowanceCharge {\n\tconst taxCategory = cacElement(charge, \"TaxCategory\");\n\tconst indicatorRaw = cbcDirectText(charge, \"ChargeIndicator\")?.toLowerCase();\n\tconst chargeIndicator = indicatorRaw === \"true\" || indicatorRaw === \"1\";\n\treturn {\n\t\tchargeIndicator,\n\t\tamount: cbcNumber(charge, \"Amount\"),\n\t\tbaseAmount: cbcDirectNumber(charge, \"BaseAmount\"),\n\t\tmultiplierFactorNumeric: cbcDirectNumber(charge, \"MultiplierFactorNumeric\"),\n\t\treason: cbcText(charge, \"AllowanceChargeReason\"),\n\t\treasonCode: cbcText(charge, \"AllowanceChargeReasonCode\"),\n\t\ttaxCategory: parseTaxCategory(taxCategory),\n\t};\n}\n\nfunction parseAllowanceCharges(parent: Element): UblAllowanceCharge[] {\n\treturn cacDirectElements(parent, \"AllowanceCharge\").map(parseAllowanceCharge);\n}\n\nfunction mergeTaxCategories(\n\tpreferred: UblTaxCategory | undefined,\n\tfallback: UblTaxCategory | undefined,\n): UblTaxCategory | undefined {\n\tif (!preferred) return fallback;\n\tif (!fallback) return preferred;\n\treturn {\n\t\tid: preferred.id ?? fallback.id,\n\t\tpercent: preferred.percent ?? fallback.percent,\n\t\tschemeId: preferred.schemeId ?? fallback.schemeId,\n\t\texemptionReason: preferred.exemptionReason ?? fallback.exemptionReason,\n\t\texemptionReasonCode:\n\t\t\tpreferred.exemptionReasonCode ?? fallback.exemptionReasonCode,\n\t};\n}\n\nfunction parseLines(root: Element, isCreditNote: boolean): UblLine[] {\n\tconst qtyTag = isCreditNote ? \"CreditedQuantity\" : \"InvoicedQuantity\";\n\tconst lineTag = isCreditNote ? \"CreditNoteLine\" : \"InvoiceLine\";\n\n\treturn cacElements(root, lineTag).map((line) => {\n\t\tconst item = cacElement(line, \"Item\");\n\t\tconst price = cacElement(line, \"Price\");\n\t\tconst classifiedCategory = parseTaxCategory(\n\t\t\titem ? cacElement(item, \"ClassifiedTaxCategory\") : null,\n\t\t);\n\t\tconst sellersId = item ? cacElement(item, \"SellersItemIdentification\") : null;\n\t\tconst buyersId = item ? cacElement(item, \"BuyersItemIdentification\") : null;\n\t\tconst qtyEl = line.getElementsByTagNameNS(CBC_NS, qtyTag)[0];\n\t\tconst lineExtensionAmount = cbcNumber(line, \"LineExtensionAmount\");\n\t\tconst lineTaxTotal = cacDirectElement(line, \"TaxTotal\");\n\t\tconst lineTaxSubtotals = lineTaxTotal\n\t\t\t? parseTaxSubtotalsFromTaxTotal(lineTaxTotal)\n\t\t\t: [];\n\t\tconst taxAmountFromSubtotals = lineTaxSubtotals.reduce(\n\t\t\t(sum, subtotal) => sum + (subtotal.taxAmount ?? 0),\n\t\t\t0,\n\t\t);\n\t\tconst taxAmountFromLineTotal = lineTaxTotal\n\t\t\t? cbcDirectNumber(lineTaxTotal, \"TaxAmount\")\n\t\t\t: undefined;\n\t\t// A line-level TaxSubtotal (E-FFF) wins over the classified category,\n\t\t// field by field.\n\t\tconst subtotalCategory = lineTaxSubtotals[0]?.category;\n\t\tconst taxCategory = mergeTaxCategories(subtotalCategory, classifiedCategory);\n\t\tconst taxPercent = taxCategory?.percent;\n\t\tconst computedTaxAmount =\n\t\t\ttaxPercent !== undefined && lineExtensionAmount !== undefined\n\t\t\t\t? Number(((lineExtensionAmount * taxPercent) / 100).toFixed(2))\n\t\t\t\t: undefined;\n\t\tconst allowanceCharges = parseAllowanceCharges(line);\n\t\t// BT-147/BT-148: the one allowance UBL permits under cac:Price.\n\t\tconst priceAllowanceElement = price\n\t\t\t? parseAllowanceCharges(price).find((charge) => !charge.chargeIndicator)\n\t\t\t: undefined;\n\t\tconst priceAllowance = priceAllowanceElement\n\t\t\t? {\n\t\t\t\t\tamount: priceAllowanceElement.amount,\n\t\t\t\t\tbaseAmount: priceAllowanceElement.baseAmount,\n\t\t\t\t\treason: priceAllowanceElement.reason,\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tconst discountAmount =\n\t\t\tallowanceCharges.reduce(\n\t\t\t\t(sum, charge) =>\n\t\t\t\t\tcharge.chargeIndicator ? sum : sum + Math.abs(charge.amount ?? 0),\n\t\t\t\t0,\n\t\t\t) + Math.abs(priceAllowance?.amount ?? 0);\n\t\tconst chargeAmount = allowanceCharges.reduce(\n\t\t\t(sum, charge) =>\n\t\t\t\tcharge.chargeIndicator ? sum + Math.abs(charge.amount ?? 0) : sum,\n\t\t\t0,\n\t\t);\n\n\t\tconst additionalItemProperties: UblItemProperty[] = [];\n\t\tif (item) {\n\t\t\tfor (const prop of cacElements(item, \"AdditionalItemProperty\")) {\n\t\t\t\tconst propName = cbcText(prop, \"Name\");\n\t\t\t\tconst propValue = cbcText(prop, \"Value\");\n\t\t\t\tif (propName) {\n\t\t\t\t\tadditionalItemProperties.push({\n\t\t\t\t\t\tname: propName,\n\t\t\t\t\t\tvalue: propValue,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// EN16931 BT-146 (PriceAmount) is the price for BT-149 (BaseQuantity) units\n\t\t// of the item, not necessarily for one unit. Effective unit price is\n\t\t// PriceAmount / BaseQuantity, with BaseQuantity defaulting to 1 when absent.\n\t\tconst priceAmount = price ? cbcNumber(price, \"PriceAmount\") : undefined;\n\t\tconst priceBaseQuantity = price\n\t\t\t? cbcDirectNumber(price, \"BaseQuantity\")\n\t\t\t: undefined;\n\t\tconst unitPrice =\n\t\t\tpriceAmount !== undefined && priceBaseQuantity && priceBaseQuantity > 0\n\t\t\t\t? priceAmount / priceBaseQuantity\n\t\t\t\t: priceAmount;\n\n\t\tconst orderLineReference = cacDirectElement(line, \"OrderLineReference\");\n\t\tconst lineDocumentReference = cacDirectElements(line, \"DocumentReference\").find(\n\t\t\t(reference) => cbcDirectText(reference, \"DocumentTypeCode\") === \"130\",\n\t\t);\n\t\tconst standardId = item\n\t\t\t? cacDirectElement(item, \"StandardItemIdentification\")\n\t\t\t: null;\n\t\tconst originCountry = item ? cacDirectElement(item, \"OriginCountry\") : null;\n\t\tconst commodityClassifications: UblCommodityClassification[] = [];\n\t\tfor (const classification of item\n\t\t\t? cacDirectElements(item, \"CommodityClassification\")\n\t\t\t: []) {\n\t\t\tconst codeElement = childElementsByTagNs(\n\t\t\t\tclassification,\n\t\t\t\tCBC_NS,\n\t\t\t\t\"ItemClassificationCode\",\n\t\t\t)[0];\n\t\t\tconst value = trimmed(codeElement?.textContent);\n\t\t\tif (value === undefined) continue;\n\t\t\tcommodityClassifications.push({\n\t\t\t\tvalue,\n\t\t\t\tlistId: attribute(codeElement, \"listID\"),\n\t\t\t\tlistVersionId: attribute(codeElement, \"listVersionID\"),\n\t\t\t});\n\t\t}\n\n\t\treturn {\n\t\t\tid: requiredCbcText(line, \"ID\", `${lineTag} identifier`),\n\t\t\tnote: cbcDirectText(line, \"Note\"),\n\t\t\tobjectIdentifier: lineDocumentReference\n\t\t\t\t? cbcDirectSchemedId(lineDocumentReference, \"ID\")\n\t\t\t\t: undefined,\n\t\t\torderLineReference: orderLineReference\n\t\t\t\t? cbcDirectText(orderLineReference, \"LineID\")\n\t\t\t\t: undefined,\n\t\t\taccountingCost: cbcDirectText(line, \"AccountingCost\"),\n\t\t\tdescription: item ? cbcText(item, \"Description\") : undefined,\n\t\t\tquantity: cbcNumber(line, qtyTag),\n\t\t\tunitCode: attribute(qtyEl, \"unitCode\"),\n\t\t\tunitPrice,\n\t\t\tlineExtensionAmount,\n\t\t\tbaseQuantity: priceBaseQuantity,\n\t\t\ttaxCategory,\n\t\t\ttaxAmount:\n\t\t\t\ttaxAmountFromLineTotal ??\n\t\t\t\t(lineTaxSubtotals.length > 0\n\t\t\t\t\t? taxAmountFromSubtotals\n\t\t\t\t\t: computedTaxAmount),\n\t\t\ttaxSubtotals: lineTaxSubtotals.length > 0 ? lineTaxSubtotals : undefined,\n\t\t\tallowanceCharges:\n\t\t\t\tallowanceCharges.length > 0 ? allowanceCharges : undefined,\n\t\t\tpriceAllowance,\n\t\t\tdiscountAmount: discountAmount > 0 ? discountAmount : undefined,\n\t\t\tchargeAmount: chargeAmount > 0 ? chargeAmount : undefined,\n\t\t\titemName: item ? cbcText(item, \"Name\") : undefined,\n\t\t\tsellersItemId: sellersId ? cbcText(sellersId, \"ID\") : undefined,\n\t\t\tbuyersItemId: buyersId ? cbcText(buyersId, \"ID\") : undefined,\n\t\t\tstandardItemId: standardId\n\t\t\t\t? cbcDirectSchemedId(standardId, \"ID\")\n\t\t\t\t: undefined,\n\t\t\tcommodityClassifications:\n\t\t\t\tcommodityClassifications.length > 0\n\t\t\t\t\t? commodityClassifications\n\t\t\t\t\t: undefined,\n\t\t\toriginCountryCode: originCountry\n\t\t\t\t? cbcDirectText(originCountry, \"IdentificationCode\")\n\t\t\t\t: undefined,\n\t\t\tadditionalItemProperties:\n\t\t\t\tadditionalItemProperties.length > 0\n\t\t\t\t\t? additionalItemProperties\n\t\t\t\t\t: undefined,\n\t\t\tinvoicePeriod: parseInvoicePeriod(line),\n\t\t};\n\t});\n}\n\nfunction parseMonetaryTotal(root: Element): UblMonetaryTotal {\n\tconst total = cacDirectElement(root, \"LegalMonetaryTotal\");\n\tif (!total) return {};\n\treturn {\n\t\tlineExtensionAmount: cbcNumber(total, \"LineExtensionAmount\"),\n\t\ttaxExclusiveAmount: cbcNumber(total, \"TaxExclusiveAmount\"),\n\t\ttaxInclusiveAmount: cbcNumber(total, \"TaxInclusiveAmount\"),\n\t\tallowanceTotalAmount: cbcNumber(total, \"AllowanceTotalAmount\"),\n\t\tchargeTotalAmount: cbcNumber(total, \"ChargeTotalAmount\"),\n\t\tprepaidAmount: cbcNumber(total, \"PrepaidAmount\"),\n\t\tpayableRoundingAmount: cbcNumber(total, \"PayableRoundingAmount\"),\n\t\tpayableAmount: cbcNumber(total, \"PayableAmount\"),\n\t};\n}\n\nfunction parsePaymentMeansElement(pm: Element): UblPaymentMeans {\n\tconst account = cacElement(pm, \"PayeeFinancialAccount\");\n\tconst branch = account ? cacElement(account, \"FinancialInstitutionBranch\") : null;\n\tconst paymentMeansCodeEl = pm.getElementsByTagNameNS(CBC_NS, \"PaymentMeansCode\")[0];\n\tconst mandate = cacElement(pm, \"PaymentMandate\");\n\tconst debitedAccount = mandate\n\t\t? cacElement(mandate, \"PayerFinancialAccount\")\n\t\t: null;\n\tconst card = cacElement(pm, \"CardAccount\");\n\n\treturn {\n\t\tcode: cbcText(pm, \"PaymentMeansCode\"),\n\t\tcodeName: attribute(paymentMeansCodeEl, \"name\"),\n\t\tpaymentId: cbcText(pm, \"PaymentID\"),\n\t\tiban: account ? cbcText(account, \"ID\") : undefined,\n\t\tbic: branch ? cbcText(branch, \"ID\") : undefined,\n\t\taccountName: account ? cbcText(account, \"Name\") : undefined,\n\t\tmandateId: mandate ? cbcDirectText(mandate, \"ID\") : undefined,\n\t\tdebitedAccount: debitedAccount ? cbcText(debitedAccount, \"ID\") : undefined,\n\t\tcardNumber: card ? cbcText(card, \"PrimaryAccountNumberID\") : undefined,\n\t\tcardHolder: card ? cbcText(card, \"HolderName\") : undefined,\n\t};\n}\n\nfunction parsePaymentMeansList(root: Element): UblPaymentMeans[] | undefined {\n\tconst list = cacElements(root, \"PaymentMeans\").map(parsePaymentMeansElement);\n\treturn list.length > 0 ? list : undefined;\n}\n\n/**\n * BT-73/BT-74 on a document, BT-134/BT-135 on a line. Direct children only:\n * a descendant search on the document root would report the first line's\n * period as the document's whenever the document states none of its own.\n */\nfunction parseInvoicePeriod(parent: Element): UblInvoicePeriod | undefined {\n\tconst period = cacDirectElement(parent, \"InvoicePeriod\");\n\tif (!period) return undefined;\n\n\tconst start = cbcText(period, \"StartDate\");\n\tconst end = cbcText(period, \"EndDate\");\n\tif (!start && !end) return undefined;\n\n\treturn {\n\t\tstartDate: start,\n\t\tendDate: end,\n\t\tdescriptionCode: cbcText(period, \"DescriptionCode\"),\n\t};\n}\n\nfunction parseDelivery(root: Element): UblDelivery | undefined {\n\tconst delivery = cacElement(root, \"Delivery\");\n\tif (!delivery) return undefined;\n\tconst actualDeliveryDate = cbcText(delivery, \"ActualDeliveryDate\");\n\tconst deliveryLocation = cacElement(delivery, \"DeliveryLocation\");\n\tconst locationId = deliveryLocation\n\t\t? cbcDirectSchemedId(deliveryLocation, \"ID\")\n\t\t: undefined;\n\tconst address = parseAddressFromElement(\n\t\tdeliveryLocation ? cacElement(deliveryLocation, \"Address\") : null,\n\t);\n\tconst deliveryParty = cacElement(delivery, \"DeliveryParty\");\n\tconst partyName = deliveryParty ? cbcText(deliveryParty, \"Name\") : undefined;\n\tif (!actualDeliveryDate && !locationId && !address && !partyName) return undefined;\n\treturn {\n\t\tactualDeliveryDate,\n\t\tlocationId,\n\t\taddress,\n\t\tpartyName,\n\t};\n}\n\nfunction parsePaymentTermsNote(root: Element): string | undefined {\n\tconst paymentTerms = cacElement(root, \"PaymentTerms\");\n\tif (!paymentTerms) return undefined;\n\treturn cbcText(paymentTerms, \"Note\");\n}\n\nfunction parseNotes(root: Element): string | undefined {\n\tconst noteEls = root.getElementsByTagNameNS(CBC_NS, \"Note\");\n\tconst notes: string[] = [];\n\tfor (let i = 0; i < noteEls.length; i++) {\n\t\tconst el = noteEls[i];\n\t\tif (!el) continue;\n\t\tif (el.parentElement === root || el.parentNode === root) {\n\t\t\tconst text = el.textContent?.trim();\n\t\t\tif (text) notes.push(text);\n\t\t}\n\t}\n\treturn notes.length > 0 ? notes.join(\"\\n\") : undefined;\n}\n\n/**\n * `cac:AdditionalDocumentReference` (BG-24), plus the two references EN 16931\n * types by `cbc:DocumentTypeCode`: 130 is the invoiced object (BT-18) and 50\n * is the tender or lot (BT-17), which on a credit note stands in for the\n * project reference (BT-11) UBL's CreditNote has no element for.\n */\nfunction parseAttachments(root: Element): {\n\tattachments: UblAttachment[] | undefined;\n\tdocumentReferences: UblDocumentReference[] | undefined;\n\tinvoicedObjectId: UblSchemedId | undefined;\n\ttypeCode50Reference: string | undefined;\n} {\n\tconst refs = cacDirectElements(root, \"AdditionalDocumentReference\");\n\tconst attachments: UblAttachment[] = [];\n\tconst documentReferences: UblDocumentReference[] = [];\n\tlet invoicedObjectId: UblSchemedId | undefined;\n\tlet typeCode50Reference: string | undefined;\n\n\tfor (const ref of refs) {\n\t\tconst attachment = cacElement(ref, \"Attachment\");\n\t\tconst refId = cbcText(ref, \"ID\");\n\t\tconst description = cbcText(ref, \"DocumentDescription\");\n\t\tconst typeCode = cbcDirectText(ref, \"DocumentTypeCode\");\n\n\t\tif (typeCode === \"130\" && !attachment) {\n\t\t\tinvoicedObjectId ??= cbcDirectSchemedId(ref, \"ID\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeCode === \"50\" && !attachment) {\n\t\t\ttypeCode50Reference ??= refId;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!attachment) {\n\t\t\t// Text-only document reference (e.g. terms & conditions, notices)\n\t\t\tif (refId || description) {\n\t\t\t\tdocumentReferences.push({ id: refId, description });\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst binaryEl = attachment.getElementsByTagNameNS(\n\t\t\tCBC_NS,\n\t\t\t\"EmbeddedDocumentBinaryObject\",\n\t\t)[0];\n\t\tconst externalRef = cacElement(attachment, \"ExternalReference\");\n\n\t\tif (binaryEl) {\n\t\t\tconst content = binaryEl.textContent?.trim();\n\t\t\tif (content) {\n\t\t\t\tattachments.push({\n\t\t\t\t\tid: refId,\n\t\t\t\t\tfilename: attribute(binaryEl, \"filename\"),\n\t\t\t\t\tmimeCode: attribute(binaryEl, \"mimeCode\"),\n\t\t\t\t\tdescription,\n\t\t\t\t\tbase64Content: content,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (externalRef) {\n\t\t\tconst uri = cbcText(externalRef, \"URI\");\n\t\t\tif (uri) {\n\t\t\t\tattachments.push({\n\t\t\t\t\tid: refId,\n\t\t\t\t\tdescription,\n\t\t\t\t\texternalUri: uri,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tattachments: attachments.length > 0 ? attachments : undefined,\n\t\tdocumentReferences:\n\t\t\tdocumentReferences.length > 0 ? documentReferences : undefined,\n\t\tinvoicedObjectId,\n\t\ttypeCode50Reference,\n\t};\n}\n\nfunction parseBillingReference(root: Element): UblBillingReference | undefined {\n\tconst billingRef = cacElement(root, \"BillingReference\");\n\tif (!billingRef) return undefined;\n\tconst invoiceRef = cacElement(billingRef, \"InvoiceDocumentReference\");\n\tif (!invoiceRef) return undefined;\n\tconst invoiceId = cbcText(invoiceRef, \"ID\");\n\tconst invoiceIssueDate = cbcText(invoiceRef, \"IssueDate\");\n\tif (!invoiceId && !invoiceIssueDate) return undefined;\n\treturn { invoiceId, invoiceIssueDate };\n}\n\n// --- Main parser ---\n\n/**\n * Drop `undefined`-valued keys recursively so an absent field is an absent\n * key, not a key holding `undefined`. Arrays keep their order and length.\n */\nfunction omitUndefined<T>(value: T): T {\n\tif (Array.isArray(value)) {\n\t\treturn value.map(omitUndefined) as T;\n\t}\n\tif (value !== null && typeof value === \"object\") {\n\t\tconst out: Record<string, unknown> = {};\n\t\tfor (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n\t\t\tif (entry !== undefined) out[key] = omitUndefined(entry);\n\t\t}\n\t\treturn out as T;\n\t}\n\treturn value;\n}\n\nconst INVOICE_NS = \"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\";\nconst CREDIT_NOTE_NS = \"urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2\";\nconst SBDH_NS = \"http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader\";\n\nconst ublDocumentType = (el: Element): \"Invoice\" | \"CreditNote\" | null => {\n\tif (el.localName === \"Invoice\" && el.namespaceURI === INVOICE_NS) return \"Invoice\";\n\tif (el.localName === \"CreditNote\" && el.namespaceURI === CREDIT_NOTE_NS) {\n\t\treturn \"CreditNote\";\n\t}\n\treturn null;\n};\n\n/**\n * The UBL document element: the root itself, or, when the root is a Peppol\n * `StandardBusinessDocument` envelope (as an access point delivers it), its\n * Invoice/CreditNote child.\n */\nconst findUblRoot = (\n\troot: Element,\n): { root: Element; documentType: \"Invoice\" | \"CreditNote\" } | null => {\n\tconst rootType = ublDocumentType(root);\n\tif (rootType) return { root, documentType: rootType };\n\tif (\n\t\troot.localName !== \"StandardBusinessDocument\" ||\n\t\troot.namespaceURI !== SBDH_NS\n\t) {\n\t\treturn null;\n\t}\n\tfor (let i = 0; i < root.childNodes.length; i++) {\n\t\tconst child = root.childNodes[i];\n\t\tif (!child || child.nodeType !== 1) continue;\n\t\tconst el = child as Element;\n\t\tconst documentType = ublDocumentType(el);\n\t\tif (documentType) return { root: el, documentType };\n\t}\n\treturn null;\n};\n\n/**\n * Parse a UBL 2.1 Invoice or CreditNote, bare or wrapped in a Peppol\n * `StandardBusinessDocument` envelope.\n *\n * Returns `null` when the XML is well-formed but neither its root nor the\n * envelope's payload is a UBL `Invoice`/`CreditNote`. Throws\n * {@link UblParseError} when the XML is malformed or the document lacks an\n * element EN 16931 makes mandatory (document id, issue date, currency, line id).\n */\nexport function parseUblInvoice(xml: string): UblInvoice | null {\n\tconst doc = parseXmlDocument(xml);\n\tif (!doc.documentElement) return null;\n\tconst found = findUblRoot(doc.documentElement);\n\tif (!found) return null;\n\tconst { root, documentType } = found;\n\n\tconst isCreditNote = documentType === \"CreditNote\";\n\tconst id = requiredCbcText(root, \"ID\", \"document identifier\");\n\tconst issueDate = requiredCbcText(root, \"IssueDate\", \"issue date\");\n\tconst currency = requiredCbcText(root, \"DocumentCurrencyCode\", \"currency code\");\n\tconst paymentMeansList = parsePaymentMeansList(root);\n\tconst orderReference = cacElement(root, \"OrderReference\");\n\tconst contractReference = cacDirectElement(root, \"ContractDocumentReference\");\n\tconst projectReference = cacDirectElement(root, \"ProjectReference\");\n\tconst despatchReference = cacDirectElement(root, \"DespatchDocumentReference\");\n\tconst receiptReference = cacDirectElement(root, \"ReceiptDocumentReference\");\n\tconst { attachments, documentReferences, invoicedObjectId, typeCode50Reference } =\n\t\tparseAttachments(root);\n\t// A credit note has no cbc:DueDate; BT-9 travels in the first PaymentMeans.\n\tconst paymentDueDate = (() => {\n\t\tconst first = cacDirectElements(root, \"PaymentMeans\")[0];\n\t\treturn first ? cbcDirectText(first, \"PaymentDueDate\") : undefined;\n\t})();\n\n\treturn omitUndefined<UblInvoice>({\n\t\tdocumentType,\n\t\tcustomizationId: cbcText(root, \"CustomizationID\"),\n\t\tprofileId: cbcText(root, \"ProfileID\"),\n\t\tid,\n\t\tinvoiceTypeCode:\n\t\t\tcbcText(root, \"InvoiceTypeCode\") ?? cbcText(root, \"CreditNoteTypeCode\"),\n\t\tissueDate,\n\t\tdueDate: cbcDirectText(root, \"DueDate\") ?? paymentDueDate,\n\t\ttaxPointDate: cbcDirectText(root, \"TaxPointDate\"),\n\t\tcurrency,\n\t\ttaxCurrency: cbcDirectText(root, \"TaxCurrencyCode\"),\n\t\taccountingCost: cbcDirectText(root, \"AccountingCost\"),\n\t\tbuyerReference: cbcText(root, \"BuyerReference\"),\n\t\torderReference: orderReference ? cbcText(orderReference, \"ID\") : undefined,\n\t\tsalesOrderId: orderReference\n\t\t\t? cbcText(orderReference, \"SalesOrderID\")\n\t\t\t: undefined,\n\t\tcontractReference: contractReference\n\t\t\t? cbcText(contractReference, \"ID\")\n\t\t\t: undefined,\n\t\tprojectReference: projectReference\n\t\t\t? cbcText(projectReference, \"ID\")\n\t\t\t: isCreditNote\n\t\t\t\t? typeCode50Reference\n\t\t\t\t: undefined,\n\t\treceivingAdviceReference: receiptReference\n\t\t\t? cbcDirectText(receiptReference, \"ID\")\n\t\t\t: undefined,\n\t\tdespatchReference: despatchReference\n\t\t\t? cbcDirectText(despatchReference, \"ID\")\n\t\t\t: undefined,\n\t\ttenderReference: isCreditNote ? undefined : typeCode50Reference,\n\t\tinvoicedObjectId,\n\t\tbillingReference: parseBillingReference(root),\n\t\tseller: parseParty(root, \"AccountingSupplierParty\"),\n\t\tbuyer: parseParty(root, \"AccountingCustomerParty\"),\n\t\tpayee: parseUnwrappedParty(root, \"PayeeParty\"),\n\t\ttaxRepresentative: parseUnwrappedParty(root, \"TaxRepresentativeParty\"),\n\t\tdelivery: parseDelivery(root),\n\t\tlines: parseLines(root, isCreditNote),\n\t\ttaxTotal: parseTaxTotal(root),\n\t\tmonetaryTotal: parseMonetaryTotal(root),\n\t\tpaymentMeansList,\n\t\tpaymentMeans: paymentMeansList?.[0],\n\t\tinvoicePeriod: parseInvoicePeriod(root),\n\t\tnote: parseNotes(root),\n\t\tpaymentTermsNote: parsePaymentTermsNote(root),\n\t\tattachments,\n\t\tdocumentReferences,\n\t\tallowanceCharges: parseAllowanceCharges(root),\n\t});\n}\n","import { UblParseError } from \"./errors.js\";\nimport { parseUblInvoice } from \"./parser.js\";\nimport type { UblAttachment } from \"./types.js\";\n\n/**\n * An embedded attachment extracted from a UBL document's\n * `AdditionalDocumentReference` entries, with its binary content still\n * base64-encoded. `sizeBytes` is the decoded size.\n */\nexport interface UblEmbeddedAttachment {\n\tid?: string | undefined;\n\tfilename: string;\n\tmimeCode: string;\n\tsizeBytes: number;\n\t/** Zero-based position among the document's embedded attachments. */\n\tlineOrder: number;\n\tbase64Content: string;\n}\n\n/** Decoded byte length of a base64 string, accounting for `=` padding. */\nexport const base64DecodedSize = (base64: string): number => {\n\tconst sanitized = base64.replace(/\\s+/g, \"\");\n\tif (!sanitized) return 0;\n\tconst padding = sanitized.endsWith(\"==\") ? 2 : sanitized.endsWith(\"=\") ? 1 : 0;\n\treturn Math.floor((sanitized.length * 3) / 4) - padding;\n};\n\n/**\n * Extract the embedded attachments (typically the human-readable PDF) from a\n * UBL invoice or credit note XML. Attachments referenced only by external URI\n * (no `EmbeddedDocumentBinaryObject`) are skipped; use {@link parseUblInvoice}\n * directly when those matter.\n *\n * @throws {UblParseError} when the XML is malformed or not a UBL invoice.\n */\nexport const extractUblEmbeddedAttachments = (xml: string): UblEmbeddedAttachment[] => {\n\tconst parsed = parseUblInvoice(xml);\n\tif (!parsed) throw new UblParseError(\"Document is not a UBL Invoice or CreditNote\");\n\tif (!parsed.attachments || parsed.attachments.length === 0) return [];\n\n\treturn parsed.attachments\n\t\t.map((attachment, index): UblEmbeddedAttachment | null => {\n\t\t\tconst base64Content = attachment.base64Content?.trim();\n\t\t\tif (!base64Content) return null;\n\t\t\treturn {\n\t\t\t\tid: attachment.id,\n\t\t\t\tfilename: attachment.filename ?? `attachment-${index + 1}`,\n\t\t\t\tmimeCode: attachment.mimeCode ?? \"application/octet-stream\",\n\t\t\t\tsizeBytes: base64DecodedSize(base64Content),\n\t\t\t\tlineOrder: index,\n\t\t\t\tbase64Content,\n\t\t\t};\n\t\t})\n\t\t.filter((entry): entry is UblEmbeddedAttachment => entry !== null);\n};\n\n/**\n * Whether an attachment looks like a PDF, by MIME type first and filename\n * extension as a fallback.\n */\nexport const isPdfLikeAttachment = (\n\tattachment: Pick<UblAttachment, \"filename\" | \"mimeCode\">,\n): boolean => {\n\tconst mimeCode = attachment.mimeCode?.toLowerCase() ?? \"\";\n\tif (mimeCode === \"application/pdf\" || mimeCode.endsWith(\"/pdf\")) return true;\n\treturn attachment.filename?.toLowerCase().endsWith(\".pdf\") ?? false;\n};\n","import type { Element } from \"@xmldom/xmldom\";\nimport { UblParseError } from \"./errors.js\";\nimport { CAC_NS, CBC_NS, parseXmlDocument } from \"./xml-dom.js\";\n\n/**\n * Peppol BIS MLR (Message Level Response) document-type identifier value\n * (Peppol `busdox-docid-qns` scheme).\n */\nexport const PEPPOL_MLR_DOCUMENT_TYPE_VALUE =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2::ApplicationResponse##urn:fdc:peppol.eu:poacc:trns:mlr:3::2.1\";\n\n/** Peppol BIS MLR process identifier value. */\nexport const PEPPOL_MLR_PROCESS_VALUE = \"urn:fdc:peppol.eu:poacc:bis:mlr:3\";\n\n/**\n * A parsed Peppol Message Level Response (a UBL `ApplicationResponse`). Every\n * field is optional: a given MLR may omit any of them, and an omitted field is\n * an absent key.\n */\nexport interface PeppolMessageLevelResponse {\n\tcustomizationId?: string | undefined;\n\tprofileId?: string | undefined;\n\tresponseId?: string | undefined;\n\tissueDate?: string | undefined;\n\tissueTime?: string | undefined;\n\treferencedDocumentId?: string | undefined;\n\tresponseCode?: string | undefined;\n\tdescription?: string | undefined;\n\t/** Sender participant id as `schemeID:value` (e.g. `0208:0793904121`). */\n\tsenderIdentifier?: string | undefined;\n\t/** Receiver participant id as `schemeID:value`. */\n\treceiverIdentifier?: string | undefined;\n}\n\nconst trimmed = (value: string | null | undefined): string | undefined => {\n\tconst text = value?.trim();\n\treturn text ? text : undefined;\n};\n\n/** First descendant CBC element's trimmed text, or undefined. */\nconst cbcText = (parent: Element, tag: string): string | undefined =>\n\ttrimmed(parent.getElementsByTagNameNS(CBC_NS, tag)[0]?.textContent);\n\n/**\n * First direct-child CBC element's trimmed text, or null. Used for the\n * top-level scalars so a nested `cbc:ID` (e.g. inside DocumentReference) cannot\n * shadow the ApplicationResponse's own id.\n */\nconst cbcDirectText = (parent: Element, tag: string): string | undefined => {\n\tfor (let i = 0; i < parent.childNodes.length; i++) {\n\t\tconst node = parent.childNodes[i];\n\t\tif (!node || node.nodeType !== 1) continue;\n\t\tconst el = node as Element;\n\t\tif (el.namespaceURI === CBC_NS && el.localName === tag) {\n\t\t\treturn trimmed(el.textContent);\n\t\t}\n\t}\n\treturn undefined;\n};\n\n/** First descendant CAC element, or null. */\nconst cacElement = (parent: Element, tag: string): Element | null =>\n\tparent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;\n\n/**\n * The Peppol participant identifier of a SenderParty / ReceiverParty, rendered\n * as `schemeID:value` when the EndpointID carries a scheme and the value does\n * not already include one, otherwise the raw value.\n */\nconst endpointIdentifier = (party: Element | null): string | undefined => {\n\tif (!party) return undefined;\n\tconst endpoint = party.getElementsByTagNameNS(CBC_NS, \"EndpointID\")[0];\n\tif (!endpoint) return undefined;\n\tconst id = trimmed(endpoint.textContent);\n\tconst scheme = endpoint.getAttribute(\"schemeID\");\n\tif (scheme && id && !id.includes(\":\")) return `${scheme}:${id}`;\n\treturn id;\n};\n\n/**\n * Locate the `ApplicationResponse` element, unwrapping a Standard Business\n * Document (SBDH) envelope when present. Returns null when the XML contains no\n * ApplicationResponse; throws {@link UblParseError} when it is malformed.\n */\nconst findApplicationResponse = (xml: string): Element | null => {\n\tconst doc = parseXmlDocument(xml);\n\tconst root = doc.documentElement;\n\tif (!root) return null;\n\tif (root.localName === \"ApplicationResponse\") return root;\n\tconst candidates = root.getElementsByTagName(\"*\");\n\tfor (let i = 0; i < candidates.length; i++) {\n\t\tconst el = candidates[i];\n\t\tif (el?.localName === \"ApplicationResponse\") return el;\n\t}\n\treturn null;\n};\n\n/**\n * Whether an inbound document is a Peppol Message Level Response, identified by\n * its document-type value, its process value, or by parsing the XML and finding\n * an `ApplicationResponse` root (SBDH-wrapped or not).\n */\nexport const isPeppolMessageLevelResponse = (params: {\n\tdocumentTypeValue?: string | null;\n\tprocessValue?: string | null;\n\txml?: string | null;\n}): boolean => {\n\tif (trimmed(params.documentTypeValue) === PEPPOL_MLR_DOCUMENT_TYPE_VALUE) {\n\t\treturn true;\n\t}\n\tif (trimmed(params.processValue) === PEPPOL_MLR_PROCESS_VALUE) return true;\n\tconst xml = trimmed(params.xml);\n\tif (!xml) return false;\n\ttry {\n\t\treturn findApplicationResponse(xml) !== null;\n\t} catch (error) {\n\t\t// A sniff answers \"is this an MLR?\"; malformed XML is simply \"no\".\n\t\tif (error instanceof UblParseError) return false;\n\t\tthrow error;\n\t}\n};\n\n/**\n * Parse a Peppol Message Level Response (UBL `ApplicationResponse`), unwrapping\n * an SBDH envelope when present. Throws {@link UblParseError} when the XML is\n * malformed or is not an ApplicationResponse.\n */\nexport const parsePeppolMessageLevelResponse = (\n\txml: string,\n): PeppolMessageLevelResponse => {\n\tconst root = findApplicationResponse(xml);\n\tif (!root) {\n\t\tthrow new UblParseError(\"Document is not a Peppol Message Level Response\");\n\t}\n\n\tconst documentResponse = cacElement(root, \"DocumentResponse\");\n\tconst response = documentResponse ? cacElement(documentResponse, \"Response\") : null;\n\tconst documentReference = documentResponse\n\t\t? cacElement(documentResponse, \"DocumentReference\")\n\t\t: null;\n\n\treturn {\n\t\tcustomizationId: cbcDirectText(root, \"CustomizationID\"),\n\t\tprofileId: cbcDirectText(root, \"ProfileID\"),\n\t\tresponseId: cbcDirectText(root, \"ID\"),\n\t\tissueDate: cbcDirectText(root, \"IssueDate\"),\n\t\tissueTime: cbcDirectText(root, \"IssueTime\"),\n\t\treferencedDocumentId: documentReference\n\t\t\t? cbcText(documentReference, \"ID\")\n\t\t\t: undefined,\n\t\tresponseCode: response ? cbcText(response, \"ResponseCode\") : undefined,\n\t\tdescription: response ? cbcText(response, \"Description\") : undefined,\n\t\tsenderIdentifier: endpointIdentifier(cacElement(root, \"SenderParty\")),\n\t\treceiverIdentifier: endpointIdentifier(cacElement(root, \"ReceiverParty\")),\n\t};\n};\n","import { base64DecodedSize } from \"./attachments.js\";\nimport { UblParseError } from \"./errors.js\";\nimport { parseUblInvoice } from \"./parser.js\";\nimport type {\n\tInvoiceExtractionDTO,\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblInvoice,\n\tUblPaymentMeans,\n} from \"./types.js\";\n\n// --- Utility helpers ---\n\nconst UTF8_BOM = 0xfeff;\n\n/** `null` for an absent value or an \"N/A\" placeholder written by the sender. */\nconst normalizeText = (value: string | undefined): string | null => {\n\tif (value === undefined) return null;\n\tconst upper = value.toUpperCase();\n\tif (upper === \"NA\" || upper === \"N/A\") return null;\n\treturn value;\n};\n\nconst toNumberOrNull = (value: number | undefined): number | null =>\n\tvalue !== undefined && Number.isFinite(value) ? value : null;\n\nconst roundToCents = (value: number): number => Math.round(value * 100) / 100;\n\nexport const normalizeCurrency = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\treturn trimmed.toUpperCase();\n};\n\nexport const parseDate = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\tconst timestamp = Date.parse(trimmed);\n\tif (Number.isNaN(timestamp)) return null;\n\tconst iso = new Date(timestamp).toISOString();\n\treturn iso.slice(0, 10);\n};\n\nconst sanitizePaymentMeans = (pm: UblPaymentMeans) => ({\n\tcode: normalizeText(pm.code),\n\tcode_name: normalizeText(pm.codeName),\n\tpayment_id: normalizeText(pm.paymentId),\n\tiban: normalizeText(pm.iban),\n\tbic: normalizeText(pm.bic),\n\taccount_name: normalizeText(pm.accountName),\n\tmandate_id: normalizeText(pm.mandateId),\n});\n\n// --- Address helpers ---\n\nconst present = (part: string | undefined): part is string => part !== undefined;\n\nconst joinStreet = (address: UblAddress): string =>\n\t[address.street, address.additionalStreet].filter(present).join(\" \");\n\nconst addressToString = (address?: UblAddress): string | null => {\n\tif (!address) return null;\n\tconst street = joinStreet(address);\n\tconst cityLine = [address.postalZone, address.city].filter(present).join(\" \");\n\tconst countryLine = [address.countrySubentity, address.countryCode]\n\t\t.filter(present)\n\t\t.join(\" \");\n\tconst lines = [street, cityLine, countryLine].filter((line) => line.length > 0);\n\treturn lines.length > 0 ? lines.join(\"\\n\") : null;\n};\n\nconst addressToStructured = (address?: UblAddress) => {\n\tif (!address) return null;\n\tconst line1 = joinStreet(address);\n\tconst result = {\n\t\tline1: line1 ? normalizeText(line1) : null,\n\t\tline2: null as string | null,\n\t\tcity: normalizeText(address.city),\n\t\tstate: normalizeText(address.countrySubentity),\n\t\tpostal_code: normalizeText(address.postalZone),\n\t\tcountry: normalizeText(address.countryCode),\n\t};\n\tconst hasValue = Object.values(result).some((value) => value);\n\treturn hasValue ? result : null;\n};\n\n// --- Attachment & charge sanitizers ---\n\nconst sanitizeAttachments = (attachments?: UblAttachment[]) =>\n\t(attachments ?? []).map((attachment) => ({\n\t\tid: normalizeText(attachment.id),\n\t\tfilename: normalizeText(attachment.filename),\n\t\tmime_code: normalizeText(attachment.mimeCode),\n\t\tdescription: normalizeText(attachment.description),\n\t\tsize_bytes:\n\t\t\tattachment.base64Content !== undefined\n\t\t\t\t? base64DecodedSize(attachment.base64Content)\n\t\t\t\t: null,\n\t\texternal_uri: normalizeText(attachment.externalUri),\n\t}));\n\nconst sanitizeAllowanceCharges = (charges?: UblAllowanceCharge[]) =>\n\t(charges ?? []).map((charge) => ({\n\t\tcharge_indicator: charge.chargeIndicator,\n\t\tamount: toNumberOrNull(charge.amount),\n\t\tbase_amount: toNumberOrNull(charge.baseAmount),\n\t\tmultiplier_factor_numeric: toNumberOrNull(charge.multiplierFactorNumeric),\n\t\treason: normalizeText(charge.reason),\n\t\treason_code: normalizeText(charge.reasonCode),\n\t\ttax_percent: toNumberOrNull(charge.taxCategory?.percent),\n\t\ttax_category_id: normalizeText(charge.taxCategory?.id),\n\t\ttax_scheme_id: normalizeText(charge.taxCategory?.schemeId),\n\t}));\n\nconst sanitizeRawUbl = (ubl: UblInvoice) => ({\n\t...ubl,\n\tattachments: sanitizeAttachments(ubl.attachments),\n\tdocumentReferences: ubl.documentReferences ?? [],\n});\n\n// --- Summation helpers ---\n\nconst sumTaxTotal = (ubl: UblInvoice): number | null => {\n\tconst { subtotals } = ubl.taxTotal;\n\tconst subtotalSum = subtotals.reduce(\n\t\t(sum, subtotal) => sum + (subtotal.taxAmount ?? 0),\n\t\t0,\n\t);\n\tif (subtotals.length > 0 && Number.isFinite(subtotalSum)) {\n\t\treturn subtotalSum;\n\t}\n\tconst { taxInclusiveAmount, taxExclusiveAmount } = ubl.monetaryTotal;\n\tif (taxInclusiveAmount === undefined || taxExclusiveAmount === undefined) {\n\t\treturn null;\n\t}\n\treturn taxInclusiveAmount - taxExclusiveAmount;\n};\n\nconst sumAllowanceChargesByType = (\n\tcharges: UblAllowanceCharge[] | undefined,\n\tchargeIndicator: boolean,\n) =>\n\t(charges ?? []).reduce((sum, charge) => {\n\t\tif (charge.chargeIndicator !== chargeIndicator) return sum;\n\t\treturn sum + Math.abs(charge.amount ?? 0);\n\t}, 0);\n\n// --- Public API ---\n\n/**\n * Decode raw XML bytes, stripping an optional UTF-8 BOM.\n */\nexport const decodeXmlBytes = (bytes: Uint8Array): string => {\n\tconst text = new TextDecoder(\"utf-8\").decode(bytes);\n\treturn text.charCodeAt(0) === UTF8_BOM ? text.slice(1) : text;\n};\n\n/**\n * Parse a UBL XML string and normalize it into a flat DTO suitable for\n * database storage or API responses.\n *\n * @throws {UblParseError} when the XML is malformed, not a UBL invoice, or\n * lacks a mandatory element.\n */\nexport const normalizeUblResponse = (\n\txml: string,\n\tdocumentId: string,\n): {\n\textracted: InvoiceExtractionDTO;\n\trawPayload: Record<string, unknown>;\n} => {\n\tconst ubl = parseUblInvoice(xml);\n\tif (!ubl) {\n\t\tthrow new UblParseError(\"Document is not a UBL Invoice or CreditNote\");\n\t}\n\n\tconst subtotal =\n\t\ttoNumberOrNull(ubl.monetaryTotal.taxExclusiveAmount) ??\n\t\ttoNumberOrNull(ubl.monetaryTotal.lineExtensionAmount);\n\tconst total =\n\t\ttoNumberOrNull(ubl.monetaryTotal.taxInclusiveAmount) ??\n\t\ttoNumberOrNull(ubl.monetaryTotal.payableAmount);\n\tconst amountDue = toNumberOrNull(ubl.monetaryTotal.payableAmount);\n\tconst prepaidAmount = toNumberOrNull(ubl.monetaryTotal.prepaidAmount);\n\tconst roundingAmount = toNumberOrNull(ubl.monetaryTotal.payableRoundingAmount) ?? 0;\n\t// BR-CO-16: payable = total - prepaid + rounding. With no declared\n\t// PrepaidAmount we invert that to infer what was paid, but the rounding\n\t// term has to come out first — a cash-rounded payable (BT-114) is a\n\t// total-vs-payable gap by design, and reading it as a prepayment reports\n\t// an unpaid invoice as partially settled. Rounded before the sign test so\n\t// the float residue of undoing it cannot pass as a sub-cent prepayment.\n\tconst inferredPaid =\n\t\ttotal !== null && amountDue !== null\n\t\t\t? roundToCents(total - (amountDue - roundingAmount))\n\t\t\t: null;\n\tconst amountPaid =\n\t\tprepaidAmount ??\n\t\t(inferredPaid !== null && inferredPaid > 0 ? inferredPaid : null);\n\tconst taxTotal = toNumberOrNull(sumTaxTotal(ubl) ?? undefined);\n\tconst hasHeaderAllowanceCharges = (ubl.allowanceCharges?.length ?? 0) > 0;\n\tconst headerDiscountTotal = sumAllowanceChargesByType(ubl.allowanceCharges, false);\n\tconst headerChargeTotal = sumAllowanceChargesByType(ubl.allowanceCharges, true);\n\tconst currency = normalizeCurrency(ubl.currency);\n\tconst paymentTerms = normalizeText(ubl.paymentTermsNote);\n\tconst poNumber =\n\t\tnormalizeText(ubl.orderReference) ?? normalizeText(ubl.salesOrderId);\n\n\tconst lineItems = ubl.lines.map((line) => ({\n\t\tdescription:\n\t\t\tnormalizeText(line.description) ??\n\t\t\tnormalizeText(line.itemName) ??\n\t\t\t\"Line item\",\n\t\tquantity: toNumberOrNull(line.quantity),\n\t\tunit: normalizeText(line.unitCode),\n\t\tunit_price: toNumberOrNull(line.unitPrice),\n\t\tamount: toNumberOrNull(line.lineExtensionAmount),\n\t\ttax_amount: toNumberOrNull(line.taxAmount),\n\t\ttax_rate: toNumberOrNull(line.taxCategory?.percent),\n\t\tproduct_code:\n\t\t\tnormalizeText(line.sellersItemId) ?? normalizeText(line.buyersItemId),\n\t\tdiscount_amount: toNumberOrNull(line.discountAmount),\n\t\tperiod_start: parseDate(line.invoicePeriod?.startDate),\n\t\tperiod_end: parseDate(line.invoicePeriod?.endDate),\n\t\textra: {\n\t\t\tubl_line_id: normalizeText(line.id),\n\t\t\titem_name: normalizeText(line.itemName),\n\t\t\tsellers_item_id: normalizeText(line.sellersItemId),\n\t\t\tbuyers_item_id: normalizeText(line.buyersItemId),\n\t\t\ttax_category_id: normalizeText(line.taxCategory?.id),\n\t\t\ttax_scheme_id: normalizeText(line.taxCategory?.schemeId),\n\t\t\ttax_subtotals: line.taxSubtotals ?? [],\n\t\t\tallowance_charges: sanitizeAllowanceCharges([\n\t\t\t\t...(line.allowanceCharges ?? []),\n\t\t\t\t...(line.priceAllowance\n\t\t\t\t\t? [{ chargeIndicator: false, ...line.priceAllowance }]\n\t\t\t\t\t: []),\n\t\t\t]),\n\t\t\tcharge_amount: toNumberOrNull(line.chargeAmount),\n\t\t\tmetadata: line.additionalItemProperties\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tline.additionalItemProperties.map((p) => [p.name, p.value]),\n\t\t\t\t\t)\n\t\t\t\t: null,\n\t\t},\n\t}));\n\n\tconst supplierAddress = addressToString(ubl.seller.address);\n\tconst receiverAddress = addressToString(ubl.buyer.address);\n\tconst supplierAddressStructured = addressToStructured(ubl.seller.address);\n\tconst receiverAddressStructured = addressToStructured(ubl.buyer.address);\n\tconst attachmentMetadata = sanitizeAttachments(ubl.attachments);\n\tconst paymentMeansList =\n\t\tubl.paymentMeansList && ubl.paymentMeansList.length > 0\n\t\t\t? ubl.paymentMeansList\n\t\t\t: ubl.paymentMeans\n\t\t\t\t? [ubl.paymentMeans]\n\t\t\t\t: [];\n\n\tconst extracted: InvoiceExtractionDTO = {\n\t\tprovider: \"ubl_xml\",\n\t\tdocument_id: documentId,\n\t\tinvoice: {\n\t\t\tinvoice_number: normalizeText(ubl.id),\n\t\t\tinvoice_date: parseDate(ubl.issueDate),\n\t\t\tdue_date: parseDate(ubl.dueDate),\n\t\t\tperiod_start: parseDate(ubl.invoicePeriod?.startDate),\n\t\t\tperiod_end: parseDate(ubl.invoicePeriod?.endDate),\n\t\t\tcurrency,\n\t\t\tsubtotal,\n\t\t\ttax_total: taxTotal,\n\t\t\ttotal,\n\t\t\tamount_due: amountDue,\n\t\t\tamount_paid: amountPaid,\n\t\t\tdiscount_total:\n\t\t\t\ttoNumberOrNull(ubl.monetaryTotal.allowanceTotalAmount) ??\n\t\t\t\t(hasHeaderAllowanceCharges\n\t\t\t\t\t? toNumberOrNull(headerDiscountTotal)\n\t\t\t\t\t: null),\n\t\t\tshipping_total:\n\t\t\t\ttoNumberOrNull(ubl.monetaryTotal.chargeTotalAmount) ??\n\t\t\t\t(hasHeaderAllowanceCharges ? toNumberOrNull(headerChargeTotal) : null),\n\t\t\trounding_total: toNumberOrNull(ubl.monetaryTotal.payableRoundingAmount),\n\t\t\tpayment_terms: paymentTerms,\n\t\t\tpo_number: poNumber,\n\t\t\tsupplier: {\n\t\t\t\tname:\n\t\t\t\t\tnormalizeText(ubl.seller.name) ??\n\t\t\t\t\tnormalizeText(ubl.seller.registrationName),\n\t\t\t\taddress: supplierAddress,\n\t\t\t\ttax_id:\n\t\t\t\t\tnormalizeText(ubl.seller.vatId) ??\n\t\t\t\t\tnormalizeText(ubl.seller.companyId?.value),\n\t\t\t\tiban: normalizeText(ubl.paymentMeans?.iban),\n\t\t\t\tbic: normalizeText(ubl.paymentMeans?.bic),\n\t\t\t},\n\t\t\treceiver: {\n\t\t\t\tname:\n\t\t\t\t\tnormalizeText(ubl.buyer.name) ??\n\t\t\t\t\tnormalizeText(ubl.buyer.registrationName),\n\t\t\t\taddress: receiverAddress,\n\t\t\t\ttax_id:\n\t\t\t\t\tnormalizeText(ubl.buyer.vatId) ??\n\t\t\t\t\tnormalizeText(ubl.buyer.companyId?.value),\n\t\t\t},\n\t\t\textra: {\n\t\t\t\tdocument_type: ubl.documentType,\n\t\t\t\tcustomization_id: normalizeText(ubl.customizationId),\n\t\t\t\tprofile_id: normalizeText(ubl.profileId),\n\t\t\t\tinvoice_type_code: normalizeText(ubl.invoiceTypeCode),\n\t\t\t\tbuyer_reference: normalizeText(ubl.buyerReference),\n\t\t\t\torder_reference_id: normalizeText(ubl.orderReference),\n\t\t\t\tsales_order_id: normalizeText(ubl.salesOrderId),\n\t\t\t\tcontract_reference: normalizeText(ubl.contractReference),\n\t\t\t\tproject_reference: normalizeText(ubl.projectReference),\n\t\t\t\tbilling_reference: ubl.billingReference\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tinvoice_id: normalizeText(ubl.billingReference.invoiceId),\n\t\t\t\t\t\t\tinvoice_issue_date: parseDate(\n\t\t\t\t\t\t\t\tubl.billingReference.invoiceIssueDate,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\ttax_point_date: parseDate(ubl.taxPointDate),\n\t\t\t\tinvoice_period: ubl.invoicePeriod ?? null,\n\t\t\t\tnote: normalizeText(ubl.note),\n\t\t\t\tpayment_means: ubl.paymentMeans\n\t\t\t\t\t? sanitizePaymentMeans(ubl.paymentMeans)\n\t\t\t\t\t: null,\n\t\t\t\tpayment_means_list: paymentMeansList.map(sanitizePaymentMeans),\n\t\t\t\tdelivery: ubl.delivery\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tactual_delivery_date: parseDate(\n\t\t\t\t\t\t\t\tubl.delivery.actualDeliveryDate,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\taddress: addressToStructured(ubl.delivery.address),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\tsupplier: {\n\t\t\t\t\tendpoint_id: normalizeText(ubl.seller.endpoint?.value),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.seller.endpoint?.scheme),\n\t\t\t\t\tregistration_name: normalizeText(ubl.seller.registrationName),\n\t\t\t\t\tcompany_legal_form: normalizeText(ubl.seller.companyLegalForm),\n\t\t\t\t\tcompany_id_scheme_id: normalizeText(ubl.seller.companyId?.scheme),\n\t\t\t\t\ttax_scheme_id: normalizeText(ubl.seller.taxSchemeId),\n\t\t\t\t\tparty_identifications: ubl.seller.partyIdentifications ?? [],\n\t\t\t\t\tcontact_name: normalizeText(ubl.seller.contact?.name),\n\t\t\t\t\tcontact_phone: normalizeText(ubl.seller.contact?.phone),\n\t\t\t\t\tcontact_email: normalizeText(ubl.seller.contact?.email),\n\t\t\t\t},\n\t\t\t\treceiver: {\n\t\t\t\t\tendpoint_id: normalizeText(ubl.buyer.endpoint?.value),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.buyer.endpoint?.scheme),\n\t\t\t\t\tregistration_name: normalizeText(ubl.buyer.registrationName),\n\t\t\t\t\tcompany_legal_form: normalizeText(ubl.buyer.companyLegalForm),\n\t\t\t\t\tcompany_id_scheme_id: normalizeText(ubl.buyer.companyId?.scheme),\n\t\t\t\t\ttax_scheme_id: normalizeText(ubl.buyer.taxSchemeId),\n\t\t\t\t\tparty_identifications: ubl.buyer.partyIdentifications ?? [],\n\t\t\t\t\tcontact_name: normalizeText(ubl.buyer.contact?.name),\n\t\t\t\t\tcontact_phone: normalizeText(ubl.buyer.contact?.phone),\n\t\t\t\t\tcontact_email: normalizeText(ubl.buyer.contact?.email),\n\t\t\t\t},\n\t\t\t\tsupplier_address_structured: supplierAddressStructured,\n\t\t\t\treceiver_address_structured: receiverAddressStructured,\n\t\t\t\ttax_subtotals: ubl.taxTotal.subtotals,\n\t\t\t\tallowance_charges: sanitizeAllowanceCharges(ubl.allowanceCharges),\n\t\t\t\tattachments: attachmentMetadata,\n\t\t\t\tdocument_references: ubl.documentReferences ?? [],\n\t\t\t},\n\t\t},\n\t\tline_items: lineItems,\n\t\tconfidence: {\n\t\t\toverall: 1,\n\t\t\tfields: {\n\t\t\t\tinvoice_id: 1,\n\t\t\t\tinvoice_date: 1,\n\t\t\t\tdue_date: 1,\n\t\t\t\ttotal_amount: 1,\n\t\t\t\tsupplier_name: 1,\n\t\t\t},\n\t\t},\n\t};\n\n\treturn {\n\t\textracted,\n\t\trawPayload: {\n\t\t\tformat: \"ubl_xml\",\n\t\t\tinvoice: sanitizeRawUbl(ubl),\n\t\t},\n\t};\n};\n\n/**\n * Parse a UBL invoice from raw bytes and normalize it into a DTO.\n */\nexport const parseUblInvoiceDocument = (params: {\n\tbytes: Uint8Array;\n\tdocumentId: string;\n\tmimeType: string;\n}) => {\n\tconst xml = decodeXmlBytes(params.bytes);\n\tconst { extracted, rawPayload } = normalizeUblResponse(xml, params.documentId);\n\treturn {\n\t\trawPayload: {\n\t\t\t...rawPayload,\n\t\t\tmime_type: params.mimeType,\n\t\t},\n\t\textracted,\n\t\tproviderJobId: null as string | null,\n\t};\n};\n"],"mappings":";;;AAGA,MAAa,SACZ;AACD,MAAa,SACZ;;;;;;AAOD,MAAa,gBAAgB,QAC5B,IAAI,QAAQ,uCAAuC,EAAE;;;;;;AAOtD,MAAa,oBAAoB,QAA0B;CAC1D,MAAM,UAAU,aAAa,GAAG;CAChC,MAAM,mBAAoB,WACxB;CACF,MAAM,SAAS,mBAAmB,IAAI,iBAAiB,IAAI,IAAIA,UAAa;CAC5E,IAAI;CACJ,IAAI;EACH,MAAM,OAAO,gBAAgB,SAAS,UAAU;CACjD,SAAS,OAAO;EACf,MAAM,IAAI,cA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e,cAAc,IAAI,MAAM,SAAS,KAAK;KACtD;KACA,6BAA6B;KAC7B,6BAA6B;KAC7B,eAAe,IAAI,SAAS;KAC5B,mBAAmB,yBAAyB,IAAI,gBAAgB;KAChE,aAAa;KACb,qBAAqB,IAAI,sBAAsB,CAAC;IACjD;GACD;GACA,YAAY;GACZ,YAAY;IACX,SAAS;IACT,QAAQ;KACP,YAAY;KACZ,cAAc;KACd,UAAU;KACV,cAAc;KACd,eAAe;IAChB;GACD;EAIQ;EACR,YAAY;GACX,QAAQ;GACR,SAAS,eAAe,GAAG;EAC5B;CACD;AACD;;;;AAKA,MAAa,2BAA2B,WAIlC;CACL,MAAM,MAAM,eAAe,OAAO,KAAK;CACvC,MAAM,EAAE,WAAW,eAAe,qBAAqB,KAAK,OAAO,UAAU;CAC7E,OAAO;EACN,YAAY;GACX,GAAG;GACH,WAAW,OAAO;EACnB;EACA;EACA,eAAe;CAChB;AACD"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@financica/ubl",
3
- "version": "0.18.1",
4
- "description": "UBL (Universal Business Language) invoice toolkit for TypeScript: parse, build, and serialize Peppol BIS Billing 3.0 documents.",
3
+ "version": "0.19.0",
4
+ "description": "UBL (Universal Business Language) invoices in TypeScript: parse, build and serialize Peppol BIS Billing 3.0 documents.",
5
5
  "homepage": "https://github.com/financica/ts-libs/tree/main/packages/ubl#readme",
6
6
  "bugs": "https://github.com/financica/ts-libs/issues",
7
7
  "license": "MIT",
@@ -53,7 +53,7 @@
53
53
  "prepack": "bun run build"
54
54
  },
55
55
  "dependencies": {
56
- "@financica/peppol": ">=0.8.0 <1.0.0",
56
+ "@financica/peppol": ">=0.9.0 <1.0.0",
57
57
  "@xmldom/xmldom": "^0.9.11"
58
58
  },
59
59
  "engines": {
@@ -207,6 +207,8 @@ export const extractCustomerTaxIdentifiers = (
207
207
  * {@link resolveVatEndpoint});
208
208
  * 4. for Belgium, the enterprise number (VAT digits without the `BE` prefix)
209
209
  * under EAS `0208` — many Belgian entities register only under that;
210
+ * for Sweden, the organisationsnummer inside the VAT number under `0007`,
211
+ * Sweden's only scheme since SE:VAT (`9955`) was withdrawn;
210
212
  * 5. a generic tax/registration number under its country's company-ID scheme.
211
213
  *
212
214
  * `countryCode` (the customer's country, when known) disambiguates schemes for
@@ -244,6 +246,13 @@ export const listPeppolReceiverIdentifierCandidates = (
244
246
  );
245
247
  }
246
248
 
249
+ // 4b. Sweden has no VAT scheme left (SE:VAT 9955 is withdrawn); a Swedish VAT
250
+ // number is the organisationsnummer + `01`, registered under EAS 0007.
251
+ const swedishOrgNumber = /^SE(\d{10})01$/.exec(
252
+ (customer.vatNumber ?? "").replace(/[^A-Za-z0-9]/g, "").toUpperCase(),
253
+ )?.[1];
254
+ if (swedishOrgNumber) add({ scheme: "0007", value: swedishOrgNumber });
255
+
247
256
  // 5. A generic tax/registration number → its country's company-ID scheme.
248
257
  const tax = normalizeString(customer.taxNumber);
249
258
  if (tax)
package/src/parser.ts CHANGED
@@ -695,31 +695,57 @@ function omitUndefined<T>(value: T): T {
695
695
 
696
696
  const INVOICE_NS = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2";
697
697
  const CREDIT_NOTE_NS = "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2";
698
+ const SBDH_NS = "http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader";
699
+
700
+ const ublDocumentType = (el: Element): "Invoice" | "CreditNote" | null => {
701
+ if (el.localName === "Invoice" && el.namespaceURI === INVOICE_NS) return "Invoice";
702
+ if (el.localName === "CreditNote" && el.namespaceURI === CREDIT_NOTE_NS) {
703
+ return "CreditNote";
704
+ }
705
+ return null;
706
+ };
698
707
 
699
708
  /**
700
- * Parse a UBL 2.1 Invoice or CreditNote.
701
- *
702
- * Returns `null` when the XML is well-formed but its root is not a UBL
703
- * `Invoice`/`CreditNote`. Throws {@link UblParseError} when the XML is
704
- * malformed or the document lacks an element EN 16931 makes mandatory
705
- * (document id, issue date, currency, line id).
709
+ * The UBL document element: the root itself, or, when the root is a Peppol
710
+ * `StandardBusinessDocument` envelope (as an access point delivers it), its
711
+ * Invoice/CreditNote child.
706
712
  */
707
- export function parseUblInvoice(xml: string): UblInvoice | null {
708
- const doc = parseXmlDocument(xml);
709
- const root = doc.documentElement;
710
- if (!root) return null;
711
-
712
- let documentType: "Invoice" | "CreditNote";
713
- if (root.localName === "Invoice" && root.namespaceURI === INVOICE_NS) {
714
- documentType = "Invoice";
715
- } else if (
716
- root.localName === "CreditNote" &&
717
- root.namespaceURI === CREDIT_NOTE_NS
713
+ const findUblRoot = (
714
+ root: Element,
715
+ ): { root: Element; documentType: "Invoice" | "CreditNote" } | null => {
716
+ const rootType = ublDocumentType(root);
717
+ if (rootType) return { root, documentType: rootType };
718
+ if (
719
+ root.localName !== "StandardBusinessDocument" ||
720
+ root.namespaceURI !== SBDH_NS
718
721
  ) {
719
- documentType = "CreditNote";
720
- } else {
721
722
  return null;
722
723
  }
724
+ for (let i = 0; i < root.childNodes.length; i++) {
725
+ const child = root.childNodes[i];
726
+ if (!child || child.nodeType !== 1) continue;
727
+ const el = child as Element;
728
+ const documentType = ublDocumentType(el);
729
+ if (documentType) return { root: el, documentType };
730
+ }
731
+ return null;
732
+ };
733
+
734
+ /**
735
+ * Parse a UBL 2.1 Invoice or CreditNote, bare or wrapped in a Peppol
736
+ * `StandardBusinessDocument` envelope.
737
+ *
738
+ * Returns `null` when the XML is well-formed but neither its root nor the
739
+ * envelope's payload is a UBL `Invoice`/`CreditNote`. Throws
740
+ * {@link UblParseError} when the XML is malformed or the document lacks an
741
+ * element EN 16931 makes mandatory (document id, issue date, currency, line id).
742
+ */
743
+ export function parseUblInvoice(xml: string): UblInvoice | null {
744
+ const doc = parseXmlDocument(xml);
745
+ if (!doc.documentElement) return null;
746
+ const found = findUblRoot(doc.documentElement);
747
+ if (!found) return null;
748
+ const { root, documentType } = found;
723
749
 
724
750
  const isCreditNote = documentType === "CreditNote";
725
751
  const id = requiredCbcText(root, "ID", "document identifier");