"use strict";

require("core-js/modules/es.array.iterator.js");
require("core-js/modules/es.string.iterator.js");
require("core-js/modules/es.weak-map.js");
require("core-js/modules/web.dom-collections.iterator.js");
require("core-js/modules/es.object.define-property.js");
require("core-js/modules/es.object.get-own-property-descriptor.js");
require("core-js/modules/es.symbol.js");
require("core-js/modules/es.array.filter.js");
require("core-js/modules/es.object.get-own-property-descriptors.js");
require("core-js/modules/es.object.define-properties.js");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.serverSideTranslations = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
require("core-js/modules/es.object.to-string.js");
require("core-js/modules/es.promise.js");
require("core-js/modules/es.array.some.js");
require("core-js/modules/es.array.is-array.js");
require("core-js/modules/es.array.for-each.js");
require("core-js/modules/web.dom-collections.for-each.js");
require("core-js/modules/es.array.concat.js");
require("core-js/modules/es.array.map.js");
require("core-js/modules/es.regexp.exec.js");
require("core-js/modules/es.string.replace.js");
require("core-js/modules/es.array.flat.js");
require("core-js/modules/es.array.unscopables.flat.js");
require("core-js/modules/es.object.keys.js");
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _fs = _interopRequireDefault(require("fs"));
var _path = _interopRequireDefault(require("path"));
var _createConfig = require("./config/createConfig");
var _node = _interopRequireDefault(require("./createClient/node"));
var _appWithTranslation = require("./appWithTranslation");
var _utils = require("./utils");
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2["default"])(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }
var DEFAULT_CONFIG_PATH = './next-i18next.config.js';

/**
 * One line expression like `const { I18NEXT_DEFAULT_CONFIG_PATH: DEFAULT_CONFIG_PATH = './next-i18next.config.js' } = process.env;`
 * is breaking the build, so keep it like this.
 *
 * @see https://github.com/i18next/next-i18next/pull/2084#issuecomment-1420511358
 */
if (process.env.I18NEXT_DEFAULT_CONFIG_PATH) {
  DEFAULT_CONFIG_PATH = process.env.I18NEXT_DEFAULT_CONFIG_PATH;
}
var serverSideTranslations = exports.serverSideTranslations = /*#__PURE__*/function () {
  var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(initialLocale) {
    var _userConfig;
    var namespacesRequired,
      configOverride,
      extraLocales,
      userConfig,
      configPath,
      config,
      localeExtension,
      localePath,
      fallbackLng,
      reloadOnPrerender,
      _createClient,
      i18n,
      initPromise,
      hasCustomBackend,
      initialI18nStore,
      getLocaleNamespaces,
      namespacesByLocale,
      _args = arguments;
    return _regenerator["default"].wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          namespacesRequired = _args.length > 1 && _args[1] !== undefined ? _args[1] : undefined;
          configOverride = _args.length > 2 && _args[2] !== undefined ? _args[2] : null;
          extraLocales = _args.length > 3 && _args[3] !== undefined ? _args[3] : false;
          if (!(typeof initialLocale !== 'string')) {
            _context.next = 5;
            break;
          }
          throw new Error('Initial locale argument was not passed into serverSideTranslations');
        case 5:
          userConfig = configOverride;
          configPath = _path["default"].resolve(DEFAULT_CONFIG_PATH);
          if (!(!userConfig && _fs["default"].existsSync(configPath))) {
            _context.next = 11;
            break;
          }
          _context.next = 10;
          return function (specifier) {
            return new Promise(function (r) {
              return r("".concat(specifier));
            }).then(function (s) {
              return _interopRequireWildcard(require(s));
            });
          }(configPath);
        case 10:
          userConfig = _context.sent;
        case 11:
          if (!(userConfig === null)) {
            _context.next = 13;
            break;
          }
          throw new Error("next-i18next was unable to find a user config at ".concat(configPath));
        case 13:
          config = (0, _createConfig.createConfig)(_objectSpread(_objectSpread({}, userConfig), {}, {
            lng: initialLocale
          }));
          localeExtension = config.localeExtension, localePath = config.localePath, fallbackLng = config.fallbackLng, reloadOnPrerender = config.reloadOnPrerender;
          if (!reloadOnPrerender) {
            _context.next = 18;
            break;
          }
          _context.next = 18;
          return _appWithTranslation.globalI18n === null || _appWithTranslation.globalI18n === void 0 ? void 0 : _appWithTranslation.globalI18n.reloadResources();
        case 18:
          _createClient = (0, _node["default"])(_objectSpread(_objectSpread({}, config), {}, {
            lng: initialLocale
          })), i18n = _createClient.i18n, initPromise = _createClient.initPromise;
          _context.next = 21;
          return initPromise;
        case 21:
          hasCustomBackend = (_userConfig = userConfig) === null || _userConfig === void 0 || (_userConfig = _userConfig.use) === null || _userConfig === void 0 ? void 0 : _userConfig.some(function (b) {
            return b.type === 'backend';
          });
          if (!(hasCustomBackend && namespacesRequired)) {
            _context.next = 25;
            break;
          }
          _context.next = 25;
          return i18n.loadNamespaces(Array.isArray(namespacesRequired) ? namespacesRequired : namespacesRequired);
        case 25:
          initialI18nStore = (0, _defineProperty2["default"])({}, initialLocale, {});
          (0, _utils.getFallbackForLng)(initialLocale, fallbackLng !== null && fallbackLng !== void 0 ? fallbackLng : false).concat(extraLocales || []).forEach(function (lng) {
            initialI18nStore[lng] = {};
          });
          if (Array.isArray(namespacesRequired)) {
            _context.next = 33;
            break;
          }
          if (!(typeof localePath === 'function')) {
            _context.next = 30;
            break;
          }
          throw new Error('Must provide namespacesRequired to serverSideTranslations when using a function as localePath');
        case 30:
          getLocaleNamespaces = function getLocaleNamespaces(path) {
            return _fs["default"].existsSync(path) ? _fs["default"].readdirSync(path).map(function (file) {
              return file.replace(".".concat(localeExtension), '');
            }) : [];
          };
          namespacesByLocale = Object.keys(initialI18nStore).map(function (locale) {
            return getLocaleNamespaces(_path["default"].resolve(process.cwd(), "".concat(localePath, "/").concat(locale)));
          }).flat();
          namespacesRequired = (0, _utils.unique)(namespacesByLocale);
        case 33:
          namespacesRequired.forEach(function (ns) {
            for (var locale in initialI18nStore) {
              initialI18nStore[locale][ns] = (i18n.services.resourceStore.data[locale] || {})[ns] || {};
            }
          });
          return _context.abrupt("return", {
            _nextI18Next: {
              initialI18nStore: initialI18nStore,
              initialLocale: initialLocale,
              ns: namespacesRequired,
              userConfig: config.serializeConfig ? userConfig : null
            }
          });
        case 35:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return function serverSideTranslations(_x) {
    return _ref.apply(this, arguments);
  };
}();