UNPKG

@salesforce/agents

Version:

Client side APIs for working with Salesforce agents

131 lines 5.52 kB
"use strict"; /* * Copyright 2025, Salesforce, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.findTraceFlag = exports.createTraceFlag = exports.getDebugLevelId = exports.writeDebugLog = exports.getDebugLog = void 0; const node_path_1 = require("node:path"); const promises_1 = require("node:fs/promises"); const core_1 = require("@salesforce/core"); const utils_1 = require("./utils"); ; const messages = new core_1.Messages('@salesforce/agents', 'apexUtils', new Map([["traceFlagCreationError", "Failed to create the trace flag for user %s."], ["apexLogIdNotFound", "No Apex debug log ID found."]])); let logger; const getLogger = () => { if (!logger) { logger = core_1.Logger.childFromRoot('AgentApexDebug'); } return logger; }; /** * Get the apex debug log with a start time that falls in between the provided start and end times. * * @param connection The connection to use to make requests. * @param start The start time of the apex debug log. * @param end The end time of the apex debug log. * @returns The apex debug log. */ const getDebugLog = async (connection, start, end) => { const query = 'SELECT Id, Application, DurationMilliseconds, Location, LogLength, LogUserId, LogUser.Name, Operation, Request, StartTime, Status FROM ApexLog ORDER BY StartTime DESC'; const queryResult = await connection.tooling.query(query); if (queryResult.records.length) { getLogger().debug(`Found ${queryResult.records.length} apex debug logs.`); for (const apexLog of queryResult.records) { const startTime = new Date(apexLog.StartTime).getTime(); if (startTime >= start && startTime <= end) { return apexLog; } } } else { getLogger().debug(`No debug logs found between ${new Date(start).toDateString()} and ${new Date(end).toDateString()}`); } }; exports.getDebugLog = getDebugLog; const writeDebugLog = async (connection, log, outputDir) => { const logId = log.Id; if (!logId) { throw messages.createError('apexLogIdNotFound'); } const logFile = (0, node_path_1.join)(outputDir, (0, utils_1.sanitizeFilename)(`${logId}.log`)); // eslint-disable-next-line no-underscore-dangle const url = `${connection.tooling._baseUrl()}/sobjects/ApexLog/${logId}/Body`; const logContent = await connection.tooling.request(url); getLogger().debug(`Writing apex debug log to file: ${logFile}`); return (0, promises_1.writeFile)(logFile, logContent); }; exports.writeDebugLog = writeDebugLog; /** * Get the debug level id for `SFDC_DevConsole`. * * @param connection The connection to use to make requests. * @returns The debug level id. */ const getDebugLevelId = async (connection) => { const query = "SELECT Id FROM DebugLevel WHERE DeveloperName = 'SFDC_DevConsole'"; return (await connection.singleRecordQuery(query, { tooling: true })).Id; }; exports.getDebugLevelId = getDebugLevelId; /** * Create a trace flag for the given user id. * * @param connection The connection to use to make requests. * @param userId The user id to create the trace flag for. */ const createTraceFlag = async (connection, userId) => { const now = Date.now(); const debuglevelid = await (0, exports.getDebugLevelId)(connection); const expirationDate = new Date(now + 30 * 60_000).toUTCString(); // 30 minute expiration const result = await connection.tooling.create('TraceFlag', { tracedentityid: userId, logtype: 'DEVELOPER_LOG', debuglevelid, StartDate: now, ExpirationDate: expirationDate, }); if (!result.success) { throw messages.createError('traceFlagCreationError', [userId]); } else { getLogger().debug(`Created new apexTraceFlag for userId: ${userId} with ExpirationDate of ${expirationDate}`); } }; exports.createTraceFlag = createTraceFlag; /** * Find a trace flag for the given user id. * * @param connection The connection to use to make requests. * @param userId The user id to find the trace flag for. * @returns The trace flag. */ const findTraceFlag = async (connection, userId) => { const traceFlagQuery = ` SELECT Id, logtype, startdate, expirationdate, debuglevelid, debuglevel.apexcode, debuglevel.visualforce FROM TraceFlag WHERE logtype='DEVELOPER_LOG' AND TracedEntityId='${userId}' ORDER BY CreatedDate DESC LIMIT 1 `; const traceFlagResult = await connection.tooling.query(traceFlagQuery); if (traceFlagResult.totalSize > 0) { const traceFlag = traceFlagResult.records[0]; if (traceFlag.ExpirationDate && new Date(traceFlag.ExpirationDate) > new Date()) { getLogger().debug(`Using apexTraceFlag in the org with ExpirationDate of ${traceFlag.ExpirationDate}`); return traceFlag; } } }; exports.findTraceFlag = findTraceFlag; //# sourceMappingURL=apexUtils.js.map