@fnndsc/chili 3.3.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/chefs/chefs.js +12 -11
  2. package/dist/commands/fs/download.d.ts +19 -4
  3. package/dist/commands/fs/download.js +75 -65
  4. package/dist/commands/fs/upload.d.ts +20 -4
  5. package/dist/commands/fs/upload.js +46 -34
  6. package/dist/commands/man/doc.js +3 -2
  7. package/dist/commands/plugins/add.js +35 -34
  8. package/dist/config/colorConfig.js +2 -1
  9. package/dist/connect/connectHandler.js +7 -6
  10. package/dist/context/contextCommand.js +3 -2
  11. package/dist/controllers/fileController.js +4 -3
  12. package/dist/controllers/pluginController.js +2 -1
  13. package/dist/feeds/feedHandler.js +19 -18
  14. package/dist/filesystem/fileGroupHandler.js +28 -27
  15. package/dist/filesystem/filesystemHandler.js +13 -11
  16. package/dist/filesystem/inodeCommand.js +2 -1
  17. package/dist/handlers/baseGroupHandler.d.ts +10 -1
  18. package/dist/handlers/baseGroupHandler.js +38 -13
  19. package/dist/index.js +3 -2
  20. package/dist/lfs/lfs.js +6 -4
  21. package/dist/man/man.js +4 -3
  22. package/dist/man/renderer.js +3 -2
  23. package/dist/pacs/pacsQueryHandler.js +14 -13
  24. package/dist/pacs/pacsRetrieveHandler.js +13 -12
  25. package/dist/path/pathCommand.js +23 -22
  26. package/dist/plugins/pluginGroupHandler.d.ts +18 -0
  27. package/dist/plugins/pluginGroupHandler.js +44 -4
  28. package/dist/plugins/pluginHandler.js +23 -22
  29. package/dist/run.d.ts +13 -0
  30. package/dist/run.js +28 -13
  31. package/dist/screen/output.d.ts +88 -0
  32. package/dist/screen/output.js +95 -0
  33. package/dist/screen/screen.d.ts +13 -0
  34. package/dist/screen/screen.js +53 -8
  35. package/dist/utils/admin_prompt.js +10 -9
  36. package/dist/utils/docker.js +10 -9
  37. package/dist/views/pluginParameters.d.ts +10 -0
  38. package/dist/views/pluginParameters.js +25 -17
  39. package/docs/pacs.adoc +3 -3
  40. package/package.json +1 -1
@@ -0,0 +1,95 @@
1
+ /**
2
+ * @file chili's output seam.
3
+ *
4
+ * chili historically printed straight to `console.log`/`console.error`, which
5
+ * fused its command layer to a terminal and forced any in-process host (the
6
+ * brasa engine, which drives chili headless) to capture output with a console
7
+ * monkeypatch. This seam inverts that: command output is written to whatever
8
+ * writer is installed, and by default that writer simply delegates to the
9
+ * process console — so chili's standalone CLI behaves exactly as it always has.
10
+ *
11
+ * A host captures a run's output with {@link chili_capture}, which swaps in a
12
+ * buffering writer for the duration of a call and returns the collected text.
13
+ * This is explicit dependency injection through a module seam, not a runtime
14
+ * override of the global `console`: the default writer calls `console.log`
15
+ * normally, and capture bypasses the console entirely.
16
+ *
17
+ * @module
18
+ */
19
+ import { format } from "util";
20
+ /**
21
+ * The default writer: delegates to the process console. Installed at import so
22
+ * the standalone CLI prints exactly as before.
23
+ */
24
+ const consoleWriter = {
25
+ log: (...args) => { console.log(...args); },
26
+ errLog: (...args) => { console.error(...args); },
27
+ write: (chunk) => { process.stdout.write(chunk); },
28
+ };
29
+ /** The writer in effect. Swapped for the duration of a captured run. */
30
+ let activeWriter = consoleWriter;
31
+ /**
32
+ * Installs a writer as the active output destination.
33
+ *
34
+ * @param writer - The writer to install.
35
+ * @returns The previously installed writer, so callers can restore it.
36
+ */
37
+ export function chiliWriter_set(writer) {
38
+ const previous = activeWriter;
39
+ activeWriter = writer;
40
+ return previous;
41
+ }
42
+ /**
43
+ * Writes to the output channel with `console.log` semantics.
44
+ *
45
+ * @param args - The values to format, exactly as passed to `console.log`.
46
+ */
47
+ export function chiliLog(...args) {
48
+ activeWriter.log(...args);
49
+ }
50
+ /**
51
+ * Writes to the error channel with `console.error` semantics.
52
+ *
53
+ * @param args - The values to format, exactly as passed to `console.error`.
54
+ */
55
+ export function chiliErrLog(...args) {
56
+ activeWriter.errLog(...args);
57
+ }
58
+ /**
59
+ * Writes raw text or bytes to the output channel without adding a newline —
60
+ * the replacement for direct `process.stdout.write` calls.
61
+ *
62
+ * @param chunk - The text or bytes to write.
63
+ */
64
+ export function chiliWrite(chunk) {
65
+ activeWriter.write(chunk);
66
+ }
67
+ /**
68
+ * Runs `fn` with both channels captured into memory and returns the collected
69
+ * text, restoring the previous writer afterwards even if `fn` throws.
70
+ *
71
+ * Formatting matches `console.log`: arguments are rendered with `util.format`
72
+ * and each `log`/`errLog` call contributes a trailing newline, exactly as the
73
+ * console would have written.
74
+ *
75
+ * @param fn - The work whose output should be captured.
76
+ * @returns The captured output and error text.
77
+ */
78
+ export async function chili_capture(fn) {
79
+ const outChunks = [];
80
+ const errChunks = [];
81
+ const previous = chiliWriter_set({
82
+ log: (...args) => { outChunks.push(`${format(...args)}\n`); },
83
+ errLog: (...args) => { errChunks.push(`${format(...args)}\n`); },
84
+ write: (chunk) => {
85
+ outChunks.push(typeof chunk === "string" ? chunk : chunk.toString("utf-8"));
86
+ },
87
+ });
88
+ try {
89
+ await fn();
90
+ }
91
+ finally {
92
+ chiliWriter_set(previous);
93
+ }
94
+ return { out: outChunks.join(""), err: errChunks.join("") };
95
+ }
@@ -75,6 +75,19 @@ export declare function border_draw(text: string, borders?: Borders): string;
75
75
  * @param options - Optional table display options.
76
76
  * @returns The `TableContent` object or null on error.
77
77
  */
78
+ /**
79
+ * Renders a table to a string, the string form of {@link table_display}.
80
+ *
81
+ * Envelope-returning callers use this to return their output rather than
82
+ * printing it; table_display remains the printing form for callers not yet
83
+ * converted. Returns an empty string when there is no table to render.
84
+ *
85
+ * @param tableData - The rows to render.
86
+ * @param headers - Column headers.
87
+ * @param options - Table formatting options.
88
+ * @returns The rendered table (with a trailing newline), or an empty string.
89
+ */
90
+ export declare function table_render(tableData: TableDataRow[] | string[][] | string[], headers: string[] | string, options?: TableOptions): string;
78
91
  export declare function table_display(tableData: TableDataRow[] | string[][] | string[], headers: string[] | string, options?: TableOptions): TableContent | null;
79
92
  /**
80
93
  * Provides screen utilities for logging and table output.
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { table, getBorderCharacters } from "table";
7
7
  import chalk from "chalk";
8
+ import { chiliLog, chiliErrLog } from "./output.js";
8
9
  /**
9
10
  * Processes raw table input data and headers into a standardized format.
10
11
  *
@@ -60,7 +61,7 @@ function tableContent_pack(tableData, selectedFields) {
60
61
  body = tableData.map((row) => headers.map((field) => (row[field] !== undefined ? row[field] : "")));
61
62
  }
62
63
  else {
63
- console.error("Invalid table data");
64
+ chiliErrLog("Invalid table data");
64
65
  return null;
65
66
  }
66
67
  return { headers, body };
@@ -118,6 +119,50 @@ function firstColumnSettings_apply(columns) {
118
119
  * @param options - Optional table display options.
119
120
  * @returns The `TableContent` object or null on error.
120
121
  */
122
+ /**
123
+ * Renders a table to a string, the string form of {@link table_display}.
124
+ *
125
+ * Envelope-returning callers use this to return their output rather than
126
+ * printing it; table_display remains the printing form for callers not yet
127
+ * converted. Returns an empty string when there is no table to render.
128
+ *
129
+ * @param tableData - The rows to render.
130
+ * @param headers - Column headers.
131
+ * @param options - Table formatting options.
132
+ * @returns The rendered table (with a trailing newline), or an empty string.
133
+ */
134
+ export function table_render(tableData, headers, options = {}) {
135
+ const { processedTableData, processedHeaders } = tableInput_process(tableData, headers);
136
+ const tableObj = tableContent_pack(processedTableData, processedHeaders);
137
+ if (!tableObj) {
138
+ return "";
139
+ }
140
+ const columns = tableObj.headers.map((_, index) => {
141
+ const existingCol = options.columns?.[index] || {};
142
+ return {
143
+ justification: "left",
144
+ ...existingCol,
145
+ };
146
+ });
147
+ const updatedColumns = firstColumnSettings_apply(columns);
148
+ const tableOptions = {
149
+ ...options,
150
+ head: processedHeaders,
151
+ columns: updatedColumns,
152
+ typeColors: {
153
+ string: "green",
154
+ number: "yellow",
155
+ boolean: "cyan",
156
+ object: "magenta",
157
+ },
158
+ };
159
+ let out = `${screen.table_output(processedTableData, tableOptions)}\n`;
160
+ if (options.pagination && options.pagination.shown < options.pagination.total) {
161
+ const { shown, total } = options.pagination;
162
+ out += `${chalk.dim(` ↓ showing ${shown} of ${total} · --all to fetch all · --limit <n> for page size`)}\n`;
163
+ }
164
+ return out;
165
+ }
121
166
  export function table_display(tableData, headers, options = {}) {
122
167
  const { processedTableData, processedHeaders } = tableInput_process(tableData, headers);
123
168
  const tableObj = tableContent_pack(processedTableData, processedHeaders);
@@ -144,10 +189,10 @@ export function table_display(tableData, headers, options = {}) {
144
189
  },
145
190
  };
146
191
  const result = screen.table_output(processedTableData, tableOptions);
147
- console.log(result);
192
+ chiliLog(result);
148
193
  if (options.pagination && options.pagination.shown < options.pagination.total) {
149
194
  const { shown, total } = options.pagination;
150
- console.log(chalk.dim(` ↓ showing ${shown} of ${total} · --all to fetch all · --limit <n> for page size`));
195
+ chiliLog(chalk.dim(` ↓ showing ${shown} of ${total} · --all to fetch all · --limit <n> for page size`));
151
196
  }
152
197
  return tableObj;
153
198
  }
@@ -156,16 +201,16 @@ export function table_display(tableData, headers, options = {}) {
156
201
  */
157
202
  export class Screen {
158
203
  log(...args) {
159
- console.log(...args);
204
+ chiliLog(...args);
160
205
  }
161
206
  error(...args) {
162
- console.error(chalk.red(...args));
207
+ chiliErrLog(chalk.red(...args));
163
208
  }
164
209
  warn(...args) {
165
- console.warn(chalk.yellow(...args));
210
+ chiliErrLog(chalk.yellow(...args));
166
211
  }
167
212
  info(...args) {
168
- console.info(chalk.blue(...args));
213
+ chiliLog(chalk.blue(...args));
169
214
  }
170
215
  /**
171
216
  * Generates a formatted table output string.
@@ -198,7 +243,7 @@ export class Screen {
198
243
  : output;
199
244
  }
200
245
  catch (error) {
201
- console.error("Error in table_output method:", error);
246
+ chiliErrLog("Error in table_output method:", error);
202
247
  return "Error generating table";
203
248
  }
204
249
  }
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import * as readline from 'readline';
11
11
  import { Writable } from 'stream';
12
+ import { chiliLog, chiliWrite } from "../screen/output.js";
12
13
  /** Injected by the host (chell) so prompts route through the active readline. */
13
14
  let _askFn = null;
14
15
  let _askHiddenFn = null;
@@ -35,24 +36,24 @@ export function adminPrompt_register(askFn, askHiddenFn) {
35
36
  */
36
37
  export async function adminCredentials_prompt(attempt = 1, maxAttempts = 3) {
37
38
  if (attempt === 1) {
38
- console.log('\nAdmin credentials required to register plugins.');
39
- console.log('You can provide these via --adminUser and --adminPassword flags.');
40
- console.log('');
39
+ chiliLog('\nAdmin credentials required to register plugins.');
40
+ chiliLog('You can provide these via --adminUser and --adminPassword flags.');
41
+ chiliLog('');
41
42
  }
42
43
  else {
43
- console.log(`\nAuthentication failed. Attempt ${attempt} of ${maxAttempts}.`);
44
- console.log('');
44
+ chiliLog(`\nAuthentication failed. Attempt ${attempt} of ${maxAttempts}.`);
45
+ chiliLog('');
45
46
  }
46
47
  const askFn = _askFn ?? ask_fallback;
47
48
  const askHiddenFn = _askHiddenFn ?? askHidden_fallback;
48
49
  const username = await askFn('Username: ');
49
50
  if (!username) {
50
- console.log('Username cannot be empty.');
51
+ chiliLog('Username cannot be empty.');
51
52
  return null;
52
53
  }
53
54
  const password = await askHiddenFn('Password: ');
54
55
  if (!password) {
55
- console.log('Password cannot be empty.');
56
+ chiliLog('Password cannot be empty.');
56
57
  return null;
57
58
  }
58
59
  return { username, password };
@@ -82,9 +83,9 @@ function askHidden_fallback(prompt) {
82
83
  output: muted,
83
84
  terminal: true,
84
85
  });
85
- process.stdout.write(prompt);
86
+ chiliWrite(prompt);
86
87
  rl.question('', (answer) => {
87
- process.stdout.write('\n');
88
+ chiliWrite('\n');
88
89
  rl.close();
89
90
  resolve(answer.trim());
90
91
  });
@@ -7,6 +7,7 @@
7
7
  * @module
8
8
  */
9
9
  import { exec } from "child_process";
10
+ import { chiliErrLog, chiliLog } from "../screen/output.js";
10
11
  /**
11
12
  * Promisified version of child_process.exec.
12
13
  * @param command - The command string to execute.
@@ -33,13 +34,13 @@ export async function shellCommand_run(command) {
33
34
  try {
34
35
  const { stdout, stderr } = await childProcess_exec(command);
35
36
  if (stderr) {
36
- // console.warn(`Command stderr: ${stderr.trim()}`); // Log stderr as warning, not necessarily an error
37
+ // chiliErrLog(`Command stderr: ${stderr.trim()}`); // Log stderr as warning, not necessarily an error
37
38
  }
38
39
  return stdout.trim();
39
40
  }
40
41
  catch (error) {
41
- // console.error(`Command failed: ${command}`);
42
- // console.error(`Error: ${error.message}`);
42
+ // chiliErrLog(`Command failed: ${command}`);
43
+ // chiliErrLog(`Error: ${error.message}`);
43
44
  return null;
44
45
  }
45
46
  }
@@ -77,8 +78,8 @@ export async function docker_checkAvailability() {
77
78
  if (result === "OK") {
78
79
  return true;
79
80
  }
80
- console.error("Error: Docker is not installed or not running.");
81
- console.error("Please ensure Docker is properly set up on your system to add plugins.");
81
+ chiliErrLog("Error: Docker is not installed or not running.");
82
+ chiliErrLog("Please ensure Docker is properly set up on your system to add plugins.");
82
83
  return false;
83
84
  }
84
85
  /**
@@ -112,17 +113,17 @@ export async function docker_imageExistsLocally(image) {
112
113
  export async function docker_pullImage(image, quiet = true) {
113
114
  const existsLocally = await docker_imageExistsLocally(image);
114
115
  if (existsLocally) {
115
- console.log(`Docker image ${image} already exists locally.`);
116
+ chiliLog(`Docker image ${image} already exists locally.`);
116
117
  return true;
117
118
  }
118
- console.log(`Pulling Docker image: ${image}...`);
119
+ chiliLog(`Pulling Docker image: ${image}...`);
119
120
  const quietFlag = quiet ? '--quiet' : '';
120
121
  const result = await shellCommand_run(`docker pull ${quietFlag} ${image}`);
121
122
  if (result !== null) {
122
- console.log(`Successfully pulled ${image}`);
123
+ chiliLog(`Successfully pulled ${image}`);
123
124
  return true;
124
125
  }
125
- console.error(`Failed to pull Docker image: ${image}`);
126
+ chiliErrLog(`Failed to pull Docker image: ${image}`);
126
127
  return false;
127
128
  }
128
129
  /**
@@ -15,3 +15,13 @@ import { FilteredResourceData } from '@fnndsc/cumin';
15
15
  * @param data - The filtered resource data containing plugin parameters.
16
16
  */
17
17
  export declare function pluginParameters_renderMan(data: FilteredResourceData): void;
18
+ /**
19
+ * Builds the "man page" style rendering of plugin parameters as a string.
20
+ *
21
+ * Same format as {@link pluginParameters_renderMan} but returns the text
22
+ * instead of printing it, so hosted surfaces can carry it in an envelope.
23
+ *
24
+ * @param data - The filtered resource data containing plugin parameters.
25
+ * @returns The rendered parameter listing.
26
+ */
27
+ export declare function pluginParameters_manRender(data: FilteredResourceData): string;
@@ -4,6 +4,7 @@
4
4
  * @module
5
5
  */
6
6
  import chalk from 'chalk';
7
+ import { chiliLog } from "../screen/output.js";
7
8
  /**
8
9
  * Renders plugin parameters in a "man page" style format.
9
10
  *
@@ -15,10 +16,22 @@ import chalk from 'chalk';
15
16
  * @param data - The filtered resource data containing plugin parameters.
16
17
  */
17
18
  export function pluginParameters_renderMan(data) {
19
+ chiliLog(pluginParameters_manRender(data));
20
+ }
21
+ /**
22
+ * Builds the "man page" style rendering of plugin parameters as a string.
23
+ *
24
+ * Same format as {@link pluginParameters_renderMan} but returns the text
25
+ * instead of printing it, so hosted surfaces can carry it in an envelope.
26
+ *
27
+ * @param data - The filtered resource data containing plugin parameters.
28
+ * @returns The rendered parameter listing.
29
+ */
30
+ export function pluginParameters_manRender(data) {
18
31
  if (!data.tableData || data.tableData.length === 0) {
19
- console.log("No parameters found.");
20
- return;
32
+ return "No parameters found.";
21
33
  }
34
+ const lines = [];
22
35
  data.tableData.forEach((param) => {
23
36
  // 1. Construct the first line: Flags and Value
24
37
  let line1Parts = [];
@@ -52,28 +65,23 @@ export function pluginParameters_renderMan(data) {
52
65
  line1Parts.push(chalk.gray(`(default: ${param.default})`));
53
66
  }
54
67
  if (line1Parts.length > 0) {
55
- console.log(line1Parts.join(' '));
68
+ lines.push(line1Parts.join(' '));
56
69
  }
57
- else {
58
- // Fallback if both are suppressed (e.g. name 'v', no flag)?
59
- // In strict adherence, we show nothing on line 1, which is weird.
60
- // But assuming a valid plugin definition, one of them should appear.
61
- // If name is 'v', it implies it should probably have a flag '-v'.
62
- // If not, we might want to show '--v' anyway despite the rule, or '-v'.
63
- // For safety, if line1 is empty but we have a name, show it as long flag to avoid invisible params.
64
- if (param.name) {
65
- console.log(chalk.bold(`--${param.name}`) + ' ' + chalk.gray('(implicit)'));
66
- }
70
+ else if (param.name) {
71
+ // Fallback: if line1 is empty but we have a name, show it as a long flag
72
+ // to avoid invisible params.
73
+ lines.push(chalk.bold(`--${param.name}`) + ' ' + chalk.gray('(implicit)'));
67
74
  }
68
75
  // 2. Type line
69
76
  if (param.type) {
70
- console.log(`Type: ${chalk.yellow(param.type)}`);
77
+ lines.push(`Type: ${chalk.yellow(param.type)}`);
71
78
  }
72
79
  // 3. Help description
73
80
  if (param.help) {
74
- console.log(chalk.white(param.help));
81
+ lines.push(chalk.white(param.help));
75
82
  }
76
- // Separator (newline)
77
- console.log('');
83
+ // Separator (blank line)
84
+ lines.push('');
78
85
  });
86
+ return lines.join('\n');
79
87
  }
package/docs/pacs.adoc CHANGED
@@ -21,7 +21,7 @@
21
21
  == PACS Queries
22
22
 
23
23
  - **Create**: `chili pacsqueries create "<query>" [--title <title>] [--description <desc>] [--pacsserver <pacs>]`
24
- - `<query>` can be JSON (`{"PatientID":"12345"}`) or comma-separated `key:value` pairs (`PatientID:12345,StudyDate:20251003`).
24
+ - `<query>` can be JSON (`{"PatientID":"12345"}`) or comma-separated `key:value` pairs (`PatientID:12345,StudyDate:20240101`).
25
25
  - On success prints: `Created PACS query id=<ID> status=<status> pacs=<pacs> title="<title>"`.
26
26
  - **List**: `chili pacsqueries list [--pacsserver <pacs>] [--fields ...] [--table|--csv]`
27
27
  - Filters to current/override PACS server. Use `fieldslist` to discover columns.
@@ -64,7 +64,7 @@
64
64
  ```bash
65
65
  chili context set --pacsserver PACSDCM
66
66
  chili pacsservers list --table
67
- chili pacsqueries create "PatientID:4456554" --title "PID 4456554"
67
+ chili pacsqueries create "PatientID:7654321" --title "PID 7654321"
68
68
  chili pacsqueries list --fields id,title,status,pacs_id,query
69
69
  chili pacsqueries decode <id>
70
70
  ```
@@ -76,7 +76,7 @@ chili pacsqueries decode <id>
76
76
  chili context set --pacsserver PACSDCM
77
77
 
78
78
  # 2. Create query
79
- chili pacsqueries create "PatientID:4456554" --title "Patient scan"
79
+ chili pacsqueries create "PatientID:7654321" --title "Patient scan"
80
80
  # Returns: Created PACS query id=123
81
81
 
82
82
  # 3. See what's available on PACS
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fnndsc/chili",
3
- "version": "3.3.0",
3
+ "version": "3.5.0",
4
4
  "description": "ChILI handles Intelligent Line Interactions: A CLI and library for ChRIS, acting as the controller layer for business logic and user presentation.",
5
5
  "repository": {
6
6
  "type": "git",