@jacebenson/jsn 5.2.0 → 5.3.0-dev.136.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.
@@ -6,7 +6,7 @@ const BASIC_COMMANDS = new Set([
6
6
  'groups', 'groupmembers', 'grouproles', 'users', 'setup', 'auth', 'skill',
7
7
  'cmdb',
8
8
  'version', 'upgrade', 'docs', 'history', 'discover', 'completion',
9
- 'catalogitems',
9
+ 'catalogitems', 'cases',
10
10
  ]);
11
11
 
12
12
  export async function detectCommandAudience(sdk, username, instanceURL = sdk?.baseURL) {
@@ -0,0 +1,218 @@
1
+ // End-user case views: list/show/search over the case table the account can
2
+ // actually read. Which "case" a person means depends on the installed
3
+ // application, so the table is detected (or named explicitly) instead of
4
+ // assuming one product's schema. Reads only — every request goes through the
5
+ // normal authenticated Table API, so application roles and ACLs decide
6
+ // visibility; nothing here widens or bypasses them.
7
+ import { AppError, CodeForbidden, errUsage, errUsageHint } from '../errors.js';
8
+ import { buildQuerySuffix, formatCommandList, formatRecordForDisplay, getStringField, quoteShellArg, resolveFieldsParam } from '../helpers.js';
9
+ import { getRecord, listRecords, recordListParams } from '../records-engine.js';
10
+ import { declareCapabilities } from '../capabilities.js';
11
+
12
+ declareCapabilities('cases', {}); // read-only: no mutating subcommands
13
+
14
+ const TABLE = /^[a-z][a-z0-9_]*$/i;
15
+ const DEFAULT_COLUMNS = ['number', 'short_description', 'state', 'opened_by', 'sys_updated_on'];
16
+
17
+ // Detection order is presentation policy, not an access claim: each candidate
18
+ // is probed with the caller's own credentials.
19
+ const CASE_SOURCES = [
20
+ { table: 'sn_customerservice_case', application: 'Customer Service Management', label: 'customer service case' },
21
+ { table: 'sn_hr_core_case', application: 'HR Service Delivery', label: 'HR case' },
22
+ ];
23
+
24
+ function sourceFor(table) { return CASE_SOURCES.find(source => source.table === table); }
25
+ function requireTableName(table) {
26
+ if (!TABLE.test(table || '')) throw errUsage('--table takes a table name such as sn_customerservice_case or sn_hr_core_case.');
27
+ return table;
28
+ }
29
+
30
+ /** Turn one failed case read into an honest error class. */
31
+ function caseReadError(table, error) {
32
+ const status = error?.status;
33
+ if (status === 401) return error; // already normalized by errAPI
34
+ if (status === 403) {
35
+ return new AppError(CodeForbidden, `Access to ${table} is denied for this account (HTTP 403).`,
36
+ 'Case visibility follows the application roles and ACLs. Ask an administrator for access, or use a profile that has it.', 403);
37
+ }
38
+ if (status === 400 || status === 404) {
39
+ return errUsageHint(`Reading ${table} failed (HTTP ${status}).`,
40
+ 'The case application may not be installed, or the query uses a field this table does not have. Try jsn cases tables, then --table with a supported table.');
41
+ }
42
+ return error;
43
+ }
44
+
45
+ /** One read-only availability probe. Authentication failures are not a table fact. */
46
+ async function probe(app, table) {
47
+ const params = new URLSearchParams({ sysparm_limit: '1', sysparm_fields: 'sys_id', sysparm_display_value: 'false' });
48
+ try {
49
+ await app.sdk.list(table, params);
50
+ return { available: true };
51
+ } catch (error) {
52
+ if (error?.status === 401) throw error;
53
+ if (error?.status === 403) return { available: false, reason: 'denied (HTTP 403)', status: 403 };
54
+ if (error?.status === 400 || error?.status === 404) return { available: false, reason: `not installed (HTTP ${error.status})`, status: error.status };
55
+ throw error;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Pick the case table to read: --hr and --table are explicit, otherwise probe
61
+ * the known case applications in order and use the first readable one.
62
+ */
63
+ async function resolveTable(app, argv) {
64
+ const explicit = argv.hr ? 'sn_hr_core_case' : argv.table === undefined ? undefined : requireTableName(argv.table);
65
+ if (argv.hr && argv.table !== undefined && argv.table !== 'sn_hr_core_case') throw errUsage('Choose --hr or --table, not both.');
66
+ if (explicit) {
67
+ const source = sourceFor(explicit);
68
+ return { table: explicit, application: source?.application ?? null, label: source?.label ?? 'case', source: 'explicit' };
69
+ }
70
+ const attempts = [];
71
+ for (const source of CASE_SOURCES) {
72
+ const probeResult = await probe(app, source.table);
73
+ attempts.push({ ...source, ...probeResult });
74
+ if (probeResult.available) return { ...source, source: 'detected', attempts };
75
+ }
76
+ const summary = attempts.map(a => `${a.table} ${a.reason}`).join('; ');
77
+ if (attempts.some(a => a.status === 403)) {
78
+ throw new AppError(CodeForbidden, `No readable case table for this account: ${summary}.`,
79
+ 'Case visibility follows the application roles and ACLs. Ask an administrator for case access, or use a profile that has it.', 403);
80
+ }
81
+ throw errUsageHint(
82
+ `No readable case table on this instance: ${summary}.`,
83
+ 'Install a case application (Customer Service Management or HR Service Delivery) and use an account with case access, or name a table explicitly with --table.',
84
+ );
85
+ }
86
+
87
+ async function listCases(app, argv, resolved, query) {
88
+ const columns = argv.columns ? argv.columns.split(',') : DEFAULT_COLUMNS;
89
+ const fields = resolveFieldsParam(columns);
90
+ const ordered = query ? `${query}^ORDERBYDESCsys_updated_on` : 'ORDERBYDESCsys_updated_on';
91
+ const params = recordListParams({ limit: argv.limit, offset: argv.offset, fields, query: ordered });
92
+ let records;
93
+ try {
94
+ records = await listRecords(app.sdk, { table: resolved.table, params, displayValues: argv.displayValues });
95
+ } catch (error) {
96
+ throw caseReadError(resolved.table, error);
97
+ }
98
+ const displayRecords = fields && !argv.displayValues ? records.map(r => formatRecordForDisplay(r, columns)) : records;
99
+ const breadcrumbs = [
100
+ { action: 'search', cmd: `jsn cases search "<text>"${argv.hr ? ' --hr' : ''}`, description: 'Search cases' },
101
+ ];
102
+ if (records.length === argv.limit) {
103
+ breadcrumbs.push({ action: 'next', cmd: `jsn cases list --limit ${argv.limit} --offset ${argv.offset + argv.limit}${buildQuerySuffix(argv.query)}`, description: 'Next page' });
104
+ }
105
+ if (argv.offset > 0) {
106
+ breadcrumbs.push({ action: 'prev', cmd: `jsn cases list --limit ${argv.limit} --offset ${Math.max(0, argv.offset - argv.limit)}${buildQuerySuffix(argv.query)}`, description: 'Previous page' });
107
+ }
108
+ app.ok({
109
+ table: resolved.table,
110
+ application: resolved.application,
111
+ table_source: resolved.source,
112
+ count: records.length,
113
+ columns,
114
+ records: displayRecords,
115
+ pagination: { limit: argv.limit, offset: argv.offset },
116
+ context: { instance_url: app.getEffectiveInstance() },
117
+ }, { summary: `${records.length} ${resolved.table}(s)`, breadcrumbs });
118
+ }
119
+
120
+ function listOptions(y) {
121
+ return y
122
+ .option('table', { type: 'string', describe: 'Case table to read (default: detected from installed case applications)' })
123
+ .option('hr', { type: 'boolean', default: false, describe: 'Read the HR case table (sn_hr_core_case)' })
124
+ .option('query', { type: 'string', describe: 'Encoded query (e.g. "active=true")' })
125
+ .option('columns', { alias: ['c', 'fields'], type: 'string', describe: 'Comma-separated columns' })
126
+ .option('limit', { alias: 'l', type: 'number', default: 20, describe: 'Max records' })
127
+ .option('offset', { alias: 'o', type: 'number', default: 0, describe: 'Offset' })
128
+ .option('display-values', { type: 'string', choices: ['raw', 'display', 'both'], describe: 'Reference values: raw, display or both' });
129
+ }
130
+
131
+ function showOptions(y) {
132
+ return y
133
+ .option('table', { type: 'string', describe: 'Case table to read (default: detected from installed case applications)' })
134
+ .option('hr', { type: 'boolean', default: false, describe: 'Read the HR case table (sn_hr_core_case)' })
135
+ .option('display-values', { type: 'string', choices: ['raw', 'display', 'both'], describe: 'Reference values: raw, display or both' });
136
+ }
137
+
138
+ function requireText(text) {
139
+ if (typeof text !== 'string' || !text.trim()) throw errUsage('Provide nonempty search text.');
140
+ if (text.includes('^')) throw errUsage('Search text cannot contain ^ (it separates encoded-query terms).');
141
+ return text.trim();
142
+ }
143
+
144
+ export function casesCmd(wrap) {
145
+ return {
146
+ command: 'cases [subcommand]',
147
+ aliases: ['case'],
148
+ describe: 'List, show or search service and HR cases visible to the connected account',
149
+ builder: (yargs) => yargs
150
+ .command({
151
+ command: 'list',
152
+ aliases: ['ls'],
153
+ describe: 'List cases the connected account can read',
154
+ builder: listOptions,
155
+ handler: wrap(async (argv, app) => {
156
+ const resolved = await resolveTable(app, argv);
157
+ await listCases(app, argv, resolved, argv.query || '');
158
+ }),
159
+ })
160
+ .command({
161
+ command: 'search <text>',
162
+ describe: 'Search case number and short description',
163
+ builder: y => listOptions(y).positional('text', { type: 'string' }),
164
+ handler: wrap(async (argv, app) => {
165
+ const text = requireText(argv.text);
166
+ const resolved = await resolveTable(app, argv);
167
+ await listCases(app, argv, resolved, `numberLIKE${text}^ORshort_descriptionLIKE${text}`);
168
+ }),
169
+ })
170
+ .command({
171
+ command: 'show <number>',
172
+ aliases: ['get'],
173
+ describe: 'Show one case by number',
174
+ builder: showOptions,
175
+ handler: wrap(async (argv, app) => {
176
+ const resolved = await resolveTable(app, argv);
177
+ let record;
178
+ try {
179
+ record = await getRecord(app.sdk, { table: resolved.table, identifier: argv.number, matchField: 'number', displayValues: argv.displayValues, resource: resolved.label });
180
+ } catch (error) {
181
+ throw caseReadError(resolved.table, error);
182
+ }
183
+ record._context = { instance_url: app.getEffectiveInstance(), table: resolved.table };
184
+ app.ok(record, {
185
+ summary: `${resolved.label.charAt(0).toUpperCase() + resolved.label.slice(1)} ${getStringField(record, 'number') || argv.number}`,
186
+ breadcrumbs: [
187
+ { action: 'list', cmd: `jsn cases list${argv.hr ? ' --hr' : argv.table ? ` --table ${quoteShellArg(argv.table)}` : ''}`, description: 'Back to cases' },
188
+ ],
189
+ });
190
+ }),
191
+ })
192
+ .command({
193
+ command: 'tables',
194
+ describe: 'Report which case applications this instance exposes to the account',
195
+ handler: wrap(async (argv, app) => {
196
+ const sources = [];
197
+ for (const source of CASE_SOURCES) {
198
+ const probeResult = await probe(app, source.table);
199
+ sources.push({ ...source, ...probeResult });
200
+ }
201
+ app.ok({ sources, available: sources.filter(s => s.available).map(s => s.table) },
202
+ { summary: sources.filter(s => s.available).length ? `Case tables: ${sources.filter(s => s.available).map(s => s.table).join(', ')}` : 'No readable case table found',
203
+ breadcrumbs: [{ action: 'list', cmd: 'jsn cases list', description: 'List cases' }] });
204
+ }),
205
+ })
206
+ .epilogue([
207
+ 'Default table: the first readable case application (Customer Service Management, then HR Service Delivery).',
208
+ 'Use --hr for sn_hr_core_case or --table <name> for any case table you can read; jsn cases tables reports each one.',
209
+ 'Reads use the caller\'s own credentials and ACLs. Self-service scoping is a query, not a bypass, and field names differ per application:',
210
+ ' jsn cases list --query "opened_by=javascript:gs.getUserID()" --hr',
211
+ 'Nothing here changes a case; use the application UI or records update for case work.',
212
+ ].join('\n')),
213
+ handler: wrap(async (argv, app) => app.ok({ subcommands: argv.subcommands || [],
214
+ _formatted: formatCommandList({ title: 'Cases', commands: argv.subcommands || [] }) },
215
+ { summary: 'Cases: list, show and search service or HR cases visible to the connected account',
216
+ breadcrumbs: [{ action: 'list', cmd: 'jsn cases list' + (argv.profile ? ` --profile ${quoteShellArg(argv.profile)}` : argv.instance ? ` --instance ${quoteShellArg(argv.instance)}` : ''), description: 'List visible cases' }] })),
217
+ };
218
+ }
@@ -1,24 +1,122 @@
1
- // Catalog item enrichment — pure async data-shaping for `catalogitems show`.
1
+ // Catalog item enrichment — one place that reads a catalog item and shapes it
2
+ // for output. `catalogitems show` owns the user-facing view (and the
3
+ // describe/inputs aliases); `catalogitems order` reuses the same request-side
4
+ // read, so both agree on what a question is.
2
5
  //
3
- // Given an sdk handle, an instance URL and an item sys_id, return the
4
- // enriched item: core fields resolved to display values, flow name resolved
5
- // through the sys_hub_flow fallback chain, workflow/delivery-plan fallback,
6
- // and variables grouped by variable set. No yargs, no output formatting —
7
- // callers own the envelope and rendering.
6
+ // Two calls, one answer:
7
+ // 1. the Table API (sc_cat_item + item_option_new) — the definition, always
8
+ // readable, and the fallback when the catalog API cannot answer;
9
+ // 2. /api/sn_sc/servicecatalog/items/{id} — what this account can actually
10
+ // request, with the variables a submission must answer.
11
+ // The catalog API wins when it answers; the definition list keeps the command
12
+ // useful when it does not (a producer whose server script throws, an item that
13
+ // is not in the catalog).
8
14
 
9
15
  import { getStringField } from '../../helpers.js';
10
16
 
17
+ export const CATALOG_API = '/api/sn_sc/servicecatalog/items';
18
+
19
+ // Layout entries draw the form; they are not values a caller can send.
20
+ // Codes are item_option_new.type on a live instance (11 label, 14 macro,
21
+ // 17 macro with label, 19/20/24 containers, 23 html, 32 rich text label).
22
+ const LAYOUT_CODES = new Set([11, 14, 17, 19, 20, 23, 24, 32]);
23
+ const LAYOUT_TYPES = new Set([
24
+ 'container_start', 'container_end', 'container_split',
25
+ 'label', 'rich_text_label', 'html', 'break', 'formatter',
26
+ 'macro', 'macro_with_abel', 'ui_macro',
27
+ ]);
28
+ // "Requested for" (type 31) is mandatory in the API payload but is not a value
29
+ // the caller builds: the instance fills it from the session and --requested-for
30
+ // overrides it. It is reported separately so it never blocks an order.
31
+ export const REQUESTED_FOR = 31;
32
+ // item_option_new.type code → the same friendly word the catalog API uses, so
33
+ // the definition fallback and the API payload render identically. Codes taken
34
+ // from this instance's type choices; unknown codes fall back to null.
35
+ const TYPE_NAMES = {
36
+ 1: 'yes_no', 2: 'multi_line_text', 3: 'multiple_choice', 4: 'numeric_scale',
37
+ 5: 'select_box', 6: 'single_line_text', 7: 'check_box', 8: 'reference',
38
+ 9: 'date', 10: 'date_time', 11: 'label', 14: 'macro', 16: 'wide_single_line_text',
39
+ 17: 'macro_with_abel', 18: 'lookup_select_box', 19: 'container_start',
40
+ 20: 'container_end', 21: 'list_collector', 23: 'html', 24: 'container_split',
41
+ 25: 'masked', 26: 'email', 28: 'ip', 29: 'duration', 31: 'requested_for',
42
+ 32: 'rich_text_label', 33: 'attachment', 40: 'table_name',
43
+ };
44
+
45
+ /** Raw value of a field: list rows come back as {value, display_value}. */
46
+ function rawValue(row, field) {
47
+ const v = row?.[field];
48
+ return v && typeof v === 'object' ? v.value : v;
49
+ }
50
+
51
+ export const isInstanceSupplied = v => v?.friendly_type === 'requested_for' || Number(v?.type) === REQUESTED_FOR;
52
+ const object = v => v && typeof v === 'object' && !Array.isArray(v);
53
+
54
+ /** Read the item from the catalog API. Throws when the instance refuses. */
55
+ export async function readCatalogApiItem(sdk, sysID) {
56
+ const response = await sdk.request(`${sdk.baseURL}${CATALOG_API}/${sysID}`, { method: 'GET' });
57
+ if (!object(response?.result) || response.result.sys_id !== sysID) {
58
+ const error = new Error('Catalog API returned no readable item with the requested identity.');
59
+ error.code = 'api_error';
60
+ throw error;
61
+ }
62
+ return response.result;
63
+ }
64
+
65
+ /**
66
+ * Flatten a catalog API `variables` tree into the questions a caller can
67
+ * answer. Containers are walked for their children; every other layout entry
68
+ * is dropped. A name is reported once — the API can repeat a variable inside a
69
+ * container.
70
+ */
71
+ export function shapeVariables(list, out = [], seen = new Set()) {
72
+ if (!Array.isArray(list)) return out;
73
+ for (const entry of list) {
74
+ if (!object(entry)) continue;
75
+ const friendly = typeof entry.friendly_type === 'string' ? entry.friendly_type : '';
76
+ const name = typeof entry.name === 'string' ? entry.name : '';
77
+ if (name && !LAYOUT_TYPES.has(friendly) && !seen.has(name)) {
78
+ seen.add(name);
79
+ out.push({
80
+ name,
81
+ label: entry.label || entry.question_text || name,
82
+ type: entry.type ?? null,
83
+ friendly_type: friendly || null,
84
+ mandatory: entry.mandatory === true || entry.mandatory === 'true',
85
+ instance_supplied: isInstanceSupplied(entry),
86
+ });
87
+ }
88
+ if (Array.isArray(entry.children)) shapeVariables(entry.children, out, seen);
89
+ }
90
+ return out;
91
+ }
92
+
93
+ /** Shape one item_option_new row into the same question shape. */
94
+ function questionFromRow(row) {
95
+ const code = Number(rawValue(row, 'type'));
96
+ const name = getStringField(row, 'name');
97
+ if (!name || LAYOUT_CODES.has(code)) return null;
98
+ return {
99
+ name,
100
+ label: getStringField(row, 'question_text') || name,
101
+ type: Number.isFinite(code) ? code : null,
102
+ friendly_type: TYPE_NAMES[code] ?? null,
103
+ mandatory: String(rawValue(row, 'mandatory')) === 'true',
104
+ instance_supplied: code === REQUESTED_FOR,
105
+ };
106
+ }
107
+
108
+ /** Required / instance-supplied names for a question list. */
109
+ export function requestDetails(variables) {
110
+ return {
111
+ required: variables.filter(v => v.mandatory && !v.instance_supplied).map(v => v.name),
112
+ instanceSupplied: variables.filter(v => v.instance_supplied).map(v => v.name),
113
+ };
114
+ }
115
+
11
116
  /**
12
117
  * Fetch a catalog item and assemble the full show envelope.
13
118
  *
14
- * @param {object} deps
15
- * @param {object} deps.sdk - SDK handle (list/get).
16
- * @param {string} deps.instanceUrl - Effective instance URL (for the item link).
17
- * @param {string} deps.sysID - sc_cat_item sys_id.
18
- * @returns {Promise<{data: object, standalone: Array, setVars: Array, totalVars: number}>}
19
- * data is the envelope payload (no _formatted — the caller attaches it);
20
- * standalone/setVars/totalVars are the raw groupings needed by
21
- * buildCatalogFormatted.
119
+ * @returns {Promise<{data: object, variables: Array, totalVars: number, source: string}>}
22
120
  */
23
121
  export async function enrichCatalogItem({ sdk, instanceUrl, sysID }) {
24
122
  // Use list + display_value=all so reference fields (category, flow) resolve
@@ -32,30 +130,27 @@ export async function enrichCatalogItem({ sdk, instanceUrl, sysID }) {
32
130
  if (!item) throw new Error(`Not found: ${sysID}`);
33
131
 
34
132
  const vp = new URLSearchParams();
35
- vp.set('sysparm_query', `cat_item=${sysID}^active=true`);
133
+ vp.set('sysparm_query', `cat_item=${sysID}^active=true^ORDERBYorder`);
36
134
  vp.set('sysparm_limit', '100');
37
135
  vp.set('sysparm_display_value', 'all');
38
136
  vp.set('sysparm_fields', 'sys_id,name,question_text,type,order,mandatory,variable_set');
39
- const variables = await sdk.list('item_option_new', vp);
40
-
41
- const standalone = [];
42
- const setVars = new Map();
43
- for (const v of variables) {
44
- const vs = getStringField(v, 'variable_set');
45
- const entry = {
46
- name: getStringField(v, 'name'),
47
- question_text: getStringField(v, 'question_text'),
48
- type: getStringField(v, 'type'),
49
- mandatory: getStringField(v, 'mandatory'),
50
- };
51
- if (vs) {
52
- if (!setVars.has(vs)) setVars.set(vs, { name: vs, variables: [] });
53
- setVars.get(vs).variables.push(entry);
54
- } else {
55
- standalone.push(entry);
137
+ const rows = await sdk.list('item_option_new', vp);
138
+
139
+ let apiItem = null;
140
+ let apiError = '';
141
+ if (typeof sdk.request === 'function' && typeof sdk.baseURL === 'string') {
142
+ try {
143
+ apiItem = await readCatalogApiItem(sdk, sysID);
144
+ } catch (error) {
145
+ apiError = error?.message || 'catalog API read failed';
56
146
  }
57
147
  }
58
- const totalVars = standalone.length + Array.from(setVars.values()).reduce((a, s) => a + s.variables.length, 0);
148
+
149
+ const fromApi = Array.isArray(apiItem?.variables);
150
+ const variables = fromApi
151
+ ? shapeVariables(apiItem.variables)
152
+ : rows.map(questionFromRow).filter(Boolean);
153
+ const source = fromApi ? 'catalog_api' : 'item_option_new';
59
154
 
60
155
  // Resolve flow name
61
156
  let flowName = '', flowCmd = '';
@@ -69,6 +164,7 @@ export async function enrichCatalogItem({ sdk, instanceUrl, sysID }) {
69
164
  }
70
165
  const wfName = getStringField(item, 'workflow') || '';
71
166
  const planName = getStringField(item, 'delivery_plan') || getStringField(item, 'execution_plan') || '';
167
+ const details = requestDetails(variables);
72
168
 
73
169
  const data = {
74
170
  name: getStringField(item, 'name'),
@@ -79,24 +175,22 @@ export async function enrichCatalogItem({ sdk, instanceUrl, sysID }) {
79
175
  flow: flowName || undefined,
80
176
  flow_cmd: flowCmd || undefined,
81
177
  workflow: wfName || undefined,
82
-
83
178
  execution_plan: planName || undefined,
84
- variables: totalVars > 0 ? {
85
- count: totalVars,
86
- standalone: standalone.map(v => ({ label: v.question_text || v.name, type: v.type, mandatory: String(v.mandatory) === 'true' })),
87
- sets: Array.from(setVars.values()).map(s => ({ name: s.name, variables: s.variables.map(v => ({ label: v.question_text || v.name, type: v.type, mandatory: String(v.mandatory) === 'true' })) })),
88
- } : undefined,
179
+ variables,
180
+ variables_source: source,
181
+ variables_reported: fromApi,
182
+ required_variables: details.required,
183
+ instance_supplied_variables: details.instanceSupplied,
184
+ ...(apiError ? { variables_api_error: apiError } : {}),
89
185
  };
90
186
 
91
- return { data, standalone, setVars: Array.from(setVars.values()), totalVars };
187
+ return { data, variables, totalVars: variables.length, source };
92
188
  }
93
189
 
94
190
  /**
95
- * Styled-mode rendering of an enriched catalog item. Kept verbatim from the
96
- * original catalog.js — the output layer is being reworked elsewhere, so this
97
- * stays byte-identical for now.
191
+ * Styled-mode rendering of an enriched catalog item.
98
192
  */
99
- export function buildCatalogFormatted(data, standalone, setVars, totalVars) {
193
+ export function buildCatalogFormatted(data, variables = data.variables || [], source = data.variables_source) {
100
194
  const lines = [];
101
195
  lines.push(`${data.name} (sc_cat_item)`);
102
196
  lines.push('');
@@ -118,19 +212,20 @@ export function buildCatalogFormatted(data, standalone, setVars, totalVars) {
118
212
  lines.push(` ${data.workflow}`);
119
213
  lines.push('');
120
214
  }
121
- if (totalVars > 0) {
122
- lines.push('─ Catalog Variables ─');
123
- for (const v of standalone) {
124
- const label = v.question_text || v.name;
125
- lines.push(` ${label}: ${v.type}${String(v.mandatory) === 'true' ? ' (mandatory)' : ''}`);
126
- }
127
- for (const s of setVars) {
128
- lines.push(` [${s.name}]`);
129
- for (const v of s.variables) {
130
- const label = v.question_text || v.name;
131
- lines.push(` ${label}: ${v.type}${String(v.mandatory) === 'true' ? ' (mandatory)' : ''}`);
132
- }
215
+ if (variables.length) {
216
+ lines.push(`─ Catalog Questions (${source === 'catalog_api' ? 'catalog API' : 'item_option_new'}) ─`);
217
+ for (const v of variables) {
218
+ const type = v.friendly_type || (v.type === null ? '?' : String(v.type));
219
+ const flags = [v.mandatory ? 'required' : '', v.instance_supplied ? 'instance-supplied' : ''].filter(Boolean);
220
+ lines.push(` ${v.name} ${v.label} [${type}]${flags.length ? ` (${flags.join(', ')})` : ''}`);
133
221
  }
222
+ if (data.required_variables?.length) lines.push(` required: ${data.required_variables.join(', ')}`);
223
+ if (data.instance_supplied_variables?.length) lines.push(` instance-supplied: ${data.instance_supplied_variables.join(', ')}`);
224
+ lines.push('');
225
+ }
226
+ if (data.variables_api_error) {
227
+ lines.push('─ Catalog API ─');
228
+ lines.push(` unavailable: ${data.variables_api_error}`);
134
229
  lines.push('');
135
230
  }
136
231
  return lines.join('\n');