@tansy/multi-tenant 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/pages.js ADDED
@@ -0,0 +1,373 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useCallback, useEffect, useState } from "react";
4
+ import { adminPath, Alert, apiPath, Badge, Button, ButtonLink, Card, DataTable, Field, Input, Modal, PageHeader, useT } from "tansy/admin";
5
+ /**
6
+ * The Tenants section and the account panel. Everything goes through this plugin's guarded
7
+ * routes as the signed-in person, which decide what they may see and do. Hiding a button here
8
+ * is only a convenience.
9
+ */
10
+ class CallError extends Error {
11
+ status;
12
+ code;
13
+ constructor(status, code, message) {
14
+ super(message);
15
+ this.status = status;
16
+ this.code = code;
17
+ }
18
+ }
19
+ async function call(path, options = {}) {
20
+ const response = await fetch(apiPath(`/ext/multi-tenant${path}`), {
21
+ method: options.method ?? "GET",
22
+ headers: options.body === undefined ? { accept: "application/json" } : { accept: "application/json", "content-type": "application/json" },
23
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
24
+ });
25
+ if (response.status === 204)
26
+ return null;
27
+ const payload = await response.json().catch(() => null);
28
+ if (!response.ok) {
29
+ const code = payload?.error?.code ?? "ERROR";
30
+ // Creating a tenant needs a recent sign-in, as other sensitive steps do.
31
+ if (code === "REAUTH_REQUIRED")
32
+ window.location.href = adminPath(`/auth/signin?reauth=1&next=${encodeURIComponent(window.location.pathname)}`);
33
+ throw new CallError(response.status, code, payload?.error?.message ?? "Request failed.");
34
+ }
35
+ return payload;
36
+ }
37
+ const message = (error) => (error instanceof Error ? error.message : String(error));
38
+ /** Reads one of this plugin's routes, with a way to read it again. */
39
+ function useCall(path) {
40
+ const [data, setData] = useState(null);
41
+ const [error, setError] = useState(null);
42
+ const [version, setVersion] = useState(0);
43
+ useEffect(() => {
44
+ if (path === null)
45
+ return;
46
+ let live = true;
47
+ call(path)
48
+ .then((result) => { if (live) {
49
+ setData(result);
50
+ setError(null);
51
+ } })
52
+ .catch((failure) => { if (live)
53
+ setError(failure instanceof CallError ? failure : new CallError(0, "ERROR", message(failure))); });
54
+ return () => { live = false; };
55
+ }, [path, version]);
56
+ const reload = useCallback(() => setVersion((value) => value + 1), []);
57
+ return { data, error, reload };
58
+ }
59
+ /** Makes a tenant the one this session works in, then reloads, since every page can depend on it. */
60
+ async function workIn(tenant, then) {
61
+ await call("/switcher", { method: "POST", body: { value: tenant } });
62
+ if (then)
63
+ window.location.href = then;
64
+ else
65
+ window.location.reload();
66
+ }
67
+ function RoleBadges({ roles, labels }) {
68
+ return _jsx("span", { className: "cms-row cms-gap-1", children: roles.map((role) => _jsx(Badge, { tight: true, children: labels?.get(role) ?? role }, role)) });
69
+ }
70
+ /** Ticks for the tenant roles someone may give. */
71
+ function RolePicker({ roles, value, onChange }) {
72
+ const { t } = useT();
73
+ if (!roles.length)
74
+ return _jsx(Alert, { kind: "warning", children: t("ext.multi-tenant.members.noRolesToGive") });
75
+ return (_jsxs("fieldset", { className: "cms-stack-2", children: [_jsx("legend", { className: "cms-label cms-mb-1", children: t("ext.multi-tenant.members.roles") }), roles.map((role) => (_jsxs("label", { className: "cms-check-label", children: [_jsx("input", { type: "checkbox", className: "cms-check", checked: value.includes(role.name), onChange: (event) => onChange(event.target.checked ? [...value, role.name] : value.filter((name) => name !== role.name)) }), role.label] }, role.name))), _jsx("p", { className: "cms-hint", children: t("ext.multi-tenant.members.rolesHint") })] }));
76
+ }
77
+ const LIMIT_KEYS = ["records", "storageBytes", "members", "requestsPerMinute"];
78
+ /**
79
+ * One tenant's plan and danger zone, for instance staff: what it uses against its limits,
80
+ * suspending and resuming it, downloading everything it has, and asking for it to be removed.
81
+ */
82
+ function TenantManage({ tenant, canUpdate, canDelete, onChanged }) {
83
+ const { t, locale } = useT();
84
+ const word = (key, values) => t(`ext.multi-tenant.manage.${key}`, values);
85
+ const plan = useCall(`/tenants/${tenant.id}/plan`);
86
+ const [limits, setLimits] = useState(null);
87
+ const [confirm, setConfirm] = useState("");
88
+ const [busy, setBusy] = useState(null);
89
+ const [error, setError] = useState(null);
90
+ const [notice, setNotice] = useState(null);
91
+ useEffect(() => {
92
+ if (!plan.data)
93
+ return;
94
+ const timer = setTimeout(() => setLimits(Object.fromEntries(LIMIT_KEYS.map((key) => [key, plan.data.limits[key] === null ? "" : String(plan.data.limits[key])]))));
95
+ return () => clearTimeout(timer);
96
+ }, [plan.data]);
97
+ const act = async (name, work, done) => {
98
+ setBusy(name);
99
+ setError(null);
100
+ setNotice(null);
101
+ try {
102
+ await work();
103
+ setNotice(done);
104
+ plan.reload();
105
+ onChanged();
106
+ }
107
+ catch (failure) {
108
+ setError(message(failure));
109
+ }
110
+ finally {
111
+ setBusy(null);
112
+ }
113
+ };
114
+ const saveLimits = (event) => {
115
+ event.preventDefault();
116
+ const body = Object.fromEntries(LIMIT_KEYS.map((key) => [key, limits?.[key]?.trim() ? Number(limits[key]) : null]));
117
+ void act("limits", () => call(`/tenants/${tenant.id}/limits`, { method: "PUT", body }), word("limitsSaved"));
118
+ };
119
+ const number = (value) => value.toLocaleString(locale);
120
+ const data = plan.data;
121
+ const suspended = (data?.tenant.status ?? tenant.status) === "suspended";
122
+ return (_jsxs("div", { className: "cms-stack-4", children: [error && _jsx(Alert, { children: error }), notice && _jsx(Alert, { kind: "success", children: notice }), plan.error && _jsx(Alert, { children: plan.error.message }), data && limits && (_jsxs("form", { onSubmit: saveLimits, className: "cms-stack-3", children: [_jsx("h3", { className: "cms-strong", children: word("limits") }), _jsx("p", { className: "cms-hint", children: word("limitsHint") }), LIMIT_KEYS.map((key) => (_jsx(Field, { label: word(`limit.${key}`), hint: key === "requestsPerMinute" ? undefined : word("used", { count: number(data.usage[key]) }), children: _jsx(Input, { type: "number", min: 0, step: 1, inputMode: "numeric", dir: "ltr", disabled: !canUpdate, placeholder: word("noLimit"), value: limits[key], onChange: (event) => setLimits({ ...limits, [key]: event.target.value }) }) }, key))), canUpdate && _jsx("div", { className: "cms-flex cms-end", children: _jsx(Button, { type: "submit", loading: busy === "limits", children: word("saveLimits") }) })] })), canDelete && data && (_jsx(Card, { children: _jsxs("div", { className: "cms-stack-3", children: [_jsx("h3", { className: "cms-strong", children: word("danger") }), _jsx("p", { className: "cms-hint", children: suspended ? word("suspendedHint") : word("activeHint") }), _jsxs("div", { className: "cms-row cms-gap-2", children: [suspended
123
+ ? _jsx(Button, { variant: "secondary", loading: busy === "resume", onClick: () => void act("resume", () => call(`/tenants/${tenant.id}/resume`, { method: "POST" }), word("resumed")), children: word("resume") })
124
+ : _jsx(Button, { variant: "danger", loading: busy === "suspend", onClick: () => void act("suspend", () => call(`/tenants/${tenant.id}/suspend`, { method: "POST" }), word("suspendedDone")), children: word("suspend") }), _jsx(ButtonLink, { native: true, variant: "secondary", href: apiPath(`/ext/multi-tenant/tenants/${tenant.id}/export`), children: word("export") })] }), suspended && (data.purgeAt
125
+ ? (_jsxs("div", { className: "cms-stack-2", children: [_jsx(Alert, { kind: "warning", children: word("purgeScheduled", { date: new Date(data.purgeAt).toLocaleString(locale) }) }), _jsx("div", { children: _jsx(Button, { variant: "secondary", loading: busy === "cancel", onClick: () => void act("cancel", () => call(`/tenants/${tenant.id}/purge`, { method: "DELETE" }), word("purgeCancelled")), children: word("cancelPurge") }) })] }))
126
+ : (_jsxs("form", { className: "cms-stack-2", onSubmit: (event) => { event.preventDefault(); void act("purge", () => call(`/tenants/${tenant.id}/purge`, { method: "POST", body: { confirm } }), word("purgeAsked")); }, children: [_jsx(Field, { label: word("purgeConfirm", { slug: tenant.slug }), hint: word("purgeHint"), children: _jsx(Input, { value: confirm, dir: "ltr", autoComplete: "off", onChange: (event) => setConfirm(event.target.value) }) }), _jsx("div", { children: _jsx(Button, { type: "submit", variant: "danger", disabled: confirm !== tenant.slug, loading: busy === "purge", children: word("purge") }) })] })))] }) }))] }));
127
+ }
128
+ export function TenantsList({ canCreate, canManage = false, canUpdate = false, canDelete = false }) {
129
+ const { t } = useT();
130
+ const word = (key, values) => t(`ext.multi-tenant.tenants.${key}`, values);
131
+ const tenants = useCall("/tenants");
132
+ const [creating, setCreating] = useState(false);
133
+ const [form, setForm] = useState({ name: "", slug: "" });
134
+ const [busy, setBusy] = useState(false);
135
+ const [error, setError] = useState(null);
136
+ const [notice, setNotice] = useState(null);
137
+ const [managing, setManaging] = useState(null);
138
+ const create = async (event) => {
139
+ event.preventDefault();
140
+ setBusy(true);
141
+ setError(null);
142
+ try {
143
+ const created = await call("/tenants", { method: "POST", body: form });
144
+ setCreating(false);
145
+ setForm({ name: "", slug: "" });
146
+ setNotice(word("created", { name: created.name }));
147
+ tenants.reload();
148
+ }
149
+ catch (failure) {
150
+ setError(message(failure));
151
+ }
152
+ finally {
153
+ setBusy(false);
154
+ }
155
+ };
156
+ const switchTo = async (id) => {
157
+ setError(null);
158
+ try {
159
+ await workIn(id);
160
+ }
161
+ catch (failure) {
162
+ setError(message(failure));
163
+ }
164
+ };
165
+ const current = tenants.data?.current ?? null;
166
+ return (_jsxs("div", { className: "cms-gutter cms-stack-6", children: [_jsx(PageHeader, { title: t("ext.multi-tenant.pages.tenants"), description: word("description"), actions: canCreate ? _jsx(Button, { onClick: () => setCreating(true), children: word("new") }) : undefined }), notice && _jsx(Alert, { kind: "success", children: notice }), error && !creating && _jsx(Alert, { children: error }), tenants.error && _jsx(Alert, { children: tenants.error.message }), _jsx(DataTable, { label: word("list"), columns: [
167
+ { id: "name", label: word("columnName") },
168
+ { id: "slug", label: word("columnSlug") },
169
+ { id: "status", label: word("columnStatus") },
170
+ { id: "roles", label: word("columnRoles") },
171
+ ], rows: tenants.data ? tenants.data.items.map((tenant) => ({
172
+ id: tenant.id,
173
+ cells: {
174
+ name: _jsxs("span", { className: "cms-row cms-gap-2", children: [_jsx("span", { className: "cms-strong", children: tenant.name }), tenant.id === current && _jsx(Badge, { tone: "info", tight: true, children: word("current") })] }),
175
+ slug: _jsx("code", { children: tenant.slug }),
176
+ status: _jsx(Badge, { tone: tenant.status === "active" ? "success" : "warning", tight: true, children: word(tenant.status) }),
177
+ roles: tenant.roles.length ? _jsx(RoleBadges, { roles: tenant.roles }) : _jsx("span", { className: "cms-muted", children: word("noRoles") }),
178
+ },
179
+ actions: (_jsxs("span", { className: "cms-row cms-gap-2", children: [tenant.status === "active" && tenant.id !== current && _jsx("button", { type: "button", className: "cms-row-action", onClick: () => void switchTo(tenant.id), children: word("switchTo") }), canManage && _jsx("button", { type: "button", className: "cms-row-action", onClick: () => setManaging(tenant), children: word("manage") })] })),
180
+ })) : null, empty: { title: word("empty"), hint: word("emptyHint") } }), _jsx(Modal, { open: managing !== null, onClose: () => setManaging(null), title: managing?.name ?? "", children: managing && _jsx(TenantManage, { tenant: managing, canUpdate: canUpdate, canDelete: canDelete, onChanged: tenants.reload }) }), _jsx(Modal, { open: creating, onClose: () => setCreating(false), title: word("new"), children: _jsxs("form", { onSubmit: create, className: "cms-stack-4", children: [error && _jsx(Alert, { children: error }), _jsx(Field, { label: word("name"), children: _jsx(Input, { required: true, maxLength: 120, value: form.name, onChange: (event) => setForm({ ...form, name: event.target.value }) }) }), _jsx(Field, { label: word("slug"), hint: word("slugHint"), children: _jsx(Input, { required: true, pattern: "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", value: form.slug, onChange: (event) => setForm({ ...form, slug: event.target.value }) }) }), _jsxs("div", { className: "cms-flex cms-end cms-gap-2", children: [_jsx(Button, { variant: "secondary", onClick: () => setCreating(false), children: word("cancel") }), _jsx(Button, { type: "submit", loading: busy, children: word("create") })] })] }) })] }));
181
+ }
182
+ /** The current tenant's members and open invitations. */
183
+ export function TenantMembers({ canRename }) {
184
+ const { t, formatDate } = useT();
185
+ const word = (key, values) => t(`ext.multi-tenant.members.${key}`, values);
186
+ const invitationWord = (key, values) => t(`ext.multi-tenant.invitations.${key}`, values);
187
+ const tenant = useCall("/tenant");
188
+ const ready = Boolean(tenant.data);
189
+ const members = useCall(ready ? "/members" : null);
190
+ const invitations = useCall(ready ? "/invitations" : null);
191
+ const roles = useCall(ready ? "/roles" : null);
192
+ const [editing, setEditing] = useState(null);
193
+ const [inviting, setInviting] = useState(null);
194
+ const [name, setName] = useState(null);
195
+ const [busy, setBusy] = useState(false);
196
+ const [error, setError] = useState(null);
197
+ const [notice, setNotice] = useState(null);
198
+ const run = async (work, done) => {
199
+ setBusy(true);
200
+ setError(null);
201
+ setNotice(null);
202
+ try {
203
+ await work();
204
+ if (done)
205
+ setNotice(done);
206
+ return true;
207
+ }
208
+ catch (failure) {
209
+ setError(message(failure));
210
+ return false;
211
+ }
212
+ finally {
213
+ setBusy(false);
214
+ }
215
+ };
216
+ if (tenant.error?.code === "SCOPE_REQUIRED") {
217
+ return _jsxs("div", { className: "cms-gutter cms-stack-6", children: [_jsx(PageHeader, { title: t("ext.multi-tenant.pages.tenants/members") }), _jsx(Alert, { kind: "info", children: word("chooseFirst") })] });
218
+ }
219
+ const labels = new Map((roles.data?.items ?? []).map((role) => [role.name, role.label]));
220
+ const giveable = roles.data?.items ?? [];
221
+ const saveRoles = async () => {
222
+ if (!editing)
223
+ return;
224
+ if (await run(() => call(`/members/${encodeURIComponent(editing.member.id)}`, { method: "PATCH", body: { roles: editing.roles } }))) {
225
+ setEditing(null);
226
+ members.reload();
227
+ }
228
+ };
229
+ const remove = async (member) => {
230
+ if (!window.confirm(word("confirmRemove", { name: member.name ?? member.email ?? member.userId })))
231
+ return;
232
+ if (await run(() => call(`/members/${encodeURIComponent(member.id)}`, { method: "DELETE" })))
233
+ members.reload();
234
+ };
235
+ const invite = async (event) => {
236
+ event.preventDefault();
237
+ if (!inviting)
238
+ return;
239
+ if (await run(() => call("/invitations", { method: "POST", body: inviting }), invitationWord("sent", { email: inviting.email }))) {
240
+ setInviting(null);
241
+ invitations.reload();
242
+ }
243
+ };
244
+ const cancelInvitation = async (invitation) => {
245
+ if (await run(() => call(`/invitations/${encodeURIComponent(invitation.id)}`, { method: "DELETE" })))
246
+ invitations.reload();
247
+ };
248
+ const rename = async (event) => {
249
+ event.preventDefault();
250
+ if (name !== null && await run(() => call("/tenant", { method: "PATCH", body: { name } }), word("renamed")))
251
+ tenant.reload();
252
+ };
253
+ return (_jsxs("div", { className: "cms-gutter cms-stack-6", children: [_jsx(PageHeader, { title: t("ext.multi-tenant.pages.tenants/members"), description: tenant.data ? word("description", { tenant: tenant.data.name }) : undefined, actions: _jsx(Button, { onClick: () => { setError(null); setInviting({ email: "", roles: [] }); }, children: word("invite") }) }), notice && _jsx(Alert, { kind: "success", children: notice }), error && !editing && !inviting && _jsx(Alert, { children: error }), tenant.error && _jsx(Alert, { children: tenant.error.message }), members.error && _jsx(Alert, { children: members.error.message }), _jsx(DataTable, { label: word("list"), title: word("list"), columns: [
254
+ { id: "name", label: word("columnName") },
255
+ { id: "email", label: word("columnEmail") },
256
+ { id: "roles", label: word("columnRoles") },
257
+ ], rows: members.data ? members.data.items.map((member) => ({
258
+ id: member.id,
259
+ cells: { name: member.name ?? "—", email: member.email ?? "—", roles: _jsx(RoleBadges, { roles: member.roles, labels: labels }) },
260
+ actions: (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", className: "cms-row-action", onClick: () => { setError(null); setEditing({ member, roles: member.roles }); }, children: word("editRoles") }), _jsx("button", { type: "button", className: "cms-row-action cms-row-action-danger", onClick: () => void remove(member), children: word("remove") })] })),
261
+ })) : null, empty: { title: word("empty"), hint: word("emptyHint") } }), _jsx(DataTable, { label: invitationWord("list"), title: invitationWord("list"), columns: [
262
+ { id: "email", label: invitationWord("columnEmail") },
263
+ { id: "roles", label: invitationWord("columnRoles") },
264
+ { id: "expires", label: invitationWord("columnExpires") },
265
+ ], rows: invitations.data ? invitations.data.items.map((invitation) => ({
266
+ id: invitation.id,
267
+ cells: { email: invitation.email, roles: _jsx(RoleBadges, { roles: invitation.roles, labels: labels }), expires: invitation.expiresAt ? formatDate(invitation.expiresAt) : "—" },
268
+ actions: _jsx("button", { type: "button", className: "cms-row-action cms-row-action-danger", onClick: () => void cancelInvitation(invitation), children: invitationWord("cancelInvitation") }),
269
+ })) : null, empty: { title: invitationWord("empty"), hint: invitationWord("emptyHint") } }), canRename && tenant.data && (_jsx(Card, { title: word("details"), children: _jsxs("form", { onSubmit: rename, className: "cms-stack-4", children: [_jsx(Field, { label: word("name"), children: _jsx(Input, { required: true, maxLength: 120, value: name ?? tenant.data.name, onChange: (event) => setName(event.target.value) }) }), _jsx("div", { className: "cms-flex cms-end", children: _jsx(Button, { type: "submit", loading: busy, children: word("rename") }) })] }) })), _jsx(Modal, { open: editing !== null, onClose: () => setEditing(null), title: word("editRoles"), children: editing && (_jsxs("div", { className: "cms-stack-4", children: [error && _jsx(Alert, { children: error }), _jsx(RolePicker, { roles: giveable, value: editing.roles, onChange: (next) => setEditing({ ...editing, roles: next }) }), _jsxs("div", { className: "cms-flex cms-end cms-gap-2", children: [_jsx(Button, { variant: "secondary", onClick: () => setEditing(null), children: word("cancel") }), _jsx(Button, { loading: busy, disabled: !editing.roles.length, onClick: () => void saveRoles(), children: word("save") })] })] })) }), _jsx(Modal, { open: inviting !== null, onClose: () => setInviting(null), title: invitationWord("title"), children: inviting && (_jsxs("form", { onSubmit: invite, className: "cms-stack-4", children: [error && _jsx(Alert, { children: error }), _jsx(Field, { label: invitationWord("email"), children: _jsx(Input, { type: "email", required: true, maxLength: 254, value: inviting.email, onChange: (event) => setInviting({ ...inviting, email: event.target.value }) }) }), _jsx(RolePicker, { roles: giveable, value: inviting.roles, onChange: (next) => setInviting({ ...inviting, roles: next }) }), _jsxs("div", { className: "cms-flex cms-end cms-gap-2", children: [_jsx(Button, { variant: "secondary", onClick: () => setInviting(null), children: word("cancel") }), _jsx(Button, { type: "submit", loading: busy, disabled: !inviting.roles.length, children: invitationWord("send") })] })] })) })] }));
270
+ }
271
+ /** The current tenant's domains: adding one, the TXT record that proves it, checking it, and choosing the main one. */
272
+ export function TenantDomains() {
273
+ const { t, formatDate } = useT();
274
+ const word = (key, values) => t(`ext.multi-tenant.domains.${key}`, values);
275
+ const tenant = useCall("/tenant");
276
+ const domains = useCall(tenant.data ? "/domains" : null);
277
+ const [adding, setAdding] = useState(null);
278
+ const [busy, setBusy] = useState(false);
279
+ const [error, setError] = useState(null);
280
+ const [notice, setNotice] = useState(null);
281
+ if (tenant.error?.code === "SCOPE_REQUIRED") {
282
+ return _jsxs("div", { className: "cms-gutter cms-stack-6", children: [_jsx(PageHeader, { title: t("ext.multi-tenant.pages.tenants/domains") }), _jsx(Alert, { kind: "info", children: word("chooseFirst") })] });
283
+ }
284
+ const run = async (work, done) => {
285
+ setBusy(true);
286
+ setError(null);
287
+ setNotice(null);
288
+ try {
289
+ await work();
290
+ if (done)
291
+ setNotice(done);
292
+ domains.reload();
293
+ return true;
294
+ }
295
+ catch (failure) {
296
+ setError(message(failure));
297
+ return false;
298
+ }
299
+ finally {
300
+ setBusy(false);
301
+ }
302
+ };
303
+ const add = async (event) => {
304
+ event.preventDefault();
305
+ if (adding !== null && await run(() => call("/domains", { method: "POST", body: { host: adding } })))
306
+ setAdding(null);
307
+ };
308
+ const remove = async (domain) => {
309
+ if (window.confirm(word("confirmRemove", { host: domain.host })))
310
+ await run(() => call(`/domains/${domain.id}`, { method: "DELETE" }));
311
+ };
312
+ const pending = (domains.data?.items ?? []).filter((domain) => !domain.verified);
313
+ return (_jsxs("div", { className: "cms-gutter cms-stack-6", children: [_jsx(PageHeader, { title: t("ext.multi-tenant.pages.tenants/domains"), description: tenant.data ? word("description", { tenant: tenant.data.name }) : undefined, actions: _jsx(Button, { onClick: () => { setError(null); setAdding(""); }, children: word("add") }) }), notice && _jsx(Alert, { kind: "success", children: notice }), error && adding === null && _jsx(Alert, { children: error }), tenant.error && _jsx(Alert, { children: tenant.error.message }), domains.error && _jsx(Alert, { children: domains.error.message }), _jsx(DataTable, { label: word("list"), columns: [
314
+ { id: "host", label: word("columnHost") },
315
+ { id: "state", label: word("columnState") },
316
+ ], rows: domains.data ? domains.data.items.map((domain) => ({
317
+ id: String(domain.id),
318
+ cells: {
319
+ host: _jsxs("span", { className: "cms-row cms-gap-2", children: [_jsx("code", { children: domain.host }), domain.primary && _jsx(Badge, { tone: "info", tight: true, children: word("primary") })] }),
320
+ state: domain.verified
321
+ ? _jsx(Badge, { tone: "success", tight: true, children: word("verified") })
322
+ : _jsxs("span", { className: "cms-row cms-gap-2", children: [_jsx(Badge, { tone: "warning", tight: true, children: word("waiting") }), domain.checkedAt && _jsx("span", { className: "cms-muted", children: word("checked", { date: formatDate(domain.checkedAt) }) })] }),
323
+ },
324
+ actions: (_jsxs(_Fragment, { children: [!domain.verified && _jsx("button", { type: "button", className: "cms-row-action", disabled: busy, onClick: () => void run(() => call(`/domains/${domain.id}/verify`, { method: "POST" }), word("verifiedNotice", { host: domain.host })), children: word("verify") }), domain.verified && !domain.primary && _jsx("button", { type: "button", className: "cms-row-action", disabled: busy, onClick: () => void run(() => call(`/domains/${domain.id}/primary`, { method: "POST" })), children: word("makePrimary") }), _jsx("button", { type: "button", className: "cms-row-action cms-row-action-danger", disabled: busy, onClick: () => void remove(domain), children: word("remove") })] })),
325
+ })) : null, empty: { title: word("empty"), hint: word("emptyHint") } }), pending.length > 0 && (_jsx(Card, { title: word("howTitle"), children: _jsxs("div", { className: "cms-stack-4", children: [_jsx("p", { children: word("how") }), pending.map((domain) => (_jsxs("dl", { className: "cms-stack-1", children: [_jsx("dt", { className: "cms-strong", children: domain.host }), _jsx("dd", { children: word("recordType", { type: domain.record.type }) }), _jsxs("dd", { children: [word("recordName"), " ", _jsx("code", { children: domain.record.name })] }), _jsxs("dd", { children: [word("recordValue"), " ", _jsx("code", { children: domain.record.value })] })] }, domain.id)))] }) })), _jsx(Modal, { open: adding !== null, onClose: () => setAdding(null), title: word("add"), children: adding !== null && (_jsxs("form", { onSubmit: add, className: "cms-stack-4", children: [error && _jsx(Alert, { children: error }), _jsx(Field, { label: word("host"), hint: word("hostHint"), children: _jsx(Input, { required: true, maxLength: 253, value: adding, onChange: (event) => setAdding(event.target.value) }) }), _jsxs("div", { className: "cms-flex cms-end cms-gap-2", children: [_jsx(Button, { variant: "secondary", onClick: () => setAdding(null), children: word("cancel") }), _jsx(Button, { type: "submit", loading: busy, children: word("add") })] })] })) })] }));
326
+ }
327
+ /**
328
+ * On the account page, which anyone signed in can open: invitations to accept, and the tenants
329
+ * they belong to, so someone with no dashboard access yet can join and open their tenant.
330
+ */
331
+ export function AccountTenants() {
332
+ const { t, formatDate } = useT();
333
+ const word = (key, values) => t(`ext.multi-tenant.account.${key}`, values);
334
+ const invitations = useCall("/invitations/mine");
335
+ const tenants = useCall("/tenants");
336
+ const [busy, setBusy] = useState(null);
337
+ const [error, setError] = useState(null);
338
+ const [joined, setJoined] = useState(null);
339
+ const answer = async (invitation, accept) => {
340
+ setBusy(invitation.id);
341
+ setError(null);
342
+ try {
343
+ await call(`/invitations/${encodeURIComponent(invitation.id)}/${accept ? "accept" : "reject"}`, { method: "POST" });
344
+ if (accept)
345
+ setJoined({ id: invitation.tenant, name: invitation.tenantName ?? invitation.tenant });
346
+ invitations.reload();
347
+ tenants.reload();
348
+ }
349
+ catch (failure) {
350
+ setError(message(failure));
351
+ }
352
+ finally {
353
+ setBusy(null);
354
+ }
355
+ };
356
+ const open = async (tenant) => {
357
+ setBusy(tenant);
358
+ setError(null);
359
+ try {
360
+ await workIn(tenant, adminPath());
361
+ }
362
+ catch (failure) {
363
+ setError(message(failure));
364
+ setBusy(null);
365
+ }
366
+ };
367
+ // Only the tenants they belong to, not every one staff can reach.
368
+ const memberships = (tenants.data?.items ?? []).filter((tenant) => tenant.roles.length && tenant.status === "active");
369
+ const pending = invitations.data?.items ?? [];
370
+ if (!pending.length && !memberships.length && !joined && !error)
371
+ return null;
372
+ return (_jsx("div", { id: "tenant-invitations", children: _jsx(Card, { title: word("title"), description: word("description"), children: _jsxs("div", { className: "cms-stack-4", children: [error && _jsx(Alert, { children: error }), joined && _jsx(Alert, { kind: "success", children: word("accepted", { tenant: joined.name }) }), pending.map((invitation) => (_jsxs("div", { className: "cms-flex cms-between cms-gap-2", children: [_jsxs("div", { children: [_jsx("p", { children: word("invited", { tenant: invitation.tenantName ?? invitation.tenant, roles: invitation.roles.join(", ") }) }), _jsx("p", { className: "cms-hint", children: word("expires", { date: formatDate(invitation.expiresAt) }) })] }), _jsxs("div", { className: "cms-row cms-gap-2", children: [_jsx(Button, { variant: "secondary", loading: busy === invitation.id, onClick: () => void answer(invitation, false), children: word("decline") }), _jsx(Button, { loading: busy === invitation.id, onClick: () => void answer(invitation, true), children: word("accept") })] })] }, invitation.id))), memberships.map((tenant) => (_jsxs("div", { className: "cms-flex cms-between cms-gap-2", children: [_jsx("p", { children: word("memberOf", { tenant: tenant.name }) }), _jsx(Button, { variant: "secondary", loading: busy === tenant.id, onClick: () => void open(tenant.id), children: word("open") })] }, tenant.id))), !memberships.length && joined && _jsx("div", { className: "cms-flex cms-end", children: _jsx(ButtonLink, { href: adminPath(), native: true, children: word("open") }) })] }) }) }));
373
+ }
package/paths.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { type ExtensionContext } from "tansy/plugin";
2
+ /** First segments the CMS itself answers on, which no tenant's site can be served under. */
3
+ export declare const RESERVED_SEGMENTS: ReadonlySet<string>;
4
+ /** A short name a tenant's site can be served under: one the CMS doesn't answer on itself. */
5
+ export declare const usableSlug: (slug: string) => boolean;
6
+ export declare function forgetSlugs(): void;
7
+ /**
8
+ * The tenant whose short name the address's first segment is, or null. Only called once the
9
+ * host has been found to be no tenant's, so this never overrides a verified domain.
10
+ */
11
+ export declare function tenantForPath(context: ExtensionContext, path: string | null | undefined): Promise<string | null>;
12
+ /** The path prefix a tenant's site is served under on the instance's own address, or null. */
13
+ export declare function basePathOf(context: ExtensionContext, tenant: string): Promise<string | null>;
package/paths.js ADDED
@@ -0,0 +1,58 @@
1
+ import { adminPath, apiPath } from "tansy/plugin";
2
+ import { listTenants, TENANT_SLUG } from "./tenants";
3
+ /**
4
+ * Where a tenant's site sits when it has no domain of its own: under its short name on the
5
+ * instance's own address, such as /acme/blog/hello. Core strips the prefix before it matches
6
+ * an address and puts it back on every address it builds (`basePath` on the scope provider).
7
+ *
8
+ * A verified domain still decides for everyone, so the prefix is read only on a host no tenant
9
+ * has verified: a path can never move a visitor off a tenant's own domain onto another tenant's
10
+ * site. The prefix keeps working once a tenant verifies a domain, so links shared before it
11
+ * don't break, and the domain is the canonical address from then on.
12
+ */
13
+ const firstSegment = (path) => path.split("/")[1] ?? "";
14
+ /** First segments the CMS itself answers on, which no tenant's site can be served under. */
15
+ export const RESERVED_SEGMENTS = new Set([firstSegment(apiPath()), firstSegment(adminPath()), "_next"].filter(Boolean));
16
+ /** A short name a tenant's site can be served under: one the CMS doesn't answer on itself. */
17
+ export const usableSlug = (slug) => TENANT_SLUG.test(slug) && !RESERVED_SEGMENTS.has(slug);
18
+ const cache = (globalThis.cmsTenantSlugs ??= { bySlug: new Map(), byId: new Map(), loadedAt: 0, loading: null });
19
+ const FRESH_MS = 15_000;
20
+ export function forgetSlugs() {
21
+ cache.loadedAt = 0;
22
+ }
23
+ async function loadSlugs(context) {
24
+ const bySlug = new Map();
25
+ const byId = new Map();
26
+ for (const tenant of await listTenants(context)) {
27
+ if (tenant.status !== "active" || !usableSlug(tenant.slug) || bySlug.has(tenant.slug))
28
+ continue;
29
+ bySlug.set(tenant.slug, tenant.id);
30
+ byId.set(tenant.id, tenant.slug);
31
+ }
32
+ cache.bySlug = bySlug;
33
+ cache.byId = byId;
34
+ cache.loadedAt = Date.now();
35
+ return bySlug;
36
+ }
37
+ async function slugs(context) {
38
+ if (cache.loadedAt && Date.now() - cache.loadedAt < FRESH_MS)
39
+ return cache;
40
+ cache.loading ??= loadSlugs(context).finally(() => { cache.loading = null; });
41
+ await cache.loading;
42
+ return cache;
43
+ }
44
+ /**
45
+ * The tenant whose short name the address's first segment is, or null. Only called once the
46
+ * host has been found to be no tenant's, so this never overrides a verified domain.
47
+ */
48
+ export async function tenantForPath(context, path) {
49
+ const slug = firstSegment(path ?? "");
50
+ if (!slug || !usableSlug(slug))
51
+ return null;
52
+ return (await slugs(context)).bySlug.get(slug) ?? null;
53
+ }
54
+ /** The path prefix a tenant's site is served under on the instance's own address, or null. */
55
+ export async function basePathOf(context, tenant) {
56
+ const slug = (await slugs(context)).byId.get(tenant);
57
+ return slug ? `/${slug}` : null;
58
+ }
package/routes.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { type ExtensionRoute } from "tansy/plugin";
2
+ import { EVERY_TENANT, MEMBERS_PERMISSION, PLUGIN } from "./tenants";
3
+ declare const DOMAINS_PERMISSION = "ext.multi-tenant:domains";
4
+ export declare function tenantRoutes(options: {
5
+ siteUrl: string;
6
+ dnsServers?: string[];
7
+ }): ExtensionRoute[];
8
+ export { DOMAINS_PERMISSION, EVERY_TENANT, MEMBERS_PERMISSION, PLUGIN };