industrial-model 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -52,7 +52,108 @@ var MAX_DEPENDENCY_DEPTH = 3;
52
52
  var AGGREGATE_LIMIT = 1e3;
53
53
  var MAX_GROUP_BY = 5;
54
54
 
55
- // src/mappers/utils.ts
55
+ // src/utils/query.ts
56
+ function mapNodesAndEdges(queryResult, _query) {
57
+ return queryResult.items;
58
+ }
59
+ function appendNodesAndEdges(initial, additional) {
60
+ if (!additional) return initial;
61
+ for (const [key, items] of Object.entries(additional)) {
62
+ const existing = initial[key];
63
+ if (existing) {
64
+ existing.push(...items);
65
+ } else {
66
+ initial[key] = [...items];
67
+ }
68
+ }
69
+ return initial;
70
+ }
71
+ function getQueryForDependenciesPagination(query, queryResult, viewExternalId) {
72
+ const cursorKeys = new Set(Object.keys(queryResult.nextCursor));
73
+ const { nodesParent, nodesChildren } = getParentAndChildrenNodes(cursorKeys);
74
+ const leafCursors = getLeafCursors(queryResult, viewExternalId, nodesParent, nodesChildren);
75
+ if (Object.keys(leafCursors).length === 0) {
76
+ return null;
77
+ }
78
+ return buildDependenciesQuery(query, nodesParent, nodesChildren, leafCursors);
79
+ }
80
+ function getParentAndChildrenNodes(keys) {
81
+ const nodesParent = /* @__PURE__ */ new Map();
82
+ const nodesChildren = /* @__PURE__ */ new Map();
83
+ for (const key of keys) {
84
+ const keyParts = key.split(NESTED_SEP);
85
+ const validParents = /* @__PURE__ */ new Set();
86
+ for (let i = keyParts.length - 1; i > 0; i--) {
87
+ const parentPath = keyParts.slice(0, i).join(NESTED_SEP);
88
+ const parentWithEdgeMarker = `${parentPath}${NESTED_SEP}${EDGE_MARKER}`;
89
+ if (keys.has(parentWithEdgeMarker)) {
90
+ validParents.add(parentWithEdgeMarker);
91
+ const children = nodesChildren.get(parentWithEdgeMarker) ?? /* @__PURE__ */ new Set();
92
+ children.add(key);
93
+ nodesChildren.set(parentWithEdgeMarker, children);
94
+ }
95
+ if (keys.has(parentPath)) {
96
+ validParents.add(parentPath);
97
+ const children = nodesChildren.get(parentPath) ?? /* @__PURE__ */ new Set();
98
+ children.add(key);
99
+ nodesChildren.set(parentPath, children);
100
+ }
101
+ }
102
+ nodesParent.set(key, validParents);
103
+ }
104
+ return { nodesParent, nodesChildren };
105
+ }
106
+ function getLeafCursors(queryResult, viewExternalId, nodesParent, nodesChildren) {
107
+ const targetCursors = {};
108
+ const targetCursorKeys = /* @__PURE__ */ new Set();
109
+ for (const [cursorKey, cursorValue] of Object.entries(queryResult.nextCursor)) {
110
+ if (cursorKey === viewExternalId || !cursorValue || (queryResult.items[cursorKey]?.length ?? 0) !== MAX_LIMIT) {
111
+ continue;
112
+ }
113
+ const children = nodesChildren.get(cursorKey) ?? /* @__PURE__ */ new Set();
114
+ let skipDueToChild = false;
115
+ for (const c of children) {
116
+ if (targetCursorKeys.has(c)) {
117
+ skipDueToChild = true;
118
+ break;
119
+ }
120
+ }
121
+ if (skipDueToChild) continue;
122
+ const parent = nodesParent.get(cursorKey) ?? /* @__PURE__ */ new Set();
123
+ for (const key of parent) {
124
+ if (targetCursorKeys.has(key)) {
125
+ delete targetCursors[key];
126
+ targetCursorKeys.delete(key);
127
+ }
128
+ }
129
+ targetCursors[cursorKey] = cursorValue;
130
+ targetCursorKeys.add(cursorKey);
131
+ }
132
+ return targetCursors;
133
+ }
134
+ function buildDependenciesQuery(previousQuery, nodesParent, nodesChildren, leafCursors) {
135
+ const withExprs = {};
136
+ const selectExprs = {};
137
+ const finalCursors = {};
138
+ for (const [cursorKey, cursorValue] of Object.entries(leafCursors)) {
139
+ const children = nodesChildren.get(cursorKey) ?? /* @__PURE__ */ new Set();
140
+ const parent = nodesParent.get(cursorKey) ?? /* @__PURE__ */ new Set();
141
+ const validKeys = /* @__PURE__ */ new Set([...parent, ...children, cursorKey]);
142
+ for (const [k, v] of Object.entries(previousQuery.with)) {
143
+ if (validKeys.has(k)) withExprs[k] = v;
144
+ }
145
+ for (const [k, v] of Object.entries(previousQuery.select)) {
146
+ if (validKeys.has(k)) selectExprs[k] = v;
147
+ }
148
+ for (const [k, v] of Object.entries(previousQuery.cursors ?? {})) {
149
+ if (parent.has(k) && v) finalCursors[k] = v;
150
+ }
151
+ finalCursors[cursorKey] = cursorValue;
152
+ }
153
+ return { with: withExprs, select: selectExprs, cursors: finalCursors };
154
+ }
155
+
156
+ // src/utils/view.ts
56
157
  var NODE_PROPERTIES = /* @__PURE__ */ new Set([
57
158
  "externalId",
58
159
  "space",
@@ -116,8 +217,6 @@ function isNumericProperty(property) {
116
217
  function getSelectedGroupByKeys(groupBy) {
117
218
  return Object.entries(groupBy).filter((entry) => entry[1] === true).map(([key]) => key);
118
219
  }
119
-
120
- // src/validation.ts
121
220
  var nodeIdSchema = z.object({
122
221
  space: z.string().min(1),
123
222
  externalId: z.string().min(1)
@@ -166,17 +265,8 @@ function propertyValueSchema(property, options = {}) {
166
265
  }
167
266
  return type.list === true ? z.array(schema) : schema;
168
267
  }
169
- function buildViewSchema(view, options = {}) {
170
- const shape = {};
171
- for (const [name, property] of Object.entries(view.properties)) {
172
- if (isViewPropertyDefinition(property)) {
173
- shape[name] = propertyValueSchema(property, options).optional();
174
- }
175
- }
176
- return z.object(shape).strict();
177
- }
178
268
 
179
- // src/mappers/query-validator.ts
269
+ // src/validators/query-validator.ts
180
270
  var NODE_STRING_PROPERTIES = ["externalId", "space"];
181
271
  var NODE_NUMBER_PROPERTIES = ["createdTime", "deletedTime", "lastUpdatedTime"];
182
272
  var NODE_PROPERTIES2 = /* @__PURE__ */ new Set([...NODE_STRING_PROPERTIES, ...NODE_NUMBER_PROPERTIES]);
@@ -387,6 +477,12 @@ ${errors.map((error) => `- ${error}`).join("\n")}`);
387
477
  );
388
478
  continue;
389
479
  }
480
+ if (isReverseDirectRelation(property) && property.targetsList) {
481
+ errors.push(
482
+ `${issuePath([...path, name])}: cannot select "${name}" \u2014 Cognite does not support inward traversal of list direct relations. Query "${property.source.externalId}" directly and filter by the "${property.through.identifier}" field instead.`
483
+ );
484
+ continue;
485
+ }
390
486
  const targetView = await this.viewMapper.getView(target);
391
487
  errors.push(...await this.validateSelect(value, targetView, [...path, name]));
392
488
  }
@@ -476,7 +572,7 @@ ${errors.map((error) => `- ${error}`).join("\n")}`);
476
572
  }
477
573
  };
478
574
 
479
- // src/mappers/aggregate-validator.ts
575
+ // src/validators/aggregate-validator.ts
480
576
  var NODE_COUNT_PROPERTIES = /* @__PURE__ */ new Set(["externalId", "space"]);
481
577
  function issuePath2(path) {
482
578
  return path.length === 0 ? "aggregate" : path.map(String).join(".");
@@ -612,6 +708,92 @@ ${errors.map((error) => `- ${error}`).join("\n")}`
612
708
  return [];
613
709
  }
614
710
  };
711
+ var nodeMetadataSchema = {
712
+ instanceType: z.literal("node").optional(),
713
+ space: z.string(),
714
+ externalId: z.string(),
715
+ version: z.number().optional(),
716
+ createdTime: z.number().optional(),
717
+ deletedTime: z.number().optional(),
718
+ lastUpdatedTime: z.number().optional(),
719
+ _edges: z.record(z.string(), z.unknown()).optional()
720
+ };
721
+ function isListRelation(property) {
722
+ if (isViewPropertyDefinition(property)) {
723
+ return isListDirectRelation(property);
724
+ }
725
+ if (isReverseDirectRelation(property)) {
726
+ return property.connectionType === "multi_reverse_direct_relation" || property.targetsList === true;
727
+ }
728
+ return isEdgeConnection(property);
729
+ }
730
+ function isRecord2(value) {
731
+ return value != null && typeof value === "object" && !Array.isArray(value);
732
+ }
733
+ var QueryResultValidator = class {
734
+ constructor(viewMapper) {
735
+ this.viewMapper = viewMapper;
736
+ }
737
+ async parseItems(rootViewExternalId, items, select) {
738
+ const rootView = await this.viewMapper.getView(rootViewExternalId);
739
+ const schema = await this.buildResultSchema(rootView, MAX_DEPENDENCY_DEPTH, select);
740
+ const result = z.array(schema).safeParse(items);
741
+ if (!result.success) {
742
+ throw new Error(
743
+ `Invalid query result:
744
+ ${result.error.issues.map((issue) => `- ${issue.path.map(String).join(".")}: ${issue.message}`).join("\n")}`
745
+ );
746
+ }
747
+ return result.data;
748
+ }
749
+ async buildResultSchema(view, remainingDepth, select) {
750
+ const shape = { ...nodeMetadataSchema };
751
+ const includeAllProperties = select == null || select._all === true;
752
+ for (const [name, property] of Object.entries(view.properties)) {
753
+ const isSelected = includeAllProperties || name in select;
754
+ if (!isSelected) continue;
755
+ const nestedSelect = isRecord2(select?.[name]) ? select[name] : void 0;
756
+ if (isViewPropertyDefinition(property)) {
757
+ const relationSource = getDirectRelationSource(property);
758
+ if (relationSource) {
759
+ shape[name] = await this.buildRelationSchema(
760
+ property,
761
+ relationSource.externalId,
762
+ remainingDepth,
763
+ nestedSelect
764
+ );
765
+ } else {
766
+ shape[name] = propertyValueSchema(property, { dateMode: "coerce" }).optional();
767
+ }
768
+ continue;
769
+ }
770
+ if (isReverseDirectRelation(property) || isEdgeConnection(property)) {
771
+ shape[name] = await this.buildRelationSchema(
772
+ property,
773
+ property.source.externalId,
774
+ remainingDepth,
775
+ nestedSelect
776
+ );
777
+ }
778
+ }
779
+ const schema = z.object(shape);
780
+ return includeAllProperties ? schema.strict() : schema;
781
+ }
782
+ async buildRelationSchema(property, targetViewExternalId, remainingDepth, select) {
783
+ const isList = isListRelation(property);
784
+ const fallbackSchema = isViewPropertyDefinition(property) ? propertyValueSchema(property, { dateMode: "coerce" }) : z.unknown();
785
+ if (remainingDepth <= 0 || select == null) {
786
+ return fallbackSchema.optional();
787
+ }
788
+ const targetView = await this.viewMapper.getView(targetViewExternalId);
789
+ const nestedSchema = await this.buildResultSchema(targetView, remainingDepth - 1, select);
790
+ if (isViewPropertyDefinition(property)) {
791
+ const nestedRelationSchema = isList ? z.array(nestedSchema) : nestedSchema;
792
+ return z.union([nestedRelationSchema, fallbackSchema]).optional();
793
+ }
794
+ return (isList ? z.array(nestedSchema) : nestedSchema).optional();
795
+ }
796
+ };
615
797
 
616
798
  // src/mappers/filter-mapper.ts
617
799
  var LEAF_OPS = /* @__PURE__ */ new Set([
@@ -1178,92 +1360,6 @@ var QueryResultMapper = class {
1178
1360
  return entry;
1179
1361
  }
1180
1362
  };
1181
- var nodeMetadataSchema = {
1182
- instanceType: z.literal("node").optional(),
1183
- space: z.string(),
1184
- externalId: z.string(),
1185
- version: z.number().optional(),
1186
- createdTime: z.number().optional(),
1187
- deletedTime: z.number().optional(),
1188
- lastUpdatedTime: z.number().optional(),
1189
- _edges: z.record(z.string(), z.unknown()).optional()
1190
- };
1191
- function isListRelation(property) {
1192
- if (isViewPropertyDefinition(property)) {
1193
- return isListDirectRelation(property);
1194
- }
1195
- if (isReverseDirectRelation(property)) {
1196
- return property.connectionType === "multi_reverse_direct_relation" || property.targetsList === true;
1197
- }
1198
- return isEdgeConnection(property);
1199
- }
1200
- function isRecord2(value) {
1201
- return value != null && typeof value === "object" && !Array.isArray(value);
1202
- }
1203
- var QueryResultValidator = class {
1204
- constructor(viewMapper) {
1205
- this.viewMapper = viewMapper;
1206
- }
1207
- async parseItems(rootViewExternalId, items, select) {
1208
- const rootView = await this.viewMapper.getView(rootViewExternalId);
1209
- const schema = await this.buildResultSchema(rootView, MAX_DEPENDENCY_DEPTH, select);
1210
- const result = z.array(schema).safeParse(items);
1211
- if (!result.success) {
1212
- throw new Error(
1213
- `Invalid query result:
1214
- ${result.error.issues.map((issue) => `- ${issue.path.map(String).join(".")}: ${issue.message}`).join("\n")}`
1215
- );
1216
- }
1217
- return result.data;
1218
- }
1219
- async buildResultSchema(view, remainingDepth, select) {
1220
- const shape = { ...nodeMetadataSchema };
1221
- const includeAllProperties = select == null || select._all === true;
1222
- for (const [name, property] of Object.entries(view.properties)) {
1223
- const isSelected = includeAllProperties || name in select;
1224
- if (!isSelected) continue;
1225
- const nestedSelect = isRecord2(select?.[name]) ? select[name] : void 0;
1226
- if (isViewPropertyDefinition(property)) {
1227
- const relationSource = getDirectRelationSource(property);
1228
- if (relationSource) {
1229
- shape[name] = await this.buildRelationSchema(
1230
- property,
1231
- relationSource.externalId,
1232
- remainingDepth,
1233
- nestedSelect
1234
- );
1235
- } else {
1236
- shape[name] = propertyValueSchema(property, { dateMode: "coerce" }).optional();
1237
- }
1238
- continue;
1239
- }
1240
- if (isReverseDirectRelation(property) || isEdgeConnection(property)) {
1241
- shape[name] = await this.buildRelationSchema(
1242
- property,
1243
- property.source.externalId,
1244
- remainingDepth,
1245
- nestedSelect
1246
- );
1247
- }
1248
- }
1249
- const schema = z.object(shape);
1250
- return includeAllProperties ? schema.strict() : schema;
1251
- }
1252
- async buildRelationSchema(property, targetViewExternalId, remainingDepth, select) {
1253
- const isList = isListRelation(property);
1254
- const fallbackSchema = isViewPropertyDefinition(property) ? propertyValueSchema(property, { dateMode: "coerce" }) : z.unknown();
1255
- if (remainingDepth <= 0 || select == null) {
1256
- return fallbackSchema.optional();
1257
- }
1258
- const targetView = await this.viewMapper.getView(targetViewExternalId);
1259
- const nestedSchema = await this.buildResultSchema(targetView, remainingDepth - 1, select);
1260
- if (isViewPropertyDefinition(property)) {
1261
- const nestedRelationSchema = isList ? z.array(nestedSchema) : nestedSchema;
1262
- return z.union([nestedRelationSchema, fallbackSchema]).optional();
1263
- }
1264
- return (isList ? z.array(nestedSchema) : nestedSchema).optional();
1265
- }
1266
- };
1267
1363
 
1268
1364
  // src/mappers/view-mapper.ts
1269
1365
  var ViewMapper = class {
@@ -1311,107 +1407,6 @@ var ViewMapper = class {
1311
1407
  }
1312
1408
  };
1313
1409
 
1314
- // src/utils/query.ts
1315
- function mapNodesAndEdges(queryResult, _query) {
1316
- return queryResult.items;
1317
- }
1318
- function appendNodesAndEdges(initial, additional) {
1319
- if (!additional) return initial;
1320
- for (const [key, items] of Object.entries(additional)) {
1321
- const existing = initial[key];
1322
- if (existing) {
1323
- existing.push(...items);
1324
- } else {
1325
- initial[key] = [...items];
1326
- }
1327
- }
1328
- return initial;
1329
- }
1330
- function getQueryForDependenciesPagination(query, queryResult, viewExternalId) {
1331
- const cursorKeys = new Set(Object.keys(queryResult.nextCursor));
1332
- const { nodesParent, nodesChildren } = getParentAndChildrenNodes(cursorKeys);
1333
- const leafCursors = getLeafCursors(queryResult, viewExternalId, nodesParent, nodesChildren);
1334
- if (Object.keys(leafCursors).length === 0) {
1335
- return null;
1336
- }
1337
- return buildDependenciesQuery(query, nodesParent, nodesChildren, leafCursors);
1338
- }
1339
- function getParentAndChildrenNodes(keys) {
1340
- const nodesParent = /* @__PURE__ */ new Map();
1341
- const nodesChildren = /* @__PURE__ */ new Map();
1342
- for (const key of keys) {
1343
- const keyParts = key.split(NESTED_SEP);
1344
- const validParents = /* @__PURE__ */ new Set();
1345
- for (let i = keyParts.length - 1; i > 0; i--) {
1346
- const parentPath = keyParts.slice(0, i).join(NESTED_SEP);
1347
- const parentWithEdgeMarker = `${parentPath}${NESTED_SEP}${EDGE_MARKER}`;
1348
- if (keys.has(parentWithEdgeMarker)) {
1349
- validParents.add(parentWithEdgeMarker);
1350
- const children = nodesChildren.get(parentWithEdgeMarker) ?? /* @__PURE__ */ new Set();
1351
- children.add(key);
1352
- nodesChildren.set(parentWithEdgeMarker, children);
1353
- }
1354
- if (keys.has(parentPath)) {
1355
- validParents.add(parentPath);
1356
- const children = nodesChildren.get(parentPath) ?? /* @__PURE__ */ new Set();
1357
- children.add(key);
1358
- nodesChildren.set(parentPath, children);
1359
- }
1360
- }
1361
- nodesParent.set(key, validParents);
1362
- }
1363
- return { nodesParent, nodesChildren };
1364
- }
1365
- function getLeafCursors(queryResult, viewExternalId, nodesParent, nodesChildren) {
1366
- const targetCursors = {};
1367
- const targetCursorKeys = /* @__PURE__ */ new Set();
1368
- for (const [cursorKey, cursorValue] of Object.entries(queryResult.nextCursor)) {
1369
- if (cursorKey === viewExternalId || !cursorValue || (queryResult.items[cursorKey]?.length ?? 0) !== MAX_LIMIT) {
1370
- continue;
1371
- }
1372
- const children = nodesChildren.get(cursorKey) ?? /* @__PURE__ */ new Set();
1373
- let skipDueToChild = false;
1374
- for (const c of children) {
1375
- if (targetCursorKeys.has(c)) {
1376
- skipDueToChild = true;
1377
- break;
1378
- }
1379
- }
1380
- if (skipDueToChild) continue;
1381
- const parent = nodesParent.get(cursorKey) ?? /* @__PURE__ */ new Set();
1382
- for (const key of parent) {
1383
- if (targetCursorKeys.has(key)) {
1384
- delete targetCursors[key];
1385
- targetCursorKeys.delete(key);
1386
- }
1387
- }
1388
- targetCursors[cursorKey] = cursorValue;
1389
- targetCursorKeys.add(cursorKey);
1390
- }
1391
- return targetCursors;
1392
- }
1393
- function buildDependenciesQuery(previousQuery, nodesParent, nodesChildren, leafCursors) {
1394
- const withExprs = {};
1395
- const selectExprs = {};
1396
- const finalCursors = {};
1397
- for (const [cursorKey, cursorValue] of Object.entries(leafCursors)) {
1398
- const children = nodesChildren.get(cursorKey) ?? /* @__PURE__ */ new Set();
1399
- const parent = nodesParent.get(cursorKey) ?? /* @__PURE__ */ new Set();
1400
- const validKeys = /* @__PURE__ */ new Set([...parent, ...children, cursorKey]);
1401
- for (const [k, v] of Object.entries(previousQuery.with)) {
1402
- if (validKeys.has(k)) withExprs[k] = v;
1403
- }
1404
- for (const [k, v] of Object.entries(previousQuery.select)) {
1405
- if (validKeys.has(k)) selectExprs[k] = v;
1406
- }
1407
- for (const [k, v] of Object.entries(previousQuery.cursors ?? {})) {
1408
- if (parent.has(k) && v) finalCursors[k] = v;
1409
- }
1410
- finalCursors[cursorKey] = cursorValue;
1411
- }
1412
- return { with: withExprs, select: selectExprs, cursors: finalCursors };
1413
- }
1414
-
1415
1410
  // src/client.ts
1416
1411
  var IndustrialModelClient = class {
1417
1412
  constructor(client, dataModelId, options = {}) {
@@ -1490,6 +1485,6 @@ var IndustrialModelClient = class {
1490
1485
  }
1491
1486
  };
1492
1487
 
1493
- export { IndustrialModelClient, buildViewSchema, nodeIdSchema };
1488
+ export { IndustrialModelClient };
1494
1489
  //# sourceMappingURL=index.js.map
1495
1490
  //# sourceMappingURL=index.js.map