@devly-cl/sii-client 0.4.4 → 0.5.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.
@@ -1,11 +1,11 @@
1
- export type TipoFacturaEmitida = 33 | 34;
2
- export interface ConsultaFacturasEmitidas {
1
+ export type InvoiceDocumentType = 33 | 34;
2
+ export interface IssuedInvoicesQuery {
3
3
  periodo: string;
4
4
  tokenRecaptcha?: string;
5
5
  }
6
- export interface FacturaEmitida {
6
+ export interface IssuedInvoice {
7
7
  issuerRut: string;
8
- documentType: TipoFacturaEmitida;
8
+ documentType: InvoiceDocumentType;
9
9
  folio: string;
10
10
  issuedDate: string;
11
11
  receiverRut: string;
@@ -17,12 +17,20 @@ export interface FacturaEmitida {
17
17
  siiBranchCode: string | null;
18
18
  rcvPeriod: string;
19
19
  }
20
- export interface ResultadoFacturasEmitidas {
21
- data: FacturaEmitida[];
20
+ export interface IssuedInvoicesResult {
21
+ data: IssuedInvoice[];
22
22
  complete: boolean;
23
23
  expectedCount: number;
24
24
  observedAt: string;
25
- incompleteDocumentTypes: TipoFacturaEmitida[];
25
+ incompleteDocumentTypes: InvoiceDocumentType[];
26
26
  }
27
+ /** @deprecated Use InvoiceDocumentType. */
28
+ export type TipoFacturaEmitida = InvoiceDocumentType;
29
+ /** @deprecated Use IssuedInvoicesQuery. */
30
+ export type ConsultaFacturasEmitidas = IssuedInvoicesQuery;
31
+ /** @deprecated Use IssuedInvoice. */
32
+ export type FacturaEmitida = IssuedInvoice;
33
+ /** @deprecated Use IssuedInvoicesResult. */
34
+ export type ResultadoFacturasEmitidas = IssuedInvoicesResult;
27
35
  /** Campos del proveedor validados; emisor y periodo vienen de la consulta autorizada. */
28
- export declare function normalizeIssuedInvoice(row: Record<string, unknown>, issuerRut: string, period: string, type: TipoFacturaEmitida): FacturaEmitida;
36
+ export declare function normalizeIssuedInvoice(row: Record<string, unknown>, issuerRut: string, period: string, type: InvoiceDocumentType): IssuedInvoice;
@@ -1,10 +1,16 @@
1
- import { type ConsultaFacturasEmitidas, type FacturaEmitida, type ResultadoFacturasEmitidas, type TipoFacturaEmitida } from './issued-invoice';
2
- export type ConsultaFacturasRecibidas = ConsultaFacturasEmitidas;
3
- export interface FacturaRecibida extends FacturaEmitida {
1
+ import { type IssuedInvoicesQuery, type IssuedInvoice, type IssuedInvoicesResult, type InvoiceDocumentType } from './issued-invoice';
2
+ export type ReceivedInvoicesQuery = IssuedInvoicesQuery;
3
+ export interface ReceivedInvoice extends IssuedInvoice {
4
4
  issuerName: string | null;
5
5
  }
6
- export interface ResultadoFacturasRecibidas extends Omit<ResultadoFacturasEmitidas, 'data'> {
7
- data: FacturaRecibida[];
6
+ export interface ReceivedInvoicesResult extends Omit<IssuedInvoicesResult, 'data'> {
7
+ data: ReceivedInvoice[];
8
8
  }
9
+ /** @deprecated Use ReceivedInvoicesQuery. */
10
+ export type ConsultaFacturasRecibidas = ReceivedInvoicesQuery;
11
+ /** @deprecated Use ReceivedInvoice. */
12
+ export type FacturaRecibida = ReceivedInvoice;
13
+ /** @deprecated Use ReceivedInvoicesResult. */
14
+ export type ResultadoFacturasRecibidas = ReceivedInvoicesResult;
9
15
  /** 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: TipoFacturaEmitida): FacturaRecibida;
16
+ export declare function normalizeReceivedInvoice(row: Record<string, unknown>, receiverRut: string, period: string, type: InvoiceDocumentType): ReceivedInvoice;
@@ -1,6 +1,6 @@
1
- declare const STAGES: readonly ["AUTHENTICATION", "SESSION_CHECK", "COMPANY_AUTHORIZATION", "RCV_INITIALIZATION", "RCV_SUMMARY", "RCV_DETAIL", "XML_COMPANY_SELECTION", "XML_DOWNLOAD", "XML_PARSE", "LOGOUT"];
2
- declare const ENDPOINTS: readonly ["CAutInicio.cgi", "aaSessionService/load", "getDcvEmpresasAutorizadas", "getDatosInicio", "getResumen", "getDetalleCompra", "getDetalleVenta", "mipeSelEmpresa.cgi", "mipeLaunchPage.cgi", "mipeDownLoad.cgi", "autTermino.cgi"];
3
- declare const REASONS: readonly ["DOCUMENT_LIMIT_EXCEEDED", "DOCUMENT_NOT_FOUND", "EMPTY_RESPONSE", "HTML_RESPONSE", "PROVIDER_ERROR_PAGE", "UNEXPECTED_PDF", "UNEXPECTED_ARCHIVE", "UNEXPECTED_FORMAT", "INVALID_XML", "XML_IDENTITY_MISMATCH", "RESPONSE_TOO_LARGE", "HTTP_ERROR", "TIMEOUT", "TRANSPORT_ERROR", "RETRY_LATER", "CAPTCHA_REQUIRED", "SESSION_REQUIRED", "LOGIN_NOT_CONFIRMED", "PERSONAL_SESSION_REQUIRED", "SESSION_IDENTITY_MISMATCH", "COMPANY_NOT_AUTHORIZED", "COMPANY_SELECTION_REQUIRED", "PROVIDER_REJECTED", "INVALID_RESPONSE"];
1
+ declare const STAGES: readonly ["AUTHENTICATION", "SESSION_CHECK", "COMPANY_AUTHORIZATION", "RCV_INITIALIZATION", "RCV_SUMMARY", "RCV_DETAIL", "XML_COMPANY_SELECTION", "XML_DOWNLOAD", "XML_PARSE", "LOGOUT", "DOCUMENT_PREPARATION", "DOCUMENT_REVIEW", "DOCUMENT_SIGNING", "DOCUMENT_SEND", "DOCUMENT_RECOVERY"];
2
+ declare const ENDPOINTS: readonly ["CAutInicio.cgi", "aaSessionService/load", "getDcvEmpresasAutorizadas", "getDatosInicio", "getResumen", "getDetalleCompra", "getDetalleVenta", "mipeSelEmpresa.cgi", "mipeLaunchPage.cgi", "mipeDownLoad.cgi", "autTermino.cgi", "mipeGenFacEx.cgi", "mipeDisplayPreView.cgi", "mipeGenXMLFirma.cgi", "getCertDigital.cgi", "postFirmaDigital.cgi", "mipeSendXML.cgi", "mipeAdminDocsEmi.cgi", "mipeGesDocEmi.cgi", "mipeDisplayPDF.cgi"];
3
+ declare const REASONS: readonly ["DOCUMENT_LIMIT_EXCEEDED", "DOCUMENT_NOT_FOUND", "EMPTY_RESPONSE", "HTML_RESPONSE", "PROVIDER_ERROR_PAGE", "UNEXPECTED_PDF", "UNEXPECTED_ARCHIVE", "UNEXPECTED_FORMAT", "INVALID_XML", "XML_IDENTITY_MISMATCH", "RESPONSE_TOO_LARGE", "HTTP_ERROR", "TIMEOUT", "TRANSPORT_ERROR", "RETRY_LATER", "CAPTCHA_REQUIRED", "SESSION_REQUIRED", "LOGIN_NOT_CONFIRMED", "PERSONAL_SESSION_REQUIRED", "SESSION_IDENTITY_MISMATCH", "COMPANY_NOT_AUTHORIZED", "COMPANY_SELECTION_REQUIRED", "PROVIDER_REJECTED", "INVALID_RESPONSE", "DOCUMENT_CONTENT_MISMATCH", "CERTIFICATE_UNAVAILABLE", "CERTIFICATE_PASSWORD_INVALID", "CERTIFICATE_EXPIRED", "CERTIFICATE_REVOKED", "SIGNATURE_INVALID", "ISSUANCE_OUTCOME_UNKNOWN"];
4
4
  declare const RESPONSE_TYPES: readonly ["XML", "HTML", "PDF", "ZIP", "JSON", "EMPTY", "UNKNOWN"];
5
5
  declare const CONTENT_TYPES: readonly ["application/xml", "text/xml", "application/octet-stream", "text/html", "application/pdf", "application/zip", "application/json", "text/plain"];
6
6
  export interface SiiDiagnostics {
@@ -2,9 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SiiError = void 0;
4
4
  exports.sanitizeSiiDiagnostics = sanitizeSiiDiagnostics;
5
- const STAGES = ['AUTHENTICATION', 'SESSION_CHECK', 'COMPANY_AUTHORIZATION', 'RCV_INITIALIZATION', 'RCV_SUMMARY', 'RCV_DETAIL', 'XML_COMPANY_SELECTION', 'XML_DOWNLOAD', 'XML_PARSE', 'LOGOUT'];
6
- const ENDPOINTS = ['CAutInicio.cgi', 'aaSessionService/load', 'getDcvEmpresasAutorizadas', 'getDatosInicio', 'getResumen', 'getDetalleCompra', 'getDetalleVenta', 'mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi', 'mipeDownLoad.cgi', 'autTermino.cgi'];
7
- const REASONS = ['DOCUMENT_LIMIT_EXCEEDED', 'DOCUMENT_NOT_FOUND', 'EMPTY_RESPONSE', 'HTML_RESPONSE', 'PROVIDER_ERROR_PAGE', 'UNEXPECTED_PDF', 'UNEXPECTED_ARCHIVE', 'UNEXPECTED_FORMAT', 'INVALID_XML', 'XML_IDENTITY_MISMATCH', 'RESPONSE_TOO_LARGE', 'HTTP_ERROR', 'TIMEOUT', 'TRANSPORT_ERROR', 'RETRY_LATER', 'CAPTCHA_REQUIRED', 'SESSION_REQUIRED', 'LOGIN_NOT_CONFIRMED', 'PERSONAL_SESSION_REQUIRED', 'SESSION_IDENTITY_MISMATCH', 'COMPANY_NOT_AUTHORIZED', 'COMPANY_SELECTION_REQUIRED', 'PROVIDER_REJECTED', 'INVALID_RESPONSE'];
5
+ const STAGES = ['AUTHENTICATION', 'SESSION_CHECK', 'COMPANY_AUTHORIZATION', 'RCV_INITIALIZATION', 'RCV_SUMMARY', 'RCV_DETAIL', 'XML_COMPANY_SELECTION', 'XML_DOWNLOAD', 'XML_PARSE', 'LOGOUT', 'DOCUMENT_PREPARATION', 'DOCUMENT_REVIEW', 'DOCUMENT_SIGNING', 'DOCUMENT_SEND', 'DOCUMENT_RECOVERY'];
6
+ const ENDPOINTS = ['CAutInicio.cgi', 'aaSessionService/load', 'getDcvEmpresasAutorizadas', 'getDatosInicio', 'getResumen', 'getDetalleCompra', 'getDetalleVenta', 'mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi', 'mipeDownLoad.cgi', 'autTermino.cgi', 'mipeGenFacEx.cgi', 'mipeDisplayPreView.cgi', 'mipeGenXMLFirma.cgi', 'getCertDigital.cgi', 'postFirmaDigital.cgi', 'mipeSendXML.cgi', 'mipeAdminDocsEmi.cgi', 'mipeGesDocEmi.cgi', 'mipeDisplayPDF.cgi'];
7
+ const REASONS = ['DOCUMENT_LIMIT_EXCEEDED', 'DOCUMENT_NOT_FOUND', 'EMPTY_RESPONSE', 'HTML_RESPONSE', 'PROVIDER_ERROR_PAGE', 'UNEXPECTED_PDF', 'UNEXPECTED_ARCHIVE', 'UNEXPECTED_FORMAT', 'INVALID_XML', 'XML_IDENTITY_MISMATCH', 'RESPONSE_TOO_LARGE', 'HTTP_ERROR', 'TIMEOUT', 'TRANSPORT_ERROR', 'RETRY_LATER', 'CAPTCHA_REQUIRED', 'SESSION_REQUIRED', 'LOGIN_NOT_CONFIRMED', 'PERSONAL_SESSION_REQUIRED', 'SESSION_IDENTITY_MISMATCH', 'COMPANY_NOT_AUTHORIZED', 'COMPANY_SELECTION_REQUIRED', 'PROVIDER_REJECTED', 'INVALID_RESPONSE', 'DOCUMENT_CONTENT_MISMATCH', 'CERTIFICATE_UNAVAILABLE', 'CERTIFICATE_PASSWORD_INVALID', 'CERTIFICATE_EXPIRED', 'CERTIFICATE_REVOKED', 'SIGNATURE_INVALID', 'ISSUANCE_OUTCOME_UNKNOWN'];
8
8
  const RESPONSE_TYPES = ['XML', 'HTML', 'PDF', 'ZIP', 'JSON', 'EMPTY', 'UNKNOWN'];
9
9
  const CONTENT_TYPES = ['application/xml', 'text/xml', 'application/octet-stream', 'text/html', 'application/pdf', 'application/zip', 'application/json', 'text/plain'];
10
10
  function member(values, value) {
@@ -32,6 +32,7 @@ const STAGE_LABELS = {
32
32
  AUTHENTICATION: 'inicio de sesión', SESSION_CHECK: 'validación de sesión', COMPANY_AUTHORIZATION: 'autorización de empresa',
33
33
  RCV_INITIALIZATION: 'inicio del RCV', RCV_SUMMARY: 'resumen del RCV', RCV_DETAIL: 'detalle del RCV',
34
34
  XML_COMPANY_SELECTION: 'selección de empresa en el facturador', XML_DOWNLOAD: 'descarga del XML', XML_PARSE: 'validación del XML', LOGOUT: 'cierre de sesión',
35
+ DOCUMENT_PREPARATION: 'preparación del documento', DOCUMENT_REVIEW: 'revisión del documento', DOCUMENT_SIGNING: 'firma del documento', DOCUMENT_SEND: 'envío del documento', DOCUMENT_RECOVERY: 'recuperación del documento emitido',
35
36
  };
36
37
  const REASON_LABELS = {
37
38
  DOCUMENT_LIMIT_EXCEEDED: 'SII rechazó la consulta porque devuelve demasiados documentos. No confirmó si el XML individual está disponible.',
@@ -51,7 +52,12 @@ const REASON_LABELS = {
51
52
  LOGIN_NOT_CONFIRMED: 'SII no confirmó el inicio de sesión.', PERSONAL_SESSION_REQUIRED: 'SII no confirmó una sesión personal.',
52
53
  SESSION_IDENTITY_MISMATCH: 'La sesión de SII no corresponde al usuario solicitado.', COMPANY_NOT_AUTHORIZED: 'SII no autorizó el acceso a la empresa solicitada.',
53
54
  COMPANY_SELECTION_REQUIRED: 'SII no confirmó la selección de empresa en el facturador.',
54
- PROVIDER_REJECTED: 'SII rechazó la consulta del RCV.', INVALID_RESPONSE: 'SII devolvió una respuesta que no cumple el contrato esperado.',
55
+ PROVIDER_REJECTED: 'SII rechazó la solicitud.', INVALID_RESPONSE: 'SII devolvió una respuesta que no cumple el contrato esperado.',
56
+ DOCUMENT_CONTENT_MISMATCH: 'El contenido fiscal recibido difiere del contenido aprobado. No se envió el documento.',
57
+ CERTIFICATE_UNAVAILABLE: 'SII no devolvió un certificado centralizado utilizable para esta identidad.',
58
+ CERTIFICATE_PASSWORD_INVALID: 'SII rechazó la clave del certificado centralizado.', CERTIFICATE_EXPIRED: 'El certificado centralizado está expirado.', CERTIFICATE_REVOKED: 'El certificado centralizado está revocado.',
59
+ SIGNATURE_INVALID: 'SII no devolvió un XML firmado válido para el documento aprobado. No se envió.',
60
+ ISSUANCE_OUTCOME_UNKNOWN: 'El envío comenzó pero no se confirmó su resultado. Conserve el XML y consulte el historial antes de volver a emitir; repetir puede duplicar el documento.',
55
61
  };
56
62
  class SiiError extends Error {
57
63
  code;
package/dist/index.d.ts CHANGED
@@ -2,8 +2,16 @@ export { SiiClient, SiiError } from './infrastructure/sii-client';
2
2
  export { sanitizeSiiDiagnostics } from './domain/sii-error';
3
3
  export type { SiiDiagnostics } from './domain/sii-error';
4
4
  export { parseRut } from './domain/rut';
5
- export { parseDteXml, DteXmlError, MAX_DTE_XML_BYTES } from './domain/invoice-xml';
5
+ export { validateInvoice, calculateInvoiceTotals, hashContent, validarFactura, calcularTotalesFactura, hashContenido } from './domain/invoicing';
6
+ export type { InvoiceInput, InvoiceLineInput, InvoiceTotals, EntradaFactura, LineaFactura, TotalesFactura } from './domain/invoicing';
7
+ export type { DocumentoPreparado, DocumentoFirmado, DocumentoEnviado, FirmaDocumento } from './infrastructure/sii-client';
8
+ export { parseDteXml, parseDteDocumentXml, DteXmlError, MAX_DTE_XML_BYTES } from './domain/invoice-xml';
6
9
  export type { ConsultaXmlFacturaEmitida, ConsultaXmlFacturaRecibida, DteInvoiceLine, DteInvoiceDetail, ResultadoXmlFacturaEmitida } from './domain/invoice-xml';
10
+ export type { TipoDocumentoEmitido, ConsultaXmlDocumentoEmitido, DteDocumentDetail, ResultadoXmlDocumentoEmitido } from './domain/invoice-xml';
7
11
  export type { ConsultaFacturasEmitidas, FacturaEmitida, ResultadoFacturasEmitidas, TipoFacturaEmitida } from './domain/issued-invoice';
8
12
  export type { ConsultaFacturasRecibidas, FacturaRecibida, ResultadoFacturasRecibidas } from './domain/received-invoice';
9
13
  export type { ConsultaResumen, CredencialesSii, EmpresaAutorizada, EstadoCompra, Operacion, RegistroSii, RespuestaSii, SesionSii, SiiClientOptions, } from './infrastructure/sii-client';
14
+ export type { SummaryQuery, SiiCredentials, SiiSession, Operation, PurchaseStatus, SiiRecord, SiiResponse, AuthorizedCompany, PreparedDocument, SignedDocument, SentDocument, SignDocumentInput, } from './infrastructure/sii-client';
15
+ export type { IssuedInvoicesQuery, IssuedInvoice, IssuedInvoicesResult, InvoiceDocumentType, } from './domain/issued-invoice';
16
+ export type { ReceivedInvoicesQuery, ReceivedInvoice, ReceivedInvoicesResult, } from './domain/received-invoice';
17
+ export type { IssuedInvoiceXmlQuery, ReceivedInvoiceXmlQuery, InvoiceXmlResult, IssuedDocumentType, IssuedDocumentXmlQuery, IssuedDocumentXmlResult, } from './domain/invoice-xml';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MAX_DTE_XML_BYTES = exports.DteXmlError = exports.parseDteXml = exports.parseRut = exports.sanitizeSiiDiagnostics = exports.SiiError = exports.SiiClient = void 0;
3
+ exports.MAX_DTE_XML_BYTES = exports.DteXmlError = exports.parseDteDocumentXml = exports.parseDteXml = exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = exports.hashContent = exports.calculateInvoiceTotals = exports.validateInvoice = exports.parseRut = exports.sanitizeSiiDiagnostics = exports.SiiError = exports.SiiClient = void 0;
4
4
  var sii_client_1 = require("./infrastructure/sii-client");
5
5
  Object.defineProperty(exports, "SiiClient", { enumerable: true, get: function () { return sii_client_1.SiiClient; } });
6
6
  Object.defineProperty(exports, "SiiError", { enumerable: true, get: function () { return sii_client_1.SiiError; } });
@@ -8,7 +8,15 @@ var sii_error_1 = require("./domain/sii-error");
8
8
  Object.defineProperty(exports, "sanitizeSiiDiagnostics", { enumerable: true, get: function () { return sii_error_1.sanitizeSiiDiagnostics; } });
9
9
  var rut_1 = require("./domain/rut");
10
10
  Object.defineProperty(exports, "parseRut", { enumerable: true, get: function () { return rut_1.parseRut; } });
11
+ var invoicing_1 = require("./domain/invoicing");
12
+ Object.defineProperty(exports, "validateInvoice", { enumerable: true, get: function () { return invoicing_1.validateInvoice; } });
13
+ Object.defineProperty(exports, "calculateInvoiceTotals", { enumerable: true, get: function () { return invoicing_1.calculateInvoiceTotals; } });
14
+ Object.defineProperty(exports, "hashContent", { enumerable: true, get: function () { return invoicing_1.hashContent; } });
15
+ Object.defineProperty(exports, "validarFactura", { enumerable: true, get: function () { return invoicing_1.validarFactura; } });
16
+ Object.defineProperty(exports, "calcularTotalesFactura", { enumerable: true, get: function () { return invoicing_1.calcularTotalesFactura; } });
17
+ Object.defineProperty(exports, "hashContenido", { enumerable: true, get: function () { return invoicing_1.hashContenido; } });
11
18
  var invoice_xml_1 = require("./domain/invoice-xml");
12
19
  Object.defineProperty(exports, "parseDteXml", { enumerable: true, get: function () { return invoice_xml_1.parseDteXml; } });
20
+ Object.defineProperty(exports, "parseDteDocumentXml", { enumerable: true, get: function () { return invoice_xml_1.parseDteDocumentXml; } });
13
21
  Object.defineProperty(exports, "DteXmlError", { enumerable: true, get: function () { return invoice_xml_1.DteXmlError; } });
14
22
  Object.defineProperty(exports, "MAX_DTE_XML_BYTES", { enumerable: true, get: function () { return invoice_xml_1.MAX_DTE_XML_BYTES; } });
@@ -0,0 +1,11 @@
1
+ /** Serialize only inert successful controls; provider scripts are never executed. */
2
+ export declare function readForm(html: string, name: string, endpoint: string): URLSearchParams;
3
+ /** Decode only the observed small JSON array declarations, never JavaScript expressions. */
4
+ export declare function readLiteralRows(html: string, variable: string): string[][];
5
+ /** Browser legacy form encoding differs from UTF-8 URLSearchParams for accents and € . */
6
+ export declare function encodePortalForm(fields: URLSearchParams): string;
7
+ export declare function readPortalHtml(bytes: Uint8Array): string;
8
+ /** Encode unsigned XML as declared, without changing its text or silently truncating Unicode. */
9
+ export declare function encodeUnsignedDteXml(value: string): Uint8Array;
10
+ /** Read confirmation text after entity decoding; scripts and hidden payloads are not evidence. */
11
+ export declare function readVisiblePortalText(html: string): string;
@@ -0,0 +1,217 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readForm = readForm;
4
+ exports.readLiteralRows = readLiteralRows;
5
+ exports.encodePortalForm = encodePortalForm;
6
+ exports.readPortalHtml = readPortalHtml;
7
+ exports.encodeUnsignedDteXml = encodeUnsignedDteXml;
8
+ exports.readVisiblePortalText = readVisiblePortalText;
9
+ const parse5_1 = require("parse5");
10
+ const invoice_xml_1 = require("../domain/invoice-xml");
11
+ const PORTAL = 'https://www1.sii.cl/cgi-bin/Portal001/';
12
+ const MAX_HTML_BYTES = 2 * 1024 * 1024;
13
+ const ROW_VARIABLES = new Set(['emisorDir', 'emisorActEco', 'recptorDir', 'recptoActEco']);
14
+ const decoder = new TextDecoder('windows-1252', { fatal: true });
15
+ const cp1252 = new Map(Array.from({ length: 256 }, (_, byte) => [decoder.decode(Uint8Array.of(byte)), byte]));
16
+ function invalid(reason = 'INVALID_RESPONSE') { throw new TypeError(`Formulario del facturador inválido: ${reason}`); }
17
+ function attr(element, name) {
18
+ return element.attrs.find(attribute => attribute.name === name)?.value;
19
+ }
20
+ function* nodes(root) {
21
+ const pending = [root];
22
+ for (let node = pending.pop(); node; node = pending.pop()) {
23
+ yield node;
24
+ if ('childNodes' in node)
25
+ for (let i = node.childNodes.length - 1; i >= 0; i--) {
26
+ const child = node.childNodes[i];
27
+ if (child)
28
+ pending.push(child);
29
+ }
30
+ }
31
+ }
32
+ function element(node) {
33
+ return 'tagName' in node && node.namespaceURI === 'http://www.w3.org/1999/xhtml';
34
+ }
35
+ function text(root) {
36
+ return [...nodes(root)].filter((node) => node.nodeName === '#text').map(node => node.value).join('');
37
+ }
38
+ function inside(node, ancestor) {
39
+ for (let current = node; current; current = 'parentNode' in current ? current.parentNode : null) {
40
+ if (current === ancestor)
41
+ return true;
42
+ }
43
+ return false;
44
+ }
45
+ function disabled(control) {
46
+ if (attr(control, 'disabled') !== undefined)
47
+ return true;
48
+ for (let parent = control.parentNode; parent; parent = 'parentNode' in parent ? parent.parentNode : null) {
49
+ if (!element(parent))
50
+ continue;
51
+ if (parent.tagName === 'optgroup' && attr(parent, 'disabled') !== undefined)
52
+ return true;
53
+ if (parent.tagName === 'fieldset' && attr(parent, 'disabled') !== undefined) {
54
+ const legend = parent.childNodes.find(child => element(child) && child.tagName === 'legend');
55
+ if (!legend || !inside(control, legend))
56
+ return true;
57
+ }
58
+ }
59
+ return false;
60
+ }
61
+ function htmlDocument(html) {
62
+ if (typeof html !== 'string' || Buffer.byteLength(html) > MAX_HTML_BYTES)
63
+ invalid();
64
+ return (0, parse5_1.parse)(html);
65
+ }
66
+ /** Serialize only inert successful controls; provider scripts are never executed. */
67
+ function readForm(html, name, endpoint) {
68
+ if (typeof name !== 'string' || !name || name.length > 128 || !/^[a-zA-Z][a-zA-Z0-9]*\.cgi$/.test(endpoint))
69
+ invalid();
70
+ const forms = [...nodes(htmlDocument(html))].filter((node) => element(node) && node.tagName === 'form' && attr(node, 'name') === name);
71
+ const form = forms[0];
72
+ if (forms.length !== 1 || !form)
73
+ invalid('FORM_COUNT');
74
+ if (attr(form, 'method')?.toLowerCase() !== 'post')
75
+ invalid('FORM_METHOD');
76
+ try {
77
+ if (new URL(attr(form, 'action') ?? '', PORTAL).href !== PORTAL + endpoint)
78
+ invalid('FORM_ACTION');
79
+ }
80
+ catch {
81
+ invalid('FORM_ACTION');
82
+ }
83
+ const fields = new URLSearchParams();
84
+ const append = (key, value) => {
85
+ const normalized = value.replace(/\r\n|\r|\n/g, '\r\n');
86
+ if (fields.has(key)) {
87
+ if (fields.get(key) !== normalized)
88
+ invalid('DUPLICATE_FIELD');
89
+ return;
90
+ }
91
+ fields.append(key, normalized);
92
+ };
93
+ for (const control of nodes(form)) {
94
+ if (!element(control) || disabled(control))
95
+ continue;
96
+ const key = attr(control, 'name');
97
+ if (!key || (attr(control, 'form') !== undefined && attr(control, 'form') !== attr(form, 'id')))
98
+ continue;
99
+ if (control.tagName === 'input') {
100
+ const type = attr(control, 'type')?.toLowerCase() ?? 'text';
101
+ if (['button', 'submit', 'image', 'reset', 'file'].includes(type))
102
+ continue;
103
+ if (['checkbox', 'radio'].includes(type) && attr(control, 'checked') === undefined)
104
+ continue;
105
+ append(key, attr(control, 'value') ?? (['checkbox', 'radio'].includes(type) ? 'on' : ''));
106
+ }
107
+ else if (control.tagName === 'textarea')
108
+ append(key, text(control));
109
+ else if (control.tagName === 'select') {
110
+ const options = [...nodes(control)].filter((node) => element(node) && node.tagName === 'option');
111
+ const selected = options.filter(option => attr(option, 'selected') !== undefined);
112
+ if (selected.length > 1)
113
+ invalid('SELECT_AMBIGUOUS');
114
+ const option = selected[0] ?? (attr(control, 'multiple') === undefined ? options.find(option => !disabled(option)) : undefined);
115
+ if (option && !disabled(option))
116
+ append(key, attr(option, 'value') ?? text(option).replace(/[\t\n\f\r ]+/g, ' ').replace(/^ | $/g, ''));
117
+ }
118
+ }
119
+ return fields;
120
+ }
121
+ /** Decode only the observed small JSON array declarations, never JavaScript expressions. */
122
+ function readLiteralRows(html, variable) {
123
+ if (!ROW_VARIABLES.has(variable))
124
+ invalid();
125
+ const declarations = [];
126
+ const pattern = new RegExp('(?:^|(?<=[;\\r\\n]))\\s*(?:var|let|const)\\s+' + variable + '\\s*=\\s*(\\[[\\s\\S]*?\\])\\s*(?:;|$)', 'g');
127
+ for (const node of nodes(htmlDocument(html)))
128
+ if (element(node) && node.tagName === 'script') {
129
+ for (const match of text(node).matchAll(pattern))
130
+ if (match[1])
131
+ declarations.push(match[1]);
132
+ }
133
+ const literal = declarations[0];
134
+ if (declarations.length !== 1 || !literal || Buffer.byteLength(literal) > 16 * 1024)
135
+ invalid();
136
+ let rows;
137
+ try {
138
+ rows = JSON.parse(literal);
139
+ }
140
+ catch {
141
+ invalid();
142
+ }
143
+ 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)))
144
+ invalid();
145
+ return rows;
146
+ }
147
+ /** Browser legacy form encoding differs from UTF-8 URLSearchParams for accents and € . */
148
+ function encodePortalForm(fields) {
149
+ const encode = (value) => {
150
+ let output = '';
151
+ for (const character of value) {
152
+ const byte = cp1252.get(character);
153
+ if (byte === undefined)
154
+ throw new TypeError('Texto no compatible con windows-1252');
155
+ output += byte === 0x20 ? '+' : /^[a-zA-Z0-9*._-]$/.test(character) ? character : '%' + byte.toString(16).toUpperCase().padStart(2, '0');
156
+ }
157
+ return output;
158
+ };
159
+ return [...fields].map(([key, value]) => encode(key) + '=' + encode(value)).join('&');
160
+ }
161
+ function readPortalHtml(bytes) {
162
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength > MAX_HTML_BYTES)
163
+ invalid();
164
+ return decoder.decode(bytes);
165
+ }
166
+ /** Encode unsigned XML as declared, without changing its text or silently truncating Unicode. */
167
+ function encodeUnsignedDteXml(value) {
168
+ const invalidXml = () => { throw new TypeError('XML sin firmar inválido'); };
169
+ if (typeof value !== 'string' || !value.length || value.length > invoice_xml_1.MAX_DTE_XML_BYTES)
170
+ invalidXml();
171
+ const declared = /<\?xml\b[^?]*\bencoding\s*=\s*['"]([^'"]+)['"]/i.exec(value.slice(0, 200))?.[1]?.toUpperCase() ?? 'UTF-8';
172
+ if (declared === 'ISO-8859-1') {
173
+ if (/[^\u0000-\u00ff]/u.test(value))
174
+ invalidXml();
175
+ return Buffer.from(value, 'latin1');
176
+ }
177
+ if (declared === 'UTF-8' || declared === 'UTF8') {
178
+ if (Buffer.byteLength(value, 'utf8') > invoice_xml_1.MAX_DTE_XML_BYTES)
179
+ invalidXml();
180
+ const bytes = Buffer.from(value, 'utf8');
181
+ if (bytes.toString('utf8') !== value)
182
+ invalidXml();
183
+ return bytes;
184
+ }
185
+ return invalidXml();
186
+ }
187
+ /** Read confirmation text after entity decoding; scripts and hidden payloads are not evidence. */
188
+ function readVisiblePortalText(html) {
189
+ const hiddenTags = new Set(['head', 'script', 'style', 'textarea', 'input', 'template', 'noscript']);
190
+ 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']);
191
+ const pending = [htmlDocument(html)];
192
+ const parts = [];
193
+ for (let node = pending.pop(); node !== undefined; node = pending.pop()) {
194
+ if (typeof node === 'string') {
195
+ parts.push(node);
196
+ continue;
197
+ }
198
+ if (element(node)) {
199
+ if (hiddenTags.has(node.tagName) || attr(node, 'hidden') !== undefined || attr(node, 'aria-hidden')?.toLowerCase() === 'true'
200
+ || /(?:^|;)\s*(?:display\s*:\s*none|(?:content-)?visibility\s*:\s*hidden)\s*(?:!important\s*)?(?:;|$)/i.test(attr(node, 'style') ?? ''))
201
+ continue;
202
+ if (blockTags.has(node.tagName)) {
203
+ parts.push(' ');
204
+ pending.push(' ');
205
+ }
206
+ }
207
+ if (node.nodeName === '#text' && 'value' in node)
208
+ parts.push(node.value);
209
+ if ('childNodes' in node)
210
+ for (let i = node.childNodes.length - 1; i >= 0; i--) {
211
+ const child = node.childNodes[i];
212
+ if (child)
213
+ pending.push(child);
214
+ }
215
+ }
216
+ return parts.join('').replace(/\s+/gu, ' ').trim();
217
+ }
@@ -1,11 +1,13 @@
1
1
  export { SiiError } from '../domain/sii-error';
2
- import { type ConsultaFacturasEmitidas, type ResultadoFacturasEmitidas } from '../domain/issued-invoice';
3
- import { type ConsultaFacturasRecibidas, type ResultadoFacturasRecibidas } from '../domain/received-invoice';
4
- import { type ConsultaXmlFacturaEmitida, type ConsultaXmlFacturaRecibida, type ResultadoXmlFacturaEmitida } from '../domain/invoice-xml';
5
- export type Operacion = 'COMPRA' | 'VENTA';
6
- export type EstadoCompra = 'REGISTRO' | 'PENDIENTE' | 'NO_INCLUIR' | 'RECLAMADO';
7
- export type RegistroSii = Record<string, unknown>;
8
- export interface RespuestaSii<T = RegistroSii> {
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> {
9
11
  data: T[];
10
12
  metaData: Record<string, unknown>;
11
13
  respEstado: {
@@ -15,7 +17,7 @@ export interface RespuestaSii<T = RegistroSii> {
15
17
  };
16
18
  [key: string]: unknown;
17
19
  }
18
- export interface EmpresaAutorizada extends RegistroSii {
20
+ export interface AuthorizedCompany extends SiiRecord {
19
21
  usrEmpRut: number;
20
22
  usrEmpDv: string;
21
23
  usrEmpRutDv: string;
@@ -26,33 +28,128 @@ export interface SiiClientOptions {
26
28
  retries?: number;
27
29
  fetchImpl?: typeof globalThis.fetch;
28
30
  }
29
- export interface CredencialesSii {
31
+ export interface SiiCredentials {
30
32
  rut: string;
31
33
  clave: string;
32
34
  }
33
- export interface ConsultaResumen {
35
+ export interface SummaryQuery {
34
36
  periodo: string;
35
- operacion: Operacion;
36
- estado?: EstadoCompra;
37
+ operacion: Operation;
38
+ estado?: PurchaseStatus;
37
39
  }
38
- export interface SesionSii {
40
+ export interface SiiSession {
39
41
  usuarioRut: string;
40
42
  empresaRut: string;
41
43
  representacion: false;
42
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;
43
110
  /** Una instancia = una empresa y una sesión personal. Nunca comparte cookies. */
44
111
  export declare class SiiClient {
45
112
  #private;
46
113
  constructor({ empresaRut, timeoutMs, retries, fetchImpl }: SiiClientOptions);
47
- login({ rut, clave }: CredencialesSii): Promise<SesionSii>;
48
- getEmpresasAutorizadas(): Promise<RespuestaSii<EmpresaAutorizada>>;
49
- getResumen({ periodo, operacion, estado }: ConsultaResumen): Promise<RespuestaSii>;
50
- getFacturasEmitidas(input: ConsultaFacturasEmitidas): Promise<ResultadoFacturasEmitidas>;
114
+ login({ rut, clave }: SiiCredentials): Promise<SiiSession>;
115
+ getAuthorizedCompanies(): Promise<SiiResponse<AuthorizedCompany>>;
116
+ getSummary({ periodo, operacion, estado }: SummaryQuery): Promise<SiiResponse>;
117
+ getIssuedInvoices(input: IssuedInvoicesQuery): Promise<IssuedInvoicesResult>;
51
118
  /** Facturas 33/34 in the official purchase register. Does not accept, claim or move documents. */
52
- getFacturasRecibidas(input: ConsultaFacturasRecibidas): Promise<ResultadoFacturasRecibidas>;
119
+ getReceivedInvoices(input: ReceivedInvoicesQuery): Promise<ReceivedInvoicesResult>;
120
+ prepareInvoice(input: InvoiceInput): Promise<PreparedDocument>;
121
+ prepareCancellationCreditNote({ factura, issuedDate }: {
122
+ factura: IssuedInvoiceXmlQuery;
123
+ issuedDate: string;
124
+ }): Promise<PreparedDocument>;
125
+ signAndSend(input: SignDocumentInput): Promise<SentDocument>;
53
126
  /** Original DTE from the free SII facturador; RCV membership alone does not guarantee XML availability. */
54
- getXmlFacturaEmitida(input: ConsultaXmlFacturaEmitida): Promise<ResultadoXmlFacturaEmitida>;
55
- getXmlFacturaRecibida(input: ConsultaXmlFacturaRecibida): Promise<ResultadoXmlFacturaEmitida>;
127
+ getIssuedInvoiceXml(input: IssuedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
128
+ getReceivedInvoiceXml(input: ReceivedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
129
+ getIssuedDocumentXml(input: IssuedDocumentXmlQuery): Promise<IssuedDocumentXmlResult>;
130
+ /** @deprecated Use getAuthorizedCompanies. */
131
+ getEmpresasAutorizadas(): Promise<SiiResponse<AuthorizedCompany>>;
132
+ /** @deprecated Use getSummary. */
133
+ getResumen(input: SummaryQuery): Promise<SiiResponse>;
134
+ /** @deprecated Use getIssuedInvoices. */
135
+ getFacturasEmitidas(input: IssuedInvoicesQuery): Promise<IssuedInvoicesResult>;
136
+ /** @deprecated Use getReceivedInvoices. */
137
+ getFacturasRecibidas(input: ReceivedInvoicesQuery): Promise<ReceivedInvoicesResult>;
138
+ /** @deprecated Use getIssuedInvoiceXml. */
139
+ getXmlFacturaEmitida(input: IssuedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
140
+ /** @deprecated Use getReceivedInvoiceXml. */
141
+ getXmlFacturaRecibida(input: ReceivedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
142
+ /** @deprecated Use getIssuedDocumentXml. */
143
+ getXmlDocumentoEmitido(input: IssuedDocumentXmlQuery): Promise<IssuedDocumentXmlResult>;
144
+ /** @deprecated Use prepareInvoice. */
145
+ prepararFactura(input: InvoiceInput): Promise<PreparedDocument>;
146
+ /** @deprecated Use prepareCancellationCreditNote. */
147
+ prepararNotaCreditoAnulacion(input: {
148
+ factura: IssuedInvoiceXmlQuery;
149
+ issuedDate: string;
150
+ }): Promise<PreparedDocument>;
151
+ /** @deprecated Use signAndSend. */
152
+ firmarYEnviar(input: SignDocumentInput): Promise<SentDocument>;
56
153
  /** Cierra esta sesión remota antes de descartar cookies; siempre esperar en finally. */
57
154
  dispose(): Promise<void>;
58
155
  }