@aderis-erp/cli 1.0.12 → 1.0.14

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