@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 CHANGED
@@ -1,19 +1,77 @@
1
1
  import { DOMParser } from "@xmldom/xmldom";
2
+ //#region src/errors.ts
3
+ /**
4
+ * Thrown by the parse side of this package when input is broken: malformed
5
+ * XML, or a UBL document missing an element EN 16931 makes mandatory. A parser
6
+ * returns `null` instead when the input is well-formed but not the document
7
+ * type it parses.
8
+ */
9
+ var UblParseError = class extends Error {
10
+ cause;
11
+ constructor(message, options) {
12
+ super(message);
13
+ this.name = "UblParseError";
14
+ if (options && "cause" in options) this.cause = options.cause;
15
+ }
16
+ };
17
+ //#endregion
18
+ //#region src/xml-dom.ts
19
+ const CBC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
20
+ const CAC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
21
+ /**
22
+ * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.
23
+ * @xmldom/xmldom resolves external entities by default, so we remove DOCTYPE
24
+ * blocks (including inline DTD subsets) before parsing.
25
+ */
26
+ const stripDoctype = (xml) => xml.replace(/<!DOCTYPE\s[^>[]*(?:\[[^\]]*\])?>/gi, "");
27
+ /**
28
+ * Parse XML into a DOM, preferring the host's `DOMParser` (browsers) and
29
+ * falling back to @xmldom/xmldom. Throws {@link UblParseError} when the XML
30
+ * is malformed.
31
+ */
32
+ const parseXmlDocument = (xml) => {
33
+ const safeXml = stripDoctype(xml);
34
+ const BrowserDomParser = globalThis.DOMParser;
35
+ const parser = BrowserDomParser ? new BrowserDomParser() : new DOMParser();
36
+ let doc;
37
+ try {
38
+ doc = parser.parseFromString(safeXml, "text/xml");
39
+ } catch (cause) {
40
+ throw new UblParseError("Malformed XML", { cause });
41
+ }
42
+ if (doc.getElementsByTagName("parsererror").length > 0 || !doc.documentElement) throw new UblParseError("Malformed XML");
43
+ return doc;
44
+ };
45
+ //#endregion
2
46
  //#region src/parser.ts
3
- const CBC_NS$1 = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
4
- const CAC_NS$1 = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
47
+ const trimmed$1 = (value) => {
48
+ const text = value?.trim();
49
+ return text ? text : void 0;
50
+ };
51
+ /** First descendant CBC element's trimmed text; absent or blank is `undefined`. */
5
52
  function cbcText$1(parent, tag) {
6
- return parent.getElementsByTagNameNS(CBC_NS$1, tag)[0]?.textContent?.trim() ?? "";
53
+ return trimmed$1(parent.getElementsByTagNameNS(CBC_NS, tag)[0]?.textContent);
54
+ }
55
+ /** Like {@link cbcText} but throws: the element is mandatory in EN 16931. */
56
+ function requiredCbcText(parent, tag, what) {
57
+ const value = cbcText$1(parent, tag);
58
+ if (value === void 0) throw new UblParseError(`Missing ${what} (cbc:${tag})`);
59
+ return value;
7
60
  }
61
+ const toNumber = (value) => {
62
+ if (value === void 0) return void 0;
63
+ const parsed = Number.parseFloat(value);
64
+ return Number.isNaN(parsed) ? void 0 : parsed;
65
+ };
8
66
  function cacElement$1(parent, tag) {
9
- return parent.getElementsByTagNameNS(CAC_NS$1, tag)[0] ?? null;
67
+ return parent.getElementsByTagNameNS("urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", tag)[0] ?? null;
10
68
  }
11
69
  function cacElements(parent, tag) {
12
- return Array.from(parent.getElementsByTagNameNS(CAC_NS$1, tag));
70
+ return Array.from(parent.getElementsByTagNameNS(CAC_NS, tag));
13
71
  }
72
+ /** First descendant CBC element as a number; absent or non-numeric is `undefined`. */
14
73
  function cbcNumber(parent, tag) {
15
- const n = Number.parseFloat(cbcText$1(parent, tag));
16
- return Number.isNaN(n) ? 0 : n;
74
+ return toNumber(cbcText$1(parent, tag));
17
75
  }
18
76
  function childElementsByTagNs(parent, namespace, tag) {
19
77
  const elements = [];
@@ -26,30 +84,28 @@ function childElementsByTagNs(parent, namespace, tag) {
26
84
  return elements;
27
85
  }
28
86
  function cbcDirectText$1(parent, tag) {
29
- return childElementsByTagNs(parent, CBC_NS$1, tag)[0]?.textContent?.trim() ?? "";
87
+ return trimmed$1(childElementsByTagNs(parent, CBC_NS, tag)[0]?.textContent);
30
88
  }
31
89
  function cbcDirectNumber(parent, tag) {
32
- const value = cbcDirectText$1(parent, tag);
33
- if (!value) return null;
34
- const parsed = Number.parseFloat(value);
35
- return Number.isNaN(parsed) ? null : parsed;
90
+ return toNumber(cbcDirectText$1(parent, tag));
36
91
  }
92
+ const attribute = (el, name) => trimmed$1(el?.getAttribute(name));
37
93
  function cacDirectElement(parent, tag) {
38
- return childElementsByTagNs(parent, CAC_NS$1, tag)[0] ?? null;
94
+ return childElementsByTagNs(parent, "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", tag)[0] ?? null;
39
95
  }
40
96
  function cacDirectElements(parent, tag) {
41
- return childElementsByTagNs(parent, CAC_NS$1, tag);
97
+ return childElementsByTagNs(parent, CAC_NS, tag);
42
98
  }
43
99
  function parseAddressFromElement(address) {
44
100
  if (!address) return void 0;
45
101
  const country = cacElement$1(address, "Country");
46
102
  return {
47
103
  street: cbcText$1(address, "StreetName"),
48
- additionalStreet: cbcText$1(address, "AdditionalStreetName") || void 0,
104
+ additionalStreet: cbcText$1(address, "AdditionalStreetName"),
49
105
  city: cbcText$1(address, "CityName"),
50
106
  postalZone: cbcText$1(address, "PostalZone"),
51
- countrySubentity: cbcText$1(address, "CountrySubentity") || void 0,
52
- countryCode: country ? cbcText$1(country, "IdentificationCode") : ""
107
+ countrySubentity: cbcText$1(address, "CountrySubentity"),
108
+ countryCode: country ? cbcText$1(country, "IdentificationCode") : void 0
53
109
  };
54
110
  }
55
111
  function parseAddress(party) {
@@ -59,7 +115,7 @@ function parseTaxSchemeId(parent) {
59
115
  if (!parent) return void 0;
60
116
  const taxScheme = cacElement$1(parent, "TaxScheme");
61
117
  if (!taxScheme) return void 0;
62
- return cbcText$1(taxScheme, "ID") || void 0;
118
+ return cbcText$1(taxScheme, "ID");
63
119
  }
64
120
  function parseContact(party) {
65
121
  const contact = cacElement$1(party, "Contact");
@@ -69,9 +125,9 @@ function parseContact(party) {
69
125
  const email = cbcText$1(contact, "ElectronicMail");
70
126
  if (!name && !phone && !email) return void 0;
71
127
  return {
72
- name: name || void 0,
73
- phone: phone || void 0,
74
- email: email || void 0
128
+ name,
129
+ phone,
130
+ email
75
131
  };
76
132
  }
77
133
  function parsePartyIdentifications(party) {
@@ -80,10 +136,9 @@ function parsePartyIdentifications(party) {
80
136
  for (const idEl of ids) {
81
137
  const idValue = cbcText$1(idEl, "ID");
82
138
  if (!idValue) continue;
83
- const schemeIdAttr = idEl.getElementsByTagNameNS(CBC_NS$1, "ID")[0]?.getAttribute("schemeID");
84
139
  result.push({
85
140
  id: idValue,
86
- schemeId: schemeIdAttr || void 0
141
+ schemeId: attribute(idEl.getElementsByTagNameNS(CBC_NS, "ID")[0], "schemeID")
87
142
  });
88
143
  }
89
144
  return result;
@@ -91,24 +146,24 @@ function parsePartyIdentifications(party) {
91
146
  function parseParty(root, role) {
92
147
  const wrapper = cacElement$1(root, role);
93
148
  const party = wrapper ? cacElement$1(wrapper, "Party") : null;
94
- if (!party) return { name: "Unknown" };
149
+ if (!party) return {};
95
150
  const partyName = cacElement$1(party, "PartyName");
96
151
  const legalEntity = cacElement$1(party, "PartyLegalEntity");
97
152
  const taxScheme = cacElement$1(party, "PartyTaxScheme");
98
153
  const partyId = cacElement$1(party, "PartyIdentification");
99
- const endpointEl = party.getElementsByTagNameNS(CBC_NS$1, "EndpointID")[0];
154
+ const endpointEl = party.getElementsByTagNameNS(CBC_NS, "EndpointID")[0];
100
155
  const partyIdentifications = parsePartyIdentifications(party);
101
- const companyIdEl = legalEntity ? legalEntity.getElementsByTagNameNS(CBC_NS$1, "CompanyID")[0] : null;
156
+ const companyIdEl = legalEntity ? legalEntity.getElementsByTagNameNS(CBC_NS, "CompanyID")[0] : null;
102
157
  return {
103
- name: partyName ? cbcText$1(partyName, "Name") : "",
104
- registrationName: legalEntity ? cbcText$1(legalEntity, "RegistrationName") || void 0 : void 0,
105
- companyLegalForm: legalEntity ? cbcText$1(legalEntity, "CompanyLegalForm") || void 0 : void 0,
106
- vatId: taxScheme ? cbcText$1(taxScheme, "CompanyID") || void 0 : void 0,
158
+ name: partyName ? cbcText$1(partyName, "Name") : void 0,
159
+ registrationName: legalEntity ? cbcText$1(legalEntity, "RegistrationName") : void 0,
160
+ companyLegalForm: legalEntity ? cbcText$1(legalEntity, "CompanyLegalForm") : void 0,
161
+ vatId: taxScheme ? cbcText$1(taxScheme, "CompanyID") : void 0,
107
162
  taxSchemeId: parseTaxSchemeId(taxScheme),
108
- companyId: companyIdEl ? companyIdEl.textContent?.trim() || void 0 : partyId ? cbcText$1(partyId, "ID") || void 0 : void 0,
109
- companyIdSchemeId: companyIdEl?.getAttribute("schemeID") || void 0,
110
- endpointId: endpointEl?.textContent?.trim() || void 0,
111
- endpointSchemeId: endpointEl?.getAttribute("schemeID") || void 0,
163
+ companyId: companyIdEl ? trimmed$1(companyIdEl.textContent) : partyId ? cbcText$1(partyId, "ID") : void 0,
164
+ companyIdSchemeId: attribute(companyIdEl, "schemeID"),
165
+ endpointId: trimmed$1(endpointEl?.textContent),
166
+ endpointSchemeId: attribute(endpointEl, "schemeID"),
112
167
  partyIdentifications: partyIdentifications.length > 0 ? partyIdentifications : void 0,
113
168
  address: parseAddress(party),
114
169
  contact: parseContact(party)
@@ -119,10 +174,10 @@ function parseTaxSubtotal(sub) {
119
174
  return {
120
175
  taxableAmount: cbcNumber(sub, "TaxableAmount"),
121
176
  taxAmount: cbcNumber(sub, "TaxAmount"),
122
- taxPercent: (cat ? cbcNumber(cat, "Percent") : 0) || cbcNumber(sub, "Percent"),
123
- taxCategoryId: cat ? cbcText$1(cat, "ID") || void 0 : void 0,
177
+ taxPercent: (cat ? cbcNumber(cat, "Percent") : void 0) ?? cbcNumber(sub, "Percent"),
178
+ taxCategoryId: cat ? cbcText$1(cat, "ID") : void 0,
124
179
  taxSchemeId: parseTaxSchemeId(cat),
125
- taxExemptionReason: cat ? cbcText$1(cat, "TaxExemptionReason") || void 0 : void 0
180
+ taxExemptionReason: cat ? cbcText$1(cat, "TaxExemptionReason") : void 0
126
181
  };
127
182
  }
128
183
  function parseTaxSubtotalsFromTaxTotal(taxTotal) {
@@ -135,16 +190,16 @@ function parseTaxSubtotals(root) {
135
190
  }
136
191
  function parseAllowanceCharge(charge) {
137
192
  const taxCategory = cacElement$1(charge, "TaxCategory");
138
- const indicatorRaw = cbcDirectText$1(charge, "ChargeIndicator").toLowerCase();
193
+ const indicatorRaw = cbcDirectText$1(charge, "ChargeIndicator")?.toLowerCase();
139
194
  return {
140
195
  chargeIndicator: indicatorRaw === "true" || indicatorRaw === "1",
141
196
  amount: cbcNumber(charge, "Amount"),
142
- baseAmount: cbcDirectNumber(charge, "BaseAmount") ?? void 0,
143
- multiplierFactorNumeric: cbcDirectNumber(charge, "MultiplierFactorNumeric") ?? void 0,
144
- reason: cbcText$1(charge, "AllowanceChargeReason") || void 0,
145
- reasonCode: cbcText$1(charge, "AllowanceChargeReasonCode") || void 0,
197
+ baseAmount: cbcDirectNumber(charge, "BaseAmount"),
198
+ multiplierFactorNumeric: cbcDirectNumber(charge, "MultiplierFactorNumeric"),
199
+ reason: cbcText$1(charge, "AllowanceChargeReason"),
200
+ reasonCode: cbcText$1(charge, "AllowanceChargeReasonCode"),
146
201
  taxPercent: taxCategory ? cbcNumber(taxCategory, "Percent") : void 0,
147
- taxCategoryId: taxCategory ? cbcText$1(taxCategory, "ID") || void 0 : void 0,
202
+ taxCategoryId: taxCategory ? cbcText$1(taxCategory, "ID") : void 0,
148
203
  taxSchemeId: parseTaxSchemeId(taxCategory)
149
204
  };
150
205
  }
@@ -153,25 +208,26 @@ function parseAllowanceCharges(parent) {
153
208
  }
154
209
  function parseLines(root, isCreditNote) {
155
210
  const qtyTag = isCreditNote ? "CreditedQuantity" : "InvoicedQuantity";
156
- return cacElements(root, isCreditNote ? "CreditNoteLine" : "InvoiceLine").map((line) => {
211
+ const lineTag = isCreditNote ? "CreditNoteLine" : "InvoiceLine";
212
+ return cacElements(root, lineTag).map((line) => {
157
213
  const item = cacElement$1(line, "Item");
158
214
  const price = cacElement$1(line, "Price");
159
215
  const taxCategory = item ? cacElement$1(item, "ClassifiedTaxCategory") : null;
160
216
  const sellersId = item ? cacElement$1(item, "SellersItemIdentification") : null;
161
217
  const buyersId = item ? cacElement$1(item, "BuyersItemIdentification") : null;
162
- const qtyEl = line.getElementsByTagNameNS(CBC_NS$1, qtyTag)[0];
218
+ const qtyEl = line.getElementsByTagNameNS(CBC_NS, qtyTag)[0];
163
219
  const lineExtensionAmount = cbcNumber(line, "LineExtensionAmount");
164
220
  const lineTaxTotal = cacDirectElement(line, "TaxTotal");
165
221
  const lineTaxSubtotals = lineTaxTotal ? parseTaxSubtotalsFromTaxTotal(lineTaxTotal) : [];
166
- const taxAmountFromSubtotals = lineTaxSubtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0);
167
- const taxAmountFromLineTotal = lineTaxTotal ? cbcDirectNumber(lineTaxTotal, "TaxAmount") : null;
222
+ const taxAmountFromSubtotals = lineTaxSubtotals.reduce((sum, subtotal) => sum + (subtotal.taxAmount ?? 0), 0);
223
+ const taxAmountFromLineTotal = lineTaxTotal ? cbcDirectNumber(lineTaxTotal, "TaxAmount") : void 0;
168
224
  const taxPercent = lineTaxSubtotals[0]?.taxPercent ?? (taxCategory ? cbcNumber(taxCategory, "Percent") : void 0);
169
- const computedTaxAmount = taxPercent !== void 0 ? Number((lineExtensionAmount * taxPercent / 100).toFixed(2)) : void 0;
225
+ const computedTaxAmount = taxPercent !== void 0 && lineExtensionAmount !== void 0 ? Number((lineExtensionAmount * taxPercent / 100).toFixed(2)) : void 0;
170
226
  const lineAllowanceCharges = parseAllowanceCharges(line);
171
227
  const priceAllowanceCharges = price ? parseAllowanceCharges(price) : [];
172
228
  const allowanceCharges = [...lineAllowanceCharges, ...priceAllowanceCharges];
173
- const discountAmount = allowanceCharges.reduce((sum, charge) => charge.chargeIndicator ? sum : sum + Math.abs(charge.amount), 0);
174
- const chargeAmount = allowanceCharges.reduce((sum, charge) => charge.chargeIndicator ? sum + Math.abs(charge.amount) : sum, 0);
229
+ const discountAmount = allowanceCharges.reduce((sum, charge) => charge.chargeIndicator ? sum : sum + Math.abs(charge.amount ?? 0), 0);
230
+ const chargeAmount = allowanceCharges.reduce((sum, charge) => charge.chargeIndicator ? sum + Math.abs(charge.amount ?? 0) : sum, 0);
175
231
  const additionalItemProperties = [];
176
232
  if (item) for (const prop of cacElements(item, "AdditionalItemProperty")) {
177
233
  const propName = cbcText$1(prop, "Name");
@@ -181,27 +237,27 @@ function parseLines(root, isCreditNote) {
181
237
  value: propValue
182
238
  });
183
239
  }
184
- const priceAmount = price ? cbcNumber(price, "PriceAmount") : 0;
185
- const priceBaseQuantity = price ? cbcDirectNumber(price, "BaseQuantity") : null;
186
- const unitPrice = priceBaseQuantity && priceBaseQuantity > 0 ? priceAmount / priceBaseQuantity : priceAmount;
240
+ const priceAmount = price ? cbcNumber(price, "PriceAmount") : void 0;
241
+ const priceBaseQuantity = price ? cbcDirectNumber(price, "BaseQuantity") : void 0;
242
+ const unitPrice = priceAmount !== void 0 && priceBaseQuantity && priceBaseQuantity > 0 ? priceAmount / priceBaseQuantity : priceAmount;
187
243
  return {
188
- id: cbcText$1(line, "ID"),
189
- description: item ? cbcText$1(item, "Description") : "",
244
+ id: requiredCbcText(line, "ID", `${lineTag} identifier`),
245
+ description: item ? cbcText$1(item, "Description") : void 0,
190
246
  quantity: cbcNumber(line, qtyTag),
191
- unitCode: qtyEl?.getAttribute("unitCode") ?? "",
247
+ unitCode: attribute(qtyEl, "unitCode"),
192
248
  unitPrice,
193
249
  lineExtensionAmount,
194
250
  taxPercent,
195
251
  taxAmount: taxAmountFromLineTotal ?? (lineTaxSubtotals.length > 0 ? taxAmountFromSubtotals : computedTaxAmount),
196
- taxCategoryId: lineTaxSubtotals[0]?.taxCategoryId ?? (taxCategory ? cbcText$1(taxCategory, "ID") || void 0 : void 0),
252
+ taxCategoryId: lineTaxSubtotals[0]?.taxCategoryId ?? (taxCategory ? cbcText$1(taxCategory, "ID") : void 0),
197
253
  taxSchemeId: lineTaxSubtotals[0]?.taxSchemeId ?? parseTaxSchemeId(taxCategory),
198
254
  taxSubtotals: lineTaxSubtotals.length > 0 ? lineTaxSubtotals : void 0,
199
255
  allowanceCharges: allowanceCharges.length > 0 ? allowanceCharges : void 0,
200
256
  discountAmount: discountAmount > 0 ? discountAmount : void 0,
201
257
  chargeAmount: chargeAmount > 0 ? chargeAmount : void 0,
202
- itemName: item ? cbcText$1(item, "Name") || void 0 : void 0,
203
- sellersItemId: sellersId ? cbcText$1(sellersId, "ID") || void 0 : void 0,
204
- buyersItemId: buyersId ? cbcText$1(buyersId, "ID") || void 0 : void 0,
258
+ itemName: item ? cbcText$1(item, "Name") : void 0,
259
+ sellersItemId: sellersId ? cbcText$1(sellersId, "ID") : void 0,
260
+ buyersItemId: buyersId ? cbcText$1(buyersId, "ID") : void 0,
205
261
  additionalItemProperties: additionalItemProperties.length > 0 ? additionalItemProperties : void 0,
206
262
  invoicePeriod: parseInvoicePeriod(line)
207
263
  };
@@ -209,36 +265,31 @@ function parseLines(root, isCreditNote) {
209
265
  }
210
266
  function parseMonetaryTotal(root) {
211
267
  const total = cacDirectElement(root, "LegalMonetaryTotal");
212
- if (!total) return {
213
- lineExtensionAmount: 0,
214
- taxExclusiveAmount: 0,
215
- taxInclusiveAmount: 0,
216
- payableAmount: 0
217
- };
268
+ if (!total) return {};
218
269
  return {
219
270
  lineExtensionAmount: cbcNumber(total, "LineExtensionAmount"),
220
271
  taxExclusiveAmount: cbcNumber(total, "TaxExclusiveAmount"),
221
272
  taxInclusiveAmount: cbcNumber(total, "TaxInclusiveAmount"),
222
- allowanceTotalAmount: cbcNumber(total, "AllowanceTotalAmount") || void 0,
223
- chargeTotalAmount: cbcNumber(total, "ChargeTotalAmount") || void 0,
224
- prepaidAmount: cbcNumber(total, "PrepaidAmount") || void 0,
225
- payableRoundingAmount: cbcNumber(total, "PayableRoundingAmount") || void 0,
273
+ allowanceTotalAmount: cbcNumber(total, "AllowanceTotalAmount"),
274
+ chargeTotalAmount: cbcNumber(total, "ChargeTotalAmount"),
275
+ prepaidAmount: cbcNumber(total, "PrepaidAmount"),
276
+ payableRoundingAmount: cbcNumber(total, "PayableRoundingAmount"),
226
277
  payableAmount: cbcNumber(total, "PayableAmount")
227
278
  };
228
279
  }
229
280
  function parsePaymentMeansElement(pm) {
230
281
  const account = cacElement$1(pm, "PayeeFinancialAccount");
231
282
  const branch = account ? cacElement$1(account, "FinancialInstitutionBranch") : null;
232
- const paymentMeansCodeEl = pm.getElementsByTagNameNS(CBC_NS$1, "PaymentMeansCode")[0];
283
+ const paymentMeansCodeEl = pm.getElementsByTagNameNS(CBC_NS, "PaymentMeansCode")[0];
233
284
  const mandate = cacElement$1(pm, "PaymentMandate");
234
285
  return {
235
286
  code: cbcText$1(pm, "PaymentMeansCode"),
236
- codeName: paymentMeansCodeEl?.getAttribute("name") || void 0,
237
- paymentId: cbcText$1(pm, "PaymentID") || void 0,
238
- iban: account ? cbcText$1(account, "ID") || void 0 : void 0,
239
- bic: branch ? cbcText$1(branch, "ID") || void 0 : void 0,
240
- accountName: account && cbcText$1(account, "Name") || void 0,
241
- mandateId: mandate ? cbcText$1(mandate, "ID") || void 0 : void 0
287
+ codeName: attribute(paymentMeansCodeEl, "name"),
288
+ paymentId: cbcText$1(pm, "PaymentID"),
289
+ iban: account ? cbcText$1(account, "ID") : void 0,
290
+ bic: branch ? cbcText$1(branch, "ID") : void 0,
291
+ accountName: account ? cbcText$1(account, "Name") : void 0,
292
+ mandateId: mandate ? cbcText$1(mandate, "ID") : void 0
242
293
  };
243
294
  }
244
295
  function parsePaymentMeansList(root) {
@@ -257,15 +308,15 @@ function parseInvoicePeriod(parent) {
257
308
  const end = cbcText$1(period, "EndDate");
258
309
  if (!start && !end) return void 0;
259
310
  return {
260
- startDate: start || void 0,
261
- endDate: end || void 0,
262
- descriptionCode: cbcText$1(period, "DescriptionCode") || void 0
311
+ startDate: start,
312
+ endDate: end,
313
+ descriptionCode: cbcText$1(period, "DescriptionCode")
263
314
  };
264
315
  }
265
316
  function parseDelivery(root) {
266
317
  const delivery = cacElement$1(root, "Delivery");
267
318
  if (!delivery) return void 0;
268
- const actualDeliveryDate = cbcText$1(delivery, "ActualDeliveryDate") || void 0;
319
+ const actualDeliveryDate = cbcText$1(delivery, "ActualDeliveryDate");
269
320
  const deliveryLocation = cacElement$1(delivery, "DeliveryLocation");
270
321
  const address = parseAddressFromElement(deliveryLocation ? cacElement$1(deliveryLocation, "Address") : null);
271
322
  if (!actualDeliveryDate && !address) return void 0;
@@ -277,10 +328,10 @@ function parseDelivery(root) {
277
328
  function parsePaymentTermsNote(root) {
278
329
  const paymentTerms = cacElement$1(root, "PaymentTerms");
279
330
  if (!paymentTerms) return void 0;
280
- return cbcText$1(paymentTerms, "Note") || void 0;
331
+ return cbcText$1(paymentTerms, "Note");
281
332
  }
282
333
  function parseNotes(root) {
283
- const noteEls = root.getElementsByTagNameNS(CBC_NS$1, "Note");
334
+ const noteEls = root.getElementsByTagNameNS(CBC_NS, "Note");
284
335
  const notes = [];
285
336
  for (let i = 0; i < noteEls.length; i++) {
286
337
  const el = noteEls[i];
@@ -299,7 +350,7 @@ function parseAttachments(root) {
299
350
  for (const ref of refs) {
300
351
  const attachment = cacElement$1(ref, "Attachment");
301
352
  const refId = cbcText$1(ref, "ID");
302
- const description = cbcText$1(ref, "DocumentDescription") || void 0;
353
+ const description = cbcText$1(ref, "DocumentDescription");
303
354
  if (!attachment) {
304
355
  if (refId || description) documentReferences.push({
305
356
  id: refId,
@@ -307,14 +358,14 @@ function parseAttachments(root) {
307
358
  });
308
359
  continue;
309
360
  }
310
- const binaryEl = attachment.getElementsByTagNameNS(CBC_NS$1, "EmbeddedDocumentBinaryObject")[0];
361
+ const binaryEl = attachment.getElementsByTagNameNS(CBC_NS, "EmbeddedDocumentBinaryObject")[0];
311
362
  const externalRef = cacElement$1(attachment, "ExternalReference");
312
363
  if (binaryEl) {
313
364
  const content = binaryEl.textContent?.trim();
314
365
  if (content) attachments.push({
315
366
  id: refId,
316
- filename: binaryEl.getAttribute("filename") || void 0,
317
- mimeCode: binaryEl.getAttribute("mimeCode") || void 0,
367
+ filename: attribute(binaryEl, "filename"),
368
+ mimeCode: attribute(binaryEl, "mimeCode"),
318
369
  description,
319
370
  base64Content: content
320
371
  });
@@ -337,8 +388,8 @@ function parseBillingReference(root) {
337
388
  if (!billingRef) return void 0;
338
389
  const invoiceRef = cacElement$1(billingRef, "InvoiceDocumentReference");
339
390
  if (!invoiceRef) return void 0;
340
- const invoiceId = cbcText$1(invoiceRef, "ID") || void 0;
341
- const invoiceIssueDate = cbcText$1(invoiceRef, "IssueDate") || void 0;
391
+ const invoiceId = cbcText$1(invoiceRef, "ID");
392
+ const invoiceIssueDate = cbcText$1(invoiceRef, "IssueDate");
342
393
  if (!invoiceId && !invoiceIssueDate) return void 0;
343
394
  return {
344
395
  invoiceId,
@@ -346,87 +397,104 @@ function parseBillingReference(root) {
346
397
  };
347
398
  }
348
399
  /**
349
- * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.
350
- * @xmldom/xmldom resolves external entities by default, so we remove
351
- * DOCTYPE blocks (including inline DTD subsets) before parsing.
400
+ * Drop `undefined`-valued keys recursively so an absent field is an absent
401
+ * key, not a key holding `undefined`. Arrays keep their order and length.
352
402
  */
353
- const stripDoctype$1 = (xml) => xml.replace(/<!DOCTYPE\s[^>[]*(?:\[[^\]]*\])?>/gi, "");
354
- function parseUblInvoice(xml) {
355
- try {
356
- const safeXml = stripDoctype$1(xml);
357
- const BrowserDomParser = globalThis.DOMParser;
358
- const doc = (BrowserDomParser ? new BrowserDomParser() : new DOMParser()).parseFromString(safeXml, "text/xml");
359
- if (doc.getElementsByTagName("parsererror").length > 0) return null;
360
- const root = doc.documentElement;
361
- if (!root) return null;
362
- const localName = root.localName;
363
- let documentType;
364
- if (localName === "Invoice") documentType = "Invoice";
365
- else if (localName === "CreditNote") documentType = "CreditNote";
366
- else return null;
367
- const isCreditNote = documentType === "CreditNote";
368
- const id = cbcText$1(root, "ID");
369
- if (!id) return null;
370
- const paymentMeansList = parsePaymentMeansList(root);
371
- const orderReference = cacElement$1(root, "OrderReference");
372
- const contractReference = cacElement$1(root, "ContractDocumentReference");
373
- const projectReference = cacElement$1(root, "ProjectReference");
374
- const { attachments, documentReferences } = parseAttachments(root);
375
- return {
376
- documentType,
377
- customizationId: cbcText$1(root, "CustomizationID") || void 0,
378
- profileId: cbcText$1(root, "ProfileID") || void 0,
379
- id,
380
- invoiceTypeCode: cbcText$1(root, "InvoiceTypeCode") || cbcText$1(root, "CreditNoteTypeCode") || void 0,
381
- issueDate: cbcText$1(root, "IssueDate"),
382
- dueDate: cbcText$1(root, "DueDate") || void 0,
383
- taxPointDate: cbcText$1(root, "TaxPointDate") || void 0,
384
- currency: cbcText$1(root, "DocumentCurrencyCode"),
385
- buyerReference: cbcText$1(root, "BuyerReference") || void 0,
386
- orderReference: orderReference ? cbcText$1(orderReference, "ID") : void 0,
387
- salesOrderId: orderReference ? cbcText$1(orderReference, "SalesOrderID") || void 0 : void 0,
388
- contractReference: contractReference ? cbcText$1(contractReference, "ID") : void 0,
389
- projectReference: projectReference ? cbcText$1(projectReference, "ID") : void 0,
390
- billingReference: parseBillingReference(root),
391
- seller: parseParty(root, "AccountingSupplierParty"),
392
- buyer: parseParty(root, "AccountingCustomerParty"),
393
- delivery: parseDelivery(root),
394
- lines: parseLines(root, isCreditNote),
395
- taxSubtotals: parseTaxSubtotals(root),
396
- monetaryTotal: parseMonetaryTotal(root),
397
- paymentMeansList,
398
- paymentMeans: paymentMeansList?.[0],
399
- invoicePeriod: parseInvoicePeriod(root),
400
- note: parseNotes(root),
401
- paymentTermsNote: parsePaymentTermsNote(root),
402
- attachments,
403
- documentReferences,
404
- allowanceCharges: parseAllowanceCharges(root)
405
- };
406
- } catch {
407
- return null;
403
+ function omitUndefined(value) {
404
+ if (Array.isArray(value)) return value.map(omitUndefined);
405
+ if (value !== null && typeof value === "object") {
406
+ const out = {};
407
+ for (const [key, entry] of Object.entries(value)) if (entry !== void 0) out[key] = omitUndefined(entry);
408
+ return out;
408
409
  }
410
+ return value;
411
+ }
412
+ const INVOICE_NS = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2";
413
+ const CREDIT_NOTE_NS = "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2";
414
+ /**
415
+ * Parse a UBL 2.1 Invoice or CreditNote.
416
+ *
417
+ * Returns `null` when the XML is well-formed but its root is not a UBL
418
+ * `Invoice`/`CreditNote`. Throws {@link UblParseError} when the XML is
419
+ * malformed or the document lacks an element EN 16931 makes mandatory
420
+ * (document id, issue date, currency, line id).
421
+ */
422
+ function parseUblInvoice(xml) {
423
+ const root = parseXmlDocument(xml).documentElement;
424
+ if (!root) return null;
425
+ let documentType;
426
+ if (root.localName === "Invoice" && root.namespaceURI === INVOICE_NS) documentType = "Invoice";
427
+ else if (root.localName === "CreditNote" && root.namespaceURI === CREDIT_NOTE_NS) documentType = "CreditNote";
428
+ else return null;
429
+ const isCreditNote = documentType === "CreditNote";
430
+ const id = requiredCbcText(root, "ID", "document identifier");
431
+ const issueDate = requiredCbcText(root, "IssueDate", "issue date");
432
+ const currency = requiredCbcText(root, "DocumentCurrencyCode", "currency code");
433
+ const paymentMeansList = parsePaymentMeansList(root);
434
+ const orderReference = cacElement$1(root, "OrderReference");
435
+ const contractReference = cacElement$1(root, "ContractDocumentReference");
436
+ const projectReference = cacElement$1(root, "ProjectReference");
437
+ const { attachments, documentReferences } = parseAttachments(root);
438
+ return omitUndefined({
439
+ documentType,
440
+ customizationId: cbcText$1(root, "CustomizationID"),
441
+ profileId: cbcText$1(root, "ProfileID"),
442
+ id,
443
+ invoiceTypeCode: cbcText$1(root, "InvoiceTypeCode") ?? cbcText$1(root, "CreditNoteTypeCode"),
444
+ issueDate,
445
+ dueDate: cbcText$1(root, "DueDate"),
446
+ taxPointDate: cbcText$1(root, "TaxPointDate"),
447
+ currency,
448
+ buyerReference: cbcText$1(root, "BuyerReference"),
449
+ orderReference: orderReference ? cbcText$1(orderReference, "ID") : void 0,
450
+ salesOrderId: orderReference ? cbcText$1(orderReference, "SalesOrderID") : void 0,
451
+ contractReference: contractReference ? cbcText$1(contractReference, "ID") : void 0,
452
+ projectReference: projectReference ? cbcText$1(projectReference, "ID") : void 0,
453
+ billingReference: parseBillingReference(root),
454
+ seller: parseParty(root, "AccountingSupplierParty"),
455
+ buyer: parseParty(root, "AccountingCustomerParty"),
456
+ delivery: parseDelivery(root),
457
+ lines: parseLines(root, isCreditNote),
458
+ taxSubtotals: parseTaxSubtotals(root),
459
+ monetaryTotal: parseMonetaryTotal(root),
460
+ paymentMeansList,
461
+ paymentMeans: paymentMeansList?.[0],
462
+ invoicePeriod: parseInvoicePeriod(root),
463
+ note: parseNotes(root),
464
+ paymentTermsNote: parsePaymentTermsNote(root),
465
+ attachments,
466
+ documentReferences,
467
+ allowanceCharges: parseAllowanceCharges(root)
468
+ });
409
469
  }
410
470
  //#endregion
411
471
  //#region src/attachments.ts
412
- /** Approximate decoded byte length of a base64 string. */
413
- const base64DecodedSize = (base64) => Math.round(base64.length * 3 / 4);
472
+ /** Decoded byte length of a base64 string, accounting for `=` padding. */
473
+ const base64DecodedSize = (base64) => {
474
+ const sanitized = base64.replace(/\s+/g, "");
475
+ if (!sanitized) return 0;
476
+ const padding = sanitized.endsWith("==") ? 2 : sanitized.endsWith("=") ? 1 : 0;
477
+ return Math.floor(sanitized.length * 3 / 4) - padding;
478
+ };
414
479
  /**
415
480
  * Extract the embedded attachments (typically the human-readable PDF) from a
416
481
  * UBL invoice or credit note XML. Attachments referenced only by external URI
417
482
  * (no `EmbeddedDocumentBinaryObject`) are skipped; use {@link parseUblInvoice}
418
483
  * directly when those matter.
484
+ *
485
+ * @throws {UblParseError} when the XML is malformed or not a UBL invoice.
419
486
  */
420
487
  const extractUblEmbeddedAttachments = (xml) => {
421
488
  const parsed = parseUblInvoice(xml);
422
- if (!parsed?.attachments || parsed.attachments.length === 0) return [];
489
+ if (!parsed) throw new UblParseError("Document is not a UBL Invoice or CreditNote");
490
+ if (!parsed.attachments || parsed.attachments.length === 0) return [];
423
491
  return parsed.attachments.map((attachment, index) => {
424
492
  const base64Content = attachment.base64Content?.trim();
425
493
  if (!base64Content) return null;
426
494
  return {
427
- id: attachment.id || null,
428
- filename: attachment.filename || `attachment-${index + 1}`,
429
- mimeCode: attachment.mimeCode || "application/octet-stream",
495
+ id: attachment.id,
496
+ filename: attachment.filename ?? `attachment-${index + 1}`,
497
+ mimeCode: attachment.mimeCode ?? "application/octet-stream",
430
498
  sizeBytes: base64DecodedSize(base64Content),
431
499
  lineOrder: index,
432
500
  base64Content
@@ -444,8 +512,6 @@ const isPdfLikeAttachment = (attachment) => {
444
512
  };
445
513
  //#endregion
446
514
  //#region src/mlr.ts
447
- const CBC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2";
448
- const CAC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2";
449
515
  /**
450
516
  * Peppol BIS MLR (Message Level Response) document-type identifier value
451
517
  * (Peppol `busdox-docid-qns` scheme).
@@ -453,24 +519,11 @@ const CAC_NS = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComp
453
519
  const PEPPOL_MLR_DOCUMENT_TYPE_VALUE = "urn:oasis:names:specification:ubl:schema:xsd:ApplicationResponse-2::ApplicationResponse##urn:fdc:peppol.eu:poacc:trns:mlr:3::2.1";
454
520
  /** Peppol BIS MLR process identifier value. */
455
521
  const PEPPOL_MLR_PROCESS_VALUE = "urn:fdc:peppol.eu:poacc:bis:mlr:3";
456
- /**
457
- * Strip DOCTYPE declarations to prevent XXE (XML External Entity) attacks.
458
- * @xmldom/xmldom resolves external entities by default, so we remove DOCTYPE
459
- * blocks (including inline DTD subsets) before parsing.
460
- */
461
- const stripDoctype = (xml) => xml.replace(/<!DOCTYPE\s[^>[]*(?:\[[^\]]*\])?>/gi, "");
462
- const parseXmlDocument = (xml) => {
463
- const safeXml = stripDoctype(xml);
464
- const BrowserDomParser = globalThis.DOMParser;
465
- const doc = (BrowserDomParser ? new BrowserDomParser() : new DOMParser()).parseFromString(safeXml, "text/xml");
466
- if (doc.getElementsByTagName("parsererror").length > 0) return null;
467
- return doc;
468
- };
469
522
  const trimmed = (value) => {
470
523
  const text = value?.trim();
471
- return text ? text : null;
524
+ return text ? text : void 0;
472
525
  };
473
- /** First descendant CBC element's trimmed text, or null. */
526
+ /** First descendant CBC element's trimmed text, or undefined. */
474
527
  const cbcText = (parent, tag) => trimmed(parent.getElementsByTagNameNS(CBC_NS, tag)[0]?.textContent);
475
528
  /**
476
529
  * First direct-child CBC element's trimmed text, or null. Used for the
@@ -482,21 +535,20 @@ const cbcDirectText = (parent, tag) => {
482
535
  const node = parent.childNodes[i];
483
536
  if (!node || node.nodeType !== 1) continue;
484
537
  const el = node;
485
- if (el.namespaceURI === CBC_NS && el.localName === tag) return trimmed(el.textContent);
538
+ if (el.namespaceURI === "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" && el.localName === tag) return trimmed(el.textContent);
486
539
  }
487
- return null;
488
540
  };
489
541
  /** First descendant CAC element, or null. */
490
- const cacElement = (parent, tag) => parent.getElementsByTagNameNS(CAC_NS, tag)[0] ?? null;
542
+ const cacElement = (parent, tag) => parent.getElementsByTagNameNS("urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", tag)[0] ?? null;
491
543
  /**
492
544
  * The Peppol participant identifier of a SenderParty / ReceiverParty, rendered
493
545
  * as `schemeID:value` when the EndpointID carries a scheme and the value does
494
546
  * not already include one, otherwise the raw value.
495
547
  */
496
548
  const endpointIdentifier = (party) => {
497
- if (!party) return null;
549
+ if (!party) return void 0;
498
550
  const endpoint = party.getElementsByTagNameNS(CBC_NS, "EndpointID")[0];
499
- if (!endpoint) return null;
551
+ if (!endpoint) return void 0;
500
552
  const id = trimmed(endpoint.textContent);
501
553
  const scheme = endpoint.getAttribute("schemeID");
502
554
  if (scheme && id && !id.includes(":")) return `${scheme}:${id}`;
@@ -504,17 +556,11 @@ const endpointIdentifier = (party) => {
504
556
  };
505
557
  /**
506
558
  * Locate the `ApplicationResponse` element, unwrapping a Standard Business
507
- * Document (SBDH) envelope when present. Returns null when the XML is not
508
- * parseable or contains no ApplicationResponse.
559
+ * Document (SBDH) envelope when present. Returns null when the XML contains no
560
+ * ApplicationResponse; throws {@link UblParseError} when it is malformed.
509
561
  */
510
562
  const findApplicationResponse = (xml) => {
511
- let doc;
512
- try {
513
- doc = parseXmlDocument(xml);
514
- } catch {
515
- return null;
516
- }
517
- const root = doc?.documentElement;
563
+ const root = parseXmlDocument(xml).documentElement;
518
564
  if (!root) return null;
519
565
  if (root.localName === "ApplicationResponse") return root;
520
566
  const candidates = root.getElementsByTagName("*");
@@ -534,16 +580,21 @@ const isPeppolMessageLevelResponse = (params) => {
534
580
  if (trimmed(params.processValue) === "urn:fdc:peppol.eu:poacc:bis:mlr:3") return true;
535
581
  const xml = trimmed(params.xml);
536
582
  if (!xml) return false;
537
- return findApplicationResponse(xml) !== null;
583
+ try {
584
+ return findApplicationResponse(xml) !== null;
585
+ } catch (error) {
586
+ if (error instanceof UblParseError) return false;
587
+ throw error;
588
+ }
538
589
  };
539
590
  /**
540
591
  * Parse a Peppol Message Level Response (UBL `ApplicationResponse`), unwrapping
541
- * an SBDH envelope when present. Throws when the XML is not an
542
- * ApplicationResponse.
592
+ * an SBDH envelope when present. Throws {@link UblParseError} when the XML is
593
+ * malformed or is not an ApplicationResponse.
543
594
  */
544
595
  const parsePeppolMessageLevelResponse = (xml) => {
545
596
  const root = findApplicationResponse(xml);
546
- if (!root) throw new Error("Document is not a Peppol Message Level Response");
597
+ if (!root) throw new UblParseError("Document is not a Peppol Message Level Response");
547
598
  const documentResponse = cacElement(root, "DocumentResponse");
548
599
  const response = documentResponse ? cacElement(documentResponse, "Response") : null;
549
600
  const documentReference = documentResponse ? cacElement(documentResponse, "DocumentReference") : null;
@@ -553,9 +604,9 @@ const parsePeppolMessageLevelResponse = (xml) => {
553
604
  responseId: cbcDirectText(root, "ID"),
554
605
  issueDate: cbcDirectText(root, "IssueDate"),
555
606
  issueTime: cbcDirectText(root, "IssueTime"),
556
- referencedDocumentId: documentReference ? cbcText(documentReference, "ID") : null,
557
- responseCode: response ? cbcText(response, "ResponseCode") : null,
558
- description: response ? cbcText(response, "Description") : null,
607
+ referencedDocumentId: documentReference ? cbcText(documentReference, "ID") : void 0,
608
+ responseCode: response ? cbcText(response, "ResponseCode") : void 0,
609
+ description: response ? cbcText(response, "Description") : void 0,
559
610
  senderIdentifier: endpointIdentifier(cacElement(root, "SenderParty")),
560
611
  receiverIdentifier: endpointIdentifier(cacElement(root, "ReceiverParty"))
561
612
  };
@@ -563,15 +614,14 @@ const parsePeppolMessageLevelResponse = (xml) => {
563
614
  //#endregion
564
615
  //#region src/normalize.ts
565
616
  const UTF8_BOM = 65279;
617
+ /** `null` for an absent value or an "N/A" placeholder written by the sender. */
566
618
  const normalizeText = (value) => {
567
- if (!value) return null;
568
- const trimmed = value.trim();
569
- if (!trimmed) return null;
570
- const upper = trimmed.toUpperCase();
619
+ if (value === void 0) return null;
620
+ const upper = value.toUpperCase();
571
621
  if (upper === "NA" || upper === "N/A") return null;
572
- return trimmed;
622
+ return value;
573
623
  };
574
- const toNumberOrNull = (value) => Number.isFinite(value ?? NaN) ? value : null;
624
+ const toNumberOrNull = (value) => value !== void 0 && Number.isFinite(value) ? value : null;
575
625
  const roundToCents = (value) => Math.round(value * 100) / 100;
576
626
  const normalizeCurrency = (value) => {
577
627
  if (!value) return null;
@@ -587,20 +637,31 @@ const parseDate = (value) => {
587
637
  if (Number.isNaN(timestamp)) return null;
588
638
  return new Date(timestamp).toISOString().slice(0, 10);
589
639
  };
640
+ const sanitizePaymentMeans = (pm) => ({
641
+ code: normalizeText(pm.code),
642
+ code_name: normalizeText(pm.codeName),
643
+ payment_id: normalizeText(pm.paymentId),
644
+ iban: normalizeText(pm.iban),
645
+ bic: normalizeText(pm.bic),
646
+ account_name: normalizeText(pm.accountName),
647
+ mandate_id: normalizeText(pm.mandateId)
648
+ });
649
+ const present = (part) => part !== void 0;
650
+ const joinStreet = (address) => [address.street, address.additionalStreet].filter(present).join(" ");
590
651
  const addressToString = (address) => {
591
652
  if (!address) return null;
592
653
  const lines = [
593
- [address.street, address.additionalStreet].filter((part) => part && part.trim().length > 0).join(" "),
594
- [address.postalZone, address.city].filter((part) => part && part.trim().length > 0).join(" "),
595
- [address.countrySubentity, address.countryCode].filter((part) => part && part.trim().length > 0).join(" ")
654
+ joinStreet(address),
655
+ [address.postalZone, address.city].filter(present).join(" "),
656
+ [address.countrySubentity, address.countryCode].filter(present).join(" ")
596
657
  ].filter((line) => line.length > 0);
597
658
  return lines.length > 0 ? lines.join("\n") : null;
598
659
  };
599
660
  const addressToStructured = (address) => {
600
661
  if (!address) return null;
601
- const line1 = [address.street, address.additionalStreet].filter((part) => part && part.trim().length > 0).join(" ");
662
+ const line1 = joinStreet(address);
602
663
  const result = {
603
- line1: normalizeText(line1),
664
+ line1: line1 ? normalizeText(line1) : null,
604
665
  line2: null,
605
666
  city: normalizeText(address.city),
606
667
  state: normalizeText(address.countrySubentity),
@@ -609,18 +670,12 @@ const addressToStructured = (address) => {
609
670
  };
610
671
  return Object.values(result).some((value) => value) ? result : null;
611
672
  };
612
- const base64ByteLength = (content) => {
613
- const sanitized = content.replace(/\s+/g, "");
614
- if (!sanitized) return 0;
615
- const paddingLength = sanitized.endsWith("==") ? 2 : sanitized.endsWith("=") ? 1 : 0;
616
- return Math.floor(sanitized.length * 3 / 4) - paddingLength;
617
- };
618
673
  const sanitizeAttachments = (attachments) => (attachments ?? []).map((attachment) => ({
619
674
  id: normalizeText(attachment.id),
620
675
  filename: normalizeText(attachment.filename),
621
676
  mime_code: normalizeText(attachment.mimeCode),
622
677
  description: normalizeText(attachment.description),
623
- size_bytes: attachment.base64Content ? base64ByteLength(attachment.base64Content) : null,
678
+ size_bytes: attachment.base64Content !== void 0 ? base64DecodedSize(attachment.base64Content) : null,
624
679
  external_uri: normalizeText(attachment.externalUri)
625
680
  }));
626
681
  const sanitizeAllowanceCharges = (charges) => (charges ?? []).map((charge) => ({
@@ -640,13 +695,15 @@ const sanitizeRawUbl = (ubl) => ({
640
695
  documentReferences: ubl.documentReferences ?? []
641
696
  });
642
697
  const sumTaxTotal = (ubl) => {
643
- const subtotalSum = ubl.taxSubtotals.reduce((sum, subtotal) => sum + subtotal.taxAmount, 0);
698
+ const subtotalSum = ubl.taxSubtotals.reduce((sum, subtotal) => sum + (subtotal.taxAmount ?? 0), 0);
644
699
  if (ubl.taxSubtotals.length > 0 && Number.isFinite(subtotalSum)) return subtotalSum;
645
- return ubl.monetaryTotal.taxInclusiveAmount - ubl.monetaryTotal.taxExclusiveAmount;
700
+ const { taxInclusiveAmount, taxExclusiveAmount } = ubl.monetaryTotal;
701
+ if (taxInclusiveAmount === void 0 || taxExclusiveAmount === void 0) return null;
702
+ return taxInclusiveAmount - taxExclusiveAmount;
646
703
  };
647
704
  const sumAllowanceChargesByType = (charges, chargeIndicator) => (charges ?? []).reduce((sum, charge) => {
648
705
  if (charge.chargeIndicator !== chargeIndicator) return sum;
649
- return sum + Math.abs(charge.amount);
706
+ return sum + Math.abs(charge.amount ?? 0);
650
707
  }, 0);
651
708
  /**
652
709
  * Decode raw XML bytes, stripping an optional UTF-8 BOM.
@@ -658,10 +715,13 @@ const decodeXmlBytes = (bytes) => {
658
715
  /**
659
716
  * Parse a UBL XML string and normalize it into a flat DTO suitable for
660
717
  * database storage or API responses.
718
+ *
719
+ * @throws {UblParseError} when the XML is malformed, not a UBL invoice, or
720
+ * lacks a mandatory element.
661
721
  */
662
722
  const normalizeUblResponse = (xml, documentId) => {
663
723
  const ubl = parseUblInvoice(xml);
664
- if (!ubl) throw new Error("Failed to parse UBL invoice XML");
724
+ if (!ubl) throw new UblParseError("Document is not a UBL Invoice or CreditNote");
665
725
  const subtotal = toNumberOrNull(ubl.monetaryTotal.taxExclusiveAmount) ?? toNumberOrNull(ubl.monetaryTotal.lineExtensionAmount);
666
726
  const total = toNumberOrNull(ubl.monetaryTotal.taxInclusiveAmount) ?? toNumberOrNull(ubl.monetaryTotal.payableAmount);
667
727
  const amountDue = toNumberOrNull(ubl.monetaryTotal.payableAmount);
@@ -669,7 +729,7 @@ const normalizeUblResponse = (xml, documentId) => {
669
729
  const roundingAmount = toNumberOrNull(ubl.monetaryTotal.payableRoundingAmount) ?? 0;
670
730
  const inferredPaid = total !== null && amountDue !== null ? roundToCents(total - (amountDue - roundingAmount)) : null;
671
731
  const amountPaid = prepaidAmount ?? (inferredPaid !== null && inferredPaid > 0 ? inferredPaid : null);
672
- const taxTotal = toNumberOrNull(sumTaxTotal(ubl));
732
+ const taxTotal = toNumberOrNull(sumTaxTotal(ubl) ?? void 0);
673
733
  const hasHeaderAllowanceCharges = (ubl.allowanceCharges?.length ?? 0) > 0;
674
734
  const headerDiscountTotal = sumAllowanceChargesByType(ubl.allowanceCharges, false);
675
735
  const headerChargeTotal = sumAllowanceChargesByType(ubl.allowanceCharges, true);
@@ -757,24 +817,8 @@ const normalizeUblResponse = (xml, documentId) => {
757
817
  tax_point_date: parseDate(ubl.taxPointDate),
758
818
  invoice_period: ubl.invoicePeriod ?? null,
759
819
  note: normalizeText(ubl.note),
760
- payment_means: ubl.paymentMeans ? {
761
- code: normalizeText(ubl.paymentMeans.code),
762
- code_name: normalizeText(ubl.paymentMeans.codeName),
763
- payment_id: normalizeText(ubl.paymentMeans.paymentId),
764
- iban: normalizeText(ubl.paymentMeans.iban),
765
- bic: normalizeText(ubl.paymentMeans.bic),
766
- account_name: normalizeText(ubl.paymentMeans.accountName),
767
- mandate_id: normalizeText(ubl.paymentMeans.mandateId)
768
- } : null,
769
- payment_means_list: paymentMeansList.map((item) => ({
770
- code: normalizeText(item.code),
771
- code_name: normalizeText(item.codeName),
772
- payment_id: normalizeText(item.paymentId),
773
- iban: normalizeText(item.iban),
774
- bic: normalizeText(item.bic),
775
- account_name: normalizeText(item.accountName),
776
- mandate_id: normalizeText(item.mandateId)
777
- })),
820
+ payment_means: ubl.paymentMeans ? sanitizePaymentMeans(ubl.paymentMeans) : null,
821
+ payment_means_list: paymentMeansList.map(sanitizePaymentMeans),
778
822
  delivery: ubl.delivery ? {
779
823
  actual_delivery_date: parseDate(ubl.delivery.actualDeliveryDate),
780
824
  address: addressToStructured(ubl.delivery.address)
@@ -845,6 +889,6 @@ const parseUblInvoiceDocument = (params) => {
845
889
  };
846
890
  };
847
891
  //#endregion
848
- export { PEPPOL_MLR_DOCUMENT_TYPE_VALUE, PEPPOL_MLR_PROCESS_VALUE, decodeXmlBytes, extractUblEmbeddedAttachments, isPdfLikeAttachment, isPeppolMessageLevelResponse, normalizeCurrency, normalizeUblResponse, parseDate, parsePeppolMessageLevelResponse, parseUblInvoice, parseUblInvoiceDocument };
892
+ export { PEPPOL_MLR_DOCUMENT_TYPE_VALUE, PEPPOL_MLR_PROCESS_VALUE, UblParseError, decodeXmlBytes, extractUblEmbeddedAttachments, isPdfLikeAttachment, isPeppolMessageLevelResponse, normalizeCurrency, normalizeUblResponse, parseDate, parsePeppolMessageLevelResponse, parseUblInvoice, parseUblInvoiceDocument };
849
893
 
850
894
  //# sourceMappingURL=index.js.map