@rebasepro/studio 0.35.1 → 0.36.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.
Files changed (91) hide show
  1. package/README.md +1 -1
  2. package/dist/{ApiExplorer-C61w8gCc.js → ApiExplorer-BVQHAjHB.js} +3 -2
  3. package/dist/{ApiExplorer-C61w8gCc.js.map → ApiExplorer-BVQHAjHB.js.map} +1 -1
  4. package/dist/{useRunAsUsers-CF7tkGzj.js → AuthSimulationSelector-XogpkeXC.js} +4 -68
  5. package/dist/AuthSimulationSelector-XogpkeXC.js.map +1 -0
  6. package/dist/{CronJobsView-DUuyzkJK.js → CronJobsView-DyX9MINh.js} +2 -2
  7. package/dist/{CronJobsView-DUuyzkJK.js.map → CronJobsView-DyX9MINh.js.map} +1 -1
  8. package/dist/DatabaseView-Bi0NZS90.js +1897 -0
  9. package/dist/DatabaseView-Bi0NZS90.js.map +1 -0
  10. package/dist/{JSEditor-Bi2Aol-Y.js → JSEditor-B4Lazm-z.js} +4 -3
  11. package/dist/{JSEditor-Bi2Aol-Y.js.map → JSEditor-B4Lazm-z.js.map} +1 -1
  12. package/dist/RLSEditor-CcHkWFNg.js +973 -0
  13. package/dist/RLSEditor-CcHkWFNg.js.map +1 -0
  14. package/dist/{SQLEditor-DRo5kW1h.js → SQLEditorRoute-f5j_ZKdj.js} +1472 -320
  15. package/dist/SQLEditorRoute-f5j_ZKdj.js.map +1 -0
  16. package/dist/SchemaDiagramView-CckQobIZ.js +98 -0
  17. package/dist/SchemaDiagramView-CckQobIZ.js.map +1 -0
  18. package/dist/{StorageView-D0D8z4lI.js → StorageView-B7QHjEGY.js} +2 -2
  19. package/dist/{StorageView-D0D8z4lI.js.map → StorageView-B7QHjEGY.js.map} +1 -1
  20. package/dist/TableEditorView-BRZNvD6U.js +3615 -0
  21. package/dist/TableEditorView-BRZNvD6U.js.map +1 -0
  22. package/dist/TablePolicies-C1-tbC8x.js +1740 -0
  23. package/dist/TablePolicies-C1-tbC8x.js.map +1 -0
  24. package/dist/{SchemaVisualizer-Dy4kWKT5.js → TablesDiagram-RTJfwVEN.js} +651 -489
  25. package/dist/TablesDiagram-RTJfwVEN.js.map +1 -0
  26. package/dist/{UsersAndRolesView-CKw4SJPj.js → UsersAndRolesView-Cx6xtMVH.js} +2 -2
  27. package/dist/{UsersAndRolesView-CKw4SJPj.js.map → UsersAndRolesView-Cx6xtMVH.js.map} +1 -1
  28. package/dist/{WebhooksView-CFPY-N9h.js → WebhooksView-Bn9KB7xG.js} +2 -2
  29. package/dist/{WebhooksView-CFPY-N9h.js.map → WebhooksView-Bn9KB7xG.js.map} +1 -1
  30. package/dist/{adminFetch-BfOnfRgU.js → adminFetch-C7Ra8rpP.js} +26 -1
  31. package/dist/{adminFetch-BfOnfRgU.js.map → adminFetch-C7Ra8rpP.js.map} +1 -1
  32. package/dist/components/Database/ActivitySection.d.ts +9 -0
  33. package/dist/components/Database/AdvisorsSection.d.ts +17 -0
  34. package/dist/components/Database/DatabaseView.d.ts +13 -0
  35. package/dist/components/Database/ExtensionsSection.d.ts +2 -0
  36. package/dist/components/Database/FunctionsSection.d.ts +2 -0
  37. package/dist/components/Database/QueriesSection.d.ts +3 -0
  38. package/dist/components/Database/TriggersSection.d.ts +2 -0
  39. package/dist/components/Database/TypesSection.d.ts +2 -0
  40. package/dist/components/Database/format.d.ts +6 -0
  41. package/dist/components/Database/links.d.ts +11 -0
  42. package/dist/components/Database/shared.d.ts +35 -0
  43. package/dist/components/Database/source.d.ts +12 -0
  44. package/dist/components/Database/useCatalogList.d.ts +13 -0
  45. package/dist/components/RLSEditor/RLSEditor.d.ts +2 -0
  46. package/dist/components/RLSEditor/TablePolicies.d.ts +54 -0
  47. package/dist/components/SQLEditor/ExplainVisualizer.d.ts +8 -20
  48. package/dist/components/SQLEditor/ResultChart.d.ts +18 -0
  49. package/dist/components/SQLEditor/SQLEditor.d.ts +13 -1
  50. package/dist/components/SQLEditor/SQLEditorRoute.d.ts +13 -0
  51. package/dist/components/SQLEditor/SQLEditorSidebar.d.ts +7 -1
  52. package/dist/components/SQLEditor/SqlParamsPanel.d.ts +16 -0
  53. package/dist/components/SQLEditor/useSqlSnippets.d.ts +47 -0
  54. package/dist/components/SchemaVisualizer/SchemaDiagramView.d.ts +12 -0
  55. package/dist/components/SchemaVisualizer/TablesDiagram.d.ts +23 -0
  56. package/dist/components/SchemaVisualizer/useSchemaGraph.d.ts +32 -1
  57. package/dist/components/TableEditor/CreateTableDialog.d.ts +8 -0
  58. package/dist/components/TableEditor/DdlConfirm.d.ts +23 -0
  59. package/dist/components/TableEditor/SqlBlock.d.ts +7 -0
  60. package/dist/components/TableEditor/TableDdlSheet.d.ts +9 -0
  61. package/dist/components/TableEditor/TableEditorView.d.ts +7 -0
  62. package/dist/components/TableEditor/tableModel.d.ts +210 -0
  63. package/dist/components/TableEditor/tabs/DataTab.d.ts +12 -0
  64. package/dist/components/TableEditor/tabs/PoliciesTab.d.ts +8 -0
  65. package/dist/components/TableEditor/tabs/RelationsTab.d.ts +8 -0
  66. package/dist/components/TableEditor/tabs/SettingsTab.d.ts +11 -0
  67. package/dist/components/TableEditor/tabs/StatsTab.d.ts +8 -0
  68. package/dist/components/TableEditor/tabs/StructureTab.d.ts +12 -0
  69. package/dist/index.es.js +29 -15
  70. package/dist/index.es.js.map +1 -1
  71. package/dist/{sql_utils-CYcgpgam.js → sql_utils-DkMYltfq.js} +27 -3
  72. package/dist/sql_utils-DkMYltfq.js.map +1 -0
  73. package/dist/useRunAsUsers-GPFCxcBC.js +69 -0
  74. package/dist/useRunAsUsers-GPFCxcBC.js.map +1 -0
  75. package/dist/utils/adminFetch.d.ts +1 -0
  76. package/dist/utils/csv_parse.d.ts +11 -0
  77. package/dist/utils/explain_plan.d.ts +70 -0
  78. package/dist/utils/sql_params.d.ts +51 -0
  79. package/dist/utils/sql_utils.d.ts +16 -0
  80. package/package.json +11 -9
  81. package/dist/RLSEditor-CTG3jLE7.js +0 -2572
  82. package/dist/RLSEditor-CTG3jLE7.js.map +0 -1
  83. package/dist/SQLEditor-DRo5kW1h.js.map +0 -1
  84. package/dist/SchemaVisualizer-Dy4kWKT5.js.map +0 -1
  85. package/dist/TableEditorView-BKhSBG-K.js +0 -1694
  86. package/dist/TableEditorView-BKhSBG-K.js.map +0 -1
  87. package/dist/components/SchemaVisualizer/SchemaVisualizer.d.ts +0 -3
  88. package/dist/policy-presets-CJKzAvQp.js +0 -167
  89. package/dist/policy-presets-CJKzAvQp.js.map +0 -1
  90. package/dist/sql_utils-CYcgpgam.js.map +0 -1
  91. package/dist/useRunAsUsers-CF7tkGzj.js.map +0 -1
@@ -0,0 +1,1897 @@
1
+ import { a as asStringArray, i as asString, n as asNullableString, o as isRecord, r as asNumber, s as useAdminFetch, t as asBoolean } from "./adminFetch-C7Ra8rpP.js";
2
+ import { useSnackbarController, useTranslation } from "@rebasepro/app";
3
+ import React, { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
4
+ import { ActivityIcon, Alert, Button, CheckCircle2Icon, Checkbox, Chip, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, ExternalLinkIcon, FunctionSquareIcon, GaugeIcon, IconButton, Label, LockIcon, PauseIcon, PlayIcon, PlusIcon, PowerIcon, PuzzleIcon, RefreshCwIcon, SearchBar, Select, SelectItem, ServerCogIcon, ShapesIcon, ShieldAlertIcon, StatusDot, Tab, Table, TableBody, TableCell, TableHeader, TableIcon, TableRow, Tabs, TerminalIcon, TextField, Tooltip, Trash2Icon, Typography, XCircleIcon, ZapIcon, cls, defaultBorderMixin, iconSize } from "@rebasepro/ui";
5
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
+ import { useNavigate, useSearchParams } from "react-router";
7
+ import { DEFAULT_DATA_SOURCE_KEY } from "@rebasepro/types";
8
+ //#region src/components/Database/format.ts
9
+ /** Bytes as the largest unit that keeps the number above one: `12.4 MB`. */
10
+ function formatBytes(bytes, locale) {
11
+ const units = [
12
+ "B",
13
+ "kB",
14
+ "MB",
15
+ "GB",
16
+ "TB"
17
+ ];
18
+ let value = bytes;
19
+ let unit = 0;
20
+ while (value >= 1024 && unit < units.length - 1) {
21
+ value /= 1024;
22
+ unit++;
23
+ }
24
+ const digits = unit === 0 || value >= 100 ? 0 : 1;
25
+ return `${new Intl.NumberFormat(locale, { maximumFractionDigits: digits }).format(value)} ${units[unit]}`;
26
+ }
27
+ /** Milliseconds as `840 ms`, `12.3 s`, `4 min 2 s` or `3 h 5 min`. */
28
+ function formatDuration(ms, locale) {
29
+ const number = (value, digits) => new Intl.NumberFormat(locale, { maximumFractionDigits: digits }).format(value);
30
+ if (ms < 1e3) return `${number(ms, ms < 10 ? 2 : ms < 100 ? 1 : 0)} ms`;
31
+ const seconds = ms / 1e3;
32
+ if (seconds < 60) return `${number(seconds, 1)} s`;
33
+ const minutes = Math.floor(seconds / 60);
34
+ if (minutes < 60) return `${minutes} min ${Math.floor(seconds % 60)} s`;
35
+ return `${Math.floor(minutes / 60)} h ${minutes % 60} min`;
36
+ }
37
+ /** A count with the locale's grouping: `12,345`. */
38
+ function formatCount(value, locale) {
39
+ return new Intl.NumberFormat(locale).format(value);
40
+ }
41
+ //#endregion
42
+ //#region src/components/Database/source.tsx
43
+ /** The key the default database answers to; an absent `?source=` means it. */
44
+ var DEFAULT_SOURCE = DEFAULT_DATA_SOURCE_KEY;
45
+ /** `path` with `?source=` for a database other than the default. */
46
+ function withSource(path, source) {
47
+ if (!source || source === DEFAULT_SOURCE) return path;
48
+ return `${path}${path.includes("?") ? "&" : "?"}source=${encodeURIComponent(source)}`;
49
+ }
50
+ var DatabaseSourceContext = React.createContext(DEFAULT_SOURCE);
51
+ /** The database the Database view is showing, for every section under it. */
52
+ function DatabaseSourceProvider({ source, children }) {
53
+ return /* @__PURE__ */ jsx(DatabaseSourceContext.Provider, {
54
+ value: source,
55
+ children
56
+ });
57
+ }
58
+ /** Builds an admin path for the database the view is showing. */
59
+ function useSourcePath() {
60
+ const source = useContext(DatabaseSourceContext);
61
+ return useCallback((path) => withSource(path, source), [source]);
62
+ }
63
+ //#endregion
64
+ //#region src/components/Database/links.ts
65
+ /**
66
+ * Links from the Database view into the other Studio tools.
67
+ *
68
+ * These two URLs are the contract between Studio views: the SQL editor reads
69
+ * `sqlDraft` into a new tab, and the Tables view opens the table `table`
70
+ * names (`schema.table`).
71
+ */
72
+ /** The SQL editor, with `sql` as a draft to review and run. */
73
+ function sqlDraftLink(sql) {
74
+ return `/sql?sqlDraft=${encodeURIComponent(sql)}`;
75
+ }
76
+ /** The Tables view, opened on `schemaTable` (`public.posts`). */
77
+ function tableLink(schemaTable) {
78
+ return `/tables?table=${encodeURIComponent(schemaTable)}`;
79
+ }
80
+ //#endregion
81
+ //#region src/components/Database/shared.tsx
82
+ /** A section's heading row: title, one line on what it shows, and its controls. */
83
+ function SectionHeader({ title, description, actions }) {
84
+ return /* @__PURE__ */ jsxs("div", {
85
+ className: "flex items-start justify-between gap-4 flex-wrap",
86
+ children: [/* @__PURE__ */ jsxs("div", {
87
+ className: "min-w-0",
88
+ children: [/* @__PURE__ */ jsx(Typography, {
89
+ variant: "subtitle1",
90
+ children: title
91
+ }), description && /* @__PURE__ */ jsx(Typography, {
92
+ variant: "caption",
93
+ color: "secondary",
94
+ className: "block",
95
+ children: description
96
+ })]
97
+ }), actions && /* @__PURE__ */ jsx("div", {
98
+ className: "flex items-center gap-2 shrink-0",
99
+ children: actions
100
+ })]
101
+ });
102
+ }
103
+ /** SQL to read: an inset well in the monospace face. */
104
+ function SqlBlock({ sql, className }) {
105
+ return /* @__PURE__ */ jsx(Typography, {
106
+ variant: "mono",
107
+ component: "pre",
108
+ className: cls("bg-surface-field rounded-md p-3 text-xs whitespace-pre-wrap break-words overflow-auto max-h-80", className),
109
+ children: sql
110
+ });
111
+ }
112
+ /** The canonical empty state: a centred message, and an icon above it. */
113
+ function EmptyState({ icon, message }) {
114
+ return /* @__PURE__ */ jsxs("div", {
115
+ className: "flex flex-col items-center justify-center gap-3 py-12 text-center",
116
+ children: [icon && /* @__PURE__ */ jsx("div", {
117
+ className: "text-text-disabled dark:text-text-disabled-dark",
118
+ children: icon
119
+ }), /* @__PURE__ */ jsx(Typography, {
120
+ variant: "label",
121
+ className: "px-4",
122
+ children: message
123
+ })]
124
+ });
125
+ }
126
+ function LoadingRow() {
127
+ return /* @__PURE__ */ jsx("div", {
128
+ className: "flex justify-center py-12",
129
+ children: /* @__PURE__ */ jsx(CircularProgress, { size: "small" })
130
+ });
131
+ }
132
+ /**
133
+ * A destructive action, confirmed against the SQL it runs.
134
+ *
135
+ * The statements shown are the server's own preview of the request, so what
136
+ * the reader confirms is what the server will execute.
137
+ */
138
+ function useConfirmSql() {
139
+ const { t } = useTranslation();
140
+ const [request, setRequest] = useState(null);
141
+ const [statements, setStatements] = useState(null);
142
+ const [error, setError] = useState(null);
143
+ const [running, setRunning] = useState(false);
144
+ const ask = useCallback((next) => {
145
+ setRequest(next);
146
+ setStatements(null);
147
+ setError(null);
148
+ next.preview().then(setStatements, (err) => {
149
+ setError(err instanceof Error ? err.message : String(err));
150
+ });
151
+ }, []);
152
+ const close = () => {
153
+ if (running) return;
154
+ setRequest(null);
155
+ };
156
+ const confirm = async () => {
157
+ if (!request) return;
158
+ setRunning(true);
159
+ setError(null);
160
+ try {
161
+ await request.run();
162
+ setRequest(null);
163
+ } catch (err) {
164
+ setError(err instanceof Error ? err.message : String(err));
165
+ } finally {
166
+ setRunning(false);
167
+ }
168
+ };
169
+ return [/* @__PURE__ */ jsxs(Dialog, {
170
+ open: request !== null,
171
+ onOpenChange: (open) => {
172
+ if (!open) close();
173
+ },
174
+ maxWidth: "lg",
175
+ fullWidth: true,
176
+ children: [
177
+ /* @__PURE__ */ jsx(DialogTitle, { children: request?.title }),
178
+ /* @__PURE__ */ jsxs(DialogContent, {
179
+ className: "flex flex-col gap-3",
180
+ children: [
181
+ typeof request?.body === "string" ? /* @__PURE__ */ jsx(Typography, {
182
+ variant: "body2",
183
+ children: request.body
184
+ }) : request?.body,
185
+ /* @__PURE__ */ jsx(Typography, {
186
+ variant: "caption",
187
+ color: "secondary",
188
+ children: t("studio_database_confirm_sql_label")
189
+ }),
190
+ statements ? /* @__PURE__ */ jsx(SqlBlock, { sql: statements.join("\n") }) : !error && /* @__PURE__ */ jsx(LoadingRow, {}),
191
+ error && /* @__PURE__ */ jsx(Alert, {
192
+ color: "error",
193
+ children: error
194
+ })
195
+ ]
196
+ }),
197
+ /* @__PURE__ */ jsxs(DialogActions, { children: [/* @__PURE__ */ jsx(Button, {
198
+ variant: "text",
199
+ onClick: close,
200
+ disabled: running,
201
+ children: t("cancel")
202
+ }), /* @__PURE__ */ jsxs(Button, {
203
+ variant: "filled",
204
+ color: "error",
205
+ disabled: running || statements === null,
206
+ onClick: () => void confirm(),
207
+ children: [running ? /* @__PURE__ */ jsx(CircularProgress, { size: "smallest" }) : null, request?.confirmLabel]
208
+ })] })
209
+ ]
210
+ }), ask];
211
+ }
212
+ /** The statements a mutation response carries — what a `dryRun` previews. */
213
+ function statementsOf(raw) {
214
+ if (typeof raw === "object" && raw !== null && "statements" in raw && Array.isArray(raw.statements)) return raw.statements.filter((statement) => typeof statement === "string");
215
+ return [];
216
+ }
217
+ //#endregion
218
+ //#region src/components/Database/AdvisorsSection.tsx
219
+ var SEVERITIES = [
220
+ "critical",
221
+ "high",
222
+ "medium",
223
+ "low",
224
+ "info"
225
+ ];
226
+ var isSeverity = (value) => typeof value === "string" && SEVERITIES.some((severity) => severity === value);
227
+ /** The tint a severity reads in: information, not decoration. */
228
+ var SEVERITY_CHIP = {
229
+ critical: "redLight",
230
+ high: "orangeLight",
231
+ medium: "yellowLight",
232
+ low: "blueLight",
233
+ info: "grayLight"
234
+ };
235
+ function parseFinding(raw) {
236
+ if (!isRecord(raw) || typeof raw.id !== "string" || typeof raw.title !== "string") return null;
237
+ const category = raw.category === "security" ? "security" : raw.category === "performance" ? "performance" : null;
238
+ if (!category || !isSeverity(raw.severity)) return null;
239
+ return {
240
+ id: raw.id,
241
+ check: asString(raw.check),
242
+ category,
243
+ severity: raw.severity,
244
+ title: raw.title,
245
+ detail: asString(raw.detail),
246
+ ...typeof raw.table === "string" ? { table: raw.table } : {},
247
+ ...typeof raw.remediationSql === "string" ? { remediationSql: raw.remediationSql } : {},
248
+ ...typeof raw.docs === "string" ? { docs: raw.docs } : {}
249
+ };
250
+ }
251
+ function AdvisorsSection({ onCount }) {
252
+ const { t } = useTranslation();
253
+ const navigate = useNavigate();
254
+ const { requestJson } = useAdminFetch();
255
+ const sourcePath = useSourcePath();
256
+ const [findings, setFindings] = useState(null);
257
+ const [errors, setErrors] = useState([]);
258
+ const [degraded, setDegraded] = useState([]);
259
+ const [error, setError] = useState(null);
260
+ const [loading, setLoading] = useState(true);
261
+ const [filter, setFilter] = useState("all");
262
+ const [open, setOpen] = useState(null);
263
+ const load = useCallback(async () => {
264
+ setLoading(true);
265
+ setError(null);
266
+ try {
267
+ const raw = await requestJson(sourcePath("/admin/db/insights/advisors"));
268
+ const parsed = (isRecord(raw) && Array.isArray(raw.findings) ? raw.findings : []).map(parseFinding).filter((finding) => finding !== null);
269
+ setFindings(parsed);
270
+ onCount?.(parsed.filter((finding) => finding.severity !== "info").length);
271
+ setErrors(isRecord(raw) && Array.isArray(raw.errors) ? raw.errors.filter(isRecord).map((entry) => ({
272
+ category: asString(entry.category),
273
+ message: asString(entry.message)
274
+ })) : []);
275
+ setDegraded(isRecord(raw) ? asStringArray(raw.degraded) : []);
276
+ } catch (err) {
277
+ setError(err instanceof Error ? err.message : t("studio_database_load_failed"));
278
+ } finally {
279
+ setLoading(false);
280
+ }
281
+ }, [
282
+ requestJson,
283
+ sourcePath,
284
+ onCount,
285
+ t
286
+ ]);
287
+ useEffect(() => {
288
+ load();
289
+ }, [load]);
290
+ const counts = useMemo(() => ({
291
+ all: findings?.length ?? 0,
292
+ security: findings?.filter((finding) => finding.category === "security").length ?? 0,
293
+ performance: findings?.filter((finding) => finding.category === "performance").length ?? 0
294
+ }), [findings]);
295
+ const shown = (findings ?? []).filter((finding) => filter === "all" || finding.category === filter);
296
+ return /* @__PURE__ */ jsxs("div", {
297
+ className: "flex flex-col gap-4",
298
+ children: [
299
+ /* @__PURE__ */ jsx(SectionHeader, {
300
+ title: t("studio_database_section_advisors"),
301
+ description: t("studio_database_advisors_description"),
302
+ actions: /* @__PURE__ */ jsx(Tooltip, {
303
+ title: t("refresh"),
304
+ children: /* @__PURE__ */ jsx(IconButton, {
305
+ size: "small",
306
+ "aria-label": t("studio_database_refresh_aria"),
307
+ onClick: () => void load(),
308
+ children: /* @__PURE__ */ jsx(RefreshCwIcon, { size: iconSize.small })
309
+ })
310
+ })
311
+ }),
312
+ /* @__PURE__ */ jsxs(Tabs, {
313
+ value: filter,
314
+ onValueChange: (value) => setFilter(value === "security" || value === "performance" ? value : "all"),
315
+ variant: "pill",
316
+ children: [
317
+ /* @__PURE__ */ jsx(Tab, {
318
+ value: "all",
319
+ children: t("studio_database_advisors_all", { count: counts.all })
320
+ }),
321
+ /* @__PURE__ */ jsx(Tab, {
322
+ value: "security",
323
+ children: t("studio_database_advisors_security", { count: counts.security })
324
+ }),
325
+ /* @__PURE__ */ jsx(Tab, {
326
+ value: "performance",
327
+ children: t("studio_database_advisors_performance", { count: counts.performance })
328
+ })
329
+ ]
330
+ }),
331
+ error && /* @__PURE__ */ jsx(Alert, {
332
+ color: "error",
333
+ children: error
334
+ }),
335
+ errors.map((entry) => /* @__PURE__ */ jsx(Alert, {
336
+ color: "warning",
337
+ children: t(entry.category === "security" ? "studio_database_advisors_security_failed" : "studio_database_advisors_performance_failed", { message: entry.message })
338
+ }, entry.category)),
339
+ degraded.length > 0 && /* @__PURE__ */ jsx(Alert, {
340
+ color: "info",
341
+ children: t("studio_database_advisors_degraded", { what: degraded.join(", ") })
342
+ }),
343
+ loading && findings === null ? /* @__PURE__ */ jsx(LoadingRow, {}) : shown.length === 0 ? /* @__PURE__ */ jsx(EmptyState, {
344
+ icon: /* @__PURE__ */ jsx(CheckCircle2Icon, { size: iconSize.large }),
345
+ message: t("studio_database_advisors_empty")
346
+ }) : /* @__PURE__ */ jsx("div", {
347
+ className: cls("rounded-lg border divide-y divide-hairline overflow-hidden", defaultBorderMixin),
348
+ children: shown.map((finding) => {
349
+ const expanded = open === finding.id;
350
+ return /* @__PURE__ */ jsxs("div", {
351
+ className: "flex flex-col gap-2 px-4 py-3",
352
+ children: [/* @__PURE__ */ jsxs("div", {
353
+ className: "flex items-start gap-3",
354
+ children: [
355
+ /* @__PURE__ */ jsx(Chip, {
356
+ size: "smallest",
357
+ colorScheme: SEVERITY_CHIP[finding.severity],
358
+ children: t(`studio_database_severity_${finding.severity}`)
359
+ }),
360
+ /* @__PURE__ */ jsxs("div", {
361
+ className: "min-w-0 flex-1 flex flex-col gap-1",
362
+ children: [/* @__PURE__ */ jsx(Typography, {
363
+ variant: "body2",
364
+ className: "font-medium",
365
+ children: finding.title
366
+ }), /* @__PURE__ */ jsxs(Typography, {
367
+ variant: "caption",
368
+ color: "secondary",
369
+ children: [
370
+ t(finding.category === "security" ? "studio_database_category_security" : "studio_database_category_performance"),
371
+ " · ",
372
+ /* @__PURE__ */ jsx("span", {
373
+ className: "font-mono",
374
+ children: finding.check
375
+ })
376
+ ]
377
+ })]
378
+ }),
379
+ /* @__PURE__ */ jsx(Button, {
380
+ size: "small",
381
+ variant: "text",
382
+ onClick: () => setOpen(expanded ? null : finding.id),
383
+ children: expanded ? t("studio_database_hide_details") : t("studio_database_show_details")
384
+ })
385
+ ]
386
+ }), expanded && /* @__PURE__ */ jsxs("div", {
387
+ className: "flex flex-col gap-3 pl-1",
388
+ children: [
389
+ /* @__PURE__ */ jsx(Typography, {
390
+ variant: "body2",
391
+ color: "secondary",
392
+ children: finding.detail
393
+ }),
394
+ finding.remediationSql && /* @__PURE__ */ jsx(SqlBlock, { sql: finding.remediationSql }),
395
+ /* @__PURE__ */ jsxs("div", {
396
+ className: "flex items-center gap-2 flex-wrap",
397
+ children: [
398
+ finding.remediationSql && /* @__PURE__ */ jsxs(Button, {
399
+ size: "small",
400
+ onClick: () => navigate(sqlDraftLink(finding.remediationSql ?? "")),
401
+ children: [/* @__PURE__ */ jsx(TerminalIcon, { size: iconSize.smallest }), t("studio_database_open_in_sql")]
402
+ }),
403
+ finding.table && /* @__PURE__ */ jsxs(Button, {
404
+ size: "small",
405
+ variant: "text",
406
+ onClick: () => navigate(tableLink(finding.table ?? "")),
407
+ children: [/* @__PURE__ */ jsx(TableIcon, { size: iconSize.smallest }), t("studio_database_open_table", { table: finding.table })]
408
+ }),
409
+ finding.docs && /* @__PURE__ */ jsxs(Button, {
410
+ size: "small",
411
+ variant: "text",
412
+ component: "a",
413
+ href: finding.docs,
414
+ target: "_blank",
415
+ rel: "noreferrer",
416
+ children: [/* @__PURE__ */ jsx(ExternalLinkIcon, { size: iconSize.smallest }), t("studio_database_docs")]
417
+ })
418
+ ]
419
+ })
420
+ ]
421
+ })]
422
+ }, finding.id);
423
+ })
424
+ })
425
+ ]
426
+ });
427
+ }
428
+ //#endregion
429
+ //#region src/components/Database/QueriesSection.tsx
430
+ function parseStatus(value) {
431
+ return value === "ok" || value === "not_installed" || value === "not_preloaded" ? value : "unavailable";
432
+ }
433
+ function QueriesSection() {
434
+ const { t, i18n } = useTranslation();
435
+ const navigate = useNavigate();
436
+ const snackbar = useSnackbarController();
437
+ const { requestJson } = useAdminFetch();
438
+ const sourcePath = useSourcePath();
439
+ const [sort, setSort] = useState("total");
440
+ const [status, setStatus] = useState(null);
441
+ const [available, setAvailable] = useState(false);
442
+ const [queries, setQueries] = useState([]);
443
+ const [error, setError] = useState(null);
444
+ const [loading, setLoading] = useState(true);
445
+ const [installing, setInstalling] = useState(false);
446
+ const [confirmDialog, confirm] = useConfirmSql();
447
+ const load = useCallback(async () => {
448
+ setLoading(true);
449
+ setError(null);
450
+ try {
451
+ const raw = await requestJson(sourcePath(`/admin/db/insights/queries?sort=${sort}`));
452
+ if (!isRecord(raw)) throw new Error(t("studio_database_load_failed"));
453
+ setStatus(parseStatus(raw.status));
454
+ setAvailable(asBoolean(raw.available));
455
+ setQueries(Array.isArray(raw.queries) ? raw.queries.filter(isRecord).map((row) => ({
456
+ queryId: asString(row.queryId),
457
+ query: asString(row.query),
458
+ calls: asNumber(row.calls),
459
+ totalMs: asNumber(row.totalMs),
460
+ meanMs: asNumber(row.meanMs),
461
+ maxMs: asNumber(row.maxMs),
462
+ rows: asNumber(row.rows)
463
+ })) : []);
464
+ } catch (err) {
465
+ setError(err instanceof Error ? err.message : t("studio_database_load_failed"));
466
+ } finally {
467
+ setLoading(false);
468
+ }
469
+ }, [
470
+ requestJson,
471
+ sourcePath,
472
+ sort,
473
+ t
474
+ ]);
475
+ useEffect(() => {
476
+ load();
477
+ }, [load]);
478
+ const install = async () => {
479
+ setInstalling(true);
480
+ try {
481
+ await requestJson(sourcePath("/admin/db/catalog/extensions/pg_stat_statements"), {
482
+ method: "POST",
483
+ body: {}
484
+ });
485
+ await load();
486
+ } catch (err) {
487
+ snackbar.open({
488
+ type: "error",
489
+ message: err instanceof Error ? err.message : t("studio_database_action_failed")
490
+ });
491
+ } finally {
492
+ setInstalling(false);
493
+ }
494
+ };
495
+ const askReset = () => confirm({
496
+ title: t("studio_database_queries_reset_title"),
497
+ body: t("studio_database_queries_reset_body"),
498
+ confirmLabel: t("studio_database_queries_reset"),
499
+ preview: async () => statementsOf(await requestJson(sourcePath("/admin/db/insights/queries/reset"), {
500
+ method: "POST",
501
+ body: { dryRun: true }
502
+ })),
503
+ run: async () => {
504
+ await requestJson(sourcePath("/admin/db/insights/queries/reset"), {
505
+ method: "POST",
506
+ body: {}
507
+ });
508
+ snackbar.open({
509
+ type: "success",
510
+ message: t("studio_database_queries_reset_done")
511
+ });
512
+ await load();
513
+ }
514
+ });
515
+ const locale = i18n.language;
516
+ return /* @__PURE__ */ jsxs("div", {
517
+ className: "flex flex-col gap-4",
518
+ children: [
519
+ /* @__PURE__ */ jsx(SectionHeader, {
520
+ title: t("studio_database_section_queries"),
521
+ description: t("studio_database_queries_description"),
522
+ actions: /* @__PURE__ */ jsxs(Fragment, { children: [
523
+ /* @__PURE__ */ jsxs(Select, {
524
+ size: "small",
525
+ value: sort,
526
+ onValueChange: (value) => setSort(value === "mean" || value === "calls" ? value : "total"),
527
+ label: t("studio_database_queries_sort"),
528
+ labelPlacement: "above",
529
+ children: [
530
+ /* @__PURE__ */ jsx(SelectItem, {
531
+ value: "total",
532
+ children: t("studio_database_queries_sort_total")
533
+ }),
534
+ /* @__PURE__ */ jsx(SelectItem, {
535
+ value: "mean",
536
+ children: t("studio_database_queries_sort_mean")
537
+ }),
538
+ /* @__PURE__ */ jsx(SelectItem, {
539
+ value: "calls",
540
+ children: t("studio_database_queries_sort_calls")
541
+ })
542
+ ]
543
+ }),
544
+ status === "ok" && /* @__PURE__ */ jsx(Button, {
545
+ size: "small",
546
+ onClick: askReset,
547
+ children: t("studio_database_queries_reset")
548
+ }),
549
+ /* @__PURE__ */ jsx(Tooltip, {
550
+ title: t("refresh"),
551
+ children: /* @__PURE__ */ jsx(IconButton, {
552
+ size: "small",
553
+ "aria-label": t("studio_database_refresh_aria"),
554
+ onClick: () => void load(),
555
+ children: /* @__PURE__ */ jsx(RefreshCwIcon, { size: iconSize.small })
556
+ })
557
+ })
558
+ ] })
559
+ }),
560
+ error && /* @__PURE__ */ jsx(Alert, {
561
+ color: "error",
562
+ children: error
563
+ }),
564
+ status === "unavailable" && /* @__PURE__ */ jsx(Alert, {
565
+ color: "info",
566
+ children: t("studio_database_queries_unavailable")
567
+ }),
568
+ status === "not_preloaded" && /* @__PURE__ */ jsx(Alert, {
569
+ color: "warning",
570
+ children: t("studio_database_queries_not_preloaded")
571
+ }),
572
+ status === "not_installed" && /* @__PURE__ */ jsx(Alert, {
573
+ color: "info",
574
+ children: /* @__PURE__ */ jsxs("div", {
575
+ className: "flex items-center justify-between gap-3 flex-wrap",
576
+ children: [/* @__PURE__ */ jsx(Typography, {
577
+ variant: "body2",
578
+ children: available ? t("studio_database_queries_not_installed") : t("studio_database_queries_not_available")
579
+ }), available && /* @__PURE__ */ jsx(Button, {
580
+ size: "small",
581
+ disabled: installing,
582
+ onClick: () => void install(),
583
+ children: t("studio_database_queries_install")
584
+ })]
585
+ })
586
+ }),
587
+ loading && status === null ? /* @__PURE__ */ jsx(LoadingRow, {}) : status === "ok" && (queries.length === 0 ? /* @__PURE__ */ jsx(EmptyState, {
588
+ icon: /* @__PURE__ */ jsx(GaugeIcon, { size: iconSize.large }),
589
+ message: t("studio_database_queries_empty")
590
+ }) : /* @__PURE__ */ jsx("div", {
591
+ className: cls("overflow-x-auto rounded-lg border", defaultBorderMixin),
592
+ children: /* @__PURE__ */ jsxs(Table, {
593
+ className: "w-full",
594
+ children: [/* @__PURE__ */ jsxs(TableHeader, { children: [
595
+ /* @__PURE__ */ jsx(TableCell, {
596
+ header: true,
597
+ children: t("studio_database_queries_query")
598
+ }),
599
+ /* @__PURE__ */ jsx(TableCell, {
600
+ header: true,
601
+ className: "text-right",
602
+ children: t("studio_database_queries_calls")
603
+ }),
604
+ /* @__PURE__ */ jsx(TableCell, {
605
+ header: true,
606
+ className: "text-right",
607
+ children: t("studio_database_queries_total")
608
+ }),
609
+ /* @__PURE__ */ jsx(TableCell, {
610
+ header: true,
611
+ className: "text-right",
612
+ children: t("studio_database_queries_mean")
613
+ }),
614
+ /* @__PURE__ */ jsx(TableCell, {
615
+ header: true,
616
+ className: "text-right",
617
+ children: t("studio_database_queries_max")
618
+ }),
619
+ /* @__PURE__ */ jsx(TableCell, {
620
+ header: true,
621
+ className: "text-right",
622
+ children: t("studio_database_queries_rows")
623
+ }),
624
+ /* @__PURE__ */ jsx(TableCell, {
625
+ header: true,
626
+ className: "text-right",
627
+ children: t("actions")
628
+ })
629
+ ] }), /* @__PURE__ */ jsx(TableBody, { children: queries.map((query) => /* @__PURE__ */ jsxs(TableRow, { children: [
630
+ /* @__PURE__ */ jsx(TableCell, {
631
+ className: "max-w-xl",
632
+ children: /* @__PURE__ */ jsx(Typography, {
633
+ variant: "mono",
634
+ className: "text-xs line-clamp-2 break-all",
635
+ children: query.query
636
+ })
637
+ }),
638
+ /* @__PURE__ */ jsx(TableCell, {
639
+ className: "text-right tabular-nums whitespace-nowrap",
640
+ children: formatCount(query.calls, locale)
641
+ }),
642
+ /* @__PURE__ */ jsx(TableCell, {
643
+ className: "text-right tabular-nums whitespace-nowrap",
644
+ children: formatDuration(query.totalMs, locale)
645
+ }),
646
+ /* @__PURE__ */ jsx(TableCell, {
647
+ className: "text-right tabular-nums whitespace-nowrap",
648
+ children: formatDuration(query.meanMs, locale)
649
+ }),
650
+ /* @__PURE__ */ jsx(TableCell, {
651
+ className: "text-right tabular-nums whitespace-nowrap",
652
+ children: formatDuration(query.maxMs, locale)
653
+ }),
654
+ /* @__PURE__ */ jsx(TableCell, {
655
+ className: "text-right tabular-nums whitespace-nowrap",
656
+ children: formatCount(query.rows, locale)
657
+ }),
658
+ /* @__PURE__ */ jsx(TableCell, {
659
+ className: "text-right",
660
+ children: /* @__PURE__ */ jsx(Tooltip, {
661
+ title: t("studio_database_open_in_sql"),
662
+ children: /* @__PURE__ */ jsx(IconButton, {
663
+ size: "small",
664
+ "aria-label": t("studio_database_open_in_sql"),
665
+ onClick: () => navigate(sqlDraftLink(query.query)),
666
+ children: /* @__PURE__ */ jsx(TerminalIcon, { size: iconSize.small })
667
+ })
668
+ })
669
+ })
670
+ ] }, query.queryId || query.query)) })]
671
+ })
672
+ })),
673
+ confirmDialog
674
+ ]
675
+ });
676
+ }
677
+ //#endregion
678
+ //#region src/components/Database/ActivitySection.tsx
679
+ /** How often the session list is re-read while it is on screen. */
680
+ var ACTIVITY_REFRESH_MS = 5e3;
681
+ function parseSession(raw) {
682
+ if (!isRecord(raw) || typeof raw.pid !== "number") return null;
683
+ return {
684
+ pid: raw.pid,
685
+ username: asNullableString(raw.username),
686
+ applicationName: asString(raw.applicationName),
687
+ state: asNullableString(raw.state),
688
+ waitEventType: asNullableString(raw.waitEventType),
689
+ waitEvent: asNullableString(raw.waitEvent),
690
+ query: asString(raw.query),
691
+ durationMs: asNumber(raw.durationMs),
692
+ blockedBy: Array.isArray(raw.blockedBy) ? raw.blockedBy.filter((pid) => typeof pid === "number") : []
693
+ };
694
+ }
695
+ /**
696
+ * The database's sessions that are doing something, re-read every five
697
+ * seconds while this section is mounted and the page is visible — telemetry,
698
+ * which has no realtime feed to subscribe to — unless the reader pauses it.
699
+ */
700
+ function ActivitySection() {
701
+ const { t, i18n } = useTranslation();
702
+ const snackbar = useSnackbarController();
703
+ const { requestJson } = useAdminFetch();
704
+ const sourcePath = useSourcePath();
705
+ const [sessions, setSessions] = useState(null);
706
+ const [error, setError] = useState(null);
707
+ const [paused, setPaused] = useState(false);
708
+ const [pageVisible, setPageVisible] = useState(() => typeof document === "undefined" || document.visibilityState !== "hidden");
709
+ const [confirmDialog, confirm] = useConfirmSql();
710
+ const inFlight = useRef(false);
711
+ const load = useCallback(async () => {
712
+ if (inFlight.current) return;
713
+ inFlight.current = true;
714
+ try {
715
+ const raw = await requestJson(sourcePath("/admin/db/insights/activity"));
716
+ const list = isRecord(raw) && Array.isArray(raw.sessions) ? raw.sessions : [];
717
+ setSessions(list.map(parseSession).filter((session) => session !== null));
718
+ setError(null);
719
+ } catch (err) {
720
+ setError(err instanceof Error ? err.message : t("studio_database_load_failed"));
721
+ } finally {
722
+ inFlight.current = false;
723
+ }
724
+ }, [
725
+ requestJson,
726
+ sourcePath,
727
+ t
728
+ ]);
729
+ useEffect(() => {
730
+ const onVisibility = () => setPageVisible(document.visibilityState !== "hidden");
731
+ document.addEventListener("visibilitychange", onVisibility);
732
+ return () => document.removeEventListener("visibilitychange", onVisibility);
733
+ }, []);
734
+ useEffect(() => {
735
+ load();
736
+ if (paused || !pageVisible) return void 0;
737
+ const timer = setInterval(() => void load(), ACTIVITY_REFRESH_MS);
738
+ return () => clearInterval(timer);
739
+ }, [
740
+ load,
741
+ paused,
742
+ pageVisible
743
+ ]);
744
+ const cancel = async (session) => {
745
+ try {
746
+ const raw = await requestJson(sourcePath(`/admin/db/insights/activity/${session.pid}/cancel`), {
747
+ method: "POST",
748
+ body: {}
749
+ });
750
+ const signalled = isRecord(raw) && raw.signalled === true;
751
+ snackbar.open({
752
+ type: signalled ? "success" : "warning",
753
+ message: t(signalled ? "studio_database_activity_cancelled" : "studio_database_activity_not_signalled", { pid: session.pid })
754
+ });
755
+ await load();
756
+ } catch (err) {
757
+ snackbar.open({
758
+ type: "error",
759
+ message: err instanceof Error ? err.message : t("studio_database_action_failed")
760
+ });
761
+ }
762
+ };
763
+ const askTerminate = (session) => confirm({
764
+ title: t("studio_database_activity_terminate_title", { pid: session.pid }),
765
+ body: t("studio_database_activity_terminate_body"),
766
+ confirmLabel: t("studio_database_activity_terminate"),
767
+ preview: async () => statementsOf(await requestJson(sourcePath(`/admin/db/insights/activity/${session.pid}/terminate`), {
768
+ method: "POST",
769
+ body: { dryRun: true }
770
+ })),
771
+ run: async () => {
772
+ await requestJson(sourcePath(`/admin/db/insights/activity/${session.pid}/terminate`), {
773
+ method: "POST",
774
+ body: {}
775
+ });
776
+ snackbar.open({
777
+ type: "success",
778
+ message: t("studio_database_activity_terminated", { pid: session.pid })
779
+ });
780
+ await load();
781
+ }
782
+ });
783
+ const stateTone = (session) => session.blockedBy.length > 0 ? "bad" : session.state === "active" ? "ok" : session.state?.startsWith("idle in transaction") ? "busy" : "idle";
784
+ return /* @__PURE__ */ jsxs("div", {
785
+ className: "flex flex-col gap-4",
786
+ children: [
787
+ /* @__PURE__ */ jsx(SectionHeader, {
788
+ title: t("studio_database_section_activity"),
789
+ description: paused ? t("studio_database_activity_paused") : t("studio_database_activity_description"),
790
+ actions: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Tooltip, {
791
+ title: paused ? t("studio_database_activity_resume") : t("studio_database_activity_pause"),
792
+ children: /* @__PURE__ */ jsx(IconButton, {
793
+ size: "small",
794
+ "aria-label": paused ? t("studio_database_activity_resume") : t("studio_database_activity_pause"),
795
+ "aria-pressed": paused,
796
+ onClick: () => setPaused((value) => !value),
797
+ children: paused ? /* @__PURE__ */ jsx(PlayIcon, { size: iconSize.small }) : /* @__PURE__ */ jsx(PauseIcon, { size: iconSize.small })
798
+ })
799
+ }), /* @__PURE__ */ jsx(Tooltip, {
800
+ title: t("refresh"),
801
+ children: /* @__PURE__ */ jsx(IconButton, {
802
+ size: "small",
803
+ "aria-label": t("studio_database_refresh_aria"),
804
+ onClick: () => void load(),
805
+ children: /* @__PURE__ */ jsx(RefreshCwIcon, { size: iconSize.small })
806
+ })
807
+ })] })
808
+ }),
809
+ error && /* @__PURE__ */ jsx(Alert, {
810
+ color: "error",
811
+ children: error
812
+ }),
813
+ sessions === null ? error ? null : /* @__PURE__ */ jsx(LoadingRow, {}) : sessions.length === 0 ? /* @__PURE__ */ jsx(EmptyState, {
814
+ icon: /* @__PURE__ */ jsx(ActivityIcon, { size: iconSize.large }),
815
+ message: t("studio_database_activity_empty")
816
+ }) : /* @__PURE__ */ jsx("div", {
817
+ className: cls("overflow-x-auto rounded-lg border", defaultBorderMixin),
818
+ children: /* @__PURE__ */ jsxs(Table, {
819
+ className: "w-full",
820
+ children: [/* @__PURE__ */ jsxs(TableHeader, { children: [
821
+ /* @__PURE__ */ jsx(TableCell, {
822
+ header: true,
823
+ children: t("studio_database_activity_pid")
824
+ }),
825
+ /* @__PURE__ */ jsx(TableCell, {
826
+ header: true,
827
+ children: t("studio_database_activity_state")
828
+ }),
829
+ /* @__PURE__ */ jsx(TableCell, {
830
+ header: true,
831
+ className: "text-right",
832
+ children: t("studio_database_activity_duration")
833
+ }),
834
+ /* @__PURE__ */ jsx(TableCell, {
835
+ header: true,
836
+ children: t("studio_database_activity_wait")
837
+ }),
838
+ /* @__PURE__ */ jsx(TableCell, {
839
+ header: true,
840
+ children: t("studio_database_queries_query")
841
+ }),
842
+ /* @__PURE__ */ jsx(TableCell, {
843
+ header: true,
844
+ className: "text-right",
845
+ children: t("actions")
846
+ })
847
+ ] }), /* @__PURE__ */ jsx(TableBody, { children: sessions.map((session) => /* @__PURE__ */ jsxs(TableRow, { children: [
848
+ /* @__PURE__ */ jsxs(TableCell, {
849
+ className: "tabular-nums font-mono text-xs",
850
+ children: [session.pid, /* @__PURE__ */ jsx(Typography, {
851
+ variant: "caption",
852
+ color: "secondary",
853
+ className: "block font-sans",
854
+ children: [session.username, session.applicationName].filter(Boolean).join(" · ")
855
+ })]
856
+ }),
857
+ /* @__PURE__ */ jsxs(TableCell, { children: [/* @__PURE__ */ jsx(StatusDot, {
858
+ tone: stateTone(session),
859
+ size: "small",
860
+ children: session.state ?? t("studio_database_activity_unknown_state")
861
+ }), session.blockedBy.length > 0 && /* @__PURE__ */ jsx(Typography, {
862
+ variant: "caption",
863
+ color: "error",
864
+ className: "block",
865
+ children: t("studio_database_activity_blocked_by", { pids: session.blockedBy.join(", ") })
866
+ })] }),
867
+ /* @__PURE__ */ jsx(TableCell, {
868
+ className: "text-right tabular-nums whitespace-nowrap",
869
+ children: formatDuration(session.durationMs, i18n.language)
870
+ }),
871
+ /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx(Typography, {
872
+ variant: "caption",
873
+ color: "secondary",
874
+ children: session.waitEventType ? `${session.waitEventType}: ${session.waitEvent ?? ""}` : "—"
875
+ }) }),
876
+ /* @__PURE__ */ jsx(TableCell, {
877
+ className: "max-w-xl",
878
+ children: /* @__PURE__ */ jsx(Typography, {
879
+ variant: "mono",
880
+ className: "text-xs line-clamp-2 break-all",
881
+ children: session.query
882
+ })
883
+ }),
884
+ /* @__PURE__ */ jsxs(TableCell, {
885
+ className: "text-right whitespace-nowrap",
886
+ children: [/* @__PURE__ */ jsx(Tooltip, {
887
+ title: t("studio_database_activity_cancel"),
888
+ children: /* @__PURE__ */ jsx(IconButton, {
889
+ size: "small",
890
+ "aria-label": t("studio_database_activity_cancel_aria", { pid: session.pid }),
891
+ onClick: () => void cancel(session),
892
+ children: /* @__PURE__ */ jsx(XCircleIcon, { size: iconSize.small })
893
+ })
894
+ }), /* @__PURE__ */ jsx(Tooltip, {
895
+ title: t("studio_database_activity_terminate"),
896
+ children: /* @__PURE__ */ jsx(IconButton, {
897
+ size: "small",
898
+ "aria-label": t("studio_database_activity_terminate_aria", { pid: session.pid }),
899
+ onClick: () => askTerminate(session),
900
+ children: /* @__PURE__ */ jsx(PowerIcon, {
901
+ size: iconSize.small,
902
+ className: "text-red-500"
903
+ })
904
+ })
905
+ })]
906
+ })
907
+ ] }, session.pid)) })]
908
+ })
909
+ }),
910
+ confirmDialog
911
+ ]
912
+ });
913
+ }
914
+ //#endregion
915
+ //#region src/components/Database/useCatalogList.ts
916
+ /**
917
+ * One catalog listing under `/admin/db/catalog`: the rows of `key` in the
918
+ * response, each parsed by `parse` (rows it cannot read are dropped).
919
+ */
920
+ function useCatalogList(path, key, parse) {
921
+ const { t } = useTranslation();
922
+ const { requestJson } = useAdminFetch();
923
+ const sourcePath = useSourcePath();
924
+ const [items, setItems] = useState(null);
925
+ const [error, setError] = useState(null);
926
+ const load = useCallback(async () => {
927
+ setError(null);
928
+ try {
929
+ const raw = await requestJson(sourcePath(`/admin/db/catalog/${path}`));
930
+ const list = isRecord(raw) && Array.isArray(raw[key]) ? raw[key] : [];
931
+ setItems(list.map(parse).filter((item) => item !== null));
932
+ } catch (err) {
933
+ setError(err instanceof Error ? err.message : t("studio_database_load_failed"));
934
+ }
935
+ }, [
936
+ requestJson,
937
+ sourcePath,
938
+ path,
939
+ key,
940
+ parse,
941
+ t
942
+ ]);
943
+ useEffect(() => {
944
+ load();
945
+ }, [load]);
946
+ return {
947
+ items,
948
+ error,
949
+ reload: load,
950
+ requestJson,
951
+ sourcePath
952
+ };
953
+ }
954
+ /** Whether `needle` occurs in any of `fields`, ignoring case. */
955
+ function matches(needle, ...fields) {
956
+ const query = needle.trim().toLowerCase();
957
+ return !query || fields.some((field) => field?.toLowerCase().includes(query));
958
+ }
959
+ //#endregion
960
+ //#region src/components/Database/FunctionsSection.tsx
961
+ function parseFunction(raw) {
962
+ if (!isRecord(raw) || typeof raw.name !== "string" || typeof raw.schema !== "string") return null;
963
+ return {
964
+ schema: raw.schema,
965
+ name: raw.name,
966
+ args: asString(raw.args),
967
+ returns: asNullableString(raw.returns),
968
+ language: asString(raw.language),
969
+ kind: raw.kind === "procedure" ? "procedure" : "function",
970
+ securityDefiner: asBoolean(raw.securityDefiner),
971
+ volatility: asString(raw.volatility),
972
+ comment: asNullableString(raw.comment),
973
+ definition: asString(raw.definition),
974
+ protected: asBoolean(raw.protected)
975
+ };
976
+ }
977
+ var signature = (fn) => `${fn.schema}.${fn.name}(${fn.args})`;
978
+ function FunctionsSection() {
979
+ const { t } = useTranslation();
980
+ const navigate = useNavigate();
981
+ const snackbar = useSnackbarController();
982
+ const { items, error, reload, requestJson, sourcePath } = useCatalogList("functions", "functions", parseFunction);
983
+ const [search, setSearch] = useState("");
984
+ const [open, setOpen] = useState(null);
985
+ const [confirmDialog, confirm] = useConfirmSql();
986
+ const path = (fn) => `/admin/db/catalog/functions/${encodeURIComponent(fn.schema)}/${encodeURIComponent(fn.name)}`;
987
+ const askDrop = (fn) => confirm({
988
+ title: t("studio_database_functions_drop_title", { name: signature(fn) }),
989
+ body: t("studio_database_functions_drop_body"),
990
+ confirmLabel: t("studio_database_drop"),
991
+ preview: async () => statementsOf(await requestJson(sourcePath(path(fn)), {
992
+ method: "DELETE",
993
+ body: {
994
+ args: fn.args,
995
+ dryRun: true
996
+ }
997
+ })),
998
+ run: async () => {
999
+ await requestJson(sourcePath(path(fn)), {
1000
+ method: "DELETE",
1001
+ body: { args: fn.args }
1002
+ });
1003
+ snackbar.open({
1004
+ type: "success",
1005
+ message: t("studio_database_dropped", { name: signature(fn) })
1006
+ });
1007
+ setOpen(null);
1008
+ await reload();
1009
+ }
1010
+ });
1011
+ const shown = (items ?? []).filter((fn) => matches(search, fn.name, fn.schema, fn.comment));
1012
+ return /* @__PURE__ */ jsxs("div", {
1013
+ className: "flex flex-col gap-4",
1014
+ children: [
1015
+ /* @__PURE__ */ jsx(SectionHeader, {
1016
+ title: t("studio_database_section_functions"),
1017
+ description: t("studio_database_functions_description"),
1018
+ actions: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(SearchBar, {
1019
+ size: "small",
1020
+ placeholder: t("studio_database_search"),
1021
+ onTextSearch: (value) => setSearch(value ?? "")
1022
+ }), /* @__PURE__ */ jsx(Tooltip, {
1023
+ title: t("refresh"),
1024
+ children: /* @__PURE__ */ jsx(IconButton, {
1025
+ size: "small",
1026
+ "aria-label": t("studio_database_refresh_aria"),
1027
+ onClick: () => void reload(),
1028
+ children: /* @__PURE__ */ jsx(RefreshCwIcon, { size: iconSize.small })
1029
+ })
1030
+ })] })
1031
+ }),
1032
+ error && /* @__PURE__ */ jsx(Alert, {
1033
+ color: "error",
1034
+ children: error
1035
+ }),
1036
+ items === null ? error ? null : /* @__PURE__ */ jsx(LoadingRow, {}) : shown.length === 0 ? /* @__PURE__ */ jsx(EmptyState, {
1037
+ icon: /* @__PURE__ */ jsx(FunctionSquareIcon, { size: iconSize.large }),
1038
+ message: t("studio_database_functions_empty")
1039
+ }) : /* @__PURE__ */ jsx("div", {
1040
+ className: cls("rounded-lg border divide-y divide-hairline overflow-hidden", defaultBorderMixin),
1041
+ children: shown.map((fn) => {
1042
+ const key = signature(fn);
1043
+ const expanded = open === key;
1044
+ return /* @__PURE__ */ jsxs("div", {
1045
+ className: "flex flex-col gap-2 px-4 py-2.5",
1046
+ children: [/* @__PURE__ */ jsxs("div", {
1047
+ className: "flex items-center gap-3",
1048
+ children: [
1049
+ /* @__PURE__ */ jsxs("button", {
1050
+ type: "button",
1051
+ className: "min-w-0 flex-1 text-left rounded-lg hover:bg-surface-hover -mx-2 px-2 py-1",
1052
+ "aria-expanded": expanded,
1053
+ onClick: () => setOpen(expanded ? null : key),
1054
+ children: [/* @__PURE__ */ jsxs(Typography, {
1055
+ variant: "mono",
1056
+ className: "text-sm truncate block",
1057
+ children: [
1058
+ fn.name,
1059
+ "(",
1060
+ fn.args,
1061
+ ")"
1062
+ ]
1063
+ }), /* @__PURE__ */ jsx(Typography, {
1064
+ variant: "caption",
1065
+ color: "secondary",
1066
+ className: "block truncate",
1067
+ children: [
1068
+ fn.schema,
1069
+ fn.kind === "procedure" ? t("studio_database_functions_procedure") : fn.returns,
1070
+ fn.language,
1071
+ fn.volatility
1072
+ ].filter(Boolean).join(" · ")
1073
+ })]
1074
+ }),
1075
+ fn.securityDefiner && /* @__PURE__ */ jsx(Chip, {
1076
+ size: "smallest",
1077
+ colorScheme: "orangeLight",
1078
+ children: t("studio_database_functions_security_definer")
1079
+ }),
1080
+ fn.protected ? /* @__PURE__ */ jsx(Tooltip, {
1081
+ title: t("studio_database_protected"),
1082
+ children: /* @__PURE__ */ jsx(LockIcon, {
1083
+ size: iconSize.smallest,
1084
+ className: "text-text-disabled dark:text-text-disabled-dark",
1085
+ "aria-label": t("studio_database_protected")
1086
+ })
1087
+ }) : /* @__PURE__ */ jsx(Tooltip, {
1088
+ title: t("studio_database_drop"),
1089
+ children: /* @__PURE__ */ jsx(IconButton, {
1090
+ size: "small",
1091
+ "aria-label": t("studio_database_functions_drop_aria", { name: key }),
1092
+ onClick: () => askDrop(fn),
1093
+ children: /* @__PURE__ */ jsx(Trash2Icon, {
1094
+ size: iconSize.small,
1095
+ className: "text-red-500"
1096
+ })
1097
+ })
1098
+ })
1099
+ ]
1100
+ }), expanded && /* @__PURE__ */ jsxs("div", {
1101
+ className: "flex flex-col gap-2",
1102
+ children: [
1103
+ fn.comment && /* @__PURE__ */ jsx(Typography, {
1104
+ variant: "body2",
1105
+ color: "secondary",
1106
+ children: fn.comment
1107
+ }),
1108
+ /* @__PURE__ */ jsx(SqlBlock, { sql: fn.definition }),
1109
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs(Button, {
1110
+ size: "small",
1111
+ onClick: () => navigate(sqlDraftLink(fn.definition)),
1112
+ children: [/* @__PURE__ */ jsx(TerminalIcon, { size: iconSize.smallest }), t("studio_database_edit_in_sql")]
1113
+ }) })
1114
+ ]
1115
+ })]
1116
+ }, key);
1117
+ })
1118
+ }),
1119
+ confirmDialog
1120
+ ]
1121
+ });
1122
+ }
1123
+ //#endregion
1124
+ //#region src/components/Database/TriggersSection.tsx
1125
+ function parseTrigger(raw) {
1126
+ if (!isRecord(raw) || typeof raw.name !== "string" || typeof raw.table !== "string") return null;
1127
+ return {
1128
+ schema: asString(raw.schema),
1129
+ table: raw.table,
1130
+ name: raw.name,
1131
+ definition: asString(raw.definition),
1132
+ enabled: asBoolean(raw.enabled, true),
1133
+ timing: asString(raw.timing),
1134
+ events: asStringArray(raw.events),
1135
+ level: asString(raw.level),
1136
+ function: asString(raw.function),
1137
+ protected: asBoolean(raw.protected)
1138
+ };
1139
+ }
1140
+ function TriggersSection() {
1141
+ const { t } = useTranslation();
1142
+ const navigate = useNavigate();
1143
+ const { items, error, reload } = useCatalogList("triggers", "triggers", parseTrigger);
1144
+ const [search, setSearch] = useState("");
1145
+ const shown = (items ?? []).filter((trigger) => matches(search, trigger.name, trigger.table, trigger.function));
1146
+ return /* @__PURE__ */ jsxs("div", {
1147
+ className: "flex flex-col gap-4",
1148
+ children: [
1149
+ /* @__PURE__ */ jsx(SectionHeader, {
1150
+ title: t("studio_database_section_triggers"),
1151
+ description: t("studio_database_triggers_description"),
1152
+ actions: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(SearchBar, {
1153
+ size: "small",
1154
+ placeholder: t("studio_database_search"),
1155
+ onTextSearch: (value) => setSearch(value ?? "")
1156
+ }), /* @__PURE__ */ jsx(Tooltip, {
1157
+ title: t("refresh"),
1158
+ children: /* @__PURE__ */ jsx(IconButton, {
1159
+ size: "small",
1160
+ "aria-label": t("studio_database_refresh_aria"),
1161
+ onClick: () => void reload(),
1162
+ children: /* @__PURE__ */ jsx(RefreshCwIcon, { size: iconSize.small })
1163
+ })
1164
+ })] })
1165
+ }),
1166
+ error && /* @__PURE__ */ jsx(Alert, {
1167
+ color: "error",
1168
+ children: error
1169
+ }),
1170
+ items === null ? error ? null : /* @__PURE__ */ jsx(LoadingRow, {}) : shown.length === 0 ? /* @__PURE__ */ jsx(EmptyState, {
1171
+ icon: /* @__PURE__ */ jsx(ZapIcon, { size: iconSize.large }),
1172
+ message: t("studio_database_triggers_empty")
1173
+ }) : /* @__PURE__ */ jsx("div", {
1174
+ className: cls("overflow-x-auto rounded-lg border", defaultBorderMixin),
1175
+ children: /* @__PURE__ */ jsxs(Table, {
1176
+ className: "w-full",
1177
+ children: [/* @__PURE__ */ jsxs(TableHeader, { children: [
1178
+ /* @__PURE__ */ jsx(TableCell, {
1179
+ header: true,
1180
+ children: t("name")
1181
+ }),
1182
+ /* @__PURE__ */ jsx(TableCell, {
1183
+ header: true,
1184
+ children: t("studio_database_triggers_table")
1185
+ }),
1186
+ /* @__PURE__ */ jsx(TableCell, {
1187
+ header: true,
1188
+ children: t("studio_database_triggers_when")
1189
+ }),
1190
+ /* @__PURE__ */ jsx(TableCell, {
1191
+ header: true,
1192
+ children: t("studio_database_triggers_function")
1193
+ }),
1194
+ /* @__PURE__ */ jsx(TableCell, {
1195
+ header: true,
1196
+ children: t("studio_enabled")
1197
+ }),
1198
+ /* @__PURE__ */ jsx(TableCell, {
1199
+ header: true,
1200
+ className: "text-right",
1201
+ children: t("actions")
1202
+ })
1203
+ ] }), /* @__PURE__ */ jsx(TableBody, { children: shown.map((trigger) => /* @__PURE__ */ jsxs(TableRow, { children: [
1204
+ /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsxs("div", {
1205
+ className: "flex items-center gap-1.5",
1206
+ children: [/* @__PURE__ */ jsx(Typography, {
1207
+ variant: "mono",
1208
+ className: "text-sm",
1209
+ children: trigger.name
1210
+ }), trigger.protected && /* @__PURE__ */ jsx(LockIcon, {
1211
+ size: iconSize.smallest,
1212
+ className: "text-text-disabled dark:text-text-disabled-dark",
1213
+ "aria-label": t("studio_database_protected")
1214
+ })]
1215
+ }) }),
1216
+ /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsxs(Button, {
1217
+ size: "small",
1218
+ variant: "text",
1219
+ onClick: () => navigate(tableLink(`${trigger.schema}.${trigger.table}`)),
1220
+ children: [
1221
+ trigger.schema,
1222
+ ".",
1223
+ trigger.table
1224
+ ]
1225
+ }) }),
1226
+ /* @__PURE__ */ jsxs(TableCell, { children: [/* @__PURE__ */ jsxs(Typography, {
1227
+ variant: "body2",
1228
+ children: [
1229
+ trigger.timing,
1230
+ " ",
1231
+ trigger.events.join(" OR ")
1232
+ ]
1233
+ }), /* @__PURE__ */ jsx(Typography, {
1234
+ variant: "caption",
1235
+ color: "secondary",
1236
+ children: t(trigger.level === "ROW" ? "studio_database_triggers_for_each_row" : "studio_database_triggers_for_each_statement")
1237
+ })] }),
1238
+ /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsxs(Typography, {
1239
+ variant: "mono",
1240
+ className: "text-xs",
1241
+ children: [trigger.function, "()"]
1242
+ }) }),
1243
+ /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx(StatusDot, {
1244
+ tone: trigger.enabled ? "ok" : "idle",
1245
+ size: "small",
1246
+ children: trigger.enabled ? t("studio_enabled") : t("studio_database_disabled")
1247
+ }) }),
1248
+ /* @__PURE__ */ jsx(TableCell, {
1249
+ className: "text-right",
1250
+ children: /* @__PURE__ */ jsx(Tooltip, {
1251
+ title: t("studio_database_open_in_sql"),
1252
+ children: /* @__PURE__ */ jsx(IconButton, {
1253
+ size: "small",
1254
+ "aria-label": t("studio_database_open_in_sql"),
1255
+ onClick: () => navigate(sqlDraftLink(`${trigger.definition};`)),
1256
+ children: /* @__PURE__ */ jsx(TerminalIcon, { size: iconSize.small })
1257
+ })
1258
+ })
1259
+ })
1260
+ ] }, `${trigger.schema}.${trigger.table}.${trigger.name}`)) })]
1261
+ })
1262
+ })
1263
+ ]
1264
+ });
1265
+ }
1266
+ //#endregion
1267
+ //#region src/components/Database/TypesSection.tsx
1268
+ function parseType(raw) {
1269
+ if (!isRecord(raw) || typeof raw.name !== "string") return null;
1270
+ const kind = raw.kind === "enum" || raw.kind === "composite" || raw.kind === "domain" ? raw.kind : null;
1271
+ if (!kind) return null;
1272
+ return {
1273
+ schema: asString(raw.schema),
1274
+ name: raw.name,
1275
+ kind,
1276
+ values: asStringArray(raw.values),
1277
+ attributes: asStringArray(raw.attributes),
1278
+ baseType: asNullableString(raw.baseType),
1279
+ comment: asNullableString(raw.comment),
1280
+ protected: asBoolean(raw.protected)
1281
+ };
1282
+ }
1283
+ /** The value that goes last, in the `after` select. */
1284
+ var AT_END = "__end__";
1285
+ function TypesSection() {
1286
+ const { t } = useTranslation();
1287
+ const snackbar = useSnackbarController();
1288
+ const { items, error, reload, requestJson, sourcePath } = useCatalogList("types", "types", parseType);
1289
+ const [search, setSearch] = useState("");
1290
+ const [adding, setAdding] = useState(null);
1291
+ const [value, setValue] = useState("");
1292
+ const [after, setAfter] = useState(AT_END);
1293
+ const [preview, setPreview] = useState(null);
1294
+ const [saving, setSaving] = useState(false);
1295
+ const [dialogError, setDialogError] = useState(null);
1296
+ const openAdd = (type) => {
1297
+ setAdding(type);
1298
+ setValue("");
1299
+ setAfter(AT_END);
1300
+ setPreview(null);
1301
+ setDialogError(null);
1302
+ };
1303
+ const body = (dryRun) => ({
1304
+ value,
1305
+ ...after !== AT_END ? { after } : {},
1306
+ dryRun
1307
+ });
1308
+ const path = (type) => `/admin/db/catalog/types/${encodeURIComponent(type.schema)}/${encodeURIComponent(type.name)}/values`;
1309
+ const showPreview = async () => {
1310
+ if (!adding) return;
1311
+ setDialogError(null);
1312
+ try {
1313
+ setPreview(statementsOf(await requestJson(sourcePath(path(adding)), {
1314
+ method: "POST",
1315
+ body: body(true)
1316
+ })));
1317
+ } catch (err) {
1318
+ setDialogError(err instanceof Error ? err.message : t("studio_database_action_failed"));
1319
+ }
1320
+ };
1321
+ const save = async () => {
1322
+ if (!adding) return;
1323
+ setSaving(true);
1324
+ setDialogError(null);
1325
+ try {
1326
+ await requestJson(sourcePath(path(adding)), {
1327
+ method: "POST",
1328
+ body: body(false)
1329
+ });
1330
+ snackbar.open({
1331
+ type: "success",
1332
+ message: t("studio_database_types_value_added", {
1333
+ value,
1334
+ type: `${adding.schema}.${adding.name}`
1335
+ })
1336
+ });
1337
+ setAdding(null);
1338
+ await reload();
1339
+ } catch (err) {
1340
+ setDialogError(err instanceof Error ? err.message : t("studio_database_action_failed"));
1341
+ } finally {
1342
+ setSaving(false);
1343
+ }
1344
+ };
1345
+ const shown = (items ?? []).filter((type) => matches(search, type.name, type.schema, ...type.values));
1346
+ return /* @__PURE__ */ jsxs("div", {
1347
+ className: "flex flex-col gap-4",
1348
+ children: [
1349
+ /* @__PURE__ */ jsx(SectionHeader, {
1350
+ title: t("studio_database_section_types"),
1351
+ description: t("studio_database_types_description"),
1352
+ actions: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(SearchBar, {
1353
+ size: "small",
1354
+ placeholder: t("studio_database_search"),
1355
+ onTextSearch: (text) => setSearch(text ?? "")
1356
+ }), /* @__PURE__ */ jsx(Tooltip, {
1357
+ title: t("refresh"),
1358
+ children: /* @__PURE__ */ jsx(IconButton, {
1359
+ size: "small",
1360
+ "aria-label": t("studio_database_refresh_aria"),
1361
+ onClick: () => void reload(),
1362
+ children: /* @__PURE__ */ jsx(RefreshCwIcon, { size: iconSize.small })
1363
+ })
1364
+ })] })
1365
+ }),
1366
+ error && /* @__PURE__ */ jsx(Alert, {
1367
+ color: "error",
1368
+ children: error
1369
+ }),
1370
+ items === null ? error ? null : /* @__PURE__ */ jsx(LoadingRow, {}) : shown.length === 0 ? /* @__PURE__ */ jsx(EmptyState, {
1371
+ icon: /* @__PURE__ */ jsx(ShapesIcon, { size: iconSize.large }),
1372
+ message: t("studio_database_types_empty")
1373
+ }) : /* @__PURE__ */ jsx("div", {
1374
+ className: cls("rounded-lg border divide-y divide-hairline overflow-hidden", defaultBorderMixin),
1375
+ children: shown.map((type) => /* @__PURE__ */ jsxs("div", {
1376
+ className: "flex flex-col gap-2 px-4 py-3",
1377
+ children: [/* @__PURE__ */ jsxs("div", {
1378
+ className: "flex items-center gap-3",
1379
+ children: [/* @__PURE__ */ jsxs("div", {
1380
+ className: "min-w-0 flex-1",
1381
+ children: [/* @__PURE__ */ jsxs(Typography, {
1382
+ variant: "mono",
1383
+ className: "text-sm truncate block",
1384
+ children: [
1385
+ type.schema,
1386
+ ".",
1387
+ type.name
1388
+ ]
1389
+ }), /* @__PURE__ */ jsxs(Typography, {
1390
+ variant: "caption",
1391
+ color: "secondary",
1392
+ className: "block",
1393
+ children: [
1394
+ t(`studio_database_types_kind_${type.kind}`),
1395
+ type.baseType ? ` · ${type.baseType}` : "",
1396
+ type.comment ? ` · ${type.comment}` : ""
1397
+ ]
1398
+ })]
1399
+ }), type.protected ? /* @__PURE__ */ jsx(LockIcon, {
1400
+ size: iconSize.smallest,
1401
+ className: "text-text-disabled dark:text-text-disabled-dark",
1402
+ "aria-label": t("studio_database_protected")
1403
+ }) : type.kind === "enum" && /* @__PURE__ */ jsxs(Button, {
1404
+ size: "small",
1405
+ onClick: () => openAdd(type),
1406
+ children: [/* @__PURE__ */ jsx(PlusIcon, { size: iconSize.smallest }), t("studio_database_types_add_value")]
1407
+ })]
1408
+ }), (type.kind === "enum" ? type.values : type.attributes).length > 0 && /* @__PURE__ */ jsx("div", {
1409
+ className: "flex flex-wrap gap-1.5",
1410
+ children: (type.kind === "enum" ? type.values : type.attributes).map((entry) => /* @__PURE__ */ jsx(Chip, {
1411
+ size: "smallest",
1412
+ colorScheme: "grayLight",
1413
+ children: entry
1414
+ }, entry))
1415
+ })]
1416
+ }, `${type.schema}.${type.name}`))
1417
+ }),
1418
+ /* @__PURE__ */ jsxs(Dialog, {
1419
+ open: adding !== null,
1420
+ onOpenChange: (open) => {
1421
+ if (!open && !saving) setAdding(null);
1422
+ },
1423
+ maxWidth: "md",
1424
+ fullWidth: true,
1425
+ children: [
1426
+ /* @__PURE__ */ jsx(DialogTitle, { children: t("studio_database_types_add_value_title", { type: adding ? `${adding.schema}.${adding.name}` : "" }) }),
1427
+ /* @__PURE__ */ jsxs(DialogContent, {
1428
+ className: "flex flex-col gap-4",
1429
+ children: [
1430
+ /* @__PURE__ */ jsx(TextField, {
1431
+ label: t("studio_database_types_value"),
1432
+ value,
1433
+ onChange: (event) => {
1434
+ setValue(event.target.value);
1435
+ setPreview(null);
1436
+ }
1437
+ }),
1438
+ /* @__PURE__ */ jsxs(Select, {
1439
+ label: t("studio_database_types_position"),
1440
+ value: after,
1441
+ onValueChange: (next) => {
1442
+ setAfter(next);
1443
+ setPreview(null);
1444
+ },
1445
+ children: [/* @__PURE__ */ jsx(SelectItem, {
1446
+ value: AT_END,
1447
+ children: t("studio_database_types_position_end")
1448
+ }), (adding?.values ?? []).map((label) => /* @__PURE__ */ jsx(SelectItem, {
1449
+ value: label,
1450
+ children: t("studio_database_types_position_after", { value: label })
1451
+ }, label))]
1452
+ }),
1453
+ /* @__PURE__ */ jsx(Typography, {
1454
+ variant: "caption",
1455
+ color: "secondary",
1456
+ children: t("studio_database_types_add_value_note")
1457
+ }),
1458
+ preview && /* @__PURE__ */ jsx(SqlBlock, { sql: preview.join("\n") }),
1459
+ dialogError && /* @__PURE__ */ jsx(Alert, {
1460
+ color: "error",
1461
+ children: dialogError
1462
+ })
1463
+ ]
1464
+ }),
1465
+ /* @__PURE__ */ jsxs(DialogActions, { children: [
1466
+ /* @__PURE__ */ jsx(Button, {
1467
+ variant: "text",
1468
+ onClick: () => setAdding(null),
1469
+ disabled: saving,
1470
+ children: t("cancel")
1471
+ }),
1472
+ /* @__PURE__ */ jsx(Button, {
1473
+ variant: "text",
1474
+ onClick: () => void showPreview(),
1475
+ disabled: !value || saving,
1476
+ children: t("studio_database_preview_sql")
1477
+ }),
1478
+ /* @__PURE__ */ jsx(Button, {
1479
+ variant: "filled",
1480
+ color: "primary",
1481
+ onClick: () => void save(),
1482
+ disabled: !value || saving,
1483
+ children: t("studio_database_types_add_value")
1484
+ })
1485
+ ] })
1486
+ ]
1487
+ })
1488
+ ]
1489
+ });
1490
+ }
1491
+ //#endregion
1492
+ //#region src/components/Database/ExtensionsSection.tsx
1493
+ function parseExtension(raw) {
1494
+ if (!isRecord(raw) || typeof raw.name !== "string") return null;
1495
+ return {
1496
+ name: raw.name,
1497
+ defaultVersion: asNullableString(raw.defaultVersion),
1498
+ installedVersion: asNullableString(raw.installedVersion),
1499
+ schema: asNullableString(raw.schema),
1500
+ comment: asNullableString(raw.comment),
1501
+ installed: asBoolean(raw.installed)
1502
+ };
1503
+ }
1504
+ /** The server's own procedural language: listed, never dropped. */
1505
+ var CORE_EXTENSIONS = /* @__PURE__ */ new Set(["plpgsql"]);
1506
+ function ExtensionsSection() {
1507
+ const { t } = useTranslation();
1508
+ const snackbar = useSnackbarController();
1509
+ const { items, error, reload, requestJson, sourcePath } = useCatalogList("extensions", "extensions", parseExtension);
1510
+ const [search, setSearch] = useState("");
1511
+ const [installing, setInstalling] = useState(null);
1512
+ const [confirmDialog, confirm] = useConfirmSql();
1513
+ const install = async (extension) => {
1514
+ setInstalling(extension.name);
1515
+ try {
1516
+ await requestJson(sourcePath(`/admin/db/catalog/extensions/${encodeURIComponent(extension.name)}`), {
1517
+ method: "POST",
1518
+ body: {}
1519
+ });
1520
+ snackbar.open({
1521
+ type: "success",
1522
+ message: t("studio_database_extensions_installed_message", { name: extension.name })
1523
+ });
1524
+ await reload();
1525
+ } catch (err) {
1526
+ snackbar.open({
1527
+ type: "error",
1528
+ message: err instanceof Error ? err.message : t("studio_database_action_failed")
1529
+ });
1530
+ } finally {
1531
+ setInstalling(null);
1532
+ }
1533
+ };
1534
+ const askDrop = (extension, cascade) => {
1535
+ const path = `/admin/db/catalog/extensions/${encodeURIComponent(extension.name)}`;
1536
+ confirm({
1537
+ title: t("studio_database_extensions_drop_title", { name: extension.name }),
1538
+ body: /* @__PURE__ */ jsxs("div", {
1539
+ className: "flex flex-col gap-3",
1540
+ children: [/* @__PURE__ */ jsx(Typography, {
1541
+ variant: "body2",
1542
+ children: t(cascade ? "studio_database_extensions_drop_body_cascade" : "studio_database_extensions_drop_body")
1543
+ }), /* @__PURE__ */ jsxs("div", {
1544
+ className: "flex items-center gap-2",
1545
+ children: [/* @__PURE__ */ jsx(Checkbox, {
1546
+ id: "drop-extension-cascade",
1547
+ size: "small",
1548
+ checked: cascade,
1549
+ onCheckedChange: (checked) => askDrop(extension, checked)
1550
+ }), /* @__PURE__ */ jsx(Label, {
1551
+ htmlFor: "drop-extension-cascade",
1552
+ children: t("studio_database_cascade")
1553
+ })]
1554
+ })]
1555
+ }),
1556
+ confirmLabel: t("studio_database_drop"),
1557
+ preview: async () => statementsOf(await requestJson(sourcePath(path), {
1558
+ method: "DELETE",
1559
+ body: {
1560
+ cascade,
1561
+ dryRun: true
1562
+ }
1563
+ })),
1564
+ run: async () => {
1565
+ await requestJson(sourcePath(path), {
1566
+ method: "DELETE",
1567
+ body: { cascade }
1568
+ });
1569
+ snackbar.open({
1570
+ type: "success",
1571
+ message: t("studio_database_dropped", { name: extension.name })
1572
+ });
1573
+ await reload();
1574
+ }
1575
+ });
1576
+ };
1577
+ const shown = (items ?? []).filter((extension) => matches(search, extension.name, extension.comment));
1578
+ return /* @__PURE__ */ jsxs("div", {
1579
+ className: "flex flex-col gap-4",
1580
+ children: [
1581
+ /* @__PURE__ */ jsx(SectionHeader, {
1582
+ title: t("studio_database_section_extensions"),
1583
+ description: t("studio_database_extensions_description"),
1584
+ actions: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(SearchBar, {
1585
+ size: "small",
1586
+ placeholder: t("studio_database_search"),
1587
+ onTextSearch: (value) => setSearch(value ?? "")
1588
+ }), /* @__PURE__ */ jsx(Tooltip, {
1589
+ title: t("refresh"),
1590
+ children: /* @__PURE__ */ jsx(IconButton, {
1591
+ size: "small",
1592
+ "aria-label": t("studio_database_refresh_aria"),
1593
+ onClick: () => void reload(),
1594
+ children: /* @__PURE__ */ jsx(RefreshCwIcon, { size: iconSize.small })
1595
+ })
1596
+ })] })
1597
+ }),
1598
+ error && /* @__PURE__ */ jsx(Alert, {
1599
+ color: "error",
1600
+ children: error
1601
+ }),
1602
+ items === null ? error ? null : /* @__PURE__ */ jsx(LoadingRow, {}) : shown.length === 0 ? /* @__PURE__ */ jsx(EmptyState, {
1603
+ icon: /* @__PURE__ */ jsx(PuzzleIcon, { size: iconSize.large }),
1604
+ message: t("studio_database_extensions_empty")
1605
+ }) : /* @__PURE__ */ jsx("div", {
1606
+ className: cls("rounded-lg border divide-y divide-hairline overflow-hidden", defaultBorderMixin),
1607
+ children: shown.map((extension) => /* @__PURE__ */ jsxs("div", {
1608
+ className: "flex items-center gap-3 px-4 py-2.5",
1609
+ children: [/* @__PURE__ */ jsxs("div", {
1610
+ className: "min-w-0 flex-1",
1611
+ children: [/* @__PURE__ */ jsxs("div", {
1612
+ className: "flex items-center gap-2",
1613
+ children: [/* @__PURE__ */ jsx(Typography, {
1614
+ variant: "mono",
1615
+ className: "text-sm",
1616
+ children: extension.name
1617
+ }), /* @__PURE__ */ jsx(Typography, {
1618
+ variant: "caption",
1619
+ color: "secondary",
1620
+ children: extension.installedVersion ?? extension.defaultVersion ?? ""
1621
+ })]
1622
+ }), extension.comment && /* @__PURE__ */ jsx(Typography, {
1623
+ variant: "caption",
1624
+ color: "secondary",
1625
+ className: "block truncate",
1626
+ children: extension.comment
1627
+ })]
1628
+ }), extension.installed ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(StatusDot, {
1629
+ tone: "ok",
1630
+ size: "small",
1631
+ children: extension.schema ? t("studio_database_extensions_installed_in", { schema: extension.schema }) : t("studio_database_extensions_installed")
1632
+ }), !CORE_EXTENSIONS.has(extension.name) && /* @__PURE__ */ jsx(Tooltip, {
1633
+ title: t("studio_database_drop"),
1634
+ children: /* @__PURE__ */ jsx(IconButton, {
1635
+ size: "small",
1636
+ "aria-label": t("studio_database_extensions_drop_aria", { name: extension.name }),
1637
+ onClick: () => askDrop(extension, false),
1638
+ children: /* @__PURE__ */ jsx(Trash2Icon, {
1639
+ size: iconSize.small,
1640
+ className: "text-red-500"
1641
+ })
1642
+ })
1643
+ })] }) : /* @__PURE__ */ jsx(Button, {
1644
+ size: "small",
1645
+ disabled: installing !== null,
1646
+ onClick: () => void install(extension),
1647
+ children: installing === extension.name ? t("studio_database_extensions_installing") : t("studio_database_extensions_install")
1648
+ })]
1649
+ }, extension.name))
1650
+ }),
1651
+ confirmDialog
1652
+ ]
1653
+ });
1654
+ }
1655
+ //#endregion
1656
+ //#region src/components/Database/DatabaseView.tsx
1657
+ var DATABASE_SECTIONS = [
1658
+ "advisors",
1659
+ "queries",
1660
+ "activity",
1661
+ "functions",
1662
+ "triggers",
1663
+ "types",
1664
+ "extensions"
1665
+ ];
1666
+ var isSection = (value) => value !== null && DATABASE_SECTIONS.some((section) => section === value);
1667
+ var SECTION_ICONS = {
1668
+ advisors: ShieldAlertIcon,
1669
+ queries: GaugeIcon,
1670
+ activity: ActivityIcon,
1671
+ functions: FunctionSquareIcon,
1672
+ triggers: ZapIcon,
1673
+ types: ShapesIcon,
1674
+ extensions: PuzzleIcon
1675
+ };
1676
+ /** Below this width the section list folds into a select above the content. */
1677
+ var SIDE_LIST_MIN_WIDTH = 720;
1678
+ function parseOverview(raw) {
1679
+ if (!isRecord(raw)) return null;
1680
+ const connections = isRecord(raw.connections) ? raw.connections : {};
1681
+ return {
1682
+ engine: raw.engine === "pglite" ? "pglite" : "postgres",
1683
+ serverVersion: asString(raw.serverVersion),
1684
+ database: asString(raw.database),
1685
+ sizeBytes: typeof raw.sizeBytes === "number" ? raw.sizeBytes : null,
1686
+ connectionsUsed: typeof connections.used === "number" ? asNumber(connections.used) : null,
1687
+ connectionsMax: typeof connections.max === "number" ? asNumber(connections.max) : null
1688
+ };
1689
+ }
1690
+ function Readout({ label, value }) {
1691
+ return /* @__PURE__ */ jsxs("div", {
1692
+ className: "flex flex-col min-w-0",
1693
+ children: [/* @__PURE__ */ jsx(Typography, {
1694
+ variant: "micro",
1695
+ color: "secondary",
1696
+ className: "uppercase",
1697
+ children: label
1698
+ }), /* @__PURE__ */ jsx(Typography, {
1699
+ variant: "body2",
1700
+ className: "tabular-nums font-medium truncate",
1701
+ children: value
1702
+ })]
1703
+ });
1704
+ }
1705
+ /**
1706
+ * The database as a whole: advice, the queries that take the time, the
1707
+ * sessions doing work now, and the objects besides tables — functions,
1708
+ * triggers, types, extensions.
1709
+ *
1710
+ * The open section is in the URL (`?section=`), so a link can land on one.
1711
+ * So is the database (`?source=`), when the backend serves more than one —
1712
+ * the default, and each declared with `database("…")`.
1713
+ */
1714
+ function DatabaseView() {
1715
+ const { t, i18n } = useTranslation();
1716
+ const { requestJson } = useAdminFetch();
1717
+ const [searchParams, setSearchParams] = useSearchParams();
1718
+ const requested = searchParams.get("section");
1719
+ const section = isSection(requested) ? requested : "advisors";
1720
+ const source = searchParams.get("source") || DEFAULT_SOURCE;
1721
+ const [sources, setSources] = useState([DEFAULT_SOURCE]);
1722
+ const [overview, setOverview] = useState(null);
1723
+ const [advisorCount, setAdvisorCount] = useState(null);
1724
+ const rootRef = useRef(null);
1725
+ const [wide, setWide] = useState(true);
1726
+ useLayoutEffect(() => {
1727
+ const element = rootRef.current;
1728
+ if (!element || typeof ResizeObserver === "undefined") return void 0;
1729
+ const observer = new ResizeObserver(([entry]) => setWide(entry.contentRect.width >= SIDE_LIST_MIN_WIDTH));
1730
+ observer.observe(element);
1731
+ return () => observer.disconnect();
1732
+ }, []);
1733
+ const loadOverview = useCallback(async () => {
1734
+ try {
1735
+ setOverview(parseOverview(await requestJson(withSource("/admin/db/insights/overview", source))));
1736
+ } catch {
1737
+ setOverview(null);
1738
+ }
1739
+ }, [requestJson, source]);
1740
+ useEffect(() => {
1741
+ loadOverview();
1742
+ }, [loadOverview]);
1743
+ useEffect(() => {
1744
+ requestJson("/admin/db/insights/sources").then((raw) => {
1745
+ const keys = isRecord(raw) && Array.isArray(raw.sources) ? asStringArray(raw.sources.filter(isRecord).map((entry) => entry.key)) : [];
1746
+ if (keys.length > 0) setSources(keys);
1747
+ }, () => void 0);
1748
+ }, [requestJson]);
1749
+ const setParam = (name, value) => {
1750
+ setSearchParams((params) => {
1751
+ const updated = new URLSearchParams(params);
1752
+ if (value === null) updated.delete(name);
1753
+ else updated.set(name, value);
1754
+ return updated;
1755
+ });
1756
+ };
1757
+ const select = (next) => setParam("section", next === "advisors" ? null : next);
1758
+ const selectSource = (next) => {
1759
+ setAdvisorCount(null);
1760
+ setParam("source", next === DEFAULT_SOURCE ? null : next);
1761
+ };
1762
+ const locale = i18n.language;
1763
+ const engine = overview?.engine === "pglite" ? t("studio_database_engine_pglite") : t("studio_database_engine_postgres");
1764
+ const connections = overview?.connectionsUsed !== null && overview?.connectionsUsed !== void 0 ? overview.connectionsMax !== null ? t("studio_database_connections_of", {
1765
+ used: formatCount(overview.connectionsUsed, locale),
1766
+ max: formatCount(overview.connectionsMax, locale)
1767
+ }) : formatCount(overview.connectionsUsed, locale) : "—";
1768
+ return /* @__PURE__ */ jsxs("div", {
1769
+ ref: rootRef,
1770
+ className: "flex flex-col h-full w-full bg-surface-sheet overflow-hidden",
1771
+ children: [/* @__PURE__ */ jsxs("div", {
1772
+ className: "px-5 pt-4 pb-3 flex items-center justify-between gap-x-8 gap-y-3 flex-wrap",
1773
+ children: [/* @__PURE__ */ jsxs("div", {
1774
+ className: "flex items-center gap-2.5 min-w-0",
1775
+ children: [/* @__PURE__ */ jsx(ServerCogIcon, {
1776
+ size: iconSize.medium,
1777
+ className: "text-text-secondary dark:text-text-secondary-dark shrink-0"
1778
+ }), /* @__PURE__ */ jsxs("div", {
1779
+ className: "min-w-0",
1780
+ children: [/* @__PURE__ */ jsx(Typography, {
1781
+ variant: "h6",
1782
+ children: t("studio_tool_database")
1783
+ }), /* @__PURE__ */ jsx(Typography, {
1784
+ variant: "caption",
1785
+ color: "secondary",
1786
+ className: "block truncate",
1787
+ children: overview?.database ? t("studio_database_subtitle_named", { database: overview.database }) : t("studio_tool_database_description")
1788
+ })]
1789
+ })]
1790
+ }), /* @__PURE__ */ jsxs("div", {
1791
+ className: "flex items-center gap-8 flex-wrap",
1792
+ children: [
1793
+ sources.length > 1 && /* @__PURE__ */ jsx(Select, {
1794
+ size: "small",
1795
+ label: t("studio_database_source"),
1796
+ labelPlacement: "above",
1797
+ value: source,
1798
+ onValueChange: selectSource,
1799
+ renderValue: (value) => value === DEFAULT_SOURCE ? t("studio_database_source_default") : value,
1800
+ children: sources.map((key) => /* @__PURE__ */ jsx(SelectItem, {
1801
+ value: key,
1802
+ children: key === DEFAULT_SOURCE ? t("studio_database_source_default") : key
1803
+ }, key))
1804
+ }),
1805
+ /* @__PURE__ */ jsx(Readout, {
1806
+ label: t("studio_database_overview_version"),
1807
+ value: overview ? `${engine} ${overview.serverVersion.split(" ")[0]}` : "—"
1808
+ }),
1809
+ /* @__PURE__ */ jsx(Readout, {
1810
+ label: t("studio_database_overview_size"),
1811
+ value: overview?.sizeBytes !== null && overview?.sizeBytes !== void 0 ? formatBytes(overview.sizeBytes, locale) : "—"
1812
+ }),
1813
+ /* @__PURE__ */ jsx(Readout, {
1814
+ label: t("studio_database_overview_connections"),
1815
+ value: connections
1816
+ }),
1817
+ /* @__PURE__ */ jsx(Tooltip, {
1818
+ title: t("refresh"),
1819
+ children: /* @__PURE__ */ jsx(IconButton, {
1820
+ size: "small",
1821
+ "aria-label": t("studio_database_overview_refresh_aria"),
1822
+ onClick: () => void loadOverview(),
1823
+ children: /* @__PURE__ */ jsx(RefreshCwIcon, { size: iconSize.small })
1824
+ })
1825
+ })
1826
+ ]
1827
+ })]
1828
+ }), /* @__PURE__ */ jsxs("div", {
1829
+ className: "flex flex-1 min-h-0",
1830
+ children: [wide && /* @__PURE__ */ jsx("nav", {
1831
+ "aria-label": t("studio_database_sections_aria"),
1832
+ className: "w-[220px] shrink-0 px-2 pb-4 flex flex-col gap-0.5 overflow-y-auto",
1833
+ children: DATABASE_SECTIONS.map((entry) => {
1834
+ const Icon = SECTION_ICONS[entry];
1835
+ const active = entry === section;
1836
+ return /* @__PURE__ */ jsxs("button", {
1837
+ type: "button",
1838
+ "aria-current": active ? "page" : void 0,
1839
+ onClick: () => select(entry),
1840
+ className: cls("group/nav flex items-center gap-2.5 h-[30px] px-3 rounded-lg text-left transition-colors", "hover:bg-surface-hover", active && "bg-surface-active"),
1841
+ children: [
1842
+ /* @__PURE__ */ jsx("span", {
1843
+ className: "text-text-secondary dark:text-text-secondary-dark group-hover/nav:text-text-primary dark:group-hover/nav:text-text-primary-dark",
1844
+ children: /* @__PURE__ */ jsx(Icon, { size: iconSize.smallest })
1845
+ }),
1846
+ /* @__PURE__ */ jsx(Typography, {
1847
+ variant: "body2",
1848
+ className: "flex-1 truncate text-[13px] font-medium",
1849
+ children: t(`studio_database_section_${entry}`)
1850
+ }),
1851
+ entry === "advisors" && advisorCount !== null && advisorCount > 0 && /* @__PURE__ */ jsx(Typography, {
1852
+ variant: "caption",
1853
+ color: "secondary",
1854
+ className: "tabular-nums",
1855
+ children: advisorCount
1856
+ })
1857
+ ]
1858
+ }, entry);
1859
+ })
1860
+ }), /* @__PURE__ */ jsxs("div", {
1861
+ className: cls("flex-1 min-w-0 overflow-auto bg-surface-card p-5", wide && "rounded-tl-xl"),
1862
+ children: [!wide && /* @__PURE__ */ jsx("div", {
1863
+ className: "mb-4",
1864
+ children: /* @__PURE__ */ jsx(Select, {
1865
+ size: "small",
1866
+ fullWidth: true,
1867
+ label: t("studio_database_sections_aria"),
1868
+ labelPlacement: "above",
1869
+ value: section,
1870
+ onValueChange: (value) => {
1871
+ if (isSection(value)) select(value);
1872
+ },
1873
+ children: DATABASE_SECTIONS.map((entry) => /* @__PURE__ */ jsx(SelectItem, {
1874
+ value: entry,
1875
+ children: t(`studio_database_section_${entry}`)
1876
+ }, entry))
1877
+ })
1878
+ }), /* @__PURE__ */ jsxs(DatabaseSourceProvider, {
1879
+ source,
1880
+ children: [
1881
+ section === "advisors" && /* @__PURE__ */ jsx(AdvisorsSection, { onCount: setAdvisorCount }),
1882
+ section === "queries" && /* @__PURE__ */ jsx(QueriesSection, {}),
1883
+ section === "activity" && /* @__PURE__ */ jsx(ActivitySection, {}),
1884
+ section === "functions" && /* @__PURE__ */ jsx(FunctionsSection, {}),
1885
+ section === "triggers" && /* @__PURE__ */ jsx(TriggersSection, {}),
1886
+ section === "types" && /* @__PURE__ */ jsx(TypesSection, {}),
1887
+ section === "extensions" && /* @__PURE__ */ jsx(ExtensionsSection, {})
1888
+ ]
1889
+ }, source)]
1890
+ })]
1891
+ })]
1892
+ });
1893
+ }
1894
+ //#endregion
1895
+ export { DatabaseView };
1896
+
1897
+ //# sourceMappingURL=DatabaseView-Bi0NZS90.js.map