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