foxnfe 1.3.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.
@@ -0,0 +1,64 @@
1
+ import { Client } from './client.js';
2
+ /**
3
+ * Eventos pós-emissão da NF-e (capacidade 8): Carta de Correção Eletrônica.
4
+ * A CC-e é assíncrona e durável: acompanhe pelo webhook `nfe.cce.registered` /
5
+ * `nfe.cce.rejected` ou pela listagem.
6
+ */
7
+ export declare class NfeEvents {
8
+ private readonly client;
9
+ constructor(client: Client);
10
+ /** Lista as CC-e da NF-e (sequência, status, protocolo). */
11
+ cceList(invoiceId: number): Promise<Record<string, unknown>>;
12
+ /**
13
+ * Solicita uma CC-e (15..1000 caracteres). `sequencial` (1..20) é opcional: sem ele
14
+ * o servidor aloca a próxima sequência durável sob lock.
15
+ */
16
+ cceCreate(invoiceId: number, correcao: string, sequencial?: number): Promise<Record<string, unknown>>;
17
+ /** Atores interessados (110150) já registrados para a NF-e. */
18
+ atorInteressadoList(invoiceId: number): Promise<Record<string, unknown>>;
19
+ /** Registra ator interessado. `documento` = CPF (11) ou CNPJ (14) só dígitos. */
20
+ atorInteressado(invoiceId: number, dados: AtorInteressadoRequest): Promise<Record<string, unknown>>;
21
+ insucessoEntregaList(invoiceId: number): Promise<Record<string, unknown>>;
22
+ /** Insucesso na entrega (110192). `tp_motivo` 1..4; 4 exige `justificativa` (15..250). A imagem não é persistida. */
23
+ insucessoEntrega(invoiceId: number, dados: InsucessoEntregaRequest): Promise<Record<string, unknown>>;
24
+ /** Cancela um insucesso na entrega já registrado (110193). */
25
+ cancelarInsucessoEntrega(invoiceId: number, eventoId: number): Promise<Record<string, unknown>>;
26
+ inutilizacoes(): Promise<Record<string, unknown>>;
27
+ inutilizacao(id: number): Promise<Record<string, unknown>>;
28
+ /** Inutiliza uma faixa de numeração (assíncrono e durável). */
29
+ inutilizar(dados: InutilizacaoRequest): Promise<Record<string, unknown>>;
30
+ /** Catálogo dos tipos de evento aceitos, com campos e autor (emitente/adquirente). */
31
+ contratos(): Promise<Record<string, unknown>>;
32
+ eventos(invoiceId: number): Promise<Record<string, unknown>>;
33
+ /** Registra um evento de contrato na NF-e própria: `tipo` do catálogo + campos do contrato. */
34
+ registrarEvento(invoiceId: number, tipo: string, payload?: Record<string, unknown>, sequencial?: number): Promise<Record<string, unknown>>;
35
+ eventosRecebida(distribuicaoId: number): Promise<Record<string, unknown>>;
36
+ /** Registra um evento de contrato numa NF-e recebida (autor adquirente). */
37
+ registrarEventoRecebida(distribuicaoId: number, tipo: string, payload?: Record<string, unknown>, sequencial?: number): Promise<Record<string, unknown>>;
38
+ private static tipo;
39
+ private static id;
40
+ }
41
+ export interface AtorInteressadoRequest {
42
+ documento: string;
43
+ tp_autor?: 1 | 2 | 3;
44
+ tp_autorizacao?: 0 | 1;
45
+ sequencial?: number;
46
+ }
47
+ export interface InsucessoEntregaRequest {
48
+ dh_tentativa: string;
49
+ tp_motivo: 1 | 2 | 3 | 4;
50
+ justificativa?: string;
51
+ n_tentativa?: number;
52
+ latitude?: number;
53
+ longitude?: number;
54
+ imagem_base64?: string;
55
+ sequencial?: number;
56
+ }
57
+ export interface InutilizacaoRequest {
58
+ serie: number;
59
+ numero_inicial: number;
60
+ numero_final: number;
61
+ justificativa: string;
62
+ modelo?: 55 | 65;
63
+ ano?: number;
64
+ }
package/dist/events.js ADDED
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NfeEvents = void 0;
4
+ /**
5
+ * Eventos pós-emissão da NF-e (capacidade 8): Carta de Correção Eletrônica.
6
+ * A CC-e é assíncrona e durável: acompanhe pelo webhook `nfe.cce.registered` /
7
+ * `nfe.cce.rejected` ou pela listagem.
8
+ */
9
+ class NfeEvents {
10
+ constructor(client) {
11
+ this.client = client;
12
+ }
13
+ /** Lista as CC-e da NF-e (sequência, status, protocolo). */
14
+ cceList(invoiceId) {
15
+ NfeEvents.id(invoiceId);
16
+ return this.client.get(`nfe/${invoiceId}/cce`);
17
+ }
18
+ /**
19
+ * Solicita uma CC-e (15..1000 caracteres). `sequencial` (1..20) é opcional: sem ele
20
+ * o servidor aloca a próxima sequência durável sob lock.
21
+ */
22
+ cceCreate(invoiceId, correcao, sequencial) {
23
+ NfeEvents.id(invoiceId);
24
+ const len = [...correcao.trim()].length;
25
+ if (len < 15 || len > 1000)
26
+ throw new TypeError('correcao deve ter entre 15 e 1000 caracteres.');
27
+ if (sequencial !== undefined && (!Number.isInteger(sequencial) || sequencial < 1 || sequencial > 20)) {
28
+ throw new TypeError('sequencial deve ser inteiro entre 1 e 20.');
29
+ }
30
+ return this.client.post(`nfe/${invoiceId}/cce`, { correcao, ...(sequencial !== undefined ? { sequencial } : {}) });
31
+ }
32
+ // ── 1.3.0 — outros eventos da NF-e própria (L17) ─────────────────────────
33
+ /** Atores interessados (110150) já registrados para a NF-e. */
34
+ atorInteressadoList(invoiceId) {
35
+ NfeEvents.id(invoiceId);
36
+ return this.client.get(`nfe/${invoiceId}/ator-interessado`);
37
+ }
38
+ /** Registra ator interessado. `documento` = CPF (11) ou CNPJ (14) só dígitos. */
39
+ atorInteressado(invoiceId, dados) {
40
+ NfeEvents.id(invoiceId);
41
+ if (!/^(?:\d{11}|\d{14})$/.test(dados.documento))
42
+ throw new TypeError('documento deve ter 11 (CPF) ou 14 (CNPJ) dígitos.');
43
+ return this.client.post(`nfe/${invoiceId}/ator-interessado`, dados);
44
+ }
45
+ insucessoEntregaList(invoiceId) {
46
+ NfeEvents.id(invoiceId);
47
+ return this.client.get(`nfe/${invoiceId}/insucesso-entrega`);
48
+ }
49
+ /** Insucesso na entrega (110192). `tp_motivo` 1..4; 4 exige `justificativa` (15..250). A imagem não é persistida. */
50
+ insucessoEntrega(invoiceId, dados) {
51
+ NfeEvents.id(invoiceId);
52
+ if (![1, 2, 3, 4].includes(dados.tp_motivo))
53
+ throw new TypeError('tp_motivo deve ser 1, 2, 3 ou 4.');
54
+ const j = [...(dados.justificativa ?? '').trim()].length;
55
+ if (dados.tp_motivo === 4 && (j < 15 || j > 250))
56
+ throw new TypeError('justificativa (15..250) é obrigatória quando tp_motivo=4.');
57
+ return this.client.post(`nfe/${invoiceId}/insucesso-entrega`, dados);
58
+ }
59
+ /** Cancela um insucesso na entrega já registrado (110193). */
60
+ cancelarInsucessoEntrega(invoiceId, eventoId) {
61
+ NfeEvents.id(invoiceId);
62
+ NfeEvents.id(eventoId);
63
+ return this.client.post(`nfe/${invoiceId}/insucesso-entrega/${eventoId}/cancelar`);
64
+ }
65
+ inutilizacoes() { return this.client.get('nfe/inutilizacoes'); }
66
+ inutilizacao(id) { NfeEvents.id(id); return this.client.get(`nfe/inutilizacoes/${id}`); }
67
+ /** Inutiliza uma faixa de numeração (assíncrono e durável). */
68
+ inutilizar(dados) {
69
+ if (!Number.isInteger(dados.numero_inicial) || !Number.isInteger(dados.numero_final) || dados.numero_inicial < 1 || dados.numero_final < dados.numero_inicial) {
70
+ throw new TypeError('numero_inicial/numero_final devem ser inteiros com numero_final >= numero_inicial >= 1.');
71
+ }
72
+ const len = [...dados.justificativa.trim()].length;
73
+ if (len < 15 || len > 255)
74
+ throw new TypeError('justificativa deve ter entre 15 e 255 caracteres.');
75
+ return this.client.post('nfe/inutilizacoes', dados);
76
+ }
77
+ // ── 1.3.0 — eventos por contrato oficial (conciliação financeira, RTC…) (L18) ──
78
+ /** Catálogo dos tipos de evento aceitos, com campos e autor (emitente/adquirente). */
79
+ contratos() { return this.client.get('nfe/eventos/contratos'); }
80
+ eventos(invoiceId) {
81
+ NfeEvents.id(invoiceId);
82
+ return this.client.get(`nfe/${invoiceId}/eventos`);
83
+ }
84
+ /** Registra um evento de contrato na NF-e própria: `tipo` do catálogo + campos do contrato. */
85
+ registrarEvento(invoiceId, tipo, payload = {}, sequencial) {
86
+ NfeEvents.id(invoiceId);
87
+ NfeEvents.tipo(tipo);
88
+ return this.client.post(`nfe/${invoiceId}/eventos`, { tipo, ...(sequencial !== undefined ? { sequencial } : {}), ...payload });
89
+ }
90
+ eventosRecebida(distribuicaoId) {
91
+ NfeEvents.id(distribuicaoId);
92
+ return this.client.get(`nfe/recebidas/${distribuicaoId}/eventos`);
93
+ }
94
+ /** Registra um evento de contrato numa NF-e recebida (autor adquirente). */
95
+ registrarEventoRecebida(distribuicaoId, tipo, payload = {}, sequencial) {
96
+ NfeEvents.id(distribuicaoId);
97
+ NfeEvents.tipo(tipo);
98
+ return this.client.post(`nfe/recebidas/${distribuicaoId}/eventos`, { tipo, ...(sequencial !== undefined ? { sequencial } : {}), ...payload });
99
+ }
100
+ static tipo(tipo) {
101
+ if (!/^[a-z0-9_]{3,60}$/.test(tipo))
102
+ throw new TypeError('tipo deve ser um identificador do catálogo (GET nfe/eventos/contratos).');
103
+ }
104
+ static id(id) {
105
+ if (!Number.isInteger(id) || id < 1)
106
+ throw new TypeError('invoiceId deve ser inteiro positivo.');
107
+ }
108
+ }
109
+ exports.NfeEvents = NfeEvents;
@@ -0,0 +1,34 @@
1
+ import { Client } from './client.js';
2
+ export { Client };
3
+ export { Nfe } from './nfe.js';
4
+ export { Nfse } from './nfse.js';
5
+ export { Mcp } from './mcp.js';
6
+ export { Webhook } from './webhook.js';
7
+ export { Reference } from './reference.js';
8
+ export type { ReferenceListParams, ReferencePage, ReferenceItem } from './reference.js';
9
+ export { Documents } from './documents.js';
10
+ export type { DocumentListParams } from './documents.js';
11
+ export { NfeEvents } from './events.js';
12
+ export type { AtorInteressadoRequest, InsucessoEntregaRequest, InutilizacaoRequest } from './events.js';
13
+ export { Rtc } from './rtc.js';
14
+ export type { RtcResolveRequest, RtcScenarioRequest } from './rtc.js';
15
+ export { Support } from './support.js';
16
+ export type { SupportCaseRequest } from './support.js';
17
+ export { Distribuicao } from './distribuicao.js';
18
+ export type { ManifestacaoRequest } from './distribuicao.js';
19
+ export type { WebhookConfig, WebhookConfigResponse, WebhookUpdateResponse, WebhookDelivery, WebhookDeliveryPage } from './webhook.js';
20
+ export { FoxNfeException, ApiException, AuthException } from './errors.js';
21
+ export type { ClientOptions, NfeEmitRequest, NfeResource, NfeRejection, NfeCancelRequest, NfseEmitRequest, NfseResource, NfseCancelRequest, NfseSubstituteRequest, McpTool, McpToolCallRequest, McpToolCallResponse, LoginResponse, ApiErrorResponse, } from './types.js';
22
+ /**
23
+ * Cria um cliente FOX NF-e pronto para uso.
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * import { createClient, Nfe } from 'foxnfe';
28
+ *
29
+ * const client = createClient({ tenantSlug: 'minha-empresa' });
30
+ * await client.login('email@empresa.com', 'senha');
31
+ * const nfe = new Nfe(client); // nfe.emit(payload)
32
+ * ```
33
+ */
34
+ export declare function createClient(options: import('./types.js').ClientOptions): Client;
package/dist/index.js ADDED
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthException = exports.ApiException = exports.FoxNfeException = exports.Distribuicao = exports.Support = exports.Rtc = exports.NfeEvents = exports.Documents = exports.Reference = exports.Webhook = exports.Mcp = exports.Nfse = exports.Nfe = exports.Client = void 0;
4
+ exports.createClient = createClient;
5
+ const client_js_1 = require("./client.js");
6
+ Object.defineProperty(exports, "Client", { enumerable: true, get: function () { return client_js_1.Client; } });
7
+ var nfe_js_1 = require("./nfe.js");
8
+ Object.defineProperty(exports, "Nfe", { enumerable: true, get: function () { return nfe_js_1.Nfe; } });
9
+ var nfse_js_1 = require("./nfse.js");
10
+ Object.defineProperty(exports, "Nfse", { enumerable: true, get: function () { return nfse_js_1.Nfse; } });
11
+ var mcp_js_1 = require("./mcp.js");
12
+ Object.defineProperty(exports, "Mcp", { enumerable: true, get: function () { return mcp_js_1.Mcp; } });
13
+ var webhook_js_1 = require("./webhook.js");
14
+ Object.defineProperty(exports, "Webhook", { enumerable: true, get: function () { return webhook_js_1.Webhook; } });
15
+ var reference_js_1 = require("./reference.js");
16
+ Object.defineProperty(exports, "Reference", { enumerable: true, get: function () { return reference_js_1.Reference; } });
17
+ var documents_js_1 = require("./documents.js");
18
+ Object.defineProperty(exports, "Documents", { enumerable: true, get: function () { return documents_js_1.Documents; } });
19
+ var events_js_1 = require("./events.js");
20
+ Object.defineProperty(exports, "NfeEvents", { enumerable: true, get: function () { return events_js_1.NfeEvents; } });
21
+ var rtc_js_1 = require("./rtc.js");
22
+ Object.defineProperty(exports, "Rtc", { enumerable: true, get: function () { return rtc_js_1.Rtc; } });
23
+ var support_js_1 = require("./support.js");
24
+ Object.defineProperty(exports, "Support", { enumerable: true, get: function () { return support_js_1.Support; } });
25
+ var distribuicao_js_1 = require("./distribuicao.js");
26
+ Object.defineProperty(exports, "Distribuicao", { enumerable: true, get: function () { return distribuicao_js_1.Distribuicao; } });
27
+ var errors_js_1 = require("./errors.js");
28
+ Object.defineProperty(exports, "FoxNfeException", { enumerable: true, get: function () { return errors_js_1.FoxNfeException; } });
29
+ Object.defineProperty(exports, "ApiException", { enumerable: true, get: function () { return errors_js_1.ApiException; } });
30
+ Object.defineProperty(exports, "AuthException", { enumerable: true, get: function () { return errors_js_1.AuthException; } });
31
+ /**
32
+ * Cria um cliente FOX NF-e pronto para uso.
33
+ *
34
+ * @example
35
+ * ```typescript
36
+ * import { createClient, Nfe } from 'foxnfe';
37
+ *
38
+ * const client = createClient({ tenantSlug: 'minha-empresa' });
39
+ * await client.login('email@empresa.com', 'senha');
40
+ * const nfe = new Nfe(client); // nfe.emit(payload)
41
+ * ```
42
+ */
43
+ function createClient(options) {
44
+ return new client_js_1.Client(options);
45
+ }
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { Client } from './client.js';
2
+ import { McpTool, McpToolCallResponse } from './types.js';
3
+ export declare class Mcp {
4
+ private readonly client;
5
+ private static readonly MCP_PATH;
6
+ constructor(client: Client);
7
+ /** Lista todas as 24 tools MCP disponíveis. */
8
+ listTools(): Promise<{
9
+ tools: McpTool[];
10
+ }>;
11
+ /** Chama uma tool MCP pelo nome. */
12
+ callTool(tool: string, input?: Record<string, unknown>): Promise<McpToolCallResponse>;
13
+ /** Retorna informações do servidor MCP (protocolo, versão, capacidades). */
14
+ initialize(): Promise<{
15
+ protocolVersion: string;
16
+ serverInfo: {
17
+ name: string;
18
+ version: string;
19
+ };
20
+ capabilities: Record<string, unknown>;
21
+ }>;
22
+ }
package/dist/mcp.js ADDED
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Mcp = void 0;
4
+ class Mcp {
5
+ constructor(client) {
6
+ this.client = client;
7
+ }
8
+ /** Lista todas as 24 tools MCP disponíveis. */
9
+ async listTools() {
10
+ return this.client.post(Mcp.MCP_PATH, {
11
+ jsonrpc: '2.0',
12
+ id: 1,
13
+ method: 'tools/list',
14
+ params: {},
15
+ });
16
+ }
17
+ /** Chama uma tool MCP pelo nome. */
18
+ async callTool(tool, input = {}) {
19
+ return this.client.post(Mcp.MCP_PATH, {
20
+ jsonrpc: '2.0',
21
+ id: 2,
22
+ method: 'tools/call',
23
+ params: { name: tool, arguments: input },
24
+ });
25
+ }
26
+ /** Retorna informações do servidor MCP (protocolo, versão, capacidades). */
27
+ async initialize() {
28
+ return this.client.post(Mcp.MCP_PATH, {
29
+ jsonrpc: '2.0',
30
+ id: 0,
31
+ method: 'initialize',
32
+ params: {
33
+ protocolVersion: '2024-11-05',
34
+ clientInfo: { name: 'foxnfe-node-sdk', version: '1.0.0' },
35
+ capabilities: {},
36
+ },
37
+ });
38
+ }
39
+ }
40
+ exports.Mcp = Mcp;
41
+ Mcp.MCP_PATH = 'mcp';
package/dist/nfe.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { Client } from './client.js';
2
+ import { NfeCancelRequest, NfeEmitRequest, NfeResource } from './types.js';
3
+ export declare class Nfe {
4
+ private readonly client;
5
+ constructor(client: Client);
6
+ /** Emite uma NF-e. Retorna imediatamente com status 'pending'. */
7
+ emit(payload: NfeEmitRequest): Promise<{
8
+ id: number;
9
+ status: string;
10
+ job_id: string;
11
+ }>;
12
+ /** Consulta status e dados de uma NF-e. */
13
+ get(id: number): Promise<NfeResource>;
14
+ /** Baixa o XML assinado da NF-e autorizada. */
15
+ xml(id: number): Promise<Buffer>;
16
+ /** Baixa o DANFE em PDF. */
17
+ pdf(id: number): Promise<Buffer>;
18
+ /** Cancela uma NF-e autorizada. */
19
+ cancel(id: number, payload: NfeCancelRequest): Promise<NfeResource>;
20
+ /** Catálogo de rejeições SEFAZ: categoria, ação e dica por cStat (xMotivo oficial preservado). */
21
+ rejeicoes(): Promise<Record<string, unknown>>;
22
+ rejeicao(cstat: string | number): Promise<Record<string, unknown>>;
23
+ /** Matriz de homologação (modelo/UF/cenário) e últimas corridas. */
24
+ homologacao(): Promise<Record<string, unknown>>;
25
+ /**
26
+ * Executa os cenários de homologação de um modelo. `simulated` (padrão) gera amostras
27
+ * XML/PDF assinadas sem transmitir; `sefaz` só com autorização no servidor (409 caso contrário).
28
+ */
29
+ homologacaoRun(modelo: 55 | 65, cenario?: string, mode?: 'simulated' | 'sefaz'): Promise<Record<string, unknown>>;
30
+ homologacaoXml(runId: number): Promise<Buffer>;
31
+ homologacaoPdf(runId: number): Promise<Buffer>;
32
+ private static id;
33
+ /**
34
+ * Aguarda até que a NF-e saia do status 'pending'.
35
+ * @param maxWaitMs Timeout total em ms (default 120000)
36
+ * @param pollMs Intervalo de polling em ms (default 3000)
37
+ */
38
+ waitForAuthorization(id: number, maxWaitMs?: number, pollMs?: number): Promise<NfeResource>;
39
+ }
package/dist/nfe.js ADDED
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Nfe = void 0;
4
+ const errors_js_1 = require("./errors.js");
5
+ class Nfe {
6
+ constructor(client) {
7
+ this.client = client;
8
+ }
9
+ /** Emite uma NF-e. Retorna imediatamente com status 'pending'. */
10
+ async emit(payload) {
11
+ return this.client.post('nfe/emit', payload);
12
+ }
13
+ /** Consulta status e dados de uma NF-e. */
14
+ async get(id) {
15
+ return this.client.get(`nfe/${id}`);
16
+ }
17
+ /** Baixa o XML assinado da NF-e autorizada. */
18
+ async xml(id) {
19
+ return this.client.download(`nfe/${id}/xml`);
20
+ }
21
+ /** Baixa o DANFE em PDF. */
22
+ async pdf(id) {
23
+ return this.client.download(`nfe/${id}/pdf`);
24
+ }
25
+ /** Cancela uma NF-e autorizada. */
26
+ async cancel(id, payload) {
27
+ return this.client.post(`nfe/${id}/cancel`, payload);
28
+ }
29
+ // ── 1.3.0 — rejeições explicadas e homologação por modelo (L20) ──────────
30
+ /** Catálogo de rejeições SEFAZ: categoria, ação e dica por cStat (xMotivo oficial preservado). */
31
+ rejeicoes() { return this.client.get('nfe/rejeicoes'); }
32
+ rejeicao(cstat) {
33
+ const c = String(cstat);
34
+ if (!/^\d{3}$/.test(c))
35
+ throw new TypeError('cstat deve ter 3 dígitos.');
36
+ return this.client.get(`nfe/rejeicoes/${c}`);
37
+ }
38
+ /** Matriz de homologação (modelo/UF/cenário) e últimas corridas. */
39
+ homologacao() { return this.client.get('nfe/homologacao'); }
40
+ /**
41
+ * Executa os cenários de homologação de um modelo. `simulated` (padrão) gera amostras
42
+ * XML/PDF assinadas sem transmitir; `sefaz` só com autorização no servidor (409 caso contrário).
43
+ */
44
+ homologacaoRun(modelo, cenario, mode = 'simulated') {
45
+ if (modelo !== 55 && modelo !== 65)
46
+ throw new TypeError('modelo deve ser 55 ou 65.');
47
+ if (mode !== 'simulated' && mode !== 'sefaz')
48
+ throw new TypeError("mode deve ser 'simulated' ou 'sefaz'.");
49
+ return this.client.post('nfe/homologacao/run', { modelo, mode, ...(cenario ? { cenario } : {}) });
50
+ }
51
+ homologacaoXml(runId) { Nfe.id(runId); return this.client.download(`nfe/homologacao/${runId}/xml`); }
52
+ homologacaoPdf(runId) { Nfe.id(runId); return this.client.download(`nfe/homologacao/${runId}/pdf`); }
53
+ static id(id) {
54
+ if (!Number.isInteger(id) || id < 1)
55
+ throw new TypeError('id deve ser inteiro positivo.');
56
+ }
57
+ /**
58
+ * Aguarda até que a NF-e saia do status 'pending'.
59
+ * @param maxWaitMs Timeout total em ms (default 120000)
60
+ * @param pollMs Intervalo de polling em ms (default 3000)
61
+ */
62
+ async waitForAuthorization(id, maxWaitMs = 120000, pollMs = 3000) {
63
+ const deadline = Date.now() + maxWaitMs;
64
+ while (Date.now() < deadline) {
65
+ const nfe = await this.get(id);
66
+ if (nfe.status !== 'pending')
67
+ return nfe;
68
+ await new Promise(r => setTimeout(r, pollMs));
69
+ }
70
+ throw new errors_js_1.FoxNfeException(`NF-e ${id} ainda pendente após ${maxWaitMs}ms.`);
71
+ }
72
+ }
73
+ exports.Nfe = Nfe;
package/dist/nfse.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ import { Client } from './client.js';
2
+ import { NfseCancelRequest, NfseEmitRequest, NfseResource, NfseSubstituteRequest } from './types.js';
3
+ export declare class Nfse {
4
+ private readonly client;
5
+ constructor(client: Client);
6
+ /** Emite NFSe via Padrão Nacional gov.br (REST/JSON). */
7
+ emit(payload: NfseEmitRequest): Promise<{
8
+ id: number;
9
+ status: string;
10
+ }>;
11
+ /** Consulta NFSe por ID interno. */
12
+ get(id: number): Promise<NfseResource>;
13
+ /** Consulta NFSe por número de RPS. */
14
+ consultByNumero(numero: string): Promise<NfseResource>;
15
+ /** Consulta NFSe pela chave de acesso gov.br. */
16
+ consultByChave(chave: string): Promise<NfseResource>;
17
+ /** Cancela uma NFSe. */
18
+ cancel(id: number, payload: NfseCancelRequest): Promise<NfseResource>;
19
+ /** Substitui uma NFSe (cancela + emite nova). */
20
+ substitute(id: number, payload: NfseSubstituteRequest): Promise<NfseResource>;
21
+ /** Municípios com provedor, tipo de integração, adesão e status por operação (50/página). */
22
+ cobertura(params?: {
23
+ uf?: string;
24
+ q?: string;
25
+ provider?: string;
26
+ page?: number;
27
+ }): Promise<Record<string, unknown>>;
28
+ /** Detalhe de um município (IBGE 7 dígitos) com capacidades e prova por operação. */
29
+ coberturaMunicipio(ibge: string): Promise<Record<string, unknown>>;
30
+ /** Matriz por provedor (suportada | composta | nao_oferecida | nao_implementada) e provas. */
31
+ coberturaProvedores(): Promise<Record<string, unknown>>;
32
+ }
package/dist/nfse.js ADDED
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Nfse = void 0;
4
+ class Nfse {
5
+ constructor(client) {
6
+ this.client = client;
7
+ }
8
+ /** Emite NFSe via Padrão Nacional gov.br (REST/JSON). */
9
+ async emit(payload) {
10
+ return this.client.post('nfse/emit', payload);
11
+ }
12
+ /** Consulta NFSe por ID interno. */
13
+ async get(id) {
14
+ return this.client.get(`nfse/${id}`);
15
+ }
16
+ /** Consulta NFSe por número de RPS. */
17
+ async consultByNumero(numero) {
18
+ return this.client.get(`nfse/consult/numero/${numero}`);
19
+ }
20
+ /** Consulta NFSe pela chave de acesso gov.br. */
21
+ async consultByChave(chave) {
22
+ return this.client.get(`nfse/consult/${chave}`);
23
+ }
24
+ /** Cancela uma NFSe. */
25
+ async cancel(id, payload) {
26
+ return this.client.post(`nfse/${id}/cancel`, payload);
27
+ }
28
+ /** Substitui uma NFSe (cancela + emite nova). */
29
+ async substitute(id, payload) {
30
+ return this.client.post(`nfse/${id}/substitute`, payload);
31
+ }
32
+ // ── 1.3.0 — cobertura por município/provedor (L21) ───────────────────────
33
+ /** Municípios com provedor, tipo de integração, adesão e status por operação (50/página). */
34
+ cobertura(params = {}) {
35
+ const p = {};
36
+ for (const [k, v] of Object.entries(params))
37
+ if (v !== undefined && v !== null)
38
+ p[k] = String(v);
39
+ return this.client.get('nfse/cobertura', p);
40
+ }
41
+ /** Detalhe de um município (IBGE 7 dígitos) com capacidades e prova por operação. */
42
+ coberturaMunicipio(ibge) {
43
+ if (!/^\d{7}$/.test(ibge))
44
+ throw new TypeError('ibge deve ter 7 dígitos.');
45
+ return this.client.get(`nfse/cobertura/${ibge}`);
46
+ }
47
+ /** Matriz por provedor (suportada | composta | nao_oferecida | nao_implementada) e provas. */
48
+ coberturaProvedores() { return this.client.get('nfse/cobertura/provedores'); }
49
+ }
50
+ exports.Nfse = Nfse;
@@ -0,0 +1,51 @@
1
+ import { Client } from './client.js';
2
+ export interface ReferenceListParams {
3
+ q?: string;
4
+ uf?: string;
5
+ page?: number;
6
+ per_page?: number;
7
+ }
8
+ export interface ReferencePage<T = Record<string, unknown>> {
9
+ data: T[];
10
+ meta: {
11
+ page: number;
12
+ per_page: number;
13
+ total: number;
14
+ count: number;
15
+ ordered_by: string;
16
+ };
17
+ source: Record<string, unknown>;
18
+ available: boolean;
19
+ }
20
+ export interface ReferenceItem<T = Record<string, unknown>> {
21
+ data: T;
22
+ source: Record<string, unknown>;
23
+ available: boolean;
24
+ }
25
+ /**
26
+ * Consultas auxiliares (capacidade 21): municípios IBGE, CFOP, CNAE, NCM, Lista de
27
+ * Serviços Nacional (cTribNac), NBS 2.0, CEP e CNPJ. Somente leitura; toda resposta
28
+ * traz `source` com proveniência. Nunca é orientação fiscal.
29
+ */
30
+ export declare class Reference {
31
+ private readonly client;
32
+ constructor(client: Client);
33
+ municipalities(params?: ReferenceListParams): Promise<ReferencePage>;
34
+ municipality(code: string): Promise<ReferenceItem>;
35
+ cfop(params?: ReferenceListParams): Promise<ReferencePage>;
36
+ cfopCode(code: string): Promise<ReferenceItem>;
37
+ cnae(params?: ReferenceListParams): Promise<ReferencePage>;
38
+ cnaeCode(code: string): Promise<ReferenceItem>;
39
+ ncm(params?: ReferenceListParams): Promise<ReferencePage>;
40
+ ncmCode(code: string): Promise<ReferenceItem>;
41
+ servicosNacionais(params?: ReferenceListParams): Promise<ReferencePage>;
42
+ servicoNacional(code: string): Promise<ReferenceItem>;
43
+ nbs(params?: ReferenceListParams): Promise<ReferencePage>;
44
+ nbsCode(code: string): Promise<ReferenceItem>;
45
+ /** CEP: 8 dígitos (hífen opcional). 404 = inexistente; 503 = provedor indisponível (não cacheado). */
46
+ cep(cep: string): Promise<ReferenceItem>;
47
+ /** CNPJ: 14 caracteres (numérico ou alfanumérico); dígitos verificadores conferidos no servidor (422). */
48
+ cnpj(cnpj: string): Promise<ReferenceItem>;
49
+ private list;
50
+ private show;
51
+ }
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Reference = void 0;
4
+ /**
5
+ * Consultas auxiliares (capacidade 21): municípios IBGE, CFOP, CNAE, NCM, Lista de
6
+ * Serviços Nacional (cTribNac), NBS 2.0, CEP e CNPJ. Somente leitura; toda resposta
7
+ * traz `source` com proveniência. Nunca é orientação fiscal.
8
+ */
9
+ class Reference {
10
+ constructor(client) {
11
+ this.client = client;
12
+ }
13
+ municipalities(params = {}) { return this.list('municipalities', params); }
14
+ municipality(code) { return this.show('municipalities', code, /^\d{7}$/, 'código IBGE de 7 dígitos'); }
15
+ cfop(params = {}) { return this.list('cfop', params); }
16
+ cfopCode(code) { return this.show('cfop', code, /^\d{4}$/, 'CFOP de 4 dígitos'); }
17
+ cnae(params = {}) { return this.list('cnae', params); }
18
+ cnaeCode(code) { return this.show('cnae', code, /^\d{7}$/, 'CNAE de 7 dígitos'); }
19
+ ncm(params = {}) { return this.list('ncm', params); }
20
+ ncmCode(code) { return this.show('ncm', code, /^\d{2,8}$/, 'NCM de 2 a 8 dígitos'); }
21
+ servicosNacionais(params = {}) { return this.list('servicos-nacionais', params); }
22
+ servicoNacional(code) { return this.show('servicos-nacionais', code, /^\d{6}$/, 'cTribNac de 6 dígitos'); }
23
+ nbs(params = {}) { return this.list('nbs', params); }
24
+ nbsCode(code) { return this.show('nbs', code, /^\d{5,9}$/, 'NBS de 5 a 9 dígitos'); }
25
+ /** CEP: 8 dígitos (hífen opcional). 404 = inexistente; 503 = provedor indisponível (não cacheado). */
26
+ cep(cep) {
27
+ const digits = cep.replace(/\D/g, '');
28
+ if (!/^\d{8}$/.test(digits))
29
+ throw new TypeError('cep deve ter 8 dígitos.');
30
+ return this.client.get(`reference-data/cep/${digits}`);
31
+ }
32
+ /** CNPJ: 14 caracteres (numérico ou alfanumérico); dígitos verificadores conferidos no servidor (422). */
33
+ cnpj(cnpj) {
34
+ const clean = cnpj.replace(/[^0-9A-Za-z]/g, '').toUpperCase();
35
+ if (!/^[0-9A-Z]{14}$/.test(clean))
36
+ throw new TypeError('cnpj deve ter 14 caracteres.');
37
+ return this.client.get(`reference-data/cnpj/${clean}`);
38
+ }
39
+ list(dataset, params) {
40
+ const p = {};
41
+ for (const [k, v] of Object.entries(params))
42
+ if (v !== undefined && v !== null)
43
+ p[k] = String(v);
44
+ return this.client.get(`reference-data/${dataset}`, p);
45
+ }
46
+ show(dataset, code, re, label) {
47
+ if (!re.test(code))
48
+ throw new TypeError(`code inválido: esperado ${label}.`);
49
+ return this.client.get(`reference-data/${dataset}/${encodeURIComponent(code)}`);
50
+ }
51
+ }
52
+ exports.Reference = Reference;