@commercelayer/cli-plugin-provisioning 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +413 -0
  3. package/bin/dev +18 -0
  4. package/bin/dev.cmd +3 -0
  5. package/bin/run +5 -0
  6. package/bin/run.cmd +3 -0
  7. package/lib/base.d.ts +59 -0
  8. package/lib/base.js +496 -0
  9. package/lib/commands/provisioning/create.d.ts +21 -0
  10. package/lib/commands/provisioning/create.js +137 -0
  11. package/lib/commands/provisioning/delete.d.ts +20 -0
  12. package/lib/commands/provisioning/delete.js +52 -0
  13. package/lib/commands/provisioning/exec.d.ts +15 -0
  14. package/lib/commands/provisioning/exec.js +55 -0
  15. package/lib/commands/provisioning/fetch.d.ts +28 -0
  16. package/lib/commands/provisioning/fetch.js +57 -0
  17. package/lib/commands/provisioning/get.d.ts +27 -0
  18. package/lib/commands/provisioning/get.js +31 -0
  19. package/lib/commands/provisioning/list.d.ts +22 -0
  20. package/lib/commands/provisioning/list.js +137 -0
  21. package/lib/commands/provisioning/noc.d.ts +6 -0
  22. package/lib/commands/provisioning/noc.js +13 -0
  23. package/lib/commands/provisioning/relationship.d.ts +30 -0
  24. package/lib/commands/provisioning/relationship.js +114 -0
  25. package/lib/commands/provisioning/resources.d.ts +11 -0
  26. package/lib/commands/provisioning/resources.js +36 -0
  27. package/lib/commands/provisioning/retrieve.d.ts +21 -0
  28. package/lib/commands/provisioning/retrieve.js +95 -0
  29. package/lib/commands/provisioning/update.d.ts +26 -0
  30. package/lib/commands/provisioning/update.js +157 -0
  31. package/lib/csv.d.ts +3 -0
  32. package/lib/csv.js +98 -0
  33. package/lib/output.d.ts +5 -0
  34. package/lib/output.js +15 -0
  35. package/lib/util/resources/available.d.ts +35 -0
  36. package/lib/util/resources/available.js +13 -0
  37. package/lib/util/resources/build.d.ts +1 -0
  38. package/lib/util/resources/build.js +47 -0
  39. package/lib/util/resources/index.d.ts +12 -0
  40. package/lib/util/resources/index.js +19 -0
  41. package/oclif.manifest.json +1502 -0
  42. package/package.json +86 -0
package/lib/base.js ADDED
@@ -0,0 +1,496 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cliux = exports.Args = exports.Flags = exports.BaseFilterCommand = exports.BaseCommand = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const core_1 = require("@oclif/core");
6
+ Object.defineProperty(exports, "Flags", { enumerable: true, get: function () { return core_1.Flags; } });
7
+ Object.defineProperty(exports, "Args", { enumerable: true, get: function () { return core_1.Args; } });
8
+ Object.defineProperty(exports, "cliux", { enumerable: true, get: function () { return core_1.ux; } });
9
+ const resources_1 = require("./util/resources");
10
+ const output_1 = require("./output");
11
+ const csv_1 = require("./csv");
12
+ const fs_1 = require("fs");
13
+ const provisioning_sdk_1 = tslib_1.__importStar(require("@commercelayer/provisioning-sdk"));
14
+ // import { availableLanguages, buildCommand, getLanguageArg, languageInfo, promptLanguage, type RequestData } from './lang'
15
+ const cli_core_1 = require("@commercelayer/cli-core");
16
+ // import { aliasExists, checkAlias, type CommandParams, loadCommandData, type ResourceOperation, saveCommandData } from './commands'
17
+ // import type { ResourceId, ResourceType } from '@commercelayer/provisioning-sdk/lib/cjs/resource'
18
+ const pkg = require('../package.json');
19
+ // export const FLAG_SAVE_PARAMS = 'save-args'
20
+ // export const FLAG_LOAD_PARAMS = 'load-args'
21
+ class BaseCommand extends core_1.Command {
22
+ checkApplication(accessToken, kinds) {
23
+ const info = cli_core_1.clToken.decodeAccessToken(accessToken);
24
+ if (info === null)
25
+ this.error('Invalid access token provided');
26
+ else if (!kinds.includes(info.application.kind))
27
+ this.error(`Invalid application kind: ${cli_core_1.clColor.msg.error(info.application.kind)}. Application kind must be one of the following: ${cli_core_1.clColor.cyanBright(kinds.join(', '))}`);
28
+ return true;
29
+ }
30
+ checkResourceId(resource, resourceId, required = true) {
31
+ let res = resource;
32
+ let id = resourceId;
33
+ const si = res.indexOf('/');
34
+ if (si >= 0) {
35
+ const rt = res.split('/');
36
+ if (id && rt[1])
37
+ this.error(`Double definition of resource id: [${res}, ${id}]`, { suggestions: [`Define resource id as command argument (${cli_core_1.clColor.italic(id)}) or as part of the resource itself (${cli_core_1.clColor.italic(res)}) but not both`] });
38
+ else
39
+ id = rt[1];
40
+ res = rt[0];
41
+ }
42
+ const res_ = (0, resources_1.findResource)(res, { singular: true });
43
+ const singleton = res_?.singleton || false;
44
+ if (id) {
45
+ if (singleton)
46
+ this.error(`Singleton resource ${cli_core_1.clColor.api.resource(res)} does not require id`);
47
+ if (id.includes('/'))
48
+ this.error(`Invalid resourde id: ${cli_core_1.clColor.msg.error(id)}`);
49
+ }
50
+ else if (required && !singleton)
51
+ this.error('Resource id not defined');
52
+ return {
53
+ res,
54
+ id,
55
+ singleton,
56
+ };
57
+ }
58
+ checkResource(res, { required = true, singular = false } = {}) {
59
+ if (!res && required)
60
+ this.error('Resource type not defined');
61
+ const resource = (0, resources_1.findResource)(res, { singular });
62
+ if (resource === undefined)
63
+ this.error(`Invalid resource ${cli_core_1.clColor.style.error(res)}`, { suggestions: [`Execute command ${cli_core_1.clColor.style.command('resources')} to get a list of all available CLI resources`] });
64
+ return resource;
65
+ }
66
+ initCommerceLayer(flags, ...options) {
67
+ const domain = flags.domain;
68
+ const accessToken = flags.accessToken;
69
+ const userAgent = cli_core_1.clUtil.userAgent(this.config);
70
+ const cl = (0, provisioning_sdk_1.default)({ domain, accessToken, userAgent, ...options });
71
+ if ('cl' in this)
72
+ this.cl = cl;
73
+ return cl;
74
+ }
75
+ checkOperation(sdk, name, attributes) {
76
+ if (!sdk[name]) {
77
+ // resource attributes reference, reference_origin and metadata are always updatable
78
+ if ((name === 'update') && attributes) {
79
+ if (!Object.keys(attributes).some(attr => !['reference', 'reference_origin', 'metadata'].includes(attr)))
80
+ return true;
81
+ }
82
+ this.error(`Operation not supported for resource ${cli_core_1.clColor.api.resource(sdk.type())}: ${cli_core_1.clColor.msg.error(name)}`);
83
+ }
84
+ return true;
85
+ }
86
+ printOutput(output, flags) {
87
+ if (output && !flags['headers-only'])
88
+ this.log((0, output_1.formatOutput)(output, flags));
89
+ }
90
+ printHeaders(headers, flags) {
91
+ if (headers) {
92
+ if (flags.headers || flags['headers-only']) {
93
+ this.log('---------- Response Headers ----------');
94
+ if (Object.keys(headers).length === 0)
95
+ this.log(cli_core_1.clColor.italic('No headers'));
96
+ else
97
+ this.log((0, output_1.formatOutput)(headers, flags));
98
+ this.log('---------- ---------------- ----------');
99
+ }
100
+ }
101
+ }
102
+ printError(error, flags, args) {
103
+ let err = error;
104
+ if (provisioning_sdk_1.CommerceLayerProvisioningStatic.isApiError(err)) {
105
+ err = err.errors || `Unable to find resource of type ${cli_core_1.clColor.msg.error(args.resource)} and id ${cli_core_1.clColor.msg.error(args.id)}`;
106
+ }
107
+ else if (error.response) {
108
+ if (error.response.status === 401)
109
+ this.error(cli_core_1.clColor.bg.red(`${error.response.statusText} [${error.response.status}]`), { suggestions: ['Execute login to get access to the selected resource'] });
110
+ else if (error.response.status === 500)
111
+ this.error(`We're sorry, but something went wrong (${error.response.status})`);
112
+ else if (error.response.status === 429)
113
+ this.error(`You have done too many requests in the last 5 minutes (${error.response.status})`);
114
+ else
115
+ err = error.response.data.errors;
116
+ }
117
+ else if (error.message)
118
+ err = error.message;
119
+ this.error((0, output_1.formatOutput)(err, flags));
120
+ }
121
+ _keyvalFlag(flag, type = 'attribute') {
122
+ const param = {};
123
+ if (flag && (flag.length > 0)) {
124
+ flag.forEach(f => {
125
+ const eqi = f.indexOf('=');
126
+ if (eqi < 1)
127
+ this.error(`Invalid ${type.toLowerCase()} ${cli_core_1.clColor.msg.error(f)}`, {
128
+ suggestions: [`${cli_core_1.clText.capitalize(type)} flags must be defined using the format ${cli_core_1.clColor.cli.value('name=value')}`],
129
+ });
130
+ const name = f.substr(0, eqi);
131
+ const value = f.substr(eqi + 1);
132
+ if (param[name])
133
+ this.warn(`${cli_core_1.clText.capitalize(type)} ${cli_core_1.clColor.msg.warning(name)} has already been defined`);
134
+ param[name] = value;
135
+ });
136
+ }
137
+ return param;
138
+ }
139
+ attributeFlag(flag) {
140
+ const attr = this._keyvalFlag(flag, 'attribute');
141
+ const attributes = {};
142
+ Object.entries(attr).forEach(([k, v]) => {
143
+ attributes[k] = (v === 'null') ? null : v;
144
+ });
145
+ return attributes;
146
+ }
147
+ }
148
+ exports.BaseCommand = BaseCommand;
149
+ BaseCommand.baseFlags = {
150
+ domain: core_1.Flags.string({
151
+ char: 'd',
152
+ required: false,
153
+ hidden: true,
154
+ env: 'CL_CLI_DOMAIN',
155
+ }),
156
+ accessToken: core_1.Flags.string({
157
+ hidden: true,
158
+ required: true,
159
+ env: 'CL_CLI_ACCESS_TOKEN',
160
+ })
161
+ };
162
+ class BaseFilterCommand extends BaseCommand {
163
+ // INIT (override)
164
+ async init() {
165
+ // Check for plugin updates only if in visible mode
166
+ if (!this.argv.includes('--blind') && !this.argv.includes('--silent') && !this.argv.includes('--quiet'))
167
+ cli_core_1.clUpdate.checkUpdate(pkg);
168
+ return await super.init();
169
+ }
170
+ // CATCH (override)
171
+ async catch(error) {
172
+ if (error.message?.match(/Missing \d required args?:\nresource/))
173
+ this.error(`Missing argument ${cli_core_1.clColor.style.error('resource')}`, { suggestions: [`Execute command ${cli_core_1.clColor.style.command('resources')} to get a list of all available Provisioning resources`] });
174
+ // else throw error // overwrite command catch method
175
+ else
176
+ return await super.catch(error); // extend command catch method
177
+ }
178
+ // -- CUSTOM METHODS -- //
179
+ includeFlag(flag, relationships, force) {
180
+ const values = [];
181
+ if (flag) {
182
+ const flagValues = flag.map(f => f.split(',').map(t => t.trim()));
183
+ flagValues.forEach(a => values.push(...a));
184
+ if (values.some(f => f.split('.').length > 3) && !force)
185
+ this.error('Can be only included resources within the 3rd level of depth');
186
+ }
187
+ if (relationships) {
188
+ Object.keys(relationships).forEach(r => {
189
+ if (!values.includes(r))
190
+ values.push(r);
191
+ });
192
+ }
193
+ return values;
194
+ }
195
+ objectFlag(flag) {
196
+ const objects = {};
197
+ if (flag && (flag.length > 0)) {
198
+ flag.forEach(f => {
199
+ const slashSep = f.indexOf('/');
200
+ if (slashSep < 0)
201
+ this.error(`No name or fields defined in flag object${cli_core_1.clColor.style.flag(f)}`);
202
+ const name = f.substring(0, slashSep);
203
+ if (name === '')
204
+ this.error(`No name defined in flag object ${f}`);
205
+ const fields = f.substring(slashSep + 1).split(/(?<!\\),/g).map(v => v.trim()); // escape ',' in value with \\ (double back slash)
206
+ if (fields[0].trim() === '')
207
+ this.error(`No fields defined for object field ${cli_core_1.clColor.style.attribute(name)}`);
208
+ const obj = {};
209
+ fields.forEach(f => {
210
+ const eqi = f.indexOf('=');
211
+ if (eqi < 0)
212
+ this.error(`No value defined for object field ${cli_core_1.clColor.style.attribute(f)} of object ${cli_core_1.clColor.style.attribute(name)}`);
213
+ const n = f.substring(0, eqi);
214
+ const v = f.substring(eqi + 1).replace(/\\,/g, ',');
215
+ obj[n] = cli_core_1.clCommand.fixValueType(v);
216
+ });
217
+ if (objects[name] === undefined)
218
+ objects[name] = {};
219
+ objects[name] = { ...objects[name], ...obj };
220
+ });
221
+ }
222
+ return objects;
223
+ }
224
+ fieldsFlag(flag, type) {
225
+ const fields = {};
226
+ if (flag && (flag.length > 0)) {
227
+ flag.forEach(f => {
228
+ let res = type;
229
+ let val = f;
230
+ if (f.includes('/')) {
231
+ const kv = f.split('/');
232
+ if (kv.length > 2)
233
+ this.error('Can be defined only one resource for each fields flag', { suggestions: [`Split the value ${cli_core_1.clColor.style.attribute(f)} into two fields flags`] });
234
+ res = kv[0].replace('[', '').replace(']', '');
235
+ this.checkResource(res);
236
+ val = kv[1];
237
+ }
238
+ const values = val.split(',').map(v => v.trim());
239
+ if (values[0].trim() === '')
240
+ this.error(`No fields defined for resource ${cli_core_1.clColor.api.resource(res)}`);
241
+ if (fields[res] === undefined)
242
+ fields[res] = [];
243
+ fields[res].push(...values);
244
+ });
245
+ }
246
+ return fields;
247
+ }
248
+ whereFlag(flag) {
249
+ const wheres = {};
250
+ if (flag && (flag.length > 0)) {
251
+ flag.forEach(f => {
252
+ const wt = f.split('=');
253
+ if (wt.length < 2)
254
+ this.error(`Filter flag must be in the form ${cli_core_1.clColor.style.attribute('predicate=value')}`);
255
+ const w = wt[0];
256
+ if (!cli_core_1.clFilter.available(w))
257
+ this.error(`Invalid query filter: ${cli_core_1.clColor.style.error(w)}`, {
258
+ suggestions: [`Execute command ${cli_core_1.clColor.style.command('resources:filters')} to get a full list of all available filter predicates`],
259
+ ref: 'https://docs.commercelayer.io/api/filtering-data#list-of-predicates',
260
+ });
261
+ const v = wt[1];
262
+ wheres[w] = v;
263
+ });
264
+ }
265
+ return wheres;
266
+ }
267
+ sortFlag(flag) {
268
+ const sort = {};
269
+ if (flag && (flag.length > 0)) {
270
+ if (flag.some(f => {
271
+ const ft = f.split(',');
272
+ return (ft.includes('asc') || ft.includes('desc'));
273
+ })) {
274
+ flag.forEach(f => {
275
+ const ot = f.split(',');
276
+ if (ot.length > 2)
277
+ this.error('Can be defined only one field for each sort flag', { suggestions: [`Split the value ${cli_core_1.clColor.style.attribute(f)} into two or more sort flags`] });
278
+ const of = ot[0];
279
+ if (of.startsWith('-'))
280
+ this.error('You cannot mix two ordering syntaxes', { suggestions: [`Choose between the style ${cli_core_1.clColor.cli.value('<field>,<order>')} and the style ${cli_core_1.clColor.cli.value('[-]<field>')}`] });
281
+ const sd = ot[1] || 'asc';
282
+ if (!['asc', 'desc'].includes(sd))
283
+ this.error(`Invalid sort flag: ${cli_core_1.clColor.msg.error(f)}`, { suggestions: [`Sort direction can assume only the values ${cli_core_1.clColor.cli.value('asc')} or ${cli_core_1.clColor.cli.value('desc')}`] });
284
+ sort[of] = sd;
285
+ });
286
+ }
287
+ else {
288
+ flag.forEach(fl => {
289
+ fl.split(',').forEach(f => {
290
+ const desc = f.startsWith('-');
291
+ const of = desc ? f.slice(1) : f;
292
+ const sd = desc ? 'desc' : 'asc';
293
+ sort[of] = sd;
294
+ });
295
+ });
296
+ }
297
+ }
298
+ return sort;
299
+ }
300
+ metadataFlag(flag, { fixTypes = false } = {}) {
301
+ const md = this._keyvalFlag(flag, 'metadata');
302
+ const metadata = {};
303
+ Object.keys(md).forEach(k => {
304
+ metadata[k] = fixTypes ? cli_core_1.clCommand.fixValueType(md[k]) : md[k];
305
+ });
306
+ return metadata;
307
+ }
308
+ relationshipFlag(flag) {
309
+ const relationships = {};
310
+ if (flag && (flag.length > 0)) {
311
+ flag.forEach(f => {
312
+ let rel;
313
+ let name;
314
+ let id;
315
+ let type;
316
+ const rt = f.split('=');
317
+ if (rt.length === 2) {
318
+ if ((name = rt[0]) === '')
319
+ this.error('Relationship attribute name is empty');
320
+ if ((rel = rt[1]) === '')
321
+ this.error('Relationship value is empty');
322
+ }
323
+ else
324
+ this.error(`Invalid relationship flag: ${cli_core_1.clColor.msg.error(f)}`, { suggestions: [`Define the relationship using the format ${cli_core_1.clColor.cli.value('attribute_name=resource_type/resource_id')}`] });
325
+ const vt = rel.split('/');
326
+ if (vt.length === 2) {
327
+ if ((type = vt[0]) === '')
328
+ this.error('Relationship type is empty');
329
+ if ((id = vt[1]) === '')
330
+ this.error('Relationship resource id is empty');
331
+ }
332
+ else {
333
+ id = vt[0];
334
+ const res = (0, resources_1.findResource)(name, { singular: true });
335
+ if (res)
336
+ type = res.api;
337
+ else
338
+ this.error('Relationship type is empty');
339
+ }
340
+ // const res = this.checkResource(type)
341
+ if (relationships[name])
342
+ this.warn(`Relationship ${cli_core_1.clColor.yellow(name)} has already been defined`);
343
+ relationships[name] = { id, type };
344
+ });
345
+ }
346
+ return relationships;
347
+ }
348
+ extractFlag(flag) {
349
+ const extract = {};
350
+ if (flag && (flag.length > 0)) {
351
+ flag.forEach(f => {
352
+ const kv = f.split('/');
353
+ if (kv.length > 2)
354
+ this.error('Can be defined only one field for each extract flag', { suggestions: [`Split the value ${cli_core_1.clColor.cli.value(f)} into two extract flags`] });
355
+ else if (kv.length === 1)
356
+ this.error(`No fields defined for object ${cli_core_1.clColor.cli.value(kv[0])}`);
357
+ const name = kv[0];
358
+ if (name === '')
359
+ this.error(`No name defined in flag extract ${f}`);
360
+ if (kv[1].trim() === '')
361
+ this.error(`No fields defined for object ${cli_core_1.clColor.cli.value(kv[0])}`);
362
+ const fields = kv[1].split(/(?<!\\),/g).map(v => v.trim()); // escape ',' in value with \\ (double back slash)
363
+ if (fields[0].trim() === '')
364
+ this.error(`No fields defined for object field ${cli_core_1.clColor.cli.value(name)}`);
365
+ if (extract[name] === undefined)
366
+ extract[name] = [];
367
+ extract[name].push(...fields);
368
+ });
369
+ }
370
+ return extract;
371
+ }
372
+ extractObjectFields(fields, obj) {
373
+ Object.entries(fields).forEach(([extObj, extFields]) => {
374
+ const objPath = extObj.split('.');
375
+ let curObj = obj;
376
+ for (const op of objPath) {
377
+ if (curObj)
378
+ curObj = curObj[op]; // if not undefined go to next level object
379
+ else
380
+ break; // if undefined stop search in depth
381
+ }
382
+ // if leaf field is an object and it is not a relationship then extract its fields
383
+ if (curObj && (typeof curObj === 'object') && !curObj.id && !curObj.type)
384
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
385
+ for (const k of Object.keys(curObj))
386
+ if (!extFields.includes(k))
387
+ delete curObj[k];
388
+ });
389
+ }
390
+ saveOutput(output, flags) {
391
+ try {
392
+ let filePath = flags.save || flags['save-path'];
393
+ if (!filePath)
394
+ this.warn('Undefined output save path');
395
+ filePath = cli_core_1.clUtil.specialFolder(filePath, flags['save-path']);
396
+ const fileExport = flags.csv ? csv_1.exportCsv : output_1.exportOutput;
397
+ fileExport(output, flags, filePath)
398
+ .then(() => {
399
+ if ((0, fs_1.existsSync)(filePath))
400
+ this.log(`Command output saved to file ${cli_core_1.clColor.style.path(filePath)}\n`);
401
+ })
402
+ .catch(() => this.error(`Unable to save command output to file ${cli_core_1.clColor.style.path(filePath)}`, { suggestions: ['Please check you have the right file system permissions'] }));
403
+ }
404
+ catch (error) {
405
+ if (error.code === 'ENOENT')
406
+ this.warn(`Path not found ${cli_core_1.clColor.msg.error(error.path)}: execute command with flag ${cli_core_1.clColor.cli.flag('-X')} to force path creation`);
407
+ else
408
+ throw error;
409
+ }
410
+ finally {
411
+ this.log();
412
+ }
413
+ }
414
+ }
415
+ exports.BaseFilterCommand = BaseFilterCommand;
416
+ BaseFilterCommand.flags = {
417
+ include: core_1.Flags.string({
418
+ char: 'i',
419
+ multiple: true,
420
+ description: 'comma separated resources to include',
421
+ }),
422
+ fields: core_1.Flags.string({
423
+ char: 'f',
424
+ multiple: true,
425
+ description: 'comma separeted list of fields in the format [resourceType/]field1,field2...',
426
+ }),
427
+ json: core_1.Flags.boolean({
428
+ char: 'j',
429
+ description: 'convert output in standard JSON format',
430
+ }),
431
+ unformatted: core_1.Flags.boolean({
432
+ char: 'u',
433
+ description: 'print unformatted JSON output',
434
+ dependsOn: ['json'],
435
+ }),
436
+ raw: core_1.Flags.boolean({
437
+ char: 'R',
438
+ description: 'print out the raw API response',
439
+ hidden: false,
440
+ }),
441
+ /*
442
+ doc: Flags.boolean({
443
+ description: 'show the CLI command in a specific language',
444
+ exclusive: ['raw'],
445
+ helpGroup: 'documentation',
446
+ }),
447
+ lang: Flags.string({
448
+ char: 'l',
449
+ description: 'show the CLI command in the specified language syntax',
450
+ exclusive: availableLanguages,
451
+ options: availableLanguages,
452
+ dependsOn: ['doc'],
453
+ helpGroup: 'documentation',
454
+ }),
455
+ curl: Flags.boolean({
456
+ description: `show the equivalent ${languageInfo.curl.label} of the CLI command`,
457
+ exclusive: ['lang', ...availableLanguages.filter(l => l !== 'curl')],
458
+ parse: async (): Promise<string> => await Promise.resolve('curl'),
459
+ hidden: !availableLanguages.includes('curl'),
460
+ dependsOn: ['doc'],
461
+ helpGroup: 'documentation',
462
+ }),
463
+ node: Flags.boolean({
464
+ description: `show the equivalent ${languageInfo.node.label} of the CLI command`,
465
+ exclusive: ['lang', ...availableLanguages.filter(l => l !== 'node')],
466
+ parse: async (): Promise<string> => await Promise.resolve('node'),
467
+ hidden: !availableLanguages.includes('node'),
468
+ dependsOn: ['doc'],
469
+ helpGroup: 'documentation',
470
+ }),
471
+ [FLAG_SAVE_PARAMS]: Flags.string({
472
+ description: 'save command data to file for future use',
473
+ }),
474
+ [FLAG_LOAD_PARAMS]: Flags.string({
475
+ description: 'load previously saved command arguments',
476
+ }),
477
+ */
478
+ headers: core_1.Flags.boolean({
479
+ char: 'H',
480
+ description: 'show response headers',
481
+ dependsOn: ['raw'],
482
+ exclusive: ['headers-only'],
483
+ }),
484
+ 'headers-only': core_1.Flags.boolean({
485
+ char: 'Y',
486
+ description: 'show only response headers',
487
+ dependsOn: ['raw'],
488
+ exclusive: ['headers', 'fields', 'include'],
489
+ }),
490
+ };
491
+ class default_1 extends BaseFilterCommand {
492
+ }
493
+ default_1.args = {
494
+ resource: core_1.Args.string({ name: 'resource', description: 'the resource type', required: true }),
495
+ };
496
+ exports.default = default_1;
@@ -0,0 +1,21 @@
1
+ import Command from '../../base';
2
+ export default class ProvisioningCreate extends Command {
3
+ static description: string;
4
+ static aliases: string[];
5
+ static examples: string[];
6
+ static flags: {
7
+ attribute: import("@oclif/core/lib/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
8
+ object: import("@oclif/core/lib/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
9
+ relationship: import("@oclif/core/lib/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
10
+ metadata: import("@oclif/core/lib/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
11
+ data: import("@oclif/core/lib/interfaces").OptionFlag<string | undefined, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
12
+ include: import("@oclif/core/lib/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
13
+ fields: import("@oclif/core/lib/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
14
+ json: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
15
+ unformatted: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
16
+ raw: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
17
+ headers: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
18
+ 'headers-only': import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
19
+ };
20
+ run(): Promise<any>;
21
+ }
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const base_1 = tslib_1.__importStar(require("../../base"));
5
+ const cli_core_1 = require("@commercelayer/cli-core");
6
+ // import { addRequestReader, isRequestInterrupted } from '../../lang'
7
+ // import { mergeCommandParams } from '../../commands'
8
+ const OPERATION = 'create';
9
+ class ProvisioningCreate extends base_1.default {
10
+ async run() {
11
+ const { args, flags } = await this.parse(ProvisioningCreate);
12
+ const resource = this.checkResource(args.resource, { singular: true });
13
+ // const loadParams = flags[FLAG_LOAD_PARAMS]
14
+ // const saveCmd = flags[FLAG_SAVE_PARAMS]
15
+ // if (saveCmd) this.checkAlias(saveCmd, resource.api, OPERATION, this.config)
16
+ const showHeaders = flags.headers || flags['headers-only'];
17
+ // Raw request
18
+ if (flags.data) {
19
+ try {
20
+ const baseUrl = cli_core_1.clApi.baseURL(undefined, flags.domain, true);
21
+ const accessToken = flags.accessToken;
22
+ const rawRes = await cli_core_1.clApi.request.raw({ operation: cli_core_1.clApi.Operation.Create, baseUrl, accessToken, resource: resource.api }, cli_core_1.clApi.request.readDataFile(flags.data));
23
+ const out = flags.raw ? rawRes : cli_core_1.clApi.response.denormalize(rawRes);
24
+ this.printOutput(out, flags);
25
+ this.log(`\n${cli_core_1.clColor.style.success('Successfully')} created new resource of type ${cli_core_1.clColor.style.resource(resource.api)} with id ${cli_core_1.clColor.style.id(rawRes.data.id)}\n`);
26
+ return out;
27
+ }
28
+ catch (error) {
29
+ this.printError(error, flags, args);
30
+ }
31
+ }
32
+ const cl = this.initCommerceLayer(flags);
33
+ // Attributes flags
34
+ const attributes = this.attributeFlag(flags.attribute);
35
+ // Objects flags
36
+ const objects = this.objectFlag(flags.object);
37
+ // Relationships flags
38
+ const relationships = this.relationshipFlag(flags.relationship);
39
+ // Metadata flags
40
+ const metadata = this.metadataFlag(flags.metadata, { fixTypes: true });
41
+ // Relationships
42
+ if (relationships && (Object.keys(relationships).length > 0))
43
+ Object.entries(relationships).forEach(([key, value]) => {
44
+ const relSdk = cl[value.type];
45
+ const rel = relSdk.relationship(value);
46
+ attributes[key] = rel;
47
+ });
48
+ // Objects
49
+ if (objects && (Object.keys(objects).length > 0)) {
50
+ for (const o of Object.keys(objects)) {
51
+ if (Object.keys(attributes).includes(o))
52
+ this.warn(`Object ${o} will overwrite attribute ${o}`);
53
+ else
54
+ attributes[o] = objects[o];
55
+ }
56
+ }
57
+ // Metadata
58
+ if (metadata && (Object.keys(metadata).length > 0)) {
59
+ if (attributes.metadata)
60
+ this.warn(`Attribute ${cli_core_1.clColor.style.attribute('metadata')} will be overwritten by the content defined with the flag ${cli_core_1.clColor.style.flag('-m')}`);
61
+ attributes.metadata = metadata;
62
+ }
63
+ // Include flags
64
+ const include = this.includeFlag(flags.include, relationships);
65
+ // Fields flags
66
+ const fields = this.fieldsFlag(flags.fields, resource.api);
67
+ const rawReader = flags.raw ? cl.addRawResponseReader({ headers: showHeaders }) : undefined;
68
+ // const reqReader = flags.doc ? addRequestReader(cl) : undefined
69
+ const params = {};
70
+ try {
71
+ const resSdk = cl[resource.api];
72
+ this.checkOperation(resSdk, OPERATION);
73
+ if (include && (include.length > 0))
74
+ params.include = include;
75
+ if (fields && (Object.keys(fields).length > 0))
76
+ params.fields = fields;
77
+ // Load saved command arguments
78
+ // if (loadParams) {
79
+ // const savedParams = this.loadParams(loadParams, resource.api, OPERATION)
80
+ // if (savedParams) mergeCommandParams(params, savedParams)
81
+ // }
82
+ const res = await resSdk.create(attributes, params);
83
+ const out = (flags.raw && rawReader) ? rawReader.rawResponse : res;
84
+ this.printHeaders(rawReader?.headers, flags);
85
+ this.printOutput(out, flags);
86
+ this.log(`\n${cli_core_1.clColor.style.success('Successfully')} created new resource of type ${cli_core_1.clColor.style.resource(resource.api)} with id ${cli_core_1.clColor.style.id(res.id)}\n`);
87
+ // Save command arguments
88
+ // if (saveCmd) this.saveParams(saveCmd, { type: resource.api }, OPERATION, params)
89
+ return out;
90
+ }
91
+ catch (error) {
92
+ /*
93
+ if (isRequestInterrupted(error) && reqReader) {
94
+ await this.showLiveDocumentation(reqReader.request, params, flags)
95
+ cl.removeInterceptor('request', reqReader.id)
96
+ } else */ this.printError(error);
97
+ }
98
+ }
99
+ }
100
+ ProvisioningCreate.description = 'create a new resource';
101
+ ProvisioningCreate.aliases = ['prov:create', 'pc', 'pcreate'];
102
+ ProvisioningCreate.examples = [
103
+ '$ commercelayer provisioning:create organizations -a name=MyOrg',
104
+ '$ clayer prov:create subscriptions -r plan=plans/<planId>',
105
+ '$ cl prov:create organization -a name=MyOrg -m meta_key="meta value"',
106
+ '$ cl pc roles -D /path/to/data/file/data.json',
107
+ ];
108
+ ProvisioningCreate.flags = {
109
+ ...base_1.default.flags,
110
+ attribute: base_1.Flags.string({
111
+ char: 'a',
112
+ description: 'define a resource attribute',
113
+ multiple: true,
114
+ }),
115
+ object: base_1.Flags.string({
116
+ char: 'O',
117
+ description: 'define a resource object attribute',
118
+ multiple: true,
119
+ }),
120
+ relationship: base_1.Flags.string({
121
+ char: 'r',
122
+ description: 'define a relationship with another resource',
123
+ multiple: true,
124
+ }),
125
+ metadata: base_1.Flags.string({
126
+ char: 'm',
127
+ description: 'define a metadata attribute or a set of metadata attributes',
128
+ multiple: true,
129
+ }),
130
+ data: base_1.Flags.string({
131
+ char: 'D',
132
+ description: 'the data file to use as request body',
133
+ multiple: false,
134
+ exclusive: ['attribute', 'relationship', 'metadata', 'doc' /* , FLAG_LOAD_PARAMS, FLAG_SAVE_PARAMS */],
135
+ })
136
+ };
137
+ exports.default = ProvisioningCreate;
@@ -0,0 +1,20 @@
1
+ import Command from '../../base';
2
+ export default class ProvisioningDelete extends Command {
3
+ static description: string;
4
+ static aliases: string[];
5
+ static examples: string[];
6
+ static flags: {
7
+ include: import("@oclif/core/lib/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
8
+ fields: import("@oclif/core/lib/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
9
+ json: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
10
+ unformatted: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
11
+ raw: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
12
+ headers: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
13
+ 'headers-only': import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
14
+ };
15
+ static args: {
16
+ id: import("@oclif/core/lib/interfaces/parser").Arg<string | undefined, Record<string, unknown>>;
17
+ resource: import("@oclif/core/lib/interfaces/parser").Arg<string, Record<string, unknown>>;
18
+ };
19
+ run(): Promise<any>;
20
+ }