"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.captureLambdaHandler = void 0;
/**
 * A middy middleware automating capture of metadata and annotations on segments or subsegments for a Lambda Handler.
 *
 * Using this middleware on your handler function will automatically:
 * * handle the subsegment lifecycle
 * * add the `ColdStart` annotation
 * * add the function response as metadata
 * * add the function error as metadata (if any)
 *
 * @example
 * ```typescript
 * import { Tracer, captureLambdaHandler } from '@aws-lambda-powertools/tracer';
 * import middy from '@middy/core';
 *
 * const tracer = new Tracer({ serviceName: 'serverlessAirline' });
 *
 * const lambdaHandler = async (_event: any, _context: any) => {
 *   ...
 * };
 *
 * export const handler = middy(lambdaHandler).use(captureLambdaHandler(tracer));
 * ```
 *
 * @param target - The Tracer instance to use for tracing
 * @param options - (_optional_) Options for the middleware
 * @returns middleware - The middy middleware object
 */
const captureLambdaHandler = (target, options) => {
    let lambdaSegment;
    const open = () => {
        lambdaSegment = target.getSegment();
        const handlerSegment = lambdaSegment.addNewSubsegment(`## ${process.env._HANDLER}`);
        target.setSegment(handlerSegment);
    };
    const close = () => {
        const subsegment = target.getSegment();
        subsegment.close();
        target.setSegment(lambdaSegment);
    };
    const captureLambdaHandlerBefore = async () => {
        if (target.isTracingEnabled()) {
            open();
            target.annotateColdStart();
            target.addServiceNameAnnotation();
        }
    };
    const captureLambdaHandlerAfter = async (request) => {
        if (target.isTracingEnabled()) {
            if (options?.captureResponse ?? true) {
                target.addResponseAsMetadata(request.response, process.env._HANDLER);
            }
            close();
        }
    };
    const captureLambdaHandlerError = async (request) => {
        if (target.isTracingEnabled()) {
            target.addErrorAsMetadata(request.error);
            close();
        }
    };
    return {
        before: captureLambdaHandlerBefore,
        after: captureLambdaHandlerAfter,
        onError: captureLambdaHandlerError
    };
};
exports.captureLambdaHandler = captureLambdaHandler;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWlkZHkuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvbW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