@kaloma-ai/framework-web 0.0.0-stage → 0.5.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,3315 @@
1
+ // src/AppShell.tsx
2
+ import { ArrowLeft, Menu as MenuIcon, X as X5, LogOut } from "lucide-react";
3
+ import { useEffect as useEffect4, useState as useState11 } from "react";
4
+ import { Link as Link3, NavLink, useLocation, useNavigate as useNavigate2 } from "react-router-dom";
5
+
6
+ // src/adminNav.ts
7
+ import { Activity, Cog, KeyRound, Plug, ScrollText, Settings, ShieldCheck, Users, UsersRound } from "lucide-react";
8
+
9
+ // src/admin/texts.ts
10
+ var a = {
11
+ users: "Users",
12
+ roles: "Roles",
13
+ groups: "Groups",
14
+ apiKeys: "API keys",
15
+ auditLog: "Audit log",
16
+ status: "Status",
17
+ settings: "Settings",
18
+ connections: "Connections",
19
+ colCopy: "Copy elsewhere",
20
+ copyNow: "Copy now",
21
+ copyDone: "Backup copied to the backup storage",
22
+ copiedEncrypted: "Copied, encrypted",
23
+ copyAuto: (keep) => `Every backup is copied to the backup storage automatically; the last ${keep} copies are kept.`,
24
+ copyManual: "Copies to the backup storage are made by hand with the buttons below.",
25
+ copyEncrypted: "Copies are encrypted.",
26
+ copyNotEncrypted: "Copies are not encrypted: set a passphrase on the Connections page to encrypt them.",
27
+ copyNotSetUp: "Backups exist only on this server. A lost server means lost backups.",
28
+ copySetUp: "Set up the backup storage",
29
+ loading: "Loading...",
30
+ cancel: "Cancel",
31
+ save: "Save",
32
+ delete: "Delete",
33
+ edit: "Edit",
34
+ genericError: "Something went wrong. Please try again.",
35
+ none: "None",
36
+ close: "Close",
37
+ moreActions: "More actions",
38
+ you: "You",
39
+ selectAll: "Select all",
40
+ clearAll: "Clear",
41
+ copyKey: "Copy key",
42
+ copied: "Copied",
43
+ search: "Search",
44
+ usersDescription: "Invite people, choose what they can do and control how long they have access.",
45
+ inviteTitle: "Invite someone",
46
+ inviteDescription: "They get an email with a link to create their account.",
47
+ inviteEmailPlaceholder: "name@company.com",
48
+ permissionCount: (n) => `${n} ${n === 1 ? "permission" : "permissions"}`,
49
+ rolesUpdated: "Roles updated",
50
+ editRolesFor: (name) => `Choose what ${name} can do.`,
51
+ accessRenewed: "Access renewed",
52
+ userDeactivated: "User deactivated",
53
+ userReactivated: "User reactivated",
54
+ invitationCancelled: "Invitation cancelled",
55
+ confirmDeactivateTitle: "Deactivate this user?",
56
+ confirmDeactivateText: "They are signed out and cannot sign in until reactivated.",
57
+ noUsers: "No users yet.",
58
+ noPendingInvitations: "No pending invitations.",
59
+ inviteEmail: "Email address",
60
+ inviteRoles: "Roles",
61
+ inviteSend: "Send invitation",
62
+ inviteSent: "Invitation sent to",
63
+ pendingInvitations: "Pending invitations",
64
+ expires: "Expires",
65
+ colName: "Name",
66
+ colEmail: "Email",
67
+ colRoles: "Roles",
68
+ colGroups: "Groups",
69
+ colStatus: "Status",
70
+ colActions: "Actions",
71
+ statusActive: "Active",
72
+ statusExpired: "Access expired",
73
+ statusDeactivated: "Deactivated",
74
+ accessUntil: "Access until",
75
+ editRoles: "Edit roles",
76
+ renew: "Renew 90 days",
77
+ deactivate: "Deactivate",
78
+ reactivate: "Reactivate",
79
+ confirmDeactivate: "Deactivate this user? They are signed out and cannot sign in until reactivated.",
80
+ rolesDescription: "A role is a named set of permissions. Give people the roles that match their work.",
81
+ newRole: "New role",
82
+ editRole: "Edit role",
83
+ roleNamePlaceholder: "For example: Reviewer",
84
+ roleCreated: "Role created",
85
+ roleSaved: "Role saved",
86
+ roleDeleted: "Role deleted",
87
+ confirmDeleteRoleText: "This cannot be undone.",
88
+ noPermissionsAvailable: "No permissions are available.",
89
+ morePermissions: (n) => `+${n} more`,
90
+ roleName: "Role name",
91
+ rolePermissions: "Permissions",
92
+ builtIn: "Built-in",
93
+ custom: "Custom",
94
+ confirmDeleteRole: "Delete this role?",
95
+ adminOnlyNote: "Administrative permissions are never available to API keys.",
96
+ newKeyDescription: "Choose a name, what the key may do and when it expires.",
97
+ keyNamePlaceholder: "For example: Reporting script",
98
+ keyPresetReadHint: "Can look at data but not change anything.",
99
+ keyPresetReadCreateHint: "Can look at data and add new items.",
100
+ keyPresetReadCreateUpdateHint: "Can look at data, add items and change existing ones.",
101
+ keyPresetCustomHint: "Pick exactly which permissions the key gets.",
102
+ keyExpiryHint: "Between 1 and 365 days.",
103
+ noUsablePermissions: "You have no permissions that an API key can use.",
104
+ keyCreatedTitle: "Your new API key",
105
+ keyRevoked: "Key revoked",
106
+ done: "Done",
107
+ keysIntro: "API keys let an agent or script act for you with a limited set of permissions. A key never has more than you have, and never administrative permissions.",
108
+ newKey: "New key",
109
+ keyName: "Name",
110
+ keyAccess: "Access",
111
+ keyPresetRead: "Read only",
112
+ keyPresetReadCreate: "Read and create",
113
+ keyPresetReadCreateUpdate: "Read, create and update",
114
+ keyPresetCustom: "Choose permissions",
115
+ keyExpiry: "Expires after (days)",
116
+ keyCreate: "Create key",
117
+ keyShownOnce: "Copy this key now. It is shown only once.",
118
+ colKeyName: "Name",
119
+ colKeyScopes: "Permissions",
120
+ colKeyExpires: "Expires",
121
+ colKeyLastUsed: "Last used",
122
+ colKeyOwner: "Owner",
123
+ never: "Never",
124
+ revoke: "Revoke",
125
+ confirmRevoke: "Revoke this key? Anything using it stops working.",
126
+ yourKeys: "Your keys",
127
+ allKeys: "All keys",
128
+ noKeys: "No keys yet.",
129
+ auditDescription: "A record of important actions: who did what, and when.",
130
+ searchAudit: "Search the log",
131
+ system: "System",
132
+ noMatches: "No entries match your search.",
133
+ colWhen: "When",
134
+ colWho: "Who",
135
+ colAction: "Action",
136
+ colTarget: "Target",
137
+ colDetails: "Details",
138
+ viaKey: "via key",
139
+ auditEmpty: "Nothing recorded yet.",
140
+ loadMore: "Load older entries",
141
+ statusTitle: "Status and backups",
142
+ overall: { ok: "Everything is working", warn: "Working, but worth a look", fail: "Something needs attention" },
143
+ checkState: { ok: "OK", warn: "Check", fail: "Problem" },
144
+ statusDescription: "Health checks refresh every 30 seconds. Backups protect your data and uploaded files.",
145
+ healthChecks: "Health checks",
146
+ backups: "Backups",
147
+ uptime: "Running for",
148
+ frameworkVersion: "appai framework",
149
+ nextBackup: "Next automatic backup",
150
+ backupsOff: "Automatic backups are switched off.",
151
+ keeps: "Keeps the latest",
152
+ backupsWord: "backups",
153
+ includesFiles: "including uploaded files",
154
+ alertsTo: "Alerts go to",
155
+ noAlerts: "No alert addresses are set (ALERT_EMAILS), so nobody is told about problems.",
156
+ addresses: "address(es)",
157
+ backupNow: "Back up now",
158
+ backingUp: "Backing up...",
159
+ backupDone: "Backup finished",
160
+ recentBackups: "Recent backups",
161
+ colStarted: "Started",
162
+ colResult: "Result",
163
+ colSize: "Size",
164
+ colHow: "How",
165
+ resultSuccess: "Success",
166
+ resultFailed: "Failed",
167
+ resultRunning: "Running",
168
+ howScheduled: "Automatic",
169
+ howManual: "Manual",
170
+ noBackups: "No backups yet.",
171
+ restoreHint: "To check that a backup can be restored, follow the test-restore steps in docs/operations.md.",
172
+ settingsDescription: "Change the name, logo, colors and the rules of this app. Changes apply right away, no restart needed.",
173
+ unsavedChanges: "You have unsaved changes.",
174
+ discard: "Discard",
175
+ settingsSaved: "Settings saved",
176
+ settingsReset: "Reset to the default",
177
+ resetToDefault: (value) => `Reset to default (${value})`,
178
+ usingDefault: "Default",
179
+ customized: "Changed",
180
+ notSet: "not set",
181
+ logo: "Logo",
182
+ logoHint: "PNG, JPG, WebP or SVG, up to 1 MB. Shown next to the name; a square or wide logo on a transparent background works best.",
183
+ noLogo: "No logo yet",
184
+ logoSave: "Use this logo",
185
+ logoRemove: "Remove logo",
186
+ logoSaved: "Logo updated",
187
+ logoRemoved: "Logo removed",
188
+ logoFileTypes: "image/png,image/jpeg,image/webp,image/svg+xml",
189
+ logoMaxBytes: 1024 * 1024,
190
+ logoMaxHint: "PNG, JPG, WebP or SVG, up to 1 MB",
191
+ logoChoose: "Choose a logo",
192
+ listHint: "Separate the numbers with commas, for example 7, 1.",
193
+ listInvalid: "Enter whole numbers separated by commas.",
194
+ yes: "On",
195
+ no: "Off"
196
+ };
197
+
198
+ // src/texts.ts
199
+ var shell = {
200
+ administration: "Administration",
201
+ adminGroups: { people: "People", configuration: "Configuration", monitoring: "Monitoring" },
202
+ adminMenu: "Administration menu",
203
+ backToApp: "Back to the app",
204
+ needsAttention: "Needs attention",
205
+ theme: { system: "Auto", light: "Light", dark: "Dark" },
206
+ themeTitle: "Switch between automatic, light and dark",
207
+ notFoundTitle: "Page not found",
208
+ notFoundText: "This page does not exist, or you do not have access to it.",
209
+ backHome: "Back to the start page",
210
+ skipToContent: "Skip to content",
211
+ menu: "Menu",
212
+ openMenu: "Open menu",
213
+ closeMenu: "Close menu",
214
+ account: "Account",
215
+ appearance: "Appearance"
216
+ };
217
+
218
+ // src/adminNav.ts
219
+ var adminGroups = [
220
+ {
221
+ title: shell.adminGroups.people,
222
+ items: [
223
+ { to: "/users", label: a.users, icon: Users, permission: "user:read" },
224
+ { to: "/groups", label: a.groups, icon: UsersRound, permission: "group:read" },
225
+ { to: "/roles", label: a.roles, icon: ShieldCheck, permission: "role:read" },
226
+ { to: "/api-keys", label: a.apiKeys, icon: KeyRound, permission: "apikey:read" }
227
+ ]
228
+ },
229
+ {
230
+ title: shell.adminGroups.configuration,
231
+ items: [
232
+ { to: "/settings", label: a.settings, icon: Settings, permission: "settings:read" },
233
+ { to: "/connections", label: a.connections, icon: Plug, permission: "storage:read" }
234
+ ]
235
+ },
236
+ {
237
+ title: shell.adminGroups.monitoring,
238
+ items: [
239
+ { to: "/status", label: a.status, icon: Activity, permission: "status:read" },
240
+ { to: "/audit", label: a.auditLog, icon: ScrollText, permission: "audit:read" }
241
+ ]
242
+ }
243
+ ];
244
+ var STATUS_PATH = "/status";
245
+ var adminIcon = Cog;
246
+ function visibleAdminGroups(allowed, groups = adminGroups) {
247
+ return groups.map((g2) => ({ title: g2.title, items: g2.items.filter(allowed) })).filter((g2) => g2.items.length > 0);
248
+ }
249
+ function isAdminPath(pathname, groups = adminGroups) {
250
+ return groups.some((g2) => g2.items.some((i) => pathname === i.to || pathname.startsWith(`${i.to}/`)));
251
+ }
252
+
253
+ // src/admin/api.ts
254
+ async function api(path, init = {}) {
255
+ const res = await fetch(path, {
256
+ method: init.method ?? (init.body === void 0 ? "GET" : "POST"),
257
+ credentials: "include",
258
+ headers: init.body === void 0 ? void 0 : { "content-type": "application/json" },
259
+ body: init.body === void 0 ? void 0 : JSON.stringify(init.body)
260
+ });
261
+ const body = await res.json().catch(() => ({}));
262
+ if (!res.ok) throw new Error(body.error ?? a.genericError);
263
+ return body;
264
+ }
265
+ async function apiForm(path, form, method = "POST") {
266
+ const res = await fetch(path, { method, credentials: "include", body: form });
267
+ const body = await res.json().catch(() => ({}));
268
+ if (!res.ok) throw new Error(body.error ?? a.genericError);
269
+ return body;
270
+ }
271
+ function roleLabel(roles, key) {
272
+ return roles.find((r) => r.key === key)?.label ?? key;
273
+ }
274
+
275
+ // src/auth/client.ts
276
+ import { createAuthClient } from "better-auth/react";
277
+ import { organizationClient } from "better-auth/client/plugins";
278
+ var authClient = createAuthClient({
279
+ basePath: "/api/auth",
280
+ plugins: [organizationClient()]
281
+ });
282
+ var { useSession } = authClient;
283
+ function can(me, permission) {
284
+ return Boolean(me?.permissions.includes(permission));
285
+ }
286
+ async function fetchMe() {
287
+ const res = await fetch("/api/me", { credentials: "include" });
288
+ return res.ok ? await res.json() : null;
289
+ }
290
+
291
+ // src/auth/pages.tsx
292
+ import { Mail } from "lucide-react";
293
+ import { useEffect as useEffect3, useState as useState9 } from "react";
294
+ import { Link as Link2, Navigate, useNavigate, useSearchParams } from "react-router-dom";
295
+
296
+ // src/ui/cn.ts
297
+ function cn(...parts) {
298
+ return parts.filter(Boolean).join(" ");
299
+ }
300
+
301
+ // src/ui/format.ts
302
+ var DAY = 24 * 60 * 60 * 1e3;
303
+ function parseDate(value) {
304
+ const [y, m, d] = value.split("-").map(Number);
305
+ return new Date(y, m - 1, d);
306
+ }
307
+ function toDateString(date) {
308
+ const pad = (n) => String(n).padStart(2, "0");
309
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
310
+ }
311
+ var todayString = () => toDateString(/* @__PURE__ */ new Date());
312
+ function addDays(date, days) {
313
+ const d = parseDate(date);
314
+ d.setDate(d.getDate() + days);
315
+ return toDateString(d);
316
+ }
317
+ function formatDate(value) {
318
+ if (!value) return "";
319
+ const date = typeof value === "string" ? value.length === 10 ? parseDate(value) : new Date(value) : value;
320
+ return date.toLocaleDateString(void 0, { day: "numeric", month: "short", year: "numeric" });
321
+ }
322
+ function formatDateLong(value) {
323
+ return parseDate(value).toLocaleDateString(void 0, { weekday: "short", day: "numeric", month: "short", year: "numeric" });
324
+ }
325
+ function formatDateTime(value) {
326
+ if (!value) return "";
327
+ const date = typeof value === "string" ? new Date(value) : value;
328
+ return `${date.toLocaleDateString(void 0, { day: "numeric", month: "short", year: "numeric" })}, ${date.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit" })}`;
329
+ }
330
+ function daysUntil(value) {
331
+ const today = parseDate(todayString()).getTime();
332
+ return Math.round((parseDate(value).getTime() - today) / DAY);
333
+ }
334
+ function dueText(value) {
335
+ const days = daysUntil(value);
336
+ if (days === 0) return "Due today";
337
+ if (days === 1) return "Due tomorrow";
338
+ if (days > 1) return `Due in ${days} days`;
339
+ return days === -1 ? "Overdue by 1 day" : `Overdue by ${-days} days`;
340
+ }
341
+ function timeAgo(value) {
342
+ if (!value) return "";
343
+ const date = typeof value === "string" ? new Date(value) : value;
344
+ const seconds = Math.round((Date.now() - date.getTime()) / 1e3);
345
+ if (seconds < 45) return "just now";
346
+ const minutes = Math.round(seconds / 60);
347
+ if (minutes < 60) return `${minutes} min ago`;
348
+ const hours = Math.round(minutes / 60);
349
+ if (hours < 24) return `${hours} h ago`;
350
+ const days = Math.round(hours / 24);
351
+ if (days === 1) return "yesterday";
352
+ if (days < 8) return `${days} days ago`;
353
+ return formatDate(date);
354
+ }
355
+ function formatBytes(bytes) {
356
+ if (bytes < 1024) return `${bytes} B`;
357
+ if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`;
358
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
359
+ }
360
+ function initials(name) {
361
+ const parts = name.trim().split(/\s+/).filter(Boolean);
362
+ if (parts.length === 0) return "?";
363
+ return (parts[0][0] + (parts.length > 1 ? parts[parts.length - 1][0] : "")).toUpperCase();
364
+ }
365
+
366
+ // src/ui/Button.tsx
367
+ import { Loader2 } from "lucide-react";
368
+ import { jsx, jsxs } from "react/jsx-runtime";
369
+ var variants = {
370
+ primary: "bg-brand text-brand-fg shadow-sm hover:brightness-110 active:brightness-95",
371
+ secondary: "border border-line-strong bg-surface text-fg shadow-sm hover:bg-surface-muted",
372
+ ghost: "text-muted hover:bg-surface-muted hover:text-fg",
373
+ danger: "border border-danger/30 bg-danger-soft text-danger hover:bg-danger hover:text-surface"
374
+ };
375
+ var sizes = {
376
+ sm: "h-8 gap-1.5 px-3 text-sm",
377
+ md: "h-10 gap-2 px-4 text-sm",
378
+ lg: "h-12 gap-2 px-6 text-base"
379
+ };
380
+ function buttonClass(variant = "secondary", size = "md", block = false) {
381
+ return cn(
382
+ "inline-flex shrink-0 items-center justify-center rounded-lg font-medium transition outline-none",
383
+ "focus-visible:ring-2 focus-visible:ring-brand/40 focus-visible:ring-offset-2 focus-visible:ring-offset-surface",
384
+ "disabled:pointer-events-none disabled:opacity-50",
385
+ variants[variant],
386
+ sizes[size],
387
+ block && "w-full"
388
+ );
389
+ }
390
+ function Button({ variant = "secondary", size = "md", loading, icon, block, className, children, disabled, type = "button", ...props }) {
391
+ return /* @__PURE__ */ jsxs("button", { type, disabled: disabled || loading, className: cn(buttonClass(variant, size, block), className), ...props, children: [
392
+ loading ? /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin", "aria-hidden": true }) : icon,
393
+ children
394
+ ] });
395
+ }
396
+ function IconButton({ label, children, className, type = "button", ...props }) {
397
+ return /* @__PURE__ */ jsx(
398
+ "button",
399
+ {
400
+ type,
401
+ "aria-label": label,
402
+ title: label,
403
+ className: cn(
404
+ "inline-flex size-9 items-center justify-center rounded-lg text-muted outline-none transition hover:bg-surface-muted hover:text-fg",
405
+ "focus-visible:ring-2 focus-visible:ring-brand/40 disabled:opacity-50",
406
+ className
407
+ ),
408
+ ...props,
409
+ children
410
+ }
411
+ );
412
+ }
413
+
414
+ // src/ui/Form.tsx
415
+ import { Check } from "lucide-react";
416
+ import { useId } from "react";
417
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
418
+ var control = "w-full rounded-lg border border-line-strong bg-surface px-3 text-sm text-fg shadow-sm outline-none transition placeholder:text-muted/70 focus:border-brand focus:ring-2 focus:ring-brand/25 disabled:opacity-60";
419
+ function Field({ label, hint, error, children, className }) {
420
+ return /* @__PURE__ */ jsxs2("label", { className: cn("block", className), children: [
421
+ /* @__PURE__ */ jsx2("span", { className: "mb-1.5 block text-sm font-medium text-fg", children: label }),
422
+ children,
423
+ error ? /* @__PURE__ */ jsx2("span", { className: "mt-1.5 block text-xs text-danger", children: error }) : hint ? /* @__PURE__ */ jsx2("span", { className: "mt-1.5 block text-xs text-muted", children: hint }) : null
424
+ ] });
425
+ }
426
+ function Input({ className, ...props }) {
427
+ return /* @__PURE__ */ jsx2("input", { className: cn(control, "h-10", className), ...props });
428
+ }
429
+ function Textarea({ className, ...props }) {
430
+ return /* @__PURE__ */ jsx2("textarea", { className: cn(control, "min-h-20 py-2", className), ...props });
431
+ }
432
+ function Select({ className, children, ...props }) {
433
+ return /* @__PURE__ */ jsx2("select", { className: cn(control, "h-10 appearance-none bg-[length:1rem] bg-[right_0.75rem_center] bg-no-repeat pr-9", className), style: { backgroundImage: chevron }, ...props, children });
434
+ }
435
+ var chevron = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%238a93a3' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E")`;
436
+ function Checkbox({ label, description, className, ...props }) {
437
+ const id = useId();
438
+ return /* @__PURE__ */ jsxs2("label", { htmlFor: id, className: cn("flex cursor-pointer items-start gap-3 text-sm", props.disabled && "cursor-not-allowed opacity-60", className), children: [
439
+ /* @__PURE__ */ jsxs2("span", { className: "relative mt-0.5 inline-flex size-5 shrink-0", children: [
440
+ /* @__PURE__ */ jsx2("input", { id, type: "checkbox", className: "peer absolute inset-0 size-5 cursor-[inherit] appearance-none rounded-md border border-line-strong bg-surface outline-none transition checked:border-brand checked:bg-brand focus-visible:ring-2 focus-visible:ring-brand/40", ...props }),
441
+ /* @__PURE__ */ jsx2(Check, { className: "pointer-events-none absolute inset-0 m-auto size-3.5 text-brand-fg opacity-0 peer-checked:opacity-100", strokeWidth: 3, "aria-hidden": true })
442
+ ] }),
443
+ /* @__PURE__ */ jsxs2("span", { children: [
444
+ /* @__PURE__ */ jsx2("span", { className: "font-medium text-fg", children: label }),
445
+ description && /* @__PURE__ */ jsx2("span", { className: "mt-0.5 block text-muted", children: description })
446
+ ] })
447
+ ] });
448
+ }
449
+ var HEX = /^#[0-9a-fA-F]{6}$/;
450
+ function ColorField({ value, onChange, placeholder = "Default", disabled }) {
451
+ const valid = value === null || HEX.test(value);
452
+ return /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-2", children: [
453
+ /* @__PURE__ */ jsx2("span", { className: "relative inline-flex size-10 shrink-0 overflow-hidden rounded-lg border border-line-strong shadow-sm focus-within:ring-2 focus-within:ring-brand/25", style: { backgroundColor: value && valid ? value : "var(--brand-primary)" }, children: /* @__PURE__ */ jsx2("input", { type: "color", "aria-label": "Pick a color", disabled, value: value && valid ? value : "#000000", onChange: (e) => onChange(e.target.value), className: "absolute inset-0 size-full cursor-pointer opacity-0" }) }),
454
+ /* @__PURE__ */ jsxs2("div", { className: "min-w-0 flex-1", children: [
455
+ /* @__PURE__ */ jsx2(Input, { value: value ?? "", disabled, placeholder, maxLength: 7, spellCheck: false, "aria-invalid": !valid, onChange: (e) => onChange(e.target.value.trim() === "" ? null : e.target.value.trim()), className: cn("font-mono", !valid && "border-danger") }),
456
+ !valid && /* @__PURE__ */ jsx2("span", { className: "mt-1 block text-xs text-danger", children: "Use a 6-digit hex color such as #2563eb." })
457
+ ] })
458
+ ] });
459
+ }
460
+
461
+ // src/ui/Surface.tsx
462
+ import { AlertCircle, CheckCircle2, Info, Loader2 as Loader22, TriangleAlert } from "lucide-react";
463
+ import { Link } from "react-router-dom";
464
+ import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
465
+ function Card({ className, ...props }) {
466
+ return /* @__PURE__ */ jsx3("div", { className: cn("rounded-card border border-line bg-surface shadow-card", className), ...props });
467
+ }
468
+ function PageHeader({ title, description, actions, back }) {
469
+ return /* @__PURE__ */ jsxs3("header", { className: "mb-6", children: [
470
+ back && /* @__PURE__ */ jsxs3(Link, { to: back.to, className: "mb-2 inline-flex items-center gap-1 text-sm text-muted hover:text-fg", children: [
471
+ /* @__PURE__ */ jsx3("span", { "aria-hidden": true, children: "\u2190" }),
472
+ " ",
473
+ back.label
474
+ ] }),
475
+ /* @__PURE__ */ jsxs3("div", { className: "flex flex-wrap items-start justify-between gap-4", children: [
476
+ /* @__PURE__ */ jsxs3("div", { className: "min-w-0", children: [
477
+ /* @__PURE__ */ jsx3("h1", { className: "text-2xl font-semibold tracking-tight text-fg", children: title }),
478
+ description && /* @__PURE__ */ jsx3("p", { className: "mt-1 max-w-2xl text-sm text-muted", children: description })
479
+ ] }),
480
+ actions && /* @__PURE__ */ jsx3("div", { className: "flex flex-wrap items-center gap-2", children: actions })
481
+ ] })
482
+ ] });
483
+ }
484
+ var tones = {
485
+ neutral: "bg-surface-muted text-muted",
486
+ brand: "bg-brand-soft text-brand",
487
+ ok: "bg-ok-soft text-ok",
488
+ warn: "bg-warn-soft text-warn",
489
+ danger: "bg-danger-soft text-danger"
490
+ };
491
+ var dots = { neutral: "bg-muted", brand: "bg-brand", ok: "bg-ok", warn: "bg-warn", danger: "bg-danger" };
492
+ function Badge({ tone = "neutral", dot, className, children }) {
493
+ return /* @__PURE__ */ jsxs3("span", { className: cn("inline-flex items-center gap-1.5 whitespace-nowrap rounded-full px-2.5 py-0.5 text-xs font-medium", tones[tone], className), children: [
494
+ dot && /* @__PURE__ */ jsx3("span", { className: cn("size-1.5 rounded-full", dots[tone]), "aria-hidden": true }),
495
+ children
496
+ ] });
497
+ }
498
+ function Avatar({ name, size = "md" }) {
499
+ const sizes2 = { sm: "size-7 text-[11px]", md: "size-9 text-xs", lg: "size-11 text-sm" };
500
+ return /* @__PURE__ */ jsx3("span", { "aria-hidden": true, className: cn("inline-flex shrink-0 items-center justify-center rounded-full bg-brand-soft font-semibold text-brand", sizes2[size]), children: initials(name) });
501
+ }
502
+ var alertStyles = {
503
+ info: { box: "border-brand/25 bg-brand-soft text-fg", icon: Info },
504
+ success: { box: "border-ok/30 bg-ok-soft text-fg", icon: CheckCircle2 },
505
+ warning: { box: "border-warn/30 bg-warn-soft text-fg", icon: TriangleAlert },
506
+ error: { box: "border-danger/30 bg-danger-soft text-fg", icon: AlertCircle }
507
+ };
508
+ var alertIconColor = { info: "text-brand", success: "text-ok", warning: "text-warn", error: "text-danger" };
509
+ function Alert({ kind = "info", title, children, className }) {
510
+ const { box, icon: Icon } = alertStyles[kind];
511
+ return /* @__PURE__ */ jsxs3("div", { role: kind === "error" ? "alert" : "status", className: cn("flex gap-3 rounded-lg border p-3.5 text-sm", box, className), children: [
512
+ /* @__PURE__ */ jsx3(Icon, { className: cn("mt-0.5 size-4 shrink-0", alertIconColor[kind]), "aria-hidden": true }),
513
+ /* @__PURE__ */ jsxs3("div", { className: "min-w-0", children: [
514
+ title && /* @__PURE__ */ jsx3("p", { className: "font-medium", children: title }),
515
+ children && /* @__PURE__ */ jsx3("div", { className: cn(title && "mt-0.5 text-muted"), children })
516
+ ] })
517
+ ] });
518
+ }
519
+ function EmptyState({ icon: Icon, title, description, action }) {
520
+ return /* @__PURE__ */ jsxs3("div", { className: "flex flex-col items-center rounded-card border border-dashed border-line-strong px-6 py-12 text-center", children: [
521
+ Icon && /* @__PURE__ */ jsx3("span", { className: "mb-3 inline-flex size-12 items-center justify-center rounded-full bg-brand-soft text-brand", children: /* @__PURE__ */ jsx3(Icon, { className: "size-6", "aria-hidden": true }) }),
522
+ /* @__PURE__ */ jsx3("h2", { className: "font-medium text-fg", children: title }),
523
+ description && /* @__PURE__ */ jsx3("p", { className: "mt-1 max-w-md text-sm text-muted", children: description }),
524
+ action && /* @__PURE__ */ jsx3("div", { className: "mt-4", children: action })
525
+ ] });
526
+ }
527
+ function Spinner({ label = "Loading..." }) {
528
+ return /* @__PURE__ */ jsxs3("div", { role: "status", className: "flex items-center justify-center gap-2 py-16 text-sm text-muted", children: [
529
+ /* @__PURE__ */ jsx3(Loader22, { className: "size-4 animate-spin", "aria-hidden": true }),
530
+ " ",
531
+ label
532
+ ] });
533
+ }
534
+ function ProgressBar({ value, max, tone = "ok", className }) {
535
+ const percent = max === 0 ? 0 : Math.round(value / max * 100);
536
+ const fill = { ok: "bg-ok", brand: "bg-brand", danger: "bg-danger", warn: "bg-warn" }[tone];
537
+ return /* @__PURE__ */ jsx3("div", { className: cn("h-2 w-full overflow-hidden rounded-full bg-surface-muted", className), role: "progressbar", "aria-valuenow": percent, "aria-valuemin": 0, "aria-valuemax": 100, children: /* @__PURE__ */ jsx3("div", { className: cn("h-full rounded-full transition-all", fill), style: { width: `${percent}%` } }) });
538
+ }
539
+ function StatCard({ icon: Icon, label, value, tone = "brand", hint, to }) {
540
+ const body = /* @__PURE__ */ jsxs3(Card, { className: cn("flex items-center gap-4 p-4", to && "transition hover:border-line-strong hover:shadow-pop"), children: [
541
+ /* @__PURE__ */ jsx3("span", { className: cn("inline-flex size-11 shrink-0 items-center justify-center rounded-xl", tones[tone]), children: /* @__PURE__ */ jsx3(Icon, { className: "size-5", "aria-hidden": true }) }),
542
+ /* @__PURE__ */ jsxs3("div", { className: "min-w-0", children: [
543
+ /* @__PURE__ */ jsx3("p", { className: "text-2xl font-semibold leading-none tracking-tight text-fg", children: value }),
544
+ /* @__PURE__ */ jsx3("p", { className: "mt-1 truncate text-sm text-muted", children: label }),
545
+ hint && /* @__PURE__ */ jsx3("p", { className: "truncate text-xs text-muted", children: hint })
546
+ ] })
547
+ ] });
548
+ return to ? /* @__PURE__ */ jsx3(Link, { to, children: body }) : body;
549
+ }
550
+ function Table({ className, ...props }) {
551
+ return /* @__PURE__ */ jsx3("div", { className: "overflow-x-auto", children: /* @__PURE__ */ jsx3("table", { className: cn("w-full border-collapse text-left text-sm", className), ...props }) });
552
+ }
553
+ var TH = ({ className, ...props }) => /* @__PURE__ */ jsx3("th", { className: cn("border-b border-line bg-surface-muted/60 px-4 py-2.5 text-xs font-semibold uppercase tracking-wide text-muted first:rounded-tl-card last:rounded-tr-card", className), ...props });
554
+ var TD = ({ className, ...props }) => /* @__PURE__ */ jsx3("td", { className: cn("border-b border-line px-4 py-3 align-middle last:border-b-0", className), ...props });
555
+ var TR = ({ className, ...props }) => /* @__PURE__ */ jsx3("tr", { className: cn("[&:last-child>td]:border-b-0", className), ...props });
556
+ function Segmented({ value, onChange, options: options2, label }) {
557
+ return /* @__PURE__ */ jsx3("div", { role: "tablist", "aria-label": label, className: "inline-flex rounded-lg border border-line bg-surface-muted p-0.5", children: options2.map((o) => /* @__PURE__ */ jsxs3(
558
+ "button",
559
+ {
560
+ role: "tab",
561
+ "aria-selected": value === o.value,
562
+ type: "button",
563
+ onClick: () => onChange(o.value),
564
+ className: cn(
565
+ "inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium outline-none transition focus-visible:ring-2 focus-visible:ring-brand/40",
566
+ value === o.value ? "bg-surface text-fg shadow-sm" : "text-muted hover:text-fg"
567
+ ),
568
+ children: [
569
+ o.label,
570
+ o.count !== void 0 && /* @__PURE__ */ jsx3("span", { className: cn("rounded-full px-1.5 text-xs", value === o.value ? "bg-brand-soft text-brand" : "bg-surface-muted text-muted"), children: o.count })
571
+ ]
572
+ },
573
+ o.value
574
+ )) });
575
+ }
576
+
577
+ // src/ui/Dialog.tsx
578
+ import * as RadixDialog from "@radix-ui/react-dialog";
579
+ import { X } from "lucide-react";
580
+ import { createContext, useCallback, useContext, useRef, useState } from "react";
581
+ import { Fragment, jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
582
+ function Dialog({
583
+ open,
584
+ onClose,
585
+ title,
586
+ description,
587
+ children,
588
+ footer,
589
+ size = "md"
590
+ }) {
591
+ const width = { sm: "max-w-md", md: "max-w-xl", lg: "max-w-3xl" }[size];
592
+ return /* @__PURE__ */ jsx4(RadixDialog.Root, { open, onOpenChange: (next) => !next && onClose(), children: /* @__PURE__ */ jsxs4(RadixDialog.Portal, { children: [
593
+ /* @__PURE__ */ jsx4(RadixDialog.Overlay, { className: "ui-fade fixed inset-0 z-40 bg-[var(--overlay)]" }),
594
+ /* @__PURE__ */ jsxs4(
595
+ RadixDialog.Content,
596
+ {
597
+ className: cn(
598
+ "ui-pop fixed left-1/2 top-1/2 z-50 flex max-h-[90vh] w-[calc(100vw-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col rounded-card border border-line bg-surface shadow-pop outline-none",
599
+ width
600
+ ),
601
+ children: [
602
+ /* @__PURE__ */ jsxs4("div", { className: "flex items-start justify-between gap-4 border-b border-line px-6 py-4", children: [
603
+ /* @__PURE__ */ jsxs4("div", { className: "min-w-0", children: [
604
+ /* @__PURE__ */ jsx4(RadixDialog.Title, { className: "text-lg font-semibold tracking-tight text-fg", children: title }),
605
+ description ? /* @__PURE__ */ jsx4(RadixDialog.Description, { className: "mt-0.5 text-sm text-muted", children: description }) : /* @__PURE__ */ jsx4(RadixDialog.Description, { className: "sr-only", children: title })
606
+ ] }),
607
+ /* @__PURE__ */ jsx4(RadixDialog.Close, { asChild: true, children: /* @__PURE__ */ jsx4(IconButton, { label: "Close", className: "-mr-2 -mt-1", children: /* @__PURE__ */ jsx4(X, { className: "size-5", "aria-hidden": true }) }) })
608
+ ] }),
609
+ /* @__PURE__ */ jsx4("div", { className: "overflow-y-auto px-6 py-5", children }),
610
+ footer && /* @__PURE__ */ jsx4("div", { className: "flex flex-wrap items-center justify-end gap-2 border-t border-line bg-surface-muted/40 px-6 py-3.5", children: footer })
611
+ ]
612
+ }
613
+ )
614
+ ] }) });
615
+ }
616
+ var ConfirmContext = createContext(null);
617
+ function useConfirm() {
618
+ const confirm = useContext(ConfirmContext);
619
+ if (!confirm) throw new Error("useConfirm needs the UiProvider (BrandProvider includes it)");
620
+ return confirm;
621
+ }
622
+ function ConfirmProvider({ children }) {
623
+ const [options2, setOptions] = useState(null);
624
+ const resolver = useRef(null);
625
+ const confirm = useCallback((next) => {
626
+ setOptions(next);
627
+ return new Promise((resolve) => {
628
+ resolver.current = resolve;
629
+ });
630
+ }, []);
631
+ const finish = (value) => {
632
+ resolver.current?.(value);
633
+ resolver.current = null;
634
+ setOptions(null);
635
+ };
636
+ return /* @__PURE__ */ jsxs4(ConfirmContext.Provider, { value: confirm, children: [
637
+ children,
638
+ /* @__PURE__ */ jsx4(
639
+ Dialog,
640
+ {
641
+ open: options2 !== null,
642
+ onClose: () => finish(false),
643
+ title: options2?.title ?? "",
644
+ description: options2?.description,
645
+ size: "sm",
646
+ footer: /* @__PURE__ */ jsxs4(Fragment, { children: [
647
+ /* @__PURE__ */ jsx4(Button, { onClick: () => finish(false), children: options2?.cancelLabel ?? "Cancel" }),
648
+ /* @__PURE__ */ jsx4(Button, { variant: options2?.tone === "danger" ? "danger" : "primary", onClick: () => finish(true), children: options2?.confirmLabel ?? "Confirm" })
649
+ ] }),
650
+ children: /* @__PURE__ */ jsx4("span", { className: "sr-only", children: options2?.description })
651
+ }
652
+ )
653
+ ] });
654
+ }
655
+
656
+ // src/ui/Toast.tsx
657
+ import { CheckCircle2 as CheckCircle22, CircleAlert, X as X2 } from "lucide-react";
658
+ import { createContext as createContext2, useCallback as useCallback2, useContext as useContext2, useState as useState2 } from "react";
659
+ import { jsx as jsx5, jsxs as jsxs5 } from "react/jsx-runtime";
660
+ var ToastContext = createContext2(null);
661
+ function useToast() {
662
+ const toast = useContext2(ToastContext);
663
+ if (!toast) throw new Error("useToast needs the UiProvider (BrandProvider includes it)");
664
+ return toast;
665
+ }
666
+ var nextId = 1;
667
+ function ToastProvider({ children }) {
668
+ const [toasts, setToasts] = useState2([]);
669
+ const dismiss = (id) => setToasts((current) => current.filter((t2) => t2.id !== id));
670
+ const add = useCallback2((kind, message) => {
671
+ const id = nextId++;
672
+ setToasts((current) => [...current, { id, kind, message }]);
673
+ setTimeout(() => setToasts((current) => current.filter((t2) => t2.id !== id)), kind === "error" ? 8e3 : 4500);
674
+ }, []);
675
+ const api2 = { success: (m) => add("success", m), error: (m) => add("error", m) };
676
+ return /* @__PURE__ */ jsxs5(ToastContext.Provider, { value: api2, children: [
677
+ children,
678
+ /* @__PURE__ */ jsx5("div", { className: "pointer-events-none fixed bottom-4 right-4 z-[60] flex w-[calc(100vw-2rem)] max-w-sm flex-col gap-2", "aria-live": "polite", children: toasts.map((t2) => /* @__PURE__ */ jsxs5("div", { className: cn("ui-pop pointer-events-auto flex items-start gap-3 rounded-lg border bg-surface p-3.5 text-sm shadow-pop", t2.kind === "error" ? "border-danger/40" : "border-line"), children: [
679
+ t2.kind === "error" ? /* @__PURE__ */ jsx5(CircleAlert, { className: "mt-0.5 size-4 shrink-0 text-danger", "aria-hidden": true }) : /* @__PURE__ */ jsx5(CheckCircle22, { className: "mt-0.5 size-4 shrink-0 text-ok", "aria-hidden": true }),
680
+ /* @__PURE__ */ jsx5("p", { className: "min-w-0 flex-1 text-fg", children: t2.message }),
681
+ /* @__PURE__ */ jsx5("button", { type: "button", onClick: () => dismiss(t2.id), "aria-label": "Dismiss", className: "text-muted hover:text-fg", children: /* @__PURE__ */ jsx5(X2, { className: "size-4", "aria-hidden": true }) })
682
+ ] }, t2.id)) })
683
+ ] });
684
+ }
685
+ function UiProvider({ children }) {
686
+ return /* @__PURE__ */ jsx5(ToastProvider, { children: /* @__PURE__ */ jsx5(ConfirmProvider, { children }) });
687
+ }
688
+
689
+ // src/ui/DatePicker.tsx
690
+ import * as Popover from "@radix-ui/react-popover";
691
+ import { DayPicker } from "@daypicker/react";
692
+ import "@daypicker/react/style.css";
693
+ import { CalendarDays, X as X3 } from "lucide-react";
694
+ import { useState as useState3 } from "react";
695
+ import { jsx as jsx6, jsxs as jsxs6 } from "react/jsx-runtime";
696
+ function DatePicker({
697
+ value,
698
+ onChange,
699
+ min,
700
+ placeholder = "Choose a date",
701
+ presets: presets2,
702
+ label,
703
+ clearable,
704
+ invalid
705
+ }) {
706
+ const [open, setOpen] = useState3(false);
707
+ const selected = value ? parseDate(value) : void 0;
708
+ const choose = (date) => {
709
+ onChange(date);
710
+ setOpen(false);
711
+ };
712
+ return /* @__PURE__ */ jsxs6(Popover.Root, { open, onOpenChange: setOpen, children: [
713
+ /* @__PURE__ */ jsxs6("div", { className: "relative", children: [
714
+ /* @__PURE__ */ jsx6(Popover.Trigger, { asChild: true, children: /* @__PURE__ */ jsxs6(
715
+ "button",
716
+ {
717
+ type: "button",
718
+ "aria-label": value ? `${label}: ${formatDateLong(value)}` : label,
719
+ className: cn(
720
+ "flex h-10 w-full items-center gap-2 rounded-lg border bg-surface px-3 text-left text-sm shadow-sm outline-none transition",
721
+ "focus-visible:border-brand focus-visible:ring-2 focus-visible:ring-brand/25",
722
+ invalid ? "border-danger" : "border-line-strong",
723
+ value ? "text-fg" : "text-muted/80"
724
+ ),
725
+ children: [
726
+ /* @__PURE__ */ jsx6(CalendarDays, { className: "size-4 shrink-0 text-muted", "aria-hidden": true }),
727
+ /* @__PURE__ */ jsx6("span", { className: "truncate", children: value ? formatDateLong(value) : placeholder })
728
+ ]
729
+ }
730
+ ) }),
731
+ clearable && value && /* @__PURE__ */ jsx6("button", { type: "button", "aria-label": `Clear ${label}`, onClick: () => onChange(""), className: "absolute right-2 top-1/2 -translate-y-1/2 rounded p-1 text-muted hover:bg-surface-muted hover:text-fg", children: /* @__PURE__ */ jsx6(X3, { className: "size-3.5", "aria-hidden": true }) })
732
+ ] }),
733
+ /* @__PURE__ */ jsx6(Popover.Portal, { children: /* @__PURE__ */ jsxs6(Popover.Content, { align: "start", sideOffset: 6, className: "ui-pop z-[70] rounded-card border border-line bg-surface p-3 shadow-pop outline-none", children: [
734
+ presets2 && presets2.length > 0 && /* @__PURE__ */ jsx6("div", { className: "mb-2 flex flex-wrap gap-1.5 border-b border-line pb-3", children: presets2.map((p) => /* @__PURE__ */ jsx6("button", { type: "button", onClick: () => choose(addDays(todayString(), p.days)), className: "rounded-full border border-line-strong px-3 py-1 text-xs font-medium text-fg transition hover:border-brand hover:bg-brand-soft hover:text-brand", children: p.label }, p.label)) }),
735
+ /* @__PURE__ */ jsx6("div", { className: "ui-calendar", children: /* @__PURE__ */ jsx6(
736
+ DayPicker,
737
+ {
738
+ mode: "single",
739
+ selected,
740
+ defaultMonth: selected ?? (min ? parseDate(min) : void 0),
741
+ onSelect: (date) => date && choose(toDateString(date)),
742
+ disabled: min ? { before: parseDate(min) } : void 0,
743
+ weekStartsOn: 1,
744
+ showOutsideDays: true,
745
+ autoFocus: true
746
+ }
747
+ ) })
748
+ ] }) })
749
+ ] });
750
+ }
751
+
752
+ // src/ui/PeoplePicker.tsx
753
+ import { Search } from "lucide-react";
754
+ import { useMemo, useState as useState4 } from "react";
755
+ import { jsx as jsx7, jsxs as jsxs7 } from "react/jsx-runtime";
756
+ function PeoplePicker({
757
+ people,
758
+ value,
759
+ onChange,
760
+ disabledIds = [],
761
+ emptyText = "Nobody to choose from.",
762
+ maxHeight = "16rem"
763
+ }) {
764
+ const [query, setQuery] = useState4("");
765
+ const shown = useMemo(() => {
766
+ const q = query.trim().toLowerCase();
767
+ return q ? people.filter((p) => p.name.toLowerCase().includes(q) || p.email.toLowerCase().includes(q)) : people;
768
+ }, [people, query]);
769
+ const selectable = shown.filter((p) => !disabledIds.includes(p.id));
770
+ const allShownChosen = selectable.length > 0 && selectable.every((p) => value.includes(p.id));
771
+ const toggle = (id) => onChange(value.includes(id) ? value.filter((x) => x !== id) : [...value, id]);
772
+ const toggleAll = () => onChange(allShownChosen ? value.filter((id) => !selectable.some((p) => p.id === id)) : [.../* @__PURE__ */ new Set([...value, ...selectable.map((p) => p.id)])]);
773
+ return /* @__PURE__ */ jsxs7("div", { className: "rounded-lg border border-line-strong", children: [
774
+ /* @__PURE__ */ jsxs7("div", { className: "flex items-center gap-2 border-b border-line px-3", children: [
775
+ /* @__PURE__ */ jsx7(Search, { className: "size-4 shrink-0 text-muted", "aria-hidden": true }),
776
+ /* @__PURE__ */ jsx7(
777
+ "input",
778
+ {
779
+ value: query,
780
+ onChange: (e) => setQuery(e.target.value),
781
+ placeholder: "Search by name or email",
782
+ "aria-label": "Search people",
783
+ className: "h-10 w-full bg-transparent text-sm text-fg outline-none placeholder:text-muted/70"
784
+ }
785
+ )
786
+ ] }),
787
+ /* @__PURE__ */ jsxs7("div", { className: "flex items-center justify-between border-b border-line bg-surface-muted/50 px-3 py-2 text-xs text-muted", children: [
788
+ /* @__PURE__ */ jsxs7("span", { children: [
789
+ /* @__PURE__ */ jsx7("strong", { className: "font-semibold text-fg", children: value.length }),
790
+ " selected"
791
+ ] }),
792
+ selectable.length > 0 && /* @__PURE__ */ jsx7("button", { type: "button", onClick: toggleAll, className: "font-medium text-brand hover:underline", children: allShownChosen ? "Clear" : query ? "Select all shown" : "Select all" })
793
+ ] }),
794
+ /* @__PURE__ */ jsxs7("ul", { className: "overflow-y-auto", style: { maxHeight }, children: [
795
+ shown.length === 0 && /* @__PURE__ */ jsx7("li", { className: "px-3 py-6 text-center text-sm text-muted", children: people.length === 0 ? emptyText : "No match." }),
796
+ shown.map((p) => {
797
+ const locked = disabledIds.includes(p.id);
798
+ const checked = value.includes(p.id) || locked;
799
+ return /* @__PURE__ */ jsx7("li", { children: /* @__PURE__ */ jsxs7("label", { className: cn("flex cursor-pointer items-center gap-3 px-3 py-2 transition hover:bg-surface-muted/60", locked && "cursor-default opacity-60"), children: [
800
+ /* @__PURE__ */ jsx7("input", { type: "checkbox", checked, disabled: locked, onChange: () => toggle(p.id), className: "size-4 shrink-0" }),
801
+ /* @__PURE__ */ jsx7(Avatar, { name: p.name, size: "sm" }),
802
+ /* @__PURE__ */ jsxs7("span", { className: "min-w-0", children: [
803
+ /* @__PURE__ */ jsx7("span", { className: "block truncate text-sm font-medium text-fg", children: p.name }),
804
+ /* @__PURE__ */ jsx7("span", { className: "block truncate text-xs text-muted", children: p.email })
805
+ ] }),
806
+ locked && /* @__PURE__ */ jsx7("span", { className: "ml-auto text-xs text-muted", children: "Already added" })
807
+ ] }) }, p.id);
808
+ })
809
+ ] })
810
+ ] });
811
+ }
812
+
813
+ // src/ui/GroupPicker.tsx
814
+ import { Check as Check2 } from "lucide-react";
815
+ import { jsx as jsx8, jsxs as jsxs8 } from "react/jsx-runtime";
816
+ function GroupPicker({
817
+ groups,
818
+ value,
819
+ onChange,
820
+ legend = "Groups",
821
+ emptyText = "There are no groups yet."
822
+ }) {
823
+ const toggle = (id) => onChange(value.includes(id) ? value.filter((x) => x !== id) : [...value, id]);
824
+ return /* @__PURE__ */ jsxs8("fieldset", { children: [
825
+ /* @__PURE__ */ jsx8("legend", { className: "sr-only", children: legend }),
826
+ groups.length === 0 ? /* @__PURE__ */ jsx8("p", { className: "text-sm text-muted", children: emptyText }) : /* @__PURE__ */ jsx8("div", { className: "flex flex-wrap gap-2", children: groups.map((group) => {
827
+ const selected = value.includes(group.id);
828
+ return /* @__PURE__ */ jsxs8(
829
+ "label",
830
+ {
831
+ className: cn(
832
+ "inline-flex cursor-pointer items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition focus-within:ring-2 focus-within:ring-brand",
833
+ selected ? "border-brand bg-brand-soft text-brand" : "border-line text-fg hover:bg-surface-muted"
834
+ ),
835
+ children: [
836
+ /* @__PURE__ */ jsx8("input", { type: "checkbox", checked: selected, onChange: () => toggle(group.id), className: "sr-only" }),
837
+ selected && /* @__PURE__ */ jsx8(Check2, { className: "size-4", "aria-hidden": true }),
838
+ /* @__PURE__ */ jsx8("span", { className: "font-medium", children: group.name }),
839
+ group.memberCount !== void 0 && /* @__PURE__ */ jsx8("span", { className: "text-xs text-muted", children: group.memberCount })
840
+ ]
841
+ },
842
+ group.id
843
+ );
844
+ }) })
845
+ ] });
846
+ }
847
+
848
+ // src/ui/FileDrop.tsx
849
+ import { FileText, UploadCloud, X as X4 } from "lucide-react";
850
+ import { useEffect, useMemo as useMemo2, useRef as useRef2, useState as useState5 } from "react";
851
+ import { jsx as jsx9, jsxs as jsxs9 } from "react/jsx-runtime";
852
+ function FileDrop({
853
+ file,
854
+ onChange,
855
+ accept = "application/pdf",
856
+ hint = "PDF, up to 20 MB",
857
+ maxBytes = 20 * 1024 * 1024,
858
+ label = "Choose a file",
859
+ existingName
860
+ }) {
861
+ const input = useRef2(null);
862
+ const [over, setOver] = useState5(false);
863
+ const [problem, setProblem] = useState5(null);
864
+ const thumbnail = useMemo2(() => file?.type.startsWith("image/") ? URL.createObjectURL(file) : null, [file]);
865
+ useEffect(() => () => thumbnail ? URL.revokeObjectURL(thumbnail) : void 0, [thumbnail]);
866
+ function take(next) {
867
+ setProblem(null);
868
+ if (!next) return;
869
+ if (accept === "application/pdf" && next.type !== "application/pdf" && !next.name.toLowerCase().endsWith(".pdf")) return setProblem("This is not a PDF file.");
870
+ if (next.size > maxBytes) return setProblem(`The file is larger than ${formatBytes(maxBytes)}.`);
871
+ onChange(next);
872
+ }
873
+ if (file) {
874
+ return /* @__PURE__ */ jsxs9("div", { className: "flex items-center gap-3 rounded-lg border border-line-strong bg-surface-muted/40 p-3", children: [
875
+ thumbnail ? /* @__PURE__ */ jsx9("img", { src: thumbnail, alt: "", className: "size-10 rounded-lg border border-line bg-surface object-contain p-1" }) : /* @__PURE__ */ jsx9("span", { className: "inline-flex size-10 items-center justify-center rounded-lg bg-brand-soft text-brand", children: /* @__PURE__ */ jsx9(FileText, { className: "size-5", "aria-hidden": true }) }),
876
+ /* @__PURE__ */ jsxs9("div", { className: "min-w-0 flex-1", children: [
877
+ /* @__PURE__ */ jsx9("p", { className: "truncate text-sm font-medium text-fg", children: file.name }),
878
+ /* @__PURE__ */ jsx9("p", { className: "text-xs text-muted", children: formatBytes(file.size) })
879
+ ] }),
880
+ /* @__PURE__ */ jsx9("button", { type: "button", onClick: () => onChange(null), "aria-label": "Remove file", className: "rounded p-1.5 text-muted hover:bg-surface-muted hover:text-fg", children: /* @__PURE__ */ jsx9(X4, { className: "size-4", "aria-hidden": true }) })
881
+ ] });
882
+ }
883
+ return /* @__PURE__ */ jsxs9("div", { children: [
884
+ /* @__PURE__ */ jsxs9(
885
+ "button",
886
+ {
887
+ type: "button",
888
+ onClick: () => input.current?.click(),
889
+ onDragOver: (e) => {
890
+ e.preventDefault();
891
+ setOver(true);
892
+ },
893
+ onDragLeave: () => setOver(false),
894
+ onDrop: (e) => {
895
+ e.preventDefault();
896
+ setOver(false);
897
+ take(e.dataTransfer.files[0]);
898
+ },
899
+ className: cn(
900
+ "flex w-full flex-col items-center gap-1 rounded-lg border-2 border-dashed px-4 py-6 text-center outline-none transition",
901
+ "focus-visible:ring-2 focus-visible:ring-brand/40",
902
+ over ? "border-brand bg-brand-soft" : "border-line-strong hover:border-brand hover:bg-surface-muted/50"
903
+ ),
904
+ children: [
905
+ /* @__PURE__ */ jsx9(UploadCloud, { className: "size-7 text-muted", "aria-hidden": true }),
906
+ /* @__PURE__ */ jsxs9("span", { className: "text-sm font-medium text-fg", children: [
907
+ label,
908
+ " ",
909
+ /* @__PURE__ */ jsx9("span", { className: "font-normal text-muted", children: "or drag it here" })
910
+ ] }),
911
+ /* @__PURE__ */ jsxs9("span", { className: "text-xs text-muted", children: [
912
+ existingName ? `Current file: ${existingName}. ` : "",
913
+ hint
914
+ ] })
915
+ ]
916
+ }
917
+ ),
918
+ /* @__PURE__ */ jsx9("input", { ref: input, type: "file", accept, className: "sr-only", tabIndex: -1, onChange: (e) => take(e.target.files?.[0]) }),
919
+ problem && /* @__PURE__ */ jsx9("p", { className: "mt-1.5 text-xs text-danger", children: problem })
920
+ ] });
921
+ }
922
+
923
+ // src/ui/Menu.tsx
924
+ import * as Popover2 from "@radix-ui/react-popover";
925
+ import { useState as useState6 } from "react";
926
+ import { jsx as jsx10, jsxs as jsxs10 } from "react/jsx-runtime";
927
+ function Menu({ trigger, label, children, align = "end" }) {
928
+ const [open, setOpen] = useState6(false);
929
+ return /* @__PURE__ */ jsxs10(Popover2.Root, { open, onOpenChange: setOpen, children: [
930
+ /* @__PURE__ */ jsx10(Popover2.Trigger, { asChild: true, children: /* @__PURE__ */ jsx10("button", { type: "button", "aria-label": label, className: "rounded-lg outline-none transition focus-visible:ring-2 focus-visible:ring-brand/40", children: trigger }) }),
931
+ /* @__PURE__ */ jsx10(Popover2.Portal, { children: /* @__PURE__ */ jsx10(Popover2.Content, { align, sideOffset: 6, className: "ui-pop z-[70] min-w-52 rounded-card border border-line bg-surface p-1.5 shadow-pop outline-none", children: children(() => setOpen(false)) }) })
932
+ ] });
933
+ }
934
+ function MenuItem({ icon, children, onClick, tone = "default" }) {
935
+ return /* @__PURE__ */ jsxs10(
936
+ "button",
937
+ {
938
+ type: "button",
939
+ onClick,
940
+ className: cn(
941
+ "flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-sm outline-none transition hover:bg-surface-muted focus-visible:bg-surface-muted",
942
+ tone === "danger" ? "text-danger" : "text-fg"
943
+ ),
944
+ children: [
945
+ icon && /* @__PURE__ */ jsx10("span", { className: "text-muted [&>svg]:size-4", children: icon }),
946
+ children
947
+ ]
948
+ }
949
+ );
950
+ }
951
+ var MenuSeparator = () => /* @__PURE__ */ jsx10("div", { className: "my-1 h-px bg-line", role: "separator" });
952
+
953
+ // src/auth/AuthLayout.tsx
954
+ import { Eye, EyeOff } from "lucide-react";
955
+ import { useId as useId2, useState as useState8 } from "react";
956
+
957
+ // src/brand.tsx
958
+ import { createContext as createContext3, useContext as useContext3, useEffect as useEffect2, useState as useState7 } from "react";
959
+ import { jsx as jsx11 } from "react/jsx-runtime";
960
+ var DEFAULT_BRAND = { appName: "appai", logoUrl: null, fontFamily: null, fontUrl: null, colors: {} };
961
+ var BrandContext = createContext3(DEFAULT_BRAND);
962
+ var useBrand = () => useContext3(BrandContext);
963
+ var SetBrandContext = createContext3(() => {
964
+ });
965
+ var useSetBrand = () => useContext3(SetBrandContext);
966
+ var declarations = (vars) => Object.entries(vars).filter(([, value]) => value).map(([name, value]) => `${name}:${value};`).join("");
967
+ function brandCss({ colors, fontFamily, fontUrl }) {
968
+ const light = declarations({
969
+ "--brand-primary": colors.primary,
970
+ "--brand-primary-contrast": colors.primaryContrast,
971
+ "--brand-secondary": colors.secondary,
972
+ "--font-sans": fontFamily ? fontUrl ? `"Brand", ${fontFamily}` : fontFamily : void 0
973
+ });
974
+ const dark = declarations({
975
+ "--brand-primary": colors.primaryDark,
976
+ "--brand-primary-contrast": colors.primaryDarkContrast,
977
+ "--brand-secondary": colors.secondaryDark
978
+ });
979
+ const face = fontUrl ? `@font-face{font-family:"Brand";src:url(${fontUrl}) format("woff2");font-display:swap;}` : "";
980
+ return `${face}:root{${light}}` + (dark ? `@media (prefers-color-scheme:dark){:root:not(.light){${dark}}}:root.dark{${dark}}` : "");
981
+ }
982
+ var THEME_KEY = "appai-theme";
983
+ function getThemeMode() {
984
+ try {
985
+ const stored = localStorage.getItem(THEME_KEY);
986
+ return stored === "light" || stored === "dark" ? stored : "system";
987
+ } catch {
988
+ return "system";
989
+ }
990
+ }
991
+ function setThemeMode(mode) {
992
+ const root = document.documentElement;
993
+ root.classList.toggle("light", mode === "light");
994
+ root.classList.toggle("dark", mode === "dark");
995
+ try {
996
+ if (mode === "system") localStorage.removeItem(THEME_KEY);
997
+ else localStorage.setItem(THEME_KEY, mode);
998
+ } catch {
999
+ }
1000
+ }
1001
+ function BrandProvider({ children }) {
1002
+ const [brand, setBrand] = useState7(null);
1003
+ useEffect2(() => {
1004
+ setThemeMode(getThemeMode());
1005
+ let cancelled = false;
1006
+ fetch("/api/brand").then((r) => r.ok ? r.json() : DEFAULT_BRAND).catch(() => DEFAULT_BRAND).then((b) => {
1007
+ if (!cancelled) setBrand(b);
1008
+ });
1009
+ return () => {
1010
+ cancelled = true;
1011
+ };
1012
+ }, []);
1013
+ useEffect2(() => {
1014
+ if (!brand) return;
1015
+ const style = document.createElement("style");
1016
+ style.dataset.brand = "";
1017
+ style.textContent = brandCss(brand);
1018
+ document.head.appendChild(style);
1019
+ document.title = brand.appName;
1020
+ return () => style.remove();
1021
+ }, [brand]);
1022
+ if (!brand) return null;
1023
+ return /* @__PURE__ */ jsx11(BrandContext.Provider, { value: brand, children: /* @__PURE__ */ jsx11(SetBrandContext.Provider, { value: setBrand, children: /* @__PURE__ */ jsx11(UiProvider, { children }) }) });
1024
+ }
1025
+
1026
+ // src/auth/texts.ts
1027
+ var t = {
1028
+ signIn: "Sign in",
1029
+ signOut: "Sign out",
1030
+ signUp: "Create account",
1031
+ email: "Email",
1032
+ name: "Your name",
1033
+ password: "Password",
1034
+ newPassword: "New password",
1035
+ passwordHint: "At least 10 characters.",
1036
+ forgotPassword: "Forgot your password?",
1037
+ resetPassword: "Reset password",
1038
+ sendResetLink: "Send reset link",
1039
+ backToSignIn: "Back to sign in",
1040
+ useInvitationLink: "To join a company, open the link in your invitation email. Creating an account here without it does not work.",
1041
+ haveInvitation: "Have an invitation? Create your account",
1042
+ checkEmailTitle: "Check your email",
1043
+ checkEmailSignUp: "If this email address can create an account, we sent a verification link to it. Open the link to finish. Accounts are created by invitation only.",
1044
+ checkEmailReset: "If an account exists for this address, we sent a link to reset the password.",
1045
+ invalidCredentials: "Wrong email or password.",
1046
+ notVerified: "Your email address is not verified yet. We sent you a new verification link.",
1047
+ genericError: "Something went wrong. Please try again.",
1048
+ passwordTooShort: "The password must have at least 10 characters.",
1049
+ resetDone: "Your password was changed. You can sign in now.",
1050
+ resetInvalid: "This reset link is invalid or has expired. Request a new one.",
1051
+ acceptingInvitation: "Joining your company...",
1052
+ invitationFailed: "The invitation could not be accepted. It may have expired or been used already.",
1053
+ loading: "Loading...",
1054
+ signInDescription: "Welcome back. Enter your details to continue.",
1055
+ signUpDescription: "Create your account to get started.",
1056
+ forgotDescription: "Enter your email address and we will send you a link to choose a new password.",
1057
+ newPasswordDescription: "Choose a new password for your account.",
1058
+ acceptingDescription: "One moment while we set up your access.",
1059
+ checkEmailDescription: "One more step before you can sign in.",
1060
+ showPassword: "Show password",
1061
+ hidePassword: "Hide password"
1062
+ };
1063
+
1064
+ // src/auth/AuthLayout.tsx
1065
+ import { jsx as jsx12, jsxs as jsxs11 } from "react/jsx-runtime";
1066
+ function AuthLayout({ title, description, children, footer }) {
1067
+ const brand = useBrand();
1068
+ return /* @__PURE__ */ jsxs11("div", { className: "relative flex min-h-svh flex-col items-center justify-center overflow-hidden bg-page px-4 py-10", children: [
1069
+ /* @__PURE__ */ jsx12("div", { "aria-hidden": true, className: "pointer-events-none absolute -top-48 left-1/2 size-[44rem] -translate-x-1/2 rounded-full bg-brand-soft blur-3xl" }),
1070
+ /* @__PURE__ */ jsx12("div", { "aria-hidden": true, className: "pointer-events-none absolute -bottom-56 -right-32 size-[34rem] rounded-full bg-brand-soft opacity-70 blur-3xl" }),
1071
+ /* @__PURE__ */ jsxs11("div", { className: "relative w-full max-w-md", children: [
1072
+ /* @__PURE__ */ jsxs11("div", { className: "mb-6 flex flex-col items-center gap-3 text-center", children: [
1073
+ brand.logoUrl ? /* @__PURE__ */ jsx12("img", { src: brand.logoUrl, alt: "", className: "h-12 w-auto max-w-56 object-contain" }) : /* @__PURE__ */ jsx12("span", { "aria-hidden": true, className: "inline-flex size-12 items-center justify-center rounded-2xl bg-brand text-lg font-semibold text-brand-fg shadow-card", children: initials(brand.appName) }),
1074
+ /* @__PURE__ */ jsx12("p", { className: "text-lg font-semibold tracking-tight text-fg", children: brand.appName })
1075
+ ] }),
1076
+ /* @__PURE__ */ jsxs11(Card, { className: "p-6 shadow-pop sm:p-8", children: [
1077
+ /* @__PURE__ */ jsx12("h1", { className: "text-2xl font-semibold tracking-tight text-fg", children: title }),
1078
+ description && /* @__PURE__ */ jsx12("p", { className: "mt-1.5 text-sm text-muted", children: description }),
1079
+ /* @__PURE__ */ jsx12("div", { className: "mt-6", children })
1080
+ ] }),
1081
+ footer && /* @__PURE__ */ jsx12("div", { className: "mt-6 space-y-2 text-center text-sm text-muted", children: footer })
1082
+ ] })
1083
+ ] });
1084
+ }
1085
+ function PasswordField({ label, hint, className, ...props }) {
1086
+ const id = useId2();
1087
+ const [visible, setVisible] = useState8(false);
1088
+ return /* @__PURE__ */ jsxs11("div", { className, children: [
1089
+ /* @__PURE__ */ jsx12("label", { htmlFor: id, className: "mb-1.5 block text-sm font-medium text-fg", children: label }),
1090
+ /* @__PURE__ */ jsxs11("div", { className: "relative", children: [
1091
+ /* @__PURE__ */ jsx12(Input, { id, type: visible ? "text" : "password", className: "pr-11", ...props }),
1092
+ /* @__PURE__ */ jsx12(
1093
+ "button",
1094
+ {
1095
+ type: "button",
1096
+ onClick: () => setVisible((v) => !v),
1097
+ "aria-label": visible ? t.hidePassword : t.showPassword,
1098
+ "aria-pressed": visible,
1099
+ className: cn("absolute right-1.5 top-1/2 inline-flex size-8 -translate-y-1/2 items-center justify-center rounded-md text-muted outline-none transition hover:text-fg", "focus-visible:ring-2 focus-visible:ring-brand/40"),
1100
+ children: visible ? /* @__PURE__ */ jsx12(EyeOff, { className: "size-4", "aria-hidden": true }) : /* @__PURE__ */ jsx12(Eye, { className: "size-4", "aria-hidden": true })
1101
+ }
1102
+ )
1103
+ ] }),
1104
+ hint && /* @__PURE__ */ jsx12("p", { className: "mt-1.5 text-xs text-muted", children: hint })
1105
+ ] });
1106
+ }
1107
+
1108
+ // src/auth/pages.tsx
1109
+ import { Fragment as Fragment2, jsx as jsx13, jsxs as jsxs12 } from "react/jsx-runtime";
1110
+ var linkClass = "font-medium text-brand hover:underline";
1111
+ function LoginPage() {
1112
+ const [params] = useSearchParams();
1113
+ const navigate = useNavigate();
1114
+ const [error, setError] = useState9(null);
1115
+ const [busy, setBusy] = useState9(false);
1116
+ const next = params.get("next") ?? "/";
1117
+ async function onSubmit(e) {
1118
+ e.preventDefault();
1119
+ const form = new FormData(e.currentTarget);
1120
+ setBusy(true);
1121
+ setError(null);
1122
+ const { error: error2 } = await authClient.signIn.email({
1123
+ email: String(form.get("email")),
1124
+ password: String(form.get("password"))
1125
+ });
1126
+ setBusy(false);
1127
+ if (!error2) return navigate(next, { replace: true });
1128
+ setError(error2.status === 403 ? t.notVerified : error2.status === 401 ? t.invalidCredentials : t.genericError);
1129
+ }
1130
+ return /* @__PURE__ */ jsx13(
1131
+ AuthLayout,
1132
+ {
1133
+ title: t.signIn,
1134
+ description: t.signInDescription,
1135
+ footer: /* @__PURE__ */ jsxs12(Fragment2, { children: [
1136
+ /* @__PURE__ */ jsx13("p", { children: /* @__PURE__ */ jsx13(Link2, { to: "/forgot-password", className: linkClass, children: t.forgotPassword }) }),
1137
+ /* @__PURE__ */ jsx13("p", { children: /* @__PURE__ */ jsx13(Link2, { to: "/signup", className: linkClass, children: t.haveInvitation }) })
1138
+ ] }),
1139
+ children: /* @__PURE__ */ jsxs12("div", { className: "space-y-4", children: [
1140
+ params.get("reset") && /* @__PURE__ */ jsx13(Alert, { kind: "success", children: t.resetDone }),
1141
+ error && /* @__PURE__ */ jsx13(Alert, { kind: "error", children: error }),
1142
+ /* @__PURE__ */ jsxs12("form", { onSubmit, className: "space-y-4", children: [
1143
+ /* @__PURE__ */ jsx13(Field, { label: t.email, children: /* @__PURE__ */ jsx13(Input, { name: "email", type: "email", autoComplete: "email", required: true, autoFocus: true }) }),
1144
+ /* @__PURE__ */ jsx13(PasswordField, { label: t.password, name: "password", autoComplete: "current-password", required: true }),
1145
+ /* @__PURE__ */ jsx13(Button, { type: "submit", variant: "primary", size: "lg", block: true, loading: busy, children: t.signIn })
1146
+ ] })
1147
+ ] })
1148
+ }
1149
+ );
1150
+ }
1151
+ function SignupPage() {
1152
+ const [params] = useSearchParams();
1153
+ const invitation = params.get("invitation");
1154
+ const [done, setDone] = useState9(false);
1155
+ const [error, setError] = useState9(null);
1156
+ const [busy, setBusy] = useState9(false);
1157
+ async function onSubmit(e) {
1158
+ e.preventDefault();
1159
+ const form = new FormData(e.currentTarget);
1160
+ const password = String(form.get("password"));
1161
+ if (password.length < 10) return setError(t.passwordTooShort);
1162
+ setBusy(true);
1163
+ setError(null);
1164
+ const callbackURL = invitation ? `/accept-invitation?invitation=${encodeURIComponent(invitation)}` : "/";
1165
+ const { error: error2 } = await authClient.signUp.email({
1166
+ name: String(form.get("name")),
1167
+ email: String(form.get("email")),
1168
+ password,
1169
+ callbackURL
1170
+ });
1171
+ setBusy(false);
1172
+ if (error2) setError(t.genericError);
1173
+ else setDone(true);
1174
+ }
1175
+ const backLink = /* @__PURE__ */ jsx13("p", { children: /* @__PURE__ */ jsx13(Link2, { to: "/login", className: linkClass, children: t.backToSignIn }) });
1176
+ if (done) {
1177
+ return /* @__PURE__ */ jsx13(AuthLayout, { title: t.checkEmailTitle, description: t.checkEmailDescription, footer: backLink, children: /* @__PURE__ */ jsxs12("div", { className: "flex gap-3 rounded-lg bg-brand-soft p-4 text-sm text-fg", children: [
1178
+ /* @__PURE__ */ jsx13(Mail, { className: "mt-0.5 size-5 shrink-0 text-brand", "aria-hidden": true }),
1179
+ /* @__PURE__ */ jsx13("p", { children: t.checkEmailSignUp })
1180
+ ] }) });
1181
+ }
1182
+ return /* @__PURE__ */ jsx13(AuthLayout, { title: t.signUp, description: t.signUpDescription, footer: backLink, children: /* @__PURE__ */ jsxs12("div", { className: "space-y-4", children: [
1183
+ error && /* @__PURE__ */ jsx13(Alert, { kind: "error", children: error }),
1184
+ /* @__PURE__ */ jsxs12("form", { onSubmit, className: "space-y-4", children: [
1185
+ /* @__PURE__ */ jsx13(Field, { label: t.name, children: /* @__PURE__ */ jsx13(Input, { name: "name", autoComplete: "name", required: true, autoFocus: true }) }),
1186
+ /* @__PURE__ */ jsx13(Field, { label: t.email, children: /* @__PURE__ */ jsx13(Input, { name: "email", type: "email", autoComplete: "email", defaultValue: params.get("email") ?? "", required: true }) }),
1187
+ /* @__PURE__ */ jsx13(PasswordField, { label: t.password, name: "password", autoComplete: "new-password", minLength: 10, required: true, hint: t.passwordHint }),
1188
+ /* @__PURE__ */ jsx13(Button, { type: "submit", variant: "primary", size: "lg", block: true, loading: busy, children: t.signUp })
1189
+ ] }),
1190
+ !invitation && /* @__PURE__ */ jsx13(Alert, { kind: "info", children: t.useInvitationLink })
1191
+ ] }) });
1192
+ }
1193
+ function ForgotPasswordPage() {
1194
+ const [sent, setSent] = useState9(false);
1195
+ const [busy, setBusy] = useState9(false);
1196
+ async function onSubmit(e) {
1197
+ e.preventDefault();
1198
+ const form = new FormData(e.currentTarget);
1199
+ setBusy(true);
1200
+ await authClient.requestPasswordReset({
1201
+ email: String(form.get("email")),
1202
+ redirectTo: `${window.location.origin}/reset-password`
1203
+ });
1204
+ setBusy(false);
1205
+ setSent(true);
1206
+ }
1207
+ return /* @__PURE__ */ jsx13(
1208
+ AuthLayout,
1209
+ {
1210
+ title: t.resetPassword,
1211
+ description: t.forgotDescription,
1212
+ footer: /* @__PURE__ */ jsx13("p", { children: /* @__PURE__ */ jsx13(Link2, { to: "/login", className: linkClass, children: t.backToSignIn }) }),
1213
+ children: sent ? /* @__PURE__ */ jsx13(Alert, { kind: "success", children: t.checkEmailReset }) : /* @__PURE__ */ jsxs12("form", { onSubmit, className: "space-y-4", children: [
1214
+ /* @__PURE__ */ jsx13(Field, { label: t.email, children: /* @__PURE__ */ jsx13(Input, { name: "email", type: "email", autoComplete: "email", required: true, autoFocus: true }) }),
1215
+ /* @__PURE__ */ jsx13(Button, { type: "submit", variant: "primary", size: "lg", block: true, loading: busy, children: t.sendResetLink })
1216
+ ] })
1217
+ }
1218
+ );
1219
+ }
1220
+ function ResetPasswordPage() {
1221
+ const [params] = useSearchParams();
1222
+ const navigate = useNavigate();
1223
+ const token = params.get("token");
1224
+ const [error, setError] = useState9(params.get("error") ? t.resetInvalid : null);
1225
+ const [busy, setBusy] = useState9(false);
1226
+ async function onSubmit(e) {
1227
+ e.preventDefault();
1228
+ const form = new FormData(e.currentTarget);
1229
+ const newPassword = String(form.get("password"));
1230
+ if (newPassword.length < 10) return setError(t.passwordTooShort);
1231
+ setBusy(true);
1232
+ const { error: error2 } = await authClient.resetPassword({ newPassword, token: token ?? "" });
1233
+ setBusy(false);
1234
+ if (error2) setError(t.resetInvalid);
1235
+ else navigate("/login?reset=1", { replace: true });
1236
+ }
1237
+ return /* @__PURE__ */ jsx13(
1238
+ AuthLayout,
1239
+ {
1240
+ title: t.resetPassword,
1241
+ description: t.newPasswordDescription,
1242
+ footer: /* @__PURE__ */ jsx13("p", { children: /* @__PURE__ */ jsx13(Link2, { to: "/forgot-password", className: linkClass, children: t.sendResetLink }) }),
1243
+ children: /* @__PURE__ */ jsxs12("div", { className: "space-y-4", children: [
1244
+ error && /* @__PURE__ */ jsx13(Alert, { kind: "error", children: error }),
1245
+ token && /* @__PURE__ */ jsxs12("form", { onSubmit, className: "space-y-4", children: [
1246
+ /* @__PURE__ */ jsx13(PasswordField, { label: t.newPassword, name: "password", autoComplete: "new-password", minLength: 10, required: true, autoFocus: true, hint: t.passwordHint }),
1247
+ /* @__PURE__ */ jsx13(Button, { type: "submit", variant: "primary", size: "lg", block: true, loading: busy, children: t.resetPassword })
1248
+ ] })
1249
+ ] })
1250
+ }
1251
+ );
1252
+ }
1253
+ function AcceptInvitationPage() {
1254
+ const [params] = useSearchParams();
1255
+ const navigate = useNavigate();
1256
+ const invitationId = params.get("invitation");
1257
+ const [failed, setFailed] = useState9(false);
1258
+ useEffect3(() => {
1259
+ if (!invitationId) return;
1260
+ void authClient.organization.acceptInvitation({ invitationId }).then(async ({ error }) => {
1261
+ const me = error ? await fetchMe() : null;
1262
+ if (!error || me && me.roles.length > 0) navigate("/", { replace: true });
1263
+ else setFailed(true);
1264
+ });
1265
+ }, [invitationId, navigate]);
1266
+ const showError = failed || !invitationId;
1267
+ return /* @__PURE__ */ jsx13(AuthLayout, { title: t.acceptingInvitation, description: showError ? void 0 : t.acceptingDescription, children: showError ? /* @__PURE__ */ jsx13(Alert, { kind: "error", children: t.invitationFailed }) : /* @__PURE__ */ jsx13(Spinner, { label: t.loading }) });
1268
+ }
1269
+ function RequireAuth({ children }) {
1270
+ const { data, isPending } = useSession();
1271
+ if (isPending) {
1272
+ return /* @__PURE__ */ jsx13("div", { className: "grid min-h-svh place-items-center bg-page", children: /* @__PURE__ */ jsx13(Spinner, { label: t.loading }) });
1273
+ }
1274
+ if (!data) {
1275
+ const next = window.location.pathname + window.location.search;
1276
+ return /* @__PURE__ */ jsx13(Navigate, { to: `/login?next=${encodeURIComponent(next)}`, replace: true });
1277
+ }
1278
+ return /* @__PURE__ */ jsx13(Fragment2, { children });
1279
+ }
1280
+ function useMe() {
1281
+ const { data } = useSession();
1282
+ const [me, setMe] = useState9(null);
1283
+ useEffect3(() => {
1284
+ if (!data) return;
1285
+ let cancelled = false;
1286
+ void fetchMe().then((m) => {
1287
+ if (!cancelled) setMe(m);
1288
+ });
1289
+ return () => {
1290
+ cancelled = true;
1291
+ };
1292
+ }, [data]);
1293
+ return data ? me : null;
1294
+ }
1295
+
1296
+ // src/ThemeToggle.tsx
1297
+ import { Monitor, Moon, Sun } from "lucide-react";
1298
+ import { useState as useState10 } from "react";
1299
+ import { jsx as jsx14, jsxs as jsxs13 } from "react/jsx-runtime";
1300
+ var options = [
1301
+ { mode: "light", label: shell.theme.light, icon: Sun },
1302
+ { mode: "dark", label: shell.theme.dark, icon: Moon },
1303
+ { mode: "system", label: shell.theme.system, icon: Monitor }
1304
+ ];
1305
+ function ThemeToggle() {
1306
+ const [mode, setMode] = useState10(getThemeMode);
1307
+ return /* @__PURE__ */ jsx14("div", { role: "radiogroup", "aria-label": shell.themeTitle, className: "grid grid-cols-3 gap-1 rounded-lg bg-surface-muted p-1", children: options.map(({ mode: m, label, icon: Icon }) => /* @__PURE__ */ jsxs13(
1308
+ "button",
1309
+ {
1310
+ type: "button",
1311
+ role: "radio",
1312
+ "aria-checked": mode === m,
1313
+ onClick: () => {
1314
+ setThemeMode(m);
1315
+ setMode(m);
1316
+ },
1317
+ className: cn(
1318
+ "flex items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs font-medium outline-none transition focus-visible:ring-2 focus-visible:ring-brand/40",
1319
+ mode === m ? "bg-surface text-fg shadow-sm" : "text-muted hover:text-fg"
1320
+ ),
1321
+ children: [
1322
+ /* @__PURE__ */ jsx14(Icon, { className: "size-3.5", "aria-hidden": true }),
1323
+ label
1324
+ ]
1325
+ },
1326
+ m
1327
+ )) });
1328
+ }
1329
+
1330
+ // src/AppShell.tsx
1331
+ import { Fragment as Fragment3, jsx as jsx15, jsxs as jsxs14 } from "react/jsx-runtime";
1332
+ var STATUS_REFRESH_MS = 5 * 6e4;
1333
+ function AttentionDot({ level }) {
1334
+ return /* @__PURE__ */ jsx15("span", { className: cn("ml-auto size-2 shrink-0 rounded-full", level === "fail" ? "bg-danger" : "bg-warn"), children: /* @__PURE__ */ jsx15("span", { className: "sr-only", children: shell.needsAttention }) });
1335
+ }
1336
+ function NavGroup({ title, items, onNavigate, attention = null }) {
1337
+ if (items.length === 0) return null;
1338
+ return /* @__PURE__ */ jsxs14("nav", { "aria-label": title ?? shell.menu, className: "mb-6", children: [
1339
+ title && /* @__PURE__ */ jsx15("p", { className: "mb-2 px-3 text-xs font-semibold uppercase tracking-wider text-muted", children: title }),
1340
+ /* @__PURE__ */ jsx15("ul", { className: "space-y-0.5", children: items.map(({ to, label, icon: Icon }) => /* @__PURE__ */ jsx15("li", { children: /* @__PURE__ */ jsxs14(
1341
+ NavLink,
1342
+ {
1343
+ to,
1344
+ end: to === "/",
1345
+ onClick: onNavigate,
1346
+ className: ({ isActive }) => cn(
1347
+ "flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium outline-none transition focus-visible:ring-2 focus-visible:ring-brand/40",
1348
+ isActive ? "bg-brand-soft text-brand" : "text-muted hover:bg-surface-muted hover:text-fg"
1349
+ ),
1350
+ children: [
1351
+ Icon && /* @__PURE__ */ jsx15(Icon, { className: "size-[18px] shrink-0", "aria-hidden": true }),
1352
+ label,
1353
+ attention && to === STATUS_PATH && /* @__PURE__ */ jsx15(AttentionDot, { level: attention })
1354
+ ]
1355
+ }
1356
+ ) }, to)) })
1357
+ ] });
1358
+ }
1359
+ function AppShell({ nav = [], children }) {
1360
+ const { data } = useSession();
1361
+ const me = useMe();
1362
+ const brand = useBrand();
1363
+ const navigate = useNavigate2();
1364
+ const { pathname } = useLocation();
1365
+ const [open, setOpen] = useState11(false);
1366
+ const [attention, setAttention] = useState11(null);
1367
+ async function signOut() {
1368
+ await authClient.signOut();
1369
+ navigate("/login");
1370
+ }
1371
+ const allowed = (items) => items.filter((i) => !i.permission || can(me, i.permission));
1372
+ const close = () => setOpen(false);
1373
+ const name = data?.user.name ?? "";
1374
+ const adminGroups2 = visibleAdminGroups((i) => !i.permission || can(me, i.permission));
1375
+ const adminPages = adminGroups2.flatMap((g2) => g2.items);
1376
+ const inAdmin = adminPages.length > 1 && isAdminPath(pathname);
1377
+ const AdminIcon = adminIcon;
1378
+ const canSeeStatus = can(me, "status:read");
1379
+ useEffect4(() => {
1380
+ if (!canSeeStatus) return;
1381
+ let stopped = false;
1382
+ const refresh = () => void api("/api/status").then((s) => !stopped && setAttention(s.status === "ok" ? null : s.status)).catch(() => void 0);
1383
+ refresh();
1384
+ const timer = setInterval(refresh, STATUS_REFRESH_MS);
1385
+ return () => {
1386
+ stopped = true;
1387
+ clearInterval(timer);
1388
+ };
1389
+ }, [canSeeStatus, inAdmin]);
1390
+ const sidebar = /* @__PURE__ */ jsxs14("div", { className: "flex h-full flex-col", children: [
1391
+ /* @__PURE__ */ jsxs14(Link3, { to: "/", onClick: close, className: "flex items-center gap-3 px-6 py-5 text-lg font-semibold tracking-tight text-fg", children: [
1392
+ brand.logoUrl && /* @__PURE__ */ jsx15("img", { src: brand.logoUrl, alt: "", className: "h-8 w-auto" }),
1393
+ /* @__PURE__ */ jsx15("span", { className: "truncate", children: brand.appName })
1394
+ ] }),
1395
+ /* @__PURE__ */ jsx15("div", { className: "flex-1 overflow-y-auto px-3 pt-2", children: inAdmin ? /* @__PURE__ */ jsxs14(Fragment3, { children: [
1396
+ /* @__PURE__ */ jsxs14(
1397
+ Link3,
1398
+ {
1399
+ to: "/",
1400
+ onClick: close,
1401
+ className: "mb-5 flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-muted outline-none transition hover:bg-surface-muted hover:text-fg focus-visible:ring-2 focus-visible:ring-brand/40",
1402
+ children: [
1403
+ /* @__PURE__ */ jsx15(ArrowLeft, { className: "size-[18px] shrink-0", "aria-hidden": true }),
1404
+ shell.backToApp
1405
+ ]
1406
+ }
1407
+ ),
1408
+ adminGroups2.map((g2) => /* @__PURE__ */ jsx15(NavGroup, { title: g2.title, items: g2.items, onNavigate: close, attention }, g2.title))
1409
+ ] }) : /* @__PURE__ */ jsx15(NavGroup, { items: allowed(nav), onNavigate: close }) }),
1410
+ !inAdmin && adminPages.length > 0 && /* @__PURE__ */ jsx15("nav", { "aria-label": shell.administration, className: "px-3 pb-3", children: /* @__PURE__ */ jsxs14(
1411
+ NavLink,
1412
+ {
1413
+ to: adminPages[0].to,
1414
+ onClick: close,
1415
+ className: ({ isActive }) => cn(
1416
+ "flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium outline-none transition focus-visible:ring-2 focus-visible:ring-brand/40",
1417
+ isActive ? "bg-brand-soft text-brand" : "text-muted hover:bg-surface-muted hover:text-fg"
1418
+ ),
1419
+ children: [
1420
+ /* @__PURE__ */ jsx15(AdminIcon, { className: "size-[18px] shrink-0", "aria-hidden": true }),
1421
+ shell.administration,
1422
+ attention && /* @__PURE__ */ jsx15(AttentionDot, { level: attention })
1423
+ ]
1424
+ }
1425
+ ) }),
1426
+ data && /* @__PURE__ */ jsx15("div", { className: "border-t border-line p-3", children: /* @__PURE__ */ jsx15(
1427
+ Menu,
1428
+ {
1429
+ label: shell.account,
1430
+ align: "start",
1431
+ trigger: /* @__PURE__ */ jsxs14("span", { className: "flex w-full items-center gap-3 rounded-lg p-2 text-left transition hover:bg-surface-muted", children: [
1432
+ /* @__PURE__ */ jsx15(Avatar, { name: name || data.user.email }),
1433
+ /* @__PURE__ */ jsxs14("span", { className: "min-w-0 flex-1", children: [
1434
+ /* @__PURE__ */ jsx15("span", { className: "block truncate text-sm font-medium text-fg", children: name || data.user.email }),
1435
+ /* @__PURE__ */ jsx15("span", { className: "block truncate text-xs text-muted", children: data.user.email })
1436
+ ] })
1437
+ ] }),
1438
+ children: () => /* @__PURE__ */ jsxs14("div", { className: "w-64", children: [
1439
+ /* @__PURE__ */ jsx15("p", { className: "px-2.5 pb-2 pt-1 text-xs font-semibold uppercase tracking-wide text-muted", children: shell.appearance }),
1440
+ /* @__PURE__ */ jsx15("div", { className: "px-1.5 pb-1", children: /* @__PURE__ */ jsx15(ThemeToggle, {}) }),
1441
+ /* @__PURE__ */ jsx15(MenuSeparator, {}),
1442
+ /* @__PURE__ */ jsxs14("button", { type: "button", onClick: signOut, className: "flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-sm text-fg transition hover:bg-surface-muted", children: [
1443
+ /* @__PURE__ */ jsx15(LogOut, { className: "size-4 text-muted", "aria-hidden": true }),
1444
+ t.signOut
1445
+ ] })
1446
+ ] })
1447
+ }
1448
+ ) })
1449
+ ] });
1450
+ return /* @__PURE__ */ jsxs14("div", { className: "min-h-screen bg-page lg:grid lg:grid-cols-[16.5rem_minmax(0,1fr)]", children: [
1451
+ /* @__PURE__ */ jsx15("a", { href: "#content", className: "sr-only focus:not-sr-only focus:absolute focus:left-2 focus:top-2 focus:z-50 focus:rounded-md focus:bg-surface focus:px-3 focus:py-2", children: shell.skipToContent }),
1452
+ /* @__PURE__ */ jsx15("aside", { className: "sticky top-0 hidden h-screen border-r border-line bg-surface lg:block", children: sidebar }),
1453
+ /* @__PURE__ */ jsxs14("header", { className: "sticky top-0 z-30 flex items-center gap-3 border-b border-line bg-surface/95 px-4 py-3 backdrop-blur lg:hidden", children: [
1454
+ /* @__PURE__ */ jsx15("button", { type: "button", onClick: () => setOpen(true), "aria-label": shell.openMenu, className: "rounded-lg p-2 text-fg hover:bg-surface-muted", children: /* @__PURE__ */ jsx15(MenuIcon, { className: "size-5", "aria-hidden": true }) }),
1455
+ /* @__PURE__ */ jsxs14(Link3, { to: "/", className: "flex items-center gap-2 font-semibold text-fg", children: [
1456
+ brand.logoUrl && /* @__PURE__ */ jsx15("img", { src: brand.logoUrl, alt: "", className: "h-7 w-auto" }),
1457
+ brand.appName
1458
+ ] })
1459
+ ] }),
1460
+ open && /* @__PURE__ */ jsxs14("div", { className: "fixed inset-0 z-40 lg:hidden", children: [
1461
+ /* @__PURE__ */ jsx15("button", { type: "button", "aria-label": shell.closeMenu, className: "ui-fade absolute inset-0 bg-[var(--overlay)]", onClick: close }),
1462
+ /* @__PURE__ */ jsxs14("div", { className: "ui-pop absolute inset-y-0 left-0 w-72 max-w-[85vw] bg-surface shadow-pop", children: [
1463
+ /* @__PURE__ */ jsx15("button", { type: "button", onClick: close, "aria-label": shell.closeMenu, className: "absolute right-3 top-4 rounded-lg p-2 text-muted hover:bg-surface-muted", children: /* @__PURE__ */ jsx15(X5, { className: "size-5", "aria-hidden": true }) }),
1464
+ sidebar
1465
+ ] })
1466
+ ] }),
1467
+ /* @__PURE__ */ jsx15("main", { id: "content", className: "min-w-0 px-4 py-6 sm:px-8 lg:px-12 lg:py-10", children: /* @__PURE__ */ jsx15("div", { className: "mx-auto max-w-6xl", children }) })
1468
+ ] });
1469
+ }
1470
+ function NotFoundPage() {
1471
+ return /* @__PURE__ */ jsxs14("section", { className: "mx-auto max-w-md py-16 text-center", children: [
1472
+ /* @__PURE__ */ jsx15("p", { className: "text-5xl font-semibold tracking-tight text-brand", children: "404" }),
1473
+ /* @__PURE__ */ jsx15("h1", { className: "mt-4 text-xl font-semibold text-fg", children: shell.notFoundTitle }),
1474
+ /* @__PURE__ */ jsx15("p", { className: "mt-2 text-sm text-muted", children: shell.notFoundText }),
1475
+ /* @__PURE__ */ jsx15(Link3, { to: "/", className: "mt-6 inline-flex h-10 items-center rounded-lg bg-brand px-4 text-sm font-medium text-brand-fg hover:brightness-110", children: shell.backHome })
1476
+ ] });
1477
+ }
1478
+
1479
+ // src/admin/UsersPage.tsx
1480
+ import { Ban, CalendarClock, MailPlus, MoreHorizontal, ShieldCheck as ShieldCheck2, UserCheck, UserPlus, Users as Users2, X as X6 } from "lucide-react";
1481
+ import { useCallback as useCallback3, useEffect as useEffect5, useState as useState12 } from "react";
1482
+ import { Fragment as Fragment4, jsx as jsx16, jsxs as jsxs15 } from "react/jsx-runtime";
1483
+ function RoleCards({ roles, value, onChange }) {
1484
+ return /* @__PURE__ */ jsxs15("fieldset", { className: "grid gap-2 sm:grid-cols-2", children: [
1485
+ /* @__PURE__ */ jsx16("legend", { className: "sr-only", children: a.inviteRoles }),
1486
+ roles.map((r) => {
1487
+ const selected = value.includes(r.key);
1488
+ return /* @__PURE__ */ jsx16(
1489
+ Checkbox,
1490
+ {
1491
+ label: r.label,
1492
+ description: a.permissionCount(r.permissions.length),
1493
+ checked: selected,
1494
+ onChange: (e) => onChange(e.target.checked ? [...value, r.key] : value.filter((k) => k !== r.key)),
1495
+ className: cn("rounded-lg border p-3 transition", selected ? "border-brand bg-brand-soft" : "border-line hover:bg-surface-muted")
1496
+ },
1497
+ r.key
1498
+ );
1499
+ })
1500
+ ] });
1501
+ }
1502
+ function RoleBadges({ roles, keys }) {
1503
+ if (keys.length === 0) return /* @__PURE__ */ jsx16("span", { className: "text-muted", children: a.none });
1504
+ return /* @__PURE__ */ jsx16("div", { className: "flex flex-wrap gap-1.5", children: keys.map((k) => /* @__PURE__ */ jsx16(Badge, { tone: "brand", children: roleLabel(roles, k) }, k)) });
1505
+ }
1506
+ function GroupBadges({ groups }) {
1507
+ if (groups.length === 0) return /* @__PURE__ */ jsx16("span", { className: "text-muted", children: a.none });
1508
+ return /* @__PURE__ */ jsx16("div", { className: "flex flex-wrap gap-1.5", children: groups.map((group) => /* @__PURE__ */ jsx16(Badge, { children: group.name }, group.id)) });
1509
+ }
1510
+ function statusBadge(u) {
1511
+ const [tone, text] = u.status === "deactivated" ? ["neutral", a.statusDeactivated] : u.status === "expired" ? ["danger", a.statusExpired] : u.accessExpiresAt ? ["warn", `${a.accessUntil} ${formatDate(u.accessExpiresAt)}`] : ["ok", a.statusActive];
1512
+ return /* @__PURE__ */ jsx16(Badge, { tone, dot: true, children: text });
1513
+ }
1514
+ function UsersPage() {
1515
+ const me = useMe();
1516
+ const toast = useToast();
1517
+ const confirm = useConfirm();
1518
+ const [users, setUsers] = useState12(null);
1519
+ const [invitations, setInvitations] = useState12([]);
1520
+ const [roles, setRoles] = useState12([]);
1521
+ const [error, setError] = useState12(null);
1522
+ const [inviting, setInviting] = useState12(false);
1523
+ const [inviteEmail, setInviteEmail] = useState12("");
1524
+ const [inviteRoles, setInviteRoles] = useState12(["member"]);
1525
+ const [editing, setEditing] = useState12(null);
1526
+ const [dialogError, setDialogError] = useState12(null);
1527
+ const [busy, setBusy] = useState12(false);
1528
+ const load = useCallback3(async () => {
1529
+ try {
1530
+ const [list, r] = await Promise.all([
1531
+ api("/api/users"),
1532
+ api("/api/roles")
1533
+ ]);
1534
+ setUsers(list.users);
1535
+ setInvitations(list.invitations);
1536
+ setRoles(r.roles);
1537
+ } catch (e) {
1538
+ setError(e.message);
1539
+ }
1540
+ }, []);
1541
+ useEffect5(() => void load(), [load]);
1542
+ async function run(action, done) {
1543
+ try {
1544
+ await action();
1545
+ if (done) toast.success(done);
1546
+ await load();
1547
+ return true;
1548
+ } catch (e) {
1549
+ toast.error(e.message);
1550
+ return false;
1551
+ }
1552
+ }
1553
+ function openInvite() {
1554
+ setInviteEmail("");
1555
+ setInviteRoles(["member"]);
1556
+ setDialogError(null);
1557
+ setInviting(true);
1558
+ }
1559
+ async function sendInvitation() {
1560
+ setBusy(true);
1561
+ setDialogError(null);
1562
+ try {
1563
+ await api("/api/users/invitations", { body: { email: inviteEmail, roles: inviteRoles } });
1564
+ toast.success(`${a.inviteSent} ${inviteEmail}`);
1565
+ setInviting(false);
1566
+ await load();
1567
+ } catch (e) {
1568
+ setDialogError(e.message);
1569
+ }
1570
+ setBusy(false);
1571
+ }
1572
+ async function saveRoles() {
1573
+ if (!editing) return;
1574
+ setBusy(true);
1575
+ setDialogError(null);
1576
+ try {
1577
+ await api(`/api/users/${editing.user.id}/roles`, { method: "PUT", body: { roles: editing.roles } });
1578
+ toast.success(a.rolesUpdated);
1579
+ setEditing(null);
1580
+ await load();
1581
+ } catch (e) {
1582
+ setDialogError(e.message);
1583
+ }
1584
+ setBusy(false);
1585
+ }
1586
+ async function deactivate(u) {
1587
+ if (!await confirm({ title: a.confirmDeactivateTitle, description: a.confirmDeactivateText, confirmLabel: a.deactivate, tone: "danger" })) return;
1588
+ await run(() => api(`/api/users/${u.id}/deactivate`, { method: "POST", body: {} }), a.userDeactivated);
1589
+ }
1590
+ if (!users) return error ? /* @__PURE__ */ jsx16(Alert, { kind: "error", children: error }) : /* @__PURE__ */ jsx16(Spinner, { label: a.loading });
1591
+ const canInvite = can(me, "user:invite");
1592
+ const canUpdate = can(me, "user:update");
1593
+ const canDeactivate = can(me, "user:deactivate");
1594
+ return /* @__PURE__ */ jsxs15(Fragment4, { children: [
1595
+ /* @__PURE__ */ jsx16(
1596
+ PageHeader,
1597
+ {
1598
+ title: a.users,
1599
+ description: a.usersDescription,
1600
+ actions: canInvite && /* @__PURE__ */ jsx16(Button, { variant: "primary", icon: /* @__PURE__ */ jsx16(UserPlus, { className: "size-4", "aria-hidden": true }), onClick: openInvite, children: a.inviteTitle })
1601
+ }
1602
+ ),
1603
+ error && /* @__PURE__ */ jsx16(Alert, { kind: "error", className: "mb-4", children: error }),
1604
+ /* @__PURE__ */ jsxs15("div", { className: "space-y-6", children: [
1605
+ /* @__PURE__ */ jsx16(Card, { children: users.length === 0 ? /* @__PURE__ */ jsx16("div", { className: "p-6", children: /* @__PURE__ */ jsx16(EmptyState, { icon: Users2, title: a.noUsers }) }) : /* @__PURE__ */ jsxs15(Table, { children: [
1606
+ /* @__PURE__ */ jsx16("thead", { children: /* @__PURE__ */ jsxs15("tr", { children: [
1607
+ /* @__PURE__ */ jsx16(TH, { children: a.colName }),
1608
+ /* @__PURE__ */ jsx16(TH, { children: a.colRoles }),
1609
+ /* @__PURE__ */ jsx16(TH, { children: a.colGroups }),
1610
+ /* @__PURE__ */ jsx16(TH, { children: a.colStatus }),
1611
+ /* @__PURE__ */ jsx16(TH, { className: "w-14", children: /* @__PURE__ */ jsx16("span", { className: "sr-only", children: a.colActions }) })
1612
+ ] }) }),
1613
+ /* @__PURE__ */ jsx16("tbody", { children: users.map((u) => {
1614
+ const isMe = u.id === me?.user.id;
1615
+ const showEdit = canUpdate;
1616
+ const showRenew = canUpdate && Boolean(u.accessExpiresAt);
1617
+ const showToggle = canDeactivate && !isMe;
1618
+ return /* @__PURE__ */ jsxs15(TR, { children: [
1619
+ /* @__PURE__ */ jsx16(TD, { children: /* @__PURE__ */ jsxs15("div", { className: "flex items-center gap-3", children: [
1620
+ /* @__PURE__ */ jsx16(Avatar, { name: u.name || u.email }),
1621
+ /* @__PURE__ */ jsxs15("div", { className: "min-w-0", children: [
1622
+ /* @__PURE__ */ jsxs15("p", { className: "flex items-center gap-2 font-medium text-fg", children: [
1623
+ u.name,
1624
+ isMe && /* @__PURE__ */ jsx16(Badge, { tone: "neutral", children: a.you })
1625
+ ] }),
1626
+ /* @__PURE__ */ jsx16("p", { className: "truncate text-muted", children: u.email })
1627
+ ] })
1628
+ ] }) }),
1629
+ /* @__PURE__ */ jsx16(TD, { children: /* @__PURE__ */ jsx16(RoleBadges, { roles, keys: u.roles }) }),
1630
+ /* @__PURE__ */ jsx16(TD, { children: /* @__PURE__ */ jsx16(GroupBadges, { groups: u.groups ?? [] }) }),
1631
+ /* @__PURE__ */ jsx16(TD, { children: statusBadge(u) }),
1632
+ /* @__PURE__ */ jsx16(TD, { className: "text-right", children: (showEdit || showRenew || showToggle) && /* @__PURE__ */ jsx16(
1633
+ Menu,
1634
+ {
1635
+ label: `${a.moreActions}: ${u.name || u.email}`,
1636
+ trigger: /* @__PURE__ */ jsx16("span", { className: "inline-flex size-9 items-center justify-center rounded-lg text-muted transition hover:bg-surface-muted hover:text-fg", children: /* @__PURE__ */ jsx16(MoreHorizontal, { className: "size-5", "aria-hidden": true }) }),
1637
+ children: (close) => /* @__PURE__ */ jsxs15(Fragment4, { children: [
1638
+ showEdit && /* @__PURE__ */ jsx16(
1639
+ MenuItem,
1640
+ {
1641
+ icon: /* @__PURE__ */ jsx16(ShieldCheck2, {}),
1642
+ onClick: () => {
1643
+ close();
1644
+ setDialogError(null);
1645
+ setEditing({ user: u, roles: u.roles });
1646
+ },
1647
+ children: a.editRoles
1648
+ }
1649
+ ),
1650
+ showRenew && /* @__PURE__ */ jsx16(
1651
+ MenuItem,
1652
+ {
1653
+ icon: /* @__PURE__ */ jsx16(CalendarClock, {}),
1654
+ onClick: () => {
1655
+ close();
1656
+ void run(() => api(`/api/users/${u.id}/access`, { method: "PUT", body: { days: 90 } }), a.accessRenewed);
1657
+ },
1658
+ children: a.renew
1659
+ }
1660
+ ),
1661
+ showToggle && (showEdit || showRenew) && /* @__PURE__ */ jsx16(MenuSeparator, {}),
1662
+ showToggle && (u.status === "deactivated" ? /* @__PURE__ */ jsx16(
1663
+ MenuItem,
1664
+ {
1665
+ icon: /* @__PURE__ */ jsx16(UserCheck, {}),
1666
+ onClick: () => {
1667
+ close();
1668
+ void run(() => api(`/api/users/${u.id}/reactivate`, { method: "POST", body: {} }), a.userReactivated);
1669
+ },
1670
+ children: a.reactivate
1671
+ }
1672
+ ) : /* @__PURE__ */ jsx16(
1673
+ MenuItem,
1674
+ {
1675
+ icon: /* @__PURE__ */ jsx16(Ban, {}),
1676
+ tone: "danger",
1677
+ onClick: () => {
1678
+ close();
1679
+ void deactivate(u);
1680
+ },
1681
+ children: a.deactivate
1682
+ }
1683
+ ))
1684
+ ] })
1685
+ }
1686
+ ) })
1687
+ ] }, u.id);
1688
+ }) })
1689
+ ] }) }),
1690
+ invitations.length > 0 && /* @__PURE__ */ jsxs15(Card, { children: [
1691
+ /* @__PURE__ */ jsxs15("div", { className: "flex items-center gap-2 border-b border-line px-4 py-3", children: [
1692
+ /* @__PURE__ */ jsx16(MailPlus, { className: "size-4 text-muted", "aria-hidden": true }),
1693
+ /* @__PURE__ */ jsx16("h2", { className: "font-medium text-fg", children: a.pendingInvitations }),
1694
+ /* @__PURE__ */ jsx16(Badge, { tone: "neutral", children: invitations.length })
1695
+ ] }),
1696
+ /* @__PURE__ */ jsx16("ul", { children: invitations.map((i) => /* @__PURE__ */ jsxs15("li", { className: "flex flex-wrap items-center justify-between gap-3 border-b border-line px-4 py-3 last:border-b-0", children: [
1697
+ /* @__PURE__ */ jsxs15("div", { className: "flex min-w-0 items-center gap-3", children: [
1698
+ /* @__PURE__ */ jsx16(Avatar, { name: i.email }),
1699
+ /* @__PURE__ */ jsxs15("div", { className: "min-w-0", children: [
1700
+ /* @__PURE__ */ jsx16("p", { className: "truncate text-sm font-medium text-fg", children: i.email }),
1701
+ /* @__PURE__ */ jsxs15("p", { className: "text-xs text-muted", children: [
1702
+ a.expires,
1703
+ " ",
1704
+ formatDate(i.expiresAt)
1705
+ ] })
1706
+ ] })
1707
+ ] }),
1708
+ /* @__PURE__ */ jsxs15("div", { className: "flex items-center gap-3", children: [
1709
+ /* @__PURE__ */ jsx16(RoleBadges, { roles, keys: i.roles }),
1710
+ canInvite && /* @__PURE__ */ jsx16(Button, { size: "sm", variant: "ghost", icon: /* @__PURE__ */ jsx16(X6, { className: "size-4", "aria-hidden": true }), onClick: () => void run(() => api(`/api/users/invitations/${i.id}`, { method: "DELETE" }), a.invitationCancelled), children: a.cancel })
1711
+ ] })
1712
+ ] }, i.id)) })
1713
+ ] })
1714
+ ] }),
1715
+ /* @__PURE__ */ jsx16(
1716
+ Dialog,
1717
+ {
1718
+ open: inviting,
1719
+ onClose: () => setInviting(false),
1720
+ title: a.inviteTitle,
1721
+ description: a.inviteDescription,
1722
+ footer: /* @__PURE__ */ jsxs15(Fragment4, { children: [
1723
+ /* @__PURE__ */ jsx16(Button, { onClick: () => setInviting(false), children: a.cancel }),
1724
+ /* @__PURE__ */ jsx16(Button, { variant: "primary", type: "submit", form: "invite-form", loading: busy, children: a.inviteSend })
1725
+ ] }),
1726
+ children: /* @__PURE__ */ jsxs15(
1727
+ "form",
1728
+ {
1729
+ id: "invite-form",
1730
+ className: "space-y-5",
1731
+ onSubmit: (e) => {
1732
+ e.preventDefault();
1733
+ void sendInvitation();
1734
+ },
1735
+ children: [
1736
+ dialogError && /* @__PURE__ */ jsx16(Alert, { kind: "error", children: dialogError }),
1737
+ /* @__PURE__ */ jsx16(Field, { label: a.inviteEmail, children: /* @__PURE__ */ jsx16(Input, { type: "email", required: true, autoFocus: true, placeholder: a.inviteEmailPlaceholder, value: inviteEmail, onChange: (e) => setInviteEmail(e.target.value) }) }),
1738
+ /* @__PURE__ */ jsxs15("div", { children: [
1739
+ /* @__PURE__ */ jsx16("p", { className: "mb-1.5 text-sm font-medium text-fg", children: a.inviteRoles }),
1740
+ /* @__PURE__ */ jsx16(RoleCards, { roles, value: inviteRoles, onChange: setInviteRoles })
1741
+ ] })
1742
+ ]
1743
+ }
1744
+ )
1745
+ }
1746
+ ),
1747
+ /* @__PURE__ */ jsx16(
1748
+ Dialog,
1749
+ {
1750
+ open: editing !== null,
1751
+ onClose: () => setEditing(null),
1752
+ title: a.editRoles,
1753
+ description: editing ? a.editRolesFor(editing.user.name || editing.user.email) : void 0,
1754
+ footer: /* @__PURE__ */ jsxs15(Fragment4, { children: [
1755
+ /* @__PURE__ */ jsx16(Button, { onClick: () => setEditing(null), children: a.cancel }),
1756
+ /* @__PURE__ */ jsx16(Button, { variant: "primary", loading: busy, onClick: () => void saveRoles(), children: a.save })
1757
+ ] }),
1758
+ children: editing && /* @__PURE__ */ jsxs15("div", { className: "space-y-4", children: [
1759
+ dialogError && /* @__PURE__ */ jsx16(Alert, { kind: "error", children: dialogError }),
1760
+ /* @__PURE__ */ jsx16(RoleCards, { roles, value: editing.roles, onChange: (v) => setEditing({ ...editing, roles: v }) })
1761
+ ] })
1762
+ }
1763
+ )
1764
+ ] });
1765
+ }
1766
+
1767
+ // src/admin/GroupsPage.tsx
1768
+ import { Pencil, Plus, Trash2, UserCog, UsersRound as UsersRound2 } from "lucide-react";
1769
+ import { useCallback as useCallback4, useEffect as useEffect6, useState as useState13 } from "react";
1770
+
1771
+ // src/admin/groupTexts.ts
1772
+ var g = {
1773
+ title: "Groups",
1774
+ description: "Organize people into groups such as teams or departments. Groups are for assigning work and sending messages; they do not give anyone extra permissions (roles do).",
1775
+ newGroup: "New group",
1776
+ editGroup: "Edit group",
1777
+ groupName: "Name",
1778
+ groupNamePlaceholder: "Marketing",
1779
+ groupDescription: "Description (optional)",
1780
+ groupDescriptionPlaceholder: "What this group is for",
1781
+ members: "Members",
1782
+ editMembers: "Edit members",
1783
+ membersFor: (name) => `Choose who is in ${name}.`,
1784
+ memberCount: (n) => `${n} ${n === 1 ? "member" : "members"}`,
1785
+ noMembers: "No members yet",
1786
+ moreMembers: (n) => `+${n}`,
1787
+ noGroups: "No groups yet.",
1788
+ noGroupsText: "Create the first group, then add people to it.",
1789
+ created: "Group created",
1790
+ saved: "Group saved",
1791
+ membersSaved: "Members saved",
1792
+ deleted: "Group deleted",
1793
+ confirmDelete: "Delete this group?",
1794
+ confirmDeleteText: "The group is removed. The people in it stay; nothing else changes about them.",
1795
+ needUsers: "To change members you also need to be allowed to view users.",
1796
+ noPeople: "There are no people to add yet."
1797
+ };
1798
+
1799
+ // src/admin/GroupsPage.tsx
1800
+ import { Fragment as Fragment5, jsx as jsx17, jsxs as jsxs16 } from "react/jsx-runtime";
1801
+ var AVATARS_SHOWN = 5;
1802
+ function GroupsPage() {
1803
+ const me = useMe();
1804
+ const toast = useToast();
1805
+ const confirm = useConfirm();
1806
+ const [groups, setGroups] = useState13(null);
1807
+ const [draft, setDraft] = useState13(null);
1808
+ const [membersDraft, setMembersDraft] = useState13(null);
1809
+ const [people, setPeople] = useState13(null);
1810
+ const [error, setError] = useState13(null);
1811
+ const [dialogError, setDialogError] = useState13(null);
1812
+ const [busy, setBusy] = useState13(false);
1813
+ const load = useCallback4(async () => {
1814
+ try {
1815
+ setGroups((await api("/api/groups")).groups);
1816
+ } catch (e) {
1817
+ setError(e.message);
1818
+ }
1819
+ }, []);
1820
+ useEffect6(() => void load(), [load]);
1821
+ async function saveGroup() {
1822
+ if (!draft) return;
1823
+ setBusy(true);
1824
+ setDialogError(null);
1825
+ try {
1826
+ const body = { name: draft.name, description: draft.description };
1827
+ if (draft.id) await api(`/api/groups/${draft.id}`, { method: "PATCH", body });
1828
+ else await api("/api/groups", { body });
1829
+ toast.success(draft.id ? g.saved : g.created);
1830
+ setDraft(null);
1831
+ await load();
1832
+ } catch (e) {
1833
+ setDialogError(e.message);
1834
+ }
1835
+ setBusy(false);
1836
+ }
1837
+ async function openMembers(group) {
1838
+ setDialogError(null);
1839
+ setMembersDraft({ group, ids: group.members.map((m) => m.id) });
1840
+ if (people) return;
1841
+ try {
1842
+ const body = await api("/api/users");
1843
+ setPeople(body.users.map(({ id, name, email }) => ({ id, name: name || email, email })));
1844
+ } catch {
1845
+ setDialogError(g.needUsers);
1846
+ }
1847
+ }
1848
+ async function saveMembers() {
1849
+ if (!membersDraft) return;
1850
+ setBusy(true);
1851
+ setDialogError(null);
1852
+ try {
1853
+ await api(`/api/groups/${membersDraft.group.id}/members`, { method: "PUT", body: { userIds: membersDraft.ids } });
1854
+ toast.success(g.membersSaved);
1855
+ setMembersDraft(null);
1856
+ await load();
1857
+ } catch (e) {
1858
+ setDialogError(e.message);
1859
+ }
1860
+ setBusy(false);
1861
+ }
1862
+ async function remove(group) {
1863
+ if (!await confirm({ title: g.confirmDelete, description: g.confirmDeleteText, confirmLabel: a.delete, tone: "danger" })) return;
1864
+ try {
1865
+ await api(`/api/groups/${group.id}`, { method: "DELETE" });
1866
+ toast.success(g.deleted);
1867
+ await load();
1868
+ } catch (e) {
1869
+ toast.error(e.message);
1870
+ }
1871
+ }
1872
+ if (!groups) return error ? /* @__PURE__ */ jsx17(Alert, { kind: "error", children: error }) : /* @__PURE__ */ jsx17(Spinner, { label: a.loading });
1873
+ const canUpdate = can(me, "group:update");
1874
+ const canDelete = can(me, "group:delete");
1875
+ const listed = people ? [...people] : [];
1876
+ for (const m of membersDraft?.group.members ?? []) if (!listed.some((p) => p.id === m.id)) listed.push({ id: m.id, name: m.name || m.email, email: m.email });
1877
+ return /* @__PURE__ */ jsxs16(Fragment5, { children: [
1878
+ /* @__PURE__ */ jsx17(
1879
+ PageHeader,
1880
+ {
1881
+ title: g.title,
1882
+ description: g.description,
1883
+ actions: can(me, "group:create") && /* @__PURE__ */ jsx17(Button, { variant: "primary", icon: /* @__PURE__ */ jsx17(Plus, { className: "size-4", "aria-hidden": true }), onClick: () => {
1884
+ setDialogError(null);
1885
+ setDraft({ id: null, name: "", description: "" });
1886
+ }, children: g.newGroup })
1887
+ }
1888
+ ),
1889
+ error && /* @__PURE__ */ jsx17(Alert, { kind: "error", className: "mb-4", children: error }),
1890
+ groups.length === 0 ? /* @__PURE__ */ jsx17(EmptyState, { icon: UsersRound2, title: g.noGroups, description: g.noGroupsText }) : /* @__PURE__ */ jsx17("div", { className: "grid gap-4 lg:grid-cols-2", children: groups.map((group) => /* @__PURE__ */ jsxs16(Card, { className: "flex flex-col p-5", children: [
1891
+ /* @__PURE__ */ jsx17("div", { className: "flex items-start justify-between gap-3", children: /* @__PURE__ */ jsxs16("div", { className: "flex min-w-0 items-center gap-3", children: [
1892
+ /* @__PURE__ */ jsx17("span", { className: "inline-flex size-10 shrink-0 items-center justify-center rounded-xl bg-brand-soft text-brand", children: /* @__PURE__ */ jsx17(UsersRound2, { className: "size-5", "aria-hidden": true }) }),
1893
+ /* @__PURE__ */ jsxs16("div", { className: "min-w-0", children: [
1894
+ /* @__PURE__ */ jsx17("h2", { className: "truncate font-semibold text-fg", children: group.name }),
1895
+ /* @__PURE__ */ jsx17("p", { className: "text-xs text-muted", children: g.memberCount(group.members.length) })
1896
+ ] })
1897
+ ] }) }),
1898
+ group.description && /* @__PURE__ */ jsx17("p", { className: "mt-3 text-sm text-muted", children: group.description }),
1899
+ /* @__PURE__ */ jsx17("div", { className: "mt-4 flex flex-1 items-center gap-1.5", children: group.members.length === 0 ? /* @__PURE__ */ jsx17("span", { className: "text-sm text-muted", children: g.noMembers }) : /* @__PURE__ */ jsxs16(Fragment5, { children: [
1900
+ group.members.slice(0, AVATARS_SHOWN).map((m) => /* @__PURE__ */ jsx17("span", { title: `${m.name || m.email} (${m.email})`, children: /* @__PURE__ */ jsx17(Avatar, { name: m.name || m.email, size: "sm" }) }, m.id)),
1901
+ group.members.length > AVATARS_SHOWN && /* @__PURE__ */ jsx17("span", { title: group.members.slice(AVATARS_SHOWN).map((m) => m.name || m.email).join(", "), children: /* @__PURE__ */ jsx17(Badge, { tone: "brand", children: g.moreMembers(group.members.length - AVATARS_SHOWN) }) })
1902
+ ] }) }),
1903
+ (canUpdate || canDelete) && /* @__PURE__ */ jsxs16("div", { className: "mt-4 flex flex-wrap gap-2 border-t border-line pt-4", children: [
1904
+ canUpdate && /* @__PURE__ */ jsx17(Button, { size: "sm", icon: /* @__PURE__ */ jsx17(UserCog, { className: "size-4", "aria-hidden": true }), onClick: () => void openMembers(group), children: g.editMembers }),
1905
+ canUpdate && /* @__PURE__ */ jsx17(Button, { size: "sm", icon: /* @__PURE__ */ jsx17(Pencil, { className: "size-4", "aria-hidden": true }), onClick: () => {
1906
+ setDialogError(null);
1907
+ setDraft({ id: group.id, name: group.name, description: group.description });
1908
+ }, children: a.edit }),
1909
+ canDelete && /* @__PURE__ */ jsx17(Button, { size: "sm", variant: "danger", icon: /* @__PURE__ */ jsx17(Trash2, { className: "size-4", "aria-hidden": true }), onClick: () => void remove(group), children: a.delete })
1910
+ ] })
1911
+ ] }, group.id)) }),
1912
+ /* @__PURE__ */ jsx17(
1913
+ Dialog,
1914
+ {
1915
+ open: draft !== null,
1916
+ onClose: () => setDraft(null),
1917
+ title: draft?.id ? g.editGroup : g.newGroup,
1918
+ footer: /* @__PURE__ */ jsxs16(Fragment5, { children: [
1919
+ /* @__PURE__ */ jsx17(Button, { onClick: () => setDraft(null), children: a.cancel }),
1920
+ /* @__PURE__ */ jsx17(Button, { variant: "primary", type: "submit", form: "group-form", loading: busy, children: a.save })
1921
+ ] }),
1922
+ children: draft && /* @__PURE__ */ jsxs16(
1923
+ "form",
1924
+ {
1925
+ id: "group-form",
1926
+ className: "space-y-4",
1927
+ onSubmit: (e) => {
1928
+ e.preventDefault();
1929
+ void saveGroup();
1930
+ },
1931
+ children: [
1932
+ dialogError && /* @__PURE__ */ jsx17(Alert, { kind: "error", children: dialogError }),
1933
+ /* @__PURE__ */ jsx17(Field, { label: g.groupName, children: /* @__PURE__ */ jsx17(Input, { required: true, autoFocus: true, maxLength: 80, placeholder: g.groupNamePlaceholder, value: draft.name, onChange: (e) => setDraft({ ...draft, name: e.target.value }) }) }),
1934
+ /* @__PURE__ */ jsx17(Field, { label: g.groupDescription, children: /* @__PURE__ */ jsx17(Textarea, { rows: 3, maxLength: 300, placeholder: g.groupDescriptionPlaceholder, value: draft.description, onChange: (e) => setDraft({ ...draft, description: e.target.value }) }) })
1935
+ ]
1936
+ }
1937
+ )
1938
+ }
1939
+ ),
1940
+ /* @__PURE__ */ jsx17(
1941
+ Dialog,
1942
+ {
1943
+ open: membersDraft !== null,
1944
+ onClose: () => setMembersDraft(null),
1945
+ title: membersDraft ? `${g.members}: ${membersDraft.group.name}` : g.members,
1946
+ description: membersDraft ? g.membersFor(membersDraft.group.name) : void 0,
1947
+ size: "lg",
1948
+ footer: /* @__PURE__ */ jsxs16(Fragment5, { children: [
1949
+ /* @__PURE__ */ jsx17(Button, { onClick: () => setMembersDraft(null), children: a.cancel }),
1950
+ /* @__PURE__ */ jsx17(Button, { variant: "primary", loading: busy, disabled: people === null, onClick: () => void saveMembers(), children: a.save })
1951
+ ] }),
1952
+ children: membersDraft && /* @__PURE__ */ jsxs16("div", { className: "space-y-4", children: [
1953
+ dialogError && /* @__PURE__ */ jsx17(Alert, { kind: "error", children: dialogError }),
1954
+ people === null && !dialogError && /* @__PURE__ */ jsx17(Spinner, { label: a.loading }),
1955
+ people !== null && /* @__PURE__ */ jsx17(PeoplePicker, { people: listed, value: membersDraft.ids, onChange: (ids) => setMembersDraft({ ...membersDraft, ids }), emptyText: g.noPeople })
1956
+ ] })
1957
+ }
1958
+ )
1959
+ ] });
1960
+ }
1961
+
1962
+ // src/admin/RolesPage.tsx
1963
+ import { Pencil as Pencil2, Plus as Plus2, ShieldCheck as ShieldCheck3, Trash2 as Trash22 } from "lucide-react";
1964
+ import { useCallback as useCallback5, useEffect as useEffect7, useState as useState14 } from "react";
1965
+ import { Fragment as Fragment6, jsx as jsx18, jsxs as jsxs17 } from "react/jsx-runtime";
1966
+ var CHIP_LIMIT = 8;
1967
+ function resourceTitle(permission) {
1968
+ const resource = permission.split(":")[0] ?? permission;
1969
+ const text = resource.replace(/[-_]/g, " ");
1970
+ return text.charAt(0).toUpperCase() + text.slice(1);
1971
+ }
1972
+ function groupByResource(permissions) {
1973
+ const groups = /* @__PURE__ */ new Map();
1974
+ for (const p of permissions) {
1975
+ const resource = p.name.split(":")[0] ?? p.name;
1976
+ groups.set(resource, [...groups.get(resource) ?? [], p]);
1977
+ }
1978
+ return [...groups.entries()];
1979
+ }
1980
+ function RolesPage() {
1981
+ const me = useMe();
1982
+ const toast = useToast();
1983
+ const confirm = useConfirm();
1984
+ const [roles, setRoles] = useState14(null);
1985
+ const [permissions, setPermissions] = useState14([]);
1986
+ const [draft, setDraft] = useState14(null);
1987
+ const [error, setError] = useState14(null);
1988
+ const [dialogError, setDialogError] = useState14(null);
1989
+ const [busy, setBusy] = useState14(false);
1990
+ const load = useCallback5(async () => {
1991
+ try {
1992
+ const body = await api("/api/roles");
1993
+ setRoles(body.roles);
1994
+ setPermissions(body.permissions);
1995
+ } catch (e) {
1996
+ setError(e.message);
1997
+ }
1998
+ }, []);
1999
+ useEffect7(() => void load(), [load]);
2000
+ function openDraft(next) {
2001
+ setDialogError(null);
2002
+ setDraft(next);
2003
+ }
2004
+ async function save() {
2005
+ if (!draft) return;
2006
+ setBusy(true);
2007
+ setDialogError(null);
2008
+ try {
2009
+ const body = { label: draft.label, permissions: draft.permissions };
2010
+ if (draft.key) await api(`/api/roles/${draft.key}`, { method: "PUT", body });
2011
+ else await api("/api/roles", { body });
2012
+ toast.success(draft.key ? a.roleSaved : a.roleCreated);
2013
+ setDraft(null);
2014
+ await load();
2015
+ } catch (e) {
2016
+ setDialogError(e.message);
2017
+ }
2018
+ setBusy(false);
2019
+ }
2020
+ async function remove(role) {
2021
+ if (!await confirm({ title: a.confirmDeleteRole, description: a.confirmDeleteRoleText, confirmLabel: a.delete, tone: "danger" })) return;
2022
+ try {
2023
+ await api(`/api/roles/${role.key}`, { method: "DELETE" });
2024
+ toast.success(a.roleDeleted);
2025
+ await load();
2026
+ } catch (e) {
2027
+ toast.error(e.message);
2028
+ }
2029
+ }
2030
+ if (!roles) return error ? /* @__PURE__ */ jsx18(Alert, { kind: "error", children: error }) : /* @__PURE__ */ jsx18(Spinner, { label: a.loading });
2031
+ const label = (name) => permissions.find((p) => p.name === name)?.label ?? name;
2032
+ const groups = groupByResource(permissions);
2033
+ const hasAdminOnly = permissions.some((p) => p.adminOnly);
2034
+ function toggle(names, on) {
2035
+ if (!draft) return;
2036
+ const rest = draft.permissions.filter((x) => !names.includes(x));
2037
+ setDraft({ ...draft, permissions: on ? [...rest, ...names] : rest });
2038
+ }
2039
+ return /* @__PURE__ */ jsxs17(Fragment6, { children: [
2040
+ /* @__PURE__ */ jsx18(
2041
+ PageHeader,
2042
+ {
2043
+ title: a.roles,
2044
+ description: a.rolesDescription,
2045
+ actions: can(me, "role:create") && /* @__PURE__ */ jsx18(Button, { variant: "primary", icon: /* @__PURE__ */ jsx18(Plus2, { className: "size-4", "aria-hidden": true }), onClick: () => openDraft({ key: null, label: "", permissions: [] }), children: a.newRole })
2046
+ }
2047
+ ),
2048
+ error && /* @__PURE__ */ jsx18(Alert, { kind: "error", className: "mb-4", children: error }),
2049
+ /* @__PURE__ */ jsx18("div", { className: "grid gap-4 lg:grid-cols-2", children: roles.map((r) => {
2050
+ const shown = r.permissions.slice(0, CHIP_LIMIT);
2051
+ const rest = r.permissions.slice(CHIP_LIMIT);
2052
+ return /* @__PURE__ */ jsxs17(Card, { className: "flex flex-col p-5", children: [
2053
+ /* @__PURE__ */ jsxs17("div", { className: "flex items-start justify-between gap-3", children: [
2054
+ /* @__PURE__ */ jsxs17("div", { className: "flex min-w-0 items-center gap-3", children: [
2055
+ /* @__PURE__ */ jsx18("span", { className: "inline-flex size-10 shrink-0 items-center justify-center rounded-xl bg-brand-soft text-brand", children: /* @__PURE__ */ jsx18(ShieldCheck3, { className: "size-5", "aria-hidden": true }) }),
2056
+ /* @__PURE__ */ jsxs17("div", { className: "min-w-0", children: [
2057
+ /* @__PURE__ */ jsx18("h2", { className: "truncate font-semibold text-fg", children: r.label }),
2058
+ /* @__PURE__ */ jsx18("p", { className: "text-xs text-muted", children: a.permissionCount(r.permissions.length) })
2059
+ ] })
2060
+ ] }),
2061
+ /* @__PURE__ */ jsx18(Badge, { tone: r.builtIn ? "neutral" : "brand", children: r.builtIn ? a.builtIn : a.custom })
2062
+ ] }),
2063
+ /* @__PURE__ */ jsx18("div", { className: "mt-4 flex flex-1 flex-wrap content-start gap-1.5", children: r.permissions.length === 0 ? /* @__PURE__ */ jsx18("span", { className: "text-sm text-muted", children: a.none }) : /* @__PURE__ */ jsxs17(Fragment6, { children: [
2064
+ shown.map((p) => /* @__PURE__ */ jsx18("span", { title: p, children: /* @__PURE__ */ jsx18(Badge, { children: label(p) }) }, p)),
2065
+ rest.length > 0 && /* @__PURE__ */ jsx18("span", { title: rest.map(label).join(", "), children: /* @__PURE__ */ jsx18(Badge, { tone: "brand", children: a.morePermissions(rest.length) }) })
2066
+ ] }) }),
2067
+ !r.builtIn && (can(me, "role:update") || can(me, "role:delete")) && /* @__PURE__ */ jsxs17("div", { className: "mt-4 flex gap-2 border-t border-line pt-4", children: [
2068
+ can(me, "role:update") && /* @__PURE__ */ jsx18(Button, { size: "sm", icon: /* @__PURE__ */ jsx18(Pencil2, { className: "size-4", "aria-hidden": true }), onClick: () => openDraft({ key: r.key, label: r.label, permissions: r.permissions }), children: a.edit }),
2069
+ can(me, "role:delete") && /* @__PURE__ */ jsx18(Button, { size: "sm", variant: "danger", icon: /* @__PURE__ */ jsx18(Trash22, { className: "size-4", "aria-hidden": true }), onClick: () => void remove(r), children: a.delete })
2070
+ ] })
2071
+ ] }, r.key);
2072
+ }) }),
2073
+ /* @__PURE__ */ jsx18(
2074
+ Dialog,
2075
+ {
2076
+ open: draft !== null,
2077
+ onClose: () => setDraft(null),
2078
+ title: draft?.key ? a.editRole : a.newRole,
2079
+ size: "lg",
2080
+ footer: /* @__PURE__ */ jsxs17(Fragment6, { children: [
2081
+ /* @__PURE__ */ jsx18(Button, { onClick: () => setDraft(null), children: a.cancel }),
2082
+ /* @__PURE__ */ jsx18(Button, { variant: "primary", type: "submit", form: "role-form", loading: busy, children: a.save })
2083
+ ] }),
2084
+ children: draft && /* @__PURE__ */ jsxs17(
2085
+ "form",
2086
+ {
2087
+ id: "role-form",
2088
+ className: "space-y-5",
2089
+ onSubmit: (e) => {
2090
+ e.preventDefault();
2091
+ void save();
2092
+ },
2093
+ children: [
2094
+ dialogError && /* @__PURE__ */ jsx18(Alert, { kind: "error", children: dialogError }),
2095
+ /* @__PURE__ */ jsx18(Field, { label: a.roleName, children: /* @__PURE__ */ jsx18(Input, { required: true, autoFocus: true, placeholder: a.roleNamePlaceholder, value: draft.label, onChange: (e) => setDraft({ ...draft, label: e.target.value }) }) }),
2096
+ /* @__PURE__ */ jsxs17("div", { children: [
2097
+ /* @__PURE__ */ jsx18("p", { className: "mb-2 text-sm font-medium text-fg", children: a.rolePermissions }),
2098
+ hasAdminOnly && /* @__PURE__ */ jsx18("p", { className: "mb-3 text-xs text-muted", children: a.adminOnlyNote }),
2099
+ groups.length === 0 && /* @__PURE__ */ jsx18("p", { className: "text-sm text-muted", children: a.noPermissionsAvailable }),
2100
+ /* @__PURE__ */ jsx18("div", { className: "space-y-3", children: groups.map(([resource, items]) => {
2101
+ const names = items.map((p) => p.name);
2102
+ const allOn = names.every((n) => draft.permissions.includes(n));
2103
+ return /* @__PURE__ */ jsxs17("div", { role: "group", "aria-label": resourceTitle(resource), className: "rounded-lg border border-line", children: [
2104
+ /* @__PURE__ */ jsxs17("div", { className: "flex items-center justify-between rounded-t-lg bg-surface-muted/60 px-4 py-2", children: [
2105
+ /* @__PURE__ */ jsx18("span", { className: "text-xs font-semibold uppercase tracking-wide text-muted", children: resourceTitle(resource) }),
2106
+ /* @__PURE__ */ jsx18(Button, { size: "sm", variant: "ghost", onClick: () => toggle(names, !allOn), children: allOn ? a.clearAll : a.selectAll })
2107
+ ] }),
2108
+ /* @__PURE__ */ jsx18("div", { className: "grid gap-3 p-4 sm:grid-cols-2", children: items.map((p) => /* @__PURE__ */ jsx18(
2109
+ Checkbox,
2110
+ {
2111
+ label: p.label,
2112
+ description: /* @__PURE__ */ jsx18("span", { className: "font-mono text-xs", children: p.name }),
2113
+ checked: draft.permissions.includes(p.name),
2114
+ onChange: (e) => toggle([p.name], e.target.checked)
2115
+ },
2116
+ p.name
2117
+ )) })
2118
+ ] }, resource);
2119
+ }) })
2120
+ ] })
2121
+ ]
2122
+ }
2123
+ )
2124
+ }
2125
+ )
2126
+ ] });
2127
+ }
2128
+
2129
+ // src/admin/ApiKeysPage.tsx
2130
+ import { Check as Check3, Copy, KeyRound as KeyRound2, Plus as Plus3, Trash2 as Trash23 } from "lucide-react";
2131
+ import { useCallback as useCallback6, useEffect as useEffect8, useState as useState15 } from "react";
2132
+ import { Fragment as Fragment7, jsx as jsx19, jsxs as jsxs18 } from "react/jsx-runtime";
2133
+ var presets = [
2134
+ ["read", a.keyPresetRead, a.keyPresetReadHint],
2135
+ ["read_create", a.keyPresetReadCreate, a.keyPresetReadCreateHint],
2136
+ [
2137
+ "read_create_update",
2138
+ a.keyPresetReadCreateUpdate,
2139
+ a.keyPresetReadCreateUpdateHint
2140
+ ],
2141
+ ["custom", a.keyPresetCustom, a.keyPresetCustomHint]
2142
+ ];
2143
+ var SCOPE_LIMIT = 3;
2144
+ function KeyTable({
2145
+ keys,
2146
+ showOwner,
2147
+ onRevoke
2148
+ }) {
2149
+ if (keys.length === 0) {
2150
+ return /* @__PURE__ */ jsx19("div", { className: "p-6", children: /* @__PURE__ */ jsx19(EmptyState, { icon: KeyRound2, title: a.noKeys }) });
2151
+ }
2152
+ return /* @__PURE__ */ jsxs18(Table, { children: [
2153
+ /* @__PURE__ */ jsx19("thead", { children: /* @__PURE__ */ jsxs18("tr", { children: [
2154
+ /* @__PURE__ */ jsx19(TH, { children: a.colKeyName }),
2155
+ showOwner && /* @__PURE__ */ jsx19(TH, { children: a.colKeyOwner }),
2156
+ /* @__PURE__ */ jsx19(TH, { children: a.colKeyScopes }),
2157
+ /* @__PURE__ */ jsx19(TH, { children: a.colKeyExpires }),
2158
+ /* @__PURE__ */ jsx19(TH, { children: a.colKeyLastUsed }),
2159
+ /* @__PURE__ */ jsx19(TH, { className: "w-px", children: /* @__PURE__ */ jsx19("span", { className: "sr-only", children: a.revoke }) })
2160
+ ] }) }),
2161
+ /* @__PURE__ */ jsx19("tbody", { children: keys.map((k) => /* @__PURE__ */ jsxs18(TR, { children: [
2162
+ /* @__PURE__ */ jsxs18(TD, { children: [
2163
+ /* @__PURE__ */ jsx19("p", { className: "font-medium text-fg", children: k.name }),
2164
+ /* @__PURE__ */ jsxs18("p", { className: "font-mono text-xs text-muted", children: [
2165
+ k.start,
2166
+ "\u2026"
2167
+ ] })
2168
+ ] }),
2169
+ showOwner && /* @__PURE__ */ jsx19(TD, { className: "text-muted", children: k.ownerEmail }),
2170
+ /* @__PURE__ */ jsx19(TD, { children: /* @__PURE__ */ jsxs18("div", { className: "flex flex-wrap gap-1.5", children: [
2171
+ k.scopes.slice(0, SCOPE_LIMIT).map((s) => /* @__PURE__ */ jsx19(Badge, { className: "font-mono", children: s }, s)),
2172
+ k.scopes.length > SCOPE_LIMIT && /* @__PURE__ */ jsx19("span", { title: k.scopes.slice(SCOPE_LIMIT).join(", "), children: /* @__PURE__ */ jsx19(Badge, { tone: "brand", children: a.morePermissions(k.scopes.length - SCOPE_LIMIT) }) })
2173
+ ] }) }),
2174
+ /* @__PURE__ */ jsx19(TD, { className: "whitespace-nowrap", children: k.expiresAt ? formatDate(k.expiresAt) : /* @__PURE__ */ jsx19("span", { className: "text-muted", children: a.never }) }),
2175
+ /* @__PURE__ */ jsx19(TD, { className: "whitespace-nowrap", children: k.lastUsedAt ? /* @__PURE__ */ jsx19("span", { title: formatDateTime(k.lastUsedAt), children: timeAgo(k.lastUsedAt) }) : /* @__PURE__ */ jsx19("span", { className: "text-muted", children: a.never }) }),
2176
+ /* @__PURE__ */ jsx19(TD, { className: "text-right", children: /* @__PURE__ */ jsx19(
2177
+ Button,
2178
+ {
2179
+ size: "sm",
2180
+ variant: "danger",
2181
+ icon: /* @__PURE__ */ jsx19(Trash23, { className: "size-4", "aria-hidden": true }),
2182
+ onClick: () => onRevoke(k.id),
2183
+ children: a.revoke
2184
+ }
2185
+ ) })
2186
+ ] }, k.id)) })
2187
+ ] });
2188
+ }
2189
+ function ApiKeysPage() {
2190
+ const me = useMe();
2191
+ const toast = useToast();
2192
+ const confirm = useConfirm();
2193
+ const [mine, setMine] = useState15(null);
2194
+ const [all, setAll] = useState15(null);
2195
+ const [permissions, setPermissions] = useState15([]);
2196
+ const [error, setError] = useState15(null);
2197
+ const [dialogError, setDialogError] = useState15(null);
2198
+ const [creating, setCreating] = useState15(false);
2199
+ const [busy, setBusy] = useState15(false);
2200
+ const [created, setCreated] = useState15(null);
2201
+ const [copied, setCopied] = useState15(false);
2202
+ const [name, setName] = useState15("");
2203
+ const [preset, setPreset] = useState15("read");
2204
+ const [custom, setCustom] = useState15([]);
2205
+ const [days, setDays] = useState15(90);
2206
+ const load = useCallback6(async () => {
2207
+ try {
2208
+ setMine((await api("/api/api-keys")).keys);
2209
+ if (me && can(me, "apikey:manage"))
2210
+ setAll((await api("/api/api-keys/all")).keys);
2211
+ if (me && can(me, "role:read"))
2212
+ setPermissions(
2213
+ (await api("/api/roles")).permissions
2214
+ );
2215
+ } catch (e) {
2216
+ setError(e.message);
2217
+ }
2218
+ }, [me]);
2219
+ useEffect8(() => void load(), [load]);
2220
+ function openCreate() {
2221
+ setName("");
2222
+ setPreset("read");
2223
+ setCustom([]);
2224
+ setDays(90);
2225
+ setDialogError(null);
2226
+ setCreating(true);
2227
+ }
2228
+ async function create() {
2229
+ setBusy(true);
2230
+ setDialogError(null);
2231
+ try {
2232
+ const res = await api("/api/api-keys", {
2233
+ body: { name, preset, scopes: custom, expiresInDays: days }
2234
+ });
2235
+ setCreating(false);
2236
+ setCopied(false);
2237
+ setCreated(res.key);
2238
+ await load();
2239
+ } catch (e) {
2240
+ setDialogError(e.message);
2241
+ }
2242
+ setBusy(false);
2243
+ }
2244
+ async function copyKey() {
2245
+ if (!created) return;
2246
+ try {
2247
+ await navigator.clipboard.writeText(created);
2248
+ setCopied(true);
2249
+ toast.success(a.copied);
2250
+ } catch {
2251
+ toast.error(a.genericError);
2252
+ }
2253
+ }
2254
+ async function revoke(id) {
2255
+ if (!await confirm({
2256
+ title: a.confirmRevoke,
2257
+ confirmLabel: a.revoke,
2258
+ tone: "danger"
2259
+ }))
2260
+ return;
2261
+ try {
2262
+ await api(`/api/api-keys/${id}`, { method: "DELETE" });
2263
+ toast.success(a.keyRevoked);
2264
+ await load();
2265
+ } catch (e) {
2266
+ toast.error(e.message);
2267
+ }
2268
+ }
2269
+ const usable = permissions.filter(
2270
+ (p) => !p.adminOnly && me?.permissions.includes(p.name)
2271
+ );
2272
+ if (!mine)
2273
+ return error ? /* @__PURE__ */ jsx19(Alert, { kind: "error", children: error }) : /* @__PURE__ */ jsx19(Spinner, { label: a.loading });
2274
+ return /* @__PURE__ */ jsxs18(Fragment7, { children: [
2275
+ /* @__PURE__ */ jsx19(
2276
+ PageHeader,
2277
+ {
2278
+ title: a.apiKeys,
2279
+ description: a.keysIntro,
2280
+ actions: /* @__PURE__ */ jsx19(
2281
+ Button,
2282
+ {
2283
+ variant: "primary",
2284
+ icon: /* @__PURE__ */ jsx19(Plus3, { className: "size-4", "aria-hidden": true }),
2285
+ onClick: openCreate,
2286
+ children: a.newKey
2287
+ }
2288
+ )
2289
+ }
2290
+ ),
2291
+ error && /* @__PURE__ */ jsx19(Alert, { kind: "error", className: "mb-4", children: error }),
2292
+ /* @__PURE__ */ jsxs18("div", { className: "space-y-6", children: [
2293
+ /* @__PURE__ */ jsxs18(Card, { children: [
2294
+ /* @__PURE__ */ jsxs18("div", { className: "flex items-center gap-2 border-b border-line px-4 py-3", children: [
2295
+ /* @__PURE__ */ jsx19("h2", { className: "font-medium text-fg", children: a.yourKeys }),
2296
+ /* @__PURE__ */ jsx19(Badge, { tone: "neutral", children: mine.length })
2297
+ ] }),
2298
+ /* @__PURE__ */ jsx19(KeyTable, { keys: mine, onRevoke: (id) => void revoke(id) })
2299
+ ] }),
2300
+ all && /* @__PURE__ */ jsxs18(Card, { children: [
2301
+ /* @__PURE__ */ jsxs18("div", { className: "flex items-center gap-2 border-b border-line px-4 py-3", children: [
2302
+ /* @__PURE__ */ jsx19("h2", { className: "font-medium text-fg", children: a.allKeys }),
2303
+ /* @__PURE__ */ jsx19(Badge, { tone: "neutral", children: all.length })
2304
+ ] }),
2305
+ /* @__PURE__ */ jsx19(KeyTable, { keys: all, showOwner: true, onRevoke: (id) => void revoke(id) })
2306
+ ] })
2307
+ ] }),
2308
+ /* @__PURE__ */ jsx19(
2309
+ Dialog,
2310
+ {
2311
+ open: creating,
2312
+ onClose: () => setCreating(false),
2313
+ title: a.newKey,
2314
+ description: a.newKeyDescription,
2315
+ footer: /* @__PURE__ */ jsxs18(Fragment7, { children: [
2316
+ /* @__PURE__ */ jsx19(Button, { onClick: () => setCreating(false), children: a.cancel }),
2317
+ /* @__PURE__ */ jsx19(
2318
+ Button,
2319
+ {
2320
+ variant: "primary",
2321
+ type: "submit",
2322
+ form: "key-form",
2323
+ loading: busy,
2324
+ children: a.keyCreate
2325
+ }
2326
+ )
2327
+ ] }),
2328
+ children: /* @__PURE__ */ jsxs18(
2329
+ "form",
2330
+ {
2331
+ id: "key-form",
2332
+ className: "space-y-5",
2333
+ onSubmit: (e) => {
2334
+ e.preventDefault();
2335
+ void create();
2336
+ },
2337
+ children: [
2338
+ dialogError && /* @__PURE__ */ jsx19(Alert, { kind: "error", children: dialogError }),
2339
+ /* @__PURE__ */ jsx19(Field, { label: a.keyName, children: /* @__PURE__ */ jsx19(
2340
+ Input,
2341
+ {
2342
+ required: true,
2343
+ autoFocus: true,
2344
+ placeholder: a.keyNamePlaceholder,
2345
+ value: name,
2346
+ onChange: (e) => setName(e.target.value)
2347
+ }
2348
+ ) }),
2349
+ /* @__PURE__ */ jsxs18("fieldset", { children: [
2350
+ /* @__PURE__ */ jsx19("legend", { className: "mb-1.5 text-sm font-medium text-fg", children: a.keyAccess }),
2351
+ /* @__PURE__ */ jsx19("div", { className: "grid gap-2", children: presets.map(([value, label, hint]) => /* @__PURE__ */ jsxs18(
2352
+ "label",
2353
+ {
2354
+ className: "flex cursor-pointer items-start gap-3 rounded-lg border border-line p-3 text-sm transition hover:bg-surface-muted has-checked:border-brand has-checked:bg-brand-soft has-focus-visible:ring-2 has-focus-visible:ring-brand/40",
2355
+ children: [
2356
+ /* @__PURE__ */ jsx19(
2357
+ "input",
2358
+ {
2359
+ type: "radio",
2360
+ name: "preset",
2361
+ value,
2362
+ checked: preset === value,
2363
+ onChange: () => setPreset(value),
2364
+ className: "mt-1"
2365
+ }
2366
+ ),
2367
+ /* @__PURE__ */ jsxs18("span", { children: [
2368
+ /* @__PURE__ */ jsx19("span", { className: "block font-medium text-fg", children: label }),
2369
+ /* @__PURE__ */ jsx19("span", { className: "block text-muted", children: hint })
2370
+ ] })
2371
+ ]
2372
+ },
2373
+ value
2374
+ )) })
2375
+ ] }),
2376
+ preset === "custom" && /* @__PURE__ */ jsxs18("div", { children: [
2377
+ /* @__PURE__ */ jsx19("p", { className: "mb-2 text-xs text-muted", children: a.adminOnlyNote }),
2378
+ usable.length === 0 && /* @__PURE__ */ jsx19("p", { className: "text-sm text-muted", children: a.noUsablePermissions }),
2379
+ /* @__PURE__ */ jsx19("div", { className: "grid gap-3 rounded-lg border border-line p-4 sm:grid-cols-2", children: usable.map((p) => /* @__PURE__ */ jsx19(
2380
+ Checkbox,
2381
+ {
2382
+ label: p.label,
2383
+ description: /* @__PURE__ */ jsx19("span", { className: "font-mono text-xs", children: p.name }),
2384
+ checked: custom.includes(p.name),
2385
+ onChange: (e) => setCustom(
2386
+ e.target.checked ? [...custom, p.name] : custom.filter((x) => x !== p.name)
2387
+ )
2388
+ },
2389
+ p.name
2390
+ )) })
2391
+ ] }),
2392
+ /* @__PURE__ */ jsx19(Field, { label: a.keyExpiry, hint: a.keyExpiryHint, children: /* @__PURE__ */ jsx19(
2393
+ Input,
2394
+ {
2395
+ type: "number",
2396
+ min: 1,
2397
+ max: 365,
2398
+ value: days,
2399
+ onChange: (e) => setDays(Number(e.target.value)),
2400
+ className: "max-w-32"
2401
+ }
2402
+ ) })
2403
+ ]
2404
+ }
2405
+ )
2406
+ }
2407
+ ),
2408
+ /* @__PURE__ */ jsx19(
2409
+ Dialog,
2410
+ {
2411
+ open: created !== null,
2412
+ onClose: () => setCreated(null),
2413
+ title: a.keyCreatedTitle,
2414
+ footer: /* @__PURE__ */ jsx19(Button, { variant: "primary", onClick: () => setCreated(null), children: a.done }),
2415
+ children: /* @__PURE__ */ jsxs18("div", { className: "space-y-4", children: [
2416
+ /* @__PURE__ */ jsx19(Alert, { kind: "warning", children: a.keyShownOnce }),
2417
+ /* @__PURE__ */ jsxs18("div", { className: "flex items-center gap-2 rounded-lg border border-line-strong bg-surface-muted p-3", children: [
2418
+ /* @__PURE__ */ jsx19("code", { className: "min-w-0 flex-1 break-all font-mono text-sm text-fg", children: created }),
2419
+ /* @__PURE__ */ jsx19(
2420
+ Button,
2421
+ {
2422
+ size: "sm",
2423
+ variant: copied ? "secondary" : "primary",
2424
+ icon: copied ? /* @__PURE__ */ jsx19(Check3, { className: "size-4", "aria-hidden": true }) : /* @__PURE__ */ jsx19(Copy, { className: "size-4", "aria-hidden": true }),
2425
+ onClick: () => void copyKey(),
2426
+ children: copied ? a.copied : a.copyKey
2427
+ }
2428
+ )
2429
+ ] })
2430
+ ] })
2431
+ }
2432
+ )
2433
+ ] });
2434
+ }
2435
+
2436
+ // src/admin/AuditPage.tsx
2437
+ import { ScrollText as ScrollText2, Search as Search2 } from "lucide-react";
2438
+ import { useEffect as useEffect9, useState as useState16 } from "react";
2439
+ import { Fragment as Fragment8, jsx as jsx20, jsxs as jsxs19 } from "react/jsx-runtime";
2440
+ var PAGE = 100;
2441
+ function summarize(details) {
2442
+ if (!details) return "";
2443
+ return Object.entries(details).map(([key, value]) => `${key}: ${typeof value === "object" && value !== null ? JSON.stringify(value) : String(value)}`).join(" \xB7 ");
2444
+ }
2445
+ var isDestructive = (action) => /delete|revoke|deactivat|remove|cancel/i.test(action);
2446
+ function AuditPage() {
2447
+ const [entries, setEntries] = useState16(null);
2448
+ const [more, setMore] = useState16(false);
2449
+ const [loadingMore, setLoadingMore] = useState16(false);
2450
+ const [error, setError] = useState16(null);
2451
+ const [query, setQuery] = useState16("");
2452
+ async function load(before) {
2453
+ try {
2454
+ const params = `?limit=${PAGE}${before ? `&before=${encodeURIComponent(before)}` : ""}`;
2455
+ const { entries: next } = await api(`/api/audit${params}`);
2456
+ setEntries((current) => [...before ? current ?? [] : [], ...next]);
2457
+ setMore(next.length === PAGE);
2458
+ } catch (e) {
2459
+ setError(e.message);
2460
+ }
2461
+ }
2462
+ useEffect9(() => void load(), []);
2463
+ async function loadOlder(before) {
2464
+ setLoadingMore(true);
2465
+ await load(before);
2466
+ setLoadingMore(false);
2467
+ }
2468
+ if (!entries) return error ? /* @__PURE__ */ jsx20(Alert, { kind: "error", children: error }) : /* @__PURE__ */ jsx20(Spinner, { label: a.loading });
2469
+ const needle = query.trim().toLowerCase();
2470
+ const visible = needle ? entries.filter((e) => [e.actorEmail, e.action, e.target, e.viaKeyId, summarize(e.details)].some((v) => v?.toLowerCase().includes(needle))) : entries;
2471
+ return /* @__PURE__ */ jsxs19(Fragment8, { children: [
2472
+ /* @__PURE__ */ jsx20(PageHeader, { title: a.auditLog, description: a.auditDescription }),
2473
+ error && /* @__PURE__ */ jsx20(Alert, { kind: "error", className: "mb-4", children: error }),
2474
+ entries.length === 0 ? /* @__PURE__ */ jsx20(EmptyState, { icon: ScrollText2, title: a.auditEmpty }) : /* @__PURE__ */ jsxs19(Fragment8, { children: [
2475
+ /* @__PURE__ */ jsxs19("div", { className: "relative mb-4 max-w-sm", children: [
2476
+ /* @__PURE__ */ jsx20(Search2, { className: "pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted", "aria-hidden": true }),
2477
+ /* @__PURE__ */ jsx20(Input, { type: "search", "aria-label": a.searchAudit, placeholder: a.searchAudit, value: query, onChange: (e) => setQuery(e.target.value), className: "pl-9" })
2478
+ ] }),
2479
+ /* @__PURE__ */ jsx20(Card, { children: visible.length === 0 ? /* @__PURE__ */ jsx20("p", { className: "px-6 py-10 text-center text-sm text-muted", children: a.noMatches }) : /* @__PURE__ */ jsxs19(Table, { children: [
2480
+ /* @__PURE__ */ jsx20("thead", { children: /* @__PURE__ */ jsxs19("tr", { children: [
2481
+ /* @__PURE__ */ jsx20(TH, { children: a.colWhen }),
2482
+ /* @__PURE__ */ jsx20(TH, { children: a.colWho }),
2483
+ /* @__PURE__ */ jsx20(TH, { children: a.colAction }),
2484
+ /* @__PURE__ */ jsx20(TH, { children: a.colTarget }),
2485
+ /* @__PURE__ */ jsx20(TH, { children: a.colDetails })
2486
+ ] }) }),
2487
+ /* @__PURE__ */ jsx20("tbody", { children: visible.map((e) => {
2488
+ const details = summarize(e.details);
2489
+ return /* @__PURE__ */ jsxs19(TR, { children: [
2490
+ /* @__PURE__ */ jsx20(TD, { className: "whitespace-nowrap text-muted", children: /* @__PURE__ */ jsx20("time", { dateTime: e.at, title: formatDateTime(e.at), children: timeAgo(e.at) }) }),
2491
+ /* @__PURE__ */ jsx20(TD, { children: /* @__PURE__ */ jsxs19("div", { className: "flex items-center gap-2.5", children: [
2492
+ /* @__PURE__ */ jsx20(Avatar, { size: "sm", name: e.actorEmail ?? a.system }),
2493
+ /* @__PURE__ */ jsx20("span", { className: "truncate text-fg", children: e.actorEmail ?? a.system }),
2494
+ e.viaKeyId && /* @__PURE__ */ jsx20("span", { title: e.viaKeyId, children: /* @__PURE__ */ jsxs19(Badge, { children: [
2495
+ a.viaKey,
2496
+ " ",
2497
+ e.viaKeyId.slice(0, 8)
2498
+ ] }) })
2499
+ ] }) }),
2500
+ /* @__PURE__ */ jsx20(TD, { children: /* @__PURE__ */ jsx20(Badge, { tone: isDestructive(e.action) ? "danger" : "neutral", className: "font-mono", children: e.action }) }),
2501
+ /* @__PURE__ */ jsx20(TD, { className: "max-w-48 break-all text-fg", children: e.target }),
2502
+ /* @__PURE__ */ jsx20(TD, { className: "max-w-xs", children: /* @__PURE__ */ jsx20("p", { className: "truncate text-muted", title: details, children: details }) })
2503
+ ] }, e.id);
2504
+ }) })
2505
+ ] }) }),
2506
+ more && /* @__PURE__ */ jsx20("div", { className: "mt-4 flex justify-center", children: /* @__PURE__ */ jsx20(Button, { loading: loadingMore, onClick: () => void loadOlder(entries[entries.length - 1].at), children: a.loadMore }) })
2507
+ ] })
2508
+ ] });
2509
+ }
2510
+
2511
+ // src/admin/StatusPage.tsx
2512
+ import { CheckCircle2 as CheckCircle23, CircleAlert as CircleAlert2, CloudUpload, Database, TriangleAlert as TriangleAlert2 } from "lucide-react";
2513
+ import { useCallback as useCallback7, useEffect as useEffect10, useState as useState17 } from "react";
2514
+ import { Link as Link4 } from "react-router-dom";
2515
+ import { Fragment as Fragment9, jsx as jsx21, jsxs as jsxs20 } from "react/jsx-runtime";
2516
+ var levels = {
2517
+ ok: { tone: "ok", icon: CheckCircle23, banner: "border-ok/30 bg-ok-soft", tile: "bg-ok-soft text-ok" },
2518
+ warn: { tone: "warn", icon: TriangleAlert2, banner: "border-warn/30 bg-warn-soft", tile: "bg-warn-soft text-warn" },
2519
+ fail: { tone: "danger", icon: CircleAlert2, banner: "border-danger/30 bg-danger-soft", tile: "bg-danger-soft text-danger" }
2520
+ };
2521
+ var levelText = { ok: "text-ok", warn: "text-warn", fail: "text-danger" };
2522
+ function duration(seconds) {
2523
+ const days = Math.floor(seconds / 86400);
2524
+ const hours = Math.floor(seconds % 86400 / 3600);
2525
+ const minutes = Math.floor(seconds % 3600 / 60);
2526
+ return days > 0 ? `${days} d ${hours} h` : hours > 0 ? `${hours} h ${minutes} min` : `${minutes} min`;
2527
+ }
2528
+ function StatusPage() {
2529
+ const me = useMe();
2530
+ const toast = useToast();
2531
+ const [status, setStatus] = useState17(null);
2532
+ const [error, setError] = useState17(null);
2533
+ const [busy, setBusy] = useState17(false);
2534
+ const [copying, setCopying] = useState17(null);
2535
+ const load = useCallback7(async () => {
2536
+ try {
2537
+ setStatus(await api("/api/status"));
2538
+ setError(null);
2539
+ } catch (e) {
2540
+ setError(e.message);
2541
+ }
2542
+ }, []);
2543
+ useEffect10(() => void load(), [load]);
2544
+ useEffect10(() => {
2545
+ const timer = setInterval(() => void load(), 3e4);
2546
+ return () => clearInterval(timer);
2547
+ }, [load]);
2548
+ async function backupNow() {
2549
+ setBusy(true);
2550
+ try {
2551
+ await api("/api/backups", { method: "POST", body: {} });
2552
+ toast.success(a.backupDone);
2553
+ } catch (e) {
2554
+ toast.error(e.message);
2555
+ }
2556
+ setBusy(false);
2557
+ await load();
2558
+ }
2559
+ async function copyBackup(folder) {
2560
+ setCopying(folder);
2561
+ try {
2562
+ await api(`/api/backups/${folder}/upload`, { method: "POST", body: {} });
2563
+ toast.success(a.copyDone);
2564
+ } catch (e) {
2565
+ toast.error(e.message);
2566
+ }
2567
+ setCopying(null);
2568
+ await load();
2569
+ }
2570
+ if (!status) return error ? /* @__PURE__ */ jsx21(Alert, { kind: "error", children: error }) : /* @__PURE__ */ jsx21(Spinner, { label: a.loading });
2571
+ const result = {
2572
+ success: { text: a.resultSuccess, tone: "ok" },
2573
+ failed: { text: a.resultFailed, tone: "danger" },
2574
+ running: { text: a.resultRunning, tone: "brand" }
2575
+ };
2576
+ const overall = levels[status.status];
2577
+ const OverallIcon = overall.icon;
2578
+ const running = busy || status.backupRunning;
2579
+ return /* @__PURE__ */ jsxs20(Fragment9, { children: [
2580
+ /* @__PURE__ */ jsx21(PageHeader, { title: a.statusTitle, description: a.statusDescription }),
2581
+ error && /* @__PURE__ */ jsx21(Alert, { kind: "error", className: "mb-4", children: error }),
2582
+ /* @__PURE__ */ jsxs20("div", { className: "space-y-6", children: [
2583
+ /* @__PURE__ */ jsxs20("div", { className: cn("flex flex-wrap items-center gap-4 rounded-card border p-5", overall.banner), role: "status", children: [
2584
+ /* @__PURE__ */ jsx21("span", { className: cn("inline-flex size-14 shrink-0 items-center justify-center rounded-full bg-surface", levelText[status.status]), children: /* @__PURE__ */ jsx21(OverallIcon, { className: "size-8", "aria-hidden": true }) }),
2585
+ /* @__PURE__ */ jsxs20("div", { className: "min-w-0 flex-1", children: [
2586
+ /* @__PURE__ */ jsx21("p", { className: "text-xl font-semibold tracking-tight text-fg", children: a.overall[status.status] }),
2587
+ /* @__PURE__ */ jsxs20("p", { className: "text-sm text-muted", children: [
2588
+ a.uptime,
2589
+ " ",
2590
+ duration(status.uptimeSeconds),
2591
+ " \xB7 ",
2592
+ a.frameworkVersion,
2593
+ " ",
2594
+ status.frameworkVersion
2595
+ ] })
2596
+ ] })
2597
+ ] }),
2598
+ /* @__PURE__ */ jsxs20("section", { "aria-label": a.healthChecks, children: [
2599
+ /* @__PURE__ */ jsx21("h2", { className: "sr-only", children: a.healthChecks }),
2600
+ /* @__PURE__ */ jsx21("div", { className: "grid gap-4 sm:grid-cols-2 xl:grid-cols-3", children: status.checks.map((c2) => {
2601
+ const level = levels[c2.status];
2602
+ const Icon = level.icon;
2603
+ return /* @__PURE__ */ jsxs20(Card, { className: "flex gap-3 p-4", children: [
2604
+ /* @__PURE__ */ jsx21("span", { className: cn("inline-flex size-10 shrink-0 items-center justify-center rounded-xl", level.tile), children: /* @__PURE__ */ jsx21(Icon, { className: "size-5", "aria-hidden": true }) }),
2605
+ /* @__PURE__ */ jsxs20("div", { className: "min-w-0 flex-1", children: [
2606
+ /* @__PURE__ */ jsxs20("div", { className: "flex items-start justify-between gap-2", children: [
2607
+ /* @__PURE__ */ jsx21("p", { className: "font-medium text-fg", children: c2.label }),
2608
+ /* @__PURE__ */ jsx21(Badge, { tone: level.tone, dot: true, children: a.checkState[c2.status] })
2609
+ ] }),
2610
+ /* @__PURE__ */ jsx21("p", { className: "mt-1 break-words text-sm text-muted", children: c2.detail })
2611
+ ] })
2612
+ ] }, c2.name);
2613
+ }) })
2614
+ ] }),
2615
+ /* @__PURE__ */ jsxs20(Card, { children: [
2616
+ /* @__PURE__ */ jsxs20("div", { className: "flex flex-wrap items-start justify-between gap-4 border-b border-line px-5 py-4", children: [
2617
+ /* @__PURE__ */ jsxs20("div", { className: "min-w-0", children: [
2618
+ /* @__PURE__ */ jsx21("h2", { className: "font-semibold text-fg", children: a.backups }),
2619
+ /* @__PURE__ */ jsxs20("p", { className: "mt-1 text-sm text-muted", children: [
2620
+ status.settings.backupEnabled && status.nextBackupAt ? `${a.nextBackup}: ${formatDateTime(status.nextBackupAt)}. ` : `${a.backupsOff} `,
2621
+ a.keeps,
2622
+ " ",
2623
+ status.settings.backupKeep,
2624
+ " ",
2625
+ a.backupsWord,
2626
+ status.settings.includesFiles ? `, ${a.includesFiles}` : "",
2627
+ ".",
2628
+ status.settings.alertRecipients > 0 && ` ${a.alertsTo} ${status.settings.alertRecipients} ${a.addresses}.`
2629
+ ] })
2630
+ ] }),
2631
+ can(me, "backup:create") && /* @__PURE__ */ jsx21(Button, { variant: "primary", icon: /* @__PURE__ */ jsx21(Database, { className: "size-4", "aria-hidden": true }), loading: running, onClick: () => void backupNow(), children: running ? a.backingUp : a.backupNow })
2632
+ ] }),
2633
+ status.copy.available && /* @__PURE__ */ jsx21("div", { className: "border-b border-line px-5 py-3 text-sm text-muted", children: status.copy.ready ? /* @__PURE__ */ jsxs20(Fragment9, { children: [
2634
+ status.copy.auto ? a.copyAuto(status.copy.keep) : a.copyManual,
2635
+ status.copy.encrypted ? ` ${a.copyEncrypted}` : ` ${a.copyNotEncrypted}`
2636
+ ] }) : /* @__PURE__ */ jsxs20(Fragment9, { children: [
2637
+ a.copyNotSetUp,
2638
+ " ",
2639
+ can(me, "storage:update") && /* @__PURE__ */ jsx21(Link4, { to: "/connections", className: "font-medium text-brand hover:underline", children: a.copySetUp })
2640
+ ] }) }),
2641
+ status.settings.alertRecipients === 0 && /* @__PURE__ */ jsx21("div", { className: "border-b border-line p-4", children: /* @__PURE__ */ jsx21(Alert, { kind: "warning", children: a.noAlerts }) }),
2642
+ /* @__PURE__ */ jsx21("h3", { className: "px-5 pb-1 pt-4 text-sm font-medium text-fg", children: a.recentBackups }),
2643
+ status.backups.length === 0 ? /* @__PURE__ */ jsx21("p", { className: "px-5 pb-6 pt-2 text-sm text-muted", children: a.noBackups }) : /* @__PURE__ */ jsxs20(Table, { children: [
2644
+ /* @__PURE__ */ jsx21("thead", { children: /* @__PURE__ */ jsxs20("tr", { children: [
2645
+ /* @__PURE__ */ jsx21(TH, { children: a.colStarted }),
2646
+ /* @__PURE__ */ jsx21(TH, { children: a.colResult }),
2647
+ /* @__PURE__ */ jsx21(TH, { children: a.colSize }),
2648
+ /* @__PURE__ */ jsx21(TH, { children: a.colHow }),
2649
+ status.copy.available && /* @__PURE__ */ jsx21(TH, { children: a.colCopy })
2650
+ ] }) }),
2651
+ /* @__PURE__ */ jsx21("tbody", { children: status.backups.map((b) => /* @__PURE__ */ jsxs20(TR, { children: [
2652
+ /* @__PURE__ */ jsx21(TD, { className: "whitespace-nowrap", children: formatDateTime(b.startedAt) }),
2653
+ /* @__PURE__ */ jsxs20(TD, { children: [
2654
+ /* @__PURE__ */ jsx21(Badge, { tone: result[b.status].tone, dot: true, children: result[b.status].text }),
2655
+ b.error && /* @__PURE__ */ jsx21("p", { className: "mt-1 break-all text-xs text-muted", children: b.error })
2656
+ ] }),
2657
+ /* @__PURE__ */ jsx21(TD, { className: "whitespace-nowrap", children: b.sizeBytes === null ? "" : formatBytes(b.sizeBytes) }),
2658
+ /* @__PURE__ */ jsx21(TD, { children: /* @__PURE__ */ jsx21(Badge, { children: b.trigger === "manual" ? a.howManual : a.howScheduled }) }),
2659
+ status.copy.available && /* @__PURE__ */ jsx21(TD, { children: b.uploadedAt ? /* @__PURE__ */ jsxs20("div", { children: [
2660
+ /* @__PURE__ */ jsx21(Badge, { tone: "ok", dot: true, children: b.uploadEncrypted ? a.copiedEncrypted : a.copied }),
2661
+ /* @__PURE__ */ jsx21("p", { className: "mt-1 text-xs text-muted", children: formatDateTime(b.uploadedAt) })
2662
+ ] }) : /* @__PURE__ */ jsxs20("div", { className: "space-y-1", children: [
2663
+ b.uploadError && /* @__PURE__ */ jsx21("p", { className: "break-all text-xs text-danger", children: b.uploadError }),
2664
+ b.status === "success" && b.folder && status.copy.ready && can(me, "backup:upload") && /* @__PURE__ */ jsx21(Button, { size: "sm", icon: /* @__PURE__ */ jsx21(CloudUpload, { className: "size-4", "aria-hidden": true }), loading: copying === b.folder || status.copy.copying, onClick: () => void copyBackup(b.folder), children: a.copyNow })
2665
+ ] }) })
2666
+ ] }, b.id)) })
2667
+ ] }),
2668
+ /* @__PURE__ */ jsx21("p", { className: "border-t border-line px-5 py-3 text-xs text-muted", children: a.restoreHint })
2669
+ ] })
2670
+ ] })
2671
+ ] });
2672
+ }
2673
+
2674
+ // src/admin/SettingsPage.tsx
2675
+ import { RotateCcw } from "lucide-react";
2676
+ import { useCallback as useCallback8, useEffect as useEffect11, useState as useState18 } from "react";
2677
+ import { Fragment as Fragment10, jsx as jsx22, jsxs as jsxs21 } from "react/jsx-runtime";
2678
+ var IDENTITY_GROUP = "Identity";
2679
+ var same = (x, y) => JSON.stringify(x) === JSON.stringify(y);
2680
+ var show = (s, value) => {
2681
+ if (value === null || value === void 0) return a.notSet;
2682
+ if (s.type === "boolean") return value ? a.yes : a.no;
2683
+ if (s.type === "numbers") return value.length === 0 ? a.none : value.join(", ");
2684
+ if (s.type === "select") return s.options?.find((o) => o.value === value)?.label ?? String(value);
2685
+ return `${value}${s.unit && s.type === "number" ? ` ${s.unit}` : ""}`;
2686
+ };
2687
+ function NumbersInput({ value, onChange, unit }) {
2688
+ const [text, setText] = useState18(value.join(", "));
2689
+ const [valid, setValid] = useState18(true);
2690
+ return /* @__PURE__ */ jsxs21(Fragment10, { children: [
2691
+ /* @__PURE__ */ jsxs21("div", { className: "flex items-center gap-2", children: [
2692
+ /* @__PURE__ */ jsx22(
2693
+ Input,
2694
+ {
2695
+ value: text,
2696
+ inputMode: "numeric",
2697
+ "aria-invalid": !valid,
2698
+ className: valid ? void 0 : "border-danger",
2699
+ onChange: (e) => {
2700
+ setText(e.target.value);
2701
+ const tokens = e.target.value.split(",").map((t2) => t2.trim()).filter(Boolean);
2702
+ const numbers = tokens.map(Number);
2703
+ const ok = numbers.every((n) => Number.isInteger(n));
2704
+ setValid(ok);
2705
+ if (ok) onChange(numbers);
2706
+ }
2707
+ }
2708
+ ),
2709
+ unit && /* @__PURE__ */ jsx22("span", { className: "shrink-0 text-sm text-muted", children: unit })
2710
+ ] }),
2711
+ !valid && /* @__PURE__ */ jsx22("span", { className: "mt-1.5 block text-xs text-danger", children: a.listInvalid })
2712
+ ] });
2713
+ }
2714
+ function Control({ s, value, onChange }) {
2715
+ switch (s.type) {
2716
+ case "text":
2717
+ return /* @__PURE__ */ jsx22(Input, { value: String(value ?? ""), onChange: (e) => onChange(e.target.value) });
2718
+ case "number":
2719
+ return /* @__PURE__ */ jsxs21("div", { className: "flex items-center gap-2", children: [
2720
+ /* @__PURE__ */ jsx22(Input, { type: "number", inputMode: "numeric", min: s.min, max: s.max, value: value === null || value === void 0 ? "" : String(value), onChange: (e) => onChange(e.target.value === "" ? "" : Number(e.target.value)), className: "max-w-32" }),
2721
+ s.unit && /* @__PURE__ */ jsx22("span", { className: "text-sm text-muted", children: s.unit })
2722
+ ] });
2723
+ case "boolean":
2724
+ return /* @__PURE__ */ jsx22(Checkbox, { label: a.yes, checked: Boolean(value), onChange: (e) => onChange(e.target.checked) });
2725
+ case "select":
2726
+ return /* @__PURE__ */ jsx22(Select, { value: String(value ?? ""), onChange: (e) => onChange(e.target.value), children: s.options?.map((o) => /* @__PURE__ */ jsx22("option", { value: o.value, children: o.label }, o.value)) });
2727
+ case "numbers":
2728
+ return /* @__PURE__ */ jsx22(NumbersInput, { value: value ?? [], onChange, unit: s.unit });
2729
+ case "color":
2730
+ return /* @__PURE__ */ jsx22(ColorField, { value: value ?? null, onChange });
2731
+ }
2732
+ }
2733
+ function LogoCard() {
2734
+ const toast = useToast();
2735
+ const brand = useBrand();
2736
+ const onBrand = useSetBrand();
2737
+ const [file, setFile] = useState18(null);
2738
+ const [busy, setBusy] = useState18(false);
2739
+ async function upload() {
2740
+ if (!file) return;
2741
+ setBusy(true);
2742
+ try {
2743
+ const form = new FormData();
2744
+ form.set("logo", file);
2745
+ onBrand((await apiForm("/api/settings/logo", form)).brand);
2746
+ setFile(null);
2747
+ toast.success(a.logoSaved);
2748
+ } catch (e) {
2749
+ toast.error(e.message);
2750
+ } finally {
2751
+ setBusy(false);
2752
+ }
2753
+ }
2754
+ async function remove() {
2755
+ setBusy(true);
2756
+ try {
2757
+ onBrand((await api("/api/settings/logo", { method: "DELETE" })).brand);
2758
+ toast.success(a.logoRemoved);
2759
+ } catch (e) {
2760
+ toast.error(e.message);
2761
+ } finally {
2762
+ setBusy(false);
2763
+ }
2764
+ }
2765
+ return /* @__PURE__ */ jsxs21("div", { children: [
2766
+ /* @__PURE__ */ jsx22("p", { className: "mb-1.5 text-sm font-medium text-fg", children: a.logo }),
2767
+ /* @__PURE__ */ jsxs21("div", { className: "flex flex-wrap items-start gap-4", children: [
2768
+ /* @__PURE__ */ jsx22("div", { className: "flex h-20 w-32 shrink-0 items-center justify-center rounded-lg border border-line bg-surface-muted/40 p-2", children: brand.logoUrl ? /* @__PURE__ */ jsx22("img", { src: brand.logoUrl, alt: "", className: "max-h-full max-w-full object-contain" }) : /* @__PURE__ */ jsx22("span", { className: "text-center text-xs text-muted", children: a.noLogo }) }),
2769
+ /* @__PURE__ */ jsxs21("div", { className: "min-w-0 flex-1 space-y-3", style: { minWidth: "16rem" }, children: [
2770
+ /* @__PURE__ */ jsx22(FileDrop, { file, onChange: setFile, accept: a.logoFileTypes, maxBytes: a.logoMaxBytes, hint: a.logoMaxHint, label: a.logoChoose }),
2771
+ /* @__PURE__ */ jsxs21("div", { className: "flex flex-wrap gap-2", children: [
2772
+ file && /* @__PURE__ */ jsx22(Button, { variant: "primary", loading: busy, onClick: upload, children: a.logoSave }),
2773
+ brand.logoUrl && !file && /* @__PURE__ */ jsx22(Button, { variant: "secondary", disabled: busy, onClick: remove, children: a.logoRemove })
2774
+ ] }),
2775
+ /* @__PURE__ */ jsx22("p", { className: "text-xs text-muted", children: a.logoHint })
2776
+ ] })
2777
+ ] })
2778
+ ] });
2779
+ }
2780
+ function SettingsPage() {
2781
+ const toast = useToast();
2782
+ const setBrand = useSetBrand();
2783
+ const [data, setData] = useState18(null);
2784
+ const [draft, setDraft] = useState18({});
2785
+ const [error, setError] = useState18(null);
2786
+ const [saving, setSaving] = useState18(false);
2787
+ const [epoch, setEpoch] = useState18(0);
2788
+ const apply = useCallback8(
2789
+ (next, keys) => {
2790
+ setData(next);
2791
+ setBrand(next.brand);
2792
+ setEpoch((e) => e + 1);
2793
+ setDraft((d) => {
2794
+ const fresh = Object.fromEntries(next.settings.map((s) => [s.key, s.value]));
2795
+ return keys ? { ...d, ...Object.fromEntries(keys.map((k) => [k, fresh[k]])) } : fresh;
2796
+ });
2797
+ },
2798
+ [setBrand]
2799
+ );
2800
+ useEffect11(() => {
2801
+ let cancelled = false;
2802
+ api("/api/settings").then((d) => !cancelled && apply(d)).catch((e) => !cancelled && setError(e.message));
2803
+ return () => {
2804
+ cancelled = true;
2805
+ };
2806
+ }, [apply]);
2807
+ if (!data) return error ? /* @__PURE__ */ jsx22(Alert, { kind: "error", children: error }) : /* @__PURE__ */ jsx22(Spinner, { label: a.loading });
2808
+ const changed = data.settings.filter((s) => !same(draft[s.key], s.value));
2809
+ const groups = [...new Set(data.settings.map((s) => s.group))];
2810
+ async function save() {
2811
+ setSaving(true);
2812
+ try {
2813
+ const values = Object.fromEntries(changed.map((s) => [s.key, draft[s.key] === "" ? null : draft[s.key]]));
2814
+ apply(await api("/api/settings", { method: "PUT", body: { values } }));
2815
+ toast.success(a.settingsSaved);
2816
+ } catch (e) {
2817
+ toast.error(e.message);
2818
+ } finally {
2819
+ setSaving(false);
2820
+ }
2821
+ }
2822
+ async function reset(s) {
2823
+ try {
2824
+ apply(await api("/api/settings", { method: "PUT", body: { values: { [s.key]: null } } }), [s.key]);
2825
+ toast.success(a.settingsReset);
2826
+ } catch (e) {
2827
+ toast.error(e.message);
2828
+ }
2829
+ }
2830
+ return /* @__PURE__ */ jsxs21(Fragment10, { children: [
2831
+ /* @__PURE__ */ jsx22(PageHeader, { title: a.settings, description: a.settingsDescription }),
2832
+ error && /* @__PURE__ */ jsx22(Alert, { kind: "error", className: "mb-4", children: error }),
2833
+ /* @__PURE__ */ jsx22("div", { className: "space-y-6 pb-24", children: groups.map((group) => /* @__PURE__ */ jsxs21(Card, { className: "p-5", children: [
2834
+ /* @__PURE__ */ jsx22("h2", { className: "mb-4 text-base font-semibold text-fg", children: group }),
2835
+ /* @__PURE__ */ jsxs21("div", { className: "space-y-5", children: [
2836
+ data.settings.filter((s) => s.group === group).map((s) => /* @__PURE__ */ jsxs21("div", { className: "max-w-xl", children: [
2837
+ /* @__PURE__ */ jsx22(Field, { label: s.label, hint: s.description, children: /* @__PURE__ */ jsx22(Control, { s, value: draft[s.key], onChange: (v) => setDraft((d) => ({ ...d, [s.key]: v })) }, epoch) }),
2838
+ !s.isDefault && /* @__PURE__ */ jsxs21("div", { className: "mt-1.5 flex items-center gap-2", children: [
2839
+ /* @__PURE__ */ jsx22(Badge, { tone: "brand", children: a.customized }),
2840
+ /* @__PURE__ */ jsxs21("button", { type: "button", onClick: () => void reset(s), className: "inline-flex items-center gap-1 text-xs text-muted hover:text-fg", children: [
2841
+ /* @__PURE__ */ jsx22(RotateCcw, { className: "size-3", "aria-hidden": true }),
2842
+ " ",
2843
+ a.resetToDefault(show(s, s.default))
2844
+ ] })
2845
+ ] })
2846
+ ] }, s.key)),
2847
+ group === IDENTITY_GROUP && /* @__PURE__ */ jsx22(LogoCard, {})
2848
+ ] })
2849
+ ] }, group)) }),
2850
+ changed.length > 0 && /* @__PURE__ */ jsx22("div", { className: "fixed inset-x-0 bottom-0 z-20 border-t border-line bg-surface/95 px-4 py-3 shadow-card backdrop-blur lg:left-[16.5rem]", children: /* @__PURE__ */ jsxs21("div", { className: "mx-auto flex max-w-5xl flex-wrap items-center justify-between gap-3", children: [
2851
+ /* @__PURE__ */ jsx22("p", { className: "text-sm text-fg", children: a.unsavedChanges }),
2852
+ /* @__PURE__ */ jsxs21("div", { className: "flex gap-2", children: [
2853
+ /* @__PURE__ */ jsx22(Button, { variant: "secondary", disabled: saving, onClick: () => {
2854
+ setDraft(Object.fromEntries(data.settings.map((s) => [s.key, s.value])));
2855
+ setEpoch((e) => e + 1);
2856
+ }, children: a.discard }),
2857
+ /* @__PURE__ */ jsx22(Button, { variant: "primary", loading: saving, onClick: save, children: a.save })
2858
+ ] })
2859
+ ] }) })
2860
+ ] });
2861
+ }
2862
+
2863
+ // src/admin/ConnectionsPage.tsx
2864
+ import { Cloud, HardDrive, Mail as Mail2, Plug as Plug2, Plus as Plus4, Sparkles, Trash2 as Trash24 } from "lucide-react";
2865
+ import { useCallback as useCallback9, useEffect as useEffect12, useMemo as useMemo3, useState as useState19 } from "react";
2866
+ import { useNavigate as useNavigate3, useSearchParams as useSearchParams2 } from "react-router-dom";
2867
+
2868
+ // src/admin/connectionTexts.ts
2869
+ var c = {
2870
+ title: "Connections",
2871
+ description: "Where this app keeps files, which AI models it may use and how it sends email. Set them up once; the app refers to each by its name.",
2872
+ tabStorage: "Storage",
2873
+ tabLlm: "AI models",
2874
+ tabEmail: "Email",
2875
+ loading: "Loading...",
2876
+ add: "Add a connection",
2877
+ setUp: "Set up",
2878
+ edit: "Edit",
2879
+ test: "Test",
2880
+ testEmail: "Send test email",
2881
+ testing: "Testing...",
2882
+ connect: "Connect",
2883
+ reconnect: "Connect again",
2884
+ remove: "Remove",
2885
+ cancel: "Cancel",
2886
+ save: "Save",
2887
+ required: "Required",
2888
+ builtIn: "Built in",
2889
+ inBackup: "Included in backups",
2890
+ notInBackup: "Not included in backups",
2891
+ notInBackupHint: "Files kept here are not part of this app's backups. Rely on the provider's own safeguards.",
2892
+ switchedOff: "Switched off",
2893
+ status: {
2894
+ ok: "Working",
2895
+ untested: "Not tested yet",
2896
+ failing: "Test failed",
2897
+ incomplete: "Needs attention",
2898
+ missing: "Not set up",
2899
+ disabled: "Switched off"
2900
+ },
2901
+ idLabel: "Name used by the app",
2902
+ idHint: 'Lowercase letters, digits and dashes, for example "fast" or "documents". The app refers to the connection by this name.',
2903
+ labelLabel: "Description",
2904
+ providerLabel: "Type",
2905
+ enabledLabel: "In use",
2906
+ secretSaved: "Saved. Leave empty to keep it.",
2907
+ secretRemove: "Remove the saved value",
2908
+ secretRemoved: "Will be removed when you save.",
2909
+ redirectTitle: "Redirect address",
2910
+ redirectHint: "Register exactly this address in the provider's console, then save and press Connect.",
2911
+ copy: "Copy",
2912
+ copied: "Copied",
2913
+ saved: "Saved",
2914
+ savedConnect: "Saved. Press Connect to sign in at the provider.",
2915
+ removed: "Removed",
2916
+ connected: (id) => `"${id}" is connected`,
2917
+ signInFailed: "Signing in did not work",
2918
+ confirmRemoveTitle: (id) => `Remove "${id}"?`,
2919
+ confirmRemoveText: "The app can no longer use it. Files that are already stored there stay where they are.",
2920
+ confirmChangeTitle: "Change the type?",
2921
+ confirmChangeText: "Files that are already stored are not moved to the new place. Only change this for a connection that holds nothing yet.",
2922
+ confirmChange: "Change it",
2923
+ testOk: "Test passed",
2924
+ usage: "Usage in the last 14 days",
2925
+ usageEmpty: "Nothing has been asked of the AI models yet.",
2926
+ colDay: "Day",
2927
+ colConnection: "Connection",
2928
+ colCalls: "Calls",
2929
+ colInput: "Tokens in",
2930
+ colOutput: "Tokens out",
2931
+ colErrors: "Errors",
2932
+ usageHint: "Only counts are kept, never the questions or the answers.",
2933
+ personalDataWarning: 'Hosted AI models receive what the app sends them. Tick "Approved for personal data" only for connections you have a data agreement for, or that run on your own network.',
2934
+ emailNote: "Every email of the app goes through this connection while it is switched on: invitations, password resets, reminders and alerts. The test sends a message to your own address. When it is switched off or removed, the server's own email settings are used again.",
2935
+ storageWarning: "Backups and files can hold personal data. Choose a provider you have a data agreement with, ideally with servers in the EU.",
2936
+ none: "Nothing is set up here yet.",
2937
+ noneHint: "This app has not asked for any connection of this kind. You can still add one; the app uses only the names it knows.",
2938
+ nothingAvailable: "You do not have access to any connections."
2939
+ };
2940
+
2941
+ // src/admin/ConnectionsPage.tsx
2942
+ import { Fragment as Fragment11, jsx as jsx23, jsxs as jsxs22 } from "react/jsx-runtime";
2943
+ var KINDS = ["storage", "llm", "email"];
2944
+ var KIND_TAB = { storage: c.tabStorage, llm: c.tabLlm, email: c.tabEmail };
2945
+ var statusTone = (s) => s.status === "ok" ? "ok" : s.status === "failing" ? "danger" : s.status === "incomplete" || s.status === "missing" && s.required ? "warn" : "neutral";
2946
+ function EditDialog({ kind, conn, creating, data, onClose, onSaved }) {
2947
+ const toast = useToast();
2948
+ const confirm = useConfirm();
2949
+ const [id, setId] = useState19(conn.id);
2950
+ const [label, setLabel] = useState19(conn.label === conn.id ? "" : conn.label);
2951
+ const [provider, setProvider] = useState19(conn.provider ?? data.providers[0]?.key ?? "");
2952
+ const [config, setConfig] = useState19(conn.config);
2953
+ const [secrets, setSecrets] = useState19({});
2954
+ const [enabled, setEnabled] = useState19(conn.status === "missing" ? true : conn.enabled);
2955
+ const [busy, setBusy] = useState19(false);
2956
+ const def = data.providers.find((p) => p.key === provider);
2957
+ const fields = useMemo3(() => [...def?.fields ?? [], ...conn.extraFields], [def, conn.extraFields]);
2958
+ const sameProvider = provider === conn.provider;
2959
+ async function save() {
2960
+ if (conn.provider && !sameProvider && !await confirm({ title: c.confirmChangeTitle, description: c.confirmChangeText, confirmLabel: c.confirmChange })) return;
2961
+ setBusy(true);
2962
+ try {
2963
+ const body = {
2964
+ label,
2965
+ provider,
2966
+ enabled,
2967
+ config: Object.fromEntries(fields.filter((f) => f.type !== "secret").map((f) => [f.key, config[f.key] ?? (f.type === "boolean" ? false : f.default)])),
2968
+ secrets: Object.fromEntries(Object.entries(secrets).filter(([, v]) => v === null || v.trim() !== ""))
2969
+ };
2970
+ const saved = await api(`/api/connections/${kind}/${creating ? id : conn.id}`, { method: "PUT", body });
2971
+ onSaved(saved, Boolean(def?.oauth));
2972
+ } catch (e) {
2973
+ toast.error(e.message);
2974
+ } finally {
2975
+ setBusy(false);
2976
+ }
2977
+ }
2978
+ const copy = () => void navigator.clipboard?.writeText(data.redirectUri).then(() => toast.success(c.copied));
2979
+ return /* @__PURE__ */ jsx23(
2980
+ Dialog,
2981
+ {
2982
+ open: true,
2983
+ onClose,
2984
+ title: creating ? c.add : conn.label === conn.id ? conn.id : `${conn.label} (${conn.id})`,
2985
+ description: conn.purpose ?? void 0,
2986
+ footer: /* @__PURE__ */ jsxs22(Fragment11, { children: [
2987
+ /* @__PURE__ */ jsx23(Button, { variant: "secondary", onClick: onClose, children: c.cancel }),
2988
+ /* @__PURE__ */ jsx23(Button, { variant: "primary", loading: busy, onClick: () => void save(), children: c.save })
2989
+ ] }),
2990
+ children: /* @__PURE__ */ jsxs22(
2991
+ "form",
2992
+ {
2993
+ className: "space-y-4",
2994
+ onSubmit: (e) => {
2995
+ e.preventDefault();
2996
+ void save();
2997
+ },
2998
+ children: [
2999
+ creating && /* @__PURE__ */ jsx23(Field, { label: c.idLabel, hint: c.idHint, children: /* @__PURE__ */ jsx23(Input, { value: id, onChange: (e) => setId(e.target.value.toLowerCase()), autoFocus: true, spellCheck: false }) }),
3000
+ /* @__PURE__ */ jsx23(Field, { label: c.providerLabel, hint: def?.description ?? void 0, children: /* @__PURE__ */ jsx23(Select, { value: provider, onChange: (e) => setProvider(e.target.value), children: data.providers.map((p) => /* @__PURE__ */ jsx23("option", { value: p.key, children: p.label }, p.key)) }) }),
3001
+ /* @__PURE__ */ jsx23(Field, { label: c.labelLabel, children: /* @__PURE__ */ jsx23(Input, { value: label, onChange: (e) => setLabel(e.target.value), placeholder: conn.id || "" }) }),
3002
+ def?.oauth && /* @__PURE__ */ jsxs22(Alert, { kind: "info", title: c.redirectTitle, children: [
3003
+ /* @__PURE__ */ jsx23("p", { className: "mb-2", children: c.redirectHint }),
3004
+ /* @__PURE__ */ jsxs22("div", { className: "flex flex-wrap items-center gap-2", children: [
3005
+ /* @__PURE__ */ jsx23("code", { className: "break-all rounded bg-surface-muted px-2 py-1 text-xs text-fg", children: data.redirectUri }),
3006
+ /* @__PURE__ */ jsx23(Button, { size: "sm", variant: "secondary", onClick: copy, children: c.copy })
3007
+ ] })
3008
+ ] }),
3009
+ fields.map((f) => {
3010
+ const has = sameProvider && conn.secretsSet.includes(f.key);
3011
+ const removing = secrets[f.key] === null;
3012
+ return /* @__PURE__ */ jsx23("div", { children: f.type === "boolean" ? /* @__PURE__ */ jsx23(Checkbox, { label: f.label, description: f.help, checked: Boolean(config[f.key]), onChange: (e) => setConfig((x) => ({ ...x, [f.key]: e.target.checked })) }) : /* @__PURE__ */ jsx23(Field, { label: f.required ? f.label : `${f.label}`, hint: f.help, children: f.type === "select" ? /* @__PURE__ */ jsx23(Select, { value: String(config[f.key] ?? f.default ?? ""), onChange: (e) => setConfig((x) => ({ ...x, [f.key]: e.target.value })), children: f.options?.map((o) => /* @__PURE__ */ jsx23("option", { value: o.value, children: o.label }, o.value)) }) : f.type === "secret" ? /* @__PURE__ */ jsxs22("div", { className: "space-y-1.5", children: [
3013
+ /* @__PURE__ */ jsx23(
3014
+ Input,
3015
+ {
3016
+ type: "password",
3017
+ autoComplete: "new-password",
3018
+ value: typeof secrets[f.key] === "string" ? secrets[f.key] : "",
3019
+ placeholder: removing ? c.secretRemoved : has ? c.secretSaved : "",
3020
+ onChange: (e) => setSecrets((x) => ({ ...x, [f.key]: e.target.value }))
3021
+ }
3022
+ ),
3023
+ has && !f.required && !removing && /* @__PURE__ */ jsx23("button", { type: "button", className: "text-xs text-muted hover:text-fg", onClick: () => setSecrets((x) => ({ ...x, [f.key]: null })), children: c.secretRemove })
3024
+ ] }) : /* @__PURE__ */ jsx23(
3025
+ Input,
3026
+ {
3027
+ type: f.type === "number" ? "number" : "text",
3028
+ inputMode: f.type === "number" ? "decimal" : void 0,
3029
+ value: String(config[f.key] ?? f.default ?? ""),
3030
+ placeholder: f.placeholder,
3031
+ onChange: (e) => setConfig((x) => ({ ...x, [f.key]: e.target.value }))
3032
+ }
3033
+ ) }) }, f.key);
3034
+ }),
3035
+ /* @__PURE__ */ jsx23(Checkbox, { label: c.enabledLabel, checked: enabled, onChange: (e) => setEnabled(e.target.checked) }),
3036
+ /* @__PURE__ */ jsx23("p", { className: "text-xs text-muted", children: kind === "llm" ? c.personalDataWarning : kind === "email" ? c.emailNote : c.storageWarning })
3037
+ ]
3038
+ }
3039
+ )
3040
+ }
3041
+ );
3042
+ }
3043
+ function ConnectionCard({ kind, conn, providers, canEdit, onEdit, onChanged }) {
3044
+ const toast = useToast();
3045
+ const confirm = useConfirm();
3046
+ const [busy, setBusy] = useState19(null);
3047
+ const Icon = kind === "llm" ? Sparkles : kind === "email" ? Mail2 : conn.provider === "local" ? HardDrive : Cloud;
3048
+ const oauth = providers.find((p) => p.key === conn.provider)?.oauth;
3049
+ const configured = conn.status !== "missing";
3050
+ async function test() {
3051
+ setBusy("test");
3052
+ try {
3053
+ const r = await api(`/api/connections/${kind}/${conn.id}/test`, { method: "POST", body: {} });
3054
+ (r.ok ? toast.success : toast.error)(r.ok ? kind === "email" ? r.message : c.testOk : r.message);
3055
+ } catch (e) {
3056
+ toast.error(e.message);
3057
+ }
3058
+ setBusy(null);
3059
+ await onChanged();
3060
+ }
3061
+ async function connect() {
3062
+ setBusy("connect");
3063
+ try {
3064
+ const { url } = await api(`/api/connections/${kind}/${conn.id}/connect`, { method: "POST", body: {} });
3065
+ window.location.assign(url);
3066
+ } catch (e) {
3067
+ toast.error(e.message);
3068
+ setBusy(null);
3069
+ }
3070
+ }
3071
+ async function remove() {
3072
+ if (!await confirm({ title: c.confirmRemoveTitle(conn.id), description: c.confirmRemoveText, confirmLabel: c.remove, tone: "danger" })) return;
3073
+ try {
3074
+ await api(`/api/connections/${kind}/${conn.id}`, { method: "DELETE" });
3075
+ toast.success(c.removed);
3076
+ } catch (e) {
3077
+ toast.error(e.message);
3078
+ }
3079
+ await onChanged();
3080
+ }
3081
+ return /* @__PURE__ */ jsx23(Card, { className: "p-4", children: /* @__PURE__ */ jsxs22("div", { className: "flex flex-wrap items-start gap-3", children: [
3082
+ /* @__PURE__ */ jsx23("span", { className: "inline-flex size-10 shrink-0 items-center justify-center rounded-xl bg-brand-soft text-brand", children: /* @__PURE__ */ jsx23(Icon, { className: "size-5", "aria-hidden": true }) }),
3083
+ /* @__PURE__ */ jsxs22("div", { className: "min-w-0 flex-1", style: { minWidth: "14rem" }, children: [
3084
+ /* @__PURE__ */ jsxs22("div", { className: "flex flex-wrap items-center gap-2", children: [
3085
+ /* @__PURE__ */ jsx23("h2", { className: "font-semibold text-fg", children: conn.label }),
3086
+ conn.label !== conn.id && /* @__PURE__ */ jsx23("code", { className: "rounded bg-surface-muted px-1.5 py-0.5 text-xs text-muted", children: conn.id }),
3087
+ /* @__PURE__ */ jsx23(Badge, { tone: statusTone(conn), dot: true, children: conn.status === "missing" && conn.required ? c.required : c.status[conn.status] }),
3088
+ conn.builtIn && /* @__PURE__ */ jsx23(Badge, { children: c.builtIn }),
3089
+ kind === "storage" && configured && conn.id !== "appai-backup" && /* @__PURE__ */ jsx23(Badge, { tone: conn.inBackup ? "ok" : "neutral", children: conn.inBackup ? c.inBackup : c.notInBackup })
3090
+ ] }),
3091
+ conn.purpose && /* @__PURE__ */ jsx23("p", { className: "mt-1 text-sm text-muted", children: conn.purpose }),
3092
+ conn.providerLabel && !conn.builtIn && /* @__PURE__ */ jsxs22("p", { className: "mt-1 text-sm text-fg", children: [
3093
+ conn.providerLabel,
3094
+ typeof conn.config.model === "string" ? ` \xB7 ${conn.config.model}` : ""
3095
+ ] }),
3096
+ conn.problem && /* @__PURE__ */ jsx23("p", { className: "mt-1 text-sm text-warn", children: conn.problem }),
3097
+ conn.lastTest && /* @__PURE__ */ jsxs22("p", { className: `mt-1 break-words text-xs ${conn.lastTest.ok ? "text-muted" : "text-danger"}`, children: [
3098
+ formatDateTime(conn.lastTest.at),
3099
+ ": ",
3100
+ conn.lastTest.message
3101
+ ] }),
3102
+ kind === "storage" && configured && !conn.inBackup && !conn.builtIn && conn.id !== "appai-backup" && /* @__PURE__ */ jsx23("p", { className: "mt-1 text-xs text-muted", children: c.notInBackupHint })
3103
+ ] }),
3104
+ canEdit && !conn.builtIn && /* @__PURE__ */ jsxs22("div", { className: "flex flex-wrap gap-2", children: [
3105
+ oauth && configured && /* @__PURE__ */ jsx23(Button, { size: "sm", variant: conn.problem ? "primary" : "secondary", loading: busy === "connect", onClick: () => void connect(), children: conn.problem ? c.connect : c.reconnect }),
3106
+ configured && /* @__PURE__ */ jsx23(Button, { size: "sm", variant: "secondary", loading: busy === "test", disabled: Boolean(conn.problem), onClick: () => void test(), children: kind === "email" ? c.testEmail : c.test }),
3107
+ /* @__PURE__ */ jsx23(Button, { size: "sm", variant: configured ? "secondary" : "primary", onClick: onEdit, children: configured ? c.edit : c.setUp }),
3108
+ configured && /* @__PURE__ */ jsx23(Button, { size: "sm", variant: "secondary", onClick: () => void remove(), "aria-label": `${c.remove} ${conn.id}`, icon: /* @__PURE__ */ jsx23(Trash24, { className: "size-4", "aria-hidden": true }), children: /* @__PURE__ */ jsx23("span", { className: "sr-only", children: c.remove }) })
3109
+ ] })
3110
+ ] }) });
3111
+ }
3112
+ function UsageCard() {
3113
+ const [usage, setUsage] = useState19(null);
3114
+ useEffect12(() => {
3115
+ let cancelled = false;
3116
+ api("/api/llm/usage").then((r) => !cancelled && setUsage(r.usage)).catch(() => !cancelled && setUsage([]));
3117
+ return () => {
3118
+ cancelled = true;
3119
+ };
3120
+ }, []);
3121
+ if (!usage) return null;
3122
+ return /* @__PURE__ */ jsxs22(Card, { children: [
3123
+ /* @__PURE__ */ jsxs22("div", { className: "border-b border-line px-5 py-4", children: [
3124
+ /* @__PURE__ */ jsx23("h2", { className: "font-semibold text-fg", children: c.usage }),
3125
+ /* @__PURE__ */ jsx23("p", { className: "mt-1 text-sm text-muted", children: c.usageHint })
3126
+ ] }),
3127
+ usage.length === 0 ? /* @__PURE__ */ jsx23("p", { className: "px-5 py-6 text-sm text-muted", children: c.usageEmpty }) : /* @__PURE__ */ jsxs22(Table, { children: [
3128
+ /* @__PURE__ */ jsx23("thead", { children: /* @__PURE__ */ jsxs22("tr", { children: [
3129
+ /* @__PURE__ */ jsx23(TH, { children: c.colDay }),
3130
+ /* @__PURE__ */ jsx23(TH, { children: c.colConnection }),
3131
+ /* @__PURE__ */ jsx23(TH, { children: c.colCalls }),
3132
+ /* @__PURE__ */ jsx23(TH, { children: c.colInput }),
3133
+ /* @__PURE__ */ jsx23(TH, { children: c.colOutput }),
3134
+ /* @__PURE__ */ jsx23(TH, { children: c.colErrors })
3135
+ ] }) }),
3136
+ /* @__PURE__ */ jsx23("tbody", { children: usage.map((u) => /* @__PURE__ */ jsxs22(TR, { children: [
3137
+ /* @__PURE__ */ jsx23(TD, { className: "whitespace-nowrap", children: u.day }),
3138
+ /* @__PURE__ */ jsx23(TD, { children: /* @__PURE__ */ jsx23("code", { className: "text-xs", children: u.connectionId }) }),
3139
+ /* @__PURE__ */ jsx23(TD, { children: u.calls }),
3140
+ /* @__PURE__ */ jsx23(TD, { children: u.inputTokens.toLocaleString() }),
3141
+ /* @__PURE__ */ jsx23(TD, { children: u.outputTokens.toLocaleString() }),
3142
+ /* @__PURE__ */ jsx23(TD, { children: u.errors > 0 ? /* @__PURE__ */ jsx23(Badge, { tone: "danger", children: u.errors }) : 0 })
3143
+ ] }, `${u.day}-${u.connectionId}`)) })
3144
+ ] })
3145
+ ] });
3146
+ }
3147
+ function ConnectionsPage() {
3148
+ const me = useMe();
3149
+ const toast = useToast();
3150
+ const navigate = useNavigate3();
3151
+ const [params] = useSearchParams2();
3152
+ const kinds = KINDS.filter((k) => can(me, `${k}:read`));
3153
+ const [kind, setKind] = useState19(kinds[0] ?? "storage");
3154
+ const [data, setData] = useState19(null);
3155
+ const [error, setError] = useState19(null);
3156
+ const [editing, setEditing] = useState19(null);
3157
+ const load = useCallback9(async () => {
3158
+ try {
3159
+ setData(await api(`/api/connections/${kind}`));
3160
+ setError(null);
3161
+ } catch (e) {
3162
+ setError(e.message);
3163
+ }
3164
+ }, [kind]);
3165
+ useEffect12(() => void load(), [load]);
3166
+ const connected = params.get("connected");
3167
+ const failed = params.get("error");
3168
+ useEffect12(() => {
3169
+ if (!connected && !failed) return;
3170
+ if (connected) toast.success(c.connected(connected));
3171
+ if (failed) toast.error(`${c.signInFailed}: ${failed}`);
3172
+ navigate("/connections", { replace: true });
3173
+ }, [connected, failed, navigate, toast]);
3174
+ if (kinds.length === 0) return /* @__PURE__ */ jsx23(EmptyState, { icon: Plug2, title: c.nothingAvailable });
3175
+ const canEdit = can(me, `${kind}:update`);
3176
+ const canAdd = canEdit && kind !== "email";
3177
+ const blank = () => ({ kind, id: "", label: "", purpose: null, required: false, declared: false, builtIn: false, provider: null, providerLabel: null, config: {}, secretsSet: [], enabled: true, status: "missing", problem: null, lastTest: null, extraFields: [], inBackup: null });
3178
+ return /* @__PURE__ */ jsxs22(Fragment11, { children: [
3179
+ /* @__PURE__ */ jsx23(
3180
+ PageHeader,
3181
+ {
3182
+ title: c.title,
3183
+ description: c.description,
3184
+ actions: canAdd && data ? /* @__PURE__ */ jsx23(Button, { variant: "primary", icon: /* @__PURE__ */ jsx23(Plus4, { className: "size-4", "aria-hidden": true }), onClick: () => setEditing({ conn: blank(), creating: true }), children: c.add }) : void 0
3185
+ }
3186
+ ),
3187
+ kinds.length > 1 && /* @__PURE__ */ jsx23("div", { className: "mb-4", children: /* @__PURE__ */ jsx23(
3188
+ Segmented,
3189
+ {
3190
+ label: c.title,
3191
+ value: kind,
3192
+ onChange: (k) => {
3193
+ setData(null);
3194
+ setKind(k);
3195
+ },
3196
+ options: kinds.map((k) => ({ value: k, label: KIND_TAB[k] }))
3197
+ }
3198
+ ) }),
3199
+ error && /* @__PURE__ */ jsx23(Alert, { kind: "error", className: "mb-4", children: error }),
3200
+ !data ? error ? null : /* @__PURE__ */ jsx23(Spinner, { label: c.loading }) : /* @__PURE__ */ jsxs22("div", { className: "space-y-4", children: [
3201
+ data.connections.length === 0 && /* @__PURE__ */ jsx23(EmptyState, { icon: Plug2, title: c.none, description: c.noneHint, action: canAdd ? /* @__PURE__ */ jsx23(Button, { variant: "primary", onClick: () => setEditing({ conn: blank(), creating: true }), children: c.add }) : void 0 }),
3202
+ data.connections.map((conn) => /* @__PURE__ */ jsx23(ConnectionCard, { kind, conn, providers: data.providers, canEdit, onEdit: () => setEditing({ conn, creating: false }), onChanged: load }, conn.id)),
3203
+ kind === "llm" && /* @__PURE__ */ jsx23(UsageCard, {})
3204
+ ] }),
3205
+ editing && data && /* @__PURE__ */ jsx23(
3206
+ EditDialog,
3207
+ {
3208
+ kind,
3209
+ conn: editing.conn,
3210
+ creating: editing.creating,
3211
+ data,
3212
+ onClose: () => setEditing(null),
3213
+ onSaved: (saved, needsConnect) => {
3214
+ setEditing(null);
3215
+ toast.success(needsConnect && saved.problem ? c.savedConnect : c.saved);
3216
+ void load();
3217
+ }
3218
+ },
3219
+ editing.conn.id || "new"
3220
+ )
3221
+ ] });
3222
+ }
3223
+
3224
+ // src/settings.ts
3225
+ import { useEffect as useEffect13, useState as useState20 } from "react";
3226
+ function useSettingValues() {
3227
+ const [values, setValues] = useState20(null);
3228
+ useEffect13(() => {
3229
+ let cancelled = false;
3230
+ api("/api/settings/values").then((v) => !cancelled && setValues(v)).catch(() => !cancelled && setValues({}));
3231
+ return () => {
3232
+ cancelled = true;
3233
+ };
3234
+ }, []);
3235
+ return values;
3236
+ }
3237
+ export {
3238
+ AcceptInvitationPage,
3239
+ Alert,
3240
+ ApiKeysPage,
3241
+ AppShell,
3242
+ AuditPage,
3243
+ Avatar,
3244
+ Badge,
3245
+ BrandProvider,
3246
+ Button,
3247
+ Card,
3248
+ Checkbox,
3249
+ ColorField,
3250
+ ConfirmProvider,
3251
+ ConnectionsPage,
3252
+ DatePicker,
3253
+ Dialog,
3254
+ EmptyState,
3255
+ Field,
3256
+ FileDrop,
3257
+ ForgotPasswordPage,
3258
+ GroupPicker,
3259
+ GroupsPage,
3260
+ IconButton,
3261
+ Input,
3262
+ LoginPage,
3263
+ Menu,
3264
+ MenuItem,
3265
+ MenuSeparator,
3266
+ NotFoundPage,
3267
+ PageHeader,
3268
+ PeoplePicker,
3269
+ ProgressBar,
3270
+ RequireAuth,
3271
+ ResetPasswordPage,
3272
+ RolesPage,
3273
+ Segmented,
3274
+ Select,
3275
+ SettingsPage,
3276
+ SignupPage,
3277
+ Spinner,
3278
+ StatCard,
3279
+ StatusPage,
3280
+ TD,
3281
+ TH,
3282
+ TR,
3283
+ Table,
3284
+ Textarea,
3285
+ ThemeToggle,
3286
+ ToastProvider,
3287
+ UiProvider,
3288
+ UsersPage,
3289
+ addDays,
3290
+ api,
3291
+ apiForm,
3292
+ authClient,
3293
+ brandCss,
3294
+ buttonClass,
3295
+ can,
3296
+ cn,
3297
+ daysUntil,
3298
+ dueText,
3299
+ formatBytes,
3300
+ formatDate,
3301
+ formatDateLong,
3302
+ formatDateTime,
3303
+ initials,
3304
+ parseDate,
3305
+ timeAgo,
3306
+ toDateString,
3307
+ todayString,
3308
+ useBrand,
3309
+ useConfirm,
3310
+ useMe,
3311
+ useSession,
3312
+ useSetBrand,
3313
+ useSettingValues,
3314
+ useToast
3315
+ };