cosmemilton-acbr-node 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +330 -60
- package/dist/cli.js.map +3 -3
- package/dist/index.cjs +320 -46
- package/dist/index.cjs.map +4 -4
- package/dist/index.js +317 -46
- package/dist/index.js.map +4 -4
- package/dist/runtime.cjs +254 -35
- package/dist/runtime.cjs.map +3 -3
- package/dist/runtime.js +251 -34
- package/dist/runtime.js.map +3 -3
- package/dist/types/generated/acbr/index.d.ts +15 -1
- package/dist/types/generated/acbr/models.d.ts +32 -0
- package/dist/types/src/diagnostics.d.ts +8 -0
- package/dist/types/src/generator.d.ts +1 -0
- package/dist/types/src/index.d.ts +13 -0
- package/dist/types/src/runtime.d.ts +1 -0
- package/dist/types/src/types.d.ts +34 -1
- package/docs/API.md +90 -32
- package/docs/CI.md +6 -0
- package/docs/VALIDACAO.md +3 -1
- package/package.json +3 -3
package/dist/runtime.js
CHANGED
|
@@ -6,25 +6,159 @@ import { createRequire } from "node:module";
|
|
|
6
6
|
import { createHash, randomUUID } from "node:crypto";
|
|
7
7
|
import { TextDecoder } from "node:util";
|
|
8
8
|
|
|
9
|
+
// src/diagnostics.ts
|
|
10
|
+
var ETAPAS = /* @__PURE__ */ new Set(["configuracao", "documento", "runtime", "geracao", "validacao", "assinatura", "transmissao", "consulta", "cancelamento", "carta_correcao", "inutilizacao", "operacao", "limpeza"]);
|
|
11
|
+
var CAMPOS = /* @__PURE__ */ new Set(["cnpj", "uf", "modelo", "ambiente", "contrato", "certificado", "certificado.senha", "certificado.pfx", "certificado.arquivo", "csc", "csc.id", "csc.valor", "timeoutMs", "limiteFila", "limiteBytes", "runtimeDirectory", "documento", "xml", "consulta", "chave", "recibo", "cancelamento", "protocolo", "justificativa", "cartaCorrecao", "correcao", "sequenciaEvento", "inutilizacao", "ano", "serie", "numeroInicial", "numeroFinal", "operacao", "signal"]);
|
|
12
|
+
var CATALOGO = {
|
|
13
|
+
CONFIGURACAO_INVALIDA: ["configuracao", "A configura\xE7\xE3o cont\xE9m um campo inv\xE1lido.", "Confira o campo indicado e seu tipo antes de continuar."],
|
|
14
|
+
CONTRATO_INVALIDO: ["configuracao", "O contrato do cliente \xE9 inv\xE1lido.", "Use o contrato gerado junto com o cliente."],
|
|
15
|
+
CERTIFICADO_INVALIDO: ["configuracao", "O certificado A1 ou sua configura\xE7\xE3o \xE9 inv\xE1lido.", "Confira formato e validade do A1, pfx ou arquivo e a senha digitada, sem registrar esses dados."],
|
|
16
|
+
CERTIFICADO_DIVERGENTE: ["assinatura", "O certificado n\xE3o corresponde \xE0 raiz CNPJ do emitente.", "Confira o CNPJ configurado e selecione o A1 correspondente ao emitente."],
|
|
17
|
+
DEPENDENCIA_AUSENTE: ["runtime", "Uma depend\xEAncia do motor fiscal n\xE3o est\xE1 dispon\xEDvel.", "Reinstale o runtime completo da plataforma; confira a disponibilidade do OpenSSL distribu\xEDdo."],
|
|
18
|
+
SCHEMAS_AUSENTES: ["runtime", "Os schemas fiscais n\xE3o est\xE3o dispon\xEDveis.", "Reinstale o runtime completo da plataforma."],
|
|
19
|
+
SERVICOS_AUSENTES: ["runtime", "A configura\xE7\xE3o dos servi\xE7os fiscais n\xE3o est\xE1 dispon\xEDvel.", "Reinstale o runtime completo da plataforma."],
|
|
20
|
+
CSC_AUSENTE: ["configuracao", "A opera\xE7\xE3o de NFC-e exige CSC.", "Informe id e valor do CSC na configura\xE7\xE3o sem registrar seu conte\xFAdo."],
|
|
21
|
+
IDENTIDADE_DIVERGENTE: ["documento", "A identidade fiscal n\xE3o corresponde \xE0 configura\xE7\xE3o ou ao retorno.", "Confira emitente, UF, modelo, ambiente e chave do documento antes de continuar."],
|
|
22
|
+
XML_SCHEMA_INVALIDO: ["validacao", "O XML n\xE3o atende aos schemas fiscais.", "Confira os campos obrigat\xF3rios e os tributos; a valida\xE7\xE3o de XML assinado deve ocorrer ap\xF3s a assinatura."],
|
|
23
|
+
ASSINATURA_INVALIDA: ["assinatura", "A assinatura do XML n\xE3o foi validada.", "Confira o A1 correspondente e use o XML assinado sem altera\xE7\xF5es."],
|
|
24
|
+
XML_NAO_ASSINADO: ["assinatura", "A opera\xE7\xE3o exige XML previamente assinado.", "Conclua a assinatura e a valida\xE7\xE3o antes de transmitir."],
|
|
25
|
+
XML_ALTERADO: ["assinatura", "O XML assinado foi alterado.", "Use exatamente o XML assinado e persistido; n\xE3o edite seu conte\xFAdo."],
|
|
26
|
+
RETORNO_INVALIDO: ["transmissao", "A identidade ou o protocolo do retorno fiscal \xE9 inv\xE1lido.", "Consulte a situa\xE7\xE3o fiscal antes de decidir repetir a opera\xE7\xE3o."],
|
|
27
|
+
OPERACAO_FISCAL_FALHOU: ["operacao", "O motor n\xE3o conseguiu concluir a etapa fiscal.", "Confira a configura\xE7\xE3o da etapa, os dados do XML e as depend\xEAncias do runtime."],
|
|
28
|
+
TLS_SERVIDOR_INVALIDO: ["transmissao", "A verifica\xE7\xE3o TLS do servi\xE7o fiscal falhou.", "Confira o servi\xE7o e a cadeia de confian\xE7a; mantenha a verifica\xE7\xE3o TLS habilitada."],
|
|
29
|
+
CSC_INVALIDO: ["configuracao", "A configura\xE7\xE3o do CSC \xE9 inv\xE1lida.", "Confira id e valor do CSC sem registrar seu conte\xFAdo."],
|
|
30
|
+
PLATAFORMA_NAO_SUPORTADA: ["runtime", "A plataforma n\xE3o \xE9 suportada.", "Execute em Windows ou Linux x64 com Node.js 22.12 ou superior."],
|
|
31
|
+
RUNTIME_AUSENTE: ["runtime", "O motor fiscal n\xE3o foi encontrado.", "Instale o runtime da plataforma incluindo depend\xEAncias opcionais."],
|
|
32
|
+
RUNTIME_INVALIDO: ["runtime", "O runtime fiscal \xE9 inv\xE1lido.", "Use um runtime distribu\xEDdo e compat\xEDvel com a plataforma."],
|
|
33
|
+
RUNTIME_INCOMPLETO: ["runtime", "Falta um arquivo do runtime fiscal.", "Reinstale o runtime da plataforma."],
|
|
34
|
+
RUNTIME_ALTERADO: ["runtime", "A integridade do runtime fiscal n\xE3o foi confirmada.", "Reinstale o runtime; n\xE3o desative a verifica\xE7\xE3o dos hashes."],
|
|
35
|
+
CONTRATO_DIVERGENTE: ["runtime", "Cliente e motor usam contratos diferentes.", "Use vers\xF5es compat\xEDveis ou regenere e recompile ambos."],
|
|
36
|
+
DOCUMENTO_INVALIDO: ["documento", "O documento cont\xE9m dados incompat\xEDveis com o modelo.", "Valide os campos e tipos do documento antes de gerar o XML."],
|
|
37
|
+
OPERACAO_INVALIDA: ["operacao", "Os par\xE2metros da opera\xE7\xE3o s\xE3o inv\xE1lidos.", "Informe um objeto com os campos exigidos pela opera\xE7\xE3o."],
|
|
38
|
+
OPERACAO_CANCELADA: ["operacao", "A opera\xE7\xE3o foi cancelada.", "Confira o estado do envio antes de decidir continuar."],
|
|
39
|
+
TIMEOUT_MOTOR: ["runtime", "O motor excedeu o tempo de espera.", "Confira o estado do envio antes de repetir a opera\xE7\xE3o."],
|
|
40
|
+
EMISSOR_FECHADO: ["operacao", "O emissor foi encerrado.", "Crie um novo emissor para continuar."],
|
|
41
|
+
FALHA_INICIAR_MOTOR: ["runtime", "N\xE3o foi poss\xEDvel iniciar o motor fiscal.", "Confira a instala\xE7\xE3o e as permiss\xF5es de execu\xE7\xE3o do runtime."],
|
|
42
|
+
FALHA_PIPE: ["runtime", "A comunica\xE7\xE3o com o motor foi interrompida.", "Confira a instala\xE7\xE3o e o estado do envio antes de continuar."],
|
|
43
|
+
RESPOSTA_EXCESSIVA: ["runtime", "A resposta do motor excedeu o limite.", "Confira o tamanho da opera\xE7\xE3o e a vers\xE3o do runtime."],
|
|
44
|
+
RESPOSTA_INVALIDA: ["runtime", "O motor devolveu uma resposta inv\xE1lida.", "Confira a compatibilidade do runtime e o estado do envio."],
|
|
45
|
+
FALHA_MOTOR: ["runtime", "O motor encerrou sem uma resposta fiscal v\xE1lida.", "Confira a instala\xE7\xE3o e o estado do envio antes de continuar."],
|
|
46
|
+
CERTIFICADO_AUSENTE: ["configuracao", "O certificado A1 n\xE3o est\xE1 dispon\xEDvel para esta opera\xE7\xE3o.", "Configure um A1 acess\xEDvel e sua senha sem registrar esses dados."],
|
|
47
|
+
CERTIFICADO_EXCESSIVO: ["configuracao", "O certificado excede o limite de tamanho.", "Use um arquivo A1 de at\xE9 2 MiB."],
|
|
48
|
+
REQUISICAO_INVALIDA: ["operacao", "Os dados n\xE3o puderam ser serializados ou excedem o limite.", "Use dados JSON e reduza o tamanho da opera\xE7\xE3o."],
|
|
49
|
+
FILA_CHEIA: ["operacao", "A fila fiscal est\xE1 cheia.", "Aguarde a opera\xE7\xE3o atual terminar antes de iniciar outra."],
|
|
50
|
+
XML_INVALIDO: ["documento", "O XML est\xE1 vazio, tem tipo inv\xE1lido ou excede o limite.", "Informe o XML como texto UTF-8 de at\xE9 2 MiB."],
|
|
51
|
+
CHAVE_INVALIDA: ["documento", "A chave fiscal tem formato inv\xE1lido.", "Informe a chave como texto com 44 d\xEDgitos."],
|
|
52
|
+
RECIBO_INVALIDO: ["documento", "O recibo tem formato inv\xE1lido.", "Informe o recibo como texto com 15 d\xEDgitos."],
|
|
53
|
+
JUSTIFICATIVA_INVALIDA: ["documento", "A justificativa tem tamanho inv\xE1lido.", "Informe uma justificativa com 15 a 255 caracteres."],
|
|
54
|
+
PROTOCOLO_INVALIDO: ["documento", "O protocolo tem formato inv\xE1lido.", "Informe o protocolo como texto com 15 d\xEDgitos."],
|
|
55
|
+
OPERACAO_NAO_SUPORTADA: ["operacao", "A opera\xE7\xE3o n\xE3o \xE9 suportada para este modelo.", "Carta de corre\xE7\xE3o exige NF-e modelo 55."],
|
|
56
|
+
CORRECAO_INVALIDA: ["documento", "Os dados da carta de corre\xE7\xE3o s\xE3o inv\xE1lidos.", "Confira a corre\xE7\xE3o de 15 a 1000 caracteres e a sequ\xEAncia de 1 a 20."],
|
|
57
|
+
INUTILIZACAO_INVALIDA: ["documento", "A faixa de inutiliza\xE7\xE3o \xE9 inv\xE1lida.", "Confira ano, s\xE9rie e n\xFAmeros inicial e final."],
|
|
58
|
+
FALHA_LOCAL: ["operacao", "N\xE3o foi poss\xEDvel concluir a opera\xE7\xE3o local.", "Confira a etapa e os tipos dos dados; n\xE3o registre o erro bruto."]
|
|
59
|
+
};
|
|
60
|
+
function etapaDaOperacao(comando) {
|
|
61
|
+
return { gerarXml: "geracao", validar: "validacao", assinar: "assinatura", transmitir: "transmissao", consultar: "consulta", cancelar: "cancelamento", cartaCorrecao: "carta_correcao", inutilizar: "inutilizacao" }[comando] ?? "operacao";
|
|
62
|
+
}
|
|
63
|
+
function criarDiagnosticoErro(codigo, desconhecido = false, detalhes = {}) {
|
|
64
|
+
const safeCode = Object.hasOwn(CATALOGO, codigo) ? codigo : "FALHA_LOCAL";
|
|
65
|
+
const [defaultStage, mensagem, defaultAction] = CATALOGO[safeCode];
|
|
66
|
+
const etapa = detalhes.etapa && ETAPAS.has(detalhes.etapa) ? detalhes.etapa : defaultStage;
|
|
67
|
+
const campo = detalhes.campo && CAMPOS.has(detalhes.campo) ? detalhes.campo : void 0;
|
|
68
|
+
const acoesConfig = { cnpj: "Informe o CNPJ como texto com 14 d\xEDgitos.", uf: "Informe a sigla da UF em letras mai\xFAsculas, por exemplo PE.", modelo: "Informe o n\xFAmero 55 para NF-e ou 65 para NFC-e, sem aspas.", ambiente: "Informe o n\xFAmero 2 para homologa\xE7\xE3o ou 1 para produ\xE7\xE3o, sem aspas.", timeoutMs: "Informe um n\xFAmero inteiro de 1 a 120000 milissegundos.", limiteFila: "Informe um n\xFAmero inteiro de 0 a 1000.", limiteBytes: "Informe um n\xFAmero inteiro de 256 a 8388608 bytes.", runtimeDirectory: "Informe o diret\xF3rio do runtime como texto n\xE3o vazio." };
|
|
69
|
+
const acao = safeCode === "CONFIGURACAO_INVALIDA" && campo && Object.hasOwn(acoesConfig, campo) ? acoesConfig[campo] : defaultAction;
|
|
70
|
+
const causa = Object.freeze({ codigo: safeCode, etapa, ...campo ? { campo } : {} });
|
|
71
|
+
return Object.freeze({
|
|
72
|
+
codigo: safeCode,
|
|
73
|
+
etapa,
|
|
74
|
+
...campo ? { campo } : {},
|
|
75
|
+
mensagem,
|
|
76
|
+
acao: desconhecido ? "Consulte a situa\xE7\xE3o fiscal antes de repetir. O envio pode ter ocorrido; n\xE3o retransmita automaticamente." : acao,
|
|
77
|
+
statusEnvio: desconhecido ? "resultado_incerto" : "nao_enviado",
|
|
78
|
+
causa
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
function diagnosticarErro(erro) {
|
|
82
|
+
return erro instanceof ErroAcbrNode ? erro.diagnostico : criarDiagnosticoErro("FALHA_LOCAL", true);
|
|
83
|
+
}
|
|
84
|
+
function adicionarDiagnosticoLimpeza(diagnostico) {
|
|
85
|
+
const acao = diagnostico.statusEnvio === "resultado_incerto" ? "Encerre esta aplica\xE7\xE3o antes de iniciar outro motor e consulte a situa\xE7\xE3o fiscal antes de repetir qualquer envio." : "Encerre esta aplica\xE7\xE3o antes de iniciar outro motor. As pr\xF3ximas opera\xE7\xF5es deste emissor foram bloqueadas.";
|
|
86
|
+
const limpeza = Object.freeze({ codigo: "ENCERRAMENTO_MOTOR_NAO_CONFIRMADO", etapa: "limpeza", mensagem: "N\xE3o foi poss\xEDvel confirmar o encerramento do motor fiscal.", acao });
|
|
87
|
+
return Object.freeze({ ...diagnostico, acao, limpeza });
|
|
88
|
+
}
|
|
89
|
+
function diagnosticarResultado(resultado, comando) {
|
|
90
|
+
const etapa = etapaDaOperacao(comando);
|
|
91
|
+
if (!resultado || typeof resultado !== "object") return criarDiagnosticoErro("FALHA_LOCAL", true, { etapa });
|
|
92
|
+
if (resultado.envioIniciado !== void 0 && typeof resultado.envioIniciado !== "boolean") return criarDiagnosticoErro("RESPOSTA_INVALIDA", true, { etapa });
|
|
93
|
+
let statusEnvio = "resultado_incerto", codigo = "RESULTADO_INCERTO";
|
|
94
|
+
let mensagem = "A situa\xE7\xE3o fiscal ainda n\xE3o foi confirmada.";
|
|
95
|
+
let acao = "Consulte a situa\xE7\xE3o fiscal antes de repetir. N\xE3o retransmita automaticamente.";
|
|
96
|
+
const local = comando === "gerarXml" && resultado.estado === "XML_GERADO" || comando === "validar" && resultado.estado === "VALIDADO" || comando === "assinar" && resultado.estado === "ASSINADO";
|
|
97
|
+
const semEvento = resultado.envioIniciado === false || resultado.envioIniciado === void 0;
|
|
98
|
+
const protocolo = typeof resultado.protocolo === "string" && /^\d{15}$/.test(resultado.protocolo);
|
|
99
|
+
const chave = typeof resultado.chave === "string" && /^\d{44}$/.test(resultado.chave);
|
|
100
|
+
const autorizacao = (comando === "transmitir" || comando === "consultar") && resultado.estado === "AUTORIZADO" && [100, 150].includes(resultado.cStat) && protocolo && chave && (comando === "consultar" || resultado.envioIniciado !== false);
|
|
101
|
+
const evento = comando === "cancelar" && resultado.estado === "CANCELADO" && [135, 136].includes(resultado.cStat) && chave || comando === "cartaCorrecao" && resultado.estado === "EVENTO_REGISTRADO" && resultado.cStat === 135 && chave || comando === "inutilizar" && resultado.estado === "INUTILIZADO" && resultado.cStat === 102;
|
|
102
|
+
if (local && resultado.sucesso === true && semEvento) {
|
|
103
|
+
statusEnvio = "nao_enviado";
|
|
104
|
+
codigo = "ETAPA_LOCAL_CONCLUIDA";
|
|
105
|
+
mensagem = "A etapa local foi conclu\xEDda; esta opera\xE7\xE3o n\xE3o transmitiu a nota.";
|
|
106
|
+
acao = "Confira o resultado antes de seguir para a pr\xF3xima etapa.";
|
|
107
|
+
} else if (resultado.sucesso === true && (autorizacao || evento && protocolo && resultado.envioIniciado !== false)) {
|
|
108
|
+
statusEnvio = "autorizado";
|
|
109
|
+
codigo = "OPERACAO_CONFIRMADA";
|
|
110
|
+
mensagem = { AUTORIZADO: "A nota foi autorizada.", CANCELADO: "O cancelamento foi confirmado.", EVENTO_REGISTRADO: "O evento foi registrado.", INUTILIZADO: "A faixa foi inutilizada." }[resultado.estado];
|
|
111
|
+
acao = "Guarde o resultado fiscal. N\xE3o repita esta opera\xE7\xE3o.";
|
|
112
|
+
} else if (resultado.sucesso === false && (comando === "consultar" || resultado.envioIniciado !== false) && ["transmitir", "consultar", "cancelar", "cartaCorrecao", "inutilizar"].includes(comando) && Number.isInteger(resultado.cStat) && Number(resultado.cStat) > 0 && Number(resultado.cStat) <= 9999 && (resultado.estado === "DENEGADO" && [110, 301, 302].includes(resultado.cStat) || resultado.estado === "REJEITADO" && ![100, 150, 110, 301, 302, 101, 151, 155, 103, 104, 105, 108, 109, 204, 539, 573, 135, 136, 102, 217].includes(resultado.cStat))) {
|
|
113
|
+
statusEnvio = "rejeitado";
|
|
114
|
+
codigo = resultado.estado === "DENEGADO" ? "NOTA_DENEGADA" : "OPERACAO_REJEITADA";
|
|
115
|
+
mensagem = resultado.estado === "DENEGADO" ? "A nota foi denegada." : "A opera\xE7\xE3o foi rejeitada.";
|
|
116
|
+
acao = resultado.estado === "DENEGADO" ? "Consulte a situa\xE7\xE3o fiscal e a orienta\xE7\xE3o respons\xE1vel antes de usar a numera\xE7\xE3o." : "Confira o cStat e revise os dados antes de decidir uma nova tentativa.";
|
|
117
|
+
} else if (resultado.estado === "ERRO" && resultado.envioIniciado === false) {
|
|
118
|
+
if (typeof resultado.codigo === "string" && Object.hasOwn(CATALOGO, resultado.codigo)) return criarDiagnosticoErro(resultado.codigo, false, { etapa });
|
|
119
|
+
statusEnvio = "nao_enviado";
|
|
120
|
+
codigo = "FALHA_ANTES_ENVIO";
|
|
121
|
+
mensagem = "O motor informou falha antes de iniciar o envio desta opera\xE7\xE3o.";
|
|
122
|
+
acao = "Revise a configura\xE7\xE3o e os dados antes de continuar.";
|
|
123
|
+
}
|
|
124
|
+
const cStat = Number.isInteger(resultado.cStat) && Number(resultado.cStat) > 0 && Number(resultado.cStat) <= 9999 ? resultado.cStat : void 0;
|
|
125
|
+
return Object.freeze({ codigo, etapa, mensagem, acao, statusEnvio, ...cStat !== void 0 ? { cStat } : {} });
|
|
126
|
+
}
|
|
127
|
+
|
|
9
128
|
// src/types.ts
|
|
10
129
|
var PROTOCOL_VERSION = 1;
|
|
11
130
|
var ErroAcbrNode = class extends Error {
|
|
12
|
-
constructor(codigo, mensagem, resultadoDesconhecido = false, xmlBase64) {
|
|
131
|
+
constructor(codigo, mensagem, resultadoDesconhecido = false, xmlBase64, detalhes) {
|
|
13
132
|
super(mensagem);
|
|
14
133
|
this.codigo = codigo;
|
|
15
134
|
this.resultadoDesconhecido = resultadoDesconhecido;
|
|
16
135
|
this.xmlBase64 = xmlBase64;
|
|
136
|
+
this.#diagnostico = criarDiagnosticoErro(codigo, resultadoDesconhecido, detalhes);
|
|
137
|
+
Object.defineProperty(this, "xmlBase64", { value: xmlBase64, enumerable: false });
|
|
138
|
+
Object.defineProperty(this, "cause", { value: this.diagnostico.causa, enumerable: false });
|
|
17
139
|
}
|
|
18
140
|
name = "ErroAcbrNode";
|
|
141
|
+
#diagnostico;
|
|
142
|
+
get diagnostico() {
|
|
143
|
+
return this.#diagnostico;
|
|
144
|
+
}
|
|
145
|
+
/** Acrescenta apenas o aviso estático de limpeza, preservando o erro da operação. */
|
|
146
|
+
anotarFalhaLimpeza() {
|
|
147
|
+
this.#diagnostico = adicionarDiagnosticoLimpeza(this.#diagnostico);
|
|
148
|
+
}
|
|
149
|
+
toJSON() {
|
|
150
|
+
return this.diagnostico;
|
|
151
|
+
}
|
|
19
152
|
};
|
|
20
153
|
|
|
21
154
|
// src/runtime.ts
|
|
22
155
|
var STATES = /* @__PURE__ */ new Set(["DENEGADO", "XML_GERADO", "VALIDADO", "ASSINADO", "AUTORIZADO", "REJEITADO", "PENDENTE", "INDETERMINADO", "CONSULTADO", "CANCELADO", "EVENTO_REGISTRADO", "INUTILIZADO", "ERRO"]);
|
|
23
156
|
var UFS = new Set("AC AL AP AM BA CE DF ES GO MA MT MS MG PA PB PR PE PI RJ RN RS RO RR SC SP SE TO".split(" "));
|
|
24
157
|
var MAX_BYTES = 8 * 1024 * 1024;
|
|
158
|
+
var MAX_TEARDOWN_MS = 1e3;
|
|
25
159
|
var plain = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
26
160
|
var validContract = (v) => plain(v) && Number.isInteger(v.sourceRevision) && Number(v.sourceRevision) > 0 && typeof v.contractHash === "string" && /^[a-f0-9]{64}$/.test(v.contractHash);
|
|
27
|
-
var fail = (code, message, req, unknown = false) => new ErroAcbrNode(code, message, unknown, req?.comando === "transmitir" ? req.xmlBase64 : void 0);
|
|
161
|
+
var fail = (code, message, req, unknown = false, detalhes) => new ErroAcbrNode(code, message, unknown, req?.comando === "transmitir" ? req.xmlBase64 : void 0, { ...req ? { etapa: etapaDaOperacao(req.comando) } : {}, ...detalhes });
|
|
28
162
|
function confined(root, relative) {
|
|
29
163
|
const file = path.resolve(root, relative), part = path.relative(root, file);
|
|
30
164
|
if (!relative || path.isAbsolute(relative) || part === ".." || part.startsWith(".." + path.sep)) throw fail("RUNTIME_INVALIDO", "Caminho inv\xE1lido no runtime.");
|
|
@@ -67,26 +201,48 @@ async function resolveRuntime(directory, contract) {
|
|
|
67
201
|
return { directory: root, executable: confined(root, m.executable) };
|
|
68
202
|
}
|
|
69
203
|
function criarEmissor(options) {
|
|
70
|
-
|
|
204
|
+
const configFail = (campo) => fail("CONFIGURACAO_INVALIDA", "Informe campos e tipos v\xE1lidos na configura\xE7\xE3o.", void 0, false, { etapa: "configuracao", campo });
|
|
205
|
+
if (!plain(options)) throw configFail();
|
|
206
|
+
if (typeof options.cnpj !== "string" || !/^\d{14}$/.test(options.cnpj)) throw configFail("cnpj");
|
|
207
|
+
if (typeof options.uf !== "string" || !UFS.has(options.uf)) throw configFail("uf");
|
|
208
|
+
if (![55, 65].includes(options.modelo)) throw configFail("modelo");
|
|
209
|
+
if (![1, 2].includes(options.ambiente)) throw configFail("ambiente");
|
|
71
210
|
if (!validContract(options.contrato)) throw fail("CONTRATO_INVALIDO", "Contrato gerado inv\xE1lido.");
|
|
72
211
|
const cert = options.certificado;
|
|
73
|
-
if (cert && (typeof cert.senha !== "string" || !!cert.pfx === !!cert.arquivo || cert.pfx && !(cert.pfx instanceof Uint8Array))) throw fail("CERTIFICADO_INVALIDO", "Informe A1 em pfx ou arquivo e sua senha.");
|
|
74
|
-
if (options.csc && (!/^\d{1,6}$/.test(options.csc.id) || typeof options.csc.valor !== "string" || !options.csc.valor || options.csc.valor.length > 256)) throw fail("CSC_INVALIDO", "CSC inv\xE1lido.");
|
|
212
|
+
if (cert !== void 0 && (!plain(cert) || typeof cert.senha !== "string" || !!cert.pfx === !!cert.arquivo || cert.pfx !== void 0 && !(cert.pfx instanceof Uint8Array) || cert.arquivo !== void 0 && (typeof cert.arquivo !== "string" || !cert.arquivo))) throw fail("CERTIFICADO_INVALIDO", "Informe A1 em pfx ou arquivo e sua senha.", void 0, false, { campo: "certificado" });
|
|
213
|
+
if (options.csc !== void 0 && (!plain(options.csc) || typeof options.csc.id !== "string" || !/^\d{1,6}$/.test(options.csc.id) || typeof options.csc.valor !== "string" || !options.csc.valor || options.csc.valor.length > 256)) throw fail("CSC_INVALIDO", "CSC inv\xE1lido.", void 0, false, { campo: "csc" });
|
|
214
|
+
if (options.runtimeDirectory !== void 0 && (typeof options.runtimeDirectory !== "string" || !options.runtimeDirectory)) throw configFail("runtimeDirectory");
|
|
215
|
+
if (options.validaDocumento !== void 0 && typeof options.validaDocumento !== "function" || options.criaProcesso !== void 0 && typeof options.criaProcesso !== "function") throw configFail();
|
|
75
216
|
const cfg = { cnpj: options.cnpj, uf: options.uf, modelo: options.modelo, ambiente: options.ambiente, csc: options.csc ? { ...options.csc } : void 0 };
|
|
76
217
|
const certificate = cert ? { ...cert, pfx: cert.pfx ? Buffer.from(cert.pfx) : void 0 } : void 0;
|
|
77
218
|
const contract = { ...options.contrato };
|
|
78
219
|
const timeout = options.timeoutMs ?? 12e4, capacity = options.limiteFila ?? 32, bytesLimit = options.limiteBytes ?? MAX_BYTES;
|
|
79
|
-
if (!Number.isInteger(timeout) || timeout < 1 || timeout > 12e4
|
|
220
|
+
if (!Number.isInteger(timeout) || timeout < 1 || timeout > 12e4) throw configFail("timeoutMs");
|
|
221
|
+
if (!Number.isInteger(capacity) || capacity < 0 || capacity > 1e3) throw configFail("limiteFila");
|
|
222
|
+
if (!Number.isInteger(bytesLimit) || bytesLimit < 256 || bytesLimit > MAX_BYTES) throw configFail("limiteBytes");
|
|
80
223
|
const launch = options.criaProcesso ?? ((exe, args, config) => spawn(exe, args, { ...config, stdio: ["pipe", "pipe", "pipe"] }));
|
|
81
|
-
let runtimePromise, closed = false, current;
|
|
224
|
+
let runtimePromise, closed = false, teardownFailed = false, current;
|
|
82
225
|
const queue = [];
|
|
226
|
+
const closedError = () => {
|
|
227
|
+
const error = fail("EMISSOR_FECHADO", "Emissor encerrado.");
|
|
228
|
+
if (teardownFailed) error.anotarFalhaLimpeza();
|
|
229
|
+
return error;
|
|
230
|
+
};
|
|
231
|
+
const rejectQueue = () => {
|
|
232
|
+
for (const item of queue.splice(0)) {
|
|
233
|
+
item.signal?.removeEventListener("abort", item.abort);
|
|
234
|
+
item.bytes.fill(0);
|
|
235
|
+
item.reject(closedError());
|
|
236
|
+
}
|
|
237
|
+
};
|
|
83
238
|
async function execute(item) {
|
|
84
239
|
if (closed || item.signal?.aborted) throw fail("OPERACAO_CANCELADA", "Opera\xE7\xE3o cancelada antes da execu\xE7\xE3o.");
|
|
85
240
|
const runtime = await (runtimePromise ??= resolveRuntime(options.runtimeDirectory, contract));
|
|
86
241
|
if (closed || item.signal?.aborted) throw fail("OPERACAO_CANCELADA", "Opera\xE7\xE3o cancelada antes da execu\xE7\xE3o.");
|
|
87
|
-
await new Promise((done) => {
|
|
242
|
+
return await new Promise((done, rejectExecution) => {
|
|
88
243
|
let stopError;
|
|
89
244
|
let child, finished = false, started = false, sending = false, total = 0, rest = Buffer.alloc(0), result;
|
|
245
|
+
let teardownTimer;
|
|
90
246
|
let finishCurrent;
|
|
91
247
|
const doneCurrent = new Promise((r) => {
|
|
92
248
|
finishCurrent = r;
|
|
@@ -96,18 +252,54 @@ function criarEmissor(options) {
|
|
|
96
252
|
if (finished) return;
|
|
97
253
|
finished = true;
|
|
98
254
|
clearTimeout(timer);
|
|
255
|
+
clearTimeout(teardownTimer);
|
|
99
256
|
item.signal?.removeEventListener("abort", abort);
|
|
100
257
|
item.bytes.fill(0);
|
|
101
258
|
if (current?.done === doneCurrent) current = void 0;
|
|
102
259
|
finishCurrent();
|
|
103
|
-
error ?
|
|
104
|
-
|
|
260
|
+
error ? rejectExecution(error) : done(result);
|
|
261
|
+
};
|
|
262
|
+
const detachOwnedChild = () => {
|
|
263
|
+
for (const pipe of [child?.stdin, child?.stdout, child?.stderr]) {
|
|
264
|
+
try {
|
|
265
|
+
pipe?.destroy();
|
|
266
|
+
} catch {
|
|
267
|
+
}
|
|
268
|
+
try {
|
|
269
|
+
pipe?.unref?.();
|
|
270
|
+
} catch {
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
try {
|
|
274
|
+
child?.unref();
|
|
275
|
+
} catch {
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
const teardownFallback = () => {
|
|
279
|
+
if (finished) return;
|
|
280
|
+
stopError ??= fail("FALHA_MOTOR", "O motor n\xE3o foi encerrado.", item.req, uncertain());
|
|
281
|
+
stopError.anotarFalhaLimpeza();
|
|
282
|
+
teardownFailed = true;
|
|
283
|
+
closed = true;
|
|
284
|
+
rejectQueue();
|
|
285
|
+
certificate?.pfx?.fill(0);
|
|
286
|
+
finish(stopError);
|
|
287
|
+
detachOwnedChild();
|
|
105
288
|
};
|
|
106
289
|
const stop = (code, message) => {
|
|
107
290
|
if (finished || stopError) return;
|
|
108
291
|
stopError = fail(code, message, item.req, uncertain());
|
|
109
|
-
if (child?.pid)
|
|
110
|
-
|
|
292
|
+
if (!child?.pid) {
|
|
293
|
+
finish(stopError);
|
|
294
|
+
detachOwnedChild();
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
teardownTimer = setTimeout(teardownFallback, MAX_TEARDOWN_MS);
|
|
298
|
+
try {
|
|
299
|
+
if (child.kill("SIGKILL") !== true) teardownFallback();
|
|
300
|
+
} catch {
|
|
301
|
+
teardownFallback();
|
|
302
|
+
}
|
|
111
303
|
};
|
|
112
304
|
const abort = () => stop("OPERACAO_CANCELADA", "Opera\xE7\xE3o cancelada; confira a situa\xE7\xE3o fiscal quando o envio foi iniciado.");
|
|
113
305
|
const timer = setTimeout(() => stop("TIMEOUT_MOTOR", "O motor excedeu o prazo; consulte a situa\xE7\xE3o antes de transmitir novamente."), timeout);
|
|
@@ -134,8 +326,17 @@ function criarEmissor(options) {
|
|
|
134
326
|
child.on("spawn", () => {
|
|
135
327
|
started = true;
|
|
136
328
|
});
|
|
137
|
-
child.on("error", () =>
|
|
329
|
+
child.on("error", () => {
|
|
330
|
+
if (finished) return;
|
|
331
|
+
if (stopError) {
|
|
332
|
+
teardownFallback();
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
stop("FALHA_INICIAR_MOTOR", "N\xE3o foi poss\xEDvel iniciar o motor.");
|
|
336
|
+
});
|
|
138
337
|
child.stdin.on("error", () => stop("FALHA_PIPE", "N\xE3o foi poss\xEDvel comunicar com o motor."));
|
|
338
|
+
child.stdout.on("error", () => stop("FALHA_PIPE", "N\xE3o foi poss\xEDvel comunicar com o motor."));
|
|
339
|
+
child.stderr.on("error", () => stop("FALHA_PIPE", "N\xE3o foi poss\xEDvel comunicar com o motor."));
|
|
139
340
|
child.stderr.on("data", () => {
|
|
140
341
|
});
|
|
141
342
|
child.stdout.on("data", (chunk) => {
|
|
@@ -161,7 +362,9 @@ function criarEmissor(options) {
|
|
|
161
362
|
if (result || frame.versao !== 1 || frame.sourceRevision !== contract.sourceRevision || frame.contractHash !== contract.contractHash || typeof frame.sucesso !== "boolean" || !STATES.has(String(frame.estado))) throw Error();
|
|
162
363
|
if (frame.xmlBase64 !== void 0 && (typeof frame.xmlBase64 !== "string" || !frame.xmlBase64.length || Buffer.from(frame.xmlBase64, "base64").toString("base64") !== frame.xmlBase64)) throw Error();
|
|
163
364
|
if (frame.cStat !== void 0 && (!Number.isInteger(frame.cStat) || Number(frame.cStat) < 1 || Number(frame.cStat) > 9999)) throw Error();
|
|
164
|
-
|
|
365
|
+
if (frame.envioIniciado !== void 0 && typeof frame.envioIniciado !== "boolean" || sending && frame.envioIniciado === false) throw Error();
|
|
366
|
+
const fiscal = frame;
|
|
367
|
+
result = { ...fiscal, diagnostico: diagnosticarResultado(sending ? { ...fiscal, envioIniciado: true } : fiscal, item.req.comando) };
|
|
165
368
|
} catch {
|
|
166
369
|
stop("RESPOSTA_INVALIDA", "O motor retornou uma resposta inv\xE1lida.");
|
|
167
370
|
return;
|
|
@@ -192,7 +395,8 @@ function criarEmissor(options) {
|
|
|
192
395
|
busy = true;
|
|
193
396
|
item.signal?.removeEventListener("abort", item.abort);
|
|
194
397
|
try {
|
|
195
|
-
await execute(item);
|
|
398
|
+
const result = await execute(item);
|
|
399
|
+
item.resolve(result);
|
|
196
400
|
} catch (e) {
|
|
197
401
|
item.bytes.fill(0);
|
|
198
402
|
item.reject(e);
|
|
@@ -202,7 +406,11 @@ function criarEmissor(options) {
|
|
|
202
406
|
}
|
|
203
407
|
}
|
|
204
408
|
async function request(command, data, operation = {}) {
|
|
205
|
-
|
|
409
|
+
const rawOperation = operation;
|
|
410
|
+
if (!plain(rawOperation)) throw fail("OPERACAO_INVALIDA", "Informe op\xE7\xF5es v\xE1lidas para a opera\xE7\xE3o.", void 0, false, { etapa: etapaDaOperacao(command), campo: "operacao" });
|
|
411
|
+
const signal = operation.signal;
|
|
412
|
+
if (signal !== void 0 && (!plain(signal) || typeof signal.aborted !== "boolean" || typeof signal.addEventListener !== "function" || typeof signal.removeEventListener !== "function")) throw fail("OPERACAO_INVALIDA", "Informe op\xE7\xF5es v\xE1lidas para a opera\xE7\xE3o.", void 0, false, { etapa: etapaDaOperacao(command), campo: "signal" });
|
|
413
|
+
if (closed) throw closedError();
|
|
206
414
|
if (operation.signal?.aborted) throw fail("OPERACAO_CANCELADA", "Opera\xE7\xE3o cancelada antes da execu\xE7\xE3o.");
|
|
207
415
|
if (["assinar", "transmitir", "consultar", "cancelar", "cartaCorrecao", "inutilizar"].includes(command) && !certificate) throw fail("CERTIFICADO_AUSENTE", "A opera\xE7\xE3o exige um certificado A1.");
|
|
208
416
|
if (command === "gerarXml") options.validaDocumento?.(data.documento);
|
|
@@ -228,7 +436,7 @@ function criarEmissor(options) {
|
|
|
228
436
|
return new Promise((resolve, reject) => {
|
|
229
437
|
if (closed) {
|
|
230
438
|
bytes.fill(0);
|
|
231
|
-
reject(
|
|
439
|
+
reject(closedError());
|
|
232
440
|
return;
|
|
233
441
|
}
|
|
234
442
|
if (busy && queue.length >= capacity) {
|
|
@@ -253,14 +461,17 @@ function criarEmissor(options) {
|
|
|
253
461
|
});
|
|
254
462
|
}
|
|
255
463
|
const xmlData = (xml) => {
|
|
256
|
-
if (typeof xml !== "string" || !xml.trim() || Buffer.byteLength(xml, "utf8") > 2 * 1024 * 1024) throw fail("XML_INVALIDO", "XML vazio ou acima do limite.");
|
|
464
|
+
if (typeof xml !== "string" || !xml.trim() || Buffer.byteLength(xml, "utf8") > 2 * 1024 * 1024) throw fail("XML_INVALIDO", "XML vazio ou acima do limite.", void 0, false, { campo: "xml" });
|
|
257
465
|
return { xmlBase64: Buffer.from(xml, "utf8").toString("base64") };
|
|
258
466
|
};
|
|
259
467
|
const checkKey = (key) => {
|
|
260
|
-
if (!/^\d{44}$/.test(key)) throw fail("CHAVE_INVALIDA", "Chave fiscal inv\xE1lida.");
|
|
468
|
+
if (typeof key !== "string" || !/^\d{44}$/.test(key)) throw fail("CHAVE_INVALIDA", "Chave fiscal inv\xE1lida.", void 0, false, { campo: "chave" });
|
|
261
469
|
};
|
|
262
470
|
const reason = (value) => {
|
|
263
|
-
if (typeof value !== "string" || value.length < 15 || value.length > 255) throw fail("JUSTIFICATIVA_INVALIDA", "Justificativa deve ter de 15 a 255 caracteres.");
|
|
471
|
+
if (typeof value !== "string" || value.length < 15 || value.length > 255) throw fail("JUSTIFICATIVA_INVALIDA", "Justificativa deve ter de 15 a 255 caracteres.", void 0, false, { campo: "justificativa" });
|
|
472
|
+
};
|
|
473
|
+
const checkObject = (data, campo) => {
|
|
474
|
+
if (!plain(data)) throw fail("OPERACAO_INVALIDA", "Informe os par\xE2metros da opera\xE7\xE3o como objeto.", void 0, false, { campo });
|
|
264
475
|
};
|
|
265
476
|
return {
|
|
266
477
|
gerarXml: (documento, op) => request("gerarXml", { documento }, op),
|
|
@@ -268,45 +479,51 @@ function criarEmissor(options) {
|
|
|
268
479
|
assinar: (xml, op) => request("assinar", xmlData(xml), op),
|
|
269
480
|
transmitir: (xml, op) => request("transmitir", xmlData(xml), op),
|
|
270
481
|
consultar: (consulta, op) => {
|
|
482
|
+
checkObject(consulta, "consulta");
|
|
271
483
|
checkKey(consulta.chave);
|
|
272
|
-
if (consulta.recibo && !/^\d{15}$/.test(consulta.recibo)) throw fail("RECIBO_INVALIDO", "Recibo inv\xE1lido.");
|
|
484
|
+
if (consulta.recibo !== void 0 && (typeof consulta.recibo !== "string" || !/^\d{15}$/.test(consulta.recibo))) throw fail("RECIBO_INVALIDO", "Recibo inv\xE1lido.", void 0, false, { campo: "recibo" });
|
|
273
485
|
return request("consultar", consulta, op);
|
|
274
486
|
},
|
|
275
487
|
cancelar: (data, op) => {
|
|
488
|
+
checkObject(data, "cancelamento");
|
|
276
489
|
checkKey(data.chave);
|
|
277
490
|
reason(data.justificativa);
|
|
278
|
-
if (!/^\d{15}$/.test(data.protocolo)) throw fail("PROTOCOLO_INVALIDO", "Protocolo inv\xE1lido.");
|
|
491
|
+
if (typeof data.protocolo !== "string" || !/^\d{15}$/.test(data.protocolo)) throw fail("PROTOCOLO_INVALIDO", "Protocolo inv\xE1lido.", void 0, false, { campo: "protocolo" });
|
|
279
492
|
return request("cancelar", data, op);
|
|
280
493
|
},
|
|
281
494
|
cartaCorrecao: (data, op) => {
|
|
495
|
+
checkObject(data, "cartaCorrecao");
|
|
282
496
|
if (cfg.modelo !== 55) throw fail("OPERACAO_NAO_SUPORTADA", "Carta de corre\xE7\xE3o exige NF-e modelo 55.");
|
|
283
497
|
checkKey(data.chave);
|
|
284
|
-
if (typeof data.correcao !== "string" || data.correcao.length < 15 || data.correcao.length > 1e3 || !Number.isInteger(data.sequenciaEvento ?? 1) || (data.sequenciaEvento ?? 1) < 1 || (data.sequenciaEvento ?? 1) > 20) throw fail("CORRECAO_INVALIDA", "Dados da carta de corre\xE7\xE3o inv\xE1lidos.");
|
|
498
|
+
if (typeof data.correcao !== "string" || data.correcao.length < 15 || data.correcao.length > 1e3 || !Number.isInteger(data.sequenciaEvento ?? 1) || (data.sequenciaEvento ?? 1) < 1 || (data.sequenciaEvento ?? 1) > 20) throw fail("CORRECAO_INVALIDA", "Dados da carta de corre\xE7\xE3o inv\xE1lidos.", void 0, false, { campo: "cartaCorrecao" });
|
|
285
499
|
return request("cartaCorrecao", { ...data, sequenciaEvento: data.sequenciaEvento ?? 1 }, op);
|
|
286
500
|
},
|
|
287
501
|
inutilizar: (data, op) => {
|
|
502
|
+
checkObject(data, "inutilizacao");
|
|
288
503
|
reason(data.justificativa);
|
|
289
|
-
if (!Number.isInteger(data.ano) || data.ano < 0 || data.ano > 99 || !Number.isInteger(data.serie) || data.serie < 0 || data.serie > 999 || !Number.isInteger(data.numeroInicial) || data.numeroInicial < 1 || !Number.isInteger(data.numeroFinal) || data.numeroFinal < data.numeroInicial || data.numeroFinal > 999999999) throw fail("INUTILIZACAO_INVALIDA", "Faixa de inutiliza\xE7\xE3o inv\xE1lida.");
|
|
504
|
+
if (!Number.isInteger(data.ano) || data.ano < 0 || data.ano > 99 || !Number.isInteger(data.serie) || data.serie < 0 || data.serie > 999 || !Number.isInteger(data.numeroInicial) || data.numeroInicial < 1 || !Number.isInteger(data.numeroFinal) || data.numeroFinal < data.numeroInicial || data.numeroFinal > 999999999) throw fail("INUTILIZACAO_INVALIDA", "Faixa de inutiliza\xE7\xE3o inv\xE1lida.", void 0, false, { campo: "inutilizacao" });
|
|
290
505
|
return request("inutilizar", { inutilizacao: { ano: data.ano, serie: data.serie, numeroInicial: data.numeroInicial, numeroFinal: data.numeroFinal }, justificativa: data.justificativa }, op);
|
|
291
506
|
},
|
|
292
507
|
async fechar() {
|
|
293
|
-
if (closed)
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
item.signal?.removeEventListener("abort", item.abort);
|
|
297
|
-
item.bytes.fill(0);
|
|
298
|
-
item.reject(fail("EMISSOR_FECHADO", "Emissor encerrado."));
|
|
508
|
+
if (!closed) {
|
|
509
|
+
closed = true;
|
|
510
|
+
rejectQueue();
|
|
299
511
|
}
|
|
300
512
|
const running = current;
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
513
|
+
try {
|
|
514
|
+
running?.stop();
|
|
515
|
+
if (running) await running.done;
|
|
516
|
+
} finally {
|
|
517
|
+
certificate?.pfx?.fill(0);
|
|
518
|
+
}
|
|
304
519
|
}
|
|
305
520
|
};
|
|
306
521
|
}
|
|
307
522
|
export {
|
|
308
523
|
ErroAcbrNode,
|
|
309
524
|
PROTOCOL_VERSION,
|
|
310
|
-
criarEmissor
|
|
525
|
+
criarEmissor,
|
|
526
|
+
diagnosticarErro,
|
|
527
|
+
diagnosticarResultado
|
|
311
528
|
};
|
|
312
529
|
//# sourceMappingURL=runtime.js.map
|