"use strict";
/*
 * @adonisjs/env
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.string = void 0;
const utils_1 = require("@poppinss/utils");
const helpers_1 = require("./helpers");
/**
 * Formats against which a string can be optionally validated. We
 * lazy load the dependencies required for validating formats
 */
const formats = {
    email: (key, value, options) => {
        if (!require('validator/lib/isEmail')(value)) {
            throw new utils_1.Exception(options.message ||
                `Value for environment variable "${key}" must be a valid email, instead received "${value}"`, 500, 'E_INVALID_ENV_VALUE');
        }
    },
    host: (key, value, options) => {
        if (!require('validator/lib/isFQDN')(value, { require_tld: false }) &&
            !require('validator/lib/isIP')(value)) {
            throw new utils_1.Exception(options.message ||
                `Value for environment variable "${key}" must be a valid (domain or ip), instead received "${value}"`, 500, 'E_INVALID_ENV_VALUE');
        }
    },
    url: (key, value, options) => {
        const { tld = true, protocol = true } = options;
        if (!require('validator/lib/isURL')(value, { require_tld: tld, require_protocol: protocol })) {
            throw new utils_1.Exception(options.message ||
                `Value for environment variable "${key}" must be a valid URL, instead received "${value}"`, 500, 'E_INVALID_ENV_VALUE');
        }
    },
};
/**
 * Enforces the value to exist and be of type string
 */
function string(options) {
    return function validate(key, value) {
        (0, helpers_1.ensureValue)(key, value, options?.message);
        if (options?.format) {
            formats[options.format](key, value, options);
        }
        return value;
    };
}
exports.string = string;
/**
 * Same as the string rule, but allows non-existing values too
 */
string.optional = function optionalString(options) {
    return function validate(key, value) {
        if (!value) {
            return undefined;
        }
        if (options?.format) {
            formats[options.format](key, value, options);
        }
        return value;
    };
};
