@devly-cl/sii-client 0.7.9 → 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.
- package/README.md +68 -2
- package/dist/application/document-status.d.ts +5 -5
- package/dist/application/document-status.js +14 -9
- package/dist/application/dte-import-mapper.d.ts +8 -0
- package/dist/application/dte-import-mapper.js +25 -0
- package/dist/application/dte-import-model.d.ts +28 -0
- package/dist/application/dte-import-model.js +2 -0
- package/dist/application/dte-import.d.ts +37 -0
- package/dist/application/dte-import.js +352 -0
- package/dist/application/invoice-queries.d.ts +12 -6
- package/dist/application/invoice-queries.js +9 -5
- package/dist/application/issuance.d.ts +2 -2
- package/dist/application/issuance.js +26 -10
- package/dist/contracts.d.ts +32 -0
- package/dist/contracts.js +17 -0
- package/dist/domain/civil-date.d.ts +2 -0
- package/dist/domain/civil-date.js +10 -0
- package/dist/domain/document-status.d.ts +0 -4
- package/dist/domain/document-status.js +18 -11
- package/dist/domain/document.js +47 -9
- package/dist/domain/dte-arithmetic.d.ts +35 -0
- package/dist/domain/dte-arithmetic.js +78 -0
- package/dist/domain/dte-components.d.ts +9 -0
- package/dist/domain/dte-components.js +37 -0
- package/dist/domain/dte-detail.d.ts +111 -0
- package/dist/domain/dte-detail.js +2 -0
- package/dist/domain/dte-identity.d.ts +19 -0
- package/dist/domain/dte-identity.js +52 -0
- package/dist/domain/dte-money.d.ts +41 -0
- package/dist/domain/dte-money.js +81 -0
- package/dist/domain/dte-reconciliation-model.d.ts +87 -0
- package/dist/domain/dte-reconciliation-model.js +2 -0
- package/dist/domain/dte-reconciliation.d.ts +14 -4
- package/dist/domain/dte-reconciliation.js +211 -172
- package/dist/domain/dte-validation.d.ts +7 -0
- package/dist/domain/dte-validation.js +84 -0
- package/dist/domain/invoice-xml.d.ts +12 -151
- package/dist/domain/invoice-xml.js +0 -10
- package/dist/domain/invoicing.d.ts +30 -4
- package/dist/domain/invoicing.js +75 -21
- package/dist/domain/issued-invoice.d.ts +0 -6
- package/dist/domain/rcv-document.d.ts +0 -4
- package/dist/domain/received-invoice.d.ts +1 -4
- package/dist/index.d.ts +18 -10
- package/dist/index.js +18 -5
- package/dist/infrastructure/document-status-gateway.d.ts +6 -4
- package/dist/infrastructure/document-status-gateway.js +34 -13
- package/dist/infrastructure/document-status-parser.js +38 -12
- package/dist/infrastructure/dte-xml-mapper.d.ts +16 -0
- package/dist/infrastructure/dte-xml-mapper.js +381 -0
- package/dist/infrastructure/dte-xml.d.ts +40 -4
- package/dist/infrastructure/dte-xml.js +116 -238
- package/dist/infrastructure/facturador-gateway.d.ts +10 -7
- package/dist/infrastructure/facturador-gateway.js +256 -56
- package/dist/infrastructure/facturador.js +14 -7
- package/dist/infrastructure/invoice-pdf.js +10 -3
- package/dist/infrastructure/rcv-gateway.d.ts +7 -4
- package/dist/infrastructure/rcv-gateway.js +53 -12
- package/dist/infrastructure/rcv-normalization.d.ts +8 -1
- package/dist/infrastructure/rcv-normalization.js +54 -12
- package/dist/infrastructure/read-options.d.ts +3 -0
- package/dist/infrastructure/read-options.js +25 -0
- package/dist/infrastructure/sii-client.d.ts +98 -13
- package/dist/infrastructure/sii-client.js +182 -31
- package/dist/infrastructure/sii-http-session.d.ts +2 -2
- package/dist/infrastructure/sii-http-session.js +83 -19
- package/dist/sii-error.d.ts +4 -0
- package/dist/sii-error.js +38 -13
- package/package.json +2 -2
|
@@ -18,7 +18,6 @@ class SiiClient {
|
|
|
18
18
|
#rcv;
|
|
19
19
|
#facturador;
|
|
20
20
|
#issuance;
|
|
21
|
-
#documentQueries;
|
|
22
21
|
#companyLookup;
|
|
23
22
|
#disposal;
|
|
24
23
|
constructor(options) {
|
|
@@ -26,41 +25,173 @@ class SiiClient {
|
|
|
26
25
|
this.#rcv = new rcv_gateway_1.RcvGateway(this.#session);
|
|
27
26
|
this.#facturador = new facturador_gateway_1.FacturadorGateway(this.#session, () => this.dispose());
|
|
28
27
|
this.#issuance = new issuance_1.DocumentIssuance(this.#facturador);
|
|
29
|
-
this.#documentQueries = new document_status_2.DocumentQueries(new document_status_gateway_1.DocumentStatusGateway(this.#session));
|
|
30
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Autentica acceso personal y comprueba que la identidad puede operar sobre la empresa fijada en la instancia.
|
|
31
|
+
* Credenciales sólo en memoria; login no se reintenta automáticamente.
|
|
32
|
+
*/
|
|
31
33
|
login(credentials) {
|
|
32
34
|
return this.#session.login(credentials, async (identity) => (await this.#rcv.companies(identity)).data.some(company => `${company.usrEmpRut}-${company.usrEmpDv}`.toUpperCase() === this.#session.company.formatted));
|
|
33
35
|
}
|
|
34
|
-
|
|
36
|
+
/**
|
|
37
|
+
* Consulta las empresas autorizadas para la sesión personal. La autorización de actor, tenant y recurso pertenece al consumidor.
|
|
38
|
+
*/
|
|
39
|
+
async getAuthorizedCompanies() {
|
|
40
|
+
return this.#rcv.companies();
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Consulta razón social, direcciones y giros observados del RUT indicado, sin preparar ni emitir facturas.
|
|
44
|
+
*/
|
|
35
45
|
getCompanyInfo(rut) {
|
|
36
46
|
if (this.#companyLookup || this.#issuance.pendingWrite)
|
|
37
47
|
return Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS'));
|
|
38
48
|
const lookup = this.#facturador.companyInfo(rut).catch(error => {
|
|
39
49
|
if (error instanceof sii_error_1.SiiError && error.diagnostics?.endpoint === 'mipeGenFacEx.cgi') {
|
|
40
|
-
throw new sii_error_1.SiiError(error.diagnostics.reason === 'RESPONSE_TOO_LARGE' ? 'SII_PROTOCOL_CHANGED' : error.code, error.httpStatus, {
|
|
50
|
+
throw new sii_error_1.SiiError(error.diagnostics.reason === 'RESPONSE_TOO_LARGE' ? 'SII_PROTOCOL_CHANGED' : error.code, error.httpStatus, {
|
|
51
|
+
...error.diagnostics,
|
|
52
|
+
stage: 'COMPANY_LOOKUP'
|
|
53
|
+
});
|
|
41
54
|
}
|
|
42
55
|
throw error;
|
|
43
56
|
});
|
|
44
57
|
this.#companyLookup = lookup;
|
|
45
|
-
void lookup.then(() => {
|
|
58
|
+
void lookup.then(() => {
|
|
59
|
+
this.#companyLookup = undefined;
|
|
60
|
+
}, () => {
|
|
61
|
+
this.#companyLookup = undefined;
|
|
62
|
+
});
|
|
46
63
|
return lookup;
|
|
47
64
|
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
65
|
+
/**
|
|
66
|
+
* Consulta el resumen RCV de toda la empresa para un período YYYYMM. El consumidor debe autorizar este alcance agregado.
|
|
67
|
+
*/
|
|
68
|
+
getSummary(input) {
|
|
69
|
+
return this.#rcv.summary(input);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Consulta facturas emitidas 33/34 en RCV; complete indica si los detalles observados cubren el resumen del proveedor.
|
|
73
|
+
*/
|
|
74
|
+
getIssuedInvoices(input) {
|
|
75
|
+
return this.#rcv.issuedInvoices(input);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Consulta facturas recibidas 33/34 en RCV; complete=false exige tratar el resultado como parcial.
|
|
79
|
+
*/
|
|
80
|
+
getReceivedInvoices(input) {
|
|
81
|
+
return this.#rcv.receivedInvoices(input);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Consulta documentos emitidos 33/34/61 en RCV, con identidades normalizadas y cobertura explícita.
|
|
85
|
+
*/
|
|
86
|
+
getIssuedDocuments(input) {
|
|
87
|
+
return this.#rcv.issuedDocuments(input);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Consulta documentos recibidos 33/34/61 en RCV; cada emisor conserva su identidad fiscal.
|
|
91
|
+
*/
|
|
92
|
+
getReceivedDocuments(input) {
|
|
93
|
+
return this.#rcv.receivedDocuments(input);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Consulta RCV emitido con importes enteros exactos como strings; mantiene las mismas reglas de autorización y cobertura.
|
|
97
|
+
*/
|
|
98
|
+
getIssuedDocumentsExact(input) {
|
|
99
|
+
return this.#rcv.issuedDocumentsExact(input);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Consulta RCV recibido con importes enteros exactos como strings, sin convertir primero los números fuente a Number.
|
|
103
|
+
*/
|
|
104
|
+
getReceivedDocumentsExact(input) {
|
|
105
|
+
return this.#rcv.receivedDocumentsExact(input);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Descarga XML de factura emitida 33/34 y comprueba su identidad.
|
|
109
|
+
* @param options reconcile=false omite la interpretación aritmética; por defecto conserva el comportamiento histórico.
|
|
110
|
+
*/
|
|
111
|
+
getIssuedInvoiceXml(input, options) {
|
|
112
|
+
return this.#facturador.issuedInvoiceXml(input, options);
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Descarga XML de factura recibida 33/34 y comprueba emisor, receptor, tipo y folio.
|
|
116
|
+
* @param options reconcile=false entrega los datos declarados sin conciliación; identidad y autorización siguen siendo obligatorias.
|
|
117
|
+
*/
|
|
118
|
+
getReceivedInvoiceXml(input, options) {
|
|
119
|
+
return this.#facturador.receivedInvoiceXml(input, options);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Descarga XML emitido 33/34/61, con encabezado fiscal e importes numéricos seguros.
|
|
123
|
+
* @param options reconcile=false permite leer hechos sin exigir una referencia fiscal interpretable para una nota de crédito.
|
|
124
|
+
*/
|
|
125
|
+
getIssuedDocumentXml(input, options) {
|
|
126
|
+
return this.#facturador.issuedDocumentXml(input, options);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Descarga XML recibido 33/34/61 y comprueba también que la empresa autorizada es su receptor.
|
|
130
|
+
* @param options reconcile=false omite conciliación y requisitos de interpretación de referencias; conserva controles técnicos y de identidad.
|
|
131
|
+
*/
|
|
132
|
+
getReceivedDocumentXml(input, options) {
|
|
133
|
+
return this.#facturador.receivedDocumentXml(input, options);
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Descarga XML emitido 33/34/61 conservando importes de hasta 18 dígitos como strings exactos.
|
|
137
|
+
* @param options reconcile=false omite el intento de conciliación numérica; los bytes originales se conservan.
|
|
138
|
+
*/
|
|
139
|
+
getIssuedDocumentXmlExact(input, options) {
|
|
140
|
+
return this.#facturador.issuedDocumentXmlExact(input, options);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Descarga XML recibido 33/34/61 con importes exactos y comprobación de emisor y receptor.
|
|
144
|
+
* @param options reconcile=false devuelve sólo los hechos declarados; no modifica precios, cantidades ni bytes.
|
|
145
|
+
*/
|
|
146
|
+
getReceivedDocumentXmlExact(input, options) {
|
|
147
|
+
return this.#facturador.receivedDocumentXmlExact(input, options);
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Descarga PDF emitido 33/34 como stream, después de verificar empresa e identidad en el historial del proveedor.
|
|
151
|
+
*/
|
|
152
|
+
getIssuedInvoicePdf(input, options) {
|
|
153
|
+
return this.#facturador.issuedInvoicePdf(input, options);
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Descarga PDF recibido 33/34 como stream y verifica también al proveedor solicitado. El consumidor debe consumir o cerrar el stream.
|
|
157
|
+
*/
|
|
158
|
+
getReceivedInvoicePdf(input, options) {
|
|
159
|
+
return this.#facturador.receivedInvoicePdf(input, options);
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Consulta evidencia del documento recibida por el SII. fiscalVerdict permanece NOT_OBSERVED; no acredita aceptación tributaria.
|
|
163
|
+
*/
|
|
164
|
+
getDocumentStatus(input, options) {
|
|
165
|
+
return this.#translate(new document_status_2.DocumentQueries(new document_status_gateway_1.DocumentStatusGateway(this.#session, options)).getDocumentStatus(input));
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Consulta eventos del receptor verificando identidad y acceso en el rol solicitado. Un reporte de pago no registra un pago en el consumidor.
|
|
169
|
+
*/
|
|
170
|
+
getDocumentRecipientEvents(input, options) {
|
|
171
|
+
return this.#translate(new document_status_2.DocumentQueries(new document_status_gateway_1.DocumentStatusGateway(this.#session, options)).getDocumentRecipientEvents(input));
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Valida y prepara una factura tipo 33 para aprobación, sin firmarla ni enviarla. La preparación es de uso único y vence a los cinco minutos.
|
|
175
|
+
*/
|
|
176
|
+
prepareInvoice(input) {
|
|
177
|
+
return this.#companyLookup ? Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS')) : this.#translate(this.#issuance.prepareInvoice(input));
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Prepara una nota de crédito de anulación contra una factura tipo 33 original. Conserva las comprobaciones estrictas de contenido.
|
|
181
|
+
*/
|
|
182
|
+
prepareCancellationCreditNote(input) {
|
|
183
|
+
return this.#companyLookup ? Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS')) : this.#translate(this.#issuance.prepareCancellationCreditNote(input));
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Firma y envía exclusivamente el contenido preparado y aprobado.
|
|
187
|
+
* Exige beforeSend para respaldar documento e identidad antes del envío; no reintenta escrituras ante resultados desconocidos.
|
|
188
|
+
*/
|
|
189
|
+
signAndSend(input) {
|
|
190
|
+
return this.#companyLookup ? Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS')) : this.#translate(this.#issuance.signAndSend(input));
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Espera operaciones pendientes, cierra la sesión remota y libera recursos. Puede rechazar con SII_LOGOUT_FAILED aunque la limpieza local termine.
|
|
194
|
+
*/
|
|
64
195
|
dispose() {
|
|
65
196
|
if (!this.#disposal) {
|
|
66
197
|
this.#issuance.clearPreparation();
|
|
@@ -80,24 +211,44 @@ class SiiClient {
|
|
|
80
211
|
});
|
|
81
212
|
}
|
|
82
213
|
/** @deprecated Use getAuthorizedCompanies. */
|
|
83
|
-
getEmpresasAutorizadas() {
|
|
214
|
+
getEmpresasAutorizadas() {
|
|
215
|
+
return this.getAuthorizedCompanies();
|
|
216
|
+
}
|
|
84
217
|
/** @deprecated Use getSummary. */
|
|
85
|
-
getResumen(input) {
|
|
218
|
+
getResumen(input) {
|
|
219
|
+
return this.getSummary(input);
|
|
220
|
+
}
|
|
86
221
|
/** @deprecated Use getIssuedInvoices. */
|
|
87
|
-
getFacturasEmitidas(input) {
|
|
222
|
+
getFacturasEmitidas(input) {
|
|
223
|
+
return this.getIssuedInvoices(input);
|
|
224
|
+
}
|
|
88
225
|
/** @deprecated Use getReceivedInvoices. */
|
|
89
|
-
getFacturasRecibidas(input) {
|
|
226
|
+
getFacturasRecibidas(input) {
|
|
227
|
+
return this.getReceivedInvoices(input);
|
|
228
|
+
}
|
|
90
229
|
/** @deprecated Use getIssuedInvoiceXml. */
|
|
91
|
-
getXmlFacturaEmitida(input) {
|
|
230
|
+
getXmlFacturaEmitida(input, options) {
|
|
231
|
+
return this.getIssuedInvoiceXml(input, options);
|
|
232
|
+
}
|
|
92
233
|
/** @deprecated Use getReceivedInvoiceXml. */
|
|
93
|
-
getXmlFacturaRecibida(input) {
|
|
234
|
+
getXmlFacturaRecibida(input, options) {
|
|
235
|
+
return this.getReceivedInvoiceXml(input, options);
|
|
236
|
+
}
|
|
94
237
|
/** @deprecated Use getIssuedDocumentXml. */
|
|
95
|
-
getXmlDocumentoEmitido(input) {
|
|
238
|
+
getXmlDocumentoEmitido(input, options) {
|
|
239
|
+
return this.getIssuedDocumentXml(input, options);
|
|
240
|
+
}
|
|
96
241
|
/** @deprecated Use prepareInvoice. */
|
|
97
|
-
prepararFactura(input) {
|
|
242
|
+
prepararFactura(input) {
|
|
243
|
+
return this.prepareInvoice(input);
|
|
244
|
+
}
|
|
98
245
|
/** @deprecated Use prepareCancellationCreditNote. */
|
|
99
|
-
prepararNotaCreditoAnulacion(input) {
|
|
246
|
+
prepararNotaCreditoAnulacion(input) {
|
|
247
|
+
return this.prepareCancellationCreditNote(input);
|
|
248
|
+
}
|
|
100
249
|
/** @deprecated Use signAndSend. */
|
|
101
|
-
firmarYEnviar(input) {
|
|
250
|
+
firmarYEnviar(input) {
|
|
251
|
+
return this.signAndSend(input);
|
|
252
|
+
}
|
|
102
253
|
}
|
|
103
254
|
exports.SiiClient = SiiClient;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { parseRut } from '../domain/rut';
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
2
|
+
import type { InvoicePdfResult, SiiClientOptions, SiiCredentials, SiiSession } from '../contracts';
|
|
3
|
+
import { type SiiDiagnostics, SiiError } from '../sii-error';
|
|
4
4
|
export declare const RCV = "https://www4.sii.cl/consdcvinternetui/";
|
|
5
5
|
export declare const FACTURADOR = "https://www1.sii.cl/cgi-bin/Portal001/";
|
|
6
6
|
export declare const DOCUMENT_STATUS_FORM = "https://palena.sii.cl/cgi_dte/UPL/DTEauth?6";
|
|
@@ -9,7 +9,7 @@ const promises_1 = require("node:timers/promises");
|
|
|
9
9
|
const promises_2 = require("node:stream/promises");
|
|
10
10
|
const tough_cookie_1 = require("tough-cookie");
|
|
11
11
|
const rut_1 = require("../domain/rut");
|
|
12
|
-
const
|
|
12
|
+
const contracts_1 = require("../contracts");
|
|
13
13
|
const sii_error_1 = require("../sii-error");
|
|
14
14
|
exports.RCV = 'https://www4.sii.cl/consdcvinternetui/';
|
|
15
15
|
exports.FACTURADOR = 'https://www1.sii.cl/cgi-bin/Portal001/';
|
|
@@ -60,7 +60,14 @@ class SiiHttpSession {
|
|
|
60
60
|
throw new TypeError('Clave inválida');
|
|
61
61
|
this.#used = true;
|
|
62
62
|
try {
|
|
63
|
-
const body = new URLSearchParams({
|
|
63
|
+
const body = new URLSearchParams({
|
|
64
|
+
rut: identity.rut,
|
|
65
|
+
dv: identity.dv,
|
|
66
|
+
referencia: exports.RCV,
|
|
67
|
+
'411': '',
|
|
68
|
+
rutcntr: identity.formatted,
|
|
69
|
+
clave
|
|
70
|
+
});
|
|
64
71
|
await this.request(AUTH, async (response) => {
|
|
65
72
|
await response.body?.cancel();
|
|
66
73
|
const redirected = response.status >= 300 && response.status < 400;
|
|
@@ -78,7 +85,15 @@ class SiiHttpSession {
|
|
|
78
85
|
const cookies = await this.cookies(exports.RCV);
|
|
79
86
|
if (!cookies.some(c => c.key === 'TOKEN' && c.value))
|
|
80
87
|
throw this.failure(redirected ? 'SESSION_OR_INTERACTIVE_AUTH_REQUIRED' : 'LOGIN_NOT_CONFIRMED', 'CAutInicio.cgi', redirected ? 'SESSION_REQUIRED' : 'LOGIN_NOT_CONFIRMED', response);
|
|
81
|
-
}, {
|
|
88
|
+
}, {
|
|
89
|
+
method: 'POST',
|
|
90
|
+
headers: {
|
|
91
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
92
|
+
Origin: 'https://zeusr.sii.cl',
|
|
93
|
+
Referer: `https://zeusr.sii.cl/AUT2000/InicioAutenticacion/IngresoRutClave.html?${exports.RCV}`
|
|
94
|
+
},
|
|
95
|
+
body: body.toString()
|
|
96
|
+
}, false, true);
|
|
82
97
|
await this.request(SESSION, async (response) => {
|
|
83
98
|
const sessionEnvelope = await this.json(response, 'aaSessionService/load');
|
|
84
99
|
const session = isRecord(sessionEnvelope) && isRecord(sessionEnvelope.data) ? sessionEnvelope.data : undefined;
|
|
@@ -97,7 +112,8 @@ class SiiHttpSession {
|
|
|
97
112
|
}
|
|
98
113
|
catch (error) {
|
|
99
114
|
// Preserve authentication failure; callers still observe cleanup failure through dispose().
|
|
100
|
-
await this.dispose().catch(() => {
|
|
115
|
+
await this.dispose().catch(() => {
|
|
116
|
+
});
|
|
101
117
|
throw error;
|
|
102
118
|
}
|
|
103
119
|
}
|
|
@@ -106,10 +122,17 @@ class SiiHttpSession {
|
|
|
106
122
|
throw new sii_error_1.SiiError('SESSION_REQUIRED');
|
|
107
123
|
return this.#identity;
|
|
108
124
|
}
|
|
109
|
-
cookies(url) {
|
|
125
|
+
cookies(url) {
|
|
126
|
+
return this.#jar.getCookies(url);
|
|
127
|
+
}
|
|
110
128
|
failure(code, endpoint, reason, response, extra = {}) {
|
|
111
|
-
return new sii_error_1.SiiError(code, response?.status, {
|
|
112
|
-
|
|
129
|
+
return new sii_error_1.SiiError(code, response?.status, {
|
|
130
|
+
traceId: this.#traceId, stage: ENDPOINT_STAGES[endpoint], endpoint, reason,
|
|
131
|
+
...(response ? {
|
|
132
|
+
httpStatus: response.status, ...responseFormat(response),
|
|
133
|
+
retryAfterMs: retryAfterMs(response)
|
|
134
|
+
} : {}), ...extra
|
|
135
|
+
});
|
|
113
136
|
}
|
|
114
137
|
abortFailure(signal, endpoint) {
|
|
115
138
|
return signal.reason instanceof sii_error_1.SiiError ? signal.reason : this.failure('SII_OPERATION_ABORTED', endpoint, 'OPERATION_ABORTED');
|
|
@@ -172,7 +195,8 @@ class SiiHttpSession {
|
|
|
172
195
|
return result;
|
|
173
196
|
}
|
|
174
197
|
catch (error) {
|
|
175
|
-
await response.body?.cancel().catch(() => {
|
|
198
|
+
await response.body?.cancel().catch(() => {
|
|
199
|
+
});
|
|
176
200
|
throw error;
|
|
177
201
|
}
|
|
178
202
|
}).catch(error => {
|
|
@@ -193,21 +217,30 @@ class SiiHttpSession {
|
|
|
193
217
|
}
|
|
194
218
|
const bytes = response.body ? await this.readBounded(response, endpoint, MAX_JSON_BYTES, 'SII_PROTOCOL_CHANGED', signal) : new Uint8Array();
|
|
195
219
|
try {
|
|
196
|
-
return JSON.parse(new TextDecoder().decode(bytes))
|
|
220
|
+
return JSON.parse(new TextDecoder().decode(bytes), (_key, value, context) => {
|
|
221
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || Number.isSafeInteger(value))
|
|
222
|
+
return value;
|
|
223
|
+
if (!context?.source || !/^-?\d{1,20}$/.test(context.source))
|
|
224
|
+
throw new TypeError('SII_UNSAFE_JSON_NUMBER');
|
|
225
|
+
return context.source;
|
|
226
|
+
});
|
|
197
227
|
}
|
|
198
228
|
catch {
|
|
199
229
|
throw this.failure('SII_PROTOCOL_CHANGED', endpoint, 'INVALID_RESPONSE', response);
|
|
200
230
|
}
|
|
201
231
|
}
|
|
202
|
-
async readBounded(response, endpoint, limit =
|
|
232
|
+
async readBounded(response, endpoint, limit = contracts_1.MAX_DTE_XML_BYTES, oversizedCode = 'SII_XML_INVALID', signal) {
|
|
203
233
|
const reader = response.body?.getReader();
|
|
204
234
|
if (!reader)
|
|
205
235
|
throw this.failure('SII_XML_UNAVAILABLE', endpoint, 'EMPTY_RESPONSE', response, { responseType: 'EMPTY' });
|
|
206
236
|
let size = 0;
|
|
207
237
|
const chunks = [];
|
|
208
238
|
let cancellation;
|
|
209
|
-
const cancelSource = () => cancellation ??= reader.cancel().catch(() => {
|
|
210
|
-
|
|
239
|
+
const cancelSource = () => cancellation ??= reader.cancel().catch(() => {
|
|
240
|
+
});
|
|
241
|
+
const onAbort = () => {
|
|
242
|
+
void cancelSource();
|
|
243
|
+
};
|
|
211
244
|
signal?.addEventListener('abort', onAbort, { once: true });
|
|
212
245
|
try {
|
|
213
246
|
for (;;) {
|
|
@@ -255,7 +288,12 @@ class SiiHttpSession {
|
|
|
255
288
|
const headers = new Headers({ Referer: exports.RCV, Cookie: cookies.map(c => c.cookieString()).join('; ') });
|
|
256
289
|
for (let attempt = 1;; attempt++) {
|
|
257
290
|
try {
|
|
258
|
-
const response = await this.#fetch(LOGOUT, {
|
|
291
|
+
const response = await this.#fetch(LOGOUT, {
|
|
292
|
+
method: 'GET',
|
|
293
|
+
headers,
|
|
294
|
+
redirect: 'manual',
|
|
295
|
+
signal: AbortSignal.timeout(this.#timeoutMs)
|
|
296
|
+
});
|
|
259
297
|
if (!response.ok) {
|
|
260
298
|
await response.body?.cancel();
|
|
261
299
|
if (!(response.status >= 300 && response.status < 400 && response.headers.get('location') === 'https://homer.sii.cl/'))
|
|
@@ -306,7 +344,12 @@ class SiiHttpSession {
|
|
|
306
344
|
let response;
|
|
307
345
|
try {
|
|
308
346
|
const timeout = AbortSignal.timeout(this.#timeoutMs);
|
|
309
|
-
response = await this.#fetch(url, {
|
|
347
|
+
response = await this.#fetch(url, {
|
|
348
|
+
...options,
|
|
349
|
+
headers,
|
|
350
|
+
redirect: 'manual',
|
|
351
|
+
signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout
|
|
352
|
+
});
|
|
310
353
|
}
|
|
311
354
|
catch (error) {
|
|
312
355
|
if (options.signal?.aborted)
|
|
@@ -352,11 +395,32 @@ function retryAfterMs(response) {
|
|
|
352
395
|
return Number.isFinite(value) && value >= 0 ? Math.min(2_592_000_000, Math.ceil(value)) : undefined;
|
|
353
396
|
}
|
|
354
397
|
const ENDPOINT_STAGES = {
|
|
355
|
-
'CAutInicio.cgi': 'AUTHENTICATION',
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
398
|
+
'CAutInicio.cgi': 'AUTHENTICATION',
|
|
399
|
+
'aaSessionService/load': 'SESSION_CHECK',
|
|
400
|
+
getDcvEmpresasAutorizadas: 'COMPANY_AUTHORIZATION',
|
|
401
|
+
getDatosInicio: 'RCV_INITIALIZATION',
|
|
402
|
+
getResumen: 'RCV_SUMMARY',
|
|
403
|
+
getDetalleCompra: 'RCV_DETAIL',
|
|
404
|
+
getDetalleVenta: 'RCV_DETAIL',
|
|
405
|
+
'mipeSelEmpresa.cgi': 'XML_COMPANY_SELECTION',
|
|
406
|
+
'mipeLaunchPage.cgi': 'XML_COMPANY_SELECTION',
|
|
407
|
+
'mipeDownLoad.cgi': 'XML_DOWNLOAD',
|
|
408
|
+
'autTermino.cgi': 'LOGOUT',
|
|
409
|
+
'mipeGenFacEx.cgi': 'DOCUMENT_PREPARATION',
|
|
410
|
+
'mipeDisplayPreView.cgi': 'DOCUMENT_REVIEW',
|
|
411
|
+
'mipeGenXMLFirma.cgi': 'DOCUMENT_SIGNING',
|
|
412
|
+
'getCertDigital.cgi': 'DOCUMENT_SIGNING',
|
|
413
|
+
'postFirmaDigital.cgi': 'DOCUMENT_SIGNING',
|
|
414
|
+
'mipeSendXML.cgi': 'DOCUMENT_SEND',
|
|
415
|
+
'mipeAdminDocsEmi.cgi': 'DOCUMENT_RECOVERY',
|
|
416
|
+
'mipeGesDocEmi.cgi': 'DOCUMENT_RECOVERY',
|
|
417
|
+
'mipeDisplayPDF.cgi': 'PDF_DOWNLOAD',
|
|
418
|
+
'mipeAdminDocsRcp.cgi': 'PDF_HISTORY',
|
|
419
|
+
'mipeShowPdf.cgi': 'PDF_DOWNLOAD',
|
|
420
|
+
DTEauth: 'DOCUMENT_STATUS',
|
|
421
|
+
QEstadoDTE: 'DOCUMENT_STATUS',
|
|
422
|
+
registrorechazodtej6ui: 'RECIPIENT_EVENTS',
|
|
423
|
+
validarAccesoReceptor: 'RECIPIENT_EVENTS',
|
|
360
424
|
};
|
|
361
425
|
const DOCUMENT_ENDPOINTS = new Map([
|
|
362
426
|
[exports.DOCUMENT_STATUS_FORM, 'DTEauth'], [exports.DOCUMENT_STATUS_URL, 'QEstadoDTE'],
|
package/dist/sii-error.d.ts
CHANGED
|
@@ -18,6 +18,10 @@ export interface SiiDiagnostics {
|
|
|
18
18
|
}
|
|
19
19
|
/** Only bounded, known protocol values cross this boundary. Never provider text or URLs. */
|
|
20
20
|
export declare function sanitizeSiiDiagnostics(value: unknown): SiiDiagnostics | undefined;
|
|
21
|
+
/**
|
|
22
|
+
* Error público del SDK con código estable, estado HTTP opcional y diagnósticos sanitizados.
|
|
23
|
+
* No conserva credenciales ni cuerpos del proveedor. description explica la etapa observada del fallo.
|
|
24
|
+
*/
|
|
21
25
|
export declare class SiiError extends Error {
|
|
22
26
|
readonly code: string;
|
|
23
27
|
readonly httpStatus?: number | undefined;
|
package/dist/sii-error.js
CHANGED
|
@@ -30,12 +30,25 @@ function sanitizeSiiDiagnostics(value) {
|
|
|
30
30
|
});
|
|
31
31
|
}
|
|
32
32
|
const STAGE_LABELS = {
|
|
33
|
-
AUTHENTICATION: 'inicio de sesión',
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
33
|
+
AUTHENTICATION: 'inicio de sesión',
|
|
34
|
+
SESSION_CHECK: 'validación de sesión',
|
|
35
|
+
COMPANY_AUTHORIZATION: 'autorización de empresa',
|
|
36
|
+
RCV_INITIALIZATION: 'inicio del RCV',
|
|
37
|
+
RCV_SUMMARY: 'resumen del RCV',
|
|
38
|
+
RCV_DETAIL: 'detalle del RCV',
|
|
39
|
+
XML_COMPANY_SELECTION: 'selección de empresa en el facturador',
|
|
40
|
+
XML_DOWNLOAD: 'descarga del XML',
|
|
41
|
+
XML_PARSE: 'validación del XML',
|
|
42
|
+
LOGOUT: 'cierre de sesión',
|
|
43
|
+
DOCUMENT_PREPARATION: 'preparación del documento',
|
|
44
|
+
DOCUMENT_REVIEW: 'revisión del documento',
|
|
45
|
+
DOCUMENT_SIGNING: 'firma del documento',
|
|
46
|
+
DOCUMENT_SEND: 'envío del documento',
|
|
47
|
+
DOCUMENT_RECOVERY: 'recuperación del documento emitido',
|
|
48
|
+
PDF_HISTORY: 'búsqueda de factura en el historial',
|
|
49
|
+
PDF_DOWNLOAD: 'descarga del PDF',
|
|
50
|
+
DOCUMENT_STATUS: 'consulta de recepción y contenido del DTE',
|
|
51
|
+
RECIPIENT_EVENTS: 'consulta de eventos del DTE',
|
|
39
52
|
COMPANY_LOOKUP: 'consulta de datos de empresa por RUT',
|
|
40
53
|
};
|
|
41
54
|
const REASON_LABELS = {
|
|
@@ -57,19 +70,31 @@ const REASON_LABELS = {
|
|
|
57
70
|
COMPANY_IDENTITY_MISMATCH: 'SII devolvió datos de otro RUT; no se entregaron.',
|
|
58
71
|
COMPANY_INFO_UNAVAILABLE: 'SII no entregó datos utilizables para este RUT. No confirma inexistencia del contribuyente.',
|
|
59
72
|
RESPONSE_TOO_LARGE: 'La respuesta de SII supera el límite permitido para este tipo de respuesta y no se procesó.',
|
|
60
|
-
HTTP_ERROR: 'SII respondió con un error HTTP.',
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
73
|
+
HTTP_ERROR: 'SII respondió con un error HTTP.',
|
|
74
|
+
TIMEOUT: 'SII no respondió dentro del tiempo permitido.',
|
|
75
|
+
TRANSPORT_ERROR: 'No se pudo completar la comunicación con SII.',
|
|
76
|
+
RETRY_LATER: 'SII pidió esperar antes de volver a consultar.',
|
|
77
|
+
CAPTCHA_REQUIRED: 'SII requiere resolver un CAPTCHA en su sitio.',
|
|
78
|
+
SESSION_REQUIRED: 'SII requiere autenticación interactiva o una sesión válida.',
|
|
79
|
+
LOGIN_NOT_CONFIRMED: 'SII no confirmó el inicio de sesión.',
|
|
80
|
+
PERSONAL_SESSION_REQUIRED: 'SII no confirmó una sesión personal.',
|
|
81
|
+
SESSION_IDENTITY_MISMATCH: 'La sesión de SII no corresponde al usuario solicitado.',
|
|
82
|
+
COMPANY_NOT_AUTHORIZED: 'SII no autorizó el acceso a la empresa solicitada.',
|
|
65
83
|
COMPANY_SELECTION_REQUIRED: 'SII no confirmó la selección de empresa en el facturador.',
|
|
66
|
-
PROVIDER_REJECTED: 'SII rechazó la solicitud.',
|
|
84
|
+
PROVIDER_REJECTED: 'SII rechazó la solicitud.',
|
|
85
|
+
INVALID_RESPONSE: 'SII devolvió una respuesta que no cumple el contrato esperado.',
|
|
67
86
|
DOCUMENT_CONTENT_MISMATCH: 'El contenido fiscal recibido difiere del contenido aprobado. No se envió el documento.',
|
|
68
87
|
CERTIFICATE_UNAVAILABLE: 'SII no devolvió un certificado centralizado utilizable para esta identidad.',
|
|
69
|
-
CERTIFICATE_PASSWORD_INVALID: 'SII rechazó la clave del certificado centralizado.',
|
|
88
|
+
CERTIFICATE_PASSWORD_INVALID: 'SII rechazó la clave del certificado centralizado.',
|
|
89
|
+
CERTIFICATE_EXPIRED: 'El certificado centralizado está expirado.',
|
|
90
|
+
CERTIFICATE_REVOKED: 'El certificado centralizado está revocado.',
|
|
70
91
|
SIGNATURE_INVALID: 'SII no devolvió un XML firmado válido para el documento aprobado. No se envió.',
|
|
71
92
|
ISSUANCE_OUTCOME_UNKNOWN: 'El envío comenzó pero no se confirmó su resultado. Conserve el XML y consulte el historial antes de volver a emitir; repetir puede duplicar el documento.',
|
|
72
93
|
};
|
|
94
|
+
/**
|
|
95
|
+
* Error público del SDK con código estable, estado HTTP opcional y diagnósticos sanitizados.
|
|
96
|
+
* No conserva credenciales ni cuerpos del proveedor. description explica la etapa observada del fallo.
|
|
97
|
+
*/
|
|
73
98
|
class SiiError extends Error {
|
|
74
99
|
code;
|
|
75
100
|
httpStatus;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@devly-cl/sii-client",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.11",
|
|
4
4
|
"description": "Cliente HTTP del SII para acceso personal, RCV, XML, PDF por streaming y emisión de facturas y notas de crédito, independiente de framework.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"type": "commonjs",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"scripts": {
|
|
28
28
|
"build": "tsc -p tsconfig.json",
|
|
29
29
|
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
30
|
-
"test": "npm run build && node test/check.mjs && node test/invoices.mjs && node test/rcv-documents.mjs && node test/xml.mjs && node test/reconciliation.mjs && node --test test/rounding.mjs && node test/logout.mjs && node --test test/session-lifecycle.mjs && node test/credit-note-xml.mjs && node test/facturador.mjs && node test/invoicing.mjs && node test/invoice-optionals.mjs && node test/invoice-optionals-http.mjs && node test/issuance.mjs && node test/issuance-edges.mjs && node test/api-naming.mjs && node test/company-selection.mjs && node test/company-info.mjs && node test/transport-lifecycle.mjs && node test/application.mjs && node test/architecture.mjs && node test/pdf.mjs && node test/pdf-http.mjs && node test/document-status.mjs",
|
|
30
|
+
"test": "npm run build && node test/check.mjs && node test/invoices.mjs && node test/rcv-documents.mjs && node test/xml.mjs && node test/reconciliation.mjs && node --test test/xml-duplicates.mjs test/dte-read.mjs test/documentary-import.mjs test/dte25.mjs && node --test test/rounding.mjs && node test/logout.mjs && node --test test/session-lifecycle.mjs && node test/credit-note-xml.mjs && node test/facturador.mjs && node test/invoicing.mjs && node test/invoice-optionals.mjs && node test/invoice-optionals-http.mjs && node test/issuance.mjs && node test/issuance-edges.mjs && node test/api-naming.mjs && node test/company-selection.mjs && node test/company-info.mjs && node test/transport-lifecycle.mjs && node test/application.mjs && node test/architecture.mjs && node test/pdf.mjs && node test/pdf-http.mjs && node test/document-status.mjs",
|
|
31
31
|
"check:example": "tsc --strict --noEmit --target ES2022 --module Node16 --moduleResolution Node16 --types node examples/consulta-rcv.ts examples/facturacion.ts examples/factura-opcionales.ts examples/consulta-pdf.ts examples/consulta-estado-documento.ts examples/consulta-empresa.ts",
|
|
32
32
|
"check": "npm run typecheck && npm test && npm run check:example",
|
|
33
33
|
"test:live": "npm run build && node scripts/live-check.mjs",
|