@financica/ubl 0.15.1 → 0.16.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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["CBC_NS","CAC_NS","cbcText","cacElement","cbcDirectText","stripDoctype","XmlDomParser","XmlDomParser"],"sources":["../src/parser.ts","../src/attachments.ts","../src/mlr.ts","../src/normalize.ts"],"sourcesContent":["import { DOMParser as XmlDomParser, type Element } from \"@xmldom/xmldom\";\nimport type {\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblBillingReference,\n\tUblDelivery,\n\tUblDocumentReference,\n\tUblInvoice,\n\tUblInvoicePeriod,\n\tUblItemProperty,\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblParty,\n\tUblPartyIdentification,\n\tUblPaymentMeans,\n\tUblTaxSubtotal,\n} from \"./types.js\";\n\nconst CBC_NS = \"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\nconst CAC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\n\n// --- DOM helpers ---\n\nfunction cbcText(parent: Element, tag: string): string {\n\tconst el = parent.getElementsByTagNameNS(CBC_NS, tag)[0];\n\treturn el?.textContent?.trim() ?? \"\";\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\nfunction cbcNumber(parent: Element, tag: string): number {\n\tconst n = Number.parseFloat(cbcText(parent, tag));\n\treturn Number.isNaN(n) ? 0 : n;\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 {\n\tconst el = childElementsByTagNs(parent, CBC_NS, tag)[0];\n\treturn el?.textContent?.trim() ?? \"\";\n}\n\nfunction cbcDirectNumber(parent: Element, tag: string): number | null {\n\tconst value = cbcDirectText(parent, tag);\n\tif (!value) return null;\n\tconst parsed = Number.parseFloat(value);\n\treturn Number.isNaN(parsed) ? null : parsed;\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\") || undefined,\n\t\tcity: cbcText(address, \"CityName\"),\n\t\tpostalZone: cbcText(address, \"PostalZone\"),\n\t\tcountrySubentity: cbcText(address, \"CountrySubentity\") || undefined,\n\t\tcountryCode: country ? cbcText(country, \"IdentificationCode\") : \"\",\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\") || undefined;\n}\n\nfunction parseContact(party: Element): import(\"./types.js\").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 {\n\t\tname: name || undefined,\n\t\tphone: phone || undefined,\n\t\temail: email || undefined,\n\t};\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\tconst schemeIdAttr = idEl\n\t\t\t.getElementsByTagNameNS(CBC_NS, \"ID\")[0]\n\t\t\t?.getAttribute(\"schemeID\");\n\t\tresult.push({\n\t\t\tid: idValue,\n\t\t\tschemeId: schemeIdAttr || undefined,\n\t\t});\n\t}\n\treturn result;\n}\n\nfunction parseParty(root: Element, role: string): UblParty {\n\tconst wrapper = cacElement(root, role);\n\tconst party = wrapper ? cacElement(wrapper, \"Party\") : null;\n\tif (!party) return { name: \"Unknown\" };\n\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\treturn {\n\t\tname: partyName ? cbcText(partyName, \"Name\") : \"\",\n\t\tregistrationName: legalEntity\n\t\t\t? cbcText(legalEntity, \"RegistrationName\") || undefined\n\t\t\t: undefined,\n\t\tcompanyLegalForm: legalEntity\n\t\t\t? cbcText(legalEntity, \"CompanyLegalForm\") || undefined\n\t\t\t: undefined,\n\t\tvatId: taxScheme ? cbcText(taxScheme, \"CompanyID\") || undefined : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(taxScheme),\n\t\tcompanyId: companyIdEl\n\t\t\t? companyIdEl.textContent?.trim() || undefined\n\t\t\t: partyId\n\t\t\t\t? cbcText(partyId, \"ID\") || undefined\n\t\t\t\t: undefined,\n\t\tcompanyIdSchemeId: companyIdEl?.getAttribute(\"schemeID\") || undefined,\n\t\tendpointId: endpointEl?.textContent?.trim() || undefined,\n\t\tendpointSchemeId: endpointEl?.getAttribute(\"schemeID\") || 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\nfunction parseTaxSubtotal(sub: Element): UblTaxSubtotal {\n\tconst cat = cacElement(sub, \"TaxCategory\");\n\treturn {\n\t\ttaxableAmount: cbcNumber(sub, \"TaxableAmount\"),\n\t\ttaxAmount: cbcNumber(sub, \"TaxAmount\"),\n\t\ttaxPercent: (cat ? cbcNumber(cat, \"Percent\") : 0) || cbcNumber(sub, \"Percent\"),\n\t\ttaxCategoryId: cat ? cbcText(cat, \"ID\") || undefined : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(cat),\n\t\ttaxExemptionReason: cat\n\t\t\t? cbcText(cat, \"TaxExemptionReason\") || undefined\n\t\t\t: undefined,\n\t};\n}\n\nfunction parseTaxSubtotalsFromTaxTotal(taxTotal: Element): UblTaxSubtotal[] {\n\treturn cacDirectElements(taxTotal, \"TaxSubtotal\").map(parseTaxSubtotal);\n}\n\nfunction parseTaxSubtotals(root: Element): UblTaxSubtotal[] {\n\tconst taxTotals = cacDirectElements(root, \"TaxTotal\");\n\tif (taxTotals.length === 0) return [];\n\treturn taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal);\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\") ?? undefined,\n\t\tmultiplierFactorNumeric:\n\t\t\tcbcDirectNumber(charge, \"MultiplierFactorNumeric\") ?? undefined,\n\t\treason: cbcText(charge, \"AllowanceChargeReason\") || undefined,\n\t\treasonCode: cbcText(charge, \"AllowanceChargeReasonCode\") || undefined,\n\t\ttaxPercent: taxCategory ? cbcNumber(taxCategory, \"Percent\") : undefined,\n\t\ttaxCategoryId: taxCategory\n\t\t\t? cbcText(taxCategory, \"ID\") || undefined\n\t\t\t: undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(taxCategory),\n\t};\n}\n\nfunction parseAllowanceCharges(parent: Element): UblAllowanceCharge[] {\n\treturn cacDirectElements(parent, \"AllowanceCharge\").map(parseAllowanceCharge);\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 taxCategory = item ? cacElement(item, \"ClassifiedTaxCategory\") : null;\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,\n\t\t\t0,\n\t\t);\n\t\tconst taxAmountFromLineTotal = lineTaxTotal\n\t\t\t? cbcDirectNumber(lineTaxTotal, \"TaxAmount\")\n\t\t\t: null;\n\t\tconst taxPercent =\n\t\t\tlineTaxSubtotals[0]?.taxPercent ??\n\t\t\t(taxCategory ? cbcNumber(taxCategory, \"Percent\") : undefined);\n\t\tconst computedTaxAmount =\n\t\t\ttaxPercent !== undefined\n\t\t\t\t? Number(((lineExtensionAmount * taxPercent) / 100).toFixed(2))\n\t\t\t\t: undefined;\n\t\tconst lineAllowanceCharges = parseAllowanceCharges(line);\n\t\tconst priceAllowanceCharges = price ? parseAllowanceCharges(price) : [];\n\t\tconst allowanceCharges = [...lineAllowanceCharges, ...priceAllowanceCharges];\n\t\tconst discountAmount = allowanceCharges.reduce(\n\t\t\t(sum, charge) =>\n\t\t\t\tcharge.chargeIndicator ? sum : sum + Math.abs(charge.amount),\n\t\t\t0,\n\t\t);\n\t\tconst chargeAmount = allowanceCharges.reduce(\n\t\t\t(sum, charge) =>\n\t\t\t\tcharge.chargeIndicator ? sum + Math.abs(charge.amount) : 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\") : 0;\n\t\tconst priceBaseQuantity = price ? cbcDirectNumber(price, \"BaseQuantity\") : null;\n\t\tconst unitPrice =\n\t\t\tpriceBaseQuantity && priceBaseQuantity > 0\n\t\t\t\t? priceAmount / priceBaseQuantity\n\t\t\t\t: priceAmount;\n\n\t\treturn {\n\t\t\tid: cbcText(line, \"ID\"),\n\t\t\tdescription: item ? cbcText(item, \"Description\") : \"\",\n\t\t\tquantity: cbcNumber(line, qtyTag),\n\t\t\tunitCode: qtyEl?.getAttribute(\"unitCode\") ?? \"\",\n\t\t\tunitPrice,\n\t\t\tlineExtensionAmount,\n\t\t\ttaxPercent,\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\ttaxCategoryId:\n\t\t\t\tlineTaxSubtotals[0]?.taxCategoryId ??\n\t\t\t\t(taxCategory ? cbcText(taxCategory, \"ID\") || undefined : undefined),\n\t\t\ttaxSchemeId:\n\t\t\t\tlineTaxSubtotals[0]?.taxSchemeId ?? parseTaxSchemeId(taxCategory),\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\tdiscountAmount: discountAmount > 0 ? discountAmount : undefined,\n\t\t\tchargeAmount: chargeAmount > 0 ? chargeAmount : undefined,\n\t\t\titemName: item ? cbcText(item, \"Name\") || undefined : undefined,\n\t\t\tsellersItemId: sellersId\n\t\t\t\t? cbcText(sellersId, \"ID\") || undefined\n\t\t\t\t: undefined,\n\t\t\tbuyersItemId: buyersId ? cbcText(buyersId, \"ID\") || undefined : 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) {\n\t\treturn {\n\t\t\tlineExtensionAmount: 0,\n\t\t\ttaxExclusiveAmount: 0,\n\t\t\ttaxInclusiveAmount: 0,\n\t\t\tpayableAmount: 0,\n\t\t};\n\t}\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\") || undefined,\n\t\tchargeTotalAmount: cbcNumber(total, \"ChargeTotalAmount\") || undefined,\n\t\tprepaidAmount: cbcNumber(total, \"PrepaidAmount\") || undefined,\n\t\tpayableRoundingAmount: cbcNumber(total, \"PayableRoundingAmount\") || undefined,\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\n\treturn {\n\t\tcode: cbcText(pm, \"PaymentMeansCode\"),\n\t\tcodeName: paymentMeansCodeEl?.getAttribute(\"name\") || undefined,\n\t\tpaymentId: cbcText(pm, \"PaymentID\") || undefined,\n\t\tiban: account ? cbcText(account, \"ID\") || undefined : undefined,\n\t\tbic: branch ? cbcText(branch, \"ID\") || undefined : undefined,\n\t\taccountName: (account && cbcText(account, \"Name\")) || undefined,\n\t\tmandateId: mandate ? cbcText(mandate, \"ID\") || undefined : 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 || undefined,\n\t\tendDate: end || undefined,\n\t\tdescriptionCode: cbcText(period, \"DescriptionCode\") || undefined,\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\") || undefined;\n\tconst deliveryLocation = cacElement(delivery, \"DeliveryLocation\");\n\tconst address = parseAddressFromElement(\n\t\tdeliveryLocation ? cacElement(deliveryLocation, \"Address\") : null,\n\t);\n\tif (!actualDeliveryDate && !address) return undefined;\n\treturn {\n\t\tactualDeliveryDate,\n\t\taddress,\n\t};\n}\n\nfunction parsePaymentTermsNote(root: Element): string | undefined {\n\tconst paymentTerms = cacElement(root, \"PaymentTerms\");\n\tif (!paymentTerms) return undefined;\n\tconst note = cbcText(paymentTerms, \"Note\");\n\treturn note || undefined;\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\nfunction parseAttachments(root: Element): {\n\tattachments: UblAttachment[] | undefined;\n\tdocumentReferences: UblDocumentReference[] | undefined;\n} {\n\tconst refs = cacElements(root, \"AdditionalDocumentReference\");\n\tconst attachments: UblAttachment[] = [];\n\tconst documentReferences: UblDocumentReference[] = [];\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\") || undefined;\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: binaryEl.getAttribute(\"filename\") || undefined,\n\t\t\t\t\tmimeCode: binaryEl.getAttribute(\"mimeCode\") || undefined,\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};\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\") || undefined;\n\tconst invoiceIssueDate = cbcText(invoiceRef, \"IssueDate\") || undefined;\n\tif (!invoiceId && !invoiceIssueDate) return undefined;\n\treturn { invoiceId, invoiceIssueDate };\n}\n\n// --- Main parser ---\n\n/**\n * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.\n * @xmldom/xmldom resolves external entities by default, so we remove\n * DOCTYPE blocks (including inline DTD subsets) before parsing.\n */\nconst stripDoctype = (xml: string): string =>\n\txml.replace(/<!DOCTYPE\\s[^>[]*(?:\\[[^\\]]*\\])?>/gi, \"\");\n\nexport function parseUblInvoice(xml: string): UblInvoice | null {\n\ttry {\n\t\tconst safeXml = stripDoctype(xml);\n\t\tconst BrowserDomParser = (globalThis as { DOMParser?: typeof XmlDomParser })\n\t\t\t.DOMParser;\n\t\tconst parser = BrowserDomParser ? new BrowserDomParser() : new XmlDomParser();\n\t\tconst doc = parser.parseFromString(safeXml, \"text/xml\");\n\t\tif (doc.getElementsByTagName(\"parsererror\").length > 0) return null;\n\n\t\tconst root = doc.documentElement;\n\t\tif (!root) return null;\n\t\tconst localName = root.localName;\n\n\t\tlet documentType: \"Invoice\" | \"CreditNote\";\n\t\tif (localName === \"Invoice\") {\n\t\t\tdocumentType = \"Invoice\";\n\t\t} else if (localName === \"CreditNote\") {\n\t\t\tdocumentType = \"CreditNote\";\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst isCreditNote = documentType === \"CreditNote\";\n\t\tconst id = cbcText(root, \"ID\");\n\t\tif (!id) return null;\n\t\tconst paymentMeansList = parsePaymentMeansList(root);\n\t\tconst orderReference = cacElement(root, \"OrderReference\");\n\t\tconst contractReference = cacElement(root, \"ContractDocumentReference\");\n\t\tconst projectReference = cacElement(root, \"ProjectReference\");\n\t\tconst { attachments, documentReferences } = parseAttachments(root);\n\n\t\treturn {\n\t\t\tdocumentType,\n\t\t\tcustomizationId: cbcText(root, \"CustomizationID\") || undefined,\n\t\t\tprofileId: cbcText(root, \"ProfileID\") || undefined,\n\t\t\tid,\n\t\t\tinvoiceTypeCode:\n\t\t\t\tcbcText(root, \"InvoiceTypeCode\") ||\n\t\t\t\tcbcText(root, \"CreditNoteTypeCode\") ||\n\t\t\t\tundefined,\n\t\t\tissueDate: cbcText(root, \"IssueDate\"),\n\t\t\tdueDate: cbcText(root, \"DueDate\") || undefined,\n\t\t\ttaxPointDate: cbcText(root, \"TaxPointDate\") || undefined,\n\t\t\tcurrency: cbcText(root, \"DocumentCurrencyCode\"),\n\t\t\tbuyerReference: cbcText(root, \"BuyerReference\") || undefined,\n\t\t\torderReference: orderReference ? cbcText(orderReference, \"ID\") : undefined,\n\t\t\tsalesOrderId: orderReference\n\t\t\t\t? cbcText(orderReference, \"SalesOrderID\") || undefined\n\t\t\t\t: undefined,\n\t\t\tcontractReference: contractReference\n\t\t\t\t? cbcText(contractReference, \"ID\")\n\t\t\t\t: undefined,\n\t\t\tprojectReference: projectReference\n\t\t\t\t? cbcText(projectReference, \"ID\")\n\t\t\t\t: undefined,\n\t\t\tbillingReference: parseBillingReference(root),\n\t\t\tseller: parseParty(root, \"AccountingSupplierParty\"),\n\t\t\tbuyer: parseParty(root, \"AccountingCustomerParty\"),\n\t\t\tdelivery: parseDelivery(root),\n\t\t\tlines: parseLines(root, isCreditNote),\n\t\t\ttaxSubtotals: parseTaxSubtotals(root),\n\t\t\tmonetaryTotal: parseMonetaryTotal(root),\n\t\t\tpaymentMeansList,\n\t\t\tpaymentMeans: paymentMeansList?.[0],\n\t\t\tinvoicePeriod: parseInvoicePeriod(root),\n\t\t\tnote: parseNotes(root),\n\t\t\tpaymentTermsNote: parsePaymentTermsNote(root),\n\t\t\tattachments,\n\t\t\tdocumentReferences,\n\t\t\tallowanceCharges: parseAllowanceCharges(root),\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n","import { 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 approximate decoded size.\n */\nexport interface UblEmbeddedAttachment {\n\tid: string | null;\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/** Approximate decoded byte length of a base64 string. */\nconst base64DecodedSize = (base64: string) => Math.round((base64.length * 3) / 4);\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 */\nexport const extractUblEmbeddedAttachments = (xml: string): UblEmbeddedAttachment[] => {\n\tconst parsed = parseUblInvoice(xml);\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 || null,\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 Document, DOMParser as XmlDomParser, type Element } from \"@xmldom/xmldom\";\n\nconst CBC_NS = \"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\";\nconst CAC_NS =\n\t\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\";\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 nullable: a given MLR may omit any of them.\n */\nexport interface PeppolMessageLevelResponse {\n\tcustomizationId: string | null;\n\tprofileId: string | null;\n\tresponseId: string | null;\n\tissueDate: string | null;\n\tissueTime: string | null;\n\treferencedDocumentId: string | null;\n\tresponseCode: string | null;\n\tdescription: string | null;\n\t/** Sender participant id as `schemeID:value` (e.g. `0208:0793904121`). */\n\tsenderIdentifier: string | null;\n\t/** Receiver participant id as `schemeID:value`. */\n\treceiverIdentifier: string | null;\n}\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 */\nconst stripDoctype = (xml: string): string =>\n\txml.replace(/<!DOCTYPE\\s[^>[]*(?:\\[[^\\]]*\\])?>/gi, \"\");\n\nconst parseXmlDocument = (xml: string): Document | null => {\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\tconst doc = parser.parseFromString(safeXml, \"text/xml\");\n\tif (doc.getElementsByTagName(\"parsererror\").length > 0) return null;\n\treturn doc;\n};\n\nconst trimmed = (value: string | null | undefined): string | null => {\n\tconst text = value?.trim();\n\treturn text ? text : null;\n};\n\n/** First descendant CBC element's trimmed text, or null. */\nconst cbcText = (parent: Element, tag: string): string | null =>\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 | null => {\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 null;\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 | null => {\n\tif (!party) return null;\n\tconst endpoint = party.getElementsByTagNameNS(CBC_NS, \"EndpointID\")[0];\n\tif (!endpoint) return null;\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 is not\n * parseable or contains no ApplicationResponse.\n */\nconst findApplicationResponse = (xml: string): Element | null => {\n\tlet doc: Document | null;\n\ttry {\n\t\tdoc = parseXmlDocument(xml);\n\t} catch {\n\t\treturn null;\n\t}\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\treturn findApplicationResponse(xml) !== null;\n};\n\n/**\n * Parse a Peppol Message Level Response (UBL `ApplicationResponse`), unwrapping\n * an SBDH envelope when present. Throws when the XML is not an\n * ApplicationResponse.\n */\nexport const parsePeppolMessageLevelResponse = (\n\txml: string,\n): PeppolMessageLevelResponse => {\n\tconst root = findApplicationResponse(xml);\n\tif (!root) {\n\t\tthrow new Error(\"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: null,\n\t\tresponseCode: response ? cbcText(response, \"ResponseCode\") : null,\n\t\tdescription: response ? cbcText(response, \"Description\") : null,\n\t\tsenderIdentifier: endpointIdentifier(cacElement(root, \"SenderParty\")),\n\t\treceiverIdentifier: endpointIdentifier(cacElement(root, \"ReceiverParty\")),\n\t};\n};\n","import { parseUblInvoice } from \"./parser.js\";\nimport type {\n\tInvoiceExtractionDTO,\n\tUblAddress,\n\tUblAllowanceCharge,\n\tUblAttachment,\n\tUblInvoice,\n} from \"./types.js\";\n\n// --- Utility helpers ---\n\nconst UTF8_BOM = 0xfeff;\n\nconst normalizeText = (value?: string | null): string | null => {\n\tif (!value) return null;\n\tconst trimmed = value.trim();\n\tif (!trimmed) return null;\n\tconst upper = trimmed.toUpperCase();\n\tif (upper === \"NA\" || upper === \"N/A\") return null;\n\treturn trimmed;\n};\n\nconst toNumberOrNull = (value: number | null | undefined): number | null =>\n\tNumber.isFinite(value ?? Number.NaN) ? (value as number) : 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\n// --- Address helpers ---\n\nconst addressToString = (address?: UblAddress): string | null => {\n\tif (!address) return null;\n\tconst street = [address.street, address.additionalStreet]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst cityLine = [address.postalZone, address.city]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst countryLine = [address.countrySubentity, address.countryCode]\n\t\t.filter((part) => part && part.trim().length > 0)\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 = [address.street, address.additionalStreet]\n\t\t.filter((part) => part && part.trim().length > 0)\n\t\t.join(\" \");\n\tconst result = {\n\t\tline1: normalizeText(line1),\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 base64ByteLength = (content: string) => {\n\tconst sanitized = content.replace(/\\s+/g, \"\");\n\tif (!sanitized) return 0;\n\tconst paddingLength = sanitized.endsWith(\"==\")\n\t\t? 2\n\t\t: sanitized.endsWith(\"=\")\n\t\t\t? 1\n\t\t\t: 0;\n\treturn Math.floor((sanitized.length * 3) / 4) - paddingLength;\n};\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: attachment.base64Content\n\t\t\t? base64ByteLength(attachment.base64Content)\n\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.taxPercent),\n\t\ttax_category_id: normalizeText(charge.taxCategoryId),\n\t\ttax_scheme_id: normalizeText(charge.taxSchemeId),\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) => {\n\tconst subtotalSum = ubl.taxSubtotals.reduce(\n\t\t(sum, subtotal) => sum + subtotal.taxAmount,\n\t\t0,\n\t);\n\tif (ubl.taxSubtotals.length > 0 && Number.isFinite(subtotalSum)) {\n\t\treturn subtotalSum;\n\t}\n\treturn ubl.monetaryTotal.taxInclusiveAmount - ubl.monetaryTotal.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);\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 */\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 Error(\"Failed to parse UBL invoice XML\");\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));\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.taxPercent),\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.taxCategoryId),\n\t\t\ttax_scheme_id: normalizeText(line.taxSchemeId),\n\t\t\ttax_subtotals: line.taxSubtotals ?? [],\n\t\t\tallowance_charges: sanitizeAllowanceCharges(line.allowanceCharges),\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),\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),\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? {\n\t\t\t\t\t\t\tcode: normalizeText(ubl.paymentMeans.code),\n\t\t\t\t\t\t\tcode_name: normalizeText(ubl.paymentMeans.codeName),\n\t\t\t\t\t\t\tpayment_id: normalizeText(ubl.paymentMeans.paymentId),\n\t\t\t\t\t\t\tiban: normalizeText(ubl.paymentMeans.iban),\n\t\t\t\t\t\t\tbic: normalizeText(ubl.paymentMeans.bic),\n\t\t\t\t\t\t\taccount_name: normalizeText(ubl.paymentMeans.accountName),\n\t\t\t\t\t\t\tmandate_id: normalizeText(ubl.paymentMeans.mandateId),\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t\t\tpayment_means_list: paymentMeansList.map((item) => ({\n\t\t\t\t\tcode: normalizeText(item.code),\n\t\t\t\t\tcode_name: normalizeText(item.codeName),\n\t\t\t\t\tpayment_id: normalizeText(item.paymentId),\n\t\t\t\t\tiban: normalizeText(item.iban),\n\t\t\t\t\tbic: normalizeText(item.bic),\n\t\t\t\t\taccount_name: normalizeText(item.accountName),\n\t\t\t\t\tmandate_id: normalizeText(item.mandateId),\n\t\t\t\t})),\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.endpointId),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.seller.endpointSchemeId),\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.companyIdSchemeId),\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.endpointId),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.buyer.endpointSchemeId),\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.companyIdSchemeId),\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.taxSubtotals,\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":";;AAmBA,MAAM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AAI,MAAM,wBAAwB,CAAC;MAC1D,cAAc,cAAc,IAAI,MAAM,SAAS,IAAI;MACnD,eAAe,cAAc,IAAI,MAAM,SAAS,KAAK;MACrD,eAAe,cAAc,IAAI,MAAM,SAAS,KAAK;KACtD;KACA,6BAA6B;KAC7B,6BAA6B;KAC7B,eAAe,IAAI;KACnB,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"}
1
+ {"version":3,"file":"index.js","names":["XmlDomParser","trimmed","cbcText","cacElement","cbcDirectText"],"sources":["../src/errors.ts","../src/xml-dom.ts","../src/parser.ts","../src/attachments.ts","../src/mlr.ts","../src/normalize.ts"],"sourcesContent":["/**\n * Thrown by the parse side of this package when input is broken: malformed\n * XML, or a UBL document missing an element EN 16931 makes mandatory. A parser\n * returns `null` instead when the input is well-formed but not the document\n * type it parses.\n */\nexport class UblParseError extends Error {\n\toverride readonly cause?: unknown;\n\n\tconstructor(message: string, options?: { cause?: unknown }) {\n\t\tsuper(message);\n\t\tthis.name = \"UblParseError\";\n\t\tif (options && \"cause\" in options) this.cause = options.cause;\n\t}\n}\n","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\tUblContact,\n\tUblDelivery,\n\tUblDocumentReference,\n\tUblInvoice,\n\tUblInvoicePeriod,\n\tUblItemProperty,\n\tUblLine,\n\tUblMonetaryTotal,\n\tUblParty,\n\tUblPartyIdentification,\n\tUblPaymentMeans,\n\tUblTaxSubtotal,\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\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 = cacElement(root, role);\n\tconst party = wrapper ? cacElement(wrapper, \"Party\") : null;\n\tif (!party) return {};\n\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\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: companyIdEl\n\t\t\t? trimmed(companyIdEl.textContent)\n\t\t\t: partyId\n\t\t\t\t? cbcText(partyId, \"ID\")\n\t\t\t\t: undefined,\n\t\tcompanyIdSchemeId: attribute(companyIdEl, \"schemeID\"),\n\t\tendpointId: trimmed(endpointEl?.textContent),\n\t\tendpointSchemeId: attribute(endpointEl, \"schemeID\"),\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\nfunction parseTaxSubtotal(sub: Element): UblTaxSubtotal {\n\tconst cat = cacElement(sub, \"TaxCategory\");\n\treturn {\n\t\ttaxableAmount: cbcNumber(sub, \"TaxableAmount\"),\n\t\ttaxAmount: cbcNumber(sub, \"TaxAmount\"),\n\t\ttaxPercent:\n\t\t\t(cat ? cbcNumber(cat, \"Percent\") : undefined) ?? cbcNumber(sub, \"Percent\"),\n\t\ttaxCategoryId: cat ? cbcText(cat, \"ID\") : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(cat),\n\t\ttaxExemptionReason: cat ? cbcText(cat, \"TaxExemptionReason\") : undefined,\n\t};\n}\n\nfunction parseTaxSubtotalsFromTaxTotal(taxTotal: Element): UblTaxSubtotal[] {\n\treturn cacDirectElements(taxTotal, \"TaxSubtotal\").map(parseTaxSubtotal);\n}\n\nfunction parseTaxSubtotals(root: Element): UblTaxSubtotal[] {\n\tconst taxTotals = cacDirectElements(root, \"TaxTotal\");\n\tif (taxTotals.length === 0) return [];\n\treturn taxTotals.flatMap(parseTaxSubtotalsFromTaxTotal);\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\ttaxPercent: taxCategory ? cbcNumber(taxCategory, \"Percent\") : undefined,\n\t\ttaxCategoryId: taxCategory ? cbcText(taxCategory, \"ID\") : undefined,\n\t\ttaxSchemeId: parseTaxSchemeId(taxCategory),\n\t};\n}\n\nfunction parseAllowanceCharges(parent: Element): UblAllowanceCharge[] {\n\treturn cacDirectElements(parent, \"AllowanceCharge\").map(parseAllowanceCharge);\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 taxCategory = item ? cacElement(item, \"ClassifiedTaxCategory\") : null;\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\tconst taxPercent =\n\t\t\tlineTaxSubtotals[0]?.taxPercent ??\n\t\t\t(taxCategory ? cbcNumber(taxCategory, \"Percent\") : undefined);\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 lineAllowanceCharges = parseAllowanceCharges(line);\n\t\tconst priceAllowanceCharges = price ? parseAllowanceCharges(price) : [];\n\t\tconst allowanceCharges = [...lineAllowanceCharges, ...priceAllowanceCharges];\n\t\tconst discountAmount = allowanceCharges.reduce(\n\t\t\t(sum, charge) =>\n\t\t\t\tcharge.chargeIndicator ? sum : sum + Math.abs(charge.amount ?? 0),\n\t\t\t0,\n\t\t);\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\treturn {\n\t\t\tid: requiredCbcText(line, \"ID\", `${lineTag} identifier`),\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\ttaxPercent,\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\ttaxCategoryId:\n\t\t\t\tlineTaxSubtotals[0]?.taxCategoryId ??\n\t\t\t\t(taxCategory ? cbcText(taxCategory, \"ID\") : undefined),\n\t\t\ttaxSchemeId:\n\t\t\t\tlineTaxSubtotals[0]?.taxSchemeId ?? parseTaxSchemeId(taxCategory),\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\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\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\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 ? cbcText(mandate, \"ID\") : 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 address = parseAddressFromElement(\n\t\tdeliveryLocation ? cacElement(deliveryLocation, \"Address\") : null,\n\t);\n\tif (!actualDeliveryDate && !address) return undefined;\n\treturn {\n\t\tactualDeliveryDate,\n\t\taddress,\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\nfunction parseAttachments(root: Element): {\n\tattachments: UblAttachment[] | undefined;\n\tdocumentReferences: UblDocumentReference[] | undefined;\n} {\n\tconst refs = cacElements(root, \"AdditionalDocumentReference\");\n\tconst attachments: UblAttachment[] = [];\n\tconst documentReferences: UblDocumentReference[] = [];\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\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};\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 = cacElement(root, \"ContractDocumentReference\");\n\tconst projectReference = cacElement(root, \"ProjectReference\");\n\tconst { attachments, documentReferences } = parseAttachments(root);\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: cbcText(root, \"DueDate\"),\n\t\ttaxPointDate: cbcText(root, \"TaxPointDate\"),\n\t\tcurrency,\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: undefined,\n\t\tbillingReference: parseBillingReference(root),\n\t\tseller: parseParty(root, \"AccountingSupplierParty\"),\n\t\tbuyer: parseParty(root, \"AccountingCustomerParty\"),\n\t\tdelivery: parseDelivery(root),\n\t\tlines: parseLines(root, isCreditNote),\n\t\ttaxSubtotals: parseTaxSubtotals(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.taxPercent),\n\t\ttax_category_id: normalizeText(charge.taxCategoryId),\n\t\ttax_scheme_id: normalizeText(charge.taxSchemeId),\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 subtotalSum = ubl.taxSubtotals.reduce(\n\t\t(sum, subtotal) => sum + (subtotal.taxAmount ?? 0),\n\t\t0,\n\t);\n\tif (ubl.taxSubtotals.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.taxPercent),\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.taxCategoryId),\n\t\t\ttax_scheme_id: normalizeText(line.taxSchemeId),\n\t\t\ttax_subtotals: line.taxSubtotals ?? [],\n\t\t\tallowance_charges: sanitizeAllowanceCharges(line.allowanceCharges),\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),\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),\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.endpointId),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.seller.endpointSchemeId),\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.companyIdSchemeId),\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.endpointId),\n\t\t\t\t\tendpoint_scheme_id: normalizeText(ubl.buyer.endpointSchemeId),\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.companyIdSchemeId),\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.taxSubtotals,\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":";;;;;;;;A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AK;KACtD;KACA,6BAA6B;KAC7B,6BAA6B;KAC7B,eAAe,IAAI;KACnB,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,6 +1,6 @@
1
1
  {
2
2
  "name": "@financica/ubl",
3
- "version": "0.15.1",
3
+ "version": "0.16.0",
4
4
  "description": "UBL (Universal Business Language) invoice toolkit for 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",
@@ -11,9 +11,17 @@
11
11
  "directory": "packages/ubl"
12
12
  },
13
13
  "files": [
14
- "dist"
14
+ "dist",
15
+ "src",
16
+ "!src/**/*.test.ts",
17
+ "!src/**/*.test.tsx",
18
+ "!src/**/__tests__/**",
19
+ "CHANGELOG.md",
20
+ "LICENSE",
21
+ "README.md"
15
22
  ],
16
23
  "type": "module",
24
+ "sideEffects": false,
17
25
  "main": "./dist/index.js",
18
26
  "types": "./dist/index.d.ts",
19
27
  "exports": {
@@ -24,7 +32,8 @@
24
32
  "./build": {
25
33
  "types": "./dist/build/index.d.ts",
26
34
  "import": "./dist/build/index.js"
27
- }
35
+ },
36
+ "./package.json": "./package.json"
28
37
  },
29
38
  "publishConfig": {
30
39
  "access": "public"
@@ -37,14 +46,14 @@
37
46
  "lint:fix": "oxlint --fix",
38
47
  "format": "oxfmt",
39
48
  "format:check": "oxfmt --check",
40
- "test": "vitest run",
41
- "test:watch": "vitest",
42
- "test:coverage": "vitest run --coverage",
49
+ "test": "vitest run --root ../.. --project @financica/ubl",
50
+ "test:watch": "vitest --root ../.. --project @financica/ubl",
51
+ "test:coverage": "vitest --root ../.. --project @financica/ubl run --coverage",
43
52
  "ci": "bun run lint && bun run format:check && bun run build && bun run typecheck && bun run test",
44
53
  "prepack": "bun run build"
45
54
  },
46
55
  "dependencies": {
47
- "@financica/peppol": ">=0.7.0 <1.0.0",
56
+ "@financica/peppol": ">=0.8.0 <1.0.0",
48
57
  "@xmldom/xmldom": "^0.9.11"
49
58
  },
50
59
  "engines": {
@@ -0,0 +1,67 @@
1
+ import { UblParseError } from "./errors.js";
2
+ import { parseUblInvoice } from "./parser.js";
3
+ import type { UblAttachment } from "./types.js";
4
+
5
+ /**
6
+ * An embedded attachment extracted from a UBL document's
7
+ * `AdditionalDocumentReference` entries, with its binary content still
8
+ * base64-encoded. `sizeBytes` is the decoded size.
9
+ */
10
+ export interface UblEmbeddedAttachment {
11
+ id?: string | undefined;
12
+ filename: string;
13
+ mimeCode: string;
14
+ sizeBytes: number;
15
+ /** Zero-based position among the document's embedded attachments. */
16
+ lineOrder: number;
17
+ base64Content: string;
18
+ }
19
+
20
+ /** Decoded byte length of a base64 string, accounting for `=` padding. */
21
+ export const base64DecodedSize = (base64: string): number => {
22
+ const sanitized = base64.replace(/\s+/g, "");
23
+ if (!sanitized) return 0;
24
+ const padding = sanitized.endsWith("==") ? 2 : sanitized.endsWith("=") ? 1 : 0;
25
+ return Math.floor((sanitized.length * 3) / 4) - padding;
26
+ };
27
+
28
+ /**
29
+ * Extract the embedded attachments (typically the human-readable PDF) from a
30
+ * UBL invoice or credit note XML. Attachments referenced only by external URI
31
+ * (no `EmbeddedDocumentBinaryObject`) are skipped; use {@link parseUblInvoice}
32
+ * directly when those matter.
33
+ *
34
+ * @throws {UblParseError} when the XML is malformed or not a UBL invoice.
35
+ */
36
+ export const extractUblEmbeddedAttachments = (xml: string): UblEmbeddedAttachment[] => {
37
+ const parsed = parseUblInvoice(xml);
38
+ if (!parsed) throw new UblParseError("Document is not a UBL Invoice or CreditNote");
39
+ if (!parsed.attachments || parsed.attachments.length === 0) return [];
40
+
41
+ return parsed.attachments
42
+ .map((attachment, index): UblEmbeddedAttachment | null => {
43
+ const base64Content = attachment.base64Content?.trim();
44
+ if (!base64Content) return null;
45
+ return {
46
+ id: attachment.id,
47
+ filename: attachment.filename ?? `attachment-${index + 1}`,
48
+ mimeCode: attachment.mimeCode ?? "application/octet-stream",
49
+ sizeBytes: base64DecodedSize(base64Content),
50
+ lineOrder: index,
51
+ base64Content,
52
+ };
53
+ })
54
+ .filter((entry): entry is UblEmbeddedAttachment => entry !== null);
55
+ };
56
+
57
+ /**
58
+ * Whether an attachment looks like a PDF, by MIME type first and filename
59
+ * extension as a fallback.
60
+ */
61
+ export const isPdfLikeAttachment = (
62
+ attachment: Pick<UblAttachment, "filename" | "mimeCode">,
63
+ ): boolean => {
64
+ const mimeCode = attachment.mimeCode?.toLowerCase() ?? "";
65
+ if (mimeCode === "application/pdf" || mimeCode.endsWith("/pdf")) return true;
66
+ return attachment.filename?.toLowerCase().endsWith(".pdf") ?? false;
67
+ };
@@ -0,0 +1,64 @@
1
+ import type { UblAddress } from "./ubl/types";
2
+ import { normalizeString } from "./utils";
3
+
4
+ const normalizeCountryCode = (value: string | null | undefined): string | null => {
5
+ const trimmed = normalizeString(value);
6
+ if (!trimmed) return null;
7
+ return trimmed.length >= 2 ? trimmed.toUpperCase().slice(0, 2) : null;
8
+ };
9
+
10
+ /**
11
+ * A free-form postal address as accepted by {@link normalizeAddress}.
12
+ *
13
+ * Both the Stripe shape (`line1`, `postal_code`, `country`, `state`) and the
14
+ * legacy/internal shape (`street`, `zip_code`, `country_code`,
15
+ * `country_subentity`) are accepted; when both keys are present the Stripe
16
+ * one wins.
17
+ */
18
+ export interface AddressInput {
19
+ line1?: string | null;
20
+ line2?: string | null;
21
+ street?: string | null;
22
+ city?: string | null;
23
+ postal_code?: string | null;
24
+ zip_code?: string | null;
25
+ state?: string | null;
26
+ country_subentity?: string | null;
27
+ country?: string | null;
28
+ country_code?: string | null;
29
+ }
30
+
31
+ /**
32
+ * Normalize a free-form address (Stripe shape, custom shape, or an internal
33
+ * shape) into a {@link UblAddress}.
34
+ *
35
+ * Accepts both `line1`/`postal_code`/`country` (Stripe) and `street`/`zip_code`
36
+ * (legacy/internal) keys. Falls back to `fallbackCountryCode` when the address
37
+ * has no country, but never silently substitutes a caller's country — pass
38
+ * `null` when "no country" is the right answer.
39
+ */
40
+ export const normalizeAddress = (
41
+ address: AddressInput | null | undefined,
42
+ fallbackCountryCode: string | null,
43
+ fallbackLine?: string | null,
44
+ ): UblAddress => {
45
+ const record: AddressInput = address ?? {};
46
+ const countryCode =
47
+ normalizeCountryCode(normalizeString(record.country)) ??
48
+ normalizeCountryCode(normalizeString(record.country_code)) ??
49
+ normalizeCountryCode(fallbackCountryCode);
50
+ return {
51
+ street:
52
+ normalizeString(record.line1) ??
53
+ normalizeString(record.street) ??
54
+ fallbackLine ??
55
+ null,
56
+ additionalStreet: normalizeString(record.line2),
57
+ city: normalizeString(record.city),
58
+ postalZone:
59
+ normalizeString(record.postal_code) ?? normalizeString(record.zip_code),
60
+ countrySubentity:
61
+ normalizeString(record.state) ?? normalizeString(record.country_subentity),
62
+ countryCode,
63
+ };
64
+ };
@@ -0,0 +1,33 @@
1
+ import type { UblAttachment, UblDocument } from "./ubl/types";
2
+
3
+ /**
4
+ * Build a UBL embedded-document attachment (BG-24) from raw bytes — e.g. the
5
+ * rendered PDF of the invoice. Emitted as a `cac:AdditionalDocumentReference`
6
+ * with an inline base64 `cbc:EmbeddedDocumentBinaryObject`.
7
+ */
8
+ export const buildPdfAttachment = (params: {
9
+ filename: string;
10
+ bytes: Uint8Array;
11
+ /** Document reference ID (BT-122). Defaults to the filename. */
12
+ id?: string;
13
+ }): UblAttachment => ({
14
+ id: params.id ?? params.filename,
15
+ filename: params.filename,
16
+ mimeCode: "application/pdf",
17
+ base64: Buffer.from(params.bytes).toString("base64"),
18
+ });
19
+
20
+ /**
21
+ * Replace each attachment's base64 payload with `[omitted]` plus a length, so a
22
+ * {@link UblDocument} is safe to log or persist for audit.
23
+ */
24
+ export const sanitizeUblDocumentForAudit = (doc: UblDocument): UblDocument => {
25
+ if (doc.attachments.length === 0) return doc;
26
+ return {
27
+ ...doc,
28
+ attachments: doc.attachments.map((attachment) => ({
29
+ ...attachment,
30
+ base64: `[omitted ${attachment.base64.length} chars]`,
31
+ })),
32
+ };
33
+ };