@aderis-erp/cli 1.0.17 → 1.1.1

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