"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deploySite = exports.internalDeploySite = void 0;
const lambda_client_1 = require("@remotion/lambda-client");
const constants_1 = require("@remotion/lambda-client/constants");
const error_handling_1 = require("@remotion/renderer/error-handling");
const serverless_1 = require("@remotion/serverless");
const node_fs_1 = __importDefault(require("node:fs"));
const full_client_implementation_1 = require("../functions/full-client-implementation");
const get_s3_operations_1 = require("../shared/get-s3-operations");
const validate_site_name_1 = require("../shared/validate-site-name");
const mandatoryDeploySite = async ({ bucketName, entryPoint, siteName, options, region, privacy, gitSource, throwIfSiteExists, providerSpecifics, forcePathStyle, fullClientSpecifics, requestHandler, }) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
    lambda_client_1.LambdaClientInternals.validateAwsRegion(region);
    (0, serverless_1.validateBucketName)({
        bucketName,
        bucketNamePrefix: constants_1.REMOTION_BUCKET_PREFIX,
        options: {
            mustStartWithRemotion: !(options === null || options === void 0 ? void 0 : options.bypassBucketNameValidation),
        },
    });
    (0, validate_site_name_1.validateSiteName)(siteName);
    (0, serverless_1.validatePrivacy)(privacy, false);
    const accountId = await providerSpecifics.getAccountId({ region });
    const bucketExists = await providerSpecifics.bucketExists({
        bucketName,
        region,
        expectedBucketOwner: accountId,
        forcePathStyle,
        requestHandler,
    });
    if (!bucketExists) {
        throw new Error(`No bucket with the name ${bucketName} exists`);
    }
    const subFolder = (0, constants_1.getSitesKey)(siteName);
    const [files, bundled] = await Promise.all([
        providerSpecifics.listObjects({
            bucketName,
            expectedBucketOwner: accountId,
            region,
            // The `/` is important to not accidentially delete sites with the same name but containing a suffix.
            prefix: `${subFolder}/`,
            forcePathStyle,
            requestHandler,
        }),
        fullClientSpecifics.bundleSite({
            publicPath: `/${subFolder}/`,
            webpackOverride: (_a = options === null || options === void 0 ? void 0 : options.webpackOverride) !== null && _a !== void 0 ? _a : ((f) => f),
            enableCaching: (_b = options === null || options === void 0 ? void 0 : options.enableCaching) !== null && _b !== void 0 ? _b : true,
            publicDir: (_c = options === null || options === void 0 ? void 0 : options.publicDir) !== null && _c !== void 0 ? _c : null,
            rootDir: (_d = options === null || options === void 0 ? void 0 : options.rootDir) !== null && _d !== void 0 ? _d : null,
            ignoreRegisterRootWarning: (_e = options === null || options === void 0 ? void 0 : options.ignoreRegisterRootWarning) !== null && _e !== void 0 ? _e : false,
            onProgress: (_f = options === null || options === void 0 ? void 0 : options.onBundleProgress) !== null && _f !== void 0 ? _f : (() => undefined),
            entryPoint,
            gitSource,
            bufferStateDelayInMilliseconds: null,
            maxTimelineTracks: null,
            onDirectoryCreated: () => undefined,
            onPublicDirCopyProgress: () => undefined,
            onSymlinkDetected: () => undefined,
            outDir: null,
            askAIEnabled: (_g = options === null || options === void 0 ? void 0 : options.askAIEnabled) !== null && _g !== void 0 ? _g : true,
            audioLatencyHint: null,
            experimentalClientSideRenderingEnabled: (_h = options === null || options === void 0 ? void 0 : options.experimentalClientSideRenderingEnabled) !== null && _h !== void 0 ? _h : false,
            keyboardShortcutsEnabled: (_j = options === null || options === void 0 ? void 0 : options.keyboardShortcutsEnabled) !== null && _j !== void 0 ? _j : true,
            renderDefaults: null,
        }),
    ]);
    if (throwIfSiteExists && files.length > 0) {
        throw new Error('`throwIfSiteExists` was passed as true, but there are already files in this folder: ' +
            files
                .slice(0, 5)
                .map((f) => f.Key)
                .join(', '));
    }
    (_k = options.onDiffingProgress) === null || _k === void 0 ? void 0 : _k.call(options, 0, false);
    let totalBytes = 0;
    const { toDelete, toUpload, existingCount } = await (0, get_s3_operations_1.getS3DiffOperations)({
        objects: files,
        bundle: bundled,
        prefix: subFolder,
        onProgress: (bytes) => {
            var _a;
            totalBytes = bytes;
            (_a = options.onDiffingProgress) === null || _a === void 0 ? void 0 : _a.call(options, bytes, false);
        },
        fullClientSpecifics,
    });
    (_l = options.onDiffingProgress) === null || _l === void 0 ? void 0 : _l.call(options, totalBytes, true);
    await Promise.all([
        fullClientSpecifics.uploadDir({
            bucket: bucketName,
            region,
            localDir: bundled,
            onProgress: (_m = options === null || options === void 0 ? void 0 : options.onUploadProgress) !== null && _m !== void 0 ? _m : (() => undefined),
            keyPrefix: subFolder,
            privacy: privacy !== null && privacy !== void 0 ? privacy : 'public',
            toUpload,
            forcePathStyle,
            requestHandler,
        }),
        Promise.all(toDelete.map((d) => {
            return providerSpecifics.deleteFile({
                bucketName,
                customCredentials: null,
                key: d.Key,
                region,
                forcePathStyle,
                requestHandler,
            });
        })),
    ]);
    if (node_fs_1.default.existsSync(bundled)) {
        node_fs_1.default.rmSync(bundled, {
            recursive: true,
        });
    }
    return {
        serveUrl: lambda_client_1.LambdaClientInternals.makeS3ServeUrl({
            bucketName,
            subFolder,
            region,
        }),
        siteName,
        stats: {
            uploadedFiles: toUpload.length,
            deletedFiles: toDelete.length,
            untouchedFiles: existingCount,
        },
    };
};
exports.internalDeploySite = (0, error_handling_1.wrapWithErrorHandling)(mandatoryDeploySite);
/*
 * @description Deploys a Remotion project to a GCP storage bucket to prepare it for rendering on Cloud Run.
 * @see [Documentation](https://remotion.dev/docs/cloudrun/deploysite)
 */
const deploySite = (args) => {
    var _a, _b, _c, _d, _e, _f, _g;
    return (0, exports.internalDeploySite)({
        bucketName: args.bucketName,
        entryPoint: args.entryPoint,
        region: args.region,
        gitSource: (_a = args.gitSource) !== null && _a !== void 0 ? _a : null,
        options: (_b = args.options) !== null && _b !== void 0 ? _b : {},
        privacy: (_c = args.privacy) !== null && _c !== void 0 ? _c : 'public',
        siteName: (_d = args.siteName) !== null && _d !== void 0 ? _d : lambda_client_1.LambdaClientInternals.awsImplementation.randomHash(),
        indent: false,
        logLevel: 'info',
        throwIfSiteExists: (_e = args.throwIfSiteExists) !== null && _e !== void 0 ? _e : false,
        providerSpecifics: lambda_client_1.LambdaClientInternals.awsImplementation,
        forcePathStyle: (_f = args.forcePathStyle) !== null && _f !== void 0 ? _f : false,
        fullClientSpecifics: full_client_implementation_1.awsFullClientSpecifics,
        requestHandler: (_g = args.requestHandler) !== null && _g !== void 0 ? _g : null,
    });
};
exports.deploySite = deploySite;
