@aderis-erp/cli 1.0.15 → 1.1.0

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