@devly-cl/sii-client 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +36 -4
  2. package/dist/application/invoice-queries.d.ts +17 -0
  3. package/dist/application/invoice-queries.js +51 -0
  4. package/dist/application/issuance.d.ts +40 -0
  5. package/dist/application/issuance.js +79 -0
  6. package/dist/contracts.d.ts +66 -0
  7. package/dist/contracts.js +2 -0
  8. package/dist/domain/document.d.ts +47 -0
  9. package/dist/domain/document.js +38 -0
  10. package/dist/domain/invoice-xml.d.ts +0 -10
  11. package/dist/domain/invoice-xml.js +0 -170
  12. package/dist/domain/issued-invoice.d.ts +1 -2
  13. package/dist/domain/issued-invoice.js +4 -43
  14. package/dist/domain/received-invoice.d.ts +1 -3
  15. package/dist/domain/received-invoice.js +0 -10
  16. package/dist/index.d.ts +5 -3
  17. package/dist/index.js +4 -3
  18. package/dist/infrastructure/dte-xml.d.ts +11 -0
  19. package/dist/infrastructure/dte-xml.js +173 -0
  20. package/dist/infrastructure/facturador-gateway.d.ts +28 -0
  21. package/dist/infrastructure/facturador-gateway.js +411 -0
  22. package/dist/infrastructure/facturador.d.ts +10 -3
  23. package/dist/infrastructure/facturador.js +16 -2
  24. package/dist/infrastructure/invoice-pdf.d.ts +9 -0
  25. package/dist/infrastructure/invoice-pdf.js +171 -0
  26. package/dist/infrastructure/rcv-gateway.d.ts +17 -0
  27. package/dist/infrastructure/rcv-gateway.js +105 -0
  28. package/dist/infrastructure/rcv-normalization.d.ts +6 -0
  29. package/dist/infrastructure/rcv-normalization.js +55 -0
  30. package/dist/infrastructure/sii-client.d.ts +22 -121
  31. package/dist/infrastructure/sii-client.js +45 -774
  32. package/dist/infrastructure/sii-http-session.d.ts +25 -0
  33. package/dist/infrastructure/sii-http-session.js +344 -0
  34. package/dist/sii-error.d.ts +27 -0
  35. package/dist/sii-error.js +86 -0
  36. package/package.json +4 -4
@@ -0,0 +1,25 @@
1
+ import { parseRut } from '../domain/rut';
2
+ import { SiiError, type SiiDiagnostics } from '../sii-error';
3
+ import type { SiiClientOptions, SiiCredentials, SiiSession, InvoicePdfResult } from '../contracts';
4
+ export declare const RCV = "https://www4.sii.cl/consdcvinternetui/";
5
+ export declare const FACTURADOR = "https://www1.sii.cl/cgi-bin/Portal001/";
6
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
7
+ /** Owns one personal HTTP session; body consumption belongs to the tracked request. */
8
+ export declare class SiiHttpSession {
9
+ #private;
10
+ readonly company: ReturnType<typeof parseRut>;
11
+ constructor({ empresaRut, timeoutMs, retries, fetchImpl }: SiiClientOptions);
12
+ login({ rut, clave }: SiiCredentials, authorize: (identity: ReturnType<typeof parseRut>) => Promise<boolean>): Promise<SiiSession>;
13
+ assertReady(): ReturnType<typeof parseRut>;
14
+ cookies(url: string): Promise<import("tough-cookie").Cookie[]>;
15
+ failure(code: string, endpoint: SiiDiagnostics['endpoint'], reason: SiiDiagnostics['reason'], response?: Response, extra?: Partial<SiiDiagnostics>): SiiError;
16
+ abortFailure(signal: AbortSignal, endpoint: SiiDiagnostics['endpoint']): SiiError;
17
+ /** Track the whole PDF operation, including an unconsumed stream, until its resources close. */
18
+ pdfOperation(endpoint: SiiDiagnostics['endpoint'], operation: (signal: AbortSignal, trackStream: (stream: InvoicePdfResult['stream']) => void) => Promise<InvoicePdfResult>, signal?: AbortSignal): Promise<InvoicePdfResult>;
19
+ request<T>(url: string, consume: (response: Response) => Promise<T>, options?: RequestInit, canRetry?: boolean, allowRedirect?: boolean): Promise<T>;
20
+ json(response: Response, endpoint: SiiDiagnostics['endpoint']): Promise<unknown>;
21
+ readBounded(response: Response, endpoint: SiiDiagnostics['endpoint'], limit?: number, oversizedCode?: string, signal?: AbortSignal): Promise<Uint8Array>;
22
+ dispose(pendingWrite?: Promise<unknown>): Promise<void>;
23
+ }
24
+ export declare function endpointFor(url: string): SiiDiagnostics['endpoint'];
25
+ export declare function responseFormat(response: Response, bytes?: Uint8Array): Pick<SiiDiagnostics, 'contentType' | 'responseType'>;
@@ -0,0 +1,344 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SiiHttpSession = exports.FACTURADOR = exports.RCV = void 0;
4
+ exports.isRecord = isRecord;
5
+ exports.endpointFor = endpointFor;
6
+ exports.responseFormat = responseFormat;
7
+ const node_crypto_1 = require("node:crypto");
8
+ const promises_1 = require("node:timers/promises");
9
+ const promises_2 = require("node:stream/promises");
10
+ const tough_cookie_1 = require("tough-cookie");
11
+ const rut_1 = require("../domain/rut");
12
+ const invoice_xml_1 = require("../domain/invoice-xml");
13
+ const sii_error_1 = require("../sii-error");
14
+ exports.RCV = 'https://www4.sii.cl/consdcvinternetui/';
15
+ exports.FACTURADOR = 'https://www1.sii.cl/cgi-bin/Portal001/';
16
+ const AUTH = 'https://zeusr.sii.cl/cgi_AUT2000/CAutInicio.cgi';
17
+ const LOGOUT = 'https://zeusr.sii.cl/cgi_AUT2000/autTermino.cgi';
18
+ const SESSION = 'https://www4.sii.cl/common-1.0/services/aaSessionService/load';
19
+ const RETRYABLE = new Set([429, 502, 503, 504]);
20
+ const MAX_JSON_BYTES = 16 * 1024 * 1024;
21
+ function isRecord(value) {
22
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
23
+ }
24
+ /** Owns one personal HTTP session; body consumption belongs to the tracked request. */
25
+ class SiiHttpSession {
26
+ company;
27
+ #jar = new tough_cookie_1.CookieJar();
28
+ #fetch;
29
+ #timeoutMs;
30
+ #retries;
31
+ #identity;
32
+ #ready = false;
33
+ #used = false;
34
+ #closed = false;
35
+ #requests = new Set();
36
+ #pdfDownloads = new Map();
37
+ #disposal;
38
+ #traceId = (0, node_crypto_1.randomUUID)();
39
+ constructor({ empresaRut, timeoutMs = 15000, retries = 1, fetchImpl = globalThis.fetch }) {
40
+ this.company = (0, rut_1.parseRut)(empresaRut);
41
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 30000)
42
+ throw new TypeError('timeoutMs inválido');
43
+ if (!Number.isInteger(retries) || retries < 0 || retries > 2)
44
+ throw new TypeError('retries inválido');
45
+ if (typeof fetchImpl !== 'function')
46
+ throw new TypeError('fetchImpl inválido');
47
+ this.#fetch = fetchImpl;
48
+ this.#timeoutMs = timeoutMs;
49
+ this.#retries = retries;
50
+ }
51
+ async login({ rut, clave }, authorize) {
52
+ if (this.#used || this.#closed)
53
+ throw new sii_error_1.SiiError('NEW_INSTANCE_REQUIRED');
54
+ const identity = (0, rut_1.parseRut)(rut);
55
+ if (typeof clave !== 'string' || !clave || clave.length > 256)
56
+ throw new TypeError('Clave inválida');
57
+ this.#used = true;
58
+ try {
59
+ const body = new URLSearchParams({ rut: identity.rut, dv: identity.dv, referencia: exports.RCV, '411': '', rutcntr: identity.formatted, clave });
60
+ await this.request(AUTH, async (response) => {
61
+ await response.body?.cancel();
62
+ const cookies = await this.cookies(exports.RCV);
63
+ if (!cookies.some(c => c.key === 'TOKEN' && c.value))
64
+ throw this.failure('LOGIN_NOT_CONFIRMED', 'CAutInicio.cgi', 'LOGIN_NOT_CONFIRMED', response);
65
+ }, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Origin: 'https://zeusr.sii.cl', Referer: `https://zeusr.sii.cl/AUT2000/InicioAutenticacion/IngresoRutClave.html?${exports.RCV}` }, body: body.toString() });
66
+ await this.request(SESSION, async (response) => {
67
+ const sessionEnvelope = await this.json(response, 'aaSessionService/load');
68
+ const session = isRecord(sessionEnvelope) && isRecord(sessionEnvelope.data) ? sessionEnvelope.data : undefined;
69
+ if (session?.hayRepresentacion !== false)
70
+ throw this.failure('PERSONAL_SESSION_REQUIRED', 'aaSessionService/load', 'PERSONAL_SESSION_REQUIRED', response);
71
+ if (`${session?.rut}-${session?.dv}`.toUpperCase() !== identity.formatted)
72
+ throw this.failure('SESSION_IDENTITY_MISMATCH', 'aaSessionService/load', 'SESSION_IDENTITY_MISMATCH', response);
73
+ }, {}, true);
74
+ this.#identity = identity;
75
+ if (!await authorize(identity))
76
+ throw this.failure('COMPANY_NOT_AUTHORIZED', 'getDcvEmpresasAutorizadas', 'COMPANY_NOT_AUTHORIZED');
77
+ if (this.#closed)
78
+ throw new sii_error_1.SiiError('CLIENT_CLOSED');
79
+ this.#ready = true;
80
+ return { usuarioRut: identity.formatted, empresaRut: this.company.formatted, representacion: false };
81
+ }
82
+ catch (error) {
83
+ await this.dispose();
84
+ throw error;
85
+ }
86
+ }
87
+ assertReady() {
88
+ if (!this.#ready || this.#closed || !this.#identity)
89
+ throw new sii_error_1.SiiError('SESSION_REQUIRED');
90
+ return this.#identity;
91
+ }
92
+ cookies(url) { return this.#jar.getCookies(url); }
93
+ failure(code, endpoint, reason, response, extra = {}) {
94
+ return new sii_error_1.SiiError(code, response?.status, { traceId: this.#traceId, stage: ENDPOINT_STAGES[endpoint], endpoint, reason,
95
+ ...(response ? { httpStatus: response.status, ...responseFormat(response) } : {}), ...extra });
96
+ }
97
+ abortFailure(signal, endpoint) {
98
+ return signal.reason instanceof sii_error_1.SiiError ? signal.reason : this.failure('SII_OPERATION_ABORTED', endpoint, 'OPERATION_ABORTED');
99
+ }
100
+ /** Track the whole PDF operation, including an unconsumed stream, until its resources close. */
101
+ async pdfOperation(endpoint, operation, signal) {
102
+ this.assertReady();
103
+ if (signal !== undefined && !(signal instanceof AbortSignal))
104
+ throw new TypeError('signal inválida');
105
+ const controller = new AbortController();
106
+ const onAbort = () => controller.abort(this.failure('SII_OPERATION_ABORTED', endpoint, 'OPERATION_ABORTED'));
107
+ const timer = setTimeout(() => controller.abort(this.failure('SII_TRANSPORT_ERROR', endpoint, 'TIMEOUT')), this.#timeoutMs);
108
+ let downloadStream;
109
+ let streamCompletion;
110
+ let release;
111
+ const closing = new Promise(resolve => {
112
+ release = () => {
113
+ clearTimeout(timer);
114
+ signal?.removeEventListener('abort', onAbort);
115
+ this.#pdfDownloads.delete(controller);
116
+ downloadStream = undefined;
117
+ resolve();
118
+ };
119
+ });
120
+ this.#pdfDownloads.set(controller, closing);
121
+ signal?.addEventListener('abort', onAbort, { once: true });
122
+ if (signal?.aborted)
123
+ onAbort();
124
+ try {
125
+ if (controller.signal.aborted)
126
+ throw this.abortFailure(controller.signal, endpoint);
127
+ const result = await operation(controller.signal, stream => {
128
+ downloadStream = stream;
129
+ streamCompletion = (0, promises_2.finished)(stream, { cleanup: true }).then(release, release);
130
+ });
131
+ if (controller.signal.aborted) {
132
+ result.stream.destroy(this.abortFailure(controller.signal, endpoint));
133
+ throw this.abortFailure(controller.signal, endpoint);
134
+ }
135
+ return result;
136
+ }
137
+ catch (error) {
138
+ if (downloadStream) {
139
+ downloadStream.destroy(error instanceof sii_error_1.SiiError ? error : this.failure('SII_TRANSPORT_ERROR', endpoint, 'TRANSPORT_ERROR'));
140
+ await streamCompletion;
141
+ }
142
+ else
143
+ release();
144
+ throw controller.signal.aborted ? this.abortFailure(controller.signal, endpoint) : error;
145
+ }
146
+ }
147
+ request(url, consume, options = {}, canRetry = false, allowRedirect = false) {
148
+ const request = this.#sendRequest(url, options, canRetry, allowRedirect).then(async (response) => {
149
+ try {
150
+ const result = await consume(response);
151
+ if (this.#closed)
152
+ throw new sii_error_1.SiiError('CLIENT_CLOSED');
153
+ if (options.signal?.aborted)
154
+ throw this.abortFailure(options.signal, endpointFor(url));
155
+ return result;
156
+ }
157
+ catch (error) {
158
+ await response.body?.cancel().catch(() => { });
159
+ throw error;
160
+ }
161
+ }).catch(error => {
162
+ if (this.#closed)
163
+ throw new sii_error_1.SiiError('CLIENT_CLOSED');
164
+ if (options.signal?.aborted)
165
+ throw this.abortFailure(options.signal, endpointFor(url));
166
+ throw error;
167
+ });
168
+ this.#requests.add(request);
169
+ void request.then(() => this.#requests.delete(request), () => this.#requests.delete(request));
170
+ return request;
171
+ }
172
+ async json(response, endpoint) {
173
+ if (!response.headers.get('content-type')?.toLowerCase().includes('json')) {
174
+ await response.body?.cancel();
175
+ throw this.failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', endpoint, 'SESSION_REQUIRED', response);
176
+ }
177
+ const bytes = response.body ? await this.readBounded(response, endpoint, MAX_JSON_BYTES, 'SII_PROTOCOL_CHANGED') : new Uint8Array();
178
+ try {
179
+ return JSON.parse(new TextDecoder().decode(bytes));
180
+ }
181
+ catch {
182
+ throw this.failure('SII_PROTOCOL_CHANGED', endpoint, 'INVALID_RESPONSE', response);
183
+ }
184
+ }
185
+ async readBounded(response, endpoint, limit = invoice_xml_1.MAX_DTE_XML_BYTES, oversizedCode = 'SII_XML_INVALID', signal) {
186
+ const reader = response.body?.getReader();
187
+ if (!reader)
188
+ throw this.failure('SII_XML_UNAVAILABLE', endpoint, 'EMPTY_RESPONSE', response, { responseType: 'EMPTY' });
189
+ let size = 0;
190
+ const chunks = [];
191
+ let cancellation;
192
+ const cancelSource = () => cancellation ??= reader.cancel().catch(() => { });
193
+ const onAbort = () => { void cancelSource(); };
194
+ signal?.addEventListener('abort', onAbort, { once: true });
195
+ try {
196
+ for (;;) {
197
+ if (signal?.aborted)
198
+ throw this.abortFailure(signal, endpoint);
199
+ const { done, value } = await reader.read();
200
+ if (signal?.aborted)
201
+ throw this.abortFailure(signal, endpoint);
202
+ if (done)
203
+ break;
204
+ size += value.byteLength;
205
+ if (size > limit) {
206
+ await cancelSource();
207
+ throw this.failure(oversizedCode, endpoint, 'RESPONSE_TOO_LARGE', response);
208
+ }
209
+ chunks.push(value);
210
+ }
211
+ return Buffer.concat(chunks, size);
212
+ }
213
+ catch (error) {
214
+ throw signal?.aborted ? this.abortFailure(signal, endpoint) : error instanceof sii_error_1.SiiError ? error : this.failure('SII_TRANSPORT_ERROR', endpoint, 'TRANSPORT_ERROR', response);
215
+ }
216
+ finally {
217
+ signal?.removeEventListener('abort', onAbort);
218
+ await cancellation;
219
+ reader.releaseLock();
220
+ }
221
+ }
222
+ dispose(pendingWrite) {
223
+ if (this.#disposal)
224
+ return this.#disposal;
225
+ this.#closed = true;
226
+ this.#ready = false;
227
+ this.#identity = undefined;
228
+ const downloads = [...this.#pdfDownloads.values()];
229
+ for (const controller of this.#pdfDownloads.keys())
230
+ controller.abort(new sii_error_1.SiiError('CLIENT_CLOSED'));
231
+ this.#disposal = (async () => {
232
+ try {
233
+ // Cleanup is never included in the requests or write it waits for.
234
+ await Promise.allSettled([...this.#requests, ...downloads, ...(pendingWrite ? [pendingWrite] : [])]);
235
+ const cookies = await this.cookies(LOGOUT);
236
+ if (!cookies.some(c => c.value && ['TOKEN', 'NETSCAPE_LIVEWIRE.mac'].includes(c.key)))
237
+ return;
238
+ const headers = new Headers({ Referer: exports.RCV, Cookie: cookies.map(c => c.cookieString()).join('; ') });
239
+ const response = await this.#fetch(LOGOUT, { method: 'GET', headers, redirect: 'manual', signal: AbortSignal.timeout(this.#timeoutMs) });
240
+ if (!response.ok) {
241
+ await response.body?.cancel();
242
+ if (!(response.status >= 300 && response.status < 400 && response.headers.get('location') === 'https://homer.sii.cl/'))
243
+ throw new sii_error_1.SiiError('SII_LOGOUT_FAILED');
244
+ }
245
+ else {
246
+ const page = Buffer.from(await this.readBounded(response, 'autTermino.cgi')).toString('latin1');
247
+ const codes = page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/g);
248
+ if (codes?.some(code => code !== '01.01.205.529.269.28'))
249
+ throw new sii_error_1.SiiError('SII_LOGOUT_FAILED');
250
+ }
251
+ }
252
+ catch {
253
+ process.emitWarning('SII_LOGOUT_FAILED', { code: 'SII_LOGOUT_FAILED' });
254
+ }
255
+ finally {
256
+ await this.#jar.removeAllCookies();
257
+ }
258
+ })();
259
+ return this.#disposal;
260
+ }
261
+ async #sendRequest(url, options, canRetry, allowRedirect) {
262
+ const endpoint = endpointFor(url);
263
+ for (let attempt = 0;; attempt++) {
264
+ if (this.#closed)
265
+ throw new sii_error_1.SiiError('CLIENT_CLOSED');
266
+ if (options.signal?.aborted)
267
+ throw this.abortFailure(options.signal, endpoint);
268
+ const headers = new Headers(options.headers);
269
+ const cookie = await this.#jar.getCookieString(url);
270
+ if (this.#closed)
271
+ throw new sii_error_1.SiiError('CLIENT_CLOSED');
272
+ if (cookie)
273
+ headers.set('Cookie', cookie);
274
+ let response;
275
+ try {
276
+ const timeout = AbortSignal.timeout(this.#timeoutMs);
277
+ response = await this.#fetch(url, { ...options, headers, redirect: 'manual', signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout });
278
+ }
279
+ catch (error) {
280
+ if (options.signal?.aborted)
281
+ throw this.abortFailure(options.signal, endpoint);
282
+ if (!canRetry || attempt >= this.#retries)
283
+ throw this.failure('SII_TRANSPORT_ERROR', endpoint, error instanceof Error && error.name === 'TimeoutError' ? 'TIMEOUT' : 'TRANSPORT_ERROR', undefined, { attempts: attempt + 1 });
284
+ await (0, promises_1.setTimeout)(250 * (attempt + 1), undefined, { signal: options.signal ?? undefined });
285
+ continue;
286
+ }
287
+ for (const setCookie of response.headers.getSetCookie())
288
+ await this.#jar.setCookie(setCookie, url, { ignoreError: true });
289
+ if (this.#closed) {
290
+ await response.body?.cancel();
291
+ throw new sii_error_1.SiiError('CLIENT_CLOSED');
292
+ }
293
+ if (options.signal?.aborted) {
294
+ await response.body?.cancel();
295
+ throw this.abortFailure(options.signal, endpoint);
296
+ }
297
+ if (canRetry && RETRYABLE.has(response.status) && attempt < this.#retries) {
298
+ const retryAfter = response.headers.get('retry-after');
299
+ const seconds = retryAfter === null ? NaN : Number(retryAfter);
300
+ const waitMs = Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : Date.parse(retryAfter ?? '') - Date.now();
301
+ await response.body?.cancel();
302
+ if (Number.isFinite(waitMs) && waitMs > 5000)
303
+ throw this.failure('SII_RETRY_LATER', endpoint, 'RETRY_LATER', response, { attempts: attempt + 1 });
304
+ await (0, promises_1.setTimeout)(Number.isFinite(waitMs) ? Math.max(0, waitMs) : 250 * (attempt + 1), undefined, { signal: options.signal ?? undefined });
305
+ continue;
306
+ }
307
+ if (!response.ok && !(allowRedirect && response.status >= 300 && response.status < 400)) {
308
+ await response.body?.cancel();
309
+ const redirect = response.status >= 300 && response.status < 400;
310
+ throw this.failure(redirect ? 'SESSION_OR_INTERACTIVE_AUTH_REQUIRED' : 'SII_HTTP_ERROR', endpoint, redirect ? 'SESSION_REQUIRED' : 'HTTP_ERROR', response, { attempts: attempt + 1 });
311
+ }
312
+ return response;
313
+ }
314
+ }
315
+ }
316
+ exports.SiiHttpSession = SiiHttpSession;
317
+ const ENDPOINT_STAGES = {
318
+ 'CAutInicio.cgi': 'AUTHENTICATION', 'aaSessionService/load': 'SESSION_CHECK', getDcvEmpresasAutorizadas: 'COMPANY_AUTHORIZATION',
319
+ getDatosInicio: 'RCV_INITIALIZATION', getResumen: 'RCV_SUMMARY', getDetalleCompra: 'RCV_DETAIL', getDetalleVenta: 'RCV_DETAIL',
320
+ 'mipeSelEmpresa.cgi': 'XML_COMPANY_SELECTION', 'mipeLaunchPage.cgi': 'XML_COMPANY_SELECTION', 'mipeDownLoad.cgi': 'XML_DOWNLOAD', 'autTermino.cgi': 'LOGOUT',
321
+ 'mipeGenFacEx.cgi': 'DOCUMENT_PREPARATION', 'mipeDisplayPreView.cgi': 'DOCUMENT_REVIEW', 'mipeGenXMLFirma.cgi': 'DOCUMENT_SIGNING', 'getCertDigital.cgi': 'DOCUMENT_SIGNING', 'postFirmaDigital.cgi': 'DOCUMENT_SIGNING', 'mipeSendXML.cgi': 'DOCUMENT_SEND', 'mipeAdminDocsEmi.cgi': 'DOCUMENT_RECOVERY', 'mipeGesDocEmi.cgi': 'DOCUMENT_RECOVERY', 'mipeDisplayPDF.cgi': 'PDF_DOWNLOAD', 'mipeAdminDocsRcp.cgi': 'PDF_HISTORY', 'mipeShowPdf.cgi': 'PDF_DOWNLOAD',
322
+ };
323
+ function endpointFor(url) {
324
+ const path = new URL(url).pathname;
325
+ const endpoint = path.endsWith('/aaSessionService/load') ? 'aaSessionService/load' : path.slice(path.lastIndexOf('/') + 1);
326
+ if (!Object.hasOwn(ENDPOINT_STAGES, endpoint))
327
+ throw new TypeError('Endpoint SII desconocido');
328
+ return endpoint;
329
+ }
330
+ function responseFormat(response, bytes) {
331
+ const contentType = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
332
+ const prefix = bytes ? Buffer.from(bytes.subarray(0, 512)).toString('latin1').trimStart() : '';
333
+ const responseType = bytes?.length === 0 ? 'EMPTY'
334
+ : prefix.startsWith('%PDF-') ? 'PDF'
335
+ : bytes && bytes[0] === 0x50 && bytes[1] === 0x4b && [0x03, 0x05, 0x07].includes(bytes[2] ?? -1) ? 'ZIP'
336
+ : /^(?:<!doctype\s+html|<html|<head|<body|<script|<div)\b/i.test(prefix) ? 'HTML'
337
+ : contentType === 'text/html' ? 'HTML'
338
+ : contentType === 'application/pdf' ? 'PDF'
339
+ : contentType === 'application/zip' ? 'ZIP'
340
+ : contentType?.includes('json') ? 'JSON'
341
+ : /^(?:application|text)\/xml$/.test(contentType ?? '') || /^<(?:\?xml|DTE|EnvioDTE|SetDTE)\b/i.test(prefix) ? 'XML' : 'UNKNOWN';
342
+ // The sanitizer copies only known MIME values.
343
+ return { responseType, ...(contentType ? { contentType: contentType } : {}) };
344
+ }
@@ -0,0 +1,27 @@
1
+ declare const STAGES: readonly ["AUTHENTICATION", "SESSION_CHECK", "COMPANY_AUTHORIZATION", "RCV_INITIALIZATION", "RCV_SUMMARY", "RCV_DETAIL", "XML_COMPANY_SELECTION", "XML_DOWNLOAD", "XML_PARSE", "LOGOUT", "DOCUMENT_PREPARATION", "DOCUMENT_REVIEW", "DOCUMENT_SIGNING", "DOCUMENT_SEND", "DOCUMENT_RECOVERY", "PDF_HISTORY", "PDF_DOWNLOAD"];
2
+ declare const ENDPOINTS: readonly ["CAutInicio.cgi", "aaSessionService/load", "getDcvEmpresasAutorizadas", "getDatosInicio", "getResumen", "getDetalleCompra", "getDetalleVenta", "mipeSelEmpresa.cgi", "mipeLaunchPage.cgi", "mipeDownLoad.cgi", "autTermino.cgi", "mipeGenFacEx.cgi", "mipeDisplayPreView.cgi", "mipeGenXMLFirma.cgi", "getCertDigital.cgi", "postFirmaDigital.cgi", "mipeSendXML.cgi", "mipeAdminDocsEmi.cgi", "mipeGesDocEmi.cgi", "mipeDisplayPDF.cgi", "mipeAdminDocsRcp.cgi", "mipeShowPdf.cgi"];
3
+ declare const REASONS: readonly ["DOCUMENT_LIMIT_EXCEEDED", "DOCUMENT_NOT_FOUND", "EMPTY_RESPONSE", "HTML_RESPONSE", "PROVIDER_ERROR_PAGE", "UNEXPECTED_PDF", "UNEXPECTED_ARCHIVE", "UNEXPECTED_FORMAT", "INVALID_XML", "XML_IDENTITY_MISMATCH", "RESPONSE_TOO_LARGE", "HTTP_ERROR", "TIMEOUT", "TRANSPORT_ERROR", "RETRY_LATER", "CAPTCHA_REQUIRED", "SESSION_REQUIRED", "LOGIN_NOT_CONFIRMED", "PERSONAL_SESSION_REQUIRED", "SESSION_IDENTITY_MISMATCH", "COMPANY_NOT_AUTHORIZED", "COMPANY_SELECTION_REQUIRED", "PROVIDER_REJECTED", "INVALID_RESPONSE", "DOCUMENT_CONTENT_MISMATCH", "CERTIFICATE_UNAVAILABLE", "CERTIFICATE_PASSWORD_INVALID", "CERTIFICATE_EXPIRED", "CERTIFICATE_REVOKED", "SIGNATURE_INVALID", "ISSUANCE_OUTCOME_UNKNOWN", "INVALID_PDF", "PDF_IDENTITY_MISMATCH", "OPERATION_ABORTED"];
4
+ declare const RESPONSE_TYPES: readonly ["XML", "HTML", "PDF", "ZIP", "JSON", "EMPTY", "UNKNOWN"];
5
+ declare const CONTENT_TYPES: readonly ["application/xml", "text/xml", "application/octet-stream", "text/html", "application/pdf", "application/zip", "application/json", "text/plain"];
6
+ export interface SiiDiagnostics {
7
+ readonly traceId: string;
8
+ readonly stage: typeof STAGES[number];
9
+ readonly endpoint: typeof ENDPOINTS[number];
10
+ readonly reason: typeof REASONS[number];
11
+ readonly responseType?: typeof RESPONSE_TYPES[number];
12
+ readonly contentType?: typeof CONTENT_TYPES[number];
13
+ readonly httpStatus?: number;
14
+ readonly siiMessageCode?: string;
15
+ readonly siiResponseCode?: number;
16
+ readonly attempts?: number;
17
+ }
18
+ /** Only bounded, known protocol values cross this boundary. Never provider text or URLs. */
19
+ export declare function sanitizeSiiDiagnostics(value: unknown): SiiDiagnostics | undefined;
20
+ export declare class SiiError extends Error {
21
+ readonly code: string;
22
+ readonly httpStatus?: number | undefined;
23
+ readonly diagnostics?: SiiDiagnostics;
24
+ readonly description?: string;
25
+ constructor(code: string, httpStatus?: number | undefined, diagnostics?: unknown);
26
+ }
27
+ export {};
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SiiError = void 0;
4
+ exports.sanitizeSiiDiagnostics = sanitizeSiiDiagnostics;
5
+ const STAGES = ['AUTHENTICATION', 'SESSION_CHECK', 'COMPANY_AUTHORIZATION', 'RCV_INITIALIZATION', 'RCV_SUMMARY', 'RCV_DETAIL', 'XML_COMPANY_SELECTION', 'XML_DOWNLOAD', 'XML_PARSE', 'LOGOUT', 'DOCUMENT_PREPARATION', 'DOCUMENT_REVIEW', 'DOCUMENT_SIGNING', 'DOCUMENT_SEND', 'DOCUMENT_RECOVERY', 'PDF_HISTORY', 'PDF_DOWNLOAD'];
6
+ const ENDPOINTS = ['CAutInicio.cgi', 'aaSessionService/load', 'getDcvEmpresasAutorizadas', 'getDatosInicio', 'getResumen', 'getDetalleCompra', 'getDetalleVenta', 'mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi', 'mipeDownLoad.cgi', 'autTermino.cgi', 'mipeGenFacEx.cgi', 'mipeDisplayPreView.cgi', 'mipeGenXMLFirma.cgi', 'getCertDigital.cgi', 'postFirmaDigital.cgi', 'mipeSendXML.cgi', 'mipeAdminDocsEmi.cgi', 'mipeGesDocEmi.cgi', 'mipeDisplayPDF.cgi', 'mipeAdminDocsRcp.cgi', 'mipeShowPdf.cgi'];
7
+ const REASONS = ['DOCUMENT_LIMIT_EXCEEDED', 'DOCUMENT_NOT_FOUND', 'EMPTY_RESPONSE', 'HTML_RESPONSE', 'PROVIDER_ERROR_PAGE', 'UNEXPECTED_PDF', 'UNEXPECTED_ARCHIVE', 'UNEXPECTED_FORMAT', 'INVALID_XML', 'XML_IDENTITY_MISMATCH', 'RESPONSE_TOO_LARGE', 'HTTP_ERROR', 'TIMEOUT', 'TRANSPORT_ERROR', 'RETRY_LATER', 'CAPTCHA_REQUIRED', 'SESSION_REQUIRED', 'LOGIN_NOT_CONFIRMED', 'PERSONAL_SESSION_REQUIRED', 'SESSION_IDENTITY_MISMATCH', 'COMPANY_NOT_AUTHORIZED', 'COMPANY_SELECTION_REQUIRED', 'PROVIDER_REJECTED', 'INVALID_RESPONSE', 'DOCUMENT_CONTENT_MISMATCH', 'CERTIFICATE_UNAVAILABLE', 'CERTIFICATE_PASSWORD_INVALID', 'CERTIFICATE_EXPIRED', 'CERTIFICATE_REVOKED', 'SIGNATURE_INVALID', 'ISSUANCE_OUTCOME_UNKNOWN', 'INVALID_PDF', 'PDF_IDENTITY_MISMATCH', 'OPERATION_ABORTED'];
8
+ const RESPONSE_TYPES = ['XML', 'HTML', 'PDF', 'ZIP', 'JSON', 'EMPTY', 'UNKNOWN'];
9
+ const CONTENT_TYPES = ['application/xml', 'text/xml', 'application/octet-stream', 'text/html', 'application/pdf', 'application/zip', 'application/json', 'text/plain'];
10
+ function member(values, value) {
11
+ return typeof value === 'string' && values.some(item => item === value);
12
+ }
13
+ /** Only bounded, known protocol values cross this boundary. Never provider text or URLs. */
14
+ function sanitizeSiiDiagnostics(value) {
15
+ if (typeof value !== 'object' || value === null)
16
+ return undefined;
17
+ const raw = value;
18
+ if (typeof raw.traceId !== 'string' || !/^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/i.test(raw.traceId)
19
+ || !member(STAGES, raw.stage) || !member(ENDPOINTS, raw.endpoint) || !member(REASONS, raw.reason))
20
+ return undefined;
21
+ return Object.freeze({
22
+ traceId: raw.traceId, stage: raw.stage, endpoint: raw.endpoint, reason: raw.reason,
23
+ ...(member(RESPONSE_TYPES, raw.responseType) ? { responseType: raw.responseType } : {}),
24
+ ...(member(CONTENT_TYPES, raw.contentType) ? { contentType: raw.contentType } : {}),
25
+ ...(typeof raw.httpStatus === 'number' && Number.isInteger(raw.httpStatus) && raw.httpStatus >= 100 && raw.httpStatus <= 599 ? { httpStatus: raw.httpStatus } : {}),
26
+ ...(typeof raw.siiMessageCode === 'string' && /^\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}$/.test(raw.siiMessageCode) ? { siiMessageCode: raw.siiMessageCode } : {}),
27
+ ...(typeof raw.siiResponseCode === 'number' && Number.isInteger(raw.siiResponseCode) && Math.abs(raw.siiResponseCode) <= 999999 ? { siiResponseCode: raw.siiResponseCode } : {}),
28
+ ...(typeof raw.attempts === 'number' && Number.isInteger(raw.attempts) && raw.attempts >= 1 && raw.attempts <= 3 ? { attempts: raw.attempts } : {}),
29
+ });
30
+ }
31
+ const STAGE_LABELS = {
32
+ AUTHENTICATION: 'inicio de sesión', SESSION_CHECK: 'validación de sesión', COMPANY_AUTHORIZATION: 'autorización de empresa',
33
+ RCV_INITIALIZATION: 'inicio del RCV', RCV_SUMMARY: 'resumen del RCV', RCV_DETAIL: 'detalle del RCV',
34
+ XML_COMPANY_SELECTION: 'selección de empresa en el facturador', XML_DOWNLOAD: 'descarga del XML', XML_PARSE: 'validación del XML', LOGOUT: 'cierre de sesión',
35
+ DOCUMENT_PREPARATION: 'preparación del documento', DOCUMENT_REVIEW: 'revisión del documento', DOCUMENT_SIGNING: 'firma del documento', DOCUMENT_SEND: 'envío del documento', DOCUMENT_RECOVERY: 'recuperación del documento emitido',
36
+ PDF_HISTORY: 'búsqueda de factura en el historial', PDF_DOWNLOAD: 'descarga del PDF',
37
+ };
38
+ const REASON_LABELS = {
39
+ DOCUMENT_LIMIT_EXCEEDED: 'SII rechazó la consulta porque devuelve demasiados documentos. No confirmó si el XML individual está disponible.',
40
+ DOCUMENT_NOT_FOUND: 'SII indicó que no encontró documentos para esta consulta.',
41
+ EMPTY_RESPONSE: 'SII devolvió una respuesta vacía; no se recibió ningún documento.',
42
+ HTML_RESPONSE: 'SII devolvió una página HTML en lugar del XML. Esto no confirma que la factura carezca de XML.',
43
+ PROVIDER_ERROR_PAGE: 'SII devolvió una página de error en lugar del documento solicitado.',
44
+ UNEXPECTED_PDF: 'SII devolvió un PDF en esta solicitud de XML. Ese archivo no permite reconstruir el detalle desde XML.',
45
+ UNEXPECTED_ARCHIVE: 'SII devolvió un ZIP en esta solicitud de XML; el SDK esperaba un DTE individual.',
46
+ UNEXPECTED_FORMAT: 'SII devolvió un formato diferente al XML solicitado.',
47
+ INVALID_XML: 'El XML recibido no contiene un DTE individual válido y no se guardó.',
48
+ XML_IDENTITY_MISMATCH: 'El XML recibido corresponde a otro documento y no se guardó.',
49
+ INVALID_PDF: 'SII no entregó una respuesta PDF válida para esta solicitud.',
50
+ PDF_IDENTITY_MISMATCH: 'El historial no identifica de forma única la factura solicitada. No se descargó el PDF.',
51
+ OPERATION_ABORTED: 'El consumidor canceló la descarga del PDF.',
52
+ RESPONSE_TOO_LARGE: 'La respuesta de SII supera el límite permitido para este tipo de respuesta y no se procesó.',
53
+ HTTP_ERROR: 'SII respondió con un error HTTP.', TIMEOUT: 'SII no respondió dentro del tiempo permitido.',
54
+ TRANSPORT_ERROR: 'No se pudo completar la comunicación con SII.', RETRY_LATER: 'SII pidió esperar antes de volver a consultar.',
55
+ CAPTCHA_REQUIRED: 'SII requiere resolver un CAPTCHA en su sitio.', SESSION_REQUIRED: 'SII requiere autenticación interactiva o una sesión válida.',
56
+ LOGIN_NOT_CONFIRMED: 'SII no confirmó el inicio de sesión.', PERSONAL_SESSION_REQUIRED: 'SII no confirmó una sesión personal.',
57
+ SESSION_IDENTITY_MISMATCH: 'La sesión de SII no corresponde al usuario solicitado.', COMPANY_NOT_AUTHORIZED: 'SII no autorizó el acceso a la empresa solicitada.',
58
+ COMPANY_SELECTION_REQUIRED: 'SII no confirmó la selección de empresa en el facturador.',
59
+ PROVIDER_REJECTED: 'SII rechazó la solicitud.', INVALID_RESPONSE: 'SII devolvió una respuesta que no cumple el contrato esperado.',
60
+ DOCUMENT_CONTENT_MISMATCH: 'El contenido fiscal recibido difiere del contenido aprobado. No se envió el documento.',
61
+ CERTIFICATE_UNAVAILABLE: 'SII no devolvió un certificado centralizado utilizable para esta identidad.',
62
+ CERTIFICATE_PASSWORD_INVALID: 'SII rechazó la clave del certificado centralizado.', CERTIFICATE_EXPIRED: 'El certificado centralizado está expirado.', CERTIFICATE_REVOKED: 'El certificado centralizado está revocado.',
63
+ SIGNATURE_INVALID: 'SII no devolvió un XML firmado válido para el documento aprobado. No se envió.',
64
+ 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.',
65
+ };
66
+ class SiiError extends Error {
67
+ code;
68
+ httpStatus;
69
+ diagnostics;
70
+ description;
71
+ constructor(code, httpStatus, diagnostics) {
72
+ super(code); // Preserve the existing code/message contract.
73
+ this.code = code;
74
+ this.httpStatus = httpStatus;
75
+ this.name = 'SiiError';
76
+ this.diagnostics = sanitizeSiiDiagnostics(diagnostics);
77
+ if (this.diagnostics) {
78
+ const d = this.diagnostics;
79
+ this.description = `Falló el paso: ${STAGE_LABELS[d.stage]} (${d.endpoint}). ${REASON_LABELS[d.reason]}`
80
+ + (d.httpStatus === undefined ? '' : ` HTTP ${d.httpStatus}.`)
81
+ + (d.siiMessageCode ? ` Código SII: ${d.siiMessageCode}.` : '')
82
+ + (d.siiResponseCode === undefined ? '' : ` Respuesta SII: ${d.siiResponseCode}.`);
83
+ }
84
+ }
85
+ }
86
+ exports.SiiError = SiiError;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@devly-cl/sii-client",
3
- "version": "0.5.0",
4
- "description": "Cliente HTTP del SII para acceso personal, RCV, XML y emisión de facturas y notas de crédito, independiente de framework.",
3
+ "version": "0.6.0",
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",
7
7
  "engines": {
@@ -27,8 +27,8 @@
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/xml.mjs && node test/logout.mjs && node test/credit-note-xml.mjs && node test/facturador.mjs && node test/invoicing.mjs && node test/issuance.mjs && node test/issuance-edges.mjs && node test/api-naming.mjs",
31
- "check:example": "tsc --strict --noEmit --target ES2022 --module Node16 --moduleResolution Node16 --types node examples/consulta-rcv.ts examples/facturacion.ts",
30
+ "test": "npm run build && node test/check.mjs && node test/invoices.mjs && node test/xml.mjs && node test/logout.mjs && node test/credit-note-xml.mjs && node test/facturador.mjs && node test/invoicing.mjs && node test/issuance.mjs && node test/issuance-edges.mjs && node test/api-naming.mjs && node test/company-selection.mjs && node test/transport-lifecycle.mjs && node test/application.mjs && node test/architecture.mjs && node test/pdf.mjs && node test/pdf-http.mjs",
31
+ "check:example": "tsc --strict --noEmit --target ES2022 --module Node16 --moduleResolution Node16 --types node examples/consulta-rcv.ts examples/facturacion.ts examples/consulta-pdf.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",
34
34
  "prepack": "npm run check"