UNPKG

@opra/core

Version:
53 lines (52 loc) 2.32 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const node_fs_1 = tslib_1.__importDefault(require("node:fs")); const node_path_1 = tslib_1.__importDefault(require("node:path")); const common_1 = require("@opra/common"); common_1.I18n.load = async function (options) { const opts = { ...options, }; delete opts.resourceDirs; const instance = common_1.I18n.createInstance(opts); await instance.init(); await instance.loadResourceDir(node_path_1.default.resolve((0, common_1.getStackFileName)(), '../../../i18n')); if (options?.resourceDirs) for (const dir of options.resourceDirs) await instance.loadResourceDir(dir); return instance; }; common_1.I18n.prototype.loadResourceBundle = async function (lang, ns, filePath, deep, overwrite) { let obj; if (URL.canParse(filePath)) { obj = (await fetch(filePath, { headers: { accept: 'application/json' } })).json(); } else { const content = node_fs_1.default.readFileSync(filePath, 'utf8'); obj = JSON.parse(content); } this.addResourceBundle(lang, ns, obj, deep, overwrite); }; common_1.I18n.prototype.loadResourceDir = async function (dirnames, deep, overwrite) { for (const dirname of Array.isArray(dirnames) ? dirnames : [dirnames]) { /* istanbul ignore next */ if (!node_fs_1.default.existsSync(dirname)) continue; const languageDirs = node_fs_1.default.readdirSync(dirname); for (const lang of languageDirs) { const langDir = node_path_1.default.join(dirname, lang); if (node_fs_1.default.statSync(langDir).isDirectory()) { const nsDirs = node_fs_1.default.readdirSync(langDir); for (const nsfile of nsDirs) { const nsFilePath = node_path_1.default.join(langDir, nsfile); const ext = node_path_1.default.extname(nsfile); if (ext === '.json' && node_fs_1.default.statSync(nsFilePath).isFile()) { const ns = node_path_1.default.basename(nsfile, ext); await this.loadResourceBundle(lang, ns, nsFilePath, deep, overwrite); } } } } } };