/* eslint-disable @typescript-eslint/ban-types */
// Note: disabling ban-type rule so we don't get an error referencing the class Function
import path from "path";
import fs from "fs-extra";
import * as cdk from "aws-cdk-lib";
import * as iam from "aws-cdk-lib/aws-iam";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as ssm from "aws-cdk-lib/aws-ssm";
import { Stack } from "./Stack.js";
import { toCdkSize } from "./util/size.js";
import { toCdkDuration } from "./util/duration.js";
import { attachPermissionsToRole } from "./util/permission.js";
import * as functionUrlCors from "./util/functionUrlCors.js";
import { State, Runtime } from "@serverless-stack/core";
import url from "url";
const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const supportedRuntimes = [
    lambda.Runtime.NODEJS,
    lambda.Runtime.NODEJS_4_3,
    lambda.Runtime.NODEJS_6_10,
    lambda.Runtime.NODEJS_8_10,
    lambda.Runtime.NODEJS_10_X,
    lambda.Runtime.NODEJS_12_X,
    lambda.Runtime.NODEJS_14_X,
    lambda.Runtime.NODEJS_16_X,
    lambda.Runtime.PYTHON_2_7,
    lambda.Runtime.PYTHON_3_6,
    lambda.Runtime.PYTHON_3_7,
    lambda.Runtime.PYTHON_3_8,
    lambda.Runtime.PYTHON_3_9,
    lambda.Runtime.DOTNET_CORE_1,
    lambda.Runtime.DOTNET_CORE_2,
    lambda.Runtime.DOTNET_CORE_2_1,
    lambda.Runtime.DOTNET_CORE_3_1,
    lambda.Runtime.DOTNET_6,
    lambda.Runtime.GO_1_X,
];
/**
 * A construct for a Lambda Function that allows you to [develop your it locally](live-lambda-development.md). Supports JS, TypeScript, Python, Golang, and C#. It also applies a couple of defaults:
 *
 * - Sets the default memory setting to 1024MB.
 * - Sets the default Lambda function timeout to 10 seconds.
 * - [Enables AWS X-Ray](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-tracing.html) by default so you can trace your serverless applications.
 * - `AWS_NODEJS_CONNECTION_REUSE_ENABLED` is turned on. Meaning that the Lambda function will automatically reuse TCP connections when working with the AWS SDK. [Read more about this here](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/node-reusing-connections.html).
 * - Sets the `IS_LOCAL` environment variable for the Lambda function when it is invoked locally through the `sst start` command.
 *
 * @example
 *
 * ### Creating a Function
 *
 * ```js
 * import { Function } from "@serverless-stack/resources";
 *
 * new Function(stack, "MySnsLambda", {
 *   handler: "src/sns/index.main",
 * });
 * ```
 */
export class Function extends lambda.Function {
    constructor(scope, id, props) {
        const root = scope.node.root;
        const stack = Stack.of(scope);
        // Merge with app defaultFunctionProps
        // note: reverse order so later prop override earlier ones
        stack.defaultFunctionProps
            .slice()
            .reverse()
            .forEach((per) => {
            props = Function.mergeProps(per, props);
        });
        // Set defaults
        const functionName = props.functionName &&
            (typeof props.functionName === "string"
                ? props.functionName
                : props.functionName({ stack, functionProps: props }));
        const handler = props.handler;
        const timeout = Function.normalizeTimeout(props.timeout);
        const srcPath = Function.normalizeSrcPath(props.srcPath || ".");
        const runtime = Function.normalizeRuntime(props.runtime);
        const architecture = (() => {
            if (props.architecture === "arm_64")
                return lambda.Architecture.ARM_64;
            if (props.architecture === "x86_64")
                return lambda.Architecture.X86_64;
            return undefined;
        })();
        const memorySize = Function.normalizeMemorySize(props.memorySize);
        const diskSize = Function.normalizeDiskSize(props.diskSize);
        const tracing = lambda.Tracing[(props.tracing || "active").toUpperCase()];
        let bundle = props.bundle;
        const permissions = props.permissions;
        const isLiveDevEnabled = props.enableLiveDev === false ? false : true;
        // Validate handler
        if (!handler) {
            throw new Error(`No handler defined for the "${id}" Lambda function`);
        }
        // Validate input
        const isNodeRuntime = runtime.toString().startsWith("nodejs");
        const isPythonRuntime = runtime.toString().startsWith("python");
        if (isNodeRuntime) {
            bundle = bundle === undefined ? true : props.bundle;
            if (!bundle && srcPath === ".") {
                throw new Error(`Bundle cannot be disabled for the "${id}" function since the "srcPath" is set to the project root. Read more here — https://github.com/serverless-stack/serverless-stack/issues/78`);
            }
        }
        else if (isPythonRuntime) {
            bundle = bundle === undefined ? {} : props.bundle;
            if (srcPath === ".") {
                throw new Error(`Cannot set the "srcPath" to the project root for the "${id}" function.`);
            }
        }
        const localId = path.posix
            .join(scope.node.path, id)
            .replace(/\$/g, "-")
            .replace(/\//g, "-")
            .replace(/\./g, "-");
        // Handle local development (ie. sst start)
        // - set runtime to nodejs12.x for non-Node runtimes (b/c the stub is in Node)
        // - set retry to 0. When the debugger is disconnected, the Cron construct
        //   will still try to periodically invoke the Lambda, and the requests would
        //   fail and retry. So when launching `sst start`, a couple of retry requests
        //   from recent failed request will be received. And this behavior is confusing.
        if (isLiveDevEnabled &&
            root.local &&
            root.debugEndpoint &&
            root.debugBucketName &&
            root.debugBucketArn) {
            // If debugIncreaseTimeout is enabled:
            //   set timeout to 900s. This will give people more time to debug the function
            //   without timing out the request. Note API Gateway requests have a maximum
            //   timeout of 29s. In this case, the API will timeout, but the Lambda function
            //   will continue to run.
            let debugOverrideProps;
            if (root.debugIncreaseTimeout) {
                debugOverrideProps = {
                    timeout: cdk.Duration.seconds(900),
                };
            }
            if (root.debugBridge) {
                super(scope, id, {
                    ...props,
                    architecture,
                    code: lambda.Code.fromAsset(path.resolve(__dirname, "../dist/bridge_client/")),
                    handler: "handler",
                    functionName,
                    runtime: lambda.Runtime.GO_1_X,
                    memorySize,
                    ephemeralStorageSize: diskSize,
                    timeout,
                    tracing,
                    environment: {
                        ...(props.environment || {}),
                        SST_DEBUG_BRIDGE: root.debugBridge,
                        SST_DEBUG_SRC_PATH: srcPath,
                        SST_DEBUG_SRC_HANDLER: handler,
                        SST_DEBUG_ENDPOINT: root.debugEndpoint,
                    },
                    layers: Function.buildLayers(scope, id, props),
                    ...(debugOverrideProps || {}),
                });
            }
            else {
                super(scope, id, {
                    ...props,
                    architecture,
                    code: lambda.Code.fromAsset(path.resolve(__dirname, "../dist/stub.zip")),
                    handler: "index.main",
                    functionName,
                    runtime: isNodeRuntime ? runtime : lambda.Runtime.NODEJS_12_X,
                    memorySize,
                    ephemeralStorageSize: diskSize,
                    timeout,
                    tracing,
                    environment: {
                        ...(props.environment || {}),
                        SST_DEBUG_SRC_PATH: srcPath,
                        SST_DEBUG_SRC_HANDLER: handler,
                        SST_DEBUG_ENDPOINT: root.debugEndpoint,
                        SST_DEBUG_BUCKET_NAME: root.debugBucketName,
                    },
                    layers: Function.buildLayers(scope, id, props),
                    retryAttempts: 0,
                    ...(debugOverrideProps || {}),
                });
            }
            State.Function.append(root.appPath, {
                id: localId,
                handler: handler,
                runtime: runtime.toString(),
                srcPath: srcPath,
                bundle: props.bundle,
            });
            this.addEnvironment("SST_FUNCTION_ID", localId);
            this.attachPermissions([
                new iam.PolicyStatement({
                    actions: ["s3:*"],
                    effect: iam.Effect.ALLOW,
                    resources: [root.debugBucketArn, `${root.debugBucketArn}/*`],
                }),
            ]);
        }
        // Handle remove (ie. sst remove)
        else if (root.skipBuild) {
            // Note: need to override runtime as CDK does not support inline code
            //       for some runtimes.
            super(scope, id, {
                ...props,
                architecture,
                code: lambda.Code.fromAsset(path.resolve(__dirname, "../assets/Function/placeholder-stub")),
                handler: "placeholder",
                functionName,
                runtime: lambda.Runtime.NODEJS_12_X,
                memorySize,
                ephemeralStorageSize: diskSize,
                timeout,
                tracing,
                environment: props.environment,
                layers: Function.buildLayers(scope, id, props),
            });
        }
        // Handle build
        else {
            const bundled = Runtime.Handler.bundle({
                id: localId,
                root: root.appPath,
                handler: handler,
                runtime: runtime.toString(),
                srcPath: srcPath,
                bundle: props.bundle,
            });
            // Python builder returns AssetCode instead of directory
            const code = (() => {
                if ("directory" in bundled) {
                    Function.copyFiles(bundle, srcPath, bundled.directory);
                    return lambda.AssetCode.fromAsset(bundled.directory);
                }
                return bundled.asset;
            })();
            super(scope, id, {
                ...props,
                architecture,
                code: code,
                handler: bundled.handler,
                functionName,
                runtime,
                memorySize,
                ephemeralStorageSize: diskSize,
                timeout,
                tracing,
                environment: props.environment,
                layers: Function.buildLayers(scope, id, props),
            });
        }
        this.props = props || {};
        // Enable reusing connections with Keep-Alive for NodeJs Lambda function
        if (isNodeRuntime) {
            this.addEnvironment("AWS_NODEJS_CONNECTION_REUSE_ENABLED", "1", {
                removeInEdge: true,
            });
        }
        // Attach permissions
        if (permissions) {
            this.attachPermissions(permissions);
        }
        // Create function URL
        this.createUrl();
        root.registerLambdaHandler({
            bundle: props.bundle,
            handler: handler,
            runtime: runtime.toString(),
            srcPath,
        });
        this._isLiveDevEnabled = isLiveDevEnabled;
        this.localId = localId;
    }
    /**
     * The AWS generated URL of the Function.
     */
    get url() {
        return this.functionUrl?.url;
    }
    /**
     * Attaches additional permissions to function
     *
     * @example
     * ```js {20}
     * fn.attachPermissions(["s3"]);
     * ```
     */
    attachPermissions(permissions) {
        if (this.role) {
            attachPermissionsToRole(this.role, permissions);
        }
    }
    getConstructMetadata() {
        return {
            type: "Function",
            data: {
                localId: this.localId,
                arn: this.functionArn,
            },
        };
    }
    createUrl() {
        const { url } = this.props;
        if (url === false || url === undefined) {
            return;
        }
        let authType;
        let cors;
        if (url === true) {
            authType = lambda.FunctionUrlAuthType.NONE;
            cors = true;
        }
        else {
            authType = url.authorizer === "iam"
                ? lambda.FunctionUrlAuthType.AWS_IAM
                : lambda.FunctionUrlAuthType.NONE;
            cors = url.cors === undefined
                ? true
                : url.cors;
        }
        this.functionUrl = this.addFunctionUrl({
            authType,
            cors: functionUrlCors.buildCorsConfig(cors),
        });
    }
    static buildLayers(scope, id, props) {
        return (props.layers || []).map((layer) => {
            if (typeof layer === "string") {
                return lambda.LayerVersion.fromLayerVersionArn(scope, `${id}${layer}`, layer);
            }
            return Function.handleImportedLayer(scope, layer);
        });
    }
    static normalizeMemorySize(memorySize) {
        if (typeof memorySize === "string") {
            return toCdkSize(memorySize).toMebibytes();
        }
        return memorySize || 1024;
    }
    static normalizeDiskSize(diskSize) {
        if (typeof diskSize === "string") {
            return toCdkSize(diskSize);
        }
        return cdk.Size.mebibytes(diskSize || 512);
    }
    static normalizeTimeout(timeout) {
        if (typeof timeout === "string") {
            return toCdkDuration(timeout);
        }
        return cdk.Duration.seconds(timeout || 10);
    }
    static normalizeRuntime(runtime) {
        runtime = runtime || "nodejs14.x";
        const runtimeClass = supportedRuntimes.find((per) => per.toString() === runtime);
        if (!runtimeClass) {
            throw new Error(`The specified runtime is not supported for sst.Function. Only NodeJS, Python, Go, and .NET runtimes are currently supported.`);
        }
        return runtimeClass;
    }
    static normalizeSrcPath(srcPath) {
        return srcPath.replace(/\/+$/, "");
    }
    static copyFiles(bundle, srcPath, buildPath) {
        if (!bundle)
            return;
        if (typeof bundle === "boolean")
            return;
        if (!bundle.copyFiles)
            return;
        bundle.copyFiles.forEach((entry) => {
            const fromPath = path.join(srcPath, entry.from);
            if (!fs.existsSync(fromPath))
                throw new Error(`Tried to copy nonexistent file from "${path.resolve(fromPath)}" - check copyFiles entry "${entry.from}"`);
            const to = entry.to || entry.from;
            if (path.isAbsolute(to))
                throw new Error(`Copy destination path "${to}" must be relative`);
            const toPath = path.join(buildPath, to);
            fs.copySync(fromPath, toPath);
        });
    }
    static handleImportedLayer(scope, layer) {
        const layerStack = Stack.of(layer);
        const currentStack = Stack.of(scope);
        // Use layer directly if:
        // - layer is created in the current stack; OR
        // - layer is imported (ie. layerArn is a string)
        if (layerStack === currentStack ||
            !cdk.Token.isUnresolved(layer.layerVersionArn)) {
            return layer;
        }
        // layer is created from another stack
        else {
            // set stack dependency b/c layerStack need to create the SSM first
            currentStack.addDependency(layerStack);
            // store layer ARN in SSM in layer's stack
            const parameterId = `${layer.node.id}Arn-${layer.node.addr}`;
            const parameterName = `/layers/${layerStack.node.id}/${parameterId}`;
            const existingSsmParam = layerStack.node.tryFindChild(parameterId);
            if (!existingSsmParam) {
                new ssm.StringParameter(layerStack, parameterId, {
                    parameterName,
                    stringValue: layer.layerVersionArn,
                });
            }
            // import layer from SSM value
            const layerId = `I${layer.node.id}-${layer.node.addr}`;
            const existingLayer = scope.node.tryFindChild(layerId);
            if (existingLayer) {
                return existingLayer;
            }
            else {
                return lambda.LayerVersion.fromLayerVersionArn(scope, layerId, ssm.StringParameter.valueForStringParameter(scope, parameterName));
            }
        }
    }
    static isInlineDefinition(definition) {
        return typeof definition === "string" || definition instanceof Function;
    }
    static fromDefinition(scope, id, definition, inheritedProps, inheritErrorMessage) {
        if (typeof definition === "string") {
            return new Function(scope, id, {
                ...(inheritedProps || {}),
                handler: definition,
            });
        }
        else if (definition instanceof Function) {
            if (inheritedProps && Object.keys(inheritedProps).length > 0) {
                throw new Error(inheritErrorMessage ||
                    `Cannot inherit default props when a Function is provided`);
            }
            return definition;
        }
        else if (definition instanceof lambda.Function) {
            throw new Error(`Please use sst.Function instead of lambda.Function for the "${id}" Function.`);
        }
        else if (definition.handler !== undefined) {
            return new Function(scope, id, Function.mergeProps(inheritedProps, definition));
        }
        throw new Error(`Invalid function definition for the "${id}" Function`);
    }
    static mergeProps(baseProps, props) {
        // Merge environment
        const environment = {
            ...(baseProps?.environment || {}),
            ...(props?.environment || {}),
        };
        const environmentProp = Object.keys(environment).length === 0 ? {} : { environment };
        // Merge layers
        const layers = [...(baseProps?.layers || []), ...(props?.layers || [])];
        const layersProp = layers.length === 0 ? {} : { layers };
        // Merge permissions
        let permissionsProp;
        if (baseProps?.permissions === "*") {
            permissionsProp = { permissions: baseProps.permissions };
        }
        else if (props?.permissions === "*") {
            permissionsProp = { permissions: props.permissions };
        }
        else {
            const permissions = (baseProps?.permissions || []).concat(props?.permissions || []);
            permissionsProp = permissions.length === 0 ? {} : { permissions };
        }
        return {
            ...(baseProps || {}),
            ...(props || {}),
            ...layersProp,
            ...environmentProp,
            ...permissionsProp,
        };
    }
}
