@itwin/presentation-backend 5.0.0-dev.4 → 5.0.0-dev.40

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/CHANGELOG.md CHANGED
@@ -1,6 +1,33 @@
1
1
  # Change Log - @itwin/presentation-backend
2
2
 
3
- This log was last generated on Wed, 06 Nov 2024 19:24:30 GMT and should not be manually modified.
3
+ This log was last generated on Mon, 13 Jan 2025 14:09:29 GMT and should not be manually modified.
4
+
5
+ ## 4.10.4
6
+ Mon, 13 Jan 2025 14:06:43 GMT
7
+
8
+ _Version update only_
9
+
10
+ ## 4.10.3
11
+ Mon, 06 Jan 2025 14:00:13 GMT
12
+
13
+ _Version update only_
14
+
15
+ ## 4.10.2
16
+ Thu, 21 Nov 2024 15:22:20 GMT
17
+
18
+ _Version update only_
19
+
20
+ ## 4.10.1
21
+ Thu, 14 Nov 2024 18:11:00 GMT
22
+
23
+ _Version update only_
24
+
25
+ ## 4.10.0
26
+ Wed, 13 Nov 2024 15:23:39 GMT
27
+
28
+ ### Updates
29
+
30
+ - Update snapshots for tests
4
31
 
5
32
  ## 4.9.7
6
33
  Wed, 06 Nov 2024 19:23:04 GMT
@@ -4,15 +4,42 @@
4
4
  import { Observable } from "rxjs";
5
5
  import { IModelDb } from "@itwin/core-backend";
6
6
  import { Id64String } from "@itwin/core-bentley";
7
- /** @internal */
8
- export declare function getElementsCount(db: IModelDb, classNames?: string[]): number;
7
+ import { ContentDescriptorRequestOptions, ContentRequestOptions, Descriptor, Item, KeySet, RulesetVariable } from "@itwin/presentation-common";
9
8
  /** @internal */
10
9
  export declare function parseFullClassName(fullClassName: string): [string, string];
11
10
  /** @internal */
12
- export declare function getClassesWithInstances(imodel: IModelDb, fullClassNames: string[]): Observable<string>;
11
+ export declare function getContentItemsObservableFromElementIds(imodel: IModelDb, contentDescriptorGetter: (partialProps: Pick<ContentDescriptorRequestOptions<IModelDb, KeySet, RulesetVariable>, "rulesetOrId" | "keys">) => Promise<Descriptor | undefined>, contentSetGetter: (partialProps: Pick<ContentRequestOptions<IModelDb, Descriptor, KeySet, RulesetVariable>, "rulesetOrId" | "keys" | "descriptor">) => Promise<Item[]>, elementIds: Id64String[], classParallelism: number, batchesParallelism: number, batchSize: number): {
12
+ itemBatches: Observable<{
13
+ descriptor: Descriptor;
14
+ items: Item[];
15
+ }>;
16
+ count: Observable<number>;
17
+ };
13
18
  /** @internal */
14
- export declare function getBatchedClassElementIds(imodel: IModelDb, fullClassName: string, batchSize: number): Promise<Array<{
19
+ export declare function getContentItemsObservableFromClassNames(imodel: IModelDb, contentDescriptorGetter: (partialProps: Pick<ContentDescriptorRequestOptions<IModelDb, KeySet, RulesetVariable>, "rulesetOrId" | "keys">) => Promise<Descriptor | undefined>, contentSetGetter: (partialProps: Pick<ContentRequestOptions<IModelDb, Descriptor, KeySet, RulesetVariable>, "rulesetOrId" | "keys" | "descriptor">) => Promise<Item[]>, elementClasses: string[], classParallelism: number, batchesParallelism: number, batchSize: number): {
20
+ itemBatches: Observable<{
21
+ descriptor: Descriptor;
22
+ items: Item[];
23
+ }>;
24
+ count: Observable<number>;
25
+ };
26
+ /**
27
+ * Given a sorted list of ECInstanceIds and a batch size, create a stream of batches. Because the IDs won't necessarily
28
+ * be sequential, a batch is defined a list of from-to pairs.
29
+ * @internal
30
+ */
31
+ export declare function createIdBatches(sortedIds: Id64String[], batchSize: number): Observable<Array<{
15
32
  from: Id64String;
16
33
  to: Id64String;
17
34
  }>>;
35
+ /**
36
+ * Query all ECInstanceIds from given class and stream from-to pairs that batch the items into batches of `batchSize` size.
37
+ * @internal
38
+ */
39
+ export declare function getBatchedClassElementIds(imodel: IModelDb, fullClassName: string, batchSize: number): Observable<Array<{
40
+ from: Id64String;
41
+ to: Id64String;
42
+ }>>;
43
+ /** @internal */
44
+ export declare function getElementsCount(db: IModelDb, classNames: string[]): number;
18
45
  //# sourceMappingURL=ElementPropertiesHelper.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ElementPropertiesHelper.d.ts","sourceRoot":"","sources":["../../../src/presentation-backend/ElementPropertiesHelper.ts"],"names":[],"mappings":"AAIA;;GAEG;AAEH,OAAO,EAA4B,UAAU,EAAU,MAAM,MAAM,CAAC;AACpE,OAAO,EAAkB,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAAY,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAG3D,gBAAgB;AAChB,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,QAAQ,EAAE,UAAU,CAAC,EAAE,MAAM,EAAE,UAWnE;AAED,gBAAgB;AAChB,wBAAgB,kBAAkB,CAAC,aAAa,EAAE,MAAM,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAG1E;AAOD,gBAAgB;AAChB,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,EAAE,GAAG,UAAU,CAAC,MAAM,CAAC,CAmBtG;AAED,gBAAgB;AAChB,wBAAsB,yBAAyB,CAC7C,MAAM,EAAE,QAAQ,EAChB,aAAa,EAAE,MAAM,EACrB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,KAAK,CAAC;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,EAAE,EAAE,UAAU,CAAA;CAAE,CAAC,CAAC,CAqBtD"}
1
+ {"version":3,"file":"ElementPropertiesHelper.d.ts","sourceRoot":"","sources":["../../../src/presentation-backend/ElementPropertiesHelper.ts"],"names":[],"mappings":"AAIA;;GAEG;AAEH,OAAO,EAAoD,UAAU,EAAsC,MAAM,MAAM,CAAC;AACxH,OAAO,EAAkB,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAA6B,UAAU,EAAuB,MAAM,qBAAqB,CAAC;AAEjG,OAAO,EACL,+BAA+B,EAC/B,qBAAqB,EACrB,UAAU,EACV,IAAI,EACJ,MAAM,EAIN,eAAe,EAChB,MAAM,4BAA4B,CAAC;AAEpC,gBAAgB;AA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AE,CAAC,EACpB,cAAc,EAAE,MAAM,EAAE,EACxB,gBAAgB,EAAE,MAAM,EACxB,kBAAkB,EAAE,MAAM,EAC1B,SAAS,EAAE,MAAM,GAChB;IAAE,WAAW,EAAE,UAAU,CAAC;QAAE,UAAU,EAAE,UAAU,CAAC;QAAC,KAAK,EAAE,IAAI,EAAE,CAAA;KAAE,CAAC,CAAC;IAAC,KAAK,EAAE,UAAU,CAAC,MAAM,CAAC,CAAA;CAAE,CAiBnG;AA4ID;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,SAAS,EAAE,UAAU,EAAE,EAAE,SAAS,EAAE,MAAM,GAAG,UAAU,CAAC,KAAK,CAAC;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,EAAE,EAAE,UAAU,CAAA;CAAE,CAAC,CAAC,CAuBnI;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,UAAU,CAAC,KAAK,CAAC;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,EAAE,EAAE,UAAU,CAAA;CAAE,CAAC,CAAC,CAM7J;AAED,gBAAgB;AAChB,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,EAAE,UAyBlE"}
@@ -7,26 +7,16 @@
7
7
  * @module Core
8
8
  */
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.getElementsCount = getElementsCount;
11
10
  exports.parseFullClassName = parseFullClassName;
12
- exports.getClassesWithInstances = getClassesWithInstances;
11
+ exports.getContentItemsObservableFromElementIds = getContentItemsObservableFromElementIds;
12
+ exports.getContentItemsObservableFromClassNames = getContentItemsObservableFromClassNames;
13
+ exports.createIdBatches = createIdBatches;
13
14
  exports.getBatchedClassElementIds = getBatchedClassElementIds;
15
+ exports.getElementsCount = getElementsCount;
14
16
  const rxjs_1 = require("rxjs");
15
17
  const core_bentley_1 = require("@itwin/core-bentley");
16
18
  const presentation_common_1 = require("@itwin/presentation-common");
17
19
  /** @internal */
18
- function getElementsCount(db, classNames) {
19
- const filter = createElementsFilter("e", classNames);
20
- const query = `
21
- SELECT COUNT(e.ECInstanceId)
22
- FROM bis.Element e
23
- ${filter ? `WHERE ${filter}` : ""}
24
- `;
25
- return db.withPreparedStatement(query, (stmt) => {
26
- return stmt.step() === core_bentley_1.DbResult.BE_SQLITE_ROW ? stmt.getValue(0).getInteger() : 0;
27
- });
28
- }
29
- /** @internal */
30
20
  function parseFullClassName(fullClassName) {
31
21
  const [schemaName, className] = fullClassName.split(/[:\.]/);
32
22
  return [schemaName, className];
@@ -36,55 +26,169 @@ function getECSqlName(fullClassName) {
36
26
  return `[${schemaName}].[${className}]`;
37
27
  }
38
28
  /** @internal */
39
- function getClassesWithInstances(imodel, fullClassNames) {
40
- return (0, rxjs_1.from)(fullClassNames).pipe((0, rxjs_1.mergeMap)((fullClassName) => {
41
- const reader = imodel.createQueryReader(`
42
- SELECT s.Name, c.Name
43
- FROM ${getECSqlName(fullClassName)} e
44
- JOIN meta.ECClassDef c ON c.ECInstanceId = e.ECClassId
45
- JOIN meta.ECSchemaDef s on s.ECInstanceId = c.Schema.Id
46
- GROUP BY c.ECInstanceId
47
- `);
48
- return (0, rxjs_1.from)(reader.toArray());
49
- }), (0, rxjs_1.mergeAll)(), (0, rxjs_1.reduce)((set, [schemaName, className]) => {
50
- set.add(`${schemaName}.${className}`);
51
- return set;
52
- }, new Set()), (0, rxjs_1.mergeMap)((set) => [...set]));
29
+ function getContentItemsObservableFromElementIds(imodel, contentDescriptorGetter, contentSetGetter, elementIds, classParallelism, batchesParallelism, batchSize) {
30
+ return {
31
+ itemBatches: getElementClassesFromIds(imodel, elementIds).pipe((0, rxjs_1.mergeMap)(({ classFullName, ids }) => getBatchedClassContentItems(classFullName, contentDescriptorGetter, contentSetGetter, () => createIdBatches(core_bentley_1.OrderedId64Iterable.sortArray(ids), batchSize), batchesParallelism), classParallelism)),
32
+ count: (0, rxjs_1.of)(elementIds.length),
33
+ };
53
34
  }
54
35
  /** @internal */
55
- async function getBatchedClassElementIds(imodel, fullClassName, batchSize) {
56
- const batches = [];
57
- const reader = imodel.createQueryReader(`SELECT ECInstanceId id FROM ${getECSqlName(fullClassName)} ORDER BY ECInstanceId`);
58
- let currId;
59
- let fromId;
60
- let count = 0;
61
- while (await reader.step()) {
62
- currId = reader.current.toRow().id;
63
- if (!fromId) {
64
- fromId = currId;
36
+ function getContentItemsObservableFromClassNames(imodel, contentDescriptorGetter, contentSetGetter, elementClasses, classParallelism, batchesParallelism, batchSize) {
37
+ return {
38
+ itemBatches: getClassesWithInstances(imodel, elementClasses).pipe((0, rxjs_1.mergeMap)((classFullName) => getBatchedClassContentItems(classFullName, contentDescriptorGetter, contentSetGetter, () => getBatchedClassElementIds(imodel, classFullName, batchSize), batchesParallelism), classParallelism)),
39
+ count: (0, rxjs_1.of)(getElementsCount(imodel, elementClasses)),
40
+ };
41
+ }
42
+ function getBatchedClassContentItems(classFullName, contentDescriptorGetter, contentSetGetter, batcher, batchesParallelism) {
43
+ return (0, rxjs_1.defer)(async () => {
44
+ const ruleset = createClassContentRuleset(classFullName);
45
+ const keys = new presentation_common_1.KeySet();
46
+ const descriptor = await contentDescriptorGetter({ rulesetOrId: ruleset, keys });
47
+ if (!descriptor) {
48
+ throw new presentation_common_1.PresentationError(presentation_common_1.PresentationStatus.Error, `Failed to get descriptor for class ${classFullName}`);
65
49
  }
66
- if (++count >= batchSize) {
67
- batches.push({ from: fromId, to: currId });
68
- fromId = undefined;
69
- count = 0;
50
+ return { descriptor, keys, ruleset };
51
+ }).pipe(
52
+ // create elements' id batches
53
+ (0, rxjs_1.mergeMap)((x) => batcher().pipe((0, rxjs_1.map)((batch) => ({ ...x, batch })))),
54
+ // request content for each batch, filter by IDs for performance
55
+ (0, rxjs_1.mergeMap)(({ descriptor, keys, ruleset, batch }) => (0, rxjs_1.defer)(async () => {
56
+ const filteringDescriptor = new presentation_common_1.Descriptor(descriptor);
57
+ filteringDescriptor.instanceFilter = {
58
+ selectClassName: classFullName,
59
+ expression: createElementIdsECExpressionFilter(batch),
60
+ };
61
+ return contentSetGetter({
62
+ rulesetOrId: ruleset,
63
+ keys,
64
+ descriptor: filteringDescriptor,
65
+ });
66
+ }).pipe((0, rxjs_1.map)((items) => ({ descriptor, items }))), batchesParallelism));
67
+ }
68
+ function createElementIdsECExpressionFilter(batch) {
69
+ let filter = "";
70
+ function appendCondition(cond) {
71
+ if (filter.length > 0) {
72
+ filter += " OR ";
70
73
  }
74
+ filter += cond;
71
75
  }
72
- if (fromId && currId) {
73
- batches.push({ from: fromId, to: currId });
76
+ for (const item of batch) {
77
+ if (item.from === item.to) {
78
+ appendCondition(`this.ECInstanceId = ${item.from}`);
79
+ }
80
+ else {
81
+ appendCondition(`this.ECInstanceId >= ${item.from} AND this.ECInstanceId <= ${item.to}`);
82
+ }
74
83
  }
75
- return batches;
84
+ return filter;
76
85
  }
77
- function createElementsFilter(elementAlias, classNames) {
78
- if (classNames === undefined || classNames.length === 0) {
79
- return undefined;
80
- }
81
- // check if list contains only valid class names
82
- const classNameRegExp = new RegExp(/^[\w]+[.:][\w]+$/);
83
- const invalidName = classNames.find((name) => !name.match(classNameRegExp));
84
- if (invalidName) {
85
- throw new presentation_common_1.PresentationError(presentation_common_1.PresentationStatus.InvalidArgument, `Encountered invalid class name - ${invalidName}.
86
- Valid class name formats: "<schema name or alias>.<class name>", "<schema name or alias>:<class name>"`);
87
- }
88
- return `${elementAlias}.ECClassId IS (${classNames.join(",")})`;
86
+ function createClassContentRuleset(fullClassName) {
87
+ const [schemaName, className] = parseFullClassName(fullClassName);
88
+ return {
89
+ id: `content/class-descriptor/${fullClassName}`,
90
+ rules: [
91
+ {
92
+ ruleType: "Content",
93
+ specifications: [
94
+ {
95
+ specType: "ContentInstancesOfSpecificClasses",
96
+ classes: {
97
+ schemaName,
98
+ classNames: [className],
99
+ arePolymorphic: false,
100
+ },
101
+ handlePropertiesPolymorphically: true,
102
+ },
103
+ ],
104
+ },
105
+ ],
106
+ };
107
+ }
108
+ /** Given a list of element ids, group them by class name. */
109
+ function getElementClassesFromIds(imodel, elementIds) {
110
+ const elementIdsBatchSize = 5000;
111
+ return (0, rxjs_1.range)(0, elementIds.length / elementIdsBatchSize).pipe((0, rxjs_1.mergeMap)((batchIndex) => {
112
+ const idsFrom = batchIndex * elementIdsBatchSize;
113
+ const idsTo = Math.min(idsFrom + elementIdsBatchSize, elementIds.length);
114
+ return (0, rxjs_1.from)(imodel.createQueryReader(`
115
+ SELECT ec_classname(e.ECClassId) className, GROUP_CONCAT(IdToHex(e.ECInstanceId)) ids
116
+ FROM bis.Element e
117
+ WHERE e.ECInstanceId IN (${elementIds.slice(idsFrom, idsTo).join(",")})
118
+ GROUP BY e.ECClassId
119
+ `));
120
+ }), (0, rxjs_1.map)((row) => ({ className: row.className, ids: row.ids.split(",") })), (0, rxjs_1.groupBy)(({ className }) => className), (0, rxjs_1.mergeMap)((groups) => groups.pipe((0, rxjs_1.reduce)((acc, g) => {
121
+ g.ids.forEach((id) => acc.ids.push(id));
122
+ return {
123
+ classFullName: g.className,
124
+ ids: acc.ids,
125
+ };
126
+ }, { classFullName: "", ids: [] }))));
127
+ }
128
+ /** Given a list of full class names, get a stream of actual class names that have instances. */
129
+ function getClassesWithInstances(imodel, fullClassNames) {
130
+ return (0, rxjs_1.from)(fullClassNames).pipe((0, rxjs_1.mergeMap)((fullClassName) => (0, rxjs_1.from)(imodel.createQueryReader(`
131
+ SELECT ec_classname(e.ECClassId, 's.c') className
132
+ FROM ${getECSqlName(fullClassName)} e
133
+ GROUP BY e.ECClassId
134
+ `))), (0, rxjs_1.map)((row) => row.className));
135
+ }
136
+ /**
137
+ * Given a sorted list of ECInstanceIds and a batch size, create a stream of batches. Because the IDs won't necessarily
138
+ * be sequential, a batch is defined a list of from-to pairs.
139
+ * @internal
140
+ */
141
+ function createIdBatches(sortedIds, batchSize) {
142
+ return (0, rxjs_1.range)(0, sortedIds.length / batchSize).pipe((0, rxjs_1.map)((batchIndex) => {
143
+ const sequences = new Array();
144
+ const startIndex = batchIndex * batchSize;
145
+ const endIndex = Math.min((batchIndex + 1) * batchSize, sortedIds.length) - 1;
146
+ let fromId = sortedIds[startIndex];
147
+ let to = {
148
+ id: sortedIds[startIndex],
149
+ localId: core_bentley_1.Id64.getLocalId(sortedIds[startIndex]),
150
+ };
151
+ for (let i = startIndex + 1; i <= endIndex; ++i) {
152
+ const currLocalId = core_bentley_1.Id64.getLocalId(sortedIds[i]);
153
+ if (currLocalId !== to.localId + 1) {
154
+ sequences.push({ from: fromId, to: sortedIds[i - 1] });
155
+ fromId = sortedIds[i];
156
+ }
157
+ to = { id: sortedIds[i], localId: currLocalId };
158
+ }
159
+ sequences.push({ from: fromId, to: sortedIds[endIndex] });
160
+ return sequences;
161
+ }));
162
+ }
163
+ /**
164
+ * Query all ECInstanceIds from given class and stream from-to pairs that batch the items into batches of `batchSize` size.
165
+ * @internal
166
+ */
167
+ function getBatchedClassElementIds(imodel, fullClassName, batchSize) {
168
+ return (0, rxjs_1.from)(imodel.createQueryReader(`SELECT IdToHex(ECInstanceId) id FROM ${getECSqlName(fullClassName)} ORDER BY ECInstanceId`)).pipe((0, rxjs_1.map)((row) => row.id), (0, rxjs_1.bufferCount)(batchSize), (0, rxjs_1.map)((batch) => [{ from: batch[0], to: batch[batch.length - 1] }]));
169
+ }
170
+ /** @internal */
171
+ function getElementsCount(db, classNames) {
172
+ const whereClause = (() => {
173
+ if (classNames === undefined || classNames.length === 0) {
174
+ return undefined;
175
+ }
176
+ // check if list contains only valid class names
177
+ const classNameRegExp = new RegExp(/^[\w]+[.:][\w]+$/);
178
+ const invalidName = classNames.find((name) => !name.match(classNameRegExp));
179
+ if (invalidName) {
180
+ throw new presentation_common_1.PresentationError(presentation_common_1.PresentationStatus.InvalidArgument, `Encountered invalid class name - ${invalidName}.
181
+ Valid class name formats: "<schema name or alias>.<class name>", "<schema name or alias>:<class name>"`);
182
+ }
183
+ return `e.ECClassId IS (${classNames.join(",")})`;
184
+ })();
185
+ const query = `
186
+ SELECT COUNT(e.ECInstanceId)
187
+ FROM bis.Element e
188
+ ${whereClause ? `WHERE ${whereClause}` : ""}
189
+ `;
190
+ return db.withPreparedStatement(query, (stmt) => {
191
+ return stmt.step() === core_bentley_1.DbResult.BE_SQLITE_ROW ? stmt.getValue(0).getInteger() : 0;
192
+ });
89
193
  }
90
194
  //# sourceMappingURL=ElementPropertiesHelper.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ElementPropertiesHelper.js","sourceRoot":"","sources":["../../../src/presentation-backend/ElementPropertiesHelper.ts"],"names":[],"mappings":";AAAA;;;gGAGgG;AAChG;;GAEG;;AAQH,4CAWC;AAGD,gDAGC;AAQD,0DAmBC;AAGD,8DAyBC;AA9ED,+BAAoE;AAEpE,sDAA2D;AAC3D,oEAAmF;AAEnF,gBAAgB;AAChB,SAAgB,gBAAgB,CAAC,EAAY,EAAE,UAAqB;IAClE,MAAM,MAAM,GAAG,oBAAoB,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC;IACrD,MAAM,KAAK,GAAG;;;MAGV,MAAM,CAAC,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE;GAClC,CAAC;IAEF,OAAO,EAAE,CAAC,qBAAqB,CAAC,KAAK,EAAE,CAAC,IAAoB,EAAE,EAAE;QAC9D,OAAO,IAAI,CAAC,IAAI,EAAE,KAAK,uBAAQ,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IACpF,CAAC,CAAC,CAAC;AACL,CAAC;AAED,gBAAgB;AAChB,SAAgB,kBAAkB,CAAC,aAAqB;IACtD,MAAM,CAAC,UAAU,EAAE,SAAS,CAAC,GAAG,aAAa,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC7D,O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ent":["/*---------------------------------------------------------------------------------------------\n * Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n * See LICENSE.md in the project root for license terms and full copyright notice.\n *--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module Core\n */\n\nimport { from, mergeAll, mergeMap, Observable, reduce } from \"rxjs\";\nimport { ECSqlStatement, IModelDb } from \"@itwin/core-backend\";\nimport { DbResult, Id64String } from \"@itwin/core-bentley\";\nimport { PresentationError, PresentationStatus } from \"@itwin/presentation-common\";\n\n/** @internal */\nexport function getElementsCount(db: IModelDb, classNames?: string[]) {\n const filter = createElementsFilter(\"e\", classNames);\n const query = `\n SELECT COUNT(e.ECInstanceId)\n FROM bis.Element e\n ${filter ? `WHERE ${filter}` : \"\"}\n `;\n\n return db.withPreparedStatement(query, (stmt: ECSqlStatement) => {\n return stmt.step() === DbResult.BE_SQLITE_ROW ? stmt.getValue(0).getInteger() : 0;\n });\n}\n\n/** @internal */\nexport function parseFullClassName(fullClassName: string): [string, string] {\n const [schemaName, className] = fullClassName.split(/[:\\.]/);\n return [schemaName, className];\n}\n\nfunction getECSqlName(fullClassName: string) {\n const [schemaName, className] = parseFullClassName(fullClassName);\n return `[${schemaName}].[${className}]`;\n}\n\n/** @internal */\nexport function getClassesWithInstances(imodel: IModelDb, fullClassNames: string[]): Observable<string> {\n return from(fullClassNames).pipe(\n mergeMap((fullClassName) => {\n const reader = imodel.createQueryReader(`\n SELECT s.Name, c.Name\n FROM ${getECSqlName(fullClassName)} e\n JOIN meta.ECClassDef c ON c.ECInstanceId = e.ECClassId\n JOIN meta.ECSchemaDef s on s.ECInstanceId = c.Schema.Id\n GROUP BY c.ECInstanceId\n `);\n return from(reader.toArray() as Promise<[string, string][]>);\n }),\n mergeAll(),\n reduce<[string, string], Set<string>>((set, [schemaName, className]) => {\n set.add(`${schemaName}.${className}`);\n return set;\n }, new Set()),\n mergeMap((set) => [...set]),\n );\n}\n\n/** @internal */\nexport async function getBatchedClassElementIds(\n imodel: IModelDb,\n fullClassName: string,\n batchSize: number,\n): Promise<Array<{ from: Id64String; to: Id64String }>> {\n const batches = [];\n const reader = imodel.createQueryReader(`SELECT ECInstanceId id FROM ${getECSqlName(fullClassName)} ORDER BY ECInstanceId`);\n let currId: Id64String | undefined;\n let fromId: Id64String | undefined;\n let count = 0;\n while (await reader.step()) {\n currId = reader.current.toRow().id as Id64String;\n if (!fromId) {\n fromId = currId;\n }\n if (++count >= batchSize) {\n batches.push({ from: fromId, to: currId });\n fromId = undefined;\n count = 0;\n }\n }\n if (fromId && currId) {\n batches.push({ from: fromId, to: currId });\n }\n return batches;\n}\n\nfunction createElementsFilter(elementAlias: string, classNames?: string[]) {\n if (classNames === undefined || classNames.length === 0) {\n return undefined;\n }\n\n // check if list contains only valid class names\n const classNameRegExp = new RegExp(/^[\\w]+[.:][\\w]+$/);\n const invalidName = classNames.find((name) => !name.match(classNameRegExp));\n if (invalidName) {\n throw new PresentationError(\n PresentationStatus.InvalidArgument,\n `Encountered invalid class name - ${invalidName}.\n Valid class name formats: \"<schema name or alias>.<class name>\", \"<schema name or alias>:<class name>\"`,\n );\n }\n\n return `${elementAlias}.ECClassId IS (${classNames.join(\",\")})`;\n}\n"]}
1
+ {"version":3,"file":"ElementPropertiesHelper.js","sourceRoot":"","sources":["../../../src/presentation-backend/ElementPropertiesHelper.ts"],"names":[],"mappings":";AAAA;;;gGAGgG;AAChG;;GAEG;;AAmBH,gDAGC;AAQD,0FA6BC;AAGD,0FA6BC;AAiJD,0CAuBC;AAMD,8DAMC;AAGD,4CAyBC;AAzSD,+BAAwH;AAExH,sDAAiG;AAEjG,oEAUoC;AAEpC,gBAAgB;AAChB,SAAgB,kBAAkB,CAAC,aAAqB;IACtD,MAAM,CAAC,UAAU,EAAE,SAAS,CAAC,GAAG,aAAa,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC7D,OAAO,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;AACjC,CAAC;AAED,SAAS,YAAY,CAAC,aAAq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AAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACxD,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,gDAAgD;QAChD,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,kBAAkB,CAAC,CAAC;QACvD,MAAM,WAAW,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC,CAAC;QAC5E,IAAI,WAAW,EAAE,CAAC;YAChB,MAAM,IAAI,uCAAiB,CACzB,wCAAkB,CAAC,eAAe,EAClC,oCAAoC,WAAW;+GACwD,CACxG,CAAC;QACJ,CAAC;QACD,OAAO,mBAAmB,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;IACpD,CAAC,CAAC,EAAE,CAAC;IACL,MAAM,KAAK,GAAG;;;MAGV,WAAW,CAAC,CAAC,CAAC,SAAS,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE;GAC5C,CAAC;IACF,OAAO,EAAE,CAAC,qBAAqB,CAAC,KAAK,EAAE,CAAC,IAAoB,EAAE,EAAE;QAC9D,OAAO,IAAI,CAAC,IAAI,EAAE,KAAK,uBAAQ,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IACpF,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n * Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n * See LICENSE.md in the project root for license terms and full copyright notice.\n *--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module Core\n */\n\nimport { bufferCount, defer, from, groupBy, map, mergeMap, Observable, ObservedValueOf, of, range, reduce } from \"rxjs\";\nimport { ECSqlStatement, IModelDb } from \"@itwin/core-backend\";\nimport { DbResult, Id64, Id64Array, Id64String, OrderedId64Iterable } from \"@itwin/core-bentley\";\nimport { QueryRowProxy } from \"@itwin/core-common\";\nimport {\n ContentDescriptorRequestOptions,\n ContentRequestOptions,\n Descriptor,\n Item,\n KeySet,\n PresentationError,\n PresentationStatus,\n Ruleset,\n RulesetVariable,\n} from \"@itwin/presentation-common\";\n\n/** @internal */\nexport function parseFullClassName(fullClassName: string): [string, string] {\n const [schemaName, className] = fullClassName.split(/[:\\.]/);\n return [schemaName, className];\n}\n\nfunction getECSqlName(fullClassName: string) {\n const [schemaName, className] = parseFullClassName(fullClassName);\n return `[${schemaName}].[${className}]`;\n}\n\n/** @internal */\nexport function getContentItemsObservableFromElementIds(\n imodel: IModelDb,\n contentDescriptorGetter: (\n partialProps: Pick<ContentDescriptorRequestOptions<IModelDb, KeySet, RulesetVariable>, \"rulesetOrId\" | \"keys\">,\n ) => Promise<Descriptor | undefined>,\n contentSetGetter: (\n partialProps: Pick<ContentRequestOptions<IModelDb, Descriptor, KeySet, RulesetVariable>, \"rulesetOrId\" | \"keys\" | \"descriptor\">,\n ) => Promise<Item[]>,\n elementIds: Id64String[],\n classParallelism: number,\n batchesParallelism: number,\n batchSize: number,\n): { itemBatches: Observable<{ descriptor: Descriptor; items: Item[] }>; count: Observable<number> } {\n return {\n itemBatches: getElementClassesFromIds(imodel, elementIds).pipe(\n mergeMap(\n ({ classFullName, ids }) =>\n getBatchedClassContentItems(\n classFullName,\n contentDescriptorGetter,\n contentSetGetter,\n () => createIdBatches(OrderedId64Iterable.sortArray(ids), batchSize),\n batchesParallelism,\n ),\n classParallelism,\n ),\n ),\n count: of(elementIds.length),\n };\n}\n\n/** @internal */\nexport function getContentItemsObservableFromClassNames(\n imodel: IModelDb,\n contentDescriptorGetter: (\n partialProps: Pick<ContentDescriptorRequestOptions<IModelDb, KeySet, RulesetVariable>, \"rulesetOrId\" | \"keys\">,\n ) => Promise<Descriptor | undefined>,\n contentSetGetter: (\n partialProps: Pick<ContentRequestOptions<IModelDb, Descriptor, KeySet, RulesetVariable>, \"rulesetOrId\" | \"keys\" | \"descriptor\">,\n ) => Promise<Item[]>,\n elementClasses: string[],\n classParallelism: number,\n batchesParallelism: number,\n batchSize: number,\n): { itemBatches: Observable<{ descriptor: Descriptor; items: Item[] }>; count: Observable<number> } {\n return {\n itemBatches: getClassesWithInstances(imodel, elementClasses).pipe(\n mergeMap(\n (classFullName) =>\n getBatchedClassContentItems(\n classFullName,\n contentDescriptorGetter,\n contentSetGetter,\n () => getBatchedClassElementIds(imodel, classFullName, batchSize),\n batchesParallelism,\n ),\n classParallelism,\n ),\n ),\n count: of(getElementsCount(imodel, elementClasses)),\n };\n}\n\nfunction getBatchedClassContentItems(\n classFullName: string,\n contentDescriptorGetter: (\n partialProps: Pick<ContentDescriptorRequestOptions<IModelDb, KeySet, RulesetVariable>, \"rulesetOrId\" | \"keys\">,\n ) => Promise<Descriptor | undefined>,\n contentSetGetter: (\n partialProps: Pick<ContentRequestOptions<IModelDb, Descriptor, KeySet, RulesetVariable>, \"rulesetOrId\" | \"keys\" | \"descriptor\">,\n ) => Promise<Item[]>,\n batcher: () => Observable<Array<{ from: Id64String; to: Id64String }>>,\n batchesParallelism: number,\n): Observable<{ descriptor: Descriptor; items: Item[] }> {\n return defer(async () => {\n const ruleset = createClassContentRuleset(classFullName);\n const keys = new KeySet();\n const descriptor = await contentDescriptorGetter({ rulesetOrId: ruleset, keys });\n if (!descriptor) {\n throw new PresentationError(PresentationStatus.Error, `Failed to get descriptor for class ${classFullName}`);\n }\n return { descriptor, keys, ruleset };\n }).pipe(\n // create elements' id batches\n mergeMap((x) => batcher().pipe(map((batch) => ({ ...x, batch })))),\n // request content for each batch, filter by IDs for performance\n mergeMap(\n ({ descriptor, keys, ruleset, batch }) =>\n defer(async () => {\n const filteringDescriptor = new Descriptor(descriptor);\n filteringDescriptor.instanceFilter = {\n selectClassName: classFullName,\n expression: createElementIdsECExpressionFilter(batch),\n };\n return contentSetGetter({\n rulesetOrId: ruleset,\n keys,\n descriptor: filteringDescriptor,\n });\n }).pipe(map((items) => ({ descriptor, items }))),\n batchesParallelism,\n ),\n );\n}\n\nfunction createElementIdsECExpressionFilter(batch: Array<{ from: Id64String; to: Id64String }>): string {\n let filter = \"\";\n function appendCondition(cond: string) {\n if (filter.length > 0) {\n filter += \" OR \";\n }\n filter += cond;\n }\n for (const item of batch) {\n if (item.from === item.to) {\n appendCondition(`this.ECInstanceId = ${item.from}`);\n } else {\n appendCondition(`this.ECInstanceId >= ${item.from} AND this.ECInstanceId <= ${item.to}`);\n }\n }\n return filter;\n}\n\nfunction createClassContentRuleset(fullClassName: string): Ruleset {\n const [schemaName, className] = parseFullClassName(fullClassName);\n return {\n id: `content/class-descriptor/${fullClassName}`,\n rules: [\n {\n ruleType: \"Content\",\n specifications: [\n {\n specType: \"ContentInstancesOfSpecificClasses\",\n classes: {\n schemaName,\n classNames: [className],\n arePolymorphic: false,\n },\n handlePropertiesPolymorphically: true,\n },\n ],\n },\n ],\n };\n}\n\n/** Given a list of element ids, group them by class name. */\nfunction getElementClassesFromIds(imodel: IModelDb, elementIds: string[]): Observable<{ classFullName: string; ids: Id64Array }> {\n const elementIdsBatchSize = 5000;\n return range(0, elementIds.length / elementIdsBatchSize).pipe(\n mergeMap((batchIndex) => {\n const idsFrom = batchIndex * elementIdsBatchSize;\n const idsTo = Math.min(idsFrom + elementIdsBatchSize, elementIds.length);\n return from(\n imodel.createQueryReader(\n `\n SELECT ec_classname(e.ECClassId) className, GROUP_CONCAT(IdToHex(e.ECInstanceId)) ids\n FROM bis.Element e\n WHERE e.ECInstanceId IN (${elementIds.slice(idsFrom, idsTo).join(\",\")})\n GROUP BY e.ECClassId\n `,\n ),\n );\n }),\n map((row: QueryRowProxy): { className: string; ids: Id64Array } => ({ className: row.className, ids: row.ids.split(\",\") })),\n groupBy(({ className }) => className),\n mergeMap((groups) =>\n groups.pipe(\n reduce<ObservedValueOf<typeof groups>, { classFullName: string; ids: Id64Array }>(\n (acc, g) => {\n g.ids.forEach((id) => acc.ids.push(id));\n return {\n classFullName: g.className,\n ids: acc.ids,\n };\n },\n { classFullName: \"\", ids: [] },\n ),\n ),\n ),\n );\n}\n\n/** Given a list of full class names, get a stream of actual class names that have instances. */\nfunction getClassesWithInstances(imodel: IModelDb, fullClassNames: string[]): Observable<string> {\n return from(fullClassNames).pipe(\n mergeMap((fullClassName) =>\n from(\n imodel.createQueryReader(\n `\n SELECT ec_classname(e.ECClassId, 's.c') className\n FROM ${getECSqlName(fullClassName)} e\n GROUP BY e.ECClassId\n `,\n ),\n ),\n ),\n map((row: QueryRowProxy): string => row.className),\n );\n}\n\n/**\n * Given a sorted list of ECInstanceIds and a batch size, create a stream of batches. Because the IDs won't necessarily\n * be sequential, a batch is defined a list of from-to pairs.\n * @internal\n */\nexport function createIdBatches(sortedIds: Id64String[], batchSize: number): Observable<Array<{ from: Id64String; to: Id64String }>> {\n return range(0, sortedIds.length / batchSize).pipe(\n map((batchIndex) => {\n const sequences = new Array<{ from: Id64String; to: Id64String }>();\n const startIndex = batchIndex * batchSize;\n const endIndex = Math.min((batchIndex + 1) * batchSize, sortedIds.length) - 1;\n let fromId = sortedIds[startIndex];\n let to = {\n id: sortedIds[startIndex],\n localId: Id64.getLocalId(sortedIds[startIndex]),\n };\n for (let i = startIndex + 1; i <= endIndex; ++i) {\n const currLocalId = Id64.getLocalId(sortedIds[i]);\n if (currLocalId !== to.localId + 1) {\n sequences.push({ from: fromId, to: sortedIds[i - 1] });\n fromId = sortedIds[i];\n }\n to = { id: sortedIds[i], localId: currLocalId };\n }\n sequences.push({ from: fromId, to: sortedIds[endIndex] });\n return sequences;\n }),\n );\n}\n\n/**\n * Query all ECInstanceIds from given class and stream from-to pairs that batch the items into batches of `batchSize` size.\n * @internal\n */\nexport function getBatchedClassElementIds(imodel: IModelDb, fullClassName: string, batchSize: number): Observable<Array<{ from: Id64String; to: Id64String }>> {\n return from(imodel.createQueryReader(`SELECT IdToHex(ECInstanceId) id FROM ${getECSqlName(fullClassName)} ORDER BY ECInstanceId`)).pipe(\n map((row): Id64String => row.id),\n bufferCount(batchSize),\n map((batch) => [{ from: batch[0], to: batch[batch.length - 1] }]),\n );\n}\n\n/** @internal */\nexport function getElementsCount(db: IModelDb, classNames: string[]) {\n const whereClause = (() => {\n if (classNames === undefined || classNames.length === 0) {\n return undefined;\n }\n // check if list contains only valid class names\n const classNameRegExp = new RegExp(/^[\\w]+[.:][\\w]+$/);\n const invalidName = classNames.find((name) => !name.match(classNameRegExp));\n if (invalidName) {\n throw new PresentationError(\n PresentationStatus.InvalidArgument,\n `Encountered invalid class name - ${invalidName}.\n Valid class name formats: \"<schema name or alias>.<class name>\", \"<schema name or alias>:<class name>\"`,\n );\n }\n return `e.ECClassId IS (${classNames.join(\",\")})`;\n })();\n const query = `\n SELECT COUNT(e.ECInstanceId)\n FROM bis.Element e\n ${whereClause ? `WHERE ${whereClause}` : \"\"}\n `;\n return db.withPreparedStatement(query, (stmt: ECSqlStatement) => {\n return stmt.step() === DbResult.BE_SQLITE_ROW ? stmt.getValue(0).getInteger() : 0;\n });\n}\n"]}
@@ -6,7 +6,6 @@
6
6
  /** @packageDocumentation
7
7
  * @module Core
8
8
  */
9
- var _a;
10
9
  Object.defineProperty(exports, "__esModule", { value: true });
11
10
  exports.Presentation = void 0;
12
11
  const core_backend_1 = require("@itwin/core-backend");
@@ -46,7 +45,7 @@ class Presentation {
46
45
  */
47
46
  static initialize(props) {
48
47
  this._initProps = props || {};
49
- this._shutdownListener = core_backend_1.IModelHost.onBeforeShutdown.addListener(() => _a.terminate());
48
+ this._shutdownListener = core_backend_1.IModelHost.onBeforeShutdown.addListener(() => Presentation.terminate());
50
49
  this._rpcImpl = new PresentationRpcImpl_1.PresentationRpcImpl({
51
50
  requestTimeout: this._initProps.requestTimeout,
52
51
  });
@@ -98,9 +97,9 @@ class Presentation {
98
97
  this._initProps = undefined;
99
98
  }
100
99
  static createClientManager(clientId, onManagerUsed) {
101
- const manager = _a._initProps && _a._initProps.clientManagerFactory
102
- ? _a._initProps.clientManagerFactory(clientId, _a._initProps)
103
- : new PresentationManager_1.PresentationManager({ ..._a._initProps, id: clientId });
100
+ const manager = Presentation._initProps && Presentation._initProps.clientManagerFactory
101
+ ? Presentation._initProps.clientManagerFactory(clientId, Presentation._initProps)
102
+ : new PresentationManager_1.PresentationManager({ ...Presentation._initProps, id: clientId });
104
103
  manager.setOnManagerUsedHandler(onManagerUsed);
105
104
  core_bentley_1.Logger.logInfo(BackendLoggerCategory_1.PresentationBackendLoggerCategory.PresentationManager, `Created a PresentationManager instance with ID: ${clientId}. Total instances: ${this._clientsStorage.values.length}.`);
106
105
  return { manager };
@@ -128,13 +127,12 @@ class Presentation {
128
127
  }
129
128
  return this._rpcImpl.requestTimeout;
130
129
  }
130
+ static { this.onIModelOpened = (imodel) => {
131
+ const manager = this.getManager();
132
+ const imodelAddon = manager.getNativePlatform().getImodelAddon(imodel);
133
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
134
+ manager.getNativePlatform().forceLoadSchemas(imodelAddon);
135
+ }; }
131
136
  }
132
137
  exports.Presentation = Presentation;
133
- _a = Presentation;
134
- Presentation.onIModelOpened = (imodel) => {
135
- const manager = _a.getManager();
136
- const imodelAddon = manager.getNativePlatform().getImodelAddon(imodel);
137
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
138
- manager.getNativePlatform().forceLoadSchemas(imodelAddon);
139
- };
140
138
  //# sourceMappingURL=Presentation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Presentation.js","sourceRoot":"","sources":["../../../src/presentation-backend/Presentation.ts"],"names":[],"mappings":";AAAA;;;gGAGgG;AAChG;;GAEG;;;;AAEH,sDAAuE;AACvE,sDAA0D;AAC1D,oDAAgD;AAChD,oEAA6G;AAC7G,mEAA4E;AAC5E,qEAAkE;AAClE,+DAAsF;AACtF,+DAA4D;AAC5D,yDAAkE;AA6DlE;;;;;;;;;GASG;AACH,MAAa,YAAY;IAQvB,0BAA0B;IAC1B,gBAAuB,CAAC;IAExB,+DAA+D;IACxD,MAAM,KAAK,S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AAE,EAAE;IACtD,MAAM,OAAO,GAAG,EAAI,CAAC,UAAU,EAAE,CAAC;IAClC,MAAM,WAAW,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;IACvE,mEAAmE;IACnE,OAAO,CAAC,iBAAiB,EAAE,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAC;AAC5D,CAAC,AAL4B,CAK3B","sourcesContent":["/*---------------------------------------------------------------------------------------------\n * Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n * See LICENSE.md in the project root for license terms and full copyright notice.\n *--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module Core\n */\n\nimport { BriefcaseDb, IModelHost, IpcHost } from \"@itwin/core-backend\";\nimport { DisposeFunc, Logger } from \"@itwin/core-bentley\";\nimport { RpcManager } from \"@itwin/core-common\";\nimport { PresentationError, PresentationRpcInterface, PresentationStatus } from \"@itwin/presentation-common\";\nimport { PresentationBackendLoggerCategory } from \"./BackendLoggerCategory\";\nimport { PresentationIpcHandler } from \"./PresentationIpcHandler\";\nimport { PresentationManager, PresentationManagerProps } from \"./PresentationManager\";\nimport { PresentationRpcImpl } from \"./PresentationRpcImpl\";\nimport { FactoryBasedTemporaryStorage } from \"./TemporaryStorage\";\n\n/**\n * Properties that can be used to configure [[Presentation]] API.\n * @public\n */\nexport interface PresentationProps extends Omit<PresentationManagerProps, \"enableSchemasPreload\"> {\n /**\n * Time in milliseconds after which the request will timeout.\n */\n requestTimeout?: number;\n\n /**\n * Should schemas preloading be enabled. If true, [[Presentation]] library listens\n * for `BriefcaseDb.onOpened` event and force pre-loads all ECSchemas.\n */\n enableSchemasPreload?: boolean;\n\n /**\n * Factory method for creating separate managers for each client\n * @internal\n */\n clientManagerFactory?: (clientId: string, props: PresentationManagerProps) => PresentationManager;\n\n /**\n * How much time should an unused client manager be stored in memory\n * before it's disposed.\n */\n unusedClientLifetime?: number;\n}\n\n/**\n * Props for initializing the [[Presentation]] library for using multiple [[PresentationManager]]\n * instances, one for each frontend.\n *\n * @public\n * @deprecated in 4.8 - use [[PresentationProps]] instead.\n */\nexport type MultiManagerPresentationProps = PresentationProps;\n\n/**\n * Base props for initializing the [[Presentation]] library.\n *\n * @public\n * @deprecated in 4.8 - use [[PresentationProps]] instead.\n */\nexport type PresentationPropsBase = PresentationProps;\n\n/**\n * Props for initializing the [[Presentation]] library with ability to use a single\n * [[PresentationManager]] instance for handling all requests.\n *\n * @public\n * @deprecated in 4.8 - use [[PresentationProps]] instead.\n */\nexport type SingleManagerPresentationProps = Omit<PresentationProps, \"clientManagerFactory\" | \"unusedClientLifetime\">;\n\ninterface ClientStoreItem {\n manager: PresentationManager;\n}\n\n/**\n * Static class used to statically set up Presentation library for the backend.\n * Basically what it does is:\n * - Register a RPC implementation\n * - Create a singleton [[PresentationManager]] instance\n * - Subscribe for [IModelHost.onBeforeShutdown]($core-backend) event and terminate\n * the presentation manager when that happens.\n *\n * @public\n */\nexport class Presentation {\n private static _initProps: PresentationProps | undefined;\n private static _clientsStorage: FactoryBasedTemporaryStorage<ClientStoreItem> | undefined;\n private static _disposeIpcHandler: DisposeFunc | undefined;\n private static _shutdownListener: DisposeFunc | undefined;\n private static _disposeIModelOpenedListener: DisposeFunc | undefined;\n private static _rpcImpl: PresentationRpcImpl | undefined;\n\n /* istanbul ignore next */\n private constructor() {}\n\n /** Properties used to initialize the presentation framework */\n public static get initProps() {\n return this._initProps;\n }\n\n /**\n * Initializes Presentation library for the backend.\n *\n * See [Setting up iTwin.js Presentation library documentation page]($docs/presentation/setup/index.md#backend) for an example.\n *\n * **Important:** The method should be called after a call to [IModelHost.startup]($core-backend)\n *\n * @param props Optional properties for [[PresentationManager]]\n */\n public static initialize(props?: PresentationProps): void {\n this._initProps = props || {};\n this._shutdownListener = IModelHost.onBeforeShutdown.addListener(() => Presentation.terminate());\n\n this._rpcImpl = new PresentationRpcImpl({\n requestTimeout: this._initProps.requestTimeout,\n });\n RpcManager.registerImpl(PresentationRpcInterface, PresentationRpcImpl);\n RpcManager.supplyImplInstance(PresentationRpcInterface, this._rpcImpl);\n\n if (IpcHost.isValid) {\n this._disposeIpcHandler = PresentationIpcHandler.register();\n }\n\n this._clientsStorage = new FactoryBasedTemporaryStorage<ClientStoreItem>({\n factory: this.createClientManager.bind(this),\n cleanupHandler: (_id, storeItem) => this.disposeClientManager(_id, storeItem),\n // cleanup unused managers every minute\n cleanupInterval: 60 * 1000,\n // by default, manager is disposed after 1 hour of being unused\n unusedValueLifetime: this._initProps.unusedClientLifetime ?? 60 * 60 * 1000,\n // add some logging\n onDisposedSingle: /* istanbul ignore next */ (id: string) =>\n Logger.logInfo(\n PresentationBackendLoggerCategory.PresentationManager,\n `Disposed PresentationManager instance with ID: ${id}. Total instances: ${this._clientsStorage!.values.length}.`,\n ),\n onDisposedAll: /* istanbul ignore next */ () =>\n Logger.logInfo(PresentationBackendLoggerCategory.PresentationManager, `Disposed all PresentationManager instances.`),\n });\n\n if (this._initProps.enableSchemasPreload) {\n this._disposeIModelOpenedListener = BriefcaseDb.onOpened.addListener(this.onIModelOpened);\n }\n }\n\n /**\n * Terminates Presentation. Consumers don't need to call this as it's automatically\n * called on [IModelHost.onBeforeShutdown]($core-backend) event.\n */\n public static terminate(): void {\n if (this._clientsStorage) {\n this._clientsStorage.dispose();\n this._clientsStorage = undefined;\n }\n if (this._disposeIModelOpenedListener) {\n this._disposeIModelOpenedListener();\n this._disposeIModelOpenedListener = undefined;\n }\n if (this._shutdownListener) {\n this._shutdownListener();\n this._shutdownListener = undefined;\n }\n RpcManager.unregisterImpl(PresentationRpcInterface);\n if (this._rpcImpl) {\n this._rpcImpl.dispose();\n this._rpcImpl = undefined;\n }\n if (this._disposeIpcHandler) {\n this._disposeIpcHandler();\n }\n this._initProps = undefined;\n }\n\n private static createClientManager(clientId: string, onManagerUsed: () => void): ClientStoreItem {\n const manager =\n Presentation._initProps && Presentation._initProps.clientManagerFactory\n ? Presentation._initProps.clientManagerFactory(clientId, Presentation._initProps)\n : new PresentationManager({ ...Presentation._initProps, id: clientId });\n manager.setOnManagerUsedHandler(onManagerUsed);\n Logger.logInfo(\n PresentationBackendLoggerCategory.PresentationManager,\n `Created a PresentationManager instance with ID: ${clientId}. Total instances: ${this._clientsStorage!.values.length}.`,\n );\n return { manager };\n }\n\n private static disposeClientManager(_id: string, storeItem: ClientStoreItem) {\n storeItem.manager.dispose();\n }\n\n /**\n * Get an instance of [[PresentationManager]] for specific client\n * @param clientId ID of the client requesting presentation data. If no\n * ID is provided, the default [[PresentationManager]] is returned.\n */\n public static getManager(clientId?: string): PresentationManager {\n if (this._clientsStorage) {\n return this._clientsStorage.getValue(clientId || \"\").manager;\n }\n throw new PresentationError(PresentationStatus.NotInitialized, \"Presentation must be first initialized by calling Presentation.initialize\");\n }\n\n /**\n * Get the time in milliseconds that backend should respond in .\n */\n public static getRequestTimeout(): number {\n if (this._rpcImpl === undefined) {\n throw new PresentationError(PresentationStatus.NotInitialized, \"Presentation must be first initialized by calling Presentation.initialize\");\n }\n return this._rpcImpl.requestTimeout;\n }\n\n private static onIModelOpened = (imodel: BriefcaseDb) => {\n const manager = this.getManager();\n const imodelAddon = manager.getNativePlatform().getImodelAddon(imodel);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n manager.getNativePlatform().forceLoadSchemas(imodelAddon);\n };\n}\n"]}
1
+ {"version":3,"file":"Presentation.js","sourceRoot":"","sources":["../../../src/presentation-backend/Presentation.ts"],"names":[],"mappings":";AAAA;;;gGAGgG;AAChG;;GAEG;;;AAEH,sDAAuE;AACvE,sDAA0D;AAC1D,oDAAgD;AAChD,oEAA6G;AAC7G,mEAA4E;AAC5E,qEAAkE;AAClE,+DAAsF;AACtF,+DAA4D;AAC5D,yDAAkE;AA6DlE;;;;;;;;;GASG;AACH,MAAa,YAAY;IAQvB,0BAA0B;IAC1B,gBAAuB,CAAC;IAExB,+DAA+D;IACxD,MAAM,KAAK,SAAS;QACzB,OAAO,IAAI,CAAC,UAAU,CAAC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,CAAC;QAClC,MAAM,WAAW,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;QACvE,mEAAmE;QACnE,OAAO,CAAC,iBAAiB,EAAE,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAC;IAC5D,CAAC,CAAC;;AArIJ,oCAsIC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n * Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n * See LICENSE.md in the project root for license terms and full copyright notice.\n *--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module Core\n */\n\nimport { BriefcaseDb, IModelHost, IpcHost } from \"@itwin/core-backend\";\nimport { DisposeFunc, Logger } from \"@itwin/core-bentley\";\nimport { RpcManager } from \"@itwin/core-common\";\nimport { PresentationError, PresentationRpcInterface, PresentationStatus } from \"@itwin/presentation-common\";\nimport { PresentationBackendLoggerCategory } from \"./BackendLoggerCategory\";\nimport { PresentationIpcHandler } from \"./PresentationIpcHandler\";\nimport { PresentationManager, PresentationManagerProps } from \"./PresentationManager\";\nimport { PresentationRpcImpl } from \"./PresentationRpcImpl\";\nimport { FactoryBasedTemporaryStorage } from \"./TemporaryStorage\";\n\n/**\n * Properties that can be used to configure [[Presentation]] API.\n * @public\n */\nexport interface PresentationProps extends Omit<PresentationManagerProps, \"enableSchemasPreload\"> {\n /**\n * Time in milliseconds after which the request will timeout.\n */\n requestTimeout?: number;\n\n /**\n * Should schemas preloading be enabled. If true, [[Presentation]] library listens\n * for `BriefcaseDb.onOpened` event and force pre-loads all ECSchemas.\n */\n enableSchemasPreload?: boolean;\n\n /**\n * Factory method for creating separate managers for each client\n * @internal\n */\n clientManagerFactory?: (clientId: string, props: PresentationManagerProps) => PresentationManager;\n\n /**\n * How much time should an unused client manager be stored in memory\n * before it's disposed.\n */\n unusedClientLifetime?: number;\n}\n\n/**\n * Props for initializing the [[Presentation]] library for using multiple [[PresentationManager]]\n * instances, one for each frontend.\n *\n * @public\n * @deprecated in 4.8 - use [[PresentationProps]] instead.\n */\nexport type MultiManagerPresentationProps = PresentationProps;\n\n/**\n * Base props for initializing the [[Presentation]] library.\n *\n * @public\n * @deprecated in 4.8 - use [[PresentationProps]] instead.\n */\nexport type PresentationPropsBase = PresentationProps;\n\n/**\n * Props for initializing the [[Presentation]] library with ability to use a single\n * [[PresentationManager]] instance for handling all requests.\n *\n * @public\n * @deprecated in 4.8 - use [[PresentationProps]] instead.\n */\nexport type SingleManagerPresentationProps = Omit<PresentationProps, \"clientManagerFactory\" | \"unusedClientLifetime\">;\n\ninterface ClientStoreItem {\n manager: PresentationManager;\n}\n\n/**\n * Static class used to statically set up Presentation library for the backend.\n * Basically what it does is:\n * - Register a RPC implementation\n * - Create a singleton [[PresentationManager]] instance\n * - Subscribe for [IModelHost.onBeforeShutdown]($core-backend) event and terminate\n * the presentation manager when that happens.\n *\n * @public\n */\nexport class Presentation {\n private static _initProps: PresentationProps | undefined;\n private static _clientsStorage: FactoryBasedTemporaryStorage<ClientStoreItem> | undefined;\n private static _disposeIpcHandler: DisposeFunc | undefined;\n private static _shutdownListener: DisposeFunc | undefined;\n private static _disposeIModelOpenedListener: DisposeFunc | undefined;\n private static _rpcImpl: PresentationRpcImpl | undefined;\n\n /* istanbul ignore next */\n private constructor() {}\n\n /** Properties used to initialize the presentation framework */\n public static get initProps() {\n return this._initProps;\n }\n\n /**\n * Initializes Presentation library for the backend.\n *\n * See [Setting up iTwin.js Presentation library documentation page]($docs/presentation/setup/index.md#backend) for an example.\n *\n * **Important:** The method should be called after a call to [IModelHost.startup]($core-backend)\n *\n * @param props Optional properties for [[PresentationManager]]\n */\n public static initialize(props?: PresentationProps): void {\n this._initProps = props || {};\n this._shutdownListener = IModelHost.onBeforeShutdown.addListener(() => Presentation.terminate());\n\n this._rpcImpl = new PresentationRpcImpl({\n requestTimeout: this._initProps.requestTimeout,\n });\n RpcManager.registerImpl(PresentationRpcInterface, PresentationRpcImpl);\n RpcManager.supplyImplInstance(PresentationRpcInterface, this._rpcImpl);\n\n if (IpcHost.isValid) {\n this._disposeIpcHandler = PresentationIpcHandler.register();\n }\n\n this._clientsStorage = new FactoryBasedTemporaryStorage<ClientStoreItem>({\n factory: this.createClientManager.bind(this),\n cleanupHandler: (_id, storeItem) => this.disposeClientManager(_id, storeItem),\n // cleanup unused managers every minute\n cleanupInterval: 60 * 1000,\n // by default, manager is disposed after 1 hour of being unused\n unusedValueLifetime: this._initProps.unusedClientLifetime ?? 60 * 60 * 1000,\n // add some logging\n onDisposedSingle: /* istanbul ignore next */ (id: string) =>\n Logger.logInfo(\n PresentationBackendLoggerCategory.PresentationManager,\n `Disposed PresentationManager instance with ID: ${id}. Total instances: ${this._clientsStorage!.values.length}.`,\n ),\n onDisposedAll: /* istanbul ignore next */ () =>\n Logger.logInfo(PresentationBackendLoggerCategory.PresentationManager, `Disposed all PresentationManager instances.`),\n });\n\n if (this._initProps.enableSchemasPreload) {\n this._disposeIModelOpenedListener = BriefcaseDb.onOpened.addListener(this.onIModelOpened);\n }\n }\n\n /**\n * Terminates Presentation. Consumers don't need to call this as it's automatically\n * called on [IModelHost.onBeforeShutdown]($core-backend) event.\n */\n public static terminate(): void {\n if (this._clientsStorage) {\n this._clientsStorage.dispose();\n this._clientsStorage = undefined;\n }\n if (this._disposeIModelOpenedListener) {\n this._disposeIModelOpenedListener();\n this._disposeIModelOpenedListener = undefined;\n }\n if (this._shutdownListener) {\n this._shutdownListener();\n this._shutdownListener = undefined;\n }\n RpcManager.unregisterImpl(PresentationRpcInterface);\n if (this._rpcImpl) {\n this._rpcImpl.dispose();\n this._rpcImpl = undefined;\n }\n if (this._disposeIpcHandler) {\n this._disposeIpcHandler();\n }\n this._initProps = undefined;\n }\n\n private static createClientManager(clientId: string, onManagerUsed: () => void): ClientStoreItem {\n const manager =\n Presentation._initProps && Presentation._initProps.clientManagerFactory\n ? Presentation._initProps.clientManagerFactory(clientId, Presentation._initProps)\n : new PresentationManager({ ...Presentation._initProps, id: clientId });\n manager.setOnManagerUsedHandler(onManagerUsed);\n Logger.logInfo(\n PresentationBackendLoggerCategory.PresentationManager,\n `Created a PresentationManager instance with ID: ${clientId}. Total instances: ${this._clientsStorage!.values.length}.`,\n );\n return { manager };\n }\n\n private static disposeClientManager(_id: string, storeItem: ClientStoreItem) {\n storeItem.manager.dispose();\n }\n\n /**\n * Get an instance of [[PresentationManager]] for specific client\n * @param clientId ID of the client requesting presentation data. If no\n * ID is provided, the default [[PresentationManager]] is returned.\n */\n public static getManager(clientId?: string): PresentationManager {\n if (this._clientsStorage) {\n return this._clientsStorage.getValue(clientId || \"\").manager;\n }\n throw new PresentationError(PresentationStatus.NotInitialized, \"Presentation must be first initialized by calling Presentation.initialize\");\n }\n\n /**\n * Get the time in milliseconds that backend should respond in .\n */\n public static getRequestTimeout(): number {\n if (this._rpcImpl === undefined) {\n throw new PresentationError(PresentationStatus.NotInitialized, \"Presentation must be first initialized by calling Presentation.initialize\");\n }\n return this._rpcImpl.requestTimeout;\n }\n\n private static onIModelOpened = (imodel: BriefcaseDb) => {\n const manager = this.getManager();\n const imodelAddon = manager.getNativePlatform().getImodelAddon(imodel);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n manager.getNativePlatform().forceLoadSchemas(imodelAddon);\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"PresentationManager.d.ts","sourceRoot":"","sources":["../../../src/presentation-backend/PresentationManager.ts"],"names":[],"mappings":"AAIA;;GAEG;AAIH,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAEL,gBAAgB,IAAI,sBAAsB,EAC1C,8BAA8B,EAC9B,OAAO,EACP,+BAA+B,EAI/B,qBAAqB,EACrB,4BAA4B,EAE5B,UAAU,E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E,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GAAG,2BAA2B,GAC5H,OAAO,CAAC,MAAM,CAAC;IAClB;;;OAGG;IAEU,gBAAgB,CAAC,cAAc,EAAE,8BAA8B,CAAC,QAAQ,CAAC,GAAG,2BAA2B,GAAG,OAAO,CAAC,MAAM,CAAC;IAetI;;;OAGG;IACU,kBAAkB,CAAC,cAAc,EAAE,uBAAuB,CAAC,QAAQ,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,oBAAoB,CAAC;CA+B3H"}
1
+ {"version":3,"file":"PresentationManager.d.ts","sourceRoot":"","sources":["../../../src/presentation-backend/PresentationManager.ts"],"names":[],"mappings":"AAIA;;GAEG;AAIH,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EAAa,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAEL,gBAAgB,IAAI,sBAAsB,EAC1C,8BAA8B,EAC9B,OAAO,EACP,+BAA+B,EAI/B,qBAAqB,EACrB,4BAA4B,EAE5B,UAAU,EACV,mBAAmB,EACnB,0BAA0B,EAC1B,2BAA2B,EAC3B,iBAAiB,EACjB,4BAA4B,EAC5B,iBAAiB,EACjB,4CAA4C,EAC5C,mCAAmC,EACnC,UAAU,EACV,oBAAoB,EACpB,uBAAuB,EACvB,sCAAsC,EAEtC,uBAAuB,EACvB,WAAW,EAGX,IAAI,EACJ,MAAM,EAEN,eAAe,EAEf,oCAAoC,EACpC,IAAI,EACJ,OAAO,EACP,eAAe,EACf,KAAK,EACL,aAAa,EAGb,WAAW,EACX,OAAO,EACP,eAAe,EACf,eAAe,EACf,cAAc,EACd,4BAA4B,EAC5B,qCAAqC,EACrC,eAAe,EAChB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,wBAAwB,EA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,eAAe,CAAC,WAAW,CAAC,oCAAoC,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC,CAAC,GAAG,2BAA2B,GACzI,OAAO,CAAC,8BAA8B,CAAC,cAAc,CAAC,CAAC;YAa5C,0BAA0B;YAqB1B,4BAA4B;IA6E1C;;;OAGG;IACU,yBAAyB,CACpC,cAAc,EAAE,eAAe,CAAC,WAAW,CAAC,0BAA0B,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC,CAAC,GAAG,2BAA2B,GAC5H,OAAO,CAAC,eAAe,CAAC;IAK3B;;;OAGG;IACU,0BAA0B,CACrC,cAAc,EAAE,eAAe,CAAC,WAAW,CAAC,KAAK,CAAC,2BAA2B,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,GAAG,2BAA2B,GACpI,OAAO,CAAC,eAAe,EAAE,CAAC;IAK7B;;;OAGG;IACU,kBAAkB,CAAC,eAAe,EAAE,4BAA4B,CAAC,QAAQ,CAAC,GAAG,2BAA2B,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;IAIjJ;;;;OAIG;IACU,gBAAgB,CAC3B,cAAc,EAAE,4BAA4B,CAAC,QAAQ,CAAC,GAAG;QAAE,GAAG,EAAE,UAAU,EAAE,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GAAG,2BAA2B,GAC5H,OAAO,CAAC,MAAM,CAAC;IAClB;;;OAGG;IAEU,gBAAgB,CAAC,cAAc,EAAE,8BAA8B,CAAC,QAAQ,CAAC,GAAG,2BAA2B,GAAG,OAAO,CAAC,MAAM,CAAC;IAetI;;;OAGG;IACU,kBAAkB,CAAC,cAAc,EAAE,uBAAuB,CAAC,QAAQ,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,oBAAoB,CAAC;CA+B3H"}
@@ -260,7 +260,7 @@ class PresentationManager {
260
260
  return parser(content.descriptor, content.contentSet[0]);
261
261
  }
262
262
  async getMultipleElementProperties(requestOptions) {
263
- const { elementClasses, contentParser, batchSize, ...contentOptions } = requestOptions;
263
+ const { contentParser, batchSize: batchSizeOption, ...contentOptions } = requestOptions;
264
264
  const parser = contentParser ?? presentation_common_1.buildElementProperties;
265
265
  const workerThreadsCount = this._props.workerThreadsCount ?? 2;
266
266
  // We don't want to request content for all classes at once - each class results in a huge content descriptor object that's cached in memory
@@ -268,75 +268,40 @@ class PresentationManager {
268
268
  // but also may push descriptors out of cache, requiring us to recreate them, thus making performance worse. For those reasons we handle at
269
269
  // most `workerThreadsCount / 2` classes in parallel.
270
270
  // istanbul ignore next
271
- const classParallelism = workerThreadsCount > 1 ? workerThreadsCount / 2 : 1;
271
+ const classParallelism = workerThreadsCount > 1 ? Math.ceil(workerThreadsCount / 2) : 1;
272
272
  // We want all worker threads to be constantly busy. However, there's some fairly expensive work being done after the worker thread is done,
273
273
  // but before we receive the response. That means the worker thread would be starving if we sent only `workerThreadsCount` requests in parallel.
274
274
  // To avoid that, we keep twice as much requests active.
275
275
  // istanbul ignore next
276
- const batchesParallelism = workerThreadsCount > 0 ? workerThreadsCount * 2 : 2;
277
- const createClassContentRuleset = (fullClassName) => {
278
- const [schemaName, className] = (0, ElementPropertiesHelper_1.parseFullClassName)(fullClassName);
279
- return {
280
- id: `content/${fullClassName}`,
281
- rules: [
282
- {
283
- ruleType: "Content",
284
- specifications: [
285
- {
286
- specType: "ContentInstancesOfSpecificClasses",
287
- classes: {
288
- schemaName,
289
- classNames: [className],
290
- arePolymorphic: false,
291
- },
292
- handlePropertiesPolymorphically: true,
293
- },
294
- ],
295
- },
296
- ],
297
- };
298
- };
299
- const getContentDescriptor = async (ruleset) => {
300
- return (await this.getContentDescriptor({
301
- ...contentOptions,
302
- rulesetOrId: ruleset,
303
- displayType: presentation_common_1.DefaultContentDisplayTypes.Grid,
304
- contentFlags: presentation_common_1.ContentFlags.ShowLabels,
305
- keys: new presentation_common_1.KeySet(),
306
- }));
307
- };
308
- const obs = (0, ElementPropertiesHelper_1.getClassesWithInstances)(requestOptions.imodel, elementClasses ?? /* istanbul ignore next */ ["BisCore.Element"]).pipe((0, rxjs_1.map)((classFullName) => ({
309
- classFullName,
310
- ruleset: createClassContentRuleset(classFullName),
311
- })), (0, rxjs_1.mergeMap)(({ classFullName, ruleset }) =>
312
- // use forkJoin to query descriptor and element ids in parallel
313
- (0, rxjs_1.forkJoin)({
314
- classFullName: (0, rxjs_1.of)(classFullName),
315
- ruleset: (0, rxjs_1.of)(ruleset),
316
- descriptor: (0, rxjs_1.from)(getContentDescriptor(ruleset)),
317
- batches: (0, rxjs_1.from)((0, ElementPropertiesHelper_1.getBatchedClassElementIds)(requestOptions.imodel, classFullName, batchSize ?? /* istanbul ignore next */ 1000)),
318
- }).pipe(
319
- // split incoming stream into individual batch requests
320
- (0, rxjs_1.mergeMap)(({ descriptor, batches }) => (0, rxjs_1.from)(batches.map((batch) => ({ classFullName, descriptor, batch })))),
321
- // request content for each batch, filter by IDs for performance
322
- (0, rxjs_1.mergeMap)(({ descriptor, batch }) => {
323
- const filteringDescriptor = new presentation_common_1.Descriptor(descriptor);
324
- filteringDescriptor.instanceFilter = {
325
- selectClassName: classFullName,
326
- expression: `this.ECInstanceId >= ${Number.parseInt(batch.from, 16)} AND this.ECInstanceId <= ${Number.parseInt(batch.to, 16)}`,
327
- };
328
- return (0, rxjs_1.from)(this.getContentSet({
329
- ...contentOptions,
330
- keys: new presentation_common_1.KeySet(),
331
- descriptor: filteringDescriptor,
332
- rulesetOrId: ruleset,
333
- })).pipe((0, rxjs_1.map)((items) => ({ classFullName, descriptor, items })));
334
- }, batchesParallelism)), classParallelism), (0, rxjs_1.map)(({ descriptor, items }) => items.map((item) => parser(descriptor, item))));
276
+ const batchesParallelism = workerThreadsCount > 0 ? workerThreadsCount : 1;
277
+ // istanbul ignore next
278
+ const batchSize = batchSizeOption ?? 100;
279
+ const elementsIdentifier = (() => {
280
+ if ("elementIds" in contentOptions && contentOptions.elementIds !== undefined) {
281
+ const elementIds = contentOptions.elementIds;
282
+ delete contentOptions.elementIds;
283
+ return { elementIds };
284
+ }
285
+ // istanbul ignore else
286
+ if ("elementClasses" in contentOptions && contentOptions.elementClasses !== undefined) {
287
+ const elementClasses = contentOptions.elementClasses;
288
+ delete contentOptions.elementClasses;
289
+ return { elementClasses };
290
+ }
291
+ // istanbul ignore next
292
+ return { elementClasses: ["BisCore:Element"] };
293
+ })();
294
+ const descriptorGetter = async (partialProps) => this.getContentDescriptor({ ...contentOptions, displayType: presentation_common_1.DefaultContentDisplayTypes.Grid, contentFlags: presentation_common_1.ContentFlags.ShowLabels, ...partialProps });
295
+ const contentSetGetter = async (partialProps) => this.getContentSet({ ...contentOptions, ...partialProps });
296
+ const { itemBatches, count } = "elementIds" in elementsIdentifier
297
+ ? (0, ElementPropertiesHelper_1.getContentItemsObservableFromElementIds)(requestOptions.imodel, descriptorGetter, contentSetGetter, elementsIdentifier.elementIds, classParallelism, batchesParallelism, batchSize)
298
+ : (0, ElementPropertiesHelper_1.getContentItemsObservableFromClassNames)(requestOptions.imodel, descriptorGetter, contentSetGetter, elementsIdentifier.elementClasses, classParallelism, batchesParallelism, batchSize);
335
299
  return {
336
- total: (0, ElementPropertiesHelper_1.getElementsCount)(requestOptions.imodel, elementClasses),
300
+ total: await (0, rxjs_1.firstValueFrom)(count),
337
301
  async *iterator() {
338
- for await (const batch of (0, rxjs_for_await_1.eachValueFrom)(obs)) {
339
- yield batch;
302
+ for await (const itemsBatch of (0, rxjs_for_await_1.eachValueFrom)(itemBatches)) {
303
+ const { descriptor, items } = itemsBatch;
304
+ yield items.map((item) => parser(descriptor, item));
340
305
  }
341
306
  },
342
307
  };
@@ -1 +1 @@
1
- {"version":3,"file":"PresentationManager.js","sourceRoot":"","sources":["../../../src/presentation-backend/PresentationManager.ts"],"names":[],"mappings":";AAAA;;;gGAGgG;AAChG;;GAEG;;;AAEH,+BAAyD;AACzD,mDAA+C;AAK/C,oEAmDoC;AACpC,uEAAqI;AACrI,qDAAwF;AACxF,2EAA4F;AAE5F,uEAAiG;AACjG,m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AAa,CAAC;QAC9F,IAAI,aAAa,CAAC,KAAK,CAAC,EAAE,KAAK,aAAa,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC;YACtD,MAAM,IAAI,uCAAiB,CAAC,wCAAkB,CAAC,eAAe,EAAE,2CAA2C,CAAC,CAAC;QAC/G,CAAC;QAED,MAAM,oBAAoB,GAAG,gBAAgB,IAAI,EAAE,CAAC;QACpD,MAAM,oBAAoB,GAAG,IAAI,CAAC,gBAAgB,IAAI,oBAAoB,CAAC;QAE3E,MAAM,MAAM,GAAG;YACb,SAAS,EAAE,2CAA0B,CAAC,kBAAkB;YACxD,GAAG,OAAO;YACV,aAAa,EAAE,aAAa,CAAC,QAAQ;YACrC,aAAa,EAAE,aAAa,CAAC,QAAQ;YACrC,oBAAoB,EAAE,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC;YAC1D,oBAAoB,EAAE,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC;YAC1D,gBAAgB,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,gBAAgB,IAAI,EAAE,CAAC;SACjE,CAAC;QAEF,4DAA4D;QAC5D,MAAM,OAAO,GAAG,CAAC,GAAW,EAAE,KAAU,EAAE,EAAE,CAAC,CAAC,GAAG,KAAK,EAAE,CAAC,CAAC,CAAC,0CAAoB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;QACzG,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC;IACjE,CAAC;CACF;AAleD,kDAkeC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n * Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n * See LICENSE.md in the project root for license terms and full copyright notice.\n *--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module Core\n */\n\nimport { forkJoin, from, map, mergeMap, of } from \"rxjs\";\nimport { eachValueFrom } from \"rxjs-for-await\";\nimport { IModelDb } from \"@itwin/core-backend\";\nimport { Id64String } from \"@itwin/core-bentley\";\nimport { UnitSystemKey } from \"@itwin/core-quantity\";\nimport { SchemaContext } from \"@itwin/ecschema-metadata\";\nimport {\n buildElementProperties,\n UnitSystemFormat as CommonUnitSystemFormat,\n ComputeSelectionRequestOptions,\n Content,\n ContentDescriptorRequestOptions,\n ContentFlags,\n ContentFormatter,\n ContentPropertyValueFormatter,\n ContentRequestOptions,\n ContentSourcesRequestOptions,\n DefaultContentDisplayTypes,\n Descriptor,\n DescriptorOverrides,\n DisplayLabelRequestOptions,\n DisplayLabelsRequestOptions,\n DisplayValueGroup,\n DistinctValuesRequestOptions,\n ElementProperties,\n FilterByInstancePathsHierarchyRequestOptions,\n FilterByTextHierarchyRequestOptions,\n FormatsMap,\n HierarchyCompareInfo,\n HierarchyCompareOptions,\n HierarchyLevelDescriptorRequestOptions,\n HierarchyLevelJSON,\n HierarchyRequestOptions,\n InstanceKey,\n isComputeSelectionRequestOptions,\n isSingleElementPropertiesRequestOptions,\n Item,\n KeySet,\n KoqPropertyValueFormatter,\n LabelDefinition,\n LocalizationHelper,\n MultiElementPropertiesRequestOptions,\n Node,\n NodeKey,\n NodePathElement,\n Paged,\n PagedResponse,\n PresentationError,\n PresentationStatus,\n Prioritized,\n Ruleset,\n RulesetVariable,\n SelectClassInfo,\n SelectionScope,\n SelectionScopeRequestOptions,\n SingleElementPropertiesRequestOptions,\n WithCancelEvent,\n} from \"@itwin/presentation-common\";\nimport { getBatchedClassElementIds, getClassesWithInstances, getElementsCount, parseFullClassName } from \"./ElementPropertiesHelper\";\nimport { NativePlatformDefinition, NativePlatformRequestTypes } from \"./NativePlatform\";\nimport { getRulesetIdObject, PresentationManagerDetail } from \"./PresentationManagerDetail\";\nimport { RulesetManager } from \"./RulesetManager\";\nimport { RulesetVariablesManager, RulesetVariablesManagerImpl } from \"./RulesetVariablesManager\";\nimport { SelectionScopesHelper } from \"./SelectionScopesHelper\";\nimport { BackendDiagnosticsAttribute, BackendDiagnosticsOptions, getLocalizedStringEN } from \"./Utils\";\n\n/**\n * Presentation manager working mode.\n * @public\n * @deprecated in 3.x. The attribute is not used by [[PresentationManager]] anymore\n */\nexport enum PresentationManagerMode {\n /**\n * Presentation manager assumes iModels are opened in read-only mode and avoids doing some work\n * related to reacting to changes in iModels.\n */\n ReadOnly,\n\n /**\n * Presentation manager assumes iModels are opened in read-write mode and it may need to\n * react to changes. This involves some additional work and gives slightly worse performance.\n */\n ReadWrite,\n}\n\n/**\n * Presentation hierarchy cache mode.\n * @public\n */\nexport enum HierarchyCacheMode {\n /**\n * Hierarchy cache is created in memory.\n */\n Memory = \"memory\",\n /**\n * Hierarchy cache is created on disk. In this mode hierarchy cache is persisted between iModel\n * openings.\n */\n Disk = \"disk\",\n /**\n * Hierarchy cache is created on disk. In this mode everything is cached in memory while creating hierarchy level\n * and persisted in disk cache when whole hierarchy level is created.\n *\n * **Note:** This mode is still experimental.\n */\n Hybrid = \"hybrid\",\n}\n\n/**\n * Configuration for hierarchy cache.\n * @public\n */\nexport type HierarchyCacheConfig = MemoryHierarchyCacheConfig | DiskHierarchyCacheConfig | HybridCacheConfig;\n\n/**\n * Base interface for all [[HierarchyCacheConfig]] implementations.\n * @public\n */\nexport interface HierarchyCacheConfigBase {\n mode: HierarchyCacheMode;\n}\n\n/**\n * Configuration for in-memory hierarchy cache.\n *\n * @see [Memory cache documentation page]($docs/presentation/advanced/Caching.md#memory-cache)\n * @public\n */\nexport interface MemoryHierarchyCacheConfig extends HierarchyCacheConfigBase {\n mode: HierarchyCacheMode.Memory;\n}\n\n/**\n * Configuration for persistent disk hierarchy cache.\n *\n * @see [Disk cache documentation page]($docs/presentation/advanced/Caching.md#disk-cache)\n * @public\n */\nexport interface DiskHierarchyCacheConfig extends HierarchyCacheConfigBase {\n mode: HierarchyCacheMode.Disk;\n\n /**\n * A directory for hierarchy caches. If set, the directory must exist. Relative paths start from `process.cwd()`.\n *\n * The default directory depends on the iModel and the way it's opened.\n */\n directory?: string;\n\n /**\n * While the cache itself is stored on a disk, there's still a required small in-memory cache.\n * The parameter allows controlling size of that cache. Defaults to `32768000` bytes (32 MB).\n */\n memoryCacheSize?: number;\n}\n\n/**\n * Configuration for the experimental hybrid hierarchy cache.\n *\n * Hybrid cache uses a combination of in-memory and disk caches, which should make it a better\n * alternative for cases when there are lots of simultaneous requests.\n *\n * @see [Hybrid cache documentation page]($docs/presentation/advanced/Caching.md#hybrid-cache)\n * @public\n */\nexport interface HybridCacheConfig extends HierarchyCacheConfigBase {\n mode: HierarchyCacheMode.Hybrid;\n\n /** Configuration for disk cache used to persist hierarchies. */\n disk?: DiskHierarchyCacheConfig;\n}\n\n/**\n * Configuration for content cache.\n *\n * @see [Content cache documentation page]($docs/presentation/advanced/Caching.md#content-cache)\n * @public\n */\nexport interface ContentCacheConfig {\n /**\n * Maximum number of content descriptors cached in memory for quicker paged content requests.\n *\n * Defaults to `100`.\n */\n size?: number;\n}\n\n/**\n * Caching configuration options for [[PresentationManager]].\n * @public\n */\nexport interface PresentationManagerCachingConfig {\n /**\n * Hierarchies-related caching options.\n *\n * @see [Hierarchies cache documentation page]($docs/presentation/advanced/Caching.md#hierarchies-cache)\n */\n hierarchies?: HierarchyCacheConfig;\n\n /**\n * Content-related caching options.\n *\n * @see [Content cache documentation page]($docs/presentation/advanced/Caching.md#content-cache)\n */\n content?: ContentCacheConfig;\n\n /**\n * Each worker thread (see [[workerThreadsCount]]) opens a connection to an iModel used for a request. This\n * means there could be `{workerThreadsCount} * {iModels count}` number of connections. Each connection\n * uses a memory cache to increase iModel read performance. This parameter allows controlling the size of that\n * cache. Defaults to `32768000` bytes (32 MB).\n *\n * @see [Worker connections cache documentation page]($docs/presentation/advanced/Caching.md#worker-connections-cache)\n */\n workerConnectionCacheSize?: number;\n}\n\n/**\n * A data structure that associates unit systems with a format. The associations are used for\n * assigning default unit formats for specific phenomenons (see [[PresentationManagerProps.defaultFormats]]).\n *\n * @public\n * @deprecated in 4.3. The type has been moved to `@itwin/presentation-common` package.\n */\nexport type UnitSystemFormat = CommonUnitSystemFormat;\n\n/**\n * Data structure for multiple element properties request response.\n * @public\n */\nexport interface MultiElementPropertiesResponse<TParsedContent = ElementProperties> {\n total: number;\n iterator: () => AsyncGenerator<TParsedContent[]>;\n}\n\n/**\n * Configuration options for supplying asset paths to [[PresentationManager]].\n * @public\n */\nexport interface PresentationAssetsRootConfig {\n /**\n * Path to `presentation-backend` assets. Relative paths start from `process.cwd()`.\n */\n backend: string;\n\n /**\n * Path to `presentation-common` assets.\n *\n * @deprecated in 3.x. This path is not used anymore\n */\n common: string;\n}\n\n/**\n * Properties that can be used to configure [[PresentationManager]]\n * @public\n */\nexport interface PresentationManagerProps {\n /**\n * Path overrides for presentation backend assets. Need to be overriden by application if it puts these assets someplace else than the default.\n *\n * By default the path to assets directory is determined during the call of [[Presentation.initialize]] using this algorithm:\n *\n * - if path of `.js` file that contains [[PresentationManager]] definition contains \"presentation-backend\", assume the package is in `node_modules` and the directory structure is:\n * - `assets/*\\*\\/*`\n * - `presentation-backend/{presentation-backend source files}`\n *\n * which means the assets can be found through a relative path `../assets/` from the JS file being executed.\n *\n * - else, assume the backend is webpacked into a single file with assets next to it:\n * - `assets/*\\*\\/*`\n * - `{source file being executed}.js`\n *\n * which means the assets can be found through a relative path `./assets/` from the `{source file being executed}`.\n *\n * @deprecated in 4.2. This attribute is not used anymore - the package is not using private assets anymore.\n */\n presentationAssetsRoot?: string | PresentationAssetsRootConfig;\n\n /**\n * A list of directories containing application's presentation rulesets. Relative\n * paths start from `process.cwd()`. The directories are traversed recursively.\n *\n * @note Only files with `.PresentationRuleSet.json` are read.\n */\n rulesetDirectories?: string[];\n\n /**\n * A list of directories containing application's supplemental presentation rulesets. Relative\n * paths start from `process.cwd()`. The directories are traversed recursively.\n *\n * @note Only files with `.PresentationRuleSet.json` are read.\n */\n supplementalRulesetDirectories?: string[];\n\n /**\n * A list of directories containing application's locale-specific localized\n * string files (in simplified i18next v3 format)\n *\n * @deprecated in 3.x. Use [[getLocalizedString]] to localize data returned by [[PresentationManager]].\n */\n localeDirectories?: string[];\n\n /**\n * Sets the active locale to use when localizing presentation-related\n * strings. It can later be changed through [[PresentationManager.activeLocale]].\n *\n * @deprecated in 3.x. Use [[getLocalizedString]] to localize data returned by [[PresentationManager]].\n */\n defaultLocale?: string;\n\n /**\n * Sets the active unit system to use for formatting property values with\n * units. Default presentation units are used if this is not specified. The active unit\n * system can later be changed through [[PresentationManager.activeUnitSystem]] or overriden for each request\n * through request options.\n */\n defaultUnitSystem?: UnitSystemKey;\n\n /**\n * A map of default unit formats to use for formatting properties that don't have a presentation format\n * in requested unit system.\n */\n defaultFormats?: FormatsMap;\n\n /**\n * Should schemas preloading be enabled. If true, presentation manager listens\n * for `BriefcaseDb.onOpened` event and force pre-loads all ECSchemas.\n *\n * @deprecated in 3.x. Use [[PresentationProps.enableSchemasPreload]] instead.\n */\n enableSchemasPreload?: boolean;\n\n /**\n * A number of worker threads to use for handling presentation requests. Defaults to `2`.\n */\n workerThreadsCount?: number;\n\n /**\n * Presentation manager working mode. Backends that use iModels in read-write mode should\n * use `ReadWrite`, others might want to set to `ReadOnly` for better performance.\n *\n * Defaults to [[PresentationManagerMode.ReadWrite]].\n *\n * @deprecated in 3.x. The attribute is not used by [[PresentationManager]] anymore\n */\n mode?: PresentationManagerMode; // eslint-disable-line @typescript-eslint/no-deprecated\n\n /**\n * The interval (in milliseconds) used to poll for presentation data changes. If not set, presentation\n * data changes are not tracked at all.\n *\n * @beta\n * @deprecated in 4.4. The manager now always tracks for iModel data changes without polling.\n */\n updatesPollInterval?: number;\n\n /** Options for caching. */\n caching?: PresentationManagerCachingConfig;\n\n /**\n * Use [SQLite's Memory-Mapped I/O](https://sqlite.org/mmap.html) for worker connections. This mode improves performance of handling\n * requests with high I/O intensity, e.g. filtering large tables on non-indexed columns. No downsides have been noticed.\n *\n * Set to a falsy value to turn off. `true` for memory-mapping the whole iModel. Number value for memory-mapping the specified amount of bytes.\n */\n useMmap?: boolean | number;\n\n /**\n * An identifier which helps separate multiple presentation managers. It's\n * mostly useful in tests where multiple presentation managers can co-exist\n * and try to share the same resources, which we don't want. With this identifier\n * set, managers put their resources into id-named subdirectories.\n *\n * @internal\n */\n id?: string;\n\n /** @internal */\n addon?: NativePlatformDefinition;\n\n /**\n * Localization function to localize data returned by presentation manager when it's used directly on the backend (as opposed to when used through RPC, where\n * data is localized on the frontend). Defaults to English localization.\n *\n * @see [Localization]($docs/presentation/advanced/Localization)\n */\n getLocalizedString?: (key: string) => string;\n\n /**\n * Callback that provides [SchemaContext]($ecschema-metadata) for supplied [IModelDb]($core-backend).\n * [SchemaContext]($ecschema-metadata) is used for getting metadata required for values formatting.\n */\n schemaContextProvider?: (imodel: IModelDb) => SchemaContext;\n\n /**\n * Parameters for gathering diagnostics at the manager level. When supplied, they're used with every request\n * made through the manager.\n *\n * @see [Diagnostics documentation page]($docs/presentation/advanced/Diagnostics.md)\n */\n diagnostics?: BackendDiagnosticsOptions;\n}\n\n/**\n * Backend Presentation manager which pulls the presentation data from\n * an iModel using native platform.\n *\n * @public\n */\nexport class PresentationManager {\n private _props: PresentationManagerProps;\n private _detail: PresentationManagerDetail;\n private _localizationHelper: LocalizationHelper;\n\n /**\n * Get / set active locale used for localizing presentation data\n * @deprecated in 3.x. Use [[PresentationManagerProps.getLocalizedString]] to localize data returned by [[PresentationManager]].\n */\n public activeLocale: string | undefined;\n\n /**\n * Creates an instance of PresentationManager.\n * @param props Optional configuration properties.\n */\n constructor(props?: PresentationManagerProps) {\n this._props = props ?? {};\n this._detail = new PresentationManagerDetail(this._props);\n this.activeLocale = this._props.defaultLocale; // eslint-disable-line @typescript-eslint/no-deprecated\n\n this._localizationHelper = new LocalizationHelper({ getLocalizedString: props?.getLocalizedString ?? getLocalizedStringEN });\n }\n\n /** Get / set active unit system used to format property values with units */\n public get activeUnitSystem(): UnitSystemKey | undefined {\n return this._detail.activeUnitSystem;\n }\n // istanbul ignore next\n public set activeUnitSystem(value: UnitSystemKey | undefined) {\n this._detail.activeUnitSystem = value;\n }\n\n /** Dispose the presentation manager. Must be called to clean up native resources. */\n public dispose() {\n this._detail.dispose();\n }\n\n /** @internal */\n public setOnManagerUsedHandler(handler: () => void) {\n this._detail.setOnManagerUsedHandler(handler);\n }\n\n /** Properties used to initialize the manager */\n public get props() {\n return this._props;\n }\n\n /** Get rulesets manager */\n public rulesets(): RulesetManager {\n return this._detail.rulesets;\n }\n\n /**\n * Get ruleset variables manager for specific ruleset\n * @param rulesetId Id of the ruleset to get variables manager for\n */\n public vars(rulesetId: string): RulesetVariablesManager {\n return new RulesetVariablesManagerImpl(this.getNativePlatform, rulesetId);\n }\n\n /** @internal */\n public getNativePlatform = (): NativePlatformDefinition => {\n return this._detail.getNativePlatform();\n };\n\n /** @internal */\n // istanbul ignore next\n public getDetail(): PresentationManagerDetail {\n return this._detail;\n }\n\n /** @internal */\n public getRulesetId(rulesetOrId: Ruleset | string) {\n return this._detail.getRulesetId(rulesetOrId);\n }\n\n /**\n * Retrieves nodes\n * @public\n */\n public async getNodes(\n requestOptions: WithCancelEvent<Prioritized<Paged<HierarchyRequestOptions<IModelDb, NodeKey, RulesetVariable>>>> & BackendDiagnosticsAttribute,\n ): Promise<Node[]> {\n const serializedNodesJson = await this._detail.getNodes(requestOptions);\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n const nodesJson = JSON.parse(serializedNodesJson) as HierarchyLevelJSON;\n const nodes = Node.listFromJSON(nodesJson.nodes);\n return this._localizationHelper.getLocalizedNodes(nodes);\n }\n\n /**\n * Retrieves nodes count\n * @public\n */\n public async getNodesCount(\n requestOptions: WithCancelEvent<Prioritized<HierarchyRequestOptions<IModelDb, NodeKey, RulesetVariable>>> & BackendDiagnosticsAttribute,\n ): Promise<number> {\n return this._detail.getNodesCount(requestOptions);\n }\n\n /**\n * Retrieves hierarchy level descriptor\n * @public\n */\n public async getNodesDescriptor(\n requestOptions: WithCancelEvent<Prioritized<HierarchyLevelDescriptorRequestOptions<IModelDb, NodeKey, RulesetVariable>>> & BackendDiagnosticsAttribute,\n ): Promise<Descriptor | undefined> {\n const response = await this._detail.getNodesDescriptor(requestOptions);\n const descriptor = Descriptor.fromJSON(JSON.parse(response));\n return descriptor ? this._localizationHelper.getLocalizedContentDescriptor(descriptor) : undefined;\n }\n\n /**\n * Retrieves paths from root nodes to children nodes according to specified instance key paths. Intersecting paths will be merged.\n * TODO: Return results in pages\n * @public\n */\n public async getNodePaths(\n requestOptions: WithCancelEvent<Prioritized<FilterByInstancePathsHierarchyRequestOptions<IModelDb, RulesetVariable>>> & BackendDiagnosticsAttribute,\n ): Promise<NodePathElement[]> {\n const result = await this._detail.getNodePaths(requestOptions);\n return result.map((npe) => this._localizationHelper.getLocalizedNodePathElement(npe));\n }\n\n /**\n * Retrieves paths from root nodes to nodes containing filter text in their label.\n * TODO: Return results in pages\n * @public\n */\n public async getFilteredNodePaths(\n requestOptions: WithCancelEvent<Prioritized<FilterByTextHierarchyRequestOptions<IModelDb, RulesetVariable>>> & BackendDiagnosticsAttribute,\n ): Promise<NodePathElement[]> {\n const result = await this._detail.getFilteredNodePaths(requestOptions);\n return result.map((npe) => this._localizationHelper.getLocalizedNodePathElement(npe));\n }\n\n /**\n * Get information about the sources of content when building it for specific ECClasses. Sources involve classes of the primary select instance,\n * its related instances for loading related and navigation properties.\n * @public\n */\n public async getContentSources(\n requestOptions: WithCancelEvent<Prioritized<ContentSourcesRequestOptions<IModelDb>>> & BackendDiagnosticsAttribute,\n ): Promise<SelectClassInfo[]> {\n return this._detail.getContentSources(requestOptions);\n }\n\n /**\n * Retrieves the content descriptor which can be used to get content\n * @public\n */\n public async getContentDescriptor(\n requestOptions: WithCancelEvent<Prioritized<ContentDescriptorRequestOptions<IModelDb, KeySet, RulesetVariable>>> & BackendDiagnosticsAttribute,\n ): Promise<Descriptor | undefined> {\n const response = await this._detail.getContentDescriptor(requestOptions);\n const descriptor = Descriptor.fromJSON(JSON.parse(response));\n return descriptor ? this._localizationHelper.getLocalizedContentDescriptor(descriptor) : undefined;\n }\n\n /**\n * Retrieves the content set size based on the supplied content descriptor override\n * @public\n */\n public async getContentSetSize(\n requestOptions: WithCancelEvent<Prioritized<ContentRequestOptions<IModelDb, Descriptor | DescriptorOverrides, KeySet, RulesetVariable>>> &\n BackendDiagnosticsAttribute,\n ): Promise<number> {\n return this._detail.getContentSetSize(requestOptions);\n }\n\n /**\n * Retrieves the content set based on the supplied content descriptor.\n * @public\n */\n public async getContentSet(\n requestOptions: WithCancelEvent<Prioritized<Paged<ContentRequestOptions<IModelDb, Descriptor, KeySet, RulesetVariable>>>> & BackendDiagnosticsAttribute,\n ): Promise<Item[]> {\n let items = await this._detail.getContentSet({\n ...requestOptions,\n ...(!requestOptions.omitFormattedValues && this.props.schemaContextProvider !== undefined ? { omitFormattedValues: true } : undefined),\n });\n\n if (!requestOptions.omitFormattedValues && this.props.schemaContextProvider !== undefined) {\n const koqPropertyFormatter = new KoqPropertyValueFormatter(this.props.schemaContextProvider(requestOptions.imodel), this.props.defaultFormats);\n const formatter = new ContentFormatter(\n new ContentPropertyValueFormatter(koqPropertyFormatter),\n requestOptions.unitSystem ?? this.props.defaultUnitSystem,\n );\n items = await formatter.formatContentItems(items, requestOptions.descriptor);\n }\n\n return this._localizationHelper.getLocalizedContentItems(items);\n }\n\n /**\n * Retrieves the content based on the supplied content descriptor override.\n * @public\n */\n public async getContent(\n requestOptions: WithCancelEvent<Prioritized<Paged<ContentRequestOptions<IModelDb, Descriptor | DescriptorOverrides, KeySet, RulesetVariable>>>> &\n BackendDiagnosticsAttribute,\n ): Promise<Content | undefined> {\n const content = await this._detail.getContent({\n ...requestOptions,\n ...(!requestOptions.omitFormattedValues && this.props.schemaContextProvider !== undefined ? { omitFormattedValues: true } : undefined),\n });\n\n if (!content) {\n return undefined;\n }\n\n if (!requestOptions.omitFormattedValues && this.props.schemaContextProvider !== undefined) {\n const koqPropertyFormatter = new KoqPropertyValueFormatter(this.props.schemaContextProvider(requestOptions.imodel), this.props.defaultFormats);\n const formatter = new ContentFormatter(\n new ContentPropertyValueFormatter(koqPropertyFormatter),\n requestOptions.unitSystem ?? this.props.defaultUnitSystem,\n );\n await formatter.formatContent(content);\n }\n\n return this._localizationHelper.getLocalizedContent(content);\n }\n\n /**\n * Retrieves distinct values of specific field from the content based on the supplied content descriptor override.\n * @param requestOptions Options for the request\n * @return A promise object that returns either distinct values on success or an error string on error.\n * @public\n */\n public async getPagedDistinctValues(\n requestOptions: WithCancelEvent<Prioritized<DistinctValuesRequestOptions<IModelDb, Descriptor | DescriptorOverrides, KeySet, RulesetVariable>>> &\n BackendDiagnosticsAttribute,\n ): Promise<PagedResponse<DisplayValueGroup>> {\n const result = await this._detail.getPagedDistinctValues(requestOptions);\n return {\n ...result,\n items: result.items.map((g) => this._localizationHelper.getLocalizedDisplayValueGroup(g)),\n };\n }\n\n /**\n * Retrieves property data in a simplified format for a single element specified by ID.\n * @public\n */\n public async getElementProperties<TParsedContent = ElementProperties>(\n requestOptions: WithCancelEvent<Prioritized<SingleElementPropertiesRequestOptions<IModelDb, TParsedContent>>> & BackendDiagnosticsAttribute,\n ): Promise<TParsedContent | undefined>;\n /**\n * Retrieves property data in simplified format for multiple elements specified by class or all element.\n * @return An object that contains element count and AsyncGenerator to iterate over properties of those elements in batches of undefined size.\n * @public\n */\n public async getElementProperties<TParsedContent = ElementProperties>(\n requestOptions: WithCancelEvent<Prioritized<MultiElementPropertiesRequestOptions<IModelDb, TParsedContent>>> & BackendDiagnosticsAttribute,\n ): Promise<MultiElementPropertiesResponse<TParsedContent>>;\n public async getElementProperties<TParsedContent = ElementProperties>(\n requestOptions: WithCancelEvent<\n Prioritized<SingleElementPropertiesRequestOptions<IModelDb, TParsedContent> | MultiElementPropertiesRequestOptions<IModelDb, TParsedContent>>\n > &\n BackendDiagnosticsAttribute,\n ): Promise<TParsedContent | undefined | MultiElementPropertiesResponse<TParsedContent>> {\n if (isSingleElementPropertiesRequestOptions(requestOptions)) {\n return this.getSingleElementProperties<TParsedContent>(requestOptions);\n }\n return this.getMultipleElementProperties<TParsedContent>(requestOptions);\n }\n\n private async getSingleElementProperties<TParsedContent>(\n requestOptions: WithCancelEvent<Prioritized<SingleElementPropertiesRequestOptions<IModelDb, TParsedContent>>> & BackendDiagnosticsAttribute,\n ): Promise<TParsedContent | undefined> {\n type TParser = Required<typeof requestOptions>[\"contentParser\"];\n const { elementId, contentParser, ...optionsNoElementId } = requestOptions;\n const parser: TParser = contentParser ?? (buildElementProperties as TParser);\n const content = await this.getContent({\n ...optionsNoElementId,\n descriptor: {\n displayType: DefaultContentDisplayTypes.PropertyPane,\n contentFlags: ContentFlags.ShowLabels,\n },\n rulesetOrId: \"ElementProperties\",\n keys: new KeySet([{ className: \"BisCore:Element\", id: elementId }]),\n });\n if (!content || content.contentSet.length === 0) {\n return undefined;\n }\n return parser(content.descriptor, content.contentSet[0]);\n }\n\n private async getMultipleElementProperties<TParsedContent>(\n requestOptions: WithCancelEvent<Prioritized<MultiElementPropertiesRequestOptions<IModelDb, TParsedContent>>> & BackendDiagnosticsAttribute,\n ): Promise<MultiElementPropertiesResponse<TParsedContent>> {\n type TParser = Required<typeof requestOptions>[\"contentParser\"];\n const { elementClasses, contentParser, batchSize, ...contentOptions } = requestOptions;\n const parser: TParser = contentParser ?? (buildElementProperties as TParser);\n const workerThreadsCount = this._props.workerThreadsCount ?? 2;\n\n // We don't want to request content for all classes at once - each class results in a huge content descriptor object that's cached in memory\n // and can be shared across all batch requests for that class. Handling multiple classes at the same time not only increases memory footprint,\n // but also may push descriptors out of cache, requiring us to recreate them, thus making performance worse. For those reasons we handle at\n // most `workerThreadsCount / 2` classes in parallel.\n // istanbul ignore next\n const classParallelism = workerThreadsCount > 1 ? workerThreadsCount / 2 : 1;\n\n // We want all worker threads to be constantly busy. However, there's some fairly expensive work being done after the worker thread is done,\n // but before we receive the response. That means the worker thread would be starving if we sent only `workerThreadsCount` requests in parallel.\n // To avoid that, we keep twice as much requests active.\n // istanbul ignore next\n const batchesParallelism = workerThreadsCount > 0 ? workerThreadsCount * 2 : 2;\n\n const createClassContentRuleset = (fullClassName: string): Ruleset => {\n const [schemaName, className] = parseFullClassName(fullClassName);\n return {\n id: `content/${fullClassName}`,\n rules: [\n {\n ruleType: \"Content\",\n specifications: [\n {\n specType: \"ContentInstancesOfSpecificClasses\",\n classes: {\n schemaName,\n classNames: [className],\n arePolymorphic: false,\n },\n handlePropertiesPolymorphically: true,\n },\n ],\n },\n ],\n };\n };\n const getContentDescriptor = async (ruleset: Ruleset): Promise<Descriptor> => {\n return (await this.getContentDescriptor({\n ...contentOptions,\n rulesetOrId: ruleset,\n displayType: DefaultContentDisplayTypes.Grid,\n contentFlags: ContentFlags.ShowLabels,\n keys: new KeySet(),\n }))!;\n };\n\n const obs = getClassesWithInstances(requestOptions.imodel, elementClasses ?? /* istanbul ignore next */ [\"BisCore.Element\"]).pipe(\n map((classFullName) => ({\n classFullName,\n ruleset: createClassContentRuleset(classFullName),\n })),\n mergeMap(\n ({ classFullName, ruleset }) =>\n // use forkJoin to query descriptor and element ids in parallel\n forkJoin({\n classFullName: of(classFullName),\n ruleset: of(ruleset),\n descriptor: from(getContentDescriptor(ruleset)),\n batches: from(getBatchedClassElementIds(requestOptions.imodel, classFullName, batchSize ?? /* istanbul ignore next */ 1000)),\n }).pipe(\n // split incoming stream into individual batch requests\n mergeMap(({ descriptor, batches }) => from(batches.map((batch) => ({ classFullName, descriptor, batch })))),\n // request content for each batch, filter by IDs for performance\n mergeMap(({ descriptor, batch }) => {\n const filteringDescriptor = new Descriptor(descriptor);\n filteringDescriptor.instanceFilter = {\n selectClassName: classFullName,\n expression: `this.ECInstanceId >= ${Number.parseInt(batch.from, 16)} AND this.ECInstanceId <= ${Number.parseInt(batch.to, 16)}`,\n };\n return from(\n this.getContentSet({\n ...contentOptions,\n keys: new KeySet(),\n descriptor: filteringDescriptor,\n rulesetOrId: ruleset,\n }),\n ).pipe(map((items) => ({ classFullName, descriptor, items })));\n }, batchesParallelism),\n ),\n classParallelism,\n ),\n map(({ descriptor, items }) => items.map((item) => parser(descriptor, item))),\n );\n\n return {\n total: getElementsCount(requestOptions.imodel, elementClasses),\n async *iterator() {\n for await (const batch of eachValueFrom(obs)) {\n yield batch;\n }\n },\n };\n }\n\n /**\n * Retrieves display label definition of specific item\n * @public\n */\n public async getDisplayLabelDefinition(\n requestOptions: WithCancelEvent<Prioritized<DisplayLabelRequestOptions<IModelDb, InstanceKey>>> & BackendDiagnosticsAttribute,\n ): Promise<LabelDefinition> {\n const labelDefinition = await this._detail.getDisplayLabelDefinition(requestOptions);\n return this._localizationHelper.getLocalizedLabelDefinition(labelDefinition);\n }\n\n /**\n * Retrieves display label definitions of specific items\n * @public\n */\n public async getDisplayLabelDefinitions(\n requestOptions: WithCancelEvent<Prioritized<Paged<DisplayLabelsRequestOptions<IModelDb, InstanceKey>>>> & BackendDiagnosticsAttribute,\n ): Promise<LabelDefinition[]> {\n const labelDefinitions = await this._detail.getDisplayLabelDefinitions(requestOptions);\n return this._localizationHelper.getLocalizedLabelDefinitions(labelDefinitions);\n }\n\n /**\n * Retrieves available selection scopes.\n * @public\n */\n public async getSelectionScopes(_requestOptions: SelectionScopeRequestOptions<IModelDb> & BackendDiagnosticsAttribute): Promise<SelectionScope[]> {\n return SelectionScopesHelper.getSelectionScopes();\n }\n\n /**\n * Computes selection set based on provided selection scope.\n * @public\n * @deprecated in 3.x. Use overload with `ComputeSelectionRequestOptions` parameter.\n */\n public async computeSelection(\n requestOptions: SelectionScopeRequestOptions<IModelDb> & { ids: Id64String[]; scopeId: string } & BackendDiagnosticsAttribute,\n ): Promise<KeySet>;\n /**\n * Computes selection based on provided element IDs and selection scope.\n * @public\n */\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n public async computeSelection(requestOptions: ComputeSelectionRequestOptions<IModelDb> & BackendDiagnosticsAttribute): Promise<KeySet>;\n public async computeSelection(\n requestOptions: ((SelectionScopeRequestOptions<IModelDb> & { ids: Id64String[]; scopeId: string }) | ComputeSelectionRequestOptions<IModelDb>) &\n BackendDiagnosticsAttribute,\n ): Promise<KeySet> {\n return SelectionScopesHelper.computeSelection(\n isComputeSelectionRequestOptions(requestOptions)\n ? requestOptions\n : (function () {\n const { ids, scopeId, ...rest } = requestOptions;\n return { ...rest, elementIds: ids, scope: { id: scopeId } };\n })(),\n );\n }\n\n /**\n * Compares two hierarchies specified in the request options\n * @public\n */\n public async compareHierarchies(requestOptions: HierarchyCompareOptions<IModelDb, NodeKey>): Promise<HierarchyCompareInfo> {\n if (!requestOptions.prev.rulesetOrId && !requestOptions.prev.rulesetVariables) {\n return { changes: [] };\n }\n\n const { rulesetOrId, prev, rulesetVariables, ...options } = requestOptions;\n this._detail.registerRuleset(rulesetOrId);\n\n const currRulesetId = getRulesetIdObject(requestOptions.rulesetOrId);\n const prevRulesetId = prev.rulesetOrId ? getRulesetIdObject(prev.rulesetOrId) : currRulesetId;\n if (prevRulesetId.parts.id !== currRulesetId.parts.id) {\n throw new PresentationError(PresentationStatus.InvalidArgument, \"Can't compare rulesets with different IDs\");\n }\n\n const currRulesetVariables = rulesetVariables ?? [];\n const prevRulesetVariables = prev.rulesetVariables ?? currRulesetVariables;\n\n const params = {\n requestId: NativePlatformRequestTypes.CompareHierarchies,\n ...options,\n prevRulesetId: prevRulesetId.uniqueId,\n currRulesetId: currRulesetId.uniqueId,\n prevRulesetVariables: JSON.stringify(prevRulesetVariables),\n currRulesetVariables: JSON.stringify(currRulesetVariables),\n expandedNodeKeys: JSON.stringify(options.expandedNodeKeys ?? []),\n };\n\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n const reviver = (key: string, value: any) => (key === \"\" ? HierarchyCompareInfo.fromJSON(value) : value);\n return JSON.parse(await this._detail.request(params), reviver);\n }\n}\n"]}
1
+ {"version":3,"file":"PresentationManager.js","sourceRoot":"","sources":["../../../src/presentation-backend/PresentationManager.ts"],"names":[],"mappings":";AAAA;;;gGAGgG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AC,CAAC;IACjE,CAAC;CACF;AA1cD,kDA0cC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n * Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n * See LICENSE.md in the project root for license terms and full copyright notice.\n *--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module Core\n */\n\nimport { firstValueFrom } from \"rxjs\";\nimport { eachValueFrom } from \"rxjs-for-await\";\nimport { IModelDb } from \"@itwin/core-backend\";\nimport { Id64Array, Id64String } from \"@itwin/core-bentley\";\nimport { UnitSystemKey } from \"@itwin/core-quantity\";\nimport { SchemaContext } from \"@itwin/ecschema-metadata\";\nimport {\n buildElementProperties,\n UnitSystemFormat as CommonUnitSystemFormat,\n ComputeSelectionRequestOptions,\n Content,\n ContentDescriptorRequestOptions,\n ContentFlags,\n ContentFormatter,\n ContentPropertyValueFormatter,\n ContentRequestOptions,\n ContentSourcesRequestOptions,\n DefaultContentDisplayTypes,\n Descriptor,\n DescriptorOverrides,\n DisplayLabelRequestOptions,\n DisplayLabelsRequestOptions,\n DisplayValueGroup,\n DistinctValuesRequestOptions,\n ElementProperties,\n FilterByInstancePathsHierarchyRequestOptions,\n FilterByTextHierarchyRequestOptions,\n FormatsMap,\n HierarchyCompareInfo,\n HierarchyCompareOptions,\n HierarchyLevelDescriptorRequestOptions,\n HierarchyLevelJSON,\n HierarchyRequestOptions,\n InstanceKey,\n isComputeSelectionRequestOptions,\n isSingleElementPropertiesRequestOptions,\n Item,\n KeySet,\n KoqPropertyValueFormatter,\n LabelDefinition,\n LocalizationHelper,\n MultiElementPropertiesRequestOptions,\n Node,\n NodeKey,\n NodePathElement,\n Paged,\n PagedResponse,\n PresentationError,\n PresentationStatus,\n Prioritized,\n Ruleset,\n RulesetVariable,\n SelectClassInfo,\n SelectionScope,\n SelectionScopeRequestOptions,\n SingleElementPropertiesRequestOptions,\n WithCancelEvent,\n} from \"@itwin/presentation-common\";\nimport { getContentItemsObservableFromClassNames, getContentItemsObservableFromElementIds } from \"./ElementPropertiesHelper\";\nimport { NativePlatformDefinition, NativePlatformRequestTypes } from \"./NativePlatform\";\nimport { getRulesetIdObject, PresentationManagerDetail } from \"./PresentationManagerDetail\";\nimport { RulesetManager } from \"./RulesetManager\";\nimport { RulesetVariablesManager, RulesetVariablesManagerImpl } from \"./RulesetVariablesManager\";\nimport { SelectionScopesHelper } from \"./SelectionScopesHelper\";\nimport { BackendDiagnosticsAttribute, BackendDiagnosticsOptions, getLocalizedStringEN } from \"./Utils\";\n\n/**\n * Presentation manager working mode.\n * @public\n * @deprecated in 3.x. The attribute is not used by [[PresentationManager]] anymore\n */\nexport enum PresentationManagerMode {\n /**\n * Presentation manager assumes iModels are opened in read-only mode and avoids doing some work\n * related to reacting to changes in iModels.\n */\n ReadOnly,\n\n /**\n * Presentation manager assumes iModels are opened in read-write mode and it may need to\n * react to changes. This involves some additional work and gives slightly worse performance.\n */\n ReadWrite,\n}\n\n/**\n * Presentation hierarchy cache mode.\n * @public\n */\nexport enum HierarchyCacheMode {\n /**\n * Hierarchy cache is created in memory.\n */\n Memory = \"memory\",\n /**\n * Hierarchy cache is created on disk. In this mode hierarchy cache is persisted between iModel\n * openings.\n */\n Disk = \"disk\",\n /**\n * Hierarchy cache is created on disk. In this mode everything is cached in memory while creating hierarchy level\n * and persisted in disk cache when whole hierarchy level is created.\n *\n * **Note:** This mode is still experimental.\n */\n Hybrid = \"hybrid\",\n}\n\n/**\n * Configuration for hierarchy cache.\n * @public\n */\nexport type HierarchyCacheConfig = MemoryHierarchyCacheConfig | DiskHierarchyCacheConfig | HybridCacheConfig;\n\n/**\n * Base interface for all [[HierarchyCacheConfig]] implementations.\n * @public\n */\nexport interface HierarchyCacheConfigBase {\n mode: HierarchyCacheMode;\n}\n\n/**\n * Configuration for in-memory hierarchy cache.\n *\n * @see [Memory cache documentation page]($docs/presentation/advanced/Caching.md#memory-cache)\n * @public\n */\nexport interface MemoryHierarchyCacheConfig extends HierarchyCacheConfigBase {\n mode: HierarchyCacheMode.Memory;\n}\n\n/**\n * Configuration for persistent disk hierarchy cache.\n *\n * @see [Disk cache documentation page]($docs/presentation/advanced/Caching.md#disk-cache)\n * @public\n */\nexport interface DiskHierarchyCacheConfig extends HierarchyCacheConfigBase {\n mode: HierarchyCacheMode.Disk;\n\n /**\n * A directory for hierarchy caches. If set, the directory must exist. Relative paths start from `process.cwd()`.\n *\n * The default directory depends on the iModel and the way it's opened.\n */\n directory?: string;\n\n /**\n * While the cache itself is stored on a disk, there's still a required small in-memory cache.\n * The parameter allows controlling size of that cache. Defaults to `32768000` bytes (32 MB).\n */\n memoryCacheSize?: number;\n}\n\n/**\n * Configuration for the experimental hybrid hierarchy cache.\n *\n * Hybrid cache uses a combination of in-memory and disk caches, which should make it a better\n * alternative for cases when there are lots of simultaneous requests.\n *\n * @see [Hybrid cache documentation page]($docs/presentation/advanced/Caching.md#hybrid-cache)\n * @public\n */\nexport interface HybridCacheConfig extends HierarchyCacheConfigBase {\n mode: HierarchyCacheMode.Hybrid;\n\n /** Configuration for disk cache used to persist hierarchies. */\n disk?: DiskHierarchyCacheConfig;\n}\n\n/**\n * Configuration for content cache.\n *\n * @see [Content cache documentation page]($docs/presentation/advanced/Caching.md#content-cache)\n * @public\n */\nexport interface ContentCacheConfig {\n /**\n * Maximum number of content descriptors cached in memory for quicker paged content requests.\n *\n * Defaults to `100`.\n */\n size?: number;\n}\n\n/**\n * Caching configuration options for [[PresentationManager]].\n * @public\n */\nexport interface PresentationManagerCachingConfig {\n /**\n * Hierarchies-related caching options.\n *\n * @see [Hierarchies cache documentation page]($docs/presentation/advanced/Caching.md#hierarchies-cache)\n */\n hierarchies?: HierarchyCacheConfig;\n\n /**\n * Content-related caching options.\n *\n * @see [Content cache documentation page]($docs/presentation/advanced/Caching.md#content-cache)\n */\n content?: ContentCacheConfig;\n\n /**\n * Each worker thread (see [[workerThreadsCount]]) opens a connection to an iModel used for a request. This\n * means there could be `{workerThreadsCount} * {iModels count}` number of connections. Each connection\n * uses a memory cache to increase iModel read performance. This parameter allows controlling the size of that\n * cache. Defaults to `32768000` bytes (32 MB).\n *\n * @see [Worker connections cache documentation page]($docs/presentation/advanced/Caching.md#worker-connections-cache)\n */\n workerConnectionCacheSize?: number;\n}\n\n/**\n * A data structure that associates unit systems with a format. The associations are used for\n * assigning default unit formats for specific phenomenons (see [[PresentationManagerProps.defaultFormats]]).\n *\n * @public\n * @deprecated in 4.3. The type has been moved to `@itwin/presentation-common` package.\n */\nexport type UnitSystemFormat = CommonUnitSystemFormat;\n\n/**\n * Data structure for multiple element properties request response.\n * @public\n */\nexport interface MultiElementPropertiesResponse<TParsedContent = ElementProperties> {\n total: number;\n iterator: () => AsyncGenerator<TParsedContent[]>;\n}\n\n/**\n * Configuration options for supplying asset paths to [[PresentationManager]].\n * @public\n */\nexport interface PresentationAssetsRootConfig {\n /**\n * Path to `presentation-backend` assets. Relative paths start from `process.cwd()`.\n */\n backend: string;\n\n /**\n * Path to `presentation-common` assets.\n *\n * @deprecated in 3.x. This path is not used anymore\n */\n common: string;\n}\n\n/**\n * Properties that can be used to configure [[PresentationManager]]\n * @public\n */\nexport interface PresentationManagerProps {\n /**\n * Path overrides for presentation backend assets. Need to be overriden by application if it puts these assets someplace else than the default.\n *\n * By default the path to assets directory is determined during the call of [[Presentation.initialize]] using this algorithm:\n *\n * - if path of `.js` file that contains [[PresentationManager]] definition contains \"presentation-backend\", assume the package is in `node_modules` and the directory structure is:\n * - `assets/*\\*\\/*`\n * - `presentation-backend/{presentation-backend source files}`\n *\n * which means the assets can be found through a relative path `../assets/` from the JS file being executed.\n *\n * - else, assume the backend is webpacked into a single file with assets next to it:\n * - `assets/*\\*\\/*`\n * - `{source file being executed}.js`\n *\n * which means the assets can be found through a relative path `./assets/` from the `{source file being executed}`.\n *\n * @deprecated in 4.2. This attribute is not used anymore - the package is not using private assets anymore.\n */\n presentationAssetsRoot?: string | PresentationAssetsRootConfig;\n\n /**\n * A list of directories containing application's presentation rulesets. Relative\n * paths start from `process.cwd()`. The directories are traversed recursively.\n *\n * @note Only files with `.PresentationRuleSet.json` are read.\n */\n rulesetDirectories?: string[];\n\n /**\n * A list of directories containing application's supplemental presentation rulesets. Relative\n * paths start from `process.cwd()`. The directories are traversed recursively.\n *\n * @note Only files with `.PresentationRuleSet.json` are read.\n */\n supplementalRulesetDirectories?: string[];\n\n /**\n * A list of directories containing application's locale-specific localized\n * string files (in simplified i18next v3 format)\n *\n * @deprecated in 3.x. Use [[getLocalizedString]] to localize data returned by [[PresentationManager]].\n */\n localeDirectories?: string[];\n\n /**\n * Sets the active locale to use when localizing presentation-related\n * strings. It can later be changed through [[PresentationManager.activeLocale]].\n *\n * @deprecated in 3.x. Use [[getLocalizedString]] to localize data returned by [[PresentationManager]].\n */\n defaultLocale?: string;\n\n /**\n * Sets the active unit system to use for formatting property values with\n * units. Default presentation units are used if this is not specified. The active unit\n * system can later be changed through [[PresentationManager.activeUnitSystem]] or overriden for each request\n * through request options.\n */\n defaultUnitSystem?: UnitSystemKey;\n\n /**\n * A map of default unit formats to use for formatting properties that don't have a presentation format\n * in requested unit system.\n */\n defaultFormats?: FormatsMap;\n\n /**\n * Should schemas preloading be enabled. If true, presentation manager listens\n * for `BriefcaseDb.onOpened` event and force pre-loads all ECSchemas.\n *\n * @deprecated in 3.x. Use [[PresentationProps.enableSchemasPreload]] instead.\n */\n enableSchemasPreload?: boolean;\n\n /**\n * A number of worker threads to use for handling presentation requests. Defaults to `2`.\n */\n workerThreadsCount?: number;\n\n /**\n * Presentation manager working mode. Backends that use iModels in read-write mode should\n * use `ReadWrite`, others might want to set to `ReadOnly` for better performance.\n *\n * Defaults to [[PresentationManagerMode.ReadWrite]].\n *\n * @deprecated in 3.x. The attribute is not used by [[PresentationManager]] anymore\n */\n mode?: PresentationManagerMode; // eslint-disable-line @typescript-eslint/no-deprecated\n\n /**\n * The interval (in milliseconds) used to poll for presentation data changes. If not set, presentation\n * data changes are not tracked at all.\n *\n * @beta\n * @deprecated in 4.4. The manager now always tracks for iModel data changes without polling.\n */\n updatesPollInterval?: number;\n\n /** Options for caching. */\n caching?: PresentationManagerCachingConfig;\n\n /**\n * Use [SQLite's Memory-Mapped I/O](https://sqlite.org/mmap.html) for worker connections. This mode improves performance of handling\n * requests with high I/O intensity, e.g. filtering large tables on non-indexed columns. No downsides have been noticed.\n *\n * Set to a falsy value to turn off. `true` for memory-mapping the whole iModel. Number value for memory-mapping the specified amount of bytes.\n */\n useMmap?: boolean | number;\n\n /**\n * An identifier which helps separate multiple presentation managers. It's\n * mostly useful in tests where multiple presentation managers can co-exist\n * and try to share the same resources, which we don't want. With this identifier\n * set, managers put their resources into id-named subdirectories.\n *\n * @internal\n */\n id?: string;\n\n /** @internal */\n addon?: NativePlatformDefinition;\n\n /**\n * Localization function to localize data returned by presentation manager when it's used directly on the backend (as opposed to when used through RPC, where\n * data is localized on the frontend). Defaults to English localization.\n *\n * @see [Localization]($docs/presentation/advanced/Localization)\n */\n getLocalizedString?: (key: string) => string;\n\n /**\n * Callback that provides [SchemaContext]($ecschema-metadata) for supplied [IModelDb]($core-backend).\n * [SchemaContext]($ecschema-metadata) is used for getting metadata required for values formatting.\n */\n schemaContextProvider?: (imodel: IModelDb) => SchemaContext;\n\n /**\n * Parameters for gathering diagnostics at the manager level. When supplied, they're used with every request\n * made through the manager.\n *\n * @see [Diagnostics documentation page]($docs/presentation/advanced/Diagnostics.md)\n */\n diagnostics?: BackendDiagnosticsOptions;\n}\n\n/**\n * Backend Presentation manager which pulls the presentation data from\n * an iModel using native platform.\n *\n * @public\n */\nexport class PresentationManager {\n private _props: PresentationManagerProps;\n private _detail: PresentationManagerDetail;\n private _localizationHelper: LocalizationHelper;\n\n /**\n * Get / set active locale used for localizing presentation data\n * @deprecated in 3.x. Use [[PresentationManagerProps.getLocalizedString]] to localize data returned by [[PresentationManager]].\n */\n public activeLocale: string | undefined;\n\n /**\n * Creates an instance of PresentationManager.\n * @param props Optional configuration properties.\n */\n constructor(props?: PresentationManagerProps) {\n this._props = props ?? {};\n this._detail = new PresentationManagerDetail(this._props);\n this.activeLocale = this._props.defaultLocale; // eslint-disable-line @typescript-eslint/no-deprecated\n\n this._localizationHelper = new LocalizationHelper({ getLocalizedString: props?.getLocalizedString ?? getLocalizedStringEN });\n }\n\n /** Get / set active unit system used to format property values with units */\n public get activeUnitSystem(): UnitSystemKey | undefined {\n return this._detail.activeUnitSystem;\n }\n // istanbul ignore next\n public set activeUnitSystem(value: UnitSystemKey | undefined) {\n this._detail.activeUnitSystem = value;\n }\n\n /** Dispose the presentation manager. Must be called to clean up native resources. */\n public dispose() {\n this._detail.dispose();\n }\n\n /** @internal */\n public setOnManagerUsedHandler(handler: () => void) {\n this._detail.setOnManagerUsedHandler(handler);\n }\n\n /** Properties used to initialize the manager */\n public get props() {\n return this._props;\n }\n\n /** Get rulesets manager */\n public rulesets(): RulesetManager {\n return this._detail.rulesets;\n }\n\n /**\n * Get ruleset variables manager for specific ruleset\n * @param rulesetId Id of the ruleset to get variables manager for\n */\n public vars(rulesetId: string): RulesetVariablesManager {\n return new RulesetVariablesManagerImpl(this.getNativePlatform, rulesetId);\n }\n\n /** @internal */\n public getNativePlatform = (): NativePlatformDefinition => {\n return this._detail.getNativePlatform();\n };\n\n /** @internal */\n // istanbul ignore next\n public getDetail(): PresentationManagerDetail {\n return this._detail;\n }\n\n /** @internal */\n public getRulesetId(rulesetOrId: Ruleset | string) {\n return this._detail.getRulesetId(rulesetOrId);\n }\n\n /**\n * Retrieves nodes\n * @public\n */\n public async getNodes(\n requestOptions: WithCancelEvent<Prioritized<Paged<HierarchyRequestOptions<IModelDb, NodeKey, RulesetVariable>>>> & BackendDiagnosticsAttribute,\n ): Promise<Node[]> {\n const serializedNodesJson = await this._detail.getNodes(requestOptions);\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n const nodesJson = JSON.parse(serializedNodesJson) as HierarchyLevelJSON;\n const nodes = Node.listFromJSON(nodesJson.nodes);\n return this._localizationHelper.getLocalizedNodes(nodes);\n }\n\n /**\n * Retrieves nodes count\n * @public\n */\n public async getNodesCount(\n requestOptions: WithCancelEvent<Prioritized<HierarchyRequestOptions<IModelDb, NodeKey, RulesetVariable>>> & BackendDiagnosticsAttribute,\n ): Promise<number> {\n return this._detail.getNodesCount(requestOptions);\n }\n\n /**\n * Retrieves hierarchy level descriptor\n * @public\n */\n public async getNodesDescriptor(\n requestOptions: WithCancelEvent<Prioritized<HierarchyLevelDescriptorRequestOptions<IModelDb, NodeKey, RulesetVariable>>> & BackendDiagnosticsAttribute,\n ): Promise<Descriptor | undefined> {\n const response = await this._detail.getNodesDescriptor(requestOptions);\n const descriptor = Descriptor.fromJSON(JSON.parse(response));\n return descriptor ? this._localizationHelper.getLocalizedContentDescriptor(descriptor) : undefined;\n }\n\n /**\n * Retrieves paths from root nodes to children nodes according to specified instance key paths. Intersecting paths will be merged.\n * TODO: Return results in pages\n * @public\n */\n public async getNodePaths(\n requestOptions: WithCancelEvent<Prioritized<FilterByInstancePathsHierarchyRequestOptions<IModelDb, RulesetVariable>>> & BackendDiagnosticsAttribute,\n ): Promise<NodePathElement[]> {\n const result = await this._detail.getNodePaths(requestOptions);\n return result.map((npe) => this._localizationHelper.getLocalizedNodePathElement(npe));\n }\n\n /**\n * Retrieves paths from root nodes to nodes containing filter text in their label.\n * TODO: Return results in pages\n * @public\n */\n public async getFilteredNodePaths(\n requestOptions: WithCancelEvent<Prioritized<FilterByTextHierarchyRequestOptions<IModelDb, RulesetVariable>>> & BackendDiagnosticsAttribute,\n ): Promise<NodePathElement[]> {\n const result = await this._detail.getFilteredNodePaths(requestOptions);\n return result.map((npe) => this._localizationHelper.getLocalizedNodePathElement(npe));\n }\n\n /**\n * Get information about the sources of content when building it for specific ECClasses. Sources involve classes of the primary select instance,\n * its related instances for loading related and navigation properties.\n * @public\n */\n public async getContentSources(\n requestOptions: WithCancelEvent<Prioritized<ContentSourcesRequestOptions<IModelDb>>> & BackendDiagnosticsAttribute,\n ): Promise<SelectClassInfo[]> {\n return this._detail.getContentSources(requestOptions);\n }\n\n /**\n * Retrieves the content descriptor which can be used to get content\n * @public\n */\n public async getContentDescriptor(\n requestOptions: WithCancelEvent<Prioritized<ContentDescriptorRequestOptions<IModelDb, KeySet, RulesetVariable>>> & BackendDiagnosticsAttribute,\n ): Promise<Descriptor | undefined> {\n const response = await this._detail.getContentDescriptor(requestOptions);\n const descriptor = Descriptor.fromJSON(JSON.parse(response));\n return descriptor ? this._localizationHelper.getLocalizedContentDescriptor(descriptor) : undefined;\n }\n\n /**\n * Retrieves the content set size based on the supplied content descriptor override\n * @public\n */\n public async getContentSetSize(\n requestOptions: WithCancelEvent<Prioritized<ContentRequestOptions<IModelDb, Descriptor | DescriptorOverrides, KeySet, RulesetVariable>>> &\n BackendDiagnosticsAttribute,\n ): Promise<number> {\n return this._detail.getContentSetSize(requestOptions);\n }\n\n /**\n * Retrieves the content set based on the supplied content descriptor.\n * @public\n */\n public async getContentSet(\n requestOptions: WithCancelEvent<Prioritized<Paged<ContentRequestOptions<IModelDb, Descriptor, KeySet, RulesetVariable>>>> & BackendDiagnosticsAttribute,\n ): Promise<Item[]> {\n let items = await this._detail.getContentSet({\n ...requestOptions,\n ...(!requestOptions.omitFormattedValues && this.props.schemaContextProvider !== undefined ? { omitFormattedValues: true } : undefined),\n });\n\n if (!requestOptions.omitFormattedValues && this.props.schemaContextProvider !== undefined) {\n const koqPropertyFormatter = new KoqPropertyValueFormatter(this.props.schemaContextProvider(requestOptions.imodel), this.props.defaultFormats);\n const formatter = new ContentFormatter(\n new ContentPropertyValueFormatter(koqPropertyFormatter),\n requestOptions.unitSystem ?? this.props.defaultUnitSystem,\n );\n items = await formatter.formatContentItems(items, requestOptions.descriptor);\n }\n\n return this._localizationHelper.getLocalizedContentItems(items);\n }\n\n /**\n * Retrieves the content based on the supplied content descriptor override.\n * @public\n */\n public async getContent(\n requestOptions: WithCancelEvent<Prioritized<Paged<ContentRequestOptions<IModelDb, Descriptor | DescriptorOverrides, KeySet, RulesetVariable>>>> &\n BackendDiagnosticsAttribute,\n ): Promise<Content | undefined> {\n const content = await this._detail.getContent({\n ...requestOptions,\n ...(!requestOptions.omitFormattedValues && this.props.schemaContextProvider !== undefined ? { omitFormattedValues: true } : undefined),\n });\n\n if (!content) {\n return undefined;\n }\n\n if (!requestOptions.omitFormattedValues && this.props.schemaContextProvider !== undefined) {\n const koqPropertyFormatter = new KoqPropertyValueFormatter(this.props.schemaContextProvider(requestOptions.imodel), this.props.defaultFormats);\n const formatter = new ContentFormatter(\n new ContentPropertyValueFormatter(koqPropertyFormatter),\n requestOptions.unitSystem ?? this.props.defaultUnitSystem,\n );\n await formatter.formatContent(content);\n }\n\n return this._localizationHelper.getLocalizedContent(content);\n }\n\n /**\n * Retrieves distinct values of specific field from the content based on the supplied content descriptor override.\n * @param requestOptions Options for the request\n * @return A promise object that returns either distinct values on success or an error string on error.\n * @public\n */\n public async getPagedDistinctValues(\n requestOptions: WithCancelEvent<Prioritized<DistinctValuesRequestOptions<IModelDb, Descriptor | DescriptorOverrides, KeySet, RulesetVariable>>> &\n BackendDiagnosticsAttribute,\n ): Promise<PagedResponse<DisplayValueGroup>> {\n const result = await this._detail.getPagedDistinctValues(requestOptions);\n return {\n ...result,\n items: result.items.map((g) => this._localizationHelper.getLocalizedDisplayValueGroup(g)),\n };\n }\n\n /**\n * Retrieves property data in a simplified format for a single element specified by ID.\n * @public\n */\n public async getElementProperties<TParsedContent = ElementProperties>(\n requestOptions: WithCancelEvent<Prioritized<SingleElementPropertiesRequestOptions<IModelDb, TParsedContent>>> & BackendDiagnosticsAttribute,\n ): Promise<TParsedContent | undefined>;\n /**\n * Retrieves property data in simplified format for multiple elements specified by class or all element.\n * @return An object that contains element count and AsyncGenerator to iterate over properties of those elements in batches of undefined size.\n * @public\n */\n public async getElementProperties<TParsedContent = ElementProperties>(\n requestOptions: WithCancelEvent<Prioritized<MultiElementPropertiesRequestOptions<IModelDb, TParsedContent>>> & BackendDiagnosticsAttribute,\n ): Promise<MultiElementPropertiesResponse<TParsedContent>>;\n public async getElementProperties<TParsedContent = ElementProperties>(\n requestOptions: WithCancelEvent<\n Prioritized<SingleElementPropertiesRequestOptions<IModelDb, TParsedContent> | MultiElementPropertiesRequestOptions<IModelDb, TParsedContent>>\n > &\n BackendDiagnosticsAttribute,\n ): Promise<TParsedContent | undefined | MultiElementPropertiesResponse<TParsedContent>> {\n if (isSingleElementPropertiesRequestOptions(requestOptions)) {\n return this.getSingleElementProperties<TParsedContent>(requestOptions);\n }\n return this.getMultipleElementProperties<TParsedContent>(requestOptions);\n }\n\n private async getSingleElementProperties<TParsedContent>(\n requestOptions: WithCancelEvent<Prioritized<SingleElementPropertiesRequestOptions<IModelDb, TParsedContent>>> & BackendDiagnosticsAttribute,\n ): Promise<TParsedContent | undefined> {\n type TParser = Required<typeof requestOptions>[\"contentParser\"];\n const { elementId, contentParser, ...optionsNoElementId } = requestOptions;\n const parser: TParser = contentParser ?? (buildElementProperties as TParser);\n const content = await this.getContent({\n ...optionsNoElementId,\n descriptor: {\n displayType: DefaultContentDisplayTypes.PropertyPane,\n contentFlags: ContentFlags.ShowLabels,\n },\n rulesetOrId: \"ElementProperties\",\n keys: new KeySet([{ className: \"BisCore:Element\", id: elementId }]),\n });\n if (!content || content.contentSet.length === 0) {\n return undefined;\n }\n return parser(content.descriptor, content.contentSet[0]);\n }\n\n private async getMultipleElementProperties<TParsedContent>(\n requestOptions: WithCancelEvent<Prioritized<MultiElementPropertiesRequestOptions<IModelDb, TParsedContent>>> & BackendDiagnosticsAttribute,\n ): Promise<MultiElementPropertiesResponse<TParsedContent>> {\n type TParser = Required<typeof requestOptions>[\"contentParser\"];\n const { contentParser, batchSize: batchSizeOption, ...contentOptions } = requestOptions;\n\n const parser: TParser = contentParser ?? (buildElementProperties as TParser);\n const workerThreadsCount = this._props.workerThreadsCount ?? 2;\n\n // We don't want to request content for all classes at once - each class results in a huge content descriptor object that's cached in memory\n // and can be shared across all batch requests for that class. Handling multiple classes at the same time not only increases memory footprint,\n // but also may push descriptors out of cache, requiring us to recreate them, thus making performance worse. For those reasons we handle at\n // most `workerThreadsCount / 2` classes in parallel.\n // istanbul ignore next\n const classParallelism = workerThreadsCount > 1 ? Math.ceil(workerThreadsCount / 2) : 1;\n\n // We want all worker threads to be constantly busy. However, there's some fairly expensive work being done after the worker thread is done,\n // but before we receive the response. That means the worker thread would be starving if we sent only `workerThreadsCount` requests in parallel.\n // To avoid that, we keep twice as much requests active.\n // istanbul ignore next\n const batchesParallelism = workerThreadsCount > 0 ? workerThreadsCount : 1;\n\n // istanbul ignore next\n const batchSize = batchSizeOption ?? 100;\n\n const elementsIdentifier = ((): { elementIds: Id64Array } | { elementClasses: string[] } => {\n if (\"elementIds\" in contentOptions && contentOptions.elementIds !== undefined) {\n const elementIds = contentOptions.elementIds;\n delete contentOptions.elementIds;\n return { elementIds };\n }\n // istanbul ignore else\n if (\"elementClasses\" in contentOptions && contentOptions.elementClasses !== undefined) {\n const elementClasses = contentOptions.elementClasses;\n delete contentOptions.elementClasses;\n return { elementClasses };\n }\n // istanbul ignore next\n return { elementClasses: [\"BisCore:Element\"] };\n })();\n\n const descriptorGetter = async (partialProps: Pick<ContentDescriptorRequestOptions<IModelDb, KeySet, RulesetVariable>, \"rulesetOrId\" | \"keys\">) =>\n this.getContentDescriptor({ ...contentOptions, displayType: DefaultContentDisplayTypes.Grid, contentFlags: ContentFlags.ShowLabels, ...partialProps });\n const contentSetGetter = async (\n partialProps: Pick<ContentRequestOptions<IModelDb, Descriptor, KeySet, RulesetVariable>, \"rulesetOrId\" | \"keys\" | \"descriptor\">,\n ) => this.getContentSet({ ...contentOptions, ...partialProps });\n const { itemBatches, count } =\n \"elementIds\" in elementsIdentifier\n ? getContentItemsObservableFromElementIds(\n requestOptions.imodel,\n descriptorGetter,\n contentSetGetter,\n elementsIdentifier.elementIds,\n classParallelism,\n batchesParallelism,\n batchSize,\n )\n : getContentItemsObservableFromClassNames(\n requestOptions.imodel,\n descriptorGetter,\n contentSetGetter,\n elementsIdentifier.elementClasses,\n classParallelism,\n batchesParallelism,\n batchSize,\n );\n return {\n total: await firstValueFrom(count),\n async *iterator() {\n for await (const itemsBatch of eachValueFrom(itemBatches)) {\n const { descriptor, items } = itemsBatch;\n yield items.map((item) => parser(descriptor, item));\n }\n },\n };\n }\n\n /**\n * Retrieves display label definition of specific item\n * @public\n */\n public async getDisplayLabelDefinition(\n requestOptions: WithCancelEvent<Prioritized<DisplayLabelRequestOptions<IModelDb, InstanceKey>>> & BackendDiagnosticsAttribute,\n ): Promise<LabelDefinition> {\n const labelDefinition = await this._detail.getDisplayLabelDefinition(requestOptions);\n return this._localizationHelper.getLocalizedLabelDefinition(labelDefinition);\n }\n\n /**\n * Retrieves display label definitions of specific items\n * @public\n */\n public async getDisplayLabelDefinitions(\n requestOptions: WithCancelEvent<Prioritized<Paged<DisplayLabelsRequestOptions<IModelDb, InstanceKey>>>> & BackendDiagnosticsAttribute,\n ): Promise<LabelDefinition[]> {\n const labelDefinitions = await this._detail.getDisplayLabelDefinitions(requestOptions);\n return this._localizationHelper.getLocalizedLabelDefinitions(labelDefinitions);\n }\n\n /**\n * Retrieves available selection scopes.\n * @public\n */\n public async getSelectionScopes(_requestOptions: SelectionScopeRequestOptions<IModelDb> & BackendDiagnosticsAttribute): Promise<SelectionScope[]> {\n return SelectionScopesHelper.getSelectionScopes();\n }\n\n /**\n * Computes selection set based on provided selection scope.\n * @public\n * @deprecated in 3.x. Use overload with `ComputeSelectionRequestOptions` parameter.\n */\n public async computeSelection(\n requestOptions: SelectionScopeRequestOptions<IModelDb> & { ids: Id64String[]; scopeId: string } & BackendDiagnosticsAttribute,\n ): Promise<KeySet>;\n /**\n * Computes selection based on provided element IDs and selection scope.\n * @public\n */\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n public async computeSelection(requestOptions: ComputeSelectionRequestOptions<IModelDb> & BackendDiagnosticsAttribute): Promise<KeySet>;\n public async computeSelection(\n requestOptions: ((SelectionScopeRequestOptions<IModelDb> & { ids: Id64String[]; scopeId: string }) | ComputeSelectionRequestOptions<IModelDb>) &\n BackendDiagnosticsAttribute,\n ): Promise<KeySet> {\n return SelectionScopesHelper.computeSelection(\n isComputeSelectionRequestOptions(requestOptions)\n ? requestOptions\n : (function () {\n const { ids, scopeId, ...rest } = requestOptions;\n return { ...rest, elementIds: ids, scope: { id: scopeId } };\n })(),\n );\n }\n\n /**\n * Compares two hierarchies specified in the request options\n * @public\n */\n public async compareHierarchies(requestOptions: HierarchyCompareOptions<IModelDb, NodeKey>): Promise<HierarchyCompareInfo> {\n if (!requestOptions.prev.rulesetOrId && !requestOptions.prev.rulesetVariables) {\n return { changes: [] };\n }\n\n const { rulesetOrId, prev, rulesetVariables, ...options } = requestOptions;\n this._detail.registerRuleset(rulesetOrId);\n\n const currRulesetId = getRulesetIdObject(requestOptions.rulesetOrId);\n const prevRulesetId = prev.rulesetOrId ? getRulesetIdObject(prev.rulesetOrId) : currRulesetId;\n if (prevRulesetId.parts.id !== currRulesetId.parts.id) {\n throw new PresentationError(PresentationStatus.InvalidArgument, \"Can't compare rulesets with different IDs\");\n }\n\n const currRulesetVariables = rulesetVariables ?? [];\n const prevRulesetVariables = prev.rulesetVariables ?? currRulesetVariables;\n\n const params = {\n requestId: NativePlatformRequestTypes.CompareHierarchies,\n ...options,\n prevRulesetId: prevRulesetId.uniqueId,\n currRulesetId: currRulesetId.uniqueId,\n prevRulesetVariables: JSON.stringify(prevRulesetVariables),\n currRulesetVariables: JSON.stringify(currRulesetVariables),\n expandedNodeKeys: JSON.stringify(options.expandedNodeKeys ?? []),\n };\n\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n const reviver = (key: string, value: any) => (key === \"\" ? HierarchyCompareInfo.fromJSON(value) : value);\n return JSON.parse(await this._detail.request(params), reviver);\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@itwin/presentation-backend",
3
- "version": "5.0.0-dev.4",
3
+ "version": "5.0.0-dev.40",
4
4
  "description": "Backend of iTwin.js Presentation library",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -23,12 +23,12 @@
23
23
  "main": "lib/cjs/presentation-backend.js",
24
24
  "typings": "lib/cjs/presentation-backend",
25
25
  "peerDependencies": {
26
- "@itwin/core-backend": "^5.0.0-dev.4",
27
- "@itwin/core-bentley": "^5.0.0-dev.4",
28
- "@itwin/core-common": "^5.0.0-dev.4",
29
- "@itwin/core-quantity": "^5.0.0-dev.4",
30
- "@itwin/ecschema-metadata": "^5.0.0-dev.4",
31
- "@itwin/presentation-common": "^5.0.0-dev.4"
26
+ "@itwin/core-backend": "5.0.0-dev.40",
27
+ "@itwin/core-bentley": "5.0.0-dev.40",
28
+ "@itwin/core-common": "5.0.0-dev.40",
29
+ "@itwin/core-quantity": "5.0.0-dev.40",
30
+ "@itwin/ecschema-metadata": "5.0.0-dev.40",
31
+ "@itwin/presentation-common": "5.0.0-dev.40"
32
32
  },
33
33
  "devDependencies": {
34
34
  "@itwin/eslint-plugin": "5.0.0-dev.1",
@@ -41,7 +41,7 @@
41
41
  "@types/faker": "^4.1.0",
42
42
  "@types/lolex": "^2.1.2",
43
43
  "@types/mocha": "^10.0.6",
44
- "@types/node": "~18.16.20",
44
+ "@types/node": "~20.9.5",
45
45
  "@types/object-hash": "^1.3.0",
46
46
  "@types/semver": "7.3.10",
47
47
  "@types/sinon": "^17.0.2",
@@ -52,7 +52,7 @@
52
52
  "chai-jest-snapshot": "^2.0.0",
53
53
  "chai-subset": "1.6.0",
54
54
  "cpx2": "^3.0.0",
55
- "cross-env": "^5.1.4",
55
+ "cross-env": "^7.0.3",
56
56
  "deep-equal": "^1",
57
57
  "eslint": "^9.13.0",
58
58
  "eslint-config-prettier": "^9.1.0",
@@ -66,13 +66,13 @@
66
66
  "source-map-support": "^0.5.6",
67
67
  "typemoq": "^2.1.0",
68
68
  "typescript": "~5.6.2",
69
- "@itwin/build-tools": "5.0.0-dev.4",
70
- "@itwin/core-backend": "5.0.0-dev.4",
71
- "@itwin/core-bentley": "5.0.0-dev.4",
72
- "@itwin/core-common": "5.0.0-dev.4",
73
- "@itwin/core-quantity": "5.0.0-dev.4",
74
- "@itwin/ecschema-metadata": "5.0.0-dev.4",
75
- "@itwin/presentation-common": "5.0.0-dev.4"
69
+ "@itwin/build-tools": "5.0.0-dev.40",
70
+ "@itwin/core-backend": "5.0.0-dev.40",
71
+ "@itwin/core-bentley": "5.0.0-dev.40",
72
+ "@itwin/core-common": "5.0.0-dev.40",
73
+ "@itwin/core-quantity": "5.0.0-dev.40",
74
+ "@itwin/ecschema-metadata": "5.0.0-dev.40",
75
+ "@itwin/presentation-common": "5.0.0-dev.40"
76
76
  },
77
77
  "dependencies": {
78
78
  "object-hash": "^1.3.1",
@@ -91,7 +91,7 @@
91
91
  "cover": "nyc npm -s test",
92
92
  "docs": "npm run -s docs:reference && npm run -s extract && npm run -s docs:changelog",
93
93
  "docs:changelog": "cpx ./CHANGELOG.md ../../generated-docs/presentation/presentation-backend",
94
- "docs:reference": "betools docs --includes=../../generated-docs/extract --json=../../generated-docs/presentation/presentation-backend/file.json --tsIndexFile=presentation-backend.ts --onlyJson",
94
+ "docs:reference": "betools docs --json=../../generated-docs/presentation/presentation-backend/file.json --tsIndexFile=presentation-backend.ts --onlyJson",
95
95
  "extract": "betools extract --fileExt=ts --extractFrom=./src/test --recursive --out=../../generated-docs/extract",
96
96
  "extract-api": "betools extract-api --entry=presentation-backend",
97
97
  "lint": "eslint \"./src/**/*.ts\" 1>&2",