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