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