@diafunc/cli 0.11.0 → 0.13.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.
@@ -1,10 +1,9 @@
1
1
  import {
2
2
  package_default
3
- } from "./chunk-Q7HG2CUO.js";
3
+ } from "./chunk-TWJWXUZL.js";
4
4
 
5
5
  // src/index.ts
6
- import { Command } from "commander";
7
- import chalk35 from "chalk";
6
+ import chalk36 from "chalk";
8
7
 
9
8
  // src/commands/auth/login.ts
10
9
  import chalk4 from "chalk";
@@ -108,8 +107,8 @@ var ApiError = class _ApiError extends Error {
108
107
  return withDetails;
109
108
  }
110
109
  };
111
- function looksLikeMarkup(text) {
112
- const head = text.trimStart().slice(0, 200).toLowerCase();
110
+ function looksLikeMarkup(text2) {
111
+ const head = text2.trimStart().slice(0, 200).toLowerCase();
113
112
  return head.startsWith("<") || head.includes("<html") || head.includes("<!doctype");
114
113
  }
115
114
  var NetworkError = class extends Error {
@@ -214,8 +213,8 @@ async function parseErrorBody(response) {
214
213
  const body = await response.json();
215
214
  return ApiError.fromBody(response.status, body);
216
215
  }
217
- const text = (await response.text()).trim();
218
- return new ApiError(response.status, text || response.statusText);
216
+ const text2 = (await response.text()).trim();
217
+ return new ApiError(response.status, text2 || response.statusText);
219
218
  } catch {
220
219
  return new ApiError(response.status, response.statusText);
221
220
  }
@@ -324,11 +323,11 @@ ${bodyPreview}`));
324
323
  return void 0;
325
324
  }
326
325
  const contentType = response.headers.get("content-type") ?? "";
327
- const text = await response.text();
326
+ const text2 = await response.text();
328
327
  if (contentType.includes("application/json")) {
329
- return text ? JSON.parse(text) : void 0;
328
+ return text2 ? JSON.parse(text2) : void 0;
330
329
  }
331
- return text;
330
+ return text2;
332
331
  },
333
332
  async requestRaw(opts) {
334
333
  const response = await doRequest(opts);
@@ -812,9 +811,9 @@ function empty(noun, options) {
812
811
  }
813
812
  console.log(chalk2.dim(`No ${noun}.`));
814
813
  }
815
- function heading(text) {
814
+ function heading(text2) {
816
815
  console.log();
817
- console.log(chalk2.bold(text));
816
+ console.log(chalk2.bold(text2));
818
817
  }
819
818
 
820
819
  // src/util/errors.ts
@@ -916,8 +915,8 @@ async function deviceCodeLogin(config, profile) {
916
915
  body: new URLSearchParams({ client_id: DEVICE_CLIENT_ID, scope: DEVICE_SCOPE }).toString()
917
916
  });
918
917
  if (!deviceResponse.ok) {
919
- const text = await deviceResponse.text();
920
- failure(`Failed to start device-code flow: ${text || deviceResponse.statusText}`);
918
+ const text2 = await deviceResponse.text();
919
+ failure(`Failed to start device-code flow: ${text2 || deviceResponse.statusText}`);
921
920
  process.exit(1);
922
921
  }
923
922
  const device = await deviceResponse.json();
@@ -974,7 +973,7 @@ async function deviceCodeLogin(config, profile) {
974
973
  failure("Code expired before approval. Run `diafunc auth login` again.");
975
974
  process.exit(1);
976
975
  }
977
- failure(`Device-code flow failed: ${errorBody.error}${errorBody.error_description ? " \u2014 " + errorBody.error_description : ""}`);
976
+ failure(`Device-code flow failed: ${errorBody.error}${errorBody.error_description ? ": " + errorBody.error_description : ""}`);
978
977
  process.exit(1);
979
978
  }
980
979
  failure("Timed out waiting for approval.");
@@ -1078,22 +1077,22 @@ function terminalWidth() {
1078
1077
  if (!columns || !Number.isFinite(columns)) return 80;
1079
1078
  return Math.max(40, columns - 1);
1080
1079
  }
1081
- function displayWidth(text) {
1082
- return stripAnsi(text).length;
1080
+ function displayWidth(text2) {
1081
+ return stripAnsi(text2).length;
1083
1082
  }
1084
1083
  var ANSI_PATTERN = new RegExp("\\u001B\\[[0-9;]*m", "g");
1085
- function stripAnsi(text) {
1086
- return text.replace(ANSI_PATTERN, "");
1084
+ function stripAnsi(text2) {
1085
+ return text2.replace(ANSI_PATTERN, "");
1087
1086
  }
1088
- function truncate(text, width) {
1089
- const plain = stripAnsi(text);
1090
- if (plain.length <= width) return text;
1087
+ function truncate(text2, width) {
1088
+ const plain = stripAnsi(text2);
1089
+ if (plain.length <= width) return text2;
1091
1090
  if (width <= 1) return plain.slice(0, Math.max(0, width));
1092
1091
  return plain.slice(0, width - 1) + "\u2026";
1093
1092
  }
1094
- function wrap(text, width) {
1093
+ function wrap(text2, width) {
1095
1094
  const out = [];
1096
- for (const paragraph of text.split("\n")) {
1095
+ for (const paragraph of text2.split("\n")) {
1097
1096
  if (paragraph.length <= width) {
1098
1097
  out.push(paragraph);
1099
1098
  continue;
@@ -1121,7 +1120,7 @@ function wrap(text, width) {
1121
1120
  import chalk5 from "chalk";
1122
1121
  var ABSENT = "\u2014";
1123
1122
  function renderValue(value, kind = "text", plain = false) {
1124
- const dim = (text) => plain ? text : chalk5.dim(text);
1123
+ const dim = (text2) => plain ? text2 : chalk5.dim(text2);
1125
1124
  if (value === null || value === void 0 || value === "") return dim(ABSENT);
1126
1125
  switch (kind) {
1127
1126
  case "id":
@@ -1144,8 +1143,8 @@ function renderValue(value, kind = "text", plain = false) {
1144
1143
  }
1145
1144
  }
1146
1145
  function renderNumber(value, plain) {
1147
- const text = typeof value === "number" && !plain ? formatNumber(value) : String(value);
1148
- return plain ? text : chalk5.cyan(text);
1146
+ const text2 = typeof value === "number" && !plain ? formatNumber(value) : String(value);
1147
+ return plain ? text2 : chalk5.cyan(text2);
1149
1148
  }
1150
1149
  function renderArray(value, plain, dim) {
1151
1150
  if (value.length === 0) return dim(ABSENT);
@@ -1211,6 +1210,18 @@ function formatDuration(millis) {
1211
1210
  const days = Math.floor(hours / 24);
1212
1211
  return `${days}d ${hours % 24}h`;
1213
1212
  }
1213
+ function formatDurationPrecise(millis) {
1214
+ const total = Math.max(0, Math.trunc(millis));
1215
+ const days = Math.floor(total / 864e5);
1216
+ const hours = Math.floor(total / 36e5) % 24;
1217
+ const minutes = Math.floor(total / 6e4) % 60;
1218
+ const seconds = Math.floor(total / 1e3) % 60;
1219
+ if (days > 0) return hours > 0 ? `${days} d ${hours} h` : `${days} d`;
1220
+ if (hours > 0) return minutes > 0 ? `${hours} h ${minutes} min` : `${hours} h`;
1221
+ if (minutes > 0) return `${minutes} min`;
1222
+ if (seconds > 0) return `${seconds} sec`;
1223
+ return `${total} ms`;
1224
+ }
1214
1225
  var GOOD_STATES = /* @__PURE__ */ new Set([
1215
1226
  "COMPLETED",
1216
1227
  "SUCCEEDED",
@@ -1361,9 +1372,9 @@ function budgetWidths(specs, cells) {
1361
1372
  }
1362
1373
  return widths;
1363
1374
  }
1364
- function pad(text, width) {
1365
- const deficit = width - displayWidth(text);
1366
- return deficit > 0 ? text + " ".repeat(deficit) : text;
1375
+ function pad(text2, width) {
1376
+ const deficit = width - displayWidth(text2);
1377
+ return deficit > 0 ? text2 + " ".repeat(deficit) : text2;
1367
1378
  }
1368
1379
  function forPipe(value, spec) {
1369
1380
  const rendered = stripAnsi(renderValue(value, spec.kind ?? inferKind(spec.key), true));
@@ -2761,7 +2772,7 @@ function registerTokenCommands(parent) {
2761
2772
  console.log(` Name: ${result.name}`);
2762
2773
  console.log(` Expires: ${result.expiresAt}`);
2763
2774
  console.log();
2764
- console.log(chalk8.yellow("Save this token \u2014 it will not be shown again."));
2775
+ console.log(chalk8.yellow("Save this token. It will not be shown again."));
2765
2776
  } else {
2766
2777
  format(result, { format: outputFormat });
2767
2778
  }
@@ -2951,15 +2962,15 @@ import chalk12 from "chalk";
2951
2962
  // src/util/references.ts
2952
2963
  function parseEntityReference(ref, overrides) {
2953
2964
  const config = loadConfig();
2954
- const defaultProject = overrides?.project ?? config.defaults.project;
2965
+ const defaultProject2 = overrides?.project ?? config.defaults.project;
2955
2966
  const defaultBranch = overrides?.branch ?? config.defaults.branch ?? "main";
2956
2967
  if (!ref.includes("/") && ref.includes(":")) {
2957
2968
  const [entityId, entityBranch] = ref.split(":");
2958
- if (!defaultProject) {
2969
+ if (!defaultProject2) {
2959
2970
  throw new Error("No default project configured. Set one with: diafunc config set defaults.project <id>");
2960
2971
  }
2961
2972
  return {
2962
- projectId: defaultProject,
2973
+ projectId: defaultProject2,
2963
2974
  projectBranch: defaultBranch,
2964
2975
  entityId,
2965
2976
  entityBranch: entityBranch || defaultBranch
@@ -2967,11 +2978,11 @@ function parseEntityReference(ref, overrides) {
2967
2978
  }
2968
2979
  const parts = ref.split("/");
2969
2980
  if (parts.length === 1) {
2970
- if (!defaultProject) {
2981
+ if (!defaultProject2) {
2971
2982
  throw new Error("No default project configured. Set one with: diafunc config set defaults.project <id>");
2972
2983
  }
2973
2984
  return {
2974
- projectId: defaultProject,
2985
+ projectId: defaultProject2,
2975
2986
  projectBranch: defaultBranch,
2976
2987
  entityId: parts[0],
2977
2988
  entityBranch: defaultBranch
@@ -3015,11 +3026,11 @@ function parseEntityReference(ref, overrides) {
3015
3026
  }
3016
3027
  function parseProjectReference(ref, overrides) {
3017
3028
  const config = loadConfig();
3018
- const defaultProject = overrides?.project ?? config.defaults.project;
3029
+ const defaultProject2 = overrides?.project ?? config.defaults.project;
3019
3030
  const defaultBranch = overrides?.branch ?? config.defaults.branch ?? "main";
3020
3031
  if (!ref.includes("/")) {
3021
3032
  return {
3022
- projectId: ref || defaultProject,
3033
+ projectId: ref || defaultProject2,
3023
3034
  projectBranch: defaultBranch
3024
3035
  };
3025
3036
  }
@@ -3237,7 +3248,7 @@ async function pollUntilFinished(storage, projectId, projectBranch, bundleId, in
3237
3248
  status.stop();
3238
3249
  }
3239
3250
  throw new Error(
3240
- `Export ${bundleId} is still running after ${formatDuration(intervalMs * maxAttempts)} \u2014 check it with 'diafunc notebook bundles ${projectId}'`
3251
+ `Export ${bundleId} is still running after ${formatDuration(intervalMs * maxAttempts)}. Check it with 'diafunc notebook bundles ${projectId}'.`
3241
3252
  );
3242
3253
  }
3243
3254
  function progressLine(label, progress, elapsedMs) {
@@ -3266,6 +3277,28 @@ async function resolveLanguage(api, projectId, explicit) {
3266
3277
  return DEFAULT_FUNCTION_LANGUAGE;
3267
3278
  }
3268
3279
 
3280
+ // src/util/project-names.ts
3281
+ var FIRST_PAGE = 100;
3282
+ var CONCURRENCY = 8;
3283
+ async function projectNames(api, projectIds) {
3284
+ const wanted = new Set(projectIds);
3285
+ const names = /* @__PURE__ */ new Map();
3286
+ if (wanted.size === 0) return names;
3287
+ const take = (items) => {
3288
+ for (const item of items) {
3289
+ if (item.contentType !== "project" || !item.name || !wanted.has(item.projectId)) continue;
3290
+ if (!names.has(item.projectId)) names.set(item.projectId, item.name);
3291
+ }
3292
+ };
3293
+ take((await api.index.searchPage({ query: "*", contentType: "project", limit: FIRST_PAGE })).items);
3294
+ const missing = [...wanted].filter((id) => !names.has(id));
3295
+ for (let i = 0; i < missing.length; i += CONCURRENCY) {
3296
+ const pages = await Promise.all(missing.slice(i, i + CONCURRENCY).map((projectId) => api.index.searchPage({ query: "*", contentType: "project", projectId, projectBranch: "main", limit: 5 }).catch(() => null)));
3297
+ for (const page of pages) if (page) take(page.items);
3298
+ }
3299
+ return names;
3300
+ }
3301
+
3269
3302
  // src/commands/project/index.ts
3270
3303
  function getOutputFormat(cmd) {
3271
3304
  const config = loadConfig();
@@ -3283,9 +3316,6 @@ Examples:
3283
3316
  $ diafunc project list the twenty most recent
3284
3317
  $ diafunc project list --limit 0 every one of them
3285
3318
  $ diafunc search "housing" --type project find a project by name
3286
-
3287
- A project's name lives on its main entity rather than on the project row, so this listing shows
3288
- ids. Use 'diafunc search --type project' when you know the name but not the id.
3289
3319
  `).action(async (options, cmd) => {
3290
3320
  try {
3291
3321
  const outputFormat = getOutputFormat(cmd);
@@ -3293,9 +3323,17 @@ ids. Use 'diafunc search --type project' when you know the name but not the id.
3293
3323
  const projects = options.all ? await api.admin.getAllProjects() : await api.admin.getProjects();
3294
3324
  const limit = Number.parseInt(options.limit, 10);
3295
3325
  const capped = Number.isFinite(limit) && limit > 0 ? projects.slice(0, limit) : projects;
3296
- format(capped, {
3326
+ let names = /* @__PURE__ */ new Map();
3327
+ try {
3328
+ names = await projectNames(api, capped.map((p) => p.projectId));
3329
+ } catch {
3330
+ console.error(chalk12.dim("Project names are unavailable right now; showing ids."));
3331
+ }
3332
+ const rows = capped.map((p) => ({ name: names.get(p.projectId) ?? null, ...p }));
3333
+ format(rows, {
3297
3334
  format: outputFormat,
3298
3335
  columns: [
3336
+ { key: "name" },
3299
3337
  { key: "projectId", kind: "id" },
3300
3338
  { key: "teamName", header: "team" },
3301
3339
  { key: "visibility" },
@@ -3306,7 +3344,7 @@ ids. Use 'diafunc search --type project' when you know the name but not the id.
3306
3344
  ]
3307
3345
  });
3308
3346
  if (capped.length < projects.length) {
3309
- console.log(chalk12.dim(
3347
+ console.error(chalk12.dim(
3310
3348
  `
3311
3349
  Showing ${capped.length} of ${projects.length}. Pass --limit 0 to see them all.`
3312
3350
  ));
@@ -4066,8 +4104,8 @@ Examples:
4066
4104
  fs3.writeFileSync(options.out, buffer);
4067
4105
  success(`Content saved to ${options.out}`);
4068
4106
  } else {
4069
- const text = await response.text();
4070
- process.stdout.write(text);
4107
+ const text2 = await response.text();
4108
+ process.stdout.write(text2);
4071
4109
  }
4072
4110
  } catch (error) {
4073
4111
  handleError(error);
@@ -4267,8 +4305,8 @@ function registerEventCommands(program) {
4267
4305
  });
4268
4306
  event.command("create").description("Create one or more events (body from JSON file or stdin)").argument("[file]", "JSON file containing a BareEvent array; defaults to stdin").action(async (file) => {
4269
4307
  try {
4270
- const fs14 = await import("fs");
4271
- const body = file ? fs14.readFileSync(file, "utf-8") : await new Promise((resolve, reject) => {
4308
+ const fs15 = await import("fs");
4309
+ const body = file ? fs15.readFileSync(file, "utf-8") : await new Promise((resolve, reject) => {
4272
4310
  let data = "";
4273
4311
  process.stdin.setEncoding("utf-8");
4274
4312
  process.stdin.on("data", (chunk) => {
@@ -4420,6 +4458,77 @@ Examples:
4420
4458
  import chalk15 from "chalk";
4421
4459
  import * as fs4 from "fs";
4422
4460
  import * as path3 from "path";
4461
+
4462
+ // src/util/table-window.ts
4463
+ var WINDOW_MAX_ROWS = 100;
4464
+ var WINDOW_MAX_COLUMNS = 50;
4465
+ var WINDOW_MAX_CELLS = 2e3;
4466
+ function decodeLongAttribute(value) {
4467
+ if (!value) return null;
4468
+ const bytes = Buffer.from(value, "base64");
4469
+ if (bytes.length !== 8) return null;
4470
+ const decoded = bytes.readBigInt64BE(0);
4471
+ return decoded >= 0n && decoded <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(decoded) : null;
4472
+ }
4473
+ function tableDimensions(entity) {
4474
+ return {
4475
+ rows: decodeLongAttribute(entity.attributes?.rows) ?? 0,
4476
+ columns: decodeLongAttribute(entity.attributes?.columns) ?? 0
4477
+ };
4478
+ }
4479
+ function defaultWindow(rows, columns) {
4480
+ const shownColumns = Math.min(columns, WINDOW_MAX_COLUMNS);
4481
+ const budgeted = Math.max(1, Math.floor(WINDOW_MAX_CELLS / Math.max(1, shownColumns)));
4482
+ const shownRows = Math.min(rows, WINDOW_MAX_ROWS, budgeted);
4483
+ return { rows: { from: 0, to: shownRows }, columns: { from: 0, to: shownColumns } };
4484
+ }
4485
+ function parseRange(text2, size, label) {
4486
+ const noun = label === "Row" ? "rows" : "columns";
4487
+ const match = /^\s*(\d*)\s*:\s*(\d*)\s*$/.exec(text2);
4488
+ if (!match || match[1] === "" && match[2] === "") {
4489
+ throw new CliError(`${label} range "${text2}" is not two numbers like 0:10.`, { exitCode: EXIT_USAGE });
4490
+ }
4491
+ const from = match[1] === "" ? 0 : Number(match[1]);
4492
+ const to = match[2] === "" ? size : Math.min(Number(match[2]), size);
4493
+ if (from >= size) {
4494
+ throw new CliError(`${label} range "${text2}" starts past the table, which has ${size} ${noun}.`, { exitCode: EXIT_USAGE });
4495
+ }
4496
+ if (to <= from) {
4497
+ throw new CliError(`${label} range "${text2}" selects no ${noun}.`, { exitCode: EXIT_USAGE });
4498
+ }
4499
+ return { from, to };
4500
+ }
4501
+ function cellRange(window) {
4502
+ return {
4503
+ fromRowIndex: window.rows.from,
4504
+ toRowIndex: window.rows.to - 1,
4505
+ fromColumnIndex: window.columns.from,
4506
+ toColumnIndex: window.columns.to - 1
4507
+ };
4508
+ }
4509
+ function describeWindow(window, rows, columns) {
4510
+ const whole = window.rows.from === 0 && window.rows.to === rows && window.columns.from === 0 && window.columns.to === columns;
4511
+ const line = `Rows ${window.rows.from}\u2013${window.rows.to - 1} of ${rows} \xB7 columns ${window.columns.from}\u2013${window.columns.to - 1} of ${columns}`;
4512
+ return whole ? line : `${line} \xB7 use --rows/--cols for more`;
4513
+ }
4514
+ function decodeCellValue(value, type) {
4515
+ if (!value) return "";
4516
+ const bytes = Buffer.from(value, "base64");
4517
+ switch (type) {
4518
+ case "integer":
4519
+ if (bytes.length === 8) return bytes.readBigInt64BE(0).toString();
4520
+ break;
4521
+ case "number":
4522
+ if (bytes.length === 8) return String(bytes.readDoubleBE(0));
4523
+ break;
4524
+ case "bool":
4525
+ if (bytes.length === 1) return bytes[0] !== 0 ? "true" : "false";
4526
+ break;
4527
+ }
4528
+ return bytes.toString("utf-8");
4529
+ }
4530
+
4531
+ // src/commands/table/index.ts
4423
4532
  function getOutputFormat7(cmd) {
4424
4533
  const config = loadConfig();
4425
4534
  const globalOpts = cmd.optsWithGlobals();
@@ -4451,26 +4560,30 @@ Examples:
4451
4560
  $ diafunc table import-formats what can be loaded
4452
4561
  `);
4453
4562
  ;
4454
- table.command("view").description("View table data").argument("<ref>", "Table entity reference").option("--rows <range>", "Row range (e.g., 0:10)").option("--cols <range>", "Column range (e.g., 0:5)").action(async (ref, options, cmd) => {
4563
+ table.command("view").description("View table data").argument("<ref>", "Table entity reference").option("--rows <range>", "Rows to show, half-open: 0:10 is the first ten, 6490: runs to the end (default: up to 100)").option("--cols <range>", "Columns to show, half-open: 0:5 is the first five (default: up to 50)").action(async (ref, options, cmd) => {
4455
4564
  try {
4456
4565
  const outputFormat = getOutputFormat7(cmd);
4457
4566
  const overrides = getOverrides6(cmd);
4458
4567
  const resolved = parseEntityReference(ref, overrides);
4459
4568
  const api = createApiClient();
4460
- const request = {};
4461
- if (options.rows) {
4462
- const [from, to] = options.rows.split(":").map(Number);
4463
- if (!isNaN(from)) request.fromRow = from;
4464
- if (!isNaN(to)) request.toRow = to;
4465
- }
4466
- if (options.cols) {
4467
- const [from, to] = options.cols.split(":").map(Number);
4468
- if (!isNaN(from)) request.fromColumn = from;
4469
- if (!isNaN(to)) request.toColumn = to;
4569
+ const { rows: totalRows, columns: totalColumns } = tableDimensions(await api.storage.getEntity(resolved, false));
4570
+ if (totalRows === 0 || totalColumns === 0) {
4571
+ if (outputFormat === "json") {
4572
+ format({ rows: [], columns: [], cells: [], totalRows, totalColumns, window: null }, { format: outputFormat });
4573
+ } else {
4574
+ console.log(chalk15.dim("Empty table."));
4575
+ }
4576
+ return;
4470
4577
  }
4471
- const snapshot = await api.storage.getTableSnapshot(resolved, request);
4578
+ const initial = defaultWindow(totalRows, totalColumns);
4579
+ const window = {
4580
+ rows: options.rows ? parseRange(options.rows, totalRows, "Row") : initial.rows,
4581
+ columns: options.cols ? parseRange(options.cols, totalColumns, "Column") : initial.columns
4582
+ };
4583
+ const snapshot = await api.storage.getTableSnapshot(resolved, { cellRanges: [cellRange(window)] });
4472
4584
  if (outputFormat === "json") {
4473
- format(snapshot, { format: outputFormat });
4585
+ const cells = snapshot.cells.map((cell3) => ({ ...cell3, text: decodeCellValue(cell3.value, cell3.type) }));
4586
+ format({ ...snapshot, cells, totalRows, totalColumns, window }, { format: outputFormat });
4474
4587
  return;
4475
4588
  }
4476
4589
  const colMap = new Map(snapshot.columns.map((c) => [c.index, c]));
@@ -4478,7 +4591,7 @@ Examples:
4478
4591
  const colNames = sortedCols.map((c) => c.name || `col${c.index}`);
4479
4592
  const cellMap = /* @__PURE__ */ new Map();
4480
4593
  for (const cell3 of snapshot.cells) {
4481
- cellMap.set(`${cell3.rowIndex}:${cell3.columnIndex}`, cell3.value ?? "");
4594
+ cellMap.set(`${cell3.rowIndex}:${cell3.columnIndex}`, decodeCellValue(cell3.value, cell3.type));
4482
4595
  }
4483
4596
  const sortedRows = [...snapshot.rows].sort((a, b) => a.index - b.index);
4484
4597
  const tableData = sortedRows.map((row2) => {
@@ -4494,14 +4607,14 @@ Examples:
4494
4607
  console.log(colNames.map((c) => row2[c] ?? "").join(" "));
4495
4608
  }
4496
4609
  } else {
4497
- console.log(chalk15.dim(`${snapshot.rows.length} rows \xD7 ${snapshot.columns.length} columns`));
4498
- format(tableData, { format: outputFormat, columns: colNames });
4610
+ format(tableData, { format: outputFormat, columns: colNames.map((name) => ({ key: name, header: name })) });
4611
+ console.log(chalk15.dim(describeWindow(window, totalRows, totalColumns)));
4499
4612
  }
4500
4613
  } catch (error) {
4501
4614
  handleError(error);
4502
4615
  }
4503
4616
  });
4504
- table.command("import").description("Import data from a file (any supported format \u2014 see `table import-formats`)").argument("<ref>", "Table entity reference").argument("<file>", "File to import").option("--selection <id>", "Pin a sheet / inner-table id for multi-table sources (Excel sheets, SQLite tables, archive entries)").action(async (ref, file, options, cmd) => {
4617
+ table.command("import").description("Import data from a file (any supported format; see `table import-formats`)").argument("<ref>", "Table entity reference").argument("<file>", "File to import").option("--selection <id>", "Pin a sheet / inner-table id for multi-table sources (Excel sheets, SQLite tables, archive entries)").action(async (ref, file, options, cmd) => {
4505
4618
  try {
4506
4619
  const overrides = getOverrides6(cmd);
4507
4620
  const resolved = parseEntityReference(ref, overrides);
@@ -4542,7 +4655,7 @@ Examples:
4542
4655
  status.stop();
4543
4656
  }
4544
4657
  failure(`Import ${importId} is still running after ${formatDuration(pollInterval * maxAttempts)}.`);
4545
- hint(`It continues on the server \u2014 re-check with 'diafunc table view ${ref}'.`);
4658
+ hint(`It continues on the server. Check again with 'diafunc table view ${ref}'.`);
4546
4659
  process.exit(EXIT_FAILURE);
4547
4660
  } catch (error) {
4548
4661
  handleError(error);
@@ -4583,7 +4696,7 @@ Examples:
4583
4696
  handleError(error);
4584
4697
  }
4585
4698
  });
4586
- table.command("export").description("Export table data in any supported format (see `table export-formats`)").argument("<ref>", "Table entity reference").argument("<format>", "Export format (csv, tsv, excel, parquet, arrow, orc, avro, json, jsonl, yaml, xml, html, pdf, sqlite, duckdb, hdf5, netcdf, ...)").option("--out <file>", "Output file").option("--compression <algorithm>", "Compression wrapper: gzip, bzip2, xz, or zstd").option("--archive <algorithm>", "Archive wrapper: zip or tar").option("--rows <range>", "Row range (e.g., 0:1000) \u2014 half-open").option("--cols <range>", "Column range (e.g., 0:5) \u2014 half-open").option("--delimiter <char>", "CSV/TSV only: single-character delimiter override").option("--quote <char>", 'CSV/TSV only: quote character (use "" for empty)').option("--null <token>", 'CSV/TSV only: null token (default "?")').option("--no-quote-all", "CSV/TSV only: only quote fields when necessary (default quotes every field)").option("--async", "Queue an async export (with progress + later re-download) instead of streaming directly to disk", false).action(async (ref, fmt, options, cmd) => {
4699
+ table.command("export").description("Export table data in any supported format (see `table export-formats`)").argument("<ref>", "Table entity reference").argument("<format>", "Export format (csv, tsv, excel, parquet, arrow, orc, avro, json, jsonl, yaml, xml, html, pdf, sqlite, duckdb, hdf5, netcdf, ...)").option("--out <file>", "Output file").option("--compression <algorithm>", "Compression wrapper: gzip, bzip2, xz, or zstd").option("--archive <algorithm>", "Archive wrapper: zip or tar").option("--rows <range>", "Row range, half-open (e.g. 0:1000)").option("--cols <range>", "Column range, half-open (e.g. 0:5)").option("--delimiter <char>", "CSV/TSV only: single-character delimiter override").option("--quote <char>", 'CSV/TSV only: quote character (use "" for empty)').option("--null <token>", 'CSV/TSV only: null token (default "?")').option("--no-quote-all", "CSV/TSV only: only quote fields when necessary (default quotes every field)").option("--async", "Queue an async export (with progress + later re-download) instead of streaming directly to disk", false).action(async (ref, fmt, options, cmd) => {
4587
4700
  try {
4588
4701
  const overrides = getOverrides6(cmd);
4589
4702
  const resolved = parseEntityReference(ref, overrides);
@@ -4710,7 +4823,7 @@ Examples:
4710
4823
  }
4711
4824
  if (exp.finished === null) {
4712
4825
  const pct = Math.round((exp.progress ?? 0) * 100);
4713
- console.log(chalk15.dim(`Export in progress: ${pct}% \u2014 check again later.`));
4826
+ console.log(chalk15.dim(`Export in progress: ${pct}%. Check again later.`));
4714
4827
  return;
4715
4828
  }
4716
4829
  if (!exp.succeeded) {
@@ -5721,14 +5834,14 @@ var MarkdownRenderer = class {
5721
5834
  }
5722
5835
  const heading2 = line.match(/^(#{1,6})\s+(.*)$/);
5723
5836
  if (heading2) {
5724
- const text = inline(heading2[2]);
5725
- return ["", heading2[1].length <= 2 ? chalk18.bold.underline(text) : chalk18.bold(text)];
5837
+ const text2 = inline(heading2[2]);
5838
+ return ["", heading2[1].length <= 2 ? chalk18.bold.underline(text2) : chalk18.bold(text2)];
5726
5839
  }
5727
5840
  if (/^\s*([-*_])\1{2,}\s*$/.test(line)) {
5728
5841
  return [chalk18.dim("\u2500".repeat(Math.min(this.width, 60)))];
5729
5842
  }
5730
- const quote = line.match(/^\s*>\s?(.*)$/);
5731
- if (quote) return [chalk18.dim(` \u2502 ${inline(quote[1])}`)];
5843
+ const quote2 = line.match(/^\s*>\s?(.*)$/);
5844
+ if (quote2) return [chalk18.dim(` \u2502 ${inline(quote2[1])}`)];
5732
5845
  const bullet = line.match(/^(\s*)[-*+]\s+(.*)$/);
5733
5846
  if (bullet) {
5734
5847
  return wrapWithIndent(
@@ -5754,12 +5867,12 @@ function renderMarkdown(source, width = terminalWidth()) {
5754
5867
  const renderer = new MarkdownRenderer(width);
5755
5868
  return [...renderer.push(source), ...renderer.flush()].join("\n");
5756
5869
  }
5757
- function wrapWithIndent(text, indent, width) {
5758
- return wrap(text, width).map((l, i) => i === 0 ? l : " ".repeat(indent) + l);
5870
+ function wrapWithIndent(text2, indent, width) {
5871
+ return wrap(text2, width).map((l, i) => i === 0 ? l : " ".repeat(indent) + l);
5759
5872
  }
5760
- function inline(text) {
5873
+ function inline(text2) {
5761
5874
  const codeSpans = [];
5762
- let working = text.replace(/`([^`]+)`/g, (_m, code) => {
5875
+ let working = text2.replace(/`([^`]+)`/g, (_m, code) => {
5763
5876
  codeSpans.push(code);
5764
5877
  return `${CODE_OPEN}${codeSpans.length - 1}${CODE_CLOSE}`;
5765
5878
  });
@@ -5856,7 +5969,7 @@ var HELP = [
5856
5969
  ];
5857
5970
  async function runChatRepl(options) {
5858
5971
  const { input: promptInput } = await import("@inquirer/prompts");
5859
- const { getUpdateNotice } = await import("./update-check-ZCS3IYOZ.js");
5972
+ const { getUpdateNotice } = await import("./update-check-V23VUFO4.js");
5860
5973
  let sessionId = options.session;
5861
5974
  let lastReportedSession;
5862
5975
  console.log(chalk19.bold("Diafunc chat") + chalk19.dim(" \xB7 /help for commands, /quit to exit"));
@@ -6169,14 +6282,14 @@ Examples:
6169
6282
  projectBranch: projectId ? overrides.branch ?? config.defaults.branch ?? "main" : null
6170
6283
  });
6171
6284
  const items = dedupe(page.items);
6172
- if (items.length === 0) {
6173
- empty("matches", { format: outputFormat });
6174
- return;
6175
- }
6176
6285
  if (outputFormat === "json") {
6177
6286
  format({ ...page, items }, { format: outputFormat });
6178
6287
  return;
6179
6288
  }
6289
+ if (items.length === 0) {
6290
+ empty("matches", { format: outputFormat });
6291
+ return;
6292
+ }
6180
6293
  if (isInteractive()) {
6181
6294
  renderResults(items);
6182
6295
  } else {
@@ -6191,7 +6304,7 @@ Examples:
6191
6304
  });
6192
6305
  }
6193
6306
  if (page.nextCursor && isInteractive()) {
6194
- console.log(chalk20.dim(`More results available \u2014 raise --limit to see them.`));
6307
+ console.log(chalk20.dim(`More results available. Raise --limit to see them.`));
6195
6308
  }
6196
6309
  } catch (error) {
6197
6310
  handleError(error);
@@ -6224,19 +6337,19 @@ function renderResults(items) {
6224
6337
  }
6225
6338
  var HIGHLIGHT_OPEN = /<mark>/g;
6226
6339
  var HIGHLIGHT_CLOSE = /<\/mark>/g;
6227
- function highlight(text) {
6228
- const parts = text.split(HIGHLIGHT_OPEN);
6340
+ function highlight(text2) {
6341
+ const parts = text2.split(HIGHLIGHT_OPEN);
6229
6342
  return parts.map((part, i) => {
6230
6343
  if (i === 0) return chalk20.dim(part);
6231
6344
  const [marked, ...rest] = part.split(HIGHLIGHT_CLOSE);
6232
6345
  return chalk20.bold.cyan(marked) + chalk20.dim(rest.join(""));
6233
6346
  }).join("");
6234
6347
  }
6235
- function stripHighlight(text) {
6236
- return text.replace(HIGHLIGHT_OPEN, "").replace(HIGHLIGHT_CLOSE, "");
6348
+ function stripHighlight(text2) {
6349
+ return text2.replace(HIGHLIGHT_OPEN, "").replace(HIGHLIGHT_CLOSE, "");
6237
6350
  }
6238
- function collapse(text) {
6239
- const flat = text.replace(/\s+/g, " ").trim();
6351
+ function collapse(text2) {
6352
+ const flat = text2.replace(/\s+/g, " ").trim();
6240
6353
  return flat.length > 160 ? `${flat.slice(0, 159)}\u2026` : flat;
6241
6354
  }
6242
6355
 
@@ -6627,7 +6740,6 @@ Examples:
6627
6740
  }
6628
6741
 
6629
6742
  // src/commands/analyze/index.ts
6630
- import chalk26 from "chalk";
6631
6743
  import * as fs8 from "fs";
6632
6744
  import * as path7 from "path";
6633
6745
  import { spawn as spawn2 } from "child_process";
@@ -6645,22 +6757,79 @@ var RUN_PHASE_LABELS = {
6645
6757
  WRITING: "Writing the report"
6646
6758
  };
6647
6759
 
6648
- // src/commands/analyze/watch-view.ts
6649
- var PHASE_ORDER = ["QUEUED", "PREPARING", "PROFILING", "DISCOVERING", "EXPLAINING", "WRITING"];
6650
- function overallProgress(run) {
6651
- if (run.overallFraction !== null && run.overallFraction !== void 0) return run.overallFraction;
6652
- if (run.progressTotal && run.progressTotal > 0) return (run.progressDone ?? 0) / run.progressTotal;
6653
- return null;
6654
- }
6760
+ // src/commands/analyze/copy.ts
6761
+ var RUN_STEPS = ["PREPARING", "PROFILING", "DISCOVERING", "EXPLAINING", "WRITING"];
6762
+ var STARTING = "Starting";
6655
6763
  function phaseLabel(run) {
6764
+ if (run.state === "QUEUED") return RUN_PHASE_LABELS.QUEUED;
6765
+ if (run.state === "DISPATCHING") return STARTING;
6656
6766
  if (run.phase && RUN_PHASE_LABELS[run.phase]) return RUN_PHASE_LABELS[run.phase];
6767
+ if (run.state === "RUNNING" && !((run.progressTotal ?? 0) > 0)) return RUN_PHASE_LABELS.PREPARING;
6657
6768
  return run.state.charAt(0) + run.state.slice(1).toLowerCase();
6658
6769
  }
6659
6770
  function stepCounter(run) {
6660
6771
  if (!run.phase) return null;
6661
- const index = PHASE_ORDER.indexOf(run.phase);
6772
+ const index = RUN_STEPS.indexOf(run.phase);
6662
6773
  if (index < 0) return null;
6663
- return `step ${index + 1} of ${PHASE_ORDER.length}`;
6774
+ return `step ${index + 1} of ${RUN_STEPS.length}`;
6775
+ }
6776
+ function runPhaseCell(run) {
6777
+ if (run.state === "COMPLETED") return null;
6778
+ if (run.state === "QUEUED" || run.state === "DISPATCHING") return phaseLabel(run);
6779
+ if (run.phase && RUN_PHASE_LABELS[run.phase]) return RUN_PHASE_LABELS[run.phase];
6780
+ return null;
6781
+ }
6782
+ function latestRunSentence(state) {
6783
+ switch (state) {
6784
+ case "COMPLETED":
6785
+ return "The latest run has already completed.";
6786
+ case "FAILED":
6787
+ return "The latest run failed.";
6788
+ case "CANCELLED":
6789
+ return "The latest run was cancelled.";
6790
+ case "QUEUED":
6791
+ return "The latest run is waiting for a slot.";
6792
+ case "DISPATCHING":
6793
+ return "The latest run is starting.";
6794
+ default:
6795
+ return "The latest run is in progress.";
6796
+ }
6797
+ }
6798
+ function cancelSentence(run) {
6799
+ switch (run.state) {
6800
+ case "CANCELLED":
6801
+ return `Cancelled run ${run.runId}.`;
6802
+ case "COMPLETED":
6803
+ return `Run ${run.runId} had already completed.`;
6804
+ case "FAILED":
6805
+ return `Run ${run.runId} had already failed.`;
6806
+ default:
6807
+ return `Run ${run.runId} is still ${phaseLabel(run).toLowerCase()}.`;
6808
+ }
6809
+ }
6810
+ function terminalSentence(state, duration) {
6811
+ switch (state) {
6812
+ case "COMPLETED":
6813
+ return `Analysis completed in ${duration}.`;
6814
+ case "CANCELLED":
6815
+ return `Analysis cancelled after ${duration}.`;
6816
+ default:
6817
+ return `Analysis failed after ${duration}.`;
6818
+ }
6819
+ }
6820
+
6821
+ // src/commands/analyze/watch-view.ts
6822
+ function overallProgress(run) {
6823
+ if (run.overallFraction !== null && run.overallFraction !== void 0) return run.overallFraction;
6824
+ if (run.progressTotal && run.progressTotal > 0) return (run.progressDone ?? 0) / run.progressTotal;
6825
+ return null;
6826
+ }
6827
+ function remainingCeiling(run, budgetHours) {
6828
+ if (run.phase !== "DISCOVERING") return null;
6829
+ if (budgetHours === null || !Number.isFinite(budgetHours) || budgetHours <= 0) return null;
6830
+ const fraction = run.phaseFraction;
6831
+ if (fraction === null || fraction === void 0) return null;
6832
+ return Math.max(0, budgetHours * 36e5 * (1 - Math.max(0, Math.min(fraction, 1))));
6664
6833
  }
6665
6834
  function phaseDetail(run) {
6666
6835
  const parts = [];
@@ -6669,7 +6838,7 @@ function phaseDetail(run) {
6669
6838
  parts.push(`generation ${formatNumber(run.fitGeneration)}`);
6670
6839
  }
6671
6840
  if (run.fitQuality !== null && run.fitQuality !== void 0) {
6672
- parts.push(`quality ${run.fitQuality.toPrecision(4)}`);
6841
+ parts.push(`quality ${Math.floor(Math.max(0, Math.min(run.fitQuality, 1)) * 100)}%`);
6673
6842
  }
6674
6843
  if (run.fitBudgetFraction !== null && run.fitBudgetFraction !== void 0) {
6675
6844
  parts.push(`${Math.round(run.fitBudgetFraction * 100)}% of budget used`);
@@ -6683,7 +6852,7 @@ function phaseDetail(run) {
6683
6852
  return parts.length > 0 ? parts.join(" \xB7 ") : null;
6684
6853
  }
6685
6854
  function renderWatchBlock(input) {
6686
- const { run, elapsedMs, caption } = input;
6855
+ const { run, elapsedMs, caption, budgetHours } = input;
6687
6856
  const lines = [];
6688
6857
  const step = stepCounter(run);
6689
6858
  const headline = [
@@ -6693,30 +6862,24 @@ function renderWatchBlock(input) {
6693
6862
  ].filter(Boolean).join(" ");
6694
6863
  lines.push(` ${headline}`);
6695
6864
  const fraction = overallProgress(run);
6696
- const elapsed = chalk24.dim(formatDuration(elapsedMs));
6865
+ const elapsed = chalk24.dim(formatDurationPrecise(elapsedMs));
6697
6866
  if (fraction === null) {
6698
6867
  lines.push(` ${chalk24.dim("working")} ${elapsed}`);
6699
6868
  } else {
6700
- const eta = estimateRemaining(fraction, elapsedMs);
6869
+ const ceiling = remainingCeiling(run, budgetHours);
6701
6870
  lines.push(
6702
- ` ${bar(fraction)} ${percent(fraction)} ${elapsed}` + (eta ? chalk24.dim(` \xB7 ~${formatDuration(eta)} left`) : "")
6871
+ ` ${bar(fraction)} ${percent(fraction)} ${elapsed}` + (ceiling !== null ? chalk24.dim(` \xB7 at most ${formatDurationPrecise(ceiling)} remaining`) : "")
6703
6872
  );
6704
6873
  }
6705
6874
  const detail2 = caption ?? phaseDetail(run);
6706
6875
  if (detail2) lines.push(` ${chalk24.dim(detail2)}`);
6707
6876
  if (run.retryAttempts && run.retryAttempts > 0) {
6708
6877
  lines.push(` ${chalk24.yellow("!")} ${chalk24.dim(
6709
- `restarted ${run.retryAttempts === 1 ? "once" : `${run.retryAttempts} times`} after an interruption \u2014 progress restarts from the beginning`
6878
+ `restarted ${run.retryAttempts === 1 ? "once" : `${run.retryAttempts} times`} after an interruption; progress restarts from the beginning`
6710
6879
  )}`);
6711
6880
  }
6712
6881
  return lines;
6713
6882
  }
6714
- function estimateRemaining(fraction, elapsedMs) {
6715
- if (fraction <= 0.02 || fraction >= 1 || elapsedMs < 3e4) return null;
6716
- const total = elapsedMs / fraction;
6717
- const remaining = total - elapsedMs;
6718
- return remaining > 0 ? remaining : null;
6719
- }
6720
6883
 
6721
6884
  // src/commands/analyze/wizard.ts
6722
6885
  import chalk25 from "chalk";
@@ -6729,51 +6892,6 @@ var DEPTH_PRESETS = [
6729
6892
  ];
6730
6893
  var DEFAULT_HOURS = "4";
6731
6894
  var DEFAULT_BUDGET = "10000";
6732
- var PromptCancelled = class extends Error {
6733
- constructor() {
6734
- super("Cancelled.");
6735
- this.name = "PromptCancelled";
6736
- }
6737
- };
6738
- function createInquirerPrompter() {
6739
- const load = () => import("@inquirer/prompts");
6740
- const guard = async (work) => {
6741
- try {
6742
- return await work();
6743
- } catch (error) {
6744
- if (error instanceof Error && error.name === "ExitPromptError") throw new PromptCancelled();
6745
- throw error;
6746
- }
6747
- };
6748
- return {
6749
- async input(options) {
6750
- const { input } = await load();
6751
- return guard(() => input(options));
6752
- },
6753
- async select(options) {
6754
- const { select } = await load();
6755
- return guard(() => select(options));
6756
- },
6757
- async checkbox(options) {
6758
- const { checkbox } = await load();
6759
- return guard(() => checkbox(options));
6760
- },
6761
- async confirm(options) {
6762
- const { confirm } = await load();
6763
- return guard(() => confirm(options));
6764
- }
6765
- };
6766
- }
6767
- function canPrompt(outputFormat, noInteractive) {
6768
- if (noInteractive) return false;
6769
- if (outputFormat !== "human") return false;
6770
- return Boolean(process.stdin.isTTY) && isInteractive();
6771
- }
6772
- function whyNoPrompt(outputFormat, noInteractive) {
6773
- if (noInteractive) return "--no-interactive is set";
6774
- if (outputFormat !== "human") return `--output ${outputFormat} does not prompt`;
6775
- return "there is no terminal to ask";
6776
- }
6777
6895
  async function promptCreationFields(prompter, supplied, fallbackName) {
6778
6896
  const name = supplied.name ?? await prompter.input({
6779
6897
  message: "Analysis name",
@@ -6841,7 +6959,7 @@ async function promptRunFields(prompter, options) {
6841
6959
  if (named.length > 0) {
6842
6960
  const preselected = new Set(defaultTargets(named));
6843
6961
  targets = await prompter.checkbox({
6844
- message: "Target variables: what should the analysis predict?",
6962
+ message: "Target columns: what should the analysis predict?",
6845
6963
  choices: named.map((c) => ({
6846
6964
  name: c.valueType ? `${c.name} ${chalk25.dim(`(${c.valueType})`)}` : c.name,
6847
6965
  value: c.name,
@@ -6850,11 +6968,11 @@ async function promptRunFields(prompter, options) {
6850
6968
  validate: (chosen) => chosen.length > 0 || "Pick at least one target column."
6851
6969
  });
6852
6970
  } else {
6853
- const typed = await prompter.input({
6971
+ const typed2 = await prompter.input({
6854
6972
  message: "Target column names (comma-separated)",
6855
6973
  validate: (value) => splitCsv(value).length > 0 || "Name at least one target column."
6856
6974
  });
6857
- targets = splitCsv(typed);
6975
+ targets = splitCsv(typed2);
6858
6976
  }
6859
6977
  }
6860
6978
  const remaining = named.filter((c) => !targets.includes(c.name));
@@ -6881,10 +6999,10 @@ async function promptRunFields(prompter, options) {
6881
6999
  if (wanted) {
6882
7000
  const collected = [];
6883
7001
  for (; ; ) {
6884
- const question = await prompter.input({
7002
+ const question2 = await prompter.input({
6885
7003
  message: collected.length === 0 ? "Question" : "Another question (blank to finish)"
6886
7004
  });
6887
- const trimmed = question.trim();
7005
+ const trimmed = question2.trim();
6888
7006
  if (trimmed.length === 0) break;
6889
7007
  collected.push(trimmed);
6890
7008
  }
@@ -6913,7 +7031,7 @@ async function promptRunFields(prompter, options) {
6913
7031
  }
6914
7032
  if (hours === void 0) {
6915
7033
  hours = await prompter.input({
6916
- message: "Computation time in hours",
7034
+ message: "Computation time (hours)",
6917
7035
  default: DEFAULT_HOURS,
6918
7036
  validate: positiveNumber("Computation time")
6919
7037
  });
@@ -6978,11 +7096,11 @@ var FIELD_COMMANDS = {
6978
7096
  budget: "budget <id> <credits>",
6979
7097
  targets: "targets <id> <csv>"
6980
7098
  };
6981
- function explainMissingRunFields(analysisId, missing, reason) {
7099
+ function explainMissingRunFields(analysisId, missing, reason2) {
6982
7100
  const commands = missing.map((f) => `'diafunc analyze ${FIELD_COMMANDS[f].replace("<id>", analysisId)}'`);
6983
7101
  const columns = missing.includes("targets") ? ` Column names: 'diafunc analyze columns ${analysisId}'.` : "";
6984
7102
  return {
6985
- message: `Analysis ${analysisId} cannot run yet: it has no ${joinList(missing)}, and ${reason}.`,
7103
+ message: `Analysis ${analysisId} cannot run yet: it has no ${joinList(missing)}, and ${reason2}.`,
6986
7104
  suggestion: `Set ${missing.length === 1 ? "it" : "them"} with ${commands.join(", ")}, then rerun.${columns}`
6987
7105
  };
6988
7106
  }
@@ -6991,6 +7109,61 @@ function joinList(items) {
6991
7109
  return `${items.slice(0, -1).join(", ")} or ${items[items.length - 1]}`;
6992
7110
  }
6993
7111
 
7112
+ // src/prompting/prompter.ts
7113
+ var PromptCancelled = class extends Error {
7114
+ constructor() {
7115
+ super("Cancelled.");
7116
+ this.name = "PromptCancelled";
7117
+ }
7118
+ };
7119
+ function createInquirerPrompter() {
7120
+ const load = () => import("@inquirer/prompts");
7121
+ const guard = async (work) => {
7122
+ try {
7123
+ return await work();
7124
+ } catch (error) {
7125
+ if (error instanceof Error && error.name === "ExitPromptError") throw new PromptCancelled();
7126
+ throw error;
7127
+ }
7128
+ };
7129
+ return {
7130
+ async input(options) {
7131
+ const { input } = await load();
7132
+ return guard(() => input(options));
7133
+ },
7134
+ async select(options) {
7135
+ const { select } = await load();
7136
+ return guard(() => select(options));
7137
+ },
7138
+ async checkbox(options) {
7139
+ const { checkbox } = await load();
7140
+ return guard(() => checkbox(options));
7141
+ },
7142
+ async confirm(options) {
7143
+ const { confirm } = await load();
7144
+ return guard(() => confirm(options));
7145
+ },
7146
+ async search(options) {
7147
+ const { search } = await load();
7148
+ return guard(() => search({
7149
+ message: options.message,
7150
+ pageSize: 12,
7151
+ source: async (term) => options.source(term ?? "")
7152
+ }));
7153
+ }
7154
+ };
7155
+ }
7156
+ function canPrompt(outputFormat, noInteractive) {
7157
+ if (noInteractive) return false;
7158
+ if (outputFormat !== "human") return false;
7159
+ return Boolean(process.stdin.isTTY) && isInteractive();
7160
+ }
7161
+ function whyNoPrompt(outputFormat, noInteractive) {
7162
+ if (noInteractive) return "--no-interactive is set";
7163
+ if (outputFormat !== "human") return `--output ${outputFormat} does not prompt`;
7164
+ return "there is no terminal to ask";
7165
+ }
7166
+
6994
7167
  // src/commands/analyze/index.ts
6995
7168
  var POLL_INTERVAL_MS = 2e3;
6996
7169
  var COLUMN_READ_ATTEMPTS = 3;
@@ -7005,6 +7178,9 @@ function getOutputFormat15(cmd) {
7005
7178
  const globalOpts = cmd.optsWithGlobals();
7006
7179
  return globalOpts.output ?? config.defaults.output ?? "human";
7007
7180
  }
7181
+ function noInteractiveFlag(cmd) {
7182
+ return cmd.optsWithGlobals().interactive === false;
7183
+ }
7008
7184
  function parseCsv(value) {
7009
7185
  if (value === void 0) return null;
7010
7186
  return value.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
@@ -7012,13 +7188,18 @@ function parseCsv(value) {
7012
7188
  function parseVisibility(value) {
7013
7189
  const upper = value.toUpperCase();
7014
7190
  if (upper !== "PRIVATE" && upper !== "PUBLIC") {
7015
- throw new Error(`Invalid visibility "${value}" \u2014 must be PRIVATE or PUBLIC.`);
7191
+ throw new Error(`Invalid visibility "${value}". Use PRIVATE or PUBLIC.`);
7016
7192
  }
7017
7193
  return upper;
7018
7194
  }
7019
7195
  function isTerminalState(state) {
7020
7196
  return state === "COMPLETED" || state === "FAILED" || state === "CANCELLED";
7021
7197
  }
7198
+ function budgetHoursOf(hours) {
7199
+ if (hours === null || hours === void 0) return null;
7200
+ const parsed = Number(hours);
7201
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
7202
+ }
7022
7203
  function multipartFromFile(file) {
7023
7204
  const buffer = fs8.readFileSync(file);
7024
7205
  const blob = new Blob([buffer]);
@@ -7027,11 +7208,7 @@ function multipartFromFile(file) {
7027
7208
  return formData;
7028
7209
  }
7029
7210
  function reportCommandError(error) {
7030
- if (error instanceof PromptCancelled) {
7031
- console.log();
7032
- console.log(chalk26.dim("Cancelled."));
7033
- process.exit(EXIT_CANCELLED);
7034
- }
7211
+ if (error instanceof PromptCancelled) throw error;
7035
7212
  handleError(error);
7036
7213
  }
7037
7214
  async function runAnalysis(file, options, cmd) {
@@ -7040,12 +7217,14 @@ async function runAnalysis(file, options, cmd) {
7040
7217
  process.exit(EXIT_FAILURE);
7041
7218
  }
7042
7219
  const outputFormat = getOutputFormat15(cmd);
7043
- const interactive = canPrompt(outputFormat, options.interactive === false);
7220
+ const noInteractive = noInteractiveFlag(cmd);
7221
+ const interactive = canPrompt(outputFormat, noInteractive);
7044
7222
  const api = createApiClient();
7045
7223
  if (options.preset) {
7046
7224
  const opt = await api.analysis.getPreset(options.preset);
7047
7225
  if (!opt.preset) {
7048
7226
  failure(`Preset not found: ${options.preset}`);
7227
+ hint(`List your presets with 'diafunc analyze presets list'.`);
7049
7228
  process.exit(EXIT_FAILURE);
7050
7229
  }
7051
7230
  const p = opt.preset;
@@ -7058,7 +7237,7 @@ async function runAnalysis(file, options, cmd) {
7058
7237
  const flagTargets = parseCsv(options.targets);
7059
7238
  if (!interactive && (flagTargets === null || flagTargets.length === 0)) {
7060
7239
  usageError(
7061
- `Target columns are required, and ${whyNoPrompt(outputFormat, options.interactive === false)}.`,
7240
+ `Target columns are required, and ${whyNoPrompt(outputFormat, noInteractive)}.`,
7062
7241
  `Pass --targets <csv> or --preset <id>. The names are the column headers of ${path7.basename(file)}.`
7063
7242
  );
7064
7243
  }
@@ -7090,20 +7269,22 @@ async function runAnalysis(file, options, cmd) {
7090
7269
  `Uploading ${path7.basename(file)}`,
7091
7270
  () => api.analysis.uploadDataMultipart(created.analysisId, multipartFromFile(file))
7092
7271
  );
7272
+ let runHours = request.hours;
7093
7273
  if (interactive) {
7094
- const configured = await configureInteractively(api, prompter, created.analysisId, request, {
7274
+ const configuredHours = await configureInteractively(api, prompter, created.analysisId, request, {
7095
7275
  targets: options.targets === void 0 ? void 0 : parseCsv(options.targets),
7096
7276
  segment: options.segment,
7097
7277
  questions: options.questions === void 0 ? void 0 : parseCsv(options.questions),
7098
7278
  hours: options.hours,
7099
7279
  budget: options.budget
7100
7280
  });
7101
- if (!configured) return;
7281
+ if (configuredHours === null) return;
7282
+ runHours = configuredHours;
7102
7283
  }
7103
7284
  const run = await withStatus("Queuing analysis run", () => api.analysis.runAnalysis(created.analysisId));
7104
7285
  detail(`runId: ${run.runId}`);
7105
7286
  console.log();
7106
- await monitorRun(api, created.analysisId, run.runId, cmd);
7287
+ await monitorRun(api, created.analysisId, run.runId, budgetHoursOf(runHours), cmd);
7107
7288
  }
7108
7289
  async function configureInteractively(api, prompter, analysisId, recipe, supplied) {
7109
7290
  const columns = await readColumns(api, analysisId);
@@ -7131,9 +7312,9 @@ async function configureInteractively(api, prompter, analysisId, recipe, supplie
7131
7312
  if (!await prompter.confirm({ message: "Start the analysis?", default: true })) {
7132
7313
  warn("Not started. The analysis and these settings are saved.");
7133
7314
  hint(`Start it later with 'diafunc analyze rerun ${analysisId}'.`);
7134
- return false;
7315
+ return null;
7135
7316
  }
7136
- return true;
7317
+ return answers.hours;
7137
7318
  }
7138
7319
  async function readColumns(api, analysisId) {
7139
7320
  for (let attempt = 0; attempt < COLUMN_READ_ATTEMPTS; attempt++) {
@@ -7154,7 +7335,7 @@ async function readPresets(api) {
7154
7335
  return [];
7155
7336
  }
7156
7337
  }
7157
- async function monitorRun(api, analysisId, runId, cmd) {
7338
+ async function monitorRun(api, analysisId, runId, budgetHours, cmd) {
7158
7339
  const config = loadConfig();
7159
7340
  const outputFormat = getOutputFormat15(cmd);
7160
7341
  const human = outputFormat === "human";
@@ -7195,7 +7376,7 @@ async function monitorRun(api, analysisId, runId, cmd) {
7195
7376
  }
7196
7377
  const startedAt = run.startedAt ?? run.submittedAt ?? Date.now();
7197
7378
  if (human) {
7198
- status.set(renderWatchBlock({ run, elapsedMs: Date.now() - startedAt, caption }));
7379
+ status.set(renderWatchBlock({ run, elapsedMs: Date.now() - startedAt, caption, budgetHours }));
7199
7380
  } else {
7200
7381
  const snapshot = JSON.stringify({
7201
7382
  type: "progress",
@@ -7215,12 +7396,12 @@ async function monitorRun(api, analysisId, runId, cmd) {
7215
7396
  status.stop();
7216
7397
  }
7217
7398
  }
7218
- function safeParse(text) {
7399
+ function safeParse(text2) {
7219
7400
  try {
7220
- const parsed = JSON.parse(text);
7221
- return parsed && typeof parsed === "object" ? parsed : { output: text };
7401
+ const parsed = JSON.parse(text2);
7402
+ return parsed && typeof parsed === "object" ? parsed : { output: text2 };
7222
7403
  } catch {
7223
- return { output: text };
7404
+ return { output: text2 };
7224
7405
  }
7225
7406
  }
7226
7407
  async function reportTerminalRun(api, config, run, analysisId, runId, outputFormat) {
@@ -7238,16 +7419,17 @@ async function reportTerminalRun(api, config, run, analysisId, runId, outputForm
7238
7419
  return;
7239
7420
  }
7240
7421
  console.log();
7422
+ const sentence = terminalSentence(run.state, formatDurationPrecise(durationMs));
7241
7423
  if (run.state === "COMPLETED") {
7242
- success(`Analysis complete in ${formatDuration(durationMs)}.`);
7424
+ success(sentence);
7243
7425
  await printNotebookLink(api, config, analysisId);
7244
7426
  return;
7245
7427
  }
7246
7428
  if (run.state === "CANCELLED") {
7247
- warn(`Analysis cancelled after ${formatDuration(durationMs)}.`);
7429
+ warn(sentence);
7248
7430
  process.exit(EXIT_FAILURE);
7249
7431
  }
7250
- failure(`Analysis failed after ${formatDuration(durationMs)}.`);
7432
+ failure(sentence);
7251
7433
  if (run.errorMessage) hint(run.errorMessage);
7252
7434
  hint(`Queue a fresh run with 'diafunc analyze rerun ${analysisId}'.`);
7253
7435
  process.exit(EXIT_FAILURE);
@@ -7298,16 +7480,16 @@ async function getAnalysisDetails(analysisId, options, cmd) {
7298
7480
  const analysis = outputFormat === "human" && !options.full ? { ...result.analysis, introduction: abbreviate(result.analysis.introduction) } : result.analysis;
7299
7481
  format(analysis, { format: outputFormat });
7300
7482
  if (outputFormat === "human" && !options.full && isLong(result.analysis.introduction)) {
7301
- hint(`Introduction abbreviated \u2014 pass --full to print it whole.`);
7483
+ hint("Introduction abbreviated. Pass --full to print it whole.");
7302
7484
  }
7303
7485
  }
7304
7486
  var INTRODUCTION_PREVIEW_LINES = 3;
7305
- function isLong(text) {
7306
- return Boolean(text && text.split("\n").length > INTRODUCTION_PREVIEW_LINES);
7487
+ function isLong(text2) {
7488
+ return Boolean(text2 && text2.split("\n").length > INTRODUCTION_PREVIEW_LINES);
7307
7489
  }
7308
- function abbreviate(text) {
7309
- if (!isLong(text)) return text;
7310
- const lines = text.split("\n").filter((l) => l.trim().length > 0);
7490
+ function abbreviate(text2) {
7491
+ if (!isLong(text2)) return text2;
7492
+ const lines = text2.split("\n").filter((l) => l.trim().length > 0);
7311
7493
  return `${lines.slice(0, INTRODUCTION_PREVIEW_LINES).join("\n")}
7312
7494
  \u2026`;
7313
7495
  }
@@ -7318,33 +7500,28 @@ async function watchAnalysis(analysisId, cmd) {
7318
7500
  empty("analysis found");
7319
7501
  return;
7320
7502
  }
7321
- const recipe = result.analysis;
7322
- const runs = await api.analysis.getRunsForAnalysis(recipe.analysisId, 1);
7503
+ const analysis = result.analysis;
7504
+ const runs = await api.analysis.getRunsForAnalysis(analysis.analysisId, 1);
7323
7505
  if (runs.length === 0) {
7324
7506
  empty("runs for this analysis");
7325
7507
  return;
7326
7508
  }
7327
7509
  const latest = runs[0];
7328
7510
  if (isTerminalState(latest.state)) {
7511
+ const sentence = latestRunSentence(latest.state);
7329
7512
  if (latest.state === "COMPLETED") {
7330
- success("The latest run has already completed.");
7513
+ success(sentence);
7331
7514
  } else {
7332
- warn(`The latest run ended as ${latest.state}.`);
7515
+ warn(sentence);
7333
7516
  if (latest.errorMessage) hint(latest.errorMessage);
7334
7517
  }
7335
- try {
7336
- const nav = await api.analysis.getNavigation(recipe.analysisId);
7337
- const config = loadConfig();
7338
- const endpoint = config.profiles[config.currentProfile]?.endpoint ?? "https://diafunc.com";
7339
- console.log(` Project: ${endpoint}${nav.labUrl}`);
7340
- } catch {
7341
- }
7518
+ await printNotebookLink(api, loadConfig(), analysis.analysisId);
7342
7519
  return;
7343
7520
  }
7344
- console.log(`Watching run ${latest.runId} for analysis ${recipe.analysisId} ...`);
7345
- await monitorRun(api, recipe.analysisId, latest.runId, cmd);
7521
+ console.log(`Watching run ${latest.runId} for analysis ${analysis.analysisId} ...`);
7522
+ await monitorRun(api, analysis.analysisId, latest.runId, budgetHoursOf(analysis.hours), cmd);
7346
7523
  }
7347
- async function rerunAnalysis(analysisId, options, cmd) {
7524
+ async function rerunAnalysis(analysisId, cmd) {
7348
7525
  const api = createApiClient();
7349
7526
  const found = await api.analysis.get(analysisId);
7350
7527
  if (!found.analysis) {
@@ -7355,7 +7532,7 @@ async function rerunAnalysis(analysisId, options, cmd) {
7355
7532
  const missing = missingRunFields(analysis);
7356
7533
  if (missing.length > 0) {
7357
7534
  const outputFormat = getOutputFormat15(cmd);
7358
- const noInteractive = options.interactive === false;
7535
+ const noInteractive = noInteractiveFlag(cmd);
7359
7536
  if (!canPrompt(outputFormat, noInteractive)) {
7360
7537
  const { message, suggestion } = explainMissingRunFields(
7361
7538
  analysisId,
@@ -7375,20 +7552,18 @@ async function rerunAnalysis(analysisId, options, cmd) {
7375
7552
  questions: analysis.questions,
7376
7553
  segment: analysis.segment
7377
7554
  };
7378
- const configured = await configureInteractively(
7555
+ const configuredHours = await configureInteractively(
7379
7556
  api,
7380
7557
  createInquirerPrompter(),
7381
7558
  analysisId,
7382
7559
  recipe,
7383
7560
  suppliedFromAnalysis(analysis)
7384
7561
  );
7385
- if (!configured) return;
7562
+ if (configuredHours === null) return;
7386
7563
  }
7387
7564
  const run = await api.analysis.runAnalysis(analysisId);
7388
- success(`Queued new run ${run.runId} for analysis ${analysisId}`);
7389
- console.log(chalk26.dim(` State: ${run.state}`));
7390
- console.log();
7391
- console.log(chalk26.dim("Track progress: diafunc analyze watch " + analysisId));
7565
+ success(`Queued run ${run.runId} for analysis ${analysisId}.`);
7566
+ hint(`Follow it with 'diafunc analyze watch ${analysisId}'.`);
7392
7567
  }
7393
7568
  async function openAnalysis(analysisId) {
7394
7569
  const api = createApiClient();
@@ -7405,10 +7580,10 @@ async function openAnalysis(analysisId) {
7405
7580
  console.log(`Opening ${url} ...`);
7406
7581
  openUrl(url);
7407
7582
  } catch {
7408
- console.log(chalk26.dim("Notebook not yet provisioned \u2014 run the analysis first."));
7583
+ hint("The notebook is not available yet. Run the analysis first.");
7409
7584
  }
7410
7585
  }
7411
- async function createRecipe(options, cmd) {
7586
+ async function createAnalysis(options, cmd) {
7412
7587
  const outputFormat = getOutputFormat15(cmd);
7413
7588
  const api = createApiClient();
7414
7589
  const visibility = parseVisibility(options.visibility);
@@ -7429,14 +7604,14 @@ async function createRecipe(options, cmd) {
7429
7604
  async function deleteAnalysis(analysisId) {
7430
7605
  const api = createApiClient();
7431
7606
  await api.analysis.delete(analysisId);
7432
- success(`Deleted analysis ${analysisId}`);
7607
+ success(`Deleted analysis ${analysisId}.`);
7433
7608
  }
7434
7609
  async function patchAndPrint(analysisId, value, handler, successLabel, cmd) {
7435
7610
  const outputFormat = getOutputFormat15(cmd);
7436
7611
  const api = createApiClient();
7437
7612
  const updated = await handler(api, analysisId, value);
7438
7613
  if (outputFormat === "human") {
7439
- success(`${successLabel} updated for analysis ${analysisId}`);
7614
+ success(`${successLabel} updated for analysis ${analysisId}.`);
7440
7615
  } else {
7441
7616
  format(updated, { format: outputFormat });
7442
7617
  }
@@ -7470,7 +7645,8 @@ async function listColumns(analysisId, cmd) {
7470
7645
  const api = createApiClient();
7471
7646
  const columns = await api.analysis.getColumns(analysisId);
7472
7647
  if (columns.length === 0) {
7473
- empty("columns yet \u2014 upload data first");
7648
+ empty("columns", { format: outputFormat });
7649
+ if (outputFormat === "human") hint(`Upload data first: diafunc analyze upload ${analysisId} data.csv`);
7474
7650
  return;
7475
7651
  }
7476
7652
  format(columns, { format: outputFormat, columns: ["name", "valueType"] });
@@ -7482,10 +7658,11 @@ async function listRuns(analysisId, count, cmd) {
7482
7658
  format(runs.map((r) => ({
7483
7659
  runId: r.runId,
7484
7660
  state: r.state,
7485
- submittedAt: r.submittedAt ? new Date(r.submittedAt).toISOString() : "\u2014",
7486
- startedAt: r.startedAt ? new Date(r.startedAt).toISOString() : "\u2014",
7487
- endedAt: r.endedAt ? new Date(r.endedAt).toISOString() : "\u2014",
7488
- evaluationId: r.evaluationId ?? "\u2014"
7661
+ phase: runPhaseCell(r),
7662
+ submittedAt: r.submittedAt,
7663
+ startedAt: r.startedAt,
7664
+ endedAt: r.endedAt,
7665
+ evaluationId: r.evaluationId
7489
7666
  })), {
7490
7667
  format: outputFormat,
7491
7668
  columns: [
@@ -7502,7 +7679,11 @@ async function cancelRun(runId, cmd) {
7502
7679
  const api = createApiClient();
7503
7680
  const run = await api.analysis.cancelRun(runId);
7504
7681
  if (outputFormat === "human") {
7505
- success(`Run ${run.runId} state: ${run.state}`);
7682
+ if (run.state === "CANCELLED") {
7683
+ success(cancelSentence(run));
7684
+ } else {
7685
+ warn(cancelSentence(run));
7686
+ }
7506
7687
  } else {
7507
7688
  format(run, { format: outputFormat });
7508
7689
  }
@@ -7512,16 +7693,24 @@ async function listPresets(cmd) {
7512
7693
  const api = createApiClient();
7513
7694
  const presets = await api.analysis.getPresets();
7514
7695
  format(presets.map((p) => ({
7515
- presetId: p.presetId ?? "\u2014",
7696
+ presetId: p.presetId,
7516
7697
  name: p.name,
7517
7698
  targets: p.targetKeys.join(", "),
7518
7699
  questions: p.questions.length,
7519
- segment: p.segmentKey ?? "\u2014",
7700
+ segment: p.segmentKey,
7520
7701
  hours: p.time,
7521
7702
  budget: p.budget
7522
7703
  })), {
7523
7704
  format: outputFormat,
7524
- columns: ["presetId", "name", "targets", "questions", "segment", "hours", "budget"]
7705
+ columns: [
7706
+ { key: "presetId", kind: "id" },
7707
+ "name",
7708
+ "targets",
7709
+ "questions",
7710
+ "segment",
7711
+ "hours",
7712
+ "budget"
7713
+ ]
7525
7714
  });
7526
7715
  }
7527
7716
  async function getPreset(presetId, cmd) {
@@ -7529,7 +7718,7 @@ async function getPreset(presetId, cmd) {
7529
7718
  const api = createApiClient();
7530
7719
  const opt = await api.analysis.getPreset(presetId);
7531
7720
  if (!opt.preset) {
7532
- console.log(chalk26.dim("Preset not found."));
7721
+ empty("preset found", { format: outputFormat });
7533
7722
  return;
7534
7723
  }
7535
7724
  format(opt.preset, { format: outputFormat });
@@ -7552,7 +7741,7 @@ async function savePreset(options, cmd) {
7552
7741
  async function deletePreset(presetId) {
7553
7742
  const api = createApiClient();
7554
7743
  await api.analysis.deletePreset(presetId);
7555
- success(`Deleted preset ${presetId}`);
7744
+ success(`Deleted preset ${presetId}.`);
7556
7745
  }
7557
7746
  async function listTriggers(analysisId, cmd) {
7558
7747
  const outputFormat = getOutputFormat15(cmd);
@@ -7563,18 +7752,24 @@ async function listTriggers(analysisId, cmd) {
7563
7752
  kind: t.kind,
7564
7753
  schedule: t.scheduleSpec,
7565
7754
  active: t.active,
7566
- nextFireAt: t.nextFireAt ? new Date(t.nextFireAt).toISOString() : "\u2014"
7755
+ nextFireAt: t.nextFireAt
7567
7756
  })), {
7568
7757
  format: outputFormat,
7569
- columns: ["triggerId", "kind", "schedule", "active", "nextFireAt"]
7758
+ columns: [
7759
+ { key: "triggerId", kind: "id" },
7760
+ "kind",
7761
+ "schedule",
7762
+ { key: "active", kind: "boolean" },
7763
+ { key: "nextFireAt", header: "next fire", kind: "date" }
7764
+ ]
7570
7765
  });
7571
7766
  }
7572
7767
  async function createTrigger(analysisId, kind, schedule, cmd) {
7573
7768
  const outputFormat = getOutputFormat15(cmd);
7574
7769
  const upper = kind.toUpperCase();
7575
7770
  if (upper !== "ONCE" && upper !== "CRON") {
7576
- failure(`Invalid kind "${kind}" \u2014 must be ONCE or CRON.`);
7577
- process.exit(1);
7771
+ failure(`Invalid kind "${kind}". Use ONCE or CRON.`);
7772
+ process.exit(EXIT_FAILURE);
7578
7773
  }
7579
7774
  const api = createApiClient();
7580
7775
  const trigger = await api.analysis.createTrigger(analysisId, {
@@ -7586,7 +7781,7 @@ async function createTrigger(analysisId, kind, schedule, cmd) {
7586
7781
  async function deleteTrigger(triggerId) {
7587
7782
  const api = createApiClient();
7588
7783
  await api.analysis.deleteTrigger(triggerId);
7589
- success(`Deleted trigger ${triggerId}`);
7784
+ success(`Deleted trigger ${triggerId}.`);
7590
7785
  }
7591
7786
  async function updateTriggerCmd(triggerId, options, cmd) {
7592
7787
  const outputFormat = getOutputFormat15(cmd);
@@ -7594,14 +7789,14 @@ async function updateTriggerCmd(triggerId, options, cmd) {
7594
7789
  if (options.active !== void 0) {
7595
7790
  const lc = options.active.toLowerCase();
7596
7791
  if (lc !== "true" && lc !== "false") {
7597
- failure(`Invalid --active value "${options.active}" \u2014 must be true or false.`);
7598
- process.exit(1);
7792
+ failure(`Invalid --active value "${options.active}". Use true or false.`);
7793
+ process.exit(EXIT_FAILURE);
7599
7794
  }
7600
7795
  activeFlag = lc === "true";
7601
7796
  }
7602
7797
  if (activeFlag === void 0 && !options.schedule) {
7603
7798
  failure("Pass at least one of --active or --schedule.");
7604
- process.exit(1);
7799
+ process.exit(EXIT_FAILURE);
7605
7800
  }
7606
7801
  const api = createApiClient();
7607
7802
  const trigger = await api.analysis.updateTrigger(triggerId, {
@@ -7612,7 +7807,7 @@ async function updateTriggerCmd(triggerId, options, cmd) {
7612
7807
  }
7613
7808
  function registerAnalyzeCommand(program) {
7614
7809
  const analyze = program.command("analyze").description("Run and manage automatic analyses");
7615
- analyze.command("run", { isDefault: true }).description("Create an analysis from a data file, configure it and run it (the default: `analyze <file>`)").argument("[file]", "CSV or Excel file to analyze").option("--name <name>", "Analysis name (asked for, or derived from the filename)").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC (default: PRIVATE)").option("--hours <hours>", `Computation time in hours (default: ${DEFAULT_HOURS}; preset value used when --preset set)`).option("--budget <credits>", `Credit budget (default: ${DEFAULT_BUDGET}; preset value used when --preset set)`).option("--targets <csv>", "Comma-separated target column names (required when not interactive)").option("--questions <csv>", "Comma-separated questions to answer").option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction at notebook position 0").option("--preset <id>", "Apply a saved preset as defaults (explicit flags override preset values)").option("--no-interactive", "Never prompt; every value a run needs must come from a flag or a preset").action(async (file, options, cmd) => {
7810
+ analyze.command("run", { isDefault: true }).description("Create an analysis from a data file, configure it and run it (the default: `analyze <file>`)").argument("[file]", "Data file to analyze (CSV, Excel, Parquet, JSON and 20+ more formats)").option("--name <name>", "Analysis name (asked for, or derived from the filename)").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC (default: PRIVATE)").option("--hours <hours>", `Computation time (hours). Default ${DEFAULT_HOURS}, the Standard preset; a saved preset applies when omitted`).option("--budget <credits>", `Credit budget. Default ${Number(DEFAULT_BUDGET).toLocaleString("en-US")}, the Standard preset; a saved preset applies when omitted`).option("--targets <csv>", "Comma-separated target column names (required when not interactive)").option("--questions <csv>", "Comma-separated questions to answer").option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").option("--preset <id>", "Apply a saved preset as defaults (explicit flags override it)").action(async (file, options, cmd) => {
7616
7811
  try {
7617
7812
  if (!file) {
7618
7813
  analyze.help();
@@ -7637,7 +7832,7 @@ function registerAnalyzeCommand(program) {
7637
7832
  handleError(error);
7638
7833
  }
7639
7834
  });
7640
- analyze.command("watch").description("Live-monitor the latest run of an analysis").argument("[id]", "Analysis ID (defaults to the most recent)").action(async (id, _options, cmd) => {
7835
+ analyze.command("watch").description("Follow the latest run of an analysis live").argument("[id]", "Analysis ID (defaults to the most recent)").action(async (id, _options, cmd) => {
7641
7836
  try {
7642
7837
  await watchAnalysis(id, cmd);
7643
7838
  } catch (error) {
@@ -7651,21 +7846,21 @@ function registerAnalyzeCommand(program) {
7651
7846
  handleError(error);
7652
7847
  }
7653
7848
  });
7654
- analyze.command("rerun").description("Queue a fresh run on an existing analysis (asks for anything a run still needs)").argument("<id>", "Analysis ID to rerun").option("--no-interactive", "Never prompt; fail if the analysis has no targets, hours or budget").action(async (id, options, cmd) => {
7849
+ analyze.command("rerun").description("Queue a fresh run on an existing analysis (asks for anything a run still needs)").argument("<id>", "Analysis ID to rerun").action(async (id, _options, cmd) => {
7655
7850
  try {
7656
- await rerunAnalysis(id, options, cmd);
7851
+ await rerunAnalysis(id, cmd);
7657
7852
  } catch (error) {
7658
7853
  reportCommandError(error);
7659
7854
  }
7660
7855
  });
7661
- analyze.command("create").description("Create an analysis recipe without uploading data or running").option("--name <name>", "Analysis name").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC", "PRIVATE").option("--hours <h>", "Computation hours").option("--budget <credits>", "Credit budget").option("--targets <csv>", "Comma-separated target column names").option("--questions <csv>", "Comma-separated questions").option("--segment <name>", "Segmentation column").option("--introduction <markdown>", "Markdown introduction").action(async (options, cmd) => {
7856
+ analyze.command("create").description("Create an analysis without uploading data or running it").option("--name <name>", "Analysis name").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC", "PRIVATE").option("--hours <hours>", "Computation time (hours)").option("--budget <credits>", "Credit budget").option("--targets <csv>", "Comma-separated target column names").option("--questions <csv>", "Comma-separated questions").option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").action(async (options, cmd) => {
7662
7857
  try {
7663
- await createRecipe(options, cmd);
7858
+ await createAnalysis(options, cmd);
7664
7859
  } catch (error) {
7665
7860
  handleError(error);
7666
7861
  }
7667
7862
  });
7668
- analyze.command("delete").description("Delete an analysis (cancels in-flight run; removes underlying project)").argument("<id>", "Analysis ID").option("-y, --yes", "Skip confirmation prompt (for CI / scripted use)").action(async (id, options) => {
7863
+ analyze.command("delete").description("Delete an analysis, cancelling any run still in flight").argument("<id>", "Analysis ID").option("-y, --yes", "Skip confirmation prompt (for CI / scripted use)").action(async (id, options) => {
7669
7864
  try {
7670
7865
  await confirmDestructive(`This will permanently delete analysis "${id}".`, { yes: options.yes, resourceId: id });
7671
7866
  await deleteAnalysis(id);
@@ -7686,11 +7881,11 @@ function registerAnalyzeCommand(program) {
7686
7881
  handleError(error);
7687
7882
  }
7688
7883
  });
7689
- analyze.command("description").description("Set or clear the analysis description (empty string clears)").argument("<id>", "Analysis ID").argument("<text>", "New description (empty string to clear)").action(async (id, text, _options, cmd) => {
7884
+ analyze.command("description").description("Set or clear the analysis description (empty string clears)").argument("<id>", "Analysis ID").argument("<text>", "New description (empty string to clear)").action(async (id, text2, _options, cmd) => {
7690
7885
  try {
7691
7886
  await patchAndPrint(
7692
7887
  id,
7693
- text,
7888
+ text2,
7694
7889
  (api, aid, v) => api.analysis.patchDescription(aid, { description: v === "" ? null : v }),
7695
7890
  "Description",
7696
7891
  cmd
@@ -7726,7 +7921,7 @@ function registerAnalyzeCommand(program) {
7726
7921
  handleError(error);
7727
7922
  }
7728
7923
  });
7729
- analyze.command("hours").description("Set the compute-hours budget for the next run").argument("<id>", "Analysis ID").argument("<hours>", "Compute hours (e.g. 4)").action(async (id, hours, _options, cmd) => {
7924
+ analyze.command("hours").description("Set the computation time (hours) for the next run").argument("<id>", "Analysis ID").argument("<hours>", "Computation time (hours), e.g. 4").action(async (id, hours, _options, cmd) => {
7730
7925
  try {
7731
7926
  await patchAndPrint(
7732
7927
  id,
@@ -7739,7 +7934,7 @@ function registerAnalyzeCommand(program) {
7739
7934
  handleError(error);
7740
7935
  }
7741
7936
  });
7742
- analyze.command("budget").description("Set the token-credit budget for the next run").argument("<id>", "Analysis ID").argument("<credits>", "Credit budget (e.g. 10000)").action(async (id, credits, _options, cmd) => {
7937
+ analyze.command("budget").description("Set the credit budget for the next run").argument("<id>", "Analysis ID").argument("<credits>", "Credit budget, e.g. 10000").action(async (id, credits, _options, cmd) => {
7743
7938
  try {
7744
7939
  await patchAndPrint(
7745
7940
  id,
@@ -7793,14 +7988,14 @@ function registerAnalyzeCommand(program) {
7793
7988
  handleError(error);
7794
7989
  }
7795
7990
  });
7796
- analyze.command("upload").description("Replace the analysis raw-data table with a new data table (any supported format \u2014 see `table import-formats`)").argument("<id>", "Analysis ID").argument("[file]", "CSV file to upload").option("--url <url>", "HTTPS URL to fetch the CSV from (mutually exclusive with file)").action(async (id, file, options) => {
7991
+ analyze.command("upload").description("Replace the analysis data with a new file (any supported format; see `table import-formats`)").argument("<id>", "Analysis ID").argument("[file]", "Data file to upload (CSV, Excel, Parquet, JSON and 20+ more formats)").option("--url <url>", "HTTPS URL to fetch the data file from, instead of a file path").action(async (id, file, options) => {
7797
7992
  try {
7798
7993
  await uploadData(id, file, options);
7799
7994
  } catch (error) {
7800
7995
  handleError(error);
7801
7996
  }
7802
7997
  });
7803
- analyze.command("columns").description("List columns of the analysis raw-data table").argument("<id>", "Analysis ID").action(async (id, _options, cmd) => {
7998
+ analyze.command("columns").description("List the columns of the analysis data").argument("<id>", "Analysis ID").action(async (id, _options, cmd) => {
7804
7999
  try {
7805
8000
  await listColumns(id, cmd);
7806
8001
  } catch (error) {
@@ -7814,7 +8009,7 @@ function registerAnalyzeCommand(program) {
7814
8009
  handleError(error);
7815
8010
  }
7816
8011
  });
7817
- analyze.command("cancel").description("Cancel a non-terminal run (idempotent on terminal runs)").argument("<runId>", "Run ID to cancel").action(async (runId, _options, cmd) => {
8012
+ analyze.command("cancel").description("Cancel a run that has not finished (a finished run is left as it is)").argument("<runId>", "Run ID to cancel").action(async (runId, _options, cmd) => {
7818
8013
  try {
7819
8014
  await cancelRun(runId, cmd);
7820
8015
  } catch (error) {
@@ -7836,7 +8031,7 @@ function registerAnalyzeCommand(program) {
7836
8031
  handleError(error);
7837
8032
  }
7838
8033
  });
7839
- presets.command("save").description("Create a new preset (omit --id) or update an existing one (with --id)").requiredOption("--name <name>", "Preset name").requiredOption("--targets <csv>", "Comma-separated target column names").requiredOption("--hours <h>", "Compute hours").requiredOption("--budget <credits>", "Credit budget").option("--questions <csv>", "Comma-separated questions").option("--segment <name>", "Segmentation column").option("--id <id>", "Existing preset ID (update mode)").action(async (options, cmd) => {
8034
+ presets.command("save").description("Create a new preset (omit --id) or update an existing one (with --id)").requiredOption("--name <name>", "Preset name").requiredOption("--targets <csv>", "Comma-separated target column names").requiredOption("--hours <hours>", "Computation time (hours)").requiredOption("--budget <credits>", "Credit budget").option("--questions <csv>", "Comma-separated questions").option("--segment <name>", "Column to segment the analysis by").option("--id <id>", "Existing preset ID (update mode)").action(async (options, cmd) => {
7840
8035
  try {
7841
8036
  await savePreset(options, cmd);
7842
8037
  } catch (error) {
@@ -7874,7 +8069,7 @@ function registerAnalyzeCommand(program) {
7874
8069
  handleError(error);
7875
8070
  }
7876
8071
  });
7877
- triggers.command("update").description("Update a trigger \u2014 pause/resume (--active) and/or reschedule (--schedule)").argument("<triggerId>", "Trigger ID").option("--active <bool>", "true to resume, false to pause").option("--schedule <spec>", "New schedule spec (ISO-8601 instant for ONCE, Quartz cron for CRON)").action(async (triggerId, options, cmd) => {
8072
+ triggers.command("update").description("Update a trigger: pause or resume it (--active), reschedule it (--schedule), or both").argument("<triggerId>", "Trigger ID").option("--active <bool>", "true to resume, false to pause").option("--schedule <spec>", "New schedule spec (ISO-8601 instant for ONCE, Quartz cron for CRON)").action(async (triggerId, options, cmd) => {
7878
8073
  try {
7879
8074
  await updateTriggerCmd(triggerId, options, cmd);
7880
8075
  } catch (error) {
@@ -7884,7 +8079,7 @@ function registerAnalyzeCommand(program) {
7884
8079
  }
7885
8080
 
7886
8081
  // src/commands/data-sources/index.ts
7887
- import chalk27 from "chalk";
8082
+ import chalk26 from "chalk";
7888
8083
  function getOutputFormat16(cmd) {
7889
8084
  const config = loadConfig();
7890
8085
  const globalOpts = cmd.optsWithGlobals();
@@ -7896,12 +8091,12 @@ function parseConfigPairs(pairs) {
7896
8091
  for (const pair of pairs) {
7897
8092
  const idx = pair.indexOf("=");
7898
8093
  if (idx <= 0) {
7899
- throw new Error(`Invalid --config "${pair}" \u2014 expected key=value.`);
8094
+ throw new Error(`Invalid --config "${pair}". Expected key=value.`);
7900
8095
  }
7901
8096
  const key = pair.substring(0, idx).trim();
7902
8097
  const value = pair.substring(idx + 1);
7903
8098
  if (!key) {
7904
- throw new Error(`Invalid --config "${pair}" \u2014 empty key.`);
8099
+ throw new Error(`Invalid --config "${pair}". The key is empty.`);
7905
8100
  }
7906
8101
  out[key] = value;
7907
8102
  }
@@ -8020,7 +8215,7 @@ async function showDashboard(projectId, cmd) {
8020
8215
  return;
8021
8216
  }
8022
8217
  const r = dashboard.rollup;
8023
- let line = chalk27.bold(`DataSources in ${projectId}: `) + `${r.totalSources} total, ${r.scheduledSources} scheduled, ${r.sourcesWithRecentFailure} failing recently`;
8218
+ let line = chalk26.bold(`DataSources in ${projectId}: `) + `${r.totalSources} total, ${r.scheduledSources} scheduled, ${r.sourcesWithRecentFailure} failing recently`;
8024
8219
  if (r.lastActivityAt) line += `, last activity ${r.lastActivityAt}`;
8025
8220
  console.log(line);
8026
8221
  if (dashboard.sources.length === 0) {
@@ -8058,8 +8253,8 @@ async function createDataSource(options, cmd) {
8058
8253
  const ds = await api.storage.createDataSource(request);
8059
8254
  if (outputFormat === "human") {
8060
8255
  success(`Created data source ${ds.id}`);
8061
- console.log(chalk27.dim(` Last run: ${ds.lastRunStatus ?? "\u2014"}`));
8062
- if (ds.lastRunError) console.log(chalk27.dim(` Error: ${ds.lastRunError}`));
8256
+ console.log(chalk26.dim(` Last run: ${ds.lastRunStatus ?? "\u2014"}`));
8257
+ if (ds.lastRunError) console.log(chalk26.dim(` Error: ${ds.lastRunError}`));
8063
8258
  } else {
8064
8259
  format(ds, { format: outputFormat });
8065
8260
  }
@@ -8104,8 +8299,8 @@ async function refreshDataSource(id, cmd) {
8104
8299
  const api = createApiClient();
8105
8300
  const run = await api.storage.refreshDataSource(id);
8106
8301
  if (outputFormat === "human") {
8107
- success(`Refresh queued \u2014 run ${run.runId}, status ${run.status}`);
8108
- if (run.errorMessage) console.log(chalk27.red(` Error: ${run.errorMessage}`));
8302
+ success(`Refresh queued: run ${run.runId}, status ${run.status}.`);
8303
+ if (run.errorMessage) console.log(chalk26.red(` Error: ${run.errorMessage}`));
8109
8304
  } else {
8110
8305
  format(run, { format: outputFormat });
8111
8306
  }
@@ -8179,14 +8374,14 @@ Examples:
8179
8374
  handleError(error);
8180
8375
  }
8181
8376
  });
8182
- dataSources.command("create").description("Create a data source (runs the initial fetch synchronously)").requiredOption("--project-id <id>", "Project ID").requiredOption("--project-branch <branch>", 'Project branch (usually "main")').requiredOption("--target-entity-id <id>", "Target table entity ID").requiredOption("--target-entity-branch <branch>", "Target table entity branch").requiredOption("--name <name>", "Display name").requiredOption("--type <type>", "Connector type (google_sheets, s3_url, jdbc)").option("--config <key=value>", "Connector config field \u2014 repeat for multiple", (value, prev = []) => prev.concat([value]), []).option("--schedule-cron <expr>", 'Quartz cron expression (e.g. "0 0 2 * * ?" for daily 02:00 UTC); omit for manual-only').action(async (options, cmd) => {
8377
+ dataSources.command("create").description("Create a data source (runs the initial fetch synchronously)").requiredOption("--project-id <id>", "Project ID").requiredOption("--project-branch <branch>", 'Project branch (usually "main")').requiredOption("--target-entity-id <id>", "Target table entity ID").requiredOption("--target-entity-branch <branch>", "Target table entity branch").requiredOption("--name <name>", "Display name").requiredOption("--type <type>", "Connector type (google_sheets, s3_url, jdbc)").option("--config <key=value>", "Connector config field; repeat for multiple", (value, prev = []) => prev.concat([value]), []).option("--schedule-cron <expr>", 'Quartz cron expression (e.g. "0 0 2 * * ?" for daily 02:00 UTC); omit for manual-only').action(async (options, cmd) => {
8183
8378
  try {
8184
8379
  await createDataSource(options, cmd);
8185
8380
  } catch (error) {
8186
8381
  handleError(error);
8187
8382
  }
8188
8383
  });
8189
- dataSources.command("update").description("Update a data source (omit a flag to leave that field unchanged)").argument("<id>", "Data source ID").option("--name <name>", "New display name").option("--type <type>", "New connector type").option("--config <key=value>", 'Replace the entire config map \u2014 repeat for multiple. Send "[redacted]" as a value to keep the existing encrypted credential.', (value, prev = []) => prev.concat([value]), []).option("--schedule-cron <expr>", "New Quartz cron expression").option("--clear-schedule", "Switch this data source to manual-only").action(async (id, options, cmd) => {
8384
+ dataSources.command("update").description("Update a data source (omit a flag to leave that field unchanged)").argument("<id>", "Data source ID").option("--name <name>", "New display name").option("--type <type>", "New connector type").option("--config <key=value>", 'Replace the entire config map; repeat for multiple. Send "[redacted]" as a value to keep the existing encrypted credential.', (value, prev = []) => prev.concat([value]), []).option("--schedule-cron <expr>", "New Quartz cron expression").option("--clear-schedule", "Switch this data source to manual-only").action(async (id, options, cmd) => {
8190
8385
  try {
8191
8386
  await updateDataSource(id, options, cmd);
8192
8387
  } catch (error) {
@@ -8232,14 +8427,14 @@ Examples:
8232
8427
  }
8233
8428
 
8234
8429
  // src/commands/table-exporters/index.ts
8235
- import chalk28 from "chalk";
8430
+ import chalk27 from "chalk";
8236
8431
  function getOutputFormat17(cmd) {
8237
8432
  const config = loadConfig();
8238
8433
  const globalOpts = cmd.optsWithGlobals();
8239
8434
  return globalOpts.output ?? config.defaults.output ?? "human";
8240
8435
  }
8241
8436
  function registerTableExportersCommands(program) {
8242
- const exporters = program.command("table-exporters").description("Manage user-defined exporters (UDE) \u2014 admin-only");
8437
+ const exporters = program.command("table-exporters").description("Manage user-defined exporters (UDE); admin only");
8243
8438
  exporters.command("list").description("List all registered user-defined exporters").action(async (_options, cmd) => {
8244
8439
  try {
8245
8440
  const outputFormat = getOutputFormat17(cmd);
@@ -8263,7 +8458,7 @@ function registerTableExportersCommands(program) {
8263
8458
  format: outputFormat,
8264
8459
  columns: ["id", "name", "format", "extension", "mimeType", "priority", "function", "createdBy"]
8265
8460
  });
8266
- console.log(chalk28.dim(`${list.length} exporter(s)`));
8461
+ console.log(chalk27.dim(`${list.length} exporter(s)`));
8267
8462
  } catch (error) {
8268
8463
  handleError(error);
8269
8464
  }
@@ -8321,7 +8516,7 @@ function registerTableExportersCommands(program) {
8321
8516
  }
8322
8517
 
8323
8518
  // src/commands/skeleton/index.ts
8324
- import chalk29 from "chalk";
8519
+ import chalk28 from "chalk";
8325
8520
  import * as fs9 from "fs";
8326
8521
  function getOutputFormat18(cmd) {
8327
8522
  const config = loadConfig();
@@ -8357,7 +8552,7 @@ function parseWeight(raw) {
8357
8552
  if (raw === void 0) return null;
8358
8553
  const value = Number(raw);
8359
8554
  if (!Number.isFinite(value) || value <= 0) {
8360
- throw new Error(`Invalid --weight "${raw}" \u2014 must be a positive number.`);
8555
+ throw new Error(`Invalid --weight "${raw}". Use a positive number.`);
8361
8556
  }
8362
8557
  return value;
8363
8558
  }
@@ -8388,10 +8583,10 @@ async function createSkeleton(options, cmd) {
8388
8583
  const skeleton = await api.storage.createSkeleton(request);
8389
8584
  if (outputFormat === "human") {
8390
8585
  success(`Created skeleton ${skeleton.id}`);
8391
- console.log(chalk29.dim(` name: ${skeleton.name}`));
8392
- console.log(chalk29.dim(` template: ${skeleton.template}`));
8393
- console.log(chalk29.dim(` paramCount: ${skeleton.paramCount}`));
8394
- console.log(chalk29.dim(` weight: ${skeleton.weight}`));
8586
+ console.log(chalk28.dim(` name: ${skeleton.name}`));
8587
+ console.log(chalk28.dim(` template: ${skeleton.template}`));
8588
+ console.log(chalk28.dim(` paramCount: ${skeleton.paramCount}`));
8589
+ console.log(chalk28.dim(` weight: ${skeleton.weight}`));
8395
8590
  } else {
8396
8591
  format(skeleton, { format: outputFormat });
8397
8592
  }
@@ -8430,10 +8625,10 @@ async function updateSkeleton(id, options, cmd) {
8430
8625
  const skeleton = await api.storage.updateSkeleton(id, request);
8431
8626
  if (outputFormat === "human") {
8432
8627
  success(`Updated skeleton ${skeleton.id}`);
8433
- console.log(chalk29.dim(` name: ${skeleton.name}`));
8434
- console.log(chalk29.dim(` template: ${skeleton.template}`));
8435
- console.log(chalk29.dim(` paramCount: ${skeleton.paramCount}`));
8436
- console.log(chalk29.dim(` weight: ${skeleton.weight}`));
8628
+ console.log(chalk28.dim(` name: ${skeleton.name}`));
8629
+ console.log(chalk28.dim(` template: ${skeleton.template}`));
8630
+ console.log(chalk28.dim(` paramCount: ${skeleton.paramCount}`));
8631
+ console.log(chalk28.dim(` weight: ${skeleton.weight}`));
8437
8632
  } else {
8438
8633
  format(skeleton, { format: outputFormat });
8439
8634
  }
@@ -8750,7 +8945,7 @@ function registerCompletionCommand(program) {
8750
8945
  }
8751
8946
 
8752
8947
  // src/commands/whoami/index.ts
8753
- import chalk30 from "chalk";
8948
+ import chalk29 from "chalk";
8754
8949
  function registerWhoamiCommand(program) {
8755
8950
  program.command("whoami").description("Show the currently authenticated user").action(async (_options, cmd) => {
8756
8951
  try {
@@ -8760,8 +8955,8 @@ function registerWhoamiCommand(program) {
8760
8955
  const api = createApiClient();
8761
8956
  const user = await api.admin.getMyUser();
8762
8957
  if (outputFormat === "human") {
8763
- console.log(chalk30.bold(user.name) + chalk30.dim(` <${user.email}>`));
8764
- console.log(chalk30.dim(` Role: ${user.role} \xB7 Remaining credits: ${user.remainingCredits} \xB7 Profile: ${config.currentProfile}`));
8958
+ console.log(chalk29.bold(user.name) + chalk29.dim(` <${user.email}>`));
8959
+ console.log(chalk29.dim(` Role: ${user.role} \xB7 Remaining credits: ${user.remainingCredits} \xB7 Profile: ${config.currentProfile}`));
8765
8960
  } else {
8766
8961
  format(user, { format: outputFormat });
8767
8962
  }
@@ -8772,7 +8967,7 @@ function registerWhoamiCommand(program) {
8772
8967
  }
8773
8968
 
8774
8969
  // src/commands/utilization/index.ts
8775
- import chalk31 from "chalk";
8970
+ import chalk30 from "chalk";
8776
8971
  function getOutputFormat19(cmd) {
8777
8972
  const config = loadConfig();
8778
8973
  const globalOpts = cmd.optsWithGlobals();
@@ -8788,20 +8983,45 @@ function windowLabel(u) {
8788
8983
  return `billing cycle ${u.year}-${String(u.month).padStart(2, "0")}`;
8789
8984
  }
8790
8985
  function printUtilizationHuman(u, label) {
8791
- const when = windowLabel(u);
8792
- console.log(label ? chalk31.bold(label) + " " + chalk31.dim(when) : chalk31.bold(when));
8986
+ const when2 = windowLabel(u);
8987
+ console.log(label ? chalk30.bold(label) + " " + chalk30.dim(when2) : chalk30.bold(when2));
8793
8988
  if (u.types.length === 0) {
8794
- console.log(chalk31.dim(" (no usage)"));
8989
+ console.log(chalk30.dim(" (no usage)"));
8795
8990
  return;
8796
8991
  }
8797
8992
  const types = [...u.types].sort((a, b) => b.credits - a.credits);
8798
8993
  const width = Math.max(...types.map((t) => t.type.length));
8799
8994
  for (const t of types) {
8800
- const line = ` ${t.type.padEnd(width)} ${formatNumber(t.quantity).padStart(12)} ${chalk31.dim("credits")} ${t.credits.toFixed(2).padStart(10)}`;
8801
- console.log(t.credits === 0 ? chalk31.dim(line) : line);
8995
+ const line = ` ${t.type.padEnd(width)} ${formatNumber(t.quantity).padStart(12)} ${chalk30.dim("credits")} ${t.credits.toFixed(2).padStart(10)}`;
8996
+ console.log(t.credits === 0 ? chalk30.dim(line) : line);
8802
8997
  }
8803
8998
  const total = u.totalCredits ?? u.types.reduce((s, t) => s + t.credits, 0);
8804
- console.log(chalk31.bold(` ${"Total".padEnd(width)} ${" ".repeat(12)} ${chalk31.dim("credits")} ${total.toFixed(2).padStart(10)}`));
8999
+ console.log(chalk30.bold(` ${"Total".padEnd(width)} ${" ".repeat(12)} ${chalk30.dim("credits")} ${total.toFixed(2).padStart(10)}`));
9000
+ }
9001
+ function formatDailyHistory(history) {
9002
+ const spentOn = (u) => u.dailyCredits ?? u.types.reduce((sum, t) => sum + (t.dailyCredits ?? 0), 0);
9003
+ const costly = (u) => u.types.filter((t) => (t.dailyCredits ?? 0) > 0).sort((a, b) => (b.dailyCredits ?? 0) - (a.dailyCredits ?? 0));
9004
+ const totalLabel = `Total, ${history.length} ${history.length === 1 ? "day" : "days"}`;
9005
+ const width = Math.max(
9006
+ totalLabel.length,
9007
+ ...history.map((u) => windowLabel(u).length),
9008
+ ...history.flatMap((u) => costly(u).map((t) => t.type.length + 2))
9009
+ );
9010
+ const amount = (credits) => credits.toFixed(2).padStart(10);
9011
+ const lines = [];
9012
+ let total = 0;
9013
+ for (const u of history) {
9014
+ const spent = spentOn(u);
9015
+ total += spent;
9016
+ const line = `${windowLabel(u).padEnd(width)} ${amount(spent)} ${chalk30.dim("credits")}`;
9017
+ lines.push(spent > 0 ? chalk30.bold(line) : chalk30.dim(line));
9018
+ for (const t of costly(u)) {
9019
+ lines.push(` ${t.type.padEnd(width - 2)} ${amount(t.dailyCredits ?? 0)}`);
9020
+ }
9021
+ }
9022
+ lines.push("");
9023
+ lines.push(chalk30.bold(`${totalLabel.padEnd(width)} ${amount(total)} ${chalk30.dim("credits")}`));
9024
+ return lines;
8805
9025
  }
8806
9026
  function registerUtilizationCommand(program) {
8807
9027
  const util = program.command("utilization").description("Show credit utilization for the current billing cycle").addHelpText("after", `
@@ -8825,7 +9045,7 @@ Examples:
8825
9045
  handleError(error);
8826
9046
  }
8827
9047
  });
8828
- util.command("history").description("Show utilization history").action(async (_options, cmd) => {
9048
+ util.command("history").description("Show what each day of the billing cycle cost").action(async (_options, cmd) => {
8829
9049
  try {
8830
9050
  const outputFormat = getOutputFormat19(cmd);
8831
9051
  const api = createApiClient();
@@ -8835,9 +9055,8 @@ Examples:
8835
9055
  empty("usage recorded");
8836
9056
  return;
8837
9057
  }
8838
- for (const u of history) {
8839
- printUtilizationHuman(u);
8840
- console.log();
9058
+ for (const line of formatDailyHistory(history)) {
9059
+ console.log(line);
8841
9060
  }
8842
9061
  } else {
8843
9062
  format(history, { format: outputFormat });
@@ -9004,7 +9223,7 @@ Examples:
9004
9223
  }
9005
9224
 
9006
9225
  // src/commands/shell/index.ts
9007
- import chalk32 from "chalk";
9226
+ import chalk31 from "chalk";
9008
9227
  import * as fs11 from "fs";
9009
9228
  import * as os3 from "os";
9010
9229
  import * as path8 from "path";
@@ -9070,21 +9289,21 @@ async function evaluate(api, fnRef, language, sourceCode) {
9070
9289
  }, false);
9071
9290
  if (result.outputs?.length) {
9072
9291
  for (const out of result.outputs) {
9073
- console.log(chalk32.dim(` [${out.type}]`) + " " + out.output);
9292
+ console.log(chalk31.dim(` [${out.type}]`) + " " + out.output);
9074
9293
  }
9075
9294
  }
9076
9295
  if (result.successful) {
9077
9296
  if (result.result) {
9078
- console.log(chalk32.green("=>") + " " + result.result);
9297
+ console.log(chalk31.green("=>") + " " + result.result);
9079
9298
  } else {
9080
- console.log(chalk32.dim("=> (no value)"));
9299
+ console.log(chalk31.dim("=> (no value)"));
9081
9300
  }
9082
9301
  const duration = result.completed - result.started;
9083
- console.log(chalk32.dim(` [${duration}ms \xB7 ${evaluationId}]`));
9302
+ console.log(chalk31.dim(` [${duration}ms \xB7 ${evaluationId}]`));
9084
9303
  } else {
9085
- console.log(chalk32.red("error: ") + result.error);
9304
+ console.log(chalk31.red("error: ") + result.error);
9086
9305
  if (result.lineNumber > 0) {
9087
- console.log(chalk32.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));
9306
+ console.log(chalk31.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));
9088
9307
  }
9089
9308
  }
9090
9309
  }
@@ -9105,19 +9324,19 @@ function registerShellCommand(program) {
9105
9324
  });
9106
9325
  const api = createApiClient();
9107
9326
  const { input: promptInput } = await import("@inquirer/prompts");
9108
- const { getUpdateNotice } = await import("./update-check-ZCS3IYOZ.js");
9327
+ const { getUpdateNotice } = await import("./update-check-V23VUFO4.js");
9109
9328
  const resolvedLanguage = await resolveLanguage(api, fnRef.projectId, options.language);
9110
- console.log(chalk32.bold("Diafunc shell") + chalk32.dim(` \xB7 function ${fnRef.entityId} \xB7 ${resolvedLanguage}`));
9111
- console.log(chalk32.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
9112
- console.log(chalk32.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
9329
+ console.log(chalk31.bold("Diafunc shell") + chalk31.dim(` \xB7 function ${fnRef.entityId} \xB7 ${resolvedLanguage}`));
9330
+ console.log(chalk31.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
9331
+ console.log(chalk31.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
9113
9332
  const notice = await getUpdateNotice();
9114
- if (notice) console.log(chalk32.dim(notice));
9333
+ if (notice) console.log(chalk31.dim(notice));
9115
9334
  console.log();
9116
9335
  let language = resolvedLanguage;
9117
9336
  for (; ; ) {
9118
9337
  let line;
9119
9338
  try {
9120
- line = await promptInput({ message: chalk32.cyan.bold(`${language} >`) });
9339
+ line = await promptInput({ message: chalk31.cyan.bold(`${language} >`) });
9121
9340
  } catch {
9122
9341
  console.log();
9123
9342
  return;
@@ -9135,54 +9354,54 @@ function registerShellCommand(program) {
9135
9354
  case "help":
9136
9355
  case "h":
9137
9356
  case "?":
9138
- console.log(chalk32.dim(" /edit open $EDITOR for multi-line code"));
9139
- console.log(chalk32.dim(" /file <path> evaluate the contents of a file"));
9140
- console.log(chalk32.dim(" /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)"));
9141
- console.log(chalk32.dim(" /quit exit the shell"));
9357
+ console.log(chalk31.dim(" /edit open $EDITOR for multi-line code"));
9358
+ console.log(chalk31.dim(" /file <path> evaluate the contents of a file"));
9359
+ console.log(chalk31.dim(" /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)"));
9360
+ console.log(chalk31.dim(" /quit exit the shell"));
9142
9361
  continue;
9143
9362
  case "lang":
9144
9363
  if (arg) language = arg;
9145
- console.log(chalk32.dim(`Language: ${language}`));
9364
+ console.log(chalk31.dim(`Language: ${language}`));
9146
9365
  continue;
9147
9366
  case "edit": {
9148
9367
  const sourceCode = await openInEditor("", extensionFor2(language));
9149
9368
  if (!sourceCode.trim()) {
9150
- console.log(chalk32.dim("(empty \u2014 not evaluated)"));
9369
+ console.log(chalk31.dim("(empty; not evaluated)"));
9151
9370
  continue;
9152
9371
  }
9153
9372
  try {
9154
9373
  await evaluate(api, fnRef, language, sourceCode);
9155
9374
  } catch (e) {
9156
- console.error(chalk32.red(e.message));
9375
+ console.error(chalk31.red(e.message));
9157
9376
  }
9158
9377
  continue;
9159
9378
  }
9160
9379
  case "file": {
9161
9380
  if (!arg) {
9162
- console.log(chalk32.dim("usage: /file <path>"));
9381
+ console.log(chalk31.dim("usage: /file <path>"));
9163
9382
  continue;
9164
9383
  }
9165
9384
  if (!fs11.existsSync(arg)) {
9166
- console.log(chalk32.red(`file not found: ${arg}`));
9385
+ console.log(chalk31.red(`file not found: ${arg}`));
9167
9386
  continue;
9168
9387
  }
9169
9388
  const sourceCode = fs11.readFileSync(arg, "utf-8");
9170
9389
  try {
9171
9390
  await evaluate(api, fnRef, language, sourceCode);
9172
9391
  } catch (e) {
9173
- console.error(chalk32.red(e.message));
9392
+ console.error(chalk31.red(e.message));
9174
9393
  }
9175
9394
  continue;
9176
9395
  }
9177
9396
  default:
9178
- console.log(chalk32.dim(`Unknown command: /${cmd2}. Try /help.`));
9397
+ console.log(chalk31.dim(`Unknown command: /${cmd2}. Try /help.`));
9179
9398
  continue;
9180
9399
  }
9181
9400
  }
9182
9401
  try {
9183
9402
  await evaluate(api, fnRef, language, trimmed);
9184
9403
  } catch (e) {
9185
- console.error(chalk32.red(e.message));
9404
+ console.error(chalk31.red(e.message));
9186
9405
  }
9187
9406
  }
9188
9407
  } catch (error) {
@@ -9192,7 +9411,7 @@ function registerShellCommand(program) {
9192
9411
  }
9193
9412
 
9194
9413
  // src/commands/update/index.ts
9195
- import chalk33 from "chalk";
9414
+ import chalk32 from "chalk";
9196
9415
  import * as path9 from "path";
9197
9416
  import { spawn as spawn4 } from "child_process";
9198
9417
 
@@ -9238,14 +9457,14 @@ function registerUpdateCommand(program) {
9238
9457
  const install = detectInstall();
9239
9458
  const latest = await fetchLatestVersion();
9240
9459
  if (latest === package_default.version) {
9241
- console.log(chalk33.dim(`diafunc is already at the latest version (${package_default.version}).`));
9460
+ console.log(chalk32.dim(`diafunc is already at the latest version (${package_default.version}).`));
9242
9461
  return;
9243
9462
  }
9244
- console.log(chalk33.dim(`Current: ${package_default.version} \u2192 Available: ${latest}`));
9463
+ console.log(chalk32.dim(`Current: ${package_default.version} \u2192 Available: ${latest}`));
9245
9464
  if (install.method === "npm") {
9246
9465
  console.log();
9247
9466
  console.log("Installed via npm. Upgrade with:");
9248
- console.log(chalk33.bold(` npm install -g @diafunc/cli@${latest}`));
9467
+ console.log(chalk32.bold(` npm install -g @diafunc/cli@${latest}`));
9249
9468
  return;
9250
9469
  }
9251
9470
  const installDir = path9.dirname(install.binaryPath);
@@ -9259,7 +9478,7 @@ function registerUpdateCommand(program) {
9259
9478
  }
9260
9479
 
9261
9480
  // src/commands/uninstall/index.ts
9262
- import chalk34 from "chalk";
9481
+ import chalk33 from "chalk";
9263
9482
  import { spawn as spawn5 } from "child_process";
9264
9483
  import * as fs13 from "fs";
9265
9484
  import * as os4 from "os";
@@ -9271,11 +9490,11 @@ function registerUninstallCommand(program) {
9271
9490
  const configDir = path10.join(os4.homedir(), ".diafunc");
9272
9491
  if (install.method === "npm") {
9273
9492
  console.log("Installed via npm. Remove with:");
9274
- console.log(chalk34.bold(" npm uninstall -g @diafunc/cli"));
9493
+ console.log(chalk33.bold(" npm uninstall -g @diafunc/cli"));
9275
9494
  if (fs13.existsSync(configDir)) {
9276
9495
  console.log();
9277
- console.log(`Config + credentials live at ${configDir} \u2014 remove manually with:`);
9278
- console.log(chalk34.bold(` rm -rf ${configDir}`));
9496
+ console.log(`Config and credentials live at ${configDir}. Remove them manually with:`);
9497
+ console.log(chalk33.bold(` rm -rf ${configDir}`));
9279
9498
  }
9280
9499
  return;
9281
9500
  }
@@ -9285,7 +9504,7 @@ function registerUninstallCommand(program) {
9285
9504
  default: false
9286
9505
  });
9287
9506
  if (!removeBinary) {
9288
- console.log(chalk34.dim("Aborted."));
9507
+ console.log(chalk33.dim("Aborted."));
9289
9508
  return;
9290
9509
  }
9291
9510
  let removeConfig = options.purge ?? false;
@@ -9297,7 +9516,7 @@ function registerUninstallCommand(program) {
9297
9516
  }
9298
9517
  if (removeConfig && fs13.existsSync(configDir)) {
9299
9518
  fs13.rmSync(configDir, { recursive: true, force: true });
9300
- console.log(chalk34.dim(`Removed ${configDir}`));
9519
+ console.log(chalk33.dim(`Removed ${configDir}`));
9301
9520
  }
9302
9521
  if (process.platform === "win32") {
9303
9522
  const cmd = `timeout /t 2 /nobreak >nul & del /f /q "${install.binaryPath}"`;
@@ -9307,13 +9526,13 @@ function registerUninstallCommand(program) {
9307
9526
  windowsHide: true
9308
9527
  });
9309
9528
  child.unref();
9310
- console.log(chalk34.dim(`Removing ${install.binaryPath} on exit...`));
9529
+ console.log(chalk33.dim(`Removing ${install.binaryPath} on exit...`));
9311
9530
  console.log();
9312
9531
  console.log("diafunc uninstalled.");
9313
9532
  return;
9314
9533
  }
9315
9534
  fs13.rmSync(install.binaryPath, { force: true });
9316
- console.log(chalk34.dim(`Removed ${install.binaryPath}`));
9535
+ console.log(chalk33.dim(`Removed ${install.binaryPath}`));
9317
9536
  console.log();
9318
9537
  console.log("diafunc uninstalled.");
9319
9538
  } catch (error) {
@@ -9322,6 +9541,757 @@ function registerUninstallCommand(program) {
9322
9541
  });
9323
9542
  }
9324
9543
 
9544
+ // src/prompting/command.ts
9545
+ import { Command } from "commander";
9546
+ var commanderOriginal = Command.prototype;
9547
+ var DiafuncCommand = class _DiafuncCommand extends Command {
9548
+ /** Gaps recorded during the current parse, in the order commander found them. */
9549
+ pendingInputs = [];
9550
+ /** Set on the program only; every command reads it from there. */
9551
+ promptEnvironment = {};
9552
+ createCommand(name) {
9553
+ return new _DiafuncCommand(name);
9554
+ }
9555
+ missingArgument(name) {
9556
+ if (!this.mayPrompt()) {
9557
+ commanderOriginal.missingArgument.call(this, name);
9558
+ return;
9559
+ }
9560
+ const index = this.registeredArguments.findIndex((a) => a.name() === name);
9561
+ const argument = this.registeredArguments[index];
9562
+ this.pendingInputs.push({
9563
+ kind: "argument",
9564
+ name,
9565
+ index,
9566
+ description: argument?.description ?? "",
9567
+ variadic: Boolean(argument?.variadic)
9568
+ });
9569
+ }
9570
+ missingMandatoryOptionValue(option) {
9571
+ if (!this.mayPrompt()) {
9572
+ commanderOriginal.missingMandatoryOptionValue.call(this, option);
9573
+ return;
9574
+ }
9575
+ this.pendingInputs.push({
9576
+ kind: "option",
9577
+ name: option.attributeName(),
9578
+ flag: option.long ?? option.flags,
9579
+ description: option.description ?? "",
9580
+ variadic: Boolean(option.variadic)
9581
+ });
9582
+ }
9583
+ /** The environment set on the program. */
9584
+ environment() {
9585
+ let root = this;
9586
+ while (root.parent) root = root.parent;
9587
+ return root instanceof _DiafuncCommand ? root.promptEnvironment : {};
9588
+ }
9589
+ mayPrompt() {
9590
+ const forced = this.environment().interactive;
9591
+ if (forced !== void 0) return forced;
9592
+ const globals = this.optsWithGlobals();
9593
+ const output = globals.output ?? loadConfig().defaults.output ?? "human";
9594
+ return canPrompt(output, globals.interactive === false);
9595
+ }
9596
+ };
9597
+
9598
+ // src/prompting/fill.ts
9599
+ import chalk35 from "chalk";
9600
+
9601
+ // src/prompting/resolvers.ts
9602
+ var PROJECT_ROLES = ["OWNER", "ADMIN", "DEVELOPER", "GUEST"];
9603
+ var TRIGGER_TYPES = ["SCHEDULE", "EVENT", "LINK", "MANUAL"];
9604
+ var ANALYSIS_TRIGGER_KINDS = ["ONCE", "CRON"];
9605
+ var VISIBILITIES = ["PRIVATE", "PUBLIC"];
9606
+ var SHELLS = ["bash", "zsh", "fish"];
9607
+ var CONFIG_KEYS = ["defaults.project", "defaults.branch", "defaults.output"];
9608
+ var ENTITY_TYPE_BY_GROUP = {
9609
+ table: "table",
9610
+ function: "function",
9611
+ trigger: "function",
9612
+ schedule: "function"
9613
+ };
9614
+ var TEXT = { kind: "text" };
9615
+ var TEXT_OR_EMPTY = { kind: "text", allowEmpty: true };
9616
+ var POSITIVE = { kind: "number", min: 0, integer: false, exclusive: true };
9617
+ var INDEX = { kind: "number", min: 0, integer: true };
9618
+ var BY_COMMAND = {
9619
+ "analyze segment": { "<name>": { kind: "analysisColumns", multiple: false, allowEmpty: true } },
9620
+ "analyze targets": { "<csv>": { kind: "analysisColumns", multiple: true, allowEmpty: false } },
9621
+ "analyze questions": { "<csv>": TEXT_OR_EMPTY },
9622
+ "analyze description": { "<text>": TEXT_OR_EMPTY },
9623
+ "analyze introduction": { "<markdown>": TEXT_OR_EMPTY },
9624
+ "analyze presets save": { "--targets": TEXT, "--hours": POSITIVE, "--budget": POSITIVE },
9625
+ "branch merge": {
9626
+ "--source": { kind: "entity", form: "ref" },
9627
+ "--target": { kind: "project", withBranch: true }
9628
+ },
9629
+ "branch create": { "<branchName>": TEXT },
9630
+ "branch delete": { "<branchName>": { kind: "projectBranch", projectFrom: "projectId" } },
9631
+ "admin backup restore-project": { "<projectBranch>": { kind: "projectBranch", projectFrom: "projectId" } },
9632
+ "data-sources create": {
9633
+ "--project-id": { kind: "project", withBranch: false },
9634
+ "--project-branch": { kind: "projectBranch", projectFrom: "projectId" },
9635
+ "--target-entity-id": { kind: "entity", form: "id", contentType: "table", projectFrom: "projectId" },
9636
+ "--target-entity-branch": { kind: "text", defaultValue: "main" },
9637
+ "--type": { kind: "connectorType" }
9638
+ },
9639
+ "table-exporters create": {
9640
+ "--function-project": { kind: "project", withBranch: false },
9641
+ "--function-entity": { kind: "entity", form: "id", contentType: "function", projectFrom: "functionProject" },
9642
+ "--format": TEXT
9643
+ },
9644
+ "table exports get": { "--ref": { kind: "entity", form: "ref", contentType: "table" } },
9645
+ "table export": { "<format>": { kind: "exportFormat" } },
9646
+ "entity export": { "<entityIds>": { kind: "entity", form: "id", projectFrom: "project", multiple: true } },
9647
+ "notebook export": {
9648
+ "<notebookIds>": { kind: "entity", form: "id", contentType: "notebook", projectFrom: "project", multiple: true }
9649
+ },
9650
+ "link delete": { "<linkId>": { kind: "link" } },
9651
+ "link create": { "<linkId>": TEXT },
9652
+ "config profile use": { "<name>": { kind: "profile" } },
9653
+ "config profile remove": { "<name>": { kind: "profile" } },
9654
+ "config get": { "<key>": { kind: "choice", choices: CONFIG_KEYS } },
9655
+ "config set": { "<key>": { kind: "choice", choices: CONFIG_KEYS } },
9656
+ "project members invite": { "<userId>": TEXT, "<role>": { kind: "choice", choices: PROJECT_ROLES } },
9657
+ "project members join": { "<userId>": TEXT },
9658
+ "trigger create": { "--type": { kind: "choice", choices: TRIGGER_TYPES } },
9659
+ "analyze triggers create": { "--kind": { kind: "choice", choices: ANALYSIS_TRIGGER_KINDS } },
9660
+ "function outputs": { "<evaluationId>": TEXT },
9661
+ "team create": { "--seats": { kind: "number", min: 1, integer: true } },
9662
+ "team seats preview": { "<count>": { kind: "number", min: 1, integer: true } },
9663
+ "team seats set": { "<count>": { kind: "number", min: 1, integer: true } }
9664
+ };
9665
+ var BY_NAME = {
9666
+ projectId: { kind: "project", withBranch: false },
9667
+ projectRef: { kind: "project", withBranch: true },
9668
+ project: { kind: "project", withBranch: true },
9669
+ teamId: { kind: "team" },
9670
+ invitationId: { kind: "teamInvitation" },
9671
+ analysisId: { kind: "analysis" },
9672
+ sessionId: { kind: "chatSession" },
9673
+ tokenId: { kind: "apiToken" },
9674
+ resource: { kind: "tokenResource" },
9675
+ scopes: { kind: "choices", choices: VALID_SCOPES },
9676
+ evaluationId: { kind: "evaluation" },
9677
+ eventId: { kind: "event" },
9678
+ occurrenceId: { kind: "occurrence" },
9679
+ exportId: { kind: "tableExport" },
9680
+ invoiceNumber: { kind: "invoice" },
9681
+ fileName: { kind: "invoiceDocument" },
9682
+ shell: { kind: "choice", choices: SHELLS },
9683
+ vis: { kind: "choice", choices: VISIBILITIES },
9684
+ kind: { kind: "choice", choices: ANALYSIS_TRIGGER_KINDS },
9685
+ date: { kind: "date" },
9686
+ file: { kind: "file" },
9687
+ email: { kind: "text", email: true },
9688
+ index: INDEX,
9689
+ row: INDEX,
9690
+ col: INDEX,
9691
+ count: INDEX,
9692
+ version: { kind: "number", min: 1, integer: true },
9693
+ hours: POSITIVE,
9694
+ credits: POSITIVE,
9695
+ seats: { kind: "number", min: 1, integer: true },
9696
+ value: TEXT_OR_EMPTY,
9697
+ // Free text: names, messages and ids the reader is creating rather than choosing.
9698
+ name: TEXT,
9699
+ newId: TEXT,
9700
+ message: TEXT,
9701
+ query: TEXT,
9702
+ title: TEXT,
9703
+ token: TEXT,
9704
+ subscriptionToken: TEXT,
9705
+ forkProjectId: TEXT,
9706
+ targetBranch: TEXT,
9707
+ bucketName: TEXT,
9708
+ objectName: TEXT,
9709
+ template: TEXT,
9710
+ plan: TEXT,
9711
+ schedule: TEXT,
9712
+ consumerType: TEXT,
9713
+ consumerId: TEXT,
9714
+ format: TEXT,
9715
+ key: TEXT
9716
+ };
9717
+ function tokenOf(input) {
9718
+ return input.kind === "option" ? input.flag ?? `--${input.name}` : `<${input.name}>`;
9719
+ }
9720
+ function specFor(path11, input) {
9721
+ const exact = BY_COMMAND[path11]?.[tokenOf(input)];
9722
+ if (exact) return exact;
9723
+ const group = path11.split(" ")[0];
9724
+ const sub = path11.split(" ").slice(0, 2).join(" ");
9725
+ switch (input.name) {
9726
+ case "ref":
9727
+ case "sourceRef":
9728
+ case "targetRef":
9729
+ return { kind: "entity", form: "ref", contentType: ENTITY_TYPE_BY_GROUP[group] };
9730
+ case "userId":
9731
+ return group === "team" ? { kind: "teamMember" } : { kind: "projectMember" };
9732
+ case "id":
9733
+ if (sub === "analyze presets") return { kind: "preset" };
9734
+ if (group === "analyze") return { kind: "analysis" };
9735
+ if (group === "data-sources") return { kind: "dataSource" };
9736
+ if (group === "skeleton") return { kind: "skeleton" };
9737
+ if (group === "table-exporters") return { kind: "tableExporter" };
9738
+ if (group === "status") return { kind: "statusComponent" };
9739
+ return null;
9740
+ case "runId":
9741
+ if (group === "analyze") return { kind: "analysisRun" };
9742
+ if (group === "data-sources") return { kind: "dataSourceRun" };
9743
+ return null;
9744
+ case "triggerId":
9745
+ if (group === "analyze") return { kind: "analysisTrigger" };
9746
+ if (group === "trigger") return { kind: "functionTrigger" };
9747
+ return null;
9748
+ case "role":
9749
+ return { kind: "choice", choices: PROJECT_ROLES };
9750
+ case "type":
9751
+ return null;
9752
+ default:
9753
+ return BY_NAME[input.name] ?? null;
9754
+ }
9755
+ }
9756
+ function dependencies(spec) {
9757
+ switch (spec.kind) {
9758
+ case "teamMember":
9759
+ case "teamInvitation":
9760
+ return ["teamId"];
9761
+ case "projectMember":
9762
+ return ["projectId"];
9763
+ case "analysisColumns":
9764
+ return ["id"];
9765
+ case "evaluation":
9766
+ return ["ref", "date"];
9767
+ case "functionTrigger":
9768
+ case "event":
9769
+ case "tableExport":
9770
+ return ["ref"];
9771
+ case "occurrence":
9772
+ return ["ref", "eventId"];
9773
+ case "link":
9774
+ return ["sourceRef"];
9775
+ case "tokenResource":
9776
+ return ["resourceType"];
9777
+ case "dataSourceRun":
9778
+ return ["id"];
9779
+ case "invoiceDocument":
9780
+ return ["invoiceNumber"];
9781
+ case "projectBranch":
9782
+ return [spec.projectFrom];
9783
+ case "entity":
9784
+ return spec.projectFrom ? [spec.projectFrom] : [];
9785
+ default:
9786
+ return [];
9787
+ }
9788
+ }
9789
+
9790
+ // src/prompting/pickers.ts
9791
+ import * as fs14 from "fs";
9792
+ import chalk34 from "chalk";
9793
+ var SEARCH_THRESHOLD = 10;
9794
+ var TYPE_IT = "\0type-it";
9795
+ async function askFor(spec, input, ctx) {
9796
+ const prefilled = ctx.prefill.get(input.name);
9797
+ if (prefilled !== void 0) return prefilled;
9798
+ switch (spec.kind) {
9799
+ case "project":
9800
+ return askProject(ctx, spec.withBranch, messageFor(input, "Project"));
9801
+ case "entity":
9802
+ return askEntity(ctx, spec, input);
9803
+ case "team":
9804
+ return listed(ctx, "teams", messageFor(input, "Team"), async () => (await ctx.api().admin.listMyTeams()).map((t) => ({ label: t.name, value: t.id, hint: t.id })));
9805
+ case "teamMember": {
9806
+ const teamId = text(ctx, "teamId");
9807
+ return listed(ctx, "team members", messageFor(input, "Team member"), async () => teamId ? (await ctx.api().admin.listTeamMembers(teamId)).filter((m) => !m.removedAt).map((m) => ({ label: m.name ?? m.email ?? m.userId, value: m.userId, hint: `${m.role} \xB7 ${m.userId}` })) : []);
9808
+ }
9809
+ case "projectMember": {
9810
+ const projectId = text(ctx, "projectId")?.split("/")[0];
9811
+ return listed(ctx, "project members", messageFor(input, "Project member"), async () => projectId ? (await ctx.api().admin.getProjectMembers(projectId)).map((m) => ({ label: m.userId, value: m.userId, hint: m.role })) : []);
9812
+ }
9813
+ case "teamInvitation": {
9814
+ const teamId = text(ctx, "teamId");
9815
+ return listed(ctx, "invitations", messageFor(input, "Invitation"), async () => teamId ? (await ctx.api().admin.listTeamInvitations(teamId)).map((i) => ({ label: i.email, value: i.invitationId, hint: `${i.role} \xB7 ${i.invitationId}` })) : []);
9816
+ }
9817
+ case "analysis":
9818
+ return askAnalysis(ctx, messageFor(input, "Analysis"));
9819
+ case "analysisRun": {
9820
+ const analysisId = text(ctx, "id") ?? await askAnalysis(ctx, "Analysis");
9821
+ return listed(ctx, "runs", messageFor(input, "Run"), async () => {
9822
+ const runs = await ctx.api().analysis.getRunsForAnalysis(analysisId, 20);
9823
+ const unfinished = (s) => !["COMPLETED", "FAILED", "CANCELLED"].includes(s);
9824
+ return [...runs].sort((a, b) => Number(unfinished(b.state)) - Number(unfinished(a.state))).map((r) => ({ label: r.state, value: r.runId, hint: `${when(r.submittedAt)} \xB7 ${r.runId}` }));
9825
+ });
9826
+ }
9827
+ case "preset":
9828
+ return listed(ctx, "presets", messageFor(input, "Preset"), async () => (await ctx.api().analysis.getPresets()).filter((p) => p.presetId).map((p) => ({ label: p.name, value: p.presetId, hint: p.presetId })));
9829
+ case "analysisTrigger": {
9830
+ const analysisId = text(ctx, "analysisId") ?? await askAnalysis(ctx, "Analysis");
9831
+ return listed(ctx, "triggers", messageFor(input, "Trigger"), async () => (await ctx.api().analysis.listTriggers(analysisId)).map((t) => ({
9832
+ label: `${t.kind} ${t.scheduleSpec}`,
9833
+ value: t.triggerId,
9834
+ hint: `${t.active ? "active" : "paused"} \xB7 ${t.triggerId}`
9835
+ })));
9836
+ }
9837
+ case "analysisColumns":
9838
+ return askColumns(ctx, spec, input);
9839
+ case "evaluation":
9840
+ return askEvaluation(ctx, input);
9841
+ case "functionTrigger": {
9842
+ const ref = entityRef(ctx, "ref");
9843
+ return listed(ctx, "triggers", messageFor(input, "Trigger"), async () => ref ? (await ctx.api().evaluation.getTriggers(ref.projectId, ref.projectBranch, ref.entityId, ref.entityBranch)).filter((t) => t.triggerId).map((t) => ({ label: `${t.type}${t.expression ? ` ${t.expression}` : ""}`, value: t.triggerId, hint: t.triggerId })) : []);
9844
+ }
9845
+ case "chatSession":
9846
+ return listed(ctx, "chat sessions", messageFor(input, "Chat session"), async () => (await ctx.api().language.getSessions()).map((s) => ({ label: s.title || "(untitled)", value: s.sessionId, hint: `${s.modified} \xB7 ${s.sessionId}` })));
9847
+ case "apiToken":
9848
+ return listed(ctx, "API tokens", messageFor(input, "API token"), async () => (await ctx.api().admin.getApiTokens()).map((t) => ({
9849
+ label: t.name,
9850
+ value: t.tokenId,
9851
+ hint: `${t.resourceType} ${t.resourceId} \xB7 ${t.scopes.join(",")}`
9852
+ })));
9853
+ case "tokenResource":
9854
+ return text(ctx, "resourceType")?.toLowerCase() === "team" ? listed(ctx, "teams", "Team", async () => (await ctx.api().admin.listMyTeams()).map((t) => ({ label: t.name, value: t.id, hint: t.id }))) : askProject(ctx, false, "Project");
9855
+ case "dataSource":
9856
+ return listed(ctx, "data sources", messageFor(input, "Data source"), async () => (await ctx.api().storage.listDataSources(defaultProject(ctx))).map((d) => ({ label: d.name, value: d.id, hint: `${d.type} \xB7 ${d.id}` })));
9857
+ case "dataSourceRun": {
9858
+ const id = text(ctx, "id");
9859
+ return listed(ctx, "runs", messageFor(input, "Run"), async () => id ? (await ctx.api().storage.listDataSourceRuns(id, 20)).map((r) => ({ label: r.status, value: r.runId, hint: `${r.startedAt ?? ""} \xB7 ${r.runId}` })) : []);
9860
+ }
9861
+ case "skeleton": {
9862
+ const projectId = defaultProject(ctx) ?? await askProject(ctx, false, "Project");
9863
+ return listed(ctx, "skeletons", messageFor(input, "Skeleton"), async () => (await ctx.api().storage.listSkeletons(projectId)).map((s) => ({ label: s.name, value: s.id, hint: `${s.template} \xB7 ${s.id}` })));
9864
+ }
9865
+ case "tableExporter":
9866
+ return listed(ctx, "exporters", messageFor(input, "Exporter"), async () => (await ctx.api().storage.listUserDefinedExporters()).filter((e) => e.id).map((e) => ({ label: e.name, value: e.id, hint: `${e.format} \xB7 ${e.id}` })));
9867
+ case "tableExport": {
9868
+ const ref = entityRef(ctx, "ref");
9869
+ return listed(ctx, "exports", messageFor(input, "Export"), async () => ref ? (await ctx.api().storage.listExports(ref)).map((e) => ({
9870
+ label: e.filename,
9871
+ value: e.exportId,
9872
+ hint: `${e.finished ? e.succeeded ? "done" : "failed" : `${Math.round(e.progress * 100)}%`} \xB7 ${e.exportId}`
9873
+ })) : []);
9874
+ }
9875
+ case "invoice":
9876
+ return listed(ctx, "invoices", messageFor(input, "Invoice"), async () => {
9877
+ const invoices = await ctx.api().admin.getInvoices();
9878
+ for (const i of invoices) ctx.prefill.set(`invoiceKind:${i.invoiceNumber}`, i.kind ?? "INVOICE");
9879
+ return invoices.map((i) => ({
9880
+ label: `#${i.invoiceNumber} ${i.periodFrom ?? ""}\u2013${i.periodTo ?? ""}`,
9881
+ value: String(i.invoiceNumber),
9882
+ hint: `${i.status ?? ""} \xB7 ${i.total ?? ""} ${i.currency ?? ""}`.trim()
9883
+ }));
9884
+ });
9885
+ case "invoiceDocument": {
9886
+ const number = text(ctx, "invoiceNumber");
9887
+ const kind = number ? ctx.prefill.get(`invoiceKind:${number}`) : void 0;
9888
+ const slug = kind && /credit/i.test(kind) ? "credit-note" : "invoice";
9889
+ return typed(ctx, messageFor(input, "Document file name"), { defaultValue: number ? `diafunc-${slug}-${number}.pdf` : void 0 });
9890
+ }
9891
+ case "projectBranch": {
9892
+ const projectId = text(ctx, spec.projectFrom)?.split("/")[0];
9893
+ return listed(ctx, "branches", messageFor(input, "Branch"), async () => projectId ? (await ctx.api().storage.getProjectBranches(projectId)).map((b) => ({ label: b, value: b })) : []);
9894
+ }
9895
+ case "event":
9896
+ return askEvent(ctx, input);
9897
+ case "occurrence": {
9898
+ const ref = entityRef(ctx, "ref");
9899
+ const eventId = text(ctx, "eventId");
9900
+ return listed(ctx, "occurrences", messageFor(input, "Occurrence"), async () => ref ? (await ctx.api().storage.getEvents(ref)).filter((e) => !eventId || e.eventId === eventId).map((e) => ({ label: e.occurrenceId, value: e.occurrenceId, hint: e.type })) : []);
9901
+ }
9902
+ case "link": {
9903
+ const ref = entityRef(ctx, "sourceRef");
9904
+ return listed(ctx, "links", messageFor(input, "Link"), async () => ref ? (await ctx.api().storage.getLinkIds("FORWARD", ref)).map((id) => ({ label: id, value: id })) : []);
9905
+ }
9906
+ case "exportFormat":
9907
+ return listed(ctx, "export formats", messageFor(input, "Export format"), async () => (await ctx.api().storage.getSupportedExportFormats()).formats.map((f) => ({ label: f.displayName, value: f.id, hint: `${f.id} \xB7 ${f.category}` })));
9908
+ case "connectorType":
9909
+ return listed(ctx, "connector types", messageFor(input, "Connector type"), async () => (await ctx.api().storage.listDataSourceConnectorTypes()).map((t) => ({ label: t, value: t })));
9910
+ case "profile":
9911
+ return listed(ctx, "profiles", messageFor(input, "Profile"), async () => Object.keys(loadConfig().profiles).map((p) => ({ label: p, value: p })));
9912
+ case "statusComponent":
9913
+ return listed(ctx, "components", messageFor(input, "Component"), async () => (await createStatusService().getComponents()).map((c) => ({ label: c.id, value: c.id, hint: `${c.state} \xB7 ${c.domainId}` })));
9914
+ case "choice":
9915
+ return choose(ctx, question(input), spec.choices.map((c) => ({ label: c, value: c })));
9916
+ case "choices": {
9917
+ const chosen = await ctx.prompter.checkbox({
9918
+ message: question(input),
9919
+ choices: spec.choices.map((c) => ({ name: c, value: c })),
9920
+ validate: (picked) => picked.length > 0 || "Pick at least one."
9921
+ });
9922
+ return chosen.join(",");
9923
+ }
9924
+ case "file":
9925
+ return typed(ctx, question(input), {
9926
+ validate: (value) => fs14.existsSync(value.trim()) || `No file at ${value.trim()}.`
9927
+ });
9928
+ case "number":
9929
+ return typed(ctx, question(input), { validate: numberRule(spec) });
9930
+ case "date":
9931
+ return typed(ctx, question(input), {
9932
+ defaultValue: currentUtcHour(),
9933
+ validate: (value) => /^\d{4}-\d{2}-\d{2}-\d{2}$/.test(value.trim()) || "Use YYYY-MM-DD-HH, in UTC."
9934
+ });
9935
+ case "text":
9936
+ return typed(ctx, question(input), {
9937
+ allowEmpty: spec.allowEmpty,
9938
+ defaultValue: spec.defaultValue,
9939
+ validate: spec.email ? (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim()) || "That is not an email address." : void 0
9940
+ });
9941
+ }
9942
+ }
9943
+ async function askProject(ctx, withBranch, message) {
9944
+ const projectId = await fromIndex(ctx, message, { contentType: "project" }, (item) => item.projectId);
9945
+ if (!withBranch) return projectId;
9946
+ let branches = [];
9947
+ try {
9948
+ branches = await ctx.api().storage.getProjectBranches(projectId);
9949
+ } catch {
9950
+ }
9951
+ if (branches.length <= 1) return projectId;
9952
+ const branch = await choose(ctx, "Branch", branches.map((b) => ({ label: b, value: b })), "main");
9953
+ return branch === "main" ? projectId : `${projectId}/${branch}`;
9954
+ }
9955
+ async function askEntity(ctx, spec, input) {
9956
+ const { projectId, projectBranch } = await projectContext(ctx, spec.projectFrom);
9957
+ const noun = spec.contentType ? capitalize(spec.contentType) : "Entity";
9958
+ const query = { contentType: spec.contentType, projectId, projectBranch };
9959
+ const answer = (item) => spec.form === "id" ? item.entityId : [item.projectId, item.projectBranch, item.entityId, ...item.entityBranch && item.entityBranch !== "main" ? [item.entityBranch] : []].join("/");
9960
+ if (spec.multiple) {
9961
+ let items = [];
9962
+ try {
9963
+ items = await indexItems(ctx, "*", query, 200);
9964
+ } catch (error) {
9965
+ ctx.note(`Could not list them (${reason(error)}).`);
9966
+ }
9967
+ if (items.length === 0) {
9968
+ const typed2 = await typedValue(ctx, `${question(input)} (space-separated)`);
9969
+ return typed2.split(/[\s,]+/).filter(Boolean);
9970
+ }
9971
+ return ctx.prompter.checkbox({
9972
+ message: messageFor(input, `${noun}s`),
9973
+ choices: items.map((item) => ({ name: labelled(item.name || item.entityId, item.entityId), value: answer(item) })),
9974
+ validate: (picked) => picked.length > 0 || "Pick at least one."
9975
+ });
9976
+ }
9977
+ return fromIndex(ctx, messageFor(input, noun), query, answer);
9978
+ }
9979
+ async function projectContext(ctx, projectFrom) {
9980
+ const config = loadConfig();
9981
+ const raw = (projectFrom ? text(ctx, projectFrom) : void 0) ?? ctx.globals.project ?? config.defaults.project ?? await askProject(ctx, true, "Project");
9982
+ const [projectId, branch] = raw.split("/");
9983
+ return { projectId, projectBranch: branch || ctx.globals.branch || config.defaults.branch || "main" };
9984
+ }
9985
+ var FIRST_PAGE2 = 100;
9986
+ async function fromIndex(ctx, message, query, answer) {
9987
+ let firstPage = null;
9988
+ let warned = false;
9989
+ const toChoice = (item) => ({
9990
+ name: labelled(item.name || item.entityId || item.projectId, item.entityId ?? item.projectId),
9991
+ value: answer(item)
9992
+ });
9993
+ const picked = await ctx.prompter.search({
9994
+ message,
9995
+ source: async (term) => {
9996
+ try {
9997
+ firstPage ??= await indexItems(ctx, "*", query, FIRST_PAGE2);
9998
+ const needle = term.trim().toLowerCase();
9999
+ let items = needle ? firstPage.filter((item) => `${item.name ?? ""} ${item.entityId ?? item.projectId}`.toLowerCase().includes(needle)) : firstPage;
10000
+ if (needle && items.length === 0) items = await indexItems(ctx, term.trim(), query, 30);
10001
+ return [...items.map(toChoice), typeItChoice()];
10002
+ } catch (error) {
10003
+ if (!warned) ctx.note(`Could not search (${reason(error)}).`);
10004
+ warned = true;
10005
+ return [typeItChoice()];
10006
+ }
10007
+ }
10008
+ });
10009
+ return picked === TYPE_IT ? typedValue(ctx, message) : picked;
10010
+ }
10011
+ async function indexItems(ctx, term, query, limit) {
10012
+ const page = await ctx.api().index.searchPage({
10013
+ query: term,
10014
+ limit,
10015
+ contentType: query.contentType ?? null,
10016
+ projectId: query.projectId ?? null,
10017
+ projectBranch: query.projectId ? query.projectBranch ?? "main" : null
10018
+ });
10019
+ const seen = /* @__PURE__ */ new Set();
10020
+ return page.items.filter((item) => {
10021
+ if (query.contentType !== "project" && !item.entityId) return false;
10022
+ const key = [item.contentType, item.projectId, item.projectBranch, item.entityId, item.entityBranch].join("|");
10023
+ if (seen.has(key)) return false;
10024
+ seen.add(key);
10025
+ return true;
10026
+ });
10027
+ }
10028
+ async function askAnalysis(ctx, message) {
10029
+ return listed(ctx, "analyses", message, async () => (await ctx.api().analysis.getRecent(50)).map((a) => ({
10030
+ label: a.name,
10031
+ value: a.analysisId,
10032
+ hint: `${a.latestRunState ?? "never run"} \xB7 ${a.analysisId}`
10033
+ })));
10034
+ }
10035
+ async function askColumns(ctx, spec, input) {
10036
+ const analysisId = text(ctx, "id");
10037
+ let columns = [];
10038
+ try {
10039
+ if (analysisId) columns = (await ctx.api().analysis.getColumns(analysisId)).map((c) => c.name).filter(Boolean);
10040
+ } catch (error) {
10041
+ ctx.note(`Could not read the columns (${reason(error)}).`);
10042
+ }
10043
+ if (columns.length === 0) return typed(ctx, question(input), { allowEmpty: spec.allowEmpty });
10044
+ if (spec.multiple) {
10045
+ const chosen = await ctx.prompter.checkbox({
10046
+ message: messageFor(input, "Columns"),
10047
+ choices: columns.map((c) => ({ name: c, value: c })),
10048
+ validate: (picked) => picked.length > 0 || "Pick at least one column."
10049
+ });
10050
+ return chosen.join(",");
10051
+ }
10052
+ const items = columns.map((c) => ({ label: c, value: c }));
10053
+ if (spec.allowEmpty) items.unshift({ label: "None (clear it)", value: "" });
10054
+ return choose(ctx, messageFor(input, "Column"), items);
10055
+ }
10056
+ async function askEvaluation(ctx, input) {
10057
+ const ref = entityRef(ctx, "ref");
10058
+ const hour = parseHour(text(ctx, "date") ?? currentUtcHour());
10059
+ return listed(ctx, "evaluations in that hour", messageFor(input, "Evaluation"), async () => ref && hour ? (await ctx.api().evaluation.getEvaluations(
10060
+ ref.projectId,
10061
+ ref.projectBranch,
10062
+ ref.entityId,
10063
+ ref.entityBranch,
10064
+ hour.year,
10065
+ hour.month,
10066
+ hour.day,
10067
+ hour.hour
10068
+ )).map((e) => ({ label: e.evaluationId, value: e.evaluationId, hint: e.active ? "running" : "finished" })) : []);
10069
+ }
10070
+ async function askEvent(ctx, input) {
10071
+ const ref = entityRef(ctx, "ref");
10072
+ let events = [];
10073
+ try {
10074
+ if (ref) events = await ctx.api().storage.getEvents(ref);
10075
+ } catch (error) {
10076
+ ctx.note(`Could not list the events (${reason(error)}).`);
10077
+ }
10078
+ if (events.length === 0) return typedValue(ctx, question(input));
10079
+ const key = await choose(ctx, messageFor(input, "Event"), events.map((e) => ({
10080
+ label: `${e.type} ${e.eventId}`,
10081
+ value: `${e.eventId}\0${e.occurrenceId}`,
10082
+ hint: e.occurrenceId
10083
+ })));
10084
+ if (key === TYPE_IT || !key.includes("\0")) return key === TYPE_IT ? typedValue(ctx, question(input)) : key;
10085
+ const [eventId, occurrenceId] = key.split("\0");
10086
+ ctx.prefill.set("occurrenceId", occurrenceId);
10087
+ return eventId;
10088
+ }
10089
+ async function listed(ctx, noun, message, load) {
10090
+ let items;
10091
+ try {
10092
+ items = await load();
10093
+ } catch (error) {
10094
+ ctx.note(`Could not list ${noun} (${reason(error)}); type it instead.`);
10095
+ return typedValue(ctx, message);
10096
+ }
10097
+ if (items.length === 0) {
10098
+ ctx.note(`No ${noun} to choose from; type it instead.`);
10099
+ return typedValue(ctx, message);
10100
+ }
10101
+ const picked = await choose(ctx, message, items);
10102
+ return picked === TYPE_IT ? typedValue(ctx, message) : picked;
10103
+ }
10104
+ async function choose(ctx, message, items, defaultValue) {
10105
+ const choices = [
10106
+ ...items.map((i) => ({ name: labelled(i.label, i.hint), value: i.value })),
10107
+ typeItChoice()
10108
+ ];
10109
+ if (items.length > SEARCH_THRESHOLD) {
10110
+ return ctx.prompter.search({
10111
+ message,
10112
+ source: (term) => {
10113
+ const needle = term.trim().toLowerCase();
10114
+ if (!needle) return choices;
10115
+ return [
10116
+ ...choices.filter((c) => c.value !== TYPE_IT && `${c.name} ${c.value}`.toLowerCase().includes(needle)),
10117
+ typeItChoice()
10118
+ ];
10119
+ }
10120
+ });
10121
+ }
10122
+ return ctx.prompter.select({ message, choices, default: defaultValue });
10123
+ }
10124
+ async function typed(ctx, message, options = {}) {
10125
+ const value = await ctx.prompter.input({
10126
+ message,
10127
+ default: options.defaultValue,
10128
+ validate: (raw) => {
10129
+ if (!options.allowEmpty && raw.trim().length === 0) return "A value is required.";
10130
+ if (options.allowEmpty && raw.trim().length === 0) return true;
10131
+ return options.validate ? options.validate(raw) : true;
10132
+ }
10133
+ });
10134
+ return value.trim();
10135
+ }
10136
+ function typedValue(ctx, message) {
10137
+ return typed(ctx, message);
10138
+ }
10139
+ function typeItChoice() {
10140
+ return { name: chalk34.dim("Type it instead"), value: TYPE_IT };
10141
+ }
10142
+ function text(ctx, name) {
10143
+ const value = ctx.known.get(name);
10144
+ return typeof value === "string" && value.length > 0 ? value : void 0;
10145
+ }
10146
+ function entityRef(ctx, name) {
10147
+ const ref = text(ctx, name);
10148
+ if (!ref) return void 0;
10149
+ try {
10150
+ return parseEntityReference(ref, ctx.globals);
10151
+ } catch {
10152
+ return void 0;
10153
+ }
10154
+ }
10155
+ function defaultProject(ctx) {
10156
+ return (ctx.globals.project ?? loadConfig().defaults.project)?.split("/")[0];
10157
+ }
10158
+ function messageFor(input, noun) {
10159
+ const lead = /^(Source|Target)\b/.exec(input.description)?.[1];
10160
+ return lead ? `${lead} ${noun.toLowerCase()}` : noun;
10161
+ }
10162
+ function question(input) {
10163
+ const text2 = input.description.trim() || input.name;
10164
+ return capitalize(text2);
10165
+ }
10166
+ function capitalize(value) {
10167
+ return value.charAt(0).toUpperCase() + value.slice(1);
10168
+ }
10169
+ function labelled(label, hint2) {
10170
+ return hint2 && hint2 !== label ? `${label} ${chalk34.dim(hint2)}` : label;
10171
+ }
10172
+ function numberRule(spec) {
10173
+ return (raw) => {
10174
+ const value = Number(raw.trim());
10175
+ if (raw.trim() === "" || !Number.isFinite(value)) return "Enter a number.";
10176
+ if (spec.integer && !Number.isInteger(value)) return "Enter a whole number.";
10177
+ if (spec.exclusive ? value <= spec.min : value < spec.min) {
10178
+ return spec.exclusive ? `Enter a number above ${spec.min}.` : `Enter ${spec.min} or more.`;
10179
+ }
10180
+ return true;
10181
+ };
10182
+ }
10183
+ function currentUtcHour(now = /* @__PURE__ */ new Date()) {
10184
+ const iso = now.toISOString();
10185
+ return `${iso.slice(0, 10)}-${iso.slice(11, 13)}`;
10186
+ }
10187
+ function parseHour(value) {
10188
+ const match = /^(\d{4})-(\d{2})-(\d{2})-(\d{2})$/.exec(value.trim());
10189
+ if (!match) return null;
10190
+ return { year: Number(match[1]), month: Number(match[2]), day: Number(match[3]), hour: Number(match[4]) };
10191
+ }
10192
+ function when(epochMs) {
10193
+ return epochMs ? new Date(epochMs).toISOString().slice(0, 16).replace("T", " ") : "";
10194
+ }
10195
+ function reason(error) {
10196
+ return error instanceof Error ? error.message : String(error);
10197
+ }
10198
+
10199
+ // src/prompting/fill.ts
10200
+ async function fillPendingInputs(actionCommand) {
10201
+ const chain = commandChain(actionCommand);
10202
+ const owners = chain.filter((c) => c instanceof DiafuncCommand && c.pendingInputs.length > 0);
10203
+ if (owners.length === 0) return;
10204
+ const env = actionCommand.environment();
10205
+ const pending = owners.flatMap((owner) => owner.pendingInputs.splice(0).map((input) => ({
10206
+ owner,
10207
+ input,
10208
+ spec: specFor(pathOf(owner), input) ?? { kind: "text" }
10209
+ })));
10210
+ const ctx = {
10211
+ prompter: env.prompter ?? createInquirerPrompter(),
10212
+ api: memoize(env.api ?? (() => createApiClient())),
10213
+ known: knownValues(actionCommand),
10214
+ globals: actionCommand.optsWithGlobals(),
10215
+ prefill: /* @__PURE__ */ new Map(),
10216
+ note: (line) => process.stderr.write(chalk35.dim(` ${line}
10217
+ `))
10218
+ };
10219
+ for (const item of orderByDependencies(pending)) {
10220
+ const value = await askFor(item.spec, item.input, ctx);
10221
+ write(item.owner, item.input, value);
10222
+ ctx.known.set(item.input.name, value);
10223
+ }
10224
+ const log = env.log ?? ((line) => console.log(line));
10225
+ log(chalk35.dim(` Equivalent: ${equivalentCommand(actionCommand)}`));
10226
+ }
10227
+ function commandChain(cmd) {
10228
+ const chain = [];
10229
+ for (let c = cmd; c; c = c.parent) chain.unshift(c);
10230
+ return chain;
10231
+ }
10232
+ function pathOf(cmd) {
10233
+ return commandChain(cmd).slice(1).map((c) => c.name()).join(" ");
10234
+ }
10235
+ function knownValues(cmd) {
10236
+ const known = /* @__PURE__ */ new Map();
10237
+ for (const [key, value] of Object.entries(cmd.optsWithGlobals())) {
10238
+ if (value !== void 0) known.set(key, value);
10239
+ }
10240
+ cmd.registeredArguments.forEach((argument, i) => {
10241
+ const value = cmd.processedArgs[i];
10242
+ if (value !== void 0) known.set(argument.name(), value);
10243
+ });
10244
+ return known;
10245
+ }
10246
+ function orderByDependencies(pending) {
10247
+ const remaining = [...pending];
10248
+ const ordered = [];
10249
+ while (remaining.length > 0) {
10250
+ const waiting = new Set(remaining.map((p) => p.input.name));
10251
+ const index = remaining.findIndex((p) => dependencies(p.spec).every((name) => !waiting.has(name) || name === p.input.name));
10252
+ ordered.push(...remaining.splice(index === -1 ? 0 : index, 1));
10253
+ }
10254
+ return ordered;
10255
+ }
10256
+ function write(owner, input, value) {
10257
+ if (input.kind === "argument" && input.index !== void 0 && input.index >= 0) {
10258
+ owner.processedArgs[input.index] = value;
10259
+ } else {
10260
+ owner.setOptionValueWithSource(input.name, value, "cli");
10261
+ }
10262
+ }
10263
+ function memoize(make) {
10264
+ let made;
10265
+ return () => made ??= make();
10266
+ }
10267
+ function equivalentCommand(cmd) {
10268
+ const chain = commandChain(cmd);
10269
+ const tokens = [chain[0].name(), ...chain.slice(1).map((c) => c.name())];
10270
+ for (const value of cmd.processedArgs) {
10271
+ if (value === void 0) continue;
10272
+ for (const v of Array.isArray(value) ? value : [value]) tokens.push(quote(String(v)));
10273
+ }
10274
+ for (const c of chain) {
10275
+ for (const option of c.options) {
10276
+ const key = option.attributeName();
10277
+ if (c.getOptionValueSource(key) !== "cli" || !option.long) continue;
10278
+ const value = c.getOptionValue(key);
10279
+ if (typeof value === "boolean") {
10280
+ if (value === !option.negate) tokens.push(option.long);
10281
+ } else if (Array.isArray(value)) {
10282
+ for (const v of value) tokens.push(option.long, quote(String(v)));
10283
+ } else if (value !== void 0) {
10284
+ tokens.push(option.long, quote(String(value)));
10285
+ }
10286
+ }
10287
+ }
10288
+ return tokens.join(" ");
10289
+ }
10290
+ function quote(value) {
10291
+ if (/^[\w@%+=:,./-]+$/.test(value)) return value;
10292
+ return `'${value.replace(/'/g, `'\\''`)}'`;
10293
+ }
10294
+
9325
10295
  // src/index.ts
9326
10296
  var HELP_EPILOGUE = `
9327
10297
  Getting started:
@@ -9340,11 +10310,16 @@ Output:
9340
10310
  Add --output json for scripting, or pipe any command to get tab-separated fields.
9341
10311
  Add --verbose to see the requests, --dry-run to preview a mutation.
9342
10312
 
10313
+ Missing input:
10314
+ In a terminal, leave out a required argument and the command asks for it, offering
10315
+ your projects, tables, teams and the like to choose from. --no-interactive never asks.
10316
+
9343
10317
  Docs: https://diafunc.com/documentation
9344
10318
  `;
9345
- function createProgram() {
9346
- const program = new Command();
9347
- program.name("diafunc").description("Diafunc CLI \u2014 command-line interface for the Diafunc platform").version(package_default.version).option("-p, --profile <name>", "Profile to use").option("-o, --output <format>", "Output format: human, json, table (default: human)").option("--project <id>", "Project to work in (overrides defaults.project)").option("--branch <name>", "Project branch (overrides defaults.branch)").option("--dry-run", "Preview mutating operations without executing them").option("--verbose", "Echo every HTTP request to stderr").option("--no-color", "Disable coloured output").showSuggestionAfterError().showHelpAfterError(`(run 'diafunc --help' to see the available commands)`).configureHelp({ showGlobalOptions: true }).configureOutput({
10319
+ function createProgram(environment = {}) {
10320
+ const program = new DiafuncCommand();
10321
+ program.promptEnvironment = environment;
10322
+ program.name("diafunc").description("Diafunc CLI: the command-line interface for the Diafunc platform").version(package_default.version).option("-p, --profile <name>", "Profile to use").option("-o, --output <format>", "Output format: human, json, table (default: human)").option("--project <id>", "Project to work in (overrides defaults.project)").option("--branch <name>", "Project branch (overrides defaults.branch)").option("--dry-run", "Preview mutating operations without executing them").option("--verbose", "Echo every HTTP request to stderr").option("--no-color", "Disable coloured output").option("--no-interactive", "Never prompt: a missing required input fails as it would in a script").showSuggestionAfterError().showHelpAfterError(`(run 'diafunc --help' to see the available commands)`).configureHelp({ showGlobalOptions: true }).configureOutput({
9348
10323
  // Commander writes usage errors to stdout by default, which puts a complaint in the middle
9349
10324
  // of whatever a caller was capturing.
9350
10325
  writeErr: (str) => process.stderr.write(str)
@@ -9352,8 +10327,8 @@ function createProgram() {
9352
10327
  const opts = thisCommand.optsWithGlobals();
9353
10328
  if (opts.dryRun) setDryRun(true);
9354
10329
  if (opts.verbose) setVerbose(true);
9355
- if (opts.color === false) chalk35.level = 0;
9356
- });
10330
+ if (opts.color === false) chalk36.level = 0;
10331
+ }).hook("preAction", (_thisCommand, actionCommand) => fillPendingInputs(actionCommand));
9357
10332
  program.addHelpText("after", HELP_EPILOGUE);
9358
10333
  registerAuthCommands(program);
9359
10334
  registerConfigCommands(program);
@@ -9389,6 +10364,9 @@ function createProgram() {
9389
10364
  }
9390
10365
 
9391
10366
  export {
10367
+ EXIT_CANCELLED,
10368
+ handleError,
10369
+ PromptCancelled,
9392
10370
  createProgram
9393
10371
  };
9394
- //# sourceMappingURL=chunk-GDW62ZQX.js.map
10372
+ //# sourceMappingURL=chunk-EJLRB75G.js.map