strapi-plugin-firebase-authentication
Version:
Allows easy integration between clients utilizing Firebase for authentication and Strapi
6,342 lines • 215 kB
JavaScript
import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import { Layouts, useQueryParams as useQueryParams$1, getFetchClient, Pagination, useNotification, Page } from "@strapi/strapi/admin";
import { useNavigate, useLocation, useParams, Routes, Route } from "react-router-dom";
import { Provider } from "@radix-ui/react-tooltip";
import m__default, { useState, useCallback, useMemo, useEffect, useRef, useLayoutEffect } from "react";
import { z as zc, T, R, N as Nn, A as Ar, S as S1, k as k1, a as A1, b as Tr, E, t as t1, v as v1, C as C1, $ as $1, c as bo, w as wo, h as h0, d as a0, o as ot, K as Km, x as x1, G as G0, e as vm, g as getFirebaseConfig$1, F as Fm, D as D1, p as pl } from "./api-CLQa5PFi.mjs";
import { useIntl } from "react-intl";
import { i as isArguments_1, a as isBufferExports, b as isTypedArray_1, c as isLength_1, d as isFunction_1, _ as _getTag, e as _Stack, f as _equalArrays, g as _equalByTag, h as isObjectLike_1, j as getDefaultExportFromCjs, U as U2, k as _baseGetTag, l as _MapCache, m as _Symbol, n as m3, o as bn, N as Nn$1, Y as Y2, J as J2, P as PLUGIN_ID, p as getAugmentedNamespace, q as commonjsGlobal, u as un, s as sn, r as _3 } from "./index-B2NvsXdF.mjs";
import styled from "styled-components";
import { RxCheck, RxCross2 } from "react-icons/rx";
import { AiOutlineUserAdd, AiFillPhone, AiFillMail, AiFillYahoo, AiFillGithub, AiFillTwitterCircle, AiFillFacebook, AiFillApple, AiFillGoogleCircle } from "react-icons/ai";
import { MdPassword } from "react-icons/md";
import * as PhoneInputModule from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";
import validator from "validator";
function arrayPush$1(array, values) {
var index = -1, length = values.length, offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
var _arrayPush = arrayPush$1;
var isArray$b = Array.isArray;
var isArray_1 = isArray$b;
var arrayPush = _arrayPush, isArray$a = isArray_1;
function baseGetAllKeys$1(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray$a(object) ? result : arrayPush(result, symbolsFunc(object));
}
var _baseGetAllKeys = baseGetAllKeys$1;
function arrayFilter$1(array, predicate) {
var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
var _arrayFilter = arrayFilter$1;
function stubArray$1() {
return [];
}
var stubArray_1 = stubArray$1;
var arrayFilter = _arrayFilter, stubArray = stubArray_1;
var objectProto$6 = Object.prototype;
var propertyIsEnumerable = objectProto$6.propertyIsEnumerable;
var nativeGetSymbols = Object.getOwnPropertySymbols;
var getSymbols$1 = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
var _getSymbols = getSymbols$1;
function baseTimes$1(n, iteratee) {
var index = -1, result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
var _baseTimes = baseTimes$1;
var MAX_SAFE_INTEGER = 9007199254740991;
var reIsUint = /^(?:0|[1-9]\d*)$/;
function isIndex$1(value, length) {
var type2 = typeof value;
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length && (type2 == "number" || type2 != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
}
var _isIndex = isIndex$1;
var baseTimes = _baseTimes, isArguments$1 = isArguments_1, isArray$9 = isArray_1, isBuffer$3 = isBufferExports, isIndex = _isIndex, isTypedArray$2 = isTypedArray_1;
var objectProto$5 = Object.prototype;
var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
function arrayLikeKeys$1(value, inherited) {
var isArr = isArray$9(value), isArg = !isArr && isArguments$1(value), isBuff = !isArr && !isArg && isBuffer$3(value), isType = !isArr && !isArg && !isBuff && isTypedArray$2(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty$4.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode.
(key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers.
isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays.
isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties.
isIndex(key, length)))) {
result.push(key);
}
}
return result;
}
var _arrayLikeKeys = arrayLikeKeys$1;
var objectProto$4 = Object.prototype;
function isPrototype$2(value) {
var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto$4;
return value === proto;
}
var _isPrototype = isPrototype$2;
function overArg$1(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
var _overArg = overArg$1;
var overArg = _overArg;
var nativeKeys$1 = overArg(Object.keys, Object);
var _nativeKeys = nativeKeys$1;
var isPrototype$1 = _isPrototype, nativeKeys = _nativeKeys;
var objectProto$3 = Object.prototype;
var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
function baseKeys$2(object) {
if (!isPrototype$1(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty$3.call(object, key) && key != "constructor") {
result.push(key);
}
}
return result;
}
var _baseKeys = baseKeys$2;
var isFunction = isFunction_1, isLength = isLength_1;
function isArrayLike$2(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
var isArrayLike_1 = isArrayLike$2;
var arrayLikeKeys = _arrayLikeKeys, baseKeys$1 = _baseKeys, isArrayLike$1 = isArrayLike_1;
function keys$1(object) {
return isArrayLike$1(object) ? arrayLikeKeys(object) : baseKeys$1(object);
}
var keys_1 = keys$1;
var baseGetAllKeys = _baseGetAllKeys, getSymbols = _getSymbols, keys = keys_1;
function getAllKeys$1(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
var _getAllKeys = getAllKeys$1;
var getAllKeys = _getAllKeys;
var COMPARE_PARTIAL_FLAG$1 = 1;
var objectProto$2 = Object.prototype;
var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
function equalObjects$1(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty$2.call(other, key))) {
return false;
}
}
var objStacked = stack.get(object);
var othStacked = stack.get(other);
if (objStacked && othStacked) {
return objStacked == other && othStacked == object;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key], othValue = other[key];
if (customizer) {
var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
}
if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
result = false;
break;
}
skipCtor || (skipCtor = key == "constructor");
}
if (result && !skipCtor) {
var objCtor = object.constructor, othCtor = other.constructor;
if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
result = false;
}
}
stack["delete"](object);
stack["delete"](other);
return result;
}
var _equalObjects = equalObjects$1;
var Stack = _Stack, equalArrays = _equalArrays, equalByTag = _equalByTag, equalObjects = _equalObjects, getTag$1 = _getTag, isArray$8 = isArray_1, isBuffer$2 = isBufferExports, isTypedArray$1 = isTypedArray_1;
var COMPARE_PARTIAL_FLAG = 1;
var argsTag = "[object Arguments]", arrayTag = "[object Array]", objectTag = "[object Object]";
var objectProto$1 = Object.prototype;
var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
function baseIsEqualDeep$1(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray$8(object), othIsArr = isArray$8(other), objTag = objIsArr ? arrayTag : getTag$1(object), othTag = othIsArr ? arrayTag : getTag$1(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag;
if (isSameTag && isBuffer$2(object)) {
if (!isBuffer$2(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack());
return objIsArr || isTypedArray$1(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty$1.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty$1.call(other, "__wrapped__");
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack());
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack());
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
var _baseIsEqualDeep = baseIsEqualDeep$1;
var baseIsEqualDeep = _baseIsEqualDeep, isObjectLike$1 = isObjectLike_1;
function baseIsEqual$1(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || !isObjectLike$1(value) && !isObjectLike$1(other)) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual$1, stack);
}
var _baseIsEqual = baseIsEqual$1;
var baseIsEqual = _baseIsEqual;
function isEqual(value, other) {
return baseIsEqual(value, other);
}
var isEqual_1 = isEqual;
const isEqual$1 = /* @__PURE__ */ getDefaultExportFromCjs(isEqual_1);
var baseKeys = _baseKeys, getTag = _getTag, isArguments = isArguments_1, isArray$7 = isArray_1, isArrayLike = isArrayLike_1, isBuffer$1 = isBufferExports, isPrototype = _isPrototype, isTypedArray = isTypedArray_1;
var mapTag = "[object Map]", setTag = "[object Set]";
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value) && (isArray$7(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer$1(value) || isTypedArray(value) || isArguments(value))) {
return !value.length;
}
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
if (isPrototype(value)) {
return !baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
var isEmpty_1 = isEmpty;
const isEmpty$1 = /* @__PURE__ */ getDefaultExportFromCjs(isEmpty_1);
const Header = ({
title,
onSave,
initialData,
modifiedData,
isCreatingEntry = false,
isLoading = false,
isSubmitButtonDisabled = false
}) => {
const navigate = useNavigate();
const didChangeData = !isEqual$1(initialData, modifiedData) || isCreatingEntry && !isEmpty$1(modifiedData);
const primaryAction = /* @__PURE__ */ jsx(T, { children: /* @__PURE__ */ jsx(R, { children: /* @__PURE__ */ jsx(
Nn,
{
disabled: !didChangeData || isSubmitButtonDisabled,
onClick: onSave,
loading: isLoading,
type: "submit",
children: "Save"
}
) }) });
return /* @__PURE__ */ jsx(
Layouts.Header,
{
title,
primaryAction,
navigationAction: /* @__PURE__ */ jsx(
zc,
{
startIcon: /* @__PURE__ */ jsx(U2, {}),
onClick: (e2) => {
e2.preventDefault();
navigate(-1);
},
to: "#",
children: "Back"
}
)
}
);
};
var baseGetTag = _baseGetTag, isObjectLike = isObjectLike_1;
var symbolTag = "[object Symbol]";
function isSymbol$4(value) {
return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag;
}
var isSymbol_1 = isSymbol$4;
var isArray$6 = isArray_1, isSymbol$3 = isSymbol_1;
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/;
function isKey$1(value, object) {
if (isArray$6(value)) {
return false;
}
var type2 = typeof value;
if (type2 == "number" || type2 == "symbol" || type2 == "boolean" || value == null || isSymbol$3(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
}
var _isKey = isKey$1;
var MapCache = _MapCache;
var FUNC_ERROR_TEXT = "Expected a function";
function memoize$1(func, resolver) {
if (typeof func != "function" || resolver != null && typeof resolver != "function") {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize$1.Cache || MapCache)();
return memoized;
}
memoize$1.Cache = MapCache;
var memoize_1 = memoize$1;
var memoize = memoize_1;
var MAX_MEMOIZE_SIZE = 500;
function memoizeCapped$1(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
var _memoizeCapped = memoizeCapped$1;
var memoizeCapped = _memoizeCapped;
var rePropName$1 = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
var reEscapeChar$1 = /\\(\\)?/g;
var stringToPath$2 = memoizeCapped(function(string) {
var result = [];
if (string.charCodeAt(0) === 46) {
result.push("");
}
string.replace(rePropName$1, function(match2, number, quote2, subString) {
result.push(quote2 ? subString.replace(reEscapeChar$1, "$1") : number || match2);
});
return result;
});
var _stringToPath = stringToPath$2;
function arrayMap$1(array, iteratee) {
var index = -1, length = array == null ? 0 : array.length, result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
var _arrayMap = arrayMap$1;
var Symbol$1 = _Symbol, arrayMap = _arrayMap, isArray$5 = isArray_1, isSymbol$2 = isSymbol_1;
var symbolProto = Symbol$1 ? Symbol$1.prototype : void 0, symbolToString = symbolProto ? symbolProto.toString : void 0;
function baseToString$1(value) {
if (typeof value == "string") {
return value;
}
if (isArray$5(value)) {
return arrayMap(value, baseToString$1) + "";
}
if (isSymbol$2(value)) {
return symbolToString ? symbolToString.call(value) : "";
}
var result = value + "";
return result == "0" && 1 / value == -Infinity ? "-0" : result;
}
var _baseToString = baseToString$1;
var baseToString = _baseToString;
function toString$1(value) {
return value == null ? "" : baseToString(value);
}
var toString_1 = toString$1;
var isArray$4 = isArray_1, isKey = _isKey, stringToPath$1 = _stringToPath, toString = toString_1;
function castPath$1(value, object) {
if (isArray$4(value)) {
return value;
}
return isKey(value, object) ? [value] : stringToPath$1(toString(value));
}
var _castPath = castPath$1;
var isSymbol$1 = isSymbol_1;
function toKey$1(value) {
if (typeof value == "string" || isSymbol$1(value)) {
return value;
}
var result = value + "";
return result == "0" && 1 / value == -Infinity ? "-0" : result;
}
var _toKey = toKey$1;
var castPath = _castPath, toKey = _toKey;
function baseGet$1(object, path) {
path = castPath(path, object);
var index = 0, length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
return index && index == length ? object : void 0;
}
var _baseGet = baseGet$1;
var baseGet = _baseGet;
function get$1(object, path, defaultValue) {
var result = object == null ? void 0 : baseGet(object, path);
return result === void 0 ? defaultValue : result;
}
var get_1 = get$1;
const get$2 = /* @__PURE__ */ getDefaultExportFromCjs(get_1);
const providerIconMapping = {
password: /* @__PURE__ */ jsx(MdPassword, { size: 24 }),
"google.com": /* @__PURE__ */ jsx(AiFillGoogleCircle, { size: 24 }),
"apple.com": /* @__PURE__ */ jsx(AiFillApple, { size: 24 }),
"facebook.com": /* @__PURE__ */ jsx(AiFillFacebook, { size: 24 }),
"twitter.com": /* @__PURE__ */ jsx(AiFillTwitterCircle, { size: 24 }),
"github.com": /* @__PURE__ */ jsx(AiFillGithub, { size: 24 }),
"yahoo.com": /* @__PURE__ */ jsx(AiFillYahoo, { size: 24 }),
"hotmail.com": /* @__PURE__ */ jsx(AiFillMail, { size: 24 }),
phone: /* @__PURE__ */ jsx(AiFillPhone, { size: 24 }),
anonymous: /* @__PURE__ */ jsx(AiOutlineUserAdd, { size: 24 })
};
const providerNameMapping = {
password: "Password",
"google.com": "Google",
"apple.com": "Apple",
"facebook.com": "Facebook",
"twitter.com": "Twitter",
"github.com": "GitHub",
"yahoo.com": "Yahoo",
"hotmail.com": "Hotmail",
phone: "Phone",
anonymous: "Anonymous"
};
const MapProviderToIcon = ({ providerData }) => {
return /* @__PURE__ */ jsx(T, { gap: 2, children: providerData?.map(({ providerId }) => /* @__PURE__ */ jsx(Ar, { description: providerNameMapping[providerId] || providerId, children: /* @__PURE__ */ jsx("div", { children: providerIconMapping[providerId] || providerId }) }, providerId)) });
};
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
return typeof o2;
} : function(o2) {
return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
}, _typeof(o);
}
function toInteger(dirtyNumber) {
if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
return NaN;
}
var number = Number(dirtyNumber);
if (isNaN(number)) {
return number;
}
return number < 0 ? Math.ceil(number) : Math.floor(number);
}
function requiredArgs(required, args) {
if (args.length < required) {
throw new TypeError(required + " argument" + (required > 1 ? "s" : "") + " required, but only " + args.length + " present");
}
}
function toDate(argument) {
requiredArgs(1, arguments);
var argStr = Object.prototype.toString.call(argument);
if (argument instanceof Date || _typeof(argument) === "object" && argStr === "[object Date]") {
return new Date(argument.getTime());
} else if (typeof argument === "number" || argStr === "[object Number]") {
return new Date(argument);
} else {
if ((typeof argument === "string" || argStr === "[object String]") && typeof console !== "undefined") {
console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments");
console.warn(new Error().stack);
}
return /* @__PURE__ */ new Date(NaN);
}
}
function addMilliseconds(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var timestamp = toDate(dirtyDate).getTime();
var amount = toInteger(dirtyAmount);
return new Date(timestamp + amount);
}
var defaultOptions = {};
function getDefaultOptions() {
return defaultOptions;
}
function getTimezoneOffsetInMilliseconds(date) {
var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
utcDate.setUTCFullYear(date.getFullYear());
return date.getTime() - utcDate.getTime();
}
function isDate$1(value) {
requiredArgs(1, arguments);
return value instanceof Date || _typeof(value) === "object" && Object.prototype.toString.call(value) === "[object Date]";
}
function isValid(dirtyDate) {
requiredArgs(1, arguments);
if (!isDate$1(dirtyDate) && typeof dirtyDate !== "number") {
return false;
}
var date = toDate(dirtyDate);
return !isNaN(Number(date));
}
function subMilliseconds(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments);
var amount = toInteger(dirtyAmount);
return addMilliseconds(dirtyDate, -amount);
}
var MILLISECONDS_IN_DAY = 864e5;
function getUTCDayOfYear(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var timestamp = date.getTime();
date.setUTCMonth(0, 1);
date.setUTCHours(0, 0, 0, 0);
var startOfYearTimestamp = date.getTime();
var difference = timestamp - startOfYearTimestamp;
return Math.floor(difference / MILLISECONDS_IN_DAY) + 1;
}
function startOfUTCISOWeek(dirtyDate) {
requiredArgs(1, arguments);
var weekStartsOn = 1;
var date = toDate(dirtyDate);
var day = date.getUTCDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setUTCDate(date.getUTCDate() - diff);
date.setUTCHours(0, 0, 0, 0);
return date;
}
function getUTCISOWeekYear(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var year = date.getUTCFullYear();
var fourthOfJanuaryOfNextYear = /* @__PURE__ */ new Date(0);
fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4);
fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0);
var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear);
var fourthOfJanuaryOfThisYear = /* @__PURE__ */ new Date(0);
fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4);
fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0);
var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear);
if (date.getTime() >= startOfNextYear.getTime()) {
return year + 1;
} else if (date.getTime() >= startOfThisYear.getTime()) {
return year;
} else {
return year - 1;
}
}
function startOfUTCISOWeekYear(dirtyDate) {
requiredArgs(1, arguments);
var year = getUTCISOWeekYear(dirtyDate);
var fourthOfJanuary = /* @__PURE__ */ new Date(0);
fourthOfJanuary.setUTCFullYear(year, 0, 4);
fourthOfJanuary.setUTCHours(0, 0, 0, 0);
var date = startOfUTCISOWeek(fourthOfJanuary);
return date;
}
var MILLISECONDS_IN_WEEK$1 = 6048e5;
function getUTCISOWeek(dirtyDate) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime();
return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1;
}
function startOfUTCWeek(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs(1, arguments);
var defaultOptions2 = getDefaultOptions();
var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions2.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions2.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0);
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
}
var date = toDate(dirtyDate);
var day = date.getUTCDay();
var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
date.setUTCDate(date.getUTCDate() - diff);
date.setUTCHours(0, 0, 0, 0);
return date;
}
function getUTCWeekYear(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var year = date.getUTCFullYear();
var defaultOptions2 = getDefaultOptions();
var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions2.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");
}
var firstWeekOfNextYear = /* @__PURE__ */ new Date(0);
firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate);
firstWeekOfNextYear.setUTCHours(0, 0, 0, 0);
var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options);
var firstWeekOfThisYear = /* @__PURE__ */ new Date(0);
firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate);
firstWeekOfThisYear.setUTCHours(0, 0, 0, 0);
var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options);
if (date.getTime() >= startOfNextYear.getTime()) {
return year + 1;
} else if (date.getTime() >= startOfThisYear.getTime()) {
return year;
} else {
return year - 1;
}
}
function startOfUTCWeekYear(dirtyDate, options) {
var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
requiredArgs(1, arguments);
var defaultOptions2 = getDefaultOptions();
var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions2.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
var year = getUTCWeekYear(dirtyDate, options);
var firstWeek = /* @__PURE__ */ new Date(0);
firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate);
firstWeek.setUTCHours(0, 0, 0, 0);
var date = startOfUTCWeek(firstWeek, options);
return date;
}
var MILLISECONDS_IN_WEEK = 6048e5;
function getUTCWeek(dirtyDate, options) {
requiredArgs(1, arguments);
var date = toDate(dirtyDate);
var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime();
return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
}
function addLeadingZeros(number, targetLength) {
var sign3 = number < 0 ? "-" : "";
var output = Math.abs(number).toString();
while (output.length < targetLength) {
output = "0" + output;
}
return sign3 + output;
}
var formatters$1 = {
// Year
y: function y(date, token) {
var signedYear = date.getUTCFullYear();
var year = signedYear > 0 ? signedYear : 1 - signedYear;
return addLeadingZeros(token === "yy" ? year % 100 : year, token.length);
},
// Month
M: function M(date, token) {
var month = date.getUTCMonth();
return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2);
},
// Day of the month
d: function d(date, token) {
return addLeadingZeros(date.getUTCDate(), token.length);
},
// AM or PM
a: function a(date, token) {
var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? "pm" : "am";
switch (token) {
case "a":
case "aa":
return dayPeriodEnumValue.toUpperCase();
case "aaa":
return dayPeriodEnumValue;
case "aaaaa":
return dayPeriodEnumValue[0];
case "aaaa":
default:
return dayPeriodEnumValue === "am" ? "a.m." : "p.m.";
}
},
// Hour [1-12]
h: function h(date, token) {
return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length);
},
// Hour [0-23]
H: function H(date, token) {
return addLeadingZeros(date.getUTCHours(), token.length);
},
// Minute
m: function m(date, token) {
return addLeadingZeros(date.getUTCMinutes(), token.length);
},
// Second
s: function s(date, token) {
return addLeadingZeros(date.getUTCSeconds(), token.length);
},
// Fraction of second
S: function S(date, token) {
var numberOfDigits = token.length;
var milliseconds = date.getUTCMilliseconds();
var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3));
return addLeadingZeros(fractionalSeconds, token.length);
}
};
var dayPeriodEnum = {
midnight: "midnight",
noon: "noon",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
};
var formatters = {
// Era
G: function G(date, token, localize2) {
var era = date.getUTCFullYear() > 0 ? 1 : 0;
switch (token) {
case "G":
case "GG":
case "GGG":
return localize2.era(era, {
width: "abbreviated"
});
case "GGGGG":
return localize2.era(era, {
width: "narrow"
});
case "GGGG":
default:
return localize2.era(era, {
width: "wide"
});
}
},
// Year
y: function y2(date, token, localize2) {
if (token === "yo") {
var signedYear = date.getUTCFullYear();
var year = signedYear > 0 ? signedYear : 1 - signedYear;
return localize2.ordinalNumber(year, {
unit: "year"
});
}
return formatters$1.y(date, token);
},
// Local week-numbering year
Y: function Y(date, token, localize2, options) {
var signedWeekYear = getUTCWeekYear(date, options);
var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;
if (token === "YY") {
var twoDigitYear = weekYear % 100;
return addLeadingZeros(twoDigitYear, 2);
}
if (token === "Yo") {
return localize2.ordinalNumber(weekYear, {
unit: "year"
});
}
return addLeadingZeros(weekYear, token.length);
},
// ISO week-numbering year
R: function R2(date, token) {
var isoWeekYear = getUTCISOWeekYear(date);
return addLeadingZeros(isoWeekYear, token.length);
},
// Extended year. This is a single number designating the year of this calendar system.
// The main difference between `y` and `u` localizers are B.C. years:
// | Year | `y` | `u` |
// |------|-----|-----|
// | AC 1 | 1 | 1 |
// | BC 1 | 1 | 0 |
// | BC 2 | 2 | -1 |
// Also `yy` always returns the last two digits of a year,
// while `uu` pads single digit years to 2 characters and returns other years unchanged.
u: function u(date, token) {
var year = date.getUTCFullYear();
return addLeadingZeros(year, token.length);
},
// Quarter
Q: function Q(date, token, localize2) {
var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
switch (token) {
case "Q":
return String(quarter);
case "QQ":
return addLeadingZeros(quarter, 2);
case "Qo":
return localize2.ordinalNumber(quarter, {
unit: "quarter"
});
case "QQQ":
return localize2.quarter(quarter, {
width: "abbreviated",
context: "formatting"
});
case "QQQQQ":
return localize2.quarter(quarter, {
width: "narrow",
context: "formatting"
});
case "QQQQ":
default:
return localize2.quarter(quarter, {
width: "wide",
context: "formatting"
});
}
},
// Stand-alone quarter
q: function q(date, token, localize2) {
var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
switch (token) {
case "q":
return String(quarter);
case "qq":
return addLeadingZeros(quarter, 2);
case "qo":
return localize2.ordinalNumber(quarter, {
unit: "quarter"
});
case "qqq":
return localize2.quarter(quarter, {
width: "abbreviated",
context: "standalone"
});
case "qqqqq":
return localize2.quarter(quarter, {
width: "narrow",
context: "standalone"
});
case "qqqq":
default:
return localize2.quarter(quarter, {
width: "wide",
context: "standalone"
});
}
},
// Month
M: function M2(date, token, localize2) {
var month = date.getUTCMonth();
switch (token) {
case "M":
case "MM":
return formatters$1.M(date, token);
case "Mo":
return localize2.ordinalNumber(month + 1, {
unit: "month"
});
case "MMM":
return localize2.month(month, {
width: "abbreviated",
context: "formatting"
});
case "MMMMM":
return localize2.month(month, {
width: "narrow",
context: "formatting"
});
case "MMMM":
default:
return localize2.month(month, {
width: "wide",
context: "formatting"
});
}
},
// Stand-alone month
L: function L(date, token, localize2) {
var month = date.getUTCMonth();
switch (token) {
case "L":
return String(month + 1);
case "LL":
return addLeadingZeros(month + 1, 2);
case "Lo":
return localize2.ordinalNumber(month + 1, {
unit: "month"
});
case "LLL":
return localize2.month(month, {
width: "abbreviated",
context: "standalone"
});
case "LLLLL":
return localize2.month(month, {
width: "narrow",
context: "standalone"
});
case "LLLL":
default:
return localize2.month(month, {
width: "wide",
context: "standalone"
});
}
},
// Local week of year
w: function w(date, token, localize2, options) {
var week = getUTCWeek(date, options);
if (token === "wo") {
return localize2.ordinalNumber(week, {
unit: "week"
});
}
return addLeadingZeros(week, token.length);
},
// ISO week of year
I: function I(date, token, localize2) {
var isoWeek = getUTCISOWeek(date);
if (token === "Io") {
return localize2.ordinalNumber(isoWeek, {
unit: "week"
});
}
return addLeadingZeros(isoWeek, token.length);
},
// Day of the month
d: function d2(date, token, localize2) {
if (token === "do") {
return localize2.ordinalNumber(date.getUTCDate(), {
unit: "date"
});
}
return formatters$1.d(date, token);
},
// Day of year
D: function D(date, token, localize2) {
var dayOfYear = getUTCDayOfYear(date);
if (token === "Do") {
return localize2.ordinalNumber(dayOfYear, {
unit: "dayOfYear"
});
}
return addLeadingZeros(dayOfYear, token.length);
},
// Day of week
E: function E2(date, token, localize2) {
var dayOfWeek = date.getUTCDay();
switch (token) {
case "E":
case "EE":
case "EEE":
return localize2.day(dayOfWeek, {
width: "abbreviated",
context: "formatting"
});
case "EEEEE":
return localize2.day(dayOfWeek, {
width: "narrow",
context: "formatting"
});
case "EEEEEE":
return localize2.day(dayOfWeek, {
width: "short",
context: "formatting"
});
case "EEEE":
default:
return localize2.day(dayOfWeek, {
width: "wide",
context: "formatting"
});
}
},
// Local day of week
e: function e(date, token, localize2, options) {
var dayOfWeek = date.getUTCDay();
var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
switch (token) {
case "e":
return String(localDayOfWeek);
case "ee":
return addLeadingZeros(localDayOfWeek, 2);
case "eo":
return localize2.ordinalNumber(localDayOfWeek, {
unit: "day"
});
case "eee":
return localize2.day(dayOfWeek, {
width: "abbreviated",
context: "formatting"
});
case "eeeee":
return localize2.day(dayOfWeek, {
width: "narrow",
context: "formatting"
});
case "eeeeee":
return localize2.day(dayOfWeek, {
width: "short",
context: "formatting"
});
case "eeee":
default:
return localize2.day(dayOfWeek, {
width: "wide",
context: "formatting"
});
}
},
// Stand-alone local day of week
c: function c(date, token, localize2, options) {
var dayOfWeek = date.getUTCDay();
var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
switch (token) {
case "c":
return String(localDayOfWeek);
case "cc":
return addLeadingZeros(localDayOfWeek, token.length);
case "co":
return localize2.ordinalNumber(localDayOfWeek, {
unit: "day"
});
case "ccc":
return localize2.day(dayOfWeek, {
width: "abbreviated",
context: "standalone"
});
case "ccccc":
return localize2.day(dayOfWeek, {
width: "narrow",
context: "standalone"
});
case "cccccc":
return localize2.day(dayOfWeek, {
width: "short",
context: "standalone"
});
case "cccc":
default:
return localize2.day(dayOfWeek, {
width: "wide",
context: "standalone"
});
}
},
// ISO day of week
i: function i(date, token, localize2) {
var dayOfWeek = date.getUTCDay();
var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
switch (token) {
case "i":
return String(isoDayOfWeek);
case "ii":
return addLeadingZeros(isoDayOfWeek, token.length);
case "io":
return localize2.ordinalNumber(isoDayOfWeek, {
unit: "day"
});
case "iii":
return localize2.day(dayOfWeek, {
width: "abbreviated",
context: "formatting"
});
case "iiiii":
return localize2.day(dayOfWeek, {
width: "narrow",
context: "formatting"
});
case "iiiiii":
return localize2.day(dayOfWeek, {
width: "short",
context: "formatting"
});
case "iiii":
default:
return localize2.day(dayOfWeek, {
width: "wide",
context: "formatting"
});
}
},
// AM or PM
a: function a2(date, token, localize2) {
var hours = date.getUTCHours();
var dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
switch (token) {
case "a":
case "aa":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "abbreviated",
context: "formatting"
});
case "aaa":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "abbreviated",
context: "formatting"
}).toLowerCase();
case "aaaaa":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "narrow",
context: "formatting"
});
case "aaaa":
default:
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "wide",
context: "formatting"
});
}
},
// AM, PM, midnight, noon
b: function b(date, token, localize2) {
var hours = date.getUTCHours();
var dayPeriodEnumValue;
if (hours === 12) {
dayPeriodEnumValue = dayPeriodEnum.noon;
} else if (hours === 0) {
dayPeriodEnumValue = dayPeriodEnum.midnight;
} else {
dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
}
switch (token) {
case "b":
case "bb":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "abbreviated",
context: "formatting"
});
case "bbb":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "abbreviated",
context: "formatting"
}).toLowerCase();
case "bbbbb":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "narrow",
context: "formatting"
});
case "bbbb":
default:
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "wide",
context: "formatting"
});
}
},
// in the morning, in the afternoon, in the evening, at night
B: function B(date, token, localize2) {
var hours = date.getUTCHours();
var dayPeriodEnumValue;
if (hours >= 17) {
dayPeriodEnumValue = dayPeriodEnum.evening;
} else if (hours >= 12) {
dayPeriodEnumValue = dayPeriodEnum.afternoon;
} else if (hours >= 4) {
dayPeriodEnumValue = dayPeriodEnum.morning;
} else {
dayPeriodEnumValue = dayPeriodEnum.night;
}
switch (token) {
case "B":
case "BB":
case "BBB":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "abbreviated",
context: "formatting"
});
case "BBBBB":
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "narrow",
context: "formatting"
});
case "BBBB":
default:
return localize2.dayPeriod(dayPeriodEnumValue, {
width: "wide",
context: "formatting"
});
}
},
// Hour [1-12]
h: function h2(date, token, localize2) {
if (token === "ho") {
var hours = date.getUTCHours() % 12;
if (hours === 0) hours = 12;
return localize2.ordinalNumber(hours, {
unit: "hour"
});
}
return formatters$1.h(date, token);
},
// Hour [0-23]
H: function H2(date, token, localize2) {
if (token === "Ho") {
return localize2.ordinalNumber(date.getUTCHours(), {
unit: "hour"
});
}
return formatters$1.H(date, token);
},
// Hour [0-11]
K: function K(date, token, localize2) {
var hours = date.getUTCHours() % 12;
if (token === "Ko") {
return localize2.ordinalNumber(hours, {
unit: "hour"
});
}
return addLeadingZeros(hours, token.length);
},
// Hour [1-24]
k: function k(date, token, localize2) {
var hours = date.getUTCHours();
if (hours === 0) hours = 24;
if (token === "ko") {
return localize2.ordinalNumber(hours, {
unit: "hour"
});
}
return addLeadingZeros(hours, token.length);
},
// Minute
m: function m2(date, token, localize2) {
if (token === "mo") {
return localize2.ordinalNumber(date.getUTCMinutes(), {
unit: "minute"
});
}
return formatters$1.m(date, token);
},
// Second
s: function s2(date, token, localize2) {
if (token === "so") {
return localize2.ordinalNumber(date.getUTCSeconds(), {
unit: "second"
});
}
return formatters$1.s(date, token);
},
// Fraction of second
S: function S2(date, token) {
return formatters$1.S(date, token);
},
// Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
X: function X(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
if (timezoneOffset === 0) {
return "Z";
}
switch (token) {
case "X":
return formatTimezoneWithOptionalMinutes(timezoneOffset);
case "XXXX":
case "XX":
return formatTimezone(timezoneOffset);
case "XXXXX":
case "XXX":
default:
return formatTimezone(timezoneOffset, ":");
}
},
// Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
x: function x(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
case "x":
return formatTimezoneWithOptionalMinutes(timezoneOffset);
case "xxxx":
case "xx":
return formatTimezone(timezoneOffset);
case "xxxxx":
case "xxx":
default:
return formatTimezone(timezoneOffset, ":");
}
},
// Timezone (GMT)
O: function O(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
case "O":
case "OO":
case "OOO":
return "GMT" + formatTimezoneShort(timezoneOffset, ":");
case "OOOO":
default:
return "GMT" + formatTimezone(timezoneOffset, ":");
}
},
// Timezone (specific non-location)
z: function z(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timezoneOffset = originalDate.getTimezoneOffset();
switch (token) {
case "z":
case "zz":
case "zzz":
return "GMT" + formatTimezoneShort(timezoneOffset, ":");
case "zzzz":
default:
return "GMT" + formatTimezone(timezoneOffset, ":");
}
},
// Seconds timestamp
t: function t(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timestamp = Math.floor(originalDate.getTime() / 1e3);
return addLeadingZeros(timestamp, token.length);
},
// Milliseconds timestamp
T: function T2(date, token, _localize, options) {
var originalDate = options._originalDate || date;
var timestamp = originalDate.getTime();
return addLeadingZeros(timestamp, token.length);
}
};
function formatTimezoneShort(offset, dirtyDelimiter) {
var sign3 = offset > 0 ? "-" : "+";
var absOffset = Math.abs(offset);
var hours = Math.floor(absOffset / 60);
var minutes = absOffset % 60;
if (minutes === 0) {
return sign3 + String(hours);
}
var delimiter = dirtyDelimiter;
return sign3 + String(hours) + delimiter + addLeadingZeros(minutes, 2);
}
function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) {
if (offset % 60 === 0) {
var sign3 = offset > 0 ? "-" : "+";
return sign3 + addLeadingZeros(Math.abs(offset) / 60, 2);
}
return formatTimezone(offset, dirtyDelimiter);
}
function formatTimezone(offset, dirtyDelimiter) {
var delimiter = dirtyDelimiter || "";
var sign3 = offset > 0 ? "-" : "+";
var absOffset = Math.abs(offset);
var hours = addLeadingZeros(Math.floor(absOffset / 60), 2);
var minutes = addLeadingZeros(absOffset % 60, 2);
return sign3 + hours + delimiter + minutes;
}
var dateLongFormatter = function dateLongFormatter2(pattern, formatLong2) {
switch (pattern) {
case "P":
return formatLong2.date({
width: "short"
});
case "PP":
return formatLong2.date({
width: "medium"
});
case "PPP":
return formatLong2.date({
width: "long"
});
case "PPPP":
default:
return formatLong2.date({
width: "full"
});
}
};
var timeLongFormatter = function timeLongFormatter2(pattern, formatLong2) {
switch (pattern) {
case "p":
return formatLong2.time({
width: "short"
});
case "pp":
return formatLong2.time({
width: "medium"
});
case "ppp":
return formatLong2.time({
width: "long"
});
case "pppp":
default:
return formatLong2.time({
width: "full"
});
}
};
var dateTimeLongFormatter = function dateTimeLongFormatter2(pattern, formatLong2) {
var matchResult = pattern.match(/(P+)(p+)?/) || [];
var datePattern = matchResult[1];
var timePattern = matchResult[2];
if (!timePattern) {
return dateLongFormatter(pattern, formatLong2);
}
var dateTimeFormat;
switch (datePattern) {
case "P":
dateTimeFormat = formatLong2.dateTime({
width: "short"
});
break;
case "PP":
dateTimeFormat = formatLong2.dateTime({
width: "medium"
});
break;
case "PPP":
dateTimeFormat = formatLong2.dateTime({
width: "long"
});
break;
case "PPPP":
default:
dateTimeFormat = formatLong2.dateTime({
width: "full"
});
break;
}
return dateTimeFormat.replace("{{date}}", dateLongFormatter(datePattern, formatLong2)).replace("{{time}}", timeLongFormatter(timePattern, formatLong2));
};
var longFormatters = {
p: timeLongFormatter,
P: dateTimeLongFormatter
};
var protectedDayOfYearTokens = ["D", "DD"];
var protectedWeekYearTokens = ["YY", "YYYY"];
function isProtectedDayOfYearToken(token) {
return protectedDayOfYearTokens.indexOf(token) !== -1;
}
function isProtectedWeekYearToken(token) {
return protectedWeekYearTokens.indexOf(token) !== -1;
}
function throwProtectedError(token, format2, input) {
if (token === "YYYY") {
throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format2, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
} else if (token === "YY") {
throw new RangeError("Use `yy` instead of `YY` (in `".concat(format2, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
} else if (token === "D") {
throw new RangeError("Use `d` instead of `D` (in `".concat(format2, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
} else if (token === "DD") {
throw new RangeError("Use `dd` instead of `DD` (in `".concat(format2, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
}
}
var formatDistanceLocale = {
lessThanXSeconds: {
one: "less than a second",
other: "less than {{count}} seconds"
},
xSeconds: {
one: "1 second",
other: "{{count}} seconds"
},
halfAMinute: "half a minute",
lessThanXMinutes: {
one: "less than a minute",
other: "less than {{count}} minutes"
},
xMinutes: {
one: "1 minute",
other: "{{count}} minutes"
},
aboutXHours: {
one: "about 1 hour",
other: "about {{count}} hours"
},
xHours: {
one: "1 hour",
other: "{{count}} hours"
},
xDays: {
one: "1 day",
other: "{{count}} days"
},
aboutXWeeks: {
one: "about 1 week",
other: "about {{count}} weeks"
},
xWeeks: {
one: "1 week",
other: "{{count}} weeks"
},
aboutXMonths: {
one: "about 1 month",
other: "about {{count}} months"
},
xMonths: {
one: "1 month",
other: "{{count}} months"
},
aboutXYears: {
one: "about 1 year",
other: "about {{count}} years"
},
xYears: {
one: "1 year",
other: "{{count}} years"
},
overXYears: {
one: "over 1 year",
other: "over {{count}} years"
},
almostXYears: {
one: "almost 1 year",
other: "almost {{count}} years"
}
};
var formatDistance = function formatDistance2(token, count, options) {
var result;
var tokenValue = formatDistanceLocale[token];
if (typeof tokenValue === "string") {
result = tokenValue;
} else if (count === 1) {
result = tokenValue.one;
} else {
result = tokenValue.other.replace("{{count}}", count.toString());
}
if (options !== null && options !== void 0 && options.addSuffix) {
if (options.comparison && options.comparison > 0) {
return "in " + result;
} else {
return result + " ago";
}
}
return result;
};
function buildFormatLongFn(args) {
return function() {
var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
var width = options.width ? String(options.width) : args.defaultWidth;
var format2 = args.formats[width] || args.formats[args.defaultWidth];
return format2;
};
}
var dateFormats = {
full: "EEEE, MMMM do, y",
long: "MMMM do, y",
medium: "MMM d, y",
short: "MM/dd/yyyy"
};
var timeFormats = {
full: "h:mm:ss a zzzz",
long: "h:mm:ss a z",
medium: "h:mm:ss a",
short: "h:mm a"
};
var dateTimeFormats = {
full: "{{date}} 'at' {{time}}",
long: "{{date}} 'at' {{time}}",
medium: "{{date}}, {{time}}",
short: "{{date}}, {{time}}"
};
var formatLong = {
date: buildFormatLongFn({
formats: dateFormats,
defaultWidth: "full"
}),
time: buildFormatLongFn({
formats: timeFormats,
defaultWidth: "full"
}),
dateTime: buildFormatLongFn({
formats: dateTimeFormats,
defaultWidth: "full"
})
};
var formatRelativeLocale = {
lastWeek: "'last' eeee 'at' p",
yesterday: "'yesterday at' p",
today: "'today at' p",
tomorrow: "'tomorrow at' p",
nextWeek: "eeee 'at' p",
other: "P"
};
var formatRelative = function formatRelative2(token, _date, _baseDate, _options) {
return formatRelativeLocale[token];
};
function buildLocalizeFn(args) {
return function(dirtyIndex, options) {
var context = options !== null && options !== void 0 && options.context ? String(options.context) : "standalone";
var valuesArray;
if (context === "formatting" && args.formattingValues) {
var defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth;
valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
} else {
var _defaultWidth = args.defaultWidth;
var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth;
valuesArray = args.values[_width] || args.values[_defaultWidth];
}
var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex;
return valuesArray[index];
};
}
var eraValues = {
narrow: ["B", "A"],
abbreviated: ["BC", "AD"],
wide: ["Before Christ", "Anno Domini"]
};
var quarterValues = {
narrow: ["1", "2", "3", "4"],
abbreviated: ["Q1", "Q2", "Q3", "Q4"],
wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]
};
var monthValues = {
narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
abbreviated: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
wide: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
};
var dayValues = {
narrow: ["S", "M", "T", "W", "T", "F", "S"],
short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
wide: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
};
var dayPeriodValues = {
narrow: {
am: "a",
pm: "p",
midnight: "mi",
noon: "n",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
},
abbreviated: {
am: "AM",
pm: "PM",
midnight: "midnight",
noon: "noon",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
},
wide: {
am: "a.m.",
pm: "p.m.",
midnight: "midnight",
noon: "noon",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
}
};
var formattingDayPeriodValues = {
narrow: {
am: "a",
pm: "p",
midnight: "mi",
noon: "n",
morning: "in the morning",
afternoon: "in the afternoon",
evening: "in the evening",
night: "at night"
},
abbreviated: {
am: "AM",
pm: "PM",
midnight: "midnight",
noon: "noon",
morning: "in the morning",
afternoon: "in the afternoon",
evening: "in the evening",
night: "at night"
},
wide: {
am: "a.m.",
pm: "p.m.",
midnight: "midnight",
noon: "noon",
morning: "in the morning",
afternoon: "in the afternoon",
evening: "in the evening",
night: "at night"
}
};
var ordinalNumber = function ordinalNumber2(dirtyNumber, _options) {
var number = Number(dirtyNumber);
var rem100 = number % 100;
if (rem100 > 20 || rem100 < 10) {
switch (rem100 % 10) {
case 1:
return number + "st";
case 2:
return number + "nd";
case 3:
return number + "rd";
}
}
return number + "th";
};
var localize = {
ordinalNumber,
era: buildLocalizeFn({
values: eraValues,
defaultWidth: "wide"
}),
quarter: buildLocalizeFn({
values: quarterValues,
defaultWidth: "wide",
argumentCallback: function argumentCallback(quarter) {
return quarter - 1;
}
}),
month: buildLocalizeFn({
values: monthValues,
defaultWidth: "wide"
}),
day: buildLocalizeFn({
values: dayValues,
defaultWidth: "wide"
}),
dayPeriod: buildLocalizeFn({
values: dayPeriodValues,
defaultWidth: "wide",
formattingValues: formattingDayPeriodValues,
defaultFormattingWidth: "wide"
})
};
function buildMatchFn(args) {
return function(string) {
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
var width = options.width;
var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
var matchResult = string.match(matchPattern);
if (!matchResult) {
return null;
}
var matchedString = matchResult[0];
var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function(pattern) {
return pattern.test(matchedString);
}) : findKey(parsePatterns, function(pattern) {
return pattern.test(matchedString);
});
var value;
value = args.valueCallback ? args.valueCallback(key) : key;
value = options.valueCallback ? options.valueCallback(value) : value;
var rest = string.slice(matchedString.length);
return {
value,
rest
};
};
}
function findKey(object, predicate) {
for (var key in object) {
if (object.hasOwnProperty(key) && predicate(object[key])) {
return key;
}
}
return void 0;
}
function findIndex(array, predicate) {
for (var key = 0; key < array.length; key++) {
if (predicate(array[key])) {
return key;
}
}
return void 0;
}
function buildMatchPatternFn(args) {
return function(string) {
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
var matchResult = string.match(args.matchPattern);
if (!matchResult) return null;
var matchedString = matchResult[0];
var parseResult = string.match(args.parsePattern);
if (!parseResult) return null;
var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
value = options.valueCallback ? options.valueCallback(value) : value;
var rest = string.slice(matchedString.length);
return {
value,
rest
};
};
}
var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
var parseOrdinalNumberPattern = /\d+/i;
var matchEraPatterns = {
narrow: /^(b|a)/i,
abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
wide: /^(before christ|before common era|anno domini|common era)/i
};
var parseEraPatterns = {
any: [/^b/i, /^(a|c)/i]
};
var matchQuarterPatterns = {
narrow: /^[1234]/i,
abbreviated: /^q[1234]/i,
wide: /^[1234](th|st|nd|rd)? quarter/i
};
var parseQuarterPatterns = {
any: [/1/i, /2/i, /3/i, /4/i]
};
var matchMonthPatterns = {
narrow: /^[jfmasond]/i,
abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
};
var parseMonthPatterns = {
narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i],
any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i]
};
var matchDayPatterns = {
narrow: /^[smtwf]/i,
short: /^(su|mo|tu|we|th|fr|sa)/i,
abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
};
var parseDayPatterns = {
narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
};
var matchDayPeriodPatterns = {
narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
};
var parseDayPeriodPatterns = {
any: {
am: /^a/i,
pm: /^p/i,
midnight: /^mi/i,
noon: /^no/i,
morning: /morning/i,
afternoon: /afternoon/i,
evening: /evening/i,
night: /night/i
}
};
var match = {
ordinalNumber: buildMatchPatternFn({
matchPattern: matchOrdinalNumberPattern,
parsePattern: parseOrdinalNumberPattern,
valueCallback: function valueCallback(value) {
return parseInt(value, 10);
}
}),
era: buildMatchFn({
matchPatterns: matchEraPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseEraPatterns,
defaultParseWidth: "any"
}),
quarter: buildMatchFn({
matchPatterns: matchQuarterPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseQuarterPatterns,
defaultParseWidth: "any",
valueCallback: function valueCallback2(index) {
return index + 1;
}
}),
month: buildMatchFn({
matchPatterns: matchMonthPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseMonthPatterns,
defaultParseWidth: "any"
}),
day: buildMatchFn({
matchPatterns: matchDayPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseDayPatterns,
defaultParseWidth: "any"
}),
dayPeriod: buildMatchFn({
matchPatterns: matchDayPeriodPatterns,
defaultMatchWidth: "any",
parsePatterns: parseDayPeriodPatterns,
defaultParseWidth: "any"
})
};
var locale = {
code: "en-US",
formatDistance,
formatLong,
formatRelative,
localize,
match,
options: {
weekStartsOn: 0,
firstWeekContainsDate: 1
}
};
var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
var escapedStringRegExp = /^'([^]*?)'?$/;
var doubleQuoteRegExp = /''/g;
var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
function format(dirtyDate, dirtyFormatStr, options) {
var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _defaultOptions$local3, _defaultOptions$local4;
requiredArgs(2, arguments);
var formatStr = String(dirtyFormatStr);
var defaultOptions2 = getDefaultOptions();
var locale$1 = (_ref = (_options$locale = void 0) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions2.locale) !== null && _ref !== void 0 ? _ref : locale;
var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = void 0) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : void 0) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions2.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions2.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1);
if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");
}
var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = void 0) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : void 0) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions2.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions2.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0);
if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
}
if (!locale$1.localize) {
throw new RangeError("locale must contain localize property");
}
if (!locale$1.formatLong) {
throw new RangeError("locale must contain formatLong property");
}
var originalDate = toDate(dirtyDate);
if (!isValid(originalDate)) {
throw new RangeError("Invalid time value");
}
var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate);
var utcDate = subMilliseconds(originalDate, timezoneOffset);
var formatterOptions = {
firstWeekContainsDate,
weekStartsOn,
locale: locale$1,
_originalDate: originalDate
};
var result = formatStr.match(longFormattingTokensRegExp).map(function(substring) {
var firstCharacter = substring[0];
if (firstCharacter === "p" || firstCharacter === "P") {
var longFormatter = longFormatters[firstCharacter];
return longFormatter(substring, locale$1.formatLong);
}
return substring;
}).join("").match(formattingTokensRegExp).map(function(substring) {
if (substring === "''") {
return "'";
}
var firstCharacter = substring[0];
if (firstCharacter === "'") {
return cleanEscapedString(substring);
}
var formatter = formatters[firstCharacter];
if (formatter) {
if (isProtectedWeekYearToken(substring)) {
throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
}
if (isProtectedDayOfYearToken(substring)) {
throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
}
return formatter(utcDate, substring, locale$1.localize, formatterOptions);
}
if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
throw new RangeError("Format string contains an unescaped latin alphabet character `" + firstCharacter + "`");
}
return substring;
}).join("");
return result;
}
function cleanEscapedString(input) {
var matched = input.match(escapedStringRegExp);
if (!matched) {
return input;
}
return matched[1].replace(doubleQuoteRegExp, "'");
}
const hasPasswordProvider = (user) => {
if (!user) return false;
if (!user.providerData || !Array.isArray(user.providerData)) {
return false;
}
return user.providerData.some((provider) => provider.providerId === "password");
};
const getPasswordResetTooltip = (user) => {
if (!user) {
return "No user selected";
}
if (!user.providerData || user.providerData.length === 0) {
return "User has no authentication providers";
}
const providers = user.providerData.map((p) => p.providerId).join(", ");
if (user.providerData.some((p) => p.providerId === "phone")) {
return `This user authenticates with phone number only. Password reset is not available.`;
}
if (user.providerData.some((p) => p.providerId === "google.com")) {
return `This user authenticates with Google. Please use Google's account recovery.`;
}
if (user.providerData.some((p) => p.providerId === "apple.com")) {
return `This user authenticates with Apple. Please use Apple's account recovery.`;
}
return `Password reset is only available for users with email/password authentication. Current provider(s): ${providers}`;
};
const TypographyMaxWidth = styled(E)`
max-width: 300px;
`;
const CellLink = styled(A1)`
text-decoration: underline;
color: ${({ theme }) => theme.colors.primary600};
&:hover {
cursor: pointer;
color: ${({ theme }) => theme.colors.primary700};
}
& > span {
color: ${({ theme }) => theme.colors.primary600};
}
`;
const ActionCell = styled(A1)`
/* Prevent scroll on button clicks */
position: relative;
/* Critical: Prevent browser from scrolling to this cell */
scroll-margin: 0;
scroll-snap-margin: 0;
/* Stop event bubbling at cell level */
& button {
position: relative;
z-index: 1;
/* Ensure button is immediately clickable */
pointer-events: auto;
touch-action: manipulation;
}
`;
const FirebaseTableRows = ({
rows,
entriesToDelete,
onSelectRow,
onResetPasswordClick,
onDeleteAccountClick
}) => {
const { formatMessage } = useIntl();
const navigate = useNavigate();
const location = useLocation();
return /* @__PURE__ */ jsx(S1, { children: rows.map((data) => {
const isChecked = entriesToDelete.includes(data.id);
return /* @__PURE__ */ jsxs(k1, { children: [
/* @__PURE__ */ jsx(A1, { children: /* @__PURE__ */ jsx(T, { justifyContent: "center", alignItems: "center", children: /* @__PURE__ */ jsx(
Tr,
{
"aria-label": formatMessage({
id: "app.component.table.select.one-entry",
defaultMessage: `Select {target}`
}),
checked: isChecked,
onCheckedChange: (checked) => {
onSelectRow({ name: data.id, value: checked === true });
}
}
) }) }),
/* @__PURE__ */ jsx(
CellLink,
{
onClick: () => {
navigate(data.uid, {
state: {
strapiId: data.strapiId,
strapiDocumentId: data.strapiDocumentId
}
});
},
children: /* @__PURE__ */ jsx(TypographyMaxWidth, { ellipsis: true, textColor: "neutral800", children: data.uid })
},
data.uid
),
/* @__PURE__ */ jsx(CellLink, { children: /* @__PURE__ */ jsx(TypographyMaxWidth, { ellipsis: true, textColor: "neutral800", children: /* @__PURE__ */ jsx(
R,
{
onClick: () => {
navigate(
`/content-manager/collection-types/plugin::users-permissions.user/${data.strapiDocumentId || data.strapiId}`,
{ state: { from: location.pathname } }
);
},
children: data.strapiId
}
) }) }, data.strapiId),
/* @__PURE__ */ jsx(A1, { children: /* @__PURE__ */ jsx(TypographyMaxWidth, { ellipsis: true, textColor: "neutral800", children: data.username }) }, data.username),
/* @__PURE__ */ jsx(A1, { children: /* @__PURE__ */ jsx(TypographyMaxWidth, { ellipsis: true, textColor: "neutral800", children: data.displayName }) }),
/* @__PURE__ */ jsx(A1, { style: { padding: 16 }, children: /* @__PURE__ */ jsx(TypographyMaxWidth, { ellipsis: true, textColor: "neutral800", children: data.email }) }, data.email),
/* @__PURE__ */ jsx(A1, { style: { padding: 16 }, children: /* @__PURE__ */ jsx(TypographyMaxWidth, { ellipsis: true, textColor: "neutral800", children: data.phoneNumber || "-" }) }, data.phoneNumber),
/* @__PURE__ */ jsx(A1, { children: /* @__PURE__ */ jsx(MapProviderToIcon, { providerData: data.providerData }) }),
/* @__PURE__ */ jsx(A1, { children: data.emailVerified ? /* @__PURE__ */ jsx(RxCheck, { size: 24 }) : /* @__PURE__ */ jsx(RxCross2, { size: 24 }) }),
/* @__PURE__ */ jsx(A1, { children: data.disabled ? /* @__PURE__ */ jsx(RxCheck, { size: 24 }) : /* @__PURE__ */ jsx(RxCross2, { size: 24 }) }, data.disabled),
/* @__PURE__ */ jsx(A1, { children: /* @__PURE__ */ jsx(TypographyMaxWidth, { ellipsis: true, textColor: "neutral800", children: data.createdAt ? format(new Date(data.createdAt), "yyyy/MM/dd HH:mm z") : data.metadata?.creationTime ? format(new Date(data.metadata.creationTime), "yyyy/MM/dd HH:mm z") : "-" }) }, data.createdAt),
/* @__PURE__ */ jsx(A1, { children: /* @__PURE__ */ jsx(TypographyMaxWidth, { ellipsis: true, textColor: "neutral800", children: data.metadata?.lastSignInTime ? format(new Date(data.metadata.lastSignInTime), "yyyy/MM/dd HH:mm z") : "-" }) }, data.metadata?.lastSignInTime || "lastSignInTime"),
/* @__PURE__ */ jsx(
ActionCell,
{
onClick: (e2) => {
e2.preventDefault();
e2.stopPropagation();
},
onMouseDown: (e2) => {
e2.preventDefault();
},
children: /* @__PURE__ */ jsxs(T, { gap: 2, justifyContent: "center", alignItems: "center", children: [
hasPasswordProvider(data) ? /* @__PURE__ */ jsx(
Nn,
{
onClick: (e2) => {
e2.preventDefault();
e2.stopPropagation();
e2.currentTarget.blur();
onResetPasswordClick(data);
},
variant: "secondary",
size: "S",
type: "button",
tabIndex: -1,
style: {
display: "inline-flex",
justifyContent: "center",
alignItems: "center",
padding: "0.25rem 0.75rem",
minWidth: "5.5rem"
},
children: /* @__PURE__ */ jsx(m3, { "aria-hidden": true, style: { display: "block" } })
}
) : /* @__PURE__ */ jsx(Ar, { label: getPasswordResetTooltip(data), children: /* @__PURE__ */ jsx(R, { children: /* @__PURE__ */ jsx(
Nn,
{
disabled: true,
variant: "secondary",
size: "S",
type: "button",
tabIndex: -1,
style: {
display: "inline-flex",
justifyContent: "center",
alignItems: "center",
padding: "0.25rem 0.75rem",
minWidth: "5.5rem",
opacity: 0.5,
cursor: "not-allowed"
},
children: /* @__PURE__ */ jsx(m3, { "aria-hidden": true, style: { display: "block" } })
}
) }) }),
/* @__PURE__ */ jsx(
Nn,
{
onClick: (e2) => {
e2.preventDefault();
e2.stopPropagation();
e2.currentTarget.blur();
onDeleteAccountClick(data);
},
variant: "danger-light",
size: "S",
type: "button",
tabIndex: -1,
style: {
display: "inline-flex",
justifyContent: "center",
alignItems: "center",
padding: "0.25rem 0.75rem",
minWidth: "5.5rem"
},
children: /* @__PURE__ */ jsx(bn, { "aria-hidden": true, style: { display: "block" } })
}
)
] })
}
)
] }, data.uid);
}) });
};
const tableHeaders = [
{
name: "uid",
fieldSchema: {
configurable: false,
type: "string"
},
metadatas: {
label: "Firebase ID",
sortable: false,
searchable: true
},
key: "__uid_key__"
},
{
name: "strapiId",
fieldSchema: {
configurable: false,
type: "object"
},
metadatas: {
label: "Strapi id",
sortable: true,
searchable: true
},
key: "__strapiid_key__"
},
{
name: "username",
fieldSchema: {
configurable: false,
type: "string"
},
metadatas: {
label: "strapi username",
sortable: true,
searchable: true
},
key: "__username_key__"
},
{
name: "displayName",
fieldSchema: {
configurable: false,
type: "string"
},
metadatas: {
label: "Display Name",
sortable: true,
searchable: true
},
key: "__displayName_key__"
},
{
name: "email",
fieldSchema: {
configurable: false,
type: "email"
},
metadatas: {
label: "Email",
sortable: true,
searchable: true
},
key: "__email_key__"
},
{
name: "phoneNumber",
fieldSchema: {
configurable: false,
type: "string"
},
metadatas: {
label: "Phone Number",
sortable: true,
searchable: true
},
key: "__phoneNumber_key__"
},
{
name: "providers",
fieldSchema: {
configurable: false,
type: "icon"
},
metadatas: {
label: "Providers",
sortable: false,
searchable: false
},
key: "__provider_key__"
},
{
name: "emailVerified",
fieldSchema: {
configurable: false,
type: "boolean"
},
metadatas: {
label: "Email Verified",
sortable: false,
searchable: false
},
key: "__emailVerified_key__"
},
{
name: "disabled",
fieldSchema: {
configurable: false,
type: "boolean"
},
metadatas: {
label: "Disabled",
sortable: false,
searchable: false
},
key: "__disabled_key__"
},
{
name: "createdAt",
fieldSchema: {
configurable: false,
type: "string"
},
metadatas: {
label: "Created At",
sortable: true,
searchable: false
},
key: "__createdAt_key__"
},
{
name: "lastSignInTime",
fieldSchema: {
configurable: false,
type: "string"
},
metadatas: {
label: "Last Sign In",
sortable: true,
searchable: false
},
key: "__lastSignInTime_key__"
}
];
const useBulkSelection = (items) => {
const [selectedIds, setSelectedIds] = useState(/* @__PURE__ */ new Set());
const toggleSelectAll = useCallback(() => {
setSelectedIds((prev) => {
if (prev.size === items.length) {
return /* @__PURE__ */ new Set();
} else {
return new Set(items.map((item) => item.id));
}
});
}, [items]);
const toggleSelectItem = useCallback((id) => {
setSelectedIds((prev) => {
const newSet = new Set(prev);
if (newSet.has(id)) {
newSet.delete(id);
} else {
newSet.add(id);
}
return newSet;
});
}, []);
const clearSelection = useCallback(() => {
setSelectedIds(/* @__PURE__ */ new Set());
}, []);
const isAllSelected = useMemo(
() => selectedIds.size === items.length && items.length > 0,
[selectedIds.size, items.length]
);
const isIndeterminate = useMemo(
() => selectedIds.size > 0 && selectedIds.size < items.length,
[selectedIds.size, items.length]
);
const hasSelection = useMemo(() => selectedIds.size > 0, [selectedIds.size]);
const selectedCount = useMemo(() => selectedIds.size, [selectedIds.size]);
const selectedArray = useMemo(() => Array.from(selectedIds), [selectedIds]);
return {
selectedIds,
toggleSelectAll,
toggleSelectItem,
clearSelection,
isAllSelected,
isIndeterminate,
hasSelection,
selectedCount,
selectedArray
};
};
const DeleteAccount = ({
isOpen,
email,
onConfirm,
onToggleDialog,
isSingleRecord = false
}) => {
const [isStrapiIncluded, setIsStrapiIncluded] = useState(true);
const [isFirebaseIncluded, setIsFirebaseIncluded] = useState(true);
useEffect(() => {
setIsStrapiIncluded(true);
setIsFirebaseIncluded(true);
}, [isOpen]);
return /* @__PURE__ */ jsx(t1.Root, { open: isOpen, onOpenChange: (open) => !open && onToggleDialog(), children: /* @__PURE__ */ jsxs(t1.Content, { children: [
/* @__PURE__ */ jsx(t1.Header, { children: /* @__PURE__ */ jsx(t1.Title, { children: "Delete Account" }) }),
/* @__PURE__ */ jsx(t1.Body, { children: /* @__PURE__ */ jsxs(T, { direction: "column", alignItems: "stretch", gap: 4, children: [
/* @__PURE__ */ jsxs(T, { direction: "row", alignItems: "center", gap: 2, children: [
/* @__PURE__ */ jsx(Nn$1, { fill: "danger700", width: "20px", height: "20px" }),
/* @__PURE__ */ jsx(E, { textColor: "danger700", children: "After you delete an account, it's permanently deleted. Accounts cannot be undeleted." })
] }),
isSingleRecord ? /* @__PURE__ */ jsxs(T, { direction: "column", alignItems: "stretch", gap: 1, children: [
/* @__PURE__ */ jsx(E, { variant: "sigma", children: "User account" }),
/* @__PURE__ */ jsx(E, { children: email })
] }) : /* @__PURE__ */ jsxs(T, { direction: "column", alignItems: "stretch", gap: 1, children: [
/* @__PURE__ */ jsx(E, { variant: "sigma", children: "Bulk delete operation" }),
/* @__PURE__ */ jsx(E, { children: "You are about to delete multiple user accounts" })
] }),
/* @__PURE__ */ jsxs(T, { direction: "column", alignItems: "stretch", gap: 2, children: [
/* @__PURE__ */ jsx(E, { children: "Delete user from:" }),
/* @__PURE__ */ jsxs(T, { direction: "row", alignItems: "center", gap: 4, children: [
/* @__PURE__ */ jsx(
Tr,
{
onCheckedChange: (checked) => setIsStrapiIncluded(checked === true),
checked: isStrapiIncluded,
children: "Strapi"
}
),
/* @__PURE__ */ jsx(
Tr,
{
onCheckedChange: (checked) => setIsFirebaseIncluded(checked === true),
checked: isFirebaseIncluded,
children: "Firebase"
}
)
] })
] })
] }) }),
/* @__PURE__ */ jsxs(t1.Footer, { children: [
/* @__PURE__ */ jsx(Nn, { onClick: onToggleDialog, variant: "tertiary", children: "Cancel" }),
/* @__PURE__ */ jsx(
Nn,
{
variant: "danger",
onClick: () => {
onConfirm(isStrapiIncluded, isFirebaseIncluded);
},
disabled: !isFirebaseIncluded && !isStrapiIncluded,
children: "Delete"
}
)
] })
] }) });
};
const StyledTableContainer = styled.div`
width: 100%;
overflow-x: auto;
border-radius: ${({ theme }) => theme.borderRadius};
table {
width: 100%;
min-width: max-content; /* Allow table to expand naturally */
/* Prevent layout shifts during interaction */
contain: layout style;
}
/* Prevent browser scroll-into-view behavior on button clicks */
td {
scroll-margin: 0;
scroll-snap-margin: 0;
}
/* Ensure buttons are always clickable */
button {
scroll-margin: 0;
scroll-snap-margin: 0;
touch-action: manipulation;
}
/* Sortable header hover styles */
th button {
cursor: pointer;
transition: background-color 0.2s ease;
}
/* Icon button in sorted column */
th button[aria-label*="Sort"] {
cursor: pointer;
}
`;
const BulkActionsBar = styled(R)`
margin-bottom: 16px;
padding: 12px 0;
`;
const SortButton = styled.button`
display: flex;
align-items: center;
gap: 4px;
background: none;
border: none;
padding: 0;
cursor: pointer;
color: inherit;
font: inherit;
text-align: left;
width: 100%;
transition: opacity 0.2s ease;
&:hover {
opacity: 0.8;
}
`;
const FirebaseTable = ({
action,
createAction,
rows,
onConfirmDeleteAll,
onResetPasswordClick,
onDeleteAccountClick
}) => {
const {
toggleSelectAll,
toggleSelectItem,
clearSelection,
isAllSelected,
isIndeterminate,
hasSelection,
selectedCount,
selectedArray
} = useBulkSelection(rows);
const [{ query }, setQuery] = useQueryParams$1();
const [showBulkDeleteDialog, setShowBulkDeleteDialog] = useState(false);
const sort = query?.sort ?? "";
const [sortBy, sortOrder] = sort.split(":");
const handleBulkDelete = async (isStrapiIncluded, isFirebaseIncluded) => {
let destination = null;
if (isStrapiIncluded && isFirebaseIncluded) {
destination = null;
} else if (isStrapiIncluded) {
destination = "strapi";
} else if (isFirebaseIncluded) {
destination = "firebase";
}
await onConfirmDeleteAll(selectedArray, destination);
clearSelection();
setShowBulkDeleteDialog(false);
};
const handleSelectRow = ({ name, value }) => {
toggleSelectItem(name);
};
const handleSort = (headerName) => {
const isSorted = sortBy === headerName;
const isAsc = sortOrder === "ASC";
setQuery({
sort: `${headerName}:${isSorted && isAsc ? "DESC" : "ASC"}`
});
};
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsx(BulkActionsBar, { paddingLeft: 0, paddingRight: 0, children: /* @__PURE__ */ jsxs(T, { direction: "row", alignItems: "center", justifyContent: "space-between", wrap: "nowrap", children: [
/* @__PURE__ */ jsxs(T, { direction: "row", alignItems: "center", gap: 2, wrap: "nowrap", children: [
action,
hasSelection && /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsxs(E, { variant: "omega", fontWeight: "semiBold", style: { whiteSpace: "nowrap" }, children: [
selectedCount,
" ",
selectedCount === 1 ? "entry" : "entries",
" selected"
] }),
/* @__PURE__ */ jsx(
Nn,
{
variant: "danger",
startIcon: /* @__PURE__ */ jsx(bn, {}),
onClick: () => setShowBulkDeleteDialog(true),
size: "S",
style: { whiteSpace: "nowrap" },
children: "Delete"
}
),
/* @__PURE__ */ jsx(
Nn,
{
variant: "secondary",
onClick: clearSelection,
size: "S",
style: { whiteSpace: "nowrap" },
children: "Deselect all"
}
)
] })
] }),
createAction
] }) }),
/* @__PURE__ */ jsx(StyledTableContainer, { children: /* @__PURE__ */ jsxs(v1, { colCount: tableHeaders.length + 2, rowCount: rows.length + 1, children: [
/* @__PURE__ */ jsx(C1, { children: /* @__PURE__ */ jsxs(k1, { children: [
/* @__PURE__ */ jsx($1, { children: /* @__PURE__ */ jsx(
Tr,
{
"aria-label": "Select all entries",
checked: isAllSelected,
indeterminate: isIndeterminate ? true : void 0,
onCheckedChange: toggleSelectAll
}
) }),
tableHeaders.map((header) => {
const isSorted = sortBy === header.name;
const isAsc = sortOrder === "ASC";
const isSortable = header.metadatas.sortable;
return /* @__PURE__ */ jsx($1, { children: isSortable ? /* @__PURE__ */ jsxs(
SortButton,
{
onClick: () => handleSort(header.name),
"aria-label": `Sort by ${header.metadatas.label}`,
children: [
/* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: header.metadatas.label }),
isSorted && /* @__PURE__ */ jsx(Fragment, { children: isAsc ? /* @__PURE__ */ jsx(Y2, { width: "10px", height: "10px" }) : /* @__PURE__ */ jsx(J2, { width: "10px", height: "10px" }) })
]
}
) : /* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: header.metadatas.label }) }, header.key);
}),
/* @__PURE__ */ jsx($1, { children: /* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: "Actions" }) })
] }) }),
/* @__PURE__ */ jsx(
FirebaseTableRows,
{
onResetPasswordClick,
onDeleteAccountClick,
rows,
entriesToDelete: selectedArray,
onSelectRow: handleSelectRow
}
)
] }) }),
/* @__PURE__ */ jsx(
DeleteAccount,
{
isOpen: showBulkDeleteDialog,
onToggleDialog: () => setShowBulkDeleteDialog(false),
onConfirm: handleBulkDelete,
email: "",
isSingleRecord: false
}
)
] });
};
const fetchUsers = async (query = {}) => {
if (!query.page) {
query.page = 1;
}
if (!query.pageSize) {
query.pageSize = 10;
}
let url = `/${PLUGIN_ID}/users?pagination[page]=${query.page}&pagination[pageSize]=${query.pageSize}`;
if (query.nextPageToken) {
url += `&nextPageToken=${query.nextPageToken}`;
}
if (query.sort) {
url += `&sort=${query.sort}`;
}
if (query.search) {
url += `&search=${encodeURIComponent(query.search)}`;
}
const { get: get2 } = getFetchClient();
const { data: users } = await get2(url);
return users;
};
const createUser = async (userPayload) => {
const url = `/${PLUGIN_ID}/users`;
try {
const { post } = getFetchClient();
const { data: user } = await post(url, userPayload);
return user;
} catch (e2) {
return null;
}
};
const fetchUserByID = async (userID) => {
const url = `/${PLUGIN_ID}/users/${userID}`;
try {
const { get: get2 } = getFetchClient();
const { data: user } = await get2(url);
return user;
} catch (e2) {
return [];
}
};
const deleteUser = async (idToDelete, destination) => {
const url = `/${PLUGIN_ID}/users/${idToDelete}${destination ? `?destination=${destination}` : ""}`;
try {
const { del } = getFetchClient();
const { data: users } = await del(url);
return users.data;
} catch (e2) {
return {};
}
};
const updateUser = async (idToUpdate, payload) => {
const url = `/${PLUGIN_ID}/users/${idToUpdate}`;
const { put } = getFetchClient();
const { data: user } = await put(url, payload);
return user;
};
const resetUserPassword = async (idToUpdate, payload) => {
const url = `/${PLUGIN_ID}/users/resetPassword/${idToUpdate}`;
const { put } = getFetchClient();
const { data: user } = await put(url, payload);
return user;
};
const sendResetEmail = async (userId) => {
const url = `/${PLUGIN_ID}/users/sendResetEmail/${userId}`;
const { put } = getFetchClient();
const { data: result } = await put(url, {});
return result;
};
const getFirebaseConfig = async () => {
const url = `/api/${PLUGIN_ID}/config`;
try {
const { get: get2 } = getFetchClient();
const { data: config } = await get2(url, {
headers: {
"Strapi-Response-Format": "v5"
// Ensure Strapi v5 response format
}
});
return config;
} catch (e2) {
return {
passwordRequirementsRegex: "^.{6,}$",
passwordRequirementsMessage: "Password must be at least 6 characters long",
passwordResetUrl: "http://localhost:3000/reset-password",
passwordResetEmailSubject: "Reset Your Password"
};
}
};
const sendVerificationEmail = async (userId) => {
const url = `/${PLUGIN_ID}/users/sendVerificationEmail/${userId}`;
const { put } = getFetchClient();
const { data: result } = await put(url, {});
return result;
};
const PaginationFooter = ({ pageCount = 0 }) => {
const [{ query }, setQuery] = useQueryParams$1();
const pageSize = query?.pageSize || "10";
const handlePageSizeChange = (value) => {
setQuery({ pageSize: value, page: 1 });
};
return /* @__PURE__ */ jsx(R, { paddingTop: 4, children: /* @__PURE__ */ jsxs(T, { alignItems: "center", justifyContent: "space-between", children: [
/* @__PURE__ */ jsxs(T, { alignItems: "center", gap: 2, children: [
/* @__PURE__ */ jsx(E, { variant: "pi", textColor: "neutral600", children: "Entries per page:" }),
/* @__PURE__ */ jsxs(
bo,
{
size: "S",
value: pageSize,
onChange: handlePageSizeChange,
"aria-label": "Entries per page",
children: [
/* @__PURE__ */ jsx(wo, { value: "10", children: "10" }),
/* @__PURE__ */ jsx(wo, { value: "25", children: "25" }),
/* @__PURE__ */ jsx(wo, { value: "50", children: "50" }),
/* @__PURE__ */ jsx(wo, { value: "100", children: "100" })
]
}
)
] }),
/* @__PURE__ */ jsx(Pagination.Root, { pageCount, children: /* @__PURE__ */ jsx(Pagination.Links, {}) })
] }) });
};
var type = TypeError;
const __viteBrowserExternal = {};
const __viteBrowserExternal$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
default: __viteBrowserExternal
}, Symbol.toStringTag, { value: "Module" }));
const require$$0 = /* @__PURE__ */ getAugmentedNamespace(__viteBrowserExternal$1);
var hasMap = typeof Map === "function" && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === "function" && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var hasWeakMap = typeof WeakMap === "function" && WeakMap.prototype;
var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
var hasWeakSet = typeof WeakSet === "function" && WeakSet.prototype;
var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
var hasWeakRef = typeof WeakRef === "function" && WeakRef.prototype;
var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString = Object.prototype.toString;
var functionToString = Function.prototype.toString;
var $match = String.prototype.match;
var $slice = String.prototype.slice;
var $replace$1 = String.prototype.replace;
var $toUpperCase = String.prototype.toUpperCase;
var $toLowerCase = String.prototype.toLowerCase;
var $test = RegExp.prototype.test;
var $concat$1 = Array.prototype.concat;
var $join = Array.prototype.join;
var $arrSlice = Array.prototype.slice;
var $floor = Math.floor;
var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null;
var gOPS = Object.getOwnPropertySymbols;
var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null;
var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object";
var toStringTag = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null;
var isEnumerable = Object.prototype.propertyIsEnumerable;
var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O2) {
return O2.__proto__;
} : null);
function addNumericSeparator(num, str) {
if (num === Infinity || num === -Infinity || num !== num || num && num > -1e3 && num < 1e3 || $test.call(/e/, str)) {
return str;
}
var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
if (typeof num === "number") {
var int = num < 0 ? -$floor(-num) : $floor(num);
if (int !== num) {
var intStr = String(int);
var dec = $slice.call(str, intStr.length + 1);
return $replace$1.call(intStr, sepRegex, "$&_") + "." + $replace$1.call($replace$1.call(dec, /([0-9]{3})/g, "$&_"), /_$/, "");
}
}
return $replace$1.call(str, sepRegex, "$&_");
}
var utilInspect = require$$0;
var inspectCustom = utilInspect.custom;
var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null;
var quotes = {
__proto__: null,
"double": '"',
single: "'"
};
var quoteREs = {
__proto__: null,
"double": /(["\\])/g,
single: /(['\\])/g
};
var objectInspect = function inspect_(obj, options, depth, seen) {
var opts = options || {};
if (has$3(opts, "quoteStyle") && !has$3(quotes, opts.quoteStyle)) {
throw new TypeError('option "quoteStyle" must be "single" or "double"');
}
if (has$3(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) {
throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
}
var customInspect = has$3(opts, "customInspect") ? opts.customInspect : true;
if (typeof customInspect !== "boolean" && customInspect !== "symbol") {
throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");
}
if (has$3(opts, "indent") && opts.indent !== null && opts.indent !== " " && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) {
throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
}
if (has$3(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") {
throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
}
var numericSeparator = opts.numericSeparator;
if (typeof obj === "undefined") {
return "undefined";
}
if (obj === null) {
return "null";
}
if (typeof obj === "boolean") {
return obj ? "true" : "false";
}
if (typeof obj === "string") {
return inspectString(obj, opts);
}
if (typeof obj === "number") {
if (obj === 0) {
return Infinity / obj > 0 ? "0" : "-0";
}
var str = String(obj);
return numericSeparator ? addNumericSeparator(obj, str) : str;
}
if (typeof obj === "bigint") {
var bigIntStr = String(obj) + "n";
return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;
}
var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth;
if (typeof depth === "undefined") {
depth = 0;
}
if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") {
return isArray$3(obj) ? "[Array]" : "[Object]";
}
var indent = getIndent(opts, depth);
if (typeof seen === "undefined") {
seen = [];
} else if (indexOf(seen, obj) >= 0) {
return "[Circular]";
}
function inspect2(value, from, noIndent) {
if (from) {
seen = $arrSlice.call(seen);
seen.push(from);
}
if (noIndent) {
var newOpts = {
depth: opts.depth
};
if (has$3(opts, "quoteStyle")) {
newOpts.quoteStyle = opts.quoteStyle;
}
return inspect_(value, newOpts, depth + 1, seen);
}
return inspect_(value, opts, depth + 1, seen);
}
if (typeof obj === "function" && !isRegExp$1(obj)) {
var name = nameOf(obj);
var keys2 = arrObjKeys(obj, inspect2);
return "[Function" + (name ? ": " + name : " (anonymous)") + "]" + (keys2.length > 0 ? " { " + $join.call(keys2, ", ") + " }" : "");
}
if (isSymbol(obj)) {
var symString = hasShammedSymbols ? $replace$1.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj);
return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString;
}
if (isElement(obj)) {
var s3 = "<" + $toLowerCase.call(String(obj.nodeName));
var attrs = obj.attributes || [];
for (var i2 = 0; i2 < attrs.length; i2++) {
s3 += " " + attrs[i2].name + "=" + wrapQuotes(quote(attrs[i2].value), "double", opts);
}
s3 += ">";
if (obj.childNodes && obj.childNodes.length) {
s3 += "...";
}
s3 += "</" + $toLowerCase.call(String(obj.nodeName)) + ">";
return s3;
}
if (isArray$3(obj)) {
if (obj.length === 0) {
return "[]";
}
var xs = arrObjKeys(obj, inspect2);
if (indent && !singleLineValues(xs)) {
return "[" + indentedJoin(xs, indent) + "]";
}
return "[ " + $join.call(xs, ", ") + " ]";
}
if (isError(obj)) {
var parts = arrObjKeys(obj, inspect2);
if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) {
return "{ [" + String(obj) + "] " + $join.call($concat$1.call("[cause]: " + inspect2(obj.cause), parts), ", ") + " }";
}
if (parts.length === 0) {
return "[" + String(obj) + "]";
}
return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }";
}
if (typeof obj === "object" && customInspect) {
if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) {
return utilInspect(obj, { depth: maxDepth - depth });
} else if (customInspect !== "symbol" && typeof obj.inspect === "function") {
return obj.inspect();
}
}
if (isMap(obj)) {
var mapParts = [];
if (mapForEach) {
mapForEach.call(obj, function(value, key) {
mapParts.push(inspect2(key, obj, true) + " => " + inspect2(value, obj));
});
}
return collectionOf("Map", mapSize.call(obj), mapParts, indent);
}
if (isSet(obj)) {
var setParts = [];
if (setForEach) {
setForEach.call(obj, function(value) {
setParts.push(inspect2(value, obj));
});
}
return collectionOf("Set", setSize.call(obj), setParts, indent);
}
if (isWeakMap(obj)) {
return weakCollectionOf("WeakMap");
}
if (isWeakSet(obj)) {
return weakCollectionOf("WeakSet");
}
if (isWeakRef(obj)) {
return weakCollectionOf("WeakRef");
}
if (isNumber(obj)) {
return markBoxed(inspect2(Number(obj)));
}
if (isBigInt(obj)) {
return markBoxed(inspect2(bigIntValueOf.call(obj)));
}
if (isBoolean(obj)) {
return markBoxed(booleanValueOf.call(obj));
}
if (isString(obj)) {
return markBoxed(inspect2(String(obj)));
}
if (typeof window !== "undefined" && obj === window) {
return "{ [object Window] }";
}
if (typeof globalThis !== "undefined" && obj === globalThis || typeof commonjsGlobal !== "undefined" && obj === commonjsGlobal) {
return "{ [object globalThis] }";
}
if (!isDate(obj) && !isRegExp$1(obj)) {
var ys = arrObjKeys(obj, inspect2);
var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
var protoTag = obj instanceof Object ? "" : "null prototype";
var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : "";
var constructorTag = isPlainObject || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : "";
var tag = constructorTag + (stringTag || protoTag ? "[" + $join.call($concat$1.call([], stringTag || [], protoTag || []), ": ") + "] " : "");
if (ys.length === 0) {
return tag + "{}";
}
if (indent) {
return tag + "{" + indentedJoin(ys, indent) + "}";
}
return tag + "{ " + $join.call(ys, ", ") + " }";
}
return String(obj);
};
function wrapQuotes(s3, defaultStyle, opts) {
var style = opts.quoteStyle || defaultStyle;
var quoteChar = quotes[style];
return quoteChar + s3 + quoteChar;
}
function quote(s3) {
return $replace$1.call(String(s3), /"/g, """);
}
function canTrustToString(obj) {
return !toStringTag || !(typeof obj === "object" && (toStringTag in obj || typeof obj[toStringTag] !== "undefined"));
}
function isArray$3(obj) {
return toStr(obj) === "[object Array]" && canTrustToString(obj);
}
function isDate(obj) {
return toStr(obj) === "[object Date]" && canTrustToString(obj);
}
function isRegExp$1(obj) {
return toStr(obj) === "[object RegExp]" && canTrustToString(obj);
}
function isError(obj) {
return toStr(obj) === "[object Error]" && canTrustToString(obj);
}
function isString(obj) {
return toStr(obj) === "[object String]" && canTrustToString(obj);
}
function isNumber(obj) {
return toStr(obj) === "[object Number]" && canTrustToString(obj);
}
function isBoolean(obj) {
return toStr(obj) === "[object Boolean]" && canTrustToString(obj);
}
function isSymbol(obj) {
if (hasShammedSymbols) {
return obj && typeof obj === "object" && obj instanceof Symbol;
}
if (typeof obj === "symbol") {
return true;
}
if (!obj || typeof obj !== "object" || !symToString) {
return false;
}
try {
symToString.call(obj);
return true;
} catch (e2) {
}
return false;
}
function isBigInt(obj) {
if (!obj || typeof obj !== "object" || !bigIntValueOf) {
return false;
}
try {
bigIntValueOf.call(obj);
return true;
} catch (e2) {
}
return false;
}
var hasOwn$1 = Object.prototype.hasOwnProperty || function(key) {
return key in this;
};
function has$3(obj, key) {
return hasOwn$1.call(obj, key);
}
function toStr(obj) {
return objectToString.call(obj);
}
function nameOf(f) {
if (f.name) {
return f.name;
}
var m4 = $match.call(functionToString.call(f), /^function\s*([\w$]+)/);
if (m4) {
return m4[1];
}
return null;
}
function indexOf(xs, x2) {
if (xs.indexOf) {
return xs.indexOf(x2);
}
for (var i2 = 0, l = xs.length; i2 < l; i2++) {
if (xs[i2] === x2) {
return i2;
}
}
return -1;
}
function isMap(x2) {
if (!mapSize || !x2 || typeof x2 !== "object") {
return false;
}
try {
mapSize.call(x2);
try {
setSize.call(x2);
} catch (s3) {
return true;
}
return x2 instanceof Map;
} catch (e2) {
}
return false;
}
function isWeakMap(x2) {
if (!weakMapHas || !x2 || typeof x2 !== "object") {
return false;
}
try {
weakMapHas.call(x2, weakMapHas);
try {
weakSetHas.call(x2, weakSetHas);
} catch (s3) {
return true;
}
return x2 instanceof WeakMap;
} catch (e2) {
}
return false;
}
function isWeakRef(x2) {
if (!weakRefDeref || !x2 || typeof x2 !== "object") {
return false;
}
try {
weakRefDeref.call(x2);
return true;
} catch (e2) {
}
return false;
}
function isSet(x2) {
if (!setSize || !x2 || typeof x2 !== "object") {
return false;
}
try {
setSize.call(x2);
try {
mapSize.call(x2);
} catch (m4) {
return true;
}
return x2 instanceof Set;
} catch (e2) {
}
return false;
}
function isWeakSet(x2) {
if (!weakSetHas || !x2 || typeof x2 !== "object") {
return false;
}
try {
weakSetHas.call(x2, weakSetHas);
try {
weakMapHas.call(x2, weakMapHas);
} catch (s3) {
return true;
}
return x2 instanceof WeakSet;
} catch (e2) {
}
return false;
}
function isElement(x2) {
if (!x2 || typeof x2 !== "object") {
return false;
}
if (typeof HTMLElement !== "undefined" && x2 instanceof HTMLElement) {
return true;
}
return typeof x2.nodeName === "string" && typeof x2.getAttribute === "function";
}
function inspectString(str, opts) {
if (str.length > opts.maxStringLength) {
var remaining = str.length - opts.maxStringLength;
var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : "");
return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;
}
var quoteRE = quoteREs[opts.quoteStyle || "single"];
quoteRE.lastIndex = 0;
var s3 = $replace$1.call($replace$1.call(str, quoteRE, "\\$1"), /[\x00-\x1f]/g, lowbyte);
return wrapQuotes(s3, "single", opts);
}
function lowbyte(c2) {
var n = c2.charCodeAt(0);
var x2 = {
8: "b",
9: "t",
10: "n",
12: "f",
13: "r"
}[n];
if (x2) {
return "\\" + x2;
}
return "\\x" + (n < 16 ? "0" : "") + $toUpperCase.call(n.toString(16));
}
function markBoxed(str) {
return "Object(" + str + ")";
}
function weakCollectionOf(type2) {
return type2 + " { ? }";
}
function collectionOf(type2, size, entries, indent) {
var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ", ");
return type2 + " (" + size + ") {" + joinedEntries + "}";
}
function singleLineValues(xs) {
for (var i2 = 0; i2 < xs.length; i2++) {
if (indexOf(xs[i2], "\n") >= 0) {
return false;
}
}
return true;
}
function getIndent(opts, depth) {
var baseIndent;
if (opts.indent === " ") {
baseIndent = " ";
} else if (typeof opts.indent === "number" && opts.indent > 0) {
baseIndent = $join.call(Array(opts.indent + 1), " ");
} else {
return null;
}
return {
base: baseIndent,
prev: $join.call(Array(depth + 1), baseIndent)
};
}
function indentedJoin(xs, indent) {
if (xs.length === 0) {
return "";
}
var lineJoiner = "\n" + indent.prev + indent.base;
return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent.prev;
}
function arrObjKeys(obj, inspect2) {
var isArr = isArray$3(obj);
var xs = [];
if (isArr) {
xs.length = obj.length;
for (var i2 = 0; i2 < obj.length; i2++) {
xs[i2] = has$3(obj, i2) ? inspect2(obj[i2], obj) : "";
}
}
var syms = typeof gOPS === "function" ? gOPS(obj) : [];
var symMap;
if (hasShammedSymbols) {
symMap = {};
for (var k2 = 0; k2 < syms.length; k2++) {
symMap["$" + syms[k2]] = syms[k2];
}
}
for (var key in obj) {
if (!has$3(obj, key)) {
continue;
}
if (isArr && String(Number(key)) === key && key < obj.length) {
continue;
}
if (hasShammedSymbols && symMap["$" + key] instanceof Symbol) {
continue;
} else if ($test.call(/[^\w$]/, key)) {
xs.push(inspect2(key, obj) + ": " + inspect2(obj[key], obj));
} else {
xs.push(key + ": " + inspect2(obj[key], obj));
}
}
if (typeof gOPS === "function") {
for (var j = 0; j < syms.length; j++) {
if (isEnumerable.call(obj, syms[j])) {
xs.push("[" + inspect2(syms[j]) + "]: " + inspect2(obj[syms[j]], obj));
}
}
}
return xs;
}
var inspect$3 = objectInspect;
var $TypeError$5 = type;
var listGetNode = function(list, key, isDelete) {
var prev = list;
var curr;
for (; (curr = prev.next) != null; prev = curr) {
if (curr.key === key) {
prev.next = curr.next;
if (!isDelete) {
curr.next = /** @type {NonNullable<typeof list.next>} */
list.next;
list.next = curr;
}
return curr;
}
}
};
var listGet = function(objects, key) {
if (!objects) {
return void 0;
}
var node = listGetNode(objects, key);
return node && node.value;
};
var listSet = function(objects, key, value) {
var node = listGetNode(objects, key);
if (node) {
node.value = value;
} else {
objects.next = /** @type {import('./list.d.ts').ListNode<typeof value, typeof key>} */
{
// eslint-disable-line no-param-reassign, no-extra-parens
key,
next: objects.next,
value
};
}
};
var listHas = function(objects, key) {
if (!objects) {
return false;
}
return !!listGetNode(objects, key);
};
var listDelete = function(objects, key) {
if (objects) {
return listGetNode(objects, key, true);
}
};
var sideChannelList = function getSideChannelList() {
var $o;
var channel = {
assert: function(key) {
if (!channel.has(key)) {
throw new $TypeError$5("Side channel does not contain " + inspect$3(key));
}
},
"delete": function(key) {
var root = $o && $o.next;
var deletedNode = listDelete($o, key);
if (deletedNode && root && root === deletedNode) {
$o = void 0;
}
return !!deletedNode;
},
get: function(key) {
return listGet($o, key);
},
has: function(key) {
return listHas($o, key);
},
set: function(key, value) {
if (!$o) {
$o = {
next: void 0
};
}
listSet(
/** @type {NonNullable<typeof $o>} */
$o,
key,
value
);
}
};
return channel;
};
var esObjectAtoms = Object;
var esErrors = Error;
var _eval = EvalError;
var range = RangeError;
var ref = ReferenceError;
var syntax = SyntaxError;
var uri = URIError;
var abs$1 = Math.abs;
var floor$1 = Math.floor;
var max$1 = Math.max;
var min$1 = Math.min;
var pow$1 = Math.pow;
var round$1 = Math.round;
var _isNaN = Number.isNaN || function isNaN2(a3) {
return a3 !== a3;
};
var $isNaN = _isNaN;
var sign$1 = function sign(number) {
if ($isNaN(number) || number === 0) {
return number;
}
return number < 0 ? -1 : 1;
};
var gOPD = Object.getOwnPropertyDescriptor;
var $gOPD$1 = gOPD;
if ($gOPD$1) {
try {
$gOPD$1([], "length");
} catch (e2) {
$gOPD$1 = null;
}
}
var gopd = $gOPD$1;
var $defineProperty$1 = Object.defineProperty || false;
if ($defineProperty$1) {
try {
$defineProperty$1({}, "a", { value: 1 });
} catch (e2) {
$defineProperty$1 = false;
}
}
var esDefineProperty = $defineProperty$1;
var shams;
var hasRequiredShams;
function requireShams() {
if (hasRequiredShams) return shams;
hasRequiredShams = 1;
shams = function hasSymbols2() {
if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") {
return false;
}
if (typeof Symbol.iterator === "symbol") {
return true;
}
var obj = {};
var sym = Symbol("test");
var symObj = Object(sym);
if (typeof sym === "string") {
return false;
}
if (Object.prototype.toString.call(sym) !== "[object Symbol]") {
return false;
}
if (Object.prototype.toString.call(symObj) !== "[object Symbol]") {
return false;
}
var symVal = 42;
obj[sym] = symVal;
for (var _ in obj) {
return false;
}
if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) {
return false;
}
if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) {
return false;
}
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) {
return false;
}
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) {
return false;
}
if (typeof Object.getOwnPropertyDescriptor === "function") {
var descriptor = (
/** @type {PropertyDescriptor} */
Object.getOwnPropertyDescriptor(obj, sym)
);
if (descriptor.value !== symVal || descriptor.enumerable !== true) {
return false;
}
}
return true;
};
return shams;
}
var hasSymbols$1;
var hasRequiredHasSymbols;
function requireHasSymbols() {
if (hasRequiredHasSymbols) return hasSymbols$1;
hasRequiredHasSymbols = 1;
var origSymbol = typeof Symbol !== "undefined" && Symbol;
var hasSymbolSham = requireShams();
hasSymbols$1 = function hasNativeSymbols() {
if (typeof origSymbol !== "function") {
return false;
}
if (typeof Symbol !== "function") {
return false;
}
if (typeof origSymbol("foo") !== "symbol") {
return false;
}
if (typeof Symbol("bar") !== "symbol") {
return false;
}
return hasSymbolSham();
};
return hasSymbols$1;
}
var Reflect_getPrototypeOf;
var hasRequiredReflect_getPrototypeOf;
function requireReflect_getPrototypeOf() {
if (hasRequiredReflect_getPrototypeOf) return Reflect_getPrototypeOf;
hasRequiredReflect_getPrototypeOf = 1;
Reflect_getPrototypeOf = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null;
return Reflect_getPrototypeOf;
}
var Object_getPrototypeOf;
var hasRequiredObject_getPrototypeOf;
function requireObject_getPrototypeOf() {
if (hasRequiredObject_getPrototypeOf) return Object_getPrototypeOf;
hasRequiredObject_getPrototypeOf = 1;
var $Object2 = esObjectAtoms;
Object_getPrototypeOf = $Object2.getPrototypeOf || null;
return Object_getPrototypeOf;
}
var implementation;
var hasRequiredImplementation;
function requireImplementation() {
if (hasRequiredImplementation) return implementation;
hasRequiredImplementation = 1;
var ERROR_MESSAGE = "Function.prototype.bind called on incompatible ";
var toStr2 = Object.prototype.toString;
var max2 = Math.max;
var funcType = "[object Function]";
var concatty = function concatty2(a3, b2) {
var arr = [];
for (var i2 = 0; i2 < a3.length; i2 += 1) {
arr[i2] = a3[i2];
}
for (var j = 0; j < b2.length; j += 1) {
arr[j + a3.length] = b2[j];
}
return arr;
};
var slicy = function slicy2(arrLike, offset) {
var arr = [];
for (var i2 = offset, j = 0; i2 < arrLike.length; i2 += 1, j += 1) {
arr[j] = arrLike[i2];
}
return arr;
};
var joiny = function(arr, joiner) {
var str = "";
for (var i2 = 0; i2 < arr.length; i2 += 1) {
str += arr[i2];
if (i2 + 1 < arr.length) {
str += joiner;
}
}
return str;
};
implementation = function bind2(that) {
var target = this;
if (typeof target !== "function" || toStr2.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function() {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max2(0, target.length - args.length);
var boundArgs = [];
for (var i2 = 0; i2 < boundLength; i2++) {
boundArgs[i2] = "$" + i2;
}
bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder);
if (target.prototype) {
var Empty = function Empty2() {
};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
return implementation;
}
var functionBind;
var hasRequiredFunctionBind;
function requireFunctionBind() {
if (hasRequiredFunctionBind) return functionBind;
hasRequiredFunctionBind = 1;
var implementation2 = requireImplementation();
functionBind = Function.prototype.bind || implementation2;
return functionBind;
}
var functionCall;
var hasRequiredFunctionCall;
function requireFunctionCall() {
if (hasRequiredFunctionCall) return functionCall;
hasRequiredFunctionCall = 1;
functionCall = Function.prototype.call;
return functionCall;
}
var functionApply;
var hasRequiredFunctionApply;
function requireFunctionApply() {
if (hasRequiredFunctionApply) return functionApply;
hasRequiredFunctionApply = 1;
functionApply = Function.prototype.apply;
return functionApply;
}
var reflectApply = typeof Reflect !== "undefined" && Reflect && Reflect.apply;
var bind$2 = requireFunctionBind();
var $apply$1 = requireFunctionApply();
var $call$2 = requireFunctionCall();
var $reflectApply = reflectApply;
var actualApply = $reflectApply || bind$2.call($call$2, $apply$1);
var bind$1 = requireFunctionBind();
var $TypeError$4 = type;
var $call$1 = requireFunctionCall();
var $actualApply = actualApply;
var callBindApplyHelpers = function callBindBasic(args) {
if (args.length < 1 || typeof args[0] !== "function") {
throw new $TypeError$4("a function is required");
}
return $actualApply(bind$1, $call$1, args);
};
var get;
var hasRequiredGet;
function requireGet() {
if (hasRequiredGet) return get;
hasRequiredGet = 1;
var callBind = callBindApplyHelpers;
var gOPD2 = gopd;
var hasProtoAccessor;
try {
hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */
[].__proto__ === Array.prototype;
} catch (e2) {
if (!e2 || typeof e2 !== "object" || !("code" in e2) || e2.code !== "ERR_PROTO_ACCESS") {
throw e2;
}
}
var desc = !!hasProtoAccessor && gOPD2 && gOPD2(
Object.prototype,
/** @type {keyof typeof Object.prototype} */
"__proto__"
);
var $Object2 = Object;
var $getPrototypeOf = $Object2.getPrototypeOf;
get = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? (
/** @type {import('./get')} */
function getDunder(value) {
return $getPrototypeOf(value == null ? value : $Object2(value));
}
) : false;
return get;
}
var getProto$1;
var hasRequiredGetProto;
function requireGetProto() {
if (hasRequiredGetProto) return getProto$1;
hasRequiredGetProto = 1;
var reflectGetProto = requireReflect_getPrototypeOf();
var originalGetProto = requireObject_getPrototypeOf();
var getDunderProto = requireGet();
getProto$1 = reflectGetProto ? function getProto2(O2) {
return reflectGetProto(O2);
} : originalGetProto ? function getProto2(O2) {
if (!O2 || typeof O2 !== "object" && typeof O2 !== "function") {
throw new TypeError("getProto: not an object");
}
return originalGetProto(O2);
} : getDunderProto ? function getProto2(O2) {
return getDunderProto(O2);
} : null;
return getProto$1;
}
var hasown;
var hasRequiredHasown;
function requireHasown() {
if (hasRequiredHasown) return hasown;
hasRequiredHasown = 1;
var call = Function.prototype.call;
var $hasOwn = Object.prototype.hasOwnProperty;
var bind2 = requireFunctionBind();
hasown = bind2.call(call, $hasOwn);
return hasown;
}
var undefined$1;
var $Object = esObjectAtoms;
var $Error = esErrors;
var $EvalError = _eval;
var $RangeError = range;
var $ReferenceError = ref;
var $SyntaxError = syntax;
var $TypeError$3 = type;
var $URIError = uri;
var abs = abs$1;
var floor = floor$1;
var max = max$1;
var min = min$1;
var pow = pow$1;
var round = round$1;
var sign2 = sign$1;
var $Function = Function;
var getEvalledConstructor = function(expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")();
} catch (e2) {
}
};
var $gOPD = gopd;
var $defineProperty = esDefineProperty;
var throwTypeError = function() {
throw new $TypeError$3();
};
var ThrowTypeError = $gOPD ? function() {
try {
arguments.callee;
return throwTypeError;
} catch (calleeThrows) {
try {
return $gOPD(arguments, "callee").get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}() : throwTypeError;
var hasSymbols = requireHasSymbols()();
var getProto = requireGetProto();
var $ObjectGPO = requireObject_getPrototypeOf();
var $ReflectGPO = requireReflect_getPrototypeOf();
var $apply = requireFunctionApply();
var $call = requireFunctionCall();
var needsEval = {};
var TypedArray = typeof Uint8Array === "undefined" || !getProto ? undefined$1 : getProto(Uint8Array);
var INTRINSICS = {
__proto__: null,
"%AggregateError%": typeof AggregateError === "undefined" ? undefined$1 : AggregateError,
"%Array%": Array,
"%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined$1 : ArrayBuffer,
"%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined$1,
"%AsyncFromSyncIteratorPrototype%": undefined$1,
"%AsyncFunction%": needsEval,
"%AsyncGenerator%": needsEval,
"%AsyncGeneratorFunction%": needsEval,
"%AsyncIteratorPrototype%": needsEval,
"%Atomics%": typeof Atomics === "undefined" ? undefined$1 : Atomics,
"%BigInt%": typeof BigInt === "undefined" ? undefined$1 : BigInt,
"%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined$1 : BigInt64Array,
"%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined$1 : BigUint64Array,
"%Boolean%": Boolean,
"%DataView%": typeof DataView === "undefined" ? undefined$1 : DataView,
"%Date%": Date,
"%decodeURI%": decodeURI,
"%decodeURIComponent%": decodeURIComponent,
"%encodeURI%": encodeURI,
"%encodeURIComponent%": encodeURIComponent,
"%Error%": $Error,
"%eval%": eval,
// eslint-disable-line no-eval
"%EvalError%": $EvalError,
"%Float16Array%": typeof Float16Array === "undefined" ? undefined$1 : Float16Array,
"%Float32Array%": typeof Float32Array === "undefined" ? undefined$1 : Float32Array,
"%Float64Array%": typeof Float64Array === "undefined" ? undefined$1 : Float64Array,
"%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined$1 : FinalizationRegistry,
"%Function%": $Function,
"%GeneratorFunction%": needsEval,
"%Int8Array%": typeof Int8Array === "undefined" ? undefined$1 : Int8Array,
"%Int16Array%": typeof Int16Array === "undefined" ? undefined$1 : Int16Array,
"%Int32Array%": typeof Int32Array === "undefined" ? undefined$1 : Int32Array,
"%isFinite%": isFinite,
"%isNaN%": isNaN,
"%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined$1,
"%JSON%": typeof JSON === "object" ? JSON : undefined$1,
"%Map%": typeof Map === "undefined" ? undefined$1 : Map,
"%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols || !getProto ? undefined$1 : getProto((/* @__PURE__ */ new Map())[Symbol.iterator]()),
"%Math%": Math,
"%Number%": Number,
"%Object%": $Object,
"%Object.getOwnPropertyDescriptor%": $gOPD,
"%parseFloat%": parseFloat,
"%parseInt%": parseInt,
"%Promise%": typeof Promise === "undefined" ? undefined$1 : Promise,
"%Proxy%": typeof Proxy === "undefined" ? undefined$1 : Proxy,
"%RangeError%": $RangeError,
"%ReferenceError%": $ReferenceError,
"%Reflect%": typeof Reflect === "undefined" ? undefined$1 : Reflect,
"%RegExp%": RegExp,
"%Set%": typeof Set === "undefined" ? undefined$1 : Set,
"%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols || !getProto ? undefined$1 : getProto((/* @__PURE__ */ new Set())[Symbol.iterator]()),
"%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined$1 : SharedArrayBuffer,
"%String%": String,
"%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined$1,
"%Symbol%": hasSymbols ? Symbol : undefined$1,
"%SyntaxError%": $SyntaxError,
"%ThrowTypeError%": ThrowTypeError,
"%TypedArray%": TypedArray,
"%TypeError%": $TypeError$3,
"%Uint8Array%": typeof Uint8Array === "undefined" ? undefined$1 : Uint8Array,
"%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined$1 : Uint8ClampedArray,
"%Uint16Array%": typeof Uint16Array === "undefined" ? undefined$1 : Uint16Array,
"%Uint32Array%": typeof Uint32Array === "undefined" ? undefined$1 : Uint32Array,
"%URIError%": $URIError,
"%WeakMap%": typeof WeakMap === "undefined" ? undefined$1 : WeakMap,
"%WeakRef%": typeof WeakRef === "undefined" ? undefined$1 : WeakRef,
"%WeakSet%": typeof WeakSet === "undefined" ? undefined$1 : WeakSet,
"%Function.prototype.call%": $call,
"%Function.prototype.apply%": $apply,
"%Object.defineProperty%": $defineProperty,
"%Object.getPrototypeOf%": $ObjectGPO,
"%Math.abs%": abs,
"%Math.floor%": floor,
"%Math.max%": max,
"%Math.min%": min,
"%Math.pow%": pow,
"%Math.round%": round,
"%Math.sign%": sign2,
"%Reflect.getPrototypeOf%": $ReflectGPO
};
if (getProto) {
try {
null.error;
} catch (e2) {
var errorProto = getProto(getProto(e2));
INTRINSICS["%Error.prototype%"] = errorProto;
}
}
var doEval = function doEval2(name) {
var value;
if (name === "%AsyncFunction%") {
value = getEvalledConstructor("async function () {}");
} else if (name === "%GeneratorFunction%") {
value = getEvalledConstructor("function* () {}");
} else if (name === "%AsyncGeneratorFunction%") {
value = getEvalledConstructor("async function* () {}");
} else if (name === "%AsyncGenerator%") {
var fn = doEval2("%AsyncGeneratorFunction%");
if (fn) {
value = fn.prototype;
}
} else if (name === "%AsyncIteratorPrototype%") {
var gen = doEval2("%AsyncGenerator%");
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
__proto__: null,
"%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"],
"%ArrayPrototype%": ["Array", "prototype"],
"%ArrayProto_entries%": ["Array", "prototype", "entries"],
"%ArrayProto_forEach%": ["Array", "prototype", "forEach"],
"%ArrayProto_keys%": ["Array", "prototype", "keys"],
"%ArrayProto_values%": ["Array", "prototype", "values"],
"%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"],
"%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"],
"%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"],
"%BooleanPrototype%": ["Boolean", "prototype"],
"%DataViewPrototype%": ["DataView", "prototype"],
"%DatePrototype%": ["Date", "prototype"],
"%ErrorPrototype%": ["Error", "prototype"],
"%EvalErrorPrototype%": ["EvalError", "prototype"],
"%Float32ArrayPrototype%": ["Float32Array", "prototype"],
"%Float64ArrayPrototype%": ["Float64Array", "prototype"],
"%FunctionPrototype%": ["Function", "prototype"],
"%Generator%": ["GeneratorFunction", "prototype"],
"%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"],
"%Int8ArrayPrototype%": ["Int8Array", "prototype"],
"%Int16ArrayPrototype%": ["Int16Array", "prototype"],
"%Int32ArrayPrototype%": ["Int32Array", "prototype"],
"%JSONParse%": ["JSON", "parse"],
"%JSONStringify%": ["JSON", "stringify"],
"%MapPrototype%": ["Map", "prototype"],
"%NumberPrototype%": ["Number", "prototype"],
"%ObjectPrototype%": ["Object", "prototype"],
"%ObjProto_toString%": ["Object", "prototype", "toString"],
"%ObjProto_valueOf%": ["Object", "prototype", "valueOf"],
"%PromisePrototype%": ["Promise", "prototype"],
"%PromiseProto_then%": ["Promise", "prototype", "then"],
"%Promise_all%": ["Promise", "all"],
"%Promise_reject%": ["Promise", "reject"],
"%Promise_resolve%": ["Promise", "resolve"],
"%RangeErrorPrototype%": ["RangeError", "prototype"],
"%ReferenceErrorPrototype%": ["ReferenceError", "prototype"],
"%RegExpPrototype%": ["RegExp", "prototype"],
"%SetPrototype%": ["Set", "prototype"],
"%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"],
"%StringPrototype%": ["String", "prototype"],
"%SymbolPrototype%": ["Symbol", "prototype"],
"%SyntaxErrorPrototype%": ["SyntaxError", "prototype"],
"%TypedArrayPrototype%": ["TypedArray", "prototype"],
"%TypeErrorPrototype%": ["TypeError", "prototype"],
"%Uint8ArrayPrototype%": ["Uint8Array", "prototype"],
"%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"],
"%Uint16ArrayPrototype%": ["Uint16Array", "prototype"],
"%Uint32ArrayPrototype%": ["Uint32Array", "prototype"],
"%URIErrorPrototype%": ["URIError", "prototype"],
"%WeakMapPrototype%": ["WeakMap", "prototype"],
"%WeakSetPrototype%": ["WeakSet", "prototype"]
};
var bind = requireFunctionBind();
var hasOwn = requireHasown();
var $concat = bind.call($call, Array.prototype.concat);
var $spliceApply = bind.call($apply, Array.prototype.splice);
var $replace = bind.call($call, String.prototype.replace);
var $strSlice = bind.call($call, String.prototype.slice);
var $exec = bind.call($call, RegExp.prototype.exec);
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g;
var stringToPath = function stringToPath2(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === "%" && last !== "%") {
throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");
} else if (last === "%" && first !== "%") {
throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");
}
var result = [];
$replace(string, rePropName, function(match2, number, quote2, subString) {
result[result.length] = quote2 ? $replace(subString, reEscapeChar, "$1") : number || match2;
});
return result;
};
var getBaseIntrinsic = function getBaseIntrinsic2(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = "%" + alias[0] + "%";
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === "undefined" && !allowMissing) {
throw new $TypeError$3("intrinsic " + name + " exists, but is not available. Please file an issue!");
}
return {
alias,
name: intrinsicName,
value
};
}
throw new $SyntaxError("intrinsic " + name + " does not exist!");
};
var getIntrinsic = function GetIntrinsic(name, allowMissing) {
if (typeof name !== "string" || name.length === 0) {
throw new $TypeError$3("intrinsic name must be a non-empty string");
}
if (arguments.length > 1 && typeof allowMissing !== "boolean") {
throw new $TypeError$3('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : "";
var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i2 = 1, isOwn = true; i2 < parts.length; i2 += 1) {
var part = parts[i2];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) {
throw new $SyntaxError("property names with quotes must have matching quotes");
}
if (part === "constructor" || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += "." + part;
intrinsicRealName = "%" + intrinsicBaseName + "%";
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError$3("base intrinsic for " + name + " exists, but the property is not available.");
}
return void 0;
}
if ($gOPD && i2 + 1 >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
if (isOwn && "get" in desc && !("originalValue" in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
var GetIntrinsic$2 = getIntrinsic;
var callBindBasic2 = callBindApplyHelpers;
var $indexOf = callBindBasic2([GetIntrinsic$2("%String.prototype.indexOf%")]);
var callBound$2 = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = (
/** @type {(this: unknown, ...args: unknown[]) => unknown} */
GetIntrinsic$2(name, !!allowMissing)
);
if (typeof intrinsic === "function" && $indexOf(name, ".prototype.") > -1) {
return callBindBasic2(
/** @type {const} */
[intrinsic]
);
}
return intrinsic;
};
var GetIntrinsic$1 = getIntrinsic;
var callBound$1 = callBound$2;
var inspect$2 = objectInspect;
var $TypeError$2 = type;
var $Map = GetIntrinsic$1("%Map%", true);
var $mapGet = callBound$1("Map.prototype.get", true);
var $mapSet = callBound$1("Map.prototype.set", true);
var $mapHas = callBound$1("Map.prototype.has", true);
var $mapDelete = callBound$1("Map.prototype.delete", true);
var $mapSize = callBound$1("Map.prototype.size", true);
var sideChannelMap = !!$Map && /** @type {Exclude<import('.'), false>} */
function getSideChannelMap() {
var $m;
var channel = {
assert: function(key) {
if (!channel.has(key)) {
throw new $TypeError$2("Side channel does not contain " + inspect$2(key));
}
},
"delete": function(key) {
if ($m) {
var result = $mapDelete($m, key);
if ($mapSize($m) === 0) {
$m = void 0;
}
return result;
}
return false;
},
get: function(key) {
if ($m) {
return $mapGet($m, key);
}
},
has: function(key) {
if ($m) {
return $mapHas($m, key);
}
return false;
},
set: function(key, value) {
if (!$m) {
$m = new $Map();
}
$mapSet($m, key, value);
}
};
return channel;
};
var GetIntrinsic2 = getIntrinsic;
var callBound = callBound$2;
var inspect$1 = objectInspect;
var getSideChannelMap$1 = sideChannelMap;
var $TypeError$1 = type;
var $WeakMap = GetIntrinsic2("%WeakMap%", true);
var $weakMapGet = callBound("WeakMap.prototype.get", true);
var $weakMapSet = callBound("WeakMap.prototype.set", true);
var $weakMapHas = callBound("WeakMap.prototype.has", true);
var $weakMapDelete = callBound("WeakMap.prototype.delete", true);
var sideChannelWeakmap = $WeakMap ? (
/** @type {Exclude<import('.'), false>} */
function getSideChannelWeakMap() {
var $wm;
var $m;
var channel = {
assert: function(key) {
if (!channel.has(key)) {
throw new $TypeError$1("Side channel does not contain " + inspect$1(key));
}
},
"delete": function(key) {
if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
if ($wm) {
return $weakMapDelete($wm, key);
}
} else if (getSideChannelMap$1) {
if ($m) {
return $m["delete"](key);
}
}
return false;
},
get: function(key) {
if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
if ($wm) {
return $weakMapGet($wm, key);
}
}
return $m && $m.get(key);
},
has: function(key) {
if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
if ($wm) {
return $weakMapHas($wm, key);
}
}
return !!$m && $m.has(key);
},
set: function(key, value) {
if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
if (!$wm) {
$wm = new $WeakMap();
}
$weakMapSet($wm, key, value);
} else if (getSideChannelMap$1) {
if (!$m) {
$m = getSideChannelMap$1();
}
$m.set(key, value);
}
}
};
return channel;
}
) : getSideChannelMap$1;
var $TypeError = type;
var inspect = objectInspect;
var getSideChannelList2 = sideChannelList;
var getSideChannelMap2 = sideChannelMap;
var getSideChannelWeakMap2 = sideChannelWeakmap;
var makeChannel = getSideChannelWeakMap2 || getSideChannelMap2 || getSideChannelList2;
var sideChannel = function getSideChannel() {
var $channelData;
var channel = {
assert: function(key) {
if (!channel.has(key)) {
throw new $TypeError("Side channel does not contain " + inspect(key));
}
},
"delete": function(key) {
return !!$channelData && $channelData["delete"](key);
},
get: function(key) {
return $channelData && $channelData.get(key);
},
has: function(key) {
return !!$channelData && $channelData.has(key);
},
set: function(key, value) {
if (!$channelData) {
$channelData = makeChannel();
}
$channelData.set(key, value);
}
};
return channel;
};
var replace = String.prototype.replace;
var percentTwenties = /%20/g;
var Format = {
RFC1738: "RFC1738",
RFC3986: "RFC3986"
};
var formats$3 = {
"default": Format.RFC3986,
formatters: {
RFC1738: function(value) {
return replace.call(value, percentTwenties, "+");
},
RFC3986: function(value) {
return String(value);
}
},
RFC1738: Format.RFC1738,
RFC3986: Format.RFC3986
};
var formats$2 = formats$3;
var has$2 = Object.prototype.hasOwnProperty;
var isArray$2 = Array.isArray;
var hexTable = function() {
var array = [];
for (var i2 = 0; i2 < 256; ++i2) {
array.push("%" + ((i2 < 16 ? "0" : "") + i2.toString(16)).toUpperCase());
}
return array;
}();
var compactQueue = function compactQueue2(queue) {
while (queue.length > 1) {
var item = queue.pop();
var obj = item.obj[item.prop];
if (isArray$2(obj)) {
var compacted = [];
for (var j = 0; j < obj.length; ++j) {
if (typeof obj[j] !== "undefined") {
compacted.push(obj[j]);
}
}
item.obj[item.prop] = compacted;
}
}
};
var arrayToObject = function arrayToObject2(source, options) {
var obj = options && options.plainObjects ? /* @__PURE__ */ Object.create(null) : {};
for (var i2 = 0; i2 < source.length; ++i2) {
if (typeof source[i2] !== "undefined") {
obj[i2] = source[i2];
}
}
return obj;
};
var merge = function merge2(target, source, options) {
if (!source) {
return target;
}
if (typeof source !== "object") {
if (isArray$2(target)) {
target.push(source);
} else if (target && typeof target === "object") {
if (options && (options.plainObjects || options.allowPrototypes) || !has$2.call(Object.prototype, source)) {
target[source] = true;
}
} else {
return [target, source];
}
return target;
}
if (!target || typeof target !== "object") {
return [target].concat(source);
}
var mergeTarget = target;
if (isArray$2(target) && !isArray$2(source)) {
mergeTarget = arrayToObject(target, options);
}
if (isArray$2(target) && isArray$2(source)) {
source.forEach(function(item, i2) {
if (has$2.call(target, i2)) {
var targetItem = target[i2];
if (targetItem && typeof targetItem === "object" && item && typeof item === "object") {
target[i2] = merge2(targetItem, item, options);
} else {
target.push(item);
}
} else {
target[i2] = item;
}
});
return target;
}
return Object.keys(source).reduce(function(acc, key) {
var value = source[key];
if (has$2.call(acc, key)) {
acc[key] = merge2(acc[key], value, options);
} else {
acc[key] = value;
}
return acc;
}, mergeTarget);
};
var assign = function assignSingleSource(target, source) {
return Object.keys(source).reduce(function(acc, key) {
acc[key] = source[key];
return acc;
}, target);
};
var decode = function(str, decoder, charset) {
var strWithoutPlus = str.replace(/\+/g, " ");
if (charset === "iso-8859-1") {
return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
}
try {
return decodeURIComponent(strWithoutPlus);
} catch (e2) {
return strWithoutPlus;
}
};
var encode = function encode2(str, defaultEncoder, charset, kind, format2) {
if (str.length === 0) {
return str;
}
var string = str;
if (typeof str === "symbol") {
string = Symbol.prototype.toString.call(str);
} else if (typeof str !== "string") {
string = String(str);
}
if (charset === "iso-8859-1") {
return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) {
return "%26%23" + parseInt($0.slice(2), 16) + "%3B";
});
}
var out = "";
for (var i2 = 0; i2 < string.length; ++i2) {
var c2 = string.charCodeAt(i2);
if (c2 === 45 || c2 === 46 || c2 === 95 || c2 === 126 || c2 >= 48 && c2 <= 57 || c2 >= 65 && c2 <= 90 || c2 >= 97 && c2 <= 122 || format2 === formats$2.RFC1738 && (c2 === 40 || c2 === 41)) {
out += string.charAt(i2);
continue;
}
if (c2 < 128) {
out = out + hexTable[c2];
continue;
}
if (c2 < 2048) {
out = out + (hexTable[192 | c2 >> 6] + hexTable[128 | c2 & 63]);
continue;
}
if (c2 < 55296 || c2 >= 57344) {
out = out + (hexTable[224 | c2 >> 12] + hexTable[128 | c2 >> 6 & 63] + hexTable[128 | c2 & 63]);
continue;
}
i2 += 1;
c2 = 65536 + ((c2 & 1023) << 10 | string.charCodeAt(i2) & 1023);
out += hexTable[240 | c2 >> 18] + hexTable[128 | c2 >> 12 & 63] + hexTable[128 | c2 >> 6 & 63] + hexTable[128 | c2 & 63];
}
return out;
};
var compact = function compact2(value) {
var queue = [{ obj: { o: value }, prop: "o" }];
var refs = [];
for (var i2 = 0; i2 < queue.length; ++i2) {
var item = queue[i2];
var obj = item.obj[item.prop];
var keys2 = Object.keys(obj);
for (var j = 0; j < keys2.length; ++j) {
var key = keys2[j];
var val = obj[key];
if (typeof val === "object" && val !== null && refs.indexOf(val) === -1) {
queue.push({ obj, prop: key });
refs.push(val);
}
}
}
compactQueue(queue);
return value;
};
var isRegExp = function isRegExp2(obj) {
return Object.prototype.toString.call(obj) === "[object RegExp]";
};
var isBuffer = function isBuffer2(obj) {
if (!obj || typeof obj !== "object") {
return false;
}
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
var combine = function combine2(a3, b2) {
return [].concat(a3, b2);
};
var maybeMap = function maybeMap2(val, fn) {
if (isArray$2(val)) {
var mapped = [];
for (var i2 = 0; i2 < val.length; i2 += 1) {
mapped.push(fn(val[i2]));
}
return mapped;
}
return fn(val);
};
var utils$2 = {
arrayToObject,
assign,
combine,
compact,
decode,
encode,
isBuffer,
isRegExp,
maybeMap,
merge
};
var getSideChannel2 = sideChannel;
var utils$1 = utils$2;
var formats$1 = formats$3;
var has$1 = Object.prototype.hasOwnProperty;
var arrayPrefixGenerators = {
brackets: function brackets(prefix) {
return prefix + "[]";
},
comma: "comma",
indices: function indices(prefix, key) {
return prefix + "[" + key + "]";
},
repeat: function repeat(prefix) {
return prefix;
}
};
var isArray$1 = Array.isArray;
var push = Array.prototype.push;
var pushToArray = function(arr, valueOrArray) {
push.apply(arr, isArray$1(valueOrArray) ? valueOrArray : [valueOrArray]);
};
var toISO = Date.prototype.toISOString;
var defaultFormat = formats$1["default"];
var defaults$1 = {
addQueryPrefix: false,
allowDots: false,
charset: "utf-8",
charsetSentinel: false,
delimiter: "&",
encode: true,
encoder: utils$1.encode,
encodeValuesOnly: false,
format: defaultFormat,
formatter: formats$1.formatters[defaultFormat],
// deprecated
indices: false,
serializeDate: function serializeDate(date) {
return toISO.call(date);
},
skipNulls: false,
strictNullHandling: false
};
var isNonNullishPrimitive = function isNonNullishPrimitive2(v) {
return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint";
};
var sentinel = {};
var stringify$1 = function stringify(object, prefix, generateArrayPrefix, commaRoundTrip, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate2, format2, formatter, encodeValuesOnly, charset, sideChannel2) {
var obj = object;
var tmpSc = sideChannel2;
var step = 0;
var findFlag = false;
while ((tmpSc = tmpSc.get(sentinel)) !== void 0 && !findFlag) {
var pos = tmpSc.get(object);
step += 1;
if (typeof pos !== "undefined") {
if (pos === step) {
throw new RangeError("Cyclic object value");
} else {
findFlag = true;
}
}
if (typeof tmpSc.get(sentinel) === "undefined") {
step = 0;
}
}
if (typeof filter === "function") {
obj = filter(prefix, obj);
} else if (obj instanceof Date) {
obj = serializeDate2(obj);
} else if (generateArrayPrefix === "comma" && isArray$1(obj)) {
obj = utils$1.maybeMap(obj, function(value2) {
if (value2 instanceof Date) {
return serializeDate2(value2);
}
return value2;
});
}
if (obj === null) {
if (strictNullHandling) {
return encoder && !encodeValuesOnly ? encoder(prefix, defaults$1.encoder, charset, "key", format2) : prefix;
}
obj = "";
}
if (isNonNullishPrimitive(obj) || utils$1.isBuffer(obj)) {
if (encoder) {
var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults$1.encoder, charset, "key", format2);
return [formatter(keyValue) + "=" + formatter(encoder(obj, defaults$1.encoder, charset, "value", format2))];
}
return [formatter(prefix) + "=" + formatter(String(obj))];
}
var values = [];
if (typeof obj === "undefined") {
return values;
}
var objKeys;
if (generateArrayPrefix === "comma" && isArray$1(obj)) {
if (encodeValuesOnly && encoder) {
obj = utils$1.maybeMap(obj, encoder);
}
objKeys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }];
} else if (isArray$1(filter)) {
objKeys = filter;
} else {
var keys2 = Object.keys(obj);
objKeys = sort ? keys2.sort(sort) : keys2;
}
var adjustedPrefix = commaRoundTrip && isArray$1(obj) && obj.length === 1 ? prefix + "[]" : prefix;
for (var j = 0; j < objKeys.length; ++j) {
var key = objKeys[j];
var value = typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key];
if (skipNulls && value === null) {
continue;
}
var keyPrefix = isArray$1(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix : adjustedPrefix + (allowDots ? "." + key : "[" + key + "]");
sideChannel2.set(object, step);
var valueSideChannel = getSideChannel2();
valueSideChannel.set(sentinel, sideChannel2);
pushToArray(values, stringify(
value,
keyPrefix,
generateArrayPrefix,
commaRoundTrip,
strictNullHandling,
skipNulls,
generateArrayPrefix === "comma" && encodeValuesOnly && isArray$1(obj) ? null : encoder,
filter,
sort,
allowDots,
serializeDate2,
format2,
formatter,
encodeValuesOnly,
charset,
valueSideChannel
));
}
return values;
};
var normalizeStringifyOptions = function normalizeStringifyOptions2(opts) {
if (!opts) {
return defaults$1;
}
if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") {
throw new TypeError("Encoder has to be a function.");
}
var charset = opts.charset || defaults$1.charset;
if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
}
var format2 = formats$1["default"];
if (typeof opts.format !== "undefined") {
if (!has$1.call(formats$1.formatters, opts.format)) {
throw new TypeError("Unknown format option provided.");
}
format2 = opts.format;
}
var formatter = formats$1.formatters[format2];
var filter = defaults$1.filter;
if (typeof opts.filter === "function" || isArray$1(opts.filter)) {
filter = opts.filter;
}
return {
addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults$1.addQueryPrefix,
allowDots: typeof opts.allowDots === "undefined" ? defaults$1.allowDots : !!opts.allowDots,
charset,
charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults$1.charsetSentinel,
delimiter: typeof opts.delimiter === "undefined" ? defaults$1.delimiter : opts.delimiter,
encode: typeof opts.encode === "boolean" ? opts.encode : defaults$1.encode,
encoder: typeof opts.encoder === "function" ? opts.encoder : defaults$1.encoder,
encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults$1.encodeValuesOnly,
filter,
format: format2,
formatter,
serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults$1.serializeDate,
skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults$1.skipNulls,
sort: typeof opts.sort === "function" ? opts.sort : null,
strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults$1.strictNullHandling
};
};
var stringify_1 = function(object, opts) {
var obj = object;
var options = normalizeStringifyOptions(opts);
var objKeys;
var filter;
if (typeof options.filter === "function") {
filter = options.filter;
obj = filter("", obj);
} else if (isArray$1(options.filter)) {
filter = options.filter;
objKeys = filter;
}
var keys2 = [];
if (typeof obj !== "object" || obj === null) {
return "";
}
var arrayFormat;
if (opts && opts.arrayFormat in arrayPrefixGenerators) {
arrayFormat = opts.arrayFormat;
} else if (opts && "indices" in opts) {
arrayFormat = opts.indices ? "indices" : "repeat";
} else {
arrayFormat = "indices";
}
var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
if (opts && "commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") {
throw new TypeError("`commaRoundTrip` must be a boolean, or absent");
}
var commaRoundTrip = generateArrayPrefix === "comma" && opts && opts.commaRoundTrip;
if (!objKeys) {
objKeys = Object.keys(obj);
}
if (options.sort) {
objKeys.sort(options.sort);
}
var sideChannel2 = getSideChannel2();
for (var i2 = 0; i2 < objKeys.length; ++i2) {
var key = objKeys[i2];
if (options.skipNulls && obj[key] === null) {
continue;
}
pushToArray(keys2, stringify$1(
obj[key],
key,
generateArrayPrefix,
commaRoundTrip,
options.strictNullHandling,
options.skipNulls,
options.encode ? options.encoder : null,
options.filter,
options.sort,
options.allowDots,
options.serializeDate,
options.format,
options.formatter,
options.encodeValuesOnly,
options.charset,
sideChannel2
));
}
var joined = keys2.join(options.delimiter);
var prefix = options.addQueryPrefix === true ? "?" : "";
if (options.charsetSentinel) {
if (options.charset === "iso-8859-1") {
prefix += "utf8=%26%2310003%3B&";
} else {
prefix += "utf8=%E2%9C%93&";
}
}
return joined.length > 0 ? prefix + joined : "";
};
var utils = utils$2;
var has = Object.prototype.hasOwnProperty;
var isArray = Array.isArray;
var defaults = {
allowDots: false,
allowPrototypes: false,
allowSparse: false,
arrayLimit: 20,
charset: "utf-8",
charsetSentinel: false,
comma: false,
decoder: utils.decode,
delimiter: "&",
depth: 5,
ignoreQueryPrefix: false,
interpretNumericEntities: false,
parameterLimit: 1e3,
parseArrays: true,
plainObjects: false,
strictNullHandling: false
};
var interpretNumericEntities = function(str) {
return str.replace(/&#(\d+);/g, function($0, numberStr) {
return String.fromCharCode(parseInt(numberStr, 10));
});
};
var parseArrayValue = function(val, options) {
if (val && typeof val === "string" && options.comma && val.indexOf(",") > -1) {
return val.split(",");
}
return val;
};
var isoSentinel = "utf8=%26%2310003%3B";
var charsetSentinel = "utf8=%E2%9C%93";
var parseValues = function parseQueryStringValues(str, options) {
var obj = {};
var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, "") : str;
var limit = options.parameterLimit === Infinity ? void 0 : options.parameterLimit;
var parts = cleanStr.split(options.delimiter, limit);
var skipIndex = -1;
var i2;
var charset = options.charset;
if (options.charsetSentinel) {
for (i2 = 0; i2 < parts.length; ++i2) {
if (parts[i2].indexOf("utf8=") === 0) {
if (parts[i2] === charsetSentinel) {
charset = "utf-8";
} else if (parts[i2] === isoSentinel) {
charset = "iso-8859-1";
}
skipIndex = i2;
i2 = parts.length;
}
}
}
for (i2 = 0; i2 < parts.length; ++i2) {
if (i2 === skipIndex) {
continue;
}
var part = parts[i2];
var bracketEqualsPos = part.indexOf("]=");
var pos = bracketEqualsPos === -1 ? part.indexOf("=") : bracketEqualsPos + 1;
var key, val;
if (pos === -1) {
key = options.decoder(part, defaults.decoder, charset, "key");
val = options.strictNullHandling ? null : "";
} else {
key = options.decoder(part.slice(0, pos), defaults.decoder, charset, "key");
val = utils.maybeMap(
parseArrayValue(part.slice(pos + 1), options),
function(encodedVal) {
return options.decoder(encodedVal, defaults.decoder, charset, "value");
}
);
}
if (val && options.interpretNumericEntities && charset === "iso-8859-1") {
val = interpretNumericEntities(val);
}
if (part.indexOf("[]=") > -1) {
val = isArray(val) ? [val] : val;
}
if (has.call(obj, key)) {
obj[key] = utils.combine(obj[key], val);
} else {
obj[key] = val;
}
}
return obj;
};
var parseObject = function(chain, val, options, valuesParsed) {
var leaf = valuesParsed ? val : parseArrayValue(val, options);
for (var i2 = chain.length - 1; i2 >= 0; --i2) {
var obj;
var root = chain[i2];
if (root === "[]" && options.parseArrays) {
obj = [].concat(leaf);
} else {
obj = options.plainObjects ? /* @__PURE__ */ Object.create(null) : {};
var cleanRoot = root.charAt(0) === "[" && root.charAt(root.length - 1) === "]" ? root.slice(1, -1) : root;
var index = parseInt(cleanRoot, 10);
if (!options.parseArrays && cleanRoot === "") {
obj = { 0: leaf };
} else if (!isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit)) {
obj = [];
obj[index] = leaf;
} else if (cleanRoot !== "__proto__") {
obj[cleanRoot] = leaf;
}
}
leaf = obj;
}
return leaf;
};
var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
if (!givenKey) {
return;
}
var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, "[$1]") : givenKey;
var brackets2 = /(\[[^[\]]*])/;
var child = /(\[[^[\]]*])/g;
var segment = options.depth > 0 && brackets2.exec(key);
var parent = segment ? key.slice(0, segment.index) : key;
var keys2 = [];
if (parent) {
if (!options.plainObjects && has.call(Object.prototype, parent)) {
if (!options.allowPrototypes) {
return;
}
}
keys2.push(parent);
}
var i2 = 0;
while (options.depth > 0 && (segment = child.exec(key)) !== null && i2 < options.depth) {
i2 += 1;
if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
if (!options.allowPrototypes) {
return;
}
}
keys2.push(segment[1]);
}
if (segment) {
keys2.push("[" + key.slice(segment.index) + "]");
}
return parseObject(keys2, val, options, valuesParsed);
};
var normalizeParseOptions = function normalizeParseOptions2(opts) {
if (!opts) {
return defaults;
}
if (opts.decoder !== null && opts.decoder !== void 0 && typeof opts.decoder !== "function") {
throw new TypeError("Decoder has to be a function.");
}
if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
}
var charset = typeof opts.charset === "undefined" ? defaults.charset : opts.charset;
return {
allowDots: typeof opts.allowDots === "undefined" ? defaults.allowDots : !!opts.allowDots,
allowPrototypes: typeof opts.allowPrototypes === "boolean" ? opts.allowPrototypes : defaults.allowPrototypes,
allowSparse: typeof opts.allowSparse === "boolean" ? opts.allowSparse : defaults.allowSparse,
arrayLimit: typeof opts.arrayLimit === "number" ? opts.arrayLimit : defaults.arrayLimit,
charset,
charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel,
comma: typeof opts.comma === "boolean" ? opts.comma : defaults.comma,
decoder: typeof opts.decoder === "function" ? opts.decoder : defaults.decoder,
delimiter: typeof opts.delimiter === "string" || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
// eslint-disable-next-line no-implicit-coercion, no-extra-parens
depth: typeof opts.depth === "number" || opts.depth === false ? +opts.depth : defaults.depth,
ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
interpretNumericEntities: typeof opts.interpretNumericEntities === "boolean" ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
parameterLimit: typeof opts.parameterLimit === "number" ? opts.parameterLimit : defaults.parameterLimit,
parseArrays: opts.parseArrays !== false,
plainObjects: typeof opts.plainObjects === "boolean" ? opts.plainObjects : defaults.plainObjects,
strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling
};
};
var parse$1 = function(str, opts) {
var options = normalizeParseOptions(opts);
if (str === "" || str === null || typeof str === "undefined") {
return options.plainObjects ? /* @__PURE__ */ Object.create(null) : {};
}
var tempObj = typeof str === "string" ? parseValues(str, options) : str;
var obj = options.plainObjects ? /* @__PURE__ */ Object.create(null) : {};
var keys2 = Object.keys(tempObj);
for (var i2 = 0; i2 < keys2.length; ++i2) {
var key = keys2[i2];
var newObj = parseKeys(key, tempObj[key], options, typeof str === "string");
obj = utils.merge(obj, newObj, options);
}
if (options.allowSparse === true) {
return obj;
}
return utils.compact(obj);
};
var stringify2 = stringify_1;
var parse = parse$1;
var formats = formats$3;
var lib = {
formats,
parse,
stringify: stringify2
};
const useQueryParams = (initialParams) => {
const { search } = useLocation();
const navigate = useNavigate();
const query = useMemo(() => {
const searchQuery = search.substring(1);
if (!search) {
return initialParams;
}
return lib.parse(searchQuery);
}, [search, initialParams]);
const setQuery = useCallback(
(nextParams, method = "push") => {
let nextQuery = { ...query };
if (method === "remove") {
Object.keys(nextParams).forEach((key) => {
delete nextQuery[key];
});
} else {
nextQuery = { ...query, ...nextParams };
}
navigate({ search: lib.stringify(nextQuery, { encode: false }) });
},
[navigate, query]
);
return { query, rawQuery: search, setQuery };
};
const SearchURLQuery = ({ label, placeholder = void 0 }) => {
const wrapperRef = useRef(null);
const iconButtonRef = useRef(null);
const { query, setQuery } = useQueryParams();
const [value, setValue] = useState(query?.search || "");
const [isOpen, setIsOpen] = useState(!!value);
const { formatMessage } = useIntl();
const handleToggle = () => setIsOpen((prev) => !prev);
useLayoutEffect(() => {
if (isOpen) {
setTimeout(() => {
wrapperRef.current?.querySelector("input").focus();
}, 0);
}
}, [isOpen]);
const handleClear = () => {
setValue("");
setQuery({ search: "" }, "remove");
};
const handleSubmit = (e2) => {
e2.preventDefault();
if (value) {
setQuery({ search: value, page: 1 });
} else {
handleToggle();
setQuery({ search: "" }, "remove");
}
};
if (isOpen) {
return /* @__PURE__ */ jsx("div", { ref: wrapperRef, style: { width: "100%" }, children: /* @__PURE__ */ jsx(h0, { onSubmit: handleSubmit, children: /* @__PURE__ */ jsx(
a0,
{
name: "search",
onChange: ({ target: { value: value2 } }) => setValue(value2),
value,
clearLabel: formatMessage({
id: "clearLabel",
defaultMessage: "Clear"
}),
onClear: handleClear,
size: "S",
placeholder,
children: label
}
) }) });
}
return /* @__PURE__ */ jsx(
ot,
{
ref: iconButtonRef,
variant: "tertiary",
onClick: handleToggle,
"aria-label": formatMessage({
id: "app.component.search.label",
defaultMessage: "Search"
}),
children: /* @__PURE__ */ jsx(un, {})
}
);
};
const ResetPassword = ({
isOpen,
email,
userId,
onClose,
onDirectReset,
onSendResetEmail,
passwordRegex = "^.{6,}$",
passwordMessage = "Password must be at least 6 characters long"
}) => {
const [mode, setMode] = useState("direct");
const [password, setPassword] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [emailSent, setEmailSent] = useState(false);
const [error, setError] = useState("");
const [isPasswordChanged, setIsPasswordChanged] = useState(false);
useEffect(() => {
if (!isOpen) {
resetState();
}
}, [isOpen]);
const resetState = () => {
setPassword("");
setEmailSent(false);
setError("");
setMode("direct");
setIsPasswordChanged(false);
setIsLoading(false);
};
const handleClose = () => {
resetState();
onClose();
};
const validatePassword = (password2) => {
if (!password2) return false;
try {
const regex = new RegExp(passwordRegex);
return regex.test(password2);
} catch (e2) {
console.error("Invalid password regex:", e2);
return password2.length >= 6;
}
};
const handleDirectReset = async () => {
if (!validatePassword(password)) return;
try {
setIsLoading(true);
setError("");
await onDirectReset(password);
handleClose();
} catch (err) {
setError(err.message || "Failed to reset password");
} finally {
setIsLoading(false);
}
};
const handleSendEmail = async () => {
try {
setIsLoading(true);
setError("");
await onSendResetEmail();
setEmailSent(true);
} catch (err) {
setError(err.message || "Failed to send reset email");
} finally {
setIsLoading(false);
}
};
return /* @__PURE__ */ jsx(Km.Root, { open: isOpen, onOpenChange: (open) => !open && handleClose(), children: /* @__PURE__ */ jsxs(Km.Content, { children: [
/* @__PURE__ */ jsx(Km.Header, { children: "Reset Password" }),
/* @__PURE__ */ jsx(Km.Body, { children: /* @__PURE__ */ jsxs(T, { direction: "column", gap: 4, children: [
/* @__PURE__ */ jsxs(T, { direction: "column", gap: 1, children: [
/* @__PURE__ */ jsx(E, { variant: "sigma", children: "User email" }),
/* @__PURE__ */ jsx(E, { children: email })
] }),
/* @__PURE__ */ jsxs(x1.Root, { value: mode, onValueChange: (val) => setMode(val), children: [
/* @__PURE__ */ jsxs(x1.List, { children: [
/* @__PURE__ */ jsx(x1.Trigger, { value: "direct", children: "Set Password Directly" }),
/* @__PURE__ */ jsx(x1.Trigger, { value: "email", children: "Send Reset Email" })
] }),
/* @__PURE__ */ jsx(x1.Content, { value: "direct", children: /* @__PURE__ */ jsxs(T, { direction: "column", gap: 3, paddingTop: 4, children: [
/* @__PURE__ */ jsx(E, { children: "Set a new password for this user. The user will not be notified of this change." }),
/* @__PURE__ */ jsxs(T, { direction: "column", gap: 1, children: [
/* @__PURE__ */ jsx(
G0,
{
type: "password",
label: "New password",
value: password,
onChange: (e2) => {
setIsPasswordChanged(true);
setPassword(e2.target.value);
setError("");
},
error: isPasswordChanged && password && !validatePassword(password) ? passwordMessage : void 0,
required: true
}
),
isPasswordChanged && password && !validatePassword(password) && /* @__PURE__ */ jsx(E, { variant: "pi", textColor: "danger500", children: passwordMessage })
] })
] }) }),
/* @__PURE__ */ jsx(x1.Content, { value: "email", children: /* @__PURE__ */ jsx(T, { direction: "column", gap: 3, paddingTop: 4, children: !emailSent ? /* @__PURE__ */ jsxs(E, { children: [
"Send a password reset email to ",
/* @__PURE__ */ jsx("strong", { children: email }),
". The link will expire in 1 hour."
] }) : /* @__PURE__ */ jsxs(vm, { variant: "success", title: "Email Sent", children: [
"Password reset email has been sent to ",
email
] }) }) })
] }),
error && /* @__PURE__ */ jsx(vm, { variant: "danger", title: "Error", children: error })
] }) }),
/* @__PURE__ */ jsxs(Km.Footer, { children: [
/* @__PURE__ */ jsx(Nn, { onClick: handleClose, variant: "tertiary", children: emailSent ? "Close" : "Cancel" }),
!emailSent && /* @__PURE__ */ jsx(
Nn,
{
variant: mode === "direct" ? "danger-light" : "success",
loading: isLoading,
disabled: mode === "direct" && !validatePassword(password),
onClick: mode === "direct" ? handleDirectReset : handleSendEmail,
children: mode === "direct" ? "Set Password" : "Send Reset Email"
}
)
] })
] }) });
};
const ResendVerification = ({
isOpen,
email,
userId,
onClose,
onSendVerificationEmail
}) => {
const [isLoading, setIsLoading] = useState(false);
const [emailSent, setEmailSent] = useState(false);
const [error, setError] = useState("");
const resetState = () => {
setEmailSent(false);
setError("");
setIsLoading(false);
};
const handleClose = () => {
resetState();
onClose();
};
const handleSendEmail = async () => {
try {
setIsLoading(true);
setError("");
await onSendVerificationEmail();
setEmailSent(true);
} catch (err) {
setError(err.message || "Failed to send verification email");
} finally {
setIsLoading(false);
}
};
return /* @__PURE__ */ jsx(Km.Root, { open: isOpen, onOpenChange: (open) => !open && handleClose(), children: /* @__PURE__ */ jsxs(Km.Content, { children: [
/* @__PURE__ */ jsx(Km.Header, { children: "Resend Verification Email" }),
/* @__PURE__ */ jsx(Km.Body, { children: /* @__PURE__ */ jsxs(T, { direction: "column", gap: 4, alignItems: "center", children: [
!emailSent ? /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsxs(E, { textAlign: "center", children: [
"Send a verification email to ",
/* @__PURE__ */ jsx("strong", { children: email }),
"?"
] }),
/* @__PURE__ */ jsx(E, { variant: "omega", textColor: "neutral600", textAlign: "center", children: "The link will expire in 1 hour." })
] }) : /* @__PURE__ */ jsxs(vm, { variant: "success", title: "Email Sent", children: [
"Verification email has been sent to ",
email
] }),
error && /* @__PURE__ */ jsx(vm, { variant: "danger", title: "Error", children: error })
] }) }),
/* @__PURE__ */ jsxs(Km.Footer, { children: [
/* @__PURE__ */ jsx(Nn, { onClick: handleClose, variant: "tertiary", children: emailSent ? "Close" : "Cancel" }),
!emailSent && /* @__PURE__ */ jsx(Nn, { variant: "success", loading: isLoading, onClick: handleSendEmail, children: "Send" })
] })
] }) });
};
const HEADER_TITLE = "Firebase Users";
const NOTIFICATION_MESSAGES = {
DELETED: "Deleted",
SAVED: "Saved",
RESET_ERROR: "Error resetting password, please try again",
LOAD_ERROR: "Failed to load users. Please try again."
};
const mapUserData = (users) => users.map((item) => ({
id: item.uid,
...item
}));
function ListView({ data, meta }) {
const [showResetPasswordDialogue, setShowResetPasswordDialogue] = useState({
isOpen: false,
email: "",
id: ""
});
const [showDeleteAccountDialogue, setShowDeleteAccountDialogue] = useState({
isOpen: false,
email: "",
id: ""
});
const [rowsData, setRowsData] = useState([]);
const [rowsMeta, setRowsMeta] = useState({
pagination: { page: 1, pageCount: 1, pageSize: 10, total: 0 }
});
const [isLoading, setIsLoading] = useState(false);
const [passwordConfig, setPasswordConfig] = useState({
passwordRequirementsRegex: "^.{6,}$",
passwordRequirementsMessage: "Password must be at least 6 characters long",
passwordResetUrl: "http://localhost:3000/reset-password",
passwordResetEmailSubject: "Reset Your Password"
});
const [query] = useQueryParams$1();
const navigate = useNavigate();
const { toggleNotification } = useNotification();
const { formatMessage } = useIntl();
const queryKey = useMemo(() => JSON.stringify(query.query), [query.query]);
const setNextPageToken = useCallback((page, nextPageToken) => {
const formattedPage = parseInt(page, 10) || 1;
const storeObject = sessionStorage.getItem("nextPageTokens");
const tokens = storeObject ? JSON.parse(storeObject) : {};
tokens[formattedPage + 1] = nextPageToken;
sessionStorage.setItem("nextPageTokens", JSON.stringify(tokens));
}, []);
const getNextPageToken = useCallback((page) => {
const formattedPage = parseInt(page, 10);
const storeObject = sessionStorage.getItem("nextPageTokens");
if (!storeObject) {
return void 0;
}
const tokens = JSON.parse(storeObject);
return tokens[formattedPage];
}, []);
const fetchPaginatedUsers = useCallback(async () => {
const page = query?.query?.page;
const nextPageToken = page ? getNextPageToken(page) : void 0;
const queryWithToken = {
...query.query,
...nextPageToken && { nextPageToken }
};
const response = await fetchUsers(queryWithToken);
if (response.pageToken && page) {
setNextPageToken(page, response.pageToken);
}
return response;
}, [query.query, getNextPageToken, setNextPageToken]);
useEffect(() => {
const fetchConfig = async () => {
try {
const config = await getFirebaseConfig();
setPasswordConfig(config);
} catch (error) {
console.error("Failed to fetch Firebase config:", error);
}
};
fetchConfig();
}, []);
useEffect(() => {
let isMounted = true;
const fetchPaginatedData = async () => {
try {
setIsLoading(true);
const response = await fetchPaginatedUsers();
if (isMounted) {
const mappedData = mapUserData(response.data || []);
setRowsData(mappedData);
setRowsMeta(response.meta);
}
} catch (err) {
if (isMounted) {
toggleNotification({
type: "warning",
message: NOTIFICATION_MESSAGES.LOAD_ERROR
});
}
} finally {
if (isMounted) {
setIsLoading(false);
}
}
};
fetchPaginatedData();
return () => {
isMounted = false;
};
}, [queryKey]);
const fetchData = useCallback(async () => {
try {
setIsLoading(true);
const response = await fetchPaginatedUsers();
const mappedData = mapUserData(response.data);
setRowsData(mappedData);
setRowsMeta(response.meta);
toggleNotification({
type: "success",
message: NOTIFICATION_MESSAGES.DELETED
});
return mappedData;
} catch (err) {
const errorMessage = get$2(err, "response.payload.message", formatMessage({ id: "error.record.delete" }));
toggleNotification({
type: "warning",
message: errorMessage
});
return Promise.reject([]);
} finally {
setIsLoading(false);
}
}, [fetchPaginatedUsers, toggleNotification, formatMessage]);
const handleDeleteAll = useCallback(
async (idsToDelete, destination = null) => {
await Promise.all(idsToDelete.map((id) => deleteUser(id, destination)));
await fetchData();
},
[fetchData]
);
const handleDeleteRecord = useCallback(
async (idsToDelete, destination) => {
await deleteUser(idsToDelete, destination);
const result = await fetchData();
return result;
},
[fetchData]
);
const handleConfirmDeleteData = useCallback(
async (idsToDelete, isStrapiIncluded, isFirebaseIncluded) => {
let destination = null;
if (isStrapiIncluded && isFirebaseIncluded) {
destination = null;
} else if (isStrapiIncluded) {
destination = "strapi";
} else if (isFirebaseIncluded) {
destination = "firebase";
}
const result = await handleDeleteRecord(idsToDelete, destination);
return result;
},
[handleDeleteRecord]
);
const handleNavigateToCreate = useCallback(() => {
navigate("users/create");
}, [navigate]);
const getCreateAction = useCallback(
() => /* @__PURE__ */ jsx(Nn, { onClick: handleNavigateToCreate, startIcon: /* @__PURE__ */ jsx(sn, {}), children: "Create" }),
[handleNavigateToCreate]
);
const handleCloseResetDialogue = useCallback(() => {
setShowResetPasswordDialogue({ isOpen: false, email: "", id: "" });
}, []);
const handleCloseDeleteDialogue = useCallback(() => {
setShowDeleteAccountDialogue({ isOpen: false, email: "", id: "" });
}, []);
const resetPassword = useCallback(
async (newPassword) => {
try {
await resetUserPassword(showResetPasswordDialogue.id, {
password: newPassword
});
handleCloseResetDialogue();
toggleNotification({
type: "success",
message: NOTIFICATION_MESSAGES.SAVED
});
} catch (err) {
toggleNotification({
type: "danger",
message: NOTIFICATION_MESSAGES.RESET_ERROR
});
}
},
[showResetPasswordDialogue.id, handleCloseResetDialogue, toggleNotification]
);
const deleteAccount = useCallback(
async (isStrapiIncluded, isFirebaseIncluded) => {
const newRowsData = await handleConfirmDeleteData(
showDeleteAccountDialogue.id,
isStrapiIncluded,
isFirebaseIncluded
);
handleCloseDeleteDialogue();
setRowsData(newRowsData);
},
[showDeleteAccountDialogue.id, handleConfirmDeleteData, handleCloseDeleteDialogue]
);
const handleResetPasswordClick = useCallback((data2) => {
setShowResetPasswordDialogue({
isOpen: true,
email: data2.email,
id: data2.uid
});
}, []);
const handleDeleteAccountClick = useCallback((data2) => {
setShowDeleteAccountDialogue({
isOpen: true,
email: data2.email,
id: data2.uid
});
}, []);
if (isLoading) {
return /* @__PURE__ */ jsx(Page.Loading, {});
}
const headSubtitle = `Showing ${rowsData?.length || 0} entries`;
return /* @__PURE__ */ jsxs(Page.Main, { children: [
/* @__PURE__ */ jsx(
Layouts.Header,
{
subtitle: headSubtitle,
title: HEADER_TITLE,
navigationAction: /* @__PURE__ */ jsx(zc, { startIcon: /* @__PURE__ */ jsx(U2, {}), to: "/content-manager/", children: "Back" })
}
),
/* @__PURE__ */ jsxs(Layouts.Content, { children: [
/* @__PURE__ */ jsx(
ResetPassword,
{
isOpen: showResetPasswordDialogue.isOpen,
onClose: handleCloseResetDialogue,
onDirectReset: resetPassword,
email: showResetPasswordDialogue.email,
userId: showResetPasswordDialogue.id,
passwordRegex: passwordConfig.passwordRequirementsRegex,
passwordMessage: passwordConfig.passwordRequirementsMessage,
onSendResetEmail: async () => {
try {
await sendResetEmail(showResetPasswordDialogue.id);
toggleNotification({
type: "success",
message: "Password reset email sent successfully"
});
} catch (err) {
toggleNotification({
type: "danger",
message: "Failed to send password reset email"
});
throw err;
}
}
}
),
/* @__PURE__ */ jsx(
DeleteAccount,
{
isOpen: showDeleteAccountDialogue.isOpen,
onToggleDialog: handleCloseDeleteDialogue,
onConfirm: deleteAccount,
email: showDeleteAccountDialogue.email,
isSingleRecord: true
}
),
/* @__PURE__ */ jsx(
FirebaseTable,
{
action: /* @__PURE__ */ jsx(
SearchURLQuery,
{
label: formatMessage(
{
id: "app.component.search.label",
defaultMessage: "Search for {target}"
},
{ target: HEADER_TITLE }
),
placeholder: formatMessage({
id: "app.component.search.placeholder",
defaultMessage: "Search..."
})
}
),
createAction: getCreateAction(),
isLoading,
rows: rowsData,
onConfirmDeleteAll: handleDeleteAll,
onResetPasswordClick: handleResetPasswordClick,
onDeleteAccountClick: handleDeleteAccountClick
}
),
/* @__PURE__ */ jsx(PaginationFooter, { pageCount: rowsMeta?.pagination?.pageCount || 1 })
] })
] });
}
const StyledPageMain = styled(Page.Main)`
overflow-x: hidden;
max-width: 100vw;
`;
const ContentContainer = styled.div`
padding-right: 70px;
width: 100%;
`;
const HomePage = () => {
const { toggleNotification } = useNotification();
const [isNotConfigured, setIsNotConfigured] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const navigate = useNavigate();
useEffect(() => {
const loadData = async () => {
try {
const config = await getFirebaseConfig$1();
if (!config || !config.firebaseConfigJson) {
setIsNotConfigured(true);
setIsLoading(false);
return;
}
setIsNotConfigured(false);
} catch (err) {
setIsNotConfigured(true);
toggleNotification({
type: "warning",
message: "An error occurred"
});
} finally {
setIsLoading(false);
}
};
loadData();
}, [toggleNotification]);
if (isLoading) {
return /* @__PURE__ */ jsx(Page.Loading, {});
}
return /* @__PURE__ */ jsxs(StyledPageMain, { children: [
/* @__PURE__ */ jsx(Page.Title, { children: "Firebase Users" }),
!isNotConfigured ? /* @__PURE__ */ jsx(ContentContainer, { children: /* @__PURE__ */ jsx(T, { direction: "column", alignItems: "stretch", gap: 4, children: /* @__PURE__ */ jsx(ListView, {}) }) }) : /* @__PURE__ */ jsxs(T, { direction: "column", marginTop: 10, children: [
/* @__PURE__ */ jsx(Nn$1, {}),
/* @__PURE__ */ jsx(R, { marginTop: 1, children: /* @__PURE__ */ jsx(E, { children: "Firebase is not configured, please configure Firebase" }) }),
/* @__PURE__ */ jsx(
Nn,
{
marginTop: 3,
onClick: () => {
navigate("/settings/firebase-authentication");
},
children: "Configure firebase"
}
)
] })
] });
};
let PhoneInputTemp = PhoneInputModule;
let unwrapCount = 0;
while (PhoneInputTemp && typeof PhoneInputTemp === "object" && PhoneInputTemp.default && unwrapCount < 5) {
PhoneInputTemp = PhoneInputTemp.default;
unwrapCount++;
}
const PhoneInput = PhoneInputTemp;
const StyledPhoneInputWrapper = styled.div`
width: 100%;
/* Main container styles */
.react-tel-input {
width: 100%;
.form-control {
width: 100%;
height: 40px;
padding: 0 0.75rem 0 58px;
border: 1px solid ${({ theme }) => theme.colors.neutral200};
border-radius: ${({ theme }) => theme.borderRadius};
background: ${({ theme }) => theme.colors.neutral0};
color: ${({ theme }) => theme.colors.neutral800};
font-size: 14px;
font-family:
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Fira Sans",
"Droid Sans", "Helvetica Neue", sans-serif;
transition: all 0.2s;
&:hover {
border-color: ${({ theme }) => theme.colors.neutral300};
}
&:focus {
border-color: ${({ theme }) => theme.colors.primary600};
outline: none;
box-shadow: ${({ theme }) => theme.colors.primary600} 0px 0px 0px 2px;
}
&::placeholder {
color: ${({ theme }) => theme.colors.neutral600};
}
}
}
/* Flag dropdown button styles */
.flag-dropdown {
background: transparent !important;
border: none;
border-right: none;
&.open {
background: transparent !important;
z-index: 1001;
}
.selected-flag {
padding: 0 0.5rem 0 1rem;
height: 40px;
display: flex;
align-items: center;
&:hover {
background: transparent;
}
.arrow {
border-top-color: ${({ theme }) => theme.colors.neutral800};
margin-left: 8px;
}
/* Fix flag background in all interactive states */
&:hover,
&:focus,
&:active,
&.open {
background: transparent;
background-color: transparent;
.arrow {
border-top-color: ${({ theme }) => theme.colors.neutral800};
}
.flag {
background-color: transparent;
}
}
/* Fix flag background flash on initial load */
.flag {
background-color: transparent;
}
}
}
/* Country dropdown list styles */
.country-list {
background: ${({ theme }) => theme.colors.neutral0};
border: 1px solid ${({ theme }) => theme.colors.neutral200};
border-radius: ${({ theme }) => theme.borderRadius};
box-shadow: 0px 8px 16px rgba(0, 0, 0, 0.15);
max-height: 300px;
overflow-y: auto;
z-index: 1002;
margin-top: 4px;
width: 300px;
/* Search field styles */
.search {
background: ${({ theme }) => theme.colors.neutral0};
padding: 10px;
position: sticky;
top: 0;
z-index: 10;
border-bottom: 1px solid ${({ theme }) => theme.colors.neutral200};
.search-box {
width: 100%;
padding: 0.5rem;
border: 1px solid ${({ theme }) => theme.colors.neutral200};
border-radius: ${({ theme }) => theme.borderRadius};
background: ${({ theme }) => theme.colors.neutral0};
color: ${({ theme }) => theme.colors.neutral800};
font-size: 14px;
font-family:
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Fira Sans",
"Droid Sans", "Helvetica Neue", sans-serif;
&:focus {
border-color: ${({ theme }) => theme.colors.primary600};
outline: none;
box-shadow: ${({ theme }) => theme.colors.primary600} 0px 0px 0px 2px;
}
&::placeholder {
color: ${({ theme }) => theme.colors.neutral600};
}
}
}
/* Country item styles */
.country {
padding: 8px 12px;
cursor: pointer;
font-size: 14px;
color: ${({ theme }) => theme.colors.neutral800};
font-family:
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Fira Sans",
"Droid Sans", "Helvetica Neue", sans-serif;
&:hover {
background: ${({ theme }) => theme.colors.neutral100};
}
&.highlight {
background: ${({ theme }) => theme.colors.primary100};
}
/* Country name and dial code */
.country-name {
color: ${({ theme }) => theme.colors.neutral800};
}
.dial-code {
color: ${({ theme }) => theme.colors.neutral600};
}
}
}
`;
const UserFormFields = ({
userData,
onTextInputChange,
onPhoneChange,
onToggleInputChange,
onEmailBlur,
emailError,
phoneError,
showPasswordHint = false,
isPasswordRequired = false,
hasBeenTouched = false
}) => {
return /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsxs(
Fm.Root,
{
style: { width: "50%" },
error: emailError || (hasBeenTouched && !userData?.email && !userData?.phoneNumber ? "Email or Phone Number is required" : void 0),
children: [
/* @__PURE__ */ jsx(Fm.Label, { children: "Email" }),
/* @__PURE__ */ jsx(
G0,
{
id: "email",
name: "email",
autoComplete: "new-password",
onChange: onTextInputChange,
onBlur: onEmailBlur,
value: userData.email || ""
}
),
/* @__PURE__ */ jsx(Fm.Error, {})
]
}
),
/* @__PURE__ */ jsxs(Fm.Root, { style: { width: "50%" }, children: [
/* @__PURE__ */ jsx(Fm.Label, { children: "Display Name" }),
/* @__PURE__ */ jsx(
G0,
{
id: "displayName",
name: "displayName",
autoComplete: "new-password",
onChange: onTextInputChange,
value: userData.displayName || ""
}
)
] }),
/* @__PURE__ */ jsxs(Fm.Root, { style: { width: "50%" }, error: phoneError || void 0, children: [
/* @__PURE__ */ jsx(Fm.Label, { children: "Phone Number" }),
/* @__PURE__ */ jsx(StyledPhoneInputWrapper, { children: /* @__PURE__ */ jsx(
PhoneInput,
{
value: userData.phoneNumber || "",
onChange: (phone) => onPhoneChange("+" + phone),
country: "us",
enableSearch: true,
searchPlaceholder: "Search countries...",
searchStyle: {
width: "100%",
padding: "8px"
},
inputProps: {
placeholder: "+1 (555) 000-0000"
},
containerStyle: {
width: "100%"
},
inputStyle: {
width: "100%"
},
buttonStyle: {
borderRight: "none"
},
dropdownStyle: {
width: "300px"
}
}
) }),
/* @__PURE__ */ jsx(Fm.Error, {}),
/* @__PURE__ */ jsx(Fm.Hint, { children: "E.164 format: +[country code][number] (e.g., +14155552671)" })
] }),
/* @__PURE__ */ jsxs(
Fm.Root,
{
style: { width: "50%" },
error: userData?.password?.length && userData?.password?.length < 6 ? "Password must be at least 6 characters" : void 0,
children: [
/* @__PURE__ */ jsx(Fm.Label, { children: "Password" }),
/* @__PURE__ */ jsx(
G0,
{
id: "password",
name: "password",
type: "password",
autoComplete: "new-password",
onChange: onTextInputChange,
value: userData.password || "",
required: isPasswordRequired
}
),
/* @__PURE__ */ jsx(Fm.Error, {}),
showPasswordHint && /* @__PURE__ */ jsx(Fm.Hint, { children: "Leave empty to keep current password" })
]
}
),
/* @__PURE__ */ jsxs(Fm.Root, { maxWidth: "320px", children: [
/* @__PURE__ */ jsx(Fm.Label, { children: "Disabled" }),
/* @__PURE__ */ jsx(
D1,
{
name: "disabled",
onLabel: "True",
offLabel: "False",
checked: Boolean(userData.disabled),
onChange: onToggleInputChange
}
)
] }),
/* @__PURE__ */ jsxs(Fm.Root, { maxWidth: "320px", children: [
/* @__PURE__ */ jsx(Fm.Label, { children: "Email Verified" }),
/* @__PURE__ */ jsx(
D1,
{
name: "emailVerified",
onLabel: "True",
offLabel: "False",
checked: Boolean(userData.emailVerified),
onChange: onToggleInputChange
}
)
] })
] });
};
const UserFormLayout = ({ children, sidebar }) => {
return /* @__PURE__ */ jsxs(T, { direction: "row", alignItems: "stretch", gap: 4, width: "100%", children: [
/* @__PURE__ */ jsx(
R,
{
background: "neutral0",
borderColor: "neutral150",
hasRadius: true,
padding: 8,
shadow: "tableShadow",
style: { flex: "9 1 0px", minWidth: 0 },
children: /* @__PURE__ */ jsx(T, { direction: "column", gap: 4, alignItems: "stretch", children })
}
),
sidebar && /* @__PURE__ */ jsx(
T,
{
direction: "column",
gap: 4,
style: { flex: "3 1 0px", minWidth: "280px", maxWidth: "380px", alignItems: "stretch" },
children: sidebar
}
)
] });
};
function validateEmail(email) {
if (!email || email.trim() === "") {
return { isValid: true, error: null };
}
const trimmed = email.trim();
if (!validator.isEmail(trimmed)) {
return {
isValid: false,
error: "Please enter a valid email address"
};
}
return { isValid: true, error: null };
}
function validatePhoneNumber(phone) {
if (!phone || phone.trim() === "") {
return { isValid: true, error: null };
}
const trimmed = phone.trim();
if (!trimmed.startsWith("+")) {
return {
isValid: false,
error: "Phone number must be in international format (E.164)"
};
}
return { isValid: true, error: null };
}
const useUserForm = (initialData = {}) => {
const [userData, setUserData] = useState(initialData);
const [emailError, setEmailError] = useState(null);
const [phoneError, setPhoneError] = useState(null);
const [hasBeenTouched, setHasBeenTouched] = useState(false);
const onTextInputChange = useCallback(
(e2) => {
const { name, value } = e2.target;
setUserData((prevState) => ({
...prevState,
[name]: value
}));
if (name === "email" && emailError) {
setEmailError(null);
}
},
[emailError]
);
const onEmailBlur = useCallback((e2) => {
const { value } = e2.target;
const validation = validateEmail(value);
setEmailError(validation.error);
setHasBeenTouched(true);
}, []);
const onPhoneChange = useCallback((value) => {
setUserData((prevState) => ({
...prevState,
phoneNumber: value || ""
}));
const validation = validatePhoneNumber(value);
setPhoneError(validation.error);
}, []);
const onToggleInputChange = useCallback((e2) => {
setUserData((prevState) => ({
...prevState,
[e2.target.name]: e2.target.checked
}));
}, []);
const isEmailEmpty = !userData?.email || userData.email.trim() === "";
const isPhoneEmpty = !userData?.phoneNumber || userData.phoneNumber.trim() === "";
const isSubmitDisabled = isEmailEmpty && isPhoneEmpty || !!(userData?.password?.length && userData?.password?.length < 6) || !!emailError || !!phoneError;
return {
userData,
setUserData,
emailError,
phoneError,
hasBeenTouched,
handlers: {
onTextInputChange,
onEmailBlur,
onPhoneChange,
onToggleInputChange
},
isSubmitDisabled
};
};
const CreateUserForm = () => {
const [isLoading, setIsLoading] = useState(false);
const { toggleNotification } = useNotification();
const navigate = useNavigate();
const { userData, emailError, phoneError, hasBeenTouched, handlers, isSubmitDisabled } = useUserForm();
const createUserHandler = useCallback(async () => {
setIsLoading(true);
try {
const createdUser = await createUser(userData);
if (!createdUser) {
throw new Error("Error creating user");
}
setIsLoading(false);
toggleNotification({
type: "success",
message: "User created successfully"
});
navigate(`/plugins/${PLUGIN_ID}?sort=createdAt:DESC`);
} catch (error) {
console.error("Error creating user:", error);
const errorMessage = error instanceof Error ? error.message : "An error occurred while creating the user";
toggleNotification({
type: "danger",
message: errorMessage
});
setIsLoading(false);
}
}, [userData, toggleNotification, navigate]);
if (isLoading) {
return /* @__PURE__ */ jsx(Page.Loading, {});
}
return /* @__PURE__ */ jsxs(Page.Main, { children: [
/* @__PURE__ */ jsx(
Header,
{
title: "Create User",
onSave: createUserHandler,
isCreatingEntry: true,
initialData: null,
modifiedData: userData,
isLoading,
isSubmitButtonDisabled: isSubmitDisabled
}
),
/* @__PURE__ */ jsx(Layouts.Content, { children: /* @__PURE__ */ jsx(UserFormLayout, { children: /* @__PURE__ */ jsx(
UserFormFields,
{
userData,
onTextInputChange: handlers.onTextInputChange,
onPhoneChange: handlers.onPhoneChange,
onToggleInputChange: handlers.onToggleInputChange,
onEmailBlur: handlers.onEmailBlur,
emailError,
phoneError,
isPasswordRequired: true,
hasBeenTouched
}
) }) })
] });
};
const PasswordResetButton = ({
user,
onClick,
fullWidth = false,
variant = "secondary",
size = "M"
}) => {
const canResetPassword = hasPasswordProvider(user);
const tooltipMessage = getPasswordResetTooltip(user);
const handleClick = () => {
if (canResetPassword && onClick) {
onClick();
}
};
const button = /* @__PURE__ */ jsx(
Nn,
{
onClick: handleClick,
disabled: !canResetPassword,
startIcon: /* @__PURE__ */ jsx(m3, {}),
variant,
size,
fullWidth,
children: "Reset Password"
}
);
if (!canResetPassword) {
return /* @__PURE__ */ jsx(Ar, { label: tooltipMessage, children: /* @__PURE__ */ jsx(R, { children: button }) });
}
return button;
};
const MetaWrapper = styled(R)`
width: 100%;
display: flex;
flex-direction: column;
justify-content: flex-start;
font-size: 18px;
`;
const ContentWrapper = styled(R)`
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 18px;
padding: 5px;
`;
const DetailsButtonWrapper = styled(R)`
width: 100%;
display: flex;
justify-content: flex-end;
align-items: center;
padding: 5px;
`;
const EditUserForm = ({ data }) => {
const [originalUserData] = useState(data);
const [isLoading, setIsLoading] = useState(false);
const [showResetPasswordDialog, setShowResetPasswordDialog] = useState({
isOpen: false,
email: "",
id: ""
});
const [showVerificationDialog, setShowVerificationDialog] = useState({
isOpen: false,
email: "",
id: ""
});
const [passwordConfig, setPasswordConfig] = useState({
passwordRequirementsRegex: "^.{6,}$",
passwordRequirementsMessage: "Password must be at least 6 characters long"
});
const { toggleNotification } = useNotification();
const navigate = useNavigate();
const location = useLocation();
const locationState = location.state || {};
const { userData, setUserData, emailError, phoneError, handlers, isSubmitDisabled } = useUserForm(data);
const updateUserHandler = useCallback(async () => {
setIsLoading(true);
try {
const updatedUser = await updateUser(userData.uid, userData);
const result = updatedUser[0];
if (result?.status === "rejected") {
const errorReason = result.reason;
const errorMessage = errorReason?.message || (errorReason?.code ? `Firebase error: ${errorReason.code}` : null) || "Error updating user";
throw new Error(errorMessage);
}
setUserData(result.value);
setIsLoading(false);
toggleNotification({
type: "success",
message: "User updated successfully"
});
} catch (error) {
console.error("Error updating user:", error);
const errorMessage = error instanceof Error ? error.message : "An error occurred while updating the user";
toggleNotification({
type: "danger",
message: errorMessage
});
setIsLoading(false);
setUserData(data);
}
}, [userData, toggleNotification, data, setUserData]);
useEffect(() => {
const fetchConfig = async () => {
try {
const config = await getFirebaseConfig();
setPasswordConfig({
passwordRequirementsRegex: config.passwordRequirementsRegex,
passwordRequirementsMessage: config.passwordRequirementsMessage
});
} catch (error) {
console.error("Failed to fetch Firebase config:", error);
}
};
fetchConfig();
}, []);
const handleCloseResetDialog = useCallback(() => {
setShowResetPasswordDialog({ isOpen: false, email: "", id: "" });
}, []);
const handleResetPassword = useCallback(
async (newPassword) => {
try {
await resetUserPassword(userData.uid, { password: newPassword });
toggleNotification({
type: "success",
message: "Password reset successfully"
});
handleCloseResetDialog();
} catch (error) {
console.error("Error resetting password:", error);
toggleNotification({
type: "danger",
message: "Failed to reset password"
});
}
},
[userData.uid, toggleNotification, handleCloseResetDialog]
);
const handleSendResetEmail = useCallback(async () => {
try {
await sendResetEmail(userData.uid);
toggleNotification({
type: "success",
message: "Password reset email sent successfully"
});
} catch (error) {
console.error("Error sending reset email:", error);
toggleNotification({
type: "danger",
message: "Failed to send reset email"
});
}
}, [userData.uid, toggleNotification]);
const handleCloseVerificationDialog = useCallback(() => {
setShowVerificationDialog({ isOpen: false, email: "", id: "" });
}, []);
const handleSendVerificationEmail = useCallback(async () => {
await sendVerificationEmail(userData.uid);
}, [userData.uid]);
if (isLoading) {
return /* @__PURE__ */ jsx(Page.Loading, {});
}
return /* @__PURE__ */ jsxs(Page.Main, { children: [
/* @__PURE__ */ jsx(
Header,
{
title: "Edit User",
onSave: updateUserHandler,
initialData: originalUserData,
modifiedData: userData,
isLoading,
isSubmitButtonDisabled: isSubmitDisabled
}
),
/* @__PURE__ */ jsx(Layouts.Content, { children: /* @__PURE__ */ jsx(
UserFormLayout,
{
sidebar: /* @__PURE__ */ jsxs(Fragment, { children: [
/* @__PURE__ */ jsxs(
R,
{
as: "aside",
background: "neutral0",
borderColor: "neutral150",
hasRadius: true,
paddingBottom: 2,
paddingLeft: 4,
paddingRight: 4,
paddingTop: 2,
shadow: "tableShadow",
children: [
/* @__PURE__ */ jsxs(T, { paddingTop: 2, paddingBottom: 2, direction: "column", alignItems: "flex-start", gap: 2, children: [
/* @__PURE__ */ jsxs(T, { gap: 1, children: [
/* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: "Firebase User ID:" }),
/* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: userData.firebaseUserID || userData.uid })
] }),
locationState?.strapiId && /* @__PURE__ */ jsxs(T, { gap: 1, children: [
/* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: "Strapi ID:" }),
/* @__PURE__ */ jsx(
E,
{
variant: "sigma",
textColor: "primary600",
component: "a",
onClick: (e2) => {
e2.preventDefault();
navigate(
`/content-manager/collection-types/plugin::users-permissions.user/${userData.strapiDocumentId || userData.documentId || locationState.strapiDocumentId}`
);
},
style: {
cursor: "pointer",
textDecoration: "underline"
},
children: locationState.strapiId
}
)
] })
] }),
/* @__PURE__ */ jsx(pl, {}),
userData.providerData?.map((provider, index) => /* @__PURE__ */ jsxs(m__default.Fragment, { children: [
index > 0 && /* @__PURE__ */ jsx(pl, {}),
/* @__PURE__ */ jsxs(T, { paddingTop: 2, paddingBottom: 2, direction: "column", alignItems: "flex-start", gap: 2, children: [
/* @__PURE__ */ jsxs(T, { gap: 1, children: [
/* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: "Provider:" }),
/* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: provider.providerId })
] }),
/* @__PURE__ */ jsxs(T, { gap: 1, children: [
/* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: "Identifier:" }),
/* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: provider.uid })
] })
] })
] }, index)),
/* @__PURE__ */ jsx(pl, {}),
/* @__PURE__ */ jsxs(T, { paddingTop: 2, paddingBottom: 2, direction: "column", alignItems: "flex-start", gap: 3, children: [
userData.metadata?.lastSignInTime && /* @__PURE__ */ jsxs(MetaWrapper, { children: [
/* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: "Last Sign In Time" }),
/* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: format(new Date(userData.metadata.lastSignInTime), "yyyy/MM/dd HH:mm z") })
] }),
(userData.metadata?.creationTime || userData.createdAt) && /* @__PURE__ */ jsxs(MetaWrapper, { children: [
/* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: "Creation Time" }),
/* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: userData.metadata?.creationTime ? format(new Date(userData.metadata.creationTime), "yyyy/MM/dd HH:mm z") : userData.createdAt ? format(new Date(userData.createdAt), "yyyy/MM/dd HH:mm z") : "-" })
] })
] })
]
}
),
/* @__PURE__ */ jsx(R, { marginTop: 5, marginBottom: 5 }),
/* @__PURE__ */ jsxs(
R,
{
as: "aside",
background: "neutral0",
borderColor: "neutral150",
hasRadius: true,
paddingBottom: 4,
paddingLeft: 4,
paddingRight: 4,
paddingTop: 4,
shadow: "tableShadow",
children: [
/* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", marginBottom: 2, children: "Account Actions" }),
/* @__PURE__ */ jsxs(T, { direction: "column", gap: 2, children: [
/* @__PURE__ */ jsx(
PasswordResetButton,
{
user: userData,
fullWidth: true,
onClick: () => {
setShowResetPasswordDialog({
isOpen: true,
email: userData.email || "",
id: userData.uid || ""
});
}
}
),
userData.email && !userData.emailVerified && /* @__PURE__ */ jsx(
Nn,
{
variant: "secondary",
fullWidth: true,
onClick: () => {
setShowVerificationDialog({
isOpen: true,
email: userData.email || "",
id: userData.uid || ""
});
},
children: "Resend Verification Email"
}
)
] })
]
}
),
/* @__PURE__ */ jsx(R, { marginTop: 5, marginBottom: 5 }),
userData.localUser && /* @__PURE__ */ jsx(
R,
{
as: "aside",
background: "neutral0",
borderColor: "neutral150",
hasRadius: true,
paddingBottom: 1,
paddingLeft: 2,
paddingRight: 2,
paddingTop: 1,
shadow: "tableShadow",
children: /* @__PURE__ */ jsxs(R, { paddingTop: 2, paddingBottom: 2, children: [
/* @__PURE__ */ jsx(DetailsButtonWrapper, { children: /* @__PURE__ */ jsx(
zc,
{
startIcon: /* @__PURE__ */ jsx(_3, {}),
onClick: () => navigate(
`/content-manager/collection-types/plugin::users-permissions.user/${userData.localUser?.id}`
),
style: { cursor: "pointer" },
children: "Details"
}
) }),
/* @__PURE__ */ jsxs(ContentWrapper, { children: [
/* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: "local user:" }),
/* @__PURE__ */ jsx(E, { variant: "sigma", textColor: "neutral600", children: userData.localUser.username })
] })
] })
}
)
] }),
children: /* @__PURE__ */ jsx(
UserFormFields,
{
userData,
onTextInputChange: handlers.onTextInputChange,
onPhoneChange: handlers.onPhoneChange,
onToggleInputChange: handlers.onToggleInputChange,
onEmailBlur: handlers.onEmailBlur,
emailError,
phoneError,
showPasswordHint: true,
hasBeenTouched: true
}
)
}
) }),
/* @__PURE__ */ jsx(
ResetPassword,
{
isOpen: showResetPasswordDialog.isOpen,
onClose: handleCloseResetDialog,
onDirectReset: handleResetPassword,
email: showResetPasswordDialog.email,
userId: showResetPasswordDialog.id,
passwordRegex: passwordConfig.passwordRequirementsRegex,
passwordMessage: passwordConfig.passwordRequirementsMessage,
onSendResetEmail: handleSendResetEmail
}
),
/* @__PURE__ */ jsx(
ResendVerification,
{
isOpen: showVerificationDialog.isOpen,
onClose: handleCloseVerificationDialog,
email: showVerificationDialog.email,
userId: showVerificationDialog.id,
onSendVerificationEmail: handleSendVerificationEmail
}
)
] });
};
const EditView = () => {
const { id } = useParams();
const { toggleNotification } = useNotification();
const [userData, setUserData] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const loadUser = async () => {
try {
if (!id) {
throw new Error("User ID is required");
}
const user = await fetchUserByID(id);
if (!user) {
throw new Error("User not found");
}
setUserData(user);
} catch (error) {
console.error("Error fetching user:", error);
const errorMessage = error instanceof Error ? error.message : "An error occurred while fetching user data";
toggleNotification({
type: "danger",
message: errorMessage
});
} finally {
setIsLoading(false);
}
};
loadUser();
}, [id, toggleNotification]);
if (isLoading) {
return /* @__PURE__ */ jsx(Page.Loading, {});
}
if (!userData) {
return /* @__PURE__ */ jsx(Page.Error, {});
}
return /* @__PURE__ */ jsx(EditUserForm, { data: userData });
};
const CreateView = () => {
return /* @__PURE__ */ jsx(CreateUserForm, {});
};
const App = () => {
return /* @__PURE__ */ jsx(Provider, { delayDuration: 300, skipDelayDuration: 100, children: /* @__PURE__ */ jsxs(Routes, { children: [
/* @__PURE__ */ jsx(Route, { index: true, element: /* @__PURE__ */ jsx(HomePage, {}) }),
/* @__PURE__ */ jsx(Route, { path: "users/create", element: /* @__PURE__ */ jsx(CreateView, {}) }),
/* @__PURE__ */ jsx(Route, { path: ":id", element: /* @__PURE__ */ jsx(EditView, {}) }),
/* @__PURE__ */ jsx(Route, { path: "*", element: /* @__PURE__ */ jsx(Page.Error, {}) })
] }) });
};
export {
App,
App as default
};