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