@devlas/dte-sii 2.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.
Files changed (60) hide show
  1. package/BoletaService.js +109 -0
  2. package/CAF.js +173 -0
  3. package/CafSolicitor.js +380 -0
  4. package/Certificado.js +123 -0
  5. package/ConsumoFolio.js +376 -0
  6. package/DTE.js +399 -0
  7. package/EnviadorSII.js +1304 -0
  8. package/Envio.js +196 -0
  9. package/FolioRegistry.js +553 -0
  10. package/FolioService.js +703 -0
  11. package/LICENSE +27 -0
  12. package/LibroBase.js +134 -0
  13. package/LibroCompraVenta.js +205 -0
  14. package/LibroGuia.js +225 -0
  15. package/README.md +239 -0
  16. package/Signer.js +94 -0
  17. package/SiiCertificacion.js +1189 -0
  18. package/SiiPortalAuth.js +460 -0
  19. package/SiiSession.js +499 -0
  20. package/cert/BoletaCert.js +731 -0
  21. package/cert/CertFolioHelper.js +185 -0
  22. package/cert/CertRunner.js +2658 -0
  23. package/cert/ConfigLoader.js +133 -0
  24. package/cert/IntercambioCert.js +429 -0
  25. package/cert/LibroCompras.js +359 -0
  26. package/cert/LibroGuias.js +171 -0
  27. package/cert/LibroVentas.js +153 -0
  28. package/cert/MuestrasImpresas.js +676 -0
  29. package/cert/SetBase.js +321 -0
  30. package/cert/SetBasico.js +413 -0
  31. package/cert/SetCompra.js +472 -0
  32. package/cert/SetExenta.js +490 -0
  33. package/cert/SetGuia.js +283 -0
  34. package/cert/SetParser.js +1184 -0
  35. package/cert/SetsProvider.js +499 -0
  36. package/cert/Simulacion.js +521 -0
  37. package/cert/comunaOficina.js +460 -0
  38. package/cert/index.js +124 -0
  39. package/cert/types.js +330 -0
  40. package/dte-sii.d.ts +458 -0
  41. package/index.js +428 -0
  42. package/package.json +48 -0
  43. package/utils/c14n.js +275 -0
  44. package/utils/calculo.js +396 -0
  45. package/utils/config.js +276 -0
  46. package/utils/constants.js +302 -0
  47. package/utils/emisor.js +174 -0
  48. package/utils/endpoints.js +225 -0
  49. package/utils/error.js +235 -0
  50. package/utils/index.js +339 -0
  51. package/utils/logger.js +239 -0
  52. package/utils/pfx.js +203 -0
  53. package/utils/receptor.js +218 -0
  54. package/utils/referencia.js +169 -0
  55. package/utils/resolucion.js +119 -0
  56. package/utils/rut.js +169 -0
  57. package/utils/sanitize.js +124 -0
  58. package/utils/tokenCache.js +214 -0
  59. package/utils/xml.js +358 -0
  60. package/utils.js +4 -0
package/utils/index.js ADDED
@@ -0,0 +1,339 @@
1
+ // Copyright (c) 2026 Devlas SpA — https://devlas.cl
2
+ // Licencia MIT. Ver archivo LICENSE para mas detalles.
3
+ /**
4
+ * Utilidades Index
5
+ *
6
+ * Re-exporta todas las utilidades desde un punto central
7
+ *
8
+ * @module dte-sii/utils
9
+ */
10
+
11
+ // Logger
12
+ const {
13
+ logger,
14
+ LOG_LEVELS,
15
+ configureLogger,
16
+ silenceLogger,
17
+ enableLogger,
18
+ getLoggerConfig,
19
+ createScopedLogger,
20
+ } = require('./logger');
21
+
22
+ // Configuración global
23
+ const {
24
+ getConfig,
25
+ getConfigSection,
26
+ configure,
27
+ configureRetry,
28
+ configureTokenCache,
29
+ configureTimeout,
30
+ resetConfig,
31
+ configureForProduction,
32
+ configureForDevelopment,
33
+ calculateRetryDelay,
34
+ isRetryableError,
35
+ isRetryableStatus,
36
+ withRetry,
37
+ DEFAULT_CONFIG,
38
+ } = require('./config');
39
+
40
+ // Token Cache
41
+ const {
42
+ getCachedToken,
43
+ setCachedToken,
44
+ invalidateToken,
45
+ invalidateAmbiente,
46
+ invalidateEmisor,
47
+ clearTokenCache,
48
+ getTokenCacheStats,
49
+ pruneExpiredTokens,
50
+ } = require('./tokenCache');
51
+
52
+ // Sanitización
53
+ const {
54
+ sanitizeSiiText,
55
+ truncateText,
56
+ sanitizeGiroRecep,
57
+ sanitizeRazonSocial,
58
+ sanitizeNombreItem,
59
+ sanitizeDescripcionItem,
60
+ safeSegment,
61
+ } = require('./sanitize');
62
+
63
+ // RUT
64
+ const {
65
+ formatRut,
66
+ cleanRut,
67
+ splitRut,
68
+ formatRutWithDots,
69
+ formatRutSii,
70
+ calcularDV,
71
+ validarRut,
72
+ validateAndFormatRut,
73
+ } = require('./rut');
74
+
75
+ // XML
76
+ const {
77
+ formatBase64InXml,
78
+ expandSelfClosingTags,
79
+ normalizeArray,
80
+ extractEnvioMetadata,
81
+ saveEnvioArtifacts,
82
+ // Nuevas funciones centralizadas
83
+ parseXml,
84
+ parseXmlNoNs,
85
+ buildXml,
86
+ decodeXmlEntities,
87
+ extractTagContent,
88
+ extractAttribute,
89
+ defaultParser,
90
+ noNsParser,
91
+ defaultBuilder,
92
+ prettyBuilder,
93
+ } = require('./xml');
94
+
95
+ // Resolución SII
96
+ const {
97
+ normalizeFechaResolucion,
98
+ createResolucion,
99
+ createResolucionCertificacion,
100
+ createResolucionProduccion,
101
+ validarResolucion,
102
+ } = require('./resolucion');
103
+
104
+ // Cálculo
105
+ const {
106
+ TASA_IVA_DEFAULT,
107
+ formatDecimal,
108
+ calcularMontoItem,
109
+ calcularTotalesDesdeItems,
110
+ calcularTotalesDesdeDetalle,
111
+ buildDetalle,
112
+ buildDetalleGuia,
113
+ buildDetalleCompra,
114
+ buildDescuentoGlobal,
115
+ } = require('./calculo');
116
+
117
+ // Referencia
118
+ const {
119
+ buildSetReferencia,
120
+ buildDocReferencia,
121
+ buildAnulacionReferencia,
122
+ buildCorreccionTextoReferencia,
123
+ buildCorreccionMontosReferencia,
124
+ buildReferenciasNcNd,
125
+ CODIGOS_REFERENCIA,
126
+ } = require('./referencia');
127
+
128
+ // Emisor
129
+ const {
130
+ buildEmisor,
131
+ buildEmisorBoleta,
132
+ normalizeEmisor,
133
+ validarEmisor,
134
+ } = require('./emisor');
135
+
136
+ // Receptor
137
+ const {
138
+ RUT_CONSUMIDOR_FINAL,
139
+ RECEPTOR_CONSUMIDOR_FINAL,
140
+ buildReceptor,
141
+ buildReceptorBoleta,
142
+ buildReceptorConsumidorFinal,
143
+ normalizeReceptor,
144
+ validarReceptor,
145
+ esConsumidorFinal,
146
+ } = require('./receptor');
147
+
148
+ // Errores
149
+ const {
150
+ DteSiiError,
151
+ ERROR_CODES,
152
+ configError,
153
+ certError,
154
+ cafError,
155
+ dteError,
156
+ siiError,
157
+ xmlError,
158
+ wrapError,
159
+ } = require('./error');
160
+
161
+ // Endpoints centralizados
162
+ const endpoints = require('./endpoints');
163
+
164
+ // Constantes DTE
165
+ const constants = require('./constants');
166
+
167
+ // PFX Loader
168
+ const pfx = require('./pfx');
169
+
170
+ // ============================================
171
+ // EXPORTS
172
+ // ============================================
173
+
174
+ module.exports = {
175
+ // ─────────────────────────────────────────
176
+ // Sanitización
177
+ // ─────────────────────────────────────────
178
+ sanitizeSiiText,
179
+ truncateText,
180
+ sanitizeGiroRecep,
181
+ sanitizeRazonSocial,
182
+ sanitizeNombreItem,
183
+ sanitizeDescripcionItem,
184
+ safeSegment,
185
+
186
+ // ─────────────────────────────────────────
187
+ // RUT
188
+ // ─────────────────────────────────────────
189
+ formatRut,
190
+ cleanRut,
191
+ splitRut,
192
+ formatRutWithDots,
193
+ formatRutSii,
194
+ calcularDV,
195
+ validarRut,
196
+ validateAndFormatRut,
197
+
198
+ // ─────────────────────────────────────────
199
+ // XML
200
+ // ─────────────────────────────────────────
201
+ formatBase64InXml,
202
+ expandSelfClosingTags,
203
+ normalizeArray,
204
+ extractEnvioMetadata,
205
+ saveEnvioArtifacts,
206
+ parseXml,
207
+ parseXmlNoNs,
208
+ buildXml,
209
+ decodeXmlEntities,
210
+ extractTagContent,
211
+ extractAttribute,
212
+ defaultParser,
213
+ noNsParser,
214
+ defaultBuilder,
215
+ prettyBuilder,
216
+
217
+ // ─────────────────────────────────────────
218
+ // Resolución SII
219
+ // ─────────────────────────────────────────
220
+ normalizeFechaResolucion,
221
+ createResolucion,
222
+ createResolucionCertificacion,
223
+ createResolucionProduccion,
224
+ validarResolucion,
225
+
226
+ // ─────────────────────────────────────────
227
+ // Cálculo
228
+ // ─────────────────────────────────────────
229
+ TASA_IVA_DEFAULT,
230
+ formatDecimal,
231
+ calcularMontoItem,
232
+ calcularTotalesDesdeItems,
233
+ calcularTotalesDesdeDetalle,
234
+ buildDetalle,
235
+ buildDetalleGuia, buildDetalleCompra, buildDescuentoGlobal,
236
+
237
+ // ─────────────────────────────────────────
238
+ // Referencia
239
+ // ─────────────────────────────────────────
240
+ buildSetReferencia,
241
+ buildDocReferencia,
242
+ buildAnulacionReferencia,
243
+ buildCorreccionTextoReferencia,
244
+ buildCorreccionMontosReferencia,
245
+ buildReferenciasNcNd,
246
+ CODIGOS_REFERENCIA,
247
+
248
+ // ─────────────────────────────────────────
249
+ // Emisor
250
+ // ─────────────────────────────────────────
251
+ buildEmisor,
252
+ buildEmisorBoleta,
253
+ normalizeEmisor,
254
+ validarEmisor,
255
+
256
+ // ─────────────────────────────────────────
257
+ // Receptor
258
+ // ─────────────────────────────────────────
259
+ RUT_CONSUMIDOR_FINAL,
260
+ RECEPTOR_CONSUMIDOR_FINAL,
261
+ buildReceptor,
262
+ buildReceptorBoleta,
263
+ buildReceptorConsumidorFinal,
264
+ normalizeReceptor,
265
+ validarReceptor,
266
+ esConsumidorFinal,
267
+
268
+ // ─────────────────────────────────────────
269
+ // Errores
270
+ // ─────────────────────────────────────────
271
+ DteSiiError,
272
+ ERROR_CODES,
273
+ configError,
274
+ certError,
275
+ cafError,
276
+ dteError,
277
+ siiError,
278
+ xmlError,
279
+ wrapError,
280
+
281
+ // ─────────────────────────────────────────
282
+ // Logger
283
+ // ─────────────────────────────────────────
284
+ logger,
285
+ LOG_LEVELS,
286
+ configureLogger,
287
+ silenceLogger,
288
+ enableLogger,
289
+ getLoggerConfig,
290
+ createScopedLogger,
291
+
292
+ // ─────────────────────────────────────────
293
+ // Configuración Global
294
+ // ─────────────────────────────────────────
295
+ getConfig,
296
+ getConfigSection,
297
+ configure,
298
+ configureRetry,
299
+ configureTokenCache,
300
+ configureTimeout,
301
+ resetConfig,
302
+ configureForProduction,
303
+ configureForDevelopment,
304
+ calculateRetryDelay,
305
+ isRetryableError,
306
+ isRetryableStatus,
307
+ withRetry,
308
+ DEFAULT_CONFIG,
309
+
310
+ // ─────────────────────────────────────────
311
+ // Token Cache
312
+ // ─────────────────────────────────────────
313
+ getCachedToken,
314
+ setCachedToken,
315
+ invalidateToken,
316
+ invalidateAmbiente,
317
+ invalidateEmisor,
318
+ clearTokenCache,
319
+ getTokenCacheStats,
320
+ pruneExpiredTokens,
321
+
322
+ // ─────────────────────────────────────────
323
+ // Endpoints (URLs centralizadas)
324
+ // ─────────────────────────────────────────
325
+ endpoints,
326
+ ...endpoints,
327
+
328
+ // ─────────────────────────────────────────
329
+ // Constantes DTE
330
+ // ─────────────────────────────────────────
331
+ constants,
332
+ ...constants,
333
+
334
+ // ─────────────────────────────────────────
335
+ // PFX Loader
336
+ // ─────────────────────────────────────────
337
+ pfx,
338
+ ...pfx,
339
+ };
@@ -0,0 +1,239 @@
1
+ // Copyright (c) 2026 Devlas SpA — https://devlas.cl
2
+ // Licencia MIT. Ver archivo LICENSE para mas detalles.
3
+ /**
4
+ * Logger Configurable
5
+ *
6
+ * Logger que puede silenciarse en producción o configurarse por nivel
7
+ *
8
+ * @module dte-sii/utils/logger
9
+ */
10
+
11
+ // ============================================
12
+ // NIVELES DE LOG
13
+ // ============================================
14
+
15
+ const LOG_LEVELS = {
16
+ SILENT: 0,
17
+ ERROR: 1,
18
+ WARN: 2,
19
+ INFO: 3,
20
+ DEBUG: 4,
21
+ TRACE: 5,
22
+ };
23
+
24
+ // ============================================
25
+ // CONFIGURACIÓN GLOBAL
26
+ // ============================================
27
+
28
+ let globalConfig = {
29
+ level: LOG_LEVELS.INFO,
30
+ prefix: '[dte-sii]',
31
+ timestamps: false,
32
+ colors: true,
33
+ };
34
+
35
+ // ============================================
36
+ // FUNCIONES INTERNAS
37
+ // ============================================
38
+
39
+ function getTimestamp() {
40
+ return new Date().toISOString();
41
+ }
42
+
43
+ function formatMessage(level, ...args) {
44
+ const parts = [];
45
+
46
+ if (globalConfig.timestamps) {
47
+ parts.push(`[${getTimestamp()}]`);
48
+ }
49
+
50
+ if (globalConfig.prefix) {
51
+ parts.push(globalConfig.prefix);
52
+ }
53
+
54
+ parts.push(`[${level}]`);
55
+
56
+ return parts.join(' ');
57
+ }
58
+
59
+ // ============================================
60
+ // LOGGER PRINCIPAL
61
+ // ============================================
62
+
63
+ const logger = {
64
+ /**
65
+ * Log de error (siempre visible excepto SILENT)
66
+ */
67
+ error(...args) {
68
+ if (globalConfig.level >= LOG_LEVELS.ERROR) {
69
+ console.error(formatMessage('ERROR'), ...args);
70
+ }
71
+ },
72
+
73
+ /**
74
+ * Log de advertencia
75
+ */
76
+ warn(...args) {
77
+ if (globalConfig.level >= LOG_LEVELS.WARN) {
78
+ console.warn(formatMessage('WARN'), ...args);
79
+ }
80
+ },
81
+
82
+ /**
83
+ * Log informativo (default)
84
+ */
85
+ info(...args) {
86
+ if (globalConfig.level >= LOG_LEVELS.INFO) {
87
+ console.log(formatMessage('INFO'), ...args);
88
+ }
89
+ },
90
+
91
+ /**
92
+ * Log de debug (solo en desarrollo)
93
+ */
94
+ debug(...args) {
95
+ if (globalConfig.level >= LOG_LEVELS.DEBUG) {
96
+ console.log(formatMessage('DEBUG'), ...args);
97
+ }
98
+ },
99
+
100
+ /**
101
+ * Log de trace (muy detallado)
102
+ */
103
+ trace(...args) {
104
+ if (globalConfig.level >= LOG_LEVELS.TRACE) {
105
+ console.log(formatMessage('TRACE'), ...args);
106
+ }
107
+ },
108
+
109
+ /**
110
+ * Log simple sin formato (para compatibilidad)
111
+ * Respeta el nivel INFO
112
+ */
113
+ log(...args) {
114
+ if (globalConfig.level >= LOG_LEVELS.INFO) {
115
+ console.log(...args);
116
+ }
117
+ },
118
+ };
119
+
120
+ // ============================================
121
+ // CONFIGURACIÓN
122
+ // ============================================
123
+
124
+ /**
125
+ * Configurar el logger
126
+ * @param {Object} config - Configuración
127
+ * @param {string|number} [config.level] - Nivel: 'silent', 'error', 'warn', 'info', 'debug', 'trace' o número
128
+ * @param {string} [config.prefix] - Prefijo para mensajes
129
+ * @param {boolean} [config.timestamps] - Incluir timestamps
130
+ * @param {boolean} [config.colors] - Usar colores (reservado para futuro)
131
+ */
132
+ function configureLogger(config = {}) {
133
+ if (config.level !== undefined) {
134
+ if (typeof config.level === 'string') {
135
+ const levelName = config.level.toUpperCase();
136
+ globalConfig.level = LOG_LEVELS[levelName] ?? LOG_LEVELS.INFO;
137
+ } else if (typeof config.level === 'number') {
138
+ globalConfig.level = config.level;
139
+ }
140
+ }
141
+
142
+ if (config.prefix !== undefined) {
143
+ globalConfig.prefix = config.prefix;
144
+ }
145
+
146
+ if (config.timestamps !== undefined) {
147
+ globalConfig.timestamps = config.timestamps;
148
+ }
149
+
150
+ if (config.colors !== undefined) {
151
+ globalConfig.colors = config.colors;
152
+ }
153
+
154
+ return { ...globalConfig };
155
+ }
156
+
157
+ /**
158
+ * Silenciar completamente el logger
159
+ */
160
+ function silenceLogger() {
161
+ globalConfig.level = LOG_LEVELS.SILENT;
162
+ }
163
+
164
+ /**
165
+ * Restaurar logger a nivel INFO
166
+ */
167
+ function enableLogger() {
168
+ globalConfig.level = LOG_LEVELS.INFO;
169
+ }
170
+
171
+ /**
172
+ * Obtener configuración actual
173
+ */
174
+ function getLoggerConfig() {
175
+ return { ...globalConfig };
176
+ }
177
+
178
+ /**
179
+ * Crear un logger con prefijo específico (scoped logger)
180
+ * @param {string} scope - Nombre del scope (ej: 'CAF', 'DTE', 'EnviadorSII')
181
+ * @returns {Object} Logger con scope
182
+ */
183
+ function createScopedLogger(scope) {
184
+ const scopePrefix = `[${scope}]`;
185
+
186
+ return {
187
+ error(...args) {
188
+ if (globalConfig.level >= LOG_LEVELS.ERROR) {
189
+ console.error(formatMessage('ERROR'), scopePrefix, ...args);
190
+ }
191
+ },
192
+ warn(...args) {
193
+ if (globalConfig.level >= LOG_LEVELS.WARN) {
194
+ console.warn(formatMessage('WARN'), scopePrefix, ...args);
195
+ }
196
+ },
197
+ info(...args) {
198
+ if (globalConfig.level >= LOG_LEVELS.INFO) {
199
+ console.log(formatMessage('INFO'), scopePrefix, ...args);
200
+ }
201
+ },
202
+ debug(...args) {
203
+ if (globalConfig.level >= LOG_LEVELS.DEBUG) {
204
+ console.log(formatMessage('DEBUG'), scopePrefix, ...args);
205
+ }
206
+ },
207
+ trace(...args) {
208
+ if (globalConfig.level >= LOG_LEVELS.TRACE) {
209
+ console.log(formatMessage('TRACE'), scopePrefix, ...args);
210
+ }
211
+ },
212
+ log(...args) {
213
+ if (globalConfig.level >= LOG_LEVELS.INFO) {
214
+ console.log(scopePrefix, ...args);
215
+ }
216
+ },
217
+ };
218
+ }
219
+
220
+ // ============================================
221
+ // EXPORTS
222
+ // ============================================
223
+
224
+ module.exports = {
225
+ // Logger principal
226
+ logger,
227
+
228
+ // Constantes
229
+ LOG_LEVELS,
230
+
231
+ // Configuración
232
+ configureLogger,
233
+ silenceLogger,
234
+ enableLogger,
235
+ getLoggerConfig,
236
+
237
+ // Factory
238
+ createScopedLogger,
239
+ };