@aderis-erp/cli 1.0.15 → 1.0.17

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 (163) hide show
  1. package/README.md +30 -8
  2. package/dist/commands/access-groups.d.ts +0 -1
  3. package/dist/commands/access-groups.js +5 -61
  4. package/dist/commands/account-transaction-allocations.d.ts +0 -1
  5. package/dist/commands/account-transaction-allocations.js +5 -61
  6. package/dist/commands/account-transactions.d.ts +0 -1
  7. package/dist/commands/account-transactions.js +9 -63
  8. package/dist/commands/accounts.d.ts +0 -1
  9. package/dist/commands/accounts.js +5 -61
  10. package/dist/commands/agent-platform.d.ts +0 -1
  11. package/dist/commands/agent-platform.js +5 -61
  12. package/dist/commands/analytics.d.ts +0 -1
  13. package/dist/commands/analytics.js +5 -61
  14. package/dist/commands/api-keys.d.ts +39 -0
  15. package/dist/commands/api-keys.js +1117 -0
  16. package/dist/commands/audit-log.d.ts +0 -1
  17. package/dist/commands/audit-log.js +5 -61
  18. package/dist/commands/auth/login.d.ts +9 -0
  19. package/dist/commands/auth/login.js +73 -20
  20. package/dist/commands/auth/logout.d.ts +4 -0
  21. package/dist/commands/auth/logout.js +4 -0
  22. package/dist/commands/auth/status.js +26 -17
  23. package/dist/commands/auth/tenant.js +3 -6
  24. package/dist/commands/auth.d.ts +0 -1
  25. package/dist/commands/auth.js +5 -34
  26. package/dist/commands/bank-accounts.d.ts +0 -1
  27. package/dist/commands/bank-accounts.js +5 -61
  28. package/dist/commands/bank-integrations.d.ts +0 -1
  29. package/dist/commands/bank-integrations.js +5 -61
  30. package/dist/commands/business-partners.d.ts +1 -1
  31. package/dist/commands/business-partners.js +14 -63
  32. package/dist/commands/chat.d.ts +0 -1
  33. package/dist/commands/chat.js +5 -61
  34. package/dist/commands/config/add.d.ts +3 -0
  35. package/dist/commands/config/add.js +34 -16
  36. package/dist/commands/config/current.js +3 -0
  37. package/dist/commands/config/list.js +3 -0
  38. package/dist/commands/credit-card-accounts.d.ts +0 -1
  39. package/dist/commands/credit-card-accounts.js +5 -61
  40. package/dist/commands/delivery-notes.d.ts +0 -1
  41. package/dist/commands/delivery-notes.js +7 -63
  42. package/dist/commands/dunning-configs.d.ts +0 -1
  43. package/dist/commands/dunning-configs.js +5 -61
  44. package/dist/commands/dunning-reminders.d.ts +0 -1
  45. package/dist/commands/dunning-reminders.js +5 -61
  46. package/dist/commands/dunning-runs.d.ts +0 -1
  47. package/dist/commands/dunning-runs.js +5 -61
  48. package/dist/commands/email-transactions.d.ts +0 -1
  49. package/dist/commands/email-transactions.js +5 -61
  50. package/dist/commands/employees.d.ts +0 -1
  51. package/dist/commands/employees.js +5 -61
  52. package/dist/commands/entity-configurations.d.ts +0 -1
  53. package/dist/commands/entity-configurations.js +5 -61
  54. package/dist/commands/event-processor-mappings.d.ts +0 -1
  55. package/dist/commands/event-processor-mappings.js +5 -61
  56. package/dist/commands/files.d.ts +0 -1
  57. package/dist/commands/files.js +5 -61
  58. package/dist/commands/health.d.ts +0 -1
  59. package/dist/commands/health.js +5 -61
  60. package/dist/commands/inbox.d.ts +0 -1
  61. package/dist/commands/inbox.js +5 -61
  62. package/dist/commands/integrations.d.ts +0 -1
  63. package/dist/commands/integrations.js +5 -61
  64. package/dist/commands/item-categories.d.ts +0 -1
  65. package/dist/commands/item-categories.js +5 -61
  66. package/dist/commands/items.d.ts +0 -1
  67. package/dist/commands/items.js +5 -61
  68. package/dist/commands/journal-lines.d.ts +0 -1
  69. package/dist/commands/journal-lines.js +5 -61
  70. package/dist/commands/journals.d.ts +1 -1
  71. package/dist/commands/journals.js +9 -62
  72. package/dist/commands/ledgers.d.ts +0 -1
  73. package/dist/commands/ledgers.js +5 -61
  74. package/dist/commands/nango-integrations.d.ts +39 -0
  75. package/dist/commands/nango-integrations.js +1115 -0
  76. package/dist/commands/office-locations.d.ts +0 -1
  77. package/dist/commands/office-locations.js +5 -61
  78. package/dist/commands/payment-methods.d.ts +0 -1
  79. package/dist/commands/payment-methods.js +5 -61
  80. package/dist/commands/payment-runs.d.ts +0 -1
  81. package/dist/commands/payment-runs.js +5 -61
  82. package/dist/commands/payment-terms.d.ts +0 -1
  83. package/dist/commands/payment-terms.js +5 -61
  84. package/dist/commands/payments.d.ts +0 -1
  85. package/dist/commands/payments.js +5 -61
  86. package/dist/commands/price-lists.d.ts +0 -1
  87. package/dist/commands/price-lists.js +5 -61
  88. package/dist/commands/processor-mappings.d.ts +0 -1
  89. package/dist/commands/processor-mappings.js +5 -61
  90. package/dist/commands/processors.d.ts +0 -1
  91. package/dist/commands/processors.js +5 -61
  92. package/dist/commands/purchase-order-types.d.ts +0 -1
  93. package/dist/commands/purchase-order-types.js +5 -61
  94. package/dist/commands/purchase-orders.d.ts +0 -1
  95. package/dist/commands/purchase-orders.js +7 -63
  96. package/dist/commands/reports.d.ts +0 -1
  97. package/dist/commands/reports.js +6 -62
  98. package/dist/commands/salary-types.d.ts +0 -1
  99. package/dist/commands/salary-types.js +5 -61
  100. package/dist/commands/sales-invoices.d.ts +0 -1
  101. package/dist/commands/sales-invoices.js +12 -65
  102. package/dist/commands/sales-orders.d.ts +0 -1
  103. package/dist/commands/sales-orders.js +7 -63
  104. package/dist/commands/saved-views.d.ts +0 -1
  105. package/dist/commands/saved-views.js +5 -61
  106. package/dist/commands/scheduled-processor-mappings.d.ts +0 -1
  107. package/dist/commands/scheduled-processor-mappings.js +5 -61
  108. package/dist/commands/schedules.d.ts +0 -1
  109. package/dist/commands/schedules.js +5 -61
  110. package/dist/commands/switch.js +4 -4
  111. package/dist/commands/tag-configurations.d.ts +0 -1
  112. package/dist/commands/tag-configurations.js +9 -64
  113. package/dist/commands/tags.d.ts +0 -1
  114. package/dist/commands/tags.js +5 -61
  115. package/dist/commands/tax-codes.d.ts +0 -1
  116. package/dist/commands/tax-codes.js +5 -61
  117. package/dist/commands/tax-matrix.d.ts +0 -1
  118. package/dist/commands/tax-matrix.js +5 -61
  119. package/dist/commands/tenants.d.ts +0 -1
  120. package/dist/commands/tenants.js +7 -62
  121. package/dist/commands/text-templates.d.ts +0 -1
  122. package/dist/commands/text-templates.js +5 -61
  123. package/dist/commands/tools.d.ts +0 -1
  124. package/dist/commands/tools.js +5 -61
  125. package/dist/commands/vat-declarations.d.ts +1 -1
  126. package/dist/commands/vat-declarations.js +11 -62
  127. package/dist/commands/vendor-invoices.d.ts +0 -1
  128. package/dist/commands/vendor-invoices.js +10 -65
  129. package/dist/commands/webhooks.d.ts +0 -1
  130. package/dist/commands/webhooks.js +5 -61
  131. package/dist/commands/workflows.d.ts +0 -1
  132. package/dist/commands/workflows.js +5 -61
  133. package/dist/lib/api-client.js +3 -6
  134. package/dist/lib/auth/constants.d.ts +11 -0
  135. package/dist/lib/auth/constants.js +11 -0
  136. package/dist/lib/auth/errors.d.ts +17 -0
  137. package/dist/lib/auth/errors.js +22 -0
  138. package/dist/lib/auth/flow.d.ts +27 -0
  139. package/dist/lib/auth/flow.js +163 -0
  140. package/dist/lib/auth/guards.d.ts +5 -0
  141. package/dist/lib/auth/guards.js +14 -0
  142. package/dist/lib/auth/http.d.ts +16 -0
  143. package/dist/lib/auth/http.js +49 -0
  144. package/dist/lib/auth/index.d.ts +49 -0
  145. package/dist/lib/auth/index.js +217 -0
  146. package/dist/lib/auth/keycloak-provider.d.ts +75 -0
  147. package/dist/lib/auth/keycloak-provider.js +215 -0
  148. package/dist/lib/auth/pages.d.ts +25 -0
  149. package/dist/lib/auth/pages.js +123 -0
  150. package/dist/lib/auth/pkce.d.ts +11 -0
  151. package/dist/lib/auth/pkce.js +17 -0
  152. package/dist/lib/auth/tokens.d.ts +54 -0
  153. package/dist/lib/auth/tokens.js +104 -0
  154. package/dist/lib/auth/types.d.ts +57 -0
  155. package/dist/lib/auth/types.js +1 -0
  156. package/dist/lib/auth/validated-url.d.ts +6 -0
  157. package/dist/lib/auth/validated-url.js +53 -0
  158. package/dist/lib/config.d.ts +13 -3
  159. package/dist/lib/config.js +24 -19
  160. package/oclif.manifest.json +440 -71
  161. package/package.json +2 -1
  162. package/dist/lib/auth.d.ts +0 -43
  163. package/dist/lib/auth.js +0 -610
@@ -0,0 +1,1117 @@
1
+ import { Command, Args, Flags } from '@oclif/core';
2
+ import { apiRequest, ApiError, normalizeSortBy } from '../lib/api-client.js';
3
+ import { getCurrentContext, getContext, getBaseUrls, hasCredentials, missingCredentialsMessage } from '../lib/config.js';
4
+ // Add 'import' action if both create and update exist
5
+ const HAS_IMPORT = false;
6
+ const HAS_EXPORT = true;
7
+ const HAS_CAMT053 = false;
8
+ const NESTED_IMPORTS = [];
9
+ const SUBCOMMANDS = [...["list", "create", "delete"], ...(HAS_IMPORT ? ['import'] : []), ...(HAS_EXPORT ? ['export'] : []), ...NESTED_IMPORTS.map(n => `import-${n}`)];
10
+ const ENDPOINTS = {
11
+ 'list': { method: 'GET', path: '/v1/auth/api-keys', summary: 'List the tenant\'s API keys', pathParams: [], hasBody: false, isMultipart: false, isBinaryResponse: false, bodyArrayFields: [] },
12
+ 'create': { method: 'POST', path: '/v1/auth/api-keys', summary: 'Create an API key for the tenant', pathParams: [], hasBody: true, isMultipart: false, isBinaryResponse: false, bodyArrayFields: ['permissions'] },
13
+ 'delete': { method: 'DELETE', path: '/v1/auth/api-keys/{apiKeyId}', summary: 'Revoke an API key', pathParams: ['apiKeyId'], hasBody: false, isMultipart: false, isBinaryResponse: false, bodyArrayFields: [] },
14
+ };
15
+ export default class ApiKeys extends Command {
16
+ static description = 'Manage api keys';
17
+ static examples = [
18
+ '<%= config.bin %> api-keys list',
19
+ '<%= config.bin %> api-keys create --data \'{...}\'',
20
+ '<%= config.bin %> api-keys export --csv > api-keys.csv',
21
+ ];
22
+ static args = {
23
+ action: Args.string({ description: 'Action: ' + SUBCOMMANDS.join(', '), required: true }),
24
+ id: Args.string({ description: 'Resource ID (for get, update, delete operations)', required: false }),
25
+ };
26
+ static flags = {
27
+ context: Flags.string({ char: 'c', aliases: ['config'], env: 'ADERIS_CONTEXT', description: 'Context to use for this command, overriding the current context (alias: --config)' }),
28
+ output: Flags.string({ char: 'o', description: 'Output format (default: table for import, json for other commands)', options: ['json', 'table', 'csv'] }),
29
+ table: Flags.boolean({ char: 't', description: 'Output as table (shortcut for --output table)' }),
30
+ csv: Flags.boolean({ description: 'Output as CSV (shortcut for --output csv)' }),
31
+ data: Flags.string({ char: 'd', description: 'JSON data for request body' }),
32
+ file: Flags.string({ char: 'f', description: 'Read request body from file' }),
33
+ set: Flags.string({ char: 's', description: 'Set individual field (e.g. --set firstName=John)', multiple: true }),
34
+ page: Flags.string({ description: 'Page number' }),
35
+ limit: Flags.string({ description: 'Items per page' }),
36
+ include: Flags.string({ description: 'Relations to include' }),
37
+ search: Flags.string({ description: 'Search term' }),
38
+ 'sort-by': Flags.string({ description: 'Sort field(s), comma-separated. Direction (:ASC/:DESC) is optional; date-like fields default to DESC, others to ASC.' }),
39
+ filter: Flags.string({ description: 'Filter (e.g. --filter status=ACTIVE). Operators: in:A,B, like:%, gt:, lt:, null:', multiple: true }),
40
+ query: Flags.string({ description: 'Additional query params as JSON' }),
41
+ fields: Flags.string({ description: 'Comma-separated list of fields to return, applied by the API (e.g. --fields=id,name,status)' }),
42
+ sanitize: Flags.boolean({ description: 'Remove null values, audit fields, and duplicate UUIDs from output' }),
43
+ 'show-http-request': Flags.boolean({ description: 'Show HTTP request details (method, URL, body)' }),
44
+ };
45
+ async run() {
46
+ const { args, flags } = await this.parse(ApiKeys);
47
+ // Handle import action specially
48
+ if (args.action === 'import') {
49
+ if (!HAS_IMPORT)
50
+ this.error('Import not available for this resource');
51
+ await this.runImport(flags);
52
+ return;
53
+ }
54
+ // Handle export action specially
55
+ if (args.action === 'export') {
56
+ if (!HAS_EXPORT)
57
+ this.error('Export not available for this resource');
58
+ await this.runExport(flags);
59
+ return;
60
+ }
61
+ // Handle CAMT.053 import specially - sends raw XML
62
+ if (args.action === 'import-camt053') {
63
+ if (!HAS_CAMT053)
64
+ this.error('CAMT.053 import not available for this resource');
65
+ await this.runCamt053Import(flags);
66
+ return;
67
+ }
68
+ // Handle nested resource imports (e.g., import-prices)
69
+ if (args.action.startsWith('import-')) {
70
+ const suffix = args.action.replace('import-', '');
71
+ if (NESTED_IMPORTS.includes(suffix)) {
72
+ await this.runNestedImport(suffix, args.id, flags);
73
+ return;
74
+ }
75
+ }
76
+ const endpoint = ENDPOINTS[args.action];
77
+ if (!endpoint)
78
+ this.error(`Unknown action: ${args.action}. Available: ${SUBCOMMANDS.join(', ')}`);
79
+ let apiPath = endpoint.path;
80
+ for (let i = 0; i < endpoint.pathParams.length; i++) {
81
+ const param = endpoint.pathParams[i];
82
+ let value;
83
+ if (i === 0) {
84
+ // First path param always comes from positional argument
85
+ value = args.id;
86
+ if (!value)
87
+ this.error('Missing required argument: id. Usage: aderis api-keys <action> <id>');
88
+ }
89
+ else {
90
+ const flagName = param.replace(/\./g, '-').replace(/([A-Z])/g, '-$1').toLowerCase().replace(/^-/, '');
91
+ value = flags[flagName];
92
+ if (!value)
93
+ this.error(`Missing required parameter: --${flagName}`);
94
+ }
95
+ apiPath = apiPath.replace(`{${param}}`, String(value));
96
+ }
97
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
98
+ if (!context)
99
+ this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
100
+ if (!hasCredentials(context))
101
+ this.error(missingCredentialsMessage(context));
102
+ const queryParams = {};
103
+ if (flags.page)
104
+ queryParams.page = flags.page;
105
+ if (flags.limit)
106
+ queryParams.limit = flags.limit;
107
+ if (flags.include)
108
+ queryParams.include = flags.include;
109
+ if (flags.search)
110
+ queryParams.search = flags.search;
111
+ if (flags['sort-by'])
112
+ queryParams.sortBy = normalizeSortBy(flags['sort-by']);
113
+ if (flags.fields)
114
+ queryParams.fields = flags.fields;
115
+ if (flags.query) {
116
+ try {
117
+ Object.assign(queryParams, JSON.parse(flags.query));
118
+ }
119
+ catch {
120
+ this.error('Invalid JSON in --query');
121
+ }
122
+ }
123
+ // Parse --filter flags (e.g., --filter status=ACTIVE becomes filter.status=$eq:ACTIVE)
124
+ if (flags.filter && flags.filter.length > 0) {
125
+ for (const f of flags.filter) {
126
+ const eqIndex = f.indexOf('=');
127
+ if (eqIndex === -1)
128
+ this.error(`Invalid --filter format: ${f}. Use: --filter key=value`);
129
+ const key = f.slice(0, eqIndex);
130
+ const value = this.parseFilterValue(f.slice(eqIndex + 1));
131
+ const filterKey = `filter.${key}`;
132
+ if (filterKey in queryParams) {
133
+ // Multiple filters on same field: collect as array
134
+ const existing = queryParams[filterKey];
135
+ queryParams[filterKey] = Array.isArray(existing) ? [...existing, value] : [existing, value];
136
+ }
137
+ else {
138
+ queryParams[filterKey] = value;
139
+ }
140
+ }
141
+ }
142
+ let data;
143
+ if (endpoint.isMultipart) {
144
+ if (!flags.file)
145
+ this.error('Missing required --file flag for file upload');
146
+ const fsModule = await import('node:fs');
147
+ const pathModule = await import('node:path');
148
+ const FormDataLib = (await import('form-data')).default;
149
+ const form = new FormDataLib();
150
+ form.append('file', fsModule.createReadStream(flags.file), pathModule.basename(flags.file));
151
+ // Append --set fields as extra form fields (e.g. --set type=CREDIT_CARD_STATEMENT)
152
+ if (flags.set && flags.set.length > 0) {
153
+ for (const pair of flags.set) {
154
+ const eqIndex = pair.indexOf('=');
155
+ if (eqIndex === -1)
156
+ this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
157
+ form.append(pair.slice(0, eqIndex), pair.slice(eqIndex + 1));
158
+ }
159
+ }
160
+ data = form;
161
+ }
162
+ else if (endpoint.hasBody) {
163
+ // For binary-response endpoints, --file is the output path, not a JSON
164
+ // input file — skip the read-as-body branch.
165
+ if (flags.file && !endpoint.isBinaryResponse) {
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
+ // Sanitize output if requested
318
+ if (flags.sanitize) {
319
+ output = this.sanitizeOutput(output);
320
+ }
321
+ const fieldList = flags.fields?.split(',').map(f => f.trim());
322
+ if (flags.csv || flags.output === 'csv')
323
+ this.printCsv(output, fieldList);
324
+ else if (flags.table || flags.output === 'table')
325
+ this.printTable(output, fieldList);
326
+ else
327
+ this.log(JSON.stringify(output, null, 2));
328
+ }
329
+ catch (error) {
330
+ if (error instanceof ApiError) {
331
+ if (error.status === 404)
332
+ this.error(error.message);
333
+ this.error(`API Error (${error.status}): ${error.message}`);
334
+ }
335
+ throw error;
336
+ }
337
+ }
338
+ async runImport(flags) {
339
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
340
+ if (!context)
341
+ this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
342
+ if (!hasCredentials(context))
343
+ this.error(missingCredentialsMessage(context));
344
+ // Get data from file, --data, or --set flags
345
+ let items = [];
346
+ if (flags.file) {
347
+ const fsModule = await import('node:fs');
348
+ try {
349
+ const content = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
350
+ items = Array.isArray(content) ? content : [content];
351
+ }
352
+ catch {
353
+ this.error(`Failed to read file: ${flags.file}`);
354
+ }
355
+ }
356
+ else if (flags.data) {
357
+ try {
358
+ const content = JSON.parse(flags.data);
359
+ items = Array.isArray(content) ? content : [content];
360
+ }
361
+ catch {
362
+ this.error('Invalid JSON in --data');
363
+ }
364
+ }
365
+ else if (flags.set && flags.set.length > 0) {
366
+ const item = {};
367
+ const arrayFields = new Set(ENDPOINTS['create']?.bodyArrayFields ?? []);
368
+ for (const pair of flags.set) {
369
+ const eqIndex = pair.indexOf('=');
370
+ if (eqIndex === -1)
371
+ this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
372
+ const key = pair.slice(0, eqIndex);
373
+ let value = pair.slice(eqIndex + 1);
374
+ try {
375
+ value = JSON.parse(value);
376
+ }
377
+ catch { /* keep as string */ }
378
+ const isArrayField = !key.includes('.') && arrayFields.has(key);
379
+ if (isArrayField && !Array.isArray(value)) {
380
+ if (typeof value === 'string') {
381
+ value = value.split(',').map(v => v.trim()).filter(v => v.length > 0);
382
+ }
383
+ else if (value !== undefined && value !== null) {
384
+ value = [value];
385
+ }
386
+ }
387
+ const keys = key.split('.');
388
+ if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
389
+ this.error(`Invalid --set key: ${key}`);
390
+ }
391
+ let obj = item;
392
+ for (let i = 0; i < keys.length - 1; i++) {
393
+ if (!(keys[i] in obj))
394
+ obj[keys[i]] = {};
395
+ obj = obj[keys[i]];
396
+ }
397
+ obj[keys[keys.length - 1]] = value;
398
+ }
399
+ items = [item];
400
+ }
401
+ else {
402
+ this.error('Import requires --file, --data, or --set flags');
403
+ }
404
+ const createEndpoint = ENDPOINTS['create'];
405
+ const updateEndpoint = ENDPOINTS['update'];
406
+ if (!createEndpoint || !updateEndpoint) {
407
+ this.error('Import requires both create and update endpoints');
408
+ }
409
+ // Helper to extract identifier from item (id, code, or xxxCode)
410
+ const getItemIdentifier = (item) => {
411
+ if (item.id)
412
+ return String(item.id);
413
+ if (item.code)
414
+ return String(item.code);
415
+ // Look for xxxCode fields (e.g., ledgerCode, accountCode)
416
+ for (const key of Object.keys(item)) {
417
+ if (key.endsWith('Code') && item[key])
418
+ return String(item[key]);
419
+ }
420
+ // Look for name as fallback
421
+ if (item.name)
422
+ return String(item.name).slice(0, 30);
423
+ return '';
424
+ };
425
+ const results = [];
426
+ // Stream output row-by-row so progress is visible during long imports.
427
+ // Pre-compute the identifier column width from the input items so the
428
+ // table stays aligned without buffering all rows.
429
+ // When stdout is piped (IDE terminals, tee, CI), Node switches to async-buffered
430
+ // mode and rows accumulate in the pipe buffer until it fills. Force blocking
431
+ // mode so each \n-terminated write flushes immediately.
432
+ const stdoutHandle = process.stdout._handle;
433
+ if (stdoutHandle?.setBlocking)
434
+ stdoutHandle.setBlocking(true);
435
+ const outputFormat = flags.output || 'table';
436
+ const useCsv = outputFormat === 'csv' || Boolean(flags.csv);
437
+ const useJson = outputFormat === 'json';
438
+ const statusWidth = 8;
439
+ const identifierWidth = Math.max(10, ...items.map(i => getItemIdentifier(i).length));
440
+ if (useCsv) {
441
+ this.log('status,identifier,id,error');
442
+ }
443
+ else if (!useJson) {
444
+ this.log(`${'status'.padEnd(statusWidth)} ${'identifier'.padEnd(identifierWidth)} error`);
445
+ this.log(`${'-'.repeat(statusWidth)} ${'-'.repeat(identifierWidth)} ${'-'.repeat(50)}`);
446
+ }
447
+ const emitRow = (r) => {
448
+ if (useJson)
449
+ return;
450
+ if (useCsv) {
451
+ const err = (r.error || '').replace(/"/g, '""');
452
+ this.log(`${r.status},${r.identifier || ''},${r.id || ''},"${err}"`);
453
+ }
454
+ else {
455
+ this.log(`${r.status.padEnd(statusWidth)} ${(r.identifier || '').padEnd(identifierWidth)} ${r.error || ''}`);
456
+ }
457
+ };
458
+ // Server-managed fields the API rejects in create/update bodies. Stripped
459
+ // before every request so re-importing a previously-exported payload Just Works.
460
+ const STRIP_FIELDS = new Set(['id', '_type', 'tenantId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy']);
461
+ const stripServerFields = (item) => {
462
+ const out = {};
463
+ for (const [k, v] of Object.entries(item)) {
464
+ if (!STRIP_FIELDS.has(k))
465
+ out[k] = v;
466
+ }
467
+ return out;
468
+ };
469
+ const processItem = async (item) => {
470
+ const identifier = getItemIdentifier(item);
471
+ const body = stripServerFields(item);
472
+ // If the payload carries an id (e.g. re-importing an export), PATCH directly.
473
+ // Fall through to POST only on 404 (so a missing record still gets created).
474
+ const itemId = typeof item.id === 'string' ? item.id : undefined;
475
+ if (itemId) {
476
+ try {
477
+ const updatePath = updateEndpoint.path.replace('{id}', itemId);
478
+ await apiRequest('PATCH', updatePath, {
479
+ data: body,
480
+ contextName: flags.context,
481
+ });
482
+ return { status: 'updated', id: itemId, identifier };
483
+ }
484
+ catch (error) {
485
+ if (!(error instanceof ApiError && error.status === 404)) {
486
+ const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
487
+ return { status: 'error', id: itemId, identifier, error: msg };
488
+ }
489
+ // 404 → record gone, try create below
490
+ }
491
+ }
492
+ try {
493
+ const response = await apiRequest('POST', createEndpoint.path, {
494
+ data: body,
495
+ contextName: flags.context,
496
+ });
497
+ const id = response.data?.id;
498
+ return { status: 'created', id: id ? String(id) : undefined, identifier };
499
+ }
500
+ catch (error) {
501
+ if (error instanceof ApiError && error.status === 409) {
502
+ const errorData = error.data;
503
+ const existingId = errorData?.existingId;
504
+ if (existingId) {
505
+ try {
506
+ const updatePath = updateEndpoint.path.replace('{id}', existingId);
507
+ await apiRequest('PATCH', updatePath, {
508
+ data: body,
509
+ contextName: flags.context,
510
+ });
511
+ return { status: 'updated', id: existingId, identifier };
512
+ }
513
+ catch (updateError) {
514
+ const msg = updateError instanceof ApiError ? updateError.message : String(updateError);
515
+ return { status: 'error', id: existingId, identifier, error: `Update failed: ${msg}` };
516
+ }
517
+ }
518
+ return { status: 'error', identifier, error: 'Conflict but no existingId returned' };
519
+ }
520
+ const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
521
+ return { status: 'error', identifier, error: msg };
522
+ }
523
+ };
524
+ // Worker pool: keep N requests in flight at all times. Rows are emitted as
525
+ // each request resolves (so output order may differ from input order). The
526
+ // summary at the end remains accurate regardless.
527
+ const concurrency = 4;
528
+ const queue = [...items];
529
+ await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
530
+ for (;;) {
531
+ const item = queue.shift();
532
+ if (!item)
533
+ return;
534
+ const r = await processItem(item);
535
+ results.push(r);
536
+ emitRow(r);
537
+ }
538
+ }));
539
+ // Summary counts
540
+ const created = results.filter(r => r.status === 'created').length;
541
+ const updated = results.filter(r => r.status === 'updated').length;
542
+ const errors = results.filter(r => r.status === 'error');
543
+ if (useJson) {
544
+ this.log(JSON.stringify(results, null, 2));
545
+ }
546
+ // Always show summary at the end
547
+ this.log('');
548
+ this.log(`Summary: ${created} created, ${updated} updated, ${errors.length} failed`);
549
+ }
550
+ async runExport(flags) {
551
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
552
+ if (!context)
553
+ this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
554
+ if (!hasCredentials(context))
555
+ this.error(missingCredentialsMessage(context));
556
+ const listEndpoint = ENDPOINTS['list'];
557
+ if (!listEndpoint)
558
+ this.error('Export requires a list endpoint');
559
+ const allItems = [];
560
+ let page = 1;
561
+ const limit = 100;
562
+ let hasMore = true;
563
+ // Build base query params
564
+ const baseParams = {};
565
+ if (flags.search)
566
+ baseParams.search = flags.search;
567
+ if (flags['sort-by'])
568
+ baseParams.sortBy = normalizeSortBy(flags['sort-by']);
569
+ if (flags.include)
570
+ baseParams.include = flags.include;
571
+ if (flags.fields)
572
+ baseParams.fields = flags.fields;
573
+ if (flags.query) {
574
+ try {
575
+ Object.assign(baseParams, JSON.parse(flags.query));
576
+ }
577
+ catch {
578
+ this.error('Invalid JSON in --query');
579
+ }
580
+ }
581
+ // Parse --filter flags (auto-prepend $eq: if no operator specified)
582
+ if (flags.filter && flags.filter.length > 0) {
583
+ for (const f of flags.filter) {
584
+ const eqIndex = f.indexOf('=');
585
+ if (eqIndex === -1)
586
+ this.error(`Invalid --filter format: ${f}. Use: --filter key=value`);
587
+ const key = f.slice(0, eqIndex);
588
+ const value = this.parseFilterValue(f.slice(eqIndex + 1));
589
+ const filterKey = `filter.${key}`;
590
+ if (filterKey in baseParams) {
591
+ const existing = baseParams[filterKey];
592
+ baseParams[filterKey] = Array.isArray(existing) ? [...existing, value] : [existing, value];
593
+ }
594
+ else {
595
+ baseParams[filterKey] = value;
596
+ }
597
+ }
598
+ }
599
+ // Fetch all pages
600
+ process.stderr.write('Exporting...');
601
+ while (hasMore) {
602
+ const params = { ...baseParams, page, limit };
603
+ const response = await apiRequest('GET', listEndpoint.path, {
604
+ params,
605
+ contextName: flags.context,
606
+ });
607
+ let items = [];
608
+ const data = response.data;
609
+ // Handle paginated response format
610
+ if (data && typeof data === 'object' && 'data' in data && Array.isArray(data.data)) {
611
+ items = data.data;
612
+ }
613
+ else if (Array.isArray(response.data)) {
614
+ items = response.data;
615
+ }
616
+ allItems.push(...items);
617
+ process.stderr.write(` ${allItems.length}`);
618
+ // Check if there are more pages
619
+ if (items.length < limit) {
620
+ hasMore = false;
621
+ }
622
+ else {
623
+ page++;
624
+ }
625
+ }
626
+ process.stderr.write(' done\n');
627
+ let output = allItems;
628
+ // Sanitize output if requested
629
+ if (flags.sanitize) {
630
+ output = this.sanitizeOutput(output);
631
+ }
632
+ // Output in requested format
633
+ const fieldList = flags.fields ? flags.fields.split(',').map(f => f.trim()) : undefined;
634
+ if (flags.csv || flags.output === 'csv') {
635
+ this.printCsv(output, fieldList);
636
+ }
637
+ else {
638
+ this.log(JSON.stringify(output, null, 2));
639
+ }
640
+ }
641
+ async runCamt053Import(flags) {
642
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
643
+ if (!context)
644
+ this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
645
+ if (!hasCredentials(context))
646
+ this.error(missingCredentialsMessage(context));
647
+ if (!flags.file) {
648
+ this.error('CAMT.053 import requires --file (-f) flag with path to XML file');
649
+ }
650
+ const fsModule = await import('node:fs');
651
+ let xmlContent;
652
+ try {
653
+ xmlContent = fsModule.readFileSync(flags.file, 'utf-8');
654
+ }
655
+ catch {
656
+ this.error(`Failed to read file: ${flags.file}`);
657
+ }
658
+ const endpoint = ENDPOINTS['import-camt053'];
659
+ try {
660
+ const response = await apiRequest(endpoint.method, endpoint.path, {
661
+ data: xmlContent,
662
+ contextName: flags.context,
663
+ contentType: 'application/xml',
664
+ });
665
+ // Extract transactions array and counts from response
666
+ let transactions = [];
667
+ let imported = 0;
668
+ let skipped = 0;
669
+ if (response.data && typeof response.data === 'object') {
670
+ const data = response.data;
671
+ if ('data' in data && Array.isArray(data.data)) {
672
+ transactions = data.data;
673
+ }
674
+ else if ('transactions' in data && Array.isArray(data.transactions)) {
675
+ transactions = data.transactions;
676
+ }
677
+ else if (Array.isArray(response.data)) {
678
+ transactions = response.data;
679
+ }
680
+ if (typeof data.imported === 'number')
681
+ imported = data.imported;
682
+ if (typeof data.skipped === 'number')
683
+ skipped = data.skipped;
684
+ }
685
+ else if (Array.isArray(response.data)) {
686
+ transactions = response.data;
687
+ }
688
+ if (imported === 0 && skipped === 0 && transactions.length > 0) {
689
+ for (const tx of transactions) {
690
+ const t = tx;
691
+ if (t.status === 'skipped' || t.skipped === true) {
692
+ skipped++;
693
+ }
694
+ else {
695
+ imported++;
696
+ }
697
+ }
698
+ if (imported === 0 && skipped === 0) {
699
+ imported = transactions.length;
700
+ }
701
+ }
702
+ let output = transactions;
703
+ if (flags.sanitize) {
704
+ output = this.sanitizeOutput(transactions);
705
+ }
706
+ const fieldList = flags.fields ? flags.fields.split(',').map(f => f.trim()) : undefined;
707
+ if (flags.csv || flags.output === 'csv') {
708
+ this.printCsv(output, fieldList);
709
+ }
710
+ else if (flags.table || flags.output === 'table') {
711
+ this.printTable(output, fieldList);
712
+ }
713
+ else {
714
+ this.log(JSON.stringify(output, null, 2));
715
+ }
716
+ this.log('');
717
+ this.log(`Summary: ${imported} imported, ${skipped} skipped`);
718
+ }
719
+ catch (error) {
720
+ if (error instanceof ApiError) {
721
+ if (error.status === 404)
722
+ this.error(error.message);
723
+ this.error(`API Error (${error.status}): ${error.message}`);
724
+ }
725
+ throw error;
726
+ }
727
+ }
728
+ async runNestedImport(suffix, parentId, flags) {
729
+ if (!parentId) {
730
+ this.error(`Missing required argument: id. Usage: aderis api-keys import-${suffix} <parent-id> --file data.json`);
731
+ }
732
+ const context = flags.context ? getContext(flags.context) : getCurrentContext();
733
+ if (!context)
734
+ this.error(flags.context ? `Context "${flags.context}" not found. List contexts with: aderis config list` : 'No context configured. Run: aderis auth login --new');
735
+ if (!hasCredentials(context))
736
+ this.error(missingCredentialsMessage(context));
737
+ // Get data from file, --data, or --set flags
738
+ let items = [];
739
+ if (flags.file) {
740
+ const fsModule = await import('node:fs');
741
+ try {
742
+ const content = JSON.parse(fsModule.readFileSync(flags.file, 'utf-8'));
743
+ items = Array.isArray(content) ? content : [content];
744
+ }
745
+ catch {
746
+ this.error(`Failed to read file: ${flags.file}`);
747
+ }
748
+ }
749
+ else if (flags.data) {
750
+ try {
751
+ const content = JSON.parse(flags.data);
752
+ items = Array.isArray(content) ? content : [content];
753
+ }
754
+ catch {
755
+ this.error('Invalid JSON in --data');
756
+ }
757
+ }
758
+ else if (flags.set && flags.set.length > 0) {
759
+ const item = {};
760
+ const arrayFields = new Set(ENDPOINTS[`create-${suffix}`]?.bodyArrayFields ?? []);
761
+ for (const pair of flags.set) {
762
+ const eqIndex = pair.indexOf('=');
763
+ if (eqIndex === -1)
764
+ this.error(`Invalid --set format: ${pair}. Use: --set key=value`);
765
+ const key = pair.slice(0, eqIndex);
766
+ let value = pair.slice(eqIndex + 1);
767
+ try {
768
+ value = JSON.parse(value);
769
+ }
770
+ catch { /* keep as string */ }
771
+ const isArrayField = !key.includes('.') && arrayFields.has(key);
772
+ if (isArrayField && !Array.isArray(value)) {
773
+ if (typeof value === 'string') {
774
+ value = value.split(',').map(v => v.trim()).filter(v => v.length > 0);
775
+ }
776
+ else if (value !== undefined && value !== null) {
777
+ value = [value];
778
+ }
779
+ }
780
+ const keys = key.split('.');
781
+ if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
782
+ this.error(`Invalid --set key: ${key}`);
783
+ }
784
+ let obj = item;
785
+ for (let i = 0; i < keys.length - 1; i++) {
786
+ if (!(keys[i] in obj))
787
+ obj[keys[i]] = {};
788
+ obj = obj[keys[i]];
789
+ }
790
+ obj[keys[keys.length - 1]] = value;
791
+ }
792
+ items = [item];
793
+ }
794
+ else {
795
+ this.error(`Import requires --file, --data, or --set flags`);
796
+ }
797
+ const createEndpoint = ENDPOINTS[`create-${suffix}`];
798
+ const updateEndpoint = ENDPOINTS[`update-${suffix}`];
799
+ if (!createEndpoint || !updateEndpoint) {
800
+ this.error(`Import requires both create-${suffix} and update-${suffix} endpoints`);
801
+ }
802
+ // Build the base path with parent ID (first path param)
803
+ const firstParam = createEndpoint.pathParams[0];
804
+ const basePath = createEndpoint.path.replace(`{${firstParam}}`, parentId);
805
+ // Helper to extract identifier from item
806
+ const getItemIdentifier = (item) => {
807
+ if (item.id)
808
+ return String(item.id);
809
+ if (item.itemId)
810
+ return String(item.itemId);
811
+ if (item.code)
812
+ return String(item.code);
813
+ for (const key of Object.keys(item)) {
814
+ if (key.endsWith('Id') && item[key])
815
+ return String(item[key]);
816
+ if (key.endsWith('Code') && item[key])
817
+ return String(item[key]);
818
+ }
819
+ return '';
820
+ };
821
+ const results = [];
822
+ const stdoutHandle = process.stdout._handle;
823
+ if (stdoutHandle?.setBlocking)
824
+ stdoutHandle.setBlocking(true);
825
+ const outputFormat = flags.output || 'table';
826
+ const useCsv = outputFormat === 'csv' || Boolean(flags.csv);
827
+ const useJson = outputFormat === 'json';
828
+ const statusWidth = 8;
829
+ const identifierWidth = Math.max(10, ...items.map(i => getItemIdentifier(i).length));
830
+ if (useCsv) {
831
+ this.log('status,identifier,id,error');
832
+ }
833
+ else if (!useJson) {
834
+ this.log(`${'status'.padEnd(statusWidth)} ${'identifier'.padEnd(identifierWidth)} error`);
835
+ this.log(`${'-'.repeat(statusWidth)} ${'-'.repeat(identifierWidth)} ${'-'.repeat(50)}`);
836
+ }
837
+ const emitRow = (r) => {
838
+ if (useJson)
839
+ return;
840
+ if (useCsv) {
841
+ const err = (r.error || '').replace(/"/g, '""');
842
+ this.log(`${r.status},${r.identifier || ''},${r.id || ''},"${err}"`);
843
+ }
844
+ else {
845
+ this.log(`${r.status.padEnd(statusWidth)} ${(r.identifier || '').padEnd(identifierWidth)} ${r.error || ''}`);
846
+ }
847
+ };
848
+ const STRIP_FIELDS = new Set(['id', '_type', 'tenantId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy']);
849
+ const stripServerFields = (item) => {
850
+ const out = {};
851
+ for (const [k, v] of Object.entries(item)) {
852
+ if (!STRIP_FIELDS.has(k))
853
+ out[k] = v;
854
+ }
855
+ return out;
856
+ };
857
+ const buildUpdatePath = (existingId) => {
858
+ const firstUpdateParam = updateEndpoint.pathParams[0];
859
+ const nestedIdParam = updateEndpoint.pathParams.find((p, i) => i > 0);
860
+ let updatePath = updateEndpoint.path.replace(`{${firstUpdateParam}}`, parentId);
861
+ if (nestedIdParam) {
862
+ updatePath = updatePath.replace(`{${nestedIdParam}}`, existingId);
863
+ }
864
+ return updatePath;
865
+ };
866
+ const processItem = async (item) => {
867
+ const identifier = getItemIdentifier(item);
868
+ const body = stripServerFields(item);
869
+ const itemId = typeof item.id === 'string' ? item.id : undefined;
870
+ if (itemId) {
871
+ try {
872
+ await apiRequest('PATCH', buildUpdatePath(itemId), {
873
+ data: body,
874
+ contextName: flags.context,
875
+ });
876
+ return { status: 'updated', id: itemId, identifier };
877
+ }
878
+ catch (error) {
879
+ if (!(error instanceof ApiError && error.status === 404)) {
880
+ const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
881
+ return { status: 'error', id: itemId, identifier, error: msg };
882
+ }
883
+ // 404 → fall through and try create
884
+ }
885
+ }
886
+ try {
887
+ const response = await apiRequest('POST', basePath, {
888
+ data: body,
889
+ contextName: flags.context,
890
+ });
891
+ const id = response.data?.id;
892
+ return { status: 'created', id: id ? String(id) : undefined, identifier };
893
+ }
894
+ catch (error) {
895
+ if (error instanceof ApiError && error.status === 409) {
896
+ const errorData = error.data;
897
+ const existingId = errorData?.existingId || item.id;
898
+ if (existingId) {
899
+ try {
900
+ await apiRequest('PATCH', buildUpdatePath(existingId), {
901
+ data: body,
902
+ contextName: flags.context,
903
+ });
904
+ return { status: 'updated', id: existingId, identifier };
905
+ }
906
+ catch (updateError) {
907
+ const msg = updateError instanceof ApiError ? updateError.message : String(updateError);
908
+ return { status: 'error', id: existingId, identifier, error: `Update failed: ${msg}` };
909
+ }
910
+ }
911
+ return { status: 'error', identifier, error: 'Conflict but no existingId returned' };
912
+ }
913
+ const msg = error instanceof ApiError ? `(${error.status}) ${error.message}` : String(error);
914
+ return { status: 'error', identifier, error: msg };
915
+ }
916
+ };
917
+ // Worker pool: 4 requests in flight at a time. Rows are emitted as each
918
+ // request resolves so output order may differ from input order.
919
+ const concurrency = 4;
920
+ const queue = [...items];
921
+ await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
922
+ for (;;) {
923
+ const item = queue.shift();
924
+ if (!item)
925
+ return;
926
+ const r = await processItem(item);
927
+ results.push(r);
928
+ emitRow(r);
929
+ }
930
+ }));
931
+ // Summary counts
932
+ const created = results.filter(r => r.status === 'created').length;
933
+ const updated = results.filter(r => r.status === 'updated').length;
934
+ const errors = results.filter(r => r.status === 'error');
935
+ if (useJson) {
936
+ this.log(JSON.stringify(results, null, 2));
937
+ }
938
+ this.log('');
939
+ this.log(`Summary: ${created} created, ${updated} updated, ${errors.length} failed`);
940
+ }
941
+ parseFilterValue(value) {
942
+ // Recognises the nestjs-paginate operator set (with or without the leading $)
943
+ // and recursively unwraps chained operators like 'not:null' -> '$not:$null'
944
+ // or 'not:like:John' -> '$not:$like:John'. Falls back to '$eq:<value>' when
945
+ // no operator prefix is present.
946
+ const opRe = /^\$?(and|or|not|eq|gt|gte|in|null|lt|lte|btw|ne|ilike|like|sw|contains)(?::|$)/;
947
+ const m = value.match(opRe);
948
+ if (!m)
949
+ return `\$eq:${value}`;
950
+ const op = m[1];
951
+ const rest = value.slice(m[0].length);
952
+ if (rest === '')
953
+ return `\$${op}`;
954
+ return opRe.test(rest) ? `\$${op}:${this.parseFilterValue(rest)}` : `\$${op}:${rest}`;
955
+ }
956
+ sanitizeOutput(data) {
957
+ const auditFields = ['_type', 'tenantId', 'createdAt', 'updatedAt', 'createdBy', 'updatedBy'];
958
+ const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
959
+ const sanitize = (obj, parentUuids = new Set()) => {
960
+ if (obj === null || obj === undefined)
961
+ return undefined;
962
+ if (Array.isArray(obj)) {
963
+ const result = obj.map(item => sanitize(item, new Set(parentUuids))).filter(item => item !== undefined);
964
+ return result.length > 0 ? result : undefined;
965
+ }
966
+ if (typeof obj === 'object') {
967
+ const input = obj;
968
+ // Use a Map to avoid any prototype-pollution risk on the result object
969
+ const collected = new Map();
970
+ // Collect UUIDs from this level to pass to children
971
+ const currentUuids = new Set(parentUuids);
972
+ for (const [, value] of Object.entries(input)) {
973
+ if (typeof value === 'string' && uuidRegex.test(value)) {
974
+ currentUuids.add(value);
975
+ }
976
+ }
977
+ for (const [key, value] of Object.entries(input)) {
978
+ // Skip prototype-pollution keys
979
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype')
980
+ continue;
981
+ // Skip audit fields
982
+ if (auditFields.includes(key))
983
+ continue;
984
+ // Skip null/undefined values
985
+ if (value === null || value === undefined)
986
+ continue;
987
+ // Skip UUID values that exist in parent
988
+ if (typeof value === 'string' && uuidRegex.test(value) && parentUuids.has(value))
989
+ continue;
990
+ // Recursively sanitize nested objects/arrays
991
+ const sanitized = sanitize(value, currentUuids);
992
+ if (sanitized !== undefined) {
993
+ collected.set(key, sanitized);
994
+ }
995
+ }
996
+ if (collected.size === 0)
997
+ return undefined;
998
+ return Object.fromEntries(collected);
999
+ }
1000
+ return obj;
1001
+ };
1002
+ return sanitize(data) ?? (Array.isArray(data) ? [] : {});
1003
+ }
1004
+ getColumns(data, fields, flatten = false) {
1005
+ const items = Array.isArray(data) ? data : [data];
1006
+ if (items.length === 0)
1007
+ return { cols: [], items: [] };
1008
+ const first = items[0];
1009
+ const hiddenFields = ['tenantId', '_type'];
1010
+ if (fields) {
1011
+ return { cols: fields, items: items };
1012
+ }
1013
+ // Recursively collect all column paths, flattening objects (but not arrays)
1014
+ const collectPaths = (obj, prefix = '') => {
1015
+ const paths = [];
1016
+ for (const key of Object.keys(obj)) {
1017
+ const fullKey = prefix ? `${prefix}.${key}` : key;
1018
+ if (hiddenFields.includes(key))
1019
+ continue;
1020
+ const val = obj[key];
1021
+ if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
1022
+ // Flatten nested objects (but not arrays)
1023
+ if (flatten) {
1024
+ paths.push(...collectPaths(val, fullKey));
1025
+ }
1026
+ // Skip objects when not flattening
1027
+ }
1028
+ else if (!Array.isArray(val)) {
1029
+ // Include primitives (and null)
1030
+ paths.push(fullKey);
1031
+ }
1032
+ // Skip arrays entirely
1033
+ }
1034
+ return paths;
1035
+ };
1036
+ // Scan multiple items to discover all columns (handles fields absent/null in first item)
1037
+ const cols = collectPaths(first);
1038
+ const colSet = new Set(cols);
1039
+ const scanCount = Math.min(items.length, 50);
1040
+ for (let i = 1; i < scanCount; i++) {
1041
+ for (const p of collectPaths(items[i])) {
1042
+ if (!colSet.has(p)) {
1043
+ cols.push(p);
1044
+ colSet.add(p);
1045
+ }
1046
+ }
1047
+ }
1048
+ return { cols: flatten ? cols : cols.slice(0, 8), items: items };
1049
+ }
1050
+ getValue(row, col) {
1051
+ if (!col.includes('.'))
1052
+ return String(row[col] ?? '');
1053
+ const parts = col.split('.');
1054
+ // Walk the dot-path; descending through an array branches into every
1055
+ // element so leaf values get collected from each one. Multiple leaves are
1056
+ // joined with ';' (e.g. dunningReminders.id -> "uuid1;uuid2").
1057
+ const walk = (o, idx) => {
1058
+ if (idx >= parts.length)
1059
+ return [o];
1060
+ if (o == null)
1061
+ return [];
1062
+ if (Array.isArray(o))
1063
+ return o.flatMap(item => walk(item, idx));
1064
+ if (typeof o === 'object')
1065
+ return walk(o[parts[idx]], idx + 1);
1066
+ return [];
1067
+ };
1068
+ return walk(row, 0).filter(v => v !== undefined && v !== null).map(v => String(v)).join(';');
1069
+ }
1070
+ printTable(data, fields) {
1071
+ const { cols, items } = this.getColumns(data, fields);
1072
+ if (items.length === 0) {
1073
+ this.log('No results');
1074
+ return;
1075
+ }
1076
+ // Calculate column widths
1077
+ const widths = cols.map(c => c.length);
1078
+ for (const item of items) {
1079
+ cols.forEach((col, i) => {
1080
+ const val = this.getValue(item, col).slice(0, 40);
1081
+ widths[i] = Math.max(widths[i], val.length);
1082
+ });
1083
+ }
1084
+ // Print header
1085
+ const header = cols.map((c, i) => c.padEnd(widths[i])).join(' ');
1086
+ this.log(header);
1087
+ this.log(widths.map(w => '-'.repeat(w)).join(' '));
1088
+ // Print rows
1089
+ for (const item of items) {
1090
+ const row = cols.map((col, i) => {
1091
+ const val = this.getValue(item, col).slice(0, 40);
1092
+ return val.padEnd(widths[i]);
1093
+ }).join(' ');
1094
+ this.log(row);
1095
+ }
1096
+ }
1097
+ printCsv(data, fields) {
1098
+ const { cols, items } = this.getColumns(data, fields, true); // flatten=true for CSV
1099
+ if (items.length === 0) {
1100
+ this.log('No results');
1101
+ return;
1102
+ }
1103
+ const escape = (val) => {
1104
+ if (val.includes(',') || val.includes('"') || val.includes('\n')) {
1105
+ return '"' + val.replace(/"/g, '""') + '"';
1106
+ }
1107
+ return val;
1108
+ };
1109
+ // Print header
1110
+ this.log(cols.map(escape).join(','));
1111
+ // Print rows
1112
+ for (const item of items) {
1113
+ const row = cols.map(col => escape(this.getValue(item, col)));
1114
+ this.log(row.join(','));
1115
+ }
1116
+ }
1117
+ }