@tekki-forge/runtime-admin 0.1.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 (138) hide show
  1. package/README.md +5 -0
  2. package/dist/account.d.ts +1 -0
  3. package/dist/account.js +105 -0
  4. package/dist/account.js.map +1 -0
  5. package/dist/activity.d.ts +65 -0
  6. package/dist/activity.js +299 -0
  7. package/dist/activity.js.map +1 -0
  8. package/dist/admin-access.d.ts +4 -0
  9. package/dist/admin-access.js +177 -0
  10. package/dist/admin-access.js.map +1 -0
  11. package/dist/admin.d.ts +5 -0
  12. package/dist/admin.js +129 -0
  13. package/dist/admin.js.map +1 -0
  14. package/dist/auth-pages.d.ts +13 -0
  15. package/dist/auth-pages.js +207 -0
  16. package/dist/auth-pages.js.map +1 -0
  17. package/dist/brand-art.d.ts +24 -0
  18. package/dist/brand-art.js +33 -0
  19. package/dist/brand-art.js.map +1 -0
  20. package/dist/brand.d.ts +11 -0
  21. package/dist/brand.js +16 -0
  22. package/dist/brand.js.map +1 -0
  23. package/dist/charts.d.ts +23 -0
  24. package/dist/charts.js +259 -0
  25. package/dist/charts.js.map +1 -0
  26. package/dist/command-palette.d.ts +9 -0
  27. package/dist/command-palette.js +115 -0
  28. package/dist/command-palette.js.map +1 -0
  29. package/dist/context.d.ts +242 -0
  30. package/dist/context.js +107 -0
  31. package/dist/context.js.map +1 -0
  32. package/dist/dashboard.d.ts +66 -0
  33. package/dist/dashboard.js +144 -0
  34. package/dist/dashboard.js.map +1 -0
  35. package/dist/fields.d.ts +71 -0
  36. package/dist/fields.js +326 -0
  37. package/dist/fields.js.map +1 -0
  38. package/dist/i18n/catalog.d.ts +7 -0
  39. package/dist/i18n/catalog.js +23 -0
  40. package/dist/i18n/catalog.js.map +1 -0
  41. package/dist/i18n/locale.d.ts +15 -0
  42. package/dist/i18n/locale.js +69 -0
  43. package/dist/i18n/locale.js.map +1 -0
  44. package/dist/i18n/messages/de.d.ts +3 -0
  45. package/dist/i18n/messages/de.js +627 -0
  46. package/dist/i18n/messages/de.js.map +1 -0
  47. package/dist/i18n/messages/en.d.ts +3 -0
  48. package/dist/i18n/messages/en.js +627 -0
  49. package/dist/i18n/messages/en.js.map +1 -0
  50. package/dist/i18n/messages/es.d.ts +3 -0
  51. package/dist/i18n/messages/es.js +627 -0
  52. package/dist/i18n/messages/es.js.map +1 -0
  53. package/dist/i18n/messages/fr.d.ts +3 -0
  54. package/dist/i18n/messages/fr.js +627 -0
  55. package/dist/i18n/messages/fr.js.map +1 -0
  56. package/dist/i18n/messages/pt.d.ts +3 -0
  57. package/dist/i18n/messages/pt.js +627 -0
  58. package/dist/i18n/messages/pt.js.map +1 -0
  59. package/dist/i18n/validation.d.ts +3 -0
  60. package/dist/i18n/validation.js +36 -0
  61. package/dist/i18n/validation.js.map +1 -0
  62. package/dist/illustrations.d.ts +6 -0
  63. package/dist/illustrations.js +16 -0
  64. package/dist/illustrations.js.map +1 -0
  65. package/dist/import-dialog.d.ts +11 -0
  66. package/dist/import-dialog.js +152 -0
  67. package/dist/import-dialog.js.map +1 -0
  68. package/dist/index.d.ts +38 -0
  69. package/dist/index.js +39 -0
  70. package/dist/index.js.map +1 -0
  71. package/dist/inline-edit.d.ts +18 -0
  72. package/dist/inline-edit.js +115 -0
  73. package/dist/inline-edit.js.map +1 -0
  74. package/dist/landing.d.ts +79 -0
  75. package/dist/landing.js +122 -0
  76. package/dist/landing.js.map +1 -0
  77. package/dist/locale-switcher.d.ts +4 -0
  78. package/dist/locale-switcher.js +15 -0
  79. package/dist/locale-switcher.js.map +1 -0
  80. package/dist/map.d.ts +26 -0
  81. package/dist/map.js +232 -0
  82. package/dist/map.js.map +1 -0
  83. package/dist/notifications.d.ts +12 -0
  84. package/dist/notifications.js +75 -0
  85. package/dist/notifications.js.map +1 -0
  86. package/dist/record-mutation.d.ts +19 -0
  87. package/dist/record-mutation.js +39 -0
  88. package/dist/record-mutation.js.map +1 -0
  89. package/dist/resource-detail.d.ts +4 -0
  90. package/dist/resource-detail.js +96 -0
  91. package/dist/resource-detail.js.map +1 -0
  92. package/dist/resource-form.d.ts +11 -0
  93. package/dist/resource-form.js +92 -0
  94. package/dist/resource-form.js.map +1 -0
  95. package/dist/resource-list.d.ts +10 -0
  96. package/dist/resource-list.js +154 -0
  97. package/dist/resource-list.js.map +1 -0
  98. package/dist/saved-views.d.ts +16 -0
  99. package/dist/saved-views.js +64 -0
  100. package/dist/saved-views.js.map +1 -0
  101. package/dist/schema-editor-diagram.d.ts +14 -0
  102. package/dist/schema-editor-diagram.js +54 -0
  103. package/dist/schema-editor-diagram.js.map +1 -0
  104. package/dist/schema-editor.d.ts +98 -0
  105. package/dist/schema-editor.js +571 -0
  106. package/dist/schema-editor.js.map +1 -0
  107. package/dist/shell.d.ts +10 -0
  108. package/dist/shell.js +228 -0
  109. package/dist/shell.js.map +1 -0
  110. package/dist/skeleton.d.ts +25 -0
  111. package/dist/skeleton.js +34 -0
  112. package/dist/skeleton.js.map +1 -0
  113. package/dist/theme-catalog.d.ts +71 -0
  114. package/dist/theme-catalog.js +55 -0
  115. package/dist/theme-catalog.js.map +1 -0
  116. package/dist/theme-head.d.ts +8 -0
  117. package/dist/theme-head.js +11 -0
  118. package/dist/theme-head.js.map +1 -0
  119. package/dist/theme-preview.d.ts +2 -0
  120. package/dist/theme-preview.js +23 -0
  121. package/dist/theme-preview.js.map +1 -0
  122. package/dist/theme-switcher.d.ts +20 -0
  123. package/dist/theme-switcher.js +159 -0
  124. package/dist/theme-switcher.js.map +1 -0
  125. package/dist/theme.d.ts +24 -0
  126. package/dist/theme.js +30 -0
  127. package/dist/theme.js.map +1 -0
  128. package/dist/toast.d.ts +21 -0
  129. package/dist/toast.js +51 -0
  130. package/dist/toast.js.map +1 -0
  131. package/dist/ui.d.ts +86 -0
  132. package/dist/ui.js +106 -0
  133. package/dist/ui.js.map +1 -0
  134. package/dist/views.d.ts +23 -0
  135. package/dist/views.js +238 -0
  136. package/dist/views.js.map +1 -0
  137. package/package.json +58 -0
  138. package/styles.css +778 -0
@@ -0,0 +1,571 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { Check, ChevronDown, ChevronUp, Database, GripVertical, Pencil, Plus, SlidersHorizontal, Trash2, Undo2, X } from "lucide-react";
4
+ import { useCallback, useEffect, useMemo, useState } from "react";
5
+ import { useForge, useMe } from "./context.js";
6
+ import { SchemaDiagram } from "./schema-editor-diagram.js";
7
+ import { useToast } from "./toast.js";
8
+ import { Alert, Badge, Button, Card, Dialog, EmptyState, Input, Label, PageHeader, Select, Spinner, cn } from "./ui.js";
9
+ /** Nav entry for the schema editor (development only); the shell links it under Administration for admins. */
10
+ export const SCHEMA_EDITOR_NAV = { label: "schema.nav", path: "admin/schema" };
11
+ const BASE = "/forge-dev/schema";
12
+ const EXIT_MARKER = "__FORGE_EXIT__";
13
+ const NAME = /^[A-Za-z][A-Za-z0-9]*$/;
14
+ const ENUM_VALUE = /^[A-Za-z][A-Za-z0-9_]*$/;
15
+ const ENTITY_NAME = /^[A-Z][A-Za-z0-9]*$/;
16
+ /** Mirrors RESERVED_ENTITY_NAMES in @tekki-forge/compiler (the server checks again). */
17
+ const RESERVED_ENTITIES = ["User", "Session", "Account", "Verification", "Organization", "Member", "Invitation", "TwoFactor", "Passkey", "AuditLog"];
18
+ export const SCHEMA_FIELD_TYPES = [
19
+ "string", "text", "richtext", "integer", "decimal", "money", "percentage", "boolean", "date", "datetime", "enum",
20
+ "email", "url", "phone", "color", "json", "location", "file", "image", "computed", "relation",
21
+ ];
22
+ const COMPUTED_TYPES = ["string", "integer", "decimal", "money", "percentage", "boolean", "date", "datetime"];
23
+ const NUMERIC = ["integer", "decimal", "money", "percentage"];
24
+ const ICONS = ["folder", "users", "user", "briefcase", "building", "file-text", "box", "tag", "layers", "star", "calendar", "credit-card", "mail", "map-pin", "package", "shopping-cart", "ticket", "check-square"];
25
+ class DevError extends Error {
26
+ status;
27
+ body;
28
+ constructor(status, body) {
29
+ super(body?.error ?? `Request failed (${status})`);
30
+ this.status = status;
31
+ this.body = body;
32
+ }
33
+ }
34
+ async function dev(path, body) {
35
+ const res = await fetch(`${BASE}${path}`, {
36
+ method: body === undefined ? "GET" : "POST",
37
+ credentials: "same-origin",
38
+ cache: "no-store",
39
+ headers: body === undefined ? { accept: "application/json" } : { accept: "application/json", "content-type": "application/json" },
40
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
41
+ });
42
+ const data = res.headers.get("content-type")?.includes("json") ? await res.json().catch(() => null) : null;
43
+ if (!res.ok)
44
+ throw new DevError(res.status, data);
45
+ return data;
46
+ }
47
+ // ---------------------------------------------------------------------------------------------
48
+ // Model
49
+ let seq = 0;
50
+ const uid = () => `k${++seq}`;
51
+ const titleCase = (s) => s
52
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
53
+ .split(/[\s_-]+/)
54
+ .filter(Boolean)
55
+ .map((w, i) => (i === 0 ? w[0].toUpperCase() + w.slice(1) : w.toLowerCase()))
56
+ .join(" ");
57
+ function formatSize(bytes) {
58
+ for (const [unit, n] of [["GB", 1024 ** 3], ["MB", 1024 ** 2], ["KB", 1024]])
59
+ if (bytes % n === 0)
60
+ return `${bytes / n}${unit}`;
61
+ return String(bytes);
62
+ }
63
+ /** The editable view of a compiled field (mirrors draftFromField in tekki-forge/schema-api). */
64
+ function draftFromField(f) {
65
+ const d = { name: f.name, type: (f.computed ? "computed" : f.kind) };
66
+ if (f.computed) {
67
+ d.computedType = f.kind;
68
+ d.expression = f.computed.expression;
69
+ }
70
+ if (f.required && !f.computed)
71
+ d.required = true;
72
+ if (f.unique)
73
+ d.unique = true;
74
+ if (f.searchable)
75
+ d.searchable = true;
76
+ if (f.enumValues) {
77
+ d.values = f.enumValues.map((v) => v.value);
78
+ if (f.enumValues.some((v) => v.label !== titleCase(v.value)))
79
+ d.labels = Object.fromEntries(f.enumValues.map((v) => [v.value, v.label]));
80
+ }
81
+ if (f.relation) {
82
+ d.entity = f.relation.entity;
83
+ if (f.relation.type === "many-to-many")
84
+ d.many = true;
85
+ if (f.relation.owner)
86
+ d.owner = true;
87
+ }
88
+ if (f.currency && f.kind === "money" && !f.computed)
89
+ d.currency = f.currency;
90
+ if (f.file) {
91
+ if (f.file.accept.length)
92
+ d.accept = f.file.accept;
93
+ d.maxSize = formatSize(f.file.maxSize);
94
+ }
95
+ if (f.default?.kind === "now")
96
+ d.default = "now";
97
+ else if (f.default?.kind === "value" && f.default.value !== null && typeof f.default.value !== "object")
98
+ d.default = f.default.value;
99
+ return d;
100
+ }
101
+ function entityFromIR(e, editable) {
102
+ return {
103
+ key: uid(),
104
+ name: e.name,
105
+ origName: e.name,
106
+ editable,
107
+ removed: false,
108
+ fields: e.fields.map((f) => ({ key: uid(), origName: f.name, draft: draftFromField(f) })),
109
+ options: { label: e.label, pluralLabel: e.pluralLabel, icon: e.icon, display: e.display, nav: e.nav },
110
+ };
111
+ }
112
+ function modelFrom(state) {
113
+ return (state.ir?.entities ?? []).map((e) => entityFromIR(e, !!state.entities?.[e.name]));
114
+ }
115
+ /** Drop empty/false values so two drafts compare by meaning. */
116
+ function clean(d) {
117
+ const out = {};
118
+ for (const [k, v] of Object.entries(d)) {
119
+ if (v === undefined || v === false || v === "" || (Array.isArray(v) && !v.length))
120
+ continue;
121
+ out[k] = v;
122
+ }
123
+ // Options that do not apply to the chosen type.
124
+ const t = d.type;
125
+ if (t !== "enum")
126
+ delete out.values, delete out.labels;
127
+ if (t !== "relation")
128
+ delete out.entity, delete out.many, delete out.owner;
129
+ if (t !== "money")
130
+ delete out.currency;
131
+ if (t !== "file" && t !== "image")
132
+ delete out.accept, delete out.maxSize;
133
+ if (t !== "computed")
134
+ delete out.computedType, delete out.expression;
135
+ else
136
+ delete out.required, delete out.unique, delete out.default;
137
+ if (out.labels && Array.isArray(out.values))
138
+ out.labels = Object.fromEntries(out.values.map((v) => [v, out.labels[v] ?? titleCase(v)]));
139
+ return out;
140
+ }
141
+ const same = (a, b) => JSON.stringify(clean(a)) === JSON.stringify(clean(b));
142
+ /** Turn the difference between the loaded schema and the edited one into server operations. */
143
+ export function computeOperations(original, working) {
144
+ const ops = [];
145
+ // Renames first: the server rewrites every reference, and later operations use the new names.
146
+ const renames = new Map();
147
+ for (const w of working) {
148
+ if (w.origName && !w.removed && w.editable && w.name !== w.origName) {
149
+ renames.set(w.origName, w.name);
150
+ ops.push({ op: "renameEntity", from: w.origName, to: w.name });
151
+ }
152
+ }
153
+ const renamed = (d) => (d.entity && renames.has(d.entity) ? { ...d, entity: renames.get(d.entity) } : d);
154
+ for (const w of working) {
155
+ if (w.removed) {
156
+ if (w.origName)
157
+ ops.push({ op: "removeEntity", name: w.origName });
158
+ continue;
159
+ }
160
+ if (!w.origName) {
161
+ ops.push({ op: "addEntity", name: w.name, fields: w.fields.map((f) => clean(f.draft)), ...(w.features && (w.features.audit || w.features.softDelete) ? { features: w.features } : {}) });
162
+ for (const key of ["label", "pluralLabel", "icon", "display"])
163
+ if (w.options[key])
164
+ ops.push({ op: "setEntityOption", entity: w.name, key, value: w.options[key] });
165
+ if (!w.options.nav)
166
+ ops.push({ op: "setEntityOption", entity: w.name, key: "nav", value: false });
167
+ continue;
168
+ }
169
+ const o = original.find((x) => x.origName === w.origName);
170
+ if (!o || !w.editable)
171
+ continue;
172
+ for (const key of ["label", "pluralLabel", "icon", "display", "nav"]) {
173
+ if (w.options[key] !== o.options[key])
174
+ ops.push({ op: "setEntityOption", entity: w.name, key, value: w.options[key] === "" ? null : w.options[key] });
175
+ }
176
+ for (const of of o.fields)
177
+ if (!w.fields.some((f) => f.origName === of.origName))
178
+ ops.push({ op: "removeField", entity: w.name, name: of.origName });
179
+ for (const f of w.fields) {
180
+ const of = f.origName ? o.fields.find((x) => x.origName === f.origName) : undefined;
181
+ if (of && !same(renamed(of.draft), f.draft))
182
+ ops.push({ op: "updateField", entity: w.name, name: f.origName, field: clean(f.draft) });
183
+ }
184
+ for (const f of w.fields)
185
+ if (!f.origName)
186
+ ops.push({ op: "addField", entity: w.name, field: clean(f.draft) });
187
+ // Order after the edits above: original order (renamed in place) then added fields at the end.
188
+ const current = [
189
+ ...o.fields.flatMap((of) => {
190
+ const f = w.fields.find((x) => x.origName === of.origName);
191
+ return f ? [f.draft.name] : [];
192
+ }),
193
+ ...w.fields.filter((f) => !f.origName).map((f) => f.draft.name),
194
+ ];
195
+ const target = w.fields.map((f) => f.draft.name);
196
+ for (let i = 0; i < target.length; i++) {
197
+ if (current[i] === target[i])
198
+ continue;
199
+ const j = current.indexOf(target[i]);
200
+ if (j < 0)
201
+ continue;
202
+ current.splice(j, 1);
203
+ current.splice(i, 0, target[i]);
204
+ ops.push({ op: "moveField", entity: w.name, name: target[i], to: i });
205
+ }
206
+ }
207
+ return ops;
208
+ }
209
+ function fieldProblem(f, siblings, t) {
210
+ if (!NAME.test(f.name))
211
+ return t("schema.error.name");
212
+ if (siblings.filter((s) => s.draft.name === f.name).length > 1)
213
+ return t("schema.error.duplicate");
214
+ if (f.type === "enum" && (!f.values?.length || f.values.some((v) => !ENUM_VALUE.test(v))))
215
+ return t("schema.error.enumValues");
216
+ if (f.type === "relation" && !f.entity)
217
+ return t("schema.error.target");
218
+ if (f.type === "computed" && !f.expression?.trim())
219
+ return t("schema.error.expression");
220
+ return undefined;
221
+ }
222
+ export function SchemaEditorPage(_props) {
223
+ const { t } = useForge();
224
+ const me = useMe();
225
+ const [load, setLoad] = useState({ status: "loading" });
226
+ const [original, setOriginal] = useState([]);
227
+ const [working, setWorking] = useState([]);
228
+ const [selected, setSelected] = useState(null);
229
+ const [tab, setTab] = useState("editor");
230
+ const [reviewing, setReviewing] = useState(false);
231
+ const [appliedAt, setAppliedAt] = useState(0);
232
+ const accept = useCallback((state) => {
233
+ const model = modelFrom(state);
234
+ setOriginal(model);
235
+ setWorking(structuredClone(model));
236
+ setSelected((s) => (s && model.some((e) => e.name === s) ? s : (model[0]?.name ?? null)));
237
+ setLoad({ status: "ready", state });
238
+ }, []);
239
+ const reload = useCallback(() => {
240
+ setLoad({ status: "loading" });
241
+ dev("")
242
+ .then(accept)
243
+ .catch((e) => {
244
+ if (e instanceof DevError && e.status === 404)
245
+ setLoad({ status: "unavailable" });
246
+ else if (e instanceof DevError && e.status === 403)
247
+ setLoad({ status: "forbidden" });
248
+ else
249
+ setLoad({ status: "error", message: e instanceof Error ? e.message : String(e) });
250
+ });
251
+ }, [accept]);
252
+ useEffect(reload, [reload]);
253
+ const operations = useMemo(() => computeOperations(original, working), [original, working]);
254
+ const problems = useMemo(() => working.filter((e) => !e.removed).flatMap((e) => [...(entityNameProblem(e, working, t) ? [e.name] : []), ...(e.fields.length ? [] : [e.name]), ...e.fields.filter((f) => fieldProblem(f.draft, e.fields, t)).map((f) => `${e.name}.${f.draft.name}`)]), [working, t]);
255
+ if (load.status === "loading" || me.isLoading)
256
+ return _jsx(Spinner, {});
257
+ if (load.status === "unavailable")
258
+ return (_jsxs(_Fragment, { children: [_jsx(PageHeader, { title: t("schema.title") }), _jsx(Card, { className: "p-6", children: _jsxs("div", { className: "flex items-start gap-3", children: [_jsx(Database, { className: "mt-0.5 size-5 text-ink-muted", "aria-hidden": true }), _jsxs("div", { children: [_jsx("p", { className: "text-sm font-medium text-ink", children: t("schema.unavailable.title") }), _jsx("p", { className: "mt-1 text-sm text-ink-muted", children: t("schema.unavailable.body") })] })] }) })] }));
259
+ if (load.status === "forbidden" || (me.data && !me.isAdmin))
260
+ return (_jsxs(_Fragment, { children: [_jsx(PageHeader, { title: t("schema.title") }), _jsx(Alert, { children: t("schema.forbidden") })] }));
261
+ if (load.status === "error")
262
+ return (_jsxs(_Fragment, { children: [_jsx(PageHeader, { title: t("schema.title") }), _jsx(Alert, { children: t("schema.loadError", { message: load.message }) }), _jsx("div", { className: "mt-4", children: _jsx(Button, { onClick: reload, children: t("schema.reload") }) })] }));
263
+ const state = load.state;
264
+ if (!state.ir)
265
+ return (_jsxs(_Fragment, { children: [_jsx(PageHeader, { title: t("schema.title"), actions: _jsx(Button, { onClick: reload, children: t("schema.reload") }) }), _jsxs(Alert, { children: [_jsx("p", { children: t("schema.invalidConfig") }), _jsx(IssueList, { issues: state.issues ?? [] })] })] }));
266
+ const current = working.find((e) => e.name === selected) ?? null;
267
+ const update = (key, fn) => setWorking((all) => all.map((e) => (e.key === key ? fn(e) : e)));
268
+ const targets = [...working.filter((e) => !e.removed).map((e) => e.name), "User", ...(state.ir.tenancy.enabled ? ["Organization"] : [])];
269
+ const addEntity = () => {
270
+ let name = "NewEntity";
271
+ for (let i = 2; working.some((e) => e.name === name); i++)
272
+ name = `NewEntity${i}`;
273
+ const e = {
274
+ key: uid(),
275
+ name,
276
+ editable: true,
277
+ removed: false,
278
+ fields: [{ key: uid(), draft: { name: "name", type: "string", required: true, searchable: true } }],
279
+ options: { label: "", pluralLabel: "", icon: "", display: "", nav: true },
280
+ };
281
+ setWorking((all) => [...all, e]);
282
+ setSelected(name);
283
+ setTab("editor");
284
+ };
285
+ return (_jsxs(_Fragment, { children: [_jsx(PageHeader, { title: t("schema.title"), description: t("schema.description"), actions: _jsxs(_Fragment, { children: [_jsx("div", { role: "tablist", "aria-label": t("schema.title"), className: "forge-input flex h-9 items-center gap-0.5 p-0.5", children: ["editor", "diagram"].map((k) => (_jsx("button", { type: "button", role: "tab", "aria-selected": tab === k, onClick: () => setTab(k), className: cn("flex h-full items-center rounded px-3 text-sm", tab === k ? "bg-selected text-ink" : "text-ink-muted hover:text-ink"), children: k === "editor" ? t("schema.tab.editor") : t("schema.tab.diagram") }, k))) }), _jsxs(Button, { variant: "primary", disabled: !operations.length || problems.length > 0, onClick: () => setReviewing(true), children: [t("schema.review"), operations.length > 0 && _jsx(Badge, { children: operations.length })] })] }) }), appliedAt > 0 && _jsx(AppliedPanel, { onClose: () => setAppliedAt(0) }, appliedAt), tab === "diagram" ? (_jsx(SchemaDiagram, { entities: working
286
+ .filter((e) => !e.removed)
287
+ .map((e) => ({ name: e.name, fields: e.fields.map((f) => ({ name: f.draft.name, type: f.draft.type === "computed" ? `= ${f.draft.computedType ?? "string"}` : f.draft.type, entity: f.draft.type === "relation" ? f.draft.entity : undefined, many: f.draft.many, required: f.draft.required })) })) })) : (_jsxs("div", { className: "grid gap-4 lg:grid-cols-[220px_minmax(0,1fr)_260px]", children: [_jsxs(Card, { className: "h-fit p-2", children: [_jsx("p", { className: "px-2 pt-1 pb-2 text-xs font-semibold tracking-wide text-ink-muted uppercase", children: t("schema.entities") }), _jsx("ul", { className: "space-y-0.5", children: working.map((e) => (_jsx("li", { children: _jsxs("button", { type: "button", onClick: () => setSelected(e.name), className: cn("flex w-full items-center justify-between gap-2 rounded px-2 py-1.5 text-left text-sm", selected === e.name ? "bg-selected text-ink" : "text-ink hover:bg-hover", e.removed && "line-through opacity-60"), children: [_jsx("span", { className: "truncate", children: e.name }), _jsx("span", { className: "shrink-0 text-xs text-ink-muted", children: t("schema.fieldCount", { count: e.fields.length }) })] }) }, e.key))) }), _jsxs(Button, { size: "sm", className: "mt-2 w-full", onClick: addEntity, children: [_jsx(Plus, { className: "size-3.5", "aria-hidden": true }), " ", t("schema.newEntity")] })] }), _jsx("div", { className: "min-w-0", children: current ? (_jsx(EntityEditor, { entity: current, targets: targets, otherNames: working.filter((e) => e.key !== current.key).map((e) => e.name), onChange: (fn) => {
288
+ const next = fn(current);
289
+ update(current.key, () => next);
290
+ if (next.name !== current.name)
291
+ setSelected(next.name);
292
+ }, onRename: (to) => {
293
+ const from = current.name;
294
+ // Relations pointing at the entity follow it (the server rewrites them in forge.config.ts too).
295
+ setWorking((all) => all.map((e) => ({
296
+ ...(e.key === current.key ? { ...e, name: to } : e),
297
+ fields: e.fields.map((f) => (f.draft.type === "relation" && f.draft.entity === from ? { ...f, draft: { ...f.draft, entity: to } } : f)),
298
+ })));
299
+ setSelected(to);
300
+ } }, current.key)) : (_jsx(Card, { children: _jsx(EmptyState, { title: t("schema.noEntity") }) })) }), _jsxs(Card, { className: "h-fit p-3", children: [_jsxs("div", { className: "mb-2 flex items-center justify-between", children: [_jsx("p", { className: "text-sm font-semibold text-ink", children: t("schema.pending") }), operations.length > 0 && (_jsxs(Button, { size: "sm", variant: "ghost", onClick: () => setWorking(structuredClone(original)), children: [_jsx(Undo2, { className: "size-3.5", "aria-hidden": true }), " ", t("schema.discard")] }))] }), operations.length ? (_jsx("ol", { className: "space-y-1 text-sm text-ink", children: operations.map((op, i) => (_jsx("li", { className: "rounded bg-surface-muted px-2 py-1 text-xs", children: _jsx(OperationLabel, { op: op }) }, i))) })) : (_jsx("p", { className: "text-sm text-ink-muted", children: t("schema.pendingEmpty") })), problems.length > 0 && (_jsxs("p", { className: "mt-2 text-xs text-danger", children: [t("schema.fixProblems"), " ", problems.join(", ")] }))] })] })), reviewing && (_jsx(ReviewDialog, { operations: operations, expectedSource: state.source, onClose: () => setReviewing(false), onConflict: () => {
301
+ setReviewing(false);
302
+ reload();
303
+ }, onApplied: (next) => {
304
+ setReviewing(false);
305
+ accept(next);
306
+ setAppliedAt(Date.now());
307
+ } }))] }));
308
+ }
309
+ function OperationLabel({ op }) {
310
+ const { t } = useForge();
311
+ switch (op.op) {
312
+ case "addEntity":
313
+ return _jsx(_Fragment, { children: t("schema.op.addEntity", { entity: op.name }) });
314
+ case "removeEntity":
315
+ return _jsx(_Fragment, { children: t("schema.op.removeEntity", { entity: op.name }) });
316
+ case "renameEntity":
317
+ return _jsx(_Fragment, { children: t("schema.op.renameEntity", { from: op.from, to: op.to }) });
318
+ case "addField":
319
+ return _jsx(_Fragment, { children: t("schema.op.addField", { entity: op.entity, field: op.field.name }) });
320
+ case "updateField":
321
+ return _jsx(_Fragment, { children: t("schema.op.updateField", { entity: op.entity, field: op.name }) });
322
+ case "removeField":
323
+ return _jsx(_Fragment, { children: t("schema.op.removeField", { entity: op.entity, field: op.name }) });
324
+ case "moveField":
325
+ return _jsx(_Fragment, { children: t("schema.op.moveField", { entity: op.entity, field: op.name, position: op.to + 1 }) });
326
+ case "setEntityOption":
327
+ return _jsx(_Fragment, { children: t("schema.op.setEntityOption", { entity: op.entity, option: op.key }) });
328
+ }
329
+ }
330
+ function IssueList({ issues }) {
331
+ return (_jsx("ul", { className: "mt-1 list-disc space-y-0.5 pl-5", children: issues.map((i, k) => (_jsxs("li", { children: [_jsx("code", { className: "font-mono text-xs", children: i.path }), " ", i.message] }, k))) }));
332
+ }
333
+ // ---------------------------------------------------------------------------------------------
334
+ // Entity editor
335
+ /** Problem with an entity's (new) name, if any. Existing entities keep their name unless renamed. */
336
+ function entityNameProblem(e, all, t) {
337
+ if (e.origName && e.name === e.origName)
338
+ return undefined;
339
+ if (!(e.origName ? ENTITY_NAME : NAME).test(e.name))
340
+ return e.origName ? t("schema.error.entityName") : t("schema.error.name");
341
+ if (RESERVED_ENTITIES.includes(e.name))
342
+ return t("schema.error.reserved");
343
+ if (all.some((x) => x.key !== e.key && (x.name === e.name || x.origName === e.name)))
344
+ return t("schema.error.duplicate");
345
+ return undefined;
346
+ }
347
+ /** Name of an existing entity, with an inline rename. */
348
+ function EntityTitle({ entity, otherNames, onRename }) {
349
+ const { t } = useForge();
350
+ const [editing, setEditing] = useState(false);
351
+ const [value, setValue] = useState(entity.name);
352
+ const canRename = entity.editable && !entity.removed;
353
+ const problem = !ENTITY_NAME.test(value)
354
+ ? t("schema.error.entityName")
355
+ : RESERVED_ENTITIES.includes(value)
356
+ ? t("schema.error.reserved")
357
+ : value !== entity.name && otherNames.includes(value)
358
+ ? t("schema.error.duplicate")
359
+ : undefined;
360
+ const commit = () => {
361
+ if (problem)
362
+ return;
363
+ if (value !== entity.name)
364
+ onRename(value);
365
+ setEditing(false);
366
+ };
367
+ const cancel = () => {
368
+ setValue(entity.name);
369
+ setEditing(false);
370
+ };
371
+ if (editing)
372
+ return (_jsxs("form", { className: "min-w-56", onSubmit: (e) => {
373
+ e.preventDefault();
374
+ commit();
375
+ }, children: [_jsx(Label, { htmlFor: "schema-entity-rename", children: t("schema.renameEntity.label") }), _jsxs("div", { className: "flex items-center gap-1", children: [_jsx(Input, { id: "schema-entity-rename", value: value, autoFocus: true, "aria-invalid": !!problem, "aria-describedby": "schema-entity-rename-hint", onChange: (e) => setValue(e.target.value.replace(/\s+/g, "")), onKeyDown: (e) => {
376
+ if (e.key === "Escape") {
377
+ e.preventDefault();
378
+ cancel();
379
+ }
380
+ } }), _jsx(Button, { size: "sm", type: "submit", variant: "primary", disabled: !!problem, "aria-label": t("schema.renameEntity.save"), children: _jsx(Check, { className: "size-3.5", "aria-hidden": true }) }), _jsx(Button, { size: "sm", type: "button", variant: "ghost", onClick: cancel, "aria-label": t("schema.renameEntity.cancel"), children: _jsx(X, { className: "size-3.5", "aria-hidden": true }) })] }), _jsx("p", { id: "schema-entity-rename-hint", className: cn("mt-1 text-xs", problem ? "text-danger" : "text-ink-muted"), children: problem ?? t("schema.renameEntity.hint") })] }));
381
+ return (_jsxs("div", { className: "flex min-w-0 items-center gap-2", children: [_jsx("h2", { className: cn("text-base font-semibold text-ink", entity.removed && "line-through"), children: entity.name }), entity.origName && entity.name !== entity.origName && (_jsx("span", { className: "text-xs text-ink-muted", children: t("schema.renameEntity.was", { name: entity.origName }) })), canRename && (_jsxs(Button, { size: "sm", variant: "ghost", onClick: () => {
382
+ setValue(entity.name);
383
+ setEditing(true);
384
+ }, children: [_jsx(Pencil, { className: "size-3.5", "aria-hidden": true }), " ", t("schema.renameEntity.action")] }))] }));
385
+ }
386
+ function EntityEditor({ entity, targets, otherNames, onChange, onRename, }) {
387
+ const { t } = useForge();
388
+ const [dragging, setDragging] = useState(null);
389
+ const [open, setOpen] = useState(null);
390
+ const readOnly = !entity.editable || entity.removed;
391
+ const setFields = (fn) => onChange((e) => ({ ...e, fields: fn(e.fields) }));
392
+ const move = (from, to) => setFields((fields) => {
393
+ if (to < 0 || to >= fields.length || from === to)
394
+ return fields;
395
+ const next = [...fields];
396
+ const [f] = next.splice(from, 1);
397
+ next.splice(to, 0, f);
398
+ return next;
399
+ });
400
+ const setOption = (key, value) => onChange((e) => ({ ...e, options: { ...e.options, [key]: value } }));
401
+ const addField = () => {
402
+ let name = "newField";
403
+ for (let i = 2; entity.fields.some((f) => f.draft.name === name); i++)
404
+ name = `newField${i}`;
405
+ const key = uid();
406
+ setFields((fields) => [...fields, { key, draft: { name, type: "string" } }]);
407
+ setOpen(key);
408
+ };
409
+ const nameTaken = !entity.origName && otherNames.includes(entity.name);
410
+ const scalarFields = entity.fields.filter((f) => !["relation", "json", "location", "file", "image"].includes(f.draft.type)).map((f) => f.draft.name);
411
+ const icons = entity.options.icon && !ICONS.includes(entity.options.icon) ? [entity.options.icon, ...ICONS] : ICONS;
412
+ return (_jsxs("div", { className: "space-y-4", children: [_jsxs(Card, { className: "p-4", children: [_jsxs("div", { className: "flex flex-wrap items-center justify-between gap-3", children: [entity.origName ? (_jsx(EntityTitle, { entity: entity, otherNames: otherNames, onRename: onRename })) : (_jsxs("div", { className: "min-w-56", children: [_jsx(Label, { htmlFor: "schema-entity-name", children: t("schema.newEntityName") }), _jsx(Input, { id: "schema-entity-name", value: entity.name, "aria-invalid": !NAME.test(entity.name) || nameTaken, onChange: (e) => onChange((x) => ({ ...x, name: e.target.value.replace(/\s+/g, "") })) }), _jsx("p", { className: cn("mt-1 text-xs", !NAME.test(entity.name) || nameTaken ? "text-danger" : "text-ink-muted"), children: nameTaken ? t("schema.error.duplicate") : !NAME.test(entity.name) ? t("schema.error.name") : t("schema.newEntityHint") })] })), entity.editable &&
413
+ (entity.removed ? (_jsxs(Button, { size: "sm", onClick: () => onChange((e) => ({ ...e, removed: false })), children: [_jsx(Undo2, { className: "size-3.5", "aria-hidden": true }), " ", t("schema.restoreEntity")] })) : (_jsxs(Button, { size: "sm", variant: "danger-ghost", onClick: () => onChange((e) => ({ ...e, removed: true })), children: [_jsx(Trash2, { className: "size-3.5", "aria-hidden": true }), " ", t("schema.removeEntity")] })))] }), !entity.editable && _jsx("p", { className: "mt-2 text-sm text-ink-muted", children: t("schema.readOnlyEntity") }), entity.removed && _jsx("p", { className: "mt-2 text-sm text-danger", children: t("schema.entityRemoved") })] }), _jsxs(Card, { className: "p-4", children: [_jsxs("div", { className: "mb-3 flex items-center justify-between", children: [_jsx("h3", { className: "text-sm font-semibold text-ink", children: t("schema.fields") }), !readOnly && (_jsxs(Button, { size: "sm", onClick: addField, children: [_jsx(Plus, { className: "size-3.5", "aria-hidden": true }), " ", t("schema.addField")] }))] }), !entity.fields.length && _jsx("p", { className: "text-sm text-danger", children: t("schema.error.noFields") }), _jsx("ul", { className: "space-y-2", children: entity.fields.map((f, i) => (_jsx("li", { draggable: !readOnly, onDragStart: (e) => {
414
+ setDragging(i);
415
+ e.dataTransfer.effectAllowed = "move";
416
+ }, onDragOver: (e) => {
417
+ if (dragging !== null)
418
+ e.preventDefault();
419
+ }, onDrop: (e) => {
420
+ e.preventDefault();
421
+ if (dragging !== null)
422
+ move(dragging, i);
423
+ setDragging(null);
424
+ }, onDragEnd: () => setDragging(null), className: cn("rounded border border-line bg-surface", dragging === i && "opacity-50"), children: _jsx(FieldRow, { field: f, index: i, count: entity.fields.length, siblings: entity.fields, targets: targets, readOnly: readOnly, open: open === f.key, onToggle: () => setOpen((o) => (o === f.key ? null : f.key)), onMove: (to) => move(i, to), onRemove: () => setFields((fields) => fields.filter((x) => x.key !== f.key)), onChange: (draft) => setFields((fields) => fields.map((x) => (x.key === f.key ? { ...x, draft } : x))) }) }, f.key))) })] }), _jsxs(Card, { className: "p-4", children: [_jsx("h3", { className: "mb-3 text-sm font-semibold text-ink", children: t("schema.options") }), _jsxs("div", { className: "grid gap-3 sm:grid-cols-2", children: [_jsx(TextOption, { id: "label", label: t("schema.option.label"), value: entity.options.label, disabled: readOnly, onChange: (v) => setOption("label", v) }), _jsx(TextOption, { id: "pluralLabel", label: t("schema.option.pluralLabel"), value: entity.options.pluralLabel, disabled: readOnly, onChange: (v) => setOption("pluralLabel", v) }), _jsxs("div", { children: [_jsx(Label, { htmlFor: "schema-opt-icon", children: t("schema.option.icon") }), _jsxs(Select, { id: "schema-opt-icon", value: entity.options.icon, disabled: readOnly, onChange: (e) => setOption("icon", e.target.value), children: [_jsx("option", { value: "", children: t("schema.option.default") }), icons.map((i) => (_jsx("option", { value: i, children: i }, i)))] })] }), _jsxs("div", { children: [_jsx(Label, { htmlFor: "schema-opt-display", children: t("schema.option.display") }), _jsxs(Select, { id: "schema-opt-display", value: entity.options.display, disabled: readOnly, onChange: (e) => setOption("display", e.target.value), children: [_jsx("option", { value: "", children: t("schema.option.default") }), [...new Set([entity.options.display, ...scalarFields].filter(Boolean))].map((n) => (_jsx("option", { value: n, children: n }, n)))] })] }), _jsx(Toggle, { label: t("schema.option.nav"), checked: entity.options.nav, disabled: readOnly, onChange: (v) => setOption("nav", v) }), !entity.origName && (_jsxs(_Fragment, { children: [_jsx(Toggle, { label: t("schema.feature.audit"), checked: !!entity.features?.audit, onChange: (v) => onChange((e) => ({ ...e, features: { ...e.features, audit: v } })) }), _jsx(Toggle, { label: t("schema.feature.softDelete"), checked: !!entity.features?.softDelete, onChange: (v) => onChange((e) => ({ ...e, features: { ...e.features, softDelete: v } })) })] }))] })] })] }));
425
+ }
426
+ function TextOption({ id, label, value, disabled, onChange }) {
427
+ const { t } = useForge();
428
+ return (_jsxs("div", { children: [_jsx(Label, { htmlFor: `schema-opt-${id}`, children: label }), _jsx(Input, { id: `schema-opt-${id}`, value: value, maxLength: 80, disabled: disabled, placeholder: t("schema.option.default"), onChange: (e) => onChange(e.target.value) })] }));
429
+ }
430
+ function Toggle({ label, checked, disabled, onChange }) {
431
+ return (_jsxs("label", { className: cn("flex items-center gap-2 text-sm text-ink", disabled && "opacity-60"), children: [_jsx("input", { type: "checkbox", className: "forge-check", checked: checked, disabled: disabled, onChange: (e) => onChange(e.target.checked) }), label] }));
432
+ }
433
+ /** Comma-separated list input that only commits on blur, so typing "a, b" is not reformatted mid-word. */
434
+ function ListInput({ id, value, disabled, placeholder, onCommit }) {
435
+ const joined = value.join(", ");
436
+ const [text, setText] = useState(joined);
437
+ useEffect(() => setText(joined), [joined]);
438
+ return (_jsx(Input, { id: id, value: text, disabled: disabled, placeholder: placeholder, onChange: (e) => setText(e.target.value), onBlur: () => onCommit(text.split(",").map((s) => s.trim()).filter(Boolean)) }));
439
+ }
440
+ function FieldRow({ field, index, count, siblings, targets, readOnly, open, onToggle, onMove, onRemove, onChange, }) {
441
+ const { t } = useForge();
442
+ const d = field.draft;
443
+ const set = (patch) => onChange({ ...d, ...patch });
444
+ const problem = fieldProblem(d, siblings, t);
445
+ const id = `schema-f-${field.key}`;
446
+ const isText = ["string", "text", "richtext", "email", "url", "phone"].includes(d.type) || (d.type === "computed" && d.computedType === "string");
447
+ const canUnique = !["json", "relation", "file", "image", "location", "computed"].includes(d.type);
448
+ const parseDefault = (raw) => {
449
+ if (raw === "")
450
+ return undefined;
451
+ if (d.type === "boolean")
452
+ return raw === "true";
453
+ if (NUMERIC.includes(d.type) && raw.trim() !== "" && !Number.isNaN(Number(raw)))
454
+ return Number(raw);
455
+ return raw;
456
+ };
457
+ return (_jsxs("div", { className: "p-2", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [!readOnly && _jsx(GripVertical, { className: "size-4 shrink-0 cursor-grab text-ink-subtle", "aria-label": t("schema.field.drag") }), _jsx(Input, { "aria-label": t("schema.field.name"), "aria-invalid": !!problem, value: d.name, disabled: readOnly, className: cn("w-40 font-mono", problem && "border-danger"), onChange: (e) => set({ name: e.target.value.replace(/\s+/g, "") }) }), _jsx(Select, { "aria-label": t("schema.field.type"), value: d.type, disabled: readOnly, className: "w-36", onChange: (e) => set({ type: e.target.value }), children: SCHEMA_FIELD_TYPES.map((k) => (_jsx("option", { value: k, children: t(`schema.type.${k}`) }, k))) }), d.type === "relation" && (_jsxs(Select, { "aria-label": t("schema.field.target"), value: d.entity ?? "", disabled: readOnly, className: "w-36", onChange: (e) => set({ entity: e.target.value || undefined }), children: [_jsxs("option", { value: "", children: [t("schema.field.target"), "\u2026"] }), [...new Set([...(d.entity ? [d.entity] : []), ...targets])].map((n) => (_jsx("option", { value: n, children: n }, n)))] })), d.type !== "computed" && _jsx(Toggle, { label: t("schema.field.required"), checked: !!d.required, disabled: readOnly, onChange: (v) => set({ required: v }) }), canUnique && _jsx(Toggle, { label: t("schema.field.unique"), checked: !!d.unique, disabled: readOnly, onChange: (v) => set({ unique: v }) }), isText && _jsx(Toggle, { label: t("schema.field.searchable"), checked: !!d.searchable, disabled: readOnly, onChange: (v) => set({ searchable: v }) }), _jsxs("div", { className: "ml-auto flex items-center gap-0.5", children: [!field.origName && _jsx(Badge, { tone: 1, children: t("schema.field.new") }), _jsx("button", { type: "button", className: "forge-btn forge-btn-ghost p-1", "aria-label": t("schema.field.details"), "aria-expanded": open, title: t("schema.field.details"), onClick: onToggle, children: _jsx(SlidersHorizontal, { className: "size-4" }) }), !readOnly && (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", className: "forge-btn forge-btn-ghost p-1", "aria-label": t("schema.field.moveUp"), title: t("schema.field.moveUp"), disabled: index === 0, onClick: () => onMove(index - 1), children: _jsx(ChevronUp, { className: "size-4" }) }), _jsx("button", { type: "button", className: "forge-btn forge-btn-ghost p-1", "aria-label": t("schema.field.moveDown"), title: t("schema.field.moveDown"), disabled: index === count - 1, onClick: () => onMove(index + 1), children: _jsx(ChevronDown, { className: "size-4" }) }), _jsx("button", { type: "button", className: "forge-btn forge-btn-danger-ghost p-1", "aria-label": t("schema.field.remove"), title: t("schema.field.remove"), disabled: count === 1, onClick: onRemove, children: _jsx(Trash2, { className: "size-4" }) })] }))] })] }), problem && _jsx("p", { className: "mt-1 text-xs text-danger", children: problem }), open && (_jsxs("div", { className: "mt-3 grid gap-3 border-t border-line pt-3 sm:grid-cols-2", children: [d.type === "enum" && (_jsxs("div", { className: "sm:col-span-2", children: [_jsx(Label, { htmlFor: `${id}-values`, children: t("schema.field.values") }), _jsx(ListInput, { id: `${id}-values`, value: d.values ?? [], disabled: readOnly, placeholder: t("schema.field.valuesHint"), onCommit: (values) => set({ values, ...(d.labels ? { labels: Object.fromEntries(values.map((v) => [v, d.labels[v] ?? titleCase(v)])) } : {}) }) }), _jsx("p", { className: "mt-1 text-xs text-ink-muted", children: t("schema.field.valuesHint") })] })), d.type === "relation" && (_jsxs(_Fragment, { children: [_jsx(Toggle, { label: t("schema.field.many"), checked: !!d.many, disabled: readOnly, onChange: (v) => set({ many: v, ...(v ? { owner: false } : {}) }) }), !d.many && _jsx(Toggle, { label: t("schema.field.owner"), checked: !!d.owner, disabled: readOnly, onChange: (v) => set({ owner: v }) })] })), d.type === "money" && (_jsxs("div", { children: [_jsx(Label, { htmlFor: `${id}-currency`, children: t("schema.field.currency") }), _jsx(Input, { id: `${id}-currency`, value: d.currency ?? "", maxLength: 3, placeholder: "USD", disabled: readOnly, onChange: (e) => set({ currency: e.target.value.toUpperCase() || undefined }) })] })), (d.type === "file" || d.type === "image") && (_jsxs(_Fragment, { children: [_jsxs("div", { children: [_jsx(Label, { htmlFor: `${id}-accept`, children: t("schema.field.accept") }), _jsx(ListInput, { id: `${id}-accept`, value: d.accept ?? [], disabled: readOnly, placeholder: t("schema.field.acceptHint"), onCommit: (accept) => set({ accept: accept.length ? accept : undefined }) })] }), _jsxs("div", { children: [_jsx(Label, { htmlFor: `${id}-max`, children: t("schema.field.maxSize") }), _jsx(Input, { id: `${id}-max`, value: d.maxSize ?? "", placeholder: "10MB", disabled: readOnly, onChange: (e) => set({ maxSize: e.target.value.trim() || undefined }) })] })] })), d.type === "computed" && (_jsxs(_Fragment, { children: [_jsxs("div", { children: [_jsx(Label, { htmlFor: `${id}-ctype`, children: t("schema.field.computedType") }), _jsx(Select, { id: `${id}-ctype`, value: d.computedType ?? "string", disabled: readOnly, onChange: (e) => set({ computedType: e.target.value }), children: COMPUTED_TYPES.map((k) => (_jsx("option", { value: k, children: t(`schema.type.${k}`) }, k))) })] }), _jsxs("div", { className: "sm:col-span-2", children: [_jsx(Label, { htmlFor: `${id}-expr`, children: t("schema.field.expression") }), _jsx(Input, { id: `${id}-expr`, className: "font-mono", value: d.expression ?? "", disabled: readOnly, placeholder: "quantity * unitPrice", onChange: (e) => set({ expression: e.target.value }) })] })] })), !["computed", "relation", "file", "image", "json", "location"].includes(d.type) && (_jsxs("div", { children: [_jsx(Label, { htmlFor: `${id}-default`, children: t("schema.field.default") }), d.type === "boolean" ? (_jsxs(Select, { id: `${id}-default`, value: d.default === undefined ? "" : String(d.default), disabled: readOnly, onChange: (e) => set({ default: parseDefault(e.target.value) }), children: [_jsx("option", { value: "", children: "\u2014" }), _jsx("option", { value: "true", children: t("common.yes") }), _jsx("option", { value: "false", children: t("common.no") })] })) : d.type === "enum" ? (_jsxs(Select, { id: `${id}-default`, value: d.default === undefined ? "" : String(d.default), disabled: readOnly, onChange: (e) => set({ default: parseDefault(e.target.value) }), children: [_jsx("option", { value: "", children: "\u2014" }), (d.values ?? []).map((v) => (_jsx("option", { value: v, children: d.labels?.[v] ?? v }, v)))] })) : (_jsx(Input, { id: `${id}-default`, value: d.default === undefined ? "" : String(d.default), disabled: readOnly, onChange: (e) => set({ default: parseDefault(e.target.value) }) }))] }))] }))] }));
458
+ }
459
+ // ---------------------------------------------------------------------------------------------
460
+ // Review + apply + migrate
461
+ function WarningText({ w }) {
462
+ const { t } = useForge();
463
+ const vars = { entity: w.entity, field: w.field ?? "", detail: w.detail ?? "", table: w.table ?? "", path: w.path ?? "" };
464
+ switch (w.kind) {
465
+ case "entityRemoved":
466
+ return _jsx(_Fragment, { children: t("schema.warning.entityRemoved", vars) });
467
+ case "entityRenamed":
468
+ return _jsx(_Fragment, { children: w.table ? t("schema.warning.entityRenamed", vars) : w.message });
469
+ case "fieldRemoved":
470
+ return _jsx(_Fragment, { children: t("schema.warning.fieldRemoved", vars) });
471
+ case "typeChange":
472
+ return _jsx(_Fragment, { children: t("schema.warning.typeChange", vars) });
473
+ case "requiredNoDefault":
474
+ return _jsx(_Fragment, { children: t("schema.warning.requiredNoDefault", vars) });
475
+ case "uniqueAdded":
476
+ return _jsx(_Fragment, { children: t("schema.warning.uniqueAdded", vars) });
477
+ case "optionsDropped":
478
+ return _jsx(_Fragment, { children: t("schema.warning.optionsDropped", vars) });
479
+ default:
480
+ return _jsx(_Fragment, { children: w.message });
481
+ }
482
+ }
483
+ function DiffView({ diff }) {
484
+ const { t } = useForge();
485
+ if (!diff)
486
+ return _jsx("p", { className: "text-sm text-ink-muted", children: t("schema.noDiff") });
487
+ return (_jsx("pre", { className: "max-h-96 overflow-auto rounded border border-line bg-surface-muted py-2 font-mono text-xs leading-5", children: diff
488
+ .replace(/\n$/, "")
489
+ .split("\n")
490
+ .map((line, i) => (_jsx("div", { className: cn("px-3 whitespace-pre", line.startsWith("+++") || line.startsWith("---") ? "font-semibold text-ink-muted" : line.startsWith("@@") ? "text-link" : line.startsWith("+") ? "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300" : line.startsWith("-") ? "bg-danger/10 text-danger" : "text-ink"), children: line || " " }, i))) }));
491
+ }
492
+ function ReviewDialog({ operations, expectedSource, onClose, onConflict, onApplied, }) {
493
+ const { t } = useForge();
494
+ const toast = useToast();
495
+ const [preview, setPreview] = useState(null);
496
+ const [error, setError] = useState(null);
497
+ const [ack, setAck] = useState(false);
498
+ const [applying, setApplying] = useState(false);
499
+ const [conflict, setConflict] = useState(false);
500
+ useEffect(() => {
501
+ let live = true;
502
+ dev("/preview", { operations })
503
+ .then((p) => live && setPreview(p))
504
+ .catch((e) => live && setError(e instanceof Error ? e.message : String(e)));
505
+ return () => {
506
+ live = false;
507
+ };
508
+ }, [operations]);
509
+ const blocked = !preview || preview.issues.length > 0 || (preview.warnings.length > 0 && !ack);
510
+ const apply = async () => {
511
+ setApplying(true);
512
+ setError(null);
513
+ try {
514
+ const next = await dev("/apply", { operations, expectedSource, acknowledgeWarnings: ack });
515
+ toast.success(t("schema.appliedTitle"), t("schema.applied"));
516
+ onApplied(next);
517
+ }
518
+ catch (e) {
519
+ if (e instanceof DevError && e.status === 409)
520
+ setConflict(true);
521
+ else if (e instanceof DevError && e.body?.issues?.length)
522
+ setError(_jsx(IssueList, { issues: e.body.issues }));
523
+ else
524
+ setError(e instanceof Error ? e.message : String(e));
525
+ }
526
+ finally {
527
+ setApplying(false);
528
+ }
529
+ };
530
+ return (_jsx(Dialog, { open: true, size: "xl", onClose: onClose, title: t("schema.reviewTitle"), footer: _jsxs(_Fragment, { children: [_jsx(Button, { onClick: onClose, children: t("common.cancel") }), conflict ? (_jsx(Button, { variant: "primary", onClick: onConflict, children: t("schema.reload") })) : (_jsx(Button, { variant: "primary", disabled: blocked, loading: applying, onClick: apply, children: t("schema.apply") }))] }), children: _jsxs("div", { className: "space-y-4", children: [conflict && _jsx(Alert, { children: t("schema.conflict") }), error && _jsx(Alert, { children: error }), !preview && !error && _jsx(Spinner, { label: t("schema.previewing") }), preview && (_jsxs(_Fragment, { children: [preview.issues.length > 0 && (_jsxs(Alert, { children: [_jsx("p", { children: t("schema.issues") }), _jsx(IssueList, { issues: preview.issues })] })), preview.warnings.length > 0 && (_jsxs("div", { role: "alert", "data-forge-alert": "info", className: "forge-alert px-3 py-2 text-sm", children: [_jsx("p", { className: "font-medium", children: t("schema.warnings") }), _jsx("ul", { className: "mt-1 list-disc space-y-0.5 pl-5", children: preview.warnings.map((w, i) => (_jsx("li", { children: _jsx(WarningText, { w: w }) }, i))) }), _jsxs("label", { className: "mt-2 flex items-center gap-2 font-medium", children: [_jsx("input", { type: "checkbox", className: "forge-check", checked: ack, onChange: (e) => setAck(e.target.checked) }), t("schema.acknowledge")] })] })), _jsxs("div", { children: [_jsx("p", { className: "mb-1.5 text-sm font-medium text-ink", children: t("schema.diff") }), _jsx(DiffView, { diff: preview.diff })] })] }))] }) }));
531
+ }
532
+ function AppliedPanel({ onClose }) {
533
+ const { t } = useForge();
534
+ const [name, setName] = useState("schema-update");
535
+ const [output, setOutput] = useState("");
536
+ const [running, setRunning] = useState(false);
537
+ const [exit, setExit] = useState(null);
538
+ const [error, setError] = useState(null);
539
+ const run = async () => {
540
+ setRunning(true);
541
+ setOutput("");
542
+ setExit(null);
543
+ setError(null);
544
+ try {
545
+ const res = await fetch(`${BASE}/migrate`, { method: "POST", credentials: "same-origin", headers: { "content-type": "application/json" }, body: JSON.stringify({ name }) });
546
+ if (!res.ok || !res.body) {
547
+ const body = await res.json().catch(() => null);
548
+ throw new Error(body?.error ?? `Request failed (${res.status})`);
549
+ }
550
+ const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
551
+ let text = "";
552
+ for (;;) {
553
+ const { done, value } = await reader.read();
554
+ if (done)
555
+ break;
556
+ text += value;
557
+ setOutput(text.replace(new RegExp(`\\n?${EXIT_MARKER} -?\\d+\\n?$`), ""));
558
+ }
559
+ const m = new RegExp(`${EXIT_MARKER} (-?\\d+)`).exec(text);
560
+ setExit(m ? Number(m[1]) : 1);
561
+ }
562
+ catch (e) {
563
+ setError(e instanceof Error ? e.message : String(e));
564
+ }
565
+ finally {
566
+ setRunning(false);
567
+ }
568
+ };
569
+ return (_jsxs(Card, { className: "mb-4 p-4", children: [_jsxs("div", { className: "flex items-start justify-between gap-3", children: [_jsx(Alert, { tone: "success", children: t("schema.applied") }), _jsx(Button, { size: "sm", variant: "ghost", onClick: onClose, children: t("common.close") })] }), _jsxs("div", { className: "mt-3", children: [_jsx("p", { className: "text-sm font-medium text-ink", children: t("schema.migration.title") }), _jsx("p", { className: "mt-0.5 text-sm text-ink-muted", children: t("schema.migration.hint") }), _jsxs("div", { className: "mt-2 flex flex-wrap items-end gap-2", children: [_jsxs("div", { className: "min-w-56", children: [_jsx(Label, { htmlFor: "schema-migration-name", children: t("schema.migration.name") }), _jsx(Input, { id: "schema-migration-name", value: name, maxLength: 60, onChange: (e) => setName(e.target.value.replace(/[^A-Za-z0-9_-]/g, "-")) })] }), _jsxs(Button, { variant: "primary", loading: running, disabled: !name, onClick: run, children: [_jsx(Database, { className: "size-3.5", "aria-hidden": true }), " ", t("schema.migration.run")] })] }), running && _jsx("p", { className: "mt-2 text-sm text-ink-muted", children: t("schema.migration.running") }), error && (_jsx("div", { className: "mt-2", children: _jsx(Alert, { children: error }) })), exit !== null && (_jsx("div", { className: "mt-2", children: _jsx(Alert, { tone: exit === 0 ? "success" : "error", children: exit === 0 ? t("schema.migration.done") : t("schema.migration.failed", { code: exit }) }) })), output && _jsx("pre", { className: "mt-2 max-h-72 overflow-auto rounded border border-line bg-surface-muted p-3 font-mono text-xs whitespace-pre-wrap text-ink", children: output })] })] }));
570
+ }
571
+ //# sourceMappingURL=schema-editor.js.map