@devly-cl/sii-client 0.5.0 → 0.7.1

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 (50) hide show
  1. package/README.md +96 -219
  2. package/dist/application/document-status.d.ts +13 -0
  3. package/dist/application/document-status.js +50 -0
  4. package/dist/application/invoice-queries.d.ts +23 -0
  5. package/dist/application/invoice-queries.js +55 -0
  6. package/dist/application/issuance.d.ts +40 -0
  7. package/dist/application/issuance.js +79 -0
  8. package/dist/contracts.d.ts +66 -0
  9. package/dist/contracts.js +2 -0
  10. package/dist/domain/company-info.d.ts +13 -0
  11. package/dist/domain/company-info.js +2 -0
  12. package/dist/domain/document-status.d.ts +93 -0
  13. package/dist/domain/document-status.js +69 -0
  14. package/dist/domain/document.d.ts +51 -0
  15. package/dist/domain/document.js +71 -0
  16. package/dist/domain/invoice-xml.d.ts +34 -11
  17. package/dist/domain/invoice-xml.js +0 -170
  18. package/dist/domain/invoicing.d.ts +78 -5
  19. package/dist/domain/invoicing.js +143 -26
  20. package/dist/domain/issued-invoice.d.ts +1 -2
  21. package/dist/domain/issued-invoice.js +4 -43
  22. package/dist/domain/rcv-document.d.ts +17 -0
  23. package/dist/domain/rcv-document.js +2 -0
  24. package/dist/domain/received-invoice.d.ts +1 -3
  25. package/dist/domain/received-invoice.js +0 -10
  26. package/dist/index.d.ts +12 -7
  27. package/dist/index.js +6 -4
  28. package/dist/infrastructure/document-status-gateway.d.ts +13 -0
  29. package/dist/infrastructure/document-status-gateway.js +127 -0
  30. package/dist/infrastructure/document-status-parser.d.ts +12 -0
  31. package/dist/infrastructure/document-status-parser.js +258 -0
  32. package/dist/infrastructure/dte-xml.d.ts +11 -0
  33. package/dist/infrastructure/dte-xml.js +248 -0
  34. package/dist/infrastructure/facturador-gateway.d.ts +31 -0
  35. package/dist/infrastructure/facturador-gateway.js +509 -0
  36. package/dist/infrastructure/facturador.d.ts +13 -3
  37. package/dist/infrastructure/facturador.js +34 -3
  38. package/dist/infrastructure/invoice-pdf.d.ts +9 -0
  39. package/dist/infrastructure/invoice-pdf.js +171 -0
  40. package/dist/infrastructure/rcv-gateway.d.ts +20 -0
  41. package/dist/infrastructure/rcv-gateway.js +109 -0
  42. package/dist/infrastructure/rcv-normalization.d.ts +13 -0
  43. package/dist/infrastructure/rcv-normalization.js +63 -0
  44. package/dist/infrastructure/sii-client.d.ts +31 -121
  45. package/dist/infrastructure/sii-client.js +69 -772
  46. package/dist/infrastructure/sii-http-session.d.ts +29 -0
  47. package/dist/infrastructure/sii-http-session.js +359 -0
  48. package/dist/{domain/sii-error.d.ts → sii-error.d.ts} +3 -3
  49. package/dist/{domain/sii-error.js → sii-error.js} +14 -4
  50. package/package.json +45 -45
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.invoicePdfCode = invoicePdfCode;
4
+ exports.readInvoicePdfStream = readInvoicePdfStream;
5
+ const node_stream_1 = require("node:stream");
6
+ const rut_1 = require("../domain/rut");
7
+ const sii_error_1 = require("../sii-error");
8
+ const facturador_1 = require("./facturador");
9
+ const sii_http_session_1 = require("./sii-http-session");
10
+ const MAX_PDF_BYTES = 20 * 1024 * 1024;
11
+ const PDF_TYPES = new Map([['33', 33], ['factura electronica', 33], ['34', 34], ['factura exenta electronica', 34], ['factura no afecta o exenta electronica', 34]]);
12
+ const normalized = (value) => value.normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/\s+/g, ' ').trim().toLowerCase();
13
+ /** Match the observed seven-column history, plus emitted rows with combined RUT/name. */
14
+ function invoicePdfCode(document, { documentType, folio }, supplierRut) {
15
+ const detailPath = `/cgi-bin/Portal001/mipeGesDoc${supplierRut ? 'Rcp' : 'Emi'}.cgi`;
16
+ const matches = [];
17
+ let candidates = 0;
18
+ let emptyHistory = false;
19
+ for (const row of (0, facturador_1.nodes)(document)) {
20
+ if (!(0, facturador_1.element)(row) || row.tagName !== 'tr')
21
+ continue;
22
+ const cells = row.childNodes.filter(facturador_1.element).filter(node => node.tagName === 'td' || node.tagName === 'th').map(facturador_1.readVisiblePortalText).map(value => value.trim()).filter(Boolean);
23
+ const links = [...(0, facturador_1.nodes)(row)].filter(facturador_1.element).filter(node => node.tagName === 'a' && (0, facturador_1.attr)(node, 'href')?.includes(detailPath.split('/').at(-1)));
24
+ if (!links.length) {
25
+ if (cells.length === 1 && /^no\s+hay\s+informaci[oó]n\b/i.test(cells[0]))
26
+ emptyHistory = true;
27
+ continue;
28
+ }
29
+ candidates++;
30
+ const combined = !supplierRut && cells.length === 6;
31
+ if (!(cells.length === 7 || combined))
32
+ throw new sii_error_1.SiiError('SII_PDF_IDENTITY_MISMATCH');
33
+ const offset = combined ? 1 : 2;
34
+ const rut = cells[0]?.match(/^(\d{1,3}(?:\.\d{3})*|\d{1,9})-([\dKk])(?:\s|$)/);
35
+ if (!rut)
36
+ throw new sii_error_1.SiiError('SII_PDF_IDENTITY_MISMATCH');
37
+ let counterparty;
38
+ try {
39
+ counterparty = (0, rut_1.parseRut)(`${rut[1]}-${rut[2]}`).formatted;
40
+ }
41
+ catch {
42
+ throw new sii_error_1.SiiError('SII_PDF_IDENTITY_MISMATCH');
43
+ }
44
+ if (PDF_TYPES.get(normalized(cells[offset] ?? '')) !== documentType || cells[offset + 1] !== folio || supplierRut && counterparty !== supplierRut)
45
+ continue;
46
+ const codes = new Set();
47
+ for (const link of links) {
48
+ let url;
49
+ try {
50
+ url = new URL((0, facturador_1.attr)(link, 'href'), sii_http_session_1.FACTURADOR);
51
+ }
52
+ catch {
53
+ throw new sii_error_1.SiiError('SII_PDF_IDENTITY_MISMATCH');
54
+ }
55
+ const code = url.searchParams.get('CODIGO');
56
+ if (url.origin !== 'https://www1.sii.cl' || url.username || url.password || url.hash || url.pathname !== detailPath || url.searchParams.getAll('CODIGO').length !== 1 || !code || !/^[1-9]\d{0,19}$/.test(code))
57
+ throw new sii_error_1.SiiError('SII_PDF_IDENTITY_MISMATCH');
58
+ codes.add(code);
59
+ }
60
+ if (codes.size !== 1)
61
+ throw new sii_error_1.SiiError('SII_PDF_IDENTITY_MISMATCH');
62
+ matches.push([...codes][0]);
63
+ }
64
+ if (matches.length === 1)
65
+ return matches[0];
66
+ if (candidates)
67
+ throw new sii_error_1.SiiError('SII_PDF_IDENTITY_MISMATCH');
68
+ if (emptyHistory || /no\s+se\s+encontraron\s+documentos/i.test((0, facturador_1.readVisiblePortalText)(document)))
69
+ throw new sii_error_1.SiiError('SII_PDF_UNAVAILABLE');
70
+ throw new sii_error_1.SiiError('SII_PROTOCOL_CHANGED');
71
+ }
72
+ /** Keep only the prefix and transport chunks; reads stop when Node applies backpressure. */
73
+ async function readInvoicePdfStream(response, session, endpoint, signal, trackStream) {
74
+ const reader = response.body?.getReader();
75
+ const fail = (reason, bytes) => session.failure('SII_PDF_INVALID', endpoint, reason, response, (0, sii_http_session_1.responseFormat)(response, bytes));
76
+ if (!reader)
77
+ throw fail('EMPTY_RESPONSE', new Uint8Array());
78
+ let stream;
79
+ const prefixChunks = [];
80
+ const prefix = new Uint8Array(5);
81
+ let prefixSize = 0, size = 0, reading = false;
82
+ let cancellation;
83
+ const cancelSource = () => cancellation ??= reader.cancel().catch(() => { });
84
+ const onAbort = () => {
85
+ void cancelSource();
86
+ stream?.destroy(session.abortFailure(signal, endpoint));
87
+ };
88
+ signal.addEventListener('abort', onAbort, { once: true });
89
+ try {
90
+ if (signal.aborted)
91
+ throw session.abortFailure(signal, endpoint);
92
+ const contentLength = response.headers.get('content-length');
93
+ if (contentLength !== null && /^\d+$/.test(contentLength) && Number(contentLength) > MAX_PDF_BYTES)
94
+ throw fail('RESPONSE_TOO_LARGE');
95
+ if (contentLength === '0')
96
+ throw fail('EMPTY_RESPONSE', new Uint8Array());
97
+ const mime = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
98
+ if (mime !== 'application/pdf' && mime !== 'application/octet-stream')
99
+ throw fail('INVALID_PDF');
100
+ while (prefixSize < prefix.length) {
101
+ const { done, value } = await reader.read();
102
+ if (signal.aborted)
103
+ throw session.abortFailure(signal, endpoint);
104
+ if (done)
105
+ throw fail(prefixSize ? 'INVALID_PDF' : 'EMPTY_RESPONSE', prefix.subarray(0, prefixSize));
106
+ size += value.byteLength;
107
+ if (size > MAX_PDF_BYTES)
108
+ throw fail('RESPONSE_TOO_LARGE');
109
+ if (!value.length)
110
+ continue;
111
+ prefixChunks.push(value);
112
+ const count = Math.min(value.length, prefix.length - prefixSize);
113
+ prefix.set(value.subarray(0, count), prefixSize);
114
+ prefixSize += count;
115
+ }
116
+ if (Buffer.from(prefix).toString('latin1') !== '%PDF-')
117
+ throw fail('INVALID_PDF', prefix);
118
+ stream = new node_stream_1.Readable({
119
+ objectMode: false, highWaterMark: 64 * 1024,
120
+ read() {
121
+ if (reading)
122
+ return;
123
+ reading = true;
124
+ void (async () => {
125
+ for (;;) {
126
+ if (this.destroyed)
127
+ return;
128
+ if (signal.aborted)
129
+ throw session.abortFailure(signal, endpoint);
130
+ const initial = prefixChunks.shift();
131
+ const { done, value } = initial ? { done: false, value: initial } : await reader.read();
132
+ if (this.destroyed)
133
+ return;
134
+ if (signal.aborted)
135
+ throw session.abortFailure(signal, endpoint);
136
+ if (done) {
137
+ reading = false;
138
+ this.push(null);
139
+ return;
140
+ }
141
+ if (!initial)
142
+ size += value.byteLength;
143
+ if (size > MAX_PDF_BYTES)
144
+ throw fail('RESPONSE_TOO_LARGE');
145
+ if (!value.byteLength)
146
+ continue;
147
+ // Node can request the next chunk synchronously from push().
148
+ reading = false;
149
+ this.push(value);
150
+ return;
151
+ }
152
+ })().catch(error => { reading = false; this.destroy(error instanceof sii_error_1.SiiError ? error : session.failure('SII_TRANSPORT_ERROR', endpoint, 'TRANSPORT_ERROR', response)); });
153
+ },
154
+ destroy(error, callback) {
155
+ signal.removeEventListener('abort', onAbort);
156
+ prefixChunks.length = 0;
157
+ void cancelSource().then(() => { reader.releaseLock(); callback(error); });
158
+ },
159
+ });
160
+ // Track before yielding: abort can happen between creation and public handoff.
161
+ trackStream(stream);
162
+ return stream;
163
+ }
164
+ catch (error) {
165
+ signal.removeEventListener('abort', onAbort);
166
+ prefixChunks.length = 0;
167
+ await cancelSource();
168
+ reader.releaseLock();
169
+ throw signal.aborted ? session.abortFailure(signal, endpoint) : error instanceof sii_error_1.SiiError ? error : session.failure('SII_TRANSPORT_ERROR', endpoint, 'TRANSPORT_ERROR', response);
170
+ }
171
+ }
@@ -0,0 +1,20 @@
1
+ import { type IssuedInvoicesQuery, type IssuedInvoicesResult } from '../domain/issued-invoice';
2
+ import type { ReceivedInvoicesQuery, ReceivedInvoicesResult } from '../domain/received-invoice';
3
+ import type { RcvDocumentsQuery, RcvDocumentsResult } from '../domain/rcv-document';
4
+ import type { AuthorizedCompany, SummaryQuery, SiiResponse } from '../contracts';
5
+ import { SiiHttpSession } from './sii-http-session';
6
+ export declare class RcvGateway {
7
+ #private;
8
+ private readonly session;
9
+ constructor(session: SiiHttpSession);
10
+ companies(identity?: {
11
+ rut: string;
12
+ dv: string;
13
+ formatted: string;
14
+ }): Promise<SiiResponse<AuthorizedCompany>>;
15
+ summary({ periodo, operacion, estado }: SummaryQuery): Promise<SiiResponse>;
16
+ issuedInvoices(input: IssuedInvoicesQuery): Promise<IssuedInvoicesResult>;
17
+ receivedInvoices(input: ReceivedInvoicesQuery): Promise<ReceivedInvoicesResult>;
18
+ issuedDocuments(input: RcvDocumentsQuery): Promise<RcvDocumentsResult>;
19
+ receivedDocuments(input: RcvDocumentsQuery): Promise<RcvDocumentsResult>;
20
+ }
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RcvGateway = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const issued_invoice_1 = require("../domain/issued-invoice");
6
+ const invoice_queries_1 = require("../application/invoice-queries");
7
+ const rcv_normalization_1 = require("./rcv-normalization");
8
+ const sii_http_session_1 = require("./sii-http-session");
9
+ const NAMESPACE = 'cl.sii.sdi.lob.diii.consdcv.data.api.interfaces.FacadeService/';
10
+ const STATES = new Set(['REGISTRO', 'PENDIENTE', 'NO_INCLUIR', 'RECLAMADO']);
11
+ const isInvoiceType = (type) => type === 33 || type === 34;
12
+ const isDocumentType = (type) => isInvoiceType(type) || type === 61;
13
+ class RcvGateway {
14
+ session;
15
+ constructor(session) {
16
+ this.session = session;
17
+ }
18
+ companies(identity = this.session.assertReady()) {
19
+ return this.#call('getDcvEmpresasAutorizadas', { rutAutenticado: identity.rut, dvAutenticado: identity.dv });
20
+ }
21
+ async summary({ periodo, operacion, estado = 'REGISTRO' }) {
22
+ this.session.assertReady();
23
+ (0, issued_invoice_1.assertPeriod)(periodo);
24
+ if (!['COMPRA', 'VENTA'].includes(operacion))
25
+ throw new TypeError('Operación inválida');
26
+ if (!STATES.has(estado) || (operacion === 'VENTA' && estado !== 'REGISTRO'))
27
+ throw new TypeError('Estado inválido');
28
+ const company = this.session.company;
29
+ return this.#call('getResumen', { rutEmisor: company.rut, dvEmisor: company.dv, ptributario: periodo, estadoContab: estado, operacion });
30
+ }
31
+ issuedInvoices(input) { return this.#documents('VENTA', input, isInvoiceType, rcv_normalization_1.normalizeIssuedInvoice); }
32
+ receivedInvoices(input) { return this.#documents('COMPRA', input, isInvoiceType, rcv_normalization_1.normalizeReceivedInvoice); }
33
+ issuedDocuments(input) { return this.#documents('VENTA', input, isDocumentType, rcv_normalization_1.normalizeIssuedDocument); }
34
+ receivedDocuments(input) { return this.#documents('COMPRA', input, isDocumentType, rcv_normalization_1.normalizeReceivedDocument); }
35
+ async #documents(operation, input, supported, normalize) {
36
+ this.session.assertReady();
37
+ const detailMethod = operation === 'COMPRA' ? 'getDetalleCompra' : 'getDetalleVenta';
38
+ try {
39
+ return await (0, invoice_queries_1.readDocuments)({
40
+ initialLimit: async () => {
41
+ const initial = await this.#call('getDatosInicio', {});
42
+ if (typeof initial.limiteDtes !== 'number' || !Number.isSafeInteger(initial.limiteDtes) || initial.limiteDtes < 1)
43
+ throw this.session.failure('SII_INVALID_RESPONSE', 'getDatosInicio', 'INVALID_RESPONSE');
44
+ return initial.limiteDtes;
45
+ },
46
+ counts: async () => {
47
+ const summary = await this.summary({ periodo: input.periodo, operacion: operation });
48
+ return summary.data.flatMap(row => {
49
+ const type = row.rsmnTipoDocInteger;
50
+ if (typeof type !== 'number' || !Number.isSafeInteger(type) || type < 1)
51
+ throw this.session.failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
52
+ if (!supported(type))
53
+ return [];
54
+ const count = row.rsmnTotDoc;
55
+ if (typeof count !== 'number' || !Number.isSafeInteger(count) || count < 0)
56
+ throw this.session.failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
57
+ return [{ documentType: type, count }];
58
+ });
59
+ },
60
+ details: async (type, tokenRecaptcha) => {
61
+ const company = this.session.company;
62
+ const details = await this.#call(detailMethod, {
63
+ rutEmisor: company.rut, dvEmisor: company.dv, ptributario: input.periodo,
64
+ codTipoDoc: String(type), operacion: operation === 'COMPRA' ? 'COMPRA' : '', estadoContab: operation === 'COMPRA' ? 'REGISTRO' : '', accionRecaptcha: operation === 'COMPRA' ? 'RCV_DETC' : 'RCV_DETV', tokenRecaptcha,
65
+ });
66
+ try {
67
+ return details.data.map(row => normalize(row, company.formatted, input.periodo, type));
68
+ }
69
+ catch {
70
+ throw this.session.failure('SII_INVALID_RESPONSE', detailMethod, 'INVALID_RESPONSE');
71
+ }
72
+ },
73
+ }, input);
74
+ }
75
+ catch (error) {
76
+ if (error instanceof invoice_queries_1.InvoiceQueryError)
77
+ throw this.session.failure('SII_INVALID_RESPONSE', error.section === 'SUMMARY' ? 'getResumen' : detailMethod, 'INVALID_RESPONSE');
78
+ throw error;
79
+ }
80
+ }
81
+ async #call(method, data) {
82
+ const token = (await this.session.cookies(sii_http_session_1.RCV)).find(c => c.key === 'TOKEN')?.value;
83
+ if (!token)
84
+ throw this.session.failure('SESSION_REQUIRED', method, 'SESSION_REQUIRED');
85
+ return this.session.request(`${sii_http_session_1.RCV}services/data/facadeService/${method}`, async (response) => {
86
+ const result = await this.session.json(response, method);
87
+ if (!(0, sii_http_session_1.isRecord)(result))
88
+ throw this.session.failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
89
+ const status = result.respEstado;
90
+ const rawMeta = result.metaData ?? {};
91
+ if (!(0, sii_http_session_1.isRecord)(status) || !(0, sii_http_session_1.isRecord)(rawMeta) || (rawMeta.errors != null && !Array.isArray(rawMeta.errors)))
92
+ throw this.session.failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
93
+ if (status.codRespuesta === 98)
94
+ throw this.session.failure('CAPTCHA_INTERACTION_REQUIRED', method, 'CAPTCHA_REQUIRED', response, { siiResponseCode: 98 });
95
+ const emptySummary = method === 'getResumen' && status.codRespuesta === 3 && status.codError == null && result.data === null;
96
+ if ((!emptySummary && status.codRespuesta !== 0) || (Array.isArray(rawMeta.errors) && rawMeta.errors.length))
97
+ throw this.session.failure('SII_SERVICE_ERROR', method, 'PROVIDER_REJECTED', response, { ...(typeof status.codRespuesta === 'number' ? { siiResponseCode: status.codRespuesta } : {}) });
98
+ const rows = emptySummary ? [] : result.data;
99
+ if (!Array.isArray(rows) || !rows.every(sii_http_session_1.isRecord))
100
+ throw this.session.failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
101
+ const { conversationId: _secret, ...metaData } = rawMeta;
102
+ return { ...result, data: rows, metaData };
103
+ }, {
104
+ method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/plain, */*', Referer: sii_http_session_1.RCV },
105
+ body: JSON.stringify({ metaData: { namespace: NAMESPACE + method, conversationId: token, transactionId: (0, node_crypto_1.randomUUID)(), page: null }, data }),
106
+ }, true);
107
+ }
108
+ }
109
+ exports.RcvGateway = RcvGateway;
@@ -0,0 +1,13 @@
1
+ import type { IssuedInvoice, InvoiceDocumentType } from '../domain/issued-invoice';
2
+ import type { ReceivedInvoice } from '../domain/received-invoice';
3
+ import type { RcvDocumentType } from '../domain/rcv-document';
4
+ /** Campos del proveedor validados; emisor y periodo vienen de la consulta autorizada. */
5
+ export declare function normalizeIssuedInvoice(row: Record<string, unknown>, issuerRut: string, period: string, type: InvoiceDocumentType): IssuedInvoice;
6
+ export declare function normalizeIssuedDocument<D extends RcvDocumentType>(row: Record<string, unknown>, issuerRut: string, period: string, type: D): Omit<IssuedInvoice, 'documentType'> & {
7
+ documentType: D;
8
+ };
9
+ /** In purchases detRutDoc identifies the supplier; the authorized company is the receiver. */
10
+ export declare function normalizeReceivedInvoice(row: Record<string, unknown>, receiverRut: string, period: string, type: InvoiceDocumentType): ReceivedInvoice;
11
+ export declare function normalizeReceivedDocument<D extends RcvDocumentType>(row: Record<string, unknown>, receiverRut: string, period: string, type: D): Omit<ReceivedInvoice, 'documentType'> & {
12
+ documentType: D;
13
+ };
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeIssuedInvoice = normalizeIssuedInvoice;
4
+ exports.normalizeIssuedDocument = normalizeIssuedDocument;
5
+ exports.normalizeReceivedInvoice = normalizeReceivedInvoice;
6
+ exports.normalizeReceivedDocument = normalizeReceivedDocument;
7
+ const rut_1 = require("../domain/rut");
8
+ function integer(value) {
9
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
10
+ throw new TypeError('SII_INVALID_RESPONSE');
11
+ return value;
12
+ }
13
+ function nullableAmount(value) { return value == null ? null : integer(value); }
14
+ function date(value) {
15
+ if (typeof value !== 'string')
16
+ throw new TypeError('SII_INVALID_RESPONSE');
17
+ const iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
18
+ const local = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(value);
19
+ const [year, month, day] = iso ? [iso[1], iso[2], iso[3]] : local ? [local[3], local[2], local[1]] : [];
20
+ if (!year || !month || !day)
21
+ throw new TypeError('SII_INVALID_RESPONSE');
22
+ const y = Number(year), m = Number(month), d = Number(day);
23
+ const days = [31, y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
24
+ if (y < 1 || m < 1 || m > 12 || d < 1 || d > days[m - 1])
25
+ throw new TypeError('SII_INVALID_RESPONSE');
26
+ return `${year}-${month}-${day}`;
27
+ }
28
+ /** Campos del proveedor validados; emisor y periodo vienen de la consulta autorizada. */
29
+ function normalizeIssuedInvoice(row, issuerRut, period, type) {
30
+ return normalizeIssuedDocument(row, issuerRut, period, type);
31
+ }
32
+ function normalizeIssuedDocument(row, issuerRut, period, type) {
33
+ if (row.detTipoDoc !== type || integer(row.detNroDoc) === 0 || integer(row.detRutDoc) === 0 || typeof row.detDvDoc !== 'string' || !/^[\dKk]$/.test(row.detDvDoc)) {
34
+ throw new TypeError('SII_INVALID_RESPONSE');
35
+ }
36
+ if (row.detRznSoc != null && typeof row.detRznSoc !== 'string')
37
+ throw new TypeError('SII_INVALID_RESPONSE');
38
+ let receiverRut;
39
+ try {
40
+ receiverRut = (0, rut_1.parseRut)(`${row.detRutDoc}-${row.detDvDoc}`).formatted;
41
+ }
42
+ catch {
43
+ throw new TypeError('SII_INVALID_RESPONSE');
44
+ }
45
+ return {
46
+ issuerRut, documentType: type, folio: String(row.detNroDoc), issuedDate: date(row.detFchDoc),
47
+ receiverRut, receiverName: typeof row.detRznSoc === 'string' ? row.detRznSoc.trim() || null : null,
48
+ netAmount: nullableAmount(row.detMntNeto), exemptAmount: nullableAmount(row.detMntExe),
49
+ vatAmount: nullableAmount(row.detMntIVA), totalAmount: integer(row.detMntTotal),
50
+ siiBranchCode: row.detCdgSIISucur == null ? null : String(integer(row.detCdgSIISucur)), rcvPeriod: period,
51
+ };
52
+ }
53
+ /** In purchases detRutDoc identifies the supplier; the authorized company is the receiver. */
54
+ function normalizeReceivedInvoice(row, receiverRut, period, type) {
55
+ return normalizeReceivedDocument(row, receiverRut, period, type);
56
+ }
57
+ function normalizeReceivedDocument(row, receiverRut, period, type) {
58
+ // getDetalleCompra returns detTipoDoc:null for the requested type (observed in RCV).
59
+ if (row.detTipoDoc != null && row.detTipoDoc !== type)
60
+ throw new TypeError('SII_INVALID_RESPONSE');
61
+ const invoice = normalizeIssuedDocument({ ...row, detTipoDoc: type }, receiverRut, period, type);
62
+ return { ...invoice, issuerRut: invoice.receiverRut, issuerName: invoice.receiverName, receiverRut, receiverName: null };
63
+ }
@@ -1,132 +1,44 @@
1
- export { SiiError } from '../domain/sii-error';
2
- import { type IssuedInvoicesQuery, type IssuedInvoicesResult } from '../domain/issued-invoice';
3
- import { type ReceivedInvoicesQuery, type ReceivedInvoicesResult } from '../domain/received-invoice';
4
- import { type IssuedInvoiceXmlQuery, type ReceivedInvoiceXmlQuery, type InvoiceXmlResult } from '../domain/invoice-xml';
5
- import { type IssuedDocumentXmlQuery, type IssuedDocumentXmlResult } from '../domain/invoice-xml';
6
- import { type InvoiceInput } from '../domain/invoicing';
7
- export type Operation = 'COMPRA' | 'VENTA';
8
- export type PurchaseStatus = 'REGISTRO' | 'PENDIENTE' | 'NO_INCLUIR' | 'RECLAMADO';
9
- export type SiiRecord = Record<string, unknown>;
10
- export interface SiiResponse<T = SiiRecord> {
11
- data: T[];
12
- metaData: Record<string, unknown>;
13
- respEstado: {
14
- codRespuesta: number;
15
- msgeRespuesta: string | null;
16
- codError: unknown;
17
- };
18
- [key: string]: unknown;
19
- }
20
- export interface AuthorizedCompany extends SiiRecord {
21
- usrEmpRut: number;
22
- usrEmpDv: string;
23
- usrEmpRutDv: string;
24
- }
25
- export interface SiiClientOptions {
26
- empresaRut: string;
27
- timeoutMs?: number;
28
- retries?: number;
29
- fetchImpl?: typeof globalThis.fetch;
30
- }
31
- export interface SiiCredentials {
32
- rut: string;
33
- clave: string;
34
- }
35
- export interface SummaryQuery {
36
- periodo: string;
37
- operacion: Operation;
38
- estado?: PurchaseStatus;
39
- }
40
- export interface SiiSession {
41
- usuarioRut: string;
42
- empresaRut: string;
43
- representacion: false;
44
- }
45
- export interface PreparedDocument {
46
- readonly preparacionId: string;
47
- readonly contentHash: string;
48
- readonly expiresAt: string;
49
- readonly issuerRut: string;
50
- readonly receiverRut: string;
51
- readonly documentType: 33 | 61;
52
- readonly issuedDate: string;
53
- readonly netAmount: number;
54
- readonly vatAmount: number;
55
- readonly totalAmount: number;
56
- readonly invoice?: InvoiceInput;
57
- readonly issuerLegalName?: string;
58
- readonly issuerBusinessActivity?: string;
59
- readonly issuerBranchCode?: string;
60
- readonly originalInvoice?: IssuedDocumentXmlResult['detail'];
61
- readonly reference?: {
62
- readonly documentType: 33;
63
- readonly folio: string;
64
- readonly issuedDate: string;
65
- readonly code: 1;
66
- };
67
- }
68
- export interface SignedDocument extends IssuedDocumentXmlResult {
69
- readonly issuerRut: string;
70
- readonly receiverRut: string;
71
- readonly documentType: 33 | 61;
72
- readonly folio: string;
73
- readonly issuedDate: string;
74
- readonly contentHash: string;
75
- }
76
- export interface SentDocument extends SignedDocument {
77
- readonly status: 'ENVIADO';
78
- }
79
- export interface SignDocumentInput {
80
- preparacionId: string;
81
- approvedHash: string;
82
- claveFirma: string;
83
- /** Persistir XML e identidad antes del envío. Si falla, no se envía. Sin guardar secretos. */
84
- beforeSend: (document: SignedDocument) => Promise<void>;
85
- }
86
- /** @deprecated Use Operation. */
87
- export type Operacion = Operation;
88
- /** @deprecated Use PurchaseStatus. */
89
- export type EstadoCompra = PurchaseStatus;
90
- /** @deprecated Use SiiRecord. */
91
- export type RegistroSii = SiiRecord;
92
- /** @deprecated Use SiiResponse. */
93
- export type RespuestaSii<T = SiiRecord> = SiiResponse<T>;
94
- /** @deprecated Use AuthorizedCompany. */
95
- export type EmpresaAutorizada = AuthorizedCompany;
96
- /** @deprecated Use SiiCredentials. */
97
- export type CredencialesSii = SiiCredentials;
98
- /** @deprecated Use SummaryQuery. */
99
- export type ConsultaResumen = SummaryQuery;
100
- /** @deprecated Use SiiSession. */
101
- export type SesionSii = SiiSession;
102
- /** @deprecated Use PreparedDocument. */
103
- export type DocumentoPreparado = PreparedDocument;
104
- /** @deprecated Use SignedDocument. */
105
- export type DocumentoFirmado = SignedDocument;
106
- /** @deprecated Use SentDocument. */
107
- export type DocumentoEnviado = SentDocument;
108
- /** @deprecated Use SignDocumentInput. */
109
- export type FirmaDocumento = SignDocumentInput;
110
- /** Una instancia = una empresa y una sesión personal. Nunca comparte cookies. */
1
+ import { type PreparedDocument, type SentDocument } from '../domain/document';
2
+ import { type DocumentStatusQuery, type DocumentStatusResult, type RecipientEventsQuery, type RecipientEventsResult, type DocumentQueryOptions } from '../domain/document-status';
3
+ import type { InvoiceInput } from '../domain/invoicing';
4
+ import type { CompanyInfo } from '../domain/company-info';
5
+ import type { IssuedInvoicesQuery, IssuedInvoicesResult } from '../domain/issued-invoice';
6
+ import type { ReceivedInvoicesQuery, ReceivedInvoicesResult } from '../domain/received-invoice';
7
+ import type { RcvDocumentsQuery, RcvDocumentsResult } from '../domain/rcv-document';
8
+ import type { IssuedInvoiceXmlQuery, ReceivedInvoiceXmlQuery, InvoiceXmlResult, IssuedDocumentXmlQuery, ReceivedDocumentXmlQuery, IssuedDocumentXmlResult } from '../domain/invoice-xml';
9
+ import type { AuthorizedCompany, SummaryQuery, SiiResponse, SiiClientOptions, SiiCredentials, SiiSession, IssuedInvoicePdfQuery, ReceivedInvoicePdfQuery, PdfDownloadOptions, InvoicePdfResult } from '../contracts';
10
+ import { type SignDocumentInput } from '../application/issuance';
11
+ export { SiiError } from '../sii-error';
12
+ export type * from '../contracts';
13
+ export type { PreparedDocument, SignedDocument, SentDocument, DocumentoPreparado, DocumentoFirmado, DocumentoEnviado } from '../domain/document';
14
+ export type { SignDocumentInput, FirmaDocumento } from '../application/issuance';
15
+ /** One company and personal session; composition and compatibility stay at this boundary. */
111
16
  export declare class SiiClient {
112
17
  #private;
113
- constructor({ empresaRut, timeoutMs, retries, fetchImpl }: SiiClientOptions);
114
- login({ rut, clave }: SiiCredentials): Promise<SiiSession>;
18
+ constructor(options: SiiClientOptions);
19
+ login(credentials: SiiCredentials): Promise<SiiSession>;
115
20
  getAuthorizedCompanies(): Promise<SiiResponse<AuthorizedCompany>>;
116
- getSummary({ periodo, operacion, estado }: SummaryQuery): Promise<SiiResponse>;
21
+ getCompanyInfo(rut: string): Promise<CompanyInfo>;
22
+ getSummary(input: SummaryQuery): Promise<SiiResponse>;
117
23
  getIssuedInvoices(input: IssuedInvoicesQuery): Promise<IssuedInvoicesResult>;
118
- /** Facturas 33/34 in the official purchase register. Does not accept, claim or move documents. */
119
24
  getReceivedInvoices(input: ReceivedInvoicesQuery): Promise<ReceivedInvoicesResult>;
25
+ getIssuedDocuments(input: RcvDocumentsQuery): Promise<RcvDocumentsResult>;
26
+ getReceivedDocuments(input: RcvDocumentsQuery): Promise<RcvDocumentsResult>;
27
+ getIssuedInvoiceXml(input: IssuedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
28
+ getReceivedInvoiceXml(input: ReceivedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
29
+ getIssuedDocumentXml(input: IssuedDocumentXmlQuery): Promise<IssuedDocumentXmlResult>;
30
+ getReceivedDocumentXml(input: ReceivedDocumentXmlQuery): Promise<IssuedDocumentXmlResult>;
31
+ getIssuedInvoicePdf(input: IssuedInvoicePdfQuery, options?: PdfDownloadOptions): Promise<InvoicePdfResult>;
32
+ getReceivedInvoicePdf(input: ReceivedInvoicePdfQuery, options?: PdfDownloadOptions): Promise<InvoicePdfResult>;
33
+ getDocumentStatus(input: DocumentStatusQuery, options?: DocumentQueryOptions): Promise<DocumentStatusResult>;
34
+ getDocumentRecipientEvents(input: RecipientEventsQuery, options?: DocumentQueryOptions): Promise<RecipientEventsResult>;
120
35
  prepareInvoice(input: InvoiceInput): Promise<PreparedDocument>;
121
- prepareCancellationCreditNote({ factura, issuedDate }: {
36
+ prepareCancellationCreditNote(input: {
122
37
  factura: IssuedInvoiceXmlQuery;
123
38
  issuedDate: string;
124
39
  }): Promise<PreparedDocument>;
125
40
  signAndSend(input: SignDocumentInput): Promise<SentDocument>;
126
- /** Original DTE from the free SII facturador; RCV membership alone does not guarantee XML availability. */
127
- getIssuedInvoiceXml(input: IssuedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
128
- getReceivedInvoiceXml(input: ReceivedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
129
- getIssuedDocumentXml(input: IssuedDocumentXmlQuery): Promise<IssuedDocumentXmlResult>;
41
+ dispose(): Promise<void>;
130
42
  /** @deprecated Use getAuthorizedCompanies. */
131
43
  getEmpresasAutorizadas(): Promise<SiiResponse<AuthorizedCompany>>;
132
44
  /** @deprecated Use getSummary. */
@@ -150,6 +62,4 @@ export declare class SiiClient {
150
62
  }): Promise<PreparedDocument>;
151
63
  /** @deprecated Use signAndSend. */
152
64
  firmarYEnviar(input: SignDocumentInput): Promise<SentDocument>;
153
- /** Cierra esta sesión remota antes de descartar cookies; siempre esperar en finally. */
154
- dispose(): Promise<void>;
155
65
  }