@aderis-erp/cli 1.0.2 → 1.0.4

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