"use strict";
/*
 * @poppinss/utils
 *
 * (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.
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.requireAll = void 0;
const path_1 = require("path");
const require_all_1 = __importDefault(require("require-all"));
const esmResolver_1 = require("../esmResolver");
const isScriptFile_1 = require("../isScriptFile");
/**
 * Function to filter and keep script files only
 */
function fileFilter(file) {
    return (0, isScriptFile_1.isScriptFile)(file);
}
/**
 * Require all files from a given directory. The method automatically looks
 * for files ending with `.ts`, `.js` and `.json`. Also files ending with
 * `.d.ts` are ignored.
 */
function requireAll(location, recursive = true, optional = false, filter = fileFilter) {
    try {
        return (0, require_all_1.default)({
            dirname: location,
            recursive,
            filter: (file) => {
                let result = true;
                /**
                 * Invoke user defined function
                 */
                if (typeof filter === 'function') {
                    result = filter(file);
                }
                /**
                 * Use the default file name when file is meant to
                 * be kept
                 */
                if (result === true) {
                    const ext = (0, path_1.extname)(file);
                    return file.replace(new RegExp(`${ext}$`), '');
                }
                return result;
            },
            resolve: esmResolver_1.esmResolver,
        });
    }
    catch (error) {
        if (error.code === 'ENOENT' && optional) {
            return;
        }
        else {
            throw error;
        }
    }
}
exports.requireAll = requireAll;
