@aderis-erp/cli 1.0.13 → 1.0.15

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