maze-blockly-wrapper
Version:
A Blockly-based maze game wrapper with editable maze generation and programming interface
1,239 lines (1,238 loc) • 388 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
var target = {};
for (var prop in source)
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
target[prop] = source[prop];
if (source != null && __getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(source)) {
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
target[prop] = source[prop];
}
return target;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxRuntime = require("react/jsx-runtime");
const React = require("react");
const ReactDOM = require("react-dom");
function _interopNamespaceDefault(e) {
const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
if (e) {
for (const k in e) {
if (k !== "default") {
const d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: () => e[k]
});
}
}
}
n.default = e;
return Object.freeze(n);
}
const React__namespace = /* @__PURE__ */ _interopNamespaceDefault(React);
const isString$1 = (obj) => typeof obj === "string";
const defer = () => {
let res;
let rej;
const promise = new Promise((resolve, reject) => {
res = resolve;
rej = reject;
});
promise.resolve = res;
promise.reject = rej;
return promise;
};
const makeString = (object) => {
if (object == null) return "";
return "" + object;
};
const copy = (a, s, t) => {
a.forEach((m) => {
if (s[m]) t[m] = s[m];
});
};
const lastOfPathSeparatorRegExp = /###/g;
const cleanKey = (key) => key && key.indexOf("###") > -1 ? key.replace(lastOfPathSeparatorRegExp, ".") : key;
const canNotTraverseDeeper = (object) => !object || isString$1(object);
const getLastOfPath = (object, path2, Empty) => {
const stack = !isString$1(path2) ? path2 : path2.split(".");
let stackIndex = 0;
while (stackIndex < stack.length - 1) {
if (canNotTraverseDeeper(object)) return {};
const key = cleanKey(stack[stackIndex]);
if (!object[key] && Empty) object[key] = new Empty();
if (Object.prototype.hasOwnProperty.call(object, key)) {
object = object[key];
} else {
object = {};
}
++stackIndex;
}
if (canNotTraverseDeeper(object)) return {};
return {
obj: object,
k: cleanKey(stack[stackIndex])
};
};
const setPath = (object, path2, newValue) => {
const {
obj,
k
} = getLastOfPath(object, path2, Object);
if (obj !== void 0 || path2.length === 1) {
obj[k] = newValue;
return;
}
let e = path2[path2.length - 1];
let p = path2.slice(0, path2.length - 1);
let last = getLastOfPath(object, p, Object);
while (last.obj === void 0 && p.length) {
e = `${p[p.length - 1]}.${e}`;
p = p.slice(0, p.length - 1);
last = getLastOfPath(object, p, Object);
if ((last == null ? void 0 : last.obj) && typeof last.obj[`${last.k}.${e}`] !== "undefined") {
last.obj = void 0;
}
}
last.obj[`${last.k}.${e}`] = newValue;
};
const pushPath = (object, path2, newValue, concat) => {
const {
obj,
k
} = getLastOfPath(object, path2, Object);
obj[k] = obj[k] || [];
obj[k].push(newValue);
};
const getPath = (object, path2) => {
const {
obj,
k
} = getLastOfPath(object, path2);
if (!obj) return void 0;
if (!Object.prototype.hasOwnProperty.call(obj, k)) return void 0;
return obj[k];
};
const getPathWithDefaults = (data, defaultData, key) => {
const value = getPath(data, key);
if (value !== void 0) {
return value;
}
return getPath(defaultData, key);
};
const deepExtend = (target, source, overwrite) => {
for (const prop in source) {
if (prop !== "__proto__" && prop !== "constructor") {
if (prop in target) {
if (isString$1(target[prop]) || target[prop] instanceof String || isString$1(source[prop]) || source[prop] instanceof String) {
if (overwrite) target[prop] = source[prop];
} else {
deepExtend(target[prop], source[prop], overwrite);
}
} else {
target[prop] = source[prop];
}
}
}
return target;
};
const regexEscape = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var _entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"/": "/"
};
const escape = (data) => {
if (isString$1(data)) {
return data.replace(/[&<>"'\/]/g, (s) => _entityMap[s]);
}
return data;
};
class RegExpCache {
constructor(capacity) {
this.capacity = capacity;
this.regExpMap = /* @__PURE__ */ new Map();
this.regExpQueue = [];
}
getRegExp(pattern) {
const regExpFromCache = this.regExpMap.get(pattern);
if (regExpFromCache !== void 0) {
return regExpFromCache;
}
const regExpNew = new RegExp(pattern);
if (this.regExpQueue.length === this.capacity) {
this.regExpMap.delete(this.regExpQueue.shift());
}
this.regExpMap.set(pattern, regExpNew);
this.regExpQueue.push(pattern);
return regExpNew;
}
}
const chars = [" ", ",", "?", "!", ";"];
const looksLikeObjectPathRegExpCache = new RegExpCache(20);
const looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
nsSeparator = nsSeparator || "";
keySeparator = keySeparator || "";
const possibleChars = chars.filter((c) => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
if (possibleChars.length === 0) return true;
const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`);
let matched = !r.test(key);
if (!matched) {
const ki = key.indexOf(keySeparator);
if (ki > 0 && !r.test(key.substring(0, ki))) {
matched = true;
}
}
return matched;
};
const deepFind = function(obj, path2) {
let keySeparator = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : ".";
if (!obj) return void 0;
if (obj[path2]) {
if (!Object.prototype.hasOwnProperty.call(obj, path2)) return void 0;
return obj[path2];
}
const tokens = path2.split(keySeparator);
let current = obj;
for (let i = 0; i < tokens.length; ) {
if (!current || typeof current !== "object") {
return void 0;
}
let next;
let nextPath = "";
for (let j = i; j < tokens.length; ++j) {
if (j !== i) {
nextPath += keySeparator;
}
nextPath += tokens[j];
next = current[nextPath];
if (next !== void 0) {
if (["string", "number", "boolean"].indexOf(typeof next) > -1 && j < tokens.length - 1) {
continue;
}
i += j - i + 1;
break;
}
}
current = next;
}
return current;
};
const getCleanedCode = (code) => code == null ? void 0 : code.replace("_", "-");
const consoleLogger = {
type: "logger",
log(args) {
this.output("log", args);
},
warn(args) {
this.output("warn", args);
},
error(args) {
this.output("error", args);
},
output(type, args) {
var _a, _b;
(_b = (_a = console == null ? void 0 : console[type]) == null ? void 0 : _a.apply) == null ? void 0 : _b.call(_a, console, args);
}
};
class Logger {
constructor(concreteLogger) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
this.init(concreteLogger, options);
}
init(concreteLogger) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
this.prefix = options.prefix || "i18next:";
this.logger = concreteLogger || consoleLogger;
this.options = options;
this.debug = options.debug;
}
log() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return this.forward(args, "log", "", true);
}
warn() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return this.forward(args, "warn", "", true);
}
error() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return this.forward(args, "error", "");
}
deprecate() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
}
forward(args, lvl, prefix, debugOnly) {
if (debugOnly && !this.debug) return null;
if (isString$1(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
return this.logger[lvl](args);
}
create(moduleName) {
return new Logger(this.logger, __spreadValues(__spreadValues({}, {
prefix: `${this.prefix}:${moduleName}:`
}), this.options));
}
clone(options) {
options = options || this.options;
options.prefix = options.prefix || this.prefix;
return new Logger(this.logger, options);
}
}
var baseLogger = new Logger();
class EventEmitter {
constructor() {
this.observers = {};
}
on(events, listener) {
events.split(" ").forEach((event) => {
if (!this.observers[event]) this.observers[event] = /* @__PURE__ */ new Map();
const numListeners = this.observers[event].get(listener) || 0;
this.observers[event].set(listener, numListeners + 1);
});
return this;
}
off(event, listener) {
if (!this.observers[event]) return;
if (!listener) {
delete this.observers[event];
return;
}
this.observers[event].delete(listener);
}
emit(event) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (this.observers[event]) {
const cloned = Array.from(this.observers[event].entries());
cloned.forEach((_ref) => {
let [observer, numTimesAdded] = _ref;
for (let i = 0; i < numTimesAdded; i++) {
observer(...args);
}
});
}
if (this.observers["*"]) {
const cloned = Array.from(this.observers["*"].entries());
cloned.forEach((_ref2) => {
let [observer, numTimesAdded] = _ref2;
for (let i = 0; i < numTimesAdded; i++) {
observer.apply(observer, [event, ...args]);
}
});
}
}
}
class ResourceStore extends EventEmitter {
constructor(data) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
ns: ["translation"],
defaultNS: "translation"
};
super();
this.data = data || {};
this.options = options;
if (this.options.keySeparator === void 0) {
this.options.keySeparator = ".";
}
if (this.options.ignoreJSONStructure === void 0) {
this.options.ignoreJSONStructure = true;
}
}
addNamespaces(ns) {
if (this.options.ns.indexOf(ns) < 0) {
this.options.ns.push(ns);
}
}
removeNamespaces(ns) {
const index = this.options.ns.indexOf(ns);
if (index > -1) {
this.options.ns.splice(index, 1);
}
}
getResource(lng, ns, key) {
var _a, _b;
let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
const ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
let path2;
if (lng.indexOf(".") > -1) {
path2 = lng.split(".");
} else {
path2 = [lng, ns];
if (key) {
if (Array.isArray(key)) {
path2.push(...key);
} else if (isString$1(key) && keySeparator) {
path2.push(...key.split(keySeparator));
} else {
path2.push(key);
}
}
}
const result = getPath(this.data, path2);
if (!result && !ns && !key && lng.indexOf(".") > -1) {
lng = path2[0];
ns = path2[1];
key = path2.slice(2).join(".");
}
if (result || !ignoreJSONStructure || !isString$1(key)) return result;
return deepFind((_b = (_a = this.data) == null ? void 0 : _a[lng]) == null ? void 0 : _b[ns], key, keySeparator);
}
addResource(lng, ns, key, value) {
let options = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : {
silent: false
};
const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
let path2 = [lng, ns];
if (key) path2 = path2.concat(keySeparator ? key.split(keySeparator) : key);
if (lng.indexOf(".") > -1) {
path2 = lng.split(".");
value = ns;
ns = path2[1];
}
this.addNamespaces(ns);
setPath(this.data, path2, value);
if (!options.silent) this.emit("added", lng, ns, key, value);
}
addResources(lng, ns, resources2) {
let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {
silent: false
};
for (const m in resources2) {
if (isString$1(resources2[m]) || Array.isArray(resources2[m])) this.addResource(lng, ns, m, resources2[m], {
silent: true
});
}
if (!options.silent) this.emit("added", lng, ns, resources2);
}
addResourceBundle(lng, ns, resources2, deep, overwrite) {
let options = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : {
silent: false,
skipCopy: false
};
let path2 = [lng, ns];
if (lng.indexOf(".") > -1) {
path2 = lng.split(".");
deep = resources2;
resources2 = ns;
ns = path2[1];
}
this.addNamespaces(ns);
let pack = getPath(this.data, path2) || {};
if (!options.skipCopy) resources2 = JSON.parse(JSON.stringify(resources2));
if (deep) {
deepExtend(pack, resources2, overwrite);
} else {
pack = __spreadValues(__spreadValues({}, pack), resources2);
}
setPath(this.data, path2, pack);
if (!options.silent) this.emit("added", lng, ns, resources2);
}
removeResourceBundle(lng, ns) {
if (this.hasResourceBundle(lng, ns)) {
delete this.data[lng][ns];
}
this.removeNamespaces(ns);
this.emit("removed", lng, ns);
}
hasResourceBundle(lng, ns) {
return this.getResource(lng, ns) !== void 0;
}
getResourceBundle(lng, ns) {
if (!ns) ns = this.options.defaultNS;
return this.getResource(lng, ns);
}
getDataByLanguage(lng) {
return this.data[lng];
}
hasLanguageSomeTranslations(lng) {
const data = this.getDataByLanguage(lng);
const n = data && Object.keys(data) || [];
return !!n.find((v) => data[v] && Object.keys(data[v]).length > 0);
}
toJSON() {
return this.data;
}
}
var postProcessor = {
processors: {},
addPostProcessor(module2) {
this.processors[module2.name] = module2;
},
handle(processors, value, key, options, translator) {
processors.forEach((processor) => {
var _a, _b;
value = (_b = (_a = this.processors[processor]) == null ? void 0 : _a.process(value, key, options, translator)) != null ? _b : value;
});
return value;
}
};
const checkedLoadedFor = {};
const shouldHandleAsObject = (res) => !isString$1(res) && typeof res !== "boolean" && typeof res !== "number";
class Translator extends EventEmitter {
constructor(services) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
super();
copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, this);
this.options = options;
if (this.options.keySeparator === void 0) {
this.options.keySeparator = ".";
}
this.logger = baseLogger.create("translator");
}
changeLanguage(lng) {
if (lng) this.language = lng;
}
exists(key) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
interpolation: {}
};
if (key == null) {
return false;
}
const resolved = this.resolve(key, options);
return (resolved == null ? void 0 : resolved.res) !== void 0;
}
extractFromKey(key, options) {
let nsSeparator = options.nsSeparator !== void 0 ? options.nsSeparator : this.options.nsSeparator;
if (nsSeparator === void 0) nsSeparator = ":";
const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
let namespaces = options.ns || this.options.defaultNS || [];
const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
const m = key.match(this.interpolator.nestingRegexp);
if (m && m.length > 0) {
return {
key,
namespaces: isString$1(namespaces) ? [namespaces] : namespaces
};
}
const parts = key.split(nsSeparator);
if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
key = parts.join(keySeparator);
}
return {
key,
namespaces: isString$1(namespaces) ? [namespaces] : namespaces
};
}
translate(keys, options, lastKey) {
if (typeof options !== "object" && this.options.overloadTranslationOptionHandler) {
options = this.options.overloadTranslationOptionHandler(arguments);
}
if (typeof options === "object") options = __spreadValues({}, options);
if (!options) options = {};
if (keys == null) return "";
if (!Array.isArray(keys)) keys = [String(keys)];
const returnDetails = options.returnDetails !== void 0 ? options.returnDetails : this.options.returnDetails;
const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
const {
key,
namespaces
} = this.extractFromKey(keys[keys.length - 1], options);
const namespace = namespaces[namespaces.length - 1];
const lng = options.lng || this.language;
const appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
if ((lng == null ? void 0 : lng.toLowerCase()) === "cimode") {
if (appendNamespaceToCIMode) {
const nsSeparator = options.nsSeparator || this.options.nsSeparator;
if (returnDetails) {
return {
res: `${namespace}${nsSeparator}${key}`,
usedKey: key,
exactUsedKey: key,
usedLng: lng,
usedNS: namespace,
usedParams: this.getUsedParamsDetails(options)
};
}
return `${namespace}${nsSeparator}${key}`;
}
if (returnDetails) {
return {
res: key,
usedKey: key,
exactUsedKey: key,
usedLng: lng,
usedNS: namespace,
usedParams: this.getUsedParamsDetails(options)
};
}
return key;
}
const resolved = this.resolve(keys, options);
let res = resolved == null ? void 0 : resolved.res;
const resUsedKey = (resolved == null ? void 0 : resolved.usedKey) || key;
const resExactUsedKey = (resolved == null ? void 0 : resolved.exactUsedKey) || key;
const noObject = ["[object Number]", "[object Function]", "[object RegExp]"];
const joinArrays = options.joinArrays !== void 0 ? options.joinArrays : this.options.joinArrays;
const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
const needsPluralHandling = options.count !== void 0 && !isString$1(options.count);
const hasDefaultValue = Translator.hasDefaultValue(options);
const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : "";
const defaultValueSuffixOrdinalFallback = options.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, {
ordinal: false
}) : "";
const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0;
const defaultValue = needsZeroSuffixLookup && options[`defaultValue${this.options.pluralSeparator}zero`] || options[`defaultValue${defaultValueSuffix}`] || options[`defaultValue${defaultValueSuffixOrdinalFallback}`] || options.defaultValue;
let resForObjHndl = res;
if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
resForObjHndl = defaultValue;
}
const handleAsObject = shouldHandleAsObject(resForObjHndl);
const resType = Object.prototype.toString.apply(resForObjHndl);
if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString$1(joinArrays) && Array.isArray(resForObjHndl))) {
if (!options.returnObjects && !this.options.returnObjects) {
if (!this.options.returnedObjectHandler) {
this.logger.warn("accessing an object - but returnObjects options is not enabled!");
}
const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, __spreadProps(__spreadValues({}, options), {
ns: namespaces
})) : `key '${key} (${this.language})' returned an object instead of string.`;
if (returnDetails) {
resolved.res = r;
resolved.usedParams = this.getUsedParamsDetails(options);
return resolved;
}
return r;
}
if (keySeparator) {
const resTypeIsArray = Array.isArray(resForObjHndl);
const copy2 = resTypeIsArray ? [] : {};
const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
for (const m in resForObjHndl) {
if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
const deepKey = `${newKeyToUse}${keySeparator}${m}`;
if (hasDefaultValue && !res) {
copy2[m] = this.translate(deepKey, __spreadValues(__spreadProps(__spreadValues({}, options), {
defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : void 0
}), {
joinArrays: false,
ns: namespaces
}));
} else {
copy2[m] = this.translate(deepKey, __spreadValues(__spreadValues({}, options), {
joinArrays: false,
ns: namespaces
}));
}
if (copy2[m] === deepKey) copy2[m] = resForObjHndl[m];
}
}
res = copy2;
}
} else if (handleAsObjectInI18nFormat && isString$1(joinArrays) && Array.isArray(res)) {
res = res.join(joinArrays);
if (res) res = this.extendTranslation(res, keys, options, lastKey);
} else {
let usedDefault = false;
let usedKey = false;
if (!this.isValidLookup(res) && hasDefaultValue) {
usedDefault = true;
res = defaultValue;
}
if (!this.isValidLookup(res)) {
usedKey = true;
res = key;
}
const missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? void 0 : res;
const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
if (usedKey || usedDefault || updateMissing) {
this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue : res);
if (keySeparator) {
const fk = this.resolve(key, __spreadProps(__spreadValues({}, options), {
keySeparator: false
}));
if (fk && fk.res) this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.");
}
let lngs = [];
const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) {
for (let i = 0; i < fallbackLngs.length; i++) {
lngs.push(fallbackLngs[i]);
}
} else if (this.options.saveMissingTo === "all") {
lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
} else {
lngs.push(options.lng || this.language);
}
const send = (l, k, specificDefaultValue) => {
var _a;
const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
if (this.options.missingKeyHandler) {
this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);
} else if ((_a = this.backendConnector) == null ? void 0 : _a.saveMissing) {
this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);
}
this.emit("missingKey", l, namespace, k, res);
};
if (this.options.saveMissing) {
if (this.options.saveMissingPlurals && needsPluralHandling) {
lngs.forEach((language2) => {
const suffixes = this.pluralResolver.getSuffixes(language2, options);
if (needsZeroSuffixLookup && options[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
suffixes.push(`${this.options.pluralSeparator}zero`);
}
suffixes.forEach((suffix) => {
send([language2], key + suffix, options[`defaultValue${suffix}`] || defaultValue);
});
});
} else {
send(lngs, key, defaultValue);
}
}
}
res = this.extendTranslation(res, keys, options, resolved, lastKey);
if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = `${namespace}:${key}`;
if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}:${key}` : key, usedDefault ? res : void 0);
}
}
if (returnDetails) {
resolved.res = res;
resolved.usedParams = this.getUsedParamsDetails(options);
return resolved;
}
return res;
}
extendTranslation(res, key, options, resolved, lastKey) {
var _a, _b;
var _this = this;
if ((_a = this.i18nFormat) == null ? void 0 : _a.parse) {
res = this.i18nFormat.parse(res, __spreadValues(__spreadValues({}, this.options.interpolation.defaultVariables), options), options.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
resolved
});
} else if (!options.skipInterpolation) {
if (options.interpolation) this.interpolator.init(__spreadValues(__spreadValues({}, options), {
interpolation: __spreadValues(__spreadValues({}, this.options.interpolation), options.interpolation)
}));
const skipOnVariables = isString$1(res) && (((_b = options == null ? void 0 : options.interpolation) == null ? void 0 : _b.skipOnVariables) !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
let nestBef;
if (skipOnVariables) {
const nb = res.match(this.interpolator.nestingRegexp);
nestBef = nb && nb.length;
}
let data = options.replace && !isString$1(options.replace) ? options.replace : options;
if (this.options.interpolation.defaultVariables) data = __spreadValues(__spreadValues({}, this.options.interpolation.defaultVariables), data);
res = this.interpolator.interpolate(res, data, options.lng || this.language || resolved.usedLng, options);
if (skipOnVariables) {
const na = res.match(this.interpolator.nestingRegexp);
const nestAft = na && na.length;
if (nestBef < nestAft) options.nest = false;
}
if (!options.lng && resolved && resolved.res) options.lng = this.language || resolved.usedLng;
if (options.nest !== false) res = this.interpolator.nest(res, function() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if ((lastKey == null ? void 0 : lastKey[0]) === args[0] && !options.context) {
_this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
return null;
}
return _this.translate(...args, key);
}, options);
if (options.interpolation) this.interpolator.reset();
}
const postProcess = options.postProcess || this.options.postProcess;
const postProcessorNames = isString$1(postProcess) ? [postProcess] : postProcess;
if (res != null && (postProcessorNames == null ? void 0 : postProcessorNames.length) && options.applyPostProcessor !== false) {
res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? __spreadValues({
i18nResolved: __spreadProps(__spreadValues({}, resolved), {
usedParams: this.getUsedParamsDetails(options)
})
}, options) : options, this);
}
return res;
}
resolve(keys) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
let found;
let usedKey;
let exactUsedKey;
let usedLng;
let usedNS;
if (isString$1(keys)) keys = [keys];
keys.forEach((k) => {
if (this.isValidLookup(found)) return;
const extracted = this.extractFromKey(k, options);
const key = extracted.key;
usedKey = key;
let namespaces = extracted.namespaces;
if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
const needsPluralHandling = options.count !== void 0 && !isString$1(options.count);
const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0;
const needsContextHandling = options.context !== void 0 && (isString$1(options.context) || typeof options.context === "number") && options.context !== "";
const codes = options.lngs ? options.lngs : this.languageUtils.toResolveHierarchy(options.lng || this.language, options.fallbackLng);
namespaces.forEach((ns) => {
var _a, _b;
if (this.isValidLookup(found)) return;
usedNS = ns;
if (!checkedLoadedFor[`${codes[0]}-${ns}`] && ((_a = this.utils) == null ? void 0 : _a.hasLoadedNamespace) && !((_b = this.utils) == null ? void 0 : _b.hasLoadedNamespace(usedNS))) {
checkedLoadedFor[`${codes[0]}-${ns}`] = true;
this.logger.warn(`key "${usedKey}" for languages "${codes.join(", ")}" won't get resolved as namespace "${usedNS}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
}
codes.forEach((code) => {
var _a2;
if (this.isValidLookup(found)) return;
usedLng = code;
const finalKeys = [key];
if ((_a2 = this.i18nFormat) == null ? void 0 : _a2.addLookupKeys) {
this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
} else {
let pluralSuffix;
if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, options.count, options);
const zeroSuffix = `${this.options.pluralSeparator}zero`;
const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
if (needsPluralHandling) {
finalKeys.push(key + pluralSuffix);
if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
}
if (needsZeroSuffixLookup) {
finalKeys.push(key + zeroSuffix);
}
}
if (needsContextHandling) {
const contextKey = `${key}${this.options.contextSeparator}${options.context}`;
finalKeys.push(contextKey);
if (needsPluralHandling) {
finalKeys.push(contextKey + pluralSuffix);
if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
}
if (needsZeroSuffixLookup) {
finalKeys.push(contextKey + zeroSuffix);
}
}
}
}
let possibleKey;
while (possibleKey = finalKeys.pop()) {
if (!this.isValidLookup(found)) {
exactUsedKey = possibleKey;
found = this.getResource(code, ns, possibleKey, options);
}
}
});
});
});
return {
res: found,
usedKey,
exactUsedKey,
usedLng,
usedNS
};
}
isValidLookup(res) {
return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
}
getResource(code, ns, key) {
var _a;
let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
if ((_a = this.i18nFormat) == null ? void 0 : _a.getResource) return this.i18nFormat.getResource(code, ns, key, options);
return this.resourceStore.getResource(code, ns, key, options);
}
getUsedParamsDetails() {
let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
const optionsKeys = ["defaultValue", "ordinal", "context", "replace", "lng", "lngs", "fallbackLng", "ns", "keySeparator", "nsSeparator", "returnObjects", "returnDetails", "joinArrays", "postProcess", "interpolation"];
const useOptionsReplaceForData = options.replace && !isString$1(options.replace);
let data = useOptionsReplaceForData ? options.replace : options;
if (useOptionsReplaceForData && typeof options.count !== "undefined") {
data.count = options.count;
}
if (this.options.interpolation.defaultVariables) {
data = __spreadValues(__spreadValues({}, this.options.interpolation.defaultVariables), data);
}
if (!useOptionsReplaceForData) {
data = __spreadValues({}, data);
for (const key of optionsKeys) {
delete data[key];
}
}
return data;
}
static hasDefaultValue(options) {
const prefix = "defaultValue";
for (const option in options) {
if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && void 0 !== options[option]) {
return true;
}
}
return false;
}
}
class LanguageUtil {
constructor(options) {
this.options = options;
this.supportedLngs = this.options.supportedLngs || false;
this.logger = baseLogger.create("languageUtils");
}
getScriptPartFromCode(code) {
code = getCleanedCode(code);
if (!code || code.indexOf("-") < 0) return null;
const p = code.split("-");
if (p.length === 2) return null;
p.pop();
if (p[p.length - 1].toLowerCase() === "x") return null;
return this.formatLanguageCode(p.join("-"));
}
getLanguagePartFromCode(code) {
code = getCleanedCode(code);
if (!code || code.indexOf("-") < 0) return code;
const p = code.split("-");
return this.formatLanguageCode(p[0]);
}
formatLanguageCode(code) {
if (isString$1(code) && code.indexOf("-") > -1) {
let formattedCode;
try {
formattedCode = Intl.getCanonicalLocales(code)[0];
} catch (e) {
}
if (formattedCode && this.options.lowerCaseLng) {
formattedCode = formattedCode.toLowerCase();
}
if (formattedCode) return formattedCode;
if (this.options.lowerCaseLng) {
return code.toLowerCase();
}
return code;
}
return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
}
isSupportedCode(code) {
if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) {
code = this.getLanguagePartFromCode(code);
}
return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
}
getBestMatchFromCodes(codes) {
if (!codes) return null;
let found;
codes.forEach((code) => {
if (found) return;
const cleanedLng = this.formatLanguageCode(code);
if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
});
if (!found && this.options.supportedLngs) {
codes.forEach((code) => {
if (found) return;
const lngOnly = this.getLanguagePartFromCode(code);
if (this.isSupportedCode(lngOnly)) return found = lngOnly;
found = this.options.supportedLngs.find((supportedLng) => {
if (supportedLng === lngOnly) return supportedLng;
if (supportedLng.indexOf("-") < 0 && lngOnly.indexOf("-") < 0) return;
if (supportedLng.indexOf("-") > 0 && lngOnly.indexOf("-") < 0 && supportedLng.substring(0, supportedLng.indexOf("-")) === lngOnly) return supportedLng;
if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
});
});
}
if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
return found;
}
getFallbackCodes(fallbacks, code) {
if (!fallbacks) return [];
if (typeof fallbacks === "function") fallbacks = fallbacks(code);
if (isString$1(fallbacks)) fallbacks = [fallbacks];
if (Array.isArray(fallbacks)) return fallbacks;
if (!code) return fallbacks.default || [];
let found = fallbacks[code];
if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
if (!found) found = fallbacks[this.formatLanguageCode(code)];
if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
if (!found) found = fallbacks.default;
return found || [];
}
toResolveHierarchy(code, fallbackCode) {
const fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
const codes = [];
const addCode = (c) => {
if (!c) return;
if (this.isSupportedCode(c)) {
codes.push(c);
} else {
this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
}
};
if (isString$1(code) && (code.indexOf("-") > -1 || code.indexOf("_") > -1)) {
if (this.options.load !== "languageOnly") addCode(this.formatLanguageCode(code));
if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly") addCode(this.getScriptPartFromCode(code));
if (this.options.load !== "currentOnly") addCode(this.getLanguagePartFromCode(code));
} else if (isString$1(code)) {
addCode(this.formatLanguageCode(code));
}
fallbackCodes.forEach((fc) => {
if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
});
return codes;
}
}
const suffixesOrder = {
zero: 0,
one: 1,
two: 2,
few: 3,
many: 4,
other: 5
};
const dummyRule = {
select: (count) => count === 1 ? "one" : "other",
resolvedOptions: () => ({
pluralCategories: ["one", "other"]
})
};
class PluralResolver {
constructor(languageUtils) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
this.languageUtils = languageUtils;
this.options = options;
this.logger = baseLogger.create("pluralResolver");
this.pluralRulesCache = {};
}
addRule(lng, obj) {
this.rules[lng] = obj;
}
clearCache() {
this.pluralRulesCache = {};
}
getRule(code) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
const cleanedCode = getCleanedCode(code === "dev" ? "en" : code);
const type = options.ordinal ? "ordinal" : "cardinal";
const cacheKey = JSON.stringify({
cleanedCode,
type
});
if (cacheKey in this.pluralRulesCache) {
return this.pluralRulesCache[cacheKey];
}
let rule;
try {
rule = new Intl.PluralRules(cleanedCode, {
type
});
} catch (err) {
if (!Intl) {
this.logger.error("No Intl support, please use an Intl polyfill!");
return dummyRule;
}
if (!code.match(/-|_/)) return dummyRule;
const lngPart = this.languageUtils.getLanguagePartFromCode(code);
rule = this.getRule(lngPart, options);
}
this.pluralRulesCache[cacheKey] = rule;
return rule;
}
needsPlural(code) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
let rule = this.getRule(code, options);
if (!rule) rule = this.getRule("dev", options);
return (rule == null ? void 0 : rule.resolvedOptions().pluralCategories.length) > 1;
}
getPluralFormsOfKey(code, key) {
let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`);
}
getSuffixes(code) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
let rule = this.getRule(code, options);
if (!rule) rule = this.getRule("dev", options);
if (!rule) return [];
return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`);
}
getSuffix(code, count) {
let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
const rule = this.getRule(code, options);
if (rule) {
return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`;
}
this.logger.warn(`no plural rule found for: ${code}`);
return this.getSuffix("dev", count, options);
}
}
const deepFindWithDefaults = function(data, defaultData, key) {
let keySeparator = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : ".";
let ignoreJSONStructure = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true;
let path2 = getPathWithDefaults(data, defaultData, key);
if (!path2 && ignoreJSONStructure && isString$1(key)) {
path2 = deepFind(data, key, keySeparator);
if (path2 === void 0) path2 = deepFind(defaultData, key, keySeparator);
}
return path2;
};
const regexSafe = (val) => val.replace(/\$/g, "$$$$");
class Interpolator {
constructor() {
var _a;
let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
this.logger = baseLogger.create("interpolator");
this.options = options;
this.format = ((_a = options == null ? void 0 : options.interpolation) == null ? void 0 : _a.format) || ((value) => value);
this.init(options);
}
init() {
let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
if (!options.interpolation) options.interpolation = {
escapeValue: true
};
const {
escape: escape$1,
escapeValue,
useRawValueToEscape,
prefix,
prefixEscaped,
suffix,
suffixEscaped,
formatSeparator,
unescapeSuffix,
unescapePrefix,
nestingPrefix,
nestingPrefixEscaped,
nestingSuffix,
nestingSuffixEscaped,
nestingOptionsSeparator,
maxReplaces,
alwaysFormat
} = options.interpolation;
this.escape = escape$1 !== void 0 ? escape$1 : escape;
this.escapeValue = escapeValue !== void 0 ? escapeValue : true;
this.useRawValueToEscape = useRawValueToEscape !== void 0 ? useRawValueToEscape : false;
this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{";
this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}";
this.formatSeparator = formatSeparator || ",";
this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix || "-";
this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix || "";
this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t(");
this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")");
this.nestingOptionsSeparator = nestingOptionsSeparator || ",";
this.maxReplaces = maxReplaces || 1e3;
this.alwaysFormat = alwaysFormat !== void 0 ? alwaysFormat : false;
this.resetRegExp();
}
reset() {
if (this.options) this.init(this.options);
}
resetRegExp() {
const getOrResetRegExp = (existingRegExp, pattern) => {
if ((existingRegExp == null ? void 0 : existingRegExp.source) === pattern) {
existingRegExp.lastIndex = 0;
return existingRegExp;
}
return new RegExp(pattern, "g");
};
this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}(.+?)${this.nestingSuffix}`);
}
interpolate(str, data, lng, options) {
var _a;
let match;
let value;
let replaces;
const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
const handleFormat = (key) => {
if (key.indexOf(this.formatSeparator) < 0) {
const path2 = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
return this.alwaysFormat ? this.format(path2, void 0, lng, __spreadProps(__spreadValues(__spreadValues({}, options), data), {
interpolationkey: key
})) : path2;
}
const p = key.split(this.formatSeparator);
const k = p.shift().trim();
const f = p.join(this.formatSeparator).trim();
return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, __spreadProps(__spreadValues(__spreadValues({}, options), data), {
interpolationkey: k
}));
};
this.resetRegExp();
const missingInterpolationHandler = (options == null ? void 0 : options.missingInterpolationHandler) || this.options.missingInterpolationHandler;
const skipOnVariables = ((_a = options == null ? void 0 : options.interpolation) == null ? void 0 : _a.skipOnVariables) !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
const todos = [{
regex: this.regexpUnescape,
safeValue: (val) => regexSafe(val)
}, {
regex: this.regexp,
safeValue: (val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
}];
todos.forEach((todo) => {
replaces = 0;
while (match = todo.regex.exec(str)) {
const matchedVar = match[1].trim();