@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,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,17 @@
1
+ import { type IssuedInvoicesQuery, type IssuedInvoicesResult } from '../domain/issued-invoice';
2
+ import type { ReceivedInvoicesQuery, ReceivedInvoicesResult } from '../domain/received-invoice';
3
+ import type { AuthorizedCompany, SummaryQuery, SiiResponse } from '../contracts';
4
+ import { SiiHttpSession } from './sii-http-session';
5
+ export declare class RcvGateway {
6
+ #private;
7
+ private readonly session;
8
+ constructor(session: SiiHttpSession);
9
+ companies(identity?: {
10
+ rut: string;
11
+ dv: string;
12
+ formatted: string;
13
+ }): Promise<SiiResponse<AuthorizedCompany>>;
14
+ summary({ periodo, operacion, estado }: SummaryQuery): Promise<SiiResponse>;
15
+ issuedInvoices(input: IssuedInvoicesQuery): Promise<IssuedInvoicesResult>;
16
+ receivedInvoices(input: ReceivedInvoicesQuery): Promise<ReceivedInvoicesResult>;
17
+ }
@@ -0,0 +1,105 @@
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
+ class RcvGateway {
12
+ session;
13
+ constructor(session) {
14
+ this.session = session;
15
+ }
16
+ companies(identity = this.session.assertReady()) {
17
+ return this.#call('getDcvEmpresasAutorizadas', { rutAutenticado: identity.rut, dvAutenticado: identity.dv });
18
+ }
19
+ async summary({ periodo, operacion, estado = 'REGISTRO' }) {
20
+ this.session.assertReady();
21
+ (0, issued_invoice_1.assertPeriod)(periodo);
22
+ if (!['COMPRA', 'VENTA'].includes(operacion))
23
+ throw new TypeError('Operación inválida');
24
+ if (!STATES.has(estado) || (operacion === 'VENTA' && estado !== 'REGISTRO'))
25
+ throw new TypeError('Estado inválido');
26
+ const company = this.session.company;
27
+ return this.#call('getResumen', { rutEmisor: company.rut, dvEmisor: company.dv, ptributario: periodo, estadoContab: estado, operacion });
28
+ }
29
+ issuedInvoices(input) { return this.#invoices('VENTA', input, rcv_normalization_1.normalizeIssuedInvoice); }
30
+ receivedInvoices(input) { return this.#invoices('COMPRA', input, rcv_normalization_1.normalizeReceivedInvoice); }
31
+ async #invoices(operation, input, normalize) {
32
+ this.session.assertReady();
33
+ const detailMethod = operation === 'COMPRA' ? 'getDetalleCompra' : 'getDetalleVenta';
34
+ try {
35
+ return await (0, invoice_queries_1.readInvoices)({
36
+ initialLimit: async () => {
37
+ const initial = await this.#call('getDatosInicio', {});
38
+ if (typeof initial.limiteDtes !== 'number' || !Number.isSafeInteger(initial.limiteDtes) || initial.limiteDtes < 1)
39
+ throw this.session.failure('SII_INVALID_RESPONSE', 'getDatosInicio', 'INVALID_RESPONSE');
40
+ return initial.limiteDtes;
41
+ },
42
+ counts: async () => {
43
+ const summary = await this.summary({ periodo: input.periodo, operacion: operation });
44
+ return summary.data.flatMap(row => {
45
+ const type = row.rsmnTipoDocInteger;
46
+ if (typeof type !== 'number' || !Number.isSafeInteger(type) || type < 1)
47
+ throw this.session.failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
48
+ if (type !== 33 && type !== 34)
49
+ return [];
50
+ const count = row.rsmnTotDoc;
51
+ if (typeof count !== 'number' || !Number.isSafeInteger(count) || count < 0)
52
+ throw this.session.failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
53
+ return [{ documentType: type, count }];
54
+ });
55
+ },
56
+ details: async (type, tokenRecaptcha) => {
57
+ const company = this.session.company;
58
+ const details = await this.#call(detailMethod, {
59
+ rutEmisor: company.rut, dvEmisor: company.dv, ptributario: input.periodo,
60
+ codTipoDoc: String(type), operacion: operation === 'COMPRA' ? 'COMPRA' : '', estadoContab: operation === 'COMPRA' ? 'REGISTRO' : '', accionRecaptcha: operation === 'COMPRA' ? 'RCV_DETC' : 'RCV_DETV', tokenRecaptcha,
61
+ });
62
+ try {
63
+ return details.data.map(row => normalize(row, company.formatted, input.periodo, type));
64
+ }
65
+ catch {
66
+ throw this.session.failure('SII_INVALID_RESPONSE', detailMethod, 'INVALID_RESPONSE');
67
+ }
68
+ },
69
+ }, input);
70
+ }
71
+ catch (error) {
72
+ if (error instanceof invoice_queries_1.InvoiceQueryError)
73
+ throw this.session.failure('SII_INVALID_RESPONSE', error.section === 'SUMMARY' ? 'getResumen' : detailMethod, 'INVALID_RESPONSE');
74
+ throw error;
75
+ }
76
+ }
77
+ async #call(method, data) {
78
+ const token = (await this.session.cookies(sii_http_session_1.RCV)).find(c => c.key === 'TOKEN')?.value;
79
+ if (!token)
80
+ throw this.session.failure('SESSION_REQUIRED', method, 'SESSION_REQUIRED');
81
+ return this.session.request(`${sii_http_session_1.RCV}services/data/facadeService/${method}`, async (response) => {
82
+ const result = await this.session.json(response, method);
83
+ if (!(0, sii_http_session_1.isRecord)(result))
84
+ throw this.session.failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
85
+ const status = result.respEstado;
86
+ const rawMeta = result.metaData ?? {};
87
+ if (!(0, sii_http_session_1.isRecord)(status) || !(0, sii_http_session_1.isRecord)(rawMeta) || (rawMeta.errors != null && !Array.isArray(rawMeta.errors)))
88
+ throw this.session.failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
89
+ if (status.codRespuesta === 98)
90
+ throw this.session.failure('CAPTCHA_INTERACTION_REQUIRED', method, 'CAPTCHA_REQUIRED', response, { siiResponseCode: 98 });
91
+ const emptySummary = method === 'getResumen' && status.codRespuesta === 3 && status.codError == null && result.data === null;
92
+ if ((!emptySummary && status.codRespuesta !== 0) || (Array.isArray(rawMeta.errors) && rawMeta.errors.length))
93
+ throw this.session.failure('SII_SERVICE_ERROR', method, 'PROVIDER_REJECTED', response, { ...(typeof status.codRespuesta === 'number' ? { siiResponseCode: status.codRespuesta } : {}) });
94
+ const rows = emptySummary ? [] : result.data;
95
+ if (!Array.isArray(rows) || !rows.every(sii_http_session_1.isRecord))
96
+ throw this.session.failure('SII_PROTOCOL_CHANGED', method, 'INVALID_RESPONSE', response);
97
+ const { conversationId: _secret, ...metaData } = rawMeta;
98
+ return { ...result, data: rows, metaData };
99
+ }, {
100
+ method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/plain, */*', Referer: sii_http_session_1.RCV },
101
+ body: JSON.stringify({ metaData: { namespace: NAMESPACE + method, conversationId: token, transactionId: (0, node_crypto_1.randomUUID)(), page: null }, data }),
102
+ }, true);
103
+ }
104
+ }
105
+ exports.RcvGateway = RcvGateway;
@@ -0,0 +1,6 @@
1
+ import type { IssuedInvoice, InvoiceDocumentType } from '../domain/issued-invoice';
2
+ import type { ReceivedInvoice } from '../domain/received-invoice';
3
+ /** Campos del proveedor validados; emisor y periodo vienen de la consulta autorizada. */
4
+ export declare function normalizeIssuedInvoice(row: Record<string, unknown>, issuerRut: string, period: string, type: InvoiceDocumentType): IssuedInvoice;
5
+ /** In purchases detRutDoc identifies the supplier; the authorized company is the receiver. */
6
+ export declare function normalizeReceivedInvoice(row: Record<string, unknown>, receiverRut: string, period: string, type: InvoiceDocumentType): ReceivedInvoice;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeIssuedInvoice = normalizeIssuedInvoice;
4
+ exports.normalizeReceivedInvoice = normalizeReceivedInvoice;
5
+ const rut_1 = require("../domain/rut");
6
+ function integer(value) {
7
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
8
+ throw new TypeError('SII_INVALID_RESPONSE');
9
+ return value;
10
+ }
11
+ function nullableAmount(value) { return value == null ? null : integer(value); }
12
+ function date(value) {
13
+ if (typeof value !== 'string')
14
+ throw new TypeError('SII_INVALID_RESPONSE');
15
+ const iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
16
+ const local = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(value);
17
+ const [year, month, day] = iso ? [iso[1], iso[2], iso[3]] : local ? [local[3], local[2], local[1]] : [];
18
+ if (!year || !month || !day)
19
+ throw new TypeError('SII_INVALID_RESPONSE');
20
+ const y = Number(year), m = Number(month), d = Number(day);
21
+ const days = [31, y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
22
+ if (y < 1 || m < 1 || m > 12 || d < 1 || d > days[m - 1])
23
+ throw new TypeError('SII_INVALID_RESPONSE');
24
+ return `${year}-${month}-${day}`;
25
+ }
26
+ /** Campos del proveedor validados; emisor y periodo vienen de la consulta autorizada. */
27
+ function normalizeIssuedInvoice(row, issuerRut, period, type) {
28
+ if (row.detTipoDoc !== type || integer(row.detNroDoc) === 0 || integer(row.detRutDoc) === 0 || typeof row.detDvDoc !== 'string' || !/^[\dKk]$/.test(row.detDvDoc)) {
29
+ throw new TypeError('SII_INVALID_RESPONSE');
30
+ }
31
+ if (row.detRznSoc != null && typeof row.detRznSoc !== 'string')
32
+ throw new TypeError('SII_INVALID_RESPONSE');
33
+ let receiverRut;
34
+ try {
35
+ receiverRut = (0, rut_1.parseRut)(`${row.detRutDoc}-${row.detDvDoc}`).formatted;
36
+ }
37
+ catch {
38
+ throw new TypeError('SII_INVALID_RESPONSE');
39
+ }
40
+ return {
41
+ issuerRut, documentType: type, folio: String(row.detNroDoc), issuedDate: date(row.detFchDoc),
42
+ receiverRut, receiverName: typeof row.detRznSoc === 'string' ? row.detRznSoc.trim() || null : null,
43
+ netAmount: nullableAmount(row.detMntNeto), exemptAmount: nullableAmount(row.detMntExe),
44
+ vatAmount: nullableAmount(row.detMntIVA), totalAmount: integer(row.detMntTotal),
45
+ siiBranchCode: row.detCdgSIISucur == null ? null : String(integer(row.detCdgSIISucur)), rcvPeriod: period,
46
+ };
47
+ }
48
+ /** In purchases detRutDoc identifies the supplier; the authorized company is the receiver. */
49
+ function normalizeReceivedInvoice(row, receiverRut, period, type) {
50
+ // getDetalleCompra returns detTipoDoc:null for the requested type (observed in RCV).
51
+ if (row.detTipoDoc != null && row.detTipoDoc !== type)
52
+ throw new TypeError('SII_INVALID_RESPONSE');
53
+ const invoice = normalizeIssuedInvoice({ ...row, detTipoDoc: type }, receiverRut, period, type);
54
+ return { ...invoice, issuerRut: invoice.receiverRut, issuerName: invoice.receiverName, receiverRut, receiverName: null };
55
+ }
@@ -1,132 +1,35 @@
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 { InvoiceInput } from '../domain/invoicing';
3
+ import type { IssuedInvoicesQuery, IssuedInvoicesResult } from '../domain/issued-invoice';
4
+ import type { ReceivedInvoicesQuery, ReceivedInvoicesResult } from '../domain/received-invoice';
5
+ import type { IssuedInvoiceXmlQuery, ReceivedInvoiceXmlQuery, InvoiceXmlResult, IssuedDocumentXmlQuery, IssuedDocumentXmlResult } from '../domain/invoice-xml';
6
+ import type { AuthorizedCompany, SummaryQuery, SiiResponse, SiiClientOptions, SiiCredentials, SiiSession, IssuedInvoicePdfQuery, ReceivedInvoicePdfQuery, PdfDownloadOptions, InvoicePdfResult } from '../contracts';
7
+ import { type SignDocumentInput } from '../application/issuance';
8
+ export { SiiError } from '../sii-error';
9
+ export type * from '../contracts';
10
+ export type { PreparedDocument, SignedDocument, SentDocument, DocumentoPreparado, DocumentoFirmado, DocumentoEnviado } from '../domain/document';
11
+ export type { SignDocumentInput, FirmaDocumento } from '../application/issuance';
12
+ /** One company and personal session; composition and compatibility stay at this boundary. */
111
13
  export declare class SiiClient {
112
14
  #private;
113
- constructor({ empresaRut, timeoutMs, retries, fetchImpl }: SiiClientOptions);
114
- login({ rut, clave }: SiiCredentials): Promise<SiiSession>;
15
+ constructor(options: SiiClientOptions);
16
+ login(credentials: SiiCredentials): Promise<SiiSession>;
115
17
  getAuthorizedCompanies(): Promise<SiiResponse<AuthorizedCompany>>;
116
- getSummary({ periodo, operacion, estado }: SummaryQuery): Promise<SiiResponse>;
18
+ getSummary(input: SummaryQuery): Promise<SiiResponse>;
117
19
  getIssuedInvoices(input: IssuedInvoicesQuery): Promise<IssuedInvoicesResult>;
118
- /** Facturas 33/34 in the official purchase register. Does not accept, claim or move documents. */
119
20
  getReceivedInvoices(input: ReceivedInvoicesQuery): Promise<ReceivedInvoicesResult>;
21
+ getIssuedInvoiceXml(input: IssuedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
22
+ getReceivedInvoiceXml(input: ReceivedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
23
+ getIssuedDocumentXml(input: IssuedDocumentXmlQuery): Promise<IssuedDocumentXmlResult>;
24
+ getIssuedInvoicePdf(input: IssuedInvoicePdfQuery, options?: PdfDownloadOptions): Promise<InvoicePdfResult>;
25
+ getReceivedInvoicePdf(input: ReceivedInvoicePdfQuery, options?: PdfDownloadOptions): Promise<InvoicePdfResult>;
120
26
  prepareInvoice(input: InvoiceInput): Promise<PreparedDocument>;
121
- prepareCancellationCreditNote({ factura, issuedDate }: {
27
+ prepareCancellationCreditNote(input: {
122
28
  factura: IssuedInvoiceXmlQuery;
123
29
  issuedDate: string;
124
30
  }): Promise<PreparedDocument>;
125
31
  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>;
32
+ dispose(): Promise<void>;
130
33
  /** @deprecated Use getAuthorizedCompanies. */
131
34
  getEmpresasAutorizadas(): Promise<SiiResponse<AuthorizedCompany>>;
132
35
  /** @deprecated Use getSummary. */
@@ -150,6 +53,4 @@ export declare class SiiClient {
150
53
  }): Promise<PreparedDocument>;
151
54
  /** @deprecated Use signAndSend. */
152
55
  firmarYEnviar(input: SignDocumentInput): Promise<SentDocument>;
153
- /** Cierra esta sesión remota antes de descartar cookies; siempre esperar en finally. */
154
- dispose(): Promise<void>;
155
56
  }