@devly-cl/sii-client 0.4.4 → 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 (40) hide show
  1. package/README.md +118 -26
  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 +58 -11
  11. package/dist/domain/invoice-xml.js +0 -138
  12. package/dist/domain/invoicing.d.ts +52 -0
  13. package/dist/domain/invoicing.js +157 -0
  14. package/dist/domain/issued-invoice.d.ts +16 -9
  15. package/dist/domain/issued-invoice.js +4 -43
  16. package/dist/domain/received-invoice.d.ts +11 -7
  17. package/dist/domain/received-invoice.js +0 -10
  18. package/dist/domain/sii-error.d.ts +3 -3
  19. package/dist/domain/sii-error.js +10 -4
  20. package/dist/index.d.ts +13 -3
  21. package/dist/index.js +12 -3
  22. package/dist/infrastructure/dte-xml.d.ts +11 -0
  23. package/dist/infrastructure/dte-xml.js +173 -0
  24. package/dist/infrastructure/facturador-gateway.d.ts +28 -0
  25. package/dist/infrastructure/facturador-gateway.js +411 -0
  26. package/dist/infrastructure/facturador.d.ts +18 -0
  27. package/dist/infrastructure/facturador.js +231 -0
  28. package/dist/infrastructure/invoice-pdf.d.ts +9 -0
  29. package/dist/infrastructure/invoice-pdf.js +171 -0
  30. package/dist/infrastructure/rcv-gateway.d.ts +17 -0
  31. package/dist/infrastructure/rcv-gateway.js +105 -0
  32. package/dist/infrastructure/rcv-normalization.d.ts +6 -0
  33. package/dist/infrastructure/rcv-normalization.js +55 -0
  34. package/dist/infrastructure/sii-client.d.ts +52 -54
  35. package/dist/infrastructure/sii-client.js +66 -487
  36. package/dist/infrastructure/sii-http-session.d.ts +25 -0
  37. package/dist/infrastructure/sii-http-session.js +344 -0
  38. package/dist/sii-error.d.ts +27 -0
  39. package/dist/sii-error.js +86 -0
  40. package/package.json +4 -4
@@ -0,0 +1,231 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.attr = attr;
4
+ exports.nodes = nodes;
5
+ exports.element = element;
6
+ exports.parsePortalPage = parsePortalPage;
7
+ exports.readForm = readForm;
8
+ exports.readLiteralRows = readLiteralRows;
9
+ exports.encodePortalForm = encodePortalForm;
10
+ exports.readPortalHtml = readPortalHtml;
11
+ exports.encodeUnsignedDteXml = encodeUnsignedDteXml;
12
+ exports.readVisiblePortalText = readVisiblePortalText;
13
+ exports.hasInteractiveCaptcha = hasInteractiveCaptcha;
14
+ const parse5_1 = require("parse5");
15
+ const invoice_xml_1 = require("../domain/invoice-xml");
16
+ const PORTAL = 'https://www1.sii.cl/cgi-bin/Portal001/';
17
+ const MAX_HTML_BYTES = 2 * 1024 * 1024;
18
+ const ROW_VARIABLES = new Set(['emisorDir', 'emisorActEco', 'recptorDir', 'recptoActEco']);
19
+ const decoder = new TextDecoder('windows-1252', { fatal: true });
20
+ const cp1252 = new Map(Array.from({ length: 256 }, (_, byte) => [decoder.decode(Uint8Array.of(byte)), byte]));
21
+ function invalid(reason = 'INVALID_RESPONSE') { throw new TypeError(`Formulario del facturador inválido: ${reason}`); }
22
+ function attr(element, name) {
23
+ return element.attrs.find(attribute => attribute.name === name)?.value;
24
+ }
25
+ function* nodes(root) {
26
+ const pending = [root];
27
+ for (let node = pending.pop(); node; node = pending.pop()) {
28
+ yield node;
29
+ if ('childNodes' in node)
30
+ for (let i = node.childNodes.length - 1; i >= 0; i--) {
31
+ const child = node.childNodes[i];
32
+ if (child)
33
+ pending.push(child);
34
+ }
35
+ }
36
+ }
37
+ function element(node) {
38
+ return 'tagName' in node && node.namespaceURI === 'http://www.w3.org/1999/xhtml';
39
+ }
40
+ function text(root) {
41
+ return [...nodes(root)].filter((node) => node.nodeName === '#text').map(node => node.value).join('');
42
+ }
43
+ function inside(node, ancestor) {
44
+ for (let current = node; current; current = 'parentNode' in current ? current.parentNode : null) {
45
+ if (current === ancestor)
46
+ return true;
47
+ }
48
+ return false;
49
+ }
50
+ function disabled(control) {
51
+ if (attr(control, 'disabled') !== undefined)
52
+ return true;
53
+ for (let parent = control.parentNode; parent; parent = 'parentNode' in parent ? parent.parentNode : null) {
54
+ if (!element(parent))
55
+ continue;
56
+ if (parent.tagName === 'optgroup' && attr(parent, 'disabled') !== undefined)
57
+ return true;
58
+ if (parent.tagName === 'fieldset' && attr(parent, 'disabled') !== undefined) {
59
+ const legend = parent.childNodes.find(child => element(child) && child.tagName === 'legend');
60
+ if (!legend || !inside(control, legend))
61
+ return true;
62
+ }
63
+ }
64
+ return false;
65
+ }
66
+ function parsePortalPage(html) {
67
+ if (typeof html !== 'string' || Buffer.byteLength(html) > MAX_HTML_BYTES)
68
+ invalid();
69
+ return (0, parse5_1.parse)(html);
70
+ }
71
+ function htmlDocument(html) {
72
+ return typeof html === 'string' ? parsePortalPage(html) : html;
73
+ }
74
+ /** Serialize only inert successful controls; provider scripts are never executed. */
75
+ function readForm(html, name, endpoint) {
76
+ if (typeof name !== 'string' || !name || name.length > 128 || !/^[a-zA-Z][a-zA-Z0-9]*\.cgi$/.test(endpoint))
77
+ invalid();
78
+ const forms = [...nodes(htmlDocument(html))].filter((node) => element(node) && node.tagName === 'form' && attr(node, 'name') === name);
79
+ const form = forms[0];
80
+ if (forms.length !== 1 || !form)
81
+ invalid('FORM_COUNT');
82
+ if (attr(form, 'method')?.toLowerCase() !== 'post')
83
+ invalid('FORM_METHOD');
84
+ try {
85
+ if (new URL(attr(form, 'action') ?? '', PORTAL).href !== PORTAL + endpoint)
86
+ invalid('FORM_ACTION');
87
+ }
88
+ catch {
89
+ invalid('FORM_ACTION');
90
+ }
91
+ const fields = new URLSearchParams();
92
+ const append = (key, value) => {
93
+ const normalized = value.replace(/\r\n|\r|\n/g, '\r\n');
94
+ if (fields.has(key)) {
95
+ if (fields.get(key) !== normalized)
96
+ invalid('DUPLICATE_FIELD');
97
+ return;
98
+ }
99
+ fields.append(key, normalized);
100
+ };
101
+ for (const control of nodes(form)) {
102
+ if (!element(control) || disabled(control))
103
+ continue;
104
+ const key = attr(control, 'name');
105
+ if (!key || (attr(control, 'form') !== undefined && attr(control, 'form') !== attr(form, 'id')))
106
+ continue;
107
+ if (control.tagName === 'input') {
108
+ const type = attr(control, 'type')?.toLowerCase() ?? 'text';
109
+ if (['button', 'submit', 'image', 'reset', 'file'].includes(type))
110
+ continue;
111
+ if (['checkbox', 'radio'].includes(type) && attr(control, 'checked') === undefined)
112
+ continue;
113
+ append(key, attr(control, 'value') ?? (['checkbox', 'radio'].includes(type) ? 'on' : ''));
114
+ }
115
+ else if (control.tagName === 'textarea')
116
+ append(key, text(control));
117
+ else if (control.tagName === 'select') {
118
+ const options = [...nodes(control)].filter((node) => element(node) && node.tagName === 'option');
119
+ const selected = options.filter(option => attr(option, 'selected') !== undefined);
120
+ if (selected.length > 1)
121
+ invalid('SELECT_AMBIGUOUS');
122
+ const option = selected[0] ?? (attr(control, 'multiple') === undefined ? options.find(option => !disabled(option)) : undefined);
123
+ if (option && !disabled(option))
124
+ append(key, attr(option, 'value') ?? text(option).replace(/[\t\n\f\r ]+/g, ' ').replace(/^ | $/g, ''));
125
+ }
126
+ }
127
+ return fields;
128
+ }
129
+ /** Decode only the observed small JSON array declarations, never JavaScript expressions. */
130
+ function readLiteralRows(html, variable) {
131
+ if (!ROW_VARIABLES.has(variable))
132
+ invalid();
133
+ const declarations = [];
134
+ const pattern = new RegExp('(?:^|(?<=[;\\r\\n]))\\s*(?:var|let|const)\\s+' + variable + '\\s*=\\s*(\\[[\\s\\S]*?\\])\\s*(?:;|$)', 'g');
135
+ for (const node of nodes(htmlDocument(html)))
136
+ if (element(node) && node.tagName === 'script') {
137
+ for (const match of text(node).matchAll(pattern))
138
+ if (match[1])
139
+ declarations.push(match[1]);
140
+ }
141
+ const literal = declarations[0];
142
+ if (declarations.length !== 1 || !literal || Buffer.byteLength(literal) > 16 * 1024)
143
+ invalid();
144
+ let rows;
145
+ try {
146
+ rows = JSON.parse(literal);
147
+ }
148
+ catch {
149
+ invalid();
150
+ }
151
+ if (!Array.isArray(rows) || rows.length > 20 || !rows.every((row) => Array.isArray(row) && row.length > 0 && row.length <= 5 && row.every(value => typeof value === 'string' && value.length <= 200)))
152
+ invalid();
153
+ return rows;
154
+ }
155
+ /** Browser legacy form encoding differs from UTF-8 URLSearchParams for accents and € . */
156
+ function encodePortalForm(fields) {
157
+ const encode = (value) => {
158
+ let output = '';
159
+ for (const character of value) {
160
+ const byte = cp1252.get(character);
161
+ if (byte === undefined)
162
+ throw new TypeError('Texto no compatible con windows-1252');
163
+ output += byte === 0x20 ? '+' : /^[a-zA-Z0-9*._-]$/.test(character) ? character : '%' + byte.toString(16).toUpperCase().padStart(2, '0');
164
+ }
165
+ return output;
166
+ };
167
+ return [...fields].map(([key, value]) => encode(key) + '=' + encode(value)).join('&');
168
+ }
169
+ function readPortalHtml(bytes) {
170
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength > MAX_HTML_BYTES)
171
+ invalid();
172
+ return decoder.decode(bytes);
173
+ }
174
+ /** Encode unsigned XML as declared, without changing its text or silently truncating Unicode. */
175
+ function encodeUnsignedDteXml(value) {
176
+ const invalidXml = () => { throw new TypeError('XML sin firmar inválido'); };
177
+ if (typeof value !== 'string' || !value.length || value.length > invoice_xml_1.MAX_DTE_XML_BYTES)
178
+ invalidXml();
179
+ const declared = /<\?xml\b[^?]*\bencoding\s*=\s*['"]([^'"]+)['"]/i.exec(value.slice(0, 200))?.[1]?.toUpperCase() ?? 'UTF-8';
180
+ if (declared === 'ISO-8859-1') {
181
+ if (/[^\u0000-\u00ff]/u.test(value))
182
+ invalidXml();
183
+ return Buffer.from(value, 'latin1');
184
+ }
185
+ if (declared === 'UTF-8' || declared === 'UTF8') {
186
+ if (Buffer.byteLength(value, 'utf8') > invoice_xml_1.MAX_DTE_XML_BYTES)
187
+ invalidXml();
188
+ const bytes = Buffer.from(value, 'utf8');
189
+ if (bytes.toString('utf8') !== value)
190
+ invalidXml();
191
+ return bytes;
192
+ }
193
+ return invalidXml();
194
+ }
195
+ /** Read confirmation text after entity decoding; scripts and hidden payloads are not evidence. */
196
+ function readVisiblePortalText(html) {
197
+ const hiddenTags = new Set(['head', 'script', 'style', 'textarea', 'input', 'template', 'noscript']);
198
+ const blockTags = new Set(['address', 'article', 'aside', 'blockquote', 'br', 'div', 'dl', 'dt', 'dd', 'fieldset', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'li', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'td', 'th', 'tr', 'ul']);
199
+ const pending = [typeof html === 'string' ? parsePortalPage(html) : html];
200
+ const parts = [];
201
+ for (let node = pending.pop(); node !== undefined; node = pending.pop()) {
202
+ if (typeof node === 'string') {
203
+ parts.push(node);
204
+ continue;
205
+ }
206
+ if (element(node)) {
207
+ if (hiddenTags.has(node.tagName) || attr(node, 'hidden') !== undefined || attr(node, 'aria-hidden')?.toLowerCase() === 'true'
208
+ || /(?:^|;)\s*(?:display\s*:\s*none|(?:content-)?visibility\s*:\s*hidden)\s*(?:!important\s*)?(?:;|$)/i.test(attr(node, 'style') ?? ''))
209
+ continue;
210
+ if (blockTags.has(node.tagName)) {
211
+ parts.push(' ');
212
+ pending.push(' ');
213
+ }
214
+ }
215
+ if (node.nodeName === '#text' && 'value' in node)
216
+ parts.push(node.value);
217
+ if ('childNodes' in node)
218
+ for (let i = node.childNodes.length - 1; i >= 0; i--) {
219
+ const child = node.childNodes[i];
220
+ if (child)
221
+ pending.push(child);
222
+ }
223
+ }
224
+ return parts.join('').replace(/\s+/gu, ' ').trim();
225
+ }
226
+ /** A shared script or hidden v3 token field does not prove an interactive challenge. */
227
+ function hasInteractiveCaptcha(document) {
228
+ return /captcha/i.test(readVisiblePortalText(document)) || [...nodes(document)].filter(element).some(node => attr(node, 'class')?.split(/\s+/).includes('g-recaptcha')
229
+ || node.tagName === 'input' && attr(node, 'type')?.toLowerCase() !== 'hidden' && /captcha/i.test(attr(node, 'name') ?? '')
230
+ || node.tagName === 'iframe' && /\/recaptcha\/(?:api2|enterprise)\/(?:anchor|bframe)(?:[?#/]|$)/i.test(attr(node, 'src') ?? ''));
231
+ }
@@ -0,0 +1,9 @@
1
+ import { Readable } from 'node:stream';
2
+ import type { DefaultTreeAdapterTypes as Html } from 'parse5';
3
+ import type { IssuedInvoicePdfQuery } from '../contracts';
4
+ import { type SiiDiagnostics } from '../sii-error';
5
+ import { SiiHttpSession } from './sii-http-session';
6
+ /** Match the observed seven-column history, plus emitted rows with combined RUT/name. */
7
+ export declare function invoicePdfCode(document: Html.Document, { documentType, folio }: IssuedInvoicePdfQuery, supplierRut?: string): string;
8
+ /** Keep only the prefix and transport chunks; reads stop when Node applies backpressure. */
9
+ export declare function readInvoicePdfStream(response: Response, session: SiiHttpSession, endpoint: SiiDiagnostics['endpoint'], signal: AbortSignal, trackStream: (stream: Readable) => void): Promise<Readable>;
@@ -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
+ }