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