@aderis-erp/cli 1.0.0

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