@devly-cl/sii-client 0.0.0-stage → 0.4.4

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.
@@ -0,0 +1,9 @@
1
+ export { SiiClient, SiiError } from './infrastructure/sii-client';
2
+ export { sanitizeSiiDiagnostics } from './domain/sii-error';
3
+ export type { SiiDiagnostics } from './domain/sii-error';
4
+ export { parseRut } from './domain/rut';
5
+ export { parseDteXml, DteXmlError, MAX_DTE_XML_BYTES } from './domain/invoice-xml';
6
+ export type { ConsultaXmlFacturaEmitida, ConsultaXmlFacturaRecibida, DteInvoiceLine, DteInvoiceDetail, ResultadoXmlFacturaEmitida } from './domain/invoice-xml';
7
+ export type { ConsultaFacturasEmitidas, FacturaEmitida, ResultadoFacturasEmitidas, TipoFacturaEmitida } from './domain/issued-invoice';
8
+ export type { ConsultaFacturasRecibidas, FacturaRecibida, ResultadoFacturasRecibidas } from './domain/received-invoice';
9
+ export type { ConsultaResumen, CredencialesSii, EmpresaAutorizada, EstadoCompra, Operacion, RegistroSii, RespuestaSii, SesionSii, SiiClientOptions, } from './infrastructure/sii-client';
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_DTE_XML_BYTES = exports.DteXmlError = exports.parseDteXml = exports.parseRut = exports.sanitizeSiiDiagnostics = exports.SiiError = exports.SiiClient = void 0;
4
+ var sii_client_1 = require("./infrastructure/sii-client");
5
+ Object.defineProperty(exports, "SiiClient", { enumerable: true, get: function () { return sii_client_1.SiiClient; } });
6
+ Object.defineProperty(exports, "SiiError", { enumerable: true, get: function () { return sii_client_1.SiiError; } });
7
+ var sii_error_1 = require("./domain/sii-error");
8
+ Object.defineProperty(exports, "sanitizeSiiDiagnostics", { enumerable: true, get: function () { return sii_error_1.sanitizeSiiDiagnostics; } });
9
+ var rut_1 = require("./domain/rut");
10
+ Object.defineProperty(exports, "parseRut", { enumerable: true, get: function () { return rut_1.parseRut; } });
11
+ var invoice_xml_1 = require("./domain/invoice-xml");
12
+ Object.defineProperty(exports, "parseDteXml", { enumerable: true, get: function () { return invoice_xml_1.parseDteXml; } });
13
+ Object.defineProperty(exports, "DteXmlError", { enumerable: true, get: function () { return invoice_xml_1.DteXmlError; } });
14
+ Object.defineProperty(exports, "MAX_DTE_XML_BYTES", { enumerable: true, get: function () { return invoice_xml_1.MAX_DTE_XML_BYTES; } });
@@ -0,0 +1,58 @@
1
+ export { SiiError } from '../domain/sii-error';
2
+ import { type ConsultaFacturasEmitidas, type ResultadoFacturasEmitidas } from '../domain/issued-invoice';
3
+ import { type ConsultaFacturasRecibidas, type ResultadoFacturasRecibidas } from '../domain/received-invoice';
4
+ import { type ConsultaXmlFacturaEmitida, type ConsultaXmlFacturaRecibida, type ResultadoXmlFacturaEmitida } from '../domain/invoice-xml';
5
+ export type Operacion = 'COMPRA' | 'VENTA';
6
+ export type EstadoCompra = 'REGISTRO' | 'PENDIENTE' | 'NO_INCLUIR' | 'RECLAMADO';
7
+ export type RegistroSii = Record<string, unknown>;
8
+ export interface RespuestaSii<T = RegistroSii> {
9
+ data: T[];
10
+ metaData: Record<string, unknown>;
11
+ respEstado: {
12
+ codRespuesta: number;
13
+ msgeRespuesta: string | null;
14
+ codError: unknown;
15
+ };
16
+ [key: string]: unknown;
17
+ }
18
+ export interface EmpresaAutorizada extends RegistroSii {
19
+ usrEmpRut: number;
20
+ usrEmpDv: string;
21
+ usrEmpRutDv: string;
22
+ }
23
+ export interface SiiClientOptions {
24
+ empresaRut: string;
25
+ timeoutMs?: number;
26
+ retries?: number;
27
+ fetchImpl?: typeof globalThis.fetch;
28
+ }
29
+ export interface CredencialesSii {
30
+ rut: string;
31
+ clave: string;
32
+ }
33
+ export interface ConsultaResumen {
34
+ periodo: string;
35
+ operacion: Operacion;
36
+ estado?: EstadoCompra;
37
+ }
38
+ export interface SesionSii {
39
+ usuarioRut: string;
40
+ empresaRut: string;
41
+ representacion: false;
42
+ }
43
+ /** Una instancia = una empresa y una sesión personal. Nunca comparte cookies. */
44
+ export declare class SiiClient {
45
+ #private;
46
+ constructor({ empresaRut, timeoutMs, retries, fetchImpl }: SiiClientOptions);
47
+ login({ rut, clave }: CredencialesSii): Promise<SesionSii>;
48
+ getEmpresasAutorizadas(): Promise<RespuestaSii<EmpresaAutorizada>>;
49
+ getResumen({ periodo, operacion, estado }: ConsultaResumen): Promise<RespuestaSii>;
50
+ getFacturasEmitidas(input: ConsultaFacturasEmitidas): Promise<ResultadoFacturasEmitidas>;
51
+ /** Facturas 33/34 in the official purchase register. Does not accept, claim or move documents. */
52
+ getFacturasRecibidas(input: ConsultaFacturasRecibidas): Promise<ResultadoFacturasRecibidas>;
53
+ /** Original DTE from the free SII facturador; RCV membership alone does not guarantee XML availability. */
54
+ getXmlFacturaEmitida(input: ConsultaXmlFacturaEmitida): Promise<ResultadoXmlFacturaEmitida>;
55
+ getXmlFacturaRecibida(input: ConsultaXmlFacturaRecibida): Promise<ResultadoXmlFacturaEmitida>;
56
+ /** Cierra esta sesión remota antes de descartar cookies; siempre esperar en finally. */
57
+ dispose(): Promise<void>;
58
+ }
@@ -0,0 +1,498 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SiiClient = exports.SiiError = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const promises_1 = require("node:timers/promises");
6
+ const tough_cookie_1 = require("tough-cookie");
7
+ const parse5_1 = require("parse5");
8
+ const rut_1 = require("../domain/rut");
9
+ const sii_error_1 = require("../domain/sii-error");
10
+ var sii_error_2 = require("../domain/sii-error");
11
+ Object.defineProperty(exports, "SiiError", { enumerable: true, get: function () { return sii_error_2.SiiError; } });
12
+ const issued_invoice_1 = require("../domain/issued-invoice");
13
+ const received_invoice_1 = require("../domain/received-invoice");
14
+ const invoice_xml_1 = require("../domain/invoice-xml");
15
+ const AUTH = 'https://zeusr.sii.cl/cgi_AUT2000/CAutInicio.cgi';
16
+ const LOGOUT = 'https://zeusr.sii.cl/cgi_AUT2000/autTermino.cgi';
17
+ const RCV = 'https://www4.sii.cl/consdcvinternetui/';
18
+ const SESSION = 'https://www4.sii.cl/common-1.0/services/aaSessionService/load';
19
+ const NAMESPACE = 'cl.sii.sdi.lob.diii.consdcv.data.api.interfaces.FacadeService/';
20
+ const RETRYABLE = new Set([429, 502, 503, 504]);
21
+ const STATES = new Set(['REGISTRO', 'PENDIENTE', 'NO_INCLUIR', 'RECLAMADO']);
22
+ const FACTURADOR = 'https://www1.sii.cl/cgi-bin/Portal001/';
23
+ const FACTURADOR_DESTINATION = 'OPCION=2&TIPO=4';
24
+ const ENDPOINT_STAGES = {
25
+ 'CAutInicio.cgi': 'AUTHENTICATION', 'aaSessionService/load': 'SESSION_CHECK', getDcvEmpresasAutorizadas: 'COMPANY_AUTHORIZATION',
26
+ getDatosInicio: 'RCV_INITIALIZATION', getResumen: 'RCV_SUMMARY', getDetalleCompra: 'RCV_DETAIL', getDetalleVenta: 'RCV_DETAIL',
27
+ 'mipeSelEmpresa.cgi': 'XML_COMPANY_SELECTION', 'mipeLaunchPage.cgi': 'XML_COMPANY_SELECTION', 'mipeDownLoad.cgi': 'XML_DOWNLOAD', 'autTermino.cgi': 'LOGOUT',
28
+ };
29
+ function endpointFor(url) {
30
+ const path = new URL(url).pathname;
31
+ const endpoint = path.endsWith('/aaSessionService/load') ? 'aaSessionService/load' : path.slice(path.lastIndexOf('/') + 1);
32
+ if (!Object.hasOwn(ENDPOINT_STAGES, endpoint))
33
+ throw new TypeError('Endpoint SII desconocido');
34
+ return endpoint;
35
+ }
36
+ function responseFormat(response, bytes) {
37
+ const contentType = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
38
+ const prefix = bytes ? Buffer.from(bytes.subarray(0, 512)).toString('latin1').trimStart() : '';
39
+ const responseType = bytes?.length === 0 ? 'EMPTY'
40
+ : prefix.startsWith('%PDF-') ? 'PDF'
41
+ : bytes && bytes[0] === 0x50 && bytes[1] === 0x4b && [0x03, 0x05, 0x07].includes(bytes[2] ?? -1) ? 'ZIP'
42
+ : /^(?:<!doctype\s+html|<html|<head|<body|<script|<div)\b/i.test(prefix) ? 'HTML'
43
+ : contentType === 'text/html' ? 'HTML'
44
+ : contentType === 'application/pdf' ? 'PDF'
45
+ : contentType === 'application/zip' ? 'ZIP'
46
+ : contentType?.includes('json') ? 'JSON'
47
+ : /^(?:application|text)\/xml$/.test(contentType ?? '') || /^<(?:\?xml|DTE|EnvioDTE|SetDTE)\b/i.test(prefix) ? 'XML' : 'UNKNOWN';
48
+ // The sanitizer copies only known MIME values.
49
+ return { responseType, ...(contentType ? { contentType: contentType } : {}) };
50
+ }
51
+ function isRecord(value) {
52
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
53
+ }
54
+ function assertPeriod(periodo) {
55
+ if (typeof periodo !== 'string' || !/^\d{4}(0[1-9]|1[0-2])$/.test(periodo) || Number(periodo.slice(0, 4)) < 2017)
56
+ throw new TypeError('Periodo inválido: YYYYMM');
57
+ }
58
+ function htmlElements(root) {
59
+ const pending = [root];
60
+ const elements = [];
61
+ for (let node = pending.pop(); node; node = pending.pop()) {
62
+ if ('tagName' in node && node.namespaceURI === 'http://www.w3.org/1999/xhtml')
63
+ elements.push(node);
64
+ if ('childNodes' in node)
65
+ for (const child of node.childNodes)
66
+ pending.push(child);
67
+ }
68
+ return elements;
69
+ }
70
+ /** Read the observed selector inertly; never execute scripts or forward arbitrary form fields. */
71
+ function companySelection(page, company) {
72
+ const attr = (element, name) => element.attrs.find(a => a.name === name)?.value;
73
+ const forms = htmlElements((0, parse5_1.parse)(page)).filter(e => e.tagName === 'form' && attr(e, 'name') === 'fPrmEmpPOP');
74
+ const form = forms[0];
75
+ if (!form)
76
+ return undefined;
77
+ if (forms.length !== 1 || attr(form, 'method')?.toLowerCase() !== 'post')
78
+ return 'INVALID_RESPONSE';
79
+ try {
80
+ if (new URL(attr(form, 'action') ?? '', FACTURADOR).href !== `${FACTURADOR}mipeSelEmpresa.cgi`)
81
+ return 'INVALID_RESPONSE';
82
+ }
83
+ catch {
84
+ return 'INVALID_RESPONSE';
85
+ }
86
+ const controls = htmlElements(form);
87
+ const selects = controls.filter(e => e.tagName === 'select' && attr(e, 'name') === 'RUT_EMP');
88
+ const destinations = controls.filter(e => e.tagName === 'input' && attr(e, 'name') === 'DESDE_DONDE_URL');
89
+ const select = selects[0], destination = destinations[0];
90
+ if (selects.length !== 1 || destinations.length !== 1 || !select || !destination
91
+ || attr(select, 'disabled') !== undefined || attr(select, 'multiple') !== undefined || attr(select, 'form') !== undefined
92
+ || attr(destination, 'type')?.toLowerCase() !== 'hidden' || attr(destination, 'disabled') !== undefined || attr(destination, 'form') !== undefined
93
+ || attr(destination, 'value') !== FACTURADOR_DESTINATION)
94
+ return 'INVALID_RESPONSE';
95
+ const options = htmlElements(select).filter(e => e.tagName === 'option' && attr(e, 'value')?.replace(/\./g, '').toUpperCase() === company);
96
+ if (options.length > 1)
97
+ return 'INVALID_RESPONSE';
98
+ const option = options[0];
99
+ if (!option || attr(option, 'disabled') !== undefined
100
+ || (option.parentNode && 'tagName' in option.parentNode && option.parentNode.tagName === 'optgroup' && attr(option.parentNode, 'disabled') !== undefined))
101
+ return 'COMPANY_NOT_AUTHORIZED';
102
+ return new URLSearchParams({ DESDE_DONDE_URL: FACTURADOR_DESTINATION, RUT_EMP: company });
103
+ }
104
+ /** Una instancia = una empresa y una sesión personal. Nunca comparte cookies. */
105
+ class SiiClient {
106
+ #jar = new tough_cookie_1.CookieJar();
107
+ #company;
108
+ #fetch;
109
+ #timeoutMs;
110
+ #retries;
111
+ #identity;
112
+ #ready = false;
113
+ #used = false;
114
+ #closed = false;
115
+ #facturadorReady = false;
116
+ #requests = new Set();
117
+ #disposal;
118
+ #traceId = (0, node_crypto_1.randomUUID)();
119
+ #failure(code, endpoint, reason, response, extra = {}) {
120
+ return new sii_error_1.SiiError(code, response?.status, { traceId: this.#traceId, stage: ENDPOINT_STAGES[endpoint], endpoint, reason,
121
+ ...(response ? { httpStatus: response.status, ...responseFormat(response) } : {}), ...extra });
122
+ }
123
+ constructor({ empresaRut, timeoutMs = 15000, retries = 1, fetchImpl = globalThis.fetch }) {
124
+ this.#company = (0, rut_1.parseRut)(empresaRut);
125
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 30000)
126
+ throw new TypeError('timeoutMs inválido');
127
+ if (!Number.isInteger(retries) || retries < 0 || retries > 2)
128
+ throw new TypeError('retries inválido');
129
+ if (typeof fetchImpl !== 'function')
130
+ throw new TypeError('fetchImpl inválido');
131
+ this.#fetch = fetchImpl;
132
+ this.#timeoutMs = timeoutMs;
133
+ this.#retries = retries;
134
+ }
135
+ async login({ rut, clave }) {
136
+ if (this.#used || this.#closed)
137
+ throw new sii_error_1.SiiError('NEW_INSTANCE_REQUIRED');
138
+ const identity = (0, rut_1.parseRut)(rut);
139
+ if (typeof clave !== 'string' || !clave || clave.length > 256)
140
+ throw new TypeError('Clave inválida');
141
+ this.#used = true;
142
+ try {
143
+ const body = new URLSearchParams({ rut: identity.rut, dv: identity.dv, referencia: RCV, '411': '', rutcntr: identity.formatted, clave });
144
+ const response = await this.#request(AUTH, {
145
+ method: 'POST',
146
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Origin: 'https://zeusr.sii.cl', Referer: `https://zeusr.sii.cl/AUT2000/InicioAutenticacion/IngresoRutClave.html?${RCV}` },
147
+ body: body.toString(),
148
+ });
149
+ await response.body?.cancel();
150
+ const cookies = await this.#jar.getCookies(RCV);
151
+ if (!cookies.some(c => c.key === 'TOKEN' && c.value))
152
+ throw this.#failure('LOGIN_NOT_CONFIRMED', 'CAutInicio.cgi', 'LOGIN_NOT_CONFIRMED', response);
153
+ const sessionResponse = await this.#request(SESSION, {}, true);
154
+ const sessionEnvelope = await this.#json(sessionResponse, 'aaSessionService/load');
155
+ const session = isRecord(sessionEnvelope) && isRecord(sessionEnvelope.data) ? sessionEnvelope.data : undefined;
156
+ if (session?.hayRepresentacion !== false)
157
+ throw this.#failure('PERSONAL_SESSION_REQUIRED', 'aaSessionService/load', 'PERSONAL_SESSION_REQUIRED', sessionResponse);
158
+ if (`${session?.rut}-${session?.dv}`.toUpperCase() !== identity.formatted)
159
+ throw this.#failure('SESSION_IDENTITY_MISMATCH', 'aaSessionService/load', 'SESSION_IDENTITY_MISMATCH', sessionResponse);
160
+ this.#identity = identity;
161
+ const companies = await this.#call('getDcvEmpresasAutorizadas', { rutAutenticado: identity.rut, dvAutenticado: identity.dv });
162
+ if (!companies.data.some(c => `${c.usrEmpRut}-${c.usrEmpDv}`.toUpperCase() === this.#company.formatted)) {
163
+ throw this.#failure('COMPANY_NOT_AUTHORIZED', 'getDcvEmpresasAutorizadas', 'COMPANY_NOT_AUTHORIZED');
164
+ }
165
+ if (this.#closed)
166
+ throw new sii_error_1.SiiError('CLIENT_CLOSED');
167
+ this.#ready = true;
168
+ return { usuarioRut: identity.formatted, empresaRut: this.#company.formatted, representacion: false };
169
+ }
170
+ catch (error) {
171
+ await this.dispose();
172
+ throw error;
173
+ }
174
+ }
175
+ async getEmpresasAutorizadas() {
176
+ const identity = this.#assertReady();
177
+ return this.#call('getDcvEmpresasAutorizadas', { rutAutenticado: identity.rut, dvAutenticado: identity.dv });
178
+ }
179
+ async getResumen({ periodo, operacion, estado = 'REGISTRO' }) {
180
+ this.#assertReady();
181
+ assertPeriod(periodo);
182
+ if (!['COMPRA', 'VENTA'].includes(operacion))
183
+ throw new TypeError('Operación inválida');
184
+ if (!STATES.has(estado) || (operacion === 'VENTA' && estado !== 'REGISTRO'))
185
+ throw new TypeError('Estado inválido');
186
+ return this.#call('getResumen', { rutEmisor: this.#company.rut, dvEmisor: this.#company.dv, ptributario: periodo, estadoContab: estado, operacion });
187
+ }
188
+ getFacturasEmitidas(input) {
189
+ return this.#getFacturas('VENTA', input, issued_invoice_1.normalizeIssuedInvoice);
190
+ }
191
+ /** Facturas 33/34 in the official purchase register. Does not accept, claim or move documents. */
192
+ getFacturasRecibidas(input) {
193
+ return this.#getFacturas('COMPRA', input, received_invoice_1.normalizeReceivedInvoice);
194
+ }
195
+ async #getFacturas(operacion, { periodo, tokenRecaptcha = 't-o-k-e-n-web' }, normalize) {
196
+ this.#assertReady();
197
+ assertPeriod(periodo);
198
+ if (typeof tokenRecaptcha !== 'string' || !tokenRecaptcha.trim())
199
+ throw new TypeError('tokenRecaptcha inválido');
200
+ const initial = await this.#call('getDatosInicio', {});
201
+ if (typeof initial.limiteDtes !== 'number' || !Number.isSafeInteger(initial.limiteDtes) || initial.limiteDtes < 1)
202
+ throw this.#failure('SII_INVALID_RESPONSE', 'getDatosInicio', 'INVALID_RESPONSE');
203
+ const summary = await this.getResumen({ periodo, operacion });
204
+ const expected = new Map();
205
+ let expectedCount = 0;
206
+ for (const row of summary.data) {
207
+ const type = row.rsmnTipoDocInteger;
208
+ if (typeof type !== 'number' || !Number.isSafeInteger(type) || type < 1)
209
+ throw this.#failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
210
+ if (type !== 33 && type !== 34)
211
+ continue;
212
+ const count = row.rsmnTotDoc;
213
+ if (typeof count !== 'number' || !Number.isSafeInteger(count) || count < 0 || (expected.has(type) && expected.get(type) !== count))
214
+ throw this.#failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
215
+ if (!expected.has(type))
216
+ expectedCount += count;
217
+ if (!Number.isSafeInteger(expectedCount))
218
+ throw this.#failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
219
+ expected.set(type, count);
220
+ }
221
+ const invoices = new Map();
222
+ const incompleteDocumentTypes = [];
223
+ for (const [type, count] of expected) {
224
+ if (count === 0)
225
+ continue;
226
+ const method = operacion === 'COMPRA' ? 'getDetalleCompra' : 'getDetalleVenta';
227
+ const details = await this.#call(method, {
228
+ rutEmisor: this.#company.rut, dvEmisor: this.#company.dv, ptributario: periodo,
229
+ codTipoDoc: String(type), operacion: operacion === 'COMPRA' ? 'COMPRA' : '', estadoContab: operacion === 'COMPRA' ? 'REGISTRO' : '', accionRecaptcha: operacion === 'COMPRA' ? 'RCV_DETC' : 'RCV_DETV', tokenRecaptcha,
230
+ });
231
+ let uniqueCount = 0;
232
+ for (const row of details.data) {
233
+ let invoice;
234
+ try {
235
+ invoice = normalize(row, this.#company.formatted, periodo, type);
236
+ }
237
+ catch {
238
+ throw this.#failure('SII_INVALID_RESPONSE', method, 'INVALID_RESPONSE');
239
+ }
240
+ const key = `${invoice.issuerRut}:${invoice.documentType}:${invoice.folio}`;
241
+ const previous = invoices.get(key);
242
+ if (previous && JSON.stringify(previous) !== JSON.stringify(invoice))
243
+ throw this.#failure('SII_INVALID_RESPONSE', method, 'INVALID_RESPONSE');
244
+ if (!previous) {
245
+ invoices.set(key, invoice);
246
+ uniqueCount++;
247
+ }
248
+ }
249
+ if (count > initial.limiteDtes || uniqueCount !== count)
250
+ incompleteDocumentTypes.push(type);
251
+ }
252
+ return { data: [...invoices.values()], complete: incompleteDocumentTypes.length === 0, expectedCount, observedAt: new Date().toISOString(), incompleteDocumentTypes };
253
+ }
254
+ /** Original DTE from the free SII facturador; RCV membership alone does not guarantee XML availability. */
255
+ getXmlFacturaEmitida(input) {
256
+ return this.#getXmlFactura(input);
257
+ }
258
+ getXmlFacturaRecibida(input) {
259
+ return this.#getXmlFactura(input, (0, rut_1.parseRut)(input.issuerRut));
260
+ }
261
+ async #getXmlFactura({ documentType, folio }, supplier) {
262
+ this.#assertReady();
263
+ if (![33, 34].includes(documentType) || typeof folio !== 'string' || !/^[1-9]\d{0,19}$/.test(folio))
264
+ throw new TypeError('Identidad de factura inválida');
265
+ if (!this.#facturadorReady) {
266
+ let url = `${FACTURADOR}mipeSelEmpresa.cgi?DESDE_DONDE_URL=OPCION%3D2%26TIPO%3D4`;
267
+ let options = {}, submitted = false;
268
+ for (let hop = 0;; hop++) {
269
+ const response = await this.#request(url, options, options.method !== 'POST', true);
270
+ const location = response.headers.get('location');
271
+ if (response.status >= 300 && response.status < 400) {
272
+ await response.body?.cancel();
273
+ if (!location || hop >= 4)
274
+ throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), 'COMPANY_SELECTION_REQUIRED', response);
275
+ const next = new URL(location, url);
276
+ if (next.origin !== 'https://www1.sii.cl' || !['mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi'].some(path => next.pathname === `/cgi-bin/Portal001/${path}`))
277
+ throw this.#failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', endpointFor(url), 'SESSION_REQUIRED', response);
278
+ url = next.href;
279
+ options = {};
280
+ continue;
281
+ }
282
+ const page = response.body ? Buffer.from(await this.#readBounded(response, endpointFor(url))).toString('latin1') : '';
283
+ if (/recaptcha-response|g-recaptcha|captcha/i.test(page))
284
+ throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', endpointFor(url), 'CAPTCHA_REQUIRED', response);
285
+ const selection = companySelection(page, this.#company.formatted);
286
+ if (typeof selection === 'string')
287
+ throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), selection, response);
288
+ if (selection) {
289
+ if (submitted || hop >= 4)
290
+ throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), 'COMPANY_SELECTION_REQUIRED', response);
291
+ submitted = true;
292
+ url = `${FACTURADOR}mipeSelEmpresa.cgi`;
293
+ options = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: selection.toString() };
294
+ continue;
295
+ }
296
+ break;
297
+ }
298
+ const cookies = await this.#jar.getCookies(FACTURADOR);
299
+ if (cookies.find(c => c.key === 'NETSCAPE_LIVEWIRE.rcmp')?.value !== this.#company.rut || cookies.find(c => c.key === 'NETSCAPE_LIVEWIRE.dcmp')?.value.toUpperCase() !== this.#company.dv)
300
+ throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', 'mipeSelEmpresa.cgi', 'COMPANY_SELECTION_REQUIRED');
301
+ this.#facturadorReady = true;
302
+ }
303
+ // A filtered backup is a read: no emission, cancellation or representation endpoint is called.
304
+ const query = new URLSearchParams({ ORIGEN: supplier ? 'RCP' : 'ENV', ...(supplier ? { RUT_EMI: supplier.rut } : { RUT_RECP: '' }), FOLIO: folio, RZN_SOC: '', FEC_DESDE: '', FEC_HASTA: '', TPO_DOC: String(documentType), ESTADO: '', ORDEN: '', DOWNLOAD: 'XML' });
305
+ const response = await this.#request(`${FACTURADOR}mipeDownLoad.cgi?${query}`, {}, true);
306
+ const bytes = await this.#readBounded(response, 'mipeDownLoad.cgi');
307
+ const format = responseFormat(response, bytes);
308
+ if (format.responseType === 'EMPTY')
309
+ throw this.#failure('SII_SERVICE_ERROR', 'mipeDownLoad.cgi', 'EMPTY_RESPONSE', response, format);
310
+ if (format.responseType === 'PDF' || format.responseType === 'ZIP')
311
+ throw this.#failure('SII_SERVICE_ERROR', 'mipeDownLoad.cgi', format.responseType === 'PDF' ? 'UNEXPECTED_PDF' : 'UNEXPECTED_ARCHIVE', response, format);
312
+ if (format.responseType !== 'XML' && !(format.responseType === 'UNKNOWN' && format.contentType === 'application/octet-stream')) {
313
+ const page = Buffer.from(bytes).toString('latin1');
314
+ const siiMessageCode = page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/)?.[0];
315
+ const evidence = { ...format, ...(siiMessageCode ? { siiMessageCode } : {}) };
316
+ if (/recaptcha-response|g-recaptcha|captcha/i.test(page))
317
+ throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', 'mipeDownLoad.cgi', 'CAPTCHA_REQUIRED', response, evidence);
318
+ const reason = /demasiados\s+documentos/i.test(page) ? 'DOCUMENT_LIMIT_EXCEEDED'
319
+ : /no\s+se\s+encontraron\s+documentos/i.test(page) ? 'DOCUMENT_NOT_FOUND'
320
+ : /error\s+al\s+contribuyente/i.test(page) ? 'PROVIDER_ERROR_PAGE'
321
+ : format.responseType === 'HTML' ? 'HTML_RESPONSE' : 'UNEXPECTED_FORMAT';
322
+ throw this.#failure(reason === 'DOCUMENT_NOT_FOUND' ? 'SII_XML_UNAVAILABLE' : 'SII_SERVICE_ERROR', 'mipeDownLoad.cgi', reason, response, evidence);
323
+ }
324
+ try {
325
+ return (0, invoice_xml_1.parseDteXml)(bytes, { issuerRut: supplier?.formatted ?? this.#company.formatted, ...(supplier ? { receiverRut: this.#company.formatted } : {}), documentType, folio });
326
+ }
327
+ catch (error) {
328
+ const code = error instanceof invoice_xml_1.DteXmlError ? error.code : 'SII_XML_INVALID';
329
+ throw this.#failure(code, 'mipeDownLoad.cgi', code === 'SII_XML_IDENTITY_MISMATCH' ? 'XML_IDENTITY_MISMATCH' : 'INVALID_XML', response, { ...format, stage: 'XML_PARSE' });
330
+ }
331
+ }
332
+ /** Cierra esta sesión remota antes de descartar cookies; siempre esperar en finally. */
333
+ dispose() {
334
+ if (this.#disposal)
335
+ return this.#disposal;
336
+ this.#closed = true;
337
+ this.#ready = false;
338
+ this.#identity = undefined;
339
+ this.#facturadorReady = false;
340
+ this.#disposal = (async () => {
341
+ try {
342
+ // An in-flight login can still issue session cookies after local closure.
343
+ await Promise.allSettled(this.#requests);
344
+ const cookies = await this.#jar.getCookies(LOGOUT);
345
+ if (!cookies.some(c => c.value && ['TOKEN', 'NETSCAPE_LIVEWIRE.mac'].includes(c.key)))
346
+ return;
347
+ const headers = new Headers({ Referer: RCV, Cookie: cookies.map(c => c.cookieString()).join('; ') });
348
+ const response = await this.#fetch(LOGOUT, { method: 'GET', headers, redirect: 'manual', signal: AbortSignal.timeout(this.#timeoutMs) });
349
+ if (!response.ok) {
350
+ await response.body?.cancel();
351
+ if (!(response.status >= 300 && response.status < 400 && response.headers.get('location') === 'https://homer.sii.cl/'))
352
+ throw new sii_error_1.SiiError('SII_LOGOUT_FAILED');
353
+ }
354
+ else {
355
+ const page = Buffer.from(await this.#readBounded(response, 'autTermino.cgi')).toString('latin1');
356
+ const codes = page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/g);
357
+ // Observed 2026-10-01: this code means the remote session is already absent.
358
+ if (codes?.some(code => code !== '01.01.205.529.269.28'))
359
+ throw new sii_error_1.SiiError('SII_LOGOUT_FAILED');
360
+ }
361
+ }
362
+ catch {
363
+ // Preserve the operation's original error; expose cleanup failure without secrets.
364
+ process.emitWarning('SII_LOGOUT_FAILED', { code: 'SII_LOGOUT_FAILED' });
365
+ }
366
+ finally {
367
+ await this.#jar.removeAllCookies();
368
+ }
369
+ })();
370
+ return this.#disposal;
371
+ }
372
+ #assertReady() {
373
+ if (!this.#ready || this.#closed || !this.#identity)
374
+ throw new sii_error_1.SiiError('SESSION_REQUIRED');
375
+ return this.#identity;
376
+ }
377
+ async #call(method, data) {
378
+ const token = (await this.#jar.getCookies(RCV)).find(c => c.key === 'TOKEN')?.value;
379
+ if (!token)
380
+ throw this.#failure('SESSION_REQUIRED', method, 'SESSION_REQUIRED');
381
+ const response = await this.#request(`${RCV}services/data/facadeService/${method}`, {
382
+ method: 'POST',
383
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/plain, */*', Referer: RCV },
384
+ body: JSON.stringify({ metaData: { namespace: NAMESPACE + method, conversationId: token, transactionId: (0, node_crypto_1.randomUUID)(), page: null }, data }),
385
+ }, true);
386
+ const result = await this.#json(response, method);
387
+ if (!isRecord(result))
388
+ throw this.#failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
389
+ const status = result.respEstado;
390
+ const rawMeta = result.metaData ?? {};
391
+ if (!isRecord(status) || !isRecord(rawMeta) || (rawMeta.errors != null && !Array.isArray(rawMeta.errors))) {
392
+ throw this.#failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
393
+ }
394
+ if (status.codRespuesta === 98)
395
+ throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', method, 'CAPTCHA_REQUIRED', response, { siiResponseCode: 98 });
396
+ // RCV shows "No hay información" for this empty-summary response (observed 2026-10-01).
397
+ const emptySummary = method === 'getResumen' && status.codRespuesta === 3 && status.codError == null && result.data === null;
398
+ if ((!emptySummary && status.codRespuesta !== 0) || (Array.isArray(rawMeta.errors) && rawMeta.errors.length))
399
+ throw this.#failure('SII_SERVICE_ERROR', method, 'PROVIDER_REJECTED', response, { ...(typeof status.codRespuesta === 'number' ? { siiResponseCode: status.codRespuesta } : {}) });
400
+ const rows = emptySummary ? [] : result.data;
401
+ if (!Array.isArray(rows) || !rows.every(isRecord))
402
+ throw this.#failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
403
+ const { conversationId: _secret, ...metaData } = rawMeta;
404
+ return { ...result, data: rows, metaData };
405
+ }
406
+ async #json(response, endpoint) {
407
+ if (!response.headers.get('content-type')?.toLowerCase().includes('json')) {
408
+ await response.body?.cancel();
409
+ throw this.#failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', endpoint, 'SESSION_REQUIRED', response);
410
+ }
411
+ try {
412
+ return await response.json();
413
+ }
414
+ catch {
415
+ throw this.#failure('SII_PROTOCOL_CHANGED', endpoint, 'INVALID_RESPONSE', response);
416
+ }
417
+ }
418
+ async #readBounded(response, endpoint) {
419
+ const reader = response.body?.getReader();
420
+ if (!reader)
421
+ throw this.#failure('SII_XML_UNAVAILABLE', endpoint, 'EMPTY_RESPONSE', response, { responseType: 'EMPTY' });
422
+ let size = 0;
423
+ const chunks = [];
424
+ try {
425
+ for (;;) {
426
+ const { done, value } = await reader.read();
427
+ if (done)
428
+ break;
429
+ size += value.byteLength;
430
+ if (size > invoice_xml_1.MAX_DTE_XML_BYTES) {
431
+ await reader.cancel();
432
+ throw this.#failure('SII_XML_INVALID', endpoint, 'RESPONSE_TOO_LARGE', response);
433
+ }
434
+ chunks.push(value);
435
+ }
436
+ return Buffer.concat(chunks, size);
437
+ }
438
+ catch (error) {
439
+ throw error instanceof sii_error_1.SiiError ? error : this.#failure('SII_TRANSPORT_ERROR', endpoint, 'TRANSPORT_ERROR', response);
440
+ }
441
+ finally {
442
+ reader.releaseLock();
443
+ }
444
+ }
445
+ #request(url, options = {}, canRetry = false, allowRedirect = false) {
446
+ const request = this.#sendRequest(url, options, canRetry, allowRedirect);
447
+ this.#requests.add(request);
448
+ void request.then(() => this.#requests.delete(request), () => this.#requests.delete(request));
449
+ return request;
450
+ }
451
+ async #sendRequest(url, options, canRetry, allowRedirect) {
452
+ const endpoint = endpointFor(url);
453
+ for (let attempt = 0;; attempt++) {
454
+ if (this.#closed)
455
+ throw new sii_error_1.SiiError('CLIENT_CLOSED');
456
+ const headers = new Headers(options.headers);
457
+ const cookie = await this.#jar.getCookieString(url);
458
+ if (this.#closed)
459
+ throw new sii_error_1.SiiError('CLIENT_CLOSED');
460
+ if (cookie)
461
+ headers.set('Cookie', cookie);
462
+ let response;
463
+ try {
464
+ response = await this.#fetch(url, { ...options, headers, redirect: 'manual', signal: AbortSignal.timeout(this.#timeoutMs) });
465
+ }
466
+ catch (error) {
467
+ if (!canRetry || attempt >= this.#retries)
468
+ throw this.#failure('SII_TRANSPORT_ERROR', endpoint, error instanceof Error && error.name === 'TimeoutError' ? 'TIMEOUT' : 'TRANSPORT_ERROR', undefined, { attempts: attempt + 1 });
469
+ await (0, promises_1.setTimeout)(250 * (attempt + 1));
470
+ continue;
471
+ }
472
+ for (const setCookie of response.headers.getSetCookie()) {
473
+ await this.#jar.setCookie(setCookie, url, { ignoreError: true });
474
+ }
475
+ if (this.#closed) {
476
+ await response.body?.cancel();
477
+ throw new sii_error_1.SiiError('CLIENT_CLOSED');
478
+ }
479
+ if (canRetry && RETRYABLE.has(response.status) && attempt < this.#retries) {
480
+ const retryAfter = response.headers.get('retry-after');
481
+ const seconds = retryAfter === null ? NaN : Number(retryAfter);
482
+ const waitMs = Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : Date.parse(retryAfter ?? '') - Date.now();
483
+ await response.body?.cancel();
484
+ if (Number.isFinite(waitMs) && waitMs > 5000)
485
+ throw this.#failure('SII_RETRY_LATER', endpoint, 'RETRY_LATER', response, { attempts: attempt + 1 });
486
+ await (0, promises_1.setTimeout)(Number.isFinite(waitMs) ? Math.max(0, waitMs) : 250 * (attempt + 1));
487
+ continue;
488
+ }
489
+ if (!response.ok && !(allowRedirect && response.status >= 300 && response.status < 400)) {
490
+ await response.body?.cancel();
491
+ const redirect = response.status >= 300 && response.status < 400;
492
+ throw this.#failure(redirect ? 'SESSION_OR_INTERACTIVE_AUTH_REQUIRED' : 'SII_HTTP_ERROR', endpoint, redirect ? 'SESSION_REQUIRED' : 'HTTP_ERROR', response, { attempts: attempt + 1 });
493
+ }
494
+ return response;
495
+ }
496
+ }
497
+ }
498
+ exports.SiiClient = SiiClient;
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@devly-cl/sii-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.4",
4
+ "description": "Cliente HTTP del SII para acceso personal, resúmenes RCV y facturas emitidas y recibidas, independiente de framework.",
5
+ "license": "UNLICENSED",
6
+ "type": "commonjs",
7
+ "engines": {
8
+ "node": ">=22.13.0"
9
+ },
10
+ "main": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "require": "./dist/index.js",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public",
25
+ "registry": "https://registry.npmjs.org"
26
+ },
27
+ "scripts": {
28
+ "build": "tsc -p tsconfig.json",
29
+ "typecheck": "tsc --noEmit -p tsconfig.json",
30
+ "test": "npm run build && node test/check.mjs && node test/invoices.mjs && node test/xml.mjs && node test/logout.mjs",
31
+ "check:example": "tsc --strict --noEmit --target ES2022 --module Node16 --moduleResolution Node16 --types node examples/consulta-rcv.ts",
32
+ "check": "npm run typecheck && npm test && npm run check:example",
33
+ "test:live": "npm run build && node scripts/live-check.mjs",
34
+ "prepack": "npm run check"
35
+ },
36
+ "dependencies": {
37
+ "parse5": "7.3.0",
38
+ "saxes": "^6.0.0",
39
+ "tough-cookie": "6.0.2"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "22.20.2",
43
+ "typescript": "5.9.3"
44
+ }
45
+ }