@contrail/cli 3.6.0-alpha-8-alpha.c613d8e → 3.6.0-alpha-8-alpha.a097890

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.
package/README.md CHANGED
@@ -17,7 +17,7 @@ $ npm install -g @contrail/cli
17
17
  $ contrail COMMAND
18
18
  running command...
19
19
  $ contrail (--version)
20
- @contrail/cli/3.6.0-alpha-8-alpha.c613d8e linux-x64 node-v24.22.1
20
+ @contrail/cli/3.6.0-alpha-8-alpha.a097890 linux-x64 node-v24.22.1
21
21
  $ contrail --help [COMMAND]
22
22
  USAGE
23
23
  $ contrail COMMAND
@@ -52,9 +52,9 @@ To get instructions on how to set up autocomplete for your shell, run `contrail
52
52
  * [`contrail config set`](#contrail-config-set)
53
53
  * [`contrail config use [NAME]`](#contrail-config-use-name)
54
54
  * [`contrail entities create PATH`](#contrail-entities-create-path)
55
- * [`contrail entities delete ENTITYNAME`](#contrail-entities-delete-entityname)
56
- * [`contrail entities get TYPEPATH`](#contrail-entities-get-typepath)
57
- * [`contrail entities update ENTITYNAME [ID]`](#contrail-entities-update-entityname-id)
55
+ * [`contrail entities delete ENTITYNAME [IDS]`](#contrail-entities-delete-entityname-ids)
56
+ * [`contrail entities get TYPEPATH [IDS]`](#contrail-entities-get-typepath-ids)
57
+ * [`contrail entities update ENTITYNAME [IDS]`](#contrail-entities-update-entityname-ids)
58
58
  * [`contrail feature-flags export`](#contrail-feature-flags-export)
59
59
  * [`contrail feature-flags import`](#contrail-feature-flags-import)
60
60
  * [`contrail file upload FILELOCATION CONTENTTYPE`](#contrail-file-upload-filelocation-contenttype)
@@ -545,17 +545,18 @@ EXAMPLES
545
545
 
546
546
  ## `contrail entities create PATH`
547
547
 
548
- (BETA) Create entities
548
+ Create entities
549
549
 
550
550
  ```
551
551
  USAGE
552
552
  $ contrail entities create PATH [-l error|warn|info|debug] [-e true|false] [-n <value>] [-d] [-i <value>] [-o
553
- <value>] [-g] [-r] [-s]
553
+ <value>] [-g] [-r] [-S] [--suffix <value>] [--apiVersion 1|2]
554
554
 
555
555
  ARGUMENTS
556
556
  PATH Path of the entity type to create
557
557
 
558
558
  FLAGS
559
+ -S, --skipHydrateRelationships If true, does not hydrate relationships for the created entities
559
560
  -d, --dryRun If true, does not create the entity but simulates the creation
560
561
  -e, --alwaysConfirmEnv=<option> [default: true] The Environment variables
561
562
  <options: true|false>
@@ -569,10 +570,13 @@ FLAGS
569
570
  -n, --count=<value> Number of random entities to create
570
571
  -o, --outputFile=<value> File to save the output (optional)
571
572
  -r, --readableIds If true, uses readable IDs for the created entities
572
- -s, --skipHydrateRelationships If true, does not hydrate relationships for the created entities
573
+ --apiVersion=<option> Api-Version header to send; selects the V1 or V2 variant of the endpoint
574
+ <options: 1|2>
575
+ --suffix=<value> Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets
576
+ /<entities>/synchronous)
573
577
 
574
578
  DESCRIPTION
575
- (BETA) Create entities
579
+ Create entities
576
580
 
577
581
  EXAMPLES
578
582
  $ contrail entities create color -g -n=10 # creates 10 random colors
@@ -594,46 +598,55 @@ EXAMPLES
594
598
  $ contrail entities create color -o /tmp/colors.json -- name=Blue green=1 red=2 blue=3 # creates a color and saves the output to /tmp/colors.json
595
599
  ```
596
600
 
597
- ## `contrail entities delete ENTITYNAME`
601
+ ## `contrail entities delete ENTITYNAME [IDS]`
598
602
 
599
- (BETA) Delete an entity
603
+ Delete entities by id
600
604
 
601
605
  ```
602
606
  USAGE
603
- $ contrail entities delete ENTITYNAME [-l error|warn|info|debug] [-e true|false] [-d] [-i <value>] [--id <value>]
607
+ $ contrail entities delete ENTITYNAME [IDS] [-l error|warn|info|debug] [-e true|false] [-d] [-i <value>] [--suffix
608
+ <value>] [--apiVersion 1|2]
604
609
 
605
610
  ARGUMENTS
606
611
  ENTITYNAME The name of the entity type to delete
612
+ IDS One or more entity ids to delete
607
613
 
608
614
  FLAGS
609
- -d, --dryRun If true, does not delete the entity but simulates the deletion
615
+ -d, --dryRun If true, does not delete the entities but simulates the deletion
610
616
  -e, --alwaysConfirmEnv=<option> [default: true] The Environment variables
611
617
  <options: true|false>
612
- -i, --input=<value> A JSON array of objects where each object is one entity to create. Cannot be used
613
- with --count. Unless --precise is specified, any missing values will be populated
614
- with random values.
618
+ -i, --inputFile=<value> A file with a JSON array of objects; only each object's id is used. Deletes every
619
+ entity in the file.
615
620
  -l, --logLevel=<option> The Log Level
616
621
  <options: error|warn|info|debug>
617
- --id=<value> The unique identifier of the entity
622
+ --apiVersion=<option> Api-Version header to send; selects the V1 or V2 variant of the endpoint
623
+ <options: 1|2>
624
+ --suffix=<value> Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets
625
+ /<entities>/synchronous)
618
626
 
619
627
  DESCRIPTION
620
- (BETA) Delete an entity
628
+ Delete entities by id
621
629
 
622
630
  EXAMPLES
623
631
  $ contrail entities delete color 123
632
+
633
+ $ contrail entities delete color id1 id2 id3
634
+
635
+ $ contrail entities delete item -i ids.json
624
636
  ```
625
637
 
626
- ## `contrail entities get TYPEPATH`
638
+ ## `contrail entities get TYPEPATH [IDS]`
627
639
 
628
- (BETA) Get an entity
640
+ Get an entity
629
641
 
630
642
  ```
631
643
  USAGE
632
- $ contrail entities get TYPEPATH [-l error|warn|info|debug] [-e true|false] [-o <value>] [-p <value>] [-P] [-s
633
- <value>] [-S] [-t <value>] [-r <value>]
644
+ $ contrail entities get TYPEPATH [IDS] [-l error|warn|info|debug] [-e true|false] [-o <value>] [-p <value>] [-P]
645
+ [-s <value>] [-S] [-t <value>] [-r <value>] [--suffix <value>] [--apiVersion 1|2]
634
646
 
635
647
  ARGUMENTS
636
648
  TYPEPATH The name of the entity type to fetch
649
+ IDS One or more entity ids; shorthand for the id/ids criteria
637
650
 
638
651
  FLAGS
639
652
  -P, --paginated If true, fetches all entities in a paginated manner
@@ -647,11 +660,19 @@ FLAGS
647
660
  -r, --relations=<value> Comma-separated list of relations to include in the output
648
661
  -s, --skip=<value> Number of entities to skip (used with paginated fetch)
649
662
  -t, --take=<value> Number of entities to fetch in a single request (default is 100)
663
+ --apiVersion=<option> Api-Version header to send; selects the V1 or V2 variant of the endpoint
664
+ <options: 1|2>
665
+ --suffix=<value> Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets
666
+ /<entities>/synchronous)
650
667
 
651
668
  DESCRIPTION
652
- (BETA) Get an entity
669
+ Get an entity
653
670
 
654
671
  EXAMPLES
672
+ $ contrail entities get color 123
673
+
674
+ $ contrail entities get color id1 id2 id3
675
+
655
676
  $ contrail entities get color -- id=123
656
677
 
657
678
  $ contrail entities get loader-processes -- createdOn=2025-09-15..2025-09-16
@@ -661,34 +682,40 @@ EXAMPLES
661
682
  $ contrail entities get events -- timestamp=..2025-09-16T23:59:59Z
662
683
  ```
663
684
 
664
- ## `contrail entities update ENTITYNAME [ID]`
685
+ ## `contrail entities update ENTITYNAME [IDS]`
665
686
 
666
- (BETA) Update an entity
687
+ Update an entity
667
688
 
668
689
  ```
669
690
  USAGE
670
- $ contrail entities update ENTITYNAME [ID] [-l error|warn|info|debug] [-e true|false] [-s] [-d] [-i <value>] [-F]
691
+ $ contrail entities update ENTITYNAME [IDS] [-l error|warn|info|debug] [-e true|false] [-S] [-d] [-i <value>]
692
+ [--suffix <value>] [--apiVersion 1|2]
671
693
 
672
694
  ARGUMENTS
673
695
  ENTITYNAME The name of the entity type to update
674
- ID The unique identifier of the entity
696
+ IDS One or more entity ids to update
675
697
 
676
698
  FLAGS
677
- -F, --force Force update without validation. Internal use only
678
- -d, --dryRun If true, does not create the entity but simulates the creation
699
+ -S, --skipHydrateRelationships Skip hydrating relationships when updating the entity
700
+ -d, --dryRun If true, does not update the entities but simulates the update
679
701
  -e, --alwaysConfirmEnv=<option> [default: true] The Environment variables
680
702
  <options: true|false>
681
- -i, --inputFile=<value> File containing properties to update the entity (optional)
703
+ -i, --inputFile=<value> A file with a JSON array of {id, ...} objects; each object is one entity to update.
682
704
  -l, --logLevel=<option> The Log Level
683
705
  <options: error|warn|info|debug>
684
- -s, --skipHydrateRelationships Skip hydrating relationships when updating the entity
706
+ --apiVersion=<option> Api-Version header to send; selects the V1 or V2 variant of the endpoint
707
+ <options: 1|2>
708
+ --suffix=<value> Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets
709
+ /<entities>/synchronous)
685
710
 
686
711
  DESCRIPTION
687
- (BETA) Update an entity
712
+ Update an entity
688
713
 
689
714
  EXAMPLES
690
715
  $ contrail entities update color 123 -- name=obsidian hex=000000
691
716
 
717
+ $ contrail entities update item id1 id2 id3 -- status=archived # apply the same change to several entities
718
+
692
719
  $ contrail entities update color 123 -- description= notes='""' # Unset description, set notes to empty string
693
720
  ```
694
721
 
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getVersionFromPackageJson = exports.authUser = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const amazon_cognito_identity_js_1 = require("amazon-cognito-identity-js");
6
- const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
7
6
  const sdk_1 = require("@contrail/sdk");
8
7
  const config_1 = require("../helpers/config/config");
9
8
  const logger_1 = tslib_1.__importDefault(require("../logger"));
@@ -63,7 +62,7 @@ exports.authUser = authUser;
63
62
  async function getOrgSlug(config) {
64
63
  const orgSlug = config?.orgSlug || process.env.CONTRAIL_CLI_ORG_SLUG;
65
64
  if (!orgSlug) {
66
- const answers = await inquirer_1.default.prompt([
65
+ const answers = await (0, common_1.promptOnStderr)([
67
66
  {
68
67
  type: 'input',
69
68
  name: 'orgSlug',
@@ -112,7 +111,7 @@ async function authenticateWithUsernamePassword(config) {
112
111
  message: 'Password',
113
112
  });
114
113
  }
115
- const answers = await inquirer_1.default.prompt(questions);
114
+ const answers = await (0, common_1.promptOnStderr)(questions);
116
115
  const params = {
117
116
  email: process.env.CONTRAIL_CLI_EMAIL || answers.email,
118
117
  password: process.env.CONTRAIL_CLI_PASSWORD || answers.password,
@@ -175,7 +174,7 @@ async function refreshCurrentUserOrg() {
175
174
  const currentUser = await (0, sdk_1.getCurrentUser)().catch((e) => {
176
175
  console.error('error getting current user', e.message);
177
176
  if (isExpiredTokenError(e)) {
178
- console.log('try frefreshing');
177
+ console.error('access token expired; attempting refresh');
179
178
  return;
180
179
  }
181
180
  throw e;
@@ -190,7 +189,7 @@ async function refreshCurrentUserOrg() {
190
189
  apiGateway: config.apiGateway,
191
190
  orgSlug: config.orgSlug,
192
191
  };
193
- console.log('fetched new access token from refresh token', newVibeAccessToken);
192
+ (0, sdk_1.setConfig)(sdk_1.Auth.config);
194
193
  }
195
194
  catch (e) {
196
195
  throw Error(`Could not get refresh token: ${e}`);
@@ -234,9 +233,11 @@ async function requestRefreshedAccessToken(vibeRefreshToken, apiGateway) {
234
233
  },
235
234
  body: JSON.stringify({ refreshToken: vibeRefreshToken }),
236
235
  });
237
- return await response.json().then((data) => {
238
- return data.accessToken;
239
- });
236
+ const data = await response.json();
237
+ if (!response.ok || !data.accessToken) {
238
+ throw new Error(`jwt_refresh returned ${response.status} with no access token`);
239
+ }
240
+ return data.accessToken;
240
241
  }
241
242
  function getVersionFromPackageJson() {
242
243
  // Get the path to the package.json file
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BaseCommand = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const core_1 = require("@oclif/core");
6
+ const common_1 = require("./common");
6
7
  const logger_1 = tslib_1.__importDefault(require("./logger"));
7
- const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
8
8
  const config_1 = require("./helpers/config/config");
9
9
  const lodash_1 = require("lodash");
10
10
  const login_1 = require("./auth/login");
@@ -73,7 +73,7 @@ class BaseCommand extends core_1.Command {
73
73
  choices: ['yes', 'no'],
74
74
  default: 'no',
75
75
  });
76
- const { confirm } = await inquirer_1.default.prompt(questions);
76
+ const { confirm } = await (0, common_1.promptOnStderr)(questions);
77
77
  if (confirm === 'no') {
78
78
  logger_1.default.info('Please use `contrail config use` command to choose the configuration or `contrail config set --environment=prod` to set different environment.');
79
79
  this.exit(1);
@@ -35,7 +35,7 @@ class GetAPIKeyApp extends basecommand_1.BaseCommand {
35
35
  },
36
36
  ];
37
37
  const answers = await inquirer_1.default.prompt(questions);
38
- logger_1.default.info(`App API key: (app:${answers.appApiKey})`);
38
+ this.log(`App API key: (app:${answers.appApiKey})`);
39
39
  }
40
40
  else {
41
41
  const appFound = installedApps.find((x) => x.app.identifier === this.flags.appIdentifier);
@@ -43,7 +43,7 @@ class GetAPIKeyApp extends basecommand_1.BaseCommand {
43
43
  logger_1.default.info('You do not have such an app installed');
44
44
  return;
45
45
  }
46
- logger_1.default.info(`App API key: (app:${appFound.apiKey.apiKey})`);
46
+ this.log(`App API key: (app:${appFound.apiKey.apiKey})`);
47
47
  }
48
48
  }
49
49
  }
@@ -1,4 +1,4 @@
1
- import { PropertyLevel } from '@contrail/types';
1
+ import { PropertyLevel, PropertyType } from '@contrail/types';
2
2
  import { ColonDelimited, TypeProperty as ExtendedTypeProperty, TypeReferencesCacheByPath } from '../../api/types';
3
3
  import { TypeWithProperties } from '../../api/types';
4
4
  import { BaseCommand } from '../../basecommand';
@@ -14,6 +14,8 @@ export default class CreateEntity extends BaseCommand {
14
14
  generateValues: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
15
15
  readableIds: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
16
16
  skipHydrateRelationships: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
17
+ suffix: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
18
+ apiVersion: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
17
19
  alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
18
20
  logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
19
21
  };
@@ -21,8 +23,17 @@ export default class CreateEntity extends BaseCommand {
21
23
  path: import("@oclif/core/lib/interfaces/parser").Arg<string, Record<string, unknown>>;
22
24
  };
23
25
  static strict: boolean;
26
+ init(): Promise<void>;
24
27
  run(): Promise<void>;
25
28
  }
29
+ export type CreateSummary = {
30
+ created: any[];
31
+ failed: {
32
+ input: any;
33
+ error: string;
34
+ }[];
35
+ };
36
+ export declare function summarizeSettledCreates(inputs: any[], settled: PromiseSettledResult<any>[]): CreateSummary;
26
37
  export type WithId = {
27
38
  id: string;
28
39
  [key: string]: any;
@@ -30,6 +41,7 @@ export type WithId = {
30
41
  export type ObjectReferenceCache = Map<string, WithId>;
31
42
  type ObjectReferenceCachesByTypePath = Map<string, ObjectReferenceCache>;
32
43
  export declare function pickRandomValueForProperty(property: ExtendedTypeProperty, objectReferencesCache: ObjectReferenceCachesByTypePath, typeReferencesCache: TypeReferencesCacheByPath): number | string | string[] | boolean | null;
44
+ export declare function castValueToPropertyType(value: string | number | string[] | number[], propertyType: PropertyType, propertySlug: string): any;
33
45
  export declare function getReferencedObjectPaths(type: TypeWithProperties): ColonDelimited[];
34
46
  export declare function buildObjectReferenceCache(entities: any[]): ObjectReferenceCache;
35
47
  export declare function selectRandomObject(cache: ObjectReferenceCache): WithId;
@@ -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.pickRandomValueForProperty = void 0;
3
+ exports.doesPropertyLevelMatchRole = exports.selectRandomObject = exports.buildObjectReferenceCache = exports.getReferencedObjectPaths = exports.castValueToPropertyType = exports.pickRandomValueForProperty = exports.summarizeSettledCreates = 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,6 +10,7 @@ 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");
13
14
  const basecommand_1 = require("../../basecommand");
14
15
  const sdk_1 = require("@contrail/sdk");
15
16
  const entities_1 = require("../../helpers/entities");
@@ -26,7 +27,7 @@ const baseValidationMap = {
26
27
  itemId: async (_slug, itemId) => (0, entities_1.throwIfInvalidItemId)(itemId),
27
28
  projectId: async (_slug, projectId) => (0, entities_1.throwIfInvalidProjectId)(projectId),
28
29
  };
29
- const throwIfInvalidPropertyLevelFn = async (_slug, maybeRoles) => maybeRoles.forEach((maybeRole) => (0, entities_1.throwIfInvalidItemLevel)(maybeRole));
30
+ const throwIfInvalidPropertyLevelFn = async (_slug, maybeRoles) => [].concat(maybeRoles).forEach((maybeRole) => (0, entities_1.throwIfInvalidItemLevel)(maybeRole));
30
31
  const throwIfInvalidUserOrgRoleFn = async (_slug, maybeRole) => {
31
32
  if (maybeRole !== 'MEMBER' && maybeRole !== 'ADMIN') {
32
33
  throw new Error(`${maybeRole} is not a valid User Org Role`); // TODO: get these roles from a shared library
@@ -144,7 +145,7 @@ const FIND_VALID_VALUE_MAP = {
144
145
  ],
145
146
  };
146
147
  class CreateEntity extends basecommand_1.BaseCommand {
147
- static description = '(BETA) Create entities';
148
+ static description = 'Create entities';
148
149
  static examples = [
149
150
  'contrail entities create color -g -n=10 # creates 10 random colors',
150
151
  'contrail entities create color -- name="Electric Blue" green=1 red=2 blue=3 # creates one color with specified properties only',
@@ -194,11 +195,20 @@ class CreateEntity extends basecommand_1.BaseCommand {
194
195
  default: false,
195
196
  }),
196
197
  skipHydrateRelationships: core_1.Flags.boolean({
197
- char: 's',
198
+ char: 'S',
198
199
  description: 'If true, does not hydrate relationships for the created entities',
199
200
  required: false,
200
201
  default: false,
201
202
  }),
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
+ }),
202
212
  };
203
213
  static args = {
204
214
  path: core_1.Args.string({
@@ -208,11 +218,14 @@ class CreateEntity extends basecommand_1.BaseCommand {
208
218
  }),
209
219
  };
210
220
  static strict = false;
221
+ async init() {
222
+ (0, common_1.routeConsoleLogToStderr)();
223
+ await super.init();
224
+ }
211
225
  async run() {
212
- this.log('🚨 This command is in BETA and may change or be removed at any time.');
213
226
  await (0, login_1.authUser)();
214
227
  const { flags, argv, args } = await this.parse(CreateEntity);
215
- const { count, dryRun: isDryRun, inputFile: inputFilename, outputFile: outputFilename, generateValues: shouldGenerateMissingValues, readableIds: shouldUseReadableIds, skipHydrateRelationships, } = flags;
228
+ const { count, dryRun: isDryRun, inputFile: inputFilename, outputFile: outputFilename, generateValues: shouldGenerateMissingValues, readableIds: shouldUseReadableIds, skipHydrateRelationships, suffix, apiVersion, } = flags;
216
229
  const { path: entityTypePath } = args;
217
230
  // Global flags is a little hacky, but it was easier
218
231
  // and it doesn't see *that* bad because they are only valid
@@ -221,10 +234,11 @@ class CreateEntity extends basecommand_1.BaseCommand {
221
234
  SHOULD_USE_READABLE_IDS = shouldUseReadableIds;
222
235
  SHOULD_SKIP_HYDRATE_RELATIONSHIPS = skipHydrateRelationships;
223
236
  SHOULD_GENERATE_MISSING_VALUES = shouldGenerateMissingValues;
224
- const propertySpecificationArgs = argv
225
- .slice(1, argv.length)
226
- .filter(propertySpecifications_1.isValidPropertySpecification);
227
- const propertySpecBySlug = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(propertySpecificationArgs);
237
+ const { ids: strayTokens, specs } = (0, propertySpecifications_1.partitionIdsAndSpecs)(argv.slice(1));
238
+ if (strayTokens.length > 0) {
239
+ this.error(`create takes no positional ids (got: ${strayTokens.join(' ')}); did you forget -- before property values?`);
240
+ }
241
+ const propertySpecBySlug = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
228
242
  // Validate args
229
243
  if (!entityTypePath) {
230
244
  this.error('You must specify an entity type path.');
@@ -257,13 +271,20 @@ class CreateEntity extends basecommand_1.BaseCommand {
257
271
  }
258
272
  try {
259
273
  const entitiesToCreate = await buildEntitiesToCreate(entityTypePath, partialEntities, propertySpecBySlug);
260
- const createdEntities = await createEntities(entityName, entitiesToCreate);
274
+ const summary = await createEntities(entityName, entitiesToCreate, {
275
+ suffix,
276
+ apiVersion: apiVersion,
277
+ });
261
278
  if (outputFilename) {
262
- fs_1.default.writeFileSync(outputFilename, JSON.stringify(createdEntities, null, 2));
263
- this.log(`Output saved to ${outputFilename}`);
279
+ fs_1.default.writeFileSync(outputFilename, JSON.stringify(summary, null, 2));
280
+ console.error(`Output saved to ${outputFilename}`);
264
281
  }
265
282
  else {
266
- console.log(`Created ${entityTypePath}(s), Entity: ${JSON.stringify(createdEntities, null, 2)}`);
283
+ this.log(JSON.stringify(summary, null, 2));
284
+ }
285
+ if (summary.failed.length > 0) {
286
+ console.error(`${summary.failed.length} of ${entitiesToCreate.length} entities failed.`);
287
+ process.exitCode = 1;
267
288
  }
268
289
  }
269
290
  catch (error) {
@@ -272,15 +293,28 @@ class CreateEntity extends basecommand_1.BaseCommand {
272
293
  }
273
294
  }
274
295
  exports.default = CreateEntity;
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))));
296
+ function summarizeSettledCreates(inputs, settled) {
297
+ const created = [];
298
+ const failed = [];
299
+ settled.forEach((result, index) => {
300
+ if (result.status === 'fulfilled') {
301
+ created.push(result.value);
302
+ }
303
+ else {
304
+ failed.push({ input: inputs[index], error: (0, common_1.sdkErrorMessage)(result.reason) });
305
+ }
306
+ });
307
+ return { created, failed };
308
+ }
309
+ exports.summarizeSettledCreates = summarizeSettledCreates;
310
+ async function createEntities(entityName, entities, routing = {}) {
280
311
  if (IS_DRY_RUN) {
281
- console.log(`Dry run mode: not creating entities, but simulating creation for ${entityName}`);
312
+ console.error(`Dry run mode: not creating entities, but simulating creation for ${entityName}`);
313
+ return { created: entities, failed: [] };
282
314
  }
283
- return createdEntities;
315
+ const limit = (0, p_limit_1.default)(20);
316
+ const settled = await Promise.allSettled(entities.map(async (e) => limit(() => createEntity(entityName, e, routing))));
317
+ return summarizeSettledCreates(entities, settled);
284
318
  }
285
319
  async function buildEntitiesToCreate(entityTypePath, entities, propertySpecificationBySlug) {
286
320
  let type = await (0, types_3.getTypeByPath)(entityTypePath);
@@ -303,7 +337,7 @@ async function buildEntitiesToCreate(entityTypePath, entities, propertySpecifica
303
337
  await Promise.all(populatedEntities.map(async () => limit(() => throwIfEntityIsInvalid)));
304
338
  // Skip system value generation unless -g flag is set (generateValues mode)
305
339
  if (!SHOULD_GENERATE_MISSING_VALUES) {
306
- console.log('Using only specified properties. Use --generate-values to auto-generate missing values.');
340
+ console.error('Using only specified properties. Use --generate-values to auto-generate missing values.');
307
341
  return populatedEntities;
308
342
  }
309
343
  // Add system values if needed
@@ -312,13 +346,13 @@ async function buildEntitiesToCreate(entityTypePath, entities, propertySpecifica
312
346
  for (const { slug, findValidValuesFn, applyValueToEntityFn } of valueFinderApplierForEntity) {
313
347
  // If the property is already specified in command-line args, skip it
314
348
  if (propertySpecificationBySlug?.has(slug)) {
315
- console.log(`Skipping property ${slug} because it is already specified.`);
349
+ console.error(`Skipping property ${slug} because it is already specified.`);
316
350
  continue;
317
351
  }
318
352
  // If all entities already have this property, skip finding values
319
353
  const allEntitiesHaveProperty = populatedEntities.every((entity) => entity[slug] !== undefined && entity[slug] !== null);
320
354
  if (allEntitiesHaveProperty) {
321
- console.log(`Skipping property ${slug} because all entities already have this value.`);
355
+ console.error(`Skipping property ${slug} because all entities already have this value.`);
322
356
  continue;
323
357
  }
324
358
  const values = await findValidValuesFn(populatedEntities, entities.length);
@@ -332,22 +366,33 @@ async function buildEntitiesToCreate(entityTypePath, entities, propertySpecifica
332
366
  return populatedEntities;
333
367
  }
334
368
  function createEntityWithPopulatedValues(type, typeReferencesCache, objectReferencesCache, propertySpecificationBySlug) {
335
- const roles = propertySpecificationBySlug?.get('roles');
369
+ const rolesValue = propertySpecificationBySlug?.get('roles');
370
+ const roles = rolesValue === undefined ? undefined : [].concat(rolesValue);
336
371
  const entity = SHOULD_GENERATE_MISSING_VALUES
337
372
  ? pickRandomPropertyValues(type, objectReferencesCache, typeReferencesCache, roles)
338
373
  : {};
339
374
  // Handle property specifications
340
375
  for (const [propertySlug, specifiedValue] of propertySpecificationBySlug.entries()) {
341
376
  const correspondingProperty = type.typeProperties.find((prop) => getPropertySlug(prop) === propertySlug);
342
- if (!specifiedValue) {
343
- throw new Error(`Value for property ${propertySlug} is required`);
377
+ if (specifiedValue === undefined) {
378
+ continue;
344
379
  }
345
- entity[propertySlug] = castValueToPropertyType(specifiedValue, correspondingProperty?.propertyType || types_1.PropertyType.String);
380
+ entity[propertySlug] = castValueToPropertyType(specifiedValue, correspondingProperty?.propertyType || types_1.PropertyType.String, propertySlug);
346
381
  }
347
382
  // Give Readbable IDs if specified
348
383
  if (SHOULD_USE_READABLE_IDS) {
349
384
  entity.specifiedId = generateRandomReadableString();
350
385
  }
386
+ // roles is a multi-value system property with no type property to drive
387
+ // coercion; a single value still has to reach the API as an array
388
+ if (typeof entity.roles === 'string') {
389
+ if (entity.roles.includes(',')) {
390
+ 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
391
+ .split(',')
392
+ .join(' roles=')}`);
393
+ }
394
+ entity.roles = [entity.roles];
395
+ }
351
396
  // Support specifiedId
352
397
  if (propertySpecificationBySlug?.has('specifiedId')) {
353
398
  const specifiedId = propertySpecificationBySlug.get('specifiedId');
@@ -478,7 +523,10 @@ function generateRandomReadableString() {
478
523
  function generateRandomDateString() {
479
524
  return new Date().toISOString();
480
525
  }
481
- function castValueToPropertyType(value, propertyType) {
526
+ function castValueToPropertyType(value, propertyType, propertySlug) {
527
+ if (Array.isArray(value) && propertyType !== types_1.PropertyType.MultiSelect) {
528
+ return value.map((element) => castValueToPropertyType(element, propertyType, propertySlug));
529
+ }
482
530
  switch (propertyType) {
483
531
  case types_1.PropertyType.Boolean:
484
532
  return value.toString().toLowerCase() === 'true';
@@ -490,16 +538,35 @@ function castValueToPropertyType(value, propertyType) {
490
538
  return numValue;
491
539
  case types_1.PropertyType.Date:
492
540
  return new Date(value.toString()).toISOString();
541
+ case types_1.PropertyType.MultiSelect:
542
+ if (Array.isArray(value)) {
543
+ return value;
544
+ }
545
+ // the old comma syntax parses as one literal value; warn instead of guessing at a split
546
+ if (typeof value === 'string' && value.includes(',')) {
547
+ console.error(`${propertySlug} value "${value}" contains a comma and is treated as one literal value. To pass several values, repeat the key: ${propertySlug}=${value
548
+ .split(',')
549
+ .join(` ${propertySlug}=`)}`);
550
+ }
551
+ return [value];
493
552
  default:
494
553
  return value; // For string and other types, return as is
495
554
  }
496
555
  }
497
- async function createEntity(entityName, entity) {
556
+ exports.castValueToPropertyType = castValueToPropertyType;
557
+ async function createEntity(entityName, entity, routing = {}) {
498
558
  const client = new sdk_1.Entities();
499
559
  const skipHydrateRelationships = SHOULD_SKIP_HYDRATE_RELATIONSHIPS;
500
- if (entityName === 'assortment-item')
501
- return (0, entities_1.createAssortmentItem)(entity, { skipHydrateRelationships }); // special case
502
- const response = await client.create({ entityName, object: entity, skipHydrateRelationships });
560
+ const { suffix, apiVersion } = routing;
561
+ if (entityName === 'assortment-item' && !suffix)
562
+ return (0, entities_1.createAssortmentItem)(entity, { skipHydrateRelationships, apiVersion }); // special case
563
+ const response = await client.create({
564
+ entityName,
565
+ object: entity,
566
+ skipHydrateRelationships,
567
+ suffix,
568
+ apiVersion,
569
+ });
503
570
  return response;
504
571
  }
505
572
  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 handle roles as comma-separated array', () => {
274
- const specs = ['roles=option,family', 'name=Test'];
273
+ it('should build roles arrays from repeated keys', () => {
274
+ const specs = ['roles=option', 'roles=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 = propertySpecs.get('roles');
336
+ const roles = [].concat(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,3 +514,32 @@ 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, 'colors')).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, 'colors')).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, 'colors')).toEqual([
530
+ 'option,family',
531
+ ]);
532
+ expect(consoleError).toHaveBeenCalledWith(expect.stringContaining('colors=option colors=family'));
533
+ consoleError.mockRestore();
534
+ });
535
+ it('should cast each element of a repeated-key array on scalar property types', () => {
536
+ expect((0, create_1.castValueToPropertyType)(['1', '2'], types_1.PropertyType.Number, 'rank')).toEqual([1, 2]);
537
+ expect((0, create_1.castValueToPropertyType)(['true', 'false'], types_1.PropertyType.Boolean, 'isActive')).toEqual([true, false]);
538
+ });
539
+ it('should keep commas literal on string properties without warning', () => {
540
+ const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined);
541
+ expect((0, create_1.castValueToPropertyType)('my,name', types_1.PropertyType.String, 'name')).toBe('my,name');
542
+ expect(consoleError).not.toHaveBeenCalled();
543
+ consoleError.mockRestore();
544
+ });
545
+ });