strapi-plugin-magic-sessionmanager 4.8.0 → 4.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +90 -5
  2. package/README.md +379 -641
  3. package/dist/admin/Analytics-dyJmyxO-.mjs +418 -0
  4. package/dist/admin/Analytics-lVDnHBYp.js +420 -0
  5. package/dist/admin/App-CdgiY_Y7.js +1896 -0
  6. package/dist/admin/App-Cgf_CSjw.mjs +1894 -0
  7. package/dist/admin/License-1XUfQty5.js +443 -0
  8. package/dist/admin/License-C4WSYoqY.mjs +443 -0
  9. package/dist/admin/OnlineUsersWidget-DJC4V1KS.mjs +255 -0
  10. package/dist/admin/OnlineUsersWidget-DMPtuIpm.js +274 -0
  11. package/dist/admin/SectionCard-BlWv8CRt.js +54 -0
  12. package/dist/admin/SectionCard-D51bv4Hi.mjs +55 -0
  13. package/dist/admin/Settings-0QsyY7fe.js +3570 -0
  14. package/dist/admin/Settings-DgeuUiMF.mjs +3568 -0
  15. package/dist/admin/de-BFKoGEVT.js +544 -0
  16. package/dist/admin/de-j0oZH9Pz.mjs +544 -0
  17. package/dist/admin/en-UY4Tb5tE.mjs +544 -0
  18. package/dist/admin/en-s7Ksdkcg.js +544 -0
  19. package/dist/admin/es-07OGMe_5.js +544 -0
  20. package/dist/admin/es-DGBcZwQy.mjs +544 -0
  21. package/dist/admin/fr-B6-DWhGO.mjs +544 -0
  22. package/dist/admin/fr-ETj_2UBY.js +544 -0
  23. package/dist/admin/index-Ck19e8qw.mjs +1760 -0
  24. package/dist/admin/index-D-Nr0TCm.js +1761 -0
  25. package/dist/admin/index.js +1 -1
  26. package/dist/admin/index.mjs +2 -2
  27. package/dist/admin/maskSensitiveValue-BWcSjow7.js +9 -0
  28. package/dist/admin/maskSensitiveValue-lLRhN_S7.mjs +10 -0
  29. package/dist/admin/pt-C7PwrQtV.js +544 -0
  30. package/dist/admin/pt-YMRLm9gx.mjs +544 -0
  31. package/dist/server/index.js +1092 -463
  32. package/dist/server/index.mjs +1092 -463
  33. package/package.json +10 -1
  34. package/pics/analytics.png +0 -0
  35. package/pics/dashboard-dark.png +0 -0
  36. package/pics/dashboard.png +0 -0
  37. package/pics/dashboardsessionmodal.png +0 -0
  38. package/pics/mobile-dashboard.png +0 -0
  39. package/pics/mobile-session.png +0 -0
  40. package/pics/sessioninfopanel.png +0 -0
  41. package/pics/settings1.png +0 -0
  42. package/pics/settings2.png +0 -0
  43. package/pics/widget.png +0 -0
  44. package/scripts/geoip-updater.cjs +35 -24
  45. package/dist/admin/Analytics-CaRlu5ad.js +0 -332
  46. package/dist/admin/Analytics-THqDbNX0.mjs +0 -330
  47. package/dist/admin/App-AbZwLHtF.js +0 -1263
  48. package/dist/admin/App-hSh7guii.mjs +0 -1261
  49. package/dist/admin/FormField-C8kIT2NE.mjs +0 -59
  50. package/dist/admin/FormField-b5KBvkrj.js +0 -60
  51. package/dist/admin/License-BXBVwUVu.mjs +0 -299
  52. package/dist/admin/License-CABdPwnd.js +0 -301
  53. package/dist/admin/OnlineUsersWidget-BnWFj9IM.mjs +0 -230
  54. package/dist/admin/OnlineUsersWidget-CPFAACSb.js +0 -230
  55. package/dist/admin/PluginPageLayout-BPFMcgrx.mjs +0 -42
  56. package/dist/admin/PluginPageLayout-DmNzMdqu.js +0 -43
  57. package/dist/admin/Settings-B4DNdeKx.js +0 -2152
  58. package/dist/admin/Settings-C4RsJosh.mjs +0 -2150
  59. package/dist/admin/de-AwIFTd9i.mjs +0 -450
  60. package/dist/admin/de-D23nmqnl.js +0 -450
  61. package/dist/admin/en-C5iYQ0mC.js +0 -450
  62. package/dist/admin/en-D6QEGeRh.mjs +0 -450
  63. package/dist/admin/es-CIXnsG-p.js +0 -435
  64. package/dist/admin/es-CnFfVdKw.mjs +0 -435
  65. package/dist/admin/fr-BglXE-W4.js +0 -435
  66. package/dist/admin/fr-DefoR7uH.mjs +0 -435
  67. package/dist/admin/index-BFVITQ-o.mjs +0 -624
  68. package/dist/admin/index-DlMm-NyK.js +0 -625
  69. package/dist/admin/maskSensitiveValue-1uGWmrfG.mjs +0 -20
  70. package/dist/admin/maskSensitiveValue-B9vhxPad.js +0 -19
  71. package/dist/admin/pt-J5sf7jiY.js +0 -435
  72. package/dist/admin/pt-TODwvNQA.mjs +0 -435
@@ -0,0 +1,1760 @@
1
+ import { useRef, useEffect, forwardRef, useId, Children, useCallback, useMemo, useState } from "react";
2
+ import { jsx, jsxs, Fragment } from "react/jsx-runtime";
3
+ import { Monitor, CheckCircle, WarningCircle, Information, Server, Code, Phone, SignOut, Lock } from "@strapi/icons";
4
+ import { useIntl } from "react-intl";
5
+ import { NavLink } from "react-router-dom";
6
+ import { Typography, Flex, Box, Grid, VisuallyHidden, Badge, Tooltip, Dialog, Button, Link, Loader } from "@strapi/design-system";
7
+ import { Page, Layouts, ConfirmDialog, useRBAC, useFetchClient, useNotification, useForm } from "@strapi/strapi/admin";
8
+ import styled, { css } from "styled-components";
9
+ const strapi = { "name": "magic-sessionmanager", "displayName": "Magic Sessionmanager" };
10
+ const pluginPkg = {
11
+ strapi
12
+ };
13
+ const pluginId = "magic-sessionmanager";
14
+ const PLUGIN_ID = pluginId;
15
+ const Initializer = ({ setPlugin }) => {
16
+ const ref = useRef(setPlugin);
17
+ useEffect(() => {
18
+ if (ref.current) {
19
+ ref.current(pluginId);
20
+ }
21
+ }, []);
22
+ return null;
23
+ };
24
+ const PluginIcon = (props) => /* @__PURE__ */ jsx(Monitor, { "aria-hidden": true, focusable: false, ...props });
25
+ const TONES = {
26
+ danger: "danger",
27
+ success: "success",
28
+ warning: "warning",
29
+ default: "primary"
30
+ };
31
+ const AlertBody = styled(Typography)`
32
+ min-width: 0;
33
+
34
+ & > * {
35
+ display: inline;
36
+ max-width: none;
37
+ margin: 0;
38
+ font-size: inherit;
39
+ font-weight: inherit;
40
+ line-height: inherit;
41
+ color: inherit;
42
+ }
43
+ `;
44
+ const PersistentAlert = forwardRef(function PersistentAlert2({
45
+ variant = "default",
46
+ title,
47
+ titleAs = "p",
48
+ action,
49
+ closeLabel: _closeLabel,
50
+ onClose: _onClose,
51
+ children,
52
+ ...rest
53
+ }, ref) {
54
+ const tone = TONES[variant] || TONES.default;
55
+ const Icon = variant === "success" ? CheckCircle : variant === "danger" || variant === "warning" ? WarningCircle : Information;
56
+ return /* @__PURE__ */ jsxs(
57
+ Flex,
58
+ {
59
+ ref,
60
+ alignItems: "flex-start",
61
+ background: `${tone}100`,
62
+ borderColor: `${tone}200`,
63
+ shadow: "filterShadow",
64
+ gap: 3,
65
+ hasRadius: true,
66
+ padding: 5,
67
+ paddingRight: 6,
68
+ "data-persistent-alert": "",
69
+ ...rest,
70
+ children: [
71
+ /* @__PURE__ */ jsx(Flex, { shrink: 0, width: "2rem", height: "2rem", children: /* @__PURE__ */ jsx(Icon, { "aria-hidden": true, focusable: "false", width: "2rem", height: "2rem", fill: `${tone}700` }) }),
72
+ /* @__PURE__ */ jsxs(
73
+ Flex,
74
+ {
75
+ alignItems: "start",
76
+ gap: action ? 2 : 1,
77
+ wrap: "wrap",
78
+ role: variant === "danger" ? "alert" : "status",
79
+ width: "100%",
80
+ minWidth: 0,
81
+ children: [
82
+ title ? /* @__PURE__ */ jsx(Typography, { fontWeight: "bold", textColor: "neutral800", tag: titleAs, children: title }) : null,
83
+ /* @__PURE__ */ jsx(AlertBody, { tag: "div", variant: "omega", textColor: "neutral800", children }),
84
+ action ? /* @__PURE__ */ jsx(Box, { children: action }) : null
85
+ ]
86
+ }
87
+ )
88
+ ]
89
+ }
90
+ );
91
+ });
92
+ const paragraphRhythm = css`
93
+ p {
94
+ max-width: 72ch;
95
+ margin-block: 0;
96
+ line-height: 1.6;
97
+ text-wrap: pretty;
98
+ }
99
+
100
+ p + p {
101
+ margin-block-start: ${({ theme }) => theme.spaces[3]};
102
+ }
103
+
104
+ li {
105
+ max-width: 72ch;
106
+ line-height: 1.6;
107
+ text-wrap: pretty;
108
+ }
109
+
110
+ li + li {
111
+ margin-block-start: ${({ theme }) => theme.spaces[2]};
112
+ }
113
+ `;
114
+ const ReadableText = styled(Typography)`
115
+ display: block;
116
+ width: 100%;
117
+ min-width: 0;
118
+ max-width: 72ch;
119
+ margin: 0;
120
+ line-height: 1.6;
121
+ text-wrap: pretty;
122
+
123
+ & + & {
124
+ margin-block-start: ${({ theme }) => theme.spaces[3]};
125
+ }
126
+ `;
127
+ const ParagraphGroup = styled.div`
128
+ display: block;
129
+ width: 100%;
130
+ min-width: 0;
131
+ `;
132
+ const InlineParagraphGroup = styled.span`
133
+ display: block;
134
+ width: 100%;
135
+ min-width: 0;
136
+ `;
137
+ const ReadableParagraphs = ({ id, text, ...typographyProps }) => {
138
+ const ParagraphContainer = typographyProps.tag === "span" ? InlineParagraphGroup : ParagraphGroup;
139
+ const paragraphs = String(text ?? "").split(/\n\s*\n/).map((paragraph) => paragraph.trim()).filter(Boolean);
140
+ return /* @__PURE__ */ jsx(ParagraphContainer, { id, "data-readable-paragraphs": "", children: paragraphs.map((paragraph, index2) => /* @__PURE__ */ jsx(
141
+ ReadableText,
142
+ {
143
+ ...typographyProps,
144
+ tag: typographyProps.tag || "p",
145
+ children: paragraph
146
+ },
147
+ `${id || "readable-paragraph"}-${index2}`
148
+ )) });
149
+ };
150
+ const PageContent = styled(Flex)`
151
+ width: 100%;
152
+ min-width: 0;
153
+
154
+ ${paragraphRhythm}
155
+ `;
156
+ const PageShell = ({
157
+ headingId,
158
+ title,
159
+ documentTitle,
160
+ subtitle,
161
+ primaryAction,
162
+ secondaryAction,
163
+ navigationAction,
164
+ startActions,
165
+ endActions,
166
+ children
167
+ }) => {
168
+ const generatedId = useId();
169
+ const titleId = headingId || `page-title-${generatedId.replace(/:/g, "")}`;
170
+ const hasActionBar = Boolean(startActions || endActions);
171
+ const tabTitle = documentTitle || (typeof title === "string" ? title : "");
172
+ return /* @__PURE__ */ jsxs(Page.Main, { "aria-labelledby": titleId, children: [
173
+ tabTitle ? /* @__PURE__ */ jsx(Page.Title, { children: tabTitle }) : null,
174
+ /* @__PURE__ */ jsx(
175
+ Layouts.Header,
176
+ {
177
+ id: titleId,
178
+ title,
179
+ subtitle,
180
+ primaryAction,
181
+ secondaryAction,
182
+ navigationAction
183
+ }
184
+ ),
185
+ hasActionBar ? /* @__PURE__ */ jsx(Layouts.Action, { startActions, endActions }) : null,
186
+ /* @__PURE__ */ jsx(Layouts.Content, { children: /* @__PURE__ */ jsx(
187
+ PageContent,
188
+ {
189
+ direction: "column",
190
+ alignItems: "stretch",
191
+ gap: 6,
192
+ paddingBottom: 8,
193
+ "data-text-rhythm": "page",
194
+ "data-page-shell": "",
195
+ children
196
+ }
197
+ ) })
198
+ ] });
199
+ };
200
+ const ALLOWED_COLUMNS = /* @__PURE__ */ new Set([1, 2, 3, 4, 6]);
201
+ function getGridItemSpans(columns, stackBelow = "medium") {
202
+ const count = ALLOWED_COLUMNS.has(columns) ? columns : 2;
203
+ const col = 12 / count;
204
+ const twoUp = count >= 2 ? 6 : 12;
205
+ if (stackBelow === "small") {
206
+ return { xs: 12, s: twoUp, m: twoUp, col };
207
+ }
208
+ return { xs: 12, s: 12, m: twoUp, col };
209
+ }
210
+ const EqualGrid = ({ columns = 2, stackBelow = "medium", gap = 6, label, children }) => {
211
+ const spans = getGridItemSpans(columns, stackBelow);
212
+ const items = Children.toArray(children).filter(Boolean);
213
+ return /* @__PURE__ */ jsx(
214
+ Grid.Root,
215
+ {
216
+ gap,
217
+ role: label ? "group" : void 0,
218
+ "aria-label": label,
219
+ "data-equal-grid": columns,
220
+ children: items.map((child, index2) => /* @__PURE__ */ jsx(
221
+ Grid.Item,
222
+ {
223
+ col: spans.col,
224
+ m: spans.m,
225
+ s: spans.s,
226
+ xs: spans.xs,
227
+ direction: "column",
228
+ alignItems: "stretch",
229
+ minWidth: 0,
230
+ children: child
231
+ },
232
+ child.key ?? index2
233
+ ))
234
+ }
235
+ );
236
+ };
237
+ const STAT_GRID_FOLD_REM = (4 * 200 + 3 * 16) / 10;
238
+ const DS_SMALL_REM = 52;
239
+ const StatGridFrame = styled.div`
240
+ container-type: inline-size;
241
+ min-width: 0;
242
+
243
+ @container (min-width: ${DS_SMALL_REM}rem) and (max-width: ${STAT_GRID_FOLD_REM - 0.01}rem) {
244
+ [data-equal-grid='4'] > * {
245
+ grid-column: span 6;
246
+ }
247
+ }
248
+
249
+ /* Rows without secondary lines: pin every value to the card bottom, so a
250
+ label that wraps onto two lines does not push its value off the row's line. */
251
+ &[data-align-values] [data-stat-body] {
252
+ flex: 1 1 auto;
253
+ }
254
+
255
+ &[data-align-values] [data-stat-text] {
256
+ justify-content: space-between;
257
+ }
258
+ `;
259
+ const StatGrid = ({ columns = 4, label, alignValues = false, children }) => /* @__PURE__ */ jsx(StatGridFrame, { "data-stat-grid": "", "data-align-values": alignValues ? "" : void 0, children: /* @__PURE__ */ jsx(EqualGrid, { columns, stackBelow: "small", gap: 4, label, children }) });
260
+ const IconTile = styled(Flex)`
261
+ align-self: flex-start;
262
+
263
+ svg {
264
+ width: ${({ theme }) => theme.spaces[5]};
265
+ height: ${({ theme }) => theme.spaces[5]};
266
+ }
267
+
268
+ svg path {
269
+ fill: ${({ theme, $tone }) => theme.colors[`${$tone}600`]};
270
+ }
271
+ `;
272
+ const STAT_TONES = /* @__PURE__ */ new Set([
273
+ "primary",
274
+ "success",
275
+ "warning",
276
+ "danger",
277
+ "neutral",
278
+ "secondary",
279
+ "alternative"
280
+ ]);
281
+ const CardButton = styled(Box)`
282
+ appearance: none;
283
+ font: inherit;
284
+ color: inherit;
285
+ text-align: start;
286
+ cursor: pointer;
287
+ width: 100%;
288
+
289
+ &:hover {
290
+ background: ${({ theme }) => theme.colors.primary100};
291
+ }
292
+ `;
293
+ const StatCard = ({
294
+ label,
295
+ value,
296
+ icon: Icon,
297
+ tone = "neutral",
298
+ description,
299
+ onClick,
300
+ pressed,
301
+ actionLabel
302
+ }) => {
303
+ const safeTone = STAT_TONES.has(tone) ? tone : "neutral";
304
+ const clickable = typeof onClick === "function";
305
+ const buttonProps = clickable ? {
306
+ tag: "button",
307
+ type: "button",
308
+ onClick,
309
+ "aria-pressed": Boolean(pressed),
310
+ "aria-label": actionLabel
311
+ } : {};
312
+ const Card = clickable ? CardButton : Box;
313
+ return /* @__PURE__ */ jsx(
314
+ Card,
315
+ {
316
+ ...buttonProps,
317
+ background: "neutral0",
318
+ hasRadius: true,
319
+ shadow: "tableShadow",
320
+ borderColor: clickable ? pressed ? "primary600" : "neutral150" : void 0,
321
+ padding: 4,
322
+ flex: "1 1 auto",
323
+ minWidth: 0,
324
+ "data-stat-card": safeTone,
325
+ children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, height: "100%", children: [
326
+ /* @__PURE__ */ jsxs(Flex, { gap: 3, alignItems: "stretch", minWidth: 0, "data-stat-body": "", children: [
327
+ Icon ? /* @__PURE__ */ jsx(
328
+ IconTile,
329
+ {
330
+ $tone: safeTone,
331
+ background: `${safeTone}100`,
332
+ hasRadius: true,
333
+ padding: 2,
334
+ shrink: 0,
335
+ justifyContent: "center",
336
+ alignItems: "center",
337
+ "aria-hidden": true,
338
+ children: /* @__PURE__ */ jsx(Icon, { "aria-hidden": true, focusable: false })
339
+ }
340
+ ) : null,
341
+ /* @__PURE__ */ jsxs(
342
+ Flex,
343
+ {
344
+ direction: "column",
345
+ alignItems: "flex-start",
346
+ gap: 1,
347
+ minWidth: 0,
348
+ flex: "1 1 auto",
349
+ "data-stat-text": "",
350
+ children: [
351
+ /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", tag: "span", children: label }),
352
+ /* @__PURE__ */ jsx(Typography, { variant: "beta", textColor: "neutral800", tag: "span", children: value })
353
+ ]
354
+ }
355
+ )
356
+ ] }),
357
+ description ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", tag: "span", children: description }) : null
358
+ ] })
359
+ }
360
+ );
361
+ };
362
+ const MISSING_VALUE_GLYPH = "—";
363
+ const MISSING_VALUE_MESSAGE = Object.freeze({
364
+ messageId: "common.value.missing",
365
+ defaultMessage: "Not available"
366
+ });
367
+ function isMissingValue(value) {
368
+ if (value === null || value === void 0) return true;
369
+ if (typeof value === "number") return !Number.isFinite(value);
370
+ if (value instanceof Date) return !Number.isFinite(value.getTime());
371
+ if (typeof value === "string") {
372
+ const trimmed = value.trim();
373
+ return trimmed === "" || trimmed.toLowerCase() === "unknown";
374
+ }
375
+ return false;
376
+ }
377
+ function presentText(value) {
378
+ if (isMissingValue(value)) return "";
379
+ return String(value).trim();
380
+ }
381
+ const getTranslation = (id) => `${PLUGIN_ID}.${id}`;
382
+ const MissingValue = ({ textColor = "neutral600", variant }) => {
383
+ const { formatMessage } = useIntl();
384
+ const label = formatMessage({
385
+ id: getTranslation(MISSING_VALUE_MESSAGE.messageId),
386
+ defaultMessage: MISSING_VALUE_MESSAGE.defaultMessage
387
+ });
388
+ return /* @__PURE__ */ jsxs(Typography, { textColor, variant, "data-missing-value": "", children: [
389
+ /* @__PURE__ */ jsx("span", { "aria-hidden": "true", children: MISSING_VALUE_GLYPH }),
390
+ /* @__PURE__ */ jsx(VisuallyHidden, { children: label })
391
+ ] });
392
+ };
393
+ const ValueOrMissing = ({ value, children, textColor, variant }) => {
394
+ if (isMissingValue(value)) return /* @__PURE__ */ jsx(MissingValue, { textColor, variant });
395
+ return /* @__PURE__ */ jsx(Fragment, { children: children ?? String(value) });
396
+ };
397
+ const List = styled.dl`
398
+ display: grid;
399
+ grid-template-columns: minmax(0, 1fr);
400
+ gap: ${({ theme }) => theme.spaces[4]};
401
+ column-gap: ${({ theme, $columnGap }) => theme.spaces[$columnGap ?? 4]};
402
+ margin: 0;
403
+ min-width: 0;
404
+
405
+ ${({ theme }) => theme.breakpoints.small} {
406
+ grid-template-columns: repeat(${({ $columns }) => $columns}, minmax(0, 1fr));
407
+ }
408
+
409
+ & > div {
410
+ display: flex;
411
+ flex-direction: column;
412
+ gap: ${({ theme }) => theme.spaces[1]};
413
+ min-width: 0;
414
+ }
415
+
416
+ & > div[data-span='full'] {
417
+ grid-column: 1 / -1;
418
+ }
419
+
420
+ dt,
421
+ dd {
422
+ margin: 0;
423
+ min-width: 0;
424
+ }
425
+
426
+ dd {
427
+ overflow-wrap: break-word;
428
+ }
429
+
430
+ dd[data-wrap='anywhere'] {
431
+ overflow-wrap: anywhere;
432
+ }
433
+ `;
434
+ const PropertyList = ({ items = [], columns = 2, label, columnGap }) => /* @__PURE__ */ jsx(
435
+ List,
436
+ {
437
+ $columns: columns === 1 ? 1 : 2,
438
+ $columnGap: columnGap,
439
+ "aria-label": label,
440
+ "data-property-list": "",
441
+ children: items.filter(Boolean).map((item) => {
442
+ const wrapsAnywhere = item.kind === "id" || item.kind === "email";
443
+ const missing = item.render === void 0 && isMissingValue(item.value);
444
+ return /* @__PURE__ */ jsxs("div", { "data-span": item.fullWidth ? "full" : void 0, children: [
445
+ /* @__PURE__ */ jsx("dt", { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: item.label }) }),
446
+ /* @__PURE__ */ jsx("dd", { "data-wrap": wrapsAnywhere ? "anywhere" : void 0, children: missing ? /* @__PURE__ */ jsx(MissingValue, { variant: "omega" }) : item.render ?? /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", children: String(item.value) }) })
447
+ ] }, item.id);
448
+ })
449
+ }
450
+ );
451
+ const DEFAULT_DATE_OPTIONS = Object.freeze({ dateStyle: "medium", timeStyle: "short" });
452
+ const RELATIVE_UNITS = [
453
+ ["year", 365 * 24 * 60 * 60],
454
+ ["month", 30 * 24 * 60 * 60],
455
+ ["week", 7 * 24 * 60 * 60],
456
+ ["day", 24 * 60 * 60],
457
+ ["hour", 60 * 60],
458
+ ["minute", 60],
459
+ ["second", 1]
460
+ ];
461
+ function toValidDate(value) {
462
+ if (value === null || value === void 0 || value === "") return null;
463
+ const date = value instanceof Date ? value : new Date(value);
464
+ return Number.isFinite(date.getTime()) ? date : null;
465
+ }
466
+ function formatSessionDate(value, locale, fallback = "", options = DEFAULT_DATE_OPTIONS) {
467
+ const date = toValidDate(value);
468
+ if (!date) return fallback;
469
+ try {
470
+ return new Intl.DateTimeFormat(locale || "en", options).format(date);
471
+ } catch {
472
+ return new Intl.DateTimeFormat("en", options).format(date);
473
+ }
474
+ }
475
+ function getRelativeTimeParts(value, now = Date.now()) {
476
+ const date = toValidDate(value);
477
+ const reference = toValidDate(now);
478
+ if (!date || !reference) return null;
479
+ const diffSeconds = Math.round((date.getTime() - reference.getTime()) / 1e3);
480
+ const absolute = Math.abs(diffSeconds);
481
+ if (absolute < 45) return { value: 0, unit: "second" };
482
+ for (const [unit, seconds] of RELATIVE_UNITS) {
483
+ if (absolute >= seconds) {
484
+ const amount = Math.round(diffSeconds / seconds);
485
+ return { value: amount === 0 ? Math.sign(diffSeconds) : amount, unit };
486
+ }
487
+ }
488
+ return { value: 0, unit: "second" };
489
+ }
490
+ function formatRelative(value, locale, { now = Date.now(), fallback = "" } = {}) {
491
+ const parts = getRelativeTimeParts(value, now);
492
+ if (!parts) return fallback;
493
+ const options = { numeric: "auto" };
494
+ try {
495
+ return new Intl.RelativeTimeFormat(locale || "en", options).format(parts.value, parts.unit);
496
+ } catch {
497
+ return new Intl.RelativeTimeFormat("en", options).format(parts.value, parts.unit);
498
+ }
499
+ }
500
+ const API_CLIENTS = [
501
+ ["curl/", "cURL"],
502
+ ["postman", "Postman"],
503
+ ["insomnia", "Insomnia"],
504
+ ["okhttp", "OkHttp"],
505
+ ["python-requests", "Python Requests"],
506
+ ["axios/", "Axios"],
507
+ ["node-fetch", "node-fetch"],
508
+ ["undici", "undici"],
509
+ ["go-http-client", "Go HTTP client"],
510
+ ["cfnetwork/", "CFNetwork"],
511
+ ["dart/", "Dart"],
512
+ ["java/", "Java"],
513
+ ["wget/", "Wget"],
514
+ ["httpie/", "HTTPie"]
515
+ ];
516
+ const RUNTIME_AGENTS = Object.freeze({ node: "Node.js", deno: "Deno", bun: "Bun" });
517
+ const BOT_PATTERN = /bot\b|crawler|spider|slurp|headlesschrome/i;
518
+ const TABLET_PATTERN = /(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i;
519
+ const MOBILE_PATTERN = /Mobile|Android|iP(?:hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(?:hpw|web)OS|Opera M(?:obi|ini)/;
520
+ const LEGACY_DEVICE_LABELS = Object.freeze({
521
+ desktop: "Desktop",
522
+ mobile: "Mobile",
523
+ tablet: "Tablet",
524
+ api: "API Client",
525
+ bot: "Bot",
526
+ "": ""
527
+ });
528
+ const detectBrowser = (ua) => {
529
+ if (ua.includes("edg/") || ua.includes("edga/") || ua.includes("edgios/")) return "Edge";
530
+ if (ua.includes("opr/") || ua.includes("opera")) return "Opera";
531
+ if (ua.includes("firefox/") || ua.includes("fxios/")) return "Firefox";
532
+ if (ua.includes("chrome/") || ua.includes("crios/")) return "Chrome";
533
+ if (ua.includes("safari/")) return "Safari";
534
+ return "";
535
+ };
536
+ const detectOs = (ua) => {
537
+ if (ua.includes("android")) return "Android";
538
+ if (ua.includes("iphone") || ua.includes("ipad") || ua.includes("ipod")) return "iOS";
539
+ if (ua.includes("windows")) return "Windows";
540
+ if (ua.includes("cros")) return "ChromeOS";
541
+ if (ua.includes("mac os x") || ua.includes("macintosh")) return "macOS";
542
+ if (ua.includes("linux") || ua.includes("x11")) return "Linux";
543
+ return "";
544
+ };
545
+ const DESKTOP_OPERATING_SYSTEMS = /* @__PURE__ */ new Set(["Windows", "macOS", "Linux", "ChromeOS"]);
546
+ function parseUserAgent(userAgent) {
547
+ const raw = typeof userAgent === "string" ? userAgent.trim() : "";
548
+ if (!raw || raw.toLowerCase() === "unknown") {
549
+ return { deviceType: "", device: "", deviceIcon: "unknown", browser: "", os: "" };
550
+ }
551
+ const ua = raw.toLowerCase();
552
+ const runtime = RUNTIME_AGENTS[ua.split("/")[0]];
553
+ if (runtime && !ua.includes(" ")) {
554
+ return {
555
+ deviceType: "api",
556
+ device: LEGACY_DEVICE_LABELS.api,
557
+ deviceIcon: "api",
558
+ browser: runtime,
559
+ os: ""
560
+ };
561
+ }
562
+ const apiClient = API_CLIENTS.find(([needle]) => ua.includes(needle));
563
+ if (apiClient) {
564
+ return {
565
+ deviceType: "api",
566
+ device: LEGACY_DEVICE_LABELS.api,
567
+ deviceIcon: "api",
568
+ browser: apiClient[1],
569
+ os: detectOs(ua)
570
+ };
571
+ }
572
+ const browser = detectBrowser(ua);
573
+ const os = detectOs(ua);
574
+ let deviceType = "";
575
+ if (BOT_PATTERN.test(raw)) deviceType = "bot";
576
+ else if (TABLET_PATTERN.test(raw)) deviceType = "tablet";
577
+ else if (MOBILE_PATTERN.test(raw)) deviceType = "mobile";
578
+ else if (DESKTOP_OPERATING_SYSTEMS.has(os)) deviceType = "desktop";
579
+ return {
580
+ deviceType,
581
+ device: LEGACY_DEVICE_LABELS[deviceType],
582
+ deviceIcon: deviceType || "unknown",
583
+ browser,
584
+ os
585
+ };
586
+ }
587
+ const BROWSER_VERSION_PATTERNS = [
588
+ /\bEdg(?:A|iOS)?\/([\d.]+)/i,
589
+ /\bOPR\/([\d.]+)/i,
590
+ /\b(?:Chrome|CriOS)\/([\d.]+)/i,
591
+ /\bFirefox\/([\d.]+)/i,
592
+ /\bVersion\/([\d.]+).*Safari/i
593
+ ];
594
+ function getBrowserVersionFromUserAgent(userAgent) {
595
+ if (typeof userAgent !== "string" || !userAgent.trim() || userAgent.trim().toLowerCase() === "unknown") {
596
+ return "";
597
+ }
598
+ for (const pattern of BROWSER_VERSION_PATTERNS) {
599
+ const match = userAgent.match(pattern);
600
+ if (match?.[1]) return match[1];
601
+ }
602
+ return "";
603
+ }
604
+ const DEVICE_TYPE_MESSAGES = Object.freeze({
605
+ desktop: Object.freeze({ messageId: "common.device.type.desktop", defaultMessage: "Desktop" }),
606
+ mobile: Object.freeze({ messageId: "common.device.type.mobile", defaultMessage: "Mobile" }),
607
+ tablet: Object.freeze({ messageId: "common.device.type.tablet", defaultMessage: "Tablet" }),
608
+ api: Object.freeze({ messageId: "common.device.type.api", defaultMessage: "API client" }),
609
+ bot: Object.freeze({ messageId: "common.device.type.bot", defaultMessage: "Bot" }),
610
+ unknown: Object.freeze({
611
+ messageId: "common.device.type.unknown",
612
+ defaultMessage: "Unknown device"
613
+ })
614
+ });
615
+ const DEVICE_SUMMARY_MESSAGE = Object.freeze({
616
+ messageId: "common.device.summary",
617
+ defaultMessage: "{browser} · {os}"
618
+ });
619
+ const DEVICE_TYPE_ALIASES = Object.freeze({
620
+ desktop: "desktop",
621
+ laptop: "desktop",
622
+ pc: "desktop",
623
+ computer: "desktop",
624
+ mobile: "mobile",
625
+ phone: "mobile",
626
+ smartphone: "mobile",
627
+ tablet: "tablet",
628
+ "api client": "api",
629
+ api: "api",
630
+ apiclient: "api",
631
+ bot: "bot",
632
+ crawler: "bot"
633
+ });
634
+ function normalizeDeviceType(value) {
635
+ if (typeof value !== "string") return "";
636
+ const key = value.trim().toLowerCase().replace(/[\s_-]+/g, " ");
637
+ return DEVICE_TYPE_ALIASES[key] || DEVICE_TYPE_ALIASES[key.replace(/ /g, "")] || "";
638
+ }
639
+ function getDeviceTypeMessage(deviceType) {
640
+ return DEVICE_TYPE_MESSAGES[deviceType] || DEVICE_TYPE_MESSAGES.unknown;
641
+ }
642
+ const TRAILING_VERSION = /\s+v?\d[\w./-]*$/i;
643
+ function splitNameAndVersion(value) {
644
+ let name2 = presentText(value);
645
+ const versions = [];
646
+ while (TRAILING_VERSION.test(name2)) {
647
+ const match = name2.match(TRAILING_VERSION);
648
+ versions.unshift(match[0].trim());
649
+ name2 = name2.slice(0, match.index).trim();
650
+ }
651
+ return { name: presentText(name2), version: versions.join(" ") };
652
+ }
653
+ function getDevicePresentation(session = {}) {
654
+ const row = session || {};
655
+ const userAgent = presentText(row.userAgent);
656
+ const parsed = userAgent ? parseUserAgent(userAgent) : null;
657
+ const storedBrowser = splitNameAndVersion(row.browserName);
658
+ const storedOs = splitNameAndVersion(row.osName);
659
+ const deviceType = parsed ? parsed.deviceType : normalizeDeviceType(row.deviceType);
660
+ const browser = parsed?.browser || storedBrowser.name;
661
+ const os = parsed?.os || storedOs.name;
662
+ const browserVersion = userAgent && getBrowserVersionFromUserAgent(userAgent) || presentText(row.browserVersion) || storedBrowser.version;
663
+ let summary = { text: "" };
664
+ if (browser && os) {
665
+ summary = { ...DEVICE_SUMMARY_MESSAGE, values: { browser, os } };
666
+ } else if (browser || os) {
667
+ summary = { text: browser || os };
668
+ }
669
+ return {
670
+ deviceType,
671
+ hasDeviceType: Boolean(deviceType),
672
+ icon: deviceType || "unknown",
673
+ deviceTypeMessage: getDeviceTypeMessage(deviceType),
674
+ browser,
675
+ browserVersion,
676
+ browserLabel: browser,
677
+ os,
678
+ hasSummary: Boolean(browser || os),
679
+ summary
680
+ };
681
+ }
682
+ const SESSION_STATES = Object.freeze(["active", "idle", "ended"]);
683
+ const SESSION_END_REASONS = Object.freeze([
684
+ "logout",
685
+ "idle",
686
+ "expired",
687
+ "manual",
688
+ "blocked",
689
+ "unrecorded"
690
+ ]);
691
+ const RECORDED_END_REASONS = /* @__PURE__ */ new Set(["logout", "idle", "expired", "manual", "blocked"]);
692
+ const ACTIVE_DEFINITION = Object.freeze({
693
+ messageId: "common.status.active.definition",
694
+ defaultMessage: "Open and used within the inactivity timeout."
695
+ });
696
+ const SESSION_STATUS_PRESENTATION = Object.freeze({
697
+ active: Object.freeze({
698
+ tone: "success",
699
+ messageId: "common.status.active",
700
+ defaultMessage: "Active",
701
+ // B.3 tooltip and A.3 definition are the same sentence: one message.
702
+ help: ACTIVE_DEFINITION,
703
+ definition: ACTIVE_DEFINITION
704
+ }),
705
+ idle: Object.freeze({
706
+ tone: "warning",
707
+ messageId: "common.status.idle",
708
+ defaultMessage: "Idle",
709
+ help: Object.freeze({
710
+ messageId: "common.status.idle.help",
711
+ defaultMessage: "Still open. It ends on its next request or at the next idle check. A token refresh makes it active again."
712
+ }),
713
+ definition: Object.freeze({
714
+ messageId: "common.status.idle.definition",
715
+ defaultMessage: "Open, but not used for longer than the inactivity timeout. It ends on its next request or at the next idle check. A token refresh makes it active again."
716
+ })
717
+ }),
718
+ ended: Object.freeze({
719
+ tone: "neutral",
720
+ messageId: "common.status.ended",
721
+ defaultMessage: "Ended",
722
+ help: null,
723
+ definition: Object.freeze({
724
+ messageId: "common.status.ended.definition",
725
+ defaultMessage: "The session can no longer be used. The user has to sign in again on this device."
726
+ })
727
+ })
728
+ });
729
+ const SESSION_END_REASON_PRESENTATION = Object.freeze({
730
+ logout: Object.freeze({
731
+ messageId: "common.endReason.logout",
732
+ defaultMessage: "Logged out",
733
+ description: Object.freeze({
734
+ messageId: "common.endReason.logout.description",
735
+ defaultMessage: "The user signed out."
736
+ })
737
+ }),
738
+ idle: Object.freeze({
739
+ messageId: "common.endReason.idle",
740
+ defaultMessage: "Timed out",
741
+ description: Object.freeze({
742
+ messageId: "common.endReason.idle.description",
743
+ defaultMessage: "Not used for longer than the inactivity timeout."
744
+ })
745
+ }),
746
+ expired: Object.freeze({
747
+ messageId: "common.endReason.expired",
748
+ defaultMessage: "Expired",
749
+ description: Object.freeze({
750
+ messageId: "common.endReason.expired.description",
751
+ defaultMessage: "Reached the maximum session age."
752
+ })
753
+ }),
754
+ manual: Object.freeze({
755
+ messageId: "common.endReason.manual",
756
+ defaultMessage: "Ended manually",
757
+ description: Object.freeze({
758
+ messageId: "common.endReason.manual.description",
759
+ defaultMessage: "Ended from the Strapi admin, or by the user from another of their devices."
760
+ })
761
+ }),
762
+ blocked: Object.freeze({
763
+ messageId: "common.endReason.blocked",
764
+ defaultMessage: "User blocked",
765
+ description: Object.freeze({
766
+ messageId: "common.endReason.blocked.description",
767
+ defaultMessage: "Ended because the user account was blocked."
768
+ })
769
+ }),
770
+ unrecorded: Object.freeze({
771
+ messageId: "common.endReason.unrecorded",
772
+ defaultMessage: "Reason not recorded",
773
+ description: Object.freeze({
774
+ messageId: "common.endReason.unrecorded.description",
775
+ defaultMessage: "No end reason was stored, for example because the session ended in Strapi’s own session store or was recorded by an older plugin version."
776
+ })
777
+ })
778
+ });
779
+ function getSessionState(session = {}) {
780
+ const row = session || {};
781
+ if (row.isActive === true) return row.isTrulyActive ? "active" : "idle";
782
+ return "ended";
783
+ }
784
+ function getSessionStatus(session = {}) {
785
+ return getSessionState(session);
786
+ }
787
+ function getSessionEndReason(session = {}) {
788
+ const row = session || {};
789
+ if (row.isActive === true) return null;
790
+ const reason = typeof row.terminationReason === "string" ? row.terminationReason.trim().toLowerCase() : "";
791
+ return RECORDED_END_REASONS.has(reason) ? (
792
+ /** @type {any} */
793
+ reason
794
+ ) : "unrecorded";
795
+ }
796
+ function isNativeOnlySession(session) {
797
+ const id = session?.id;
798
+ return typeof id === "string" && id.startsWith("native_");
799
+ }
800
+ function isSessionStatus(status) {
801
+ return SESSION_STATES.includes(
802
+ /** @type {any} */
803
+ status
804
+ );
805
+ }
806
+ function isSessionEndReason(reason) {
807
+ return SESSION_END_REASONS.includes(
808
+ /** @type {any} */
809
+ reason
810
+ );
811
+ }
812
+ function getSessionStatusPresentation(statusOrSession) {
813
+ const status = typeof statusOrSession === "string" ? statusOrSession : getSessionState(statusOrSession);
814
+ const key = isSessionStatus(status) ? status : "ended";
815
+ return { status: key, ...SESSION_STATUS_PRESENTATION[key] };
816
+ }
817
+ function getEndReasonPresentation(reason) {
818
+ const key = isSessionEndReason(reason) ? reason : "unrecorded";
819
+ return { reason: key, ...SESSION_END_REASON_PRESENTATION[key] };
820
+ }
821
+ function getSessionEndReasonPresentation(session) {
822
+ const reason = getSessionEndReason(session);
823
+ return reason ? getEndReasonPresentation(reason) : null;
824
+ }
825
+ function useSessionFormatters() {
826
+ const { formatMessage, locale } = useIntl();
827
+ const translate = useCallback(
828
+ (descriptor, values) => formatMessage(
829
+ { id: getTranslation(descriptor.messageId), defaultMessage: descriptor.defaultMessage },
830
+ values
831
+ ),
832
+ [formatMessage]
833
+ );
834
+ return useMemo(() => {
835
+ const formatDate = (value, options) => formatSessionDate(value, locale, MISSING_VALUE_GLYPH, options);
836
+ const formatRelativeTime = (value, now) => formatRelative(value, locale, { now: now ?? Date.now(), fallback: MISSING_VALUE_GLYPH });
837
+ const statusLabel = (statusOrSession) => translate(getSessionStatusPresentation(statusOrSession));
838
+ const endReasonLabel = (sessionOrReason) => {
839
+ const reason = typeof sessionOrReason === "string" ? getEndReasonPresentation(sessionOrReason) : getSessionEndReasonPresentation(sessionOrReason);
840
+ return reason ? translate(reason) : "";
841
+ };
842
+ const deviceTypeLabel = (session) => translate(getDevicePresentation(session).deviceTypeMessage);
843
+ const deviceSummary = (session) => {
844
+ const { summary } = getDevicePresentation(session);
845
+ return summary.text ?? translate(summary, summary.values);
846
+ };
847
+ return {
848
+ locale,
849
+ formatDate,
850
+ formatRelativeTime,
851
+ translate,
852
+ statusLabel,
853
+ endReasonLabel,
854
+ deviceTypeLabel,
855
+ deviceSummary
856
+ };
857
+ }, [locale, translate]);
858
+ }
859
+ const NoWrap = styled.span`
860
+ white-space: nowrap;
861
+ `;
862
+ const StatusDetail = ({ session, status }) => {
863
+ const { formatMessage } = useIntl();
864
+ const { formatDate, formatRelativeTime, endReasonLabel } = useSessionFormatters();
865
+ const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
866
+ let text;
867
+ if (status === "ended") {
868
+ const endedAt = toValidDate(session.logoutTime);
869
+ text = t("common.status.ended.detail", "{reason} · {endedAt}", {
870
+ reason: /* @__PURE__ */ jsx(NoWrap, { children: endReasonLabel(session) }, "reason"),
871
+ endedAt: endedAt ? /* @__PURE__ */ jsx(NoWrap, { children: formatDate(endedAt) }, "ended-at") : /* @__PURE__ */ jsx(MissingValue, { variant: "pi" }, "ended-at")
872
+ });
873
+ } else {
874
+ const minutes = Number(session.minutesSinceActive);
875
+ const hasMinutes = session.minutesSinceActive !== null && session.minutesSinceActive !== void 0 && Number.isFinite(minutes);
876
+ text = status === "idle" && hasMinutes ? t("common.status.idle.detail", "Not used for {minutes} min", { minutes }) : t("common.status.active.detail", "Last active {time}", {
877
+ time: formatRelativeTime(session.lastActive || session.loginTime)
878
+ });
879
+ }
880
+ return /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", "data-status-detail": "", children: text });
881
+ };
882
+ const getBadgeColors = (tone) => tone === "warning" ? { backgroundColor: "warning200", textColor: "neutral800" } : { variant: tone };
883
+ const StatusBadge = ({ status, session, detail = false, showEndReason = false, size = "M" }) => {
884
+ const { formatMessage } = useIntl();
885
+ const presentation = getSessionStatusPresentation(status || session || {});
886
+ const translate = (descriptor) => formatMessage({
887
+ id: getTranslation(descriptor.messageId),
888
+ defaultMessage: descriptor.defaultMessage
889
+ });
890
+ const label = translate(presentation);
891
+ const badge = /* @__PURE__ */ jsx(
892
+ Badge,
893
+ {
894
+ ...getBadgeColors(presentation.tone),
895
+ size,
896
+ "data-session-status": presentation.status,
897
+ children: label
898
+ }
899
+ );
900
+ if (!(detail || showEndReason) || !session) return badge;
901
+ const reason = presentation.status === "ended" ? getSessionEndReasonPresentation(session) : null;
902
+ const help = reason ? reason.description : presentation.help;
903
+ const native = isNativeOnlySession(session);
904
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
905
+ /* @__PURE__ */ jsxs(Flex, { gap: 1, alignItems: "center", wrap: "wrap", children: [
906
+ help ? /* @__PURE__ */ jsx(Tooltip, { label: translate(help), children: /* @__PURE__ */ jsx("span", { children: badge }) }) : badge,
907
+ native ? /* @__PURE__ */ jsx(
908
+ Tooltip,
909
+ {
910
+ label: formatMessage({
911
+ id: getTranslation("common.status.nativeSession.help"),
912
+ defaultMessage: "Created by Strapi’s own session store. No device or location details were recorded."
913
+ }),
914
+ children: /* @__PURE__ */ jsx("span", { children: /* @__PURE__ */ jsx(Badge, { variant: "neutral", size, "data-native-session": "", children: formatMessage({
915
+ id: getTranslation("common.status.nativeSession"),
916
+ defaultMessage: "Strapi session"
917
+ }) }) })
918
+ }
919
+ ) : null
920
+ ] }),
921
+ /* @__PURE__ */ jsx(StatusDetail, { session, status: presentation.status })
922
+ ] });
923
+ };
924
+ const canTakeFocus = (element) => Boolean(
925
+ element?.isConnected && typeof element.focus === "function" && !element.disabled && element.getAttribute?.("aria-disabled") !== "true"
926
+ );
927
+ function pickFocusTarget(opener, fallback) {
928
+ if (canTakeFocus(opener)) return opener;
929
+ return canTakeFocus(fallback) ? fallback : null;
930
+ }
931
+ function restoreDialogFocus(event, opener, fallback) {
932
+ const target = pickFocusTarget(opener, fallback);
933
+ if (!target) return;
934
+ event.preventDefault();
935
+ target.focus();
936
+ }
937
+ function refocusIfLost(opener, fallback, doc = typeof document === "undefined" ? void 0 : document) {
938
+ if (!doc) return;
939
+ const active = doc.activeElement;
940
+ if (active && active !== doc.body) return;
941
+ pickFocusTarget(opener, fallback)?.focus();
942
+ }
943
+ const ConfirmAction = ({
944
+ trigger,
945
+ title,
946
+ body,
947
+ confirmLabel,
948
+ onConfirm,
949
+ variant = "danger",
950
+ disabled = false,
951
+ fallbackFocusRef,
952
+ isOpen,
953
+ onOpenChange,
954
+ returnFocusRef
955
+ }) => {
956
+ const [internalOpen, setInternalOpen] = useState(false);
957
+ const [busy, setBusy] = useState(false);
958
+ const triggerRef = useRef(null);
959
+ const controlled = !trigger;
960
+ const open = controlled ? Boolean(isOpen) : internalOpen;
961
+ const restoreFocus = () => {
962
+ if (typeof window === "undefined") return;
963
+ window.requestAnimationFrame(() => {
964
+ const active = document.activeElement;
965
+ if (active && active !== document.body) return;
966
+ const ownTrigger = controlled ? returnFocusRef?.current : triggerRef.current;
967
+ const target = pickFocusTarget(ownTrigger, fallbackFocusRef?.current);
968
+ if (target) target.focus();
969
+ });
970
+ };
971
+ const setOpen = (next) => {
972
+ if (controlled) onOpenChange?.(next);
973
+ else setInternalOpen(next);
974
+ };
975
+ const handleOpenChange = (next) => {
976
+ if (busy) return;
977
+ setOpen(next);
978
+ if (!next) restoreFocus();
979
+ };
980
+ const handleConfirm = async (event) => {
981
+ event?.preventDefault?.();
982
+ setBusy(true);
983
+ try {
984
+ await onConfirm();
985
+ setOpen(false);
986
+ restoreFocus();
987
+ } catch {
988
+ } finally {
989
+ setBusy(false);
990
+ }
991
+ };
992
+ return /* @__PURE__ */ jsxs(Dialog.Root, { open, onOpenChange: handleOpenChange, children: [
993
+ trigger ? /* @__PURE__ */ jsx(Dialog.Trigger, { ref: triggerRef, disabled, children: trigger }) : null,
994
+ /* @__PURE__ */ jsx(
995
+ ConfirmDialog,
996
+ {
997
+ title,
998
+ variant,
999
+ endAction: /* @__PURE__ */ jsx(
1000
+ Button,
1001
+ {
1002
+ fullWidth: true,
1003
+ variant,
1004
+ onClick: handleConfirm,
1005
+ loading: busy,
1006
+ disabled: busy,
1007
+ children: confirmLabel
1008
+ }
1009
+ ),
1010
+ children: body
1011
+ }
1012
+ )
1013
+ ] });
1014
+ };
1015
+ const DEVICE_ICONS = {
1016
+ desktop: Monitor,
1017
+ mobile: Phone,
1018
+ tablet: Phone,
1019
+ api: Code,
1020
+ bot: Server,
1021
+ unknown: Information
1022
+ };
1023
+ const DeviceIcon = ({ icon }) => {
1024
+ const Icon = DEVICE_ICONS[icon] || Information;
1025
+ return /* @__PURE__ */ jsx(Icon, { "aria-hidden": true, focusable: false });
1026
+ };
1027
+ const TargetLink = styled(Link)`
1028
+ min-height: 3.2rem;
1029
+ display: inline-flex;
1030
+ align-items: center;
1031
+ align-self: flex-start;
1032
+ `;
1033
+ const ActionStack = styled.div`
1034
+ display: grid;
1035
+ grid-template-columns: minmax(0, 1fr);
1036
+ grid-auto-rows: 1fr;
1037
+ gap: ${({ theme }) => theme.spaces[2]};
1038
+ min-width: 0;
1039
+
1040
+ /* The buttons are the plugin's own children; wrapped labels centre
1041
+ through inheritance, not through a selector into the DS button. */
1042
+ & > button {
1043
+ height: auto;
1044
+ min-height: 3.2rem;
1045
+ padding-block: ${({ theme }) => theme.spaces[1]};
1046
+ text-align: center;
1047
+ }
1048
+ `;
1049
+ function requireSessionList(payload) {
1050
+ if (!Array.isArray(payload?.data)) throw new Error("Invalid session response");
1051
+ return payload.data;
1052
+ }
1053
+ function requireSuccessfulMutation(payload) {
1054
+ if (payload?.success !== true) throw new Error("Invalid mutation response");
1055
+ return payload;
1056
+ }
1057
+ const DEFAULT_SESSION_FILTER = "all";
1058
+ const SESSION_FILTER_OPTIONS = Object.freeze(["all", "open", "active", "idle", "ended"]);
1059
+ const DEFAULT_END_REASON_FILTER = "all";
1060
+ const END_REASON_FILTER_OPTIONS = Object.freeze(["all", ...SESSION_END_REASONS]);
1061
+ const VALID_SESSION_FILTERS = new Set(SESSION_FILTER_OPTIONS);
1062
+ const VALID_END_REASON_FILTERS = new Set(END_REASON_FILTER_OPTIONS);
1063
+ function isSessionFilter(value) {
1064
+ return typeof value === "string" && VALID_SESSION_FILTERS.has(value);
1065
+ }
1066
+ function isEndReasonFilter(value) {
1067
+ return typeof value === "string" && VALID_END_REASON_FILTERS.has(value);
1068
+ }
1069
+ const matchesStatus = (session, status) => {
1070
+ if (status === "all") return true;
1071
+ if (status === "open") return session?.isActive === true;
1072
+ return getSessionState(session) === status;
1073
+ };
1074
+ function filterSessionsByStatus(sessions, status = DEFAULT_SESSION_FILTER, reason = DEFAULT_END_REASON_FILTER) {
1075
+ if (!Array.isArray(sessions) || !VALID_SESSION_FILTERS.has(status)) return [];
1076
+ const byReason = status === "ended" && isEndReasonFilter(reason) && reason !== DEFAULT_END_REASON_FILTER;
1077
+ if (status === "all") return sessions;
1078
+ return sessions.filter(
1079
+ (session) => matchesStatus(session, status) && (!byReason || getSessionEndReason(session) === reason)
1080
+ );
1081
+ }
1082
+ function getSessionSearchText(session, extraText = "") {
1083
+ const row = session || {};
1084
+ const device = getDevicePresentation(row);
1085
+ return [
1086
+ row.user?.username,
1087
+ row.user?.email,
1088
+ row.ipAddress,
1089
+ device.browser,
1090
+ device.os,
1091
+ device.deviceType,
1092
+ extraText
1093
+ ].map(presentText).filter(Boolean).join(" ").toLowerCase();
1094
+ }
1095
+ function filterSessionsBySearch(sessions, query, getExtraText) {
1096
+ if (!Array.isArray(sessions)) return [];
1097
+ const needle = typeof query === "string" ? query.trim().toLowerCase() : "";
1098
+ if (!needle) return sessions;
1099
+ return sessions.filter(
1100
+ (session) => getSessionSearchText(session, getExtraText ? getExtraText(session) : "").includes(needle)
1101
+ );
1102
+ }
1103
+ function getManageableSessions(sessions) {
1104
+ if (!Array.isArray(sessions)) return [];
1105
+ return sessions.filter((session) => session?.isActive === true);
1106
+ }
1107
+ const USER_MODEL_UID = "plugin::users-permissions.user";
1108
+ const PANEL_SESSION_LIMIT = 5;
1109
+ const DASHBOARD_PATH = "/plugins/magic-sessionmanager";
1110
+ function isUserModel(model) {
1111
+ return model === USER_MODEL_UID;
1112
+ }
1113
+ const getActivity = (session) => toValidDate(session?.lastActive) || toValidDate(session?.loginTime);
1114
+ function getUserSessionSummary(sessions) {
1115
+ const rows = Array.isArray(sessions) ? sessions.filter((row) => row && typeof row === "object") : [];
1116
+ const open = rows.filter((session) => session.isActive === true);
1117
+ const activeCount = open.filter((session) => session.isTrulyActive === true).length;
1118
+ let lastActive = null;
1119
+ for (const session of rows) {
1120
+ const activity = getActivity(session);
1121
+ if (activity && (!lastActive || activity.getTime() > lastActive.getTime()))
1122
+ lastActive = activity;
1123
+ }
1124
+ return { isOnline: activeCount > 0, openCount: open.length, activeCount, lastActive };
1125
+ }
1126
+ function getVisiblePanelSessions(sessions, limit = PANEL_SESSION_LIMIT) {
1127
+ const rows = Array.isArray(sessions) ? [...sessions] : [];
1128
+ rows.sort(
1129
+ (a, b) => (getActivity(b)?.getTime() ?? -Infinity) - (getActivity(a)?.getTime() ?? -Infinity)
1130
+ );
1131
+ return { visible: rows.slice(0, limit), hiddenCount: Math.max(0, rows.length - limit) };
1132
+ }
1133
+ function endOpenSessions(sessions, reason) {
1134
+ if (!Array.isArray(sessions)) return [];
1135
+ return sessions.map(
1136
+ (session) => session?.isActive === true ? { ...session, isActive: false, isTrulyActive: false, terminationReason: reason } : session
1137
+ );
1138
+ }
1139
+ function getPanelUserLabel(user) {
1140
+ return presentText(user?.username) || presentText(user?.email);
1141
+ }
1142
+ function isNotFoundError(error) {
1143
+ if (!error || typeof error !== "object") return false;
1144
+ return error.status === 404 || error.response?.status === 404;
1145
+ }
1146
+ function buildUserSessionsHref(user) {
1147
+ const query = presentText(user?.email) || presentText(user?.username);
1148
+ if (!query) return DASHBOARD_PATH;
1149
+ return `${DASHBOARD_PATH}?${new URLSearchParams({ search: query }).toString()}`;
1150
+ }
1151
+ function planBlockedFormSync({ initialValues, modified, blocked }) {
1152
+ const hasBlockedField = Boolean(initialValues) && typeof initialValues === "object" && Object.prototype.hasOwnProperty.call(initialValues, "blocked");
1153
+ if (!hasBlockedField || typeof blocked !== "boolean") return { mode: "notice" };
1154
+ if (!modified) return { mode: "reset", initialValues: { ...initialValues, blocked } };
1155
+ return { mode: "change", field: "blocked", value: blocked };
1156
+ }
1157
+ function applyBlockedFormSync(plan, form) {
1158
+ try {
1159
+ if (plan.mode === "reset" && typeof form?.resetForm === "function") {
1160
+ form.resetForm(plan.initialValues);
1161
+ return true;
1162
+ }
1163
+ if (plan.mode === "change" && typeof form?.onChange === "function") {
1164
+ form.onChange(plan.field, plan.value);
1165
+ return true;
1166
+ }
1167
+ } catch {
1168
+ return false;
1169
+ }
1170
+ return false;
1171
+ }
1172
+ const pluginPermissions = {
1173
+ access: [{ action: `plugin::${pluginId}.access`, subject: null }]
1174
+ };
1175
+ const SAFE_SCOPE = /^[A-Za-z0-9_.:-]{1,48}$/;
1176
+ const CANCEL_NAMES = /* @__PURE__ */ new Set(["AbortError", "TimeoutError", "CanceledError"]);
1177
+ function safeGet(value, key) {
1178
+ try {
1179
+ return value && typeof value === "object" ? value[key] : void 0;
1180
+ } catch {
1181
+ return void 0;
1182
+ }
1183
+ }
1184
+ function isCancelledRequest(error) {
1185
+ const name2 = safeGet(error, "name");
1186
+ return typeof name2 === "string" && CANCEL_NAMES.has(name2);
1187
+ }
1188
+ function logSafeAdminError(scope, error) {
1189
+ if (isCancelledRequest(error)) return;
1190
+ const safeScope = typeof scope === "string" && SAFE_SCOPE.test(scope) ? scope : "admin";
1191
+ const directStatus = safeGet(error, "status");
1192
+ const status = Number.isInteger(directStatus) ? directStatus : safeGet(safeGet(error, "response"), "status");
1193
+ const statusSuffix = Number.isInteger(status) && status >= 400 && status <= 599 ? ` (HTTP ${status})` : "";
1194
+ console.warn(`[${safeScope}] Request failed${statusSuffix}`);
1195
+ }
1196
+ const FORM_CONSUMER = "MagicSessionManagerPanel";
1197
+ const PanelSessionCard = ({ session, t }) => {
1198
+ const { formatDate, formatRelativeTime, translate } = useSessionFormatters();
1199
+ const device = getDevicePresentation(session);
1200
+ const hasSummary = Boolean(device.browserLabel || device.os);
1201
+ const summary = hasSummary ? device.summary.text ?? translate(device.summary, device.summary.values) : "";
1202
+ const lastActivity = toValidDate(session.lastActive) || toValidDate(session.loginTime);
1203
+ const ipAddress = presentText(session.ipAddress);
1204
+ return /* @__PURE__ */ jsx(
1205
+ Box,
1206
+ {
1207
+ tag: "li",
1208
+ padding: 3,
1209
+ background: "neutral0",
1210
+ borderColor: "neutral200",
1211
+ hasRadius: true,
1212
+ minWidth: 0,
1213
+ "data-panel-session": "",
1214
+ children: /* @__PURE__ */ jsxs(Flex, { gap: 3, alignItems: "flex-start", minWidth: 0, children: [
1215
+ /* @__PURE__ */ jsx(
1216
+ Flex,
1217
+ {
1218
+ background: "neutral100",
1219
+ color: "neutral700",
1220
+ hasRadius: true,
1221
+ padding: 2,
1222
+ shrink: 0,
1223
+ justifyContent: "center",
1224
+ alignItems: "center",
1225
+ "aria-hidden": true,
1226
+ children: /* @__PURE__ */ jsx(DeviceIcon, { icon: device.icon })
1227
+ }
1228
+ ),
1229
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 1, minWidth: 0, flex: "1 1 auto", children: [
1230
+ /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "center", gap: 2, wrap: "wrap", children: [
1231
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "semiBold", textColor: "neutral800", children: translate(device.deviceTypeMessage) }),
1232
+ /* @__PURE__ */ jsx(StatusBadge, { session, size: "S" })
1233
+ ] }),
1234
+ summary ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: summary }) : null,
1235
+ ipAddress ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("panel.sessions.ip", "IP {ip}", { ip: ipAddress }) }) : null,
1236
+ lastActivity ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", title: formatDate(lastActivity), children: t("panel.sessions.lastActive", "Last active {time}", {
1237
+ time: formatRelativeTime(lastActivity)
1238
+ }) }) : null
1239
+ ] })
1240
+ ] })
1241
+ }
1242
+ );
1243
+ };
1244
+ const SessionInfoPanel = ({ documentId, model, document: document2 }) => {
1245
+ const { formatMessage } = useIntl();
1246
+ const { formatDate, formatRelativeTime } = useSessionFormatters();
1247
+ const {
1248
+ allowedActions: { canAccess },
1249
+ isLoading: permissionsLoading
1250
+ } = useRBAC(pluginPermissions.access);
1251
+ const [sessions, setSessions] = useState([]);
1252
+ const [loading, setLoading] = useState(true);
1253
+ const [loadError, setLoadError] = useState(false);
1254
+ const [reloadKey, setReloadKey] = useState(0);
1255
+ const [isBlocked, setIsBlocked] = useState(Boolean(document2?.blocked));
1256
+ const [pendingAction, setPendingAction] = useState(null);
1257
+ const [formOutOfSync, setFormOutOfSync] = useState(false);
1258
+ const panelRef = useRef(null);
1259
+ const blockToggleRef = useRef(null);
1260
+ const focusBlockToggle = useRef(false);
1261
+ const noOpenSessionsHintId = useId();
1262
+ const { get, post: postRequest } = useFetchClient();
1263
+ const { toggleNotification } = useNotification();
1264
+ const formInitialValues = useForm(FORM_CONSUMER, (state) => state.initialValues, false);
1265
+ const formModified = useForm(FORM_CONSUMER, (state) => state.modified, false);
1266
+ const formOnChange = useForm(FORM_CONSUMER, (state) => state.onChange, false);
1267
+ const formResetForm = useForm(FORM_CONSUMER, (state) => state.resetForm, false);
1268
+ const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
1269
+ const userId = document2?.documentId || documentId;
1270
+ const isUserPanel = isUserModel(model);
1271
+ const persistedBlocked = Boolean(document2?.blocked);
1272
+ const userLabel = getPanelUserLabel(document2) || String(userId ?? "");
1273
+ useEffect(() => {
1274
+ setIsBlocked(persistedBlocked);
1275
+ setFormOutOfSync(false);
1276
+ }, [persistedBlocked, userId]);
1277
+ useEffect(() => {
1278
+ if (!focusBlockToggle.current || pendingAction !== null) return void 0;
1279
+ const expected = isBlocked ? "unblock" : "block";
1280
+ let attempts = 0;
1281
+ let timer;
1282
+ const tryFocus = () => {
1283
+ const button = blockToggleRef.current;
1284
+ if (button?.isConnected && !button.disabled && button.dataset.blockToggle === expected) {
1285
+ focusBlockToggle.current = false;
1286
+ button.focus();
1287
+ return;
1288
+ }
1289
+ attempts += 1;
1290
+ if (attempts < 20) timer = window.setTimeout(tryFocus, 25);
1291
+ else focusBlockToggle.current = false;
1292
+ };
1293
+ timer = window.setTimeout(tryFocus, 0);
1294
+ return () => window.clearTimeout(timer);
1295
+ }, [isBlocked, pendingAction]);
1296
+ useEffect(() => {
1297
+ if (model !== "plugin::users-permissions.user" || !userId || permissionsLoading || !canAccess) {
1298
+ setLoading(false);
1299
+ return void 0;
1300
+ }
1301
+ let cancelled = false;
1302
+ const fetchData = async () => {
1303
+ setLoading(true);
1304
+ setLoadError(false);
1305
+ try {
1306
+ const { data } = await get(`/magic-sessionmanager/user/${userId}/sessions`);
1307
+ if (cancelled) return;
1308
+ setSessions(requireSessionList(data));
1309
+ } catch (err) {
1310
+ if (!cancelled) setLoadError(true);
1311
+ logSafeAdminError("userSessions.load", err);
1312
+ } finally {
1313
+ if (!cancelled) setLoading(false);
1314
+ }
1315
+ };
1316
+ fetchData();
1317
+ return () => {
1318
+ cancelled = true;
1319
+ };
1320
+ }, [userId, model, get, reloadKey, canAccess, permissionsLoading]);
1321
+ const handleEndAll = async () => {
1322
+ if (!userId) return;
1323
+ setPendingAction("endAll");
1324
+ try {
1325
+ const response = await postRequest(`/magic-sessionmanager/user/${userId}/terminate-all`);
1326
+ requireSuccessfulMutation(response.data);
1327
+ setSessions((rows) => endOpenSessions(rows, "manual"));
1328
+ toggleNotification({
1329
+ type: "success",
1330
+ message: t("panel.notify.endAllSuccess", "All sessions of {user} ended.", {
1331
+ user: userLabel
1332
+ })
1333
+ });
1334
+ } catch (error) {
1335
+ toggleNotification({
1336
+ type: "danger",
1337
+ message: isNotFoundError(error) ? t("panel.notify.userNotFound", "User not found.") : t("panel.notify.endAllError", "The sessions could not be ended. Please try again.")
1338
+ });
1339
+ logSafeAdminError("userSessions.endAll", error);
1340
+ throw error;
1341
+ } finally {
1342
+ setPendingAction(null);
1343
+ }
1344
+ };
1345
+ const changeBlocked = async (blocked) => {
1346
+ const response = await postRequest(`/magic-sessionmanager/user/${userId}/toggle-block`, {
1347
+ blocked
1348
+ });
1349
+ requireSuccessfulMutation(response.data);
1350
+ const newBlockedStatus = response.data.blocked === true;
1351
+ focusBlockToggle.current = newBlockedStatus !== isBlocked;
1352
+ setIsBlocked(newBlockedStatus);
1353
+ if (newBlockedStatus) setSessions((rows) => endOpenSessions(rows, "blocked"));
1354
+ const plan = planBlockedFormSync({
1355
+ initialValues: formInitialValues,
1356
+ modified: formModified,
1357
+ blocked: newBlockedStatus
1358
+ });
1359
+ const synced = applyBlockedFormSync(plan, { resetForm: formResetForm, onChange: formOnChange });
1360
+ setFormOutOfSync(!synced);
1361
+ return newBlockedStatus;
1362
+ };
1363
+ const handleBlock = async () => {
1364
+ if (!userId) return;
1365
+ setPendingAction("block");
1366
+ try {
1367
+ await changeBlocked(true);
1368
+ toggleNotification({
1369
+ type: "success",
1370
+ message: t("panel.notify.blockSuccess", "{user} is blocked.", { user: userLabel })
1371
+ });
1372
+ } catch (error) {
1373
+ toggleNotification({
1374
+ type: "danger",
1375
+ message: isNotFoundError(error) ? t("panel.notify.userNotFound", "User not found.") : t("panel.notify.blockError", "The user could not be blocked. Please try again.")
1376
+ });
1377
+ logSafeAdminError("userSessions.block", error);
1378
+ throw error;
1379
+ } finally {
1380
+ setPendingAction(null);
1381
+ }
1382
+ };
1383
+ const handleUnblock = async () => {
1384
+ if (!userId) return;
1385
+ setPendingAction("unblock");
1386
+ try {
1387
+ await changeBlocked(false);
1388
+ toggleNotification({
1389
+ type: "success",
1390
+ message: t("panel.notify.unblockSuccess", "{user} can sign in again.", { user: userLabel })
1391
+ });
1392
+ } catch (error) {
1393
+ toggleNotification({
1394
+ type: "danger",
1395
+ message: isNotFoundError(error) ? t("panel.notify.userNotFound", "User not found.") : t("panel.notify.unblockError", "The block could not be removed. Please try again.")
1396
+ });
1397
+ logSafeAdminError("userSessions.unblock", error);
1398
+ } finally {
1399
+ setPendingAction(null);
1400
+ }
1401
+ };
1402
+ if (!isUserPanel) {
1403
+ return null;
1404
+ }
1405
+ if (permissionsLoading || !canAccess) {
1406
+ return null;
1407
+ }
1408
+ const title = t("panel.title", "Sessions");
1409
+ if (!userId) {
1410
+ return {
1411
+ title,
1412
+ content: /* @__PURE__ */ jsx(Box, { width: "100%", minWidth: 0, children: /* @__PURE__ */ jsx(ReadableText, { variant: "omega", textColor: "neutral700", tag: "p", children: t("panel.unsaved.description", "Save this user before you can manage sessions.") }) })
1413
+ };
1414
+ }
1415
+ if (loadError) {
1416
+ return {
1417
+ title,
1418
+ content: /* @__PURE__ */ jsx(Box, { width: "100%", minWidth: 0, children: /* @__PURE__ */ jsx(
1419
+ PersistentAlert,
1420
+ {
1421
+ variant: "danger",
1422
+ closeLabel: t("common.close", "Close"),
1423
+ action: /* @__PURE__ */ jsx(Button, { size: "S", variant: "secondary", onClick: () => setReloadKey((key) => key + 1), children: t("common.tryAgain", "Try again") }),
1424
+ children: t("panel.error.message", "Sessions could not be loaded.")
1425
+ }
1426
+ ) })
1427
+ };
1428
+ }
1429
+ const openSessions = getManageableSessions(sessions);
1430
+ const summary = getUserSessionSummary(sessions);
1431
+ const { visible, hiddenCount } = getVisiblePanelSessions(openSessions);
1432
+ const actionsDisabled = loading || pendingAction !== null;
1433
+ const hasOpenSessions = summary.openCount > 0;
1434
+ const endAllLabel = t("panel.actions.endAll", "End all sessions");
1435
+ const blockLabel = t("panel.actions.blockUser", "Block user");
1436
+ const unblockLabel = t("panel.actions.unblock", "Unblock user");
1437
+ return {
1438
+ title,
1439
+ content: /* @__PURE__ */ jsxs(
1440
+ Flex,
1441
+ {
1442
+ ref: panelRef,
1443
+ direction: "column",
1444
+ alignItems: "stretch",
1445
+ gap: 4,
1446
+ width: "100%",
1447
+ minWidth: 0,
1448
+ tabIndex: -1,
1449
+ children: [
1450
+ loading ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 2, "data-panel-summary": "", children: /* @__PURE__ */ jsx(Loader, { small: true, children: t("panel.loading", "Loading sessions") }) }) : /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 1, "data-panel-summary": "", children: [
1451
+ /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", wrap: "wrap", children: [
1452
+ /* @__PURE__ */ jsx(Badge, { variant: summary.isOnline ? "success" : "neutral", size: "M", children: summary.isOnline ? t("panel.status.online", "Online") : t("panel.status.notOnline", "Not online") }),
1453
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "semiBold", textColor: "neutral800", children: t(
1454
+ "panel.summary.openCount",
1455
+ "{count, plural, one {# open session} other {# open sessions}}",
1456
+ { count: summary.openCount }
1457
+ ) })
1458
+ ] }),
1459
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("panel.summary.openHint", "Active or idle") }),
1460
+ summary.lastActive ? /* @__PURE__ */ jsx(
1461
+ Typography,
1462
+ {
1463
+ variant: "pi",
1464
+ textColor: "neutral600",
1465
+ title: formatDate(summary.lastActive),
1466
+ children: t("panel.sessions.lastActive", "Last active {time}", {
1467
+ time: formatRelativeTime(summary.lastActive)
1468
+ })
1469
+ }
1470
+ ) : /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("panel.summary.noSessions", "No sessions recorded") })
1471
+ ] }),
1472
+ isBlocked ? /* @__PURE__ */ jsx(PersistentAlert, { variant: "danger", closeLabel: t("common.close", "Close"), children: t("panel.blocked.message", "This account is blocked. The user cannot sign in.") }) : null,
1473
+ formOutOfSync ? /* @__PURE__ */ jsx(PersistentAlert, { variant: "warning", closeLabel: t("common.close", "Close"), children: t(
1474
+ "panel.form.reloadNotice",
1475
+ "Reload this page before saving, or the Blocked field will be overwritten."
1476
+ ) }) : null,
1477
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-panel-actions": "", children: [
1478
+ /* @__PURE__ */ jsxs(ActionStack, { children: [
1479
+ /* @__PURE__ */ jsx(
1480
+ ConfirmAction,
1481
+ {
1482
+ title: t("panel.confirm.endAllTitle", "End all sessions of {user}?", {
1483
+ user: userLabel
1484
+ }),
1485
+ body: t(
1486
+ "panel.confirm.endAllBody",
1487
+ "{count, plural, one {# open session ends} other {# open sessions end}} on all devices. {user} can sign in again unless you also block the account.",
1488
+ { count: summary.openCount, user: userLabel }
1489
+ ),
1490
+ confirmLabel: endAllLabel,
1491
+ onConfirm: handleEndAll,
1492
+ fallbackFocusRef: panelRef,
1493
+ disabled: actionsDisabled || !hasOpenSessions,
1494
+ trigger: /* @__PURE__ */ jsx(
1495
+ Button,
1496
+ {
1497
+ fullWidth: true,
1498
+ size: "S",
1499
+ variant: "danger-light",
1500
+ startIcon: /* @__PURE__ */ jsx(SignOut, { "aria-hidden": true, focusable: false }),
1501
+ loading: pendingAction === "endAll",
1502
+ disabled: actionsDisabled || !hasOpenSessions,
1503
+ "aria-describedby": !loading && !hasOpenSessions ? noOpenSessionsHintId : void 0,
1504
+ type: "button",
1505
+ children: endAllLabel
1506
+ }
1507
+ )
1508
+ }
1509
+ ),
1510
+ isBlocked ? /* @__PURE__ */ jsx(
1511
+ Button,
1512
+ {
1513
+ ref: blockToggleRef,
1514
+ "data-block-toggle": "unblock",
1515
+ fullWidth: true,
1516
+ size: "S",
1517
+ variant: "secondary",
1518
+ startIcon: /* @__PURE__ */ jsx(CheckCircle, { "aria-hidden": true, focusable: false }),
1519
+ loading: pendingAction === "unblock",
1520
+ disabled: actionsDisabled,
1521
+ onClick: handleUnblock,
1522
+ type: "button",
1523
+ children: unblockLabel
1524
+ }
1525
+ ) : /* @__PURE__ */ jsx(
1526
+ ConfirmAction,
1527
+ {
1528
+ title: t("panel.confirm.blockTitle", "Block {user}?", { user: userLabel }),
1529
+ body: t(
1530
+ "panel.confirm.blockBody",
1531
+ "{user} can no longer sign in, and {count, plural, =0 {no open sessions are affected} one {# open session ends now} other {# open sessions end now}}. You can unblock the account later; ended sessions stay ended.",
1532
+ { count: summary.openCount, user: userLabel }
1533
+ ),
1534
+ confirmLabel: blockLabel,
1535
+ onConfirm: handleBlock,
1536
+ fallbackFocusRef: panelRef,
1537
+ disabled: actionsDisabled,
1538
+ trigger: /* @__PURE__ */ jsx(
1539
+ Button,
1540
+ {
1541
+ ref: blockToggleRef,
1542
+ "data-block-toggle": "block",
1543
+ fullWidth: true,
1544
+ size: "S",
1545
+ variant: "danger-light",
1546
+ startIcon: /* @__PURE__ */ jsx(Lock, { "aria-hidden": true, focusable: false }),
1547
+ loading: pendingAction === "block",
1548
+ disabled: actionsDisabled,
1549
+ type: "button",
1550
+ children: blockLabel
1551
+ }
1552
+ )
1553
+ }
1554
+ )
1555
+ ] }),
1556
+ !loading && !hasOpenSessions ? /* @__PURE__ */ jsx(Typography, { id: noOpenSessionsHintId, variant: "pi", textColor: "neutral600", children: t("panel.actions.noOpenSessions", "No open sessions") }) : null,
1557
+ /* @__PURE__ */ jsx(ReadableText, { variant: "pi", textColor: "neutral600", tag: "p", children: t(
1558
+ "panel.actions.hint",
1559
+ "End all sessions lets the user sign in again. Block user also prevents new sign-ins."
1560
+ ) })
1561
+ ] }),
1562
+ loading ? null : /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-panel-sessions": "", children: [
1563
+ /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", tag: "h3", children: t("panel.sessions.openTitle", "Open sessions") }),
1564
+ visible.length > 0 ? /* @__PURE__ */ jsx(
1565
+ Flex,
1566
+ {
1567
+ tag: "ul",
1568
+ direction: "column",
1569
+ alignItems: "stretch",
1570
+ gap: 2,
1571
+ margin: 0,
1572
+ padding: 0,
1573
+ style: { listStyle: "none" },
1574
+ children: visible.map((session) => /* @__PURE__ */ jsx(PanelSessionCard, { session, t }, session.id))
1575
+ }
1576
+ ) : /* @__PURE__ */ jsx(Box, { padding: 3, background: "neutral0", borderColor: "neutral200", hasRadius: true, children: /* @__PURE__ */ jsx(ReadableText, { variant: "omega", textColor: "neutral800", tag: "p", children: t(
1577
+ "panel.empty.noOpenSessions",
1578
+ "No open sessions. {user} is not signed in on any device.",
1579
+ { user: userLabel }
1580
+ ) }) }),
1581
+ hiddenCount > 0 ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("panel.sessions.more", "{count, plural, other {+# more}}", {
1582
+ count: hiddenCount
1583
+ }) }) : null
1584
+ ] }),
1585
+ /* @__PURE__ */ jsx(TargetLink, { tag: NavLink, to: buildUserSessionsHref(document2), children: t("panel.sessions.showAllLink", "Show all sessions") })
1586
+ ]
1587
+ }
1588
+ )
1589
+ };
1590
+ };
1591
+ const prefixPluginTranslations = (data, pluginId2) => {
1592
+ const prefixed = {};
1593
+ Object.keys(data).forEach((key) => {
1594
+ prefixed[`${pluginId2}.${key}`] = data[key];
1595
+ });
1596
+ return prefixed;
1597
+ };
1598
+ const name = pluginPkg.strapi.name;
1599
+ const index = {
1600
+ register(app) {
1601
+ const pluginPermissions$1 = pluginPermissions.access;
1602
+ app.addMenuLink({
1603
+ to: `plugins/${pluginId}`,
1604
+ icon: PluginIcon,
1605
+ intlLabel: {
1606
+ id: `${pluginId}.plugin.name`,
1607
+ defaultMessage: pluginPkg.strapi.displayName
1608
+ },
1609
+ Component: () => import("./App-Cgf_CSjw.mjs"),
1610
+ permissions: pluginPermissions$1
1611
+ });
1612
+ app.addSettingsLink(
1613
+ {
1614
+ id: pluginId,
1615
+ intlLabel: { id: `${pluginId}.settings.section`, defaultMessage: "Session Manager" }
1616
+ },
1617
+ [
1618
+ {
1619
+ intlLabel: {
1620
+ id: `${pluginId}.settings.link.configuration`,
1621
+ defaultMessage: "Configuration"
1622
+ },
1623
+ id: "general",
1624
+ to: `${pluginId}/general`,
1625
+ Component: () => import("./Settings-DgeuUiMF.mjs"),
1626
+ permissions: pluginPermissions$1
1627
+ },
1628
+ {
1629
+ intlLabel: {
1630
+ id: `${pluginId}.settings.link.analytics`,
1631
+ defaultMessage: "Analytics"
1632
+ },
1633
+ id: "analytics",
1634
+ to: `${pluginId}/analytics`,
1635
+ Component: () => import("./Analytics-dyJmyxO-.mjs"),
1636
+ permissions: pluginPermissions$1
1637
+ },
1638
+ {
1639
+ intlLabel: {
1640
+ id: `${pluginId}.settings.link.license`,
1641
+ defaultMessage: "License"
1642
+ },
1643
+ id: "license",
1644
+ to: `${pluginId}/license`,
1645
+ Component: () => import("./License-C4WSYoqY.mjs"),
1646
+ permissions: pluginPermissions$1
1647
+ }
1648
+ ]
1649
+ );
1650
+ app.registerPlugin({
1651
+ id: pluginId,
1652
+ initializer: Initializer,
1653
+ isReady: true,
1654
+ name
1655
+ });
1656
+ if ("widgets" in app && app.widgets && typeof app.widgets.register === "function") {
1657
+ app.widgets.register({
1658
+ icon: PluginIcon,
1659
+ title: {
1660
+ id: `${pluginId}.widget.online-users.title`,
1661
+ defaultMessage: "Online users"
1662
+ },
1663
+ link: {
1664
+ label: {
1665
+ id: `${pluginId}.widget.link`,
1666
+ defaultMessage: "Open Session Manager"
1667
+ },
1668
+ href: `/plugins/${pluginId}`
1669
+ },
1670
+ component: async () => {
1671
+ const component = await import("./OnlineUsersWidget-DJC4V1KS.mjs");
1672
+ return component.default;
1673
+ },
1674
+ id: "online-users-widget",
1675
+ pluginId,
1676
+ permissions: pluginPermissions$1
1677
+ });
1678
+ }
1679
+ },
1680
+ bootstrap(app) {
1681
+ try {
1682
+ const contentManagerPlugin = app.getPlugin("content-manager");
1683
+ if (contentManagerPlugin?.apis?.addEditViewSidePanel) {
1684
+ contentManagerPlugin.apis.addEditViewSidePanel([SessionInfoPanel]);
1685
+ }
1686
+ } catch (error) {
1687
+ logSafeAdminError("plugin.bootstrap", error);
1688
+ }
1689
+ },
1690
+ async registerTrads({ locales }) {
1691
+ const importedTrads = {
1692
+ en: () => import("./en-UY4Tb5tE.mjs"),
1693
+ de: () => import("./de-j0oZH9Pz.mjs"),
1694
+ es: () => import("./es-DGBcZwQy.mjs"),
1695
+ fr: () => import("./fr-B6-DWhGO.mjs"),
1696
+ pt: () => import("./pt-YMRLm9gx.mjs")
1697
+ };
1698
+ const translatedLanguages = Object.keys(importedTrads).filter((lang) => locales.includes(lang));
1699
+ const translations = await Promise.all(
1700
+ translatedLanguages.map(
1701
+ (language) => importedTrads[language]().then(({ default: data }) => ({
1702
+ data: prefixPluginTranslations(data, pluginId),
1703
+ locale: language
1704
+ })).catch(() => ({
1705
+ data: {},
1706
+ locale: language
1707
+ }))
1708
+ )
1709
+ );
1710
+ return Promise.resolve(translations);
1711
+ }
1712
+ };
1713
+ export {
1714
+ StatGrid as A,
1715
+ StatCard as B,
1716
+ ConfirmAction as C,
1717
+ DEFAULT_SESSION_FILTER as D,
1718
+ END_REASON_FILTER_OPTIONS as E,
1719
+ restoreDialogFocus as F,
1720
+ pluginPermissions as G,
1721
+ ReadableParagraphs as H,
1722
+ EqualGrid as I,
1723
+ formatSessionDate as J,
1724
+ refocusIfLost as K,
1725
+ requireSuccessfulMutation as L,
1726
+ MissingValue as M,
1727
+ normalizeDeviceType as N,
1728
+ getDeviceTypeMessage as O,
1729
+ PropertyList as P,
1730
+ index as Q,
1731
+ ReadableText as R,
1732
+ StatusBadge as S,
1733
+ ValueOrMissing as V,
1734
+ getEndReasonPresentation as a,
1735
+ getTranslation as b,
1736
+ isEndReasonFilter as c,
1737
+ DEFAULT_END_REASON_FILTER as d,
1738
+ getSessionState as e,
1739
+ getDevicePresentation as f,
1740
+ getSessionEndReason as g,
1741
+ getSessionStatus as h,
1742
+ isSessionFilter as i,
1743
+ isNativeOnlySession as j,
1744
+ getSessionEndReasonPresentation as k,
1745
+ DeviceIcon as l,
1746
+ pluginId as m,
1747
+ logSafeAdminError as n,
1748
+ PersistentAlert as o,
1749
+ presentText as p,
1750
+ SESSION_STATES as q,
1751
+ SESSION_STATUS_PRESENTATION as r,
1752
+ requireSessionList as s,
1753
+ toValidDate as t,
1754
+ useSessionFormatters as u,
1755
+ isCancelledRequest as v,
1756
+ filterSessionsBySearch as w,
1757
+ filterSessionsByStatus as x,
1758
+ SESSION_FILTER_OPTIONS as y,
1759
+ PageShell as z
1760
+ };