@aderis-erp/cli 1.0.4 → 1.0.8

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