insightfulpipe 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.1
4
+
5
+ - `--table` now works on `query`, `action`, `raw` and `helper` too. Result rows print as columns (one
6
+ per field), a single record as field and value, long values shortened. Footers state a partial
7
+ failure and the server's message, name any other fields beside the rows, say when the server has
8
+ more rows (any platform's paging marker; a count never hides one), point out partial errors, warnings
9
+ and notes, and name every other `meta` field that is not purely descriptive. Rows with more than 40
10
+ different fields, and `helper --actions` (the body to copy into `-b`), stay JSON with a note. JSON
11
+ stays the default and is unchanged.
12
+ - Text from the server printed under `--table` (tables, error sentences, `whoami`, `prompts --id`,
13
+ `doctor`, `skills` lines, JSON fallbacks) shows control characters and bidi overrides as `\uXXXX`,
14
+ so text from a connected platform cannot move the cursor, clear the screen or write to the clipboard.
15
+ - `skills list`, `update` and `remove` accept `--private` (private workspace skills only) instead of
16
+ failing with "unknown option". They already took each skill back to its own source without it.
17
+
3
18
  ## 0.4.0
4
19
 
5
20
  **Private skills, separate from the public library.**
package/README.md CHANGED
@@ -92,7 +92,9 @@ insightfulpipe use -w 34 # or save
92
92
  insightfulpipe skills install weekly-brief --private
93
93
  ```
94
94
 
95
- `list` and `update` take each installed skill back to the source it came from. Private skills go to
95
+ `list` and `update` take each installed skill back to the source it came from, so they need no flag;
96
+ add `--private` to `list`, `update` or `remove` to act on private skills only
97
+ (`insightfulpipe skills update --all --private`). Private skills go to
96
98
  your personal skills folder by default; installing one with `--project` or `--dir` prints a warning to
97
99
  keep it out of shared repositories. Only private skills you installed are trusted: each install is
98
100
  recorded under `~/.insightfulpipe/private-skills/`, and a private skill folder that record does not
@@ -187,8 +189,15 @@ Output is **JSON by default** — it is read by scripts and agents far more ofte
187
189
  ```bash
188
190
  insightfulpipe accounts # JSON
189
191
  insightfulpipe accounts --table # aligned columns
192
+ insightfulpipe query google-analytics -b '{…}' --table # one column per field
190
193
  ```
191
194
 
195
+ Under `--table`, the rows of a `query`, `action` or `raw` result print as columns, and a single record
196
+ as field and value. Long values are shortened (the JSON has them in full), and control characters in
197
+ the data are shown escaped. Footers state a partial failure and the server's message, say when the
198
+ server has more rows or sent errors, warnings or notes, and name any field the table leaves out.
199
+ `helper --actions` stays JSON, since that is the body you copy into `-b`.
200
+
192
201
  `--json` is still accepted and does nothing, so existing scripts and docs keep working. Errors follow
193
202
  the same rule: `{"status":"error","message":"…"}` on stderr, or a plain sentence under `--table`.
194
203
  Either way they go to stderr and exit 1, so `insightfulpipe … | jq` is never polluted.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "insightfulpipe",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "InsightfulPipe CLI \u2014 query your marketing data from the terminal",
5
5
  "bin": {
6
6
  "insightfulpipe": "bin/cli.js"
@@ -1,6 +1,6 @@
1
1
  import { getConfigSnapshot, getContext, getToken, saveContext, tokenProblem } from '../../config.js';
2
2
  import { apiGet } from '../../api.js';
3
- import { printJson, printTable, wantsJson } from '../../output.js';
3
+ import { printJson, printJsonForHumans, printResult, printTable, say, wantsJson } from '../../output.js';
4
4
  import {
5
5
  buildQueryString,
6
6
  parseIdList,
@@ -29,14 +29,14 @@ export function registerDiscoveryCommands(program) {
29
29
  return;
30
30
  }
31
31
 
32
- console.log(`User: ${data.user.email}`);
33
- console.log(`Name: ${data.user.full_name || '-'}`);
34
- console.log(`Workspaces: ${data.total_workspaces}`);
32
+ say(`User: ${data.user.email}`);
33
+ say(`Name: ${data.user.full_name || '-'}`);
34
+ say(`Workspaces: ${data.total_workspaces}`);
35
35
  for (const workspace of data.workspaces || []) {
36
36
  const subscription = workspace.subscription || {};
37
37
  const planName = subscription.plan_name || '-';
38
38
  const planStatus = subscription.status || (subscription.is_active ? 'active' : '-');
39
- console.log(` - ${workspace.name} (${workspace.role}; ${planName}; ${planStatus})`);
39
+ say(` - ${workspace.name} (${workspace.role}; ${planName}; ${planStatus})`);
40
40
  }
41
41
  });
42
42
 
@@ -210,10 +210,19 @@ export function registerDiscoveryCommands(program) {
210
210
  .argument('<platform>', 'Platform slug (e.g., google-analytics)')
211
211
  .description('Show available actions and schema for a platform')
212
212
  .option('-a, --actions <actions>', 'Comma-separated action names')
213
- .action(async (platform, opts) => {
213
+ .action(async (platform, opts, command) => {
214
214
  const actions = opts.actions ? opts.actions.split(',').map((value) => value.trim()).filter(Boolean) : undefined;
215
215
  const data = await fetchHelperPayload(platform, actions);
216
- printJson(data);
216
+ if (!actions) {
217
+ printResult(data, command, 'actions');
218
+ return;
219
+ }
220
+ if (wantsJson(command)) {
221
+ printJson(data);
222
+ return;
223
+ }
224
+ console.error('Request templates stay JSON under --table, so you can copy the body into -b.');
225
+ printJsonForHumans(data);
217
226
  });
218
227
 
219
228
  program
@@ -247,7 +256,7 @@ export function registerDiscoveryCommands(program) {
247
256
  printJson(data);
248
257
  return;
249
258
  }
250
- console.log(data.prompt_detail || '');
259
+ say(data.prompt_detail || '');
251
260
  return;
252
261
  }
253
262
 
@@ -263,7 +272,7 @@ export function registerDiscoveryCommands(program) {
263
272
  printJson(data);
264
273
  return;
265
274
  }
266
- console.log(data.prompt_detail || '');
275
+ say(data.prompt_detail || '');
267
276
  return;
268
277
  }
269
278
 
@@ -349,11 +358,11 @@ export function registerDiscoveryCommands(program) {
349
358
  if (wantsJson(command)) {
350
359
  printJson(payload);
351
360
  } else {
352
- console.log(`Config file: ${payload.config_file}`);
361
+ say(`Config file: ${payload.config_file}`);
353
362
  for (const item of payload.checks) {
354
- console.log(`${item.name}: ${item.status} (${item.details}; ${item.source})`);
363
+ say(`${item.name}: ${item.status} (${item.details}; ${item.source})`);
355
364
  }
356
- console.log(`connectivity: ${payload.connectivity.status} (${payload.connectivity.details})`);
365
+ say(`connectivity: ${payload.connectivity.status} (${payload.connectivity.details})`);
357
366
  }
358
367
 
359
368
  if (status === 'error') {
@@ -1,6 +1,6 @@
1
1
  import { apiPost } from '../../api.js';
2
2
  import { applyContextToBody } from '../../config.js';
3
- import { printJson } from '../../output.js';
3
+ import { printResult } from '../../output.js';
4
4
  import {
5
5
  confirmWriteAction,
6
6
  ensureJsonObject,
@@ -24,17 +24,17 @@ const SCOPE_OPTIONS = [
24
24
  ];
25
25
 
26
26
  export function registerExecutionCommands(program) {
27
- const readAction = async (platform, opts) => {
27
+ const readAction = async (platform, opts, command) => {
28
28
  const body = scopedBody(ensureJsonObject(await readJsonInput(opts, true), 'Request body'), opts);
29
29
  const data = handleApiError(await apiPost('/', withPlatform(platform, body)), { platform });
30
- printJson(data);
30
+ printResult(data, command);
31
31
  };
32
32
 
33
- const writeAction = async (platform, opts) => {
33
+ const writeAction = async (platform, opts, command) => {
34
34
  const body = scopedBody(ensureJsonObject(await readJsonInput(opts, true), 'Request body'), opts);
35
35
  await confirmWriteAction(platform, body, opts.yes);
36
36
  const data = handleApiError(await apiPost('/', withPlatform(platform, body)), { platform });
37
- printJson(data);
37
+ printResult(data, command);
38
38
  };
39
39
 
40
40
  program
@@ -83,9 +83,9 @@ export function registerExecutionCommands(program) {
83
83
  .option('-b, --body <json>', 'Request body as inline JSON')
84
84
  .option('-f, --file <path>', 'Request body from a JSON file')
85
85
  .description('Send a raw request to the universal dispatcher')
86
- .action(async (opts) => {
86
+ .action(async (opts, command) => {
87
87
  const body = ensureJsonObject(await readJsonInput(opts, true), 'Request body');
88
88
  const data = handleApiError(await apiPost('/', body), { platform: body.platform });
89
- printJson(data);
89
+ printResult(data, command);
90
90
  });
91
91
  }
@@ -2,7 +2,7 @@ import { randomBytes } from 'node:crypto';
2
2
  import { renameSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { resolve } from 'node:path';
4
4
 
5
- import { printJson, printTable, wantsJson } from '../../output.js';
5
+ import { printJson, printTable, say, wantsJson, warn } from '../../output.js';
6
6
  import { fail } from '../errors.js';
7
7
  import { confirm } from '../input.js';
8
8
  import { parseIntegerOption } from '../options.js';
@@ -25,6 +25,16 @@ function withTargetOptions(command) {
25
25
  .option('--dir <path>', 'Use this skills directory instead');
26
26
  }
27
27
 
28
+ /** `--private` on list, update and remove keeps only private workspace skills, so the flag that installed
29
+ * a skill also works on everything done to it afterwards. */
30
+ const PRIVATE_FILTER = ['--private', "Only your workspace's private skills"];
31
+
32
+ function inScope(installed, opts) {
33
+ return opts.private ? installed.filter(({ marker }) => markerOrigin(marker) === 'private') : installed;
34
+ }
35
+
36
+ const notPrivate = (name, where) => `"${name}" is not a private skill installed in ${where.dir}.`;
37
+
28
38
  const NOT_YOURS =
29
39
  'Not installed by you here, so it is never checked or updated. To use it, install it again with --private --force.';
30
40
 
@@ -207,13 +217,13 @@ export function registerSkillsCommand(program) {
207
217
  printJson({ status: 'success', ...sourceFields(source), skill: info });
208
218
  return;
209
219
  }
210
- console.log(`${info.name} (${skillKey(skill)}${info.key ? `, ${info.key}, workspace ${source.workspaceId}` : ''})`);
211
- console.log(`Version: ${info.version ?? 'unknown'}`);
212
- if (info.page) console.log(`Page: ${info.page}`);
213
- console.log(`Install: ${info.install}`);
214
- console.log(`Files: ${info.files.map((file) => file.path).join(', ') || 'unknown'}`);
220
+ say(`${info.name} (${skillKey(skill)}${info.key ? `, ${info.key}, workspace ${source.workspaceId}` : ''})`);
221
+ say(`Version: ${info.version ?? 'unknown'}`);
222
+ if (info.page) say(`Page: ${info.page}`);
223
+ say(`Install: ${info.install}`);
224
+ say(`Files: ${info.files.map((file) => file.path).join(', ') || 'unknown'}`);
215
225
  console.log('');
216
- console.log(info.description);
226
+ say(info.description);
217
227
  });
218
228
 
219
229
  withPrivateOptions(
@@ -272,19 +282,19 @@ export function registerSkillsCommand(program) {
272
282
  next_step: `Start a new ${agentLabel(where)} session to load the skill. ${MCP_TIP}`,
273
283
  });
274
284
  } else {
275
- for (const row of installed) console.log(`Installed ${row.skill} (${row.version}) -> ${row.path}`);
276
- for (const row of installed) if (row.warning) console.error(`Warning: ${row.warning}`);
277
- for (const row of failed) console.error(`Failed ${row.skill}: ${row.error}`);
278
- if (installed.length) console.log(`\nStart a new ${agentLabel(where)} session to load it. ${MCP_TIP}`);
285
+ for (const row of installed) say(`Installed ${row.skill} (${row.version}) -> ${row.path}`);
286
+ for (const row of installed) if (row.warning) warn(`Warning: ${row.warning}`);
287
+ for (const row of failed) warn(`Failed ${row.skill}: ${row.error}`);
288
+ if (installed.length) say(`\nStart a new ${agentLabel(where)} session to load it. ${MCP_TIP}`);
279
289
  }
280
290
  if (failed.length) process.exitCode = 1;
281
291
  });
282
292
 
283
293
  withTargetOptions(
284
- skills.command('list').description('List the InsightfulPipe skills installed in a skills folder'),
294
+ skills.command('list').option(...PRIVATE_FILTER).description('List the InsightfulPipe skills installed in a skills folder'),
285
295
  ).action(async (opts, command) => {
286
296
  const where = target(opts);
287
- const installed = listInstalled(where.dir);
297
+ const installed = inScope(listInstalled(where.dir), opts);
288
298
  const sourceFor = sourcesForMarkers();
289
299
  let publicReached = null;
290
300
 
@@ -360,9 +370,9 @@ export function registerSkillsCommand(program) {
360
370
  ],
361
371
  );
362
372
  for (const row of rows) {
363
- if (row.note) console.error(`${row.skill}: ${row.note}`);
373
+ if (row.note) warn(`${row.skill}: ${row.note}`);
364
374
  if (row.error) {
365
- console.error(`${row.skill}: ${row.error}`);
375
+ warn(`${row.skill}: ${row.error}`);
366
376
  process.exitCode = 1;
367
377
  }
368
378
  }
@@ -374,13 +384,14 @@ export function registerSkillsCommand(program) {
374
384
  .argument('[skills...]', 'Installed skills to update')
375
385
  .option('--all', 'Update every InsightfulPipe skill in the folder')
376
386
  .option('-f, --force', 'Update even if you edited the installed files (your edits are replaced)')
387
+ .option(...PRIVATE_FILTER)
377
388
  .description('Update installed skills to the latest version, keeping your local edits unless --force'),
378
389
  ).action(async (names, opts, command) => {
379
390
  if (!names?.length && !opts.all) {
380
391
  fail('Name the skills to update, or use --all.');
381
392
  }
382
393
  const where = target(opts);
383
- const installed = listInstalled(where.dir);
394
+ const installed = inScope(listInstalled(where.dir), opts);
384
395
 
385
396
  const targets = [];
386
397
  if (opts.all) {
@@ -389,7 +400,8 @@ export function registerSkillsCommand(program) {
389
400
  for (const name of names) {
390
401
  const matches = findInstalled(installed, name);
391
402
  if (matches.length !== 1) {
392
- fail(matches.length ? `"${name}" matches more than one installed skill.` : `"${name}" is not installed in ${where.dir}.`);
403
+ if (matches.length) fail(`"${name}" matches more than one installed skill.`);
404
+ fail(opts.private ? notPrivate(name, where) : `"${name}" is not installed in ${where.dir}.`);
393
405
  }
394
406
  targets.push(matches[0]);
395
407
  }
@@ -457,12 +469,12 @@ export function registerSkillsCommand(program) {
457
469
  if (result.failed.length && !result.updated.length) fail('No skill was updated.', undefined, { skills_dir: where.dir, ...result });
458
470
  printJson({ status: result.failed.length ? 'partial' : 'success', skills_dir: where.dir, ...result });
459
471
  } else {
460
- for (const row of result.updated) console.log(`Updated ${row.skill} ${row.from} -> ${row.version}`);
461
- for (const row of result.updated) if (row.warning) console.error(`Warning: ${row.warning}`);
462
- for (const row of result.up_to_date) console.log(`Up to date ${row.skill} (${row.version})`);
463
- for (const row of result.skipped) console.log(`Skipped ${row.skill}: ${row.reason}`);
464
- for (const row of result.failed) console.error(`Failed ${row.skill}: ${row.error}`);
465
- if (!targets.length) console.log('No InsightfulPipe skills installed here.');
472
+ for (const row of result.updated) say(`Updated ${row.skill} ${row.from} -> ${row.version}`);
473
+ for (const row of result.updated) if (row.warning) warn(`Warning: ${row.warning}`);
474
+ for (const row of result.up_to_date) say(`Up to date ${row.skill} (${row.version})`);
475
+ for (const row of result.skipped) say(`Skipped ${row.skill}: ${row.reason}`);
476
+ for (const row of result.failed) warn(`Failed ${row.skill}: ${row.error}`);
477
+ if (!targets.length) say(`No ${opts.private ? 'private' : 'InsightfulPipe'} skills installed here.`);
466
478
  }
467
479
  if (result.failed.length) process.exitCode = 1;
468
480
  });
@@ -472,14 +484,16 @@ export function registerSkillsCommand(program) {
472
484
  .command('remove')
473
485
  .argument('<skills...>', 'Installed skills to remove')
474
486
  .option('-y, --yes', 'Skip the confirmation prompt')
487
+ .option(...PRIVATE_FILTER)
475
488
  .description('Remove installed InsightfulPipe skills (only folders this CLI installed)'),
476
489
  ).action(async (names, opts, command) => {
477
490
  const where = target(opts);
478
- const installed = listInstalled(where.dir);
491
+ const installed = inScope(listInstalled(where.dir), opts);
479
492
  const targets = names.map((name) => {
480
493
  const matches = findInstalled(installed, name);
481
494
  if (matches.length !== 1) {
482
- fail(matches.length ? `"${name}" matches more than one installed skill.` : `"${name}" is not an InsightfulPipe skill installed in ${where.dir}.`);
495
+ if (matches.length) fail(`"${name}" matches more than one installed skill.`);
496
+ fail(opts.private ? notPrivate(name, where) : `"${name}" is not an InsightfulPipe skill installed in ${where.dir}.`);
483
497
  }
484
498
  return matches[0];
485
499
  });
@@ -507,7 +521,7 @@ export function registerSkillsCommand(program) {
507
521
  removed.push({ skill: markerLabel(marker), path: dir, ...(warning ? { warning } : {}) });
508
522
  }
509
523
  if (wantsJson(command)) printJson({ status: 'success', removed });
510
- else for (const row of removed) console.log(`Removed ${row.skill} (${row.path})`);
524
+ else for (const row of removed) say(`Removed ${row.skill} (${row.path})`);
511
525
  });
512
526
 
513
527
  skills
@@ -549,6 +563,6 @@ export function registerSkillsCommand(program) {
549
563
 
550
564
  const next = 'Upload this ZIP as a custom skill in Claude.ai or Claude Desktop.';
551
565
  if (wantsJson(command)) printJson({ status: 'success', skill: skillKey(skill), path: output, bytes: zip.length, next_step: next });
552
- else console.log(`Saved ${skillKey(skill)} to ${output}\n${next}`);
566
+ else say(`Saved ${skillKey(skill)} to ${output}\n${next}`);
553
567
  });
554
568
  }
package/src/cli/errors.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { printable } from '../output.js';
2
+
1
3
  /** Anything meant for reading is cut here; the marker says how much the server actually sent. */
2
4
  const MAX_TEXT_CHARS = 2000;
3
5
  const TRUNCATION_MARKER = /\.\.\. \[truncated, \d+ more characters\]$/;
@@ -26,7 +28,8 @@ function writeStderr(text) {
26
28
 
27
29
  export function fail(message, tip, details = {}) {
28
30
  if (humanOutput()) {
29
- writeStderr(tip ? `Error: ${message}\nTip: ${tip}` : `Error: ${message}`);
31
+ const text = (value) => printable(value, { lines: true });
32
+ writeStderr(tip ? `Error: ${text(message)}\nTip: ${text(tip)}` : `Error: ${text(message)}`);
30
33
  } else {
31
34
  writeStderr(JSON.stringify({ status: 'error', message, ...(tip ? { tip } : {}), ...details }, null, 2));
32
35
  }
@@ -14,7 +14,8 @@ export function buildProgram() {
14
14
  .name('insightfulpipe')
15
15
  .description(
16
16
  'InsightfulPipe CLI — query your marketing data from the terminal.\n\n' +
17
- 'Output is JSON by default; add --table for a human-readable view.\n\n' +
17
+ 'Output is JSON by default; add --table for a human-readable view\n' +
18
+ '(helper --actions request templates stay JSON, to copy into -b).\n\n' +
18
19
  'Run "insightfulpipe platforms" to see all supported platforms.\n\n' +
19
20
  'Set your scope once and stop passing ids:\n' +
20
21
  ' insightfulpipe use Adopt your only workspace\n' +
package/src/output.js CHANGED
@@ -10,28 +10,175 @@ export function wantsJson(command) {
10
10
  return !opts.table;
11
11
  }
12
12
 
13
+ // C0/C1 controls, DEL and the bidi overrides: a terminal acts on them instead of showing them.
14
+ const UNPRINTABLE = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g;
15
+
16
+ /** Text as the terminal will show it: control characters become visible \uXXXX escapes, so data from a
17
+ * connected platform can never move the cursor, clear the screen or write to the clipboard. `lines`
18
+ * keeps line breaks, for multi-line text such as pretty-printed JSON or an error sentence. */
19
+ export function printable(value, { lines = false } = {}) {
20
+ return String(value ?? '').replace(UNPRINTABLE, (ch) =>
21
+ (lines && ch === '\n' ? ch : `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`));
22
+ }
23
+
24
+ /** JSON shown under `--table` when a result has no table form. The escapes keep it valid JSON with the
25
+ * same values; the default JSON output is never passed through here. */
26
+ export function printJsonForHumans(data) {
27
+ console.log(printable(JSON.stringify(data, null, 2), { lines: true }));
28
+ }
29
+
30
+ /** Lines of the human view that carry text from the server (names, descriptions, errors). */
31
+ export const say = (text) => console.log(printable(text, { lines: true }));
32
+ export const warn = (text) => console.error(printable(text, { lines: true }));
33
+
13
34
  export function printTable(rows, columns) {
14
35
  if (!rows || rows.length === 0) {
15
36
  console.log('No data.');
16
37
  return;
17
38
  }
18
39
 
19
- const widths = {};
20
- for (const col of columns) {
21
- widths[col.key] = col.label.length;
22
- for (const row of rows) {
23
- const val = String(row[col.key] ?? '');
24
- widths[col.key] = Math.max(widths[col.key], val.length);
25
- }
40
+ const labels = columns.map((c) => printable(c.label));
41
+ const lines = rows.map((row) => columns.map((c) => printable(row[c.key])));
42
+ const widths = labels.map((label) => label.length);
43
+ for (const line of lines) {
44
+ line.forEach((text, i) => {
45
+ widths[i] = Math.max(widths[i], text.length);
46
+ });
47
+ }
48
+
49
+ console.log(labels.map((label, i) => label.padEnd(widths[i])).join(' '));
50
+ console.log(widths.map((width) => '-'.repeat(width)).join(' '));
51
+ for (const line of lines) {
52
+ console.log(line.map((text, i) => text.padEnd(widths[i])).join(' '));
53
+ }
54
+ }
55
+
56
+ const CELL_MAX_CHARS = 60;
57
+ const MAX_COLUMNS = 40;
58
+ // Fields that frame a result rather than carry its data; anything else beside the rows is named.
59
+ const ENVELOPE_FIELDS = new Set(['status', 'data', 'meta', 'next_step', 'request', 'partial_failure', 'message']);
60
+ // Where platforms put paging: on meta itself, or in one of these objects inside it.
61
+ const PAGING_PLACES = ['paging', 'pagination', 'page_info'];
62
+ // Every way a platform marks a list as cut short; they differ (Meta's has_next, X's next_cursor, …).
63
+ const MORE_MARKERS = [
64
+ 'next', 'has_next', 'has_next_page', 'has_more', 'row_limit_applied', 'page_limit_applied',
65
+ 'next_cursor', 'next_page_token', 'nextPageToken', 'next_pagination_token', 'next_token', 'cursor',
66
+ ];
67
+ const TOTAL_FIELDS = ['total_available', 'total_documents', 'total_count', 'total'];
68
+ const PROBLEM_FIELDS = ['partial_errors', 'errors', 'failed_count', 'missing_metrics'];
69
+ const NOTE_FIELDS = ['warnings', 'notes'];
70
+ // meta fields that only describe the request or the reply. Anything else is named under the table,
71
+ // so a platform's new way of saying "there is more" can never pass as a complete result.
72
+ const DESCRIPTIVE_META = new Set([
73
+ 'resource', 'path', 'endpoint', 'http_method', 'method', 'label', 'category', 'slug', 'query', 'report',
74
+ 'request_id', 'request_config', 'task_id', 'task_cost', 'token_type', 'timeout', 'wait_for_load', 'includes',
75
+ 'is_read_only', 'is_write_operation', 'readback_action', 'auto_paginate', 'incremental_field',
76
+ 'supports_incremental', 'content_type', 'row_count', 'result_count', 'count', 'response_aggregation_type',
77
+ 'api_dimensions', 'dimension_mapping', 'calculated_dimensions',
78
+ ]);
79
+
80
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
81
+ const hasContent = (value) => (Array.isArray(value) ? value.length > 0 : isRecord(value) ? Object.keys(value).length > 0 : Boolean(value));
82
+
83
+ /** One cell of the human view: one line, nested values as compact JSON, long text cut. */
84
+ function cell(value) {
85
+ if (value === null || value === undefined) return { text: '', cut: false };
86
+ const text = (typeof value === 'object' ? JSON.stringify(value) : String(value)).replace(/\s+/g, ' ');
87
+ const chars = Array.from(text);
88
+ if (chars.length <= CELL_MAX_CHARS) return { text, cut: false };
89
+ return { text: `${chars.slice(0, CELL_MAX_CHARS - 1).join('')}…`, cut: true };
90
+ }
91
+
92
+ /** The rows a result carries: its list (`data`, or a helper's `actions`), else one record as
93
+ * field/value pairs (`data` when it is an object, the whole result otherwise). */
94
+ function resultRows(result, listField) {
95
+ const list = result[listField];
96
+ if (Array.isArray(list)) return list.map((item) => (isRecord(item) ? item : { value: item }));
97
+ const record = isRecord(result.data) ? result.data : result;
98
+ return Object.entries(record)
99
+ .filter(([field]) => record !== result || field !== 'next_step')
100
+ .map(([field, value]) => ({ field, value }));
101
+ }
102
+
103
+ /** What meta says the table cannot show. A "more" marker wins over any count; a total proves a list
104
+ * complete only without one. Every meta field left over that is not descriptive is named. */
105
+ function metaFooters(meta, shown) {
106
+ if (meta === undefined || meta === null) return [];
107
+ if (!isRecord(meta)) return hasContent(meta) ? ['More in meta (drop --table to read it).'] : [];
108
+ const places = [meta, ...PAGING_PLACES.map((key) => meta[key]).filter(isRecord)];
109
+ const total = places.flatMap((place) => TOTAL_FIELDS.map((key) => place[key])).find(Number.isInteger);
110
+ const more = places.some((place) => MORE_MARKERS.some((marker) => place[marker]));
111
+ const footers = [];
112
+ const told = new Set();
113
+ const pagingTold = () => [...PAGING_PLACES, ...MORE_MARKERS, ...TOTAL_FIELDS].forEach((key) => told.add(key));
114
+ if (more) {
115
+ const of = shown !== null && total > shown ? ` of ${total}` : '';
116
+ footers.push(shown === null
117
+ ? 'The server has more (drop --table for its paging details).'
118
+ : `Showing ${shown}${of} rows; the server has more (drop --table for its paging details).`);
119
+ pagingTold();
120
+ } else if (shown !== null && total !== undefined) {
121
+ if (total > shown) footers.push(`Showing ${shown} of ${total} rows.`);
122
+ pagingTold();
26
123
  }
124
+ const problems = PROBLEM_FIELDS.filter((key) => hasContent(meta[key]));
125
+ if (problems.length) footers.push(`Some items failed or were left out: see meta ${problems.join(', ')} (drop --table to read it).`);
126
+ if (NOTE_FIELDS.some((key) => hasContent(meta[key]))) footers.push('The server sent warnings or notes; drop --table to read them.');
127
+ [...PROBLEM_FIELDS, ...NOTE_FIELDS].forEach((key) => told.add(key));
128
+ const rest = Object.keys(meta).filter((key) => !told.has(key) && !DESCRIPTIVE_META.has(key) && hasContent(meta[key]));
129
+ if (rest.length) footers.push(`More in meta: ${rest.map((key) => printable(key)).join(', ')} (drop --table to read it).`);
130
+ return footers;
131
+ }
27
132
 
28
- const header = columns.map(c => c.label.padEnd(widths[c.key])).join(' ');
29
- const separator = columns.map(c => '-'.repeat(widths[c.key])).join(' ');
133
+ /** What the table leaves out of the result itself: a partial failure and its message, the server's
134
+ * message, and the names of any other fields beside the rows. */
135
+ function resultFooters(result, listField, fromWholeResult) {
136
+ const footers = [];
137
+ if (result.partial_failure === true) {
138
+ footers.push(`Partial failure: ${printable(result.message || 'some items were refused')}`);
139
+ } else if (!fromWholeResult && typeof result.message === 'string' && result.message) {
140
+ footers.push(`Message: ${printable(result.message)}`);
141
+ }
142
+ if (!fromWholeResult) {
143
+ const others = Object.keys(result).filter((field) => field !== listField && !ENVELOPE_FIELDS.has(field));
144
+ if (others.length) footers.push(`Also in the result: ${others.map((field) => printable(field)).join(', ')} (drop --table to read them).`);
145
+ }
146
+ return footers;
147
+ }
30
148
 
31
- console.log(header);
32
- console.log(separator);
33
- for (const row of rows) {
34
- const line = columns.map(c => String(row[c.key] ?? '').padEnd(widths[c.key])).join(' ');
35
- console.log(line);
149
+ /** Results of query, action, raw and helper: JSON by default, a table under `--table`. A result with
150
+ * no table form (not an object, or rows with too many different fields) stays JSON, with a note. */
151
+ export function printResult(result, command, listField = 'data') {
152
+ if (wantsJson(command)) {
153
+ printJson(result);
154
+ return;
155
+ }
156
+ if (!isRecord(result)) {
157
+ console.error('This result has no table view; showing JSON.');
158
+ printJsonForHumans(result);
159
+ return;
160
+ }
161
+ const rows = resultRows(result, listField);
162
+ const keys = [...new Set(rows.flatMap((row) => Object.keys(row)))];
163
+ if (keys.length > MAX_COLUMNS) {
164
+ console.error('These rows have too many different fields for a table; showing JSON.');
165
+ printJsonForHumans(result);
166
+ return;
36
167
  }
168
+ let cut = false;
169
+ const cells = rows.map((row) => Object.fromEntries(keys.map((key) => {
170
+ const one = cell(Object.hasOwn(row, key) ? row[key] : undefined);
171
+ cut ||= one.cut;
172
+ return [key, one.text];
173
+ })));
174
+ if (rows.length && !keys.length) console.log(`${rows.length} rows, all empty.`);
175
+ else printTable(cells, keys.map((key) => ({ key, label: key })));
176
+ const isList = Array.isArray(result[listField]);
177
+ const fromWholeResult = !isList && !isRecord(result.data);
178
+ const footers = [
179
+ ...metaFooters(result.meta, isList ? rows.length : null),
180
+ ...(cut ? ['Long values are shortened; drop --table for the full JSON.'] : []),
181
+ ...resultFooters(result, listField, fromWholeResult),
182
+ ];
183
+ if (footers.length) console.log(`\n${footers.join('\n')}`);
37
184
  }