import { EventEmitter } from 'events'; import { GoogleAuthOptions } from '@google-cloud/common'; import { Service } from '@google-cloud/common'; declare type Action = 'CAPTURE' | 'LOG'; declare interface AgentCaptureConfig { /** * Whether to include details about stack frames belonging to node-core. */ includeNodeModules: boolean; /** * Maximum number of stack frames to capture data for. The limit is aimed to * reduce overall capture time. */ maxFrames: number; /** * We collect locals and arguments on a few top frames. For the rest only * collect the source location */ maxExpandFrames: number; /** * To reduce the overall capture time, limit the number of properties * gathered on large objects. A value of 0 disables the limit. */ maxProperties: number; /** * To reduce the overall capture time, limit the number of nested properties * gathered on a deeply nested objects. For example a->b->c with a value of 2 will only take values of a and b */ maxVariableDepth: number; /** * To reduce the overall capture time, limit the number of properties * gathered on large objects. * This is an extended limitation for under watch expressions */ maxWatchProperties: number; /** * Total 'size' of data to gather. This is NOT the number of bytes of data * that are sent over the wire, but instead a very very coarse approximation * based on the length of names and values of the properties. This should be * somewhat proportional to the amount of processing needed to capture the * data and subsequently the network traffic. A value of 0 disables the * limit. * @deprecated since version 1.16.0, use maxSnapshotBufferSize instead */ maxDataSize?: number; /** * To limit the size of the buffer, we truncate long strings. A value of 0 * disables truncation. * @deprecated since version 1.16.0 use maxVariableSize instead */ maxStringLength?: number; /** * To limit the size of the buffer, we truncate long string. A value of 0 * disables truncation. */ maxVariableSize: number; /** * Maximum number of characters we allow for a watch list variable * if a user wants to see a large variable (which is > than maxVariableSize) we can show him more characters for the variable * with a watch variable (expression) to allow more characters for this variable. * This configuration limits the maximum amount of characters we allow for watch variables. */ maxWatchListVariableSize: number; /** * Total 'size' of data to gather. This is NOT the number of bytes of data * that are sent over the wire, but instead a very very coarse approximation * based on the length of names and values of the properties. This should be * somewhat proportional to the amount of processing needed to capture the * data and subsequently the network traffic. A value of 0 disables the * limit. */ maxSnapshotBufferSize: number; resolveFrameLocations: boolean; } declare type AgentLogLevel = 'debug' | 'info' | 'warn' | 'error'; declare interface AgentMetadata { filename?: string; registration?: { displayName?: string; tags?: (string | { name: string; })[]; }; } declare interface AliasContext { kind: 'ANY' | 'FIXED' | 'MOVABLE' | 'OTHER'; name: string; } export declare function asyncStart(options?: DebugAgentConfig | StackdriverConfig): Promise; declare class Breakpoint { stackFrames: StackFrame[]; evaluatedExpressions: (Variable | null)[]; variableTable: (Variable | null)[]; id: BreakpointId; action?: Action; location?: SourceLocation; condition?: string; expressions?: string[]; logMessageFormat?: string; logLevel?: LogLevel; isFinalState?: boolean; createTime?: Timestamp; expirationSeconds?: number; finalTime?: string; status?: StatusMessage; labels?: Record; maxHitCount: number; ignoreQuota: boolean; pipingStatus: Piping; expirationTime?: number; maxSnapshotBufferSize?: number; maxSnapshotFrameCount?: number; captureObjectExploreMaxDepth?: number; constructor(apiBreakpoint?: Partial); toString(): string; } declare type BreakpointId = string; declare interface CloudRepoSourceContext { cloudRepo: { repoId: RepoId; revisionId: string; aliasName?: string; aliasContext: AliasContext; }; } declare interface CloudWorkspaceId { repoId: RepoId; name: string; } declare interface CloudWorkspaceSourceContext { cloudWorkspace: { workspaceId: CloudWorkspaceId; snapshotId: string; }; } declare type ConfigErrors = Record; declare type CustomAgentLogLevel = 'NOT_SET' | 'DEBUG'; declare class Debug extends Service { options: DebugOptions; packageInfo: PackageInfo; /** *

* **This is an experimental release of Stackdriver Debug.** This API is not * covered by any SLA of deprecation policy and may be subject to backwards * incompatible changes. *

* * This module provides Stackdriver Debugger support for Node.js applications. * [Stackdriver Debugger](https://cloud.google.com/debug/) is a feature of * [Google Cloud Platform](https://cloud.google.com/) that lets you debug your * applications in production without stopping or pausing your application. * * This module provides an agent that lets you automatically enable debugging * without changes to your application. * * @constructor * @alias module:debug * * @resource [What is Stackdriver Debug]{@link * https://cloud.google.com/debug/} * * @param options - [Authentication options](#/docs) * @param packageJson */ constructor(options: DebugOptions | undefined, packageJson: PackageInfo); } declare type DebugAgentConfig = GoogleAuthOptions & { [K in keyof ResolvedDebugAgentConfig]?: Partial; } & { errors?: ConfigErrors; }; declare class Debuglet extends EventEmitter { #private; isReadyManager: IsReady; config: ResolvedDebugAgentConfig; private fetcherActive; private readonly logger; private debuggee; private readonly activeBreakpointMap; private collectLogRequestId?; private pipingManager; /** * @param debug - A Debug instance. * @param config - The option parameters for the Debuglet. * @event 'started' once the startup tasks are completed. Only called once. * @event 'stopped' if the agent stops due to a fatal error after starting. * Only called once. * @event 'registered' once successfully registered to the debug api. May be * emitted multiple times. * @event 'remotelyDisabled' if the debuggee is disabled by the server. May be * called multiple times. * @constructor */ constructor(debug: Debug, config: DebugAgentConfig); waitForTransmissionQueueDrain(timeoutMs: number): Promise; getClientConnectionTimeoutInSeconds(): number | undefined; waitForBreakpoints(waitTime?: number): Promise; /** * This function is for AWS lambda to determine if it should fetch breakpoints * before the handler is called. */ fetchBreakpointsOnce(): void; isRegistered(): boolean; private findFiles; /** * Starts the Debuglet. It is important that this is as quick as possible * as it is on the critical path of application startup. * @private */ start(): Promise; /** * isReady returns a promise that only resolved if the last breakpoint update * happened within a duration (PROMISE_RESOLVE_CUT_OFF_IN_MILLISECONDS). This * feature is mainly used in Google Cloud Function (GCF), as it is a * serverless environment and we wanted to make sure debug agent always * captures the snapshots. */ isReady(): Promise; private static getSourceContextFromFile; register(): void; isRunning(): boolean; /** * Stops the Debuglet. This is for testing purposes only. Stop should only be * called on a agent that has started (i.e. emitted the 'started' event). * Calling this while the agent is initializing may not necessarily stop all * pending operations. */ stop(): void; stringifyBreakpointForInfoLog(breakpoint: Breakpoint): string; setCustomLogLevel(agentLogLevel: CustomAgentLogLevel | undefined): void; } declare interface DebugOptions extends GoogleAuthOptions { /** * The API endpoint of the service used to make requests. * Defaults to `clouddebugger.googleapis.com`. */ apiEndpoint?: string; } /** * class that logs the dynamic breakpoint logs. * notice - if one of the functions calls this it should be bound to the context before adding it to the configuration. * i.e: info = info.bind(this) */ declare interface DynamicLogger { warn(msg: string): void; error(msg: string): void; info(msg: string): void; } declare interface FormatMessage { format: string; errorId?: number; parameters?: string[]; } declare interface GerritSourceContext { gerrit: { hostUri: string; gerritProject: string; revisionId?: string; aliasName?: string; aliasContext?: AliasContext; }; } export declare function get(): Debuglet | null | undefined; export declare type GetFunction = typeof get; declare interface GitSourceContext { git: { url: string; revisionId: string; }; } /** * IsReady will return a promise to user after user starting the debug agent. * This promise will be resolved when one of the following is true: * 1. Time since last listBreakpoint was within a heuristic time. * 2. listBreakpoint completed successfully. * 3. Debuggee registration expired or failed, listBreakpoint cannot be * completed. */ declare interface IsReady { isReady(): Promise; } export declare type Lightrun = { start: StartFunction; stop: StopFunction; get: GetFunction; }; declare type LogLevel = 'INFO' | 'WARN' | 'ERROR'; declare interface PackageInfo { name: string; version: string; } declare type Piping = 'APP_ONLY' | 'PLUGIN_ONLY' | 'BOTH' | 'NOT_SET'; declare interface ProjectRepoId { projectId: string; repoName: string; } declare type Reference = 'UNSPECIFIED' | 'BREAKPOINT_SOURCE_LOCATION' | 'BREAKPOINT_CONDITION' | 'BREAKPOINT_EXPRESSION' | 'BREAKPOINT_AGE' | 'VARIABLE_NAME' | 'VARIABLE_VALUE'; declare interface RepoId { projectRepoId: ProjectRepoId; uid: string; } declare interface ResolvedDebugAgentConfig extends GoogleAuthOptions { /** * Specifies the working directory of the application being * debugged. That is, the directory containing the application's * `package.json` file. * * The default value is the value of `process.cwd()`. */ workingDirectory: string; /** * Specifies whether or not the computer's root directory should * be allowed for the value of the `workingDirectory` configuration * option. * * On startup, the debug agent scans the working directory for source * files. If the working directory is the computer's root directory, * this scan would result is scanning the entire drive. * * To avoid this, the debug agent, by default, does not allow the * working directory to be computer's root directory. That check * can be disabled with this configuration option. */ allowRootAsWorkingDirectory: boolean; /** * A user specified way of identifying the service */ description?: string; /** * Whether or not it is permitted to evaluate expressions. * Locals and arguments are not displayed and watch expressions and * conditions are dissallowed when this is `false`. */ allowExpressions: boolean; /** * Identifies the context of the running service - * [ServiceContext](https://cloud.google.com/error-reporting/reference/rest/v1beta1/ServiceContext?authuser=2). * This information is utilized in the UI to identify all the running * instances of your service. This is discovered automatically when your * application is running on Google Cloud Platform. You may optionally * choose to provide this information yourself to identify your service * differently from the default mechanism. */ serviceContext: { /** * The service name. */ service?: string; /** * The service version. */ version?: string; /** * A unique deployment identifier. This is used internally only. */ minorVersion_?: string; }; /** * A SourceContext is a reference to a tree of files. A SourceContext together * with a path point to a unique version of a single file or directory. * Managed environments such as AppEngine generate a source-contexts.json file * at deployment time. The agent can load the SourceContext from that file if * it exists. In other environments, e.g. locally, GKE, GCE, AWS, etc., users * can either generate the source context file, or pass the context as part of * the agent configuration. * * @link * https://cloud.google.com/debugger/api/reference/rest/v2/Debuggee#SourceContext */ sourceContext?: CloudRepoSourceContext | CloudWorkspaceSourceContext | GerritSourceContext | GitSourceContext; /** * The path within your repository to the directory * containing the package.json for your deployed application. This should * be provided if your deployed application appears as a subdirectory of * your repository. Usually this is unnecessary, but may be useful in * cases where the debug agent is unable to resolve breakpoint locations * unambiguously. */ appPathRelativeToRepository?: string; /** * The set of file extensions that identify javascript code to be debugged. * By default, only .js files or files with sourcemaps are considered to be * debuggable. This setting can be used to inform the debugger if you have * javascript code in files with extensions other than .js. * Example: ['.js', '.jsz'] */ javascriptFileExtensions: string[]; /** * A function which takes the path of a source file in your repository, * a list of your project's Javascript files known to the debugger, * and the file(s) in your project that the debugger thinks is identified * by the given path. * * This function should return the file(s) that is/are identified by the * given path or `undefined` to specify that the files(s) that the agent * thinks are associated with the file should be used. * * Note that the list of paths must be a subset of the files in `knownFiles` * and the debug agent can set a breakpoint for the input path if and only * if there is a unique file that this function returns (an array with * exactly one entry). * * This configuration option is usually unecessary, but can be useful in * situations where the debug agent cannot not identify the file in your * application associated with a path. * * This could occur if your application uses a structure that the debug * agent does not understand, or if more than one file in your application * has the same name. * * For example, if your running application (either locally or in the cloud) * has the Javascript files: * /x/y/src/index.js * /x/y/src/someDir/index.js * /x/y/src/util.js * and a breakpoint is set in the `/x/y/src/index.js` through the cloud * console, the `appResolver` function would be invoked with the following * arguments: * scriptPath: 'index.js' * knownFiles: ['/x/y/src/index.js', * '/x/y/src/someDir/index.js', * '/x/y/src/util.js'] * resolved: ['/x/y/src/index.js', * '/x/y/src/someDir/index.js'] * This is because out of the known files, the files, '/x/y/src/index.js' * and '/x/y/src/someDir/index.js' end with 'index.js'. * * If the array `['/x/y/src/index.js', '/x/y/src/someDir/index.js']` or * equivalently `undefined` is returned by the `pathResolver` function, the * debug agent will not be able to set the breakpoint. * * If, however, the `pathResolver` function returned `['/x/y/src/index.js']`, * for example, the debug agent would know to set the breakpoint in * the `/x/y/src/index.js` file. */ pathResolver?(scriptPath: string, knownFiles: string[], resolved: string[]): string[] | undefined; /** * How frequently should the list of breakpoints be refreshed from the cloud * debug server. */ breakpointUpdateIntervalSec: number; /** * breakpoints and logpoints older than this number of seconds will be expired * on the server. */ breakpointExpirationSec: number; /** * timeout for expressionsEval */ expressionsEvalTimeoutMillis: number; errors?: ConfigErrors; warnings?: string[]; /** * configuration options on what is captured on a snapshot. */ capture: AgentCaptureConfig; /** * options affecting log points. */ log: { /** * an objects that implements warn, err and info functions. by default this is console. * */ logger: DynamicLogger; }; /** * These configuration options are for internal experimentation only. */ internal: { registerDelayOnFetcherErrorSec: number; maxRequestRetryDelaySeconds: number; sourceMapDiagnostics: boolean; lambdaDebug?: boolean; isLambda?: boolean; dumpJSContentFilenames?: string[]; }; /** * Used by tests to force loading of a new agent if one exists already */ forceNewAgent_: boolean; /** * Uses by tests to cause the start() function to return the debuglet. */ testMode_: boolean; /** * used to set a default api url */ apiEndpoint?: string; /** * The secret of the agent, authenticating it against the server */ lightrunSecret: string; /** * All properties related to agent logging */ agentLog: { /** * Path to store the log files of the agent. If empty, the logs will be logged to the console. */ agentLogTargetDir?: string; agentLogMaxFileSizeMb?: number; agentLogMaxFileCount?: number; /** * log level of the agent */ agentLogLevel: AgentLogLevel; /** * Copy log messages at or above this level to stderr in addition to logfiles. */ stdErrThreshold: StdErrThresholdLevel; /** * How many ms should pass between log collections */ collectCooldownMs: number; /** * Maximum bytes of logfile to collect and send to server */ maxLogFileBytes: number; }; /** * List of sha256 hashes on the certificates' public keys to use for certificate pinning when communicating with * the server */ pinnedCerts: string[]; /** * Boolean indicating if should skip the certificate pinning when communicating with the server */ noCheckCertificate: boolean; /** * Path to the pem file of the ca used for the self signed certificate in on-prem deployments. */ caPath?: string; /** * metadata for the agent registration */ metadata?: AgentMetadata; /** * Max size for bulks to send as updates to the server */ transmissionBulkMaxSize: number; /** * Max size in bytes to be allowed for bulks to send in the network * (@transmissionBulkMaxSize is the amount if breakpoints, this is the total allowed size in bytes * In case of a single breakpoint where breakpoint size > transmissionBulkMaxNetworkSizeInBytes * we will allow to send it iff breakpoint size < hardNetworkLimitSizeInBytes */ transmissionBulkMaxNetworkSizeInBytes: number; /** * Hard limit of max size in bytes we will allow in the transmit breakpoints to the server * in every scenario, transmit breakpoints to the server should be lower than this limit */ transmissionHardMaxNetworkSizeLimitInBytes: number; quota: { /** * quota for condition evaluation time */ maxConditionCost: number; /** * quota for breakpoint evaluation time */ maxCPUCost: number; /** * quota for dynamic logs amount */ maxDynamicLogRate: number; /** * quota for dynamic log bytes */ maxDynamicLogByteRate: number; /** * should quota be ignored */ ignoreQuota: boolean; /** * seconds needed for recovery from quota exceeded */ quotaRecoverySeconds: number; }; agentConfigFile: string; fetchBreakpointsOnce: boolean; /** * When true, re-maps breakpoints from compiled JS to instrumented JS using live * script source maps. */ useScriptSourcemap?: boolean; /** * Number of times the V8 pauses (could be breakpoint hits) before the * debugging session is reset. This is to release the memory usage held by V8 * engine for each breakpoint hit to prevent the memory leak. The default * value is specified in defaultConfig. */ resetV8DebuggerThreshold: number; /** * Boolean to wait for the debugger to set first breakpoint before starting client's app */ lightrunWaitForInit: boolean; /** * Max time to wait for init */ lightrunInitWaitTimeMs: number; /** * A comma separated list of extra paths that are used for searching source files. * The path is any directory or file inside or outside of the the working directory. * It can be either absolute or relative to the working directory. * Notice, that passing the whole "node_modules" may slow down agent starting * and cause file name collisions. * It's recommended to pass more granular paths like "node_modules/express/lib" */ extraPaths?: string[]; /** Additional environment-variable names included in agent metadata collection. */ metadataLookupKeysExtra?: string[]; /** Additional local files inspected for agent metadata. */ metadataDownwardApiPathsExtra?: string[]; redactionEnabled?: boolean; /** * HTTP proxy configuration */ proxy?: { host: string; port: number; username?: string; password?: string; }; } declare interface SourceLocation { path: string; column?: number; line: number; } declare interface StackdriverConfig extends GoogleAuthOptions { debug?: DebugAgentConfig; } declare interface StackFrame { function: string; location: SourceLocation; arguments: Variable[]; locals: Variable[]; } /** * Start the Debug agent that will make your application available for debugging * with Stackdriver Debug. * * @param options - Authentication and agent configuration. * * @resource [Introductory video]{@link * https://www.youtube.com/watch?v=tyHcK_kAOpw} * * @example * debug.startAgent(); */ export declare function start(options?: DebugAgentConfig | StackdriverConfig): Debuglet | IsReady | undefined; export declare type StartFunction = typeof start; declare interface StatusMessage { isAccepted?: boolean; isError: boolean; refersTo: Reference; description: FormatMessage; } declare type StdErrThresholdLevel = AgentLogLevel | 'none'; declare function stop_2(): void; export { stop_2 as stop } export declare type StopFunction = typeof stop_2; declare interface Timestamp { seconds: string; nanos: number; } declare interface Variable { varTableIndex?: number; name?: string; value?: string; type?: string; members?: Variable[]; status?: StatusMessage; } export { }