"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpfxServeTask = exports.DEBUG_MANIFESTS_QUERY_PARAMETER = void 0;
const colors_1 = __importDefault(require("colors"));
const path = __importStar(require("path"));
const url_1 = require("url");
const ServeTask_1 = require("@microsoft/gulp-core-build-serve/lib/ServeTask");
const spfx_heft_plugins_1 = require("@microsoft/spfx-heft-plugins");
const CONFIG_CLI_PARAMETER = 'config';
exports.DEBUG_MANIFESTS_QUERY_PARAMETER = 'debugManifestsFile';
const LOAD_SPFX_QUERY_PARAMETER = 'loadSPFX';
const CUSTOM_ACTIONS_QUERY_PARAMETER = 'customActions';
const FIELD_CUSTOMIZERS_QUERY_PARAMETER = 'fieldCustomizers';
class SpfxServeTask extends ServeTask_1.ServeTask {
    constructor() {
        super('spfx-serve', {});
        this._defaultInitialPage = this.taskConfig.initialPage;
    }
    async executeTask(gulp) {
        var _a;
        let buildProperties;
        if (!this.buildConfig.properties) {
            this.buildConfig.properties = {};
        }
        buildProperties = this.buildConfig.properties;
        buildProperties.serveMode = true;
        const selectedServeConfiguration = this.buildConfig.args[CONFIG_CLI_PARAMETER];
        let serveConfiguration;
        if (selectedServeConfiguration) {
            this.logVerbose(`Attempting to use serve configuration: "${selectedServeConfiguration}"`);
            serveConfiguration = (_a = this.taskConfig.serveConfigurations) === null || _a === void 0 ? void 0 : _a[selectedServeConfiguration];
            if (!serveConfiguration) {
                this.logWarning(`Selected serve configuration "${selectedServeConfiguration}" is not present in the ` +
                    'task configuration. Falling back to default configuration.');
            }
        }
        if (!serveConfiguration && this.taskConfig.serveConfigurations) {
            serveConfiguration = this.taskConfig.serveConfigurations.default;
            if (serveConfiguration && this.taskConfig.initialPage !== this._defaultInitialPage) {
                this.logWarning('Both a default serve configuration and an initialPage are specified. In this task, ' +
                    'the default configuration takes precedence. Consider removing the initialPage property.');
            }
        }
        if (serveConfiguration) {
            this.taskConfig.initialPage = this._convertServeConfigurationToPageUrl(serveConfiguration);
        }
        this.log(`To load your scripts, use this query string: ` +
            `${colors_1.default.yellow(`?debug=true&noredir=true&${exports.DEBUG_MANIFESTS_QUERY_PARAMETER}=${this._getManifestJsUrl().href}`)}`);
        // We're using ipAddress instead of hostname if provided to start the server.
        if (this.taskConfig.ipAddress) {
            this.taskConfig.hostname = this.taskConfig.ipAddress;
        }
        return await super.executeTask(gulp);
    }
    loadSchema() {
        return (0, spfx_heft_plugins_1._loadServeSchemaJson)();
    }
    _getConfigFilePath() {
        // Make sure this task uses the "serve.json" config file, not "spfx-serve.json"
        return path.join(path.dirname(super._getConfigFilePath()), 'serve.json');
    }
    _convertServeConfigurationToPageUrl(serveConfiguration) {
        if (!serveConfiguration.pageUrl) {
            this.logError('The pageUrl property of the selected serve configuration must be set.');
            return undefined;
        }
        const url = new url_1.URL(serveConfiguration.pageUrl);
        if (!url.searchParams.has(exports.DEBUG_MANIFESTS_QUERY_PARAMETER)) {
            url.searchParams.set(exports.DEBUG_MANIFESTS_QUERY_PARAMETER, this._getManifestJsUrl().href);
        }
        if (serveConfiguration.customActions || serveConfiguration.fieldCustomizers) {
            if (!url.searchParams.has(LOAD_SPFX_QUERY_PARAMETER)) {
                url.searchParams.set(LOAD_SPFX_QUERY_PARAMETER, 'true');
            }
        }
        if (serveConfiguration.customActions) {
            url.searchParams.set(CUSTOM_ACTIONS_QUERY_PARAMETER, JSON.stringify(serveConfiguration.customActions));
        }
        if (serveConfiguration.fieldCustomizers) {
            url.searchParams.set(FIELD_CUSTOMIZERS_QUERY_PARAMETER, JSON.stringify(serveConfiguration.fieldCustomizers));
        }
        return url.href;
    }
    _getManifestJsUrl() {
        const manifestsJsUrl = this._getBaseServeUrl();
        manifestsJsUrl.pathname = 'temp/manifests.js';
        return manifestsJsUrl;
    }
    _getBaseServeUrl() {
        const taskConfig = this.taskConfig;
        return new url_1.URL(`${taskConfig.https ? 'https' : 'http'}://${taskConfig.hostname}:${taskConfig.port}/`);
    }
}
exports.SpfxServeTask = SpfxServeTask;
//# sourceMappingURL=SpfxServeTask.js.map