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