@financica/ubl 0.15.1 → 0.17.0

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