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