@contrail/cli 3.6.0-alpha-8-alpha.694fd70 → 3.6.0-alpha-8-alpha.351376b

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 (63) hide show
  1. package/README.md +80 -58
  2. package/dist/api/feature-flags.d.ts +3 -0
  3. package/dist/api/feature-flags.js +29 -0
  4. package/dist/api/users.d.ts +1 -0
  5. package/dist/api/users.js +10 -1
  6. package/dist/auth/login.js +41 -24
  7. package/dist/auth/login.spec.js +124 -0
  8. package/dist/basecommand.js +1 -1
  9. package/dist/commands/app/getApiKey.js +2 -2
  10. package/dist/commands/entities/create.d.ts +1 -12
  11. package/dist/commands/entities/create.js +30 -93
  12. package/dist/commands/entities/create.spec.js +3 -28
  13. package/dist/commands/entities/delete.d.ts +2 -5
  14. package/dist/commands/entities/delete.js +52 -68
  15. package/dist/commands/entities/get.d.ts +0 -3
  16. package/dist/commands/entities/get.js +15 -63
  17. package/dist/commands/entities/update.d.ts +2 -14
  18. package/dist/commands/entities/update.js +44 -77
  19. package/dist/commands/feature-flags/export.d.ts +19 -0
  20. package/dist/commands/feature-flags/export.js +66 -0
  21. package/dist/commands/feature-flags/export.spec.js +109 -0
  22. package/dist/commands/feature-flags/import.d.ts +42 -0
  23. package/dist/commands/feature-flags/import.js +191 -0
  24. package/dist/commands/feature-flags/import.spec.js +194 -0
  25. package/dist/commands/instance/export.d.ts +9 -0
  26. package/dist/commands/instance/export.js +18 -3
  27. package/dist/commands/instance/export.spec.js +32 -0
  28. package/dist/commands/instance/import.d.ts +3 -0
  29. package/dist/commands/instance/import.js +5 -0
  30. package/dist/commands/instance/import.spec.js +4 -0
  31. package/dist/common.d.ts +0 -2
  32. package/dist/common.js +1 -13
  33. package/dist/helpers/config/config.d.ts +2 -0
  34. package/dist/helpers/config/config.js +6 -1
  35. package/dist/helpers/propertySpecifications/propertySpecifications.d.ts +0 -8
  36. package/dist/helpers/propertySpecifications/propertySpecifications.js +9 -21
  37. package/dist/helpers/propertySpecifications/propertySpecifications.spec.js +10 -20
  38. package/dist/logger.js +1 -4
  39. package/node_modules/@contrail/entity-compare/package.json +3 -6
  40. package/node_modules/@contrail/loader/lib/common/conditional-columns.js +1 -1
  41. package/node_modules/@contrail/loader/lib/constants.d.ts +8 -0
  42. package/node_modules/@contrail/loader/lib/constants.js +9 -1
  43. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.d.ts +4 -0
  44. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.js +57 -0
  45. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.spec.js +492 -34
  46. package/node_modules/@contrail/loader/lib/pipeline/validate.js +2 -52
  47. package/node_modules/@contrail/loader/lib/pipeline/validate.spec.js +0 -85
  48. package/node_modules/@contrail/loader/package.json +2 -2
  49. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/image-search/image-search.d.ts +34 -0
  50. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/image-search/image-search.js +42 -0
  51. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/image-search/index.d.ts +1 -0
  52. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/image-search/index.js +17 -0
  53. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/index.d.ts +1 -0
  54. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/lib/index.js +1 -0
  55. package/node_modules/@contrail/org-config-migration/node_modules/@contrail/sdk/package.json +1 -1
  56. package/oclif.manifest.json +137 -99
  57. package/package.json +4 -1
  58. package/dist/commands/entities/grammar.spec.js +0 -80
  59. package/dist/commands/entities/output.spec.js +0 -72
  60. package/dist/logger.spec.js +0 -12
  61. /package/dist/commands/{entities/grammar.spec.d.ts → feature-flags/export.spec.d.ts} +0 -0
  62. /package/dist/commands/{entities/output.spec.d.ts → feature-flags/import.spec.d.ts} +0 -0
  63. /package/dist/{logger.spec.d.ts → commands/instance/export.spec.d.ts} +0 -0
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.doesPropertyLevelMatchRole = exports.selectRandomObject = exports.buildObjectReferenceCache = exports.getReferencedObjectPaths = exports.castValueToPropertyType = exports.pickRandomValueForProperty = exports.summarizeSettledCreates = void 0;
3
+ exports.doesPropertyLevelMatchRole = exports.selectRandomObject = exports.buildObjectReferenceCache = exports.getReferencedObjectPaths = exports.pickRandomValueForProperty = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const fs_1 = tslib_1.__importDefault(require("fs"));
6
6
  const unique_names_generator_1 = require("unique-names-generator");
@@ -10,7 +10,6 @@ const types_2 = require("../../api/types");
10
10
  const core_1 = require("@oclif/core");
11
11
  const types_3 = require("../../api/types");
12
12
  const login_1 = require("../../auth/login");
13
- const common_1 = require("../../common");
14
13
  const basecommand_1 = require("../../basecommand");
15
14
  const sdk_1 = require("@contrail/sdk");
16
15
  const entities_1 = require("../../helpers/entities");
@@ -27,7 +26,7 @@ const baseValidationMap = {
27
26
  itemId: async (_slug, itemId) => (0, entities_1.throwIfInvalidItemId)(itemId),
28
27
  projectId: async (_slug, projectId) => (0, entities_1.throwIfInvalidProjectId)(projectId),
29
28
  };
30
- const throwIfInvalidPropertyLevelFn = async (_slug, maybeRoles) => [].concat(maybeRoles).forEach((maybeRole) => (0, entities_1.throwIfInvalidItemLevel)(maybeRole));
29
+ const throwIfInvalidPropertyLevelFn = async (_slug, maybeRoles) => maybeRoles.forEach((maybeRole) => (0, entities_1.throwIfInvalidItemLevel)(maybeRole));
31
30
  const throwIfInvalidUserOrgRoleFn = async (_slug, maybeRole) => {
32
31
  if (maybeRole !== 'MEMBER' && maybeRole !== 'ADMIN') {
33
32
  throw new Error(`${maybeRole} is not a valid User Org Role`); // TODO: get these roles from a shared library
@@ -145,7 +144,7 @@ const FIND_VALID_VALUE_MAP = {
145
144
  ],
146
145
  };
147
146
  class CreateEntity extends basecommand_1.BaseCommand {
148
- static description = 'Create entities';
147
+ static description = '(BETA) Create entities';
149
148
  static examples = [
150
149
  'contrail entities create color -g -n=10 # creates 10 random colors',
151
150
  'contrail entities create color -- name="Electric Blue" green=1 red=2 blue=3 # creates one color with specified properties only',
@@ -195,20 +194,11 @@ class CreateEntity extends basecommand_1.BaseCommand {
195
194
  default: false,
196
195
  }),
197
196
  skipHydrateRelationships: core_1.Flags.boolean({
198
- char: 'S',
197
+ char: 's',
199
198
  description: 'If true, does not hydrate relationships for the created entities',
200
199
  required: false,
201
200
  default: false,
202
201
  }),
203
- suffix: core_1.Flags.string({
204
- description: 'Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets /<entities>/synchronous)',
205
- required: false,
206
- }),
207
- apiVersion: core_1.Flags.string({
208
- description: 'Api-Version header to send; selects the V1 or V2 variant of the endpoint',
209
- options: ['1', '2'],
210
- required: false,
211
- }),
212
202
  };
213
203
  static args = {
214
204
  path: core_1.Args.string({
@@ -219,10 +209,10 @@ class CreateEntity extends basecommand_1.BaseCommand {
219
209
  };
220
210
  static strict = false;
221
211
  async run() {
222
- (0, common_1.routeConsoleLogToStderr)();
212
+ this.log('🚨 This command is in BETA and may change or be removed at any time.');
223
213
  await (0, login_1.authUser)();
224
214
  const { flags, argv, args } = await this.parse(CreateEntity);
225
- const { count, dryRun: isDryRun, inputFile: inputFilename, outputFile: outputFilename, generateValues: shouldGenerateMissingValues, readableIds: shouldUseReadableIds, skipHydrateRelationships, suffix, apiVersion, } = flags;
215
+ const { count, dryRun: isDryRun, inputFile: inputFilename, outputFile: outputFilename, generateValues: shouldGenerateMissingValues, readableIds: shouldUseReadableIds, skipHydrateRelationships, } = flags;
226
216
  const { path: entityTypePath } = args;
227
217
  // Global flags is a little hacky, but it was easier
228
218
  // and it doesn't see *that* bad because they are only valid
@@ -231,11 +221,10 @@ class CreateEntity extends basecommand_1.BaseCommand {
231
221
  SHOULD_USE_READABLE_IDS = shouldUseReadableIds;
232
222
  SHOULD_SKIP_HYDRATE_RELATIONSHIPS = skipHydrateRelationships;
233
223
  SHOULD_GENERATE_MISSING_VALUES = shouldGenerateMissingValues;
234
- const { ids: strayTokens, specs } = (0, propertySpecifications_1.partitionIdsAndSpecs)(argv.slice(1));
235
- if (strayTokens.length > 0) {
236
- this.error(`create takes no positional ids (got: ${strayTokens.join(' ')}); did you forget -- before property values?`);
237
- }
238
- const propertySpecBySlug = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
224
+ const propertySpecificationArgs = argv
225
+ .slice(1, argv.length)
226
+ .filter(propertySpecifications_1.isValidPropertySpecification);
227
+ const propertySpecBySlug = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(propertySpecificationArgs);
239
228
  // Validate args
240
229
  if (!entityTypePath) {
241
230
  this.error('You must specify an entity type path.');
@@ -268,20 +257,13 @@ class CreateEntity extends basecommand_1.BaseCommand {
268
257
  }
269
258
  try {
270
259
  const entitiesToCreate = await buildEntitiesToCreate(entityTypePath, partialEntities, propertySpecBySlug);
271
- const summary = await createEntities(entityName, entitiesToCreate, {
272
- suffix,
273
- apiVersion: apiVersion,
274
- });
260
+ const createdEntities = await createEntities(entityName, entitiesToCreate);
275
261
  if (outputFilename) {
276
- fs_1.default.writeFileSync(outputFilename, JSON.stringify(summary, null, 2));
277
- console.error(`Output saved to ${outputFilename}`);
262
+ fs_1.default.writeFileSync(outputFilename, JSON.stringify(createdEntities, null, 2));
263
+ this.log(`Output saved to ${outputFilename}`);
278
264
  }
279
265
  else {
280
- this.log(JSON.stringify(summary, null, 2));
281
- }
282
- if (summary.failed.length > 0) {
283
- console.error(`${summary.failed.length} of ${entitiesToCreate.length} entities failed.`);
284
- process.exitCode = 1;
266
+ console.log(`Created ${entityTypePath}(s), Entity: ${JSON.stringify(createdEntities, null, 2)}`);
285
267
  }
286
268
  }
287
269
  catch (error) {
@@ -290,28 +272,15 @@ class CreateEntity extends basecommand_1.BaseCommand {
290
272
  }
291
273
  }
292
274
  exports.default = CreateEntity;
293
- function summarizeSettledCreates(inputs, settled) {
294
- const created = [];
295
- const failed = [];
296
- settled.forEach((result, index) => {
297
- if (result.status === 'fulfilled') {
298
- created.push(result.value);
299
- }
300
- else {
301
- failed.push({ input: inputs[index], error: (0, common_1.sdkErrorMessage)(result.reason) });
302
- }
303
- });
304
- return { created, failed };
305
- }
306
- exports.summarizeSettledCreates = summarizeSettledCreates;
307
- async function createEntities(entityName, entities, routing = {}) {
275
+ async function createEntities(entityName, entities) {
276
+ const limit = (0, p_limit_1.default)(20);
277
+ const createdEntities = IS_DRY_RUN
278
+ ? entities
279
+ : await Promise.allSettled(entities.map(async (e) => limit(() => createEntity(entityName, e))));
308
280
  if (IS_DRY_RUN) {
309
- console.error(`Dry run mode: not creating entities, but simulating creation for ${entityName}`);
310
- return { created: entities, failed: [] };
281
+ console.log(`Dry run mode: not creating entities, but simulating creation for ${entityName}`);
311
282
  }
312
- const limit = (0, p_limit_1.default)(20);
313
- const settled = await Promise.allSettled(entities.map(async (e) => limit(() => createEntity(entityName, e, routing))));
314
- return summarizeSettledCreates(entities, settled);
283
+ return createdEntities;
315
284
  }
316
285
  async function buildEntitiesToCreate(entityTypePath, entities, propertySpecificationBySlug) {
317
286
  let type = await (0, types_3.getTypeByPath)(entityTypePath);
@@ -334,7 +303,7 @@ async function buildEntitiesToCreate(entityTypePath, entities, propertySpecifica
334
303
  await Promise.all(populatedEntities.map(async () => limit(() => throwIfEntityIsInvalid)));
335
304
  // Skip system value generation unless -g flag is set (generateValues mode)
336
305
  if (!SHOULD_GENERATE_MISSING_VALUES) {
337
- console.error('Using only specified properties. Use --generate-values to auto-generate missing values.');
306
+ console.log('Using only specified properties. Use --generate-values to auto-generate missing values.');
338
307
  return populatedEntities;
339
308
  }
340
309
  // Add system values if needed
@@ -343,13 +312,13 @@ async function buildEntitiesToCreate(entityTypePath, entities, propertySpecifica
343
312
  for (const { slug, findValidValuesFn, applyValueToEntityFn } of valueFinderApplierForEntity) {
344
313
  // If the property is already specified in command-line args, skip it
345
314
  if (propertySpecificationBySlug?.has(slug)) {
346
- console.error(`Skipping property ${slug} because it is already specified.`);
315
+ console.log(`Skipping property ${slug} because it is already specified.`);
347
316
  continue;
348
317
  }
349
318
  // If all entities already have this property, skip finding values
350
319
  const allEntitiesHaveProperty = populatedEntities.every((entity) => entity[slug] !== undefined && entity[slug] !== null);
351
320
  if (allEntitiesHaveProperty) {
352
- console.error(`Skipping property ${slug} because all entities already have this value.`);
321
+ console.log(`Skipping property ${slug} because all entities already have this value.`);
353
322
  continue;
354
323
  }
355
324
  const values = await findValidValuesFn(populatedEntities, entities.length);
@@ -363,18 +332,15 @@ async function buildEntitiesToCreate(entityTypePath, entities, propertySpecifica
363
332
  return populatedEntities;
364
333
  }
365
334
  function createEntityWithPopulatedValues(type, typeReferencesCache, objectReferencesCache, propertySpecificationBySlug) {
366
- const rolesValue = propertySpecificationBySlug?.get('roles');
367
- const roles = rolesValue === undefined ? undefined : [].concat(rolesValue);
335
+ const roles = propertySpecificationBySlug?.get('roles');
368
336
  const entity = SHOULD_GENERATE_MISSING_VALUES
369
337
  ? pickRandomPropertyValues(type, objectReferencesCache, typeReferencesCache, roles)
370
338
  : {};
371
339
  // Handle property specifications
372
340
  for (const [propertySlug, specifiedValue] of propertySpecificationBySlug.entries()) {
373
341
  const correspondingProperty = type.typeProperties.find((prop) => getPropertySlug(prop) === propertySlug);
374
- // slug= means unset; on create there is nothing to unset, so skip it.
375
- // slug='""' is the empty string and is written like any other value.
376
- if (specifiedValue === undefined) {
377
- continue;
342
+ if (!specifiedValue) {
343
+ throw new Error(`Value for property ${propertySlug} is required`);
378
344
  }
379
345
  entity[propertySlug] = castValueToPropertyType(specifiedValue, correspondingProperty?.propertyType || types_1.PropertyType.String);
380
346
  }
@@ -382,16 +348,6 @@ function createEntityWithPopulatedValues(type, typeReferencesCache, objectRefere
382
348
  if (SHOULD_USE_READABLE_IDS) {
383
349
  entity.specifiedId = generateRandomReadableString();
384
350
  }
385
- // roles is a multi-value system property with no type property to drive
386
- // coercion; a single value still has to reach the API as an array
387
- if (typeof entity.roles === 'string') {
388
- if (entity.roles.includes(',')) {
389
- console.error(`roles value "${entity.roles}" contains a comma and is treated as one literal value. To pass several roles, repeat the key: roles=${entity.roles
390
- .split(',')
391
- .join(' roles=')}`);
392
- }
393
- entity.roles = [entity.roles];
394
- }
395
351
  // Support specifiedId
396
352
  if (propertySpecificationBySlug?.has('specifiedId')) {
397
353
  const specifiedId = propertySpecificationBySlug.get('specifiedId');
@@ -534,35 +490,16 @@ function castValueToPropertyType(value, propertyType) {
534
490
  return numValue;
535
491
  case types_1.PropertyType.Date:
536
492
  return new Date(value.toString()).toISOString();
537
- case types_1.PropertyType.MultiSelect:
538
- if (Array.isArray(value)) {
539
- return value;
540
- }
541
- // the old comma syntax parses as one literal value; warn instead of guessing at a split
542
- if (typeof value === 'string' && value.includes(',')) {
543
- console.error(`Value "${value}" for a multi-value property contains a comma and is treated as one literal value. To pass several values, repeat the key: slug=${value
544
- .split(',')
545
- .join(' slug=')}`);
546
- }
547
- return [value];
548
493
  default:
549
494
  return value; // For string and other types, return as is
550
495
  }
551
496
  }
552
- exports.castValueToPropertyType = castValueToPropertyType;
553
- async function createEntity(entityName, entity, routing = {}) {
497
+ async function createEntity(entityName, entity) {
554
498
  const client = new sdk_1.Entities();
555
499
  const skipHydrateRelationships = SHOULD_SKIP_HYDRATE_RELATIONSHIPS;
556
- const { suffix, apiVersion } = routing;
557
- if (entityName === 'assortment-item' && !suffix)
500
+ if (entityName === 'assortment-item')
558
501
  return (0, entities_1.createAssortmentItem)(entity, { skipHydrateRelationships }); // special case
559
- const response = await client.create({
560
- entityName,
561
- object: entity,
562
- skipHydrateRelationships,
563
- suffix,
564
- apiVersion,
565
- });
502
+ const response = await client.create({ entityName, object: entity, skipHydrateRelationships });
566
503
  return response;
567
504
  }
568
505
  function getReferencedObjectPaths(type) {
@@ -270,8 +270,8 @@ describe('Entity Creation E2E Happy Path', () => {
270
270
  expect(result.get('quantity')).toBe('10');
271
271
  expect(result.get('isActive')).toBe('true');
272
272
  });
273
- it('should build roles arrays from repeated keys', () => {
274
- const specs = ['roles=option', 'roles=family', 'name=Test'];
273
+ it('should handle roles as comma-separated array', () => {
274
+ const specs = ['roles=option,family', 'name=Test'];
275
275
  const result = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
276
276
  expect(result.get('roles')).toEqual(['option', 'family']);
277
277
  expect(result.get('name')).toBe('Test');
@@ -333,7 +333,7 @@ describe('Entity Creation E2E Happy Path', () => {
333
333
  const propertySpecs = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)([
334
334
  'roles=option',
335
335
  ]);
336
- const roles = [].concat(propertySpecs.get('roles'));
336
+ const roles = propertySpecs.get('roles');
337
337
  // Test that property level matching works with specified roles
338
338
  expect((0, create_1.doesPropertyLevelMatchRole)(types_1.PropertyLevel.OPTION, roles[0])).toBe(true);
339
339
  expect((0, create_1.doesPropertyLevelMatchRole)(types_1.PropertyLevel.FAMILY, roles[0])).toBe(false);
@@ -514,28 +514,3 @@ describe('Entity Creation E2E Happy Path', () => {
514
514
  });
515
515
  });
516
516
  });
517
- describe('castValueToPropertyType array coercion', () => {
518
- it('should coerce a single value on a multi-value property to a one-element array', () => {
519
- expect((0, create_1.castValueToPropertyType)('option', types_1.PropertyType.MultiSelect)).toEqual(['option']);
520
- });
521
- it('should pass arrays through on multi-value properties', () => {
522
- expect((0, create_1.castValueToPropertyType)(['option', 'family'], types_1.PropertyType.MultiSelect)).toEqual([
523
- 'option',
524
- 'family',
525
- ]);
526
- });
527
- it('should keep a comma value literal on a multi-value property and warn with the repeated-key form', () => {
528
- const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined);
529
- expect((0, create_1.castValueToPropertyType)('option,family', types_1.PropertyType.MultiSelect)).toEqual([
530
- 'option,family',
531
- ]);
532
- expect(consoleError).toHaveBeenCalledWith(expect.stringContaining('slug=option slug=family'));
533
- consoleError.mockRestore();
534
- });
535
- it('should keep commas literal on string properties without warning', () => {
536
- const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined);
537
- expect((0, create_1.castValueToPropertyType)('my,name', types_1.PropertyType.String)).toBe('my,name');
538
- expect(consoleError).not.toHaveBeenCalled();
539
- consoleError.mockRestore();
540
- });
541
- });
@@ -4,16 +4,13 @@ export default class DeleteEntity extends BaseCommand {
4
4
  static examples: string[];
5
5
  static flags: {
6
6
  dryRun: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
7
- inputFile: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
8
- suffix: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
9
- apiVersion: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
7
+ input: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
8
+ id: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
10
9
  alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
11
10
  logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
12
11
  };
13
12
  static args: {
14
13
  entityName: import("@oclif/core/lib/interfaces/parser").Arg<string, Record<string, unknown>>;
15
- ids: import("@oclif/core/lib/interfaces/parser").Arg<string, Record<string, unknown>>;
16
14
  };
17
- static strict: boolean;
18
15
  run(): Promise<void>;
19
16
  }
@@ -6,37 +6,27 @@ const p_limit_1 = tslib_1.__importDefault(require("p-limit"));
6
6
  const basecommand_1 = require("../../basecommand");
7
7
  const sdk_1 = require("@contrail/sdk");
8
8
  const login_1 = require("../../auth/login");
9
- const common_1 = require("../../common");
10
9
  const file_helpers_1 = require("../../helpers/file-helpers");
11
10
  let IS_DRY_RUN = false;
12
11
  class DeleteEntity extends basecommand_1.BaseCommand {
13
- static description = 'Delete entities by id';
14
- static examples = [
15
- 'contrail entities delete color 123',
16
- 'contrail entities delete color id1 id2 id3',
17
- 'contrail entities delete item -i ids.json',
18
- ];
12
+ static description = '(BETA) Delete an entity';
13
+ static examples = ['contrail entities delete color 123'];
19
14
  static flags = {
20
15
  ...basecommand_1.BaseCommand.baseFlags,
21
16
  dryRun: core_1.Flags.boolean({
22
17
  char: 'd',
23
- description: 'If true, does not delete the entities but simulates the deletion',
18
+ description: 'If true, does not delete the entity but simulates the deletion',
24
19
  required: false,
25
20
  default: false,
26
21
  }),
27
- inputFile: core_1.Flags.string({
22
+ input: core_1.Flags.string({
28
23
  char: 'i',
29
- description: "A file with a JSON array of objects; only each object's id is used. Deletes every entity in the file.",
24
+ description: 'A JSON array of objects where each object is one entity to create. Cannot be used with --count. Unless --precise is specified, any missing values will be populated with random values.',
30
25
  required: false,
31
26
  multiple: false,
32
27
  }),
33
- suffix: core_1.Flags.string({
34
- description: 'Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets /<entities>/synchronous)',
35
- required: false,
36
- }),
37
- apiVersion: core_1.Flags.string({
38
- description: 'Api-Version header to send; selects the V1 or V2 variant of the endpoint',
39
- options: ['1', '2'],
28
+ id: core_1.Flags.string({
29
+ description: 'The unique identifier of the entity',
40
30
  required: false,
41
31
  }),
42
32
  };
@@ -45,90 +35,84 @@ class DeleteEntity extends basecommand_1.BaseCommand {
45
35
  description: 'The name of the entity type to delete',
46
36
  required: true,
47
37
  }),
48
- ids: core_1.Args.string({
49
- description: 'One or more entity ids to delete',
50
- required: false,
51
- }),
52
38
  };
53
- static strict = false;
54
39
  async run() {
55
- (0, common_1.routeConsoleLogToStderr)();
40
+ this.log('🚨 This command is in BETA and may change or be removed at any time.');
56
41
  await (0, login_1.authUser)();
57
- const { args, flags, argv } = await this.parse(DeleteEntity);
42
+ const { args, flags } = await this.parse(DeleteEntity);
58
43
  const { entityName } = args;
59
- const { inputFile: inputFilename, suffix, apiVersion } = flags;
44
+ const { id, input: inputFilename } = flags;
60
45
  if (flags.dryRun) {
61
46
  IS_DRY_RUN = true;
62
- console.error('Running in dry run mode. No entities will be deleted.');
63
- }
64
- const tokens = argv.slice(1);
65
- const valueTokens = tokens.filter((token) => token.includes('='));
66
- if (valueTokens.length > 0) {
67
- this.error(`delete takes no -- values (got: ${valueTokens.join(' ')}); pass ids positionally or use an input file (-i).`);
68
- }
69
- const positionalIds = tokens;
70
- if (inputFilename && positionalIds.length > 0) {
71
- this.error('You cannot use --inputFile and positional ids together. Please specify one or the other.');
72
- }
73
- if (!inputFilename && positionalIds.length === 0) {
74
- this.error('You must provide one or more ids or an input file (-i) of entities to delete.');
47
+ this.log('Running in dry run mode. No entities will be deleted.');
75
48
  }
76
49
  const jsonInput = inputFilename ? (0, file_helpers_1.parseFileAsJsonArray)(inputFilename) : undefined;
77
- const rowsWithId = jsonInput?.filter((item) => item.id);
78
- if (jsonInput && rowsWithId.length < jsonInput.length) {
79
- console.error(`${jsonInput.length - rowsWithId.length} row(s) without an id were skipped.`);
50
+ if (!jsonInput && !id) {
51
+ this.error('You must provide either an ID or a JSON input file with entities to delete.');
80
52
  }
81
- const ids = rowsWithId ? rowsWithId.map((item) => item.id) : positionalIds;
53
+ const ids = jsonInput ? jsonInput.map((item) => item.id) : [id];
82
54
  try {
83
- const response = await deleteEntityByIds(entityName, ids, {
84
- suffix,
85
- apiVersion: apiVersion,
86
- });
55
+ const response = await deleteEntityByIds(entityName, ids);
87
56
  if (IS_DRY_RUN) {
88
- console.error('simulated deletion of entities:');
57
+ this.log('simulated deletion of entities:');
89
58
  }
90
59
  else {
91
- console.error('deleted entities:');
60
+ this.log('deleted entities:');
92
61
  }
93
62
  this.log(JSON.stringify(response, null, 2));
94
- if (response.failed.length > 0) {
95
- console.error(`${response.failed.length} of ${ids.length} deletes failed.`);
96
- process.exitCode = 1;
97
- }
98
63
  }
99
64
  catch (e) {
100
- this.error(`Error deleting entities: ${e.message}`);
65
+ this.error(`Error fetching entity: ${e.message}`);
101
66
  }
102
67
  }
103
68
  }
104
69
  exports.default = DeleteEntity;
105
- async function deleteEntityByIds(entityName, ids, routing = {}) {
106
- const deletedIds = [];
107
- const notFoundIds = [];
108
- const failed = [];
70
+ async function deleteEntityByIds(entityName, ids) {
71
+ const idsDeleted = new Set();
72
+ const idsNotFound = new Set();
73
+ const idsErrored = new Set();
109
74
  const limit = (0, p_limit_1.default)(10);
110
- const deletePromises = ids.map((id) => limit(() => deleteEntityById(entityName, id, routing).then((entity) => {
75
+ const deletePromises = ids.map((id) => limit(() => deleteEntityById(entityName, id).then((entity) => {
111
76
  if (!entity) {
112
- notFoundIds.push(id);
113
- return;
77
+ idsNotFound.add(id);
78
+ return null;
114
79
  }
115
- deletedIds.push(id);
80
+ idsDeleted.add(id);
81
+ return entity;
116
82
  }, (error) => {
117
83
  if (error.message.includes('not found')) {
118
- notFoundIds.push(id);
84
+ idsNotFound.add(id);
119
85
  }
120
86
  else {
121
- failed.push({ id, error: (0, common_1.sdkErrorMessage)(error) });
87
+ idsErrored.add(id);
122
88
  }
89
+ return null;
123
90
  })));
124
91
  await Promise.all(deletePromises);
125
- return { deletedIds, notFoundIds, failed };
92
+ return {
93
+ idsDeleted: Array.from(idsDeleted),
94
+ idsNotFound: Array.from(idsNotFound),
95
+ idsErrored: Array.from(idsErrored),
96
+ };
126
97
  }
127
- async function deleteEntityById(entityName, id, routing = {}) {
98
+ async function deleteEntityById(entityName, id) {
128
99
  const client = new sdk_1.Entities();
129
100
  if (IS_DRY_RUN) {
130
- return client.get({ entityName, id, ignore404: true });
101
+ return client.get({ entityName, id, ignore404: true }).catch(throwIfNot404);
102
+ }
103
+ return client.delete({ entityName, id, ignore404: true }).catch(throwIfNot404);
104
+ }
105
+ function throwIfNot404(e) {
106
+ const { statusCode } = parseSDKErrorMessage(e);
107
+ if (statusCode === 404) {
108
+ return null;
131
109
  }
132
- const { suffix, apiVersion } = routing;
133
- return client.delete({ entityName, id, ignore404: true, suffix, apiVersion });
110
+ throw e;
111
+ }
112
+ function parseSDKErrorMessage(e) {
113
+ const parsed = JSON.parse(e.details);
114
+ return {
115
+ statusCode: parsed.statusCode,
116
+ message: parsed.message,
117
+ };
134
118
  }
@@ -10,14 +10,11 @@ export default class GetEntity extends BaseCommand {
10
10
  skipHydrateRelationships: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
11
11
  take: import("@oclif/core/lib/interfaces").OptionFlag<number, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
12
12
  relations: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
13
- suffix: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
14
- apiVersion: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
15
13
  alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
16
14
  logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
17
15
  };
18
16
  static args: {
19
17
  typePath: import("@oclif/core/lib/interfaces/parser").Arg<string, Record<string, unknown>>;
20
- ids: import("@oclif/core/lib/interfaces/parser").Arg<string, Record<string, unknown>>;
21
18
  };
22
19
  static strict: boolean;
23
20
  run(): Promise<void>;