@devly-cl/sii-client 0.7.1 → 0.7.11

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.
Files changed (70) hide show
  1. package/README.md +84 -1
  2. package/dist/application/document-status.d.ts +5 -5
  3. package/dist/application/document-status.js +14 -9
  4. package/dist/application/dte-import-mapper.d.ts +8 -0
  5. package/dist/application/dte-import-mapper.js +25 -0
  6. package/dist/application/dte-import-model.d.ts +28 -0
  7. package/dist/application/dte-import-model.js +2 -0
  8. package/dist/application/dte-import.d.ts +37 -0
  9. package/dist/application/dte-import.js +352 -0
  10. package/dist/application/invoice-queries.d.ts +12 -6
  11. package/dist/application/invoice-queries.js +9 -5
  12. package/dist/application/issuance.d.ts +2 -2
  13. package/dist/application/issuance.js +26 -10
  14. package/dist/contracts.d.ts +32 -0
  15. package/dist/contracts.js +17 -0
  16. package/dist/domain/civil-date.d.ts +2 -0
  17. package/dist/domain/civil-date.js +10 -0
  18. package/dist/domain/document-status.d.ts +0 -4
  19. package/dist/domain/document-status.js +18 -11
  20. package/dist/domain/document.js +49 -9
  21. package/dist/domain/dte-arithmetic.d.ts +35 -0
  22. package/dist/domain/dte-arithmetic.js +78 -0
  23. package/dist/domain/dte-components.d.ts +9 -0
  24. package/dist/domain/dte-components.js +37 -0
  25. package/dist/domain/dte-detail.d.ts +111 -0
  26. package/dist/domain/dte-detail.js +2 -0
  27. package/dist/domain/dte-identity.d.ts +19 -0
  28. package/dist/domain/dte-identity.js +52 -0
  29. package/dist/domain/dte-money.d.ts +41 -0
  30. package/dist/domain/dte-money.js +81 -0
  31. package/dist/domain/dte-reconciliation-model.d.ts +87 -0
  32. package/dist/domain/dte-reconciliation-model.js +2 -0
  33. package/dist/domain/dte-reconciliation.d.ts +15 -0
  34. package/dist/domain/dte-reconciliation.js +390 -0
  35. package/dist/domain/dte-validation.d.ts +7 -0
  36. package/dist/domain/dte-validation.js +84 -0
  37. package/dist/domain/invoice-xml.d.ts +17 -57
  38. package/dist/domain/invoice-xml.js +0 -10
  39. package/dist/domain/invoicing.d.ts +30 -4
  40. package/dist/domain/invoicing.js +75 -21
  41. package/dist/domain/issued-invoice.d.ts +0 -6
  42. package/dist/domain/rcv-document.d.ts +0 -4
  43. package/dist/domain/received-invoice.d.ts +1 -4
  44. package/dist/index.d.ts +19 -9
  45. package/dist/index.js +20 -4
  46. package/dist/infrastructure/document-status-gateway.d.ts +6 -4
  47. package/dist/infrastructure/document-status-gateway.js +34 -13
  48. package/dist/infrastructure/document-status-parser.js +38 -12
  49. package/dist/infrastructure/dte-xml-mapper.d.ts +16 -0
  50. package/dist/infrastructure/dte-xml-mapper.js +381 -0
  51. package/dist/infrastructure/dte-xml.d.ts +40 -4
  52. package/dist/infrastructure/dte-xml.js +117 -196
  53. package/dist/infrastructure/facturador-gateway.d.ts +10 -7
  54. package/dist/infrastructure/facturador-gateway.js +256 -56
  55. package/dist/infrastructure/facturador.d.ts +1 -1
  56. package/dist/infrastructure/facturador.js +18 -10
  57. package/dist/infrastructure/invoice-pdf.js +10 -3
  58. package/dist/infrastructure/rcv-gateway.d.ts +7 -4
  59. package/dist/infrastructure/rcv-gateway.js +53 -12
  60. package/dist/infrastructure/rcv-normalization.d.ts +8 -1
  61. package/dist/infrastructure/rcv-normalization.js +54 -12
  62. package/dist/infrastructure/read-options.d.ts +3 -0
  63. package/dist/infrastructure/read-options.js +25 -0
  64. package/dist/infrastructure/sii-client.d.ts +98 -13
  65. package/dist/infrastructure/sii-client.js +182 -31
  66. package/dist/infrastructure/sii-http-session.d.ts +2 -2
  67. package/dist/infrastructure/sii-http-session.js +134 -37
  68. package/dist/sii-error.d.ts +5 -0
  69. package/dist/sii-error.js +39 -13
  70. package/package.json +2 -2
@@ -1,5 +1,9 @@
1
+ import type { DteDeclaredDetail } from './dte-detail';
2
+ import type { DteReconciliation } from './dte-reconciliation-model';
1
3
  import type { InvoiceDocumentType } from './issued-invoice';
2
- export declare const MAX_DTE_XML_BYTES = 1048576;
4
+ import type { ExactDte } from './dte-money';
5
+ export type { DteFiscalReference, DteReferenceIdentity, DteFiscalComponents, DteFiscalConditions, DteCommission, DteInvoiceLine, DteDeclaredDetail } from './dte-detail';
6
+ export type { DteProjectedTax, DteReconciliationDiagnostic, DteFiscalObservation, DteReconciledLine, DteTotalRounding, DteReconciledAmounts, DteReconciliation } from './dte-reconciliation-model';
3
7
  export type IssuedDocumentType = InvoiceDocumentType | 61;
4
8
  export interface IssuedDocumentXmlQuery {
5
9
  documentType: IssuedDocumentType;
@@ -15,60 +19,15 @@ export interface IssuedInvoiceXmlQuery {
15
19
  export interface ReceivedInvoiceXmlQuery extends IssuedInvoiceXmlQuery {
16
20
  issuerRut: string;
17
21
  }
18
- export interface DteInvoiceLine {
19
- lineNumber: number;
20
- name: string;
21
- description: string | null;
22
- codes: {
23
- type: string;
24
- value: string;
25
- }[];
26
- quantity: string | null;
27
- unit: string | null;
28
- unitPrice: string | null;
29
- discountPercent: string | null;
30
- discountAmount: number | null;
31
- surchargePercent: string | null;
32
- surchargeAmount: number | null;
33
- exemptIndicator: number | null;
34
- amount: number;
35
- }
36
- export interface DteInvoiceDetail {
37
- /** Present only for MntBruto=1: line amounts/prices include VAT. Original fiscal totals are unchanged. */
38
- grossAmounts?: boolean;
39
- issuerRut: string;
22
+ /** Compatible invoice read model: source facts plus optional arithmetic interpretation. */
23
+ export interface DteInvoiceDetail extends DteDeclaredDetail {
40
24
  documentType: InvoiceDocumentType;
41
- folio: string;
42
- issuedDate: string;
43
- receiverRut: string;
44
- netAmount: number | null;
45
- exemptAmount: number | null;
46
- vatRate: string | null;
47
- vatAmount: number | null;
48
- totalAmount: number;
49
- lines: DteInvoiceLine[];
50
- taxes: {
51
- type: number;
52
- rate: string | null;
53
- amount: number;
54
- }[];
55
- adjustments: {
56
- lineNumber: number;
57
- movement: 'D' | 'R';
58
- description: string | null;
59
- valueType: '%' | '$';
60
- value: string;
61
- exemptIndicator: number | null;
62
- }[];
63
- references: {
64
- lineNumber: number;
65
- documentType: string;
66
- folio: string;
67
- date: string;
68
- code: number | null;
69
- reason: string | null;
70
- }[];
25
+ reconciliation?: DteReconciliation;
71
26
  }
27
+ /** Fiscal parser model, also usable for reconciling previously stored declared detail. */
28
+ export type DteFiscalDetail = Omit<DteInvoiceDetail, 'documentType'> & {
29
+ documentType: number;
30
+ };
72
31
  export interface InvoiceXmlResult {
73
32
  /** Original bytes, including the original encoding and signatures. */
74
33
  xml: Uint8Array;
@@ -138,6 +97,11 @@ export interface DteIssuanceOptions {
138
97
  export interface IssuedDocumentXmlResult extends Omit<InvoiceXmlResult, 'detail'> {
139
98
  detail: DteDocumentDetail;
140
99
  }
100
+ export type ExactDteDocumentDetail = ExactDte<DteDocumentDetail>;
101
+ export type ExactDteFiscalDetail = ExactDte<DteFiscalDetail>;
102
+ export interface ExactDteDocumentXmlResult extends Omit<InvoiceXmlResult, 'detail'> {
103
+ detail: ExactDteDocumentDetail;
104
+ }
141
105
  /** @deprecated Use IssuedDocumentType. */
142
106
  export type TipoDocumentoEmitido = IssuedDocumentType;
143
107
  /** @deprecated Use IssuedDocumentXmlQuery. */
@@ -150,7 +114,3 @@ export type ConsultaXmlFacturaRecibida = ReceivedInvoiceXmlQuery;
150
114
  export type ResultadoXmlFacturaEmitida = InvoiceXmlResult;
151
115
  /** @deprecated Use IssuedDocumentXmlResult. */
152
116
  export type ResultadoXmlDocumentoEmitido = IssuedDocumentXmlResult;
153
- export declare class DteXmlError extends Error {
154
- readonly code: 'SII_XML_INVALID' | 'SII_XML_IDENTITY_MISMATCH';
155
- constructor(code: 'SII_XML_INVALID' | 'SII_XML_IDENTITY_MISMATCH');
156
- }
@@ -1,12 +1,2 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DteXmlError = exports.MAX_DTE_XML_BYTES = void 0;
4
- exports.MAX_DTE_XML_BYTES = 1_048_576;
5
- class DteXmlError extends Error {
6
- code;
7
- constructor(code) {
8
- super(code);
9
- this.code = code;
10
- }
11
- }
12
- exports.DteXmlError = DteXmlError;
@@ -12,6 +12,10 @@ export interface InvoiceLineInput {
12
12
  discountPercent?: string;
13
13
  }
14
14
  export type InvoiceAdditionalTaxCode = 23 | 44 | 24 | 25 | 26 | 27 | 271;
15
+ /**
16
+ * Tasas admitidas por la emisión de facturas tipo 33 en el facturador gratuito.
17
+ * Los códigos desconocidos pueden leerse documentalmente; esta tabla limita la emisión soportada.
18
+ */
15
19
  export declare const INVOICE_ADDITIONAL_TAX_RATES: Readonly<{
16
20
  23: "15";
17
21
  44: "15";
@@ -28,7 +32,8 @@ export type InvoiceGlobalDiscount = {
28
32
  amountClp: number;
29
33
  percent?: never;
30
34
  };
31
- export type InvoiceReferenceDocumentType = '30' | '32' | '33' | '34' | '35' | '38' | '39' | '40' | '41' | '43' | '45' | '46' | '48' | '50' | '52' | '55' | '56' | '60' | '61' | '103' | '801' | '802' | '803' | '804' | '805' | '806' | '813' | '820' | '821' | '822' | '823' | 'HES';
35
+ declare const referenceTypes: readonly ["30", "32", "33", "34", "35", "38", "39", "40", "41", "43", "45", "46", "48", "50", "52", "55", "56", "60", "61", "103", "801", "802", "803", "804", "805", "806", "813", "820", "821", "822", "823", "HES"];
36
+ export type InvoiceReferenceDocumentType = typeof referenceTypes[number];
32
37
  export interface InvoiceReferenceInput {
33
38
  documentType: InvoiceReferenceDocumentType;
34
39
  folio: string;
@@ -111,11 +116,31 @@ export declare function invoiceBreakdown(lines: readonly InvoiceLineInput[], dis
111
116
  amount: number;
112
117
  }[];
113
118
  };
114
- /** Tipo 33, IVA 19%, con opcionales explícitos del facturador gratuito. */
119
+ /**
120
+ * Valida y normaliza una orden de emisión de factura tipo 33 con IVA 19%.
121
+ * Aplica límites del facturador, normaliza RUT/decimales y congela la estructura devuelta.
122
+ * @param input Orden plana sin campos desconocidos; hasta diez ítems, con cantidades y precios de hasta dos decimales.
123
+ * @returns Una nueva orden normalizada e inmutable; no prepara ni envía documentos al SII.
124
+ * @throws TypeError por estructura, identidad, importes, fechas u opcionales fuera del alcance de emisión.
125
+ * @remarks Esta política de emisión no se usa para aceptar o rechazar documentos históricos de lectura.
126
+ */
115
127
  export declare function validateInvoice(input: unknown): InvoiceInput;
116
- /** Redondea líneas, descuento global, IVA e impuestos adicionales sin decimales binarios. */
128
+ /**
129
+ * Calcula totales de emisión tipo 33: líneas, descuento global, IVA 19% e impuestos adicionales soportados.
130
+ * Usa aritmética entera; no introduce decimales binarios en cantidades, precios ni porcentajes.
131
+ * @param input Array de InvoiceLineInput, con los mismos límites que validateInvoice.
132
+ * @param discount Descuento global opcional, porcentual o importe entero CLP.
133
+ * @returns netAmount, vatAmount y totalAmount como enteros CLP seguros; el total incluye impuestos adicionales.
134
+ * @throws TypeError por líneas, descuentos o totales fuera del alcance de emisión.
135
+ */
117
136
  export declare function calculateInvoiceTotals(input: unknown, discount?: InvoiceGlobalDiscount): InvoiceTotals;
118
- /** Huella determinista del contenido fiscal; el llamador excluye claves y tokens. */
137
+ /**
138
+ * Calcula SHA-256 hexadecimal sobre una serialización determinista del contenido.
139
+ * Ordena claves de objetos y conserva el orden de arrays; rechaza ciclos, undefined y objetos no planos.
140
+ * @param value Contenido fiscal compatible con JSON. El llamador debe excluir claves, tokens y otros secretos.
141
+ * @returns Huella de 64 caracteres; no modifica ni persiste el contenido.
142
+ * @throws TypeError si el contenido no tiene una representación canónica soportada.
143
+ */
119
144
  export declare function hashContent(value: unknown): string;
120
145
  /** @deprecated Use validateInvoice. */
121
146
  export declare const validarFactura: typeof validateInvoice;
@@ -123,3 +148,4 @@ export declare const validarFactura: typeof validateInvoice;
123
148
  export declare const calcularTotalesFactura: typeof calculateInvoiceTotals;
124
149
  /** @deprecated Use hashContent. */
125
150
  export declare const hashContenido: typeof hashContent;
151
+ export {};
@@ -5,11 +5,28 @@ exports.invoiceBreakdown = invoiceBreakdown;
5
5
  exports.validateInvoice = validateInvoice;
6
6
  exports.calculateInvoiceTotals = calculateInvoiceTotals;
7
7
  exports.hashContent = hashContent;
8
+ const civil_date_1 = require("./civil-date");
8
9
  const node_crypto_1 = require("node:crypto");
9
10
  const rut_1 = require("./rut");
10
- exports.INVOICE_ADDITIONAL_TAX_RATES = Object.freeze({ 23: '15', 44: '15', 24: '31.5', 25: '20.5', 26: '20.5', 27: '10', 271: '18' });
11
+ /**
12
+ * Tasas admitidas por la emisión de facturas tipo 33 en el facturador gratuito.
13
+ * Los códigos desconocidos pueden leerse documentalmente; esta tabla limita la emisión soportada.
14
+ */
15
+ exports.INVOICE_ADDITIONAL_TAX_RATES = Object.freeze({
16
+ 23: '15',
17
+ 44: '15',
18
+ 24: '31.5',
19
+ 25: '20.5',
20
+ 26: '20.5',
21
+ 27: '10',
22
+ 271: '18'
23
+ });
24
+ const referenceTypes = ['30', '32', '33', '34', '35', '38', '39', '40', '41', '43', '45', '46', '48', '50', '52', '55', '56', '60', '61', '103', '801', '802', '803', '804', '805', '806', '813', '820', '821', '822', '823', 'HES'];
25
+ const referenceTypeSet = new Set(referenceTypes);
11
26
  const controls = /[\u0000-\u001f\u007f-\u009f]/u;
12
- function invalid(field) { throw new TypeError(`Factura inválida: ${field}`); }
27
+ function invalid(field) {
28
+ throw new TypeError(`Factura inválida: ${field}`);
29
+ }
13
30
  function isRecord(value) {
14
31
  return typeof value === 'object' && value !== null && !Array.isArray(value)
15
32
  && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
@@ -83,7 +100,12 @@ function items(value) {
83
100
  quantity: decimal(source.quantity, 'quantity'),
84
101
  unitNetPriceClp: decimal(source.unitNetPriceClp, 'unitNetPriceClp'),
85
102
  ...(unit === undefined ? {} : { unit }),
86
- ...(code === undefined ? {} : { productCode: Object.freeze({ type: requiredText(code.type, 10, 'productCode.type'), value: requiredText(code.value, 15, 'productCode.value') }) }),
103
+ ...(code === undefined ? {} : {
104
+ productCode: Object.freeze({
105
+ type: requiredText(code.type, 10, 'productCode.type'),
106
+ value: requiredText(code.value, 15, 'productCode.value')
107
+ })
108
+ }),
87
109
  ...(additionalTaxCode === undefined ? {} : { additionalTaxCode: additionalTaxCode }),
88
110
  ...(source.discountPercent === undefined ? {} : { discountPercent: percentage(source.discountPercent, 'discountPercent') }),
89
111
  });
@@ -113,8 +135,10 @@ function invoiceBreakdown(lines, discount) {
113
135
  const net = subtotal - discountAmount;
114
136
  const vat = (net * 19n + 50n) / 100n;
115
137
  const taxBases = new Map();
116
- lines.forEach((line, index) => { if (line.additionalTaxCode !== undefined)
117
- taxBases.set(line.additionalTaxCode, (taxBases.get(line.additionalTaxCode) ?? 0n) + BigInt(lineAmounts[index].amount)); });
138
+ lines.forEach((line, index) => {
139
+ if (line.additionalTaxCode !== undefined)
140
+ taxBases.set(line.additionalTaxCode, (taxBases.get(line.additionalTaxCode) ?? 0n) + BigInt(lineAmounts[index].amount));
141
+ });
118
142
  let taxNumerator = 0n;
119
143
  const taxes = [...taxBases].map(([type, base]) => {
120
144
  const rate = exports.INVOICE_ADDITIONAL_TAX_RATES[type];
@@ -130,17 +154,17 @@ function invoiceBreakdown(lines, discount) {
130
154
  invalid('totalAmount');
131
155
  return {
132
156
  totals: Object.freeze({ netAmount: Number(net), vatAmount: Number(vat), totalAmount: Number(total) }),
133
- subtotal: Number(subtotal), discountAmount: Number(discountAmount), discountPercent: fromHundredths(discountPercent), discountAmountFromPercent: Number(round(subtotal * discountPercent, 10000n)),
134
- additionalTaxAmount: Number(additionalTaxAmount), lineAmounts, taxes,
157
+ subtotal: Number(subtotal),
158
+ discountAmount: Number(discountAmount),
159
+ discountPercent: fromHundredths(discountPercent),
160
+ discountAmountFromPercent: Number(round(subtotal * discountPercent, 10000n)),
161
+ additionalTaxAmount: Number(additionalTaxAmount),
162
+ lineAmounts,
163
+ taxes,
135
164
  };
136
165
  }
137
166
  function civilDate(value, field, minimum, maximum = '9999-12-31') {
138
- if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/u.test(value))
139
- invalid(field);
140
- const year = Number(value.slice(0, 4)), month = Number(value.slice(5, 7)), day = Number(value.slice(8, 10));
141
- const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
142
- const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
143
- if (value < minimum || value > maximum || month < 1 || month > 12 || day < 1 || day > days[month - 1])
167
+ if (!(0, civil_date_1.isCivilDate)(value) || value < minimum || value > maximum)
144
168
  invalid(field);
145
169
  return value;
146
170
  }
@@ -149,11 +173,10 @@ function smallArray(value, field) {
149
173
  invalid(field);
150
174
  return Array.from(value);
151
175
  }
152
- const referenceTypes = ['30', '32', '33', '34', '35', '38', '39', '40', '41', '43', '45', '46', '48', '50', '52', '55', '56', '60', '61', '103', '801', '802', '803', '804', '805', '806', '813', '820', '821', '822', '823', 'HES'];
153
176
  function references(value) {
154
177
  return Object.freeze(smallArray(value, 'references').map(entry => {
155
178
  const source = record(entry, ['documentType', 'folio', 'date', 'reason', 'global'], 'reference');
156
- if (typeof source.documentType !== 'string' || !referenceTypes.includes(source.documentType))
179
+ if (typeof source.documentType !== 'string' || !referenceTypeSet.has(source.documentType))
157
180
  invalid('reference.documentType');
158
181
  if (source.global !== undefined && typeof source.global !== 'boolean')
159
182
  invalid('reference.global');
@@ -161,7 +184,11 @@ function references(value) {
161
184
  if (source.global ? folio !== '0' : ['30', '32', '38', '40', '45', '50', '55', '60', '33', '34', '39', '46', '56', '61', '52', '103'].includes(source.documentType) && !/^[1-9]\d*$/.test(folio))
162
185
  invalid('reference.folio');
163
186
  const reason = text(source.reason, 90, 'reference.reason', true);
164
- return Object.freeze({ documentType: source.documentType, folio, date: civilDate(source.date, 'reference.date', '2002-08-01', '2050-12-31'), ...(reason === undefined ? {} : { reason }), ...(source.global ? { global: true } : {}) });
187
+ return Object.freeze({
188
+ documentType: source.documentType,
189
+ folio,
190
+ date: civilDate(source.date, 'reference.date', '2002-08-01', '2050-12-31'), ...(reason === undefined ? {} : { reason }), ...(source.global ? { global: true } : {})
191
+ });
165
192
  }));
166
193
  }
167
194
  function payments(value, issued, total) {
@@ -183,9 +210,21 @@ function payments(value, issued, total) {
183
210
  }
184
211
  function transport(value) {
185
212
  const source = record(value, ['carrierRut', 'licensePlate', 'driverRut', 'driverName'], 'transport');
186
- return Object.freeze({ carrierRut: (0, rut_1.parseRut)(requiredText(source.carrierRut, 15, 'transport.carrierRut')).formatted, licensePlate: requiredText(source.licensePlate, 8, 'transport.licensePlate'), driverRut: (0, rut_1.parseRut)(requiredText(source.driverRut, 15, 'transport.driverRut')).formatted, driverName: requiredText(source.driverName, 30, 'transport.driverName') });
213
+ return Object.freeze({
214
+ carrierRut: (0, rut_1.parseRut)(requiredText(source.carrierRut, 15, 'transport.carrierRut')).formatted,
215
+ licensePlate: requiredText(source.licensePlate, 8, 'transport.licensePlate'),
216
+ driverRut: (0, rut_1.parseRut)(requiredText(source.driverRut, 15, 'transport.driverRut')).formatted,
217
+ driverName: requiredText(source.driverName, 30, 'transport.driverName')
218
+ });
187
219
  }
188
- /** Tipo 33, IVA 19%, con opcionales explícitos del facturador gratuito. */
220
+ /**
221
+ * Valida y normaliza una orden de emisión de factura tipo 33 con IVA 19%.
222
+ * Aplica límites del facturador, normaliza RUT/decimales y congela la estructura devuelta.
223
+ * @param input Orden plana sin campos desconocidos; hasta diez ítems, con cantidades y precios de hasta dos decimales.
224
+ * @returns Una nueva orden normalizada e inmutable; no prepara ni envía documentos al SII.
225
+ * @throws TypeError por estructura, identidad, importes, fechas u opcionales fuera del alcance de emisión.
226
+ * @remarks Esta política de emisión no se usa para aceptar o rechazar documentos históricos de lectura.
227
+ */
189
228
  function validateInvoice(input) {
190
229
  const source = record(input, ['issuedDate', 'issuer', 'receiver', 'paymentForm', 'saleType', 'purchaseType', 'items', 'globalDiscount', 'references', 'payments', 'requesterRut', 'transport', 'smallBusiness'], 'input');
191
230
  const issuer = record(source.issuer, ['address', 'commune', 'city', 'activityCode', 'email', 'phone'], 'issuer');
@@ -240,9 +279,24 @@ function validateInvoice(input) {
240
279
  Object.freeze(result.items);
241
280
  return Object.freeze(result);
242
281
  }
243
- /** Redondea líneas, descuento global, IVA e impuestos adicionales sin decimales binarios. */
244
- function calculateInvoiceTotals(input, discount) { return invoiceBreakdown(items(input), globalDiscount(discount)).totals; }
245
- /** Huella determinista del contenido fiscal; el llamador excluye claves y tokens. */
282
+ /**
283
+ * Calcula totales de emisión tipo 33: líneas, descuento global, IVA 19% e impuestos adicionales soportados.
284
+ * Usa aritmética entera; no introduce decimales binarios en cantidades, precios ni porcentajes.
285
+ * @param input Array de InvoiceLineInput, con los mismos límites que validateInvoice.
286
+ * @param discount Descuento global opcional, porcentual o importe entero CLP.
287
+ * @returns netAmount, vatAmount y totalAmount como enteros CLP seguros; el total incluye impuestos adicionales.
288
+ * @throws TypeError por líneas, descuentos o totales fuera del alcance de emisión.
289
+ */
290
+ function calculateInvoiceTotals(input, discount) {
291
+ return invoiceBreakdown(items(input), globalDiscount(discount)).totals;
292
+ }
293
+ /**
294
+ * Calcula SHA-256 hexadecimal sobre una serialización determinista del contenido.
295
+ * Ordena claves de objetos y conserva el orden de arrays; rechaza ciclos, undefined y objetos no planos.
296
+ * @param value Contenido fiscal compatible con JSON. El llamador debe excluir claves, tokens y otros secretos.
297
+ * @returns Huella de 64 caracteres; no modifica ni persiste el contenido.
298
+ * @throws TypeError si el contenido no tiene una representación canónica soportada.
299
+ */
246
300
  function hashContent(value) {
247
301
  const ancestors = new Set();
248
302
  function canonical(input) {
@@ -1,8 +1,4 @@
1
1
  export type InvoiceDocumentType = 33 | 34;
2
- export interface IssuedInvoicesQuery {
3
- periodo: string;
4
- tokenRecaptcha?: string;
5
- }
6
2
  export interface IssuedInvoice {
7
3
  issuerRut: string;
8
4
  documentType: InvoiceDocumentType;
@@ -26,8 +22,6 @@ export interface IssuedInvoicesResult {
26
22
  }
27
23
  /** @deprecated Use InvoiceDocumentType. */
28
24
  export type TipoFacturaEmitida = InvoiceDocumentType;
29
- /** @deprecated Use IssuedInvoicesQuery. */
30
- export type ConsultaFacturasEmitidas = IssuedInvoicesQuery;
31
25
  /** @deprecated Use IssuedInvoice. */
32
26
  export type FacturaEmitida = IssuedInvoice;
33
27
  /** @deprecated Use IssuedInvoicesResult. */
@@ -1,9 +1,5 @@
1
1
  import type { IssuedInvoice } from './issued-invoice';
2
2
  export type RcvDocumentType = 33 | 34 | 61;
3
- export interface RcvDocumentsQuery {
4
- periodo: string;
5
- tokenRecaptcha?: string;
6
- }
7
3
  export interface RcvDocument extends Omit<IssuedInvoice, 'documentType'> {
8
4
  documentType: RcvDocumentType;
9
5
  issuerName?: string | null;
@@ -1,13 +1,10 @@
1
- import { type IssuedInvoicesQuery, type IssuedInvoice, type IssuedInvoicesResult } from './issued-invoice';
2
- export type ReceivedInvoicesQuery = IssuedInvoicesQuery;
1
+ import type { IssuedInvoice, IssuedInvoicesResult } from './issued-invoice';
3
2
  export interface ReceivedInvoice extends IssuedInvoice {
4
3
  issuerName: string | null;
5
4
  }
6
5
  export interface ReceivedInvoicesResult extends Omit<IssuedInvoicesResult, 'data'> {
7
6
  data: ReceivedInvoice[];
8
7
  }
9
- /** @deprecated Use ReceivedInvoicesQuery. */
10
- export type ConsultaFacturasRecibidas = ReceivedInvoicesQuery;
11
8
  /** @deprecated Use ReceivedInvoice. */
12
9
  export type FacturaRecibida = ReceivedInvoice;
13
10
  /** @deprecated Use ReceivedInvoicesResult. */
package/dist/index.d.ts CHANGED
@@ -2,21 +2,31 @@ export { SiiClient, SiiError } from './infrastructure/sii-client';
2
2
  export { sanitizeSiiDiagnostics } from './sii-error';
3
3
  export type { SiiDiagnostics } from './sii-error';
4
4
  export type { CompanyInfo } from './domain/company-info';
5
- export type { RcvDocumentType, RcvDocument, RcvDocumentsQuery, RcvDocumentsResult } from './domain/rcv-document';
6
- export type { DocumentQueryOptions, DocumentDirection, DocumentIdentity, DocumentStatusQuery, DocumentVerification, DocumentStatusResult, RecipientEventsQuery, RecipientEvent, RecipientEventsResult, } from './domain/document-status';
7
- export type { IssuedInvoicePdfQuery, ReceivedInvoicePdfQuery, PdfDownloadOptions, InvoicePdfResult } from './contracts';
5
+ export type { RcvDocumentType, RcvDocument, RcvDocumentsResult } from './domain/rcv-document';
6
+ export type { DocumentDirection, DocumentIdentity, DocumentStatusQuery, DocumentVerification, DocumentStatusResult, RecipientEventsQuery, RecipientEvent, RecipientEventsResult, } from './domain/document-status';
7
+ export type { IssuedInvoicePdfQuery, ReceivedInvoicePdfQuery, PdfDownloadOptions, InvoicePdfResult, DteXmlReadOptions, DocumentQueryOptions, IssuedInvoicesQuery, ReceivedInvoicesQuery, RcvDocumentsQuery, ConsultaFacturasEmitidas, ConsultaFacturasRecibidas } from './contracts';
8
+ export type { DteDeclaredDetail } from './domain/dte-detail';
8
9
  export { parseRut } from './domain/rut';
9
10
  export { validateInvoice, calculateInvoiceTotals, hashContent, INVOICE_ADDITIONAL_TAX_RATES, validarFactura, calcularTotalesFactura, hashContenido } from './domain/invoicing';
10
11
  export type { InvoiceInput, InvoiceLineInput, InvoiceTotals, InvoiceAdditionalTaxCode, InvoiceGlobalDiscount, InvoiceReferenceDocumentType, InvoiceReferenceInput, InvoicePaymentInput, InvoiceTransportInput, EntradaFactura, LineaFactura, TotalesFactura } from './domain/invoicing';
11
12
  export type { DocumentoPreparado, DocumentoFirmado, DocumentoEnviado, FirmaDocumento } from './infrastructure/sii-client';
12
- export { parseDteXml, parseDteDocumentXml } from './infrastructure/dte-xml';
13
- export { DteXmlError, MAX_DTE_XML_BYTES } from './domain/invoice-xml';
13
+ export { parseDteXml, parseDteDocumentXml, parseDteDocumentXmlExact } from './infrastructure/dte-xml';
14
+ export { exactDteMoney, withExactDteAmounts, withNumberDteAmounts, DteMoneyRangeError } from './domain/dte-money';
15
+ export type { ExactDte } from './domain/dte-money';
16
+ export { buildDteImportProjection, buildDteImportProjectionExact, projectDteForImport, projectDteForImportExact } from './application/dte-import';
17
+ export type { DteImportAmounts, DteImportProjection, ExactDteImportProjection } from './application/dte-import-model';
18
+ export type { ExactDteDocumentDetail, ExactDteFiscalDetail, ExactDteDocumentXmlResult } from './domain/invoice-xml';
19
+ export { reconcileDteDetail } from './domain/dte-reconciliation';
20
+ export { normalizeDteFolio, resolveDteReferenceIdentity } from './domain/dte-identity';
21
+ export type { DteFiscalReference, DteReferenceIdentity, DteFiscalComponents, DteFiscalConditions, DteCommission, DteProjectedTax } from './domain/invoice-xml';
22
+ export type { DteFiscalDetail, DteReconciliation, DteReconciliationDiagnostic, DteReconciledAmounts, DteReconciledLine, DteTotalRounding, DteFiscalObservation } from './domain/invoice-xml';
23
+ export { DteXmlError, MAX_DTE_XML_BYTES } from './contracts';
14
24
  export type { ConsultaXmlFacturaEmitida, ConsultaXmlFacturaRecibida, DteInvoiceLine, DteInvoiceDetail, ResultadoXmlFacturaEmitida } from './domain/invoice-xml';
15
25
  export type { TipoDocumentoEmitido, ConsultaXmlDocumentoEmitido, DteDocumentDetail, DteIssuanceOptions, ResultadoXmlDocumentoEmitido } from './domain/invoice-xml';
16
- export type { ConsultaFacturasEmitidas, FacturaEmitida, ResultadoFacturasEmitidas, TipoFacturaEmitida } from './domain/issued-invoice';
17
- export type { ConsultaFacturasRecibidas, FacturaRecibida, ResultadoFacturasRecibidas } from './domain/received-invoice';
26
+ export type { FacturaEmitida, ResultadoFacturasEmitidas, TipoFacturaEmitida } from './domain/issued-invoice';
27
+ export type { FacturaRecibida, ResultadoFacturasRecibidas } from './domain/received-invoice';
18
28
  export type { ConsultaResumen, CredencialesSii, EmpresaAutorizada, EstadoCompra, Operacion, RegistroSii, RespuestaSii, SesionSii, SiiClientOptions, } from './infrastructure/sii-client';
19
29
  export type { SummaryQuery, SiiCredentials, SiiSession, Operation, PurchaseStatus, SiiRecord, SiiResponse, AuthorizedCompany, PreparedDocument, SignedDocument, SentDocument, SignDocumentInput, } from './infrastructure/sii-client';
20
- export type { IssuedInvoicesQuery, IssuedInvoice, IssuedInvoicesResult, InvoiceDocumentType, } from './domain/issued-invoice';
21
- export type { ReceivedInvoicesQuery, ReceivedInvoice, ReceivedInvoicesResult, } from './domain/received-invoice';
30
+ export type { IssuedInvoice, IssuedInvoicesResult, InvoiceDocumentType, } from './domain/issued-invoice';
31
+ export type { ReceivedInvoice, ReceivedInvoicesResult, } from './domain/received-invoice';
22
32
  export type { IssuedInvoiceXmlQuery, ReceivedInvoiceXmlQuery, InvoiceXmlResult, IssuedDocumentType, IssuedDocumentXmlQuery, ReceivedDocumentXmlQuery, IssuedDocumentXmlResult, } from './domain/invoice-xml';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MAX_DTE_XML_BYTES = exports.DteXmlError = exports.parseDteDocumentXml = exports.parseDteXml = exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = exports.INVOICE_ADDITIONAL_TAX_RATES = exports.hashContent = exports.calculateInvoiceTotals = exports.validateInvoice = exports.parseRut = exports.sanitizeSiiDiagnostics = exports.SiiError = exports.SiiClient = void 0;
3
+ exports.MAX_DTE_XML_BYTES = exports.DteXmlError = exports.resolveDteReferenceIdentity = exports.normalizeDteFolio = exports.reconcileDteDetail = exports.projectDteForImportExact = exports.projectDteForImport = exports.buildDteImportProjectionExact = exports.buildDteImportProjection = exports.DteMoneyRangeError = exports.withNumberDteAmounts = exports.withExactDteAmounts = exports.exactDteMoney = exports.parseDteDocumentXmlExact = exports.parseDteDocumentXml = exports.parseDteXml = exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = exports.INVOICE_ADDITIONAL_TAX_RATES = exports.hashContent = exports.calculateInvoiceTotals = exports.validateInvoice = exports.parseRut = exports.sanitizeSiiDiagnostics = exports.SiiError = exports.SiiClient = void 0;
4
4
  var sii_client_1 = require("./infrastructure/sii-client");
5
5
  Object.defineProperty(exports, "SiiClient", { enumerable: true, get: function () { return sii_client_1.SiiClient; } });
6
6
  Object.defineProperty(exports, "SiiError", { enumerable: true, get: function () { return sii_client_1.SiiError; } });
@@ -19,6 +19,22 @@ Object.defineProperty(exports, "hashContenido", { enumerable: true, get: functio
19
19
  var dte_xml_1 = require("./infrastructure/dte-xml");
20
20
  Object.defineProperty(exports, "parseDteXml", { enumerable: true, get: function () { return dte_xml_1.parseDteXml; } });
21
21
  Object.defineProperty(exports, "parseDteDocumentXml", { enumerable: true, get: function () { return dte_xml_1.parseDteDocumentXml; } });
22
- var invoice_xml_1 = require("./domain/invoice-xml");
23
- Object.defineProperty(exports, "DteXmlError", { enumerable: true, get: function () { return invoice_xml_1.DteXmlError; } });
24
- Object.defineProperty(exports, "MAX_DTE_XML_BYTES", { enumerable: true, get: function () { return invoice_xml_1.MAX_DTE_XML_BYTES; } });
22
+ Object.defineProperty(exports, "parseDteDocumentXmlExact", { enumerable: true, get: function () { return dte_xml_1.parseDteDocumentXmlExact; } });
23
+ var dte_money_1 = require("./domain/dte-money");
24
+ Object.defineProperty(exports, "exactDteMoney", { enumerable: true, get: function () { return dte_money_1.exactDteMoney; } });
25
+ Object.defineProperty(exports, "withExactDteAmounts", { enumerable: true, get: function () { return dte_money_1.withExactDteAmounts; } });
26
+ Object.defineProperty(exports, "withNumberDteAmounts", { enumerable: true, get: function () { return dte_money_1.withNumberDteAmounts; } });
27
+ Object.defineProperty(exports, "DteMoneyRangeError", { enumerable: true, get: function () { return dte_money_1.DteMoneyRangeError; } });
28
+ var dte_import_1 = require("./application/dte-import");
29
+ Object.defineProperty(exports, "buildDteImportProjection", { enumerable: true, get: function () { return dte_import_1.buildDteImportProjection; } });
30
+ Object.defineProperty(exports, "buildDteImportProjectionExact", { enumerable: true, get: function () { return dte_import_1.buildDteImportProjectionExact; } });
31
+ Object.defineProperty(exports, "projectDteForImport", { enumerable: true, get: function () { return dte_import_1.projectDteForImport; } });
32
+ Object.defineProperty(exports, "projectDteForImportExact", { enumerable: true, get: function () { return dte_import_1.projectDteForImportExact; } });
33
+ var dte_reconciliation_1 = require("./domain/dte-reconciliation");
34
+ Object.defineProperty(exports, "reconcileDteDetail", { enumerable: true, get: function () { return dte_reconciliation_1.reconcileDteDetail; } });
35
+ var dte_identity_1 = require("./domain/dte-identity");
36
+ Object.defineProperty(exports, "normalizeDteFolio", { enumerable: true, get: function () { return dte_identity_1.normalizeDteFolio; } });
37
+ Object.defineProperty(exports, "resolveDteReferenceIdentity", { enumerable: true, get: function () { return dte_identity_1.resolveDteReferenceIdentity; } });
38
+ var contracts_1 = require("./contracts");
39
+ Object.defineProperty(exports, "DteXmlError", { enumerable: true, get: function () { return contracts_1.DteXmlError; } });
40
+ Object.defineProperty(exports, "MAX_DTE_XML_BYTES", { enumerable: true, get: function () { return contracts_1.MAX_DTE_XML_BYTES; } });
@@ -1,13 +1,15 @@
1
1
  import type { DocumentReadPort } from '../application/document-status';
2
- import type { BoundDocumentStatusQuery, BoundRecipientEventsQuery, DocumentQueryOptions } from '../domain/document-status';
2
+ import type { BoundDocumentStatusQuery, BoundRecipientEventsQuery } from '../domain/document-status';
3
+ import type { DocumentQueryOptions } from '../contracts';
3
4
  import { SiiHttpSession } from './sii-http-session';
4
5
  /** Read-only personal queries; authentication and company authorization belong to the session. */
5
6
  export declare class DocumentStatusGateway implements DocumentReadPort {
6
7
  #private;
7
8
  private readonly session;
8
- constructor(session: SiiHttpSession);
9
+ private readonly options?;
10
+ constructor(session: SiiHttpSession, options?: DocumentQueryOptions | undefined);
9
11
  get companyRut(): string;
10
12
  assertReady(): void;
11
- status(query: BoundDocumentStatusQuery, options?: DocumentQueryOptions): Promise<import("../domain/document-status").DocumentVerification>;
12
- recipientEvents(query: BoundRecipientEventsQuery, options?: DocumentQueryOptions): Promise<import("../domain/document-status").RecipientEventsObservation>;
13
+ status(query: BoundDocumentStatusQuery): Promise<import("../domain/document-status").DocumentVerification>;
14
+ recipientEvents(query: BoundRecipientEventsQuery): Promise<import("../domain/document-status").RecipientEventsObservation>;
13
15
  }
@@ -3,19 +3,27 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DocumentStatusGateway = void 0;
4
4
  const node_crypto_1 = require("node:crypto");
5
5
  const rut_1 = require("../domain/rut");
6
+ const read_options_1 = require("./read-options");
6
7
  const facturador_1 = require("./facturador");
7
8
  const document_status_parser_1 = require("./document-status-parser");
8
9
  const sii_http_session_1 = require("./sii-http-session");
9
10
  /** Read-only personal queries; authentication and company authorization belong to the session. */
10
11
  class DocumentStatusGateway {
11
12
  session;
12
- constructor(session) {
13
+ options;
14
+ constructor(session, options) {
13
15
  this.session = session;
16
+ this.options = options;
14
17
  }
15
- get companyRut() { return this.session.company.formatted; }
16
- assertReady() { this.session.assertReady(); }
17
- status(query, options) {
18
- return this.#read('QEstadoDTE', options?.signal, async (signal) => {
18
+ get companyRut() {
19
+ return this.session.company.formatted;
20
+ }
21
+ assertReady() {
22
+ this.session.assertReady();
23
+ }
24
+ status(query) {
25
+ (0, read_options_1.assertDocumentQueryOptions)(this.options);
26
+ return this.#read('QEstadoDTE', this.options?.signal, async (signal) => {
19
27
  const actor = this.session.assertReady();
20
28
  const fields = await this.session.request(sii_http_session_1.DOCUMENT_STATUS_FORM, async (response) => {
21
29
  const html = await this.#html(response, 'DTEauth', signal);
@@ -32,14 +40,17 @@ class DocumentStatusGateway {
32
40
  return this.session.request(sii_http_session_1.DOCUMENT_STATUS_URL, async (response) => {
33
41
  const html = await this.#html(response, 'QEstadoDTE', signal);
34
42
  return this.#parse('QEstadoDTE', response, () => (0, document_status_parser_1.parseDocumentVerification)(html));
35
- }, { method: 'POST', signal, headers: {
43
+ }, {
44
+ method: 'POST', signal, headers: {
36
45
  'Content-Type': 'application/x-www-form-urlencoded', Accept: 'text/html',
37
46
  Origin: 'https://palena.sii.cl', Referer: sii_http_session_1.DOCUMENT_STATUS_FORM,
38
- }, body: fields.toString() }, true);
47
+ }, body: fields.toString()
48
+ }, true);
39
49
  });
40
50
  }
41
- recipientEvents(query, options) {
42
- return this.#read('validarAccesoReceptor', options?.signal, async (signal) => {
51
+ recipientEvents(query) {
52
+ (0, read_options_1.assertDocumentQueryOptions)(this.options);
53
+ return this.#read('validarAccesoReceptor', this.options?.signal, async (signal) => {
43
54
  const actor = this.session.assertReady(), issuer = (0, rut_1.parseRut)(query.issuerRut);
44
55
  await this.session.request(sii_http_session_1.RECIPIENT_EVENTS_PORTAL, async (response) => {
45
56
  const html = await this.#html(response, 'registrorechazodtej6ui', signal);
@@ -53,7 +64,14 @@ class DocumentStatusGateway {
53
64
  namespace: 'cl.sii.sdi.lob.diii.registrorechazodtej6.data.api.interfaces.FacadeService/validarAccesoReceptor',
54
65
  conversationId: token, transactionId: (0, node_crypto_1.randomUUID)(), page: null,
55
66
  },
56
- data: { rutEmisor: issuer.rut, dvEmisor: issuer.dv, tipoDoc: query.documentType, folio: query.folio, rutToken: actor.rut, dvToken: actor.dv },
67
+ data: {
68
+ rutEmisor: issuer.rut,
69
+ dvEmisor: issuer.dv,
70
+ tipoDoc: query.documentType,
71
+ folio: query.folio,
72
+ rutToken: actor.rut,
73
+ dvToken: actor.dv
74
+ },
57
75
  });
58
76
  return this.session.request(sii_http_session_1.RECIPIENT_EVENTS_URL, async (response) => {
59
77
  const mime = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
@@ -67,10 +85,12 @@ class DocumentStatusGateway {
67
85
  }
68
86
  const value = await this.session.json(response, 'validarAccesoReceptor', signal);
69
87
  return this.#parse('validarAccesoReceptor', response, () => (0, document_status_parser_1.parseRecipientEvents)(value));
70
- }, { method: 'POST', signal, headers: {
88
+ }, {
89
+ method: 'POST', signal, headers: {
71
90
  'Content-Type': 'application/json', Accept: 'application/json, text/plain, */*',
72
91
  Origin: 'https://www4.sii.cl', Referer: sii_http_session_1.RECIPIENT_EVENTS_PORTAL,
73
- }, body }, true);
92
+ }, body
93
+ }, true);
74
94
  });
75
95
  }
76
96
  async #html(response, endpoint, signal) {
@@ -89,7 +109,8 @@ class DocumentStatusGateway {
89
109
  if (['utf-8', 'utf8'].includes(charset))
90
110
  return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
91
111
  }
92
- catch { /* Reject bytes outside the declared encoding. */ }
112
+ catch { /* Reject bytes outside the declared encoding. */
113
+ }
93
114
  throw this.session.failure('SII_PROTOCOL_CHANGED', endpoint, 'INVALID_RESPONSE', response, (0, sii_http_session_1.responseFormat)(response, bytes));
94
115
  }
95
116
  #parse(endpoint, response, parse) {