UNPKG

@bruno-valero/gerencianet-sdk-typescript

Version:

Este pacote oferece uma SDK moderna para integrar a API da Gerencianet com TypeScript. Diferente da SDK oficial, esta versão foi desenvolvida com foco total no TypeScript, proporcionando segurança de tipos, melhor reportagem de erros e sugestões de código

1,623 lines (1,599 loc) 149 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // node_modules/dotenv/package.json var require_package = __commonJS({ "node_modules/dotenv/package.json"(exports2, module2) { module2.exports = { name: "dotenv", version: "16.4.5", description: "Loads environment variables from .env file", main: "lib/main.js", types: "lib/main.d.ts", exports: { ".": { types: "./lib/main.d.ts", require: "./lib/main.js", default: "./lib/main.js" }, "./config": "./config.js", "./config.js": "./config.js", "./lib/env-options": "./lib/env-options.js", "./lib/env-options.js": "./lib/env-options.js", "./lib/cli-options": "./lib/cli-options.js", "./lib/cli-options.js": "./lib/cli-options.js", "./package.json": "./package.json" }, scripts: { "dts-check": "tsc --project tests/types/tsconfig.json", lint: "standard", "lint-readme": "standard-markdown", pretest: "npm run lint && npm run dts-check", test: "tap tests/*.js --100 -Rspec", "test:coverage": "tap --coverage-report=lcov", prerelease: "npm test", release: "standard-version" }, repository: { type: "git", url: "git://github.com/motdotla/dotenv.git" }, funding: "https://dotenvx.com", keywords: [ "dotenv", "env", ".env", "environment", "variables", "config", "settings" ], readmeFilename: "README.md", license: "BSD-2-Clause", devDependencies: { "@definitelytyped/dtslint": "^0.0.133", "@types/node": "^18.11.3", decache: "^4.6.1", sinon: "^14.0.1", standard: "^17.0.0", "standard-markdown": "^7.1.0", "standard-version": "^9.5.0", tap: "^16.3.0", tar: "^6.1.11", typescript: "^4.8.4" }, engines: { node: ">=12" }, browser: { fs: false } }; } }); // node_modules/dotenv/lib/main.js var require_main = __commonJS({ "node_modules/dotenv/lib/main.js"(exports2, module2) { "use strict"; var fs2 = require("fs"); var path = require("path"); var os = require("os"); var crypto = require("crypto"); var packageJson = require_package(); var version = packageJson.version; var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; function parse(src) { const obj = {}; let lines = src.toString(); lines = lines.replace(/\r\n?/mg, "\n"); let match; while ((match = LINE.exec(lines)) != null) { const key = match[1]; let value = match[2] || ""; value = value.trim(); const maybeQuote = value[0]; value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2"); if (maybeQuote === '"') { value = value.replace(/\\n/g, "\n"); value = value.replace(/\\r/g, "\r"); } obj[key] = value; } return obj; } function _parseVault(options) { const vaultPath = _vaultPath(options); const result = DotenvModule.configDotenv({ path: vaultPath }); if (!result.parsed) { const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`); err.code = "MISSING_DATA"; throw err; } const keys = _dotenvKey(options).split(","); const length = keys.length; let decrypted; for (let i = 0; i < length; i++) { try { const key = keys[i].trim(); const attrs = _instructions(result, key); decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key); break; } catch (error) { if (i + 1 >= length) { throw error; } } } return DotenvModule.parse(decrypted); } function _log(message) { console.log(`[dotenv@${version}][INFO] ${message}`); } function _warn(message) { console.log(`[dotenv@${version}][WARN] ${message}`); } function _debug(message) { console.log(`[dotenv@${version}][DEBUG] ${message}`); } function _dotenvKey(options) { if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) { return options.DOTENV_KEY; } if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) { return process.env.DOTENV_KEY; } return ""; } function _instructions(result, dotenvKey) { let uri; try { uri = new URL(dotenvKey); } catch (error) { if (error.code === "ERR_INVALID_URL") { const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development"); err.code = "INVALID_DOTENV_KEY"; throw err; } throw error; } const key = uri.password; if (!key) { const err = new Error("INVALID_DOTENV_KEY: Missing key part"); err.code = "INVALID_DOTENV_KEY"; throw err; } const environment = uri.searchParams.get("environment"); if (!environment) { const err = new Error("INVALID_DOTENV_KEY: Missing environment part"); err.code = "INVALID_DOTENV_KEY"; throw err; } const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`; const ciphertext = result.parsed[environmentKey]; if (!ciphertext) { const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`); err.code = "NOT_FOUND_DOTENV_ENVIRONMENT"; throw err; } return { ciphertext, key }; } function _vaultPath(options) { let possibleVaultPath = null; if (options && options.path && options.path.length > 0) { if (Array.isArray(options.path)) { for (const filepath of options.path) { if (fs2.existsSync(filepath)) { possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`; } } } else { possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`; } } else { possibleVaultPath = path.resolve(process.cwd(), ".env.vault"); } if (fs2.existsSync(possibleVaultPath)) { return possibleVaultPath; } return null; } function _resolveHome(envPath) { return envPath[0] === "~" ? path.join(os.homedir(), envPath.slice(1)) : envPath; } function _configVault(options) { _log("Loading env from encrypted .env.vault"); const parsed = DotenvModule._parseVault(options); let processEnv = process.env; if (options && options.processEnv != null) { processEnv = options.processEnv; } DotenvModule.populate(processEnv, parsed, options); return { parsed }; } function configDotenv(options) { const dotenvPath = path.resolve(process.cwd(), ".env"); let encoding = "utf8"; const debug = Boolean(options && options.debug); if (options && options.encoding) { encoding = options.encoding; } else { if (debug) { _debug("No encoding is specified. UTF-8 is used by default"); } } let optionPaths = [dotenvPath]; if (options && options.path) { if (!Array.isArray(options.path)) { optionPaths = [_resolveHome(options.path)]; } else { optionPaths = []; for (const filepath of options.path) { optionPaths.push(_resolveHome(filepath)); } } } let lastError; const parsedAll = {}; for (const path2 of optionPaths) { try { const parsed = DotenvModule.parse(fs2.readFileSync(path2, { encoding })); DotenvModule.populate(parsedAll, parsed, options); } catch (e) { if (debug) { _debug(`Failed to load ${path2} ${e.message}`); } lastError = e; } } let processEnv = process.env; if (options && options.processEnv != null) { processEnv = options.processEnv; } DotenvModule.populate(processEnv, parsedAll, options); if (lastError) { return { parsed: parsedAll, error: lastError }; } else { return { parsed: parsedAll }; } } function config(options) { if (_dotenvKey(options).length === 0) { return DotenvModule.configDotenv(options); } const vaultPath = _vaultPath(options); if (!vaultPath) { _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`); return DotenvModule.configDotenv(options); } return DotenvModule._configVault(options); } function decrypt(encrypted, keyStr) { const key = Buffer.from(keyStr.slice(-64), "hex"); let ciphertext = Buffer.from(encrypted, "base64"); const nonce = ciphertext.subarray(0, 12); const authTag = ciphertext.subarray(-16); ciphertext = ciphertext.subarray(12, -16); try { const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce); aesgcm.setAuthTag(authTag); return `${aesgcm.update(ciphertext)}${aesgcm.final()}`; } catch (error) { const isRange = error instanceof RangeError; const invalidKeyLength = error.message === "Invalid key length"; const decryptionFailed = error.message === "Unsupported state or unable to authenticate data"; if (isRange || invalidKeyLength) { const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)"); err.code = "INVALID_DOTENV_KEY"; throw err; } else if (decryptionFailed) { const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY"); err.code = "DECRYPTION_FAILED"; throw err; } else { throw error; } } } function populate(processEnv, parsed, options = {}) { const debug = Boolean(options && options.debug); const override = Boolean(options && options.override); if (typeof parsed !== "object") { const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate"); err.code = "OBJECT_REQUIRED"; throw err; } for (const key of Object.keys(parsed)) { if (Object.prototype.hasOwnProperty.call(processEnv, key)) { if (override === true) { processEnv[key] = parsed[key]; } if (debug) { if (override === true) { _debug(`"${key}" is already defined and WAS overwritten`); } else { _debug(`"${key}" is already defined and was NOT overwritten`); } } } else { processEnv[key] = parsed[key]; } } } var DotenvModule = { configDotenv, _configVault, _parseVault, config, decrypt, parse, populate }; module2.exports.configDotenv = DotenvModule.configDotenv; module2.exports._configVault = DotenvModule._configVault; module2.exports._parseVault = DotenvModule._parseVault; module2.exports.config = DotenvModule.config; module2.exports.decrypt = DotenvModule.decrypt; module2.exports.parse = DotenvModule.parse; module2.exports.populate = DotenvModule.populate; module2.exports = DotenvModule; } }); // node_modules/dotenv/lib/env-options.js var require_env_options = __commonJS({ "node_modules/dotenv/lib/env-options.js"(exports2, module2) { "use strict"; var options = {}; if (process.env.DOTENV_CONFIG_ENCODING != null) { options.encoding = process.env.DOTENV_CONFIG_ENCODING; } if (process.env.DOTENV_CONFIG_PATH != null) { options.path = process.env.DOTENV_CONFIG_PATH; } if (process.env.DOTENV_CONFIG_DEBUG != null) { options.debug = process.env.DOTENV_CONFIG_DEBUG; } if (process.env.DOTENV_CONFIG_OVERRIDE != null) { options.override = process.env.DOTENV_CONFIG_OVERRIDE; } if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) { options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY; } module2.exports = options; } }); // node_modules/dotenv/lib/cli-options.js var require_cli_options = __commonJS({ "node_modules/dotenv/lib/cli-options.js"(exports2, module2) { "use strict"; var re = /^dotenv_config_(encoding|path|debug|override|DOTENV_KEY)=(.+)$/; module2.exports = function optionMatcher(args) { return args.reduce(function(acc, cur) { const matches = cur.match(re); if (matches) { acc[matches[1]] = matches[2]; } return acc; }, {}); }; } }); // src/index.ts var src_exports = {}; __export(src_exports, { Address: () => Address, CalendarDueCharge: () => CalendarDueCharge, CalendarImediateCharge: () => CalendarImediateCharge, Cep: () => Cep, Cnpj: () => Cnpj, Cpf: () => Cpf, E2eId: () => E2eId, Email: () => Email, Id: () => Id, IdEnvio: () => IdEnvio, MonetaryValue: () => MonetaryValue, PixBatchCollections: () => PixBatchCollections, PixBatchCollectionsCreateOrUpdateDueChargeResponse: () => PixBatchCollectionsCreateOrUpdateDueChargeResponse, PixBatchCollectionsResponse: () => PixBatchCollectionsResponse, PixBatchCollectionsResponseArray: () => PixBatchCollectionsResponseArray, PixDueCharge: () => PixDueCharge, PixDueChargeResponse: () => PixDueChargeResponse, PixDueChargeResponseArray: () => PixDueChargeResponseArray, PixImediateCharge: () => PixImediateCharge, PixImediateChargeResponse: () => PixImediateChargeResponse, PixImediateChargeResponseArray: () => PixImediateChargeResponseArray, PixLocation: () => PixLocation, PixManage: () => PixManage, PixManageResponse: () => PixManageResponse, PixManageResponseArray: () => PixManageResponseArray, PixManageReturnResponse: () => PixManageReturnResponse, PixPayloadLocations: () => PixPayloadLocations, PixPayloadLocationsQRCodeResponse: () => PixPayloadLocationsQRCodeResponse, PixPayloadLocationsResponse: () => PixPayloadLocationsResponse, PixPayloadLocationsResponseArray: () => PixPayloadLocationsResponseArray, PixPaymentSplit: () => PixPaymentSplit, PixPaymentSplitAttachmentResponse: () => PixPaymentSplitAttachmentResponse, PixPaymentSplitDueChargeAttachmentResponse: () => PixPaymentSplitDueChargeAttachmentResponse, PixPaymentSplitImediateChargeAttachmentResponse: () => PixPaymentSplitImediateChargeAttachmentResponse, PixPaymentSplitResponse: () => PixPaymentSplitResponse, PixRequest: () => PixRequest, PixSendAndPayment: () => PixSendAndPayment, PixSendAndPaymentSendResponse: () => PixSendAndPaymentSendResponse, PixWebhooks: () => PixWebhooks, PixWebhooksAddResponse: () => PixWebhooksAddResponse, PixWebhooksDeleteResponse: () => PixWebhooksDeleteResponse, PixWebhooksResponse: () => PixWebhooksResponse, PixWebhooksResponseArray: () => PixWebhooksResponseArray, State: () => State, TxId: () => TxId, UserAccount: () => UserAccount, default: () => src_default }); module.exports = __toCommonJS(src_exports); var import_node_fs2 = require("fs"); // src/domain-driven-design/core/apis/api-request.ts var import_axios2 = __toESM(require("axios")); // src/domain-driven-design/core/apis/contas-end-points.ts var contasEndpoints = { URL: { PRODUCTION: `https://apis.gerencianet.com.br`, SANDBOX: `https://apis-h.gerencianet.com.br` }, ENDPOINTS: { authorize: () => ({ route: `/oauth/token`, method: `post` }), createAccount: () => ({ route: `/cadastro/conta-simplificada`, method: `post` }), createAccountCertificate: ({ identificador }) => ({ route: `/cadastro/conta-simplificada/${identificador}/certificado`, method: `post` }), getAccountCredentials: ({ identificador }) => ({ route: `/cadastro/conta-simplificada/${identificador}/credenciais`, method: `get` }), accountConfigWebhook: () => ({ route: `/cadastro/webhook`, method: `post` }), accountDeleteWebhook: ({ identificador }) => ({ route: `/cadastro/webhook/${identificador}Webhook`, method: `delete` }), accountDetailWebhook: ({ identificador }) => ({ route: `/cadastro/webhook/${identificador}Webhook`, method: `get` }), accountListWebhook: () => ({ route: `/cadastro/webhooks`, method: `get` }) } }; // src/domain-driven-design/core/apis/default-end-points.ts var defaultEndpoints = { URL: { PRODUCTION: `https://api.gerencianet.com.br/v1`, SANDBOX: `https://sandbox.gerencianet.com.br/v1` }, ENDPOINTS: { authorize: () => ({ route: `/authorize`, method: `post` }), sendSubscriptionLinkEmail: ({ id }) => ({ route: `/charge/${id}/subscription/resend`, method: `post` }), oneStepSubscription: ({ id }) => ({ route: `/plan/${id}/subscription/one-step`, method: `post` }), settleCarnet: ({ id }) => ({ route: `/carnet/${id}/settle`, method: `put` }), oneStepSubscriptionLink: ({ id }) => ({ route: `/plan/${id}/subscription/one-step/link`, method: `post` }), sendLinkEmail: ({ id }) => ({ route: `/charge/${id}/link/resend`, method: `post` }), createOneStepLink: () => ({ route: `/charge/one-step/link`, method: `post` }), createCharge: () => ({ route: `/charge`, method: `post` }), detailCharge: ({ id }) => ({ route: `/charge/${id}`, method: `get` }), updateChargeMetadata: ({ id }) => ({ route: `/charge/${id}/metadata`, method: `put` }), updateBillet: ({ id }) => ({ route: `/charge/${id}/billet`, method: `put` }), definePayMethod: ({ id }) => ({ route: `/charge/${id}/pay`, method: `post` }), cancelCharge: ({ id }) => ({ route: `/charge/${id}/cancel`, method: `put` }), createCarnet: () => ({ route: `/carnet`, method: `post` }), detailCarnet: ({ id }) => ({ route: `/carnet/${id}`, method: `get` }), updateCarnetParcel: ({ id, parcel }) => ({ route: `/carnet/${id}/parcel/${parcel}`, method: `put` }), updateCarnetMetadata: ({ id }) => ({ route: `/carnet/${id}/metadata`, method: `put` }), getNotification: ({ token }) => ({ route: `/notification/${token}`, method: `get` }), listPlans: () => ({ route: `/plans`, method: `get` }), createPlan: () => ({ route: `/plan`, method: `post` }), deletePlan: ({ id }) => ({ route: `/plan/${id}`, method: `delete` }), createSubscription: ({ id }) => ({ route: `/plan/${id}/subscription`, method: `post` }), detailSubscription: ({ id }) => ({ route: `/subscription/${id}`, method: `get` }), defineSubscriptionPayMethod: ({ id }) => ({ route: `/subscription/${id}/pay`, method: `post` }), cancelSubscription: ({ id }) => ({ route: `/subscription/${id}/cancel`, method: `put` }), updateSubscriptionMetadata: ({ id }) => ({ route: `/subscription/${id}/metadata`, method: `put` }), getInstallments: () => ({ route: `/installments`, method: `get` }), sendBilletEmail: ({ id }) => ({ route: `/charge/${id}/billet/resend`, method: `post` }), createChargeHistory: ({ id }) => ({ route: `/charge/${id}/history`, method: `post` }), sendCarnetEmail: ({ id }) => ({ route: `/carnet/${id}/resend`, method: `post` }), sendCarnetParcelEmail: ({ id, parcel }) => ({ route: `/carnet/${id}/parcel/${parcel}/resend`, method: `post` }), createCarnetHistory: ({ id }) => ({ route: `/carnet/${id}/history`, method: `post` }), cancelCarnet: ({ id }) => ({ route: `/carnet/${id}/cancel`, method: `put` }), cancelCarnetParcel: ({ id, parcel }) => ({ route: `/carnet/${id}/parcel/${parcel}/cancel`, method: `put` }), linkCharge: ({ id }) => ({ route: `/charge/${id}/link`, method: `post` }), defineLinkPayMethod: ({ id }) => ({ route: `/charge/${id}/link`, method: `post` }), updateChargeLink: ({ id }) => ({ route: `/charge/${id}/link`, method: `put` }), updatePlan: ({ id }) => ({ route: `/plan/${id}`, method: `put` }), createSubscriptionHistory: ({ id }) => ({ route: `/subscription/${id}/history`, method: `post` }), defineBalanceSheetBillet: ({ id }) => ({ route: `/charge/${id}/balance-sheet`, method: `post` }), settleCharge: ({ id }) => ({ route: `/charge/${id}/settle`, method: `put` }), settleCarnetParcel: ({ id, parcel }) => ({ route: `/carnet/${id}/parcel/${parcel}/settle`, method: `put` }), createOneStepCharge: () => ({ route: `/charge/one-step`, method: `post` }) } }; // src/domain-driven-design/core/apis/open-finance-end-points.ts var openFinanceEndpoints = { URL: { PRODUCTION: `https://apis.gerencianet.com.br/open-finance`, SANDBOX: `https://apis-h.gerencianet.com.br/open-finance` }, ENDPOINTS: { authorize: () => ({ route: `/oauth/token`, method: `post` }), ofListParticipants: () => ({ route: `/participantes/`, method: `GET` }), ofStartPixPayment: () => ({ route: `/pagamentos/pix`, method: `POST` }), ofListPixPayment: () => ({ route: `/pagamentos/pix`, method: `GET` }), ofConfigUpdate: () => ({ route: `/config`, method: `PUT` }), ofConfigDetail: () => ({ route: `/config`, method: `GET` }), ofDevolutionPix: ({ identificadorPagamento }) => ({ route: `/pagamentos/pix/${identificadorPagamento}/devolver`, method: `post` }) } }; // src/domain-driven-design/core/apis/pagamentos-end-points.ts var pagamentosEndpoints = { URL: { PRODUCTION: `https://apis.gerencianet.com.br/pagamento`, SANDBOX: `https://apis-h.gerencianet.com.br/pagamento` }, ENDPOINTS: { authorize: () => ({ route: `/oauth/token`, method: `post` }), payDetailBarCode: ({ codBarras }) => ({ route: `/codBarras/${codBarras}`, method: `GET` }), payRequestBarCode: ({ codBarras }) => ({ route: `/codBarras/${codBarras}`, method: `POST` }), payDetailPayment: ({ idPagamento }) => ({ route: `/${idPagamento}`, method: `GET` }), payListPayments: () => ({ route: `/resumo`, method: `GET` }) } }; // src/domain-driven-design/core/apis/pix-end-points.ts var pixEndpoints = { URL: { PRODUCTION: "https://pix.api.efipay.com.br", SANDBOX: "https://pix-h.api.efipay.com.br" }, ENDPOINTS: { authorize: () => ({ route: "/oauth/token", method: "post" }), pixCreateDueCharge: ({ txid }) => ({ route: `/v2/cobv/${txid}`, method: `put` }), pixUpdateDueCharge: ({ txid }) => ({ route: `/v2/cobv/${txid}`, method: `patch` }), pixDetailDueCharge: ({ txid }) => ({ route: `/v2/cobv/${txid}`, method: `get` }), pixListDueCharges: () => ({ route: `/v2/cobv/`, method: `get` }), createReport: () => ({ route: `/v2/gn/relatorios/extrato-conciliacao`, method: `post` }), detailReport: ({ id }) => ({ route: `/v2/gn/relatorios/${id}`, method: `get` }), pixCreateCharge: ({ txid }) => ({ route: `/v2/cob/${txid}`, method: `put` }), pixUpdateCharge: ({ txid }) => ({ route: `/v2/cob/${txid}`, method: `patch` }), pixCreateImmediateCharge: () => ({ route: `/v2/cob`, method: `post` }), pixDetailCharge: ({ txid }) => ({ route: `/v2/cob/${txid}`, method: `get` }), pixListCharges: () => ({ route: `/v2/cob`, method: `get` }), pixDetailReceived: ({ e2eId }) => ({ route: `/v2/pix/${e2eId}`, method: `get` }), pixReceivedList: () => ({ route: `/v2/pix`, method: `get` }), pixSend: ({ idEnvio }) => ({ route: `/v2/gn/pix/${idEnvio}`, method: `put` }), pixSendDetail: ({ e2eId }) => ({ route: `/v2/gn/pix/enviados/${e2eId}`, method: `get` }), pixSendList: () => ({ route: `/v2/gn/pix/enviados`, method: `get` }), pixDevolution: ({ id, e2eId }) => ({ route: `/v2/pix/${e2eId}/devolucao/${id}`, method: `put` }), pixDetailDevolution: ({ id, e2eId }) => ({ route: `/v2/pix/${e2eId}/devolucao/${id}`, method: `get` }), pixConfigWebhook: ({ chave }) => ({ route: `/v2/webhook/${chave}`, method: `put` }), pixDetailWebhook: ({ chave }) => ({ route: `/v2/webhook/${chave}`, method: `get` }), pixListWebhook: () => ({ route: `/v2/webhook`, method: `get` }), pixDeleteWebhook: ({ chave }) => ({ route: `/v2/webhook/${chave}`, method: `delete` }), pixCreateDueChargeBatch: ({ id }) => ({ route: `/v2/lotecobv/${id}`, method: `put` }), pixUpdateDueChargeBatch: ({ id }) => ({ route: `/v2/lotecobv/${id}`, method: `patch` }), pixDetailDueChargeBatch: ({ id }) => ({ route: `/v2/lotecobv/${id}`, method: `get` }), pixListDueChargeBatch: () => ({ route: `/v2/lotecobv/`, method: `get` }), pixCreateLocation: () => ({ route: `/v2/loc`, method: `post` }), pixLocationList: () => ({ route: `/v2/loc`, method: `get` }), pixDetailLocation: ({ id }) => ({ route: `/v2/loc/${id}`, method: `get` }), pixGenerateQRCode: ({ id }) => ({ route: `/v2/loc/${id}/qrcode`, method: `get` }), pixUnlinkTxidLocation: ({ id }) => ({ route: `/v2/loc/${id}/txid`, method: `delete` }), pixCreateEvp: () => ({ route: `/v2/gn/evp`, method: `post` }), pixListEvp: () => ({ route: `/v2/gn/evp`, method: `get` }), pixDeleteEvp: ({ chave }) => ({ route: `/v2/gn/evp/${chave}`, method: `delete` }), getAccountBalance: () => ({ route: `/v2/gn/saldo`, method: `get` }), updateAccountConfig: () => ({ route: `/v2/gn/config`, method: `put` }), listAccountConfig: () => ({ route: `/v2/gn/config`, method: `get` }), pixSplitDetailCharge: ({ txid }) => ({ route: `/v2/gn/split/cob/${txid}`, method: `get` }), pixSplitLinkCharge: ({ txid, splitConfigId }) => ({ route: `/v2/gn/split/cob/${txid}/vinculo/${splitConfigId}`, method: `put` }), pixSplitUnlinkCharge: ({ txid }) => ({ route: `/v2/gn/split/cob/${txid}/vinculo`, method: `delete` }), pixSplitDetailDueCharge: ({ txid }) => ({ route: `/v2/gn/split/cobv/${txid}`, method: `get` }), pixSplitLinkDueCharge: ({ txid, splitConfigId }) => ({ route: `/v2/gn/split/cobv/${txid}/vinculo/${splitConfigId}`, method: `put` }), pixSplitUnlinkDueCharge: ({ txid }) => ({ route: `/v2/gn/split/cobv/${txid}/vinculo`, method: `delete` }), pixSplitConfig: () => ({ route: `/v2/gn/split/config`, method: `post` }), pixSplitConfigId: ({ id }) => ({ route: `/v2/gn/split/config/${id}`, method: `put` }), pixSplitDetailConfig: ({ id }) => ({ route: `/v2/gn/split/config/${id}`, method: `get` }), pixSendDetailId: ({ idEnvio }) => ({ route: `/v2/gn/pix/enviados/id-envio/${idEnvio}`, method: `get` }) } }; // src/domain-driven-design/core/apis/constants-callbacks.ts var constantsCallbacks = { APIS: { PIX: pixEndpoints, DEFAULT: defaultEndpoints, OPENFINANCE: openFinanceEndpoints, PAGAMENTOS: pagamentosEndpoints, CONTAS: contasEndpoints } }; // src/domain-driven-design/domains/apis/enterprise/entities/auth.ts var import_node_fs = __toESM(require("fs")); var import_node_https = __toESM(require("https")); var import_axios = __toESM(require("axios")); var Auth = class { constants; client_id; client_secret; baseUrl; agent; authRoute; #options; constructor(options) { this.constants = constantsCallbacks; this.client_id = options.client_id; this.client_secret = options.client_secret; this.baseUrl = options.baseUrl; this.#options = options; if (options.agent) { this.agent = options.agent; } if (options.authRoute) { this.authRoute = options.authRoute; } } get options() { return this.#options; } async getAccessToken() { if (!this.baseUrl) return null; const environment = this.options.sandbox ? "SANDBOX" : "PRODUCTION"; let postParams; if (this.constants.APIS.DEFAULT.URL.PRODUCTION === this.baseUrl || this.constants.APIS.DEFAULT.URL.SANDBOX === this.baseUrl) { postParams = { method: "POST", url: `${this.baseUrl}${this.constants.APIS.DEFAULT.ENDPOINTS.authorize().route}`, headers: { "api-sdk": "typescript-1.0.2" }, data: { grant_type: "client_credentials" }, auth: { username: this.client_id, password: this.client_secret } }; } else { const data_credentials = `${this.client_id}:${this.client_secret}`; const auth = Buffer.from(data_credentials).toString("base64"); const agent = this.getAgent(); if (!agent) throw new Error("cannot build http agent"); this.agent = agent; postParams = { method: "POST", url: `${this.baseUrl}${this.authRoute.route}`, headers: { Authorization: `Basic ${auth}`, "Content-Type": "application/json", "api-sdk": "typescript-1.0.2" }, httpsAgent: this.agent, data: { grant_type: "client_credentials" } }; } try { const { data } = await (0, import_axios.default)(postParams); return data; } catch (error) { if (error instanceof import_axios.AxiosError) { console.log("error.response:", error.response); console.log("error.cause:", error.cause); } else { console.log("error:", error); } return null; } } getAgent() { try { if (this.options.certificate) { if (this.options.pemKey) { switch (this.options.certificateType) { case "file": this.#options.agent = new import_node_https.default.Agent({ cert: import_node_fs.default.readFileSync(this.options.certificate), key: import_node_fs.default.readFileSync(this.options.pemKey), passphrase: "" }); break; case "buffer": if (!(this.options.certificate instanceof Buffer)) throw new Error( `"options.certificate" is not instance of "Buffer"` ); if (!(this.options.pemKey instanceof Buffer)) throw new Error(`"options.pemKey" is not instance of "Buffer"`); this.#options.agent = new import_node_https.default.Agent({ cert: this.options.certificate, key: this.options.pemKey, passphrase: "" }); break; case "base64": if (!(typeof this.options.certificate === "string")) throw new Error(`"options.certificate" is not type of "string"`); if (!(this.options.pemKey instanceof String)) throw new Error(`"options.pemKey" is not instance of "Buffer"`); this.#options.agent = new import_node_https.default.Agent({ cert: Buffer.from(this.options.certificate, "base64"), key: Buffer.from(this.options.pemKey, "base64"), passphrase: "" }); break; } } else { switch (this.options.certificateType) { case "file": this.#options.agent = new import_node_https.default.Agent({ pfx: import_node_fs.default.readFileSync(this.options.certificate), passphrase: "" }); break; case "buffer": if (!(this.options.certificate instanceof Buffer)) throw new Error( `"options.certificate" is not instance of "Buffer"` ); this.#options.agent = new import_node_https.default.Agent({ pfx: this.options.certificate, passphrase: "" }); break; case "base64": if (!(typeof this.options.certificate === "string")) throw new Error(`"options.certificate" is not type of "string"`); this.#options.agent = new import_node_https.default.Agent({ pfx: Buffer.from(this.options.certificate, "base64"), passphrase: "" }); break; } } } return this.#options.agent; } catch (error) { throw new Error( `FALHA AO LER O CERTIFICADO. Verifique se o caminho informado est\xE1 correto: ${this.options.certificate} ` ); } } }; var auth_default = Auth; // src/domain-driven-design/core/apis/api-request.ts var ApiRequest = class { #constants; #endpoints; #options; #auth; #baseUrl; #type; #operation; constructor(type, operation, options) { this.#constants = constantsCallbacks; this.#endpoints = this.#constants.APIS[operation]; this.#baseUrl = this.#endpoints.URL[type]; this.#type = type; this.#operation = operation; const optionsComplete = { ...options, sandbox: type === "SANDBOX", // eslint-disable-next-line // @ts-ignore baseUrl: this.#baseUrl, // eslint-disable-next-line // @ts-ignore authRoute: this.#endpoints.ENDPOINTS.authorize() }; this.#options = optionsComplete; this.#auth = new auth_default(optionsComplete); } get type() { return this.#type; } get operation() { return this.#operation; } get environment() { return this.#options.sandbox ? "SANDBOX" : "PRODUCTION"; } get endpoints() { return this.#endpoints; } get options() { return this.#options; } get auth() { return this.#auth; } get baseUrl() { return this.#baseUrl; } get config() { return { environment: this.environment, endpoints: this.endpoints, options: this.options, auth: this.auth, baseUrl: this.baseUrl }; } makeHeaders({ accessToken }) { const headers = { "api-sdk": `efi-typescript-${"1.0.2"}`, "Content-Type": "application/json", authorization: `Bearer ${accessToken}`, "x-skip-mtls-checking": !this.options.validateMtls }; const optionalHeaders = { ...headers }; if (this.options.partnerToken) { optionalHeaders["partner-token"] = this.options.partnerToken; } return optionalHeaders; } makeRequest({ accessToken, method, searchParams, routeUrl, body }) { const headers = this.makeHeaders({ accessToken }); const url = new URL(routeUrl); Object.entries(searchParams ?? {}).forEach(([key, value]) => { url.searchParams.append( key, value instanceof Date ? value.toISOString() : String(value) ); }); const req = { method, url: url.toString(), headers, data: body }; const request = { ...req }; if (this.options.baseUrl !== this.#constants.APIS.DEFAULT.URL.PRODUCTION && this.options.baseUrl !== this.#constants.APIS.DEFAULT.URL.SANDBOX) { request.httpsAgent = this.auth.getAgent(); } return request; } async sendRequest({ route, body, method, searchParams, ResponseClass }) { const token = await this.auth.getAccessToken(); if (!token) return null; const { access_token: accessToken } = token; const url = `${this.baseUrl}${route}`; const request = this.makeRequest({ accessToken, body, method, routeUrl: url, searchParams }); try { const { data } = ( // eslint-disable-next-line // @ts-ignore await (0, import_axios2.default)(request) ); const response = new ResponseClass(data); return response; } catch (error) { if (error instanceof import_axios2.AxiosError) { console.log("error on request:", error.response?.data); } else { console.log("error on request:", error); } return null; } } }; // src/domain-driven-design/domains/apis/enterprise/entities/cobranca/cobranca-modules/card/index.ts var Card = class _Card extends ApiRequest { // get paymentSupport() { // return new CardPaymentSupport<type>({ // environmentType: this.environment as type, // }) // } // eslint-disable-next-line // @ts-ignore useCredentials({ clientId, clientSecret }) { const type = this.type; const options = this.options; const pix = new _Card(type, "DEFAULT", { ...options, client_id: clientId, client_secret: clientSecret }); return pix; } }; // src/domain-driven-design/domains/apis/enterprise/entities/cobranca/cobranca.ts var CobrancaRequest = class _CobrancaRequest extends ApiRequest { #card; constructor({ type, options }) { super(type, "DEFAULT", options); this.#card = new Card(type, "DEFAULT", options); } /** * * --- * * As transações online via cartão de crédito exigem apenas a numeração de face e o código no verso do cartão, o que pode resultar em transações suspeitas. Por isso, é importante adotar procedimentos de segurança para evitar prejuízos financeiros, como o Chargeback. * * Quando uma transação com cartão de crédito é realizada, ela passa por três etapas: autorização da operadora, análise de segurança e captura. Cada transação é analisada para identificar possíveis riscos. Se for aprovada, o valor é debitado na fatura do cliente. Caso contrário, o valor fica reservado até que a comunicação reversa seja concluída e o limite do cartão seja reestabelecido. * * --- * * ### Lista de Cartões aceitos pela Efí Pay * * - Visa * - Master * - AmericanExpress * - Elo * - Hipercard * * --- * * ### Atenção! * * Para fazer o pagamento com cartão de crédito,***é necessário obter o payment_token*** da transação. Portanto, é imprescindível seguir os procedimentos para [obter o payment_token](https://dev.efipay.com.br/docs/api-cobrancas/cartao#obten%C3%A7%C3%A3o-do-payment_token) conforme descrito no documento antes de criar a cobrança com cartão de crédito. * * Outra informação importante é você precisa cadastrar o ramo de atividade em sua conta. Confira mais detalhes [aqui](https://sejaefi.com.br/artigo/inserir-ramo-de-atividade/#versao-7). * * --- * * ### Tokenização de cartão * * Se você precisa reutilizar o payment_token para fins de recorrência, utilize o atributo `reuse` com o valor booleano `true`. Dessa forma, o payment_token pode ser usado em mais de uma transação de forma segura, sem a necessidade de salvar os dados do cartão * * --- * * ### Simulação em Ambiente de Homologação * * A simulação de cobranças de cartão em ambiente de Homologação funciona com base na análise imediata de acordo com o último dígito do número do cartão de crédito utilizado: * * - Cartão com final 1 retorna: `"reason":"Dados do cartão inválidos."` * - Cartão com final 2 retorna: `"reason":"Transação não autorizada por motivos de segurança."` * - Cartão com final 3 retorna: `"reason":"Transação não autorizada, tente novamente mais tarde."` * - Demais finais têm transação aprovada. * */ get card() { return this.#card; } // eslint-disable-next-line // @ts-ignore useCredentials({ clientId, clientSecret }) { const type = this.type; const options = this.options; const request = new _CobrancaRequest({ type, options: { ...options, client_id: clientId, client_secret: clientSecret } }); return request; } }; // src/domain-driven-design/core/apis/api-response.ts var ApiResponse = class { /** * * --- * * Transforma a Classe um formato Json * * --- * * @param replacer Um array de strings e números que atua como uma lista aprovada para selecionar as propriedades do objeto que serão convertidas em string. * @param space Adiciona indentação, espaços em branco e caracteres de quebra de linha ao texto JSON retornado para torná-lo mais fácil de ler. * @returns `string` */ toJson(replacer, space) { return JSON.stringify(this.toObject(), replacer, space); } }; // src/domain-driven-design/domains/apis/enterprise/entities/pix/pix-modules/pix-batch-collections/pix-batch-collections-create-or-update-due-charge-response.ts var PixBatchCollectionsCreateOrUpdateDueChargeResponse = class extends ApiResponse { #success; constructor(props) { super(); this.#success = props === ""; } get success() { return this.#success; } toObject() { return this.success; } }; // src/domain-driven-design/domains/apis/enterprise/entities/pix/pix-modules/pix-batch-collections/pix-batch-collections-response.ts var import_dayjs = __toESM(require("dayjs")); // src/domain-driven-design/core/entities/unique-entity-id.ts var import_node_crypto = require("crypto"); var import_zod = __toESM(require("zod")); var uniqueEntityIdInstanceSchema = import_zod.default.custom( (data) => data instanceof UniqueEntityId, "must be an UniqueEntityId" ); var UniqueEntityId = class { _value; constructor(id) { this._value = id ?? (0, import_node_crypto.randomUUID)(); } get value() { return this._value; } equals(id) { return id.value === this.value; } }; // src/domain-driven-design/domains/apis/enterprise/entities/pix/value-objects/id.ts var Id = class { #value; #size; constructor({ size, value }) { this.#size = size; if (value) { this.#value = value; } else { this.#value = this.generateNew(size); } } get value() { return this.#value; } generateNew(size) { size = size || this.#size; function getOnlyAlphaNumeric(str) { return str.replaceAll(/[^0-9a-z]/gi, ""); } let id = getOnlyAlphaNumeric(new UniqueEntityId().value); while (id.length < size) { id += getOnlyAlphaNumeric(new UniqueEntityId().value); } const data = id.slice(0, size); return data; } }; // src/domain-driven-design/domains/apis/enterprise/entities/pix/value-objects/tx-id.ts var TxId = class extends Id { constructor(id) { const min = 26; const max = 35; const mean = Math.ceil((min + max) / 2); super({ size: mean, value: id }); } generate() { return this.generateNew(); } }; // src/domain-driven-design/domains/apis/enterprise/entities/pix/pix-modules/pix-batch-collections/pix-batch-collections-response.ts var PixBatchCollectionsCobv = class extends ApiResponse { #props; constructor(props) { super(); this.#props = { criacao: props.criacao ? new Date(props.criacao) : void 0, txid: new TxId(props.txid), problema: props.problema ? { type: props.problema.type, title: props.problema.title, status: props.problema.status, detail: props.problema.detail, violacoes: props.problema.violacoes.map((violation) => { return { razao: violation.razao, propriedade: violation.propriedade }; }) } : void 0, status: props.status }; } /** * Data de criação da cobrança com vencimento * * ISO String no formato `{year}-{month}-{day}T{hour}:{minute}:{seconds}.{milliseconds}Z` */ get criacao() { return (0, import_dayjs.default)(this.#props.criacao); } /** * O campo txid determina o identificador da transação. Para mais detalhes [clique aqui](https://dev.efipay.com.br/docs/api-pix/glossario). * * Cada transação Pix possui um **Identificador da Transação**, chamado `txid`, que no contexto de representação de uma cobrança, é único por CPF/CNPJ da pessoa usuária recebedora. * * Um `txid` é uma string alfanumérica com comprimentos mínimo de 26 e máximo de 35 caracteres. Um txid válido, portanto, deve obedecer à seguinte expressão regular (regex): `^[a-zA-Z0-9]{26,35}$`. * Você pode validar strings txid sob a regex [aqui](https://regex101.com/r/iZ08y4/1). * * - string (Id da Transação) `^[a-zA-Z0-9]{26,35}$` */ get txid() { return this.#props.txid; } /** * Esta propriedade se apresenta apenas quando há uma rejeição durante a criação da cobrança */ get problema() { return this.#props.problema; } get status() { return this.#props.status; } toObject() { return { criacao: this.criacao.toDate(), txid: this.txid.value, problema: this.problema, status: this.status }; } }; var PixBatchCollectionsResponse = class extends ApiResponse { #props; constructor(props) { super(); this.#props = { descricao: props.descricao, criacao: new Date(props.criacao), cobsv: props.cobsv.map((item) => new PixBatchCollectionsCobv(item)) }; } get descricao() { return this.#props.descricao; } /** * Data de criação do Lote de Cobrança * * Objeto `dayjs` */ get criacao() { return (0, import_dayjs.default)(this.#props.criacao); } get cobsv() { return this.#props.cobsv; } toObject() { return { descricao: this.descricao, criacao: this.criacao.toDate(), cobsv: this.cobsv.map((item) => item.toObject()) }; } }; // src/domain-driven-design/core/apis/api-array-response.ts var import_dayjs2 = __toESM(require("dayjs")); var ApiArrayResponse = class extends ApiResponse { props; constructor(props, CobClass) { super(); this.props = { arrayData: props.arrayData.map((item) => new CobClass(item)), parametros: { inicio: new Date(props.parametros.inicio), fim: new Date(props.parametros.fim), paginacao: { paginaAtual: props.parametros.paginacao.paginaAtual, itensPorPagina: props.parametros.paginacao.itensPorPagina, quantidadeDePaginas: props.parametros.paginacao.quantidadeDePaginas, quantidadeTotalDeItens: props.parametros.paginacao.quantidadeTotalDeItens } } }; } /** * Filtro dos registros cuja data de criação seja maior ou igual que a data de início. Respeita RFC 3339. */ get inicio() { return (0, import_dayjs2.default)(this.props.parametros.inicio); } /** * Filtro dos registros cuja data de criação seja menor ou igual que a data de fim. Respeita RFC 3339. */ get fim() { return (0, import_dayjs2.default)(this.props.parametros.fim); } /** * Paginação - indica a página atual. */ get paginaAtual() { return this.props.parametros.paginacao.paginaAtual; } /** * Paginação - indica a quantidade de itens por página. */ get itensPorPagina() { return this.props.parametros.paginacao.itensPorPagina; } /** * Paginação - indica a quantidade total de páginas. */ get quantidadeDePaginas() { return this.props.parametros.paginacao.quantidadeDePaginas; } /** * Paginação - indica a quantidade total de itens. */ get quantidadeTotal