@itwin/imodel-transformer 0.1.14 → 0.1.15

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,12 +1,12 @@
1
1
  # Change Log - @itwin/imodel-transformer
2
2
 
3
- This log was last generated on Thu, 01 Jun 2023 22:51:28 GMT and should not be manually modified.
3
+ This log was last generated on Thu, 01 Jun 2023 22:51:33 GMT and should not be manually modified.
4
4
 
5
5
  <!-- Start content -->
6
6
 
7
7
  ## 0.1.14
8
8
 
9
- Thu, 01 Jun 2023 22:51:28 GMT
9
+ Thu, 01 Jun 2023 22:51:33 GMT
10
10
 
11
11
  ### Patches
12
12
 
@@ -163,6 +163,7 @@ class ECReferenceTypesCache {
163
163
  this._propQualifierToRefType.clear();
164
164
  }
165
165
  }
166
+ exports.ECReferenceTypesCache = ECReferenceTypesCache;
166
167
  ECReferenceTypesCache.bisRootClassToRefType = {
167
168
  /* eslint-disable quote-props, @typescript-eslint/naming-convention */
168
169
  "Element": core_common_1.ConcreteEntityTypes.Element,
@@ -174,5 +175,4 @@ ECReferenceTypesCache.bisRootClassToRefType = {
174
175
  // see [ConcreteEntityTypes]($common)
175
176
  /* eslint-enable quote-props, @typescript-eslint/naming-convention */
176
177
  };
177
- exports.ECReferenceTypesCache = ECReferenceTypesCache;
178
178
  //# sourceMappingURL=ECReferenceTypesCache.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ECReferenceTypesCache.js","sourceRoot":"","sources":["../../src/ECReferenceTypesCache.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,sDAA8D;AAC9D,oDAAmF;AACnF,gEAAyJ;AACzJ,iCAAiC;AAGjC;;GAEG;AACH,MAAa,mBAAoB,SAAQ,KAAK;IAC5C,gBAAuB,KAAK,CAAC,iDAAiD,CAAC,CAAC,CAAC,CAAC;CACnF;AAFD,kDAEC;AAED;;;;;;;GAOG;AACH,MAAa,q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ourcesContent":["/*---------------------------------------------------------------------------------------------\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 iModels\n */\n\nimport { DbResult, TupleKeyedMap } from \"@itwin/core-bentley\";\nimport { ConcreteEntityTypes, IModelError, RelTypeInfo } from \"@itwin/core-common\";\nimport { ECClass, Mixin, RelationshipClass, RelationshipConstraint, Schema, SchemaKey, SchemaLoader, StrengthDirection } from \"@itwin/ecschema-metadata\";\nimport * as assert from \"assert\";\nimport { IModelDb } from \"@itwin/core-backend\";\n\n/** The context for transforming a *source* Element to a *target* Element and remapping internal identifiers to the target iModel.\n * @internal\n */\nexport class SchemaNotInCacheErr extends Error {\n public constructor() { super(\"Schema was not in cache, initialize that schema\"); }\n}\n\n/**\n * A cache of the entity types referenced by navprops in ecchemas, as well as the source and target entity types of\n * The transformer needs the referenced type to determine how to resolve references.\n *\n * Using multiple of these usually performs redundant computation, for static schemas at least. A possible future optimization\n * would be to seed the computation from a global cache of non-dynamic schemas, but dynamic schemas can collide willy-nilly\n * @internal\n */\nexport class ECReferenceTypesCache {\n /** nesting based tuple map keyed by qualified property path tuple [schemaName, className, propName] */\n private _propQualifierToRefType = new TupleKeyedMap<[string, string, string], ConcreteEntityTypes>();\n private _relClassNameEndToRefTypes = new TupleKeyedMap<[string, string], RelTypeInfo>();\n private _initedSchemas = new Map<string, SchemaKey>();\n\n private static bisRootClassToRefType: Record<string, ConcreteEntityTypes | undefined> = {\n /* eslint-disable quote-props, @typescript-eslint/naming-convention */\n \"Element\": ConcreteEntityTypes.Element,\n \"Model\": ConcreteEntityTypes.Model,\n \"ElementAspect\": ConcreteEntityTypes.ElementAspect,\n \"ElementRefersToElements\": ConcreteEntityTypes.Relationship,\n \"ElementDrivesElement\": ConcreteEntityTypes.Relationship,\n // code spec is technically a potential root class but it is ignored currently\n // see [ConcreteEntityTypes]($common)\n /* eslint-enable quote-props, @typescript-eslint/naming-convention */\n };\n\n private async getRootBisClass(ecclass: ECClass) {\n let bisRootForConstraint: ECClass = ecclass;\n await ecclass.traverseBaseClasses((baseClass) => {\n // The depth first traversal will descend all the way to the root class before making any lateral traversal\n // of mixin hierarchies, (or if the constraint is a mixin, it will traverse to the root of the mixin hierarchy)\n // Once we see that we've moved laterally, we can terminate early\n const isFirstTest = bisRootForConstraint === ecclass;\n const traversalSwitchedRootPath = baseClass.name !== bisRootForConstraint.baseClass?.name;\n const stillTraversingRootPath = isFirstTest || !traversalSwitchedRootPath;\n if (!stillTraversingRootPath)\n return true; // stop traversal early\n bisRootForConstraint = baseClass;\n return false;\n });\n // if the root class of the constraint was a mixin, use its AppliesToEntityClass\n if (bisRootForConstraint instanceof Mixin) {\n assert(bisRootForConstraint.appliesTo !== undefined, \"The referenced AppliesToEntityClass could not be found, how did it pass schema validation?\");\n bisRootForConstraint = await this.getRootBisClass(await bisRootForConstraint.appliesTo);\n }\n return bisRootForConstraint;\n }\n\n private async getAbstractConstraintClass(constraint: RelationshipConstraint): Promise<ECClass> {\n // constraint classes must share a base so we can get the root from any of them, just use the first\n const ecclass = await (constraint.constraintClasses?.[0] || constraint.abstractConstraint);\n assert(ecclass !== undefined, \"At least one constraint class or an abstract constraint must have been defined, the constraint is not valid\");\n return ecclass;\n }\n\n /** initialize from an imodel with metadata */\n public async initAllSchemasInIModel(imodel: IModelDb): Promise<void> {\n const schemaLoader = new SchemaLoader((name: string) => imodel.getSchemaProps(name));\n await imodel.withPreparedStatement(`\n WITH RECURSIVE refs(SchemaId) AS (\n SELECT ECInstanceId FROM ECDbMeta.ECSchemaDef WHERE Name='BisCore'\n UNION ALL\n SELECT sr.SourceECInstanceId\n FROM ECDbMeta.SchemaHasSchemaReferences sr\n JOIN refs ON sr.TargetECInstanceId = refs.SchemaId\n )\n SELECT s.Name\n FROM refs\n JOIN ECDbMeta.ECSchemaDef s ON refs.SchemaId=s.ECInstanceId\n -- ensure schema dependency order\n ORDER BY ECInstanceId\n `, async (stmt) => {\n let status: DbResult;\n while ((status = stmt.step()) === DbResult.BE_SQLITE_ROW) {\n const schemaName = stmt.getValue(0).getString();\n const schema = schemaLoader.getSchema(schemaName);\n await this.considerInitSchema(schema);\n }\n if (status !== DbResult.BE_SQLITE_DONE)\n throw new IModelError(status, \"unexpected query failure\");\n });\n }\n\n private async considerInitSchema(schema: Schema): Promise<void> {\n if (this._initedSchemas.has(schema.name)) {\n const cachedSchemaKey = this._initedSchemas.get(schema.name);\n assert(cachedSchemaKey !== undefined);\n const incomingSchemaIsEqualOrOlder = schema.schemaKey.compareByVersion(cachedSchemaKey) <= 0;\n if (incomingSchemaIsEqualOrOlder) {\n return;\n }\n }\n return this.initSchema(schema);\n }\n\n private async initSchema(schema: Schema): Promise<void> {\n for (const ecclass of schema.getClasses()) {\n for (const prop of await ecclass.getProperties()) {\n if (!prop.isNavigation())\n continue;\n const relClass = await prop.relationshipClass;\n const relInfo = await this.relInfoFromRelClass(relClass);\n if (relInfo === undefined)\n continue;\n const navPropRefType = prop.direction === StrengthDirection.Forward ? relInfo.target : relInfo.source;\n this._propQualifierToRefType.set([schema.name.toLowerCase(), ecclass.name.toLowerCase(), prop.name.toLowerCase()], navPropRefType);\n }\n\n if (ecclass instanceof RelationshipClass) {\n const relInfo = await this.relInfoFromRelClass(ecclass);\n if (relInfo)\n this._relClassNameEndToRefTypes.set([schema.name.toLowerCase(), ecclass.name.toLowerCase()], relInfo);\n }\n }\n\n this._initedSchemas.set(schema.name, schema.schemaKey);\n }\n\n private async relInfoFromRelClass(ecclass: RelationshipClass): Promise<RelTypeInfo | undefined> {\n assert(ecclass.source.constraintClasses !== undefined);\n assert(ecclass.target.constraintClasses !== undefined);\n const [[sourceClass, sourceRootBisClass], [targetClass, targetRootBisClass]] = await Promise.all([\n this.getAbstractConstraintClass(ecclass.source)\n .then(async (constraintClass) => [constraintClass, await this.getRootBisClass(constraintClass)]),\n this.getAbstractConstraintClass(ecclass.target)\n .then(async (constraintClass) => [constraintClass, await this.getRootBisClass(constraintClass)]),\n ]);\n\n if (sourceRootBisClass.name === \"CodeSpec\" || targetRootBisClass.name === \"CodeSpec\")\n return undefined;\n const sourceType = ECReferenceTypesCache.bisRootClassToRefType[sourceRootBisClass.name];\n const targetType = ECReferenceTypesCache.bisRootClassToRefType[targetRootBisClass.name];\n const makeAssertMsg = (root: ECClass, cls: ECClass) => [\n `An unknown root class '${root.fullName}' was encountered while populating`,\n `the nav prop reference type cache for ${cls.fullName}.`,\n \"This is a bug.\",\n ].join(\"\\n\");\n assert(sourceType !== undefined, makeAssertMsg(sourceRootBisClass, sourceClass));\n assert(targetType !== undefined, makeAssertMsg(targetRootBisClass, targetClass));\n return { source: sourceType, target: targetType };\n }\n\n public getNavPropRefType(schemaName: string, className: string, propName: string): undefined | ConcreteEntityTypes {\n if (!this._initedSchemas.has(schemaName))\n throw new SchemaNotInCacheErr();\n return this._propQualifierToRefType.get([\n schemaName.toLowerCase(),\n className.toLowerCase(),\n propName.toLowerCase(),\n ]);\n }\n\n public getRelationshipEndType(schemaName: string, className: string): undefined | RelTypeInfo {\n if (!this._initedSchemas.has(schemaName))\n throw new SchemaNotInCacheErr();\n return this._relClassNameEndToRefTypes.get([\n schemaName.toLowerCase(),\n className.toLowerCase(),\n ]);\n }\n\n public clear() {\n this._initedSchemas.clear();\n this._propQualifierToRefType.clear();\n }\n}\n"]}
1
+ {"version":3,"file":"ECReferenceTypesCache.js","sourceRoot":"","sources":["../../src/ECReferenceTypesCache.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,sDAA8D;AAC9D,oDAAmF;AACnF,gEAAyJ;AACzJ,iCAAiC;AAGjC;;GAEG;AACH,MAAa,mBAAoB,SAAQ,KAAK;IAC5C,gBAAuB,KAAK,CAAC,iDAAiD,CAAC,CAAC,CAAC,CAAC;CACnF;AAFD,kDAEC;AAED;;;;;;;GAOG;AACH,MAAa,qBAAqB;IAAlC;QACE,uGAAuG;QAC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S,EAAE,aAAa,CAAC,kBAAkB,EAAE,WAAW,CAAC,CAAC,CAAC;QACjF,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;IACpD,CAAC;IAEM,iBAAiB,CAAC,UAAkB,EAAE,SAAiB,EAAE,QAAgB;QAC9E,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,UAAU,CAAC;YACtC,MAAM,IAAI,mBAAmB,EAAE,CAAC;QAClC,OAAO,IAAI,CAAC,uBAAuB,CAAC,GAAG,CAAC;YACtC,UAAU,CAAC,WAAW,EAAE;YACxB,SAAS,CAAC,WAAW,EAAE;YACvB,QAAQ,CAAC,WAAW,EAAE;SACvB,CAAC,CAAC;IACL,CAAC;IAEM,sBAAsB,CAAC,UAAkB,EAAE,SAAiB;QACjE,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,UAAU,CAAC;YACtC,MAAM,IAAI,mBAAmB,EAAE,CAAC;QAClC,OAAO,IAAI,CAAC,0BAA0B,CAAC,GAAG,CAAC;YACzC,UAAU,CAAC,WAAW,EAAE;YACxB,SAAS,CAAC,WAAW,EAAE;SACxB,CAAC,CAAC;IACL,CAAC;IAEM,KAAK;QACV,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAC;QAC5B,IAAI,CAAC,uBAAuB,CAAC,KAAK,EAAE,CAAC;IACvC,CAAC;;AA5JH,sDA6JC;AAvJgB,2CAAqB,GAAoD;IACtF,sEAAsE;IACtE,SAAS,EAAE,iCAAmB,CAAC,OAAO;IACtC,OAAO,EAAE,iCAAmB,CAAC,KAAK;IAClC,eAAe,EAAE,iCAAmB,CAAC,aAAa;IAClD,yBAAyB,EAAE,iCAAmB,CAAC,YAAY;IAC3D,sBAAsB,EAAE,iCAAmB,CAAC,YAAY;IACxD,8EAA8E;IAC9E,qCAAqC;IACrC,qEAAqE;CACtE,AAVmC,CAUlC","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 iModels\n */\n\nimport { DbResult, TupleKeyedMap } from \"@itwin/core-bentley\";\nimport { ConcreteEntityTypes, IModelError, RelTypeInfo } from \"@itwin/core-common\";\nimport { ECClass, Mixin, RelationshipClass, RelationshipConstraint, Schema, SchemaKey, SchemaLoader, StrengthDirection } from \"@itwin/ecschema-metadata\";\nimport * as assert from \"assert\";\nimport { IModelDb } from \"@itwin/core-backend\";\n\n/** The context for transforming a *source* Element to a *target* Element and remapping internal identifiers to the target iModel.\n * @internal\n */\nexport class SchemaNotInCacheErr extends Error {\n public constructor() { super(\"Schema was not in cache, initialize that schema\"); }\n}\n\n/**\n * A cache of the entity types referenced by navprops in ecchemas, as well as the source and target entity types of\n * The transformer needs the referenced type to determine how to resolve references.\n *\n * Using multiple of these usually performs redundant computation, for static schemas at least. A possible future optimization\n * would be to seed the computation from a global cache of non-dynamic schemas, but dynamic schemas can collide willy-nilly\n * @internal\n */\nexport class ECReferenceTypesCache {\n /** nesting based tuple map keyed by qualified property path tuple [schemaName, className, propName] */\n private _propQualifierToRefType = new TupleKeyedMap<[string, string, string], ConcreteEntityTypes>();\n private _relClassNameEndToRefTypes = new TupleKeyedMap<[string, string], RelTypeInfo>();\n private _initedSchemas = new Map<string, SchemaKey>();\n\n private static bisRootClassToRefType: Record<string, ConcreteEntityTypes | undefined> = {\n /* eslint-disable quote-props, @typescript-eslint/naming-convention */\n \"Element\": ConcreteEntityTypes.Element,\n \"Model\": ConcreteEntityTypes.Model,\n \"ElementAspect\": ConcreteEntityTypes.ElementAspect,\n \"ElementRefersToElements\": ConcreteEntityTypes.Relationship,\n \"ElementDrivesElement\": ConcreteEntityTypes.Relationship,\n // code spec is technically a potential root class but it is ignored currently\n // see [ConcreteEntityTypes]($common)\n /* eslint-enable quote-props, @typescript-eslint/naming-convention */\n };\n\n private async getRootBisClass(ecclass: ECClass) {\n let bisRootForConstraint: ECClass = ecclass;\n await ecclass.traverseBaseClasses((baseClass) => {\n // The depth first traversal will descend all the way to the root class before making any lateral traversal\n // of mixin hierarchies, (or if the constraint is a mixin, it will traverse to the root of the mixin hierarchy)\n // Once we see that we've moved laterally, we can terminate early\n const isFirstTest = bisRootForConstraint === ecclass;\n const traversalSwitchedRootPath = baseClass.name !== bisRootForConstraint.baseClass?.name;\n const stillTraversingRootPath = isFirstTest || !traversalSwitchedRootPath;\n if (!stillTraversingRootPath)\n return true; // stop traversal early\n bisRootForConstraint = baseClass;\n return false;\n });\n // if the root class of the constraint was a mixin, use its AppliesToEntityClass\n if (bisRootForConstraint instanceof Mixin) {\n assert(bisRootForConstraint.appliesTo !== undefined, \"The referenced AppliesToEntityClass could not be found, how did it pass schema validation?\");\n bisRootForConstraint = await this.getRootBisClass(await bisRootForConstraint.appliesTo);\n }\n return bisRootForConstraint;\n }\n\n private async getAbstractConstraintClass(constraint: RelationshipConstraint): Promise<ECClass> {\n // constraint classes must share a base so we can get the root from any of them, just use the first\n const ecclass = await (constraint.constraintClasses?.[0] || constraint.abstractConstraint);\n assert(ecclass !== undefined, \"At least one constraint class or an abstract constraint must have been defined, the constraint is not valid\");\n return ecclass;\n }\n\n /** initialize from an imodel with metadata */\n public async initAllSchemasInIModel(imodel: IModelDb): Promise<void> {\n const schemaLoader = new SchemaLoader((name: string) => imodel.getSchemaProps(name));\n await imodel.withPreparedStatement(`\n WITH RECURSIVE refs(SchemaId) AS (\n SELECT ECInstanceId FROM ECDbMeta.ECSchemaDef WHERE Name='BisCore'\n UNION ALL\n SELECT sr.SourceECInstanceId\n FROM ECDbMeta.SchemaHasSchemaReferences sr\n JOIN refs ON sr.TargetECInstanceId = refs.SchemaId\n )\n SELECT s.Name\n FROM refs\n JOIN ECDbMeta.ECSchemaDef s ON refs.SchemaId=s.ECInstanceId\n -- ensure schema dependency order\n ORDER BY ECInstanceId\n `, async (stmt) => {\n let status: DbResult;\n while ((status = stmt.step()) === DbResult.BE_SQLITE_ROW) {\n const schemaName = stmt.getValue(0).getString();\n const schema = schemaLoader.getSchema(schemaName);\n await this.considerInitSchema(schema);\n }\n if (status !== DbResult.BE_SQLITE_DONE)\n throw new IModelError(status, \"unexpected query failure\");\n });\n }\n\n private async considerInitSchema(schema: Schema): Promise<void> {\n if (this._initedSchemas.has(schema.name)) {\n const cachedSchemaKey = this._initedSchemas.get(schema.name);\n assert(cachedSchemaKey !== undefined);\n const incomingSchemaIsEqualOrOlder = schema.schemaKey.compareByVersion(cachedSchemaKey) <= 0;\n if (incomingSchemaIsEqualOrOlder) {\n return;\n }\n }\n return this.initSchema(schema);\n }\n\n private async initSchema(schema: Schema): Promise<void> {\n for (const ecclass of schema.getClasses()) {\n for (const prop of await ecclass.getProperties()) {\n if (!prop.isNavigation())\n continue;\n const relClass = await prop.relationshipClass;\n const relInfo = await this.relInfoFromRelClass(relClass);\n if (relInfo === undefined)\n continue;\n const navPropRefType = prop.direction === StrengthDirection.Forward ? relInfo.target : relInfo.source;\n this._propQualifierToRefType.set([schema.name.toLowerCase(), ecclass.name.toLowerCase(), prop.name.toLowerCase()], navPropRefType);\n }\n\n if (ecclass instanceof RelationshipClass) {\n const relInfo = await this.relInfoFromRelClass(ecclass);\n if (relInfo)\n this._relClassNameEndToRefTypes.set([schema.name.toLowerCase(), ecclass.name.toLowerCase()], relInfo);\n }\n }\n\n this._initedSchemas.set(schema.name, schema.schemaKey);\n }\n\n private async relInfoFromRelClass(ecclass: RelationshipClass): Promise<RelTypeInfo | undefined> {\n assert(ecclass.source.constraintClasses !== undefined);\n assert(ecclass.target.constraintClasses !== undefined);\n const [[sourceClass, sourceRootBisClass], [targetClass, targetRootBisClass]] = await Promise.all([\n this.getAbstractConstraintClass(ecclass.source)\n .then(async (constraintClass) => [constraintClass, await this.getRootBisClass(constraintClass)]),\n this.getAbstractConstraintClass(ecclass.target)\n .then(async (constraintClass) => [constraintClass, await this.getRootBisClass(constraintClass)]),\n ]);\n\n if (sourceRootBisClass.name === \"CodeSpec\" || targetRootBisClass.name === \"CodeSpec\")\n return undefined;\n const sourceType = ECReferenceTypesCache.bisRootClassToRefType[sourceRootBisClass.name];\n const targetType = ECReferenceTypesCache.bisRootClassToRefType[targetRootBisClass.name];\n const makeAssertMsg = (root: ECClass, cls: ECClass) => [\n `An unknown root class '${root.fullName}' was encountered while populating`,\n `the nav prop reference type cache for ${cls.fullName}.`,\n \"This is a bug.\",\n ].join(\"\\n\");\n assert(sourceType !== undefined, makeAssertMsg(sourceRootBisClass, sourceClass));\n assert(targetType !== undefined, makeAssertMsg(targetRootBisClass, targetClass));\n return { source: sourceType, target: targetType };\n }\n\n public getNavPropRefType(schemaName: string, className: string, propName: string): undefined | ConcreteEntityTypes {\n if (!this._initedSchemas.has(schemaName))\n throw new SchemaNotInCacheErr();\n return this._propQualifierToRefType.get([\n schemaName.toLowerCase(),\n className.toLowerCase(),\n propName.toLowerCase(),\n ]);\n }\n\n public getRelationshipEndType(schemaName: string, className: string): undefined | RelTypeInfo {\n if (!this._initedSchemas.has(schemaName))\n throw new SchemaNotInCacheErr();\n return this._relClassNameEndToRefTypes.get([\n schemaName.toLowerCase(),\n className.toLowerCase(),\n ]);\n }\n\n public clear() {\n this._initedSchemas.clear();\n this._propQualifierToRefType.clear();\n }\n}\n"]}
@@ -74,5 +74,5 @@ var EntityUnifier;
74
74
  }
75
75
  }
76
76
  EntityUnifier.exists = exists;
77
- })(EntityUnifier = exports.EntityUnifier || (exports.EntityUnifier = {}));
77
+ })(EntityUnifier || (exports.EntityUnifier = EntityUnifier = {}));
78
78
  //# sourceMappingURL=EntityUnifier.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"EntityUnifier.js","sourceRoot":"","sources":["../../src/EntityUnifier.ts"],"names":[],"mappings":";;;AAAA;;;+FAG+F;AAC/F;;;;GAIG;AACH,iCAAiC;AACjC,oDAAkG;AAClG,sDAA4I;AAC5I,sDAA2C;AAE3C,gBAAgB;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AAb,qBAAa,QA0D7B","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 Utils\n * utilities that unify operations, especially CRUD operations, on entities\n * for entity-generic operations in the transformer\n */\nimport * as assert from \"assert\";\nimport { ConcreteEntityTypes, DbResult, EntityReference, IModelError } from \"@itwin/core-common\";\nimport { ConcreteEntity, ConcreteEntityProps, Element, ElementAspect, EntityReferences, IModelDb, Relationship } from \"@itwin/core-backend\";\nimport { Id64 } from \"@itwin/core-bentley\";\n\n/** @internal */\nexport namespace EntityUnifier {\n export function getReadableType(entity: ConcreteEntity) {\n if (entity instanceof Element)\n return \"element\";\n else if (entity instanceof ElementAspect)\n return \"element aspect\";\n else if (entity instanceof Relationship)\n return \"relationship\";\n else\n return \"unknown entity type\";\n }\n\n type EntityUpdater = (entityProps: ConcreteEntityProps) => void;\n\n /** needs to return a widened type otherwise typescript complains when result is used with a narrow type */\n export function updaterFor(db: IModelDb, entity: ConcreteEntity) {\n if (entity instanceof Element)\n return db.elements.updateElement.bind(db.elements) as EntityUpdater;\n else if (entity instanceof Relationship)\n return db.relationships.updateInstance.bind(db.relationships) as EntityUpdater;\n else if (entity instanceof ElementAspect)\n return db.elements.updateAspect.bind(db.elements) as EntityUpdater;\n else\n assert(false, `unreachable; entity was '${entity.constructor.name}' not an Element, Relationship, or ElementAspect`);\n }\n\n export function exists(db: IModelDb, arg: { entity: ConcreteEntity } | { entityReference: EntityReference }) {\n if (\"entityReference\" in arg) {\n const [type, id] = EntityReferences.split(arg.entityReference);\n // FIXME: add a test with a deleted reference that triggers this\n if (id === undefined || Id64.isInvalid(id))\n return false;\n const bisCoreRootClassName = ConcreteEntityTypes.toBisCoreRootClassFullName(type);\n return db.withPreparedStatement(`SELECT 1 FROM ${bisCoreRootClassName} WHERE ECInstanceId=?`, (stmt) => {\n stmt.bindId(1, id);\n const matchesResult = stmt.step();\n if (matchesResult === DbResult.BE_SQLITE_ROW)\n return true;\n if (matchesResult === DbResult.BE_SQLITE_DONE)\n return false;\n else\n throw new IModelError(matchesResult, \"query failed\");\n });\n } else {\n if (arg.entity.id === undefined || Id64.isInvalid(arg.entity.id))\n return false;\n return db.withPreparedStatement(`SELECT 1 FROM [${arg.entity.schemaName}].[${arg.entity.className}] WHERE ECInstanceId=?`, (stmt) => {\n stmt.bindId(1, arg.entity.id);\n const matchesResult = stmt.step();\n if (matchesResult === DbResult.BE_SQLITE_ROW)\n return true;\n if (matchesResult === DbResult.BE_SQLITE_DONE)\n return false;\n else\n throw new IModelError(matchesResult, \"query failed\");\n });\n }\n }\n}\n"]}
1
+ {"version":3,"file":"EntityUnifier.js","sourceRoot":"","sources":["../../src/EntityUnifier.ts"],"names":[],"mappings":";;;AAAA;;;+FAG+F;AAC/F;;;;GAIG;AACH,iCAAiC;AACjC,oDAAkG;AAClG,sDAA4I;AAC5I,sDAA2C;AAE3C,gBAAgB;AAChB,IAAiB,aAAa,CA0D7B;AA1DD,WAAiB,aAAa;IAC5B,SAAgB,eAAe,CAAC,MAAsB;QACpD,IAAI,MAAM,YAAY,sBAAO;YAC3B,OAAO,SAAS,CAAC;aACd,IAAI,MAAM,YAAY,4BAAa;YACtC,OAAO,gBAAgB,CAAC;aACrB,IAAI,MAAM,YAAY,2BAAY;YACrC,OAAO,cAAc,CAAC;;YAEtB,OAAO,qBAAqB,CAAC;IACjC,CAAC;IATe,6BAAe,kBAS9B,CAAA;IAID,2GAA2G;IAC3G,SAAgB,UAAU,CAAC,EAAY,EAAE,MAAsB;QAC7D,IAAI,MAAM,YAAY,sBAAO;YAC3B,OAAO,EAAE,CAAC,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC,QAAQ,CAAkB,CAAC;aACjE,IAAI,MAAM,YAAY,2BAAY;YACrC,OAAO,EAAE,CAAC,aAAa,CAAC,cAAc,CAAC,IAAI,CA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AAC;gBAC9D,OAAO,KAAK,CAAC;YACf,OAAO,EAAE,CAAC,qBAAqB,CAAC,kBAAkB,GAAG,CAAC,MAAM,CAAC,UAAU,MAAM,GAAG,CAAC,MAAM,CAAC,SAAS,wBAAwB,EAAE,CAAC,IAAI,EAAE,EAAE;gBAClI,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBAC9B,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;gBAClC,IAAI,aAAa,KAAK,sBAAQ,CAAC,aAAa;oBAC1C,OAAO,IAAI,CAAC;gBACd,IAAI,aAAa,KAAK,sBAAQ,CAAC,cAAc;oBAC3C,OAAO,KAAK,CAAC;;oBAEb,MAAM,IAAI,yBAAW,CAAC,aAAa,EAAE,cAAc,CAAC,CAAC;YACzD,CAAC,CAAC,CAAC;SACJ;IACH,CAAC;IA/Be,oBAAM,SA+BrB,CAAA;AACH,CAAC,EA1DgB,aAAa,6BAAb,aAAa,QA0D7B","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 Utils\n * utilities that unify operations, especially CRUD operations, on entities\n * for entity-generic operations in the transformer\n */\nimport * as assert from \"assert\";\nimport { ConcreteEntityTypes, DbResult, EntityReference, IModelError } from \"@itwin/core-common\";\nimport { ConcreteEntity, ConcreteEntityProps, Element, ElementAspect, EntityReferences, IModelDb, Relationship } from \"@itwin/core-backend\";\nimport { Id64 } from \"@itwin/core-bentley\";\n\n/** @internal */\nexport namespace EntityUnifier {\n export function getReadableType(entity: ConcreteEntity) {\n if (entity instanceof Element)\n return \"element\";\n else if (entity instanceof ElementAspect)\n return \"element aspect\";\n else if (entity instanceof Relationship)\n return \"relationship\";\n else\n return \"unknown entity type\";\n }\n\n type EntityUpdater = (entityProps: ConcreteEntityProps) => void;\n\n /** needs to return a widened type otherwise typescript complains when result is used with a narrow type */\n export function updaterFor(db: IModelDb, entity: ConcreteEntity) {\n if (entity instanceof Element)\n return db.elements.updateElement.bind(db.elements) as EntityUpdater;\n else if (entity instanceof Relationship)\n return db.relationships.updateInstance.bind(db.relationships) as EntityUpdater;\n else if (entity instanceof ElementAspect)\n return db.elements.updateAspect.bind(db.elements) as EntityUpdater;\n else\n assert(false, `unreachable; entity was '${entity.constructor.name}' not an Element, Relationship, or ElementAspect`);\n }\n\n export function exists(db: IModelDb, arg: { entity: ConcreteEntity } | { entityReference: EntityReference }) {\n if (\"entityReference\" in arg) {\n const [type, id] = EntityReferences.split(arg.entityReference);\n // FIXME: add a test with a deleted reference that triggers this\n if (id === undefined || Id64.isInvalid(id))\n return false;\n const bisCoreRootClassName = ConcreteEntityTypes.toBisCoreRootClassFullName(type);\n return db.withPreparedStatement(`SELECT 1 FROM ${bisCoreRootClassName} WHERE ECInstanceId=?`, (stmt) => {\n stmt.bindId(1, id);\n const matchesResult = stmt.step();\n if (matchesResult === DbResult.BE_SQLITE_ROW)\n return true;\n if (matchesResult === DbResult.BE_SQLITE_DONE)\n return false;\n else\n throw new IModelError(matchesResult, \"query failed\");\n });\n } else {\n if (arg.entity.id === undefined || Id64.isInvalid(arg.entity.id))\n return false;\n return db.withPreparedStatement(`SELECT 1 FROM [${arg.entity.schemaName}].[${arg.entity.className}] WHERE ECInstanceId=?`, (stmt) => {\n stmt.bindId(1, arg.entity.id);\n const matchesResult = stmt.step();\n if (matchesResult === DbResult.BE_SQLITE_ROW)\n return true;\n if (matchesResult === DbResult.BE_SQLITE_DONE)\n return false;\n else\n throw new IModelError(matchesResult, \"query failed\");\n });\n }\n }\n}\n"]}
@@ -145,7 +145,7 @@ class IModelCloneContext extends core_backend_1.IModelElementCloneContext {
145
145
  targetId: this.findTargetEntityId(relInSource.targetId),
146
146
  };
147
147
  // return a null
148
- if (core_bentley_1.Id64.isInvalid(relInTarget.sourceId) || core_bentley_1.Id64.isInvalid(relInTarget.targetId))
148
+ if (!core_backend_1.EntityReferences.isValid(relInTarget.sourceId) || !core_backend_1.EntityReferences.isValid(relInTarget.targetId))
149
149
  break;
150
150
  const relInTargetId = this.sourceDb.withPreparedStatement(`
151
151
  SELECT ECInstanceId
@@ -221,6 +221,6 @@ class IModelCloneContext extends core_backend_1.IModelElementCloneContext {
221
221
  });
222
222
  }
223
223
  }
224
- IModelCloneContext.aspectRemapTableName = "AspectIdRemaps";
225
224
  exports.IModelCloneContext = IModelCloneContext;
225
+ IModelCloneContext.aspectRemapTableName = "AspectIdRemaps";
226
226
  //# sourceMappingURL=IModelCloneContext.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"IModelCloneContext.js","sourceRoot":"","sources":["../../src/IModelCloneContext.ts"],"names":[],"mappings":";;;AAAA;;;+FAG+F;AAC/F;;GAEG;AACH,iCAAiC;AACjC,sDAAyE;AACzE,oDAK4B;AAC5B,sDAE6B;AAC7B,mEAAgE;AAChE,mDAAgD;AAChD,2EAAwE;AAExE,MAAM,cAAc,GAAW,qDAAyB,CAAC,kBAAkB,CAAC;AAE5E;;GAEG;AACH,MAAa,kBAAmB,SAAQ,wCAAyB;IAAjE;;QAEU,mBAAc,GAAG,IAAI,6CAAqB,EAAE,CAAC;QAC7C,sBAAiB,GAAG,IAAI,GAAG,EAA0B,CAAC;IAwNhE,CAAC;IAtNC,0HAA0H;IAC1G,KAAK,CAAC,UAAU;QAC9B,MAAM,IAAI,CAAC,cAAc,CAAC,sBAAsB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAClE,CAAC;IAED;;OAEG;IACa,YAAY,CAAC,aAAsB,EAAE,YAAiD;QACpG,2DAA2D;QAC3D,MAAM,kBAAkB,GAAiB,IAAI,CAAC,gBAAgB,CAAC,CAAC,YAAY,CAAC,aAAa,CAAC,EAAE,EAAE,YAAY,CAAC,CAAC;QAC7G,iJAAiJ;QACjJ,aAAa,CAAC,eAAe,CAAC,CAAC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CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;gBACxC,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;gBACxC,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;aAC5C;YACD,MAAM,CAAC,MAAM,KAAK,uBAAQ,CAAC,cAAc,CAAC,CAAC;QAC7C,CAAC,CAAC,CAAC;IACL,CAAC;;AAlCc,uCAAoB,GAAG,gBAAgB,AAAnB,CAAoB;AAxL5C,gDAAkB","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 iModels\n */\nimport * as assert from \"assert\";\nimport { DbResult, Id64, Id64String, Logger } from \"@itwin/core-bentley\";\nimport {\n Code,\n CodeScopeSpec,\n ConcreteEntityTypes, ElementAspectProps, ElementProps, EntityReference, IModel, IModelError,\n PrimitiveTypeCode, PropertyMetaData, RelatedElement, RelatedElementProps,\n} from \"@itwin/core-common\";\nimport {\n Element, ElementAspect, EntityReferences, IModelElementCloneContext, IModelJsNative, SQLiteDb,\n} from \"@itwin/core-backend\";\nimport { ECReferenceTypesCache } from \"./ECReferenceTypesCache\";\nimport { EntityUnifier } from \"./EntityUnifier\";\nimport { TransformerLoggerCategory } from \"./TransformerLoggerCategory\";\n\nconst loggerCategory: string = TransformerLoggerCategory.IModelCloneContext;\n\n/** The context for transforming a *source* Element to a *target* Element and remapping internal identifiers to the target iModel.\n * @beta\n */\nexport class IModelCloneContext extends IModelElementCloneContext {\n\n private _refTypesCache = new ECReferenceTypesCache();\n private _aspectRemapTable = new Map<Id64String, Id64String>();\n\n /** perform necessary initialization to use a clone context, namely caching the reference types in the source's schemas */\n public override async initialize() {\n await this._refTypesCache.initAllSchemasInIModel(this.sourceDb);\n }\n\n /** Clone the specified source Element into ElementProps for the target iModel.\n * @internal\n */\n public override cloneElement(sourceElement: Element, cloneOptions?: IModelJsNative.CloneElementOptions): ElementProps {\n // eslint-disable-next-line @typescript-eslint/dot-notation\n const targetElementProps: ElementProps = this[\"_nativeContext\"].cloneElement(sourceElement.id, cloneOptions);\n // Ensure that all NavigationProperties in targetElementProps have a defined value so \"clearing\" changes will be part of the JSON used for update\n sourceElement.forEachProperty((propertyName: string, meta: PropertyMetaData) => {\n if ((meta.isNavigation) && (undefined === (sourceElement as any)[propertyName])) {\n (targetElementProps as any)[propertyName] = RelatedElement.none;\n }\n }, false); // exclude custom because C++ has already handled them\n if (this.isBetweenIModels) {\n // The native C++ cloneElement strips off federationGuid, want to put it back if transformation is between iModels\n targetElementProps.federationGuid = sourceElement.federationGuid;\n const targetElementCodeScopeType = this.targetDb.codeSpecs.getById(targetElementProps.code.spec).scopeType;\n if (CodeScopeSpec.Type.Repository === targetElementCodeScopeType && targetElementProps.code.scope !== IModel.rootSubjectId) {\n Logger.logWarning(loggerCategory, `Incorrect CodeScope '${targetElementCodeScopeType}' is set for target element ${targetElementProps.id}`);\n }\n }\n // unlike other references, code cannot be null. If it is null, use an empty code instead\n // this will be updated back later as the transformer resolves references\n if (targetElementProps.code.scope === Id64.invalid || targetElementProps.code.spec === Id64.invalid) {\n targetElementProps.code = Code.createEmpty();\n }\n const jsClass = this.sourceDb.getJsClass<typeof Element>(sourceElement.classFullName);\n // eslint-disable-next-line @typescript-eslint/dot-notation\n jsClass[\"onCloned\"](this, sourceElement.toJSON(), targetElementProps);\n return targetElementProps;\n }\n\n /** Add a rule that remaps the specified source ElementAspect to the specified target ElementAspect. */\n public remapElementAspect(aspectSourceId: Id64String, aspectTargetId: Id64String): void {\n this._aspectRemapTable.set(aspectSourceId, aspectTargetId);\n }\n\n /** Remove a rule that remaps the specified source ElementAspect */\n public removeElementAspect(aspectSourceId: Id64String): void {\n this._aspectRemapTable.delete(aspectSourceId);\n }\n\n /** Look up a target AspectId from the source AspectId.\n * @returns the target AspectId or [Id64.invalid]($bentley) if a mapping not found.\n */\n public findTargetAspectId(sourceAspectId: Id64String): Id64String {\n return this._aspectRemapTable.get(sourceAspectId) ?? Id64.invalid;\n }\n\n /** Look up a target [EntityReference]($bentley) from a source [EntityReference]($bentley)\n * @returns the target CodeSpecId or a [EntityReference]($bentley) containing [Id64.invalid]($bentley) if a mapping is not found.\n */\n public findTargetEntityId(sourceEntityId: EntityReference): EntityReference {\n const [type, rawId] = EntityReferences.split(sourceEntityId);\n if (Id64.isValid(rawId)) {\n switch (type) {\n case ConcreteEntityTypes.Model: {\n const targetId = `m${this.findTargetElementId(rawId)}` as const;\n // Check if the model exists, `findTargetElementId` may have worked because the element exists when the model doesn't.\n // That can occur in the transformer since a submodeled element is imported before its submodel.\n if (EntityUnifier.exists(this.targetDb, { entityReference: targetId }))\n return targetId;\n break;\n }\n case ConcreteEntityTypes.Element:\n return `e${this.findTargetElementId(rawId)}`;\n case ConcreteEntityTypes.ElementAspect:\n return `a${this.findTargetAspectId(rawId)}`;\n case ConcreteEntityTypes.Relationship: {\n const makeGetConcreteEntityTypeSql = (property: string) => `\n CASE\n WHEN [${property}] IS (BisCore.ElementUniqueAspect) OR [${property}] IS (BisCore.ElementMultiAspect)\n THEN 'a'\n WHEN [${property}] IS (BisCore.Element)\n THEN 'e'\n WHEN [${property}] IS (BisCore.Model)\n THEN 'm'\n WHEN [${property}] IS (BisCore.CodeSpec)\n THEN 'c'\n WHEN [${property}] IS (BisCore.ElementRefersToElements) -- TODO: ElementDrivesElement still not handled by the transformer\n THEN 'r'\n ELSE 'error'\n END\n `;\n const relInSource = this.sourceDb.withPreparedStatement(\n `\n SELECT\n SourceECInstanceId,\n TargetECInstanceId,\n (${makeGetConcreteEntityTypeSql(\"SourceECClassId\")}) AS SourceType,\n (${makeGetConcreteEntityTypeSql(\"TargetECClassId\")}) AS TargetType\n FROM BisCore:ElementRefersToElements\n WHERE ECInstanceId=?\n `, (stmt) => {\n stmt.bindId(1, rawId);\n let status: DbResult;\n while ((status = stmt.step()) === DbResult.BE_SQLITE_ROW) {\n const sourceId = stmt.getValue(0).getId();\n const targetId = stmt.getValue(1).getId();\n const sourceType = stmt.getValue(2).getString() as ConcreteEntityTypes | \"error\";\n const targetType = stmt.getValue(3).getString() as ConcreteEntityTypes | \"error\";\n if (sourceType === \"error\" || targetType === \"error\")\n throw Error(\"relationship end had unknown root class\");\n return {\n sourceId: `${sourceType}${sourceId}`,\n targetId: `${targetType}${targetId}`,\n } as const;\n }\n if (status !== DbResult.BE_SQLITE_DONE)\n throw new IModelError(status, \"unexpected query failure\");\n return undefined;\n });\n if (relInSource === undefined)\n break;\n // just in case prevent recursion\n if (relInSource.sourceId === sourceEntityId || relInSource.targetId === sourceEntityId)\n throw Error(\"link table relationship end was resolved to itself. This should be impossible\");\n const relInTarget = {\n sourceId: this.findTargetEntityId(relInSource.sourceId),\n targetId: this.findTargetEntityId(relInSource.targetId),\n };\n // return a null\n if (Id64.isInvalid(relInTarget.sourceId) || Id64.isInvalid(relInTarget.targetId))\n break;\n const relInTargetId = this.sourceDb.withPreparedStatement(\n `\n SELECT ECInstanceId\n FROM BisCore:ElementRefersToElements\n WHERE SourceECInstanceId=?\n AND TargetECInstanceId=?\n `, (stmt) => {\n stmt.bindId(1, EntityReferences.toId64(relInTarget.sourceId));\n stmt.bindId(2, EntityReferences.toId64(relInTarget.targetId));\n let status: DbResult;\n if ((status = stmt.step()) === DbResult.BE_SQLITE_ROW)\n return stmt.getValue(0).getId();\n if (status !== DbResult.BE_SQLITE_DONE)\n throw new IModelError(status, \"unexpected query failure\");\n return Id64.invalid;\n });\n return `r${relInTargetId}`;\n }\n }\n }\n return `${type}${Id64.invalid}`;\n }\n\n /** Clone the specified source Element into ElementProps for the target iModel.\n * @internal\n */\n public cloneElementAspect(sourceElementAspect: ElementAspect): ElementAspectProps {\n const targetElementAspectProps: ElementAspectProps = sourceElementAspect.toJSON();\n targetElementAspectProps.id = undefined;\n sourceElementAspect.forEachProperty((propertyName, propertyMetaData) => {\n if (propertyMetaData.isNavigation) {\n const sourceNavProp: RelatedElementProps | undefined = sourceElementAspect.asAny[propertyName];\n if (sourceNavProp?.id) {\n const navPropRefType = this._refTypesCache.getNavPropRefType(\n sourceElementAspect.schemaName,\n sourceElementAspect.className,\n propertyName\n );\n assert(navPropRefType !== undefined,`nav prop ref type for '${propertyName}' was not in the cache, this is a bug.`);\n const targetEntityReference = this.findTargetEntityId(EntityReferences.fromEntityType(sourceNavProp.id, navPropRefType));\n const targetEntityId = EntityReferences.toId64(targetEntityReference);\n // spread the property in case toJSON did not deep-clone\n (targetElementAspectProps as any)[propertyName] = { ...(targetElementAspectProps as any)[propertyName], id: targetEntityId };\n }\n } else if ((PrimitiveTypeCode.Long === propertyMetaData.primitiveType) && (\"Id\" === propertyMetaData.extendedType)) {\n (targetElementAspectProps as any)[propertyName] = this.findTargetElementId(sourceElementAspect.asAny[propertyName]);\n }\n });\n return targetElementAspectProps;\n }\n\n private static aspectRemapTableName = \"AspectIdRemaps\";\n\n public override saveStateToDb(db: SQLiteDb): void {\n super.saveStateToDb(db);\n if (DbResult.BE_SQLITE_DONE !== db.executeSQL(\n `CREATE TABLE ${IModelCloneContext.aspectRemapTableName} (Source INTEGER, Target INTEGER)`\n ))\n throw Error(\"Failed to create the aspect remap table in the state database\");\n db.saveChanges();\n db.withPreparedSqliteStatement(\n `INSERT INTO ${IModelCloneContext.aspectRemapTableName} (Source, Target) VALUES (?, ?)`,\n (stmt) => {\n for (const [source, target] of this._aspectRemapTable) {\n stmt.reset();\n stmt.bindId(1, source);\n stmt.bindId(2, target);\n if (DbResult.BE_SQLITE_DONE !== stmt.step())\n throw Error(\"Failed to insert aspect remapping into the state database\");\n }\n });\n }\n\n public override loadStateFromDb(db: SQLiteDb): void {\n super.loadStateFromDb(db);\n // FIXME: test this\n db.withSqliteStatement(`SELECT Source, Target FROM ${IModelCloneContext.aspectRemapTableName}`, (stmt) => {\n let status = DbResult.BE_SQLITE_ERROR;\n while ((status = stmt.step()) === DbResult.BE_SQLITE_ROW) {\n const source = stmt.getValue(0).getId();\n const target = stmt.getValue(1).getId();\n this._aspectRemapTable.set(source, target);\n }\n assert(status === DbResult.BE_SQLITE_DONE);\n });\n }\n}\n"]}
1
+ {"version":3,"file":"IModelCloneContext.js","sourceRoot":"","sources":["../../src/IModelCloneContext.ts"],"names":[],"mappings":";;;AAAA;;;+FAG+F;AAC/F;;GAEG;AACH,iCAAiC;AACjC,sDAAyE;AACzE,oDAK4B;AAC5B,sDAE6B;AAC7B,mEAAgE;AAChE,mDAAgD;AAChD,2EAAwE;AAExE,MAAM,cAAc,GAAW,qDAAyB,CAAC,kBAAkB,CAAC;AAE5E;;GAEG;AACH,MAAa,kBAAmB,SAAQ,wCAAyB;IAAjE;;QAEU,mBAAc,GAAG,IAAI,6CAAqB,EAAE,CAAC;QAC7C,sBAAiB,GAAG,IAAI,GAAG,EAA0B,CAAC;IAwNhE,CAAC;IAtNC,0HAA0H;IAC1G,KAAK,CAAC,UAAU;QAC9B,MAAM,IAAI,CAAC,cAAc,CAAC,sBAAsB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAClE,CAAC;IAED;;OAEG;IACa,YAAY,CAAC,aAAsB,EAAE,YAAiD;QACpG,2DAA2D;QAC3D,MAAM,kBAAkB,GAAiB,IAAI,CAAC,gBAAgB,CAAC,CAAC,YAAY,CAAC,aAAa,CAAC,EAAE,EAAE,YAAY,CAAC,CAAC;QAC7G,iJAAiJ;QACjJ,aAAa,CAAC,eAAe,CAAC,CAAC,YAAoB,EAAE,IAAsB,EAAE,EAAE;YAC7E,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,SAAS,KAAM,aAAqB,CAAC,YAAY,CAAC,CAAC,EAAE;gBAC9E,kBAA0B,CAAC,YAAY,CAAC,GAAG,4BAAc,CAAC,IAAI,CAAC;aACjE;QACH,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,sD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uBAAQ,CAAC,cAAc,CAAC,CAAC;QAC7C,CAAC,CAAC,CAAC;IACL,CAAC;;AA1NH,gDA2NC;AAnCgB,uCAAoB,GAAG,gBAAgB,AAAnB,CAAoB","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 iModels\n */\nimport * as assert from \"assert\";\nimport { DbResult, Id64, Id64String, Logger } from \"@itwin/core-bentley\";\nimport {\n Code,\n CodeScopeSpec,\n ConcreteEntityTypes, ElementAspectProps, ElementProps, EntityReference, IModel, IModelError,\n PrimitiveTypeCode, PropertyMetaData, RelatedElement, RelatedElementProps,\n} from \"@itwin/core-common\";\nimport {\n Element, ElementAspect, EntityReferences, IModelElementCloneContext, IModelJsNative, SQLiteDb,\n} from \"@itwin/core-backend\";\nimport { ECReferenceTypesCache } from \"./ECReferenceTypesCache\";\nimport { EntityUnifier } from \"./EntityUnifier\";\nimport { TransformerLoggerCategory } from \"./TransformerLoggerCategory\";\n\nconst loggerCategory: string = TransformerLoggerCategory.IModelCloneContext;\n\n/** The context for transforming a *source* Element to a *target* Element and remapping internal identifiers to the target iModel.\n * @beta\n */\nexport class IModelCloneContext extends IModelElementCloneContext {\n\n private _refTypesCache = new ECReferenceTypesCache();\n private _aspectRemapTable = new Map<Id64String, Id64String>();\n\n /** perform necessary initialization to use a clone context, namely caching the reference types in the source's schemas */\n public override async initialize() {\n await this._refTypesCache.initAllSchemasInIModel(this.sourceDb);\n }\n\n /** Clone the specified source Element into ElementProps for the target iModel.\n * @internal\n */\n public override cloneElement(sourceElement: Element, cloneOptions?: IModelJsNative.CloneElementOptions): ElementProps {\n // eslint-disable-next-line @typescript-eslint/dot-notation\n const targetElementProps: ElementProps = this[\"_nativeContext\"].cloneElement(sourceElement.id, cloneOptions);\n // Ensure that all NavigationProperties in targetElementProps have a defined value so \"clearing\" changes will be part of the JSON used for update\n sourceElement.forEachProperty((propertyName: string, meta: PropertyMetaData) => {\n if ((meta.isNavigation) && (undefined === (sourceElement as any)[propertyName])) {\n (targetElementProps as any)[propertyName] = RelatedElement.none;\n }\n }, false); // exclude custom because C++ has already handled them\n if (this.isBetweenIModels) {\n // The native C++ cloneElement strips off federationGuid, want to put it back if transformation is between iModels\n targetElementProps.federationGuid = sourceElement.federationGuid;\n const targetElementCodeScopeType = this.targetDb.codeSpecs.getById(targetElementProps.code.spec).scopeType;\n if (CodeScopeSpec.Type.Repository === targetElementCodeScopeType && targetElementProps.code.scope !== IModel.rootSubjectId) {\n Logger.logWarning(loggerCategory, `Incorrect CodeScope '${targetElementCodeScopeType}' is set for target element ${targetElementProps.id}`);\n }\n }\n // unlike other references, code cannot be null. If it is null, use an empty code instead\n // this will be updated back later as the transformer resolves references\n if (targetElementProps.code.scope === Id64.invalid || targetElementProps.code.spec === Id64.invalid) {\n targetElementProps.code = Code.createEmpty();\n }\n const jsClass = this.sourceDb.getJsClass<typeof Element>(sourceElement.classFullName);\n // eslint-disable-next-line @typescript-eslint/dot-notation\n jsClass[\"onCloned\"](this, sourceElement.toJSON(), targetElementProps);\n return targetElementProps;\n }\n\n /** Add a rule that remaps the specified source ElementAspect to the specified target ElementAspect. */\n public remapElementAspect(aspectSourceId: Id64String, aspectTargetId: Id64String): void {\n this._aspectRemapTable.set(aspectSourceId, aspectTargetId);\n }\n\n /** Remove a rule that remaps the specified source ElementAspect */\n public removeElementAspect(aspectSourceId: Id64String): void {\n this._aspectRemapTable.delete(aspectSourceId);\n }\n\n /** Look up a target AspectId from the source AspectId.\n * @returns the target AspectId or [Id64.invalid]($bentley) if a mapping not found.\n */\n public findTargetAspectId(sourceAspectId: Id64String): Id64String {\n return this._aspectRemapTable.get(sourceAspectId) ?? Id64.invalid;\n }\n\n /** Look up a target [EntityReference]($bentley) from a source [EntityReference]($bentley)\n * @returns the target CodeSpecId or a [EntityReference]($bentley) containing [Id64.invalid]($bentley) if a mapping is not found.\n */\n public findTargetEntityId(sourceEntityId: EntityReference): EntityReference {\n const [type, rawId] = EntityReferences.split(sourceEntityId);\n if (Id64.isValid(rawId)) {\n switch (type) {\n case ConcreteEntityTypes.Model: {\n const targetId = `m${this.findTargetElementId(rawId)}` as const;\n // Check if the model exists, `findTargetElementId` may have worked because the element exists when the model doesn't.\n // That can occur in the transformer since a submodeled element is imported before its submodel.\n if (EntityUnifier.exists(this.targetDb, { entityReference: targetId }))\n return targetId;\n break;\n }\n case ConcreteEntityTypes.Element:\n return `e${this.findTargetElementId(rawId)}`;\n case ConcreteEntityTypes.ElementAspect:\n return `a${this.findTargetAspectId(rawId)}`;\n case ConcreteEntityTypes.Relationship: {\n const makeGetConcreteEntityTypeSql = (property: string) => `\n CASE\n WHEN [${property}] IS (BisCore.ElementUniqueAspect) OR [${property}] IS (BisCore.ElementMultiAspect)\n THEN 'a'\n WHEN [${property}] IS (BisCore.Element)\n THEN 'e'\n WHEN [${property}] IS (BisCore.Model)\n THEN 'm'\n WHEN [${property}] IS (BisCore.CodeSpec)\n THEN 'c'\n WHEN [${property}] IS (BisCore.ElementRefersToElements) -- TODO: ElementDrivesElement still not handled by the transformer\n THEN 'r'\n ELSE 'error'\n END\n `;\n const relInSource = this.sourceDb.withPreparedStatement(\n `\n SELECT\n SourceECInstanceId,\n TargetECInstanceId,\n (${makeGetConcreteEntityTypeSql(\"SourceECClassId\")}) AS SourceType,\n (${makeGetConcreteEntityTypeSql(\"TargetECClassId\")}) AS TargetType\n FROM BisCore:ElementRefersToElements\n WHERE ECInstanceId=?\n `, (stmt) => {\n stmt.bindId(1, rawId);\n let status: DbResult;\n while ((status = stmt.step()) === DbResult.BE_SQLITE_ROW) {\n const sourceId = stmt.getValue(0).getId();\n const targetId = stmt.getValue(1).getId();\n const sourceType = stmt.getValue(2).getString() as ConcreteEntityTypes | \"error\";\n const targetType = stmt.getValue(3).getString() as ConcreteEntityTypes | \"error\";\n if (sourceType === \"error\" || targetType === \"error\")\n throw Error(\"relationship end had unknown root class\");\n return {\n sourceId: `${sourceType}${sourceId}`,\n targetId: `${targetType}${targetId}`,\n } as const;\n }\n if (status !== DbResult.BE_SQLITE_DONE)\n throw new IModelError(status, \"unexpected query failure\");\n return undefined;\n });\n if (relInSource === undefined)\n break;\n // just in case prevent recursion\n if (relInSource.sourceId === sourceEntityId || relInSource.targetId === sourceEntityId)\n throw Error(\"link table relationship end was resolved to itself. This should be impossible\");\n const relInTarget = {\n sourceId: this.findTargetEntityId(relInSource.sourceId),\n targetId: this.findTargetEntityId(relInSource.targetId),\n };\n // return a null\n if (!EntityReferences.isValid(relInTarget.sourceId) || !EntityReferences.isValid(relInTarget.targetId))\n break;\n const relInTargetId = this.sourceDb.withPreparedStatement(\n `\n SELECT ECInstanceId\n FROM BisCore:ElementRefersToElements\n WHERE SourceECInstanceId=?\n AND TargetECInstanceId=?\n `, (stmt) => {\n stmt.bindId(1, EntityReferences.toId64(relInTarget.sourceId));\n stmt.bindId(2, EntityReferences.toId64(relInTarget.targetId));\n let status: DbResult;\n if ((status = stmt.step()) === DbResult.BE_SQLITE_ROW)\n return stmt.getValue(0).getId();\n if (status !== DbResult.BE_SQLITE_DONE)\n throw new IModelError(status, \"unexpected query failure\");\n return Id64.invalid;\n });\n return `r${relInTargetId}`;\n }\n }\n }\n return `${type}${Id64.invalid}`;\n }\n\n /** Clone the specified source Element into ElementProps for the target iModel.\n * @internal\n */\n public cloneElementAspect(sourceElementAspect: ElementAspect): ElementAspectProps {\n const targetElementAspectProps: ElementAspectProps = sourceElementAspect.toJSON();\n targetElementAspectProps.id = undefined;\n sourceElementAspect.forEachProperty((propertyName, propertyMetaData) => {\n if (propertyMetaData.isNavigation) {\n const sourceNavProp: RelatedElementProps | undefined = sourceElementAspect.asAny[propertyName];\n if (sourceNavProp?.id) {\n const navPropRefType = this._refTypesCache.getNavPropRefType(\n sourceElementAspect.schemaName,\n sourceElementAspect.className,\n propertyName\n );\n assert(navPropRefType !== undefined,`nav prop ref type for '${propertyName}' was not in the cache, this is a bug.`);\n const targetEntityReference = this.findTargetEntityId(EntityReferences.fromEntityType(sourceNavProp.id, navPropRefType));\n const targetEntityId = EntityReferences.toId64(targetEntityReference);\n // spread the property in case toJSON did not deep-clone\n (targetElementAspectProps as any)[propertyName] = { ...(targetElementAspectProps as any)[propertyName], id: targetEntityId };\n }\n } else if ((PrimitiveTypeCode.Long === propertyMetaData.primitiveType) && (\"Id\" === propertyMetaData.extendedType)) {\n (targetElementAspectProps as any)[propertyName] = this.findTargetElementId(sourceElementAspect.asAny[propertyName]);\n }\n });\n return targetElementAspectProps;\n }\n\n private static aspectRemapTableName = \"AspectIdRemaps\";\n\n public override saveStateToDb(db: SQLiteDb): void {\n super.saveStateToDb(db);\n if (DbResult.BE_SQLITE_DONE !== db.executeSQL(\n `CREATE TABLE ${IModelCloneContext.aspectRemapTableName} (Source INTEGER, Target INTEGER)`\n ))\n throw Error(\"Failed to create the aspect remap table in the state database\");\n db.saveChanges();\n db.withPreparedSqliteStatement(\n `INSERT INTO ${IModelCloneContext.aspectRemapTableName} (Source, Target) VALUES (?, ?)`,\n (stmt) => {\n for (const [source, target] of this._aspectRemapTable) {\n stmt.reset();\n stmt.bindId(1, source);\n stmt.bindId(2, target);\n if (DbResult.BE_SQLITE_DONE !== stmt.step())\n throw Error(\"Failed to insert aspect remapping into the state database\");\n }\n });\n }\n\n public override loadStateFromDb(db: SQLiteDb): void {\n super.loadStateFromDb(db);\n // FIXME: test this\n db.withSqliteStatement(`SELECT Source, Target FROM ${IModelCloneContext.aspectRemapTableName}`, (stmt) => {\n let status = DbResult.BE_SQLITE_ERROR;\n while ((status = stmt.step()) === DbResult.BE_SQLITE_ROW) {\n const source = stmt.getValue(0).getId();\n const target = stmt.getValue(1).getId();\n this._aspectRemapTable.set(source, target);\n }\n assert(status === DbResult.BE_SQLITE_DONE);\n });\n }\n}\n"]}
@@ -525,8 +525,8 @@ class IModelImporter {
525
525
  };
526
526
  }
527
527
  }
528
- IModelImporter._realityDataSourceLinkPartitionStaticId = "0xe";
529
528
  exports.IModelImporter = IModelImporter;
529
+ IModelImporter._realityDataSourceLinkPartitionStaticId = "0xe";
530
530
  /** Returns true if a change within an Entity is detected.
531
531
  * @param entity The current persistent Entity.
532
532
  * @param entityProps The new EntityProps to compare against
@@ -1 +1 @@
1
- {"version":3,"file":"IModelImporter.js","sourceRoot":"","sources":["../../src/IModelImporter.ts"],"names":[],"mappings":";;;AAAA;;;+FAG+F;AAC/F;;GAEG;AACH,sDAAgG;AAChG,oDAG4B;AAC5B,2EAAwE;AACxE,sDAA4K;AAE5K,iCAAiC;AAEjC,MAAM,cAAc,GAAW,qDAAyB,CAAC,cAAc,CAAC;AA8BxE;;;;;GAKG;AACH,MAAa,cAAc;IASzB;;;;;OAKG;IACH,IAAW,wBAAwB;QACjC,OAAO,IAAI,CAAC,OAAO,CAAC,wBAAwB,CAAC;IAC/C,CAAC;IACD,IAAW,wBAAwB,CAAC,GAA8D;QAChG,IAAI,CAAC,OAAO,CAAC,wBAAwB,GAAG,GAAG,CAAC;IAC9C,CAAC;IAED;;;OAGG;IACH,IAAW,8BAA8B;QACvC,OAAO,IAAI,CAAC,OAAO,CAAC,8BAA8B,CAAC;IACrD,CAAC;IACD,IAAW,8BAA8B,CAAC,GAAY;QACpD,IAAI,CAAC,OAAO,CAAC,8BAA8B,GAAG,GAAG,CAAC;IACpD,CAAC;IAED;;;OAGG;IACH,IAAW,uBAAuB;QAChC,OAAO,IAAI,CAAC,OAAO,CAAC,uBAAuB,CAAC;IAC9C,CAAC;IACD,IAAW,uBAAuB,CAAC,GAAY;QAC7C,IAAI,CAAC,OAAO,CAAC,uBAAuB,GAAG,GAAG,CAAC;IAC7C,CAAC;IAsBD;;;OAGG;IACH,YAAmB,QAAkB,EAAE,OAA6B;QAtBpE;;;WAGG;QACa,0BAAqB,GAAG,IAAI,GAAG,CAAa;YAC1D,oBAAM,CAAC,aAAa;YACpB,oBAAM,CAAC,YAAY;YACnB,cA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,CAAC,CAAC;IACrE,MAAM,eAAe,GAAG,4BAAc,CAAC,QAAQ,CAAC,mBAAmB,CAAC,CAAC;IACrE,MAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;IACpD,MAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;IACpD,OAAO,WAAW,KAAK,WAAW,CAAC;AACrC,CAAC;AAED,8EAA8E;AAC9E,SAAS,eAAe,CAAC,SAAc,EAAE,SAAc;IACrD,OAAO,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;AACjE,CAAC;AAED,+CAA+C;AAC/C,SAAS,aAAa,CAAC,KAAmB;IACxC,OAAO,KAAK,CAAC,aAAa,KAAK,0BAAW,CAAC,aAAa,CAAC;AAC3D,CAAC;AAED,2EAA2E;AAC3E,SAAS,oBAAoB,CAAC,KAAuB;IACnD,IAAI,KAAK,CAAC,EAAE,KAAK,SAAS;QACxB,OAAO,KAAK,CAAC;IAEf,IAAI,CAAC,mBAAI,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;QACxB,MAAM,IAAI,yBAAW,CAAC,2BAAY,CAAC,UAAU,EAAE,4BAA4B,CAAC,CAAC;IAC/E,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE,KAAK,SAAS;QAChC,MAAM,IAAI,yBAAW,CAAC,2BAAY,CAAC,UAAU,EAAE,uBAAuB,KAAK,CAAC,EAAE,gBAAgB,CAAC,CAAC;IAClG,OAAO,KAAK,CAAC,EAAE,KAAK,uBAAQ,CAAC,uBAAuB,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AACxE,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 iModels\n */\nimport { CompressedId64Set, Id64, Id64String, IModelStatus, Logger } from \"@itwin/core-bentley\";\nimport {\n AxisAlignedBox3d, Base64EncodedString, ElementAspectProps, ElementProps, EntityProps, IModel, IModelError, ModelProps, PrimitiveTypeCode,\n PropertyMetaData, RelatedElement, SubCategoryProps,\n} from \"@itwin/core-common\";\nimport { TransformerLoggerCategory } from \"./TransformerLoggerCategory\";\nimport { deleteElementTree, ElementAspect, ElementMultiAspect, Entity, IModelDb, Relationship, RelationshipProps, SourceAndTarget, SubCategory } from \"@itwin/core-backend\";\nimport type { IModelTransformOptions } from \"./IModelTransformer\";\nimport * as assert from \"assert\";\n\nconst loggerCategory: string = TransformerLoggerCategory.IModelImporter;\n\n/** Options provided to [[IModelImporter.optimizeGeometry]] specifying post-processing optimizations to be applied to the iModel's geometry.\n * @beta\n */\nexport interface OptimizeGeometryOptions {\n /** If true, identify any [GeometryPart]($backend)s that are referenced exactly once. For each such part,\n * replace the reference in the element's geometry stream with the part's own geometry stream, then delete the part.\n */\n inlineUniqueGeometryParts?: boolean;\n}\n\n/** Options provided to the [[IModelImporter]] constructor.\n * @beta\n */\nexport interface IModelImportOptions {\n /** If `true` (the default), compute the projectExtents of the target iModel after elements are imported.\n * The computed projectExtents will either include or exclude *outliers* depending on the `excludeOutliers` flag that defaults to `false`.\n * @see [[IModelImporter.autoExtendProjectExtents]]\n * @see [IModelImporter Options]($docs/learning/transformer/index.md#IModelImporter)\n */\n autoExtendProjectExtents?: boolean | { excludeOutliers: boolean };\n /** See [IModelTransformOptions]($transformer) */\n preserveElementIdsForFiltering?: boolean;\n /** If `true`, simplify the element geometry for visualization purposes. For example, convert b-reps into meshes.\n * @default false\n */\n simplifyElementGeometry?: boolean;\n}\n\n/** Base class for importing data into an iModel.\n * @see [iModel Transformation and Data Exchange]($docs/learning/transformer/index.md)\n * @see [IModelExporter]($transformer)\n * @see [IModelTransformer]($transformer)\n * @beta\n */\nexport class IModelImporter implements Required<IModelImportOptions> {\n /** The read/write target iModel. */\n public readonly targetDb: IModelDb;\n\n /** resolved initialization options for the importer\n * @beta\n */\n public readonly options: Required<IModelImportOptions>;\n\n /** If `true` (the default), compute the projectExtents of the target iModel after elements are imported.\n * The computed projectExtents will either include or exclude *outliers* depending on the `excludeOutliers` flag that defaults to `false`.\n * @see [[IModelImportOptions.autoExtendProjectExtents]]\n * @see [IModelImporter Options]($docs/learning/transformer/index.md#IModelImporter)\n * @deprecated in 3.x. Use [[IModelImporter.options.autoExtendProjectExtents]] instead\n */\n public get autoExtendProjectExtents(): Required<IModelImportOptions>[\"autoExtendProjectExtents\"] {\n return this.options.autoExtendProjectExtents;\n }\n public set autoExtendProjectExtents(val: Required<IModelImportOptions>[\"autoExtendProjectExtents\"]) {\n this.options.autoExtendProjectExtents = val;\n }\n\n /**\n * See [IModelTransformOptions.preserveElementIdsForFiltering]($transformer)\n * @deprecated in 3.x. Use [[IModelImporter.options.preserveElementIdsForFiltering]] instead\n */\n public get preserveElementIdsForFiltering(): boolean {\n return this.options.preserveElementIdsForFiltering;\n }\n public set preserveElementIdsForFiltering(val: boolean) {\n this.options.preserveElementIdsForFiltering = val;\n }\n\n /**\n * See [[IModelImportOptions.simplifyElementGeometry]]\n * @deprecated in 3.x. Use [[IModelImporter.options.simplifyElementGeometry]] instead\n */\n public get simplifyElementGeometry(): boolean {\n return this.options.simplifyElementGeometry;\n }\n public set simplifyElementGeometry(val: boolean) {\n this.options.simplifyElementGeometry = val;\n }\n\n private static _realityDataSourceLinkPartitionStaticId: Id64String = \"0xe\";\n\n /** The set of elements that should not be updated by this IModelImporter.\n * Defaults to the elements that are always present (even in an \"empty\" iModel) and therefore do not need to be updated\n * @note Adding an element to this set is typically necessary when remapping a source element to one that already exists in the target and already has the desired properties.\n */\n public readonly doNotUpdateElementIds = new Set<Id64String>([\n IModel.rootSubjectId,\n IModel.dictionaryId,\n IModelImporter._realityDataSourceLinkPartitionStaticId,\n ]);\n /** The number of entity changes before incremental progress should be reported via the [[onProgress]] callback. */\n public progressInterval: number = 1000;\n /** Tracks the current total number of entity changes. */\n private _progressCounter: number = 0;\n /** */\n private _modelPropertiesToIgnore = new Set<string>([\n \"geometryGuid\", // cannot compare GeometricModel.GeometryGuid values across iModels\n ]);\n\n /** Construct a new IModelImporter\n * @param targetDb The target IModelDb\n * @param options The options that specify how the import should be done.\n */\n public constructor(targetDb: IModelDb, options?: IModelImportOptions) {\n this.targetDb = targetDb;\n this.options = {\n autoExtendProjectExtents: options?.autoExtendProjectExtents ?? true,\n preserveElementIdsForFiltering: options?.preserveElementIdsForFiltering ?? false,\n simplifyElementGeometry: options?.simplifyElementGeometry ?? false,\n };\n }\n\n /** Import the specified ModelProps (either as an insert or an update) into the target iModel. */\n public importModel(modelProps: ModelProps): void {\n if ((undefined === modelProps.id) || !Id64.isValidId64(modelProps.id))\n throw new IModelError(IModelStatus.InvalidId, \"Model Id not provided, should be the same as the ModeledElementId\");\n\n if (this.doNotUpdateElementIds.has(modelProps.id)) {\n Logger.logInfo(loggerCategory, `Do not update target model ${modelProps.id}`);\n return;\n }\n try {\n const model = this.targetDb.models.getModel(modelProps.id); // throws IModelError.NotFound if model does not exist\n if (hasEntityChanged(model, modelProps, this._modelPropertiesToIgnore)) {\n this.onUpdateModel(modelProps);\n }\n } catch (error) {\n // catch NotFound error and insertModel\n if (error instanceof IModelError && error.errorNumber === IModelStatus.NotFound) {\n this.onInsertModel(modelProps);\n return;\n }\n throw error;\n }\n }\n\n /** Create a new Model from the specified ModelProps and insert it into the target iModel.\n * @note A subclass may override this method to customize insert behavior but should call `super.onInsertModel`.\n */\n protected onInsertModel(modelProps: ModelProps): Id64String {\n try {\n const modelId: Id64String = this.targetDb.models.insertModel(modelProps);\n Logger.logInfo(loggerCategory, `Inserted ${this.formatModelForLogger(modelProps)}`);\n this.trackProgress();\n return modelId;\n } catch (error) {\n if (!this.targetDb.containsClass(modelProps.classFullName)) {\n // replace standard insert error with something more helpful\n const errorMessage = `Model class \"${modelProps.classFullName}\" not found in the target iModel. Was the latest version of the schema imported?`;\n throw new IModelError(IModelStatus.InvalidName, errorMessage);\n }\n throw error; // throw original error\n }\n }\n\n /** Update an existing Model in the target iModel from the specified ModelProps.\n * @note A subclass may override this method to customize update behavior but should call `super.onUpdateModel`.\n */\n protected onUpdateModel(modelProps: ModelProps): void {\n this.targetDb.models.updateModel(modelProps);\n Logger.logInfo(loggerCategory, `Updated ${this.formatModelForLogger(modelProps)}`);\n this.trackProgress();\n }\n\n /** Format a Model for the Logger. */\n private formatModelForLogger(modelProps: ModelProps): string {\n return `${modelProps.classFullName} [${modelProps.id!}]`;\n }\n\n /** Import the specified ElementProps (either as an insert or an update) into the target iModel. */\n public importElement(elementProps: ElementProps): Id64String {\n if (undefined !== elementProps.id && this.doNotUpdateElementIds.has(elementProps.id)) {\n Logger.logInfo(loggerCategory, `Do not update target element ${elementProps.id}`);\n return elementProps.id;\n }\n if (this.options.preserveElementIdsForFiltering) {\n if (elementProps.id === undefined) {\n throw new IModelError(IModelStatus.BadElement, `elementProps.id must be defined during a preserveIds operation`);\n }\n // Categories are the only element that onInserted will immediately insert a new element (their default subcategory)\n // since default subcategories always exist and always will be inserted after their categories, we treat them as an update\n // to prevent duplicate inserts.\n // Otherwise we always insert during a preserveElementIdsForFiltering operation\n if (isSubCategory(elementProps) && isDefaultSubCategory(elementProps)) {\n this.onUpdateElement(elementProps);\n } else {\n this.onInsertElement(elementProps);\n }\n } else {\n if (undefined !== elementProps.id) {\n this.onUpdateElement(elementProps);\n } else {\n this.onInsertElement(elementProps); // targetElementProps.id assigned by insertElement\n }\n }\n return elementProps.id!;\n }\n\n /** Create a new Element from the specified ElementProps and insert it into the target iModel.\n * @returns The Id of the newly inserted Element.\n * @note A subclass may override this method to customize insert behavior but should call `super.onInsertElement`.\n */\n protected onInsertElement(elementProps: ElementProps): Id64String {\n try {\n const elementId = this.targetDb.nativeDb.insertElement(\n elementProps,\n { forceUseId: this.options.preserveElementIdsForFiltering },\n );\n // set the id like [IModelDb.insertElement]($backend), does, the raw nativeDb method does not\n elementProps.id = elementId;\n Logger.logInfo(loggerCategory, `Inserted ${this.formatElementForLogger(elementProps)}`);\n this.trackProgress();\n if (this.options.simplifyElementGeometry) {\n this.targetDb.nativeDb.simplifyElementGeometry({ id: elementId, convertBReps: true });\n Logger.logInfo(loggerCategory, `Simplified element geometry for ${this.formatElementForLogger(elementProps)}`);\n }\n return elementId;\n } catch (error) {\n if (!this.targetDb.containsClass(elementProps.classFullName)) {\n // replace standard insert error with something more helpful\n const errorMessage = `Element class \"${elementProps.classFullName}\" not found in the target iModel. Was the latest version of the schema imported?`;\n throw new IModelError(IModelStatus.InvalidName, errorMessage);\n }\n throw error; // throw original error\n }\n }\n\n /** Update an existing Element in the target iModel from the specified ElementProps.\n * @note A subclass may override this method to customize update behavior but should call `super.onUpdateElement`.\n */\n protected onUpdateElement(elementProps: ElementProps): void {\n if (!elementProps.id) {\n throw new IModelError(IModelStatus.InvalidId, \"ElementId not provided\");\n }\n this.targetDb.elements.updateElement(elementProps);\n Logger.logInfo(loggerCategory, `Updated ${this.formatElementForLogger(elementProps)}`);\n this.trackProgress();\n if (this.options.simplifyElementGeometry) {\n this.targetDb.nativeDb.simplifyElementGeometry({ id: elementProps.id, convertBReps: true });\n Logger.logInfo(loggerCategory, `Simplified element geometry for ${this.formatElementForLogger(elementProps)}`);\n }\n }\n\n /** Delete the specified Element (and all its children) from the target iModel.\n * Will delete special elements like definition elements and subjects.\n * @note A subclass may override this method to customize delete behavior but should call `super.onDeleteElement`.\n */\n protected onDeleteElement(elementId: Id64String): void {\n deleteElementTree(this.targetDb, elementId);\n Logger.logInfo(loggerCategory, `Deleted element ${elementId} and its descendants`);\n this.trackProgress();\n }\n\n /** Delete the specified Element from the target iModel. */\n public deleteElement(elementId: Id64String): void {\n if (this.doNotUpdateElementIds.has(elementId)) {\n Logger.logInfo(loggerCategory, `Do not delete target element ${elementId}`);\n return;\n }\n this.onDeleteElement(elementId);\n }\n\n /** Delete the specified Model from the target iModel.\n * @note A subclass may override this method to customize delete behavior but should call `super.onDeleteModel`.\n */\n protected onDeleteModel(modelId: Id64String): void {\n this.targetDb.models.deleteModel(modelId);\n Logger.logInfo(loggerCategory, `Deleted model ${modelId}`);\n this.trackProgress();\n }\n\n /** Delete the specified Model from the target iModel. */\n public deleteModel(modelId: Id64String): void {\n this.onDeleteModel(modelId);\n }\n\n /** Format an Element for the Logger. */\n private formatElementForLogger(elementProps: ElementProps): string {\n const namePiece: string = elementProps.code.value ? `${elementProps.code.value} ` : elementProps.userLabel ? `${elementProps.userLabel} ` : \"\";\n return `${elementProps.classFullName} ${namePiece}[${elementProps.id}]`;\n }\n\n /** Import an ElementUniqueAspect into the target iModel. */\n public importElementUniqueAspect(aspectProps: ElementAspectProps): Id64String {\n const aspects: ElementAspect[] = this.targetDb.elements.getAspects(aspectProps.element.id, aspectProps.classFullName);\n if (aspects.length === 0) {\n return this.onInsertElementAspect(aspectProps);\n } else if (hasEntityChanged(aspects[0], aspectProps)) {\n aspectProps.id = aspects[0].id;\n this.onUpdateElementAspect(aspectProps);\n }\n return aspects[0].id;\n }\n\n /** Import the collection of ElementMultiAspects into the target iModel.\n * @param aspectPropsArray The ElementMultiAspects to import\n * @param filterFunc Optional filter func that is used to exclude target ElementMultiAspects that were added during iModel transformation from the update detection logic.\n * @note For insert vs. update reasons, it is important to process all ElementMultiAspects owned by an Element at once since we don't have aspect-specific provenance.\n * @returns the array of ids of the resulting ElementMultiAspects, in the same order of the aspectPropsArray parameter\n */\n public importElementMultiAspects(\n aspectPropsArray: ElementAspectProps[],\n /** caller must use this to enforce any aspects added by IModelTransformer are not considered for update */\n filterFunc: (a: ElementMultiAspect) => boolean = () => true\n ): Id64String[] {\n const result = new Array<Id64String | undefined>(aspectPropsArray.length).fill(undefined);\n\n if (aspectPropsArray.length === 0) {\n return result as Id64String[];\n }\n\n const elementId: Id64String = aspectPropsArray[0].element.id;\n // Determine the set of ElementMultiAspect classes to consider\n const aspectClassFullNames = new Set<string>();\n aspectPropsArray.forEach((aspectsProps: ElementAspectProps): void => {\n aspectClassFullNames.add(aspectsProps.classFullName);\n });\n\n // Handle ElementMultiAspects in groups by class\n aspectClassFullNames.forEach((aspectClassFullName: string) => {\n const proposedAspects = aspectPropsArray\n .map((props, index) => ({ props, index }))\n .filter(({props}) => aspectClassFullName === props.classFullName);\n\n const currentAspects = this.targetDb.elements\n .getAspects(elementId, aspectClassFullName)\n .map((props, index) => ({ props, index }) as const)\n .filter(({props}) => filterFunc(props));\n\n if (proposedAspects.length >= currentAspects.length) {\n proposedAspects.forEach(({props, index: resultIndex}, index) => {\n let id: Id64String;\n if (index < currentAspects.length) {\n id = currentAspects[index].props.id;\n props.id = id;\n if (hasEntityChanged(currentAspects[index].props, props)) {\n this.onUpdateElementAspect(props);\n }\n id = props.id;\n } else {\n id = this.onInsertElementAspect(props);\n }\n result[resultIndex] = id;\n });\n } else {\n currentAspects.forEach(({props, index: resultIndex}, index) => {\n let id: Id64String;\n if (index < proposedAspects.length) {\n id = props.id;\n proposedAspects[index].props.id = id;\n if (hasEntityChanged(props, proposedAspects[index].props)) {\n this.onUpdateElementAspect(proposedAspects[index].props);\n }\n result[resultIndex] = id;\n } else {\n this.onDeleteElementAspect(props);\n }\n });\n }\n });\n\n assert(result.every((r) => typeof r !== undefined));\n return result as Id64String[];\n }\n\n /** Insert the ElementAspect into the target iModel.\n * @note A subclass may override this method to customize insert behavior but should call `super.onInsertElementAspect`.\n */\n protected onInsertElementAspect(aspectProps: ElementAspectProps): Id64String {\n try {\n const id = this.targetDb.elements.insertAspect(aspectProps);\n Logger.logInfo(loggerCategory, `Inserted ${this.formatElementAspectForLogger(aspectProps)}`);\n this.trackProgress();\n return id;\n } catch (error) {\n if (!this.targetDb.containsClass(aspectProps.classFullName)) {\n // replace standard insert error with something more helpful\n const errorMessage = `ElementAspect class \"${aspectProps.classFullName}\" not found in the target iModel. Was the latest version of the schema imported?`;\n throw new IModelError(IModelStatus.InvalidName, errorMessage);\n }\n throw error; // throw original error\n }\n }\n\n /** Update the ElementAspect within the target iModel.\n * @note A subclass may override this method to customize update behavior but should call `super.onUpdateElementAspect`.\n */\n protected onUpdateElementAspect(aspectProps: ElementAspectProps): void {\n this.targetDb.elements.updateAspect(aspectProps);\n Logger.logInfo(loggerCategory, `Updated ${this.formatElementAspectForLogger(aspectProps)}`);\n this.trackProgress();\n }\n\n /** Delete the specified ElementAspect from the target iModel.\n * @note A subclass may override this method to customize delete behavior but should call `super.onDeleteElementAspect`.\n */\n protected onDeleteElementAspect(targetElementAspect: ElementAspect): void {\n this.targetDb.elements.deleteAspect(targetElementAspect.id);\n Logger.logInfo(loggerCategory, `Deleted ${this.formatElementAspectForLogger(targetElementAspect)}`);\n this.trackProgress();\n }\n\n /** Format an ElementAspect for the Logger. */\n private formatElementAspectForLogger(elementAspectProps: ElementAspectProps | ElementAspect): string {\n return `${elementAspectProps.classFullName} elementId=[${elementAspectProps.element.id}]`;\n }\n\n /** Import the specified RelationshipProps (either as an insert or an update) into the target iModel.\n * @returns The instance Id of the inserted or updated Relationship.\n */\n public importRelationship(relationshipProps: RelationshipProps): Id64String {\n if ((undefined === relationshipProps.sourceId) || !Id64.isValidId64(relationshipProps.sourceId)) {\n Logger.logInfo(loggerCategory, `Ignoring ${relationshipProps.classFullName} instance because of invalid RelationshipProps.sourceId`);\n return Id64.invalid;\n }\n if ((undefined === relationshipProps.targetId) || !Id64.isValidId64(relationshipProps.targetId)) {\n Logger.logInfo(loggerCategory, `Ignoring ${relationshipProps.classFullName} instance because of invalid RelationshipProps.targetId`);\n return Id64.invalid;\n }\n // check for an existing relationship\n const relSourceAndTarget: SourceAndTarget = { sourceId: relationshipProps.sourceId, targetId: relationshipProps.targetId };\n const relationship: Relationship | undefined = this.targetDb.relationships.tryGetInstance(relationshipProps.classFullName, relSourceAndTarget);\n if (undefined !== relationship) { // if relationship found, update it\n relationshipProps.id = relationship.id;\n if (hasEntityChanged(relationship, relationshipProps)) {\n this.onUpdateRelationship(relationshipProps);\n }\n return relationshipProps.id;\n } else {\n return this.onInsertRelationship(relationshipProps);\n }\n }\n\n /** Create a new Relationship from the specified RelationshipProps and insert it into the target iModel.\n * @returns The instance Id of the newly inserted relationship.\n * @note A subclass may override this method to customize insert behavior but should call `super.onInsertRelationship`.\n */\n protected onInsertRelationship(relationshipProps: RelationshipProps): Id64String {\n try {\n const targetRelInstanceId: Id64String = this.targetDb.relationships.insertInstance(relationshipProps);\n Logger.logInfo(loggerCategory, `Inserted ${this.formatRelationshipForLogger(relationshipProps)}`);\n this.trackProgress();\n return targetRelInstanceId;\n } catch (error) {\n if (!this.targetDb.containsClass(relationshipProps.classFullName)) {\n // replace standard insert error with something more helpful\n const errorMessage = `Relationship class \"${relationshipProps.classFullName}\" not found in the target iModel. Was the latest version of the schema imported?`;\n throw new IModelError(IModelStatus.InvalidName, errorMessage);\n }\n throw error; // throw original error\n }\n }\n\n /** Update an existing Relationship in the target iModel from the specified RelationshipProps.\n * @note A subclass may override this method to customize update behavior but should call `super.onUpdateRelationship`.\n */\n protected onUpdateRelationship(relationshipProps: RelationshipProps): void {\n if (!relationshipProps.id) {\n throw new IModelError(IModelStatus.InvalidId, \"Relationship instance Id not provided\");\n }\n this.targetDb.relationships.updateInstance(relationshipProps);\n Logger.logInfo(loggerCategory, `Updated ${this.formatRelationshipForLogger(relationshipProps)}`);\n this.trackProgress();\n }\n\n /** Delete the specified Relationship from the target iModel. */\n protected onDeleteRelationship(relationshipProps: RelationshipProps): void {\n this.targetDb.relationships.deleteInstance(relationshipProps);\n Logger.logInfo(loggerCategory, `Deleted relationship ${this.formatRelationshipForLogger(relationshipProps)}`);\n this.trackProgress();\n }\n\n /** Delete the specified Relationship from the target iModel. */\n public deleteRelationship(relationshipProps: RelationshipProps): void {\n this.onDeleteRelationship(relationshipProps);\n }\n\n /** Format a Relationship for the Logger. */\n private formatRelationshipForLogger(relProps: RelationshipProps): string {\n return `${relProps.classFullName} sourceId=[${relProps.sourceId}] targetId=[${relProps.targetId}]`;\n }\n\n /** Tracks incremental progress */\n private trackProgress(): void {\n this._progressCounter++;\n if (0 === (this._progressCounter % this.progressInterval)) {\n this.onProgress();\n }\n }\n\n /** This method is called when IModelImporter has made incremental progress based on the [[progressInterval]] setting.\n * @note A subclass may override this method to report custom progress but should call `super.onProgress`.\n */\n protected onProgress(): void { }\n\n /** Optionally compute the projectExtents for the target iModel depending on the options for this IModelImporter.\n * @note This method is automatically called from [IModelTransformer.processChanges]($transformer) and [IModelTransformer.processAll]($transformer).\n * @see [IModelDb.computeProjectExtents]($backend), [[autoExtendProjectExtents]]\n */\n public computeProjectExtents(): void {\n const computedProjectExtents = this.targetDb.computeProjectExtents({ reportExtentsWithOutliers: true, reportOutliers: true });\n Logger.logInfo(loggerCategory, `Current projectExtents=${JSON.stringify(this.targetDb.projectExtents)}`);\n Logger.logInfo(loggerCategory, `Computed projectExtents without outliers=${JSON.stringify(computedProjectExtents.extents)}`);\n Logger.logInfo(loggerCategory, `Computed projectExtents with outliers=${JSON.stringify(computedProjectExtents.extentsWithOutliers)}`);\n if (this.options.autoExtendProjectExtents) {\n const excludeOutliers: boolean = typeof this.options.autoExtendProjectExtents === \"object\" ? this.options.autoExtendProjectExtents.excludeOutliers : false;\n const newProjectExtents: AxisAlignedBox3d = excludeOutliers ? computedProjectExtents.extents : computedProjectExtents.extentsWithOutliers!;\n if (!newProjectExtents.isAlmostEqual(this.targetDb.projectExtents)) {\n this.targetDb.updateProjectExtents(newProjectExtents);\n Logger.logInfo(loggerCategory, `Updated projectExtents=${JSON.stringify(this.targetDb.projectExtents)}`);\n }\n if (!excludeOutliers && computedProjectExtents.outliers && computedProjectExtents.outliers.length > 0) {\n Logger.logInfo(loggerCategory, `${computedProjectExtents.outliers.length} outliers detected within projectExtents`);\n }\n } else {\n if (!this.targetDb.projectExtents.containsRange(computedProjectExtents.extents)) {\n Logger.logWarning(loggerCategory, \"Current project extents may be too small\");\n }\n if (computedProjectExtents.outliers && computedProjectExtents.outliers.length > 0) {\n Logger.logInfo(loggerCategory, `${computedProjectExtents.outliers.length} outliers detected within projectExtents`);\n }\n }\n }\n\n /** Examine the geometry streams of every [GeometricElement3d]($backend) in the target iModel and apply the specified optimizations.\n * @note This method is automatically called from [[IModelTransformer.processChanges]] and [[IModelTransformer.processAll]] if\n * [[IModelTransformOptions.optimizeGeometry]] is defined.\n */\n public optimizeGeometry(options: OptimizeGeometryOptions): void {\n if (options.inlineUniqueGeometryParts) {\n const result = this.targetDb.nativeDb.inlineGeometryPartReferences();\n Logger.logInfo(loggerCategory, `Inlined ${result.numRefsInlined} references to ${result.numCandidateParts} geometry parts and deleted ${result.numPartsDeleted} parts.`);\n }\n }\n\n /**\n * You may override this to store arbitrary json state in a exporter state dump, useful for some resumptions\n * @see [[IModelTransformer.saveStateToFile]]\n */\n protected getAdditionalStateJson(): any {\n return {};\n }\n\n /**\n * You may override this to load arbitrary json state in a transformer state dump, useful for some resumptions\n * @see [[IModelTransformer.loadStateFromFile]]\n */\n protected loadAdditionalStateJson(_additionalState: any): void {}\n\n /**\n * Reload our state from a JSON object\n * Intended for [[IModelTransformer.resumeTransformation]]\n * @internal\n * You can load custom json from the importer save state for custom importers by overriding [[IModelImporter.loadAdditionalStateJson]]\n */\n public loadStateFromJson(state: IModelImporterState): void {\n if (state.importerClass !== this.constructor.name)\n throw Error(\"resuming from a differently named importer class, it is not necessarily valid to resume with a different importer class\");\n // ignore readonly since this runs right after construction in [[IModelTransformer.resumeTransformation]]\n (this.options as IModelTransformOptions) = state.options;\n if (this.targetDb.iModelId !== state.targetDbId)\n throw Error(\"can only load importer state when the same target is reused\");\n // TODO: fix upstream, looks like a bad case for the linter rule when casting away readonly for this generic\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n (this.doNotUpdateElementIds as Set<Id64String>) = CompressedId64Set.decompressSet(state.doNotUpdateElementIds);\n this.loadAdditionalStateJson(state.additionalState);\n }\n\n /**\n * Serialize state to a JSON object\n * Intended for [[IModelTransformer.resumeTransformation]]\n * @internal\n * You can add custom json to the importer save state for custom importers by overriding [[IModelImporter.getAdditionalStateJson]]\n */\n public saveStateToJson(): IModelImporterState {\n return {\n importerClass: this.constructor.name,\n options: this.options,\n targetDbId: this.targetDb.iModelId || this.targetDb.nativeDb.getFilePath(),\n doNotUpdateElementIds: CompressedId64Set.compressSet(this.doNotUpdateElementIds),\n additionalState: this.getAdditionalStateJson(),\n };\n }\n}\n\n/**\n * The JSON format of a serialized IModelimporter instance\n * Used for starting an importer in the middle of an imxport operation,\n * such as resuming a crashed transformation\n *\n * @note Must be kept synchronized with IModelImxporter\n * @internal\n */\nexport interface IModelImporterState {\n importerClass: string;\n options: IModelImportOptions;\n targetDbId: string;\n doNotUpdateElementIds: CompressedId64Set;\n additionalState?: any;\n}\n\n/** Returns true if a change within an Entity is detected.\n * @param entity The current persistent Entity.\n * @param entityProps The new EntityProps to compare against\n * @note This method should only be called if changeset information is not available.\n * @internal\n */\nexport function hasEntityChanged(entity: Entity, entityProps: EntityProps, namesToIgnore?: Set<string>): boolean {\n let changed: boolean = false;\n entity.forEachProperty((propertyName: string, propertyMeta: PropertyMetaData) => {\n if (!changed) {\n if (namesToIgnore && namesToIgnore.has(propertyName)) {\n // skip\n } else if (PrimitiveTypeCode.Binary === propertyMeta.primitiveType) {\n changed = hasBinaryValueChanged(entity.asAny[propertyName], (entityProps as any)[propertyName]);\n } else if (propertyMeta.isNavigation) {\n changed = hasNavigationValueChanged(entity.asAny[propertyName], (entityProps as any)[propertyName]);\n } else {\n changed = hasValueChanged(entity.asAny[propertyName], (entityProps as any)[propertyName]);\n }\n }\n });\n return changed;\n}\n\n/** Returns true if the specified binary values are different. */\nfunction hasBinaryValueChanged(binaryProperty1: any, binaryProperty2: any): boolean {\n const jsonString1 = JSON.stringify(binaryProperty1, Base64EncodedString.replacer);\n const jsonString2 = JSON.stringify(binaryProperty2, Base64EncodedString.replacer);\n return jsonString1 !== jsonString2;\n}\n\n/** Returns true if the specified navigation property values are different. */\nfunction hasNavigationValueChanged(navigationProperty1: any, navigationProperty2: any): boolean {\n const relatedElement1 = RelatedElement.fromJSON(navigationProperty1);\n const relatedElement2 = RelatedElement.fromJSON(navigationProperty2);\n const jsonString1 = JSON.stringify(relatedElement1);\n const jsonString2 = JSON.stringify(relatedElement2);\n return jsonString1 !== jsonString2;\n}\n\n/** Returns true if the specified navigation property values are different. */\nfunction hasValueChanged(property1: any, property2: any): boolean {\n return JSON.stringify(property1) !== JSON.stringify(property2);\n}\n\n/** check if element props are a subcategory */\nfunction isSubCategory(props: ElementProps): props is SubCategoryProps {\n return props.classFullName === SubCategory.classFullName;\n}\n\n/** check if element props are a subcategory without loading the element */\nfunction isDefaultSubCategory(props: SubCategoryProps): boolean {\n if (props.id === undefined)\n return false;\n\n if (!Id64.isId64(props.id))\n throw new IModelError(IModelStatus.BadElement, `subcategory had invalid id`);\n if (props.parent?.id === undefined)\n throw new IModelError(IModelStatus.BadElement, `subcategory with id ${props.id} had no parent`);\n return props.id === IModelDb.getDefaultSubCategoryId(props.parent.id);\n}\n"]}
1
+ {"version":3,"file":"IModelImporter.js","sourceRoot":"","sources":["../../src/IModelImporter.ts"],"names":[],"mappings":";;;AAAA;;;+FAG+F;AAC/F;;GAEG;AACH,sDAAgG;AAChG,oDAG4B;AAC5B,2EAAwE;AACxE,sDAA4K;AAE5K,iCAAiC;AAEjC,MAAM,cAAc,GAAW,qDAAyB,CAAC,cAAc,CAAC;AA8BxE;;;;;GAKG;AACH,MAAa,cAAc;IASzB;;;;;OAKG;IACH,IAAW,wBAAwB;QACjC,OAAO,IAAI,CAAC,OAAO,CAAC,wBAAwB,CAAC;IAC/C,CAAC;IACD,IAAW,wBAAwB,CAAC,GAA8D;QAChG,IAAI,CAAC,OAAO,CAAC,wBAAwB,GAAG,GAAG,CAAC;IAC9C,CAAC;IAED;;;OAGG;IACH,IAAW,8BAA8B;QACvC,OAAO,IAAI,CAAC,OAAO,CAAC,8BAA8B,CAAC;IACrD,CAAC;IACD,IAAW,8BAA8B,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4BAA4B,CAAC,CAAC;IAC/E,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE,KAAK,SAAS;QAChC,MAAM,IAAI,yBAAW,CAAC,2BAAY,CAAC,UAAU,EAAE,uBAAuB,KAAK,CAAC,EAAE,gBAAgB,CAAC,CAAC;IAClG,OAAO,KAAK,CAAC,EAAE,KAAK,uBAAQ,CAAC,uBAAuB,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AACxE,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 iModels\n */\nimport { CompressedId64Set, Id64, Id64String, IModelStatus, Logger } from \"@itwin/core-bentley\";\nimport {\n AxisAlignedBox3d, Base64EncodedString, ElementAspectProps, ElementProps, EntityProps, IModel, IModelError, ModelProps, PrimitiveTypeCode,\n PropertyMetaData, RelatedElement, SubCategoryProps,\n} from \"@itwin/core-common\";\nimport { TransformerLoggerCategory } from \"./TransformerLoggerCategory\";\nimport { deleteElementTree, ElementAspect, ElementMultiAspect, Entity, IModelDb, Relationship, RelationshipProps, SourceAndTarget, SubCategory } from \"@itwin/core-backend\";\nimport type { IModelTransformOptions } from \"./IModelTransformer\";\nimport * as assert from \"assert\";\n\nconst loggerCategory: string = TransformerLoggerCategory.IModelImporter;\n\n/** Options provided to [[IModelImporter.optimizeGeometry]] specifying post-processing optimizations to be applied to the iModel's geometry.\n * @beta\n */\nexport interface OptimizeGeometryOptions {\n /** If true, identify any [GeometryPart]($backend)s that are referenced exactly once. For each such part,\n * replace the reference in the element's geometry stream with the part's own geometry stream, then delete the part.\n */\n inlineUniqueGeometryParts?: boolean;\n}\n\n/** Options provided to the [[IModelImporter]] constructor.\n * @beta\n */\nexport interface IModelImportOptions {\n /** If `true` (the default), compute the projectExtents of the target iModel after elements are imported.\n * The computed projectExtents will either include or exclude *outliers* depending on the `excludeOutliers` flag that defaults to `false`.\n * @see [[IModelImporter.autoExtendProjectExtents]]\n * @see [IModelImporter Options]($docs/learning/transformer/index.md#IModelImporter)\n */\n autoExtendProjectExtents?: boolean | { excludeOutliers: boolean };\n /** See [IModelTransformOptions]($transformer) */\n preserveElementIdsForFiltering?: boolean;\n /** If `true`, simplify the element geometry for visualization purposes. For example, convert b-reps into meshes.\n * @default false\n */\n simplifyElementGeometry?: boolean;\n}\n\n/** Base class for importing data into an iModel.\n * @see [iModel Transformation and Data Exchange]($docs/learning/transformer/index.md)\n * @see [IModelExporter]($transformer)\n * @see [IModelTransformer]($transformer)\n * @beta\n */\nexport class IModelImporter implements Required<IModelImportOptions> {\n /** The read/write target iModel. */\n public readonly targetDb: IModelDb;\n\n /** resolved initialization options for the importer\n * @beta\n */\n public readonly options: Required<IModelImportOptions>;\n\n /** If `true` (the default), compute the projectExtents of the target iModel after elements are imported.\n * The computed projectExtents will either include or exclude *outliers* depending on the `excludeOutliers` flag that defaults to `false`.\n * @see [[IModelImportOptions.autoExtendProjectExtents]]\n * @see [IModelImporter Options]($docs/learning/transformer/index.md#IModelImporter)\n * @deprecated in 3.x. Use [[IModelImporter.options.autoExtendProjectExtents]] instead\n */\n public get autoExtendProjectExtents(): Required<IModelImportOptions>[\"autoExtendProjectExtents\"] {\n return this.options.autoExtendProjectExtents;\n }\n public set autoExtendProjectExtents(val: Required<IModelImportOptions>[\"autoExtendProjectExtents\"]) {\n this.options.autoExtendProjectExtents = val;\n }\n\n /**\n * See [IModelTransformOptions.preserveElementIdsForFiltering]($transformer)\n * @deprecated in 3.x. Use [[IModelImporter.options.preserveElementIdsForFiltering]] instead\n */\n public get preserveElementIdsForFiltering(): boolean {\n return this.options.preserveElementIdsForFiltering;\n }\n public set preserveElementIdsForFiltering(val: boolean) {\n this.options.preserveElementIdsForFiltering = val;\n }\n\n /**\n * See [[IModelImportOptions.simplifyElementGeometry]]\n * @deprecated in 3.x. Use [[IModelImporter.options.simplifyElementGeometry]] instead\n */\n public get simplifyElementGeometry(): boolean {\n return this.options.simplifyElementGeometry;\n }\n public set simplifyElementGeometry(val: boolean) {\n this.options.simplifyElementGeometry = val;\n }\n\n private static _realityDataSourceLinkPartitionStaticId: Id64String = \"0xe\";\n\n /** The set of elements that should not be updated by this IModelImporter.\n * Defaults to the elements that are always present (even in an \"empty\" iModel) and therefore do not need to be updated\n * @note Adding an element to this set is typically necessary when remapping a source element to one that already exists in the target and already has the desired properties.\n */\n public readonly doNotUpdateElementIds = new Set<Id64String>([\n IModel.rootSubjectId,\n IModel.dictionaryId,\n IModelImporter._realityDataSourceLinkPartitionStaticId,\n ]);\n /** The number of entity changes before incremental progress should be reported via the [[onProgress]] callback. */\n public progressInterval: number = 1000;\n /** Tracks the current total number of entity changes. */\n private _progressCounter: number = 0;\n /** */\n private _modelPropertiesToIgnore = new Set<string>([\n \"geometryGuid\", // cannot compare GeometricModel.GeometryGuid values across iModels\n ]);\n\n /** Construct a new IModelImporter\n * @param targetDb The target IModelDb\n * @param options The options that specify how the import should be done.\n */\n public constructor(targetDb: IModelDb, options?: IModelImportOptions) {\n this.targetDb = targetDb;\n this.options = {\n autoExtendProjectExtents: options?.autoExtendProjectExtents ?? true,\n preserveElementIdsForFiltering: options?.preserveElementIdsForFiltering ?? false,\n simplifyElementGeometry: options?.simplifyElementGeometry ?? false,\n };\n }\n\n /** Import the specified ModelProps (either as an insert or an update) into the target iModel. */\n public importModel(modelProps: ModelProps): void {\n if ((undefined === modelProps.id) || !Id64.isValidId64(modelProps.id))\n throw new IModelError(IModelStatus.InvalidId, \"Model Id not provided, should be the same as the ModeledElementId\");\n\n if (this.doNotUpdateElementIds.has(modelProps.id)) {\n Logger.logInfo(loggerCategory, `Do not update target model ${modelProps.id}`);\n return;\n }\n try {\n const model = this.targetDb.models.getModel(modelProps.id); // throws IModelError.NotFound if model does not exist\n if (hasEntityChanged(model, modelProps, this._modelPropertiesToIgnore)) {\n this.onUpdateModel(modelProps);\n }\n } catch (error) {\n // catch NotFound error and insertModel\n if (error instanceof IModelError && error.errorNumber === IModelStatus.NotFound) {\n this.onInsertModel(modelProps);\n return;\n }\n throw error;\n }\n }\n\n /** Create a new Model from the specified ModelProps and insert it into the target iModel.\n * @note A subclass may override this method to customize insert behavior but should call `super.onInsertModel`.\n */\n protected onInsertModel(modelProps: ModelProps): Id64String {\n try {\n const modelId: Id64String = this.targetDb.models.insertModel(modelProps);\n Logger.logInfo(loggerCategory, `Inserted ${this.formatModelForLogger(modelProps)}`);\n this.trackProgress();\n return modelId;\n } catch (error) {\n if (!this.targetDb.containsClass(modelProps.classFullName)) {\n // replace standard insert error with something more helpful\n const errorMessage = `Model class \"${modelProps.classFullName}\" not found in the target iModel. Was the latest version of the schema imported?`;\n throw new IModelError(IModelStatus.InvalidName, errorMessage);\n }\n throw error; // throw original error\n }\n }\n\n /** Update an existing Model in the target iModel from the specified ModelProps.\n * @note A subclass may override this method to customize update behavior but should call `super.onUpdateModel`.\n */\n protected onUpdateModel(modelProps: ModelProps): void {\n this.targetDb.models.updateModel(modelProps);\n Logger.logInfo(loggerCategory, `Updated ${this.formatModelForLogger(modelProps)}`);\n this.trackProgress();\n }\n\n /** Format a Model for the Logger. */\n private formatModelForLogger(modelProps: ModelProps): string {\n return `${modelProps.classFullName} [${modelProps.id!}]`;\n }\n\n /** Import the specified ElementProps (either as an insert or an update) into the target iModel. */\n public importElement(elementProps: ElementProps): Id64String {\n if (undefined !== elementProps.id && this.doNotUpdateElementIds.has(elementProps.id)) {\n Logger.logInfo(loggerCategory, `Do not update target element ${elementProps.id}`);\n return elementProps.id;\n }\n if (this.options.preserveElementIdsForFiltering) {\n if (elementProps.id === undefined) {\n throw new IModelError(IModelStatus.BadElement, `elementProps.id must be defined during a preserveIds operation`);\n }\n // Categories are the only element that onInserted will immediately insert a new element (their default subcategory)\n // since default subcategories always exist and always will be inserted after their categories, we treat them as an update\n // to prevent duplicate inserts.\n // Otherwise we always insert during a preserveElementIdsForFiltering operation\n if (isSubCategory(elementProps) && isDefaultSubCategory(elementProps)) {\n this.onUpdateElement(elementProps);\n } else {\n this.onInsertElement(elementProps);\n }\n } else {\n if (undefined !== elementProps.id) {\n this.onUpdateElement(elementProps);\n } else {\n this.onInsertElement(elementProps); // targetElementProps.id assigned by insertElement\n }\n }\n return elementProps.id!;\n }\n\n /** Create a new Element from the specified ElementProps and insert it into the target iModel.\n * @returns The Id of the newly inserted Element.\n * @note A subclass may override this method to customize insert behavior but should call `super.onInsertElement`.\n */\n protected onInsertElement(elementProps: ElementProps): Id64String {\n try {\n const elementId = this.targetDb.nativeDb.insertElement(\n elementProps,\n { forceUseId: this.options.preserveElementIdsForFiltering },\n );\n // set the id like [IModelDb.insertElement]($backend), does, the raw nativeDb method does not\n elementProps.id = elementId;\n Logger.logInfo(loggerCategory, `Inserted ${this.formatElementForLogger(elementProps)}`);\n this.trackProgress();\n if (this.options.simplifyElementGeometry) {\n this.targetDb.nativeDb.simplifyElementGeometry({ id: elementId, convertBReps: true });\n Logger.logInfo(loggerCategory, `Simplified element geometry for ${this.formatElementForLogger(elementProps)}`);\n }\n return elementId;\n } catch (error) {\n if (!this.targetDb.containsClass(elementProps.classFullName)) {\n // replace standard insert error with something more helpful\n const errorMessage = `Element class \"${elementProps.classFullName}\" not found in the target iModel. Was the latest version of the schema imported?`;\n throw new IModelError(IModelStatus.InvalidName, errorMessage);\n }\n throw error; // throw original error\n }\n }\n\n /** Update an existing Element in the target iModel from the specified ElementProps.\n * @note A subclass may override this method to customize update behavior but should call `super.onUpdateElement`.\n */\n protected onUpdateElement(elementProps: ElementProps): void {\n if (!elementProps.id) {\n throw new IModelError(IModelStatus.InvalidId, \"ElementId not provided\");\n }\n this.targetDb.elements.updateElement(elementProps);\n Logger.logInfo(loggerCategory, `Updated ${this.formatElementForLogger(elementProps)}`);\n this.trackProgress();\n if (this.options.simplifyElementGeometry) {\n this.targetDb.nativeDb.simplifyElementGeometry({ id: elementProps.id, convertBReps: true });\n Logger.logInfo(loggerCategory, `Simplified element geometry for ${this.formatElementForLogger(elementProps)}`);\n }\n }\n\n /** Delete the specified Element (and all its children) from the target iModel.\n * Will delete special elements like definition elements and subjects.\n * @note A subclass may override this method to customize delete behavior but should call `super.onDeleteElement`.\n */\n protected onDeleteElement(elementId: Id64String): void {\n deleteElementTree(this.targetDb, elementId);\n Logger.logInfo(loggerCategory, `Deleted element ${elementId} and its descendants`);\n this.trackProgress();\n }\n\n /** Delete the specified Element from the target iModel. */\n public deleteElement(elementId: Id64String): void {\n if (this.doNotUpdateElementIds.has(elementId)) {\n Logger.logInfo(loggerCategory, `Do not delete target element ${elementId}`);\n return;\n }\n this.onDeleteElement(elementId);\n }\n\n /** Delete the specified Model from the target iModel.\n * @note A subclass may override this method to customize delete behavior but should call `super.onDeleteModel`.\n */\n protected onDeleteModel(modelId: Id64String): void {\n this.targetDb.models.deleteModel(modelId);\n Logger.logInfo(loggerCategory, `Deleted model ${modelId}`);\n this.trackProgress();\n }\n\n /** Delete the specified Model from the target iModel. */\n public deleteModel(modelId: Id64String): void {\n this.onDeleteModel(modelId);\n }\n\n /** Format an Element for the Logger. */\n private formatElementForLogger(elementProps: ElementProps): string {\n const namePiece: string = elementProps.code.value ? `${elementProps.code.value} ` : elementProps.userLabel ? `${elementProps.userLabel} ` : \"\";\n return `${elementProps.classFullName} ${namePiece}[${elementProps.id}]`;\n }\n\n /** Import an ElementUniqueAspect into the target iModel. */\n public importElementUniqueAspect(aspectProps: ElementAspectProps): Id64String {\n const aspects: ElementAspect[] = this.targetDb.elements.getAspects(aspectProps.element.id, aspectProps.classFullName);\n if (aspects.length === 0) {\n return this.onInsertElementAspect(aspectProps);\n } else if (hasEntityChanged(aspects[0], aspectProps)) {\n aspectProps.id = aspects[0].id;\n this.onUpdateElementAspect(aspectProps);\n }\n return aspects[0].id;\n }\n\n /** Import the collection of ElementMultiAspects into the target iModel.\n * @param aspectPropsArray The ElementMultiAspects to import\n * @param filterFunc Optional filter func that is used to exclude target ElementMultiAspects that were added during iModel transformation from the update detection logic.\n * @note For insert vs. update reasons, it is important to process all ElementMultiAspects owned by an Element at once since we don't have aspect-specific provenance.\n * @returns the array of ids of the resulting ElementMultiAspects, in the same order of the aspectPropsArray parameter\n */\n public importElementMultiAspects(\n aspectPropsArray: ElementAspectProps[],\n /** caller must use this to enforce any aspects added by IModelTransformer are not considered for update */\n filterFunc: (a: ElementMultiAspect) => boolean = () => true\n ): Id64String[] {\n const result = new Array<Id64String | undefined>(aspectPropsArray.length).fill(undefined);\n\n if (aspectPropsArray.length === 0) {\n return result as Id64String[];\n }\n\n const elementId: Id64String = aspectPropsArray[0].element.id;\n // Determine the set of ElementMultiAspect classes to consider\n const aspectClassFullNames = new Set<string>();\n aspectPropsArray.forEach((aspectsProps: ElementAspectProps): void => {\n aspectClassFullNames.add(aspectsProps.classFullName);\n });\n\n // Handle ElementMultiAspects in groups by class\n aspectClassFullNames.forEach((aspectClassFullName: string) => {\n const proposedAspects = aspectPropsArray\n .map((props, index) => ({ props, index }))\n .filter(({props}) => aspectClassFullName === props.classFullName);\n\n const currentAspects = this.targetDb.elements\n .getAspects(elementId, aspectClassFullName)\n .map((props, index) => ({ props, index }) as const)\n .filter(({props}) => filterFunc(props));\n\n if (proposedAspects.length >= currentAspects.length) {\n proposedAspects.forEach(({props, index: resultIndex}, index) => {\n let id: Id64String;\n if (index < currentAspects.length) {\n id = currentAspects[index].props.id;\n props.id = id;\n if (hasEntityChanged(currentAspects[index].props, props)) {\n this.onUpdateElementAspect(props);\n }\n id = props.id;\n } else {\n id = this.onInsertElementAspect(props);\n }\n result[resultIndex] = id;\n });\n } else {\n currentAspects.forEach(({props, index: resultIndex}, index) => {\n let id: Id64String;\n if (index < proposedAspects.length) {\n id = props.id;\n proposedAspects[index].props.id = id;\n if (hasEntityChanged(props, proposedAspects[index].props)) {\n this.onUpdateElementAspect(proposedAspects[index].props);\n }\n result[resultIndex] = id;\n } else {\n this.onDeleteElementAspect(props);\n }\n });\n }\n });\n\n assert(result.every((r) => typeof r !== undefined));\n return result as Id64String[];\n }\n\n /** Insert the ElementAspect into the target iModel.\n * @note A subclass may override this method to customize insert behavior but should call `super.onInsertElementAspect`.\n */\n protected onInsertElementAspect(aspectProps: ElementAspectProps): Id64String {\n try {\n const id = this.targetDb.elements.insertAspect(aspectProps);\n Logger.logInfo(loggerCategory, `Inserted ${this.formatElementAspectForLogger(aspectProps)}`);\n this.trackProgress();\n return id;\n } catch (error) {\n if (!this.targetDb.containsClass(aspectProps.classFullName)) {\n // replace standard insert error with something more helpful\n const errorMessage = `ElementAspect class \"${aspectProps.classFullName}\" not found in the target iModel. Was the latest version of the schema imported?`;\n throw new IModelError(IModelStatus.InvalidName, errorMessage);\n }\n throw error; // throw original error\n }\n }\n\n /** Update the ElementAspect within the target iModel.\n * @note A subclass may override this method to customize update behavior but should call `super.onUpdateElementAspect`.\n */\n protected onUpdateElementAspect(aspectProps: ElementAspectProps): void {\n this.targetDb.elements.updateAspect(aspectProps);\n Logger.logInfo(loggerCategory, `Updated ${this.formatElementAspectForLogger(aspectProps)}`);\n this.trackProgress();\n }\n\n /** Delete the specified ElementAspect from the target iModel.\n * @note A subclass may override this method to customize delete behavior but should call `super.onDeleteElementAspect`.\n */\n protected onDeleteElementAspect(targetElementAspect: ElementAspect): void {\n this.targetDb.elements.deleteAspect(targetElementAspect.id);\n Logger.logInfo(loggerCategory, `Deleted ${this.formatElementAspectForLogger(targetElementAspect)}`);\n this.trackProgress();\n }\n\n /** Format an ElementAspect for the Logger. */\n private formatElementAspectForLogger(elementAspectProps: ElementAspectProps | ElementAspect): string {\n return `${elementAspectProps.classFullName} elementId=[${elementAspectProps.element.id}]`;\n }\n\n /** Import the specified RelationshipProps (either as an insert or an update) into the target iModel.\n * @returns The instance Id of the inserted or updated Relationship.\n */\n public importRelationship(relationshipProps: RelationshipProps): Id64String {\n if ((undefined === relationshipProps.sourceId) || !Id64.isValidId64(relationshipProps.sourceId)) {\n Logger.logInfo(loggerCategory, `Ignoring ${relationshipProps.classFullName} instance because of invalid RelationshipProps.sourceId`);\n return Id64.invalid;\n }\n if ((undefined === relationshipProps.targetId) || !Id64.isValidId64(relationshipProps.targetId)) {\n Logger.logInfo(loggerCategory, `Ignoring ${relationshipProps.classFullName} instance because of invalid RelationshipProps.targetId`);\n return Id64.invalid;\n }\n // check for an existing relationship\n const relSourceAndTarget: SourceAndTarget = { sourceId: relationshipProps.sourceId, targetId: relationshipProps.targetId };\n const relationship: Relationship | undefined = this.targetDb.relationships.tryGetInstance(relationshipProps.classFullName, relSourceAndTarget);\n if (undefined !== relationship) { // if relationship found, update it\n relationshipProps.id = relationship.id;\n if (hasEntityChanged(relationship, relationshipProps)) {\n this.onUpdateRelationship(relationshipProps);\n }\n return relationshipProps.id;\n } else {\n return this.onInsertRelationship(relationshipProps);\n }\n }\n\n /** Create a new Relationship from the specified RelationshipProps and insert it into the target iModel.\n * @returns The instance Id of the newly inserted relationship.\n * @note A subclass may override this method to customize insert behavior but should call `super.onInsertRelationship`.\n */\n protected onInsertRelationship(relationshipProps: RelationshipProps): Id64String {\n try {\n const targetRelInstanceId: Id64String = this.targetDb.relationships.insertInstance(relationshipProps);\n Logger.logInfo(loggerCategory, `Inserted ${this.formatRelationshipForLogger(relationshipProps)}`);\n this.trackProgress();\n return targetRelInstanceId;\n } catch (error) {\n if (!this.targetDb.containsClass(relationshipProps.classFullName)) {\n // replace standard insert error with something more helpful\n const errorMessage = `Relationship class \"${relationshipProps.classFullName}\" not found in the target iModel. Was the latest version of the schema imported?`;\n throw new IModelError(IModelStatus.InvalidName, errorMessage);\n }\n throw error; // throw original error\n }\n }\n\n /** Update an existing Relationship in the target iModel from the specified RelationshipProps.\n * @note A subclass may override this method to customize update behavior but should call `super.onUpdateRelationship`.\n */\n protected onUpdateRelationship(relationshipProps: RelationshipProps): void {\n if (!relationshipProps.id) {\n throw new IModelError(IModelStatus.InvalidId, \"Relationship instance Id not provided\");\n }\n this.targetDb.relationships.updateInstance(relationshipProps);\n Logger.logInfo(loggerCategory, `Updated ${this.formatRelationshipForLogger(relationshipProps)}`);\n this.trackProgress();\n }\n\n /** Delete the specified Relationship from the target iModel. */\n protected onDeleteRelationship(relationshipProps: RelationshipProps): void {\n this.targetDb.relationships.deleteInstance(relationshipProps);\n Logger.logInfo(loggerCategory, `Deleted relationship ${this.formatRelationshipForLogger(relationshipProps)}`);\n this.trackProgress();\n }\n\n /** Delete the specified Relationship from the target iModel. */\n public deleteRelationship(relationshipProps: RelationshipProps): void {\n this.onDeleteRelationship(relationshipProps);\n }\n\n /** Format a Relationship for the Logger. */\n private formatRelationshipForLogger(relProps: RelationshipProps): string {\n return `${relProps.classFullName} sourceId=[${relProps.sourceId}] targetId=[${relProps.targetId}]`;\n }\n\n /** Tracks incremental progress */\n private trackProgress(): void {\n this._progressCounter++;\n if (0 === (this._progressCounter % this.progressInterval)) {\n this.onProgress();\n }\n }\n\n /** This method is called when IModelImporter has made incremental progress based on the [[progressInterval]] setting.\n * @note A subclass may override this method to report custom progress but should call `super.onProgress`.\n */\n protected onProgress(): void { }\n\n /** Optionally compute the projectExtents for the target iModel depending on the options for this IModelImporter.\n * @note This method is automatically called from [IModelTransformer.processChanges]($transformer) and [IModelTransformer.processAll]($transformer).\n * @see [IModelDb.computeProjectExtents]($backend), [[autoExtendProjectExtents]]\n */\n public computeProjectExtents(): void {\n const computedProjectExtents = this.targetDb.computeProjectExtents({ reportExtentsWithOutliers: true, reportOutliers: true });\n Logger.logInfo(loggerCategory, `Current projectExtents=${JSON.stringify(this.targetDb.projectExtents)}`);\n Logger.logInfo(loggerCategory, `Computed projectExtents without outliers=${JSON.stringify(computedProjectExtents.extents)}`);\n Logger.logInfo(loggerCategory, `Computed projectExtents with outliers=${JSON.stringify(computedProjectExtents.extentsWithOutliers)}`);\n if (this.options.autoExtendProjectExtents) {\n const excludeOutliers: boolean = typeof this.options.autoExtendProjectExtents === \"object\" ? this.options.autoExtendProjectExtents.excludeOutliers : false;\n const newProjectExtents: AxisAlignedBox3d = excludeOutliers ? computedProjectExtents.extents : computedProjectExtents.extentsWithOutliers!;\n if (!newProjectExtents.isAlmostEqual(this.targetDb.projectExtents)) {\n this.targetDb.updateProjectExtents(newProjectExtents);\n Logger.logInfo(loggerCategory, `Updated projectExtents=${JSON.stringify(this.targetDb.projectExtents)}`);\n }\n if (!excludeOutliers && computedProjectExtents.outliers && computedProjectExtents.outliers.length > 0) {\n Logger.logInfo(loggerCategory, `${computedProjectExtents.outliers.length} outliers detected within projectExtents`);\n }\n } else {\n if (!this.targetDb.projectExtents.containsRange(computedProjectExtents.extents)) {\n Logger.logWarning(loggerCategory, \"Current project extents may be too small\");\n }\n if (computedProjectExtents.outliers && computedProjectExtents.outliers.length > 0) {\n Logger.logInfo(loggerCategory, `${computedProjectExtents.outliers.length} outliers detected within projectExtents`);\n }\n }\n }\n\n /** Examine the geometry streams of every [GeometricElement3d]($backend) in the target iModel and apply the specified optimizations.\n * @note This method is automatically called from [[IModelTransformer.processChanges]] and [[IModelTransformer.processAll]] if\n * [[IModelTransformOptions.optimizeGeometry]] is defined.\n */\n public optimizeGeometry(options: OptimizeGeometryOptions): void {\n if (options.inlineUniqueGeometryParts) {\n const result = this.targetDb.nativeDb.inlineGeometryPartReferences();\n Logger.logInfo(loggerCategory, `Inlined ${result.numRefsInlined} references to ${result.numCandidateParts} geometry parts and deleted ${result.numPartsDeleted} parts.`);\n }\n }\n\n /**\n * You may override this to store arbitrary json state in a exporter state dump, useful for some resumptions\n * @see [[IModelTransformer.saveStateToFile]]\n */\n protected getAdditionalStateJson(): any {\n return {};\n }\n\n /**\n * You may override this to load arbitrary json state in a transformer state dump, useful for some resumptions\n * @see [[IModelTransformer.loadStateFromFile]]\n */\n protected loadAdditionalStateJson(_additionalState: any): void {}\n\n /**\n * Reload our state from a JSON object\n * Intended for [[IModelTransformer.resumeTransformation]]\n * @internal\n * You can load custom json from the importer save state for custom importers by overriding [[IModelImporter.loadAdditionalStateJson]]\n */\n public loadStateFromJson(state: IModelImporterState): void {\n if (state.importerClass !== this.constructor.name)\n throw Error(\"resuming from a differently named importer class, it is not necessarily valid to resume with a different importer class\");\n // ignore readonly since this runs right after construction in [[IModelTransformer.resumeTransformation]]\n (this.options as IModelTransformOptions) = state.options;\n if (this.targetDb.iModelId !== state.targetDbId)\n throw Error(\"can only load importer state when the same target is reused\");\n // TODO: fix upstream, looks like a bad case for the linter rule when casting away readonly for this generic\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n (this.doNotUpdateElementIds as Set<Id64String>) = CompressedId64Set.decompressSet(state.doNotUpdateElementIds);\n this.loadAdditionalStateJson(state.additionalState);\n }\n\n /**\n * Serialize state to a JSON object\n * Intended for [[IModelTransformer.resumeTransformation]]\n * @internal\n * You can add custom json to the importer save state for custom importers by overriding [[IModelImporter.getAdditionalStateJson]]\n */\n public saveStateToJson(): IModelImporterState {\n return {\n importerClass: this.constructor.name,\n options: this.options,\n targetDbId: this.targetDb.iModelId || this.targetDb.nativeDb.getFilePath(),\n doNotUpdateElementIds: CompressedId64Set.compressSet(this.doNotUpdateElementIds),\n additionalState: this.getAdditionalStateJson(),\n };\n }\n}\n\n/**\n * The JSON format of a serialized IModelimporter instance\n * Used for starting an importer in the middle of an imxport operation,\n * such as resuming a crashed transformation\n *\n * @note Must be kept synchronized with IModelImxporter\n * @internal\n */\nexport interface IModelImporterState {\n importerClass: string;\n options: IModelImportOptions;\n targetDbId: string;\n doNotUpdateElementIds: CompressedId64Set;\n additionalState?: any;\n}\n\n/** Returns true if a change within an Entity is detected.\n * @param entity The current persistent Entity.\n * @param entityProps The new EntityProps to compare against\n * @note This method should only be called if changeset information is not available.\n * @internal\n */\nexport function hasEntityChanged(entity: Entity, entityProps: EntityProps, namesToIgnore?: Set<string>): boolean {\n let changed: boolean = false;\n entity.forEachProperty((propertyName: string, propertyMeta: PropertyMetaData) => {\n if (!changed) {\n if (namesToIgnore && namesToIgnore.has(propertyName)) {\n // skip\n } else if (PrimitiveTypeCode.Binary === propertyMeta.primitiveType) {\n changed = hasBinaryValueChanged(entity.asAny[propertyName], (entityProps as any)[propertyName]);\n } else if (propertyMeta.isNavigation) {\n changed = hasNavigationValueChanged(entity.asAny[propertyName], (entityProps as any)[propertyName]);\n } else {\n changed = hasValueChanged(entity.asAny[propertyName], (entityProps as any)[propertyName]);\n }\n }\n });\n return changed;\n}\n\n/** Returns true if the specified binary values are different. */\nfunction hasBinaryValueChanged(binaryProperty1: any, binaryProperty2: any): boolean {\n const jsonString1 = JSON.stringify(binaryProperty1, Base64EncodedString.replacer);\n const jsonString2 = JSON.stringify(binaryProperty2, Base64EncodedString.replacer);\n return jsonString1 !== jsonString2;\n}\n\n/** Returns true if the specified navigation property values are different. */\nfunction hasNavigationValueChanged(navigationProperty1: any, navigationProperty2: any): boolean {\n const relatedElement1 = RelatedElement.fromJSON(navigationProperty1);\n const relatedElement2 = RelatedElement.fromJSON(navigationProperty2);\n const jsonString1 = JSON.stringify(relatedElement1);\n const jsonString2 = JSON.stringify(relatedElement2);\n return jsonString1 !== jsonString2;\n}\n\n/** Returns true if the specified navigation property values are different. */\nfunction hasValueChanged(property1: any, property2: any): boolean {\n return JSON.stringify(property1) !== JSON.stringify(property2);\n}\n\n/** check if element props are a subcategory */\nfunction isSubCategory(props: ElementProps): props is SubCategoryProps {\n return props.classFullName === SubCategory.classFullName;\n}\n\n/** check if element props are a subcategory without loading the element */\nfunction isDefaultSubCategory(props: SubCategoryProps): boolean {\n if (props.id === undefined)\n return false;\n\n if (!Id64.isId64(props.id))\n throw new IModelError(IModelStatus.BadElement, `subcategory had invalid id`);\n if (props.parent?.id === undefined)\n throw new IModelError(IModelStatus.BadElement, `subcategory with id ${props.id} had no parent`);\n return props.id === IModelDb.getDefaultSubCategoryId(props.parent.id);\n}\n"]}
@@ -1255,11 +1255,11 @@ class IModelTransformer extends IModelExporter_1.IModelExportHandler {
1255
1255
  this.finalizeTransformation();
1256
1256
  }
1257
1257
  }
1258
+ exports.IModelTransformer = IModelTransformer;
1258
1259
  /** @internal the name of the table where javascript state of the transformer is serialized in transformer state dumps */
1259
1260
  IModelTransformer.jsStateTable = "TransformerJsState";
1260
1261
  /** @internal the name of the table where the target state heuristics is serialized in transformer state dumps */
1261
1262
  IModelTransformer.lastProvenanceEntityInfoTable = "LastProvenanceEntityInfo";
1262
- exports.IModelTransformer = IModelTransformer;
1263
1263
  /** IModelTransformer that clones the contents of a template model.
1264
1264
  * @beta
1265
1265
  */