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

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.82b70ea linux-x64 node-v24.22.1
20
+ @contrail/cli/3.6.0-alpha-8-alpha.5ffe1e1 linux-x64 node-v24.22.2
21
21
  $ contrail --help [COMMAND]
22
22
  USAGE
23
23
  $ contrail COMMAND
@@ -1,4 +1,4 @@
1
- import { PropertyLevel, PropertyType } from '@contrail/types';
1
+ import { PropertyLevel } 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';
@@ -42,7 +42,6 @@ export type WithId = {
42
42
  export type ObjectReferenceCache = Map<string, WithId>;
43
43
  type ObjectReferenceCachesByTypePath = Map<string, ObjectReferenceCache>;
44
44
  export declare function pickRandomValueForProperty(property: ExtendedTypeProperty, objectReferencesCache: ObjectReferenceCachesByTypePath, typeReferencesCache: TypeReferencesCacheByPath): number | string | string[] | boolean | null;
45
- export declare function castValueToPropertyType(value: string | number | string[] | number[], propertyType: PropertyType, propertySlug: string): any;
46
45
  export declare function getReferencedObjectPaths(type: TypeWithProperties): ColonDelimited[];
47
46
  export declare function buildObjectReferenceCache(entities: any[]): ObjectReferenceCache;
48
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.castValueToPropertyType = exports.pickRandomValueForProperty = exports.pickRandomPropertyValues = exports.summarizeSettledCreates = void 0;
3
+ exports.doesPropertyLevelMatchRole = exports.selectRandomObject = exports.buildObjectReferenceCache = exports.getReferencedObjectPaths = exports.pickRandomValueForProperty = exports.pickRandomPropertyValues = 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");
@@ -14,6 +14,7 @@ const common_1 = require("../../common");
14
14
  const basecommand_1 = require("../../basecommand");
15
15
  const sdk_1 = require("@contrail/sdk");
16
16
  const entities_1 = require("../../helpers/entities");
17
+ const propertyValues_1 = require("../../helpers/propertySpecifications/propertyValues");
17
18
  const propertySpecifications_1 = require("../../helpers/propertySpecifications/propertySpecifications");
18
19
  const file_helpers_1 = require("../../helpers/file-helpers");
19
20
  let IS_DRY_RUN = false;
@@ -233,6 +234,9 @@ class CreateEntity extends basecommand_1.BaseCommand {
233
234
  this.error(`create takes no positional ids (got: ${strayTokens.join(' ')}); did you forget -- before property values?`);
234
235
  }
235
236
  const propertySpecBySlug = (0, propertySpecifications_1.parsePropertySpecificationsIntoMap)(specs);
237
+ if (Array.isArray(propertySpecBySlug.get('typePath'))) {
238
+ this.error('typePath takes a single value. Repeat the key only for multi-value properties.');
239
+ }
236
240
  // Validate args
237
241
  if (!entityTypePath) {
238
242
  this.error('You must specify an entity type path.');
@@ -360,17 +364,19 @@ async function buildEntitiesToCreate(entityTypePath, entities, propertySpecifica
360
364
  function createEntityWithPopulatedValues(type, typeReferencesCache, objectReferencesCache, propertySpecificationBySlug, inputRow) {
361
365
  const rolesValue = inputRow?.roles ?? propertySpecificationBySlug?.get('roles');
362
366
  const roles = rolesValue === undefined ? undefined : [].concat(rolesValue);
363
- const suppliedSlugs = collectSuppliedSlugs(propertySpecificationBySlug, inputRow);
367
+ const suppliedSlugs = new Set([...(propertySpecificationBySlug?.entries() ?? []), ...Object.entries(inputRow ?? {})]
368
+ .filter(([, value]) => value !== undefined)
369
+ .map(([slug]) => slug));
364
370
  const entity = SHOULD_GENERATE_MISSING_VALUES
365
371
  ? pickRandomPropertyValues(type, objectReferencesCache, typeReferencesCache, roles, suppliedSlugs)
366
372
  : {};
367
373
  // Handle property specifications
368
374
  for (const [propertySlug, specifiedValue] of propertySpecificationBySlug.entries()) {
369
- const correspondingProperty = type.typeProperties.find((prop) => getPropertySlug(prop) === propertySlug);
375
+ const correspondingProperty = type.typeProperties.find((prop) => (0, propertyValues_1.getPropertySlug)(prop) === propertySlug);
370
376
  if (specifiedValue === undefined) {
371
377
  continue;
372
378
  }
373
- entity[propertySlug] = castValueToPropertyType(specifiedValue, correspondingProperty?.propertyType || types_1.PropertyType.String, propertySlug);
379
+ entity[propertySlug] = (0, propertyValues_1.castValueToPropertyType)(specifiedValue, correspondingProperty?.propertyType || types_1.PropertyType.String, propertySlug);
374
380
  }
375
381
  // Give Readbable IDs if specified
376
382
  if (SHOULD_USE_READABLE_IDS) {
@@ -400,15 +406,6 @@ function createEntityWithPopulatedValues(type, typeReferencesCache, objectRefere
400
406
  }
401
407
  return entity;
402
408
  }
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
409
  function pickRandomPropertyValues(type, objectReferencesCache, typeReferencesCache, roles, suppliedSlugs) {
413
410
  const entity = {};
414
411
  // Get values for properties
@@ -416,7 +413,7 @@ function pickRandomPropertyValues(type, objectReferencesCache, typeReferencesCac
416
413
  // Validate property level
417
414
  if (roles?.length && roles.every((r) => !doesPropertyLevelMatchRole(property.propertyLevel, r)))
418
415
  continue;
419
- if (suppliedSlugs?.has(getPropertySlug(property)))
416
+ if (suppliedSlugs?.has((0, propertyValues_1.getPropertySlug)(property)))
420
417
  continue;
421
418
  // Generate random value
422
419
  if (property.propertyType === types_1.PropertyType.ObjectReference) {
@@ -424,10 +421,10 @@ function pickRandomPropertyValues(type, objectReferencesCache, typeReferencesCac
424
421
  if (!cache || cache.size === 0) {
425
422
  throw new Error(`No object references found for referencedTypePath: ${property.referencedTypePath}`);
426
423
  }
427
- entity[getPropertySlug(property)] = selectRandomObject(cache).id;
424
+ entity[(0, propertyValues_1.getPropertySlug)(property)] = selectRandomObject(cache).id;
428
425
  }
429
426
  else {
430
- entity[getPropertySlug(property)] = pickRandomValueForProperty(property, objectReferencesCache, typeReferencesCache);
427
+ entity[(0, propertyValues_1.getPropertySlug)(property)] = pickRandomValueForProperty(property, objectReferencesCache, typeReferencesCache);
431
428
  }
432
429
  }
433
430
  return entity;
@@ -520,37 +517,6 @@ function generateRandomReadableString() {
520
517
  function generateRandomDateString() {
521
518
  return new Date().toISOString();
522
519
  }
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
520
  async function createEntity(entityName, entity, routing = {}) {
555
521
  const client = new sdk_1.Entities();
556
522
  const skipHydrateRelationships = SHOULD_SKIP_HYDRATE_RELATIONSHIPS;
@@ -626,11 +592,6 @@ function requiredValues(path, typeCache) {
626
592
  return [{ slug: 'typeId', value: typeCache.get(path)?.id || '' }];
627
593
  }
628
594
  }
629
- function getPropertySlug(property) {
630
- return property.propertyType === types_1.PropertyType.ObjectReference
631
- ? `${property.slug}Id`
632
- : property.slug;
633
- }
634
595
  function doesPropertyLevelMatchRole(propertyLevel, role) {
635
596
  const isMatchingLevel = propertyLevel === role;
636
597
  return (isMatchingLevel ||
@@ -514,37 +514,6 @@ 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([
520
- 'option',
521
- ]);
522
- });
523
- it('should pass arrays through on multi-value properties', () => {
524
- expect((0, create_1.castValueToPropertyType)(['option', 'family'], types_1.PropertyType.MultiSelect, 'colors')).toEqual(['option', 'family']);
525
- });
526
- it('should keep a comma value literal on a multi-value property and warn with the repeated-key form', () => {
527
- const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined);
528
- expect((0, create_1.castValueToPropertyType)('option,family', types_1.PropertyType.MultiSelect, 'colors')).toEqual([
529
- 'option,family',
530
- ]);
531
- expect(consoleError).toHaveBeenCalledWith(expect.stringContaining('colors=option colors=family'));
532
- consoleError.mockRestore();
533
- });
534
- it('should cast each element of a repeated-key array on scalar property types', () => {
535
- expect((0, create_1.castValueToPropertyType)(['1', '2'], types_1.PropertyType.Number, 'rank')).toEqual([1, 2]);
536
- expect((0, create_1.castValueToPropertyType)(['true', 'false'], types_1.PropertyType.Boolean, 'isActive')).toEqual([
537
- true,
538
- false,
539
- ]);
540
- });
541
- it('should keep commas literal on string properties without warning', () => {
542
- const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined);
543
- expect((0, create_1.castValueToPropertyType)('my,name', types_1.PropertyType.String, 'name')).toBe('my,name');
544
- expect(consoleError).not.toHaveBeenCalled();
545
- consoleError.mockRestore();
546
- });
547
- });
548
517
  describe('pickRandomPropertyValues', () => {
549
518
  const caches = [new Map(), new Map()];
550
519
  const typeWith = (properties) => ({ typePath: 't', typeProperties: properties });
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
4
  const fs_1 = tslib_1.__importDefault(require("fs"));
5
5
  const core_1 = require("@oclif/core");
6
+ const types_1 = require("../../api/types");
7
+ const propertyValues_1 = require("../../helpers/propertySpecifications/propertyValues");
6
8
  const basecommand_1 = require("../../basecommand");
7
9
  const sdk_1 = require("@contrail/sdk");
8
10
  const login_1 = require("../../auth/login");
@@ -127,12 +129,12 @@ class GetEntity extends basecommand_1.BaseCommand {
127
129
  .map((s) => s.trim())
128
130
  .filter(Boolean)
129
131
  : [];
132
+ const queryTypes = await resolveQueryTypes(entityName, propertySpecBySlug);
130
133
  try {
131
- // TODO: Refactor this so it's easier to read. It was partially vibe-coded and Adam
132
- // thinks it is hard to read. Consider breaking it into smaller functions.
134
+ // TODO: break the paginated and single-shot branches into their own functions.
133
135
  if (SHOULD_USE_PAGINATED_FIND) {
134
136
  const stream = streamPaginatedFind(entityName, {
135
- criteria: convertPropertySpecIntoCriteria(propertySpecBySlug),
137
+ criteria: convertPropertySpecIntoCriteria(propertySpecBySlug, queryTypes),
136
138
  skipHydrateRelationships,
137
139
  skip,
138
140
  suffix,
@@ -154,7 +156,7 @@ class GetEntity extends basecommand_1.BaseCommand {
154
156
  console.error(`Output saved to ${outputFile}`);
155
157
  }
156
158
  else {
157
- const response = await getEntitiesByName(entityName, propertySpecBySlug, {
159
+ const response = await getEntitiesByName(entityName, propertySpecBySlug, queryTypes, {
158
160
  skipHydrateRelationships,
159
161
  relations,
160
162
  propertySlugs: propertySlugsArray,
@@ -184,10 +186,10 @@ class GetEntity extends basecommand_1.BaseCommand {
184
186
  }
185
187
  }
186
188
  exports.default = GetEntity;
187
- async function getEntitiesByName(entityName, propertySpec, options = {}) {
189
+ async function getEntitiesByName(entityName, propertySpec, typePropertySets, options = {}) {
188
190
  const { propertySlugs, relations, skipHydrateRelationships, skip, suffix, apiVersion, take } = options;
189
191
  const id = propertySpec?.get('id')?.toString() || undefined;
190
- const criteria = convertPropertySpecIntoCriteria(propertySpec || new Map());
192
+ const criteria = convertPropertySpecIntoCriteria(propertySpec || new Map(), typePropertySets);
191
193
  return find(entityName, {
192
194
  id,
193
195
  // a missing id returns null (no retries); the command turns it into a clean not-found error
@@ -202,15 +204,32 @@ async function getEntitiesByName(entityName, propertySpec, options = {}) {
202
204
  take,
203
205
  });
204
206
  }
205
- function convertPropertySpecIntoCriteria(propertySpec) {
206
- const criteria = {};
207
+ function convertPropertySpecIntoCriteria(propertySpec, typePropertySets = []) {
208
+ const ranges = new Map();
209
+ const values = new Map();
207
210
  propertySpec.forEach((value, slug) => {
208
- criteria[slug] = (0, dateRanges_1.isDateRangeValue)(value)
209
- ? (0, dateRanges_1.convertDateRangeToJSURL)((0, dateRanges_1.parseDateRange)(value))
210
- : value;
211
+ ((0, dateRanges_1.isDateRangeValue)(value) ? ranges : values).set(slug, value);
212
+ });
213
+ const criteria = (0, propertyValues_1.castCriteriaValues)(values, typePropertySets);
214
+ ranges.forEach((value, slug) => {
215
+ criteria[slug] = (0, dateRanges_1.convertDateRangeToJSURL)((0, dateRanges_1.parseDateRange)(value));
211
216
  });
212
217
  return criteria;
213
218
  }
219
+ /**
220
+ * The types a query should be read against: the subtypes named by a typePath
221
+ * criterion if there is one, otherwise the entity's root type. A subtype
222
+ * carries its inherited properties, so one lookup per named path is enough.
223
+ */
224
+ async function resolveQueryTypes(entityName, propertySpec) {
225
+ const specified = propertySpec.get('typePath');
226
+ const paths = specified === undefined ? [entityName] : [specified].flat().map(String);
227
+ const types = await Promise.all(paths.map((path) => (0, types_1.getTypeByPath)(path).catch(() => {
228
+ console.error(`Could not resolve type ${path}; criteria on it are read as written.`);
229
+ return undefined;
230
+ })));
231
+ return types.map((type) => type?.typeProperties);
232
+ }
214
233
  async function find(entityName, options = {}) {
215
234
  const client = new sdk_1.Entities();
216
235
  const { criteria, id, ignore404, propertySlugs, skipHydrateRelationships, relations, skip, suffix, apiVersion, take, } = options;
@@ -268,9 +287,3 @@ async function* streamPaginatedFind(entityName, options = {}) {
268
287
  return;
269
288
  }
270
289
  }
271
- // Useful for troubleshooting
272
- function logMemoryUsage(entityCount) {
273
- const used = process.memoryUsage();
274
- const toMB = (bytes) => (bytes / 1024 / 1024).toFixed(2);
275
- console.error(`[${entityCount} entities] Memory Usage → RSS: ${toMB(used.rss)} MB | Heap: ${toMB(used.heapUsed)} MB / ${toMB(used.heapTotal)} MB`);
276
- }
@@ -10,6 +10,8 @@ const login_1 = require("../../auth/login");
10
10
  const common_1 = require("../../common");
11
11
  const propertySpecifications_1 = require("../../helpers/propertySpecifications/propertySpecifications");
12
12
  const file_helpers_1 = require("../../helpers/file-helpers");
13
+ const propertyValues_1 = require("../../helpers/propertySpecifications/propertyValues");
14
+ const types_1 = require("../../api/types");
13
15
  class UpdateEntity extends basecommand_1.BaseCommand {
14
16
  static description = 'Update an entity';
15
17
  static examples = [
@@ -88,12 +90,24 @@ class UpdateEntity extends basecommand_1.BaseCommand {
88
90
  : positionalIds.map((id) => ({ id }));
89
91
  const skipped = entitiesToUpdate.filter(({ id }) => !id).length;
90
92
  const entitiesWithId = entitiesToUpdate.filter(({ id }) => id);
91
- // will be applied to all entities
93
+ if (Array.isArray(propertySpec.get('typePath'))) {
94
+ this.error('typePath takes a single value. Repeat the key only for multi-value properties.');
95
+ }
96
+ // cast against each record's own subtype: the API converts numeric strings itself
97
+ // but rejects boolean ones, so an uncast isArchived=false comes back as a 400
98
+ const typePropertiesById = await resolvePropertiesByEntityId(entityName, entitiesWithId.map(({ id }) => id));
92
99
  // JSON.stringify drops undefined keys, so an unset has to travel as an explicit null
93
- const fixedValues = Object.fromEntries([...propertySpec.entries()].map(([slug, value]) => [slug, value ?? null]));
100
+ const unsetValues = Object.fromEntries([...propertySpec.keys()]
101
+ .filter((slug) => propertySpec.get(slug) === undefined)
102
+ .map((slug) => [slug, null]));
103
+ const specifiedValues = new Map([...propertySpec.entries()].filter(([, value]) => value !== undefined));
94
104
  async function updateEntity(entity) {
95
- const newEntityState = { ...entity, ...fixedValues };
96
105
  const id = entity.id;
106
+ const newEntityState = {
107
+ ...entity,
108
+ ...(0, propertyValues_1.castValuesToPropertyTypes)(specifiedValues, typePropertiesById.get(id)),
109
+ ...unsetValues,
110
+ };
97
111
  return isDryRun
98
112
  ? mockUpdateById(entityName, id, newEntityState, { skipHydrateRelationships })
99
113
  : updateEntityById(entityName, id, newEntityState, {
@@ -121,6 +135,39 @@ class UpdateEntity extends basecommand_1.BaseCommand {
121
135
  }
122
136
  }
123
137
  exports.default = UpdateEntity;
138
+ // The ids criterion travels in the URL, which the gateway rejects somewhere past
139
+ // 5k characters, so the lookup goes out in chunks.
140
+ const ID_LOOKUP_CHUNK_SIZE = 250;
141
+ async function resolvePropertiesByEntityId(entityName, ids) {
142
+ const rootType = await (0, types_1.getTypeByPath)(entityName).catch(() => undefined);
143
+ const typePathById = await fetchTypePathsByIds(entityName, ids);
144
+ const distinctPaths = [...new Set([...typePathById.values()])];
145
+ const propertiesByPath = new Map();
146
+ await Promise.all(distinctPaths.map(async (path) => {
147
+ const type = await (0, types_1.getTypeByPath)(path).catch(() => undefined);
148
+ propertiesByPath.set(path, type?.typeProperties ?? rootType?.typeProperties);
149
+ }));
150
+ // an id the lookup did not return falls back to the root type; the write reports its own 404
151
+ return new Map(ids.map((id) => [id, propertiesByPath.get(typePathById.get(id)) ?? rootType?.typeProperties]));
152
+ }
153
+ async function fetchTypePathsByIds(entityName, ids) {
154
+ const client = new sdk_1.Entities();
155
+ const chunks = [];
156
+ for (let i = 0; i < ids.length; i += ID_LOOKUP_CHUNK_SIZE) {
157
+ chunks.push(ids.slice(i, i + ID_LOOKUP_CHUNK_SIZE));
158
+ }
159
+ const pages = await Promise.all(chunks.map((chunk) => client
160
+ .get({
161
+ entityName,
162
+ criteria: { ids: chunk },
163
+ customParams: { propertySlugs: 'id,typePath' },
164
+ })
165
+ .catch(() => [])));
166
+ return new Map(pages
167
+ .flat()
168
+ .filter((entity) => entity?.id && entity?.typePath)
169
+ .map((entity) => [entity.id, entity.typePath]));
170
+ }
124
171
  function summarizeSettledUpdates(inputs, settled, skipped) {
125
172
  const updated = [];
126
173
  const failed = [];
@@ -1,8 +1,6 @@
1
1
  import { Item } from '@contrail/entity-types';
2
2
  export type SparseItem = Pick<Item, 'id' | 'itemFamilyId' | 'roles' | 'name'>;
3
- export declare function getAllItemsUsingCacheFallback(): Promise<SparseItem[]>;
4
3
  export declare function getManyItems(maxCount?: number): Promise<SparseItem[]>;
5
4
  export declare function getItemFamilies(count: number): Promise<SparseItem[] | undefined>;
6
- export declare function getFamilyName(item: SparseItem): Promise<string[] | undefined>;
7
5
  export declare const Roles: readonly ["option", "family"];
8
6
  export type Role = (typeof Roles)[number];
@@ -1,35 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Roles = exports.getFamilyName = exports.getItemFamilies = exports.getManyItems = exports.getAllItemsUsingCacheFallback = void 0;
3
+ exports.Roles = exports.getItemFamilies = exports.getManyItems = void 0;
4
4
  const sdk_1 = require("@contrail/sdk");
5
- const ITEMS_CACHE_BY_ID = new Map();
6
- async function getAllItemsUsingCacheFallback() {
7
- if (ITEMS_CACHE_BY_ID.size > 0) {
8
- return Array.from(ITEMS_CACHE_BY_ID.values());
9
- }
10
- const items = await getManyItems();
11
- items.forEach((item) => {
12
- ITEMS_CACHE_BY_ID.set(item.id, item);
13
- });
14
- return items;
15
- }
16
- exports.getAllItemsUsingCacheFallback = getAllItemsUsingCacheFallback;
17
5
  async function getManyItems(maxCount = 10000) {
18
6
  const client = new sdk_1.Entities();
19
- // paginate to get all items
20
- // Note: This will only return the first 100 assortments by default.
21
7
  const items = [];
22
8
  let nextPageKey = undefined;
23
9
  while (true) {
24
10
  const response = await client.get({
25
11
  entityName: 'item',
26
12
  apiVersion: sdk_1.API_VERSION.V2,
27
- // customParams: { propertySlugs: 'id,familyId,roles,name' }, // not compatible with V2 for some reason
28
13
  nextPageKey,
29
14
  });
30
15
  nextPageKey = response.nextPageKey;
31
16
  if (response.results.length === 0) {
32
- break; // No more assortments to fetch
17
+ break;
33
18
  }
34
19
  items.push(...response.results);
35
20
  if (!nextPageKey) {
@@ -37,7 +22,7 @@ async function getManyItems(maxCount = 10000) {
37
22
  }
38
23
  if (items.length >= maxCount) {
39
24
  console.warn(`Reached maximum item limit of ${maxCount}. Some items may not be included.`);
40
- break; // Stop if we reach the maximum limit
25
+ break;
41
26
  }
42
27
  }
43
28
  return items;
@@ -47,23 +32,6 @@ async function getItemFamilies(count) {
47
32
  return getItems({ roles: ['family'] }, count);
48
33
  }
49
34
  exports.getItemFamilies = getItemFamilies;
50
- async function getFamilyName(item) {
51
- if (!item.roles.includes('option')) {
52
- return undefined;
53
- }
54
- if (!item.itemFamilyId) {
55
- return undefined;
56
- }
57
- await ensureItemCacheIsPopulated();
58
- const family = ITEMS_CACHE_BY_ID.get(item.itemFamilyId);
59
- return family ? [family.name] : ['placeholder']; // placeholder if family not found
60
- }
61
- exports.getFamilyName = getFamilyName;
62
- async function ensureItemCacheIsPopulated() {
63
- if (ITEMS_CACHE_BY_ID.size === 0) {
64
- await getAllItemsUsingCacheFallback();
65
- }
66
- }
67
35
  exports.Roles = ['option', 'family'];
68
36
  async function getItems(criteria, count = 100) {
69
37
  const client = new sdk_1.Entities();
@@ -78,7 +46,7 @@ async function getItems(criteria, count = 100) {
78
46
  });
79
47
  nextPageKey = response.nextPageKey;
80
48
  if (response.results.length === 0) {
81
- break; // No more items to fetch
49
+ break;
82
50
  }
83
51
  const numItemsCanBeAdded = count - items.length;
84
52
  const itemsToAdd = response.results.slice(0, numItemsCanBeAdded);
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * Date Range Parsing Utilities
3
3
  *
4
- * Handles parsing date range syntax like:
5
- * - createdOn=2025-09-15..2025-09-16 (date range)
6
- * - createdOn=2025-09-15T04:00:00Z..2025-09-16T03:59:59Z (timestamp range)
7
- * - createdOn=2025-09-15.. (from date onwards)
8
- * - createdOn=..2025-09-16 (until date)
4
+ * Resolves the date range syntax used in get criteria values:
5
+ * - 2025-09-15..2025-09-16 (date range)
6
+ * - 2025-09-15T04:00:00Z..2025-09-16T03:59:59Z (timestamp range)
7
+ * - 2025-09-15.. (from date onwards)
8
+ * - ..2025-09-16 (until date)
9
9
  */
10
10
  export type DateRange = {
11
11
  start?: Date;
@@ -2,11 +2,11 @@
2
2
  /**
3
3
  * Date Range Parsing Utilities
4
4
  *
5
- * Handles parsing date range syntax like:
6
- * - createdOn=2025-09-15..2025-09-16 (date range)
7
- * - createdOn=2025-09-15T04:00:00Z..2025-09-16T03:59:59Z (timestamp range)
8
- * - createdOn=2025-09-15.. (from date onwards)
9
- * - createdOn=..2025-09-16 (until date)
5
+ * Resolves the date range syntax used in get criteria values:
6
+ * - 2025-09-15..2025-09-16 (date range)
7
+ * - 2025-09-15T04:00:00Z..2025-09-16T03:59:59Z (timestamp range)
8
+ * - 2025-09-15.. (from date onwards)
9
+ * - ..2025-09-16 (until date)
10
10
  */
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.convertDateRangeToJSURL = exports.parseDate = exports.parseDateRange = exports.isDateRangeValue = void 0;
@@ -19,7 +19,6 @@
19
19
  * contrail entities get color -- id=123
20
20
  * contrail entities update color 123 -- name=obsidian hex=000000
21
21
  * contrail entities update color 123 -- description= notes='""'
22
- * contrail entities get loader-processes -- createdOn=2025-09-15..2025-09-16 (ranges resolve in get)
23
22
  */
24
23
  export type PropertySpecification = {
25
24
  slug: string;
@@ -20,7 +20,6 @@
20
20
  * contrail entities get color -- id=123
21
21
  * contrail entities update color 123 -- name=obsidian hex=000000
22
22
  * contrail entities update color 123 -- description= notes='""'
23
- * contrail entities get loader-processes -- createdOn=2025-09-15..2025-09-16 (ranges resolve in get)
24
23
  */
25
24
  Object.defineProperty(exports, "__esModule", { value: true });
26
25
  exports.isValidPropertySpecification = exports.partitionIdsAndSpecs = exports.parsePropertySpecificationsIntoMap = exports.parsePropertySpecification = void 0;
@@ -80,8 +79,7 @@ exports.parsePropertySpecificationsIntoMap = parsePropertySpecificationsIntoMap;
80
79
  * property specifications.
81
80
  */
82
81
  function partitionIdsAndSpecs(tokens) {
83
- // a token carrying '=' is neither an id nor a usable spec, so dropping it would
84
- // silently discard a filter the caller asked for
82
+ // a token carrying '=' belongs to neither bucket below, so it would vanish silently
85
83
  const malformed = tokens.filter((token) => token.includes('=') && !isValidPropertySpecification(token));
86
84
  if (malformed.length > 0) {
87
85
  throw new Error(`Invalid property specification: ${malformed.join(' ')}. Expected slug=value.`);
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Turns parsed property specification values into the shapes the API expects.
3
+ *
4
+ * Writes cast only from a type definition and never guess, so a wrong value
5
+ * fails loudly rather than being silently rewritten. Reads fall back to the
6
+ * value's own shape for slugs no resolved type defines, because the alternative
7
+ * is a criterion that matches nothing and reports no error.
8
+ */
9
+ import { PropertyType, TypeProperty } from '@contrail/types';
10
+ export declare function getPropertySlug(property: TypeProperty): string;
11
+ export declare function castValueToPropertyType(value: string | number | string[] | number[], propertyType: PropertyType, propertySlug: string): any;
12
+ /**
13
+ * Coerces a value from its own shape. Only used for reads, and only for slugs
14
+ * no resolved type defines.
15
+ */
16
+ export declare function inferAndCastValue(value: any): any;
17
+ /**
18
+ * Builds the slug to property type lookup for one or more resolved types.
19
+ * Where two types define the same slug differently the first one given wins.
20
+ */
21
+ export declare function buildPropertyTypeMap(typePropertySets: (TypeProperty[] | undefined)[]): Map<string, PropertyType>;
22
+ /**
23
+ * Casts values for a write. A slug the type does not define is written through
24
+ * unchanged, which is what happens for a property only a subtype declares.
25
+ */
26
+ export declare function castValuesToPropertyTypes(valueBySlug: Map<string, any>, typeProperties?: TypeProperty[]): Record<string, any>;
27
+ /**
28
+ * Casts values for a read, falling back to the value's own shape so that a
29
+ * criterion on a slug the resolved types do not define still matches.
30
+ */
31
+ export declare function castCriteriaValues(valueBySlug: Map<string, any>, typePropertySets?: (TypeProperty[] | undefined)[]): Record<string, any>;
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ /**
3
+ * Turns parsed property specification values into the shapes the API expects.
4
+ *
5
+ * Writes cast only from a type definition and never guess, so a wrong value
6
+ * fails loudly rather than being silently rewritten. Reads fall back to the
7
+ * value's own shape for slugs no resolved type defines, because the alternative
8
+ * is a criterion that matches nothing and reports no error.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.castCriteriaValues = exports.castValuesToPropertyTypes = exports.buildPropertyTypeMap = exports.inferAndCastValue = exports.castValueToPropertyType = exports.getPropertySlug = void 0;
12
+ const types_1 = require("@contrail/types");
13
+ // identifiers are always strings; coercing one would turn a numeric id into a number
14
+ const SLUGS_NEVER_CAST = new Set(['id', 'ids']);
15
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})?)?$/;
16
+ function getPropertySlug(property) {
17
+ return property.propertyType === types_1.PropertyType.ObjectReference
18
+ ? `${property.slug}Id`
19
+ : property.slug;
20
+ }
21
+ exports.getPropertySlug = getPropertySlug;
22
+ function castValueToPropertyType(value, propertyType, propertySlug) {
23
+ if (Array.isArray(value) && propertyType !== types_1.PropertyType.MultiSelect) {
24
+ return value.map((element) => castValueToPropertyType(element, propertyType, propertySlug));
25
+ }
26
+ switch (propertyType) {
27
+ case types_1.PropertyType.Boolean:
28
+ return value.toString().toLowerCase() === 'true';
29
+ case types_1.PropertyType.Number:
30
+ case types_1.PropertyType.Currency:
31
+ case types_1.PropertyType.Percent:
32
+ case types_1.PropertyType.Rating:
33
+ case types_1.PropertyType.Sequence:
34
+ const numValue = parseFloat(value.toString());
35
+ if (isNaN(numValue)) {
36
+ throw new Error(`Invalid number value: ${value}`);
37
+ }
38
+ return numValue;
39
+ case types_1.PropertyType.Date:
40
+ return new Date(value.toString()).toISOString();
41
+ case types_1.PropertyType.MultiSelect:
42
+ if (Array.isArray(value)) {
43
+ return value;
44
+ }
45
+ // the old comma syntax parses as one literal value; warn instead of guessing at a split
46
+ if (typeof value === 'string' && value.includes(',')) {
47
+ console.error(`${propertySlug} value "${value}" contains a comma and is treated as one literal value. To pass several values, repeat the key: ${propertySlug}=${value
48
+ .split(',')
49
+ .join(` ${propertySlug}=`)}`);
50
+ }
51
+ return [value];
52
+ default:
53
+ return value; // For string and other types, return as is
54
+ }
55
+ }
56
+ exports.castValueToPropertyType = castValueToPropertyType;
57
+ /**
58
+ * Coerces a value from its own shape. Only used for reads, and only for slugs
59
+ * no resolved type defines.
60
+ */
61
+ function inferAndCastValue(value) {
62
+ if (Array.isArray(value)) {
63
+ return value.map(inferAndCastValue);
64
+ }
65
+ if (typeof value !== 'string' || value === '') {
66
+ return value;
67
+ }
68
+ if (value === 'true')
69
+ return true;
70
+ if (value === 'false')
71
+ return false;
72
+ if (ISO_DATE.test(value) && !isNaN(new Date(value).getTime())) {
73
+ return new Date(value).toISOString();
74
+ }
75
+ // only coerce a number that survives the round trip, so 000000, 007 and 12.50 stay strings
76
+ const asNumber = Number(value);
77
+ return !isNaN(asNumber) && String(asNumber) === value ? asNumber : value;
78
+ }
79
+ exports.inferAndCastValue = inferAndCastValue;
80
+ /**
81
+ * Builds the slug to property type lookup for one or more resolved types.
82
+ * Where two types define the same slug differently the first one given wins.
83
+ */
84
+ function buildPropertyTypeMap(typePropertySets) {
85
+ const propertyTypeBySlug = new Map();
86
+ for (const typeProperties of typePropertySets) {
87
+ for (const property of typeProperties ?? []) {
88
+ const slug = getPropertySlug(property);
89
+ if (!propertyTypeBySlug.has(slug)) {
90
+ propertyTypeBySlug.set(slug, property.propertyType);
91
+ }
92
+ }
93
+ }
94
+ return propertyTypeBySlug;
95
+ }
96
+ exports.buildPropertyTypeMap = buildPropertyTypeMap;
97
+ /**
98
+ * Casts values for a write. A slug the type does not define is written through
99
+ * unchanged, which is what happens for a property only a subtype declares.
100
+ */
101
+ function castValuesToPropertyTypes(valueBySlug, typeProperties = []) {
102
+ const propertyTypeBySlug = buildPropertyTypeMap([typeProperties]);
103
+ return Object.fromEntries([...valueBySlug.entries()].map(([slug, value]) => [
104
+ slug,
105
+ SLUGS_NEVER_CAST.has(slug) || !propertyTypeBySlug.has(slug)
106
+ ? value
107
+ : castValueToPropertyType(value, propertyTypeBySlug.get(slug), slug),
108
+ ]));
109
+ }
110
+ exports.castValuesToPropertyTypes = castValuesToPropertyTypes;
111
+ /**
112
+ * Casts values for a read, falling back to the value's own shape so that a
113
+ * criterion on a slug the resolved types do not define still matches.
114
+ */
115
+ function castCriteriaValues(valueBySlug, typePropertySets = []) {
116
+ const propertyTypeBySlug = buildPropertyTypeMap(typePropertySets);
117
+ return Object.fromEntries([...valueBySlug.entries()].map(([slug, value]) => {
118
+ if (SLUGS_NEVER_CAST.has(slug))
119
+ return [slug, value];
120
+ return [
121
+ slug,
122
+ propertyTypeBySlug.has(slug)
123
+ ? castValueToPropertyType(value, propertyTypeBySlug.get(slug), slug)
124
+ : inferAndCastValue(value),
125
+ ];
126
+ }));
127
+ }
128
+ exports.castCriteriaValues = castCriteriaValues;
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const types_1 = require("@contrail/types");
4
+ const propertyValues_1 = require("./propertyValues");
5
+ describe('castValueToPropertyType array coercion', () => {
6
+ it('should coerce a single value on a multi-value property to a one-element array', () => {
7
+ expect((0, propertyValues_1.castValueToPropertyType)('option', types_1.PropertyType.MultiSelect, 'colors')).toEqual([
8
+ 'option',
9
+ ]);
10
+ });
11
+ it('should pass arrays through on multi-value properties', () => {
12
+ expect((0, propertyValues_1.castValueToPropertyType)(['option', 'family'], types_1.PropertyType.MultiSelect, 'colors')).toEqual(['option', 'family']);
13
+ });
14
+ it('should keep a comma value literal on a multi-value property and warn with the repeated-key form', () => {
15
+ const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined);
16
+ expect((0, propertyValues_1.castValueToPropertyType)('option,family', types_1.PropertyType.MultiSelect, 'colors')).toEqual([
17
+ 'option,family',
18
+ ]);
19
+ expect(consoleError).toHaveBeenCalledWith(expect.stringContaining('colors=option colors=family'));
20
+ consoleError.mockRestore();
21
+ });
22
+ it('should cast each element of a repeated-key array on scalar property types', () => {
23
+ expect((0, propertyValues_1.castValueToPropertyType)(['1', '2'], types_1.PropertyType.Number, 'rank')).toEqual([1, 2]);
24
+ expect((0, propertyValues_1.castValueToPropertyType)(['true', 'false'], types_1.PropertyType.Boolean, 'isActive')).toEqual([
25
+ true,
26
+ false,
27
+ ]);
28
+ });
29
+ it('should keep commas literal on string properties without warning', () => {
30
+ const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined);
31
+ expect((0, propertyValues_1.castValueToPropertyType)('my,name', types_1.PropertyType.String, 'name')).toBe('my,name');
32
+ expect(consoleError).not.toHaveBeenCalled();
33
+ consoleError.mockRestore();
34
+ });
35
+ });
36
+ describe('getPropertySlug', () => {
37
+ it('suffixes Id for an object reference', () => {
38
+ expect((0, propertyValues_1.getPropertySlug)({ slug: 'fabric', propertyType: types_1.PropertyType.ObjectReference })).toBe('fabricId');
39
+ });
40
+ it('leaves every other property type alone', () => {
41
+ expect((0, propertyValues_1.getPropertySlug)({ slug: 'name', propertyType: types_1.PropertyType.String })).toBe('name');
42
+ });
43
+ });
44
+ describe('castValuesToPropertyTypes', () => {
45
+ const typeProperties = [
46
+ { slug: 'isArchived', propertyType: types_1.PropertyType.Boolean },
47
+ { slug: 'rank', propertyType: types_1.PropertyType.Number },
48
+ { slug: 'fabric', propertyType: types_1.PropertyType.ObjectReference },
49
+ ];
50
+ it('casts each value using its property type', () => {
51
+ const result = (0, propertyValues_1.castValuesToPropertyTypes)(new Map([
52
+ ['isArchived', 'false'],
53
+ ['rank', '3'],
54
+ ]), typeProperties);
55
+ expect(result).toEqual({ isArchived: false, rank: 3 });
56
+ });
57
+ it('matches an object reference by its suffixed slug', () => {
58
+ const result = (0, propertyValues_1.castValuesToPropertyTypes)(new Map([['fabricId', 'abc']]), typeProperties);
59
+ expect(result).toEqual({ fabricId: 'abc' });
60
+ });
61
+ it('writes a slug the type does not define through as a string', () => {
62
+ const result = (0, propertyValues_1.castValuesToPropertyTypes)(new Map([['unknown', 'false']]), typeProperties);
63
+ expect(result).toEqual({ unknown: 'false' });
64
+ });
65
+ it('treats a missing type as defining no properties', () => {
66
+ expect((0, propertyValues_1.castValuesToPropertyTypes)(new Map([['isArchived', 'true']]))).toEqual({
67
+ isArchived: 'true',
68
+ });
69
+ });
70
+ });
71
+ describe('inferAndCastValue', () => {
72
+ it('coerces a number only when it survives the round trip', () => {
73
+ expect((0, propertyValues_1.inferAndCastValue)('3650')).toBe(3650);
74
+ expect((0, propertyValues_1.inferAndCastValue)('12.5')).toBe(12.5);
75
+ expect((0, propertyValues_1.inferAndCastValue)('0')).toBe(0);
76
+ });
77
+ it('keeps numeric-looking strings that would not round trip', () => {
78
+ // hex=000000 appears in the create examples, and parseFloat would make it 0
79
+ expect((0, propertyValues_1.inferAndCastValue)('000000')).toBe('000000');
80
+ expect((0, propertyValues_1.inferAndCastValue)('007')).toBe('007');
81
+ expect((0, propertyValues_1.inferAndCastValue)('12.50')).toBe('12.50');
82
+ expect((0, propertyValues_1.inferAndCastValue)('1e5')).toBe('1e5');
83
+ });
84
+ it('coerces exact booleans only', () => {
85
+ expect((0, propertyValues_1.inferAndCastValue)('true')).toBe(true);
86
+ expect((0, propertyValues_1.inferAndCastValue)('false')).toBe(false);
87
+ expect((0, propertyValues_1.inferAndCastValue)('True')).toBe('True');
88
+ });
89
+ it('coerces ISO dates', () => {
90
+ expect((0, propertyValues_1.inferAndCastValue)('2025-09-15')).toBe('2025-09-15T00:00:00.000Z');
91
+ expect((0, propertyValues_1.inferAndCastValue)('not-a-date')).toBe('not-a-date');
92
+ });
93
+ it('maps over arrays and leaves non-strings alone', () => {
94
+ expect((0, propertyValues_1.inferAndCastValue)(['1', 'x'])).toEqual([1, 'x']);
95
+ expect((0, propertyValues_1.inferAndCastValue)(7)).toBe(7);
96
+ });
97
+ });
98
+ describe('buildPropertyTypeMap', () => {
99
+ it('gives the first type precedence for a conflicting slug', () => {
100
+ const first = [{ slug: 'matchingProperty2', propertyType: types_1.PropertyType.Number }];
101
+ const second = [{ slug: 'matchingProperty2', propertyType: types_1.PropertyType.String }];
102
+ expect((0, propertyValues_1.buildPropertyTypeMap)([first, second]).get('matchingProperty2')).toBe(types_1.PropertyType.Number);
103
+ expect((0, propertyValues_1.buildPropertyTypeMap)([second, first]).get('matchingProperty2')).toBe(types_1.PropertyType.String);
104
+ });
105
+ it('tolerates a type that could not be resolved', () => {
106
+ expect((0, propertyValues_1.buildPropertyTypeMap)([undefined]).size).toBe(0);
107
+ });
108
+ });
109
+ describe('castCriteriaValues', () => {
110
+ const typeProperties = [
111
+ { slug: 'isArchived', propertyType: types_1.PropertyType.Boolean },
112
+ { slug: 'optionSequence', propertyType: types_1.PropertyType.Sequence },
113
+ { slug: 'hex', propertyType: types_1.PropertyType.String },
114
+ ];
115
+ it('casts a defined slug from its property type', () => {
116
+ expect((0, propertyValues_1.castCriteriaValues)(new Map([['isArchived', 'false']]), [typeProperties])).toEqual({
117
+ isArchived: false,
118
+ });
119
+ });
120
+ it('casts the whole numeric family, not just Number', () => {
121
+ expect((0, propertyValues_1.castCriteriaValues)(new Map([['optionSequence', '3650']]), [typeProperties])).toEqual({
122
+ optionSequence: 3650,
123
+ });
124
+ });
125
+ it('leaves a defined string property alone', () => {
126
+ expect((0, propertyValues_1.castCriteriaValues)(new Map([['hex', '000000']]), [typeProperties])).toEqual({
127
+ hex: '000000',
128
+ });
129
+ });
130
+ it('falls back to the value shape for an undefined slug', () => {
131
+ expect((0, propertyValues_1.castCriteriaValues)(new Map([['unknown', 'true']]), [typeProperties])).toEqual({
132
+ unknown: true,
133
+ });
134
+ });
135
+ it('never coerces id or ids', () => {
136
+ expect((0, propertyValues_1.castCriteriaValues)(new Map([
137
+ ['id', '12345'],
138
+ ['ids', ['1', '2']],
139
+ ]), [])).toEqual({ id: '12345', ids: ['1', '2'] });
140
+ });
141
+ });
142
+ describe('castValuesToPropertyTypes never guesses', () => {
143
+ it('writes an undefined slug through unchanged', () => {
144
+ expect((0, propertyValues_1.castValuesToPropertyTypes)(new Map([['unknown', 'true']]), [])).toEqual({
145
+ unknown: 'true',
146
+ });
147
+ });
148
+ });
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "3.6.0-alpha-8-alpha.82b70ea",
2
+ "version": "3.6.0-alpha-8-alpha.5ffe1e1",
3
3
  "commands": {
4
4
  "app:create": {
5
5
  "id": "app:create",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contrail/cli",
3
- "version": "3.6.0-alpha-8-alpha.82b70ea",
3
+ "version": "3.6.0-alpha-8-alpha.5ffe1e1",
4
4
  "description": "VibeIQ's Contrail Platform CLI.",
5
5
  "bin": {
6
6
  "contrail-cli": "./bin/run",