@localazy/strapi-plugin
Version:
The official Strapi Plugin by Localazy.
5,303 lines • 171 kB
JavaScript
import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import { useNavigate, useLocation, NavLink, Routes, Route } from "react-router-dom";
import { u as useTranslation, F as ForwardRef$2H, a as ForwardRef$d, b as ForwardRef$3P, c as Flex, L as Loader, g as getDefaultExportFromCjs, B as Button, d as Box, T as Typography, e as Link, S as SubNav, f as SubNavHeader, h as SubNavSections, i as SubNavSection, j as SubNavLink, k as ForwardRef$L, G as Grid, D as Divider, P as PluginSettingsService, l as darkTheme, m as lightTheme, A as Alert, n as cloneDeep, s as set, o as DesignSystemProvider } from "./set-Dnhh_SyE.mjs";
import { useState, useEffect } from "react";
import { P as PLUGIN_ID, c as createStrapiApiAxiosInstance, u as useLocalazyIdentity, L as LocalazyUserService, e as emptyIdentity } from "./index-Dj68Ixl2.mjs";
import { P as ProjectService, L as LanguagesSelector } from "./LanguagesSelector-CeB7tVcb.mjs";
import { Layouts, Page } from "@strapi/strapi/admin";
import { h as hasModelChanged } from "./has-model-changed-DViUIQHk.mjs";
var PLUGIN_ROUTES = /* @__PURE__ */ ((PLUGIN_ROUTES2) => {
PLUGIN_ROUTES2["ROOT"] = "";
PLUGIN_ROUTES2["LOGIN"] = "login";
PLUGIN_ROUTES2["UPLOAD"] = "upload";
PLUGIN_ROUTES2["DOWNLOAD"] = "download";
PLUGIN_ROUTES2["OVERVIEW"] = "overview";
PLUGIN_ROUTES2["CONTENT_TRANSFER_SETUP"] = "content-transfer-setup";
PLUGIN_ROUTES2["GLOBAL_SETTINGS"] = "global-settings";
return PLUGIN_ROUTES2;
})(PLUGIN_ROUTES || {});
const useRedirectToPluginRoute = () => {
const navigate = useNavigate();
const navigateToPluginRoute = (route) => {
if ([
"content-transfer-setup",
"global-settings"
/* GLOBAL_SETTINGS */
].includes(route)) {
navigate(`/settings/${PLUGIN_ID}/${route}`);
return;
}
navigate(`/plugins/${PLUGIN_ID}/${route}`);
};
return {
navigateToPluginRoute
};
};
const useNav = () => {
const { t: t2 } = useTranslation();
return [
{
id: "overview",
label: t2("common.overview"),
description: t2("overview.description"),
icon: /* @__PURE__ */ jsx(ForwardRef$2H, {}),
to: `/plugins/${PLUGIN_ID}/overview`,
active: false
},
{
id: "upload",
label: t2("common.upload_to_localazy"),
description: t2("upload.description"),
icon: /* @__PURE__ */ jsx(ForwardRef$d, {}),
to: `/plugins/${PLUGIN_ID}/upload`,
active: false
},
{
id: "download",
label: t2("common.download_to_strapi"),
description: t2("download.description"),
icon: /* @__PURE__ */ jsx(ForwardRef$3P, {}),
to: `/plugins/${PLUGIN_ID}/download`,
active: false
}
];
};
const useHeaderTitle = () => {
const { t: t2 } = useTranslation();
const location2 = useLocation();
const navigation = useNav();
const pluginSegment = location2?.pathname.split(`/${PLUGIN_ID}/`)[1];
if (!pluginSegment) {
return t2("common.localazy_plugin_hand");
}
const currentNavItem = navigation.find((navItem) => pluginSegment.includes(navItem.id));
return currentNavItem?.label || t2("common.localazy_plugin_hand");
};
const useHeaderSubtitle = () => {
const location2 = useLocation();
const navigation = useNav();
const pluginSegment = location2?.pathname.split(`/${PLUGIN_ID}/`)[1];
if (!pluginSegment) {
return "";
}
const currentNavItem = navigation.find((navItem) => pluginSegment.includes(navItem.id));
return currentNavItem?.description || "";
};
function PluginPageLoader() {
const { t: t2 } = useTranslation();
return /* @__PURE__ */ jsx(Flex, { marginTop: 10, alignItems: "center", justifyContent: "center", children: /* @__PURE__ */ jsx(Loader, { children: t2("common.loading_content") }) });
}
var propTypes = { exports: {} };
var reactIs = { exports: {} };
var reactIs_production_min = {};
/** @license React v16.13.1
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var hasRequiredReactIs_production_min;
function requireReactIs_production_min() {
if (hasRequiredReactIs_production_min) return reactIs_production_min;
hasRequiredReactIs_production_min = 1;
var b = "function" === typeof Symbol && Symbol.for, c2 = b ? Symbol.for("react.element") : 60103, d = b ? Symbol.for("react.portal") : 60106, e2 = b ? Symbol.for("react.fragment") : 60107, f = b ? Symbol.for("react.strict_mode") : 60108, g = b ? Symbol.for("react.profiler") : 60114, h = b ? Symbol.for("react.provider") : 60109, k = b ? Symbol.for("react.context") : 60110, l2 = b ? Symbol.for("react.async_mode") : 60111, m = b ? Symbol.for("react.concurrent_mode") : 60111, n2 = b ? Symbol.for("react.forward_ref") : 60112, p = b ? Symbol.for("react.suspense") : 60113, q = b ? Symbol.for("react.suspense_list") : 60120, r2 = b ? Symbol.for("react.memo") : 60115, t2 = b ? Symbol.for("react.lazy") : 60116, v = b ? Symbol.for("react.block") : 60121, w = b ? Symbol.for("react.fundamental") : 60117, x = b ? Symbol.for("react.responder") : 60118, y = b ? Symbol.for("react.scope") : 60119;
function z(a2) {
if ("object" === typeof a2 && null !== a2) {
var u = a2.$$typeof;
switch (u) {
case c2:
switch (a2 = a2.type, a2) {
case l2:
case m:
case e2:
case g:
case f:
case p:
return a2;
default:
switch (a2 = a2 && a2.$$typeof, a2) {
case k:
case n2:
case t2:
case r2:
case h:
return a2;
default:
return u;
}
}
case d:
return u;
}
}
}
function A(a2) {
return z(a2) === m;
}
reactIs_production_min.AsyncMode = l2;
reactIs_production_min.ConcurrentMode = m;
reactIs_production_min.ContextConsumer = k;
reactIs_production_min.ContextProvider = h;
reactIs_production_min.Element = c2;
reactIs_production_min.ForwardRef = n2;
reactIs_production_min.Fragment = e2;
reactIs_production_min.Lazy = t2;
reactIs_production_min.Memo = r2;
reactIs_production_min.Portal = d;
reactIs_production_min.Profiler = g;
reactIs_production_min.StrictMode = f;
reactIs_production_min.Suspense = p;
reactIs_production_min.isAsyncMode = function(a2) {
return A(a2) || z(a2) === l2;
};
reactIs_production_min.isConcurrentMode = A;
reactIs_production_min.isContextConsumer = function(a2) {
return z(a2) === k;
};
reactIs_production_min.isContextProvider = function(a2) {
return z(a2) === h;
};
reactIs_production_min.isElement = function(a2) {
return "object" === typeof a2 && null !== a2 && a2.$$typeof === c2;
};
reactIs_production_min.isForwardRef = function(a2) {
return z(a2) === n2;
};
reactIs_production_min.isFragment = function(a2) {
return z(a2) === e2;
};
reactIs_production_min.isLazy = function(a2) {
return z(a2) === t2;
};
reactIs_production_min.isMemo = function(a2) {
return z(a2) === r2;
};
reactIs_production_min.isPortal = function(a2) {
return z(a2) === d;
};
reactIs_production_min.isProfiler = function(a2) {
return z(a2) === g;
};
reactIs_production_min.isStrictMode = function(a2) {
return z(a2) === f;
};
reactIs_production_min.isSuspense = function(a2) {
return z(a2) === p;
};
reactIs_production_min.isValidElementType = function(a2) {
return "string" === typeof a2 || "function" === typeof a2 || a2 === e2 || a2 === m || a2 === g || a2 === f || a2 === p || a2 === q || "object" === typeof a2 && null !== a2 && (a2.$$typeof === t2 || a2.$$typeof === r2 || a2.$$typeof === h || a2.$$typeof === k || a2.$$typeof === n2 || a2.$$typeof === w || a2.$$typeof === x || a2.$$typeof === y || a2.$$typeof === v);
};
reactIs_production_min.typeOf = z;
return reactIs_production_min;
}
var reactIs_development = {};
/** @license React v16.13.1
* react-is.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var hasRequiredReactIs_development;
function requireReactIs_development() {
if (hasRequiredReactIs_development) return reactIs_development;
hasRequiredReactIs_development = 1;
if (process.env.NODE_ENV !== "production") {
(function() {
var hasSymbol = typeof Symbol === "function" && Symbol.for;
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for("react.element") : 60103;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for("react.portal") : 60106;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for("react.fragment") : 60107;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for("react.strict_mode") : 60108;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for("react.profiler") : 60114;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for("react.provider") : 60109;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 60110;
var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for("react.async_mode") : 60111;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for("react.concurrent_mode") : 60111;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for("react.forward_ref") : 60112;
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for("react.suspense") : 60113;
var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for("react.suspense_list") : 60120;
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for("react.memo") : 60115;
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116;
var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for("react.block") : 60121;
var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for("react.fundamental") : 60117;
var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for("react.responder") : 60118;
var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for("react.scope") : 60119;
function isValidElementType(type) {
return typeof type === "string" || typeof type === "function" || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === "object" && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
}
function typeOf(object) {
if (typeof object === "object" && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_ASYNC_MODE_TYPE:
case REACT_CONCURRENT_MODE_TYPE:
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return void 0;
}
var AsyncMode = REACT_ASYNC_MODE_TYPE;
var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment2 = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false;
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true;
console["warn"]("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API.");
}
}
return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
}
function isConcurrentMode(object) {
return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement(object) {
return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
return typeOf(object) === REACT_LAZY_TYPE;
}
function isMemo(object) {
return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
}
reactIs_development.AsyncMode = AsyncMode;
reactIs_development.ConcurrentMode = ConcurrentMode;
reactIs_development.ContextConsumer = ContextConsumer;
reactIs_development.ContextProvider = ContextProvider;
reactIs_development.Element = Element;
reactIs_development.ForwardRef = ForwardRef;
reactIs_development.Fragment = Fragment2;
reactIs_development.Lazy = Lazy;
reactIs_development.Memo = Memo;
reactIs_development.Portal = Portal;
reactIs_development.Profiler = Profiler;
reactIs_development.StrictMode = StrictMode;
reactIs_development.Suspense = Suspense;
reactIs_development.isAsyncMode = isAsyncMode;
reactIs_development.isConcurrentMode = isConcurrentMode;
reactIs_development.isContextConsumer = isContextConsumer;
reactIs_development.isContextProvider = isContextProvider;
reactIs_development.isElement = isElement;
reactIs_development.isForwardRef = isForwardRef;
reactIs_development.isFragment = isFragment;
reactIs_development.isLazy = isLazy;
reactIs_development.isMemo = isMemo;
reactIs_development.isPortal = isPortal;
reactIs_development.isProfiler = isProfiler;
reactIs_development.isStrictMode = isStrictMode;
reactIs_development.isSuspense = isSuspense;
reactIs_development.isValidElementType = isValidElementType;
reactIs_development.typeOf = typeOf;
})();
}
return reactIs_development;
}
var hasRequiredReactIs;
function requireReactIs() {
if (hasRequiredReactIs) return reactIs.exports;
hasRequiredReactIs = 1;
if (process.env.NODE_ENV === "production") {
reactIs.exports = requireReactIs_production_min();
} else {
reactIs.exports = requireReactIs_development();
}
return reactIs.exports;
}
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
var objectAssign;
var hasRequiredObjectAssign;
function requireObjectAssign() {
if (hasRequiredObjectAssign) return objectAssign;
hasRequiredObjectAssign = 1;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === void 0) {
throw new TypeError("Object.assign cannot be called with null or undefined");
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
var test1 = new String("abc");
test1[5] = "de";
if (Object.getOwnPropertyNames(test1)[0] === "5") {
return false;
}
var test2 = {};
for (var i2 = 0; i2 < 10; i2++) {
test2["_" + String.fromCharCode(i2)] = i2;
}
var order2 = Object.getOwnPropertyNames(test2).map(function(n2) {
return test2[n2];
});
if (order2.join("") !== "0123456789") {
return false;
}
var test3 = {};
"abcdefghijklmnopqrst".split("").forEach(function(letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") {
return false;
}
return true;
} catch (err) {
return false;
}
}
objectAssign = shouldUseNative() ? Object.assign : function(target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s2 = 1; s2 < arguments.length; s2++) {
from = Object(arguments[s2]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i2 = 0; i2 < symbols.length; i2++) {
if (propIsEnumerable.call(from, symbols[i2])) {
to[symbols[i2]] = from[symbols[i2]];
}
}
}
}
return to;
};
return objectAssign;
}
var ReactPropTypesSecret_1;
var hasRequiredReactPropTypesSecret;
function requireReactPropTypesSecret() {
if (hasRequiredReactPropTypesSecret) return ReactPropTypesSecret_1;
hasRequiredReactPropTypesSecret = 1;
var ReactPropTypesSecret = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";
ReactPropTypesSecret_1 = ReactPropTypesSecret;
return ReactPropTypesSecret_1;
}
var has;
var hasRequiredHas;
function requireHas() {
if (hasRequiredHas) return has;
hasRequiredHas = 1;
has = Function.call.bind(Object.prototype.hasOwnProperty);
return has;
}
var checkPropTypes_1;
var hasRequiredCheckPropTypes;
function requireCheckPropTypes() {
if (hasRequiredCheckPropTypes) return checkPropTypes_1;
hasRequiredCheckPropTypes = 1;
var printWarning = function() {
};
if (process.env.NODE_ENV !== "production") {
var ReactPropTypesSecret = requireReactPropTypesSecret();
var loggedTypeFailures = {};
var has2 = requireHas();
printWarning = function(text) {
var message = "Warning: " + text;
if (typeof console !== "undefined") {
console.error(message);
}
try {
throw new Error(message);
} catch (x) {
}
};
}
function checkPropTypes(typeSpecs, values, location2, componentName, getStack) {
if (process.env.NODE_ENV !== "production") {
for (var typeSpecName in typeSpecs) {
if (has2(typeSpecs, typeSpecName)) {
var error;
try {
if (typeof typeSpecs[typeSpecName] !== "function") {
var err = Error(
(componentName || "React class") + ": " + location2 + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."
);
err.name = "Invariant Violation";
throw err;
}
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location2, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
if (error && !(error instanceof Error)) {
printWarning(
(componentName || "React class") + ": type specification of " + location2 + " `" + typeSpecName + "` is invalid; the type checker function must return `null` or an `Error` but returned a " + typeof error + ". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."
);
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : "";
printWarning(
"Failed " + location2 + " type: " + error.message + (stack != null ? stack : "")
);
}
}
}
}
}
checkPropTypes.resetWarningCache = function() {
if (process.env.NODE_ENV !== "production") {
loggedTypeFailures = {};
}
};
checkPropTypes_1 = checkPropTypes;
return checkPropTypes_1;
}
var factoryWithTypeCheckers;
var hasRequiredFactoryWithTypeCheckers;
function requireFactoryWithTypeCheckers() {
if (hasRequiredFactoryWithTypeCheckers) return factoryWithTypeCheckers;
hasRequiredFactoryWithTypeCheckers = 1;
var ReactIs = requireReactIs();
var assign = requireObjectAssign();
var ReactPropTypesSecret = requireReactPropTypesSecret();
var has2 = requireHas();
var checkPropTypes = requireCheckPropTypes();
var printWarning = function() {
};
if (process.env.NODE_ENV !== "production") {
printWarning = function(text) {
var message = "Warning: " + text;
if (typeof console !== "undefined") {
console.error(message);
}
try {
throw new Error(message);
} catch (x) {
}
};
}
function emptyFunctionThatReturnsNull() {
return null;
}
factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) {
var ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = "@@iterator";
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === "function") {
return iteratorFn;
}
}
var ANONYMOUS = "<<anonymous>>";
var ReactPropTypes = {
array: createPrimitiveTypeChecker("array"),
bigint: createPrimitiveTypeChecker("bigint"),
bool: createPrimitiveTypeChecker("boolean"),
func: createPrimitiveTypeChecker("function"),
number: createPrimitiveTypeChecker("number"),
object: createPrimitiveTypeChecker("object"),
string: createPrimitiveTypeChecker("string"),
symbol: createPrimitiveTypeChecker("symbol"),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
elementType: createElementTypeTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker,
exact: createStrictShapeTypeChecker
};
function is(x, y) {
if (x === y) {
return x !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function PropTypeError(message, data) {
this.message = message;
this.data = data && typeof data === "object" ? data : {};
this.stack = "";
}
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
if (process.env.NODE_ENV !== "production") {
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location2, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret) {
if (throwOnDirectAccess) {
var err = new Error(
"Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types"
);
err.name = "Invariant Violation";
throw err;
} else if (process.env.NODE_ENV !== "production" && typeof console !== "undefined") {
var cacheKey = componentName + ":" + propName;
if (!manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount < 3) {
printWarning(
"You are manually calling a React.PropTypes validation function for the `" + propFullName + "` prop on `" + componentName + "`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."
);
manualPropTypeCallCache[cacheKey] = true;
manualPropTypeWarningCount++;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError("The " + location2 + " `" + propFullName + "` is marked as required " + ("in `" + componentName + "`, but its value is `null`."));
}
return new PropTypeError("The " + location2 + " `" + propFullName + "` is marked as required in " + ("`" + componentName + "`, but its value is `undefined`."));
}
return null;
} else {
return validate(props, propName, componentName, location2, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location2, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
var preciseType = getPreciseType(propValue);
return new PropTypeError(
"Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + preciseType + "` supplied to `" + componentName + "`, expected ") + ("`" + expectedType + "`."),
{ expectedType }
);
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunctionThatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location2, propFullName) {
if (typeof typeChecker !== "function") {
return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside arrayOf.");
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an array."));
}
for (var i2 = 0; i2 < propValue.length; i2++) {
var error = typeChecker(propValue, i2, componentName, location2, propFullName + "[" + i2 + "]", ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location2, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement."));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeTypeChecker() {
function validate(props, propName, componentName, location2, propFullName) {
var propValue = props[propName];
if (!ReactIs.isValidElementType(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement type."));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location2, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + actualClassName + "` supplied to `" + componentName + "`, expected ") + ("instance of `" + expectedClassName + "`."));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
if (process.env.NODE_ENV !== "production") {
if (arguments.length > 1) {
printWarning(
"Invalid arguments supplied to oneOf, expected an array, got " + arguments.length + " arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z])."
);
} else {
printWarning("Invalid argument supplied to oneOf, expected an array.");
}
}
return emptyFunctionThatReturnsNull;
}
function validate(props, propName, componentName, location2, propFullName) {
var propValue = props[propName];
for (var i2 = 0; i2 < expectedValues.length; i2++) {
if (is(propValue, expectedValues[i2])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues, function replacer(key, value2) {
var type = getPreciseType(value2);
if (type === "symbol") {
return String(value2);
}
return value2;
});
return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of value `" + String(propValue) + "` " + ("supplied to `" + componentName + "`, expected one of " + valuesString + "."));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location2, propFullName) {
if (typeof typeChecker !== "function") {
return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside objectOf.");
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== "object") {
return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an object."));
}
for (var key in propValue) {
if (has2(propValue, key)) {
var error = typeChecker(propValue, key, componentName, location2, propFullName + "." + key, ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
process.env.NODE_ENV !== "production" ? printWarning("Invalid argument supplied to oneOfType, expected an instance of array.") : void 0;
return emptyFunctionThatReturnsNull;
}
for (var i2 = 0; i2 < arrayOfTypeCheckers.length; i2++) {
var checker = arrayOfTypeCheckers[i2];
if (typeof checker !== "function") {
printWarning(
"Invalid argument supplied to oneOfType. Expected an array of check functions, but received " + getPostfixForTypeWarning(checker) + " at index " + i2 + "."
);
return emptyFunctionThatReturnsNull;
}
}
function validate(props, propName, componentName, location2, propFullName) {
var expectedTypes = [];
for (var i3 = 0; i3 < arrayOfTypeCheckers.length; i3++) {
var checker2 = arrayOfTypeCheckers[i3];
var checkerResult = checker2(props, propName, componentName, location2, propFullName, ReactPropTypesSecret);
if (checkerResult == null) {
return null;
}
if (checkerResult.data && has2(checkerResult.data, "expectedType")) {
expectedTypes.push(checkerResult.data.expectedType);
}
}
var expectedTypesMessage = expectedTypes.length > 0 ? ", expected one of type [" + expectedTypes.join(", ") + "]" : "";
return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` supplied to " + ("`" + componentName + "`" + expectedTypesMessage + "."));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location2, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a ReactNode."));
}
return null;
}
return createChainableTypeChecker(validate);
}
function invalidValidatorError(componentName, location2, propFullName, key, type) {
return new PropTypeError(
(componentName || "React class") + ": " + location2 + " type `" + propFullName + "." + key + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + type + "`."
);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location2, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== "object") {
return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (typeof checker !== "function") {
return invalidValidatorError(componentName, location2, propFullName, key, getPreciseType(checker));
}
var error = checker(propValue, key, componentName, location2, propFullName + "." + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createStrictShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location2, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== "object") {
return new PropTypeError("Invalid " + location2 + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."));
}
var allKeys = assign({}, props[propName], shapeTypes);
for (var key in allKeys) {
var checker = shapeTypes[key];
if (has2(shapeTypes, key) && typeof checker !== "function") {
return invalidValidatorError(componentName, location2, propFullName, key, getPreciseType(checker));
}
if (!checker) {
return new PropTypeError(
"Invalid " + location2 + " `" + propFullName + "` key `" + key + "` supplied to `" + componentName + "`.\nBad object: " + JSON.stringify(props[propName], null, " ") + "\nValid keys: " + JSON.stringify(Object.keys(shapeTypes), null, " ")
);
}
var error = checker(propValue, key, componentName, location2, propFullName + "." + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case "number":
case "string":
case "undefined":
return true;
case "boolean":
return !propValue;
case "object":
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
if (propType === "symbol") {
return true;
}
if (!propValue) {
return false;
}
if (propValue["@@toStringTag"] === "Symbol") {
return true;
}
if (typeof Symbol === "function" && propValue instanceof Symbol) {
return true;
}
return false;
}
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return "array";
}
if (propValue instanceof RegExp) {
return "object";
}
if (isSymbol(propType, propValue)) {
return "symbol";
}
return propType;
}
function getPreciseType(propValue) {
if (typeof propValue === "undefined" || propValue === null) {
return "" + propValue;
}
var propType = getPropType(propValue);
if (propType === "object") {
if (propValue instanceof Date) {
return "date";
} else if (propValue instanceof RegExp) {
return "regexp";
}
}
return propType;
}
function getPostfixForTypeWarning(value2) {
var type = getPreciseType(value2);
switch (type) {
case "array":
case "object":
return "an " + type;
case "boolean":
case "date":
case "regexp":
return "a " + type;
default:
return type;
}
}
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes;
ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
return factoryWithTypeCheckers;
}
var factoryWithThrowingShims;
var hasRequiredFactoryWithThrowingShims;
function requireFactoryWithThrowingShims() {
if (hasRequiredFactoryWithThrowingShims) return factoryWithThrowingShims;
hasRequiredFactoryWithThrowingShims = 1;
var ReactPropTypesSecret = requireReactPropTypesSecret();
function emptyFunction() {
}
function emptyFunctionWithReset() {
}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
factoryWithThrowingShims = function() {
function shim(props, propName, componentName, location2, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
return;
}
var err = new Error(
"Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types"
);
err.name = "Invariant Violation";
throw err;
}
shim.isRequired = shim;
function getShim() {
return shim;
}
var ReactPropTypes = {
array: shim,
bigint: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
elementType: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim,
checkPropTypes: emptyFunctionWithReset,
resetWarningCache: emptyFunction
};
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
return factoryWithThrowingShims;
}
if (process.env.NODE_ENV !== "production") {
var ReactIs = requireReactIs();
var throwOnDirectAccess = true;
propTypes.exports = requireFactoryWithTypeCheckers()(ReactIs.isElement, throwOnDirectAccess);
} else {
propTypes.exports = requireFactoryWithThrowingShims()();
}
var propTypesExports = propTypes.exports;
const PropTypes = /* @__PURE__ */ getDefaultExportFromCjs(propTypesExports);
var t = Object.defineProperty, e = (e2, a2, n2) => (((e3, a3, n3) => {
a3 in e3 ? t(e3, a3, { enumerable: true, configurable: true, writable: true, value: n3 }) : e3[a3] = n3;
})(e2, "symbol" != typeof a2 ? a2 + "" : a2, n2), n2);
/* @localazy/generic-connector-client@0.3.0
* (c) 2024 Localazy <team@localazy.com>
* @license MIT */
class a {
constructor(t2) {
e(this, "genericConnectorUrl"), e(this, "pluginId"), this.genericConnectorUrl = t2.genericConnectorUrl || "https://plugins.localazy.com/generic-connector", this.pluginId = t2.pluginId;
}
async get(t2, e2) {
return this.makeRequest("GET", t2, e2);
}
async post(t2, e2, a2) {
return this.makeRequest("POST", t2, a2, e2);
}
async put(t2, e2, a2) {
return this.makeRequest("PUT", t2, a2, e2);
}
async delete(t2, e2) {
return this.makeRequest("DELETE", t2, e2);
}
urlFactory(t2) {
return `${this.genericConnectorUrl}${t2}`;
}
configFactory(t2, e2, a2) {
const n2 = { method: t2, headers: { ...(null == e2 ? void 0 : e2.headers) || {}, "X-Localazy-Plugin-Id": `${this.pluginId}`, Accept: "application/json", "Content-Type": "application/json" } };
return a2 && (n2.body = JSON.stringify(a2)), n2;
}
async makeRequest(t2, e2, a2, n2) {
let s2 = this.urlFactory(e2);
if ("GET" === t2 && (null == a2 ? void 0 : a2.params)) {
s2 += `?${new URLSearchParams(a2.params).toString()}`;
}
const r2 = await fetch(s2, this.configFactory(t2, a2, n2)), i2 = r2.headers.get("content-type"), o2 = "blob" === (null == a2 ? void 0 : a2.responseType) || false, c2 = (null == i2 ? void 0 : i2.startsWith("application/json")) || false;
let l2;
if (l2 = o2 ? await r2.blob() : c2 ? await r2.json() : await r2.text(), r2.status >= 400) {
const t3 = c2 && l2.error ? l2.error : r2.statusText;
throw new Error(`Request failed with status code ${r2.status}: ${t3}`);
}
return l2;
}
}
class n {
constructor(t2) {
e(this, "api"), this.api = t2;
}
}
class s extends n {
async keys(t2) {
return await this.api.client.get("/public/keys", { ...t2 });
}
}
class r extends n {
async poll(t2, e2) {
return await this.api.client.get("/oauth/poll", { ...e2, params: { ...null == e2 ? void 0 : e2.params, ...t2 } });
}
async continuousPoll(t2, e2) {
const a2 = t2.pollingMaxAttempts || 60, n2 = t2.pollingIntervalMs || 2e3;
let s2 = 1, r2 = await this.poll({ readKey: t2.readKey }, e2);
return r2.completed ? r2 : new Promise((i2, o2) => {
const c2 = setInterval(async () => {
r2 = await this.poll({ readKey: t2.readKey }, e2), r2.completed && (clearInterval(c2), i2(r2)), s2 += 1, s2 >= a2 && (clearInterval(c2), o2(new Error("Sign in attempts timed out.")));
}, n2);
});
}
}
class i extends n {
async track(t2, e2) {
return await this.api.client.post("/analytics/track", t2, e2);
}
}
class o {
constructor(t2) {
e(this, "client"), e(this, "public"), e(this, "oauth"), e(this, "analytics"), this.client = new a(t2), this.public = new s(this), this.oauth = new r(this), this.analytics = new i(this);
}
}
var c = ((t2) => (t2[t2.UNKNOWN_SERVICE = -1] = "UNKNOWN_SERVICE", t2[t2.FIGMA = 0] = "FIGMA", t2[t2.STRAPI = 1] = "STRAPI", t2[t2.ZAPIER = 2] = "ZAPIER", t2[t2.STORYBLOK = 3] = "STORYBLOK", t2[t2.INTERCOM = 4] = "INTERCOM", t2[t2.DIRECTUS = 5] = "DIRECTUS", t2[t2.ZENDESK = 6] = "ZENDESK", t2))(c || {});
function l(t2, e2) {
const a2 = new URLSearchParams();
a2.append("client_id", t2.clientId), t2.redirectUri && a2.append("redirect_uri", t2.redirectUri), t2.customId && a2.append("custom_id", t2.customId), t2.state && a2.append("state", t2.state), t2.scope && a2.append("scope", t2.scope), t2.allowCreate && a2.append("allow_create", t2.allowCreate.toString()), t2.createType && a2.append("create_type", t2.createType), t2.createLocale && a2.append("create_locale", t2.createLocale), t2.minimalRole && a2.append("minimal_role", t2.minimalRole);
const n2 = e2 || "https://localazy.com";
return "/" !== new URL(n2).pathname ? `${n2}?${a2.toString()}` : `${n2}/oauth/authorize?${a2.toString()}`;
}
const BASE_PATH$2 = "/auth";
const axiosInstance = createStrapiApiAxiosInstance();
class LocalazyLoginService {
static async generateKeys() {
try {
const result = await axiosInstance.get(`${BASE_PATH$2}/generate-keys`);
return result.data;
} catch (e2) {
throw e2;
}
}
static async continuousPoll(readKey) {
try {
const result = await axiosInstance.get(`${BASE_PATH$2}/continuous-poll?readKey=${readKey}`);
return result.data;
} catch (e2) {
throw e2;
}
}
}
const strapiApiInstance$1 = createStrapiApiAxiosInstance("/i18n");
class I18nService {
static async getLocales() {
try {
const result = await strapiApiInstance$1.get(`/locales`);
return result.data;
} catch (e2) {
throw e2;
}
}
}
async function getStrapiDefaultLocale() {
const locales = await I18nService.getLocales();
const defaultLocale = locales.find((locale) => !!locale.isDefault);
if (!defaultLocale) {
return null;
}
return defaultLocale;
}
async function getLocalazySourceLanguage() {
const connectedProject = await ProjectService.getConnectedProject();
if (!connectedProject) {
return null;
}
const sourceLanguageId = connectedProject.sourceLanguage;
const sourceLanguage = connectedProject.languages.find((language) => language.id === sourceLanguageId);
if (!sourceLanguage) {
return null;
}
return sourceLanguage;
}
const isoStrapiToLocalazy = (isoStrapi) => {
if (!isoStrapi) {
return null;
}
const split = isoStrapi.split("-");
const language = split[0];
const hasRegionAndScript = split.length === 3;
if (hasRegionAndScript) {
const script = split[1];
const region = split[2];
return `${language}_${region}#${script}`;
}
const hasPossiblyRegion = split.length === 2;
if (hasPossiblyRegion) {
const regionOrScript = split[1];
const isItRegion = regionOrScript.toUpperCase() === regionOrScript;
return isItRegion ? `${language}_${regionOrScript}` : `${language}#${regionOrScript}`;
}
return isoStrapi.replace("-", "_");
};
const isoLocalazyToStrapi = (isoLocalazy) => {
if (!isoLocalazy) {
return null;
}
const scriptIndex = isoLocalazy.indexOf("#");
const hasScript = scriptIndex > -1;
if (hasScript) {
const script = isoLocalazy.substring(scriptIndex + 1);
const isoLocalazyWithoutScript = isoLocalazy.substring(0, scriptIndex);
const split = isoLocalazyWithoutScript.split("_");
const language = split[0];
const region = split[1];
if (!region) {
return `${language}-${script}`;
}
const isoStrapi = `${language}-${script}-${region.toUpperCase()}`;
return isoStrapi;
}
return isoLocalazy.replace("_", "-");
};
const production = {
LOCALAZY_OAUTH_URL: "https://localazy.com/oauth/authorize",
LOCALAZY_OAUTH_APP_CLIENT_ID: "18395772851999073783",
LOCALAZY_PLUGIN_CONNECTOR_API_URL: "https://plugins.localazy.com/generic-connector"
};
const local = {
LOCALAZY_OAUTH_URL: "https://testing.localazy.com/oauth/authorize",
LOCALAZY_OAUTH_APP_CLIENT_ID: "18503917571895066465",
LOCALAZY_PLUGIN_CONNECTOR_API_URL: "http://localhost:3000",
LOCALAZY_PUBLIC_API_URL: "https://testing.localazy.com/pubapi",
LOCALAZY_PLUGIN_ID: "1",
LOCALAZY_DEFAULT_FILE_NAME: "strapi.json",
LOCALAZY_DEFAULT_FILE_PATH: "",
LOCALAZY_DEFAULT_FILE_EXTENSION: "json",
LOCALAZY_DEFAULT_LOCALE: "en",
LOCALAZY_API_USER_JWT_COOKIE_NAME: "LOCALAZY-API-USER-JWT",
LOCALAZY_API_USER_COOKIE_EXPIRATION: 7,
LOCALAZY_PUBLIC_API_LIFTED_LIMITS: false
};
const development = {
LOCALAZY_OAUTH_URL: "https://testing.localazy.com/oauth/authorize",
LOCALAZY_OAUTH_APP_CLIENT_ID: "18503917571895066466",
LOCALAZY_PLUGIN_CONNECTOR_API_URL: "https://testing.localazy.com/plugin-connector",
LOCALAZY_PUBLIC_API_URL: "https://testing.localazy.com/pubapi",
LOCALAZY_PLUGIN_ID: "1",
LOCALAZY_DEFAULT_FILE_NAME: "strapi.json",
LOCALAZY_DEFAULT_FILE_PATH: "",
LOCALAZY_DEFAULT_FILE_EXTENSION: "json",
LOCALAZY_DEFAULT_LOCALE: "en",
LOCALAZY_API_USER_JWT_COOKIE_NAME: "LOCALAZY-API-USER-JWT",
LOCALAZY_API_USER_COOKIE_EXPIRATION: 7,
LOCALAZY_PUBLIC_API_LIFTED_LIMITS: true
};
let config = production;
if (process.env.STRAPI_ADMIN_LOCALAZY_ENV === "local") {
config = local;
}
if (process.env.STRAPI_ADMIN_LOCALAZY_ENV === "development") {
config = development;
}
const LoginButton = (props) => {
const { t: t2 } = useTranslation();
const [isLoading, setIsLoading] = useState(false);
const login = async () => {
setIsLoading(true);
const strapiDefaultLocale = await getStrapiDefaultLocale();
const localazyFormatLocaleCode = isoStrapiToLocalazy(strapiDefaultLocale?.code);
const keys = await LocalazyLoginService.generateKeys();
const url2 = l(
{
clientId: config.LOCALAZY_OAUTH_APP_CLIENT_ID,
customId: keys.writeKey,
allowCreate: true,
createLocale: localazyFormatLocaleCode ? localazyFormatLocaleCode : "en"
},
config.LOCALAZY_OAUTH_URL
);
window.open(url2);
const pollResult = await LocalazyLoginService.continuousPoll(keys.readKey);
setIsLoading(false);
props.onResultFetched(pollResult);
};
return /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Button, { variant: "default", size: "L", loading: isLoading, onClick: login, children: t2("login.login_with_localazy") }) });
};
LoginButton.propTypes = {
onResultFetched: PropTypes.func.isRequired
};
const client = new o({
pluginId: c.STRAPI,
genericConnectorUrl: config.LOCALAZY_PLUGIN_CONNECTOR_API_URL
});
const strapiApiInstance = createStrapiApiAxiosInstance();
class PluginService {
static async getPluginVersion() {
try {
const result = await strapiApiInstance.get("/strapi/version");
return result.data;
} catch (e2) {
throw e2;
}
}
}
class ProductAnalyticsService {
static async trackAppConnected(userId, project, params = {}) {
try {
const data = await this.buildData("Strapi Connected", project, params);
await client.analytics.track({
event: data.event,
data: {
...data.data,
userId,
orgId: project.orgId,
category: "Project"
}
});
} catch (e2) {
console.warn(e2);
}
}
static async trackAppDisconnected(userId, project, params = {}) {
try {
const data = await this.buildData("Strapi Disconnected", project, params);
await client.analytics.track({
event: data.event,
data: {
...data.data,
userId,
orgId: project.orgId,
category: "Project"
}
});
} catch (e2) {
console.warn(e2);
}
}
static async trackUploadToLocalazy(userId, project, params = {}) {
try {
const data = await this.buildData("Strapi Upload", project, params);
await client.analytics.track({
event: data.event,
data: {
...data.data,
userId,
orgId: project.orgId,
category: "Project"
}
});
} catch (e2) {
console.warn(e2);
}
}
static async trackDownloadToStrapi(userId, project, params = {}) {
try {
const data = await this.buildData("Strapi Download", project, params);
await client.analytics.track({
event: data.event,
data: {
...data.data,
userId,
orgId: project.orgId,
category: "Project"
}
});
} catch (e2) {
console.warn(e2);
}
}
static async buildData(event, project, params) {
const { version } = await PluginService.getPluginVersion();
return {
event,
data: {
"Project Id": project.id,
"Project Name": project.name,
version,
...params
}
};
}
}
const Login = ({ title, subtitle, isLoading = false }) => {
const { t: t2 } = useTranslation();
const localazyStrapiDocsLink = "https://localazy.com/docs/strapi";
const { setIdentity, identity, isLoggedIn } = useLocalazyIdentity();
const onLoginResultFetched = async (result) => {
await LocalazyUserService.updateIdentity(result);
setIdentity(result);
};
useEffect(() => {
if (isLoggedIn && identity.user && identity.project) {
ProductAnalyticsService.trackAppConnected(identity.user.id, identity.project);
}
}, [isLoggedIn, identity]);
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(Layouts.Header, { title, subtitle, as: "h1" }),
isLoading && /* @__PURE__ */ jsx(PluginPageLoader, {}),
!isLoading && /* @__PURE__ */ jsxs(
Box,
{
marginLeft: 10,
marginRight: 10,
background: "neutral0",
paddingTop: 6,
paddingRight: 7,
paddingBottom: 6,
paddingLeft: 7,
hasRadius: true,
shadow: "tableShadow",
children: [
/* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsxs(Typography, { variant: "epsilon", textColor: "neutral600", children: [
t2("common.localazy_plugin_description"),
/* @__PURE__ */ jsx("br", {}),
t2("login.login_and_start_translating_your_project"),
/* @__PURE__ */ jsx("br", {}),
/* @__PURE__ */ jsx("br", {}),
t2("login.you_have_to_own_account_for_the_plugin_to_work_properly")
] }) }),
/* @__PURE__ */ jsx(Box, { paddingTop: 6, children: /* @__PURE__ */ jsx(LoginButton, { onResultFetched: onLoginResultFetched }) }),
/* @__PURE__ */ jsx(Box, { paddingTop: 6, children: /* @__PURE__ */ jsx(Link, { href: localazyStrapiDocsLink, isExternal: true, children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "primary600", children: t2("login.read_the_documentation") }) }) })
]
}
)
] });
};
const SideNav = () => {
const { t: t2 } = useTranslation();
const navigation = useNav();
const isActive = (navItem) => {
return location.pathname.includes(navItem.to);
};
return /* @__PURE__ */ jsxs(SubNav, { "aria-label": t2("common.localazy_plugin"), children: [
/* @__PURE__ */ jsx(SubNavHeader, { label: t2("common.localazy_plugin") }),
/* @__PURE__ */ jsx(SubNavSections, { children: /* @__PURE__ */ jsx(SubNavSection, { label: t2("common.navigation"), children: navigation.map((navItem) => /* @__PURE__ */ jsx(SubNavLink, { tag: NavLink, to: navItem.to, active: isActive(navItem), icon: navItem.icon, children: navItem.label }, navItem.id)) }) })
] });
};
const LogoutButton = (props) => {
const { t: t2 } = useTranslation();
const [isLoading, setIsLoading] = useState(false);
const { setIdentity } = useLocalazyIdentity();
const logout = async () => {
setIsLoading(true);
LocalazyUserService.deleteIdentity();
setIdentity(emptyIdentity);
setIsLoading(false);
props.onResultFetched();
};
return /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Button, { startIcon: /* @__PURE__ */ jsx(ForwardRef$L, {}), variant: "secondary", loading: isLoading, onClick: logout, children: t2("login.logout_from_localazy") }) });
};
const OverviewItem = (props) => {
return /* @__PURE__ */ jsxs(Grid.Root, { padding: 1, col: 6, s: 12, children: [
/* @__PURE__ */ jsx(Grid.Item, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", textTransform: "uppercase", children: props.label }) }),
/* @__PURE__ */ jsx(Grid.Item, { children: /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", fontWeight: "semiBold", children: props.value }) })
] });
};
const OverviewItemLink = (props) => {
return /* @__PURE__ */ jsx(Grid.Root, { padding: 1, col: 6, s: 12, children: /* @__PURE__ */ jsx(Grid.Item, { children: /* @__PURE__ */ jsx(Link, { href: props.to, isExternal: true, children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "primary600", textTransform: "uppercase", children: props.label }) }) }) });
};
const PrerequisitiesInfo = () => {
const { t: t2 } = useTranslation();
return /* @__PURE__ */ jsxs(Box, { children: [
/* @__PURE__ */ jsx(Typography, { variant: "omega", children: t2("overview.transfer_setup_message_a") }),
/* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "semiBold", children: t2("overview.transfer_setup_message_b") })
] });
};
const formatNumber = (value2, options = void 0) => new Intl.NumberFormat("en-GB", options).format(value2);
const Overview = ({ title, subtitle, isLoadingProp = false }) => {
const { t: t2 } = useTranslation();
const { navigateToPluginRoute } = useRedirectToPluginRoute();
const [isLoading, setIsLoading] = useState(true);
const { identity } = useLocalazyIdentity();
const projectUrl = identity.project.url;
const [connectedProject, setConnectedProject] = useState(null);
useEffect(() => {
async function initComponent() {
setIsLoading(true);
const project = await ProjectService.getConnectedProject();
setConnectedProject(project);
PluginSettingsService.updatePluginSettings({ defaultRoute: PLUGIN_ROUTES.OVERVIEW });
setIsLoading(false);
}
initComponent();
}, []);
const onLoggedOut = () => {
ProductAnalyticsService.trackAppDisconnected(identity.user.id, identity.project);
navigateToPluginRoute(PLUGIN_ROUTES.LOGIN);
};
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(
Layouts.Header,
{
title,
subtitle,
primaryAction: /* @__PURE__ */ jsx(LogoutButton, { onResultFetched: onLoggedOut }),
as: "h2"
}
),
(isLoadingProp || isLoading) && /* @__PURE__ */ jsx(PluginPageLoader, {}),
!(isLoadingProp || isLoading) && /* @__PURE__ */ jsx(Box, { paddingRight: 10, paddingLeft: 10, children: /* @__PURE__ */ jsxs(
Box,
{
background: "neutral0",
paddingTop: 6,
paddingRight: 7,
paddingBottom: 6,
paddingLeft: 7,
hasRadius: true,
shadow: "tableShadow",
children: [
/* @__PURE__ */ jsxs(
Grid.Root,
{
gap: {
desktop: 5,
tablet: 2,
mobile: 1
},
children: [
/* @__PURE__ */ jsx(Grid.Item, { children: /* @__PURE__ */ jsx(OverviewItem, { label: t2("overview.connected_user"), value: identity.user.name }) }),
/* @__PURE__ */ jsx(Grid.Item, { children: /* @__PURE__ */ jsx(OverviewItem, { label: t2("overview.connected_project"), value: identity.project.name }) }),
/* @__PURE__ */ jsx(Grid.Item, { children: /* @__PURE__ */ jsx(
OverviewItem,
{
label: t2("overview.remaining_organization_keys"),
value: formatNumber(
(connectedProject?.organization?.availableKeys ?? 0) - (connectedProject?.organization?.usedKeys ?? 0)
)
}
) }),
/* @__PURE__ */ jsx(Grid.Item, { children: /* @__PURE__ */ jsx(OverviewItemLink, { label: t2("overview.open_project_in_localazy"), to: projectUrl }) })
]
}
),
/* @__PURE__ */ jsx(Box, { paddingTop: 4, paddingBottom: 4, children: /* @__PURE__ */ jsx(Divider, {}) }),
/* @__PURE__ */ jsx(PrerequisitiesInfo, {})
]
}
) })
] });
};
const THEME_KEY = "STRAPI_THEME";
const getDefaultThemeName = () => {
const persistedTheme = localStorage.getItem(THEME_KEY);
return persistedTheme || "system";
};
const getDefaultTheme = () => {
const themeName = getDefaultThemeName();
return themeName === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? darkTheme : lightTheme : themeName === "dark" ? darkTheme : lightTheme;
};
const BASE_PATH$1 = "/transfer";
class LocalazyUploadService {
static async upload(data = {}) {
try {
const strapiApiInstance2 = createStrapiApiAxiosInstance();
const result = await strapiApiInstance2.post(`${BASE_PATH$1}/upload`, data);
return result.data;
} catch (e2) {
throw e2.data;
}
}
}
const areLocalesCompatible = async (defaultLocale = null, sourceLanguage = null) => {
try {
if (!defaultLocale) {
const locales = await I18nService.getLocales();
defaultLocale = locales.find((locale) => !!locale.isDefault);
}
if (!defaultLocale) {
return false;
}
if (!sourceLanguage) {
const connectedProject = await ProjectService.getConnectedProject();
if (!connectedProject) {
return false;
}
const sourceLanguageId = connectedProject.sourceLanguage;
sourceLanguage = connectedProject.languages.find((language) => language.id === sourceLanguageId);
}
if (!sourceLanguage) {
return false;
}
const defaultLocaleCode = defaultLocale.code;
const sourceLanguageStrapiCode = isoLocalazyToStrapi(sourceLanguage.code);
return defaultLocaleCode === sourceLanguageStrapiCode;
} catch (e2) {
console.error(e2.message);
return false;
}
};
const TransferReport = (props) => {
const { t: t2 } = useTranslation();
const [reportLocal, setReportLocal] = useState(props.report);
const onCloseItem = (index) => {
const newReportLocal = reportLocal;
newReportLocal.splice(index, 1);
setReportLocal([...newReportLocal]);
};
useEffect(() => {
setReportLocal(props.report);
}, [props.report]);
if (!reportLocal) {
return null;
}
return reportLocal.map((item, index) => {
return /* @__PURE__ */ jsx(Box, { marginTop: 4, marginBottom: 4, children: /* @__PURE__ */ jsx(Alert, { onClose: () => onCloseItem(index), closeLabel: t2("upload.close"), variant: "default", children: item }, index) }, index);
});
};
const ReadDocsButton = () => {
const { t: t2 } = useTranslation();
const link = "https://localazy.com/docs/strapi";
const onReadDocumentationClick = () => {
window.open(link, "_blank");
};
return /* @__PURE__ */ jsx(Button, { variant: "tertiary", onClick: onReadDocumentationClick, children: t2("upload.read_documentation") });
};
const PACKET_TYPES = /* @__PURE__ */ Object.create(null);
PACKET_TYPES["open"] = "0";
PACKET_TYPES["close"] = "1";
PACKET_TYPES["ping"] = "2";
PACKET_TYPES["pong"] = "3";
PACKET_TYPES["message"] = "4";
PACKET_TYPES["upgrade"] = "5";
PACKET_TYPES["noop"] = "6";
const PACKET_TYPES_REVERSE = /* @__PURE__ */ Object.create(null);
Object.keys(PACKET_TYPES).forEach((key) => {
PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
});
const ERROR_PACKET = { type: "error", data: "parser error" };
const withNativeBlob$1 = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
const withNativeArrayBuffer$2 = typeof ArrayBuffer === "function";
const isView$1 = (obj) => {
return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
};
const encodePacket = ({ type, data }, supportsBinary, callback) => {
if (withNativeBlob$1 && data instanceof Blob) {
if (supportsBinary) {
return callback(data);
} else {
return encodeBlobAsBase64(data, callback);
}
} else if (withNativeArrayBuffer$2 && (data instanceof ArrayBuffer || isView$1(data))) {
if (supportsBinary) {
return callback(data);
} else {
return encodeBlobAsBase64(new Blob([data]), callback);
}
}
return callback(PACKET_TYPES[type] + (data || ""));
};
const encodeBlobAsBase64 = (data, callback) => {
const fileReader = new FileReader();
fileReader.onload = function() {
const content = fileReader.result.split(",")[1];
callback("b" + (content || ""));
};
return fileReader.readAsDataURL(data);
};
function toArray(data) {
if (data instanceof Uint8Array) {
return data;
} else if (data instanceof ArrayBuffer) {
return new Uint8Array(data);
} else {
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
}
}
let TEXT_ENCODER;
function encodePacketToBinary(packet, callback) {
if (withNativeBlob$1 && packet.data instanceof Blob) {
return packet.data.arrayBuffer().then(toArray).then(callback);
} else if (withNativeArrayBuffer$2 && (packet.data instanceof ArrayBuffer || isView$1(packet.data))) {
return callback(toArray(packet.data));
}
encodePacket(packet, false, (encoded) => {
if (!TEXT_ENCODER) {
TEXT_ENCODER = new TextEncoder();
}
callback(TEXT_ENCODER.encode(encoded));
});
}
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const lookup$1 = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
for (let i2 = 0; i2 < chars.length; i2++) {
lookup$1[chars.charCodeAt(i2)] = i2;
}
const decode$1 = (base64) => {
let bufferLength = base64.length * 0.75, len = base64.length, i2, p = 0, encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === "=") {
bufferLength--;
if (base64[base64.length - 2] === "=") {
bufferLength--;
}
}
const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
for (i2 = 0; i2 < len; i2 += 4) {
encoded1 = lookup$1[base64.charCodeAt(i2)];
encoded2 = lookup$1[base64.charCodeAt(i2 + 1)];
encoded3 = lookup$1[base64.charCodeAt(i2 + 2)];
encoded4 = lookup$1[base64.charCodeAt(i2 + 3)];
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return arraybuffer;
};
const withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
const decodePacket = (encodedPacket, binaryType) => {
if (typeof encodedPacket !== "string") {
return {
type: "message",
data: mapBinary(encodedPacket, binaryType)
};
}
const type = encodedPacket.charAt(0);
if (type === "b") {
return {
type: "message",
data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
};
}
const packetType = PACKET_TYPES_REVERSE[type];
if (!packetType) {
return ERROR_PACKET;
}
return encodedPacket.length > 1 ? {
type: PACKET_TYPES_REVERSE[type],
data: encodedPacket.substring(1)
} : {
type: PACKET_TYPES_REVERSE[type]
};
};
const decodeBase64Packet = (data, binaryType) => {
if (withNativeArrayBuffer$1) {
const decoded = decode$1(data);
return mapBinary(decoded, binaryType);
} else {
return { base64: true, data };
}
};
const mapBinary = (data, binaryType) => {
switch (binaryType) {
case "blob":
if (data instanceof Blob) {
return data;
} else {
return new Blob([data]);
}
case "arraybuffer":
default:
if (data instanceof ArrayBuffer) {
return data;
} else {
return data.buffer;
}
}
};
const SEPARATOR = String.fromCharCode(30);
const encodePayload = (packets, callback) => {
const length = packets.length;
const encodedPackets = new Array(length);
let count = 0;
packets.forEach((packet, i2) => {
encodePacket(packet, false, (encodedPacket) => {
encodedPackets[i2] = encodedPacket;
if (++count === length) {
callback(encodedPackets.join(SEPARATOR));
}
});
});
};
const decodePayload = (encodedPayload, binaryType) => {
const encodedPackets = encodedPayload.split(SEPARATOR);
const packets = [];
for (let i2 = 0; i2 < encodedPackets.length; i2++) {
const decodedPacket = decodePacket(encodedPackets[i2], binaryType);
packets.push(decodedPacket);
if (decodedPacket.type === "error") {
break;
}
}
return packets;
};
function createPacketEncoderStream() {
return new TransformStream({
transform(packet, controller) {
encodePacketToBinary(packet, (encodedPacket) => {
const payloadLength = encodedPacket.length;
let header;
if (payloadLength < 126) {
header = new Uint8Array(1);
new DataView(header.buffer).setUint8(0, payloadLength);
} else if (payloadLength < 65536) {
header = new Uint8Array(3);
const view = new DataView(header.buffer);
view.setUint8(0, 126);
view.setUint16(1, payloadLength);
} else {
header = new Uint8Array(9);
const view = new DataView(header.buffer);
view.setUint8(0, 127);
view.setBigUint64(1, BigInt(payloadLength));
}
if (packet.data && typeof packet.data !== "string") {
header[0] |= 128;
}
controller.enqueue(header);
controller.enqueue(encodedPacket);
});
}
});
}
let TEXT_DECODER;
function totalLength(chunks) {
return chunks.reduce((acc, chunk) => acc + chunk.length, 0);
}
function concatChunks(chunks, size) {
if (chunks[0].length === size) {
return chunks.shift();
}
const buffer = new Uint8Array(size);
let j = 0;
for (let i2 = 0; i2 < size; i2++) {
buffer[i2] = chunks[0][j++];
if (j === chunks[0].length) {
chunks.shift();
j = 0;
}
}
if (chunks.length && j < chunks[0].length) {
chunks[0] = chunks[0].slice(j);
}
return buffer;
}
function createPacketDecoderStream(maxPayload, binaryType) {
if (!TEXT_DECODER) {
TEXT_DECODER = new TextDecoder();
}
const chunks = [];
let state = 0;
let expectedLength = -1;
let isBinary2 = false;
return new TransformStream({
transform(chunk, controller) {
chunks.push(chunk);
while (true) {
if (state === 0) {
if (totalLength(chunks) < 1) {
break;
}
const header = concatChunks(chunks, 1);
isBinary2 = (header[0] & 128) === 128;
expectedLength = header[0] & 127;
if (expectedLength < 126) {
state = 3;
} else if (expectedLength === 126) {
state = 1;
} else {
state = 2;
}
} else if (state === 1) {
if (totalLength(chunks) < 2) {
break;
}
const headerArray = concatChunks(chunks, 2);
expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
state = 3;
} else if (state === 2) {
if (totalLength(chunks) < 8) {
break;
}
const headerArray = concatChunks(chunks, 8);
const view = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length);
const n2 = view.getUint32(0);
if (n2 > Math.pow(2, 53 - 32) - 1) {
controller.enqueue(ERROR_PACKET);
break;
}
expectedLength = n2 * Math.pow(2, 32) + view.getUint32(4);
state = 3;
} else {
if (totalLength(chunks) < expectedLength) {
break;
}
const data = concatChunks(chunks, expectedLength);
controller.enqueue(decodePacket(isBinary2 ? data : TEXT_DECODER.decode(data), binaryType));
state = 0;
}
if (expectedLength === 0 || expectedLength > maxPayload) {
controller.enqueue(ERROR_PACKET);
break;
}
}
}
});
}
const protocol$1 = 4;
function Emitter(obj) {
if (obj) return mixin(obj);
}
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn) {
this._callbacks = this._callbacks || {};
(this._callbacks["$" + event] = this._callbacks["$" + event] || []).push(fn);
return this;
};
Emitter.prototype.once = function(event, fn) {
function on2() {
this.off(event, on2);
fn.apply(this, arguments);
}
on2.fn = fn;
this.on(event, on2);
return this;
};
Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn) {
this._callbacks = this._callbacks || {};
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
var callbacks = this._callbacks["$" + event];
if (!callbacks) return this;
if (1 == arguments.length) {
delete this._callbacks["$" + event];
return this;
}
var cb;
for (var i2 = 0; i2 < callbacks.length; i2++) {
cb = callbacks[i2];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i2, 1);
break;
}
}
if (callbacks.length === 0) {
delete this._callbacks["$" + event];
}
return this;
};
Emitter.prototype.emit = function(event) {
this._callbacks = this._callbacks || {};
var args = new Array(arguments.length - 1), callbacks = this._callbacks["$" + event];
for (var i2 = 1; i2 < arguments.length; i2++) {
args[i2 - 1] = arguments[i2];
}
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i2 = 0, len = callbacks.length; i2 < len; ++i2) {
callbacks[i2].apply(this, args);
}
}
return this;
};
Emitter.prototype.emitReserved = Emitter.prototype.emit;
Emitter.prototype.listeners = function(event) {
this._callbacks = this._callbacks || {};
return this._callbacks["$" + event] || [];
};
Emitter.prototype.hasListeners = function(event) {
return !!this.listeners(event).length;
};
const nextTick = (() => {
const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
if (isPromiseAvailable) {
return (cb) => Promise.resolve().then(cb);
} else {
return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);
}
})();
const globalThisShim = (() => {
if (typeof self !== "undefined") {
return self;
} else if (typeof window !== "undefined") {
return window;
} else {
return Function("return this")();
}
})();
const defaultBinaryType = "arraybuffer";
function createCookieJar() {
}
function pick(obj, ...attr) {
return attr.reduce((acc, k) => {
if (obj.hasOwnProperty(k)) {
acc[k] = obj[k];
}
return acc;
}, {});
}
const NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
const NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
function installTimerFunctions(obj, opts) {
if (opts.useNativeTimers) {
obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
} else {
obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
}
}
const BASE64_OVERHEAD = 1.33;
function byteLength(obj) {
if (typeof obj === "string") {
return utf8Length(obj);
}
return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
}
function utf8Length(str) {
let c2 = 0, length = 0;
for (let i2 = 0, l2 = str.length; i2 < l2; i2++) {
c2 = str.charCodeAt(i2);
if (c2 < 128) {
length += 1;
} else if (c2 < 2048) {
length += 2;
} else if (c2 < 55296 || c2 >= 57344) {
length += 3;
} else {
i2++;
length += 4;
}
}
return length;
}
function randomString() {
return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5);
}
function encode(obj) {
let str = "";
for (let i2 in obj) {
if (obj.hasOwnProperty(i2)) {
if (str.length)
str += "&";
str += encodeURIComponent(i2) + "=" + encodeURIComponent(obj[i2]);
}
}
return str;
}
function decode(qs) {
let qry = {};
let pairs = qs.split("&");
for (let i2 = 0, l2 = pairs.length; i2 < l2; i2++) {
let pair = pairs[i2].split("=");
qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return qry;
}
class TransportError extends Error {
constructor(reason, description, context) {
super(reason);
this.description = description;
this.context = context;
this.type = "TransportError";
}
}
class Transport extends Emitter {
/**
* Transport abstract constructor.
*
* @param {Object} opts - options
* @protected
*/
constructor(opts) {
super();
this.writable = false;
installTimerFunctions(this, opts);
this.opts = opts;
this.query = opts.query;
this.socket = opts.socket;
this.supportsBinary = !opts.forceBase64;
}
/**
* Emits an error.
*
* @param {String} reason
* @param description
* @param context - the error context
* @return {Transport} for chaining
* @protected
*/
onError(reason, description, context) {
super.emitReserved("error", new TransportError(reason, description, context));
return this;
}
/**
* Opens the transport.
*/
open() {
this.readyState = "opening";
this.doOpen();
return this;
}
/**
* Closes the transport.
*/
close() {
if (this.readyState === "opening" || this.readyState === "open") {
this.doClose();
this.onClose();
}
return this;
}
/**
* Sends multiple packets.
*
* @param {Array} packets
*/
send(packets) {
if (this.readyState === "open") {
this.write(packets);
}
}
/**
* Called upon open
*
* @protected
*/
onOpen() {
this.readyState = "open";
this.writable = true;
super.emitReserved("open");
}
/**
* Called with data.
*
* @param {String} data
* @protected
*/
onData(data) {
const packet = decodePacket(data, this.socket.binaryType);
this.onPacket(packet);
}
/**
* Called with a decoded packet.
*
* @protected
*/
onPacket(packet) {
super.emitReserved("packet", packet);
}
/**
* Called upon close.
*
* @protected
*/
onClose(details) {
this.readyState = "closed";
super.emitReserved("close", details);
}
/**
* Pauses the transport, in order not to lose packets during an upgrade.
*
* @param onPause
*/
pause(onPause) {
}
createUri(schema, query = {}) {
return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
}
_hostname() {
const hostname = this.opts.hostname;
return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
}
_port() {
if (this.opts.port && (this.opts.secure && Number(this.opts.port !== 443) || !this.opts.secure && Number(this.opts.port) !== 80)) {
return ":" + this.opts.port;
} else {
return "";
}
}
_query(query) {
const encodedQuery = encode(query);
return encodedQuery.length ? "?" + encodedQuery : "";
}
}
class Polling extends Transport {
constructor() {
super(...arguments);
this._polling = false;
}
get name() {
return "polling";
}
/**
* Opens the socket (triggers polling). We write a PING message to determine
* when the transport is open.
*
* @protected
*/
doOpen() {
this._poll();
}
/**
* Pauses polling.
*
* @param {Function} onPause - callback upon buffers are flushed and transport is paused
* @package
*/
pause(onPause) {
this.readyState = "pausing";
const pause = () => {
this.readyState = "paused";
onPause();
};
if (this._polling || !this.writable) {
let total = 0;
if (this._polling) {
total++;
this.once("pollComplete", function() {
--total || pause();
});
}
if (!this.writable) {
total++;
this.once("drain", function() {
--total || pause();
});
}
} else {
pause();
}
}
/**
* Starts polling cycle.
*
* @private
*/
_poll() {
this._polling = true;
this.doPoll();
this.emitReserved("poll");
}
/**
* Overloads onData to detect payloads.
*
* @protected
*/
onData(data) {
const callback = (packet) => {
if ("opening" === this.readyState && packet.type === "open") {
this.onOpen();
}
if ("close" === packet.type) {
this.onClose({ description: "transport closed by the server" });
return false;
}
this.onPacket(packet);
};
decodePayload(data, this.socket.binaryType).forEach(callback);
if ("closed" !== this.readyState) {
this._polling = false;
this.emitReserved("pollComplete");
if ("open" === this.readyState) {
this._poll();
}
}
}
/**
* For polling, send a close packet.
*
* @protected
*/
doClose() {
const close = () => {
this.write([{ type: "close" }]);
};
if ("open" === this.readyState) {
close();
} else {
this.once("open", close);
}
}
/**
* Writes a packets payload.
*
* @param {Array} packets - data packets
* @protected
*/
write(packets) {
this.writable = false;
encodePayload(packets, (data) => {
this.doWrite(data, () => {
this.writable = true;
this.emitReserved("drain");
});
});
}
/**
* Generates uri for connection.
*
* @private
*/
uri() {
const schema = this.opts.secure ? "https" : "http";
const query = this.query || {};
if (false !== this.opts.timestampRequests) {
query[this.opts.timestampParam] = randomString();
}
if (!this.supportsBinary && !query.sid) {
query.b64 = 1;
}
return this.createUri(schema, query);
}
}
let value = false;
try {
value = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest();
} catch (err) {
}
const hasCORS = value;
function empty() {
}
class BaseXHR extends Polling {
/**
* XHR Polling constructor.
*
* @param {Object} opts
* @package
*/
constructor(opts) {
super(opts);
if (typeof location !== "undefined") {
const isSSL = "https:" === location.protocol;
let port = location.port;
if (!port) {
port = isSSL ? "443" : "80";
}
this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
}
}
/**
* Sends data.
*
* @param {String} data to send.
* @param {Function} called upon flush.
* @private
*/
doWrite(data, fn) {
const req = this.request({
method: "POST",
data
});
req.on("success", fn);
req.on("error", (xhrStatus, context) => {
this.onError("xhr post error", xhrStatus, context);
});
}
/**
* Starts a poll cycle.
*
* @private
*/
doPoll() {
const req = this.request();
req.on("data", this.onData.bind(this));
req.on("error", (xhrStatus, context) => {
this.onError("xhr poll error", xhrStatus, context);
});
this.pollXhr = req;
}
}
class Request extends Emitter {
/**
* Request constructor
*
* @param {Object} options
* @package
*/
constructor(createRequest, uri, opts) {
super();
this.createRequest = createRequest;
installTimerFunctions(this, opts);
this._opts = opts;
this._method = opts.method || "GET";
this._uri = uri;
this._data = void 0 !== opts.data ? opts.data : null;
this._create();
}
/**
* Creates the XHR object and sends the request.
*
* @private
*/
_create() {
var _a;
const opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
opts.xdomain = !!this._opts.xd;
const xhr = this._xhr = this.createRequest(opts);
try {
xhr.open(this._method, this._uri, true);
try {
if (this._opts.extraHeaders) {
xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
for (let i2 in this._opts.extraHeaders) {
if (this._opts.extraHeaders.hasOwnProperty(i2)) {
xhr.setRequestHeader(i2, this._opts.extraHeaders[i2]);
}
}
}
} catch (e2) {
}
if ("POST" === this._method) {
try {
xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
} catch (e2) {
}
}
try {
xhr.setRequestHeader("Accept", "*/*");
} catch (e2) {
}
(_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
if ("withCredentials" in xhr) {
xhr.withCredentials = this._opts.withCredentials;
}
if (this._opts.requestTimeout) {
xhr.timeout = this._opts.requestTimeout;
}
xhr.onreadystatechange = () => {
var _a2;
if (xhr.readyState === 3) {
(_a2 = this._opts.cookieJar) === null || _a2 === void 0 ? void 0 : _a2.parseCookies(
// @ts-ignore
xhr.getResponseHeader("set-cookie")
);
}
if (4 !== xhr.readyState)
return;
if (200 === xhr.status || 1223 === xhr.status) {
this._onLoad();
} else {
this.setTimeoutFn(() => {
this._onError(typeof xhr.status === "number" ? xhr.status : 0);
}, 0);
}
};
xhr.send(this._data);
} catch (e2) {
this.setTimeoutFn(() => {
this._onError(e2);
}, 0);
return;
}
if (typeof document !== "undefined") {
this._index = Request.requestsCount++;
Request.requests[this._index] = this;
}
}
/**
* Called upon error.
*
* @private
*/
_onError(err) {
this.emitReserved("error", err, this._xhr);
this._cleanup(true);
}
/**
* Cleans up house.
*
* @private
*/
_cleanup(fromError) {
if ("undefined" === typeof this._xhr || null === this._xhr) {
return;
}
this._xhr.onreadystatechange = empty;
if (fromError) {
try {
this._xhr.abort();
} catch (e2) {
}
}
if (typeof document !== "undefined") {
delete Request.requests[this._index];
}
this._xhr = null;
}
/**
* Called upon load.
*
* @private
*/
_onLoad() {
const data = this._xhr.responseText;
if (data !== null) {
this.emitReserved("data", data);
this.emitReserved("success");
this._cleanup();
}
}
/**
* Aborts the request.
*
* @package
*/
abort() {
this._cleanup();
}
}
Request.requestsCount = 0;
Request.requests = {};
if (typeof document !== "undefined") {
if (typeof attachEvent === "function") {
attachEvent("onunload", unloadHandler);
} else if (typeof addEventListener === "function") {
const terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
addEventListener(terminationEvent, unloadHandler, false);
}
}
function unloadHandler() {
for (let i2 in Request.requests) {
if (Request.requests.hasOwnProperty(i2)) {
Request.requests[i2].abort();
}
}
}
const hasXHR2 = function() {
const xhr = newRequest({
xdomain: false
});
return xhr && xhr.responseType !== null;
}();
class XHR extends BaseXHR {
constructor(opts) {
super(opts);
const forceBase64 = opts && opts.forceBase64;
this.supportsBinary = hasXHR2 && !forceBase64;
}
request(opts = {}) {
Object.assign(opts, { xd: this.xd }, this.opts);
return new Request(newRequest, this.uri(), opts);
}
}
function newRequest(opts) {
const xdomain = opts.xdomain;
try {
if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
return new XMLHttpRequest();
}
} catch (e2) {
}
if (!xdomain) {
try {
return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
} catch (e2) {
}
}
}
const isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
class BaseWS extends Transport {
get name() {
return "websocket";
}
doOpen() {
const uri = this.uri();
const protocols = this.opts.protocols;
const opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
if (this.opts.extraHeaders) {
opts.headers = this.opts.extraHeaders;
}
try {
this.ws = this.createSocket(uri, protocols, opts);
} catch (err) {
return this.emitReserved("error", err);
}
this.ws.binaryType = this.socket.binaryType;
this.addEventListeners();
}
/**
* Adds event listeners to the socket
*
* @private
*/
addEventListeners() {
this.ws.onopen = () => {
if (this.opts.autoUnref) {
this.ws._socket.unref();
}
this.onOpen();
};
this.ws.onclose = (closeEvent) => this.onClose({
description: "websocket connection closed",
context: closeEvent
});
this.ws.onmessage = (ev) => this.onData(ev.data);
this.ws.onerror = (e2) => this.onError("websocket error", e2);
}
write(packets) {
this.writable = false;
for (let i2 = 0; i2 < packets.length; i2++) {
const packet = packets[i2];
const lastPacket = i2 === packets.length - 1;
encodePacket(packet, this.supportsBinary, (data) => {
try {
this.doWrite(packet, data);
} catch (e2) {
}
if (lastPacket) {
nextTick(() => {
this.writable = true;
this.emitReserved("drain");
}, this.setTimeoutFn);
}
});
}
}
doClose() {
if (typeof this.ws !== "undefined") {
this.ws.onerror = () => {
};
this.ws.close();
this.ws = null;
}
}
/**
* Generates uri for connection.
*
* @private
*/
uri() {
const schema = this.opts.secure ? "wss" : "ws";
const query = this.query || {};
if (this.opts.timestampRequests) {
query[this.opts.timestampParam] = randomString();
}
if (!this.supportsBinary) {
query.b64 = 1;
}
return this.createUri(schema, query);
}
}
const WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
class WS extends BaseWS {
createSocket(uri, protocols, opts) {
return !isReactNative ? protocols ? new WebSocketCtor(uri, protocols) : new WebSocketCtor(uri) : new WebSocketCtor(uri, protocols, opts);
}
doWrite(_packet, data) {
this.ws.send(data);
}
}
class WT extends Transport {
get name() {
return "webtransport";
}
doOpen() {
try {
this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
} catch (err) {
return this.emitReserved("error", err);
}
this._transport.closed.then(() => {
this.onClose();
}).catch((err) => {
this.onError("webtransport error", err);
});
this._transport.ready.then(() => {
this._transport.createBidirectionalStream().then((stream) => {
const decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, this.socket.binaryType);
const reader = stream.readable.pipeThrough(decoderStream).getReader();
const encoderStream = createPacketEncoderStream();
encoderStream.readable.pipeTo(stream.writable);
this._writer = encoderStream.writable.getWriter();
const read = () => {
reader.read().then(({ done, value: value2 }) => {
if (done) {
return;
}
this.onPacket(value2);
read();
}).catch((err) => {
});
};
read();
const packet = { type: "open" };
if (this.query.sid) {
packet.data = `{"sid":"${this.query.sid}"}`;
}
this._writer.write(packet).then(() => this.onOpen());
});
});
}
write(packets) {
this.writable = false;
for (let i2 = 0; i2 < packets.length; i2++) {
const packet = packets[i2];
const lastPacket = i2 === packets.length - 1;
this._writer.write(packet).then(() => {
if (lastPacket) {
nextTick(() => {
this.writable = true;
this.emitReserved("drain");
}, this.setTimeoutFn);
}
});
}
}
doClose() {
var _a;
(_a = this._transport) === null || _a === void 0 ? void 0 : _a.close();
}
}
const transports = {
websocket: WS,
webtransport: WT,
polling: XHR
};
const re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
const parts = [
"source",
"protocol",
"authority",
"userInfo",
"user",
"password",
"host",
"port",
"relative",
"path",
"directory",
"file",
"query",
"anchor"
];
function parse(str) {
if (str.length > 8e3) {
throw "URI too long";
}
const src = str, b = str.indexOf("["), e2 = str.indexOf("]");
if (b != -1 && e2 != -1) {
str = str.substring(0, b) + str.substring(b, e2).replace(/:/g, ";") + str.substring(e2, str.length);
}
let m = re.exec(str || ""), uri = {}, i2 = 14;
while (i2--) {
uri[parts[i2]] = m[i2] || "";
}
if (b != -1 && e2 != -1) {
uri.source = src;
uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ":");
uri.authority = uri.authority.replace("[", "").replace("]", "").replace(/;/g, ":");
uri.ipv6uri = true;
}
uri.pathNames = pathNames(uri, uri["path"]);
uri.queryKey = queryKey(uri, uri["query"]);
return uri;
}
function pathNames(obj, path) {
const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/");
if (path.slice(0, 1) == "/" || path.length === 0) {
names.splice(0, 1);
}
if (path.slice(-1) == "/") {
names.splice(names.length - 1, 1);
}
return names;
}
function queryKey(uri, query) {
const data = {};
query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function($0, $1, $2) {
if ($1) {
data[$1] = $2;
}
});
return data;
}
const withEventListeners = typeof addEventListener === "function" && typeof removeEventListener === "function";
const OFFLINE_EVENT_LISTENERS = [];
if (withEventListeners) {
addEventListener("offline", () => {
OFFLINE_EVENT_LISTENERS.forEach((listener) => listener());
}, false);
}
class SocketWithoutUpgrade extends Emitter {
/**
* Socket constructor.
*
* @param {String|Object} uri - uri or options
* @param {Object} opts - options
*/
constructor(uri, opts) {
super();
this.binaryType = defaultBinaryType;
this.writeBuffer = [];
this._prevBufferLen = 0;
this._pingInterval = -1;
this._pingTimeout = -1;
this._maxPayload = -1;
this._pingTimeoutTime = Infinity;
if (uri && "object" === typeof uri) {
opts = uri;
uri = null;
}
if (uri) {
const parsedUri = parse(uri);
opts.hostname = parsedUri.host;
opts.secure = parsedUri.protocol === "https" || parsedUri.protocol === "wss";
opts.port = parsedUri.port;
if (parsedUri.query)
opts.query = parsedUri.query;
} else if (opts.host) {
opts.hostname = parse(opts.host).host;
}
installTimerFunctions(this, opts);
this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
if (opts.hostname && !opts.port) {
opts.port = this.secure ? "443" : "80";
}
this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : this.secure ? "443" : "80");
this.transports = [];
this._transportsByName = {};
opts.transports.forEach((t2) => {
const transportName = t2.prototype.name;
this.transports.push(transportName);
this._transportsByName[transportName] = t2;
});
this.opts = Object.assign({
path: "/engine.io",
agent: false,
withCredentials: false,
upgrade: true,
timestampParam: "t",
rememberUpgrade: false,
addTrailingSlash: true,
rejectUnauthorized: true,
perMessageDeflate: {
threshold: 1024
},
transportOptions: {},
closeOnBeforeunload: false
}, opts);
this.opts.path = this.opts.path.replace(/\/$/, "") + (this.opts.addTrailingSlash ? "/" : "");
if (typeof this.opts.query === "string") {
this.opts.query = decode(this.opts.query);
}
if (withEventListeners) {
if (this.opts.closeOnBeforeunload) {
this._beforeunloadEventListener = () => {
if (this.transport) {
this.transport.removeAllListeners();
this.transport.close();
}
};
addEventListener("beforeunload", this._beforeunloadEventListener, false);
}
if (this.hostname !== "localhost") {
this._offlineEventListener = () => {
this._onClose("transport close", {
description: "network connection lost"
});
};
OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener);
}
}
if (this.opts.withCredentials) {
this._cookieJar = createCookieJar();
}
this._open();
}
/**
* Creates transport of the given type.
*
* @param {String} name - transport name
* @return {Transport}
* @private
*/
createTransport(name) {
const query = Object.assign({}, this.opts.query);
query.EIO = protocol$1;
query.transport = name;
if (this.id)
query.sid = this.id;
const opts = Object.assign({}, this.opts, {
query,
socket: this,
hostname: this.hostname,
secure: this.secure,
port: this.port
}, this.opts.transportOptions[name]);
return new this._transportsByName[name](opts);
}
/**
* Initializes transport to use and starts probe.
*
* @private
*/
_open() {
if (this.transports.length === 0) {
this.setTimeoutFn(() => {
this.emitReserved("error", "No transports available");
}, 0);
return;
}
const transportName = this.opts.rememberUpgrade && SocketWithoutUpgrade.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1 ? "websocket" : this.transports[0];
this.readyState = "opening";
const transport = this.createTransport(transportName);
transport.open();
this.setTransport(transport);
}
/**
* Sets the current transport. Disables the existing one (if any).
*
* @private
*/
setTransport(transport) {
if (this.transport) {
this.transport.removeAllListeners();
}
this.transport = transport;
transport.on("drain", this._onDrain.bind(this)).on("packet", this._onPacket.bind(this)).on("error", this._onError.bind(this)).on("close", (reason) => this._onClose("transport close", reason));
}
/**
* Called when connection is deemed open.
*
* @private
*/
onOpen() {
this.readyState = "open";
SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === this.transport.name;
this.emitReserved("open");
this.flush();
}
/**
* Handles a packet.
*
* @private
*/
_onPacket(packet) {
if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
this.emitReserved("packet", packet);
this.emitReserved("heartbeat");
switch (packet.type) {
case "open":
this.onHandshake(JSON.parse(packet.data));
break;
case "ping":
this._sendPacket("pong");
this.emitReserved("ping");
this.emitReserved("pong");
this._resetPingTimeout();
break;
case "error":
const err = new Error("server error");
err.code = packet.data;
this._onError(err);
break;
case "message":
this.emitReserved("data", packet.data);
this.emitReserved("message", packet.data);
break;
}
}
}
/**
* Called upon handshake completion.
*
* @param {Object} data - handshake obj
* @private
*/
onHandshake(data) {
this.emitReserved("handshake", data);
this.id = data.sid;
this.transport.query.sid = data.sid;
this._pingInterval = data.pingInterval;
this._pingTimeout = data.pingTimeout;
this._maxPayload = data.maxPayload;
this.onOpen();
if ("closed" === this.readyState)
return;
this._resetPingTimeout();
}
/**
* Sets and resets ping timeout timer based on server pings.
*
* @private
*/
_resetPingTimeout() {
this.clearTimeoutFn(this._pingTimeoutTimer);
const delay = this._pingInterval + this._pingTimeout;
this._pingTimeoutTime = Date.now() + delay;
this._pingTimeoutTimer = this.setTimeoutFn(() => {
this._onClose("ping timeout");
}, delay);
if (this.opts.autoUnref) {
this._pingTimeoutTimer.unref();
}
}
/**
* Called on `drain` event
*
* @private
*/
_onDrain() {
this.writeBuffer.splice(0, this._prevBufferLen);
this._prevBufferLen = 0;
if (0 === this.writeBuffer.length) {
this.emitReserved("drain");
} else {
this.flush();
}
}
/**
* Flush write buffers.
*
* @private
*/
flush() {
if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
const packets = this._getWritablePackets();
this.transport.send(packets);
this._prevBufferLen = packets.length;
this.emitReserved("flush");
}
}
/**
* Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
* long-polling)
*
* @private
*/
_getWritablePackets() {
const shouldCheckPayloadSize = this._maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
if (!shouldCheckPayloadSize) {
return this.writeBuffer;
}
let payloadSize = 1;
for (let i2 = 0; i2 < this.writeBuffer.length; i2++) {
const data = this.writeBuffer[i2].data;
if (data) {
payloadSize += byteLength(data);
}
if (i2 > 0 && payloadSize > this._maxPayload) {
return this.writeBuffer.slice(0, i2);
}
payloadSize += 2;
}
return this.writeBuffer;
}
/**
* Checks whether the heartbeat timer has expired but the socket has not yet been notified.
*
* Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
* `write()` method then the message would not be buffered by the Socket.IO client.
*
* @return {boolean}
* @private
*/
/* private */
_hasPingExpired() {
if (!this._pingTimeoutTime)
return true;
const hasExpired = Date.now() > this._pingTimeoutTime;
if (hasExpired) {
this._pingTimeoutTime = 0;
nextTick(() => {
this._onClose("ping timeout");
}, this.setTimeoutFn);
}
return hasExpired;
}
/**
* Sends a message.
*
* @param {String} msg - message.
* @param {Object} options.
* @param {Function} fn - callback function.
* @return {Socket} for chaining.
*/
write(msg, options, fn) {
this._sendPacket("message", msg, options, fn);
return this;
}
/**
* Sends a message. Alias of {@link Socket#write}.
*
* @param {String} msg - message.
* @param {Object} options.
* @param {Function} fn - callback function.
* @return {Socket} for chaining.
*/
send(msg, options, fn) {
this._sendPacket("message", msg, options, fn);
return this;
}
/**
* Sends a packet.
*
* @param {String} type: packet type.
* @param {String} data.
* @param {Object} options.
* @param {Function} fn - callback function.
* @private
*/
_sendPacket(type, data, options, fn) {
if ("function" === typeof data) {
fn = data;
data = void 0;
}
if ("function" === typeof options) {
fn = options;
options = null;
}
if ("closing" === this.readyState || "closed" === this.readyState) {
return;
}
options = options || {};
options.compress = false !== options.compress;
const packet = {
type,
data,
options
};
this.emitReserved("packetCreate", packet);
this.writeBuffer.push(packet);
if (fn)
this.once("flush", fn);
this.flush();
}
/**
* Closes the connection.
*/
close() {
const close = () => {
this._onClose("forced close");
this.transport.close();
};
const cleanupAndClose = () => {
this.off("upgrade", cleanupAndClose);
this.off("upgradeError", cleanupAndClose);
close();
};
const waitForUpgrade = () => {
this.once("upgrade", cleanupAndClose);
this.once("upgradeError", cleanupAndClose);
};
if ("opening" === this.readyState || "open" === this.readyState) {
this.readyState = "closing";
if (this.writeBuffer.length) {
this.once("drain", () => {
if (this.upgrading) {
waitForUpgrade();
} else {
close();
}
});
} else if (this.upgrading) {
waitForUpgrade();
} else {
close();
}
}
return this;
}
/**
* Called upon transport error
*
* @private
*/
_onError(err) {
SocketWithoutUpgrade.priorWebsocketSuccess = false;
if (this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening") {
this.transports.shift();
return this._open();
}
this.emitReserved("error", err);
this._onClose("transport error", err);
}
/**
* Called upon transport close.
*
* @private
*/
_onClose(reason, description) {
if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
this.clearTimeoutFn(this._pingTimeoutTimer);
this.transport.removeAllListeners("close");
this.transport.close();
this.transport.removeAllListeners();
if (withEventListeners) {
if (this._beforeunloadEventListener) {
removeEventListener("beforeunload", this._beforeunloadEventListener, false);
}
if (this._offlineEventListener) {
const i2 = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
if (i2 !== -1) {
OFFLINE_EVENT_LISTENERS.splice(i2, 1);
}
}
}
this.readyState = "closed";
this.id = null;
this.emitReserved("close", reason, description);
this.writeBuffer = [];
this._prevBufferLen = 0;
}
}
}
SocketWithoutUpgrade.protocol = protocol$1;
class SocketWithUpgrade extends SocketWithoutUpgrade {
constructor() {
super(...arguments);
this._upgrades = [];
}
onOpen() {
super.onOpen();
if ("open" === this.readyState && this.opts.upgrade) {
for (let i2 = 0; i2 < this._upgrades.length; i2++) {
this._probe(this._upgrades[i2]);
}
}
}
/**
* Probes a transport.
*
* @param {String} name - transport name
* @private
*/
_probe(name) {
let transport = this.createTransport(name);
let failed = false;
SocketWithoutUpgrade.priorWebsocketSuccess = false;
const onTransportOpen = () => {
if (failed)
return;
transport.send([{ type: "ping", data: "probe" }]);
transport.once("packet", (msg) => {
if (failed)
return;
if ("pong" === msg.type && "probe" === msg.data) {
this.upgrading = true;
this.emitReserved("upgrading", transport);
if (!transport)
return;
SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === transport.name;
this.transport.pause(() => {
if (failed)
return;
if ("closed" === this.readyState)
return;
cleanup();
this.setTransport(transport);
transport.send([{ type: "upgrade" }]);
this.emitReserved("upgrade", transport);
transport = null;
this.upgrading = false;
this.flush();
});
} else {
const err = new Error("probe error");
err.transport = transport.name;
this.emitReserved("upgradeError", err);
}
});
};
function freezeTransport() {
if (failed)
return;
failed = true;
cleanup();
transport.close();
transport = null;
}
const onerror = (err) => {
const error = new Error("probe error: " + err);
error.transport = transport.name;
freezeTransport();
this.emitReserved("upgradeError", error);
};
function onTransportClose() {
onerror("transport closed");
}
function onclose() {
onerror("socket closed");
}
function onupgrade(to) {
if (transport && to.name !== transport.name) {
freezeTransport();
}
}
const cleanup = () => {
transport.removeListener("open", onTransportOpen);
transport.removeListener("error", onerror);
transport.removeListener("close", onTransportClose);
this.off("close", onclose);
this.off("upgrading", onupgrade);
};
transport.once("open", onTransportOpen);
transport.once("error", onerror);
transport.once("close", onTransportClose);
this.once("close", onclose);
this.once("upgrading", onupgrade);
if (this._upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") {
this.setTimeoutFn(() => {
if (!failed) {
transport.open();
}
}, 200);
} else {
transport.open();
}
}
onHandshake(data) {
this._upgrades = this._filterUpgrades(data.upgrades);
super.onHandshake(data);
}
/**
* Filters upgrades, returning only those matching client transports.
*
* @param {Array} upgrades - server upgrades
* @private
*/
_filterUpgrades(upgrades) {
const filteredUpgrades = [];
for (let i2 = 0; i2 < upgrades.length; i2++) {
if (~this.transports.indexOf(upgrades[i2]))
filteredUpgrades.push(upgrades[i2]);
}
return filteredUpgrades;
}
}
let Socket$1 = class Socket extends SocketWithUpgrade {
constructor(uri, opts = {}) {
const o2 = typeof uri === "object" ? uri : opts;
if (!o2.transports || o2.transports && typeof o2.transports[0] === "string") {
o2.transports = (o2.transports || ["polling", "websocket", "webtransport"]).map((transportName) => transports[transportName]).filter((t2) => !!t2);
}
super(uri, o2);
}
};
function url(uri, path = "", loc) {
let obj = uri;
loc = loc || typeof location !== "undefined" && location;
if (null == uri)
uri = loc.protocol + "//" + loc.host;
if (typeof uri === "string") {
if ("/" === uri.charAt(0)) {
if ("/" === uri.charAt(1)) {
uri = loc.protocol + uri;
} else {
uri = loc.host + uri;
}
}
if (!/^(https?|wss?):\/\//.test(uri)) {
if ("undefined" !== typeof loc) {
uri = loc.protocol + "//" + uri;
} else {
uri = "https://" + uri;
}
}
obj = parse(uri);
}
if (!obj.port) {
if (/^(http|ws)$/.test(obj.protocol)) {
obj.port = "80";
} else if (/^(http|ws)s$/.test(obj.protocol)) {
obj.port = "443";
}
}
obj.path = obj.path || "/";
const ipv6 = obj.host.indexOf(":") !== -1;
const host = ipv6 ? "[" + obj.host + "]" : obj.host;
obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
return obj;
}
const withNativeArrayBuffer = typeof ArrayBuffer === "function";
const isView = (obj) => {
return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
};
const toString = Object.prototype.toString;
const withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]";
const withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]";
function isBinary(obj) {
return withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)) || withNativeBlob && obj instanceof Blob || withNativeFile && obj instanceof File;
}
function hasBinary(obj, toJSON) {
if (!obj || typeof obj !== "object") {
return false;
}
if (Array.isArray(obj)) {
for (let i2 = 0, l2 = obj.length; i2 < l2; i2++) {
if (hasBinary(obj[i2])) {
return true;
}
}
return false;
}
if (isBinary(obj)) {
return true;
}
if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
return hasBinary(obj.toJSON(), true);
}
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
return true;
}
}
return false;
}
function deconstructPacket(packet) {
const buffers = [];
const packetData = packet.data;
const pack = packet;
pack.data = _deconstructPacket(packetData, buffers);
pack.attachments = buffers.length;
return { packet: pack, buffers };
}
function _deconstructPacket(data, buffers) {
if (!data)
return data;
if (isBinary(data)) {
const placeholder = { _placeholder: true, num: buffers.length };
buffers.push(data);
return placeholder;
} else if (Array.isArray(data)) {
const newData = new Array(data.length);
for (let i2 = 0; i2 < data.length; i2++) {
newData[i2] = _deconstructPacket(data[i2], buffers);
}
return newData;
} else if (typeof data === "object" && !(data instanceof Date)) {
const newData = {};
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
newData[key] = _deconstructPacket(data[key], buffers);
}
}
return newData;
}
return data;
}
function reconstructPacket(packet, buffers) {
packet.data = _reconstructPacket(packet.data, buffers);
delete packet.attachments;
return packet;
}
function _reconstructPacket(data, buffers) {
if (!data)
return data;
if (data && data._placeholder === true) {
const isIndexValid = typeof data.num === "number" && data.num >= 0 && data.num < buffers.length;
if (isIndexValid) {
return buffers[data.num];
} else {
throw new Error("illegal attachments");
}
} else if (Array.isArray(data)) {
for (let i2 = 0; i2 < data.length; i2++) {
data[i2] = _reconstructPacket(data[i2], buffers);
}
} else if (typeof data === "object") {
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
data[key] = _reconstructPacket(data[key], buffers);
}
}
}
return data;
}
const RESERVED_EVENTS$1 = [
"connect",
"connect_error",
"disconnect",
"disconnecting",
"newListener",
"removeListener"
// used by the Node.js EventEmitter
];
const protocol = 5;
var PacketType;
(function(PacketType2) {
PacketType2[PacketType2["CONNECT"] = 0] = "CONNECT";
PacketType2[PacketType2["DISCONNECT"] = 1] = "DISCONNECT";
PacketType2[PacketType2["EVENT"] = 2] = "EVENT";
PacketType2[PacketType2["ACK"] = 3] = "ACK";
PacketType2[PacketType2["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
PacketType2[PacketType2["BINARY_EVENT"] = 5] = "BINARY_EVENT";
PacketType2[PacketType2["BINARY_ACK"] = 6] = "BINARY_ACK";
})(PacketType || (PacketType = {}));
class Encoder {
/**
* Encoder constructor
*
* @param {function} replacer - custom replacer to pass down to JSON.parse
*/
constructor(replacer) {
this.replacer = replacer;
}
/**
* Encode a packet as a single string if non-binary, or as a
* buffer sequence, depending on packet type.
*
* @param {Object} obj - packet object
*/
encode(obj) {
if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
if (hasBinary(obj)) {
return this.encodeAsBinary({
type: obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK,
nsp: obj.nsp,
data: obj.data,
id: obj.id
});
}
}
return [this.encodeAsString(obj)];
}
/**
* Encode packet as string.
*/
encodeAsString(obj) {
let str = "" + obj.type;
if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) {
str += obj.attachments + "-";
}
if (obj.nsp && "/" !== obj.nsp) {
str += obj.nsp + ",";
}
if (null != obj.id) {
str += obj.id;
}
if (null != obj.data) {
str += JSON.stringify(obj.data, this.replacer);
}
return str;
}
/**
* Encode packet as 'buffer sequence' by removing blobs, and
* deconstructing packet into object with placeholders and
* a list of buffers.
*/
encodeAsBinary(obj) {
const deconstruction = deconstructPacket(obj);
const pack = this.encodeAsString(deconstruction.packet);
const buffers = deconstruction.buffers;
buffers.unshift(pack);
return buffers;
}
}
function isObject(value2) {
return Object.prototype.toString.call(value2) === "[object Object]";
}
class Decoder extends Emitter {
/**
* Decoder constructor
*
* @param {function} reviver - custom reviver to pass down to JSON.stringify
*/
constructor(reviver) {
super();
this.reviver = reviver;
}
/**
* Decodes an encoded packet string into packet JSON.
*
* @param {String} obj - encoded packet
*/
add(obj) {
let packet;
if (typeof obj === "string") {
if (this.reconstructor) {
throw new Error("got plaintext data when reconstructing a packet");
}
packet = this.decodeString(obj);
const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
this.reconstructor = new BinaryReconstructor(packet);
if (packet.attachments === 0) {
super.emitReserved("decoded", packet);
}
} else {
super.emitReserved("decoded", packet);
}
} else if (isBinary(obj) || obj.base64) {
if (!this.reconstructor) {
throw new Error("got binary data when not reconstructing a packet");
} else {
packet = this.reconstructor.takeBinaryData(obj);
if (packet) {
this.reconstructor = null;
super.emitReserved("decoded", packet);
}
}
} else {
throw new Error("Unknown type: " + obj);
}
}
/**
* Decode a packet String (JSON data)
*
* @param {String} str
* @return {Object} packet
*/
decodeString(str) {
let i2 = 0;
const p = {
type: Number(str.charAt(0))
};
if (PacketType[p.type] === void 0) {
throw new Error("unknown packet type " + p.type);
}
if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
const start = i2 + 1;
while (str.charAt(++i2) !== "-" && i2 != str.length) {
}
const buf = str.substring(start, i2);
if (buf != Number(buf) || str.charAt(i2) !== "-") {
throw new Error("Illegal attachments");
}
p.attachments = Number(buf);
}
if ("/" === str.charAt(i2 + 1)) {
const start = i2 + 1;
while (++i2) {
const c2 = str.charAt(i2);
if ("," === c2)
break;
if (i2 === str.length)
break;
}
p.nsp = str.substring(start, i2);
} else {
p.nsp = "/";
}
const next = str.charAt(i2 + 1);
if ("" !== next && Number(next) == next) {
const start = i2 + 1;
while (++i2) {
const c2 = str.charAt(i2);
if (null == c2 || Number(c2) != c2) {
--i2;
break;
}
if (i2 === str.length)
break;
}
p.id = Number(str.substring(start, i2 + 1));
}
if (str.charAt(++i2)) {
const payload = this.tryParse(str.substr(i2));
if (Decoder.isPayloadValid(p.type, payload)) {
p.data = payload;
} else {
throw new Error("invalid payload");
}
}
return p;
}
tryParse(str) {
try {
return JSON.parse(str, this.reviver);
} catch (e2) {
return false;
}
}
static isPayloadValid(type, payload) {
switch (type) {
case PacketType.CONNECT:
return isObject(payload);
case PacketType.DISCONNECT:
return payload === void 0;
case PacketType.CONNECT_ERROR:
return typeof payload === "string" || isObject(payload);
case PacketType.EVENT:
case PacketType.BINARY_EVENT:
return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS$1.indexOf(payload[0]) === -1);
case PacketType.ACK:
case PacketType.BINARY_ACK:
return Array.isArray(payload);
}
}
/**
* Deallocates a parser's resources
*/
destroy() {
if (this.reconstructor) {
this.reconstructor.finishedReconstruction();
this.reconstructor = null;
}
}
}
class BinaryReconstructor {
constructor(packet) {
this.packet = packet;
this.buffers = [];
this.reconPack = packet;
}
/**
* Method to be called when binary data received from connection
* after a BINARY_EVENT packet.
*
* @param {Buffer | ArrayBuffer} binData - the raw binary data received
* @return {null | Object} returns null if more binary data is expected or
* a reconstructed packet object if all buffers have been received.
*/
takeBinaryData(binData) {
this.buffers.push(binData);
if (this.buffers.length === this.reconPack.attachments) {
const packet = reconstructPacket(this.reconPack, this.buffers);
this.finishedReconstruction();
return packet;
}
return null;
}
/**
* Cleans up binary packet reconstruction variables.
*/
finishedReconstruction() {
this.reconPack = null;
this.buffers = [];
}
}
const parser = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
Decoder,
Encoder,
get PacketType() {
return PacketType;
},
protocol
}, Symbol.toStringTag, { value: "Module" }));
function on(obj, ev, fn) {
obj.on(ev, fn);
return function subDestroy() {
obj.off(ev, fn);
};
}
const RESERVED_EVENTS = Object.freeze({
connect: 1,
connect_error: 1,
disconnect: 1,
disconnecting: 1,
// EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
newListener: 1,
removeListener: 1
});
class Socket2 extends Emitter {
/**
* `Socket` constructor.
*/
constructor(io, nsp, opts) {
super();
this.connected = false;
this.recovered = false;
this.receiveBuffer = [];
this.sendBuffer = [];
this._queue = [];
this._queueSeq = 0;
this.ids = 0;
this.acks = {};
this.flags = {};
this.io = io;
this.nsp = nsp;
if (opts && opts.auth) {
this.auth = opts.auth;
}
this._opts = Object.assign({}, opts);
if (this.io._autoConnect)
this.open();
}
/**
* Whether the socket is currently disconnected
*
* @example
* const socket = io();
*
* socket.on("connect", () => {
* console.log(socket.disconnected); // false
* });
*
* socket.on("disconnect", () => {
* console.log(socket.disconnected); // true
* });
*/
get disconnected() {
return !this.connected;
}
/**
* Subscribe to open, close and packet events
*
* @private
*/
subEvents() {
if (this.subs)
return;
const io = this.io;
this.subs = [
on(io, "open", this.onopen.bind(this)),
on(io, "packet", this.onpacket.bind(this)),
on(io, "error", this.onerror.bind(this)),
on(io, "close", this.onclose.bind(this))
];
}
/**
* Whether the Socket will try to reconnect when its Manager connects or reconnects.
*
* @example
* const socket = io();
*
* console.log(socket.active); // true
*
* socket.on("disconnect", (reason) => {
* if (reason === "io server disconnect") {
* // the disconnection was initiated by the server, you need to manually reconnect
* console.log(socket.active); // false
* }
* // else the socket will automatically try to reconnect
* console.log(socket.active); // true
* });
*/
get active() {
return !!this.subs;
}
/**
* "Opens" the socket.
*
* @example
* const socket = io({
* autoConnect: false
* });
*
* socket.connect();
*/
connect() {
if (this.connected)
return this;
this.subEvents();
if (!this.io["_reconnecting"])
this.io.open();
if ("open" === this.io._readyState)
this.onopen();
return this;
}
/**
* Alias for {@link connect()}.
*/
open() {
return this.connect();
}
/**
* Sends a `message` event.
*
* This method mimics the WebSocket.send() method.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
*
* @example
* socket.send("hello");
*
* // this is equivalent to
* socket.emit("message", "hello");
*
* @return self
*/
send(...args) {
args.unshift("message");
this.emit.apply(this, args);
return this;
}
/**
* Override `emit`.
* If the event is in `events`, it's emitted normally.
*
* @example
* socket.emit("hello", "world");
*
* // all serializable datastructures are supported (no need to call JSON.stringify)
* socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
*
* // with an acknowledgement from the server
* socket.emit("hello", "world", (val) => {
* // ...
* });
*
* @return self
*/
emit(ev, ...args) {
var _a, _b, _c;
if (RESERVED_EVENTS.hasOwnProperty(ev)) {
throw new Error('"' + ev.toString() + '" is a reserved event name');
}
args.unshift(ev);
if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
this._addToQueue(args);
return this;
}
const packet = {
type: PacketType.EVENT,
data: args
};
packet.options = {};
packet.options.compress = this.flags.compress !== false;
if ("function" === typeof args[args.length - 1]) {
const id = this.ids++;
const ack = args.pop();
this._registerAckCallback(id, ack);
packet.id = id;
}
const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
const discardPacket = this.flags.volatile && !isTransportWritable;
if (discardPacket) ;
else if (isConnected) {
this.notifyOutgoingListeners(packet);
this.packet(packet);
} else {
this.sendBuffer.push(packet);
}
this.flags = {};
return this;
}
/**
* @private
*/
_registerAckCallback(id, ack) {
var _a;
const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
if (timeout === void 0) {
this.acks[id] = ack;
return;
}
const timer = this.io.setTimeoutFn(() => {
delete this.acks[id];
for (let i2 = 0; i2 < this.sendBuffer.length; i2++) {
if (this.sendBuffer[i2].id === id) {
this.sendBuffer.splice(i2, 1);
}
}
ack.call(this, new Error("operation has timed out"));
}, timeout);
const fn = (...args) => {
this.io.clearTimeoutFn(timer);
ack.apply(this, args);
};
fn.withError = true;
this.acks[id] = fn;
}
/**
* Emits an event and waits for an acknowledgement
*
* @example
* // without timeout
* const response = await socket.emitWithAck("hello", "world");
*
* // with a specific timeout
* try {
* const response = await socket.timeout(1000).emitWithAck("hello", "world");
* } catch (err) {
* // the server did not acknowledge the event in the given delay
* }
*
* @return a Promise that will be fulfilled when the server acknowledges the event
*/
emitWithAck(ev, ...args) {
return new Promise((resolve, reject) => {
const fn = (arg1, arg2) => {
return arg1 ? reject(arg1) : resolve(arg2);
};
fn.withError = true;
args.push(fn);
this.emit(ev, ...args);
});
}
/**
* Add the packet to the queue.
* @param args
* @private
*/
_addToQueue(args) {
let ack;
if (typeof args[args.length - 1] === "function") {
ack = args.pop();
}
const packet = {
id: this._queueSeq++,
tryCount: 0,
pending: false,
args,
flags: Object.assign({ fromQueue: true }, this.flags)
};
args.push((err, ...responseArgs) => {
if (packet !== this._queue[0]) {
return;
}
const hasError = err !== null;
if (hasError) {
if (packet.tryCount > this._opts.retries) {
this._queue.shift();
if (ack) {
ack(err);
}
}
} else {
this._queue.shift();
if (ack) {
ack(null, ...responseArgs);
}
}
packet.pending = false;
return this._drainQueue();
});
this._queue.push(packet);
this._drainQueue();
}
/**
* Send the first packet of the queue, and wait for an acknowledgement from the server.
* @param force - whether to resend a packet that has not been acknowledged yet
*
* @private
*/
_drainQueue(force = false) {
if (!this.connected || this._queue.length === 0) {
return;
}
const packet = this._queue[0];
if (packet.pending && !force) {
return;
}
packet.pending = true;
packet.tryCount++;
this.flags = packet.flags;
this.emit.apply(this, packet.args);
}
/**
* Sends a packet.
*
* @param packet
* @private
*/
packet(packet) {
packet.nsp = this.nsp;
this.io._packet(packet);
}
/**
* Called upon engine `open`.
*
* @private
*/
onopen() {
if (typeof this.auth == "function") {
this.auth((data) => {
this._sendConnectPacket(data);
});
} else {
this._sendConnectPacket(this.auth);
}
}
/**
* Sends a CONNECT packet to initiate the Socket.IO session.
*
* @param data
* @private
*/
_sendConnectPacket(data) {
this.packet({
type: PacketType.CONNECT,
data: this._pid ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data) : data
});
}
/**
* Called upon engine or manager `error`.
*
* @param err
* @private
*/
onerror(err) {
if (!this.connected) {
this.emitReserved("connect_error", err);
}
}
/**
* Called upon engine `close`.
*
* @param reason
* @param description
* @private
*/
onclose(reason, description) {
this.connected = false;
delete this.id;
this.emitReserved("disconnect", reason, description);
this._clearAcks();
}
/**
* Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
* the server.
*
* @private
*/
_clearAcks() {
Object.keys(this.acks).forEach((id) => {
const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
if (!isBuffered) {
const ack = this.acks[id];
delete this.acks[id];
if (ack.withError) {
ack.call(this, new Error("socket has been disconnected"));
}
}
});
}
/**
* Called with socket packet.
*
* @param packet
* @private
*/
onpacket(packet) {
const sameNamespace = packet.nsp === this.nsp;
if (!sameNamespace)
return;
switch (packet.type) {
case PacketType.CONNECT:
if (packet.data && packet.data.sid) {
this.onconnect(packet.data.sid, packet.data.pid);
} else {
this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
}
break;
case PacketType.EVENT:
case PacketType.BINARY_EVENT:
this.onevent(packet);
break;
case PacketType.ACK:
case PacketType.BINARY_ACK:
this.onack(packet);
break;
case PacketType.DISCONNECT:
this.ondisconnect();
break;
case PacketType.CONNECT_ERROR:
this.destroy();
const err = new Error(packet.data.message);
err.data = packet.data.data;
this.emitReserved("connect_error", err);
break;
}
}
/**
* Called upon a server event.
*
* @param packet
* @private
*/
onevent(packet) {
const args = packet.data || [];
if (null != packet.id) {
args.push(this.ack(packet.id));
}
if (this.connected) {
this.emitEvent(args);
} else {
this.receiveBuffer.push(Object.freeze(args));
}
}
emitEvent(args) {
if (this._anyListeners && this._anyListeners.length) {
const listeners = this._anyListeners.slice();
for (const listener of listeners) {
listener.apply(this, args);
}
}
super.emit.apply(this, args);
if (this._pid && args.length && typeof args[args.length - 1] === "string") {
this._lastOffset = args[args.length - 1];
}
}
/**
* Produces an ack callback to emit with an event.
*
* @private
*/
ack(id) {
const self2 = this;
let sent = false;
return function(...args) {
if (sent)
return;
sent = true;
self2.packet({
type: PacketType.ACK,
id,
data: args
});
};
}
/**
* Called upon a server acknowledgement.
*
* @param packet
* @private
*/
onack(packet) {
const ack = this.acks[packet.id];
if (typeof ack !== "function") {
return;
}
delete this.acks[packet.id];
if (ack.withError) {
packet.data.unshift(null);
}
ack.apply(this, packet.data);
}
/**
* Called upon server connect.
*
* @private
*/
onconnect(id, pid) {
this.id = id;
this.recovered = pid && this._pid === pid;
this._pid = pid;
this.connected = true;
this.emitBuffered();
this.emitReserved("connect");
this._drainQueue(true);
}
/**
* Emit buffered events (received and emitted).
*
* @private
*/
emitBuffered() {
this.receiveBuffer.forEach((args) => this.emitEvent(args));
this.receiveBuffer = [];
this.sendBuffer.forEach((packet) => {
this.notifyOutgoingListeners(packet);
this.packet(packet);
});
this.sendBuffer = [];
}
/**
* Called upon server disconnect.
*
* @private
*/
ondisconnect() {
this.destroy();
this.onclose("io server disconnect");
}
/**
* Called upon forced client/server side disconnections,
* this method ensures the manager stops tracking us and
* that reconnections don't get triggered for this.
*
* @private
*/
destroy() {
if (this.subs) {
this.subs.forEach((subDestroy) => subDestroy());
this.subs = void 0;
}
this.io["_destroy"](this);
}
/**
* Disconnects the socket manually. In that case, the socket will not try to reconnect.
*
* If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
*
* @example
* const socket = io();
*
* socket.on("disconnect", (reason) => {
* // console.log(reason); prints "io client disconnect"
* });
*
* socket.disconnect();
*
* @return self
*/
disconnect() {
if (this.connected) {
this.packet({ type: PacketType.DISCONNECT });
}
this.destroy();
if (this.connected) {
this.onclose("io client disconnect");
}
return this;
}
/**
* Alias for {@link disconnect()}.
*
* @return self
*/
close() {
return this.disconnect();
}
/**
* Sets the compress flag.
*
* @example
* socket.compress(false).emit("hello");
*
* @param compress - if `true`, compresses the sending data
* @return self
*/
compress(compress) {
this.flags.compress = compress;
return this;
}
/**
* Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
* ready to send messages.
*
* @example
* socket.volatile.emit("hello"); // the server may or may not receive it
*
* @returns self
*/
get volatile() {
this.flags.volatile = true;
return this;
}
/**
* Sets a modifier for a subsequent event emission that the callback will be called with an error when the
* given number of milliseconds have elapsed without an acknowledgement from the server:
*
* @example
* socket.timeout(5000).emit("my-event", (err) => {
* if (err) {
* // the server did not acknowledge the event in the given delay
* }
* });
*
* @returns self
*/
timeout(timeout) {
this.flags.timeout = timeout;
return this;
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback.
*
* @example
* socket.onAny((event, ...args) => {
* console.log(`got ${event}`);
* });
*
* @param listener
*/
onAny(listener) {
this._anyListeners = this._anyListeners || [];
this._anyListeners.push(listener);
return this;
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback. The listener is added to the beginning of the listeners array.
*
* @example
* socket.prependAny((event, ...args) => {
* console.log(`got event ${event}`);
* });
*
* @param listener
*/
prependAny(listener) {
this._anyListeners = this._anyListeners || [];
this._anyListeners.unshift(listener);
return this;
}
/**
* Removes the listener that will be fired when any event is emitted.
*
* @example
* const catchAllListener = (event, ...args) => {
* console.log(`got event ${event}`);
* }
*
* socket.onAny(catchAllListener);
*
* // remove a specific listener
* socket.offAny(catchAllListener);
*
* // or remove all listeners
* socket.offAny();
*
* @param listener
*/
offAny(listener) {
if (!this._anyListeners) {
return this;
}
if (listener) {
const listeners = this._anyListeners;
for (let i2 = 0; i2 < listeners.length; i2++) {
if (listener === listeners[i2]) {
listeners.splice(i2, 1);
return this;
}
}
} else {
this._anyListeners = [];
}
return this;
}
/**
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
* e.g. to remove listeners.
*/
listenersAny() {
return this._anyListeners || [];
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback.
*
* Note: acknowledgements sent to the server are not included.
*
* @example
* socket.onAnyOutgoing((event, ...args) => {
* console.log(`sent event ${event}`);
* });
*
* @param listener
*/
onAnyOutgoing(listener) {
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
this._anyOutgoingListeners.push(listener);
return this;
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback. The listener is added to the beginning of the listeners array.
*
* Note: acknowledgements sent to the server are not included.
*
* @example
* socket.prependAnyOutgoing((event, ...args) => {
* console.log(`sent event ${event}`);
* });
*
* @param listener
*/
prependAnyOutgoing(listener) {
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
this._anyOutgoingListeners.unshift(listener);
return this;
}
/**
* Removes the listener that will be fired when any event is emitted.
*
* @example
* const catchAllListener = (event, ...args) => {
* console.log(`sent event ${event}`);
* }
*
* socket.onAnyOutgoing(catchAllListener);
*
* // remove a specific listener
* socket.offAnyOutgoing(catchAllListener);
*
* // or remove all listeners
* socket.offAnyOutgoing();
*
* @param [listener] - the catch-all listener (optional)
*/
offAnyOutgoing(listener) {
if (!this._anyOutgoingListeners) {
return this;
}
if (listener) {
const listeners = this._anyOutgoingListeners;
for (let i2 = 0; i2 < listeners.length; i2++) {
if (listener === listeners[i2]) {
listeners.splice(i2, 1);
return this;
}
}
} else {
this._anyOutgoingListeners = [];
}
return this;
}
/**
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
* e.g. to remove listeners.
*/
listenersAnyOutgoing() {
return this._anyOutgoingListeners || [];
}
/**
* Notify the listeners for each packet sent
*
* @param packet
*
* @private
*/
notifyOutgoingListeners(packet) {
if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
const listeners = this._anyOutgoingListeners.slice();
for (const listener of listeners) {
listener.apply(this, packet.data);
}
}
}
}
function Backoff(opts) {
opts = opts || {};
this.ms = opts.min || 100;
this.max = opts.max || 1e4;
this.factor = opts.factor || 2;
this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
this.attempts = 0;
}
Backoff.prototype.duration = function() {
var ms = this.ms * Math.pow(this.factor, this.attempts++);
if (this.jitter) {
var rand = Math.random();
var deviation = Math.floor(rand * this.jitter * ms);
ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
}
return Math.min(ms, this.max) | 0;
};
Backoff.prototype.reset = function() {
this.attempts = 0;
};
Backoff.prototype.setMin = function(min) {
this.ms = min;
};
Backoff.prototype.setMax = function(max) {
this.max = max;
};
Backoff.prototype.setJitter = function(jitter) {
this.jitter = jitter;
};
class Manager extends Emitter {
constructor(uri, opts) {
var _a;
super();
this.nsps = {};
this.subs = [];
if (uri && "object" === typeof uri) {
opts = uri;
uri = void 0;
}
opts = opts || {};
opts.path = opts.path || "/socket.io";
this.opts = opts;
installTimerFunctions(this, opts);
this.reconnection(opts.reconnection !== false);
this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
this.reconnectionDelay(opts.reconnectionDelay || 1e3);
this.reconnectionDelayMax(opts.reconnectionDelayMax || 5e3);
this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
this.backoff = new Backoff({
min: this.reconnectionDelay(),
max: this.reconnectionDelayMax(),
jitter: this.randomizationFactor()
});
this.timeout(null == opts.timeout ? 2e4 : opts.timeout);
this._readyState = "closed";
this.uri = uri;
const _parser = opts.parser || parser;
this.encoder = new _parser.Encoder();
this.decoder = new _parser.Decoder();
this._autoConnect = opts.autoConnect !== false;
if (this._autoConnect)
this.open();
}
reconnection(v) {
if (!arguments.length)
return this._reconnection;
this._reconnection = !!v;
if (!v) {
this.skipReconnect = true;
}
return this;
}
reconnectionAttempts(v) {
if (v === void 0)
return this._reconnectionAttempts;
this._reconnectionAttempts = v;
return this;
}
reconnectionDelay(v) {
var _a;
if (v === void 0)
return this._reconnectionDelay;
this._reconnectionDelay = v;
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
return this;
}
randomizationFactor(v) {
var _a;
if (v === void 0)
return this._randomizationFactor;
this._randomizationFactor = v;
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
return this;
}
reconnectionDelayMax(v) {
var _a;
if (v === void 0)
return this._reconnectionDelayMax;
this._reconnectionDelayMax = v;
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
return this;
}
timeout(v) {
if (!arguments.length)
return this._timeout;
this._timeout = v;
return this;
}
/**
* Starts trying to reconnect if reconnection is enabled and we have not
* started reconnecting yet
*
* @private
*/
maybeReconnectOnOpen() {
if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
this.reconnect();
}
}
/**
* Sets the current transport `socket`.
*
* @param {Function} fn - optional, callback
* @return self
* @public
*/
open(fn) {
if (~this._readyState.indexOf("open"))
return this;
this.engine = new Socket$1(this.uri, this.opts);
const socket = this.engine;
const self2 = this;
this._readyState = "opening";
this.skipReconnect = false;
const openSubDestroy = on(socket, "open", function() {
self2.onopen();
fn && fn();
});
const onError = (err) => {
this.cleanup();
this._readyState = "closed";
this.emitReserved("error", err);
if (fn) {
fn(err);
} else {
this.maybeReconnectOnOpen();
}
};
const errorSub = on(socket, "error", onError);
if (false !== this._timeout) {
const timeout = this._timeout;
const timer = this.setTimeoutFn(() => {
openSubDestroy();
onError(new Error("timeout"));
socket.close();
}, timeout);
if (this.opts.autoUnref) {
timer.unref();
}
this.subs.push(() => {
this.clearTimeoutFn(timer);
});
}
this.subs.push(openSubDestroy);
this.subs.push(errorSub);
return this;
}
/**
* Alias for open()
*
* @return self
* @public
*/
connect(fn) {
return this.open(fn);
}
/**
* Called upon transport open.
*
* @private
*/
onopen() {
this.cleanup();
this._readyState = "open";
this.emitReserved("open");
const socket = this.engine;
this.subs.push(
on(socket, "ping", this.onping.bind(this)),
on(socket, "data", this.ondata.bind(this)),
on(socket, "error", this.onerror.bind(this)),
on(socket, "close", this.onclose.bind(this)),
// @ts-ignore
on(this.decoder, "decoded", this.ondecoded.bind(this))
);
}
/**
* Called upon a ping.
*
* @private
*/
onping() {
this.emitReserved("ping");
}
/**
* Called with data.
*
* @private
*/
ondata(data) {
try {
this.decoder.add(data);
} catch (e2) {
this.onclose("parse error", e2);
}
}
/**
* Called when parser fully decodes a packet.
*
* @private
*/
ondecoded(packet) {
nextTick(() => {
this.emitReserved("packet", packet);
}, this.setTimeoutFn);
}
/**
* Called upon socket error.
*
* @private
*/
onerror(err) {
this.emitReserved("error", err);
}
/**
* Creates a new socket for the given `nsp`.
*
* @return {Socket}
* @public
*/
socket(nsp, opts) {
let socket = this.nsps[nsp];
if (!socket) {
socket = new Socket2(this, nsp, opts);
this.nsps[nsp] = socket;
} else if (this._autoConnect && !socket.active) {
socket.connect();
}
return socket;
}
/**
* Called upon a socket close.
*
* @param socket
* @private
*/
_destroy(socket) {
const nsps = Object.keys(this.nsps);
for (const nsp of nsps) {
const socket2 = this.nsps[nsp];
if (socket2.active) {
return;
}
}
this._close();
}
/**
* Writes a packet.
*
* @param packet
* @private
*/
_packet(packet) {
const encodedPackets = this.encoder.encode(packet);
for (let i2 = 0; i2 < encodedPackets.length; i2++) {
this.engine.write(encodedPackets[i2], packet.options);
}
}
/**
* Clean up transport subscriptions and packet buffer.
*
* @private
*/
cleanup() {
this.subs.forEach((subDestroy) => subDestroy());
this.subs.length = 0;
this.decoder.destroy();
}
/**
* Close the current socket.
*
* @private
*/
_close() {
this.skipReconnect = true;
this._reconnecting = false;
this.onclose("forced close");
}
/**
* Alias for close()
*
* @private
*/
disconnect() {
return this._close();
}
/**
* Called when:
*
* - the low-level engine is closed
* - the parser encountered a badly formatted packet
* - all sockets are disconnected
*
* @private
*/
onclose(reason, description) {
var _a;
this.cleanup();
(_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
this.backoff.reset();
this._readyState = "closed";
this.emitReserved("close", reason, description);
if (this._reconnection && !this.skipReconnect) {
this.reconnect();
}
}
/**
* Attempt a reconnection.
*
* @private
*/
reconnect() {
if (this._reconnecting || this.skipReconnect)
return this;
const self2 = this;
if (this.backoff.attempts >= this._reconnectionAttempts) {
this.backoff.reset();
this.emitReserved("reconnect_failed");
this._reconnecting = false;
} else {
const delay = this.backoff.duration();
this._reconnecting = true;
const timer = this.setTimeoutFn(() => {
if (self2.skipReconnect)
return;
this.emitReserved("reconnect_attempt", self2.backoff.attempts);
if (self2.skipReconnect)
return;
self2.open((err) => {
if (err) {
self2._reconnecting = false;
self2.reconnect();
this.emitReserved("reconnect_error", err);
} else {
self2.onreconnect();
}
});
}, delay);
if (this.opts.autoUnref) {
timer.unref();
}
this.subs.push(() => {
this.clearTimeoutFn(timer);
});
}
}
/**
* Called upon successful reconnect.
*
* @private
*/
onreconnect() {
const attempt = this.backoff.attempts;
this._reconnecting = false;
this.backoff.reset();
this.emitReserved("reconnect", attempt);
}
}
const cache = {};
function lookup(uri, opts) {
if (typeof uri === "object") {
opts = uri;
uri = void 0;
}
opts = opts || {};
const parsed = url(uri, opts.path || "/socket.io");
const source = parsed.source;
const id = parsed.id;
const path = parsed.path;
const sameNamespace = cache[id] && path in cache[id]["nsps"];
const newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
let io;
if (newConnection) {
io = new Manager(source, opts);
} else {
if (!cache[id]) {
cache[id] = new Manager(source, opts);
}
io = cache[id];
}
if (parsed.query && !opts.query) {
opts.query = parsed.queryKey;
}
return io.socket(parsed.path, opts);
}
Object.assign(lookup, {
Manager,
Socket: Socket2,
io: lookup,
connect: lookup
});
class AlertsService {
_client;
_streamIdentifier = "";
constructor() {
this._client = lookup(window.location.origin, {
withCredentials: true,
transports: ["websocket"]
});
}
setStreamIdentifier(streamIdentifier) {
this._streamIdentifier = streamIdentifier;
}
on(event, callback) {
this._client.on(`${event}:${this._streamIdentifier}`, callback);
}
}
const UPLOAD_EVENT = "upload";
const UPLOAD_FINISHED_EVENT = "upload:finished";
const DOWNLOAD_EVENT = "download";
const DOWNLOAD_FINISHED_EVENT = "download:finished";
class UploadAlertsService extends AlertsService {
onUpload(callback) {
this.on(UPLOAD_EVENT, callback);
}
onUploadFinished(callback) {
this.on(UPLOAD_FINISHED_EVENT, callback);
}
}
const uploadAlertsService = new UploadAlertsService();
const Upload = (props) => {
const { t: t2 } = useTranslation();
const { identity } = useLocalazyIdentity();
const { navigateToPluginRoute } = useRedirectToPluginRoute();
const [isLoading, setIsLoading] = useState(true);
const [modelChanged, setModelChanged] = useState(false);
const [localesIncompatible, setLocalesIncompatible] = useState(false);
const [showUploadFinishedModal, setShowUploadFinishedModal] = useState(false);
const [uploadResult, setUploadResult] = useState({
success: false,
report: []
});
const [isUploading, setIsUploading] = useState(false);
const [strapiDefaultLocale, setStrapiDefaultLocale] = useState(null);
const [localazySourceLanguage, setLocalazySourceLanguage] = useState(null);
const onChangeSettingsClick = () => {
navigateToPluginRoute(PLUGIN_ROUTES.CONTENT_TRANSFER_SETUP);
};
const onUploadClick = async () => {
setIsUploading(true);
setShowUploadFinishedModal(false);
setUploadResult({
success: false,
report: []
});
const result = await LocalazyUploadService.upload();
const { streamIdentifier } = result;
uploadAlertsService.setStreamIdentifier(streamIdentifier);
uploadAlertsService.onUpload((data) => {
setUploadResult((old) => {
return {
success: data.success,
report: [...old.report || [], data.message]
};
});
});
uploadAlertsService.onUploadFinished((data) => {
setUploadResult((old) => {
return {
success: data.success,
report: [...old.report || [], data.message]
};
});
setIsUploading(false);
setShowUploadFinishedModal(true);
});
ProductAnalyticsService.trackUploadToLocalazy(identity.user.id, identity.project, {
"Source Language Code": localazySourceLanguage.code
});
};
useEffect(() => {
async function initComponent() {
setIsLoading(true);
setStrapiDefaultLocale(await getStrapiDefaultLocale());
setLocalazySourceLanguage(await getLocalazySourceLanguage());
setModelChanged(await hasModelChanged());
setLocalesIncompatible(!await areLocalesCompatible(strapiDefaultLocale, localazySourceLanguage));
PluginSettingsService.updatePluginSettings({ defaultRoute: PLUGIN_ROUTES.UPLOAD });
setIsLoading(false);
}
initComponent();
}, []);
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(
Layouts.Header,
{
title: props.title,
subtitle: props.subtitle,
primaryAction: /* @__PURE__ */ jsx(
Button,
{
startIcon: /* @__PURE__ */ jsx(ForwardRef$d, {}),
disabled: isLoading || modelChanged || localesIncompatible,
loading: isUploading,
onClick: onUploadClick,
children: t2("upload.upload_to_localazy")
}
),
as: "h2"
}
),
isLoading && /* @__PURE__ */ jsx(PluginPageLoader, {}),
!isLoading && /* @__PURE__ */ jsxs(Box, { paddingRight: 10, paddingLeft: 10, children: [
/* @__PURE__ */ jsxs(
Box,
{
background: "neutral0",
paddingTop: 6,
paddingRight: 7,
paddingBottom: 6,
paddingLeft: 7,
hasRadius: true,
shadow: "tableShadow",
children: [
/* @__PURE__ */ jsxs(
Grid.Root,
{
gap: {
desktop: 5,
tablet: 2,
mobile: 1
},
children: [
/* @__PURE__ */ jsx(Grid.Item, { children: /* @__PURE__ */ jsx(OverviewItem, { label: t2("upload.default_strapi_language"), value: strapiDefaultLocale.name }) }),
/* @__PURE__ */ jsx(Grid.Item, { children: /* @__PURE__ */ jsx(OverviewItem, { label: t2("upload.localazy_source_language"), value: localazySourceLanguage.name }) })
]
}
),
/* @__PURE__ */ jsx(Box, { paddingTop: 4, paddingBottom: 4, children: /* @__PURE__ */ jsx(Divider, {}) }),
/* @__PURE__ */ jsx(PrerequisitiesInfo, {}),
/* @__PURE__ */ jsx(Box, { marginTop: 4, children: /* @__PURE__ */ jsxs(Flex, { gap: "2", children: [
/* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: onChangeSettingsClick, children: t2("upload.change_settings") }),
/* @__PURE__ */ jsx(ReadDocsButton, {})
] }) })
]
}
),
showUploadFinishedModal && /* @__PURE__ */ jsx(Box, { marginTop: 4, marginBottom: 4, children: /* @__PURE__ */ jsx(
Alert,
{
onClose: () => setShowUploadFinishedModal(false),
closeLabel: t2("upload.close"),
title: t2("upload.upload_result"),
variant: uploadResult.success ? "success" : "danger",
children: uploadResult.success ? t2("upload.upload_success") : t2("upload.upload_failed")
}
) }),
isUploading && /* @__PURE__ */ jsx(Box, { marginTop: 4, marginBottom: 4, children: /* @__PURE__ */ jsx(Alert, { title: t2("upload.upload_in_progress"), variant: "warning", children: t2("upload.to_see_to_progress") }) }),
localesIncompatible && /* @__PURE__ */ jsx(Box, { marginTop: 4, marginBottom: 4, children: /* @__PURE__ */ jsx(
Alert,
{
onClose: () => setLocalesIncompatible(false),
closeLabel: t2("upload.close"),
title: t2("upload.languages_incompatible"),
variant: "danger",
children: t2("upload.languages_incompatible_message")
}
) }),
modelChanged && /* @__PURE__ */ jsx(Box, { marginTop: 4, marginBottom: 4, children: /* @__PURE__ */ jsx(
Alert,
{
onClose: () => setModelChanged(false),
closeLabel: t2("upload.close"),
title: t2("upload.content_types_model_changed"),
variant: "default",
children: t2("upload.please_update_your_content")
}
) }),
uploadResult.report && uploadResult.report.length > 0 && /* @__PURE__ */ jsx(TransferReport, { report: uploadResult.report })
] })
] });
};
const BASE_PATH = "/transfer";
class LocalazyDownloadService {
static async download(data = {}) {
try {
const strapiApiInstance2 = createStrapiApiAxiosInstance();
const result = await strapiApiInstance2.post(`${BASE_PATH}/download`, data);
return result.data;
} catch (e2) {
throw e2.data;
}
}
}
class DownloadAlertsService extends AlertsService {
onDownload(callback) {
this.on(DOWNLOAD_EVENT, callback);
}
onDownloadFinished(callback) {
this.on(DOWNLOAD_FINISHED_EVENT, callback);
}
}
const downloadAlertsService = new DownloadAlertsService();
const Download = (props) => {
const { t: t2 } = useTranslation();
const { identity } = useLocalazyIdentity();
const [isLoading, setIsLoading] = useState(true);
const [modelChanged, setModelChanged] = useState(false);
const [localesIncompatible, setLocalesIncompatible] = useState(false);
const [showDownloadFinishedModal, setshowDownloadFinishedModal] = useState(false);
const [downloadResult, setDownloadResult] = useState({
success: false,
report: []
});
const [isDownloading, setIsDownloading] = useState(false);
const onTranslateInLocalazyClick = () => {
window.open(identity.project.url, "_blank");
};
const [projectLanguages, setProjectLanguages] = useState([]);
const [formModel, setFormModel] = useState({});
const onDownloadLanguagesChange = (languages) => {
const newFormModel = cloneDeep(formModel);
set(newFormModel, "download.uiLanguages", languages);
setFormModel(newFormModel);
try {
PluginSettingsService.updatePluginSettings(newFormModel);
} catch (e2) {
console.error(e2.message);
}
};
const onDownloadClick = async () => {
setIsDownloading(true);
setshowDownloadFinishedModal(false);
setDownloadResult({
success: false,
report: []
});
const result = await LocalazyDownloadService.download();
const { streamIdentifier } = result;
downloadAlertsService.setStreamIdentifier(streamIdentifier);
downloadAlertsService.onDownload((data) => {
setDownloadResult((old) => ({
success: data.success,
report: [...old.report || [], data.message]
}));
});
downloadAlertsService.onDownloadFinished((data) => {
setDownloadResult((old) => ({
success: data.success,
report: [...old.report || [], data.message]
}));
setIsDownloading(false);
setshowDownloadFinishedModal(true);
});
ProductAnalyticsService.trackDownloadToStrapi(identity.user.id, identity.project, {
"Target Languages Codes": "all"
});
};
useEffect(() => {
async function initComponent() {
setIsLoading(true);
setModelChanged(await hasModelChanged());
setLocalesIncompatible(!await areLocalesCompatible());
const project = await ProjectService.getConnectedProject();
const projectLanguagesWithoutDefaultLanguage = project?.languages?.filter((language) => language.id !== project.sourceLanguage) || [];
setProjectLanguages(projectLanguagesWithoutDefaultLanguage);
const globalSettings = await PluginSettingsService.getPluginSettings();
setFormModel(globalSettings);
PluginSettingsService.updatePluginSettings({ defaultRoute: PLUGIN_ROUTES.DOWNLOAD });
setIsLoading(false);
}
initComponent();
}, []);
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(
Layouts.Header,
{
title: props.title,
subtitle: props.subtitle,
primaryAction: /* @__PURE__ */ jsx(
Button,
{
startIcon: /* @__PURE__ */ jsx(ForwardRef$3P, {}),
disabled: isLoading || modelChanged || localesIncompatible,
loading: isDownloading,
onClick: onDownloadClick,
children: t2("download.download_to_strapi")
}
),
as: "h2"
}
),
isLoading && /* @__PURE__ */ jsx(PluginPageLoader, {}),
!isLoading && /* @__PURE__ */ jsxs(Box, { paddingRight: 10, paddingLeft: 10, children: [
/* @__PURE__ */ jsxs(
Box,
{
background: "neutral0",
paddingTop: 6,
paddingRight: 7,
paddingBottom: 6,
paddingLeft: 7,
hasRadius: true,
shadow: "tableShadow",
children: [
/* @__PURE__ */ jsx(Typography, { variant: "omega", children: t2("download.download_note_a") }),
/* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "semiBold", children: t2("download.download_note_b") }),
/* @__PURE__ */ jsx("br", {}),
/* @__PURE__ */ jsx("br", {}),
/* @__PURE__ */ jsx(Typography, { variant: "omega", children: t2("download.make_sure_note_a") }),
/* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "semiBold", children: t2("download.make_sure_note_b") }),
/* @__PURE__ */ jsx(Typography, { variant: "omega", children: t2("download.make_sure_note_c") }),
/* @__PURE__ */ jsx(Box, { paddingTop: 6, children: /* @__PURE__ */ jsx(
LanguagesSelector,
{
preselectedLanguages: formModel?.download?.uiLanguages || [],
projectLanguages,
onChange: (languages) => onDownloadLanguagesChange(languages),
label: t2("download.ui_languages"),
hint: t2("download.ui_languages_info"),
placeholder: t2("download.ui_languages_placeholder")
}
) }),
/* @__PURE__ */ jsx(Box, { paddingTop: 4, paddingBottom: 4, children: /* @__PURE__ */ jsx(Divider, {}) }),
/* @__PURE__ */ jsx(Box, { marginTop: 2, children: /* @__PURE__ */ jsxs(Flex, { gap: "2", children: [
/* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: onTranslateInLocalazyClick, children: t2("download.translate_in_localazy") }),
/* @__PURE__ */ jsx(ReadDocsButton, {})
] }) })
]
}
),
showDownloadFinishedModal && /* @__PURE__ */ jsx(Box, { marginTop: 4, marginBottom: 4, children: /* @__PURE__ */ jsx(
Alert,
{
onClose: () => setshowDownloadFinishedModal(false),
closeLabel: t2("download.close"),
title: t2("download.download_result"),
variant: downloadResult.success ? "success" : "danger",
children: downloadResult.success ? t2("download.download_success") : t2("download.download_failed")
}
) }),
isDownloading && /* @__PURE__ */ jsx(Box, { marginTop: 4, marginBottom: 4, children: /* @__PURE__ */ jsx(Alert, { title: t2("download.download_in_progress"), variant: "warning", children: t2("download.to_see_to_progress") }) }),
localesIncompatible && /* @__PURE__ */ jsx(Box, { marginTop: 4, marginBottom: 4, children: /* @__PURE__ */ jsx(
Alert,
{
onClose: () => setLocalesIncompatible(false),
closeLabel: t2("download.close"),
title: t2("download.languages_incompatible"),
variant: "danger",
children: t2("download.languages_incompatible_message")
}
) }),
modelChanged && /* @__PURE__ */ jsx(Box, { marginTop: 4, marginBottom: 4, children: /* @__PURE__ */ jsx(
Alert,
{
onClose: () => setModelChanged(false),
closeLabel: t2("download.close"),
title: t2("download.content_types_model_changed"),
variant: "default",
children: t2("download.please_update_your_content")
}
) }),
downloadResult.report && downloadResult.report.length > 0 && /* @__PURE__ */ jsx(TransferReport, { report: downloadResult.report })
] })
] });
};
const App = () => {
const { navigateToPluginRoute } = useRedirectToPluginRoute();
const { isLoggedIn, isFetchingIdentity } = useLocalazyIdentity();
const headerTitle = useHeaderTitle();
const headerSubtitle = useHeaderSubtitle();
useEffect(() => {
const fetchData = async () => {
if (isFetchingIdentity) {
return;
}
if (!isLoggedIn) {
navigateToPluginRoute(PLUGIN_ROUTES.LOGIN);
} else {
const lastRoute = (await PluginSettingsService.getPluginSettings()).defaultRoute || PLUGIN_ROUTES.UPLOAD;
navigateToPluginRoute(lastRoute);
}
};
fetchData();
}, [isLoggedIn, isFetchingIdentity]);
return /* @__PURE__ */ jsx(DesignSystemProvider, { theme: getDefaultTheme(), children: /* @__PURE__ */ jsx(Box, { background: "neutral100", children: /* @__PURE__ */ jsxs(Layouts.Root, { sideNav: isLoggedIn && /* @__PURE__ */ jsx(SideNav, {}), children: [
isFetchingIdentity && /* @__PURE__ */ jsx(PluginPageLoader, {}),
/* @__PURE__ */ jsxs(Routes, { children: [
/* @__PURE__ */ jsx(Route, { path: `login`, element: /* @__PURE__ */ jsx(Login, { title: headerTitle, subtitle: headerSubtitle, isLoading: false }) }),
/* @__PURE__ */ jsx(
Route,
{
path: `overview`,
element: /* @__PURE__ */ jsx(Overview, { title: headerTitle, subtitle: headerSubtitle, isLoadingProp: false })
}
),
/* @__PURE__ */ jsx(Route, { path: `upload`, element: /* @__PURE__ */ jsx(Upload, { title: headerTitle, subtitle: headerSubtitle }) }),
/* @__PURE__ */ jsx(Route, { path: `download`, element: /* @__PURE__ */ jsx(Download, { title: headerTitle, subtitle: headerSubtitle }) }),
/* @__PURE__ */ jsx(Route, { path: "*", element: /* @__PURE__ */ jsx(Page.Error, {}) })
] })
] }) }) });
};
export {
App
};