@platforma-sdk/pl-cli 0.8.29 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +196 -120
- package/dist/cli.js.map +1 -1
- package/dist/cmd/admin/delete-user.d.ts +2 -0
- package/dist/index.js +2 -2
- package/dist/output-BAuWMUzX.js +232 -0
- package/dist/output-BAuWMUzX.js.map +1 -0
- package/dist/project_ops.d.ts +54 -0
- package/package.json +4 -4
- package/src/cli.ts +2 -0
- package/src/cmd/admin/delete-user.ts +210 -0
- package/src/project_ops.ts +182 -1
- package/dist/output-KEq0q5fS.js +0 -166
- package/dist/output-KEq0q5fS.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export {
|
|
1
|
+
import { a as e, b as t, c as n, d as r, f as i, g as a, i as o, m as s, n as c, o as l, s as u, t as d, u as f, v as p, x as m, y as h } from "./output-BAuWMUzX.js";
|
|
2
|
+
export { t as createAdminPlConnection, m as createPlConnection, l as deduplicateName, u as deleteProject, n as duplicateProject, d as formatDate, c as formatTable, f as getExistingLabelsInTx, r as getProjectInfo, i as getProjectListRid, s as listProjects, a as navigateToUserRoot, o as outputJson, e as outputText, p as renameProject, h as resolveProject };
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { PlClient as e, UnauthenticatedPlClient as t, field as n, isNotFoundError as r, isNullSignedResourceId as i, plAddressToConfig as a, resourceIdToString as o } from "@milaboratories/pl-client";
|
|
2
|
+
import { randomUUID as s } from "node:crypto";
|
|
3
|
+
import { ProjectCreatedTimestamp as c, ProjectLastModifiedTimestamp as l, ProjectMetaKey as u, ProjectStructureKey as d, ProjectsField as f, ProjectsResourceType as p, SchemaVersionKey as m, duplicateProject as h } from "@milaboratories/pl-middle-layer";
|
|
4
|
+
//#region src/connection.ts
|
|
5
|
+
async function g(n) {
|
|
6
|
+
let r = a(n.address);
|
|
7
|
+
n.user !== void 0 && (r.user = n.user), n.password !== void 0 && (r.password = n.password);
|
|
8
|
+
let i = await t.build(r), o;
|
|
9
|
+
if (await i.requireAuth()) {
|
|
10
|
+
if (r.user === void 0 || r.password === void 0) throw Error("Server requires authentication but no credentials provided. Use --user/--password flags or PL_USER/PL_PASSWORD env vars.");
|
|
11
|
+
o = await i.login(r.user, r.password);
|
|
12
|
+
} else o = {};
|
|
13
|
+
return await e.init(r, { authInformation: o });
|
|
14
|
+
}
|
|
15
|
+
async function _(n) {
|
|
16
|
+
let r = a(n.address), i = await (await t.build(r)).login(n.adminUser, n.adminPassword);
|
|
17
|
+
return await e.init(r, { authInformation: i });
|
|
18
|
+
}
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region src/project_ops.ts
|
|
21
|
+
async function v(e, t) {
|
|
22
|
+
return await e.withReadTx("listProjects", async (e) => {
|
|
23
|
+
let n = await e.getResourceData(t, !0), r = [];
|
|
24
|
+
for (let t of n.fields) {
|
|
25
|
+
if (i(t.value)) continue;
|
|
26
|
+
let [n, a, s] = await Promise.all([
|
|
27
|
+
e.getKValueStringIfExists(t.value, u),
|
|
28
|
+
e.getKValueStringIfExists(t.value, c),
|
|
29
|
+
e.getKValueStringIfExists(t.value, l)
|
|
30
|
+
]), d = n ? JSON.parse(n) : { label: "(unknown)" }, f = o(t.value);
|
|
31
|
+
r.push({
|
|
32
|
+
id: f,
|
|
33
|
+
rid: t.value,
|
|
34
|
+
label: d.label,
|
|
35
|
+
created: a ? new Date(Number(a)) : /* @__PURE__ */ new Date(0),
|
|
36
|
+
lastModified: s ? new Date(Number(s)) : /* @__PURE__ */ new Date(0)
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return r.sort((e, t) => t.lastModified.getTime() - e.lastModified.getTime()), r;
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
async function y(e, t) {
|
|
43
|
+
return await e.withReadTx("listProjectIdentities", async (e) => await b(e, t));
|
|
44
|
+
}
|
|
45
|
+
async function b(e, t) {
|
|
46
|
+
let n = await e.getResourceData(t, !0), r = [];
|
|
47
|
+
for (let t of n.fields) {
|
|
48
|
+
if (i(t.value)) continue;
|
|
49
|
+
let n = await e.getKValueStringIfExists(t.value, u), a = n ? JSON.parse(n) : { label: "(unknown)" };
|
|
50
|
+
r.push({
|
|
51
|
+
id: o(t.value),
|
|
52
|
+
rid: t.value,
|
|
53
|
+
fieldName: t.name,
|
|
54
|
+
label: a.label
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
return r;
|
|
58
|
+
}
|
|
59
|
+
async function x(e, t, n) {
|
|
60
|
+
return await e.withReadTx("getProjectInfo", async (e) => {
|
|
61
|
+
let r = await e.listKeyValuesString(n), i = r.find((e) => e.key === u), a = r.find((e) => e.key === c), o = r.find((e) => e.key === l), s = r.find((e) => e.key === m), f = r.find((e) => e.key === d), p = i ? JSON.parse(i.value) : { label: "(unknown)" }, h = s ? JSON.parse(s.value) : void 0, g = [];
|
|
62
|
+
if (f) {
|
|
63
|
+
let e = JSON.parse(f.value);
|
|
64
|
+
for (let t of e.groups ?? []) for (let e of t.blocks ?? []) g.push(e.id);
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
id: t,
|
|
68
|
+
rid: n,
|
|
69
|
+
label: p.label,
|
|
70
|
+
created: a ? new Date(Number(a.value)) : /* @__PURE__ */ new Date(0),
|
|
71
|
+
lastModified: o ? new Date(Number(o.value)) : /* @__PURE__ */ new Date(0),
|
|
72
|
+
schemaVersion: h,
|
|
73
|
+
blockCount: g.length,
|
|
74
|
+
blockIds: g
|
|
75
|
+
};
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
async function S(e, t, n) {
|
|
79
|
+
return await e.withReadTx("resolveProject", async (e) => {
|
|
80
|
+
let r = await e.getResourceData(t, !0);
|
|
81
|
+
for (let e of r.fields) {
|
|
82
|
+
if (i(e.value)) continue;
|
|
83
|
+
let t = o(e.value);
|
|
84
|
+
if (t === n) return {
|
|
85
|
+
id: t,
|
|
86
|
+
rid: e.value,
|
|
87
|
+
fieldName: e.name
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
for (let t of r.fields) {
|
|
91
|
+
if (i(t.value)) continue;
|
|
92
|
+
let r = await e.getKValueStringIfExists(t.value, u);
|
|
93
|
+
if (r && JSON.parse(r).label === n) return {
|
|
94
|
+
id: o(t.value),
|
|
95
|
+
rid: t.value,
|
|
96
|
+
fieldName: t.name
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
throw Error(`Project "${n}" not found (searched by id and label).`);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
async function C(e, t) {
|
|
103
|
+
let n = await e.getResourceData(t, !0), r = [];
|
|
104
|
+
for (let t of n.fields) {
|
|
105
|
+
if (i(t.value)) continue;
|
|
106
|
+
let n = await e.getKValueStringIfExists(t.value, u);
|
|
107
|
+
if (n) {
|
|
108
|
+
let e = JSON.parse(n);
|
|
109
|
+
r.push(e.label);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return r;
|
|
113
|
+
}
|
|
114
|
+
function w(e, t) {
|
|
115
|
+
let n = `${e} (Copy)`, r = 2;
|
|
116
|
+
for (; t.includes(n);) n = `${e} (Copy ${r})`, r++;
|
|
117
|
+
return n;
|
|
118
|
+
}
|
|
119
|
+
async function T(e, t, n) {
|
|
120
|
+
await e.withWriteTx("renameProject", async (e) => {
|
|
121
|
+
let r = await e.getKValueString(t, u), i = {
|
|
122
|
+
...JSON.parse(r),
|
|
123
|
+
label: n
|
|
124
|
+
};
|
|
125
|
+
e.setKValue(t, u, JSON.stringify(i)), e.setKValue(t, l, String(Date.now())), await e.commit();
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
async function E(e, t, r) {
|
|
129
|
+
await e.withWriteTx("deleteProject", async (e) => {
|
|
130
|
+
e.removeField(n(t, r)), await e.commit();
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
async function D(e, t, r) {
|
|
134
|
+
return await e.withWriteTx("moveProjects", async (e) => {
|
|
135
|
+
let i = await b(e, t);
|
|
136
|
+
if (i.length === 0) return [];
|
|
137
|
+
let a = await C(e, r), o = [];
|
|
138
|
+
for (let c of i) {
|
|
139
|
+
let i = await e.getKValueString(c.rid, u), d = JSON.parse(i), f = d.label, p = f;
|
|
140
|
+
a.includes(p) && (p = w(f, a), e.setKValue(c.rid, u, JSON.stringify({
|
|
141
|
+
...d,
|
|
142
|
+
label: p
|
|
143
|
+
})), e.setKValue(c.rid, l, String(Date.now()))), a.push(p), e.createField(n(r, s()), "Dynamic", c.rid), e.removeField(n(t, c.fieldName)), o.push({
|
|
144
|
+
id: c.id,
|
|
145
|
+
sourceLabel: f,
|
|
146
|
+
targetLabel: p
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
return await e.commit(), o;
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
async function O(e) {
|
|
153
|
+
return await e.withReadTx("getProjectList", async (e) => {
|
|
154
|
+
let t = await e.getField({
|
|
155
|
+
resourceId: e.clientRoot,
|
|
156
|
+
fieldName: f
|
|
157
|
+
});
|
|
158
|
+
if (i(t.value)) throw Error("No project list found for this user.");
|
|
159
|
+
return t.value;
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
async function k(e, t) {
|
|
163
|
+
let a;
|
|
164
|
+
try {
|
|
165
|
+
a = await e.getUserRoot({ login: t });
|
|
166
|
+
} catch (e) {
|
|
167
|
+
throw r(e) ? Error(`User "${t}" not found on this server.`) : e;
|
|
168
|
+
}
|
|
169
|
+
if (a === void 0) throw Error(`User "${t}" not found on this server (no root resource).`);
|
|
170
|
+
return await e.withReadTx("openUserRoot", async (e) => {
|
|
171
|
+
let t = await e.getFieldIfExists(n(a, f));
|
|
172
|
+
return t === void 0 || i(t.value) ? {
|
|
173
|
+
userRoot: a,
|
|
174
|
+
projectListRid: void 0
|
|
175
|
+
} : {
|
|
176
|
+
userRoot: a,
|
|
177
|
+
projectListRid: t.value
|
|
178
|
+
};
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
async function A(e, t) {
|
|
182
|
+
return await e.withWriteTx("ensureUserProjectList", async (e) => {
|
|
183
|
+
let r = n(t, f);
|
|
184
|
+
e.createField(r, "Dynamic");
|
|
185
|
+
let a = await e.getField(r);
|
|
186
|
+
if (!i(a.value)) return await e.commit(), a.value;
|
|
187
|
+
let o = e.createEphemeral(p);
|
|
188
|
+
return e.lock(o), e.setField(r, o), await e.commit(), await o.globalId;
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
async function j(e, t) {
|
|
192
|
+
let n;
|
|
193
|
+
if (n = await e.getUserRoot({ login: t }), n === void 0) throw Error(`User "${t}" not found on this server (no root resource).`);
|
|
194
|
+
return await e.withReadTx("navigateToUserProjects", async (e) => {
|
|
195
|
+
let r = await e.getField({
|
|
196
|
+
resourceId: n,
|
|
197
|
+
fieldName: f
|
|
198
|
+
});
|
|
199
|
+
if (i(r.value)) throw Error(`User "${t}" has no project list.`);
|
|
200
|
+
return {
|
|
201
|
+
userRoot: n,
|
|
202
|
+
projectListRid: r.value
|
|
203
|
+
};
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
//#endregion
|
|
207
|
+
//#region src/output.ts
|
|
208
|
+
function M(e) {
|
|
209
|
+
console.log(e);
|
|
210
|
+
}
|
|
211
|
+
function N(e) {
|
|
212
|
+
console.log(JSON.stringify(e, null, 2));
|
|
213
|
+
}
|
|
214
|
+
function P(e, t) {
|
|
215
|
+
let n = (e) => /[",\r\n]/.test(e) ? `"${e.replace(/"/g, "\"\"")}"` : e, r = [e, ...t].map((e) => e.map(n).join(","));
|
|
216
|
+
console.log(r.join("\n"));
|
|
217
|
+
}
|
|
218
|
+
function F(e, t) {
|
|
219
|
+
let n = e.map((e, n) => Math.max(e.length, ...t.map((e) => (e[n] ?? "").length))), r = n.map((e) => "-".repeat(e)).join(" ");
|
|
220
|
+
return [
|
|
221
|
+
e.map((e, t) => e.padEnd(n[t])).join(" "),
|
|
222
|
+
r,
|
|
223
|
+
...t.map((e) => e.map((e, t) => (e ?? "").padEnd(n[t])).join(" "))
|
|
224
|
+
].join("\n");
|
|
225
|
+
}
|
|
226
|
+
function I(e) {
|
|
227
|
+
return e.getTime() === 0 ? "(unknown)" : e.toISOString().replace("T", " ").replace(/\.\d+Z$/, "Z");
|
|
228
|
+
}
|
|
229
|
+
//#endregion
|
|
230
|
+
export { k as _, M as a, _ as b, h as c, x as d, O as f, j as g, D as h, N as i, A as l, v as m, F as n, w as o, y as p, P as r, E as s, I as t, C as u, T as v, g as x, S as y };
|
|
231
|
+
|
|
232
|
+
//# sourceMappingURL=output-BAuWMUzX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"output-BAuWMUzX.js","names":[],"sources":["../src/connection.ts","../src/project_ops.ts","../src/output.ts"],"sourcesContent":["import {\n PlClient,\n UnauthenticatedPlClient,\n plAddressToConfig,\n type AuthInformation,\n type PlClientConfig,\n} from \"@milaboratories/pl-client\";\n\nexport interface PlConnectionOptions {\n address: string;\n user?: string;\n password?: string;\n}\n\nexport interface AdminConnectionOptions {\n address: string;\n adminUser: string;\n adminPassword: string;\n}\n\n/** Creates an authenticated PlClient from address + credentials. */\nexport async function createPlConnection(opts: PlConnectionOptions): Promise<PlClient> {\n const config: PlClientConfig = plAddressToConfig(opts.address);\n\n if (opts.user !== undefined) config.user = opts.user;\n if (opts.password !== undefined) config.password = opts.password;\n\n const unauth = await UnauthenticatedPlClient.build(config);\n let authInformation: AuthInformation;\n\n if (await unauth.requireAuth()) {\n if (config.user === undefined || config.password === undefined) {\n throw new Error(\n \"Server requires authentication but no credentials provided. \" +\n \"Use --user/--password flags or PL_USER/PL_PASSWORD env vars.\",\n );\n }\n authInformation = await unauth.login(config.user, config.password);\n } else {\n authInformation = {};\n }\n\n return await PlClient.init(config, { authInformation });\n}\n\n/** Creates a PlClient with admin/controller credentials. */\nexport async function createAdminPlConnection(opts: AdminConnectionOptions): Promise<PlClient> {\n const config: PlClientConfig = plAddressToConfig(opts.address);\n\n const unauth = await UnauthenticatedPlClient.build(config);\n const authInformation: AuthInformation = await unauth.login(opts.adminUser, opts.adminPassword);\n\n return await PlClient.init(config, { authInformation });\n}\n","import type { PlClient, SignedResourceId, PlTransaction } from \"@milaboratories/pl-client\";\nimport {\n field,\n isNotFoundError,\n isNullSignedResourceId,\n resourceIdToString,\n} from \"@milaboratories/pl-client\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n ProjectMetaKey,\n ProjectCreatedTimestamp,\n ProjectLastModifiedTimestamp,\n SchemaVersionKey,\n ProjectStructureKey,\n ProjectsField,\n ProjectsResourceType,\n duplicateProject,\n} from \"@milaboratories/pl-middle-layer\";\nimport type { ProjectMeta } from \"@milaboratories/pl-middle-layer\";\n\nexport interface ProjectEntry {\n id: string;\n rid: SignedResourceId;\n label: string;\n created: Date;\n lastModified: Date;\n}\n\nexport interface ProjectIdentity {\n /** Project ID (resourceIdToString of resource ID) */\n id: string;\n /** Signed resource ID for use in transactions */\n rid: SignedResourceId;\n /** UUID field name in the project list resource */\n fieldName: string;\n}\n\nexport interface ProjectInfo extends ProjectEntry {\n schemaVersion: string | undefined;\n blockCount: number;\n blockIds: string[];\n}\n\n/** List all projects from a project list resource. */\nexport async function listProjects(\n pl: PlClient,\n projectListRid: SignedResourceId,\n): Promise<ProjectEntry[]> {\n return await pl.withReadTx(\"listProjects\", async (tx) => {\n const data = await tx.getResourceData(projectListRid, true);\n const entries: ProjectEntry[] = [];\n\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n\n const [metaStr, createdStr, modifiedStr] = await Promise.all([\n tx.getKValueStringIfExists(f.value, ProjectMetaKey),\n tx.getKValueStringIfExists(f.value, ProjectCreatedTimestamp),\n tx.getKValueStringIfExists(f.value, ProjectLastModifiedTimestamp),\n ]);\n\n const meta: ProjectMeta = metaStr ? JSON.parse(metaStr) : { label: \"(unknown)\" };\n\n const projectId = resourceIdToString(f.value);\n entries.push({\n id: projectId,\n rid: f.value,\n label: meta.label,\n created: createdStr ? new Date(Number(createdStr)) : new Date(0),\n lastModified: modifiedStr ? new Date(Number(modifiedStr)) : new Date(0),\n });\n }\n\n entries.sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());\n return entries;\n });\n}\n\n/** A project's identity plus its label — what a whole-root operation needs per project. */\nexport interface ProjectIdentityWithLabel extends ProjectIdentity {\n label: string;\n}\n\n/**\n * Lists every project in a project list with the field name holding it, which\n * {@link listProjects} omits. Whole-root operations (moving a user's projects out before the\n * account is deleted) need that field name to detach each project from its old owner.\n */\nexport async function listProjectIdentities(\n pl: PlClient,\n projectListRid: SignedResourceId,\n): Promise<ProjectIdentityWithLabel[]> {\n return await pl.withReadTx(\"listProjectIdentities\", async (tx) => {\n return await listProjectIdentitiesInTx(tx, projectListRid);\n });\n}\n\n/**\n * {@link listProjectIdentities} against a transaction the caller already holds, so a write that\n * acts on the list can read it in the same transaction rather than trusting an earlier snapshot.\n */\nexport async function listProjectIdentitiesInTx(\n tx: PlTransaction,\n projectListRid: SignedResourceId,\n): Promise<ProjectIdentityWithLabel[]> {\n const data = await tx.getResourceData(projectListRid, true);\n const projects: ProjectIdentityWithLabel[] = [];\n\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n\n const metaStr = await tx.getKValueStringIfExists(f.value, ProjectMetaKey);\n const meta: ProjectMeta = metaStr ? JSON.parse(metaStr) : { label: \"(unknown)\" };\n\n projects.push({\n id: resourceIdToString(f.value),\n rid: f.value,\n fieldName: f.name,\n label: meta.label,\n });\n }\n\n return projects;\n}\n\n/** Get detailed info about a project. */\nexport async function getProjectInfo(\n pl: PlClient,\n projectId: string,\n rid: SignedResourceId,\n): Promise<ProjectInfo> {\n return await pl.withReadTx(\"getProjectInfo\", async (tx) => {\n const kvs = await tx.listKeyValuesString(rid);\n\n const metaKV = kvs.find((kv: { key: string }) => kv.key === ProjectMetaKey);\n const createdKV = kvs.find((kv: { key: string }) => kv.key === ProjectCreatedTimestamp);\n const modifiedKV = kvs.find((kv: { key: string }) => kv.key === ProjectLastModifiedTimestamp);\n const schemaKV = kvs.find((kv: { key: string }) => kv.key === SchemaVersionKey);\n const structureKV = kvs.find((kv: { key: string }) => kv.key === ProjectStructureKey);\n\n const meta: ProjectMeta = metaKV ? JSON.parse(metaKV.value) : { label: \"(unknown)\" };\n const schemaVersion = schemaKV ? JSON.parse(schemaKV.value) : undefined;\n\n const blockIds: string[] = [];\n if (structureKV) {\n const structure = JSON.parse(structureKV.value);\n for (const group of structure.groups ?? []) {\n for (const block of group.blocks ?? []) {\n blockIds.push(block.id);\n }\n }\n }\n\n return {\n id: projectId,\n rid: rid,\n label: meta.label,\n created: createdKV ? new Date(Number(createdKV.value)) : new Date(0),\n lastModified: modifiedKV ? new Date(Number(modifiedKV.value)) : new Date(0),\n schemaVersion,\n blockCount: blockIds.length,\n blockIds,\n };\n });\n}\n\n/** Resolve a project identifier (id or label) to its project ID, ResourceId and field name. */\nexport async function resolveProject(\n pl: PlClient,\n projectListRid: SignedResourceId,\n identifier: string,\n): Promise<ProjectIdentity> {\n return await pl.withReadTx(\"resolveProject\", async (tx) => {\n const data = await tx.getResourceData(projectListRid, true);\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const projectId = resourceIdToString(f.value);\n if (projectId === identifier) {\n return { id: projectId, rid: f.value, fieldName: f.name };\n }\n }\n // Fallback: match by label\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const metaStr = await tx.getKValueStringIfExists(f.value, ProjectMetaKey);\n if (metaStr) {\n const meta: ProjectMeta = JSON.parse(metaStr);\n if (meta.label === identifier) {\n return { id: resourceIdToString(f.value), rid: f.value, fieldName: f.name };\n }\n }\n }\n\n throw new Error(`Project \"${identifier}\" not found (searched by id and label).`);\n });\n}\n\n/** Read all project labels within an existing transaction. */\nexport async function getExistingLabelsInTx(\n tx: PlTransaction,\n projectListRid: SignedResourceId,\n): Promise<string[]> {\n const data = await tx.getResourceData(projectListRid, true);\n const labels: string[] = [];\n for (const f of data.fields) {\n if (isNullSignedResourceId(f.value)) continue;\n const metaStr = await tx.getKValueStringIfExists(f.value, ProjectMetaKey);\n if (metaStr) {\n const meta: ProjectMeta = JSON.parse(metaStr);\n labels.push(meta.label);\n }\n }\n return labels;\n}\n\n/** Get all project labels from a project list. */\nexport async function getProjectLabels(\n pl: PlClient,\n projectListRid: SignedResourceId,\n): Promise<string[]> {\n return await pl.withReadTx(\"getProjectLabels\", async (tx) => {\n return getExistingLabelsInTx(tx, projectListRid);\n });\n}\n\n/**\n * Deduplicates a project name against existing labels.\n * \"X\" → \"X (Copy)\" → \"X (Copy 2)\" → ...\n */\nexport function deduplicateName(baseName: string, existingLabels: string[]): string {\n let candidate = `${baseName} (Copy)`;\n let i = 2;\n while (existingLabels.includes(candidate)) {\n candidate = `${baseName} (Copy ${i})`;\n i++;\n }\n return candidate;\n}\n\n/** Rename a project (update its label). */\nexport async function renameProject(\n pl: PlClient,\n projectRid: SignedResourceId,\n newLabel: string,\n): Promise<void> {\n await pl.withWriteTx(\"renameProject\", async (tx) => {\n const metaStr = await tx.getKValueString(projectRid, ProjectMetaKey);\n const meta: ProjectMeta = JSON.parse(metaStr);\n const updated: ProjectMeta = { ...meta, label: newLabel };\n tx.setKValue(projectRid, ProjectMetaKey, JSON.stringify(updated));\n tx.setKValue(projectRid, ProjectLastModifiedTimestamp, String(Date.now()));\n await tx.commit();\n });\n}\n\n/** Delete a project from the project list. */\nexport async function deleteProject(\n pl: PlClient,\n projectListRid: SignedResourceId,\n fieldName: string,\n): Promise<void> {\n await pl.withWriteTx(\"deleteProject\", async (tx) => {\n tx.removeField(field(projectListRid, fieldName));\n await tx.commit();\n });\n}\n\n/** One project moved by {@link moveProjects}, as it ended up in the target root. */\nexport interface MovedProject {\n id: string;\n /** Label the project had in the source root. */\n sourceLabel: string;\n /** Label it carries in the target root — differs when the name collided and was deduplicated. */\n targetLabel: string;\n}\n\n/**\n * Re-attaches projects from one user's project list to another's, keeping the same project\n * resources — no copy is made, so nothing is duplicated and no data is rewritten.\n *\n * This works across roots because the backend permits a reference between differently coloured\n * resources when the caller holds write access to both, which admin credentials do. Names that\n * collide in the target are deduplicated the way {@link duplicateProject} callers deduplicate\n * theirs, so a move never silently shadows a project the target user already has.\n *\n * The whole batch is one transaction: either every project lands in the target root, or none\n * moves and both roots are untouched.\n */\nexport async function moveProjects(\n pl: PlClient,\n sourceProjectListRid: SignedResourceId,\n targetProjectListRid: SignedResourceId,\n): Promise<MovedProject[]> {\n return await pl.withWriteTx(\"moveProjects\", async (tx) => {\n // Read here rather than taken from the caller: a list read before an operator answered a\n // confirmation prompt describes the account as it was minutes ago, and a project attached\n // since then would be left on the source root — where the account deletion that follows\n // destroys it. Moving what this transaction sees narrows that to the transaction itself.\n const projects = await listProjectIdentitiesInTx(tx, sourceProjectListRid);\n if (projects.length === 0) return [];\n\n const takenLabels = await getExistingLabelsInTx(tx, targetProjectListRid);\n const moved: MovedProject[] = [];\n\n for (const project of projects) {\n const metaStr = await tx.getKValueString(project.rid, ProjectMetaKey);\n const meta: ProjectMeta = JSON.parse(metaStr);\n const sourceLabel = meta.label;\n\n let targetLabel = sourceLabel;\n if (takenLabels.includes(targetLabel)) {\n targetLabel = deduplicateName(sourceLabel, takenLabels);\n tx.setKValue(project.rid, ProjectMetaKey, JSON.stringify({ ...meta, label: targetLabel }));\n tx.setKValue(project.rid, ProjectLastModifiedTimestamp, String(Date.now()));\n }\n // Reserved even when the label was free, so two source projects with the same name do not\n // both keep it.\n takenLabels.push(targetLabel);\n\n // Attached to the target before being detached from the source: the project keeps a\n // reference throughout, so it is never momentarily unreferenced.\n tx.createField(field(targetProjectListRid, randomUUID()), \"Dynamic\", project.rid);\n tx.removeField(field(sourceProjectListRid, project.fieldName));\n\n moved.push({ id: project.id, sourceLabel, targetLabel });\n }\n\n await tx.commit();\n return moved;\n });\n}\n\n/** Get the project list ResourceId for the connected user. */\nexport async function getProjectListRid(pl: PlClient): Promise<SignedResourceId> {\n return await pl.withReadTx(\"getProjectList\", async (tx) => {\n const fieldData = await tx.getField({\n resourceId: tx.clientRoot,\n fieldName: ProjectsField,\n });\n if (isNullSignedResourceId(fieldData.value)) {\n throw new Error(\"No project list found for this user.\");\n }\n return fieldData.value;\n });\n}\n\n/**\n * Resolves a user's root and, if they have one, their project list.\n *\n * Unlike {@link navigateToUserRoot} a missing project list is not an error here: a user who has\n * never opened the app has a root and no list, and that account is still a legitimate target for\n * whole-account operations. Callers that need a list to write into use\n * {@link ensureUserProjectList}.\n */\nexport async function openUserRoot(\n pl: PlClient,\n username: string,\n): Promise<{ userRoot: SignedResourceId; projectListRid: SignedResourceId | undefined }> {\n let userRoot: SignedResourceId | undefined;\n try {\n userRoot = await pl.getUserRoot({ login: username });\n } catch (e) {\n // The backend reports an unknown login as NOT_FOUND on the root, which reads as a missing\n // resource rather than a missing user. Name the actual problem.\n if (isNotFoundError(e)) {\n throw new Error(`User \"${username}\" not found on this server.`);\n }\n throw e;\n }\n if (userRoot === undefined) {\n throw new Error(`User \"${username}\" not found on this server (no root resource).`);\n }\n\n return await pl.withReadTx(\"openUserRoot\", async (tx) => {\n const projectsField = await tx.getFieldIfExists(field(userRoot, ProjectsField));\n if (projectsField === undefined || isNullSignedResourceId(projectsField.value)) {\n return { userRoot, projectListRid: undefined };\n }\n return { userRoot, projectListRid: projectsField.value };\n });\n}\n\n/**\n * Returns a user's project list, creating an empty one when the root has none — the same lazy\n * creation the middle layer performs for the signed-in user, but against an impersonated root, so\n * projects can be re-homed to a user who has never opened the app.\n */\nexport async function ensureUserProjectList(\n pl: PlClient,\n userRoot: SignedResourceId,\n): Promise<SignedResourceId> {\n return await pl.withWriteTx(\"ensureUserProjectList\", async (tx) => {\n const projectsField = field(userRoot, ProjectsField);\n tx.createField(projectsField, \"Dynamic\");\n const fieldData = await tx.getField(projectsField);\n if (!isNullSignedResourceId(fieldData.value)) {\n await tx.commit();\n return fieldData.value;\n }\n\n const list = tx.createEphemeral(ProjectsResourceType);\n tx.lock(list);\n tx.setField(projectsField, list);\n await tx.commit();\n return await list.globalId;\n });\n}\n\n/**\n * Navigates to a specific user's project list resource ID.\n * Tries ListUserResources first (new backend), falls back to SHA256 named resource lookup.\n */\nexport async function navigateToUserRoot(\n pl: PlClient,\n username: string,\n): Promise<{ userRoot: SignedResourceId; projectListRid: SignedResourceId }> {\n let userRootRid: SignedResourceId | undefined;\n\n userRootRid = await pl.getUserRoot({ login: username });\n if (userRootRid === undefined) {\n throw new Error(`User \"${username}\" not found on this server (no root resource).`);\n }\n\n // Read the projects field from the resolved user root\n return await pl.withReadTx(\"navigateToUserProjects\", async (tx) => {\n const projectsFieldData = await tx.getField({\n resourceId: userRootRid,\n fieldName: ProjectsField,\n });\n\n if (isNullSignedResourceId(projectsFieldData.value)) {\n throw new Error(`User \"${username}\" has no project list.`);\n }\n\n return { userRoot: userRootRid, projectListRid: projectsFieldData.value };\n });\n}\n\n// Re-export duplicateProject from pl-middle-layer for use in commands\nexport { duplicateProject };\n","export type OutputFormat = \"text\" | \"json\" | \"csv\";\n\n/** Outputs a line of text to stdout. */\nexport function outputText(message: string): void {\n console.log(message);\n}\n\n/** Outputs data as formatted JSON to stdout. */\nexport function outputJson(data: unknown): void {\n console.log(JSON.stringify(data, null, 2));\n}\n\n/** Outputs a header row + data rows as RFC-4180-ish CSV to stdout. */\nexport function outputCsv(headers: string[], rows: string[][]): void {\n const esc = (v: string) => (/[\",\\r\\n]/.test(v) ? `\"${v.replace(/\"/g, '\"\"')}\"` : v);\n const lines = [headers, ...rows].map((r) => r.map(esc).join(\",\"));\n console.log(lines.join(\"\\n\"));\n}\n\n/** Formats a table as aligned text columns. */\nexport function formatTable(headers: string[], rows: string[][]): string {\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").length)),\n );\n\n const sep = colWidths.map((w) => \"-\".repeat(w)).join(\" \");\n const headerLine = headers.map((h, i) => h.padEnd(colWidths[i])).join(\" \");\n const dataLines = rows.map((row) =>\n row.map((cell, i) => (cell ?? \"\").padEnd(colWidths[i])).join(\" \"),\n );\n\n return [headerLine, sep, ...dataLines].join(\"\\n\");\n}\n\n/** Formats a Date as a short human-readable string. */\nexport function formatDate(d: Date): string {\n if (d.getTime() === 0) return \"(unknown)\";\n return d\n .toISOString()\n .replace(\"T\", \" \")\n .replace(/\\.\\d+Z$/, \"Z\");\n}\n"],"mappings":";;;;AAqBA,eAAsB,EAAmB,GAA8C;CACrF,IAAM,IAAyB,EAAkB,EAAK,QAAQ;AAG9D,CADI,EAAK,SAAS,KAAA,MAAW,EAAO,OAAO,EAAK,OAC5C,EAAK,aAAa,KAAA,MAAW,EAAO,WAAW,EAAK;CAExD,IAAM,IAAS,MAAM,EAAwB,MAAM,EAAO,EACtD;AAEJ,KAAI,MAAM,EAAO,aAAa,EAAE;AAC9B,MAAI,EAAO,SAAS,KAAA,KAAa,EAAO,aAAa,KAAA,EACnD,OAAU,MACR,2HAED;AAEH,MAAkB,MAAM,EAAO,MAAM,EAAO,MAAM,EAAO,SAAS;OAElE,KAAkB,EAAE;AAGtB,QAAO,MAAM,EAAS,KAAK,GAAQ,EAAE,oBAAiB,CAAC;;AAIzD,eAAsB,EAAwB,GAAiD;CAC7F,IAAM,IAAyB,EAAkB,EAAK,QAAQ,EAGxD,IAAmC,OAD1B,MAAM,EAAwB,MAAM,EAAO,EACJ,MAAM,EAAK,WAAW,EAAK,cAAc;AAE/F,QAAO,MAAM,EAAS,KAAK,GAAQ,EAAE,oBAAiB,CAAC;;;;ACRzD,eAAsB,EACpB,GACA,GACyB;AACzB,QAAO,MAAM,EAAG,WAAW,gBAAgB,OAAO,MAAO;EACvD,IAAM,IAAO,MAAM,EAAG,gBAAgB,GAAgB,GAAK,EACrD,IAA0B,EAAE;AAElC,OAAK,IAAM,KAAK,EAAK,QAAQ;AAC3B,OAAI,EAAuB,EAAE,MAAM,CAAE;GAErC,IAAM,CAAC,GAA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AAO;GAAE,UAAU;GAAa,gBAAgB,EAAkB;GAAO;GACzE;;;;AChbJ,SAAgB,EAAW,GAAuB;AAChD,SAAQ,IAAI,EAAQ;;AAItB,SAAgB,EAAW,GAAqB;AAC9C,SAAQ,IAAI,KAAK,UAAU,GAAM,MAAM,EAAE,CAAC;;AAI5C,SAAgB,EAAU,GAAmB,GAAwB;CACnE,IAAM,KAAO,MAAe,WAAW,KAAK,EAAE,GAAG,IAAI,EAAE,QAAQ,MAAM,OAAK,CAAC,KAAK,GAC1E,IAAQ,CAAC,GAAS,GAAG,EAAK,CAAC,KAAK,MAAM,EAAE,IAAI,EAAI,CAAC,KAAK,IAAI,CAAC;AACjE,SAAQ,IAAI,EAAM,KAAK,KAAK,CAAC;;AAI/B,SAAgB,EAAY,GAAmB,GAA0B;CACvE,IAAM,IAAY,EAAQ,KAAK,GAAG,MAChC,KAAK,IAAI,EAAE,QAAQ,GAAG,EAAK,KAAK,OAAO,EAAE,MAAM,IAAI,OAAO,CAAC,CAC5D,EAEK,IAAM,EAAU,KAAK,MAAM,IAAI,OAAO,EAAE,CAAC,CAAC,KAAK,KAAK;AAM1D,QAAO;EALY,EAAQ,KAAK,GAAG,MAAM,EAAE,OAAO,EAAU,GAAG,CAAC,CAAC,KAAK,KAAK;EAKvD;EAAK,GAJP,EAAK,KAAK,MAC1B,EAAI,KAAK,GAAM,OAAO,KAAQ,IAAI,OAAO,EAAU,GAAG,CAAC,CAAC,KAAK,KAAK,CACnE;EAEqC,CAAC,KAAK,KAAK;;AAInD,SAAgB,EAAW,GAAiB;AAE1C,QADI,EAAE,SAAS,KAAK,IAAU,cACvB,EACJ,aAAa,CACb,QAAQ,KAAK,IAAI,CACjB,QAAQ,WAAW,IAAI"}
|
package/dist/project_ops.d.ts
CHANGED
|
@@ -22,6 +22,21 @@ export interface ProjectInfo extends ProjectEntry {
|
|
|
22
22
|
}
|
|
23
23
|
/** List all projects from a project list resource. */
|
|
24
24
|
export declare function listProjects(pl: PlClient, projectListRid: SignedResourceId): Promise<ProjectEntry[]>;
|
|
25
|
+
/** A project's identity plus its label — what a whole-root operation needs per project. */
|
|
26
|
+
export interface ProjectIdentityWithLabel extends ProjectIdentity {
|
|
27
|
+
label: string;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Lists every project in a project list with the field name holding it, which
|
|
31
|
+
* {@link listProjects} omits. Whole-root operations (moving a user's projects out before the
|
|
32
|
+
* account is deleted) need that field name to detach each project from its old owner.
|
|
33
|
+
*/
|
|
34
|
+
export declare function listProjectIdentities(pl: PlClient, projectListRid: SignedResourceId): Promise<ProjectIdentityWithLabel[]>;
|
|
35
|
+
/**
|
|
36
|
+
* {@link listProjectIdentities} against a transaction the caller already holds, so a write that
|
|
37
|
+
* acts on the list can read it in the same transaction rather than trusting an earlier snapshot.
|
|
38
|
+
*/
|
|
39
|
+
export declare function listProjectIdentitiesInTx(tx: PlTransaction, projectListRid: SignedResourceId): Promise<ProjectIdentityWithLabel[]>;
|
|
25
40
|
/** Get detailed info about a project. */
|
|
26
41
|
export declare function getProjectInfo(pl: PlClient, projectId: string, rid: SignedResourceId): Promise<ProjectInfo>;
|
|
27
42
|
/** Resolve a project identifier (id or label) to its project ID, ResourceId and field name. */
|
|
@@ -39,8 +54,47 @@ export declare function deduplicateName(baseName: string, existingLabels: string
|
|
|
39
54
|
export declare function renameProject(pl: PlClient, projectRid: SignedResourceId, newLabel: string): Promise<void>;
|
|
40
55
|
/** Delete a project from the project list. */
|
|
41
56
|
export declare function deleteProject(pl: PlClient, projectListRid: SignedResourceId, fieldName: string): Promise<void>;
|
|
57
|
+
/** One project moved by {@link moveProjects}, as it ended up in the target root. */
|
|
58
|
+
export interface MovedProject {
|
|
59
|
+
id: string;
|
|
60
|
+
/** Label the project had in the source root. */
|
|
61
|
+
sourceLabel: string;
|
|
62
|
+
/** Label it carries in the target root — differs when the name collided and was deduplicated. */
|
|
63
|
+
targetLabel: string;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Re-attaches projects from one user's project list to another's, keeping the same project
|
|
67
|
+
* resources — no copy is made, so nothing is duplicated and no data is rewritten.
|
|
68
|
+
*
|
|
69
|
+
* This works across roots because the backend permits a reference between differently coloured
|
|
70
|
+
* resources when the caller holds write access to both, which admin credentials do. Names that
|
|
71
|
+
* collide in the target are deduplicated the way {@link duplicateProject} callers deduplicate
|
|
72
|
+
* theirs, so a move never silently shadows a project the target user already has.
|
|
73
|
+
*
|
|
74
|
+
* The whole batch is one transaction: either every project lands in the target root, or none
|
|
75
|
+
* moves and both roots are untouched.
|
|
76
|
+
*/
|
|
77
|
+
export declare function moveProjects(pl: PlClient, sourceProjectListRid: SignedResourceId, targetProjectListRid: SignedResourceId): Promise<MovedProject[]>;
|
|
42
78
|
/** Get the project list ResourceId for the connected user. */
|
|
43
79
|
export declare function getProjectListRid(pl: PlClient): Promise<SignedResourceId>;
|
|
80
|
+
/**
|
|
81
|
+
* Resolves a user's root and, if they have one, their project list.
|
|
82
|
+
*
|
|
83
|
+
* Unlike {@link navigateToUserRoot} a missing project list is not an error here: a user who has
|
|
84
|
+
* never opened the app has a root and no list, and that account is still a legitimate target for
|
|
85
|
+
* whole-account operations. Callers that need a list to write into use
|
|
86
|
+
* {@link ensureUserProjectList}.
|
|
87
|
+
*/
|
|
88
|
+
export declare function openUserRoot(pl: PlClient, username: string): Promise<{
|
|
89
|
+
userRoot: SignedResourceId;
|
|
90
|
+
projectListRid: SignedResourceId | undefined;
|
|
91
|
+
}>;
|
|
92
|
+
/**
|
|
93
|
+
* Returns a user's project list, creating an empty one when the root has none — the same lazy
|
|
94
|
+
* creation the middle layer performs for the signed-in user, but against an impersonated root, so
|
|
95
|
+
* projects can be re-homed to a user who has never opened the app.
|
|
96
|
+
*/
|
|
97
|
+
export declare function ensureUserProjectList(pl: PlClient, userRoot: SignedResourceId): Promise<SignedResourceId>;
|
|
44
98
|
/**
|
|
45
99
|
* Navigates to a specific user's project list resource ID.
|
|
46
100
|
* Tries ListUserResources first (new backend), falls back to SHA256 named resource lookup.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@platforma-sdk/pl-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.1",
|
|
4
4
|
"description": "CLI for Platforma server state manipulation",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"bin": {
|
|
@@ -23,8 +23,8 @@
|
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"commander": "^15.0.0",
|
|
26
|
-
"@milaboratories/pl-client": "3.
|
|
27
|
-
"@milaboratories/pl-middle-layer": "1.68.
|
|
26
|
+
"@milaboratories/pl-client": "3.15.0",
|
|
27
|
+
"@milaboratories/pl-middle-layer": "1.68.2"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
30
|
"@types/node": "~24.5.2",
|
|
@@ -33,8 +33,8 @@
|
|
|
33
33
|
"vite": "^8.0.6",
|
|
34
34
|
"vite-plugin-dts": "^5.0.3",
|
|
35
35
|
"vitest": "^4.1.3",
|
|
36
|
-
"@milaboratories/ts-builder": "1.7.1",
|
|
37
36
|
"@milaboratories/build-configs": "2.0.1",
|
|
37
|
+
"@milaboratories/ts-builder": "1.7.2",
|
|
38
38
|
"@milaboratories/ts-configs": "1.4.0"
|
|
39
39
|
},
|
|
40
40
|
"scripts": {
|
package/src/cli.ts
CHANGED
|
@@ -6,6 +6,7 @@ import projectRenameCommand from "./cmd/project/rename";
|
|
|
6
6
|
import projectDeleteCommand from "./cmd/project/delete";
|
|
7
7
|
import adminCopyProjectCommand from "./cmd/admin/copy-project";
|
|
8
8
|
import adminUserListCommand from "./cmd/admin/user-list";
|
|
9
|
+
import adminDeleteUserCommand from "./cmd/admin/delete-user";
|
|
9
10
|
|
|
10
11
|
export function buildProgram(): Command {
|
|
11
12
|
const program = new Command();
|
|
@@ -24,6 +25,7 @@ export function buildProgram(): Command {
|
|
|
24
25
|
);
|
|
25
26
|
admin.addCommand(adminCopyProjectCommand());
|
|
26
27
|
admin.addCommand(adminUserListCommand());
|
|
28
|
+
admin.addCommand(adminDeleteUserCommand());
|
|
27
29
|
program.addCommand(admin);
|
|
28
30
|
|
|
29
31
|
return program;
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { Command, Option } from "commander";
|
|
2
|
+
import { createInterface } from "node:readline";
|
|
3
|
+
import { connectClient } from "../../base_command";
|
|
4
|
+
import { addOptions, GlobalOptions, AdminAuthOptions } from "../../cmd-opts";
|
|
5
|
+
import {
|
|
6
|
+
ensureUserProjectList,
|
|
7
|
+
listProjectIdentities,
|
|
8
|
+
moveProjects,
|
|
9
|
+
openUserRoot,
|
|
10
|
+
} from "../../project_ops";
|
|
11
|
+
import type { MovedProject, ProjectIdentityWithLabel } from "../../project_ops";
|
|
12
|
+
import { formatTable, outputJson, outputText } from "../../output";
|
|
13
|
+
|
|
14
|
+
export default function adminDeleteUserCommand(): Command {
|
|
15
|
+
const cmd = new Command("delete-user").description(
|
|
16
|
+
"Delete a user account. Optionally re-homes the user's projects to another user first. " +
|
|
17
|
+
"Requires admin/controller credentials.",
|
|
18
|
+
);
|
|
19
|
+
|
|
20
|
+
cmd.argument("<user>", "Username of the account to delete");
|
|
21
|
+
addOptions(cmd, GlobalOptions(), AdminAuthOptions());
|
|
22
|
+
cmd.addOption(
|
|
23
|
+
new Option(
|
|
24
|
+
"--move-projects-to <user>",
|
|
25
|
+
"Re-home the deleted user's projects to this user before deleting the account",
|
|
26
|
+
),
|
|
27
|
+
);
|
|
28
|
+
cmd.addOption(
|
|
29
|
+
new Option(
|
|
30
|
+
"--delete-projects",
|
|
31
|
+
"Delete the user's projects along with the account, losing their data",
|
|
32
|
+
),
|
|
33
|
+
);
|
|
34
|
+
cmd.option("--force", "Skip confirmation", false);
|
|
35
|
+
|
|
36
|
+
cmd.action(async (user: string, flags) => {
|
|
37
|
+
// The two modes are alternatives, not a combination: one keeps the projects, the other
|
|
38
|
+
// destroys them, and a request for both says nothing about which was meant.
|
|
39
|
+
if (flags.moveProjectsTo && flags.deleteProjects) {
|
|
40
|
+
throw new Error("--move-projects-to and --delete-projects are mutually exclusive");
|
|
41
|
+
}
|
|
42
|
+
if (flags.moveProjectsTo === user) {
|
|
43
|
+
throw new Error("--move-projects-to must name a different user than the one being deleted");
|
|
44
|
+
}
|
|
45
|
+
// Caught here as well as server-side, where it is authoritative: the operator gets the reason
|
|
46
|
+
// instead of a failure from whichever lookup happens to run first.
|
|
47
|
+
if (flags.adminUser === user) {
|
|
48
|
+
throw new Error(
|
|
49
|
+
`Refusing to delete "${user}" — it is the account these credentials authenticate as.`,
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const pl = await connectClient(flags);
|
|
54
|
+
try {
|
|
55
|
+
const source = await openUserRoot(pl, user);
|
|
56
|
+
// No project list means the account never opened the app, so it owns nothing — a state to
|
|
57
|
+
// delete straight through, not to fail on.
|
|
58
|
+
const projects =
|
|
59
|
+
source.projectListRid === undefined
|
|
60
|
+
? []
|
|
61
|
+
: await listProjectIdentities(pl, source.projectListRid);
|
|
62
|
+
|
|
63
|
+
// Neither mode given while the account still owns projects: refuse rather than pick. Both
|
|
64
|
+
// defaults are wrong to assume — one silently destroys data, the other silently hands it to
|
|
65
|
+
// someone. An account with no projects has nothing to decide about, so it just proceeds.
|
|
66
|
+
if (projects.length > 0 && !flags.moveProjectsTo && !flags.deleteProjects) {
|
|
67
|
+
throw new Error(
|
|
68
|
+
`User "${user}" owns ${projects.length} project(s). Pass --move-projects-to <user> to ` +
|
|
69
|
+
"re-home them, or --delete-projects to delete them with the account.",
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const confirmed = await confirmDeletion(user, projects, flags);
|
|
74
|
+
if (!confirmed) {
|
|
75
|
+
outputText("Aborted.");
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
let moved: MovedProject[] = [];
|
|
80
|
+
if (flags.moveProjectsTo && projects.length > 0) {
|
|
81
|
+
const target = await openUserRoot(pl, flags.moveProjectsTo);
|
|
82
|
+
// Created if the target has none, so re-homing to a user who has never opened the app
|
|
83
|
+
// works rather than failing halfway with the account still present.
|
|
84
|
+
const targetList = await ensureUserProjectList(pl, target.userRoot);
|
|
85
|
+
moved = await moveProjects(pl, source.projectListRid!, targetList);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// deleteUser takes the root and everything still attached to it. The listing, the prompt and
|
|
89
|
+
// the move each ran in an earlier transaction, so re-read: a project attached since then would
|
|
90
|
+
// be destroyed without ever being reviewed.
|
|
91
|
+
const remaining =
|
|
92
|
+
source.projectListRid === undefined
|
|
93
|
+
? []
|
|
94
|
+
: await listProjectIdentities(pl, source.projectListRid);
|
|
95
|
+
assertProjectsAccountedFor(user, flags, projects, remaining);
|
|
96
|
+
|
|
97
|
+
const report = await pl.deleteUser(user);
|
|
98
|
+
|
|
99
|
+
if (flags.format === "json") {
|
|
100
|
+
outputJson({
|
|
101
|
+
deleted: true,
|
|
102
|
+
user,
|
|
103
|
+
movedTo: flags.moveProjectsTo ?? null,
|
|
104
|
+
movedProjects: moved,
|
|
105
|
+
deletedProjects: flags.moveProjectsTo ? [] : remaining.map((p) => p.label),
|
|
106
|
+
userRootId: report.userRootId === undefined ? null : report.userRootId.toString(),
|
|
107
|
+
userRootDeleted: report.userRootDeleted,
|
|
108
|
+
revokedGrants: report.revokedGrants,
|
|
109
|
+
removedIdentityIndexEntries: report.removedIdentityIndexEntries,
|
|
110
|
+
});
|
|
111
|
+
} else {
|
|
112
|
+
outputText(renderResult(user, flags.moveProjectsTo, moved, remaining));
|
|
113
|
+
}
|
|
114
|
+
} finally {
|
|
115
|
+
await pl.close();
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
return cmd;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Refuses while the root holds a project the operator never agreed to lose — attached after the
|
|
124
|
+
* listing, or left behind by the move.
|
|
125
|
+
*
|
|
126
|
+
* A last read, not a lock: it closes the prompt-sized window, not the round trip that follows.
|
|
127
|
+
*/
|
|
128
|
+
function assertProjectsAccountedFor(
|
|
129
|
+
user: string,
|
|
130
|
+
flags: { moveProjectsTo?: string },
|
|
131
|
+
approved: ProjectIdentityWithLabel[],
|
|
132
|
+
remaining: ProjectIdentityWithLabel[],
|
|
133
|
+
): void {
|
|
134
|
+
if (flags.moveProjectsTo) {
|
|
135
|
+
if (remaining.length === 0) return;
|
|
136
|
+
throw new Error(
|
|
137
|
+
`User "${user}" still owns ${remaining.length} project(s) after the move: ` +
|
|
138
|
+
`${remaining.map((p) => p.label).join(", ")}. The account was NOT deleted — ` +
|
|
139
|
+
"the projects were attached while the move ran. Re-run the command to move them too.",
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const approvedIds = new Set(approved.map((p) => p.id));
|
|
144
|
+
const unapproved = remaining.filter((p) => !approvedIds.has(p.id));
|
|
145
|
+
if (unapproved.length === 0) return;
|
|
146
|
+
throw new Error(
|
|
147
|
+
`User "${user}" gained ${unapproved.length} project(s) since the list you confirmed: ` +
|
|
148
|
+
`${unapproved.map((p) => p.label).join(", ")}. The account was NOT deleted — ` +
|
|
149
|
+
"deleting it now would destroy them unreviewed. Re-run the command to see the current list.",
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Asks the operator to confirm, naming the affected projects and their fate. */
|
|
154
|
+
async function confirmDeletion(
|
|
155
|
+
user: string,
|
|
156
|
+
projects: ProjectIdentityWithLabel[],
|
|
157
|
+
flags: { moveProjectsTo?: string; force?: boolean },
|
|
158
|
+
): Promise<boolean> {
|
|
159
|
+
if (flags.force) return true;
|
|
160
|
+
|
|
161
|
+
const fate = flags.moveProjectsTo
|
|
162
|
+
? `${projects.length} project(s) will move to "${flags.moveProjectsTo}"`
|
|
163
|
+
: projects.length > 0
|
|
164
|
+
? `${projects.length} project(s) will be PERMANENTLY DELETED`
|
|
165
|
+
: "the account owns no projects";
|
|
166
|
+
|
|
167
|
+
process.stderr.write(`Delete user "${user}"? ${fate}.\n`);
|
|
168
|
+
if (projects.length > 0) {
|
|
169
|
+
process.stderr.write(projects.map((p) => ` - ${p.label}`).join("\n") + "\n");
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
173
|
+
try {
|
|
174
|
+
const answer = await new Promise<string>((resolve) => {
|
|
175
|
+
rl.question("Proceed? [y/N] ", resolve);
|
|
176
|
+
});
|
|
177
|
+
return answer.toLowerCase() === "y";
|
|
178
|
+
} finally {
|
|
179
|
+
rl.close();
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function renderResult(
|
|
184
|
+
user: string,
|
|
185
|
+
movedTo: string | undefined,
|
|
186
|
+
moved: MovedProject[],
|
|
187
|
+
projects: ProjectIdentityWithLabel[],
|
|
188
|
+
): string {
|
|
189
|
+
const lines: string[] = [];
|
|
190
|
+
|
|
191
|
+
if (movedTo) {
|
|
192
|
+
if (moved.length > 0) {
|
|
193
|
+
lines.push(`Moved ${moved.length} project(s) from ${user} to ${movedTo}:`);
|
|
194
|
+
lines.push(
|
|
195
|
+
formatTable(
|
|
196
|
+
["id", "name", "name in target"],
|
|
197
|
+
moved.map((p) => [p.id, p.sourceLabel, p.targetLabel]),
|
|
198
|
+
),
|
|
199
|
+
);
|
|
200
|
+
} else {
|
|
201
|
+
lines.push(`User ${user} had no projects to move.`);
|
|
202
|
+
}
|
|
203
|
+
} else if (projects.length > 0) {
|
|
204
|
+
lines.push(`Deleted ${projects.length} project(s) belonging to ${user}:`);
|
|
205
|
+
lines.push(projects.map((p) => ` - ${p.label}`).join("\n"));
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
lines.push(`Deleted user "${user}".`);
|
|
209
|
+
return lines.join("\n");
|
|
210
|
+
}
|