@contrail/cli 3.6.0-alpha-8-alpha.82b70ea → 3.6.0-alpha.5ecc188

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 (88) hide show
  1. package/README.md +26 -181
  2. package/dist/api/types.d.ts +0 -35
  3. package/dist/api/types.js +1 -49
  4. package/dist/auth/login.d.ts +4 -0
  5. package/dist/auth/login.js +136 -56
  6. package/dist/auth/login.spec.js +117 -3
  7. package/dist/auth/sign-in-error.d.ts +7 -0
  8. package/dist/auth/sign-in-error.js +24 -0
  9. package/dist/auth/sign-in-error.spec.js +22 -0
  10. package/dist/auth/sso.d.ts +38 -0
  11. package/dist/auth/sso.js +184 -0
  12. package/dist/auth/sso.spec.js +191 -0
  13. package/dist/basecommand.d.ts +3 -0
  14. package/dist/basecommand.js +10 -3
  15. package/dist/commands/app/getApiKey.js +2 -2
  16. package/dist/commands/login.d.ts +12 -0
  17. package/dist/commands/login.js +25 -0
  18. package/dist/common.d.ts +1 -4
  19. package/dist/common.js +1 -18
  20. package/dist/helpers/config/config.d.ts +3 -3
  21. package/dist/helpers/config/config.js +3 -3
  22. package/dist/helpers/file-helpers.d.ts +0 -1
  23. package/dist/helpers/file-helpers.js +3 -20
  24. package/dist/logger.js +1 -4
  25. package/node_modules/@contrail/entity-compare/package.json +3 -6
  26. package/node_modules/@contrail/loader/lib/common/conditional-columns.js +1 -1
  27. package/node_modules/@contrail/loader/lib/constants.d.ts +8 -0
  28. package/node_modules/@contrail/loader/lib/constants.js +9 -1
  29. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.d.ts +4 -0
  30. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.js +57 -0
  31. package/node_modules/@contrail/loader/lib/entities-v2/linesheet-v2/item-processor.spec.js +492 -34
  32. package/node_modules/@contrail/loader/lib/pipeline/validate.js +2 -52
  33. package/node_modules/@contrail/loader/lib/pipeline/validate.spec.js +0 -85
  34. package/node_modules/@contrail/loader/package.json +2 -2
  35. package/node_modules/@contrail/sdk/.github/workflows/publish-to-npm.yml +4 -1
  36. package/node_modules/@contrail/sdk/lib/auth/login.js +1 -1
  37. package/node_modules/@contrail/sdk/lib/config/config.d.ts +0 -3
  38. package/node_modules/@contrail/sdk/lib/config/config.js +7 -13
  39. package/node_modules/@contrail/sdk/lib/core/request.js +2 -6
  40. package/node_modules/@contrail/sdk/lib/entities/entities.client.d.ts +0 -2
  41. package/node_modules/@contrail/sdk/lib/entities/entities.client.js +1 -3
  42. package/node_modules/@contrail/sdk/lib/entities/entity.resource.registry.js +0 -1
  43. package/node_modules/@contrail/sdk/lib/index.d.ts +0 -1
  44. package/node_modules/@contrail/sdk/lib/index.js +0 -1
  45. package/node_modules/@contrail/sdk/package.json +1 -1
  46. package/oclif.manifest.json +50 -449
  47. package/package.json +12 -5
  48. package/dist/commands/entities/create.d.ts +0 -50
  49. package/dist/commands/entities/create.js +0 -640
  50. package/dist/commands/entities/create.spec.js +0 -583
  51. package/dist/commands/entities/delete.d.ts +0 -20
  52. package/dist/commands/entities/delete.js +0 -140
  53. package/dist/commands/entities/get.d.ts +0 -25
  54. package/dist/commands/entities/get.js +0 -276
  55. package/dist/commands/entities/grammar.spec.js +0 -79
  56. package/dist/commands/entities/output.spec.d.ts +0 -1
  57. package/dist/commands/entities/output.spec.js +0 -72
  58. package/dist/commands/entities/update.d.ts +0 -32
  59. package/dist/commands/entities/update.js +0 -161
  60. package/dist/helpers/entities/assortment-items.d.ts +0 -11
  61. package/dist/helpers/entities/assortment-items.js +0 -76
  62. package/dist/helpers/entities/batchFetch.d.ts +0 -8
  63. package/dist/helpers/entities/batchFetch.js +0 -49
  64. package/dist/helpers/entities/index.d.ts +0 -3
  65. package/dist/helpers/entities/index.js +0 -6
  66. package/dist/helpers/entities/items.d.ts +0 -8
  67. package/dist/helpers/entities/items.js +0 -88
  68. package/dist/helpers/entities/items.spec.d.ts +0 -1
  69. package/dist/helpers/entities/items.spec.js +0 -19
  70. package/dist/helpers/entities/project-items.d.ts +0 -2
  71. package/dist/helpers/entities/project-items.js +0 -44
  72. package/dist/helpers/propertySpecifications/dateRanges.d.ts +0 -34
  73. package/dist/helpers/propertySpecifications/dateRanges.js +0 -83
  74. package/dist/helpers/propertySpecifications/dateRanges.spec.d.ts +0 -1
  75. package/dist/helpers/propertySpecifications/dateRanges.spec.js +0 -91
  76. package/dist/helpers/propertySpecifications/propertySpecifications.d.ts +0 -40
  77. package/dist/helpers/propertySpecifications/propertySpecifications.js +0 -104
  78. package/dist/helpers/propertySpecifications/propertySpecifications.spec.d.ts +0 -1
  79. package/dist/helpers/propertySpecifications/propertySpecifications.spec.js +0 -387
  80. package/dist/logger.spec.d.ts +0 -1
  81. package/dist/logger.spec.js +0 -12
  82. package/node_modules/@contrail/sdk/lib/image-search/image-search.d.ts +0 -34
  83. package/node_modules/@contrail/sdk/lib/image-search/image-search.js +0 -42
  84. package/node_modules/@contrail/sdk/lib/image-search/index.d.ts +0 -1
  85. package/node_modules/@contrail/sdk/lib/image-search/index.js +0 -17
  86. package/node_modules/@contrail/sdk/scripts/replicate-bug.js +0 -69
  87. /package/dist/{commands/entities/create.spec.d.ts → auth/sign-in-error.spec.d.ts} +0 -0
  88. /package/dist/{commands/entities/grammar.spec.d.ts → auth/sso.spec.d.ts} +0 -0
@@ -1,640 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.doesPropertyLevelMatchRole = exports.selectRandomObject = exports.buildObjectReferenceCache = exports.getReferencedObjectPaths = exports.castValueToPropertyType = exports.pickRandomValueForProperty = exports.pickRandomPropertyValues = exports.summarizeSettledCreates = void 0;
4
- const tslib_1 = require("tslib");
5
- const fs_1 = tslib_1.__importDefault(require("fs"));
6
- const unique_names_generator_1 = require("unique-names-generator");
7
- const p_limit_1 = tslib_1.__importDefault(require("p-limit"));
8
- const types_1 = require("@contrail/types");
9
- const types_2 = require("../../api/types");
10
- const core_1 = require("@oclif/core");
11
- const types_3 = require("../../api/types");
12
- const login_1 = require("../../auth/login");
13
- const common_1 = require("../../common");
14
- const basecommand_1 = require("../../basecommand");
15
- const sdk_1 = require("@contrail/sdk");
16
- const entities_1 = require("../../helpers/entities");
17
- const propertySpecifications_1 = require("../../helpers/propertySpecifications/propertySpecifications");
18
- const file_helpers_1 = require("../../helpers/file-helpers");
19
- let IS_DRY_RUN = false;
20
- let SHOULD_USE_READABLE_IDS = false;
21
- let SHOULD_SKIP_HYDRATE_RELATIONSHIPS = false;
22
- let SHOULD_GENERATE_MISSING_VALUES = false;
23
- let NUM_ENTITIES_TO_CREATE = 1; // Default to creating one entity if not specified
24
- const getNumEntitiesToCreate = () => NUM_ENTITIES_TO_CREATE; // method to get the latest number in case this changes later
25
- const SLUGS_THAT_MUST_BE_SPECIFIED_BY_TYPE_PATH = {
26
- item: ['roles'],
27
- 'project-item': ['projectId'],
28
- 'assortment-item': ['assortmentId'],
29
- 'user-org': ['role'],
30
- };
31
- function throwIfParentsAreMixed(entities, parentSlug, parentLabel) {
32
- const parentIds = new Set(entities.map((entity) => entity[parentSlug]));
33
- if (parentIds.size > 1) {
34
- throw new Error(`Generated item ids are drawn from one ${parentLabel}'s candidates, but the input spans ${parentIds.size} ${parentLabel}s. Run one ${parentLabel} per command, or supply itemId for each row.`);
35
- }
36
- }
37
- const FIND_VALID_VALUE_MAP = {
38
- assortment: [
39
- {
40
- slug: 'name',
41
- findValidValuesFn: async (assortments) => new Set(Array.from({ length: assortments.length }, () => generateRandomReadableString())),
42
- applyValueToEntityFn: (entity, validValues) => {
43
- if (entity.name)
44
- return; // skip if already specified
45
- entity.name = Array.from(validValues)[Math.floor(Math.random() * validValues.size)];
46
- validValues.delete(entity.name);
47
- },
48
- },
49
- ],
50
- 'assortment-item': [
51
- {
52
- slug: 'itemId',
53
- findValidValuesFn: async (assortmentItems, count) => {
54
- throwIfParentsAreMixed(assortmentItems, 'assortmentId', 'assortment');
55
- return new Set((await (0, entities_1.findItemsNotInAssortment)(assortmentItems[0].assortmentId, count)).map(({ id }) => id));
56
- },
57
- applyValueToEntityFn: (entity, validValues) => {
58
- if (entity.itemId)
59
- return; // skip if already specified
60
- entity.itemId = Array.from(validValues)[Math.floor(Math.random() * validValues.size)];
61
- validValues.delete(entity.itemId);
62
- },
63
- },
64
- ],
65
- 'project-item': [
66
- {
67
- slug: 'itemId',
68
- findValidValuesFn: async (projectItems) => {
69
- throwIfParentsAreMixed(projectItems, 'projectId', 'project');
70
- return new Set((await (0, entities_1.findItemsNotInProject)(projectItems[0].projectId)).map(({ id }) => id));
71
- },
72
- applyValueToEntityFn: (entity, validValues) => {
73
- if (entity.itemId)
74
- return; // skip if already specified
75
- entity.itemId = Array.from(validValues)[Math.floor(Math.random() * validValues.size)];
76
- validValues.delete(entity.itemId);
77
- },
78
- },
79
- ],
80
- item: [
81
- {
82
- slug: 'itemFamilyId',
83
- findValidValuesFn: async (_items) => new Set(await (0, entities_1.getItemFamilies)(getNumEntitiesToCreate()).then((families) => families === undefined ? undefined : families.map(({ id }) => id))),
84
- applyValueToEntityFn: (entity, validValues) => {
85
- if (entity.itemFamilyId)
86
- return; // skip if already specified
87
- if (entity.roles?.includes('option')) {
88
- entity.itemFamilyId =
89
- Array.from(validValues)[Math.floor(Math.random() * validValues.size)];
90
- // can reuse itemFamilyId for options
91
- }
92
- },
93
- },
94
- {
95
- slug: 'name',
96
- findValidValuesFn: async (items) => new Set(Array.from({ length: items.length }, () => generateRandomReadableString())),
97
- applyValueToEntityFn: (entity, validValues) => {
98
- if (entity.name)
99
- return; // skip if already specified
100
- entity.name = Array.from(validValues)[Math.floor(Math.random() * validValues.size)];
101
- validValues.delete(entity.name);
102
- },
103
- },
104
- {
105
- slug: 'optionName',
106
- findValidValuesFn: async (items) => new Set(Array.from({ length: items.length }, () => generateRandomReadableString())),
107
- applyValueToEntityFn: (entity, validValues) => {
108
- if (entity.optionName)
109
- return; // skip if already specified
110
- if (!entity.roles?.includes('option'))
111
- return; // only apply to options
112
- entity.optionName = Array.from(validValues)[Math.floor(Math.random() * validValues.size)];
113
- validValues.delete(entity.optionName);
114
- },
115
- },
116
- {
117
- slug: 'optionGroup',
118
- findValidValuesFn: async (_items) => new Set(),
119
- applyValueToEntityFn: (entity, _validValues) => {
120
- if (entity.optionGroup)
121
- return; // skip if already specified
122
- if (!entity.roles?.includes('option'))
123
- return; // only apply to options
124
- entity.optionGroup = 'color';
125
- },
126
- },
127
- ],
128
- workspace: [
129
- {
130
- slug: 'name',
131
- findValidValuesFn: async (items) => new Set(Array.from({ length: items.length }, () => generateRandomReadableString())),
132
- applyValueToEntityFn: (entity, validValues) => {
133
- if (entity.name)
134
- return; // skip if already specified
135
- entity.name = Array.from(validValues)[Math.floor(Math.random() * validValues.size)];
136
- validValues.delete(entity.name);
137
- },
138
- },
139
- ],
140
- };
141
- class CreateEntity extends basecommand_1.BaseCommand {
142
- static description = 'Create entities';
143
- static examples = [
144
- 'contrail entities create color -g -n=10 # creates 10 random colors',
145
- 'contrail entities create color -- name="Electric Blue" green=1 red=2 blue=3 # creates one color with specified properties only',
146
- 'contrail entities create custom-entities:franchise',
147
- 'contrail entities create project-item -n=1 -- projectId=abc # creates 10 project items within project ABC',
148
- 'contrail entities create color -g -r # creates a random color with a human readable ID',
149
- 'contrail entities create color -d -- name=test # simulates the creation of a color without actually creating it',
150
- 'contrail entities create custom-entity:franchise -s # creates an entity and the response does not contain hydrating relationships',
151
- 'contrail entities create color -g -- name=Electric Blue # creates a color with the name specified and other properties auto-generated',
152
- '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',
153
- ];
154
- static flags = {
155
- ...basecommand_1.BaseCommand.baseFlags,
156
- count: core_1.Flags.integer({
157
- char: 'n',
158
- description: 'Number of random entities to create',
159
- required: false,
160
- }),
161
- dryRun: core_1.Flags.boolean({
162
- char: 'd',
163
- description: 'If true, does not create the entity but simulates the creation',
164
- required: false,
165
- default: false,
166
- }),
167
- inputFile: core_1.Flags.string({
168
- char: 'i',
169
- description: 'A file with a JSON array of objects where each object is one entity to create. Cannot be used with --count. Unless --generateValues is specified, only the properties in the file will be used.',
170
- required: false,
171
- multiple: false,
172
- }),
173
- outputFile: core_1.Flags.string({
174
- char: 'o',
175
- description: 'File to save the output (optional)',
176
- required: false,
177
- multiple: false,
178
- }),
179
- generateValues: core_1.Flags.boolean({
180
- char: 'g',
181
- description: 'If true, generates random values for properties that are not specified. By default, only specified properties are used.',
182
- required: false,
183
- default: false,
184
- }),
185
- readableIds: core_1.Flags.boolean({
186
- char: 'r',
187
- description: 'If true, uses readable IDs for the created entities',
188
- required: false,
189
- default: false,
190
- }),
191
- skipHydrateRelationships: core_1.Flags.boolean({
192
- char: 'S',
193
- description: 'If true, does not hydrate relationships for the created entities',
194
- required: false,
195
- default: false,
196
- }),
197
- suffix: core_1.Flags.string({
198
- description: 'Append a sub-route to the entity endpoint (e.g. --suffix=synchronous targets /<entities>/synchronous)',
199
- required: false,
200
- }),
201
- apiVersion: core_1.Flags.string({
202
- description: 'Api-Version header to send; selects the V1 or V2 variant of the endpoint',
203
- options: ['1', '2'],
204
- required: false,
205
- }),
206
- };
207
- static args = {
208
- typePath: core_1.Args.string({
209
- description: 'The type path of the entity to create (e.g. color, custom-entity:franchise)',
210
- required: true,
211
- multiple: false,
212
- }),
213
- };
214
- static strict = false;
215
- async init() {
216
- (0, common_1.routeConsoleLogToStderr)();
217
- await super.init();
218
- }
219
- async run() {
220
- await (0, login_1.authUser)();
221
- const { flags, argv, args } = await this.parse(CreateEntity);
222
- const { count, dryRun: isDryRun, inputFile: inputFilename, outputFile: outputFilename, generateValues: shouldGenerateMissingValues, readableIds: shouldUseReadableIds, skipHydrateRelationships, suffix, apiVersion, } = flags;
223
- const { typePath: entityTypePath } = args;
224
- // Global flags is a little hacky, but it was easier
225
- // and it doesn't see *that* bad because they are only valid
226
- // for the lifecycle of the command.
227
- IS_DRY_RUN = isDryRun;
228
- SHOULD_USE_READABLE_IDS = shouldUseReadableIds;
229
- SHOULD_SKIP_HYDRATE_RELATIONSHIPS = skipHydrateRelationships;
230
- SHOULD_GENERATE_MISSING_VALUES = shouldGenerateMissingValues;
231
- const { ids: strayTokens, specs } = (0, propertySpecifications_1.partitionIdsAndSpecs)(argv.slice(1));
232
- if (strayTokens.length > 0) {
233
- this.error(`create takes no positional ids (got: ${strayTokens.join(' ')}); did you forget -- before property values?`);
234
- }
235
- const propertySpecBySlug = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
236
- // Validate args
237
- if (!entityTypePath) {
238
- this.error('You must specify an entity type path.');
239
- }
240
- if (inputFilename && count) {
241
- throw new Error('You cannot use --inputFile and --count together. Please specify one or the other.');
242
- }
243
- if (count !== undefined && count <= 0) {
244
- this.error('Count must be a positive integer.');
245
- }
246
- const partialEntities = inputFilename
247
- ? (0, file_helpers_1.parseFileAsJsonArray)(inputFilename)
248
- : Array.from({ length: count || 1 }).fill({});
249
- NUM_ENTITIES_TO_CREATE = partialEntities.length;
250
- const { root: entityName } = (0, types_2.parseTypePath)(entityTypePath);
251
- // Ensure we have the required properties for the entity type
252
- if (SLUGS_THAT_MUST_BE_SPECIFIED_BY_TYPE_PATH[entityName]) {
253
- const requiredSlugs = SLUGS_THAT_MUST_BE_SPECIFIED_BY_TYPE_PATH[entityName];
254
- for (const slug of requiredSlugs) {
255
- // Check if the property is specified in command-line args
256
- const isInCommandLineArgs = propertySpecBySlug.has(slug);
257
- // Check if all entities from input file have this property
258
- const allEntitiesHaveProperty = inputFilename
259
- ? partialEntities.every((entity) => entity[slug] !== undefined && entity[slug] !== null)
260
- : false;
261
- if (!isInCommandLineArgs && !allEntitiesHaveProperty) {
262
- this.error(`Property '${slug}' must be specified for entity type '${entityName}'.`);
263
- }
264
- }
265
- }
266
- try {
267
- const entitiesToCreate = await buildEntitiesToCreate(entityTypePath, partialEntities, propertySpecBySlug);
268
- const summary = await createEntities(entityName, entitiesToCreate, {
269
- suffix,
270
- apiVersion: apiVersion,
271
- });
272
- if (outputFilename) {
273
- fs_1.default.writeFileSync(outputFilename, JSON.stringify(summary, null, 2));
274
- console.error(`Output saved to ${outputFilename}`);
275
- }
276
- else {
277
- this.log(JSON.stringify(summary, null, 2));
278
- }
279
- if (summary.failed.length > 0) {
280
- console.error(`${summary.failed.length} of ${entitiesToCreate.length} entities failed.`);
281
- process.exitCode = 1;
282
- }
283
- }
284
- catch (error) {
285
- this.error(`Failed to create entities: ${error.message}, ${error.stack}`);
286
- }
287
- }
288
- }
289
- exports.default = CreateEntity;
290
- function summarizeSettledCreates(inputs, settled) {
291
- const created = [];
292
- const failed = [];
293
- settled.forEach((result, index) => {
294
- if (result.status === 'fulfilled') {
295
- created.push(result.value);
296
- }
297
- else {
298
- failed.push({ input: inputs[index], error: (0, common_1.sdkErrorMessage)(result.reason) });
299
- }
300
- });
301
- return { created, failed };
302
- }
303
- exports.summarizeSettledCreates = summarizeSettledCreates;
304
- async function createEntities(entityName, entities, routing = {}) {
305
- if (IS_DRY_RUN) {
306
- console.error(`Dry run mode: not creating entities, but simulating creation for ${entityName}`);
307
- return { created: entities, failed: [] };
308
- }
309
- const limit = (0, p_limit_1.default)(20);
310
- const settled = await Promise.allSettled(entities.map(async (e) => limit(() => createEntity(entityName, e, routing))));
311
- return summarizeSettledCreates(entities, settled);
312
- }
313
- async function buildEntitiesToCreate(entityTypePath, entities, propertySpecificationBySlug) {
314
- let type = await (0, types_3.getTypeByPath)(entityTypePath);
315
- if (!type) {
316
- console.warn(`Type not found for path: ${entityTypePath}`);
317
- type = {
318
- typePath: '',
319
- typeProperties: [],
320
- }; // Fallback to an empty type; This allows us to create entities that are not type-managed
321
- }
322
- const [typesCache, objectReferencesCache] = await Promise.all([
323
- (0, types_2.buildLocalTypesCache)([...(0, types_2.getReferencedTypePaths)(type), entityTypePath]),
324
- buildLocalObjectReferencesCache(getReferencedObjectPaths(type)),
325
- ]);
326
- const populatedEntities = entities.map((entity) => ({
327
- ...createEntityWithPopulatedValues(type, typesCache, objectReferencesCache, propertySpecificationBySlug, entity),
328
- ...entity,
329
- }));
330
- // Skip system value generation unless -g flag is set (generateValues mode)
331
- if (!SHOULD_GENERATE_MISSING_VALUES) {
332
- console.error('Using only specified properties. Use --generateValues to auto-generate missing values.');
333
- return populatedEntities;
334
- }
335
- // Add system values if needed
336
- const { root } = (0, types_2.parseTypePath)(type.typePath);
337
- const valueFinderApplierForEntity = FIND_VALID_VALUE_MAP[root] || [];
338
- for (const { slug, findValidValuesFn, applyValueToEntityFn } of valueFinderApplierForEntity) {
339
- // If the property is already specified in command-line args, skip it
340
- if (propertySpecificationBySlug?.has(slug)) {
341
- console.error(`Skipping property ${slug} because it is already specified.`);
342
- continue;
343
- }
344
- // If all entities already have this property, skip finding values
345
- const allEntitiesHaveProperty = populatedEntities.every((entity) => entity[slug] !== undefined && entity[slug] !== null);
346
- if (allEntitiesHaveProperty) {
347
- console.error(`Skipping property ${slug} because all entities already have this value.`);
348
- continue;
349
- }
350
- const values = await findValidValuesFn(populatedEntities, entities.length);
351
- if (values) {
352
- populatedEntities.forEach((e) => applyValueToEntityFn(e, values));
353
- }
354
- else {
355
- console.warn(`No valid values found for property ${slug}. Skipping.`);
356
- }
357
- }
358
- return populatedEntities;
359
- }
360
- function createEntityWithPopulatedValues(type, typeReferencesCache, objectReferencesCache, propertySpecificationBySlug, inputRow) {
361
- const rolesValue = inputRow?.roles ?? propertySpecificationBySlug?.get('roles');
362
- const roles = rolesValue === undefined ? undefined : [].concat(rolesValue);
363
- const suppliedSlugs = collectSuppliedSlugs(propertySpecificationBySlug, inputRow);
364
- const entity = SHOULD_GENERATE_MISSING_VALUES
365
- ? pickRandomPropertyValues(type, objectReferencesCache, typeReferencesCache, roles, suppliedSlugs)
366
- : {};
367
- // Handle property specifications
368
- for (const [propertySlug, specifiedValue] of propertySpecificationBySlug.entries()) {
369
- const correspondingProperty = type.typeProperties.find((prop) => getPropertySlug(prop) === propertySlug);
370
- if (specifiedValue === undefined) {
371
- continue;
372
- }
373
- entity[propertySlug] = castValueToPropertyType(specifiedValue, correspondingProperty?.propertyType || types_1.PropertyType.String, propertySlug);
374
- }
375
- // Give Readbable IDs if specified
376
- if (SHOULD_USE_READABLE_IDS) {
377
- entity.specifiedId = generateRandomReadableString();
378
- }
379
- // roles is a multi-value system property with no type property to drive
380
- // coercion; a single value still has to reach the API as an array
381
- if (typeof entity.roles === 'string') {
382
- if (entity.roles.includes(',')) {
383
- 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
384
- .split(',')
385
- .join(' roles=')}`);
386
- }
387
- entity.roles = [entity.roles];
388
- }
389
- // Support specifiedId
390
- if (propertySpecificationBySlug?.has('specifiedId')) {
391
- const specifiedId = propertySpecificationBySlug.get('specifiedId');
392
- entity.specifiedId = specifiedId;
393
- }
394
- // There are some required values for certain entity types
395
- const requiredValuesForType = requiredValues(type.typePath, typeReferencesCache);
396
- if (requiredValuesForType) {
397
- requiredValuesForType.forEach(({ slug, value }) => {
398
- entity[slug] = value;
399
- });
400
- }
401
- return entity;
402
- }
403
- function collectSuppliedSlugs(propertySpecificationBySlug, inputRow) {
404
- const fromCommandLine = [...(propertySpecificationBySlug?.entries() ?? [])]
405
- .filter(([, value]) => value !== undefined)
406
- .map(([slug]) => slug);
407
- const fromRow = Object.entries(inputRow ?? {})
408
- .filter(([, value]) => value !== undefined)
409
- .map(([slug]) => slug);
410
- return new Set([...fromCommandLine, ...fromRow]);
411
- }
412
- function pickRandomPropertyValues(type, objectReferencesCache, typeReferencesCache, roles, suppliedSlugs) {
413
- const entity = {};
414
- // Get values for properties
415
- for (const property of type.typeProperties) {
416
- // Validate property level
417
- if (roles?.length && roles.every((r) => !doesPropertyLevelMatchRole(property.propertyLevel, r)))
418
- continue;
419
- if (suppliedSlugs?.has(getPropertySlug(property)))
420
- continue;
421
- // Generate random value
422
- if (property.propertyType === types_1.PropertyType.ObjectReference) {
423
- const cache = objectReferencesCache.get(property.referencedTypePath);
424
- if (!cache || cache.size === 0) {
425
- throw new Error(`No object references found for referencedTypePath: ${property.referencedTypePath}`);
426
- }
427
- entity[getPropertySlug(property)] = selectRandomObject(cache).id;
428
- }
429
- else {
430
- entity[getPropertySlug(property)] = pickRandomValueForProperty(property, objectReferencesCache, typeReferencesCache);
431
- }
432
- }
433
- return entity;
434
- }
435
- exports.pickRandomPropertyValues = pickRandomPropertyValues;
436
- function pickRandomValueForProperty(property, objectReferencesCache, typeReferencesCache) {
437
- const getRandomObjectReference = (referencedTypePath) => {
438
- if (!objectReferencesCache.has(referencedTypePath)) {
439
- throw new Error(`No object references found for referencedTypePath: ${referencedTypePath}`);
440
- }
441
- const cache = objectReferencesCache.get(referencedTypePath);
442
- if (cache.size === 0) {
443
- return null;
444
- }
445
- const randomIndex = Math.floor(Math.random() * cache.size);
446
- const randomObjectReference = Array.from(cache.values())[randomIndex];
447
- return randomObjectReference;
448
- };
449
- switch (property.propertyType) {
450
- case types_1.PropertyType.String:
451
- return generateRandomReadableString();
452
- case types_1.PropertyType.Text:
453
- return generateRandomReadableString();
454
- case types_1.PropertyType.Boolean:
455
- return generateRandomBooleanValue();
456
- case types_1.PropertyType.Number:
457
- return generateRandomNumber();
458
- case types_1.PropertyType.Currency:
459
- return generateRandomNumber();
460
- case types_1.PropertyType.SingleSelect:
461
- if (!property.options)
462
- throw new Error(`Option set is required for SingleSelect property ${property.slug}, ${JSON.stringify(property, null, 2)}`);
463
- return pickRandomOptions(property.options, 1)[0].value;
464
- case types_1.PropertyType.MultiSelect:
465
- if (!property.options)
466
- throw new Error('Option set is required for MultiSelect property');
467
- const randomSelection = pickRandomOptions(property.options, Math.max(2, property.options.length)); // Avoid picking more than the number of options
468
- return randomSelection.map((option) => option.value);
469
- case types_1.PropertyType.Sequence:
470
- return generateRandomNumber();
471
- case types_1.PropertyType.Date:
472
- return generateRandomDateString();
473
- case types_1.PropertyType.Percent:
474
- return generateRandomNumber(0, 100);
475
- case types_1.PropertyType.ObjectReference:
476
- const { referencedTypePath: typeForObjectReference } = property;
477
- const randomObjectReference = getRandomObjectReference(typeForObjectReference);
478
- if (!randomObjectReference) {
479
- throw new Error(`No object references found for referencedTypePath: ${typeForObjectReference}`);
480
- }
481
- return randomObjectReference.id; // Assuming the object reference has an 'id' field
482
- case types_1.PropertyType.TypeReference:
483
- const { referencedTypePath } = property;
484
- const type = typeReferencesCache.get(referencedTypePath);
485
- if (!type) {
486
- throw new Error(`Referenced type not found for path: ${referencedTypePath}`);
487
- }
488
- return type.id;
489
- case types_1.PropertyType.Formula:
490
- return undefined; // Placeholder for formula properties because they are evaluated on save anyway
491
- default:
492
- throw new Error(`Cannot handle property type: ${property.propertyType}.\n\n See property: ${JSON.stringify(property, null, 2)}`);
493
- // TODO: Handle UserList
494
- // TODO: Handle ObjectReferenceList
495
- }
496
- }
497
- exports.pickRandomValueForProperty = pickRandomValueForProperty;
498
- function pickRandomOptions(options, count) {
499
- const shuffled = options.sort(() => 0.5 - Math.random());
500
- return shuffled.slice(0, count);
501
- }
502
- function generateRandomBooleanValue() {
503
- return Math.random() < 0.5;
504
- }
505
- function generateRandomNumber(min, max) {
506
- if (min === undefined) {
507
- min = 0;
508
- }
509
- if (max === undefined) {
510
- max = 100;
511
- }
512
- return Math.floor(Math.random() * (max - min + 1)) + min;
513
- }
514
- function generateRandomReadableString() {
515
- return (0, unique_names_generator_1.uniqueNamesGenerator)({
516
- dictionaries: [unique_names_generator_1.adjectives, unique_names_generator_1.animals, unique_names_generator_1.colors, unique_names_generator_1.animals, unique_names_generator_1.colors],
517
- length: 5,
518
- });
519
- }
520
- function generateRandomDateString() {
521
- return new Date().toISOString();
522
- }
523
- function castValueToPropertyType(value, propertyType, propertySlug) {
524
- if (Array.isArray(value) && propertyType !== types_1.PropertyType.MultiSelect) {
525
- return value.map((element) => castValueToPropertyType(element, propertyType, propertySlug));
526
- }
527
- switch (propertyType) {
528
- case types_1.PropertyType.Boolean:
529
- return value.toString().toLowerCase() === 'true';
530
- case types_1.PropertyType.Number:
531
- const numValue = parseFloat(value.toString());
532
- if (isNaN(numValue)) {
533
- throw new Error(`Invalid number value: ${value}`);
534
- }
535
- return numValue;
536
- case types_1.PropertyType.Date:
537
- return new Date(value.toString()).toISOString();
538
- case types_1.PropertyType.MultiSelect:
539
- if (Array.isArray(value)) {
540
- return value;
541
- }
542
- // the old comma syntax parses as one literal value; warn instead of guessing at a split
543
- if (typeof value === 'string' && value.includes(',')) {
544
- console.error(`${propertySlug} value "${value}" contains a comma and is treated as one literal value. To pass several values, repeat the key: ${propertySlug}=${value
545
- .split(',')
546
- .join(` ${propertySlug}=`)}`);
547
- }
548
- return [value];
549
- default:
550
- return value; // For string and other types, return as is
551
- }
552
- }
553
- exports.castValueToPropertyType = castValueToPropertyType;
554
- async function createEntity(entityName, entity, routing = {}) {
555
- const client = new sdk_1.Entities();
556
- const skipHydrateRelationships = SHOULD_SKIP_HYDRATE_RELATIONSHIPS;
557
- const { suffix, apiVersion } = routing;
558
- if (entityName === 'assortment-item' && !suffix)
559
- return (0, entities_1.createAssortmentItem)(entity, { skipHydrateRelationships, apiVersion }); // special case
560
- const response = await client.create({
561
- entityName,
562
- object: entity,
563
- skipHydrateRelationships,
564
- suffix,
565
- apiVersion,
566
- });
567
- return response;
568
- }
569
- function getReferencedObjectPaths(type) {
570
- const properties = type.typeProperties || [];
571
- return properties
572
- .filter((prop) => prop.propertyType === types_1.PropertyType.ObjectReference)
573
- .map(({ referencedTypePath }) => referencedTypePath);
574
- }
575
- exports.getReferencedObjectPaths = getReferencedObjectPaths;
576
- async function buildLocalObjectReferencesCache(paths) {
577
- const cache = new Map();
578
- const getExampleCustomEntitiesByTypePath = (path) => {
579
- const client = new sdk_1.Entities();
580
- const entities = client.get({
581
- entityName: 'custom-entity',
582
- criteria: {
583
- typePath: path,
584
- },
585
- });
586
- return entities;
587
- };
588
- const getExampleEntites = async (path) => {
589
- if (path.startsWith('custom-entity')) {
590
- return getExampleCustomEntitiesByTypePath(path);
591
- }
592
- const { root } = (0, types_2.parseTypePath)(path);
593
- const client = new sdk_1.Entities();
594
- const entities = await client.get({
595
- entityName: root,
596
- });
597
- return entities;
598
- };
599
- const entitiesByPath = await Promise.all((paths || []).map(async (path) => {
600
- const entities = await getExampleEntites(path);
601
- return { path, entities };
602
- }));
603
- entitiesByPath.forEach(({ path, entities }) => {
604
- const cacheForPath = buildObjectReferenceCache(entities);
605
- cache.set(path, cacheForPath);
606
- });
607
- return cache;
608
- }
609
- function buildObjectReferenceCache(entities) {
610
- const cache = new Map();
611
- entities.forEach((entity) => {
612
- const { id } = entity;
613
- if (id && !cache.has(id)) {
614
- cache.set(id, entity);
615
- }
616
- });
617
- return cache;
618
- }
619
- exports.buildObjectReferenceCache = buildObjectReferenceCache;
620
- function selectRandomObject(cache) {
621
- return Array.from(cache.values())[Math.floor(Math.random() * cache.size)];
622
- }
623
- exports.selectRandomObject = selectRandomObject;
624
- function requiredValues(path, typeCache) {
625
- if (path.startsWith('custom-entity')) {
626
- return [{ slug: 'typeId', value: typeCache.get(path)?.id || '' }];
627
- }
628
- }
629
- function getPropertySlug(property) {
630
- return property.propertyType === types_1.PropertyType.ObjectReference
631
- ? `${property.slug}Id`
632
- : property.slug;
633
- }
634
- function doesPropertyLevelMatchRole(propertyLevel, role) {
635
- const isMatchingLevel = propertyLevel === role;
636
- return (isMatchingLevel ||
637
- propertyLevel === types_1.PropertyLevel.ALL ||
638
- propertyLevel === types_1.PropertyLevel.OVERRIDABLE);
639
- }
640
- exports.doesPropertyLevelMatchRole = doesPropertyLevelMatchRole;