@aderis-erp/cli 1.0.12 → 1.0.13

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.
@@ -0,0 +1,1182 @@
1
+ import { Command, Args, Flags } from '@oclif/core';
2
+ import { apiRequest, ApiError } from '../lib/api-client.js';
3
+ import { getCurrentContext, getContext, getBaseUrls } from '../lib/config.js';
4
+ // Add 'import' action if both create and update exist
5
+ const HAS_IMPORT = true;
6
+ const HAS_EXPORT = true;
7
+ const HAS_CAMT053 = false;
8
+ const NESTED_IMPORTS = [];
9
+ const SUBCOMMANDS = [...["list", "create", "get", "update", "delete", "runs", "pause", "resume", "trigger"], ...(HAS_IMPORT ? ['import'] : []), ...(HAS_EXPORT ? ['export'] : []), ...NESTED_IMPORTS.map(n => `import-${n}`)];
10
+ const ENDPOINTS = {
11
+ 'list': { method: 'GET', path: '/v1/schedules', summary: 'List schedules with pagination (admin only)', pathParams: [], hasBody: false, isMultipart: false, isBinaryResponse: false, bodyArrayFields: [] },
12
+ 'create': { method: 'POST', path: '/v1/schedules', summary: 'Create a schedule (admin only)', pathParams: [], hasBody: true, isMultipart: false, isBinaryResponse: false, bodyArrayFields: [] },
13
+ 'get': { method: 'GET', path: '/v1/schedules/{id}', summary: 'Get a schedule by ID (admin only)', pathParams: ['id'], hasBody: false, isMultipart: false, isBinaryResponse: false, bodyArrayFields: [] },
14
+ 'update': { method: 'PATCH', path: '/v1/schedules/{id}', summary: 'Update a schedule (admin only)', pathParams: ['id'], hasBody: true, isMultipart: false, isBinaryResponse: false, bodyArrayFields: [] },
15
+ 'delete': { method: 'DELETE', path: '/v1/schedules/{id}', summary: 'Delete a schedule (admin only)', pathParams: ['id'], hasBody: false, isMultipart: false, isBinaryResponse: false, bodyArrayFields: [] },
16
+ 'runs': { method: 'GET', path: '/v1/schedules/{id}/runs', summary: 'List a schedule\'s execution history with pagination (admin only)', pathParams: ['id'], hasBody: false, isMultipart: false, isBinaryResponse: false, bodyArrayFields: [] },
17
+ 'pause': { method: 'POST', path: '/v1/schedules/{id}/pause', summary: 'Pause a schedule so it no longer runs (admin only)', pathParams: ['id'], hasBody: false, isMultipart: false, isBinaryResponse: false, bodyArrayFields: [] },
18
+ 'resume': { method: 'POST', path: '/v1/schedules/{id}/resume', summary: 'Resume a paused schedule (admin only)', pathParams: ['id'], hasBody: false, isMultipart: false, isBinaryResponse: false, bodyArrayFields: [] },
19
+ 'trigger': { method: 'POST', path: '/v1/schedules/{id}/trigger', summary: 'Manually run a schedule right now, rate-limited to one accepted trigger per schedule per 60 seconds (admin only)', pathParams: ['id'], hasBody: false, isMultipart: false, isBinaryResponse: false, bodyArrayFields: [] },
20
+ };
21
+ export default class Schedules extends Command {
22
+ static description = 'Manage schedules';
23
+ static examples = [
24
+ '<%= config.bin %> schedules list',
25
+ '<%= config.bin %> schedules get <id>',
26
+ '<%= config.bin %> schedules create --data \'{...}\'',
27
+ '<%= config.bin %> schedules update <id> --set field=value',
28
+ '<%= config.bin %> schedules import --file data.json',
29
+ '<%= config.bin %> schedules export --csv > schedules.csv',
30
+ ];
31
+ static args = {
32
+ action: Args.string({ description: 'Action: ' + SUBCOMMANDS.join(', '), required: true }),
33
+ id: Args.string({ description: 'Resource ID (for get, update, delete operations)', required: false }),
34
+ };
35
+ static flags = {
36
+ context: Flags.string({ char: 'c', description: 'Context to use' }),
37
+ output: Flags.string({ char: 'o', description: 'Output format (default: table for import, json for other commands)', options: ['json', 'table', 'csv'] }),
38
+ table: Flags.boolean({ char: 't', description: 'Output as table (shortcut for --output table)' }),
39
+ csv: Flags.boolean({ description: 'Output as CSV (shortcut for --output csv)' }),
40
+ data: Flags.string({ char: 'd', description: 'JSON data for request body' }),
41
+ file: Flags.string({ char: 'f', description: 'Read request body from file' }),
42
+ set: Flags.string({ char: 's', description: 'Set individual field (e.g. --set firstName=John)', multiple: true }),
43
+ page: Flags.string({ description: 'Page number' }),
44
+ limit: Flags.string({ description: 'Items per page' }),
45
+ include: Flags.string({ description: 'Relations to include' }),
46
+ search: Flags.string({ description: 'Search term' }),
47
+ 'sort-by': Flags.string({ description: 'Sort field' }),
48
+ filter: Flags.string({ description: 'Filter (e.g. --filter status=ACTIVE). Operators: in:A,B, like:%, gt:, lt:, null:', multiple: true }),
49
+ query: Flags.string({ description: 'Additional query params as JSON' }),
50
+ fields: Flags.string({ description: 'Comma-separated list of fields to show (e.g. --fields=id,name,status)' }),
51
+ sanitize: Flags.boolean({ description: 'Remove null values, audit fields, and duplicate UUIDs from output' }),
52
+ 'show-http-request': Flags.boolean({ description: 'Show HTTP request details (method, URL, body)' }),
53
+ };
54
+ async run() {
55
+ const { args, flags } = await this.parse(Schedules);
56
+ // Handle import action specially
57
+ if (args.action === 'import') {
58
+ if (!HAS_IMPORT)
59
+ this.error('Import not available for this resource');
60
+ await this.runImport(flags);
61
+ return;
62
+ }
63
+ // Handle export action specially
64
+ if (args.action === 'export') {
65
+ if (!HAS_EXPORT)
66
+ this.error('Export not available for this resource');
67
+ await this.runExport(flags);
68
+ return;
69
+ }
70
+ // Handle CAMT.053 import specially - sends raw XML
71
+ if (args.action === 'import-camt053') {
72
+ if (!HAS_CAMT053)
73
+ this.error('CAMT.053 import not available for this resource');
74
+ await this.runCamt053Import(flags);
75
+ return;
76
+ }
77
+ // Handle nested resource imports (e.g., import-prices)
78
+ if (args.action.startsWith('import-')) {
79
+ const suffix = args.action.replace('import-', '');
80
+ if (NESTED_IMPORTS.includes(suffix)) {
81
+ await this.runNestedImport(suffix, args.id, flags);
82
+ return;
83
+ }
84
+ }
85
+ const endpoint = ENDPOINTS[args.action];
86
+ if (!endpoint)
87
+ this.error(`Unknown action: ${args.action}. Available: ${SUBCOMMANDS.join(', ')}`);
88
+ let apiPath = endpoint.path;
89
+ for (let i = 0; i < endpoint.pathParams.length; i++) {
90
+ const param = endpoint.pathParams[i];
91
+ let value;
92
+ if (i === 0) {
93
+ // First path param always comes from positional argument
94
+ value = args.id;
95
+ if (!value)
96
+ this.error('Missing required argument: id. Usage: aderis schedules <action> <id>');
97
+ }
98
+ else {
99
+ const flagName = param.replace(/\./g, '-').replace(/([A-Z])/g, '-$1').toLowerCase().replace(/^-/, '');
100
+ value = flags[flagName];
101
+ if (!value)
102
+ this.error(`Missing required parameter: --${flagName}`);
103
+ }
104
+ apiPath = apiPath.replace(`{${param}}`, String(value));
105
+ }
106
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
107
+ if (!context)
108
+ this.error('No context configured. Run: aderis auth login --new');
109
+ if (!context.tokens)
110
+ this.error('Not logged in. Run: aderis auth login');
111
+ const queryParams = {};
112
+ if (flags.page)
113
+ queryParams.page = flags.page;
114
+ if (flags.limit)
115
+ queryParams.limit = flags.limit;
116
+ if (flags.include)
117
+ queryParams.include = flags.include;
118
+ if (flags.search)
119
+ queryParams.search = flags.search;
120
+ if (flags['sort-by'])
121
+ queryParams.sortBy = flags['sort-by'];
122
+ if (flags.query) {
123
+ try {
124
+ Object.assign(queryParams, JSON.parse(flags.query));
125
+ }
126
+ catch {
127
+ this.error('Invalid JSON in --query');
128
+ }
129
+ }
130
+ // Parse --filter flags (e.g., --filter status=ACTIVE becomes filter.status=$eq:ACTIVE)
131
+ if (flags.filter && flags.filter.length > 0) {
132
+ for (const f of flags.filter) {
133
+ const eqIndex = f.indexOf('=');
134
+ if (eqIndex === -1)
135
+ this.error(`Invalid --filter format: ${f}. Use: --filter key=value`);
136
+ const key = f.slice(0, eqIndex);
137
+ const value = this.parseFilterValue(f.slice(eqIndex + 1));
138
+ const filterKey = `filter.${key}`;
139
+ if (filterKey in queryParams) {
140
+ // Multiple filters on same field: collect as array
141
+ const existing = queryParams[filterKey];
142
+ queryParams[filterKey] = Array.isArray(existing) ? [...existing, value] : [existing, value];
143
+ }
144
+ else {
145
+ queryParams[filterKey] = value;
146
+ }
147
+ }
148
+ }
149
+ let data;
150
+ if (endpoint.isMultipart) {
151
+ if (!flags.file)
152
+ this.error('Missing required --file flag for file upload');
153
+ const fsModule = await import('node:fs');
154
+ const pathModule = await import('node:path');
155
+ const FormDataLib = (await import('form-data')).default;
156
+ const form = new FormDataLib();
157
+ form.append('file', fsModule.createReadStream(flags.file), pathModule.basename(flags.file));
158
+ // Append --set fields as extra form fields (e.g. --set type=CREDIT_CARD_STATEMENT)
159
+ if (flags.set && flags.set.length > 0) {
160
+ for (const pair of flags.set) {
161
+ const eqIndex = pair.indexOf('=');
162
+ if (eqIndex === -1)
163
+ this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
164
+ form.append(pair.slice(0, eqIndex), pair.slice(eqIndex + 1));
165
+ }
166
+ }
167
+ data = form;
168
+ }
169
+ else if (endpoint.hasBody) {
170
+ // For binary-response endpoints, --file is the output path, not a JSON
171
+ // input file — skip the read-as-body branch.
172
+ if (flags.file && !endpoint.isBinaryResponse) {
173
+ const fsModule = await import('node:fs');
174
+ try {
175
+ data = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
176
+ }
177
+ catch {
178
+ this.error(`Failed to read file: ${flags.file}`);
179
+ }
180
+ }
181
+ else if (flags.data) {
182
+ try {
183
+ data = JSON.parse(flags.data);
184
+ }
185
+ catch {
186
+ this.error('Invalid JSON in --data');
187
+ }
188
+ }
189
+ // Apply --set flags (can be combined with --data or --file)
190
+ if (flags.set && flags.set.length > 0) {
191
+ if (!data)
192
+ data = {};
193
+ const body = data;
194
+ const arrayFields = new Set(endpoint.bodyArrayFields);
195
+ for (const pair of flags.set) {
196
+ const eqIndex = pair.indexOf('=');
197
+ if (eqIndex === -1)
198
+ this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
199
+ const key = pair.slice(0, eqIndex);
200
+ let value = pair.slice(eqIndex + 1);
201
+ // Try to parse as JSON for numbers, booleans, arrays, objects
202
+ try {
203
+ value = JSON.parse(value);
204
+ }
205
+ catch { /* keep as string */ }
206
+ // For top-level keys typed as array in the API schema, split bare
207
+ // comma-separated input (e.g. "1171,1170" -> ["1171","1170"]) and
208
+ // wrap a lone scalar in a single-element array. Skips when --set
209
+ // already provided a JSON array.
210
+ const isArrayField = !key.includes('.') && arrayFields.has(key);
211
+ if (isArrayField && !Array.isArray(value)) {
212
+ if (typeof value === 'string') {
213
+ value = value.split(',').map(v => v.trim()).filter(v => v.length > 0);
214
+ }
215
+ else if (value !== undefined && value !== null) {
216
+ value = [value];
217
+ }
218
+ }
219
+ // Support nested keys like "address.city"
220
+ const keys = key.split('.');
221
+ if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
222
+ this.error(`Invalid --set key: ${key}`);
223
+ }
224
+ let obj = body;
225
+ for (let i = 0; i < keys.length - 1; i++) {
226
+ if (!(keys[i] in obj) || typeof obj[keys[i]] !== 'object') {
227
+ obj[keys[i]] = {};
228
+ }
229
+ obj = obj[keys[i]];
230
+ }
231
+ obj[keys[keys.length - 1]] = value;
232
+ }
233
+ }
234
+ }
235
+ else if (flags.set && flags.set.length > 0) {
236
+ // For GET endpoints, --set adds query params
237
+ for (const pair of flags.set) {
238
+ const eqIndex = pair.indexOf('=');
239
+ if (eqIndex === -1)
240
+ this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
241
+ const key = pair.slice(0, eqIndex);
242
+ let value = pair.slice(eqIndex + 1);
243
+ try {
244
+ value = JSON.parse(value);
245
+ }
246
+ catch { /* keep as string */ }
247
+ queryParams[key] = value;
248
+ }
249
+ }
250
+ // Show HTTP request details if --show-http-request flag is set
251
+ if (flags['show-http-request']) {
252
+ const baseUrls = getBaseUrls(context.environment);
253
+ const queryString = Object.keys(queryParams).length > 0
254
+ ? '?' + Object.entries(queryParams).flatMap(([k, v]) => {
255
+ const vals = Array.isArray(v) ? v : [v];
256
+ return vals.map(val => `${encodeURIComponent(k)}=${encodeURIComponent(String(val))}`);
257
+ }).join('&')
258
+ : '';
259
+ process.stderr.write(`\n${endpoint.method.toUpperCase()} ${baseUrls.api}${apiPath}${queryString}\n`);
260
+ if (endpoint.isMultipart) {
261
+ process.stderr.write(`Body: [multipart/form-data file upload]\n`);
262
+ }
263
+ else if (data) {
264
+ process.stderr.write(`Body: ${JSON.stringify(data, null, 2)}\n`);
265
+ }
266
+ process.stderr.write('\n');
267
+ }
268
+ try {
269
+ // Binary response: download to file
270
+ if (endpoint.isBinaryResponse) {
271
+ if (!flags.file) {
272
+ this.error(`Endpoint returns a binary file. Specify the output path with -f / --file (e.g. -f report.xlsx).`);
273
+ }
274
+ const binResponse = await apiRequest(endpoint.method, apiPath, {
275
+ params: Object.keys(queryParams).length > 0 ? queryParams : undefined,
276
+ data,
277
+ contextName: flags.context,
278
+ binary: true,
279
+ });
280
+ const fsModule = await import('node:fs');
281
+ const binData = binResponse.data;
282
+ const buffer = Buffer.isBuffer(binData)
283
+ ? binData
284
+ : Buffer.from(binData);
285
+ fsModule.writeFileSync(flags.file, buffer);
286
+ this.log(`Saved ${buffer.length} bytes to ${flags.file}`);
287
+ return;
288
+ }
289
+ const response = await apiRequest(endpoint.method, apiPath, {
290
+ params: Object.keys(queryParams).length > 0 ? queryParams : undefined,
291
+ data,
292
+ contextName: flags.context,
293
+ acceptAny: true,
294
+ });
295
+ // Check content-type for non-JSON responses (XML, text, etc.)
296
+ const contentType = (response.headers['content-type'] || '').toLowerCase();
297
+ if (contentType.includes('xml') || contentType.includes('text/')) {
298
+ // Output raw content for XML/text responses (CSV, plain, HTML, etc.)
299
+ this.log(String(response.data));
300
+ return;
301
+ }
302
+ // Parse JSON if response came as string (due to acceptAny)
303
+ let output = response.data;
304
+ if (typeof output === 'string') {
305
+ try {
306
+ output = JSON.parse(output);
307
+ }
308
+ catch { /* keep as string */ }
309
+ }
310
+ // Extract data array from paginated wrapper (e.g., { data: [...], total: 3 })
311
+ if (output && typeof output === 'object' && !Array.isArray(output) && 'data' in output && Array.isArray(output.data)) {
312
+ output = output.data;
313
+ }
314
+ // For table/csv on non-array responses, auto-extract the primary array
315
+ // e.g., { payments: [...], total: 3 } → extract payments array
316
+ if ((flags.table || flags.output === 'table' || flags.csv || flags.output === 'csv')
317
+ && output && typeof output === 'object' && !Array.isArray(output)) {
318
+ const obj = output;
319
+ const arrayKeys = Object.keys(obj).filter(k => Array.isArray(obj[k]));
320
+ if (arrayKeys.length === 1) {
321
+ output = obj[arrayKeys[0]];
322
+ }
323
+ }
324
+ // Filter fields if --fields flag is provided
325
+ if (flags.fields) {
326
+ const fieldList = flags.fields.split(',').map(f => f.trim());
327
+ output = this.filterFields(output, fieldList);
328
+ }
329
+ // Sanitize output if requested
330
+ if (flags.sanitize) {
331
+ output = this.sanitizeOutput(output);
332
+ }
333
+ const fieldList = flags.fields?.split(',').map(f => f.trim());
334
+ if (flags.csv || flags.output === 'csv')
335
+ this.printCsv(output, fieldList);
336
+ else if (flags.table || flags.output === 'table')
337
+ this.printTable(output, fieldList);
338
+ else
339
+ this.log(JSON.stringify(output, null, 2));
340
+ }
341
+ catch (error) {
342
+ if (error instanceof ApiError) {
343
+ if (error.status === 404)
344
+ this.error(error.message);
345
+ this.error(`API Error (${error.status}): ${error.message}`);
346
+ }
347
+ throw error;
348
+ }
349
+ }
350
+ async runImport(flags) {
351
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
352
+ if (!context)
353
+ this.error('No context configured. Run: aderis auth login --new');
354
+ if (!context.tokens)
355
+ this.error('Not logged in. Run: aderis auth login');
356
+ // Get data from file, --data, or --set flags
357
+ let items = [];
358
+ if (flags.file) {
359
+ const fsModule = await import('node:fs');
360
+ try {
361
+ const content = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
362
+ items = Array.isArray(content) ? content : [content];
363
+ }
364
+ catch {
365
+ this.error(`Failed to read file: ${flags.file}`);
366
+ }
367
+ }
368
+ else if (flags.data) {
369
+ try {
370
+ const content = JSON.parse(flags.data);
371
+ items = Array.isArray(content) ? content : [content];
372
+ }
373
+ catch {
374
+ this.error('Invalid JSON in --data');
375
+ }
376
+ }
377
+ else if (flags.set && flags.set.length > 0) {
378
+ const item = {};
379
+ const arrayFields = new Set(ENDPOINTS['create']?.bodyArrayFields ?? []);
380
+ for (const pair of flags.set) {
381
+ const eqIndex = pair.indexOf('=');
382
+ if (eqIndex === -1)
383
+ this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
384
+ const key = pair.slice(0, eqIndex);
385
+ let value = pair.slice(eqIndex + 1);
386
+ try {
387
+ value = JSON.parse(value);
388
+ }
389
+ catch { /* keep as string */ }
390
+ const isArrayField = !key.includes('.') && arrayFields.has(key);
391
+ if (isArrayField && !Array.isArray(value)) {
392
+ if (typeof value === 'string') {
393
+ value = value.split(',').map(v => v.trim()).filter(v => v.length > 0);
394
+ }
395
+ else if (value !== undefined && value !== null) {
396
+ value = [value];
397
+ }
398
+ }
399
+ const keys = key.split('.');
400
+ if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
401
+ this.error(`Invalid --set key: ${key}`);
402
+ }
403
+ let obj = item;
404
+ for (let i = 0; i < keys.length - 1; i++) {
405
+ if (!(keys[i] in obj))
406
+ obj[keys[i]] = {};
407
+ obj = obj[keys[i]];
408
+ }
409
+ obj[keys[keys.length - 1]] = value;
410
+ }
411
+ items = [item];
412
+ }
413
+ else {
414
+ this.error('Import requires --file, --data, or --set flags');
415
+ }
416
+ const createEndpoint = ENDPOINTS['create'];
417
+ const updateEndpoint = ENDPOINTS['update'];
418
+ if (!createEndpoint || !updateEndpoint) {
419
+ this.error('Import requires both create and update endpoints');
420
+ }
421
+ // Helper to extract identifier from item (id, code, or xxxCode)
422
+ const getItemIdentifier = (item) => {
423
+ if (item.id)
424
+ return String(item.id);
425
+ if (item.code)
426
+ return String(item.code);
427
+ // Look for xxxCode fields (e.g., ledgerCode, accountCode)
428
+ for (const key of Object.keys(item)) {
429
+ if (key.endsWith('Code') && item[key])
430
+ return String(item[key]);
431
+ }
432
+ // Look for name as fallback
433
+ if (item.name)
434
+ return String(item.name).slice(0, 30);
435
+ return '';
436
+ };
437
+ const results = [];
438
+ // Stream output row-by-row so progress is visible during long imports.
439
+ // Pre-compute the identifier column width from the input items so the
440
+ // table stays aligned without buffering all rows.
441
+ // When stdout is piped (IDE terminals, tee, CI), Node switches to async-buffered
442
+ // mode and rows accumulate in the pipe buffer until it fills. Force blocking
443
+ // mode so each \n-terminated write flushes immediately.
444
+ const stdoutHandle = process.stdout._handle;
445
+ if (stdoutHandle?.setBlocking)
446
+ stdoutHandle.setBlocking(true);
447
+ const outputFormat = flags.output || 'table';
448
+ const useCsv = outputFormat === 'csv' || Boolean(flags.csv);
449
+ const useJson = outputFormat === 'json';
450
+ const statusWidth = 8;
451
+ const identifierWidth = Math.max(10, ...items.map(i => getItemIdentifier(i).length));
452
+ if (useCsv) {
453
+ this.log('status,identifier,id,error');
454
+ }
455
+ else if (!useJson) {
456
+ this.log(`${'status'.padEnd(statusWidth)} ${'identifier'.padEnd(identifierWidth)} error`);
457
+ this.log(`${'-'.repeat(statusWidth)} ${'-'.repeat(identifierWidth)} ${'-'.repeat(50)}`);
458
+ }
459
+ const emitRow = (r) => {
460
+ if (useJson)
461
+ return;
462
+ if (useCsv) {
463
+ const err = (r.error || '').replace(/"/g, '""');
464
+ this.log(`${r.status},${r.identifier || ''},${r.id || ''},"${err}"`);
465
+ }
466
+ else {
467
+ this.log(`${r.status.padEnd(statusWidth)} ${(r.identifier || '').padEnd(identifierWidth)} ${r.error || ''}`);
468
+ }
469
+ };
470
+ // Server-managed fields the API rejects in create/update bodies. Stripped
471
+ // before every request so re-importing a previously-exported payload Just Works.
472
+ const STRIP_FIELDS = new Set(['id', '_type', 'tenantId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy']);
473
+ const stripServerFields = (item) => {
474
+ const out = {};
475
+ for (const [k, v] of Object.entries(item)) {
476
+ if (!STRIP_FIELDS.has(k))
477
+ out[k] = v;
478
+ }
479
+ return out;
480
+ };
481
+ const processItem = async (item) => {
482
+ const identifier = getItemIdentifier(item);
483
+ const body = stripServerFields(item);
484
+ // If the payload carries an id (e.g. re-importing an export), PATCH directly.
485
+ // Fall through to POST only on 404 (so a missing record still gets created).
486
+ const itemId = typeof item.id === 'string' ? item.id : undefined;
487
+ if (itemId) {
488
+ try {
489
+ const updatePath = updateEndpoint.path.replace('{id}', itemId);
490
+ await apiRequest('PATCH', updatePath, {
491
+ data: body,
492
+ contextName: flags.context,
493
+ });
494
+ return { status: 'updated', id: itemId, identifier };
495
+ }
496
+ catch (error) {
497
+ if (!(error instanceof ApiError && error.status === 404)) {
498
+ const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
499
+ return { status: 'error', id: itemId, identifier, error: msg };
500
+ }
501
+ // 404 → record gone, try create below
502
+ }
503
+ }
504
+ try {
505
+ const response = await apiRequest('POST', createEndpoint.path, {
506
+ data: body,
507
+ contextName: flags.context,
508
+ });
509
+ const id = response.data?.id;
510
+ return { status: 'created', id: id ? String(id) : undefined, identifier };
511
+ }
512
+ catch (error) {
513
+ if (error instanceof ApiError && error.status === 409) {
514
+ const errorData = error.data;
515
+ const existingId = errorData?.existingId;
516
+ if (existingId) {
517
+ try {
518
+ const updatePath = updateEndpoint.path.replace('{id}', existingId);
519
+ await apiRequest('PATCH', updatePath, {
520
+ data: body,
521
+ contextName: flags.context,
522
+ });
523
+ return { status: 'updated', id: existingId, identifier };
524
+ }
525
+ catch (updateError) {
526
+ const msg = updateError instanceof ApiError ? updateError.message : String(updateError);
527
+ return { status: 'error', id: existingId, identifier, error: `Update failed: ${msg}` };
528
+ }
529
+ }
530
+ return { status: 'error', identifier, error: 'Conflict but no existingId returned' };
531
+ }
532
+ const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
533
+ return { status: 'error', identifier, error: msg };
534
+ }
535
+ };
536
+ // Worker pool: keep N requests in flight at all times. Rows are emitted as
537
+ // each request resolves (so output order may differ from input order). The
538
+ // summary at the end remains accurate regardless.
539
+ const concurrency = 4;
540
+ const queue = [...items];
541
+ await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
542
+ for (;;) {
543
+ const item = queue.shift();
544
+ if (!item)
545
+ return;
546
+ const r = await processItem(item);
547
+ results.push(r);
548
+ emitRow(r);
549
+ }
550
+ }));
551
+ // Summary counts
552
+ const created = results.filter(r => r.status === 'created').length;
553
+ const updated = results.filter(r => r.status === 'updated').length;
554
+ const errors = results.filter(r => r.status === 'error');
555
+ if (useJson) {
556
+ this.log(JSON.stringify(results, null, 2));
557
+ }
558
+ // Always show summary at the end
559
+ this.log('');
560
+ this.log(`Summary: ${created} created, ${updated} updated, ${errors.length} failed`);
561
+ }
562
+ async runExport(flags) {
563
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
564
+ if (!context)
565
+ this.error('No context configured. Run: aderis auth login --new');
566
+ if (!context.tokens)
567
+ this.error('Not logged in. Run: aderis auth login');
568
+ const listEndpoint = ENDPOINTS['list'];
569
+ if (!listEndpoint)
570
+ this.error('Export requires a list endpoint');
571
+ const allItems = [];
572
+ let page = 1;
573
+ const limit = 100;
574
+ let hasMore = true;
575
+ // Build base query params
576
+ const baseParams = {};
577
+ if (flags.search)
578
+ baseParams.search = flags.search;
579
+ if (flags['sort-by'])
580
+ baseParams.sortBy = flags['sort-by'];
581
+ if (flags.include)
582
+ baseParams.include = flags.include;
583
+ if (flags.query) {
584
+ try {
585
+ Object.assign(baseParams, JSON.parse(flags.query));
586
+ }
587
+ catch {
588
+ this.error('Invalid JSON in --query');
589
+ }
590
+ }
591
+ // Parse --filter flags (auto-prepend $eq: if no operator specified)
592
+ if (flags.filter && flags.filter.length > 0) {
593
+ for (const f of flags.filter) {
594
+ const eqIndex = f.indexOf('=');
595
+ if (eqIndex === -1)
596
+ this.error(`Invalid --filter format: ${f}. Use: --filter key=value`);
597
+ const key = f.slice(0, eqIndex);
598
+ const value = this.parseFilterValue(f.slice(eqIndex + 1));
599
+ const filterKey = `filter.${key}`;
600
+ if (filterKey in baseParams) {
601
+ const existing = baseParams[filterKey];
602
+ baseParams[filterKey] = Array.isArray(existing) ? [...existing, value] : [existing, value];
603
+ }
604
+ else {
605
+ baseParams[filterKey] = value;
606
+ }
607
+ }
608
+ }
609
+ // Fetch all pages
610
+ process.stderr.write('Exporting...');
611
+ while (hasMore) {
612
+ const params = { ...baseParams, page, limit };
613
+ const response = await apiRequest('GET', listEndpoint.path, {
614
+ params,
615
+ contextName: flags.context,
616
+ });
617
+ let items = [];
618
+ const data = response.data;
619
+ // Handle paginated response format
620
+ if (data && typeof data === 'object' && 'data' in data && Array.isArray(data.data)) {
621
+ items = data.data;
622
+ }
623
+ else if (Array.isArray(response.data)) {
624
+ items = response.data;
625
+ }
626
+ allItems.push(...items);
627
+ process.stderr.write(` ${allItems.length}`);
628
+ // Check if there are more pages
629
+ if (items.length < limit) {
630
+ hasMore = false;
631
+ }
632
+ else {
633
+ page++;
634
+ }
635
+ }
636
+ process.stderr.write(' done\n');
637
+ // Filter fields if specified
638
+ let output = allItems;
639
+ if (flags.fields) {
640
+ const fieldList = flags.fields.split(',').map(f => f.trim());
641
+ output = this.filterFields(allItems, fieldList);
642
+ }
643
+ // Sanitize output if requested
644
+ if (flags.sanitize) {
645
+ output = this.sanitizeOutput(output);
646
+ }
647
+ // Output in requested format
648
+ const fieldList = flags.fields ? flags.fields.split(',').map(f => f.trim()) : undefined;
649
+ if (flags.csv || flags.output === 'csv') {
650
+ this.printCsv(output, fieldList);
651
+ }
652
+ else {
653
+ this.log(JSON.stringify(output, null, 2));
654
+ }
655
+ }
656
+ async runCamt053Import(flags) {
657
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
658
+ if (!context)
659
+ this.error('No context configured. Run: aderis auth login --new');
660
+ if (!context.tokens)
661
+ this.error('Not logged in. Run: aderis auth login');
662
+ if (!flags.file) {
663
+ this.error('CAMT.053 import requires --file (-f) flag with path to XML file');
664
+ }
665
+ const fsModule = await import('node:fs');
666
+ let xmlContent;
667
+ try {
668
+ xmlContent = fsModule.readFileSync(flags.file, 'utf-8');
669
+ }
670
+ catch {
671
+ this.error(`Failed to read file: ${flags.file}`);
672
+ }
673
+ const endpoint = ENDPOINTS['import-camt053'];
674
+ try {
675
+ const response = await apiRequest(endpoint.method, endpoint.path, {
676
+ data: xmlContent,
677
+ contextName: flags.context,
678
+ contentType: 'application/xml',
679
+ });
680
+ // Extract transactions array and counts from response
681
+ let transactions = [];
682
+ let imported = 0;
683
+ let skipped = 0;
684
+ if (response.data && typeof response.data === 'object') {
685
+ const data = response.data;
686
+ if ('data' in data && Array.isArray(data.data)) {
687
+ transactions = data.data;
688
+ }
689
+ else if ('transactions' in data && Array.isArray(data.transactions)) {
690
+ transactions = data.transactions;
691
+ }
692
+ else if (Array.isArray(response.data)) {
693
+ transactions = response.data;
694
+ }
695
+ if (typeof data.imported === 'number')
696
+ imported = data.imported;
697
+ if (typeof data.skipped === 'number')
698
+ skipped = data.skipped;
699
+ }
700
+ else if (Array.isArray(response.data)) {
701
+ transactions = response.data;
702
+ }
703
+ if (imported === 0 && skipped === 0 && transactions.length > 0) {
704
+ for (const tx of transactions) {
705
+ const t = tx;
706
+ if (t.status === 'skipped' || t.skipped === true) {
707
+ skipped++;
708
+ }
709
+ else {
710
+ imported++;
711
+ }
712
+ }
713
+ if (imported === 0 && skipped === 0) {
714
+ imported = transactions.length;
715
+ }
716
+ }
717
+ let output = transactions;
718
+ if (flags.sanitize) {
719
+ output = this.sanitizeOutput(transactions);
720
+ }
721
+ const fieldList = flags.fields ? flags.fields.split(',').map(f => f.trim()) : undefined;
722
+ if (flags.csv || flags.output === 'csv') {
723
+ this.printCsv(output, fieldList);
724
+ }
725
+ else if (flags.table || flags.output === 'table') {
726
+ this.printTable(output, fieldList);
727
+ }
728
+ else {
729
+ this.log(JSON.stringify(output, null, 2));
730
+ }
731
+ this.log('');
732
+ this.log(`Summary: ${imported} imported, ${skipped} skipped`);
733
+ }
734
+ catch (error) {
735
+ if (error instanceof ApiError) {
736
+ if (error.status === 404)
737
+ this.error(error.message);
738
+ this.error(`API Error (${error.status}): ${error.message}`);
739
+ }
740
+ throw error;
741
+ }
742
+ }
743
+ async runNestedImport(suffix, parentId, flags) {
744
+ if (!parentId) {
745
+ this.error(`Missing required argument: id. Usage: aderis schedules import-${suffix} <parent-id> --file data.json`);
746
+ }
747
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
748
+ if (!context)
749
+ this.error('No context configured. Run: aderis auth login --new');
750
+ if (!context.tokens)
751
+ this.error('Not logged in. Run: aderis auth login');
752
+ // Get data from file, --data, or --set flags
753
+ let items = [];
754
+ if (flags.file) {
755
+ const fsModule = await import('node:fs');
756
+ try {
757
+ const content = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
758
+ items = Array.isArray(content) ? content : [content];
759
+ }
760
+ catch {
761
+ this.error(`Failed to read file: ${flags.file}`);
762
+ }
763
+ }
764
+ else if (flags.data) {
765
+ try {
766
+ const content = JSON.parse(flags.data);
767
+ items = Array.isArray(content) ? content : [content];
768
+ }
769
+ catch {
770
+ this.error('Invalid JSON in --data');
771
+ }
772
+ }
773
+ else if (flags.set && flags.set.length > 0) {
774
+ const item = {};
775
+ const arrayFields = new Set(ENDPOINTS[`create-${suffix}`]?.bodyArrayFields ?? []);
776
+ for (const pair of flags.set) {
777
+ const eqIndex = pair.indexOf('=');
778
+ if (eqIndex === -1)
779
+ this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
780
+ const key = pair.slice(0, eqIndex);
781
+ let value = pair.slice(eqIndex + 1);
782
+ try {
783
+ value = JSON.parse(value);
784
+ }
785
+ catch { /* keep as string */ }
786
+ const isArrayField = !key.includes('.') && arrayFields.has(key);
787
+ if (isArrayField && !Array.isArray(value)) {
788
+ if (typeof value === 'string') {
789
+ value = value.split(',').map(v => v.trim()).filter(v => v.length > 0);
790
+ }
791
+ else if (value !== undefined && value !== null) {
792
+ value = [value];
793
+ }
794
+ }
795
+ const keys = key.split('.');
796
+ if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
797
+ this.error(`Invalid --set key: ${key}`);
798
+ }
799
+ let obj = item;
800
+ for (let i = 0; i < keys.length - 1; i++) {
801
+ if (!(keys[i] in obj))
802
+ obj[keys[i]] = {};
803
+ obj = obj[keys[i]];
804
+ }
805
+ obj[keys[keys.length - 1]] = value;
806
+ }
807
+ items = [item];
808
+ }
809
+ else {
810
+ this.error(`Import requires --file, --data, or --set flags`);
811
+ }
812
+ const createEndpoint = ENDPOINTS[`create-${suffix}`];
813
+ const updateEndpoint = ENDPOINTS[`update-${suffix}`];
814
+ if (!createEndpoint || !updateEndpoint) {
815
+ this.error(`Import requires both create-${suffix} and update-${suffix} endpoints`);
816
+ }
817
+ // Build the base path with parent ID (first path param)
818
+ const firstParam = createEndpoint.pathParams[0];
819
+ const basePath = createEndpoint.path.replace(`{${firstParam}}`, parentId);
820
+ // Helper to extract identifier from item
821
+ const getItemIdentifier = (item) => {
822
+ if (item.id)
823
+ return String(item.id);
824
+ if (item.itemId)
825
+ return String(item.itemId);
826
+ if (item.code)
827
+ return String(item.code);
828
+ for (const key of Object.keys(item)) {
829
+ if (key.endsWith('Id') && item[key])
830
+ return String(item[key]);
831
+ if (key.endsWith('Code') && item[key])
832
+ return String(item[key]);
833
+ }
834
+ return '';
835
+ };
836
+ const results = [];
837
+ const stdoutHandle = process.stdout._handle;
838
+ if (stdoutHandle?.setBlocking)
839
+ stdoutHandle.setBlocking(true);
840
+ const outputFormat = flags.output || 'table';
841
+ const useCsv = outputFormat === 'csv' || Boolean(flags.csv);
842
+ const useJson = outputFormat === 'json';
843
+ const statusWidth = 8;
844
+ const identifierWidth = Math.max(10, ...items.map(i => getItemIdentifier(i).length));
845
+ if (useCsv) {
846
+ this.log('status,identifier,id,error');
847
+ }
848
+ else if (!useJson) {
849
+ this.log(`${'status'.padEnd(statusWidth)} ${'identifier'.padEnd(identifierWidth)} error`);
850
+ this.log(`${'-'.repeat(statusWidth)} ${'-'.repeat(identifierWidth)} ${'-'.repeat(50)}`);
851
+ }
852
+ const emitRow = (r) => {
853
+ if (useJson)
854
+ return;
855
+ if (useCsv) {
856
+ const err = (r.error || '').replace(/"/g, '""');
857
+ this.log(`${r.status},${r.identifier || ''},${r.id || ''},"${err}"`);
858
+ }
859
+ else {
860
+ this.log(`${r.status.padEnd(statusWidth)} ${(r.identifier || '').padEnd(identifierWidth)} ${r.error || ''}`);
861
+ }
862
+ };
863
+ const STRIP_FIELDS = new Set(['id', '_type', 'tenantId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy']);
864
+ const stripServerFields = (item) => {
865
+ const out = {};
866
+ for (const [k, v] of Object.entries(item)) {
867
+ if (!STRIP_FIELDS.has(k))
868
+ out[k] = v;
869
+ }
870
+ return out;
871
+ };
872
+ const buildUpdatePath = (existingId) => {
873
+ const firstUpdateParam = updateEndpoint.pathParams[0];
874
+ const nestedIdParam = updateEndpoint.pathParams.find((p, i) => i > 0);
875
+ let updatePath = updateEndpoint.path.replace(`{${firstUpdateParam}}`, parentId);
876
+ if (nestedIdParam) {
877
+ updatePath = updatePath.replace(`{${nestedIdParam}}`, existingId);
878
+ }
879
+ return updatePath;
880
+ };
881
+ const processItem = async (item) => {
882
+ const identifier = getItemIdentifier(item);
883
+ const body = stripServerFields(item);
884
+ const itemId = typeof item.id === 'string' ? item.id : undefined;
885
+ if (itemId) {
886
+ try {
887
+ await apiRequest('PATCH', buildUpdatePath(itemId), {
888
+ data: body,
889
+ contextName: flags.context,
890
+ });
891
+ return { status: 'updated', id: itemId, identifier };
892
+ }
893
+ catch (error) {
894
+ if (!(error instanceof ApiError && error.status === 404)) {
895
+ const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
896
+ return { status: 'error', id: itemId, identifier, error: msg };
897
+ }
898
+ // 404 → fall through and try create
899
+ }
900
+ }
901
+ try {
902
+ const response = await apiRequest('POST', basePath, {
903
+ data: body,
904
+ contextName: flags.context,
905
+ });
906
+ const id = response.data?.id;
907
+ return { status: 'created', id: id ? String(id) : undefined, identifier };
908
+ }
909
+ catch (error) {
910
+ if (error instanceof ApiError && error.status === 409) {
911
+ const errorData = error.data;
912
+ const existingId = errorData?.existingId || item.id;
913
+ if (existingId) {
914
+ try {
915
+ await apiRequest('PATCH', buildUpdatePath(existingId), {
916
+ data: body,
917
+ contextName: flags.context,
918
+ });
919
+ return { status: 'updated', id: existingId, identifier };
920
+ }
921
+ catch (updateError) {
922
+ const msg = updateError instanceof ApiError ? updateError.message : String(updateError);
923
+ return { status: 'error', id: existingId, identifier, error: `Update failed: ${msg}` };
924
+ }
925
+ }
926
+ return { status: 'error', identifier, error: 'Conflict but no existingId returned' };
927
+ }
928
+ const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
929
+ return { status: 'error', identifier, error: msg };
930
+ }
931
+ };
932
+ // Worker pool: 4 requests in flight at a time. Rows are emitted as each
933
+ // request resolves so output order may differ from input order.
934
+ const concurrency = 4;
935
+ const queue = [...items];
936
+ await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
937
+ for (;;) {
938
+ const item = queue.shift();
939
+ if (!item)
940
+ return;
941
+ const r = await processItem(item);
942
+ results.push(r);
943
+ emitRow(r);
944
+ }
945
+ }));
946
+ // Summary counts
947
+ const created = results.filter(r => r.status === 'created').length;
948
+ const updated = results.filter(r => r.status === 'updated').length;
949
+ const errors = results.filter(r => r.status === 'error');
950
+ if (useJson) {
951
+ this.log(JSON.stringify(results, null, 2));
952
+ }
953
+ this.log('');
954
+ this.log(`Summary: ${created} created, ${updated} updated, ${errors.length} failed`);
955
+ }
956
+ parseFilterValue(value) {
957
+ // Recognises the nestjs-paginate operator set (with or without the leading $)
958
+ // and recursively unwraps chained operators like 'not:null' -> '$not:$null'
959
+ // or 'not:like:John' -> '$not:$like:John'. Falls back to '$eq:<value>' when
960
+ // no operator prefix is present.
961
+ const opRe = /^\$?(and|or|not|eq|gt|gte|in|null|lt|lte|btw|ne|ilike|like|sw|contains)(?::|$)/;
962
+ const m = value.match(opRe);
963
+ if (!m)
964
+ return `\$eq:${value}`;
965
+ const op = m[1];
966
+ const rest = value.slice(m[0].length);
967
+ if (rest === '')
968
+ return `\$${op}`;
969
+ return opRe.test(rest) ? `\$${op}:${this.parseFilterValue(rest)}` : `\$${op}:${rest}`;
970
+ }
971
+ filterFields(data, fields) {
972
+ const isUnsafeKey = (k) => k === '__proto__' || k === 'constructor' || k === 'prototype';
973
+ const pick = (obj, keys) => {
974
+ // Group keys by their first segment so sibling sub-paths
975
+ // (e.g. 'items.amount' + 'items._type') resolve in one recursive pass
976
+ // and don't clobber each other on merge.
977
+ const directKeys = new Set();
978
+ const nestedKeys = new Map();
979
+ for (const key of keys) {
980
+ if (key.split('.').some(isUnsafeKey))
981
+ continue;
982
+ if (key.includes('.')) {
983
+ const [first, ...rest] = key.split('.');
984
+ if (isUnsafeKey(first))
985
+ continue;
986
+ const list = nestedKeys.get(first);
987
+ if (list) {
988
+ list.push(rest.join('.'));
989
+ }
990
+ else {
991
+ nestedKeys.set(first, [rest.join('.')]);
992
+ }
993
+ }
994
+ else {
995
+ directKeys.add(key);
996
+ }
997
+ }
998
+ const result = {};
999
+ for (const key of directKeys) {
1000
+ if (key in obj)
1001
+ result[key] = obj[key];
1002
+ }
1003
+ for (const [first, restKeys] of nestedKeys) {
1004
+ const val = obj[first];
1005
+ if (!val || typeof val !== 'object')
1006
+ continue;
1007
+ if (Array.isArray(val)) {
1008
+ result[first] = val.map(item => pick(item, restKeys));
1009
+ }
1010
+ else {
1011
+ result[first] = pick(val, restKeys);
1012
+ }
1013
+ }
1014
+ return result;
1015
+ };
1016
+ if (Array.isArray(data)) {
1017
+ return data.map(item => pick(item, fields));
1018
+ }
1019
+ return pick(data, fields);
1020
+ }
1021
+ sanitizeOutput(data) {
1022
+ const auditFields = ['_type', 'tenantId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy'];
1023
+ const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1024
+ const sanitize = (obj, parentUuids = new Set()) => {
1025
+ if (obj === null || obj === undefined)
1026
+ return undefined;
1027
+ if (Array.isArray(obj)) {
1028
+ const result = obj.map(item => sanitize(item, new Set(parentUuids))).filter(item => item !== undefined);
1029
+ return result.length > 0 ? result : undefined;
1030
+ }
1031
+ if (typeof obj === 'object') {
1032
+ const input = obj;
1033
+ // Use a Map to avoid any prototype-pollution risk on the result object
1034
+ const collected = new Map();
1035
+ // Collect UUIDs from this level to pass to children
1036
+ const currentUuids = new Set(parentUuids);
1037
+ for (const [, value] of Object.entries(input)) {
1038
+ if (typeof value === 'string' && uuidRegex.test(value)) {
1039
+ currentUuids.add(value);
1040
+ }
1041
+ }
1042
+ for (const [key, value] of Object.entries(input)) {
1043
+ // Skip prototype-pollution keys
1044
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype')
1045
+ continue;
1046
+ // Skip audit fields
1047
+ if (auditFields.includes(key))
1048
+ continue;
1049
+ // Skip null/undefined values
1050
+ if (value === null || value === undefined)
1051
+ continue;
1052
+ // Skip UUID values that exist in parent
1053
+ if (typeof value === 'string' && uuidRegex.test(value) && parentUuids.has(value))
1054
+ continue;
1055
+ // Recursively sanitize nested objects/arrays
1056
+ const sanitized = sanitize(value, currentUuids);
1057
+ if (sanitized !== undefined) {
1058
+ collected.set(key, sanitized);
1059
+ }
1060
+ }
1061
+ if (collected.size === 0)
1062
+ return undefined;
1063
+ return Object.fromEntries(collected);
1064
+ }
1065
+ return obj;
1066
+ };
1067
+ return sanitize(data) ?? (Array.isArray(data) ? [] : {});
1068
+ }
1069
+ getColumns(data, fields, flatten = false) {
1070
+ const items = Array.isArray(data) ? data : [data];
1071
+ if (items.length === 0)
1072
+ return { cols: [], items: [] };
1073
+ const first = items[0];
1074
+ const hiddenFields = ['tenantId', '_type'];
1075
+ if (fields) {
1076
+ return { cols: fields, items: items };
1077
+ }
1078
+ // Recursively collect all column paths, flattening objects (but not arrays)
1079
+ const collectPaths = (obj, prefix = '') => {
1080
+ const paths = [];
1081
+ for (const key of Object.keys(obj)) {
1082
+ const fullKey = prefix ? `${prefix}.${key}` : key;
1083
+ if (hiddenFields.includes(key))
1084
+ continue;
1085
+ const val = obj[key];
1086
+ if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
1087
+ // Flatten nested objects (but not arrays)
1088
+ if (flatten) {
1089
+ paths.push(...collectPaths(val, fullKey));
1090
+ }
1091
+ // Skip objects when not flattening
1092
+ }
1093
+ else if (!Array.isArray(val)) {
1094
+ // Include primitives (and null)
1095
+ paths.push(fullKey);
1096
+ }
1097
+ // Skip arrays entirely
1098
+ }
1099
+ return paths;
1100
+ };
1101
+ // Scan multiple items to discover all columns (handles fields absent/null in first item)
1102
+ const cols = collectPaths(first);
1103
+ const colSet = new Set(cols);
1104
+ const scanCount = Math.min(items.length, 50);
1105
+ for (let i = 1; i < scanCount; i++) {
1106
+ for (const p of collectPaths(items[i])) {
1107
+ if (!colSet.has(p)) {
1108
+ cols.push(p);
1109
+ colSet.add(p);
1110
+ }
1111
+ }
1112
+ }
1113
+ return { cols: flatten ? cols : cols.slice(0, 8), items: items };
1114
+ }
1115
+ getValue(row, col) {
1116
+ if (!col.includes('.'))
1117
+ return String(row[col] ?? '');
1118
+ const parts = col.split('.');
1119
+ // Walk the dot-path; descending through an array branches into every
1120
+ // element so leaf values get collected from each one. Multiple leaves are
1121
+ // joined with ';' (e.g. dunningReminders.id -> "uuid1;uuid2").
1122
+ const walk = (o, idx) => {
1123
+ if (idx >= parts.length)
1124
+ return [o];
1125
+ if (o == null)
1126
+ return [];
1127
+ if (Array.isArray(o))
1128
+ return o.flatMap(item => walk(item, idx));
1129
+ if (typeof o === 'object')
1130
+ return walk(o[parts[idx]], idx + 1);
1131
+ return [];
1132
+ };
1133
+ return walk(row, 0).filter(v => v !== undefined && v !== null).map(v => String(v)).join(';');
1134
+ }
1135
+ printTable(data, fields) {
1136
+ const { cols, items } = this.getColumns(data, fields);
1137
+ if (items.length === 0) {
1138
+ this.log('No results');
1139
+ return;
1140
+ }
1141
+ // Calculate column widths
1142
+ const widths = cols.map(c => c.length);
1143
+ for (const item of items) {
1144
+ cols.forEach((col, i) => {
1145
+ const val = this.getValue(item, col).slice(0, 40);
1146
+ widths[i] = Math.max(widths[i], val.length);
1147
+ });
1148
+ }
1149
+ // Print header
1150
+ const header = cols.map((c, i) => c.padEnd(widths[i])).join(' ');
1151
+ this.log(header);
1152
+ this.log(widths.map(w => '-'.repeat(w)).join(' '));
1153
+ // Print rows
1154
+ for (const item of items) {
1155
+ const row = cols.map((col, i) => {
1156
+ const val = this.getValue(item, col).slice(0, 40);
1157
+ return val.padEnd(widths[i]);
1158
+ }).join(' ');
1159
+ this.log(row);
1160
+ }
1161
+ }
1162
+ printCsv(data, fields) {
1163
+ const { cols, items } = this.getColumns(data, fields, true); // flatten=true for CSV
1164
+ if (items.length === 0) {
1165
+ this.log('No results');
1166
+ return;
1167
+ }
1168
+ const escape = (val) => {
1169
+ if (val.includes(',') || val.includes('"') || val.includes('\n')) {
1170
+ return '"' + val.replace(/"/g, '""') + '"';
1171
+ }
1172
+ return val;
1173
+ };
1174
+ // Print header
1175
+ this.log(cols.map(escape).join(','));
1176
+ // Print rows
1177
+ for (const item of items) {
1178
+ const row = cols.map(col => escape(this.getValue(item, col)));
1179
+ this.log(row.join(','));
1180
+ }
1181
+ }
1182
+ }