@platforma-sdk/pl-cli 0.11.4 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,52 +1,52 @@
1
- import { _ as e, a as t, b as n, c as r, d as i, f as a, g as o, h as s, i as c, l, m as u, n as d, o as f, p, r as m, s as h, t as g, u as _, v, x as y, y as b } from "./output-D41Wn0wM.js";
2
- import { Command as x, InvalidArgumentError as S, Option as C } from "commander";
3
- import { asSignedResourceId as ee, createSignedResourceId as te, field as w, isLocalResourceId as T, isNotNullSignedResourceId as E, resourceIdFromString as D, resourceIdToString as O, resourceType as k, resourceTypeToString as A } from "@milaboratories/pl-client";
4
- import { randomUUID as j } from "node:crypto";
5
- import { InstanceStatsContextTypeName as ne, ProjectMetaKey as M, parseInstanceStats as re } from "@milaboratories/pl-middle-layer";
6
- import { createInterface as N } from "node:readline";
7
- import { once as ie } from "node:events";
1
+ import { _ as e, a as t, b as n, c as r, d as i, f as a, g as o, h as s, i as c, l, m as u, n as d, o as f, p, r as m, s as h, t as g, u as _, v as ee, x as te, y as v } from "./output-D41Wn0wM.js";
2
+ import { Command as y, InvalidArgumentError as b, Option as x } from "commander";
3
+ import { anyResourceIdToBigint as S, asSignedResourceId as C, createSignedResourceId as ne, field as w, isLocalResourceId as re, isNotNullSignedResourceId as T, listRegisteredControllers as E, resourceIdFromString as ie, resourceIdToString as D, resourceType as ae, resourceTypeToString as oe } from "@milaboratories/pl-client";
4
+ import { randomUUID as O } from "node:crypto";
5
+ import { InstanceStatsContextTypeName as se, ProjectMetaKey as k, parseInstanceStats as A } from "@milaboratories/pl-middle-layer";
6
+ import { createInterface as j } from "node:readline";
7
+ import { once as ce } from "node:events";
8
8
  // src/base_command.ts
9
- async function P(e) {
9
+ async function M(e) {
10
10
  return e.adminUser && e.adminPassword ? n({
11
11
  address: e.address,
12
12
  adminUser: e.adminUser,
13
13
  adminPassword: e.adminPassword
14
- }) : y({
14
+ }) : te({
15
15
  address: e.address,
16
16
  user: e.user,
17
17
  password: e.password
18
18
  });
19
19
  }
20
- async function F(e) {
20
+ async function N(e) {
21
21
  let t = !!e.adminUser, n = !!e.adminPassword, r = !!e.targetUser;
22
22
  if (r && !(t && n)) throw Error("--target-user requires --admin-user and --admin-password");
23
23
  if ((t || n) && !r) throw Error("--admin-user/--admin-password require --target-user for project commands");
24
- let i = await P(e), s;
24
+ let i = await M(e), s;
25
25
  return s = r ? (await o(i, e.targetUser)).projectListRid : await a(i), {
26
26
  pl: i,
27
27
  projectListRid: s
28
28
  };
29
29
  }
30
30
  // src/cmd-opts.ts
31
- function I(e, ...t) {
31
+ function P(e, ...t) {
32
32
  for (let n of t) for (let t of n) e.addOption(t);
33
33
  return e;
34
34
  }
35
- var L = () => [new C("-a, --address <url>", "Platforma server address").env("PL_ADDRESS").makeOptionMandatory()], R = (e = "text", t = ["text", "json"]) => [...L(), new C("-f, --format <format>", "Output format").choices(t).default(e)], z = () => [new C("-u, --user <user>", "Username for authentication").env("PL_USER"), new C("-p, --password <password>", "Password for authentication").env("PL_PASSWORD")], B = () => [new C("--admin-user <user>", "Admin/controller username").env("PL_ADMIN_USER").makeOptionMandatory(), new C("--admin-password <password>", "Admin/controller password").env("PL_ADMIN_PASSWORD").makeOptionMandatory()], V = () => [
36
- new C("--admin-user <user>", "Admin/controller username (enables admin mode)").env("PL_ADMIN_USER"),
37
- new C("--admin-password <password>", "Admin/controller password").env("PL_ADMIN_PASSWORD"),
38
- new C("--target-user <user>", "Operate on this user's data (requires admin credentials)").env("PL_TARGET_USER")
35
+ var F = () => [new x("-a, --address <url>", "Platforma server address").env("PL_ADDRESS").makeOptionMandatory()], I = (e = "text", t = ["text", "json"]) => [...F(), new x("-f, --format <format>", "Output format").choices(t).default(e)], L = () => [new x("-u, --user <user>", "Username for authentication").env("PL_USER"), new x("-p, --password <password>", "Password for authentication").env("PL_PASSWORD")], R = () => [new x("--admin-user <user>", "Admin/controller username").env("PL_ADMIN_USER").makeOptionMandatory(), new x("--admin-password <password>", "Admin/controller password").env("PL_ADMIN_PASSWORD").makeOptionMandatory()], z = () => [
36
+ new x("--admin-user <user>", "Admin/controller username (enables admin mode)").env("PL_ADMIN_USER"),
37
+ new x("--admin-password <password>", "Admin/controller password").env("PL_ADMIN_PASSWORD"),
38
+ new x("--target-user <user>", "Operate on this user's data (requires admin credentials)").env("PL_TARGET_USER")
39
39
  ];
40
40
  // src/cmd/project/list.ts
41
- function H() {
42
- let e = new x("list").description("List all projects for the authenticated user.");
43
- return I(e, R(), z(), V()), e.action(async (e) => {
44
- let { pl: n, projectListRid: r } = await F(e);
41
+ function B() {
42
+ let e = new y("list").description("List all projects for the authenticated user.");
43
+ return P(e, I(), L(), z()), e.action(async (e) => {
44
+ let { pl: n, projectListRid: r } = await N(e);
45
45
  try {
46
46
  let i = await u(n, r);
47
47
  if (e.format === "json") c(i.map((e) => ({
48
48
  id: e.id,
49
- rid: O(e.rid),
49
+ rid: D(e.rid),
50
50
  label: e.label,
51
51
  created: e.created.toISOString(),
52
52
  lastModified: e.lastModified.toISOString()
@@ -64,7 +64,7 @@ function H() {
64
64
  "LAST MODIFIED"
65
65
  ], i.map((e) => [
66
66
  e.id,
67
- O(e.rid),
67
+ D(e.rid),
68
68
  e.label,
69
69
  g(e.created),
70
70
  g(e.lastModified)
@@ -76,15 +76,15 @@ function H() {
76
76
  }), e;
77
77
  }
78
78
  // src/cmd/project/info.ts
79
- function U() {
80
- let e = new x("info").description("Show detailed information about a project.");
81
- return e.argument("<project>", "Project ID or label"), I(e, R(), z(), V()), e.action(async (e, n) => {
82
- let { pl: r, projectListRid: a } = await F(n);
79
+ function V() {
80
+ let e = new y("info").description("Show detailed information about a project.");
81
+ return e.argument("<project>", "Project ID or label"), P(e, I(), L(), z()), e.action(async (e, n) => {
82
+ let { pl: r, projectListRid: a } = await N(n);
83
83
  try {
84
- let { id: o, rid: s } = await b(r, a, e), l = await i(r, o, s);
84
+ let { id: o, rid: s } = await v(r, a, e), l = await i(r, o, s);
85
85
  if (n.format === "json") c({
86
86
  id: l.id,
87
- rid: O(l.rid),
87
+ rid: D(l.rid),
88
88
  label: l.label,
89
89
  schemaVersion: l.schemaVersion,
90
90
  blockCount: l.blockCount,
@@ -93,7 +93,7 @@ function U() {
93
93
  lastModified: l.lastModified.toISOString()
94
94
  });
95
95
  else {
96
- if (t(`Project: ${l.label}`), t(`ID: ${l.id}`), t(`RID: ${O(l.rid)}`), t(`Schema: ${l.schemaVersion ?? "(unknown)"}`), t(`Blocks: ${l.blockCount}`), l.blockIds.length > 0) for (let e of l.blockIds) t(` - ${e}`);
96
+ if (t(`Project: ${l.label}`), t(`ID: ${l.id}`), t(`RID: ${D(l.rid)}`), t(`Schema: ${l.schemaVersion ?? "(unknown)"}`), t(`Blocks: ${l.blockCount}`), l.blockIds.length > 0) for (let e of l.blockIds) t(` - ${e}`);
97
97
  t(`Created: ${g(l.created)}`), t(`Last Modified: ${g(l.lastModified)}`);
98
98
  }
99
99
  } finally {
@@ -102,13 +102,13 @@ function U() {
102
102
  }), e;
103
103
  }
104
104
  // src/cmd/project/duplicate.ts
105
- function W() {
106
- let e = new x("duplicate").description("Duplicate a project within the same user. Auto-renames on collision by default.");
107
- return e.argument("<project>", "Project ID or label"), I(e, R(), z(), V()), e.option("-n, --name <name>", "Name for the duplicate"), e.addOption(new C("--auto-rename", "Auto-rename on collision (default: true)").default(!0)), e.option("--no-auto-rename", "Fail on name collision instead of auto-renaming"), e.action(async (e, n) => {
108
- let { pl: i, projectListRid: a } = await F(n);
105
+ function H() {
106
+ let e = new y("duplicate").description("Duplicate a project within the same user. Auto-renames on collision by default.");
107
+ return e.argument("<project>", "Project ID or label"), P(e, I(), L(), z()), e.option("-n, --name <name>", "Name for the duplicate"), e.addOption(new x("--auto-rename", "Auto-rename on collision (default: true)").default(!0)), e.option("--no-auto-rename", "Fail on name collision instead of auto-renaming"), e.action(async (e, n) => {
108
+ let { pl: i, projectListRid: a } = await N(n);
109
109
  try {
110
- let { rid: o } = await b(i, a, e), s = j(), l = await i.withWriteTx("duplicateProject", async (e) => {
111
- let t = await e.getKValueString(o, M), i = JSON.parse(t).label, c = await _(e, a), l;
110
+ let { rid: o } = await v(i, a, e), s = O(), l = await i.withWriteTx("duplicateProject", async (e) => {
111
+ let t = await e.getKValueString(o, k), i = JSON.parse(t).label, c = await _(e, a), l;
112
112
  if (n.name) {
113
113
  if (!n.autoRename && c.includes(n.name)) throw Error(`Project name "${n.name}" already exists.`);
114
114
  l = c.includes(n.name) ? f(n.name, c) : n.name;
@@ -117,14 +117,14 @@ function W() {
117
117
  e.createField(w(a, s), "Dynamic", u), await e.commit();
118
118
  let d = await u.globalId;
119
119
  return {
120
- id: O(d),
120
+ id: D(d),
121
121
  rid: d,
122
122
  label: l
123
123
  };
124
124
  });
125
125
  n.format === "json" ? c({
126
126
  id: l.id,
127
- rid: O(l.rid),
127
+ rid: D(l.rid),
128
128
  label: l.label
129
129
  }) : t(`Duplicated project as "${l.label}" (id: ${l.id})`);
130
130
  } finally {
@@ -133,15 +133,15 @@ function W() {
133
133
  }), e;
134
134
  }
135
135
  // src/cmd/project/rename.ts
136
- function G() {
137
- let e = new x("rename").description("Rename a project.");
138
- return e.argument("<project>", "Project ID or label"), I(e, R(), z(), V()), e.addOption(new C("-n, --name <name>", "New name for the project").makeOptionMandatory()), e.action(async (e, n) => {
139
- let { pl: r, projectListRid: i } = await F(n);
136
+ function U() {
137
+ let e = new y("rename").description("Rename a project.");
138
+ return e.argument("<project>", "Project ID or label"), P(e, I(), L(), z()), e.addOption(new x("-n, --name <name>", "New name for the project").makeOptionMandatory()), e.action(async (e, n) => {
139
+ let { pl: r, projectListRid: i } = await N(n);
140
140
  try {
141
- let { id: a, rid: o } = await b(r, i, e);
142
- await v(r, o, n.name), n.format === "json" ? c({
141
+ let { id: a, rid: o } = await v(r, i, e);
142
+ await ee(r, o, n.name), n.format === "json" ? c({
143
143
  id: a,
144
- rid: O(o),
144
+ rid: D(o),
145
145
  label: n.name
146
146
  }) : t(`Renamed project to "${n.name}"`);
147
147
  } finally {
@@ -150,14 +150,14 @@ function G() {
150
150
  }), e;
151
151
  }
152
152
  // src/cmd/project/delete.ts
153
- function K() {
154
- let e = new x("delete").description("Delete a project. This permanently destroys all project data.");
155
- return e.argument("<project>", "Project ID or label"), I(e, R(), z(), V()), e.option("--force", "Skip confirmation", !1), e.action(async (e, n) => {
156
- let { pl: r, projectListRid: a } = await F(n);
153
+ function W() {
154
+ let e = new y("delete").description("Delete a project. This permanently destroys all project data.");
155
+ return e.argument("<project>", "Project ID or label"), P(e, I(), L(), z()), e.option("--force", "Skip confirmation", !1), e.action(async (e, n) => {
156
+ let { pl: r, projectListRid: a } = await N(n);
157
157
  try {
158
- let { id: o, rid: s, fieldName: l } = await b(r, a, e), u = await i(r, o, s);
158
+ let { id: o, rid: s, fieldName: l } = await v(r, a, e), u = await i(r, o, s);
159
159
  if (!n.force) {
160
- let e = N({
160
+ let e = j({
161
161
  input: process.stdin,
162
162
  output: process.stderr
163
163
  });
@@ -183,13 +183,13 @@ function K() {
183
183
  }), e;
184
184
  }
185
185
  // src/cmd/admin/copy-project.ts
186
- function q() {
187
- let e = new x("copy-project").description("Copy a project from one user to another. Requires admin/controller credentials.");
188
- return I(e, R(), B()), e.addOption(new C("--source-user <user>", "Username of the source project owner").makeOptionMandatory()), e.addOption(new C("--source-project <project>", "Source project ID or label").makeOptionMandatory()), e.option("--target-user <user>", "Username of the target user (defaults to source-user for same-user copy)"), e.option("-n, --name <name>", "Name for the copied project"), e.addOption(new C("--auto-rename", "Auto-rename on collision (default: true)").default(!0)), e.option("--no-auto-rename", "Fail on name collision instead of auto-renaming"), e.action(async (e) => {
189
- let n = await P(e);
186
+ function G() {
187
+ let e = new y("copy-project").description("Copy a project from one user to another. Requires admin/controller credentials.");
188
+ return P(e, I(), R()), e.addOption(new x("--source-user <user>", "Username of the source project owner").makeOptionMandatory()), e.addOption(new x("--source-project <project>", "Source project ID or label").makeOptionMandatory()), e.option("--target-user <user>", "Username of the target user (defaults to source-user for same-user copy)"), e.option("-n, --name <name>", "Name for the copied project"), e.addOption(new x("--auto-rename", "Auto-rename on collision (default: true)").default(!0)), e.option("--no-auto-rename", "Fail on name collision instead of auto-renaming"), e.action(async (e) => {
189
+ let n = await M(e);
190
190
  try {
191
- let i = e.targetUser ?? e.sourceUser, a = await o(n, e.sourceUser), { rid: s } = await b(n, a.projectListRid, e.sourceProject), l = i === e.sourceUser ? a : await o(n, i), u = j(), d = await n.withWriteTx("adminCopyProject", async (t) => {
192
- let n = await t.getKValueString(s, M), i = JSON.parse(n).label, a = await _(t, l.projectListRid), o = e.name ?? i;
191
+ let i = e.targetUser ?? e.sourceUser, a = await o(n, e.sourceUser), { rid: s } = await v(n, a.projectListRid, e.sourceProject), l = i === e.sourceUser ? a : await o(n, i), u = O(), d = await n.withWriteTx("adminCopyProject", async (t) => {
192
+ let n = await t.getKValueString(s, k), i = JSON.parse(n).label, a = await _(t, l.projectListRid), o = e.name ?? i;
193
193
  if (a.includes(o)) {
194
194
  if (!e.autoRename) throw Error(`Project name "${o}" already exists for target user.`);
195
195
  o = f(e.name ?? i, a);
@@ -198,32 +198,32 @@ function q() {
198
198
  t.createField(w(l.projectListRid, u), "Dynamic", c), await t.commit();
199
199
  let d = await c.globalId;
200
200
  return {
201
- id: O(d),
201
+ id: D(d),
202
202
  rid: d,
203
203
  label: o
204
204
  };
205
205
  });
206
206
  e.format === "json" ? c({
207
207
  id: d.id,
208
- rid: O(d.rid),
208
+ rid: D(d.rid),
209
209
  label: d.label,
210
210
  sourceUser: e.sourceUser,
211
211
  targetUser: i
212
- }) : t(`Copied project from ${e.sourceUser} to ${i} as "${d.label}" (id: ${d.id}, rid: ${O(d.rid)})`);
212
+ }) : t(`Copied project from ${e.sourceUser} to ${i} as "${d.label}" (id: ${d.id}, rid: ${D(d.rid)})`);
213
213
  } finally {
214
214
  await n.close();
215
215
  }
216
216
  }), e;
217
217
  }
218
218
  // src/cmd/admin/user-list.ts
219
- function J() {
220
- let e = new x("user-list").description("List all known users' logins from a live server. Requires admin/controller credentials.");
221
- return I(e, R("csv", [
219
+ function le() {
220
+ let e = new y("user-list").description("List all known users' logins from a live server. Requires admin/controller credentials.");
221
+ return P(e, I("csv", [
222
222
  "text",
223
223
  "json",
224
224
  "csv"
225
- ]), B()), e.action(async (e) => {
226
- let n = await P(e);
225
+ ]), R()), e.action(async (e) => {
226
+ let n = await M(e);
227
227
  try {
228
228
  let r = (await n.listUsers()).map((e) => e.login).sort();
229
229
  e.format === "json" ? c(r) : e.format === "text" ? t(r.join("\n")) : m(["login"], r.map((e) => [e]));
@@ -233,17 +233,17 @@ function J() {
233
233
  }), e;
234
234
  }
235
235
  // src/cmd/admin/delete-user.ts
236
- function ae() {
237
- let n = new x("delete-user").description("Delete a user account. Optionally re-homes the user's projects to another user first. Requires admin/controller credentials.");
238
- return n.argument("<user>", "Username of the account to delete"), I(n, R(), B()), n.addOption(new C("--move-projects-to <user>", "Re-home the deleted user's projects to this user before deleting the account")), n.addOption(new C("--delete-projects", "Delete the user's projects along with the account, losing their data")), n.option("--force", "Skip confirmation", !1), n.action(async (n, r) => {
236
+ function ue() {
237
+ let n = new y("delete-user").description("Delete a user account. Optionally re-homes the user's projects to another user first. Requires admin/controller credentials.");
238
+ return n.argument("<user>", "Username of the account to delete"), P(n, I(), R()), n.addOption(new x("--move-projects-to <user>", "Re-home the deleted user's projects to this user before deleting the account")), n.addOption(new x("--delete-projects", "Delete the user's projects along with the account, losing their data")), n.option("--force", "Skip confirmation", !1), n.action(async (n, r) => {
239
239
  if (r.moveProjectsTo && r.deleteProjects) throw Error("--move-projects-to and --delete-projects are mutually exclusive");
240
240
  if (r.moveProjectsTo === n) throw Error("--move-projects-to must name a different user than the one being deleted");
241
241
  if (r.adminUser === n) throw Error(`Refusing to delete "${n}" — it is the account these credentials authenticate as.`);
242
- let i = await P(r);
242
+ let i = await M(r);
243
243
  try {
244
244
  let a = await e(i, n), o = a.projectListRid === void 0 ? [] : await p(i, a.projectListRid);
245
245
  if (o.length > 0 && !r.moveProjectsTo && !r.deleteProjects) throw Error(`User "${n}" owns ${o.length} project(s). Pass --move-projects-to <user> to re-home them, or --delete-projects to delete them with the account.`);
246
- if (!await se(n, o, r)) {
246
+ if (!await fe(n, o, r)) {
247
247
  t("Aborted.");
248
248
  return;
249
249
  }
@@ -253,7 +253,7 @@ function ae() {
253
253
  u = await s(i, a.projectListRid, n);
254
254
  }
255
255
  let d = a.projectListRid === void 0 ? [] : await p(i, a.projectListRid);
256
- oe(n, r, o, d);
256
+ de(n, r, o, d);
257
257
  let f = await i.deleteUser(n);
258
258
  r.format === "json" ? c({
259
259
  deleted: !0,
@@ -265,13 +265,13 @@ function ae() {
265
265
  userRootDeleted: f.userRootDeleted,
266
266
  revokedGrants: f.revokedGrants,
267
267
  removedIdentityIndexEntries: f.removedIdentityIndexEntries
268
- }) : t(ce(n, r.moveProjectsTo, u, d));
268
+ }) : t(pe(n, r.moveProjectsTo, u, d));
269
269
  } finally {
270
270
  await i.close();
271
271
  }
272
272
  }), n;
273
273
  }
274
- function oe(e, t, n, r) {
274
+ function de(e, t, n, r) {
275
275
  if (t.moveProjectsTo) {
276
276
  if (r.length === 0) return;
277
277
  throw Error(`User "${e}" still owns ${r.length} project(s) after the move: ${r.map((e) => e.label).join(", ")}. The account was NOT deleted — the projects were attached while the move ran. Re-run the command to move them too.`);
@@ -279,11 +279,11 @@ function oe(e, t, n, r) {
279
279
  let i = new Set(n.map((e) => e.id)), a = r.filter((e) => !i.has(e.id));
280
280
  if (a.length !== 0) throw Error(`User "${e}" gained ${a.length} project(s) since the list you confirmed: ${a.map((e) => e.label).join(", ")}. The account was NOT deleted — deleting it now would destroy them unreviewed. Re-run the command to see the current list.`);
281
281
  }
282
- async function se(e, t, n) {
282
+ async function fe(e, t, n) {
283
283
  if (n.force) return !0;
284
284
  let r = n.moveProjectsTo ? `${t.length} project(s) will move to "${n.moveProjectsTo}"` : t.length > 0 ? `${t.length} project(s) will be PERMANENTLY DELETED` : "the account owns no projects";
285
285
  process.stderr.write(`Delete user "${e}"? ${r}.\n`), t.length > 0 && process.stderr.write(t.map((e) => ` - ${e.label}`).join("\n") + "\n");
286
- let i = N({
286
+ let i = j({
287
287
  input: process.stdin,
288
288
  output: process.stderr
289
289
  });
@@ -295,7 +295,7 @@ async function se(e, t, n) {
295
295
  i.close();
296
296
  }
297
297
  }
298
- function ce(e, t, n, r) {
298
+ function pe(e, t, n, r) {
299
299
  let i = [];
300
300
  return t ? n.length > 0 ? (i.push(`Moved ${n.length} project(s) from ${e} to ${t}:`), i.push(d([
301
301
  "id",
@@ -308,33 +308,33 @@ function ce(e, t, n, r) {
308
308
  ])))) : i.push(`User ${e} had no projects to move.`) : r.length > 0 && (i.push(`Deleted ${r.length} project(s) belonging to ${e}:`), i.push(r.map((e) => ` - ${e.label}`).join("\n"))), i.push(`Deleted user "${e}".`), i.join("\n");
309
309
  }
310
310
  // src/cmd/admin/instance-stats.ts
311
- function le() {
312
- let e = new x("instance-stats").description("Show the instance statistics as JSON.");
313
- return I(e, R(), B()), e.action(async (e) => {
314
- let t = await P(e);
311
+ function me() {
312
+ let e = new y("instance-stats").description("Show the instance statistics as JSON.");
313
+ return P(e, I(), R()), e.action(async (e) => {
314
+ let t = await M(e);
315
315
  try {
316
- let [e] = await t.listSharedResourcesByType(ne);
316
+ let [e] = await t.listSharedResourcesByType(se);
317
317
  if (e === void 0) throw Error("The instance has no instance statistics.");
318
318
  let n = await t.withReadTx("instanceStats", (t) => t.listKeyValuesString(e));
319
- c(re(n));
319
+ c(A(n));
320
320
  } finally {
321
321
  await t.close();
322
322
  }
323
323
  }), e;
324
324
  }
325
325
  // src/resource_id.ts
326
- function Y(e) {
326
+ function K(e) {
327
327
  let t = e.trim();
328
- if (t.includes("|")) return ee(t);
329
- let n = D(t);
330
- if (n === void 0 && /^\d+$/.test(t) && (n = BigInt(t)), n === void 0 || n === 0n || T(n)) throw Error(`not a global resource ID: ${e}`);
331
- return te(n);
328
+ if (t.includes("|")) return C(t);
329
+ let n = ie(t);
330
+ if (n === void 0 && /^\d+$/.test(t) && (n = BigInt(t)), n === void 0 || n === 0n || re(n)) throw Error(`not a global resource ID: ${e}`);
331
+ return ne(n);
332
332
  }
333
333
  // src/cmd/maintenance/list-resources.ts
334
- function X() {
335
- let e = new x("list-resources").description("List resources of one type as JSON lines, in ascending order of resource ID. Resource data and key-value values are printed as JSON when they are valid JSON, as text when they are valid UTF-8, and as {\"base64\": ...} in other cases. Requires admin/controller credentials.");
336
- return I(e, L(), B()), e.addOption(new C("--type <name:version>", "Resource type to list (e.g. 'Blob/work:1')").argParser(fe).makeOptionMandatory()), e.addOption(new C("--limit <n>", "Maximum number of resources to list. 0 lists all resources").argParser(pe).default(0)), e.addOption(new C("--after <resource-id>", "List only resources with IDs greater than this ID. To get the next page, give the ID of the last resource of the previous page").argParser(Y)), e.option("--load-fields", "Load the fields and the error of each resource ('fields' and 'error' keys)", !1), e.option("--load-kv", "Load the key-value entries of each resource ('kv' key)", !1), e.action(async (e) => {
337
- let t = await P(e);
334
+ function he() {
335
+ let e = new y("list-resources").description("List resources of one type as JSON lines, in ascending order of resource ID. Resource data and key-value values are printed as JSON when they are valid JSON, as text when they are valid UTF-8, and as {\"base64\": ...} in other cases. Requires admin/controller credentials.");
336
+ return P(e, F(), R()), e.addOption(new x("--type <name:version>", "Resource type to list (e.g. 'Blob/work:1')").argParser(ve).makeOptionMandatory()), e.addOption(new x("--limit <n>", "Maximum number of resources to list. 0 lists all resources").argParser(ye).default(0)), e.addOption(new x("--after <resource-id>", "List only resources with IDs greater than this ID. To get the next page, give the ID of the last resource of the previous page").argParser(K)), e.option("--load-fields", "Load the fields and the error of each resource ('fields' and 'error' keys)", !1), e.option("--load-kv", "Load the key-value entries of each resource ('kv' key)", !1), e.action(async (e) => {
337
+ let t = await M(e);
338
338
  try {
339
339
  let n = await t.withReadTx("listResources", async (t) => {
340
340
  let n = await t.listResourcesByType(e.type, {
@@ -348,46 +348,46 @@ function X() {
348
348
  })));
349
349
  });
350
350
  for (let { resource: t, kv: r } of n) {
351
- let n = JSON.stringify(ue(t, e.loadFields, r)) + "\n";
352
- process.stdout.write(n) || await ie(process.stdout, "drain");
351
+ let n = JSON.stringify(ge(t, e.loadFields, r)) + "\n";
352
+ process.stdout.write(n) || await ce(process.stdout, "drain");
353
353
  }
354
354
  } finally {
355
355
  await t.close();
356
356
  }
357
357
  }), e;
358
358
  }
359
- function ue(e, t, n) {
359
+ function ge(e, t, n) {
360
360
  return {
361
- id: O(e.id),
362
- type: A(e.type),
361
+ id: D(e.id),
362
+ type: oe(e.type),
363
363
  kind: e.kind,
364
- originalId: Z(e.originalResourceId),
364
+ originalId: q(e.originalResourceId),
365
365
  inputsLocked: e.inputsLocked,
366
366
  outputsLocked: e.outputsLocked,
367
367
  ready: e.resourceReady,
368
368
  final: e.final,
369
- data: e.data === void 0 || e.data.length === 0 ? null : Q(e.data),
369
+ data: e.data === void 0 || e.data.length === 0 ? null : J(e.data),
370
370
  ...t ? {
371
- error: Z(e.error),
372
- fields: e.fields.map(de)
371
+ error: q(e.error),
372
+ fields: e.fields.map(_e)
373
373
  } : {},
374
- ...n === void 0 ? {} : { kv: Object.fromEntries(n.map((e) => [e.key, Q(e.value)])) }
374
+ ...n === void 0 ? {} : { kv: Object.fromEntries(n.map((e) => [e.key, J(e.value)])) }
375
375
  };
376
376
  }
377
- function de(e) {
377
+ function _e(e) {
378
378
  return {
379
379
  name: e.name,
380
380
  type: e.type,
381
381
  status: e.status,
382
- value: Z(e.value),
383
- error: Z(e.error),
382
+ value: q(e.value),
383
+ error: q(e.error),
384
384
  valueIsFinal: e.valueIsFinal
385
385
  };
386
386
  }
387
- function Z(e) {
388
- return E(e) ? O(e) : null;
387
+ function q(e) {
388
+ return T(e) ? D(e) : null;
389
389
  }
390
- function Q(e) {
390
+ function J(e) {
391
391
  let t;
392
392
  try {
393
393
  t = new TextDecoder("utf-8", { fatal: !0 }).decode(e);
@@ -400,28 +400,28 @@ function Q(e) {
400
400
  return t;
401
401
  }
402
402
  }
403
- function fe(e) {
403
+ function ve(e) {
404
404
  let t = e.lastIndexOf(":");
405
- if (t <= 0 || t === e.length - 1) throw new S(`expected <name>:<version>, e.g. 'Blob/work:1': ${e}`);
406
- return k(e.slice(0, t), e.slice(t + 1));
405
+ if (t <= 0 || t === e.length - 1) throw new b(`expected <name>:<version>, e.g. 'Blob/work:1': ${e}`);
406
+ return ae(e.slice(0, t), e.slice(t + 1));
407
407
  }
408
- function pe(e) {
408
+ function ye(e) {
409
409
  let t = Number(e);
410
- if (!Number.isInteger(t) || t < 0) throw new S(`not a non-negative integer: ${e}`);
410
+ if (!Number.isInteger(t) || t < 0) throw new b(`not a non-negative integer: ${e}`);
411
411
  return t;
412
412
  }
413
413
  // src/cmd/maintenance/set-resource-error.ts
414
- var me = "Manual error set by administrator to trigger blocks re-run. Run block once again to get rid of it.";
415
- function he() {
416
- let e = new x("set-resource-error").description("Put an error on one or more resources in a single transaction. Resources that already have an error are skipped. Requires admin/controller credentials.");
417
- return e.argument("<resource-id...>", "Resource IDs: as printed by the server (NG:0x1A2B), as decimal numbers, or as signed IDs (<decimal ID>|<signature hex>)"), I(e, L(), B()), e.addOption(new C("-m, --error-message <message>", "Error message to put on the resources").default(me)), e.option("--skip-missing", "Skip resources that do not exist instead of failing the whole transaction", !1), e.action(async (e, n) => {
418
- let r = e.map(Y), i = await P(n);
414
+ var be = "Manual error set by administrator to trigger blocks re-run. Run block once again to get rid of it.";
415
+ function xe() {
416
+ let e = new y("set-resource-error").description("Put an error on one or more resources in a single transaction. Resources that already have an error are skipped. Requires admin/controller credentials.");
417
+ return e.argument("<resource-id...>", "Resource IDs: as printed by the server (NG:0x1A2B), as decimal numbers, or as signed IDs (<decimal ID>|<signature hex>)"), P(e, F(), R()), e.addOption(new x("-m, --error-message <message>", "Error message to put on the resources").default(be)), e.option("--skip-missing", "Skip resources that do not exist instead of failing the whole transaction", !1), e.action(async (e, n) => {
418
+ let r = e.map(K), i = await M(n);
419
419
  try {
420
420
  let e = await i.withWriteTx("setResourceError", async (e) => {
421
421
  let t = await Promise.all(r.map(async (t) => ({
422
422
  id: t,
423
423
  data: n.skipMissing ? await e.getResourceDataIfExists(t, !0) : await e.getResourceData(t, !0, !0)
424
- }))), i = t.filter((e) => e.data === void 0).map((e) => e.id), a = t.flatMap((e) => e.data === void 0 ? [] : [e.data]), o = a.filter((e) => !E(e.error)), s = a.filter((e) => E(e.error));
424
+ }))), i = t.filter((e) => e.data === void 0).map((e) => e.id), a = t.flatMap((e) => e.data === void 0 ? [] : [e.data]), o = a.filter((e) => !T(e.error)), s = a.filter((e) => T(e.error));
425
425
  if (o.length > 0) {
426
426
  let t = e.createError(n.errorMessage);
427
427
  for (let n of o) e.setResourceError(n.id, t);
@@ -433,28 +433,111 @@ function he() {
433
433
  missing: i
434
434
  };
435
435
  });
436
- for (let n of e.missing) t(`skipped ${O(n)}: resource does not exist`);
437
- for (let n of e.skipped) t(`skipped ${O(n.id)}: resource already has an error`);
438
- for (let n of e.targets) t(`error set ${O(n.id)}`);
436
+ for (let n of e.missing) t(`skipped ${D(n)}: resource does not exist`);
437
+ for (let n of e.skipped) t(`skipped ${D(n.id)}: resource already has an error`);
438
+ for (let n of e.targets) t(`error set ${D(n.id)}`);
439
439
  } finally {
440
440
  await i.close();
441
441
  }
442
442
  }), e;
443
443
  }
444
+ // src/cmd/maintenance/controller/fixup_level.ts
445
+ var Y = "ctl/ctlsdk/resourcesFixupLevel", X = 4;
446
+ async function Z(e, t) {
447
+ let n = await e.getControllerKValueIfExists(t, Y);
448
+ return n === void 0 ? "not set" : n.length === X ? String(Buffer.from(n).readUInt32BE(0)) : `invalid (${n.length} bytes)`;
449
+ }
450
+ function Se(e, t) {
451
+ e.setControllerKValue(t, Y, new Uint8Array(X));
452
+ }
453
+ // src/cmd/maintenance/controller/list.ts
454
+ function Ce() {
455
+ let e = new y("list").description("List the controllers registered in the backend, with their IDs and resources fixup levels. Requires admin/controller credentials.");
456
+ return P(e, I("text", [
457
+ "text",
458
+ "json",
459
+ "csv"
460
+ ]), R()), e.action(async (e) => {
461
+ let n = await M(e);
462
+ try {
463
+ let r = await n.withReadTx("listControllers", async (e) => {
464
+ let t = await E(e);
465
+ return await Promise.all(t.map(async (t) => ({
466
+ id: D(t.id),
467
+ type: t.type,
468
+ fixupLevel: await Z(e, t.type)
469
+ })));
470
+ }), i = [
471
+ "id",
472
+ "type",
473
+ "fixup level"
474
+ ], a = r.map((e) => [
475
+ e.id,
476
+ e.type,
477
+ e.fixupLevel
478
+ ]);
479
+ e.format === "json" ? c(r) : e.format === "csv" ? m(i, a) : t(d(i, a));
480
+ } finally {
481
+ await n.close();
482
+ }
483
+ }), e;
484
+ }
485
+ // src/cmd/maintenance/controller/rerun-fixups.ts
486
+ function Q(e) {
487
+ return (t, n) => [...n ?? [], e(t)];
488
+ }
489
+ function we() {
490
+ let e = new y("rerun-fixups").description("Set the resources fixup level of the selected controllers to 0 in a single transaction. On its next start, each controller applies all its one-time resources fixups again. Use this after a rollback to a backend version without resources fixups. Select controllers with --controller-name and --controller-id (see 'maintenance controller list'). Requires admin/controller credentials.");
491
+ return P(e, F(), R()), e.addOption(new x("--controller-name <type>", "Controller type, as the controller registers it (for example \"File/Manager\"). Repeat the option to select more controllers").argParser(Q((e) => e))), e.addOption(new x("--controller-id <resource-id>", "Controller ID, as 'maintenance controller list' prints it. Repeat the option to select more controllers").argParser(Q(K))), e.action(async (e) => {
492
+ let n = e.controllerName ?? [], r = e.controllerId ?? [];
493
+ if (n.length === 0 && r.length === 0) throw Error("select at least one controller with --controller-name or --controller-id");
494
+ let i = await M(e);
495
+ try {
496
+ let e = await i.withWriteTx("rerunControllerFixups", async (e) => {
497
+ let t = await Te(e, n, r), i = await Promise.all(t.map(async (t) => ({
498
+ controller: t,
499
+ level: await Z(e, t.type)
500
+ })));
501
+ for (let n of t) Se(e, n.type);
502
+ return await e.commit(), i;
503
+ });
504
+ for (let { controller: n, level: r } of e) t(`${n.type} (${D(n.id)}): resources fixup level ${r} -> 0`);
505
+ t("Restart the backend to apply the resources fixups.");
506
+ } finally {
507
+ await i.close();
508
+ }
509
+ }), e;
510
+ }
511
+ async function Te(e, t, n) {
512
+ let r = await E(e), i = /* @__PURE__ */ new Map();
513
+ for (let e of t) {
514
+ let t = r.find((t) => t.type === e);
515
+ if (t === void 0) throw Error(`controller "${e}" is not registered`);
516
+ i.set(t.type, t);
517
+ }
518
+ for (let e of n) {
519
+ let t = S(e), n = r.find((e) => S(e.id) === t);
520
+ if (n === void 0) throw Error(`no registered controller has ID ${D(e)}`);
521
+ i.set(n.type, n);
522
+ }
523
+ return [...i.values()];
524
+ }
444
525
  // src/cli.ts
445
526
  function $() {
446
- let e = new x();
527
+ let e = new y();
447
528
  e.name("pl-cli").description("Platforma command-line client");
448
- let t = new x("project").description("Manage projects");
449
- t.addCommand(H()), t.addCommand(U()), t.addCommand(W()), t.addCommand(G()), t.addCommand(K()), e.addCommand(t);
450
- let n = new x("admin").description("Admin operations (requires controller credentials)");
451
- n.addCommand(q()), n.addCommand(J()), n.addCommand(ae()), n.addCommand(le()), e.addCommand(n);
452
- let r = new x("maintenance").description("Low-level server state repair (requires admin/controller credentials)");
453
- return r.addCommand(X()), r.addCommand(he()), e.addCommand(r), e;
454
- }
455
- async function ge(e = process.argv) {
529
+ let t = new y("project").description("Manage projects");
530
+ t.addCommand(B()), t.addCommand(V()), t.addCommand(H()), t.addCommand(U()), t.addCommand(W()), e.addCommand(t);
531
+ let n = new y("admin").description("Admin operations (requires controller credentials)");
532
+ n.addCommand(G()), n.addCommand(le()), n.addCommand(ue()), n.addCommand(me()), e.addCommand(n);
533
+ let r = new y("maintenance").description("Low-level server state repair (requires admin/controller credentials)");
534
+ r.addCommand(he()), r.addCommand(xe());
535
+ let i = new y("controller").description("Inspect registered controllers and their resources fixups");
536
+ return i.addCommand(Ce()), i.addCommand(we()), r.addCommand(i), e.addCommand(r), e;
537
+ }
538
+ async function Ee(e = process.argv) {
456
539
  await $().parseAsync(e);
457
540
  }
458
- export { $ as buildProgram, ge as run };
541
+ export { $ as buildProgram, Ee as run };
459
542
 
460
543
  //# sourceMappingURL=cli.js.map
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":["openUserRoot","outputText","createAdminPlConnection","duplicateProject","getProjectInfo","getProjectListRid","navigateToUserRoot","moveProjects","outputJson","listProjects","formatTable","deduplicateName","outputCsv","deleteProject","formatDate","getExistingLabelsInTx","createPlConnection","resolveProject","connectClient","flags","connect","hasAdminUser","hasAdminPassword","hasTarget","pl","projectListRid","addOptions","optionGroups","group","opt","cmd","AddressOptions","Option","GlobalOptions","allowedFormats","formatDefault","UserAuthOptions","AdminAuthOptions","AdminTargetOptions","projectListCommand","Command","projects","p","resourceIdToString","projectInfoCommand","project","info","id","rid","bid","projectDuplicateCommand","sourceRid","newId","randomUUID","result","sourceMetaStr","tx","ProjectMetaKey","sourceLabel","existingLabels","newLabel","newPrj","field","projectResourceId","projectRenameCommand","renameProject","projectDeleteCommand","rl","createInterface","resolve","fieldName","adminCopyProjectCommand","targetUser","source","target","prjResourceId","adminUserListCommand","logins","u","l","adminDeleteUserCommand","user","listProjectIdentities","confirmDeletion","moved","targetList","ensureUserProjectList","remaining","report","renderResult","assertProjectsAccountedFor","approvedIds","approved","unapproved","fate","lines","movedTo","adminInstanceStatsCommand","context","InstanceStatsContextTypeName","kvs","parseInstanceStats","parseResourceId","str","raw","asSignedResourceId","resourceIdFromString","isLocalResourceId","createSignedResourceId","maintenanceListResourcesCommand","parseResourceTypeArg","parseNonNegativeInt","resources","list","resource","line","toJson","kv","once","r","resourceTypeToString","optionalIdToString","decodeBytes","withFields","fieldToJson","f","isNotNullSignedResourceId","text","bytes","sep","value","InvalidArgumentError","resourceType","n","DefaultErrorMessage","maintenanceSetResourceErrorCommand","ids","rawIds","found","missing","targets","skipped","error","buildProgram","program","admin","maintenance","run","argv"],"sources":["../src/base_command.ts","../src/cmd-opts.ts","../src/cmd/project/list.ts","../src/cmd/project/info.ts","../src/cmd/project/duplicate.ts","../src/cmd/project/rename.ts","../src/cmd/project/delete.ts","../src/cmd/admin/copy-project.ts","../src/cmd/admin/user-list.ts","../src/cmd/admin/delete-user.ts","../src/cmd/admin/instance-stats.ts","../src/resource_id.ts","../src/cmd/maintenance/list-resources.ts","../src/cmd/maintenance/set-resource-error.ts","../src/cli.ts"],"sourcesContent":["import type { PlClient, SignedResourceId } from \"@milaboratories/pl-client\";\nimport { createPlConnection, createAdminPlConnection } from \"./connection\";\nimport { getProjectListRid, navigateToUserRoot } from \"./project_ops\";\n\n/**\n * Low-level: get an authenticated PlClient without resolving a project list.\n * Use this for commands that navigate to multiple users (e.g. admin copy-project).\n *\n * Callers own the returned client and must `await pl.close()` when done.\n */\nexport async function connectClient(flags: {\n address: string;\n user?: string;\n password?: string;\n adminUser?: string;\n adminPassword?: string;\n}): Promise<PlClient> {\n if (flags.adminUser && flags.adminPassword) {\n return createAdminPlConnection({\n address: flags.address,\n adminUser: flags.adminUser,\n adminPassword: flags.adminPassword,\n });\n }\n return createPlConnection({\n address: flags.address,\n user: flags.user,\n password: flags.password,\n });\n}\n\n/**\n * Connect and resolve the project list for a single user.\n * In admin mode (--admin-user + --admin-password + --target-user), operates on the target user's data.\n * In user mode, operates on the authenticated user's own data.\n *\n * Callers own the returned client and must `await pl.close()` when done.\n */\nexport async function connect(flags: {\n address: string;\n user?: string;\n password?: string;\n adminUser?: string;\n adminPassword?: string;\n targetUser?: string;\n}): Promise<{ pl: PlClient; projectListRid: SignedResourceId }> {\n const hasAdminUser = !!flags.adminUser;\n const hasAdminPassword = !!flags.adminPassword;\n const hasTarget = !!flags.targetUser;\n\n // Validate flag combinations\n if (hasTarget && !(hasAdminUser && hasAdminPassword)) {\n throw new Error(\"--target-user requires --admin-user and --admin-password\");\n }\n if ((hasAdminUser || hasAdminPassword) && !hasTarget) {\n throw new Error(\"--admin-user/--admin-password require --target-user for project commands\");\n }\n\n const pl = await connectClient(flags);\n\n let projectListRid: SignedResourceId;\n if (hasTarget) {\n const nav = await navigateToUserRoot(pl, flags.targetUser!);\n projectListRid = nav.projectListRid;\n } else {\n projectListRid = await getProjectListRid(pl);\n }\n\n return { pl, projectListRid };\n}\n","import { Command, Option } from \"commander\";\nimport type { OutputFormat } from \"./output\";\n\n/** Add one or more groups of options to a command, preserving group order. */\nexport function addOptions(cmd: Command, ...optionGroups: Option[][]): Command {\n for (const group of optionGroups) {\n for (const opt of group) cmd.addOption(opt);\n }\n return cmd;\n}\n\n/** Server address only (for commands with a fixed output format). */\nexport const AddressOptions = (): Option[] => [\n new Option(\"-a, --address <url>\", \"Platforma server address\")\n .env(\"PL_ADDRESS\")\n .makeOptionMandatory(),\n];\n\nexport const GlobalOptions = (\n formatDefault: OutputFormat = \"text\",\n allowedFormats: OutputFormat[] = [\"text\", \"json\"],\n): Option[] => [\n ...AddressOptions(),\n new Option(\"-f, --format <format>\", \"Output format\")\n .choices(allowedFormats)\n .default(formatDefault),\n];\n\nexport const UserAuthOptions = (): Option[] => [\n new Option(\"-u, --user <user>\", \"Username for authentication\").env(\"PL_USER\"),\n new Option(\"-p, --password <password>\", \"Password for authentication\").env(\"PL_PASSWORD\"),\n];\n\n/** Admin credentials only (for purely admin commands like copy-project). */\nexport const AdminAuthOptions = (): Option[] => [\n new Option(\"--admin-user <user>\", \"Admin/controller username\")\n .env(\"PL_ADMIN_USER\")\n .makeOptionMandatory(),\n new Option(\"--admin-password <password>\", \"Admin/controller password\")\n .env(\"PL_ADMIN_PASSWORD\")\n .makeOptionMandatory(),\n];\n\n/** Admin credentials + target user (for regular commands that can optionally operate on another user). */\nexport const AdminTargetOptions = (): Option[] => [\n new Option(\"--admin-user <user>\", \"Admin/controller username (enables admin mode)\").env(\n \"PL_ADMIN_USER\",\n ),\n new Option(\"--admin-password <password>\", \"Admin/controller password\").env(\"PL_ADMIN_PASSWORD\"),\n new Option(\n \"--target-user <user>\",\n \"Operate on this user's data (requires admin credentials)\",\n ).env(\"PL_TARGET_USER\"),\n];\n","import { Command } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { listProjects } from \"../../project_ops\";\nimport { formatTable, formatDate, outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectListCommand(): Command {\n const cmd = new Command(\"list\").description(\"List all projects for the authenticated user.\");\n\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n\n cmd.action(async (flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const projects = await listProjects(pl, projectListRid);\n\n if (flags.format === \"json\") {\n outputJson(\n projects.map((p) => ({\n id: p.id,\n rid: resourceIdToString(p.rid),\n label: p.label,\n created: p.created.toISOString(),\n lastModified: p.lastModified.toISOString(),\n })),\n );\n } else {\n if (projects.length === 0) {\n outputText(\"No projects found.\");\n return;\n }\n\n outputText(\n formatTable(\n [\"ID\", \"RID\", \"LABEL\", \"CREATED\", \"LAST MODIFIED\"],\n projects.map((p) => [\n p.id,\n resourceIdToString(p.rid),\n p.label,\n formatDate(p.created),\n formatDate(p.lastModified),\n ]),\n ),\n );\n outputText(`\\n${projects.length} project(s)`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, getProjectInfo } from \"../../project_ops\";\nimport { formatDate, outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectInfoCommand(): Command {\n const cmd = new Command(\"info\").description(\"Show detailed information about a project.\");\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid } = await resolveProject(pl, projectListRid, project);\n const info = await getProjectInfo(pl, id, rid);\n\n if (flags.format === \"json\") {\n outputJson({\n id: info.id,\n rid: resourceIdToString(info.rid),\n label: info.label,\n schemaVersion: info.schemaVersion,\n blockCount: info.blockCount,\n blockIds: info.blockIds,\n created: info.created.toISOString(),\n lastModified: info.lastModified.toISOString(),\n });\n } else {\n outputText(`Project: ${info.label}`);\n outputText(`ID: ${info.id}`);\n outputText(`RID: ${resourceIdToString(info.rid)}`);\n outputText(`Schema: ${info.schemaVersion ?? \"(unknown)\"}`);\n outputText(`Blocks: ${info.blockCount}`);\n if (info.blockIds.length > 0) {\n for (const bid of info.blockIds) {\n outputText(` - ${bid}`);\n }\n }\n outputText(`Created: ${formatDate(info.created)}`);\n outputText(`Last Modified: ${formatDate(info.lastModified)}`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { field, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { ProjectMetaKey } from \"@milaboratories/pl-middle-layer\";\nimport { randomUUID } from \"node:crypto\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport {\n resolveProject,\n deduplicateName,\n duplicateProject,\n getExistingLabelsInTx,\n} from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function projectDuplicateCommand(): Command {\n const cmd = new Command(\"duplicate\").description(\n \"Duplicate a project within the same user. Auto-renames on collision by default.\",\n );\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.option(\"-n, --name <name>\", \"Name for the duplicate\");\n cmd.addOption(\n new Option(\"--auto-rename\", \"Auto-rename on collision (default: true)\").default(true),\n );\n cmd.option(\"--no-auto-rename\", \"Fail on name collision instead of auto-renaming\");\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { rid: sourceRid } = await resolveProject(pl, projectListRid, project);\n\n const newId = randomUUID();\n\n const result = await pl.withWriteTx(\"duplicateProject\", async (tx) => {\n const sourceMetaStr = await tx.getKValueString(sourceRid, ProjectMetaKey);\n const sourceMeta = JSON.parse(sourceMetaStr);\n const sourceLabel: string = sourceMeta.label;\n\n const existingLabels = await getExistingLabelsInTx(tx, projectListRid);\n\n // Compute new label\n let newLabel: string;\n if (flags.name) {\n if (!flags.autoRename && existingLabels.includes(flags.name)) {\n throw new Error(`Project name \"${flags.name}\" already exists.`);\n }\n newLabel = existingLabels.includes(flags.name)\n ? deduplicateName(flags.name, existingLabels)\n : flags.name;\n } else {\n newLabel = deduplicateName(sourceLabel, existingLabels);\n }\n\n const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });\n tx.createField(field(projectListRid, newId), \"Dynamic\", newPrj);\n await tx.commit();\n\n const projectResourceId = await newPrj.globalId;\n const projectId = resourceIdToString(projectResourceId);\n return { id: projectId, rid: projectResourceId, label: newLabel };\n });\n\n if (flags.format === \"json\") {\n outputJson({ id: result.id, rid: resourceIdToString(result.rid), label: result.label });\n } else {\n outputText(`Duplicated project as \"${result.label}\" (id: ${result.id})`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, renameProject } from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectRenameCommand(): Command {\n const cmd = new Command(\"rename\").description(\"Rename a project.\");\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.addOption(new Option(\"-n, --name <name>\", \"New name for the project\").makeOptionMandatory());\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid } = await resolveProject(pl, projectListRid, project);\n\n await renameProject(pl, rid, flags.name);\n\n if (flags.format === \"json\") {\n outputJson({ id, rid: resourceIdToString(rid), label: flags.name });\n } else {\n outputText(`Renamed project to \"${flags.name}\"`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, deleteProject, getProjectInfo } from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function projectDeleteCommand(): Command {\n const cmd = new Command(\"delete\").description(\n \"Delete a project. This permanently destroys all project data.\",\n );\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.option(\"--force\", \"Skip confirmation\", false);\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid, fieldName } = await resolveProject(pl, projectListRid, project);\n\n const info = await getProjectInfo(pl, id, rid);\n\n if (!flags.force) {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await new Promise<string>((resolve) => {\n rl.question(\n `Delete project \"${info.label}\" (${info.blockCount} blocks)? [y/N] `,\n resolve,\n );\n });\n if (answer.toLowerCase() !== \"y\") {\n outputText(\"Aborted.\");\n return;\n }\n } finally {\n rl.close();\n }\n }\n\n await deleteProject(pl, projectListRid, fieldName);\n\n if (flags.format === \"json\") {\n outputJson({ deleted: true, id, label: info.label });\n } else {\n outputText(`Deleted project \"${info.label}\"`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { field, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { ProjectMetaKey } from \"@milaboratories/pl-middle-layer\";\nimport { randomUUID } from \"node:crypto\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport {\n resolveProject,\n deduplicateName,\n duplicateProject,\n getExistingLabelsInTx,\n navigateToUserRoot,\n} from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function adminCopyProjectCommand(): Command {\n const cmd = new Command(\"copy-project\").description(\n \"Copy a project from one user to another. Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\n \"--source-user <user>\",\n \"Username of the source project owner\",\n ).makeOptionMandatory(),\n );\n cmd.addOption(\n new Option(\"--source-project <project>\", \"Source project ID or label\").makeOptionMandatory(),\n );\n cmd.option(\n \"--target-user <user>\",\n \"Username of the target user (defaults to source-user for same-user copy)\",\n );\n cmd.option(\"-n, --name <name>\", \"Name for the copied project\");\n cmd.addOption(\n new Option(\"--auto-rename\", \"Auto-rename on collision (default: true)\").default(true),\n );\n cmd.option(\"--no-auto-rename\", \"Fail on name collision instead of auto-renaming\");\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const targetUser = flags.targetUser ?? flags.sourceUser;\n\n const source = await navigateToUserRoot(pl, flags.sourceUser);\n const { rid: sourceRid } = await resolveProject(\n pl,\n source.projectListRid,\n flags.sourceProject,\n );\n\n const target =\n targetUser === flags.sourceUser ? source : await navigateToUserRoot(pl, targetUser);\n\n const newId = randomUUID();\n\n const result = await pl.withWriteTx(\"adminCopyProject\", async (tx) => {\n const sourceMetaStr = await tx.getKValueString(sourceRid, ProjectMetaKey);\n const sourceMeta = JSON.parse(sourceMetaStr);\n const sourceLabel: string = sourceMeta.label;\n\n const existingLabels = await getExistingLabelsInTx(tx, target.projectListRid);\n\n let newLabel: string = flags.name ?? sourceLabel;\n\n if (existingLabels.includes(newLabel)) {\n if (!flags.autoRename) {\n throw new Error(`Project name \"${newLabel}\" already exists for target user.`);\n }\n newLabel = deduplicateName(flags.name ?? sourceLabel, existingLabels);\n }\n\n const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });\n tx.createField(field(target.projectListRid, newId), \"Dynamic\", newPrj);\n await tx.commit();\n\n const prjResourceId = await newPrj.globalId;\n const prjId = resourceIdToString(prjResourceId);\n return { id: prjId, rid: prjResourceId, label: newLabel };\n });\n\n if (flags.format === \"json\") {\n outputJson({\n id: result.id,\n rid: resourceIdToString(result.rid),\n label: result.label,\n sourceUser: flags.sourceUser,\n targetUser,\n });\n } else {\n outputText(\n `Copied project from ${flags.sourceUser} to ${targetUser} as \"${result.label}\" (id: ${result.id}, rid: ${resourceIdToString(result.rid)})`,\n );\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputJson, outputText, outputCsv } from \"../../output\";\n\nexport default function adminUserListCommand(): Command {\n const cmd = new Command(\"user-list\").description(\n \"List all known users' logins from a live server. Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, GlobalOptions(\"csv\", [\"text\", \"json\", \"csv\"]), AdminAuthOptions());\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const logins = (await pl.listUsers()).map((u) => u.login).sort();\n if (flags.format === \"json\") outputJson(logins);\n else if (flags.format === \"text\") outputText(logins.join(\"\\n\"));\n else\n outputCsv(\n [\"login\"],\n logins.map((l) => [l]),\n );\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport {\n ensureUserProjectList,\n listProjectIdentities,\n moveProjects,\n openUserRoot,\n} from \"../../project_ops\";\nimport type { MovedProject, ProjectIdentityWithLabel } from \"../../project_ops\";\nimport { formatTable, outputJson, outputText } from \"../../output\";\n\nexport default function adminDeleteUserCommand(): Command {\n const cmd = new Command(\"delete-user\").description(\n \"Delete a user account. Optionally re-homes the user's projects to another user first. \" +\n \"Requires admin/controller credentials.\",\n );\n\n cmd.argument(\"<user>\", \"Username of the account to delete\");\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\n \"--move-projects-to <user>\",\n \"Re-home the deleted user's projects to this user before deleting the account\",\n ),\n );\n cmd.addOption(\n new Option(\n \"--delete-projects\",\n \"Delete the user's projects along with the account, losing their data\",\n ),\n );\n cmd.option(\"--force\", \"Skip confirmation\", false);\n\n cmd.action(async (user: string, flags) => {\n // The two modes are alternatives, not a combination: one keeps the projects, the other\n // destroys them, and a request for both says nothing about which was meant.\n if (flags.moveProjectsTo && flags.deleteProjects) {\n throw new Error(\"--move-projects-to and --delete-projects are mutually exclusive\");\n }\n if (flags.moveProjectsTo === user) {\n throw new Error(\"--move-projects-to must name a different user than the one being deleted\");\n }\n // Caught here as well as server-side, where it is authoritative: the operator gets the reason\n // instead of a failure from whichever lookup happens to run first.\n if (flags.adminUser === user) {\n throw new Error(\n `Refusing to delete \"${user}\" — it is the account these credentials authenticate as.`,\n );\n }\n\n const pl = await connectClient(flags);\n try {\n const source = await openUserRoot(pl, user);\n // No project list means the account never opened the app, so it owns nothing — a state to\n // delete straight through, not to fail on.\n const projects =\n source.projectListRid === undefined\n ? []\n : await listProjectIdentities(pl, source.projectListRid);\n\n // Neither mode given while the account still owns projects: refuse rather than pick. Both\n // defaults are wrong to assume — one silently destroys data, the other silently hands it to\n // someone. An account with no projects has nothing to decide about, so it just proceeds.\n if (projects.length > 0 && !flags.moveProjectsTo && !flags.deleteProjects) {\n throw new Error(\n `User \"${user}\" owns ${projects.length} project(s). Pass --move-projects-to <user> to ` +\n \"re-home them, or --delete-projects to delete them with the account.\",\n );\n }\n\n const confirmed = await confirmDeletion(user, projects, flags);\n if (!confirmed) {\n outputText(\"Aborted.\");\n return;\n }\n\n let moved: MovedProject[] = [];\n if (flags.moveProjectsTo && projects.length > 0) {\n const target = await openUserRoot(pl, flags.moveProjectsTo);\n // Created if the target has none, so re-homing to a user who has never opened the app\n // works rather than failing halfway with the account still present.\n const targetList = await ensureUserProjectList(pl, target.userRoot);\n moved = await moveProjects(pl, source.projectListRid!, targetList);\n }\n\n // deleteUser takes the root and everything still attached to it. The listing, the prompt and\n // the move each ran in an earlier transaction, so re-read: a project attached since then would\n // be destroyed without ever being reviewed.\n const remaining =\n source.projectListRid === undefined\n ? []\n : await listProjectIdentities(pl, source.projectListRid);\n assertProjectsAccountedFor(user, flags, projects, remaining);\n\n const report = await pl.deleteUser(user);\n\n if (flags.format === \"json\") {\n outputJson({\n deleted: true,\n user,\n movedTo: flags.moveProjectsTo ?? null,\n movedProjects: moved,\n deletedProjects: flags.moveProjectsTo ? [] : remaining.map((p) => p.label),\n userRootId: report.userRootId === undefined ? null : report.userRootId.toString(),\n userRootDeleted: report.userRootDeleted,\n revokedGrants: report.revokedGrants,\n removedIdentityIndexEntries: report.removedIdentityIndexEntries,\n });\n } else {\n outputText(renderResult(user, flags.moveProjectsTo, moved, remaining));\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n\n/**\n * Refuses while the root holds a project the operator never agreed to lose — attached after the\n * listing, or left behind by the move.\n *\n * A last read, not a lock: it closes the prompt-sized window, not the round trip that follows.\n */\nfunction assertProjectsAccountedFor(\n user: string,\n flags: { moveProjectsTo?: string },\n approved: ProjectIdentityWithLabel[],\n remaining: ProjectIdentityWithLabel[],\n): void {\n if (flags.moveProjectsTo) {\n if (remaining.length === 0) return;\n throw new Error(\n `User \"${user}\" still owns ${remaining.length} project(s) after the move: ` +\n `${remaining.map((p) => p.label).join(\", \")}. The account was NOT deleted — ` +\n \"the projects were attached while the move ran. Re-run the command to move them too.\",\n );\n }\n\n const approvedIds = new Set(approved.map((p) => p.id));\n const unapproved = remaining.filter((p) => !approvedIds.has(p.id));\n if (unapproved.length === 0) return;\n throw new Error(\n `User \"${user}\" gained ${unapproved.length} project(s) since the list you confirmed: ` +\n `${unapproved.map((p) => p.label).join(\", \")}. The account was NOT deleted — ` +\n \"deleting it now would destroy them unreviewed. Re-run the command to see the current list.\",\n );\n}\n\n/** Asks the operator to confirm, naming the affected projects and their fate. */\nasync function confirmDeletion(\n user: string,\n projects: ProjectIdentityWithLabel[],\n flags: { moveProjectsTo?: string; force?: boolean },\n): Promise<boolean> {\n if (flags.force) return true;\n\n const fate = flags.moveProjectsTo\n ? `${projects.length} project(s) will move to \"${flags.moveProjectsTo}\"`\n : projects.length > 0\n ? `${projects.length} project(s) will be PERMANENTLY DELETED`\n : \"the account owns no projects\";\n\n process.stderr.write(`Delete user \"${user}\"? ${fate}.\\n`);\n if (projects.length > 0) {\n process.stderr.write(projects.map((p) => ` - ${p.label}`).join(\"\\n\") + \"\\n\");\n }\n\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await new Promise<string>((resolve) => {\n rl.question(\"Proceed? [y/N] \", resolve);\n });\n return answer.toLowerCase() === \"y\";\n } finally {\n rl.close();\n }\n}\n\nfunction renderResult(\n user: string,\n movedTo: string | undefined,\n moved: MovedProject[],\n projects: ProjectIdentityWithLabel[],\n): string {\n const lines: string[] = [];\n\n if (movedTo) {\n if (moved.length > 0) {\n lines.push(`Moved ${moved.length} project(s) from ${user} to ${movedTo}:`);\n lines.push(\n formatTable(\n [\"id\", \"name\", \"name in target\"],\n moved.map((p) => [p.id, p.sourceLabel, p.targetLabel]),\n ),\n );\n } else {\n lines.push(`User ${user} had no projects to move.`);\n }\n } else if (projects.length > 0) {\n lines.push(`Deleted ${projects.length} project(s) belonging to ${user}:`);\n lines.push(projects.map((p) => ` - ${p.label}`).join(\"\\n\"));\n }\n\n lines.push(`Deleted user \"${user}\".`);\n return lines.join(\"\\n\");\n}\n","import { Command } from \"commander\";\nimport { InstanceStatsContextTypeName, parseInstanceStats } from \"@milaboratories/pl-middle-layer\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputJson } from \"../../output\";\n\nexport default function adminInstanceStatsCommand(): Command {\n const cmd = new Command(\"instance-stats\").description(\"Show the instance statistics as JSON.\");\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const [context] = await pl.listSharedResourcesByType(InstanceStatsContextTypeName);\n if (context === undefined) throw new Error(\"The instance has no instance statistics.\");\n const kvs = await pl.withReadTx(\"instanceStats\", (tx) => tx.listKeyValuesString(context));\n outputJson(parseInstanceStats(kvs));\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import {\n asSignedResourceId,\n createSignedResourceId,\n isLocalResourceId,\n resourceIdFromString,\n type SignedResourceId,\n} from \"@milaboratories/pl-client\";\n\n/**\n * Admin and controller roles do not need resource signatures: an ID without a signature\n * is accepted by the backend for these roles.\n */\nexport function parseResourceId(raw: string): SignedResourceId {\n const str = raw.trim();\n if (str.includes(\"|\")) return asSignedResourceId(str);\n\n let id: bigint | undefined = resourceIdFromString(str);\n if (id === undefined && /^\\d+$/.test(str)) id = BigInt(str);\n if (id === undefined || id === 0n || isLocalResourceId(id))\n throw new Error(`not a global resource ID: ${raw}`);\n\n return createSignedResourceId(id);\n}\n","import { once } from \"node:events\";\nimport { Command, InvalidArgumentError, Option } from \"commander\";\nimport {\n isNotNullSignedResourceId,\n resourceIdToString,\n resourceType,\n resourceTypeToString,\n type FieldData,\n type KeyValue,\n type OptionalSignedResourceId,\n type ResourceData,\n type ResourceType,\n} from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, AddressOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { parseResourceId } from \"../../resource_id\";\n\nexport default function maintenanceListResourcesCommand(): Command {\n const cmd = new Command(\"list-resources\").description(\n \"List resources of one type as JSON lines, in ascending order of resource ID. \" +\n \"Resource data and key-value values are printed as JSON when they are valid JSON, \" +\n 'as text when they are valid UTF-8, and as {\"base64\": ...} in other cases. ' +\n \"Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, AddressOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\"--type <name:version>\", \"Resource type to list (e.g. 'Blob/work:1')\")\n .argParser(parseResourceTypeArg)\n .makeOptionMandatory(),\n );\n cmd.addOption(\n new Option(\"--limit <n>\", \"Maximum number of resources to list. 0 lists all resources\")\n .argParser(parseNonNegativeInt)\n .default(0),\n );\n cmd.addOption(\n new Option(\n \"--after <resource-id>\",\n \"List only resources with IDs greater than this ID. \" +\n \"To get the next page, give the ID of the last resource of the previous page\",\n ).argParser(parseResourceId),\n );\n cmd.option(\n \"--load-fields\",\n \"Load the fields and the error of each resource ('fields' and 'error' keys)\",\n false,\n );\n cmd.option(\"--load-kv\", \"Load the key-value entries of each resource ('kv' key)\", false);\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const resources = await pl.withReadTx(\"listResources\", async (tx) => {\n const list = await tx.listResourcesByType(flags.type, {\n limit: flags.limit,\n after: flags.after,\n loadFields: flags.loadFields,\n });\n return await Promise.all(\n list.map(async (resource) => ({\n resource,\n kv: flags.loadKv ? await tx.listKeyValues(resource.id) : undefined,\n })),\n );\n });\n\n for (const { resource, kv } of resources) {\n const line = JSON.stringify(toJson(resource, flags.loadFields, kv)) + \"\\n\";\n // Wait for a slow reader: else the output collects in memory a second time.\n if (!process.stdout.write(line)) await once(process.stdout, \"drain\");\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n\nfunction toJson(\n r: ResourceData,\n withFields: boolean,\n kv: KeyValue[] | undefined,\n): Record<string, unknown> {\n return {\n id: resourceIdToString(r.id),\n type: resourceTypeToString(r.type),\n kind: r.kind,\n originalId: optionalIdToString(r.originalResourceId),\n inputsLocked: r.inputsLocked,\n outputsLocked: r.outputsLocked,\n ready: r.resourceReady,\n final: r.final,\n data: r.data === undefined || r.data.length === 0 ? null : decodeBytes(r.data),\n // The backend sends the resource error as a field: without fields it is not known.\n ...(withFields\n ? { error: optionalIdToString(r.error), fields: r.fields.map(fieldToJson) }\n : {}),\n ...(kv === undefined\n ? {}\n : { kv: Object.fromEntries(kv.map((e) => [e.key, decodeBytes(e.value)])) }),\n };\n}\n\nfunction fieldToJson(f: FieldData): Record<string, unknown> {\n return {\n name: f.name,\n type: f.type,\n status: f.status,\n value: optionalIdToString(f.value),\n error: optionalIdToString(f.error),\n valueIsFinal: f.valueIsFinal,\n };\n}\n\nfunction optionalIdToString(id: OptionalSignedResourceId): string | null {\n return isNotNullSignedResourceId(id) ? resourceIdToString(id) : null;\n}\n\n/** JSON value when the bytes are valid JSON, text when valid UTF-8, {\"base64\": ...} otherwise. */\nfunction decodeBytes(bytes: Uint8Array): unknown {\n let text: string;\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch {\n return { base64: Buffer.from(bytes).toString(\"base64\") };\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction parseResourceTypeArg(value: string): ResourceType {\n const sep = value.lastIndexOf(\":\");\n if (sep <= 0 || sep === value.length - 1)\n throw new InvalidArgumentError(`expected <name>:<version>, e.g. 'Blob/work:1': ${value}`);\n return resourceType(value.slice(0, sep), value.slice(sep + 1));\n}\n\nfunction parseNonNegativeInt(value: string): number {\n const n = Number(value);\n if (!Number.isInteger(n) || n < 0)\n throw new InvalidArgumentError(`not a non-negative integer: ${value}`);\n return n;\n}\n","import { Command, Option } from \"commander\";\nimport { isNotNullSignedResourceId, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, AddressOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputText } from \"../../output\";\nimport { parseResourceId } from \"../../resource_id\";\n\nconst DefaultErrorMessage =\n \"Manual error set by administrator to trigger blocks re-run. \" +\n \"Run block once again to get rid of it.\";\n\nexport default function maintenanceSetResourceErrorCommand(): Command {\n const cmd = new Command(\"set-resource-error\").description(\n \"Put an error on one or more resources in a single transaction. \" +\n \"Resources that already have an error are skipped. \" +\n \"Requires admin/controller credentials.\",\n );\n\n cmd.argument(\n \"<resource-id...>\",\n \"Resource IDs: as printed by the server (NG:0x1A2B), as decimal numbers, \" +\n \"or as signed IDs (<decimal ID>|<signature hex>)\",\n );\n addOptions(cmd, AddressOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\"-m, --error-message <message>\", \"Error message to put on the resources\").default(\n DefaultErrorMessage,\n ),\n );\n cmd.option(\n \"--skip-missing\",\n \"Skip resources that do not exist instead of failing the whole transaction\",\n false,\n );\n\n cmd.action(async (rawIds: string[], flags) => {\n // Parse all IDs before the connection, so that a typo does not leave a half-done job.\n const ids = rawIds.map(parseResourceId);\n\n const pl = await connectClient(flags);\n try {\n const result = await pl.withWriteTx(\"setResourceError\", async (tx) => {\n const found = await Promise.all(\n ids.map(async (id) => ({\n id,\n data: flags.skipMissing\n ? await tx.getResourceDataIfExists(id, true)\n : await tx.getResourceData(id, true, true),\n })),\n );\n\n const missing = found.filter((r) => r.data === undefined).map((r) => r.id);\n const resources = found.flatMap((r) => (r.data === undefined ? [] : [r.data]));\n const targets = resources.filter((r) => !isNotNullSignedResourceId(r.error));\n const skipped = resources.filter((r) => isNotNullSignedResourceId(r.error));\n\n if (targets.length > 0) {\n // One error resource for all targets: the backend links it to each target separately.\n const error = tx.createError(flags.errorMessage);\n for (const r of targets) tx.setResourceError(r.id, error);\n await tx.commit();\n }\n\n return { targets, skipped, missing };\n });\n\n for (const id of result.missing)\n outputText(`skipped ${resourceIdToString(id)}: resource does not exist`);\n for (const r of result.skipped)\n outputText(`skipped ${resourceIdToString(r.id)}: resource already has an error`);\n for (const r of result.targets) outputText(`error set ${resourceIdToString(r.id)}`);\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport projectListCommand from \"./cmd/project/list\";\nimport projectInfoCommand from \"./cmd/project/info\";\nimport projectDuplicateCommand from \"./cmd/project/duplicate\";\nimport projectRenameCommand from \"./cmd/project/rename\";\nimport projectDeleteCommand from \"./cmd/project/delete\";\nimport adminCopyProjectCommand from \"./cmd/admin/copy-project\";\nimport adminUserListCommand from \"./cmd/admin/user-list\";\nimport adminDeleteUserCommand from \"./cmd/admin/delete-user\";\nimport adminInstanceStatsCommand from \"./cmd/admin/instance-stats\";\nimport maintenanceListResourcesCommand from \"./cmd/maintenance/list-resources\";\nimport maintenanceSetResourceErrorCommand from \"./cmd/maintenance/set-resource-error\";\n\nexport function buildProgram(): Command {\n const program = new Command();\n program.name(\"pl-cli\").description(\"Platforma command-line client\");\n\n const project = new Command(\"project\").description(\"Manage projects\");\n project.addCommand(projectListCommand());\n project.addCommand(projectInfoCommand());\n project.addCommand(projectDuplicateCommand());\n project.addCommand(projectRenameCommand());\n project.addCommand(projectDeleteCommand());\n program.addCommand(project);\n\n const admin = new Command(\"admin\").description(\n \"Admin operations (requires controller credentials)\",\n );\n admin.addCommand(adminCopyProjectCommand());\n admin.addCommand(adminUserListCommand());\n admin.addCommand(adminDeleteUserCommand());\n admin.addCommand(adminInstanceStatsCommand());\n program.addCommand(admin);\n\n const maintenance = new Command(\"maintenance\").description(\n \"Low-level server state repair (requires admin/controller credentials)\",\n );\n maintenance.addCommand(maintenanceListResourcesCommand());\n maintenance.addCommand(maintenanceSetResourceErrorCommand());\n program.addCommand(maintenance);\n\n return program;\n}\n\nexport async function run(argv: string[] = process.argv): Promise<void> {\n await buildProgram().parseAsync(argv);\n}\n"],"mappings":";;;;;;;;AAUA,eAAsBkB,EAAc,GAMd;CAQpB,OAPIC,EAAM,aAAaA,EAAM,gBACpBjB,EAAwB;EAC7B,SAASiB,EAAM;EACf,WAAWA,EAAM;EACjB,eAAeA,EAAM;CACvB,CAAC,IAEIH,EAAmB;EACxB,SAASG,EAAM;EACf,MAAMA,EAAM;EACZ,UAAUA,EAAM;CAClB,CAAC;AACH;AASA,eAAsBC,EAAQ,GAOkC;CAC9D,I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,EAAqB,CAAC,GACzCnB,EAAQ,WAAWqB,EAAqB,CAAC,GACzC8E,EAAQ,WAAWnG,CAAO;CAE1B,IAAMoG,IAAQ,IAAIzG,EAAQ,OAAO,CAAC,CAAC,YACjC,oDACF;CAKA,AAJAyG,EAAM,WAAW1E,EAAwB,CAAC,GAC1C0E,EAAM,WAAWrE,EAAqB,CAAC,GACvCqE,EAAM,WAAWjE,GAAuB,CAAC,GACzCiE,EAAM,WAAWhD,GAA0B,CAAC,GAC5C+C,EAAQ,WAAWC,CAAK;CAExB,IAAMC,IAAc,IAAI1G,EAAQ,aAAa,CAAC,CAAC,YAC7C,uEACF;CAKA,OAJA0G,EAAY,WAAWrC,EAAgC,CAAC,GACxDqC,EAAY,WAAWX,GAAmC,CAAC,GAC3DS,EAAQ,WAAWE,CAAW,GAEvBF;AACT;AAEA,eAAsBG,GAAI,IAAiB,QAAQ,MAAqB;CACtE,MAAMJ,EAAa,CAAC,CAAC,WAAWK,CAAI;AACtC"}
1
+ {"version":3,"file":"cli.js","names":["openUserRoot","outputText","createAdminPlConnection","duplicateProject","getProjectInfo","getProjectListRid","navigateToUserRoot","moveProjects","outputJson","listProjects","formatTable","deduplicateName","outputCsv","deleteProject","formatDate","getExistingLabelsInTx","renameProject","createPlConnection","resolveProject","connectClient","flags","connect","hasAdminUser","hasAdminPassword","hasTarget","pl","projectListRid","addOptions","optionGroups","group","opt","cmd","AddressOptions","Option","GlobalOptions","allowedFormats","formatDefault","UserAuthOptions","AdminAuthOptions","AdminTargetOptions","projectListCommand","Command","projects","p","resourceIdToString","projectInfoCommand","project","info","id","rid","bid","projectDuplicateCommand","sourceRid","newId","randomUUID","result","sourceMetaStr","tx","ProjectMetaKey","sourceLabel","existingLabels","newLabel","newPrj","field","projectResourceId","projectRenameCommand","projectDeleteCommand","rl","createInterface","resolve","fieldName","adminCopyProjectCommand","targetUser","source","target","prjResourceId","adminUserListCommand","logins","u","l","adminDeleteUserCommand","user","listProjectIdentities","confirmDeletion","moved","targetList","ensureUserProjectList","remaining","report","renderResult","assertProjectsAccountedFor","approvedIds","approved","unapproved","fate","lines","movedTo","adminInstanceStatsCommand","context","InstanceStatsContextTypeName","kvs","parseInstanceStats","parseResourceId","str","raw","asSignedResourceId","resourceIdFromString","isLocalResourceId","createSignedResourceId","maintenanceListResourcesCommand","parseResourceTypeArg","parseNonNegativeInt","resources","list","resource","line","toJson","kv","once","r","resourceTypeToString","optionalIdToString","decodeBytes","withFields","fieldToJson","f","isNotNullSignedResourceId","text","bytes","sep","value","InvalidArgumentError","resourceType","n","DefaultErrorMessage","maintenanceSetResourceErrorCommand","ids","rawIds","found","missing","targets","skipped","error","ResourcesFixupLevelKey","ResourcesFixupLevelSize","readFixupLevel","controllerType","resetFixupLevel","maintenanceControllerListCommand","controllers","listRegisteredControllers","c","headers","rows","collect","previous","parse","maintenanceControllerRerunFixupsCommand","names","reset","selected","selectControllers","levels","controller","level","registered","byType","name","wanted","anyResourceIdToBigint","buildProgram","program","admin","maintenance","run","argv"],"sources":["../src/base_command.ts","../src/cmd-opts.ts","../src/cmd/project/list.ts","../src/cmd/project/info.ts","../src/cmd/project/duplicate.ts","../src/cmd/project/rename.ts","../src/cmd/project/delete.ts","../src/cmd/admin/copy-project.ts","../src/cmd/admin/user-list.ts","../src/cmd/admin/delete-user.ts","../src/cmd/admin/instance-stats.ts","../src/resource_id.ts","../src/cmd/maintenance/list-resources.ts","../src/cmd/maintenance/set-resource-error.ts","../src/cmd/maintenance/controller/fixup_level.ts","../src/cmd/maintenance/controller/list.ts","../src/cmd/maintenance/controller/rerun-fixups.ts","../src/cli.ts"],"sourcesContent":["import type { PlClient, SignedResourceId } from \"@milaboratories/pl-client\";\nimport { createPlConnection, createAdminPlConnection } from \"./connection\";\nimport { getProjectListRid, navigateToUserRoot } from \"./project_ops\";\n\n/**\n * Low-level: get an authenticated PlClient without resolving a project list.\n * Use this for commands that navigate to multiple users (e.g. admin copy-project).\n *\n * Callers own the returned client and must `await pl.close()` when done.\n */\nexport async function connectClient(flags: {\n address: string;\n user?: string;\n password?: string;\n adminUser?: string;\n adminPassword?: string;\n}): Promise<PlClient> {\n if (flags.adminUser && flags.adminPassword) {\n return createAdminPlConnection({\n address: flags.address,\n adminUser: flags.adminUser,\n adminPassword: flags.adminPassword,\n });\n }\n return createPlConnection({\n address: flags.address,\n user: flags.user,\n password: flags.password,\n });\n}\n\n/**\n * Connect and resolve the project list for a single user.\n * In admin mode (--admin-user + --admin-password + --target-user), operates on the target user's data.\n * In user mode, operates on the authenticated user's own data.\n *\n * Callers own the returned client and must `await pl.close()` when done.\n */\nexport async function connect(flags: {\n address: string;\n user?: string;\n password?: string;\n adminUser?: string;\n adminPassword?: string;\n targetUser?: string;\n}): Promise<{ pl: PlClient; projectListRid: SignedResourceId }> {\n const hasAdminUser = !!flags.adminUser;\n const hasAdminPassword = !!flags.adminPassword;\n const hasTarget = !!flags.targetUser;\n\n // Validate flag combinations\n if (hasTarget && !(hasAdminUser && hasAdminPassword)) {\n throw new Error(\"--target-user requires --admin-user and --admin-password\");\n }\n if ((hasAdminUser || hasAdminPassword) && !hasTarget) {\n throw new Error(\"--admin-user/--admin-password require --target-user for project commands\");\n }\n\n const pl = await connectClient(flags);\n\n let projectListRid: SignedResourceId;\n if (hasTarget) {\n const nav = await navigateToUserRoot(pl, flags.targetUser!);\n projectListRid = nav.projectListRid;\n } else {\n projectListRid = await getProjectListRid(pl);\n }\n\n return { pl, projectListRid };\n}\n","import { Command, Option } from \"commander\";\nimport type { OutputFormat } from \"./output\";\n\n/** Add one or more groups of options to a command, preserving group order. */\nexport function addOptions(cmd: Command, ...optionGroups: Option[][]): Command {\n for (const group of optionGroups) {\n for (const opt of group) cmd.addOption(opt);\n }\n return cmd;\n}\n\n/** Server address only (for commands with a fixed output format). */\nexport const AddressOptions = (): Option[] => [\n new Option(\"-a, --address <url>\", \"Platforma server address\")\n .env(\"PL_ADDRESS\")\n .makeOptionMandatory(),\n];\n\nexport const GlobalOptions = (\n formatDefault: OutputFormat = \"text\",\n allowedFormats: OutputFormat[] = [\"text\", \"json\"],\n): Option[] => [\n ...AddressOptions(),\n new Option(\"-f, --format <format>\", \"Output format\")\n .choices(allowedFormats)\n .default(formatDefault),\n];\n\nexport const UserAuthOptions = (): Option[] => [\n new Option(\"-u, --user <user>\", \"Username for authentication\").env(\"PL_USER\"),\n new Option(\"-p, --password <password>\", \"Password for authentication\").env(\"PL_PASSWORD\"),\n];\n\n/** Admin credentials only (for purely admin commands like copy-project). */\nexport const AdminAuthOptions = (): Option[] => [\n new Option(\"--admin-user <user>\", \"Admin/controller username\")\n .env(\"PL_ADMIN_USER\")\n .makeOptionMandatory(),\n new Option(\"--admin-password <password>\", \"Admin/controller password\")\n .env(\"PL_ADMIN_PASSWORD\")\n .makeOptionMandatory(),\n];\n\n/** Admin credentials + target user (for regular commands that can optionally operate on another user). */\nexport const AdminTargetOptions = (): Option[] => [\n new Option(\"--admin-user <user>\", \"Admin/controller username (enables admin mode)\").env(\n \"PL_ADMIN_USER\",\n ),\n new Option(\"--admin-password <password>\", \"Admin/controller password\").env(\"PL_ADMIN_PASSWORD\"),\n new Option(\n \"--target-user <user>\",\n \"Operate on this user's data (requires admin credentials)\",\n ).env(\"PL_TARGET_USER\"),\n];\n","import { Command } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { listProjects } from \"../../project_ops\";\nimport { formatTable, formatDate, outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectListCommand(): Command {\n const cmd = new Command(\"list\").description(\"List all projects for the authenticated user.\");\n\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n\n cmd.action(async (flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const projects = await listProjects(pl, projectListRid);\n\n if (flags.format === \"json\") {\n outputJson(\n projects.map((p) => ({\n id: p.id,\n rid: resourceIdToString(p.rid),\n label: p.label,\n created: p.created.toISOString(),\n lastModified: p.lastModified.toISOString(),\n })),\n );\n } else {\n if (projects.length === 0) {\n outputText(\"No projects found.\");\n return;\n }\n\n outputText(\n formatTable(\n [\"ID\", \"RID\", \"LABEL\", \"CREATED\", \"LAST MODIFIED\"],\n projects.map((p) => [\n p.id,\n resourceIdToString(p.rid),\n p.label,\n formatDate(p.created),\n formatDate(p.lastModified),\n ]),\n ),\n );\n outputText(`\\n${projects.length} project(s)`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, getProjectInfo } from \"../../project_ops\";\nimport { formatDate, outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectInfoCommand(): Command {\n const cmd = new Command(\"info\").description(\"Show detailed information about a project.\");\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid } = await resolveProject(pl, projectListRid, project);\n const info = await getProjectInfo(pl, id, rid);\n\n if (flags.format === \"json\") {\n outputJson({\n id: info.id,\n rid: resourceIdToString(info.rid),\n label: info.label,\n schemaVersion: info.schemaVersion,\n blockCount: info.blockCount,\n blockIds: info.blockIds,\n created: info.created.toISOString(),\n lastModified: info.lastModified.toISOString(),\n });\n } else {\n outputText(`Project: ${info.label}`);\n outputText(`ID: ${info.id}`);\n outputText(`RID: ${resourceIdToString(info.rid)}`);\n outputText(`Schema: ${info.schemaVersion ?? \"(unknown)\"}`);\n outputText(`Blocks: ${info.blockCount}`);\n if (info.blockIds.length > 0) {\n for (const bid of info.blockIds) {\n outputText(` - ${bid}`);\n }\n }\n outputText(`Created: ${formatDate(info.created)}`);\n outputText(`Last Modified: ${formatDate(info.lastModified)}`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { field, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { ProjectMetaKey } from \"@milaboratories/pl-middle-layer\";\nimport { randomUUID } from \"node:crypto\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport {\n resolveProject,\n deduplicateName,\n duplicateProject,\n getExistingLabelsInTx,\n} from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function projectDuplicateCommand(): Command {\n const cmd = new Command(\"duplicate\").description(\n \"Duplicate a project within the same user. Auto-renames on collision by default.\",\n );\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.option(\"-n, --name <name>\", \"Name for the duplicate\");\n cmd.addOption(\n new Option(\"--auto-rename\", \"Auto-rename on collision (default: true)\").default(true),\n );\n cmd.option(\"--no-auto-rename\", \"Fail on name collision instead of auto-renaming\");\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { rid: sourceRid } = await resolveProject(pl, projectListRid, project);\n\n const newId = randomUUID();\n\n const result = await pl.withWriteTx(\"duplicateProject\", async (tx) => {\n const sourceMetaStr = await tx.getKValueString(sourceRid, ProjectMetaKey);\n const sourceMeta = JSON.parse(sourceMetaStr);\n const sourceLabel: string = sourceMeta.label;\n\n const existingLabels = await getExistingLabelsInTx(tx, projectListRid);\n\n // Compute new label\n let newLabel: string;\n if (flags.name) {\n if (!flags.autoRename && existingLabels.includes(flags.name)) {\n throw new Error(`Project name \"${flags.name}\" already exists.`);\n }\n newLabel = existingLabels.includes(flags.name)\n ? deduplicateName(flags.name, existingLabels)\n : flags.name;\n } else {\n newLabel = deduplicateName(sourceLabel, existingLabels);\n }\n\n const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });\n tx.createField(field(projectListRid, newId), \"Dynamic\", newPrj);\n await tx.commit();\n\n const projectResourceId = await newPrj.globalId;\n const projectId = resourceIdToString(projectResourceId);\n return { id: projectId, rid: projectResourceId, label: newLabel };\n });\n\n if (flags.format === \"json\") {\n outputJson({ id: result.id, rid: resourceIdToString(result.rid), label: result.label });\n } else {\n outputText(`Duplicated project as \"${result.label}\" (id: ${result.id})`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, renameProject } from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\nimport { resourceIdToString } from \"@milaboratories/pl-client\";\n\nexport default function projectRenameCommand(): Command {\n const cmd = new Command(\"rename\").description(\"Rename a project.\");\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.addOption(new Option(\"-n, --name <name>\", \"New name for the project\").makeOptionMandatory());\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid } = await resolveProject(pl, projectListRid, project);\n\n await renameProject(pl, rid, flags.name);\n\n if (flags.format === \"json\") {\n outputJson({ id, rid: resourceIdToString(rid), label: flags.name });\n } else {\n outputText(`Renamed project to \"${flags.name}\"`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { connect } from \"../../base_command\";\nimport { addOptions, GlobalOptions, UserAuthOptions, AdminTargetOptions } from \"../../cmd-opts\";\nimport { resolveProject, deleteProject, getProjectInfo } from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function projectDeleteCommand(): Command {\n const cmd = new Command(\"delete\").description(\n \"Delete a project. This permanently destroys all project data.\",\n );\n\n cmd.argument(\"<project>\", \"Project ID or label\");\n addOptions(cmd, GlobalOptions(), UserAuthOptions(), AdminTargetOptions());\n cmd.option(\"--force\", \"Skip confirmation\", false);\n\n cmd.action(async (project: string, flags) => {\n const { pl, projectListRid } = await connect(flags);\n try {\n const { id, rid, fieldName } = await resolveProject(pl, projectListRid, project);\n\n const info = await getProjectInfo(pl, id, rid);\n\n if (!flags.force) {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await new Promise<string>((resolve) => {\n rl.question(\n `Delete project \"${info.label}\" (${info.blockCount} blocks)? [y/N] `,\n resolve,\n );\n });\n if (answer.toLowerCase() !== \"y\") {\n outputText(\"Aborted.\");\n return;\n }\n } finally {\n rl.close();\n }\n }\n\n await deleteProject(pl, projectListRid, fieldName);\n\n if (flags.format === \"json\") {\n outputJson({ deleted: true, id, label: info.label });\n } else {\n outputText(`Deleted project \"${info.label}\"`);\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { field, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { ProjectMetaKey } from \"@milaboratories/pl-middle-layer\";\nimport { randomUUID } from \"node:crypto\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport {\n resolveProject,\n deduplicateName,\n duplicateProject,\n getExistingLabelsInTx,\n navigateToUserRoot,\n} from \"../../project_ops\";\nimport { outputJson, outputText } from \"../../output\";\n\nexport default function adminCopyProjectCommand(): Command {\n const cmd = new Command(\"copy-project\").description(\n \"Copy a project from one user to another. Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\n \"--source-user <user>\",\n \"Username of the source project owner\",\n ).makeOptionMandatory(),\n );\n cmd.addOption(\n new Option(\"--source-project <project>\", \"Source project ID or label\").makeOptionMandatory(),\n );\n cmd.option(\n \"--target-user <user>\",\n \"Username of the target user (defaults to source-user for same-user copy)\",\n );\n cmd.option(\"-n, --name <name>\", \"Name for the copied project\");\n cmd.addOption(\n new Option(\"--auto-rename\", \"Auto-rename on collision (default: true)\").default(true),\n );\n cmd.option(\"--no-auto-rename\", \"Fail on name collision instead of auto-renaming\");\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const targetUser = flags.targetUser ?? flags.sourceUser;\n\n const source = await navigateToUserRoot(pl, flags.sourceUser);\n const { rid: sourceRid } = await resolveProject(\n pl,\n source.projectListRid,\n flags.sourceProject,\n );\n\n const target =\n targetUser === flags.sourceUser ? source : await navigateToUserRoot(pl, targetUser);\n\n const newId = randomUUID();\n\n const result = await pl.withWriteTx(\"adminCopyProject\", async (tx) => {\n const sourceMetaStr = await tx.getKValueString(sourceRid, ProjectMetaKey);\n const sourceMeta = JSON.parse(sourceMetaStr);\n const sourceLabel: string = sourceMeta.label;\n\n const existingLabels = await getExistingLabelsInTx(tx, target.projectListRid);\n\n let newLabel: string = flags.name ?? sourceLabel;\n\n if (existingLabels.includes(newLabel)) {\n if (!flags.autoRename) {\n throw new Error(`Project name \"${newLabel}\" already exists for target user.`);\n }\n newLabel = deduplicateName(flags.name ?? sourceLabel, existingLabels);\n }\n\n const newPrj = await duplicateProject(tx, sourceRid, { label: newLabel });\n tx.createField(field(target.projectListRid, newId), \"Dynamic\", newPrj);\n await tx.commit();\n\n const prjResourceId = await newPrj.globalId;\n const prjId = resourceIdToString(prjResourceId);\n return { id: prjId, rid: prjResourceId, label: newLabel };\n });\n\n if (flags.format === \"json\") {\n outputJson({\n id: result.id,\n rid: resourceIdToString(result.rid),\n label: result.label,\n sourceUser: flags.sourceUser,\n targetUser,\n });\n } else {\n outputText(\n `Copied project from ${flags.sourceUser} to ${targetUser} as \"${result.label}\" (id: ${result.id}, rid: ${resourceIdToString(result.rid)})`,\n );\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command } from \"commander\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputJson, outputText, outputCsv } from \"../../output\";\n\nexport default function adminUserListCommand(): Command {\n const cmd = new Command(\"user-list\").description(\n \"List all known users' logins from a live server. Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, GlobalOptions(\"csv\", [\"text\", \"json\", \"csv\"]), AdminAuthOptions());\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const logins = (await pl.listUsers()).map((u) => u.login).sort();\n if (flags.format === \"json\") outputJson(logins);\n else if (flags.format === \"text\") outputText(logins.join(\"\\n\"));\n else\n outputCsv(\n [\"login\"],\n logins.map((l) => [l]),\n );\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport {\n ensureUserProjectList,\n listProjectIdentities,\n moveProjects,\n openUserRoot,\n} from \"../../project_ops\";\nimport type { MovedProject, ProjectIdentityWithLabel } from \"../../project_ops\";\nimport { formatTable, outputJson, outputText } from \"../../output\";\n\nexport default function adminDeleteUserCommand(): Command {\n const cmd = new Command(\"delete-user\").description(\n \"Delete a user account. Optionally re-homes the user's projects to another user first. \" +\n \"Requires admin/controller credentials.\",\n );\n\n cmd.argument(\"<user>\", \"Username of the account to delete\");\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\n \"--move-projects-to <user>\",\n \"Re-home the deleted user's projects to this user before deleting the account\",\n ),\n );\n cmd.addOption(\n new Option(\n \"--delete-projects\",\n \"Delete the user's projects along with the account, losing their data\",\n ),\n );\n cmd.option(\"--force\", \"Skip confirmation\", false);\n\n cmd.action(async (user: string, flags) => {\n // The two modes are alternatives, not a combination: one keeps the projects, the other\n // destroys them, and a request for both says nothing about which was meant.\n if (flags.moveProjectsTo && flags.deleteProjects) {\n throw new Error(\"--move-projects-to and --delete-projects are mutually exclusive\");\n }\n if (flags.moveProjectsTo === user) {\n throw new Error(\"--move-projects-to must name a different user than the one being deleted\");\n }\n // Caught here as well as server-side, where it is authoritative: the operator gets the reason\n // instead of a failure from whichever lookup happens to run first.\n if (flags.adminUser === user) {\n throw new Error(\n `Refusing to delete \"${user}\" — it is the account these credentials authenticate as.`,\n );\n }\n\n const pl = await connectClient(flags);\n try {\n const source = await openUserRoot(pl, user);\n // No project list means the account never opened the app, so it owns nothing — a state to\n // delete straight through, not to fail on.\n const projects =\n source.projectListRid === undefined\n ? []\n : await listProjectIdentities(pl, source.projectListRid);\n\n // Neither mode given while the account still owns projects: refuse rather than pick. Both\n // defaults are wrong to assume — one silently destroys data, the other silently hands it to\n // someone. An account with no projects has nothing to decide about, so it just proceeds.\n if (projects.length > 0 && !flags.moveProjectsTo && !flags.deleteProjects) {\n throw new Error(\n `User \"${user}\" owns ${projects.length} project(s). Pass --move-projects-to <user> to ` +\n \"re-home them, or --delete-projects to delete them with the account.\",\n );\n }\n\n const confirmed = await confirmDeletion(user, projects, flags);\n if (!confirmed) {\n outputText(\"Aborted.\");\n return;\n }\n\n let moved: MovedProject[] = [];\n if (flags.moveProjectsTo && projects.length > 0) {\n const target = await openUserRoot(pl, flags.moveProjectsTo);\n // Created if the target has none, so re-homing to a user who has never opened the app\n // works rather than failing halfway with the account still present.\n const targetList = await ensureUserProjectList(pl, target.userRoot);\n moved = await moveProjects(pl, source.projectListRid!, targetList);\n }\n\n // deleteUser takes the root and everything still attached to it. The listing, the prompt and\n // the move each ran in an earlier transaction, so re-read: a project attached since then would\n // be destroyed without ever being reviewed.\n const remaining =\n source.projectListRid === undefined\n ? []\n : await listProjectIdentities(pl, source.projectListRid);\n assertProjectsAccountedFor(user, flags, projects, remaining);\n\n const report = await pl.deleteUser(user);\n\n if (flags.format === \"json\") {\n outputJson({\n deleted: true,\n user,\n movedTo: flags.moveProjectsTo ?? null,\n movedProjects: moved,\n deletedProjects: flags.moveProjectsTo ? [] : remaining.map((p) => p.label),\n userRootId: report.userRootId === undefined ? null : report.userRootId.toString(),\n userRootDeleted: report.userRootDeleted,\n revokedGrants: report.revokedGrants,\n removedIdentityIndexEntries: report.removedIdentityIndexEntries,\n });\n } else {\n outputText(renderResult(user, flags.moveProjectsTo, moved, remaining));\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n\n/**\n * Refuses while the root holds a project the operator never agreed to lose — attached after the\n * listing, or left behind by the move.\n *\n * A last read, not a lock: it closes the prompt-sized window, not the round trip that follows.\n */\nfunction assertProjectsAccountedFor(\n user: string,\n flags: { moveProjectsTo?: string },\n approved: ProjectIdentityWithLabel[],\n remaining: ProjectIdentityWithLabel[],\n): void {\n if (flags.moveProjectsTo) {\n if (remaining.length === 0) return;\n throw new Error(\n `User \"${user}\" still owns ${remaining.length} project(s) after the move: ` +\n `${remaining.map((p) => p.label).join(\", \")}. The account was NOT deleted — ` +\n \"the projects were attached while the move ran. Re-run the command to move them too.\",\n );\n }\n\n const approvedIds = new Set(approved.map((p) => p.id));\n const unapproved = remaining.filter((p) => !approvedIds.has(p.id));\n if (unapproved.length === 0) return;\n throw new Error(\n `User \"${user}\" gained ${unapproved.length} project(s) since the list you confirmed: ` +\n `${unapproved.map((p) => p.label).join(\", \")}. The account was NOT deleted — ` +\n \"deleting it now would destroy them unreviewed. Re-run the command to see the current list.\",\n );\n}\n\n/** Asks the operator to confirm, naming the affected projects and their fate. */\nasync function confirmDeletion(\n user: string,\n projects: ProjectIdentityWithLabel[],\n flags: { moveProjectsTo?: string; force?: boolean },\n): Promise<boolean> {\n if (flags.force) return true;\n\n const fate = flags.moveProjectsTo\n ? `${projects.length} project(s) will move to \"${flags.moveProjectsTo}\"`\n : projects.length > 0\n ? `${projects.length} project(s) will be PERMANENTLY DELETED`\n : \"the account owns no projects\";\n\n process.stderr.write(`Delete user \"${user}\"? ${fate}.\\n`);\n if (projects.length > 0) {\n process.stderr.write(projects.map((p) => ` - ${p.label}`).join(\"\\n\") + \"\\n\");\n }\n\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await new Promise<string>((resolve) => {\n rl.question(\"Proceed? [y/N] \", resolve);\n });\n return answer.toLowerCase() === \"y\";\n } finally {\n rl.close();\n }\n}\n\nfunction renderResult(\n user: string,\n movedTo: string | undefined,\n moved: MovedProject[],\n projects: ProjectIdentityWithLabel[],\n): string {\n const lines: string[] = [];\n\n if (movedTo) {\n if (moved.length > 0) {\n lines.push(`Moved ${moved.length} project(s) from ${user} to ${movedTo}:`);\n lines.push(\n formatTable(\n [\"id\", \"name\", \"name in target\"],\n moved.map((p) => [p.id, p.sourceLabel, p.targetLabel]),\n ),\n );\n } else {\n lines.push(`User ${user} had no projects to move.`);\n }\n } else if (projects.length > 0) {\n lines.push(`Deleted ${projects.length} project(s) belonging to ${user}:`);\n lines.push(projects.map((p) => ` - ${p.label}`).join(\"\\n\"));\n }\n\n lines.push(`Deleted user \"${user}\".`);\n return lines.join(\"\\n\");\n}\n","import { Command } from \"commander\";\nimport { InstanceStatsContextTypeName, parseInstanceStats } from \"@milaboratories/pl-middle-layer\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, GlobalOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputJson } from \"../../output\";\n\nexport default function adminInstanceStatsCommand(): Command {\n const cmd = new Command(\"instance-stats\").description(\"Show the instance statistics as JSON.\");\n addOptions(cmd, GlobalOptions(), AdminAuthOptions());\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const [context] = await pl.listSharedResourcesByType(InstanceStatsContextTypeName);\n if (context === undefined) throw new Error(\"The instance has no instance statistics.\");\n const kvs = await pl.withReadTx(\"instanceStats\", (tx) => tx.listKeyValuesString(context));\n outputJson(parseInstanceStats(kvs));\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import {\n asSignedResourceId,\n createSignedResourceId,\n isLocalResourceId,\n resourceIdFromString,\n type SignedResourceId,\n} from \"@milaboratories/pl-client\";\n\n/**\n * Admin and controller roles do not need resource signatures: an ID without a signature\n * is accepted by the backend for these roles.\n */\nexport function parseResourceId(raw: string): SignedResourceId {\n const str = raw.trim();\n if (str.includes(\"|\")) return asSignedResourceId(str);\n\n let id: bigint | undefined = resourceIdFromString(str);\n if (id === undefined && /^\\d+$/.test(str)) id = BigInt(str);\n if (id === undefined || id === 0n || isLocalResourceId(id))\n throw new Error(`not a global resource ID: ${raw}`);\n\n return createSignedResourceId(id);\n}\n","import { once } from \"node:events\";\nimport { Command, InvalidArgumentError, Option } from \"commander\";\nimport {\n isNotNullSignedResourceId,\n resourceIdToString,\n resourceType,\n resourceTypeToString,\n type FieldData,\n type KeyValue,\n type OptionalSignedResourceId,\n type ResourceData,\n type ResourceType,\n} from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, AddressOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { parseResourceId } from \"../../resource_id\";\n\nexport default function maintenanceListResourcesCommand(): Command {\n const cmd = new Command(\"list-resources\").description(\n \"List resources of one type as JSON lines, in ascending order of resource ID. \" +\n \"Resource data and key-value values are printed as JSON when they are valid JSON, \" +\n 'as text when they are valid UTF-8, and as {\"base64\": ...} in other cases. ' +\n \"Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, AddressOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\"--type <name:version>\", \"Resource type to list (e.g. 'Blob/work:1')\")\n .argParser(parseResourceTypeArg)\n .makeOptionMandatory(),\n );\n cmd.addOption(\n new Option(\"--limit <n>\", \"Maximum number of resources to list. 0 lists all resources\")\n .argParser(parseNonNegativeInt)\n .default(0),\n );\n cmd.addOption(\n new Option(\n \"--after <resource-id>\",\n \"List only resources with IDs greater than this ID. \" +\n \"To get the next page, give the ID of the last resource of the previous page\",\n ).argParser(parseResourceId),\n );\n cmd.option(\n \"--load-fields\",\n \"Load the fields and the error of each resource ('fields' and 'error' keys)\",\n false,\n );\n cmd.option(\"--load-kv\", \"Load the key-value entries of each resource ('kv' key)\", false);\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const resources = await pl.withReadTx(\"listResources\", async (tx) => {\n const list = await tx.listResourcesByType(flags.type, {\n limit: flags.limit,\n after: flags.after,\n loadFields: flags.loadFields,\n });\n return await Promise.all(\n list.map(async (resource) => ({\n resource,\n kv: flags.loadKv ? await tx.listKeyValues(resource.id) : undefined,\n })),\n );\n });\n\n for (const { resource, kv } of resources) {\n const line = JSON.stringify(toJson(resource, flags.loadFields, kv)) + \"\\n\";\n // Wait for a slow reader: else the output collects in memory a second time.\n if (!process.stdout.write(line)) await once(process.stdout, \"drain\");\n }\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n\nfunction toJson(\n r: ResourceData,\n withFields: boolean,\n kv: KeyValue[] | undefined,\n): Record<string, unknown> {\n return {\n id: resourceIdToString(r.id),\n type: resourceTypeToString(r.type),\n kind: r.kind,\n originalId: optionalIdToString(r.originalResourceId),\n inputsLocked: r.inputsLocked,\n outputsLocked: r.outputsLocked,\n ready: r.resourceReady,\n final: r.final,\n data: r.data === undefined || r.data.length === 0 ? null : decodeBytes(r.data),\n // The backend sends the resource error as a field: without fields it is not known.\n ...(withFields\n ? { error: optionalIdToString(r.error), fields: r.fields.map(fieldToJson) }\n : {}),\n ...(kv === undefined\n ? {}\n : { kv: Object.fromEntries(kv.map((e) => [e.key, decodeBytes(e.value)])) }),\n };\n}\n\nfunction fieldToJson(f: FieldData): Record<string, unknown> {\n return {\n name: f.name,\n type: f.type,\n status: f.status,\n value: optionalIdToString(f.value),\n error: optionalIdToString(f.error),\n valueIsFinal: f.valueIsFinal,\n };\n}\n\nfunction optionalIdToString(id: OptionalSignedResourceId): string | null {\n return isNotNullSignedResourceId(id) ? resourceIdToString(id) : null;\n}\n\n/** JSON value when the bytes are valid JSON, text when valid UTF-8, {\"base64\": ...} otherwise. */\nfunction decodeBytes(bytes: Uint8Array): unknown {\n let text: string;\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch {\n return { base64: Buffer.from(bytes).toString(\"base64\") };\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction parseResourceTypeArg(value: string): ResourceType {\n const sep = value.lastIndexOf(\":\");\n if (sep <= 0 || sep === value.length - 1)\n throw new InvalidArgumentError(`expected <name>:<version>, e.g. 'Blob/work:1': ${value}`);\n return resourceType(value.slice(0, sep), value.slice(sep + 1));\n}\n\nfunction parseNonNegativeInt(value: string): number {\n const n = Number(value);\n if (!Number.isInteger(n) || n < 0)\n throw new InvalidArgumentError(`not a non-negative integer: ${value}`);\n return n;\n}\n","import { Command, Option } from \"commander\";\nimport { isNotNullSignedResourceId, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../base_command\";\nimport { addOptions, AddressOptions, AdminAuthOptions } from \"../../cmd-opts\";\nimport { outputText } from \"../../output\";\nimport { parseResourceId } from \"../../resource_id\";\n\nconst DefaultErrorMessage =\n \"Manual error set by administrator to trigger blocks re-run. \" +\n \"Run block once again to get rid of it.\";\n\nexport default function maintenanceSetResourceErrorCommand(): Command {\n const cmd = new Command(\"set-resource-error\").description(\n \"Put an error on one or more resources in a single transaction. \" +\n \"Resources that already have an error are skipped. \" +\n \"Requires admin/controller credentials.\",\n );\n\n cmd.argument(\n \"<resource-id...>\",\n \"Resource IDs: as printed by the server (NG:0x1A2B), as decimal numbers, \" +\n \"or as signed IDs (<decimal ID>|<signature hex>)\",\n );\n addOptions(cmd, AddressOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\"-m, --error-message <message>\", \"Error message to put on the resources\").default(\n DefaultErrorMessage,\n ),\n );\n cmd.option(\n \"--skip-missing\",\n \"Skip resources that do not exist instead of failing the whole transaction\",\n false,\n );\n\n cmd.action(async (rawIds: string[], flags) => {\n // Parse all IDs before the connection, so that a typo does not leave a half-done job.\n const ids = rawIds.map(parseResourceId);\n\n const pl = await connectClient(flags);\n try {\n const result = await pl.withWriteTx(\"setResourceError\", async (tx) => {\n const found = await Promise.all(\n ids.map(async (id) => ({\n id,\n data: flags.skipMissing\n ? await tx.getResourceDataIfExists(id, true)\n : await tx.getResourceData(id, true, true),\n })),\n );\n\n const missing = found.filter((r) => r.data === undefined).map((r) => r.id);\n const resources = found.flatMap((r) => (r.data === undefined ? [] : [r.data]));\n const targets = resources.filter((r) => !isNotNullSignedResourceId(r.error));\n const skipped = resources.filter((r) => isNotNullSignedResourceId(r.error));\n\n if (targets.length > 0) {\n // One error resource for all targets: the backend links it to each target separately.\n const error = tx.createError(flags.errorMessage);\n for (const r of targets) tx.setResourceError(r.id, error);\n await tx.commit();\n }\n\n return { targets, skipped, missing };\n });\n\n for (const id of result.missing)\n outputText(`skipped ${resourceIdToString(id)}: resource does not exist`);\n for (const r of result.skipped)\n outputText(`skipped ${resourceIdToString(r.id)}: resource already has an error`);\n for (const r of result.targets) outputText(`error set ${resourceIdToString(r.id)}`);\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import type { PlTransaction } from \"@milaboratories/pl-client\";\n\n/**\n * Key of the resources fixup level in the key-value store of a controller.\n * Must match MetadataResourcesFixupLevel in the backend (controllers/shared/ctlsdk/resources_fixup.go).\n */\nexport const ResourcesFixupLevelKey = \"ctl/ctlsdk/resourcesFixupLevel\";\n\n/** The backend keeps the level as a big-endian uint32. */\nconst ResourcesFixupLevelSize = 4;\n\n/** Reads the resources fixup level of the controller as text: a number, \"not set\" or \"invalid\". */\nexport async function readFixupLevel(tx: PlTransaction, controllerType: string): Promise<string> {\n const value = await tx.getControllerKValueIfExists(controllerType, ResourcesFixupLevelKey);\n if (value === undefined) return \"not set\";\n if (value.length !== ResourcesFixupLevelSize) return `invalid (${value.length} bytes)`;\n return String(Buffer.from(value).readUInt32BE(0));\n}\n\n/** Sets the resources fixup level of the controller to 0. The transaction must be writable. */\nexport function resetFixupLevel(tx: PlTransaction, controllerType: string): void {\n tx.setControllerKValue(\n controllerType,\n ResourcesFixupLevelKey,\n new Uint8Array(ResourcesFixupLevelSize),\n );\n}\n","import { Command } from \"commander\";\nimport { listRegisteredControllers, resourceIdToString } from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../../base_command\";\nimport { addOptions, AdminAuthOptions, GlobalOptions } from \"../../../cmd-opts\";\nimport { formatTable, outputCsv, outputJson, outputText } from \"../../../output\";\nimport { readFixupLevel } from \"./fixup_level\";\n\nexport default function maintenanceControllerListCommand(): Command {\n const cmd = new Command(\"list\").description(\n \"List the controllers registered in the backend, with their IDs and resources fixup levels. \" +\n \"Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, GlobalOptions(\"text\", [\"text\", \"json\", \"csv\"]), AdminAuthOptions());\n\n cmd.action(async (flags) => {\n const pl = await connectClient(flags);\n try {\n const controllers = await pl.withReadTx(\"listControllers\", async (tx) => {\n const list = await listRegisteredControllers(tx);\n return await Promise.all(\n list.map(async (c) => ({\n id: resourceIdToString(c.id),\n type: c.type,\n fixupLevel: await readFixupLevel(tx, c.type),\n })),\n );\n });\n\n const headers = [\"id\", \"type\", \"fixup level\"];\n const rows = controllers.map((c) => [c.id, c.type, c.fixupLevel]);\n if (flags.format === \"json\") outputJson(controllers);\n else if (flags.format === \"csv\") outputCsv(headers, rows);\n else outputText(formatTable(headers, rows));\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n","import { Command, Option } from \"commander\";\nimport {\n anyResourceIdToBigint,\n listRegisteredControllers,\n resourceIdToString,\n type PlTransaction,\n type RegisteredController,\n type SignedResourceId,\n} from \"@milaboratories/pl-client\";\nimport { connectClient } from \"../../../base_command\";\nimport { addOptions, AddressOptions, AdminAuthOptions } from \"../../../cmd-opts\";\nimport { outputText } from \"../../../output\";\nimport { parseResourceId } from \"../../../resource_id\";\nimport { readFixupLevel, resetFixupLevel } from \"./fixup_level\";\n\nfunction collect<T>(parse: (raw: string) => T) {\n return (raw: string, previous: T[] | undefined): T[] => [...(previous ?? []), parse(raw)];\n}\n\nexport default function maintenanceControllerRerunFixupsCommand(): Command {\n const cmd = new Command(\"rerun-fixups\").description(\n \"Set the resources fixup level of the selected controllers to 0 in a single transaction. \" +\n \"On its next start, each controller applies all its one-time resources fixups again. \" +\n \"Use this after a rollback to a backend version without resources fixups. \" +\n \"Select controllers with --controller-name and --controller-id \" +\n \"(see 'maintenance controller list'). Requires admin/controller credentials.\",\n );\n\n addOptions(cmd, AddressOptions(), AdminAuthOptions());\n cmd.addOption(\n new Option(\n \"--controller-name <type>\",\n 'Controller type, as the controller registers it (for example \"File/Manager\"). ' +\n \"Repeat the option to select more controllers\",\n ).argParser(collect((raw) => raw)),\n );\n cmd.addOption(\n new Option(\n \"--controller-id <resource-id>\",\n \"Controller ID, as 'maintenance controller list' prints it. \" +\n \"Repeat the option to select more controllers\",\n ).argParser(collect(parseResourceId)),\n );\n\n cmd.action(async (flags) => {\n const names: string[] = flags.controllerName ?? [];\n const ids: SignedResourceId[] = flags.controllerId ?? [];\n if (names.length === 0 && ids.length === 0)\n throw new Error(\"select at least one controller with --controller-name or --controller-id\");\n\n const pl = await connectClient(flags);\n try {\n const reset = await pl.withWriteTx(\"rerunControllerFixups\", async (tx) => {\n const selected = await selectControllers(tx, names, ids);\n const levels = await Promise.all(\n selected.map(async (c) => ({ controller: c, level: await readFixupLevel(tx, c.type) })),\n );\n\n for (const c of selected) resetFixupLevel(tx, c.type);\n await tx.commit();\n\n return levels;\n });\n\n for (const { controller, level } of reset)\n outputText(\n `${controller.type} (${resourceIdToString(controller.id)}): ` +\n `resources fixup level ${level} -> 0`,\n );\n outputText(\"Restart the backend to apply the resources fixups.\");\n } finally {\n await pl.close();\n }\n });\n\n return cmd;\n}\n\n/** Resolves the selected controllers. Throws when a name or an ID matches no registered controller. */\nasync function selectControllers(\n tx: PlTransaction,\n names: string[],\n ids: SignedResourceId[],\n): Promise<RegisteredController[]> {\n const registered = await listRegisteredControllers(tx);\n const byType = new Map<string, RegisteredController>();\n\n for (const name of names) {\n const controller = registered.find((c) => c.type === name);\n if (controller === undefined) throw new Error(`controller \"${name}\" is not registered`);\n byType.set(controller.type, controller);\n }\n\n for (const id of ids) {\n const wanted = anyResourceIdToBigint(id);\n const controller = registered.find((c) => anyResourceIdToBigint(c.id) === wanted);\n if (controller === undefined)\n throw new Error(`no registered controller has ID ${resourceIdToString(id)}`);\n byType.set(controller.type, controller);\n }\n\n return [...byType.values()];\n}\n","import { Command } from \"commander\";\nimport projectListCommand from \"./cmd/project/list\";\nimport projectInfoCommand from \"./cmd/project/info\";\nimport projectDuplicateCommand from \"./cmd/project/duplicate\";\nimport projectRenameCommand from \"./cmd/project/rename\";\nimport projectDeleteCommand from \"./cmd/project/delete\";\nimport adminCopyProjectCommand from \"./cmd/admin/copy-project\";\nimport adminUserListCommand from \"./cmd/admin/user-list\";\nimport adminDeleteUserCommand from \"./cmd/admin/delete-user\";\nimport adminInstanceStatsCommand from \"./cmd/admin/instance-stats\";\nimport maintenanceListResourcesCommand from \"./cmd/maintenance/list-resources\";\nimport maintenanceSetResourceErrorCommand from \"./cmd/maintenance/set-resource-error\";\nimport maintenanceControllerListCommand from \"./cmd/maintenance/controller/list\";\nimport maintenanceControllerRerunFixupsCommand from \"./cmd/maintenance/controller/rerun-fixups\";\n\nexport function buildProgram(): Command {\n const program = new Command();\n program.name(\"pl-cli\").description(\"Platforma command-line client\");\n\n const project = new Command(\"project\").description(\"Manage projects\");\n project.addCommand(projectListCommand());\n project.addCommand(projectInfoCommand());\n project.addCommand(projectDuplicateCommand());\n project.addCommand(projectRenameCommand());\n project.addCommand(projectDeleteCommand());\n program.addCommand(project);\n\n const admin = new Command(\"admin\").description(\n \"Admin operations (requires controller credentials)\",\n );\n admin.addCommand(adminCopyProjectCommand());\n admin.addCommand(adminUserListCommand());\n admin.addCommand(adminDeleteUserCommand());\n admin.addCommand(adminInstanceStatsCommand());\n program.addCommand(admin);\n\n const maintenance = new Command(\"maintenance\").description(\n \"Low-level server state repair (requires admin/controller credentials)\",\n );\n maintenance.addCommand(maintenanceListResourcesCommand());\n maintenance.addCommand(maintenanceSetResourceErrorCommand());\n const controller = new Command(\"controller\").description(\n \"Inspect registered controllers and their resources fixups\",\n );\n controller.addCommand(maintenanceControllerListCommand());\n controller.addCommand(maintenanceControllerRerunFixupsCommand());\n maintenance.addCommand(controller);\n program.addCommand(maintenance);\n\n return program;\n}\n\nexport async function run(argv: string[] = process.argv): Promise<void> {\n await buildProgram().parseAsync(argv);\n}\n"],"mappings":";;;;;;;;AAUA,eAAsBmB,EAAc,GAMd;CAQpB,OAPIC,EAAM,aAAaA,EAAM,gBACpBlB,EAAwB;EAC7B,SAASkB,EAAM;EACf,WAAWA,EAAM;EACjB,eAAeA,EAAM;CACvB,CAAC,IAEIH,GAAmB;EACxB,SAASG,EAAM;EACf,MAAMA,EAAM;EACZ,UAAUA,EAAM;CAClB,CAAC;AACH;AASA,eAAsBC,EAAQ,GAOkC;CAC9D,IAAMC,IAAe,CAAC,CAACF,EAAM,WACvBG,IAAmB,CAAC,CAACH,EAAM,eAC3BI,IAAY,CAAC,CAACJ,EAAM;CAG1B,IAAII,KAAa,EAAEF,KAAgBC,IACjC,MAAU,MAAM,0DAA0D;CAE5E,KAAKD,KAAgBC,MAAqB,CAACC,GACzC,MAAU,MAAM,0EAA0E;CAG5F,IAAMC,IAAK,MAAMN,EAAcC,CAAK,GAEhCM;CAQJ,OAPA,AAIEA,IAJEF,KAEe,MADClB,EAAmBmB,GAAIL,EAAM,UAAW,EAAA,CACrC,iBAEJ,MAAMf,EAAkBoB,CAAE,GAGtC;EAAE;EAAI;CAAe;AAC9B;;ACjEA,SAAgBE,EAAW,GAAc,GAAGC,GAAmC;CAC7E,KAAK,IAAMC,KAASD,GAClB,KAAK,IAAME,KAAOD,GAAO,EAAI,UAAUC,CAAG;CAE5C,OAAOC;AACT;AAGA,IAAaC,UAAiC,CAC5C,IAAIC,EAAO,uBAAuB,0BAA0B,CAAC,CAC1D,IAAI,YAAY,CAAC,CACjB,oBAAoB,CACzB,GAEaC,KACX,IAA8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WAAWK,EAAwB,CAAC,GAC5CL,EAAQ,WAAWmB,EAAqB,CAAC,GACzCnB,EAAQ,WAAWoB,EAAqB,CAAC,GACzCyG,EAAQ,WAAW7H,CAAO;CAE1B,IAAM8H,IAAQ,IAAInI,EAAQ,OAAO,CAAC,CAAC,YACjC,oDACF;CAKA,AAJAmI,EAAM,WAAWrG,EAAwB,CAAC,GAC1CqG,EAAM,WAAWhG,GAAqB,CAAC,GACvCgG,EAAM,WAAW5F,GAAuB,CAAC,GACzC4F,EAAM,WAAW3E,GAA0B,CAAC,GAC5C0E,EAAQ,WAAWC,CAAK;CAExB,IAAMC,IAAc,IAAIpI,EAAQ,aAAa,CAAC,CAAC,YAC7C,uEACF;CAEA,AADAoI,EAAY,WAAWhE,GAAgC,CAAC,GACxDgE,EAAY,WAAWtC,GAAmC,CAAC;CAC3D,IAAM4B,IAAa,IAAI1H,EAAQ,YAAY,CAAC,CAAC,YAC3C,2DACF;CAMA,OALA0H,EAAW,WAAWf,GAAiC,CAAC,GACxDe,EAAW,WAAWN,GAAwC,CAAC,GAC/DgB,EAAY,WAAWV,CAAU,GACjCQ,EAAQ,WAAWE,CAAW,GAEvBF;AACT;AAEA,eAAsBG,GAAI,IAAiB,QAAQ,MAAqB;CACtE,MAAMJ,EAAa,CAAC,CAAC,WAAWK,CAAI;AACtC"}
@@ -0,0 +1,10 @@
1
+ import { PlTransaction } from '@milaboratories/pl-client';
2
+ /**
3
+ * Key of the resources fixup level in the key-value store of a controller.
4
+ * Must match MetadataResourcesFixupLevel in the backend (controllers/shared/ctlsdk/resources_fixup.go).
5
+ */
6
+ export declare const ResourcesFixupLevelKey = "ctl/ctlsdk/resourcesFixupLevel";
7
+ /** Reads the resources fixup level of the controller as text: a number, "not set" or "invalid". */
8
+ export declare function readFixupLevel(tx: PlTransaction, controllerType: string): Promise<string>;
9
+ /** Sets the resources fixup level of the controller to 0. The transaction must be writable. */
10
+ export declare function resetFixupLevel(tx: PlTransaction, controllerType: string): void;
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export default function maintenanceControllerListCommand(): Command;
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export default function maintenanceControllerRerunFixupsCommand(): Command;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@platforma-sdk/pl-cli",
3
- "version": "0.11.4",
3
+ "version": "0.12.0",
4
4
  "description": "CLI for Platforma server state manipulation",
5
5
  "license": "UNLICENSED",
6
6
  "bin": {
@@ -22,8 +22,8 @@
22
22
  }
23
23
  },
24
24
  "dependencies": {
25
- "@milaboratories/pl-client": "3.23.0",
26
- "@milaboratories/pl-middle-layer": "2.6.1",
25
+ "@milaboratories/pl-client": "3.24.0",
26
+ "@milaboratories/pl-middle-layer": "2.6.2",
27
27
  "commander": "^15.0.0"
28
28
  },
29
29
  "devDependencies": {
package/src/cli.ts CHANGED
@@ -10,6 +10,8 @@ import adminDeleteUserCommand from "./cmd/admin/delete-user";
10
10
  import adminInstanceStatsCommand from "./cmd/admin/instance-stats";
11
11
  import maintenanceListResourcesCommand from "./cmd/maintenance/list-resources";
12
12
  import maintenanceSetResourceErrorCommand from "./cmd/maintenance/set-resource-error";
13
+ import maintenanceControllerListCommand from "./cmd/maintenance/controller/list";
14
+ import maintenanceControllerRerunFixupsCommand from "./cmd/maintenance/controller/rerun-fixups";
13
15
 
14
16
  export function buildProgram(): Command {
15
17
  const program = new Command();
@@ -37,6 +39,12 @@ export function buildProgram(): Command {
37
39
  );
38
40
  maintenance.addCommand(maintenanceListResourcesCommand());
39
41
  maintenance.addCommand(maintenanceSetResourceErrorCommand());
42
+ const controller = new Command("controller").description(
43
+ "Inspect registered controllers and their resources fixups",
44
+ );
45
+ controller.addCommand(maintenanceControllerListCommand());
46
+ controller.addCommand(maintenanceControllerRerunFixupsCommand());
47
+ maintenance.addCommand(controller);
40
48
  program.addCommand(maintenance);
41
49
 
42
50
  return program;
@@ -0,0 +1,27 @@
1
+ import type { PlTransaction } from "@milaboratories/pl-client";
2
+
3
+ /**
4
+ * Key of the resources fixup level in the key-value store of a controller.
5
+ * Must match MetadataResourcesFixupLevel in the backend (controllers/shared/ctlsdk/resources_fixup.go).
6
+ */
7
+ export const ResourcesFixupLevelKey = "ctl/ctlsdk/resourcesFixupLevel";
8
+
9
+ /** The backend keeps the level as a big-endian uint32. */
10
+ const ResourcesFixupLevelSize = 4;
11
+
12
+ /** Reads the resources fixup level of the controller as text: a number, "not set" or "invalid". */
13
+ export async function readFixupLevel(tx: PlTransaction, controllerType: string): Promise<string> {
14
+ const value = await tx.getControllerKValueIfExists(controllerType, ResourcesFixupLevelKey);
15
+ if (value === undefined) return "not set";
16
+ if (value.length !== ResourcesFixupLevelSize) return `invalid (${value.length} bytes)`;
17
+ return String(Buffer.from(value).readUInt32BE(0));
18
+ }
19
+
20
+ /** Sets the resources fixup level of the controller to 0. The transaction must be writable. */
21
+ export function resetFixupLevel(tx: PlTransaction, controllerType: string): void {
22
+ tx.setControllerKValue(
23
+ controllerType,
24
+ ResourcesFixupLevelKey,
25
+ new Uint8Array(ResourcesFixupLevelSize),
26
+ );
27
+ }
@@ -0,0 +1,41 @@
1
+ import { Command } from "commander";
2
+ import { listRegisteredControllers, resourceIdToString } from "@milaboratories/pl-client";
3
+ import { connectClient } from "../../../base_command";
4
+ import { addOptions, AdminAuthOptions, GlobalOptions } from "../../../cmd-opts";
5
+ import { formatTable, outputCsv, outputJson, outputText } from "../../../output";
6
+ import { readFixupLevel } from "./fixup_level";
7
+
8
+ export default function maintenanceControllerListCommand(): Command {
9
+ const cmd = new Command("list").description(
10
+ "List the controllers registered in the backend, with their IDs and resources fixup levels. " +
11
+ "Requires admin/controller credentials.",
12
+ );
13
+
14
+ addOptions(cmd, GlobalOptions("text", ["text", "json", "csv"]), AdminAuthOptions());
15
+
16
+ cmd.action(async (flags) => {
17
+ const pl = await connectClient(flags);
18
+ try {
19
+ const controllers = await pl.withReadTx("listControllers", async (tx) => {
20
+ const list = await listRegisteredControllers(tx);
21
+ return await Promise.all(
22
+ list.map(async (c) => ({
23
+ id: resourceIdToString(c.id),
24
+ type: c.type,
25
+ fixupLevel: await readFixupLevel(tx, c.type),
26
+ })),
27
+ );
28
+ });
29
+
30
+ const headers = ["id", "type", "fixup level"];
31
+ const rows = controllers.map((c) => [c.id, c.type, c.fixupLevel]);
32
+ if (flags.format === "json") outputJson(controllers);
33
+ else if (flags.format === "csv") outputCsv(headers, rows);
34
+ else outputText(formatTable(headers, rows));
35
+ } finally {
36
+ await pl.close();
37
+ }
38
+ });
39
+
40
+ return cmd;
41
+ }
@@ -0,0 +1,103 @@
1
+ import { Command, Option } from "commander";
2
+ import {
3
+ anyResourceIdToBigint,
4
+ listRegisteredControllers,
5
+ resourceIdToString,
6
+ type PlTransaction,
7
+ type RegisteredController,
8
+ type SignedResourceId,
9
+ } from "@milaboratories/pl-client";
10
+ import { connectClient } from "../../../base_command";
11
+ import { addOptions, AddressOptions, AdminAuthOptions } from "../../../cmd-opts";
12
+ import { outputText } from "../../../output";
13
+ import { parseResourceId } from "../../../resource_id";
14
+ import { readFixupLevel, resetFixupLevel } from "./fixup_level";
15
+
16
+ function collect<T>(parse: (raw: string) => T) {
17
+ return (raw: string, previous: T[] | undefined): T[] => [...(previous ?? []), parse(raw)];
18
+ }
19
+
20
+ export default function maintenanceControllerRerunFixupsCommand(): Command {
21
+ const cmd = new Command("rerun-fixups").description(
22
+ "Set the resources fixup level of the selected controllers to 0 in a single transaction. " +
23
+ "On its next start, each controller applies all its one-time resources fixups again. " +
24
+ "Use this after a rollback to a backend version without resources fixups. " +
25
+ "Select controllers with --controller-name and --controller-id " +
26
+ "(see 'maintenance controller list'). Requires admin/controller credentials.",
27
+ );
28
+
29
+ addOptions(cmd, AddressOptions(), AdminAuthOptions());
30
+ cmd.addOption(
31
+ new Option(
32
+ "--controller-name <type>",
33
+ 'Controller type, as the controller registers it (for example "File/Manager"). ' +
34
+ "Repeat the option to select more controllers",
35
+ ).argParser(collect((raw) => raw)),
36
+ );
37
+ cmd.addOption(
38
+ new Option(
39
+ "--controller-id <resource-id>",
40
+ "Controller ID, as 'maintenance controller list' prints it. " +
41
+ "Repeat the option to select more controllers",
42
+ ).argParser(collect(parseResourceId)),
43
+ );
44
+
45
+ cmd.action(async (flags) => {
46
+ const names: string[] = flags.controllerName ?? [];
47
+ const ids: SignedResourceId[] = flags.controllerId ?? [];
48
+ if (names.length === 0 && ids.length === 0)
49
+ throw new Error("select at least one controller with --controller-name or --controller-id");
50
+
51
+ const pl = await connectClient(flags);
52
+ try {
53
+ const reset = await pl.withWriteTx("rerunControllerFixups", async (tx) => {
54
+ const selected = await selectControllers(tx, names, ids);
55
+ const levels = await Promise.all(
56
+ selected.map(async (c) => ({ controller: c, level: await readFixupLevel(tx, c.type) })),
57
+ );
58
+
59
+ for (const c of selected) resetFixupLevel(tx, c.type);
60
+ await tx.commit();
61
+
62
+ return levels;
63
+ });
64
+
65
+ for (const { controller, level } of reset)
66
+ outputText(
67
+ `${controller.type} (${resourceIdToString(controller.id)}): ` +
68
+ `resources fixup level ${level} -> 0`,
69
+ );
70
+ outputText("Restart the backend to apply the resources fixups.");
71
+ } finally {
72
+ await pl.close();
73
+ }
74
+ });
75
+
76
+ return cmd;
77
+ }
78
+
79
+ /** Resolves the selected controllers. Throws when a name or an ID matches no registered controller. */
80
+ async function selectControllers(
81
+ tx: PlTransaction,
82
+ names: string[],
83
+ ids: SignedResourceId[],
84
+ ): Promise<RegisteredController[]> {
85
+ const registered = await listRegisteredControllers(tx);
86
+ const byType = new Map<string, RegisteredController>();
87
+
88
+ for (const name of names) {
89
+ const controller = registered.find((c) => c.type === name);
90
+ if (controller === undefined) throw new Error(`controller "${name}" is not registered`);
91
+ byType.set(controller.type, controller);
92
+ }
93
+
94
+ for (const id of ids) {
95
+ const wanted = anyResourceIdToBigint(id);
96
+ const controller = registered.find((c) => anyResourceIdToBigint(c.id) === wanted);
97
+ if (controller === undefined)
98
+ throw new Error(`no registered controller has ID ${resourceIdToString(id)}`);
99
+ byType.set(controller.type, controller);
100
+ }
101
+
102
+ return [...byType.values()];
103
+ }