@itwin/imodel-transformer 0.2.2-dev.3 → 0.3.18-fedguidopt.5

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.
@@ -1 +1 @@
1
- {"version":3,"file":"IModelTransformer.js","sourceRoot":"","sources":["../../src/IModelTransformer.ts"],"names":[],"mappings":";;;AAAA;;;+FAG+F;AAC/F;;GAEG;AACH,6BAA6B;AAC7B,iCAAiC;AACjC,qCAAqC;AACrC,sDAG6B;AAE7B,wDAA0D;AAC1D,sDAM6B;AAC7B,oDAI4B;AAC5B,qDAAsI;AACtI,qDAAgG;AAChG,2EAAwE;AACxE,+DAA8E;AAC9E,2CAAmD;AACnD,6DAA0D;AAC1D,mDAAgD;AAEhD,MAAM,cAAc,GAAW,qDAAyB,CAAC,iBAAiB,CAAC;AAE3E,MAAM,4BAA4B,GAAG;IACnC,QAAQ,EAAE,mBAAI,CAAC,OAAO;IACtB,QAAQ,EAAE,mBAAI,CAAC,OAAO;IACtB,aAAa,EAAE,EAAE;IACjB,UAAU,EAAE,mCAAoB,CAAC,IAAI,CAAC,OAAO;CAC9C,CAAC;AA6GF;;;GAGG;AACH,MAAM,wBAAwB;IAC5B;IACE;;;;OAIG;IACK,kBAAsC,EACtC,WAAuB;QADvB,uBAAkB,GAAlB,kBAAkB,CAAoB;QACtC,gBAAW,GAAX,WAAW,CAAY;IAC9B,CAAC;IACG,gBAAgB,CAAC,EAAmB;QACzC,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACnC,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,KAAK,CAAC;YACpC,IAAI,CAAC,WAAW,EAAE,CAAC;IACvB,CAAC;IACM,aAAa;QAClB,IAAI,CAAC,WAAW,EAAE,CAAC;IACrB,CAAC;CACF;AAED;;;;;GAKG;AACH,SAAS,OAAO,CACd,WAAwD,EACxD,IAA2B;IAE3B,MAAM,YAAY,GAAG,CAAC,GAAQ,E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C,CAAC,CAAC,qGAAqG;QACvK,OAAO,kBAAkB,CAAC;IAC5B,CAAC;CACF;AAlGD,kDAkGC","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 path from \"path\";\nimport * as Semver from \"semver\";\nimport * as nodeAssert from \"assert\";\nimport {\n AccessToken, assert, DbResult, Guid, Id64, Id64String, IModelStatus, Logger, MarkRequired,\n OpenMode, YieldManager,\n} from \"@itwin/core-bentley\";\nimport * as ECSchemaMetaData from \"@itwin/ecschema-metadata\";\nimport { Point3d, Transform } from \"@itwin/core-geometry\";\nimport {\n ChangeSummaryManager,\n ChannelRootAspect, ConcreteEntity, DefinitionElement, DefinitionModel, DefinitionPartition, ECSchemaXmlContext, ECSqlStatement, Element, ElementAspect, ElementMultiAspect, ElementOwnsExternalSourceAspects,\n ElementRefersToElements, ElementUniqueAspect, Entity, EntityReferences, ExternalSource, ExternalSourceAspect, ExternalSourceAttachment,\n FolderLink, GeometricElement2d, GeometricElement3d, IModelDb, IModelHost, IModelJsFs, InformationPartitionElement, KnownLocations, Model,\n RecipeDefinitionElement, Relationship, RelationshipProps, Schema, SQLiteDb, Subject, SynchronizationConfigLink,\n} from \"@itwin/core-backend\";\nimport {\n ChangeOpCode, Code, CodeProps, CodeSpec, ConcreteEntityTypes, ElementAspectProps, ElementProps, EntityReference, EntityReferenceSet,\n ExternalSourceAspectProps, FontProps, GeometricElement2dProps, GeometricElement3dProps, IModel, IModelError, ModelProps,\n Placement2d, Placement3d, PrimitiveTypeCode, PropertyMetaData, RelatedElement,\n} from \"@itwin/core-common\";\nimport { ExportChangesOptions, ExportSchemaResult, IModelExporter, IModelExporterState, IModelExportHandler } from \"./IModelExporter\";\nimport { IModelImporter, IModelImporterState, OptimizeGeometryOptions } from \"./IModelImporter\";\nimport { TransformerLoggerCategory } from \"./TransformerLoggerCategory\";\nimport { PendingReference, PendingReferenceMap } from \"./PendingReferenceMap\";\nimport { EntityKey, EntityMap } from \"./EntityMap\";\nimport { IModelCloneContext } from \"./IModelCloneContext\";\nimport { EntityUnifier } from \"./EntityUnifier\";\n\nconst loggerCategory: string = TransformerLoggerCategory.IModelTransformer;\n\nconst nullLastProvenanceEntityInfo = {\n entityId: Id64.invalid,\n aspectId: Id64.invalid,\n aspectVersion: \"\",\n aspectKind: ExternalSourceAspect.Kind.Element,\n};\n\ntype EntityTransformHandler = (entity: ConcreteEntity) => ElementProps | ModelProps | RelationshipProps | ElementAspectProps;\n\n/** Options provided to the [[IModelTransformer]] constructor.\n * @beta\n * @note if adding an option, you must explicitly add its serialization to [[IModelTransformer.saveStateToFile]]!\n */\nexport interface IModelTransformOptions {\n /** The Id of the Element in the **target** iModel that represents the **source** repository as a whole and scopes its [ExternalSourceAspect]($backend) instances.\n * When the goal is to consolidate multiple source iModels into a single target iModel, this option must be specified.\n */\n targetScopeElementId?: Id64String;\n\n /** Set to `true` if IModelTransformer should not record its provenance.\n * Provenance tracks a target element back to its corresponding source element and is essential for [[IModelTransformer.processChanges]] to work properly.\n * Turning off IModelTransformer provenance is really only relevant for producing snapshots or another one time transformations.\n * @note See the [[includeSourceProvenance]] option for determining whether existing source provenance is cloned into the target.\n * @note The default is `false` which means that new IModelTransformer provenance will be recorded.\n */\n noProvenance?: boolean;\n\n /** Set to `true` to clone existing source provenance into the target.\n * @note See the [[noProvenance]] option for determining whether new IModelTransformer provenance is recorded.\n * @note The default is `false` which means that existing provenance in the source will not be carried into the target.\n */\n includeSourceProvenance?: boolean;\n\n /** Flag that indicates that the target iModel was created by copying the source iModel.\n * This is common when the target iModel is intended to be a *branch* of the source iModel.\n * This *hint* is essential to properly initialize the source to target element mapping and to cause provenance to be recorded for future synchronizations.\n * @note This *hint* is typically only set for the first synchronization after the iModel was copied since every other synchronization can utilize the provenance.\n */\n wasSourceIModelCopiedToTarget?: boolean;\n\n /** Flag that indicates that the current source and target iModels are now synchronizing in the reverse direction from a prior synchronization.\n * The most common example is to first synchronize master to branch, make changes to the branch, and then reverse directions to synchronize from branch to master.\n * This means that the provenance on the (current) source is used instead.\n * @note This also means that only [[IModelTransformer.processChanges]] can detect deletes.\n */\n isReverseSynchronization?: boolean;\n\n /** Flag that indicates whether or not the transformation process needs to consider the source geometry before cloning/transforming.\n * For standard cases, it is not required to load the source GeometryStream in JavaScript since the cloning happens in native code.\n * Also, the target GeometryStream will be available in JavaScript prior to insert.\n * @note If the source geometry affects the class mapping or transformation logic, then this flag should be set to `true`. The default is `false`.\n * @see [IModelExporter.wantGeometry]($transformer)\n */\n loadSourceGeometry?: boolean;\n\n /** Flag that indicates whether or not the transformation process should clone using binary geometry.\n *\n * Prefer to never to set this flag. If you need geometry changes, instead override [[IModelTransformer.onTransformElement]]\n * and provide an [ElementGeometryBuilderParams]($backend) to the `elementGeometryBuilderParams`\n * property of [ElementProps]($common) instead, it is much faster. You can read geometry during the transformation by setting the\n * [[IModelTransformOptions.loadSourceGeometry]] property to `true`, and passing that to a [GeometryStreamIterator]($common)\n * @note this flag will be deprecated when `elementGeometryBuilderParams` is no longer an alpha API\n *\n * @default true\n */\n cloneUsingBinaryGeometry?: boolean;\n\n /** Flag that indicates that ids should be preserved while copying elements to the target\n * Intended only for pure-filter transforms, so you can keep parts of the source, while deleting others,\n * and element ids are guaranteed to be the same, (other entity ids are not, however)\n * @note The target must be empty.\n * @note It is invalid to insert elements during the transformation, do not use this with transformers that try to.\n * @note This does not preserve the ids of non-element entities such as link table relationships, or aspects, etc.\n * @default false\n * @beta\n */\n preserveElementIdsForFiltering?: boolean;\n\n /** The behavior to use when an element reference (id) is found stored as a reference on an element in the source,\n * but the referenced element does not actually exist in the source.\n * It is possible to craft an iModel with dangling references/invalidated relationships by, e.g., deleting certain\n * elements without fixing up references.\n *\n * @note \"reject\" will throw an error and reject the transformation upon finding this case.\n * @note \"ignore\" passes the issue down to consuming applications, iModels that have invalid element references\n * like this can cause errors, and you should consider adding custom logic in your transformer to remove the\n * reference depending on your use case.\n * @default \"reject\"\n * @beta\n * @deprecated in 3.x. use [[danglingReferencesBehavior]] instead, the use of the term *predecessors* was confusing and became inaccurate when the transformer could handle cycles\n */\n danglingPredecessorsBehavior?: \"reject\" | \"ignore\";\n\n /** The behavior to use when an element reference (id) is found stored as a reference on an element in the source,\n * but the referenced element does not actually exist in the source.\n * It is possible to craft an iModel with dangling references/invalidated relationships by, e.g., deleting certain\n * elements without fixing up references.\n *\n * @note \"reject\" will throw an error and reject the transformation upon finding this case.\n * @note \"ignore\" passes the issue down to consuming applications, iModels that have invalid element references\n * like this can cause errors, and you should consider adding custom logic in your transformer to remove the\n * reference depending on your use case.\n * @default \"reject\"\n * @beta\n */\n danglingReferencesBehavior?: \"reject\" | \"ignore\";\n\n /** If defined, options to be supplied to [[IModelImporter.optimizeGeometry]] by [[IModelTransformer.processChanges]] and [[IModelTransformer.processAll]]\n * as a post-processing step to optimize the geometry in the iModel.\n * @beta\n */\n optimizeGeometry?: OptimizeGeometryOptions;\n}\n\n/**\n * A container for tracking the state of a partially committed entity and finalizing it when it's ready to be fully committed\n * @internal\n */\nclass PartiallyCommittedEntity {\n public constructor(\n /**\n * A set of \"model|element ++ ID64\" pairs, (e.g. `model0x11` or `element0x12`)\n * It is possible for the submodel of an element to be separately resolved from the actual element,\n * so its resolution must be tracked separately\n */\n private _missingReferences: EntityReferenceSet,\n private _onComplete: () => void\n ) {}\n public resolveReference(id: EntityReference) {\n this._missingReferences.delete(id);\n if (this._missingReferences.size === 0)\n this._onComplete();\n }\n public forceComplete() {\n this._onComplete();\n }\n}\n\n/**\n * Apply a function to each Id64 in a supported container type of Id64s.\n * Currently only supports raw Id64String or RelatedElement-like objects containing an `id` property that is a Id64String,\n * which matches the possible containers of references in [Element.requiredReferenceKeys]($backend).\n * @internal\n */\nfunction mapId64<R>(\n idContainer: Id64String | { id: Id64String } | undefined,\n func: (id: Id64String) => R\n): R[] {\n const isId64String = (arg: any): arg is Id64String => {\n const isString = typeof arg === \"string\";\n assert(() => !isString || Id64.isValidId64(arg));\n return isString;\n };\n const isRelatedElem = (arg: any): arg is RelatedElement =>\n arg && typeof arg === \"object\" && \"id\" in arg;\n\n const results = [];\n\n // is a string if compressed or singular id64, but check for singular just checks if it's a string so do this test first\n if (idContainer === undefined) {\n // nothing\n } else if (isId64String(idContainer)) {\n results.push(func(idContainer));\n } else if (isRelatedElem(idContainer)) {\n results.push(func(idContainer.id));\n } else {\n throw Error([\n `Id64 container '${idContainer}' is unsupported.`,\n \"Currently only singular Id64 strings or prop-like objects containing an 'id' property are supported.\",\n ].join(\"\\n\"));\n }\n return results;\n}\n\n/** Arguments you can pass to [[IModelTransformer.initExternalSourceAspects]]\n * @beta\n */\nexport interface InitFromExternalSourceAspectsArgs {\n accessToken?: AccessToken;\n /**\n * Include changes from this changeset up through and including the current changeset.\n * @note To form a range of versions to process, set `startChangeset` for the start (inclusive)\n * of the desired range and open the source iModel as of the end (inclusive) of the desired range.\n * @default the current changeset of the sourceDb, if undefined\n */\n startChangeset?: {\n id?: string;\n index?: number;\n };\n}\n\n/**\n * Arguments for [[IModelTransformer.processChanges]]\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface ProcessChangesOptions extends ExportChangesOptions {\n}\n\n/** Base class used to transform a source iModel into a different target iModel.\n * @see [iModel Transformation and Data Exchange]($docs/learning/transformer/index.md), [IModelExporter]($transformer), [IModelImporter]($transformer)\n * @beta\n */\nexport class IModelTransformer extends IModelExportHandler {\n /** The IModelExporter that will export from the source iModel. */\n public readonly exporter: IModelExporter;\n /** The IModelImporter that will import into the target iModel. */\n public readonly importer: IModelImporter;\n /** The normally read-only source iModel.\n * @note The source iModel will need to be read/write when provenance is being stored during a reverse synchronization.\n */\n public readonly sourceDb: IModelDb;\n /** The read/write target iModel. */\n public readonly targetDb: IModelDb;\n /** The IModelTransformContext for this IModelTransformer. */\n public readonly context: IModelCloneContext;\n /** The Id of the Element in the **target** iModel that represents the **source** repository as a whole and scopes its [ExternalSourceAspect]($backend) instances. */\n public get targetScopeElementId(): Id64String {\n return this._options.targetScopeElementId;\n }\n\n /** map of (unprocessed element, referencing processed element) pairs to the partially committed element that needs the reference resolved\n * and have some helper methods below for now */\n protected _pendingReferences = new PendingReferenceMap<PartiallyCommittedEntity>();\n\n /** map of partially committed entities to their partial commit progress */\n protected _partiallyCommittedEntities = new EntityMap<PartiallyCommittedEntity>();\n\n /** the options that were used to initialize this transformer */\n private readonly _options: MarkRequired<IModelTransformOptions, \"targetScopeElementId\" | \"danglingReferencesBehavior\">;\n\n /** Set if it can be determined whether this is the first source --> target synchronization. */\n private _isFirstSynchronization?: boolean;\n\n /** The element classes that are considered to define provenance in the iModel */\n public static get provenanceElementClasses(): (typeof Entity)[] {\n return [FolderLink, SynchronizationConfigLink, ExternalSource, ExternalSourceAttachment];\n }\n\n /** The element aspect classes that are considered to define provenance in the iModel */\n public static get provenanceElementAspectClasses(): (typeof Entity)[] {\n return [ExternalSourceAspect];\n }\n\n /** Set of entity keys which were not exported and don't need to be tracked for pending reference resolution.\n * @note Currently only tracks elements which were not exported.\n */\n protected _skippedEntities = new Set<EntityKey>();\n\n /** Construct a new IModelTransformer\n * @param source Specifies the source IModelExporter or the source IModelDb that will be used to construct the source IModelExporter.\n * @param target Specifies the target IModelImporter or the target IModelDb that will be used to construct the target IModelImporter.\n * @param options The options that specify how the transformation should be done.\n */\n public constructor(source: IModelDb | IModelExporter, target: IModelDb | IModelImporter, options?: IModelTransformOptions) {\n super();\n // initialize IModelTransformOptions\n this._options = {\n ...options,\n // non-falsy defaults\n cloneUsingBinaryGeometry: options?.cloneUsingBinaryGeometry ?? true,\n targetScopeElementId: options?.targetScopeElementId ?? IModel.rootSubjectId,\n // eslint-disable-next-line deprecation/deprecation\n danglingReferencesBehavior: options?.danglingReferencesBehavior ?? options?.danglingPredecessorsBehavior ?? \"reject\",\n };\n this._isFirstSynchronization = this._options.wasSourceIModelCopiedToTarget ? true : undefined;\n // initialize exporter and sourceDb\n if (source instanceof IModelDb) {\n this.exporter = new IModelExporter(source);\n } else {\n this.exporter = source;\n }\n this.sourceDb = this.exporter.sourceDb;\n this.exporter.registerHandler(this);\n this.exporter.wantGeometry = options?.loadSourceGeometry ?? false; // optimization to not load source GeometryStreams by default\n if (!this._options.includeSourceProvenance) { // clone provenance from the source iModel into the target iModel?\n IModelTransformer.provenanceElementClasses.forEach((cls) => this.exporter.excludeElementClass(cls.classFullName));\n IModelTransformer.provenanceElementAspectClasses.forEach((cls) => this.exporter.excludeElementAspectClass(cls.classFullName));\n }\n this.exporter.excludeElementAspectClass(ChannelRootAspect.classFullName); // Channel boundaries within the source iModel are not relevant to the target iModel\n this.exporter.excludeElementAspectClass(\"BisCore:TextAnnotationData\"); // This ElementAspect is auto-created by the BisCore:TextAnnotation2d/3d element handlers\n // initialize importer and targetDb\n if (target instanceof IModelDb) {\n this.importer = new IModelImporter(target, { preserveElementIdsForFiltering: this._options.preserveElementIdsForFiltering });\n } else {\n this.importer = target;\n /* eslint-disable deprecation/deprecation */\n if (Boolean(this._options.preserveElementIdsForFiltering) !== this.importer.preserveElementIdsForFiltering) {\n Logger.logWarning(\n loggerCategory,\n [\n \"A custom importer was passed as a target but its 'preserveElementIdsForFiltering' option is out of sync with the transformer's option.\",\n \"The custom importer target's option will be force updated to use the transformer's value.\",\n \"This behavior is deprecated and will be removed in a future version, throwing an error if they are out of sync.\",\n ].join(\"\\n\")\n );\n this.importer.preserveElementIdsForFiltering = Boolean(this._options.preserveElementIdsForFiltering);\n }\n /* eslint-enable deprecation/deprecation */\n }\n this.targetDb = this.importer.targetDb;\n // create the IModelCloneContext, it must be initialized later\n this.context = new IModelCloneContext(this.sourceDb, this.targetDb);\n }\n\n /** Dispose any native resources associated with this IModelTransformer. */\n public dispose(): void {\n Logger.logTrace(loggerCategory, \"dispose()\");\n this.context.dispose();\n }\n\n /** Log current settings that affect IModelTransformer's behavior. */\n private logSettings(): void {\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.visitElements=${this.exporter.visitElements}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.visitRelationships=${this.exporter.visitRelationships}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.wantGeometry=${this.exporter.wantGeometry}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.wantSystemSchemas=${this.exporter.wantSystemSchemas}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.wantTemplateModels=${this.exporter.wantTemplateModels}`);\n Logger.logInfo(loggerCategory, `this.targetScopeElementId=${this.targetScopeElementId}`);\n Logger.logInfo(loggerCategory, `this._noProvenance=${this._options.noProvenance}`);\n Logger.logInfo(loggerCategory, `this._includeSourceProvenance=${this._options.includeSourceProvenance}`);\n Logger.logInfo(loggerCategory, `this._cloneUsingBinaryGeometry=${this._options.cloneUsingBinaryGeometry}`);\n Logger.logInfo(loggerCategory, `this._wasSourceIModelCopiedToTarget=${this._options.wasSourceIModelCopiedToTarget}`);\n Logger.logInfo(loggerCategory, `this._isReverseSynchronization=${this._options.isReverseSynchronization}`);\n Logger.logInfo(TransformerLoggerCategory.IModelImporter, `this.importer.autoExtendProjectExtents=${this.importer.options.autoExtendProjectExtents}`);\n Logger.logInfo(TransformerLoggerCategory.IModelImporter, `this.importer.simplifyElementGeometry=${this.importer.options.simplifyElementGeometry}`);\n }\n\n /** Return the IModelDb where IModelTransformer will store its provenance.\n * @note This will be [[targetDb]] except when it is a reverse synchronization. In that case it be [[sourceDb]].\n */\n public get provenanceDb(): IModelDb {\n return this._options.isReverseSynchronization ? this.sourceDb : this.targetDb;\n }\n\n /** Return the IModelDb where IModelTransformer looks for entities referred to by stored provenance.\n * @note This will be [[sourceDb]] except when it is a reverse synchronization. In that case it be [[targetDb]].\n */\n public get provenanceSourceDb(): IModelDb {\n return this._options.isReverseSynchronization ? this.targetDb : this.sourceDb;\n }\n\n /** Create an ExternalSourceAspectProps in a standard way for an Element in an iModel --> iModel transformation. */\n public static initElementProvenanceOptions(\n sourceElementId: Id64String,\n targetElementId: Id64String,\n args: {\n sourceDb: IModelDb;\n isReverseSynchronization: boolean;\n targetScopeElementId: Id64String;\n },\n ): ExternalSourceAspectProps {\n const elementId = args.isReverseSynchronization ? sourceElementId : targetElementId;\n const aspectIdentifier = args.isReverseSynchronization ? targetElementId : sourceElementId;\n const aspectProps: ExternalSourceAspectProps = {\n classFullName: ExternalSourceAspect.classFullName,\n element: { id: elementId, relClassName: ElementOwnsExternalSourceAspects.classFullName },\n scope: { id: args.targetScopeElementId },\n identifier: aspectIdentifier,\n kind: ExternalSourceAspect.Kind.Element,\n version: args.sourceDb.elements.queryLastModifiedTime(sourceElementId),\n };\n return aspectProps;\n }\n\n /** Create an ExternalSourceAspectProps in a standard way for an Element in an iModel --> iModel transformation. */\n private initElementProvenance(sourceElementId: Id64String, targetElementId: Id64String): ExternalSourceAspectProps {\n return IModelTransformer.initElementProvenanceOptions(\n sourceElementId,\n targetElementId,\n {\n isReverseSynchronization: !!this._options.isReverseSynchronization,\n targetScopeElementId: this.targetScopeElementId,\n sourceDb: this.sourceDb,\n },\n );\n }\n\n /** Create an ExternalSourceAspectProps in a standard way for a Relationship in an iModel --> iModel transformations.\n * The ExternalSourceAspect is meant to be owned by the Element in the target iModel that is the `sourceId` of transformed relationship.\n * The `identifier` property of the ExternalSourceAspect will be the ECInstanceId of the relationship in the source iModel.\n * The ECInstanceId of the relationship in the target iModel will be stored in the JsonProperties of the ExternalSourceAspect.\n */\n private initRelationshipProvenance(sourceRelationship: Relationship, targetRelInstanceId: Id64String): ExternalSourceAspectProps {\n const targetRelationship: Relationship = this.targetDb.relationships.getInstance(ElementRefersToElements.classFullName, targetRelInstanceId);\n const elementId = this._options.isReverseSynchronization ? sourceRelationship.sourceId : targetRelationship.sourceId;\n const aspectIdentifier = this._options.isReverseSynchronization ? targetRelInstanceId : sourceRelationship.id;\n const aspectProps: ExternalSourceAspectProps = {\n classFullName: ExternalSourceAspect.classFullName,\n element: { id: elementId, relClassName: ElementOwnsExternalSourceAspects.classFullName },\n scope: { id: this.targetScopeElementId },\n identifier: aspectIdentifier,\n kind: ExternalSourceAspect.Kind.Relationship,\n jsonProperties: JSON.stringify({ targetRelInstanceId }),\n };\n aspectProps.id = this.queryExternalSourceAspectId(aspectProps);\n return aspectProps;\n }\n\n private validateScopeProvenance(): void {\n const aspectProps: ExternalSourceAspectProps = {\n classFullName: ExternalSourceAspect.classFullName,\n element: { id: this.targetScopeElementId, relClassName: ElementOwnsExternalSourceAspects.classFullName },\n scope: { id: IModel.rootSubjectId }, // the root Subject scopes scope elements\n identifier: this._options.isReverseSynchronization ? this.targetDb.iModelId : this.sourceDb.iModelId, // the opposite side of where provenance is stored\n kind: ExternalSourceAspect.Kind.Scope,\n };\n aspectProps.id = this.queryExternalSourceAspectId(aspectProps); // this query includes \"identifier\"\n if (undefined === aspectProps.id) {\n // this query does not include \"identifier\" to find possible conflicts\n const sql = `SELECT ECInstanceId FROM ${ExternalSourceAspect.classFullName} WHERE Element.Id=:elementId AND Scope.Id=:scopeId AND Kind=:kind LIMIT 1`;\n const hasConflictingScope = this.provenanceDb.withPreparedStatement(sql, (statement: ECSqlStatement): boolean => {\n statement.bindId(\"elementId\", aspectProps.element.id);\n statement.bindId(\"scopeId\", aspectProps.scope.id); // this scope.id can never be invalid, we create it above\n statement.bindString(\"kind\", aspectProps.kind);\n return DbResult.BE_SQLITE_ROW === statement.step();\n });\n if (hasConflictingScope) {\n throw new IModelError(IModelStatus.InvalidId, \"Provenance scope conflict\");\n }\n if (!this._options.noProvenance) {\n this.provenanceDb.elements.insertAspect(aspectProps);\n }\n }\n }\n\n private queryExternalSourceAspectId(aspectProps: ExternalSourceAspectProps): Id64String | undefined {\n const sql = `SELECT ECInstanceId FROM ${ExternalSourceAspect.classFullName} WHERE Element.Id=:elementId AND Scope.Id=:scopeId AND Kind=:kind AND Identifier=:identifier LIMIT 1`;\n return this.provenanceDb.withPreparedStatement(sql, (statement: ECSqlStatement): Id64String | undefined => {\n statement.bindId(\"elementId\", aspectProps.element.id);\n if (aspectProps.scope === undefined)\n return undefined; // return undefined instead of binding an invalid id\n statement.bindId(\"scopeId\", aspectProps.scope.id);\n statement.bindString(\"kind\", aspectProps.kind);\n statement.bindString(\"identifier\", aspectProps.identifier);\n return (DbResult.BE_SQLITE_ROW === statement.step()) ? statement.getValue(0).getId() : undefined;\n });\n }\n\n /** Iterate all matching ExternalSourceAspects in the provenance iModel (target unless reverse sync) and call a function for each one. */\n public static forEachTrackedElement(args: {\n provenanceSourceDb: IModelDb;\n provenanceDb: IModelDb;\n targetScopeElementId: Id64String;\n isReverseSynchronization: boolean;\n fn: (sourceElementId: Id64String, targetElementId: Id64String) => void;\n }): void {\n if (!args.provenanceDb.containsClass(ExternalSourceAspect.classFullName)) {\n throw new IModelError(IModelStatus.BadSchema, \"The BisCore schema version of the target database is too old\");\n }\n const sql = `SELECT Identifier,Element.Id FROM ${ExternalSourceAspect.classFullName} WHERE Scope.Id=:scopeId AND Kind=:kind`;\n args.provenanceDb.withPreparedStatement(sql, (statement: ECSqlStatement): void => {\n statement.bindId(\"scopeId\", args.targetScopeElementId);\n statement.bindString(\"kind\", ExternalSourceAspect.Kind.Element);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n const aspectIdentifier: Id64String = statement.getValue(0).getString(); // ExternalSourceAspect.Identifier is of type string\n const elementId: Id64String = statement.getValue(1).getId();\n if (args.isReverseSynchronization) {\n args.fn(elementId, aspectIdentifier); // provenance coming from the sourceDb\n } else {\n args.fn(aspectIdentifier, elementId); // provenance coming from the targetDb\n }\n }\n });\n }\n\n private forEachTrackedElement(fn: (sourceElementId: Id64String, targetElementId: Id64String) => void): void {\n return IModelTransformer.forEachTrackedElement({\n provenanceSourceDb: this._options.isReverseSynchronization ? this.sourceDb : this.targetDb,\n provenanceDb: this.provenanceDb,\n targetScopeElementId: this.targetScopeElementId,\n isReverseSynchronization: !!this._options.isReverseSynchronization,\n fn,\n });\n }\n\n /** Initialize the source to target Element mapping from ExternalSourceAspects in the target iModel.\n * @note This method is called from all `process*` functions and should never need to be called directly.\n * @deprecated in 3.x. call [[initialize]] instead, it does the same thing among other initialization\n * @note Passing an [[InitFromExternalSourceAspectsArgs]] is required when processing changes, to remap any elements that may have been deleted.\n * You must await the returned promise as well in this case. The synchronous behavior has not changed but is deprecated and won't process everything.\n */\n public initFromExternalSourceAspects(args?: InitFromExternalSourceAspectsArgs): void | Promise<void> {\n this.forEachTrackedElement((sourceElementId: Id64String, targetElementId: Id64String) => {\n this.context.remapElement(sourceElementId, targetElementId);\n });\n\n if (args)\n return this.remapDeletedSourceElements(args);\n }\n\n /** When processing deleted elements in a reverse synchronization, the [[provenanceDb]] (usually a branch iModel) has already\n * deleted the [ExternalSourceAspect]($backend)s that tell us which elements in the reverse synchronization target (usually\n * a master iModel) should be deleted. We must use the changesets to get the values of those before they were deleted.\n */\n private async remapDeletedSourceElements(args: InitFromExternalSourceAspectsArgs) {\n // we need a connected iModel with changes to remap elements with deletions\n if (this.sourceDb.iTwinId === undefined)\n return;\n\n try {\n\n const startChangesetIndexOrId\n = args.startChangeset?.index\n ?? args.startChangeset?.id\n ?? this.sourceDb.changeset.index\n ?? this.sourceDb.changeset.id;\n const endChangesetId = this.sourceDb.changeset.id;\n\n const [firstChangesetIndex, endChangesetIndex] = await Promise.all(\n ([startChangesetIndexOrId, endChangesetId])\n .map(async (indexOrId) => typeof indexOrId === \"number\"\n ? indexOrId\n : IModelHost.hubAccess\n .queryChangeset({\n iModelId: this.sourceDb.iModelId,\n // eslint-disable-next-line deprecation/deprecation\n changeset: { id: indexOrId },\n accessToken: args.accessToken,\n })\n .then((changeset) => changeset.index)\n )\n );\n\n const changesetIds = await ChangeSummaryManager.createChangeSummaries({\n accessToken: args.accessToken,\n iModelId: this.sourceDb.iModelId,\n iTwinId: this.sourceDb.iTwinId,\n range: { first: firstChangesetIndex, end: endChangesetIndex },\n });\n\n ChangeSummaryManager.attachChangeCache(this.sourceDb);\n for (const changesetId of changesetIds) {\n this.sourceDb.withPreparedStatement(\n `\n SELECT esac.Element.Id, esac.Identifier\n FROM ecchange.change.InstanceChange ic\n JOIN BisCore.ExternalSourceAspect.Changes(:changesetId, 'BeforeDelete') esac\n ON ic.ChangedInstance.Id=esac.ECInstanceId\n WHERE ic.OpCode=:opcode\n AND ic.Summary.Id=:changesetId\n AND esac.Scope.Id=:targetScopeElementId\n -- not yet documented ecsql feature to check class id\n AND ic.ChangedInstance.ClassId IS (ONLY BisCore.ExternalSourceAspect)\n `,\n (stmt) => {\n stmt.bindInteger(\"opcode\", ChangeOpCode.Delete);\n stmt.bindInteger(\"changesetId\", changesetId);\n stmt.bindInteger(\"targetScopeElementId\", this.targetScopeElementId);\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\n const targetId = stmt.getValue(0).getId();\n const sourceId: Id64String = stmt.getValue(1).getString(); // BisCore.ExternalSourceAspect.Identifier stores a hex Id64String\n // TODO: maybe delete and don't just remap\n this.context.remapElement(targetId, sourceId);\n }\n }\n );\n }\n } finally {\n if (ChangeSummaryManager.isChangeCacheAttached(this.sourceDb))\n ChangeSummaryManager.detachChangeCache(this.sourceDb);\n }\n }\n\n /** Returns `true` if *brute force* delete detections should be run.\n * @note Not relevant for processChanges when change history is known.\n */\n private shouldDetectDeletes(): boolean {\n if (this._isFirstSynchronization)\n return false; // not necessary the first time since there are no deletes to detect\n\n if (this._options.isReverseSynchronization)\n return false; // not possible for a reverse synchronization since provenance will be deleted when element is deleted\n\n return true;\n }\n\n /** Detect Element deletes using ExternalSourceAspects in the target iModel and a *brute force* comparison against Elements in the source iModel.\n * @see processChanges\n * @note This method is called from [[processAll]] and is not needed by [[processChanges]], so it only needs to be called directly when processing a subset of an iModel.\n * @throws [[IModelError]] If the required provenance information is not available to detect deletes.\n */\n public async detectElementDeletes(): Promise<void> {\n if (this._options.isReverseSynchronization) {\n throw new IModelError(IModelStatus.BadRequest, \"Cannot detect deletes when isReverseSynchronization=true\");\n }\n const targetElementsToDelete: Id64String[] = [];\n this.forEachTrackedElement((sourceElementId: Id64String, targetElementId: Id64String) => {\n if (undefined === this.sourceDb.elements.tryGetElementProps(sourceElementId)) {\n // if the sourceElement is not found, then it must have been deleted, so propagate the delete to the target iModel\n targetElementsToDelete.push(targetElementId);\n }\n });\n targetElementsToDelete.forEach((targetElementId: Id64String) => {\n try {\n // TODO: make it possible to delete more elements at once to prevent redundant expensive\n // element reference scanning\n this.importer.deleteElement(targetElementId);\n } catch (err: any) {\n // ignore not found elements, iterative element tree deletion might have already deleted them\n if (err.name !== \"Not Found\")\n throw err;\n }\n });\n }\n\n /**\n * @deprecated in 3.x, this no longer has any effect except emitting a warning\n */\n protected skipElement(_sourceElement: Element): void {\n Logger.logWarning(loggerCategory, `Tried to defer/skip an element, which is no longer necessary`);\n }\n\n /** Transform the specified sourceElement into ElementProps for the target iModel.\n * @param sourceElement The Element from the source iModel to transform.\n * @returns ElementProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n * @note This can be called more than once for an element in arbitrary order, so it should not have side-effects.\n */\n public onTransformElement(sourceElement: Element): ElementProps {\n Logger.logTrace(loggerCategory, `onTransformElement(${sourceElement.id}) \"${sourceElement.getDisplayLabel()}\"`);\n const targetElementProps: ElementProps = this.context.cloneElement(sourceElement, { binaryGeometry: this._options.cloneUsingBinaryGeometry });\n if (sourceElement instanceof Subject) {\n if (targetElementProps.jsonProperties?.Subject?.Job) {\n // don't propagate source channels into target (legacy bridge case)\n targetElementProps.jsonProperties.Subject.Job = undefined;\n }\n }\n return targetElementProps;\n }\n\n /** Returns true if a change within sourceElement is detected.\n * @param sourceElement The Element from the source iModel\n * @param targetElementId The Element from the target iModel to compare against.\n * @note A subclass can override this method to provide custom change detection behavior.\n */\n protected hasElementChanged(sourceElement: Element, targetElementId: Id64String): boolean {\n const sourceAspects = this.targetDb.elements.getAspects(targetElementId, ExternalSourceAspect.classFullName) as ExternalSourceAspect[];\n for (const sourceAspect of sourceAspects) {\n if (sourceAspect.scope === undefined) // if the scope was lost, we can't correlate so assume it changed\n return true;\n if (\n sourceAspect.identifier === sourceElement.id &&\n sourceAspect.scope.id === this.targetScopeElementId &&\n sourceAspect.kind === ExternalSourceAspect.Kind.Element\n ) {\n const lastModifiedTime = sourceElement.iModel.elements.queryLastModifiedTime(sourceElement.id);\n return lastModifiedTime !== sourceAspect.version;\n }\n }\n return true;\n }\n\n private static transformCallbackFor(transformer: IModelTransformer, entity: ConcreteEntity): EntityTransformHandler {\n if (entity instanceof Element)\n return transformer.onTransformElement as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else if (entity instanceof Element)\n return transformer.onTransformModel as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else if (entity instanceof Relationship)\n return transformer.onTransformRelationship as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else if (entity instanceof ElementAspect)\n return transformer.onTransformElementAspect as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else\n assert(false, `unreachable; entity was '${entity.constructor.name}' not an Element, Relationship, or ElementAspect`);\n }\n\n /** callback to perform when a partial element says it's ready to be completed\n * transforms the source element with all references now valid, then updates the partial element with the results\n */\n private makePartialEntityCompleter(\n sourceEntity: ConcreteEntity\n ) {\n return () => {\n const targetId = this.context.findTargetEntityId(EntityReferences.from(sourceEntity));\n if (!EntityReferences.isValid(targetId))\n throw Error(`${sourceEntity.id} has not been inserted into the target yet, the completer is invalid. This is a bug.`);\n const onEntityTransform = IModelTransformer.transformCallbackFor(this, sourceEntity);\n const updateEntity = EntityUnifier.updaterFor(this.targetDb, sourceEntity);\n const targetProps = onEntityTransform.call(this, sourceEntity);\n if (sourceEntity instanceof Relationship) {\n (targetProps as RelationshipProps).sourceId = this.context.findTargetElementId(sourceEntity.sourceId);\n (targetProps as RelationshipProps).targetId = this.context.findTargetElementId(sourceEntity.targetId);\n }\n updateEntity({ ...targetProps, id: EntityReferences.toId64(targetId) });\n this._partiallyCommittedEntities.delete(sourceEntity);\n };\n }\n\n /** collect references this entity has that are yet to be mapped, and if there are any\n * create a [[PartiallyCommittedEntity]] to track resolution of those references\n */\n private collectUnmappedReferences(entity: ConcreteEntity) {\n const missingReferences = new EntityReferenceSet();\n let thisPartialElem: PartiallyCommittedEntity | undefined;\n\n // eslint-disable-next-line deprecation/deprecation\n for (const referenceId of entity.getReferenceConcreteIds()) {\n // TODO: probably need to rename from 'id' to 'ref' so these names aren't so ambiguous\n const referenceIdInTarget = this.context.findTargetEntityId(referenceId);\n const alreadyProcessed = EntityReferences.isValid(referenceIdInTarget) || this._skippedEntities.has(referenceId);\n if (alreadyProcessed)\n continue;\n Logger.logTrace(loggerCategory, `Deferring resolution of reference '${referenceId}' of element '${entity.id}'`);\n const referencedExistsInSource = EntityUnifier.exists(this.sourceDb, { entityReference: referenceId });\n if (!referencedExistsInSource) {\n Logger.logWarning(loggerCategory, `Source ${EntityUnifier.getReadableType(entity)} (${entity.id}) has a dangling reference to (${referenceId})`);\n switch (this._options.danglingReferencesBehavior) {\n case \"ignore\":\n continue;\n case \"reject\":\n throw new IModelError(\n IModelStatus.NotFound,\n [\n `Found a reference to an element \"${referenceId}\" that doesn't exist while looking for references of \"${entity.id}\".`,\n \"This must have been caused by an upstream application that changed the iModel.\",\n \"You can set the IModelTransformerOptions.danglingReferencesBehavior option to 'ignore' to ignore this, but this will leave the iModel\",\n \"in a state where downstream consuming applications will need to handle the invalidity themselves. In some cases, writing a custom\",\n \"transformer to remove the reference and fix affected elements may be suitable.\",\n ].join(\"\\n\")\n );\n }\n }\n if (thisPartialElem === undefined) {\n thisPartialElem = new PartiallyCommittedEntity(missingReferences, this.makePartialEntityCompleter(entity));\n if (!this._partiallyCommittedEntities.has(entity))\n this._partiallyCommittedEntities.set(entity, thisPartialElem);\n }\n missingReferences.add(referenceId);\n const entityReference = EntityReferences.from(entity);\n this._pendingReferences.set({ referenced: referenceId, referencer: entityReference }, thisPartialElem);\n }\n }\n\n /** Cause the specified Element and its child Elements (if applicable) to be exported from the source iModel and imported into the target iModel.\n * @param sourceElementId Identifies the Element from the source iModel to import.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processElement(sourceElementId: Id64String): Promise<void> {\n await this.initialize();\n if (sourceElementId === IModel.rootSubjectId) {\n throw new IModelError(IModelStatus.BadRequest, \"The root Subject should not be directly imported\");\n }\n return this.exporter.exportElement(sourceElementId);\n }\n\n /** Import child elements into the target IModelDb\n * @param sourceElementId Import the child elements of this element in the source IModelDb.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processChildElements(sourceElementId: Id64String): Promise<void> {\n await this.initialize();\n return this.exporter.exportChildElements(sourceElementId);\n }\n\n /** Override of [IModelExportHandler.shouldExportElement]($transformer) that is called to determine if an element should be exported from the source iModel.\n * @note Reaching this point means that the element has passed the standard exclusion checks in IModelExporter.\n */\n public override shouldExportElement(_sourceElement: Element): boolean { return true; }\n\n public override onSkipElement(sourceElementId: Id64String): void {\n if (this.context.findTargetElementId(sourceElementId) !== Id64.invalid) {\n // element already has provenance\n return;\n }\n\n Logger.logInfo(loggerCategory, `Element '${sourceElementId}' won't be exported. Marking its references as resolved`);\n const elementKey: EntityKey = `e${sourceElementId}`;\n this._skippedEntities.add(elementKey);\n\n // Mark any existing pending references to the skipped element as resolved.\n for (const referencer of this._pendingReferences.getReferencersByEntityKey(elementKey)) {\n const key = PendingReference.from(referencer, elementKey);\n const pendingRef = this._pendingReferences.get(key);\n if (!pendingRef)\n continue;\n pendingRef.resolveReference(elementKey);\n this._pendingReferences.delete(key);\n }\n }\n\n /**\n * If they haven't been already, import all of the required references\n * @internal do not call, override or implement this, it will be removed\n */\n public override async preExportElement(sourceElement: Element): Promise<void> {\n const elemClass = sourceElement.constructor as typeof Element;\n\n const unresolvedReferences = elemClass.requiredReferenceKeys\n .map((referenceKey) => {\n const idContainer = sourceElement[referenceKey as keyof Element];\n const referenceType = elemClass.requiredReferenceKeyTypeMap[referenceKey];\n // For now we just consider all required references to be elements (as they are in biscore), and do not support\n // entities that refuse to be inserted without a different kind of entity (e.g. aspect or relationship) first being inserted\n assert(referenceType === ConcreteEntityTypes.Element || referenceType === ConcreteEntityTypes.Model);\n return mapId64(idContainer, (id) => {\n if (id === Id64.invalid || id === IModel.rootSubjectId)\n return undefined; // not allowed to directly export the root subject\n if (!this.context.isBetweenIModels) {\n // Within the same iModel, can use existing DefinitionElements without remapping\n // This is relied upon by the TemplateModelCloner\n // TODO: extract this out to only be in the TemplateModelCloner\n const asDefinitionElem = this.sourceDb.elements.tryGetElement(id, DefinitionElement);\n if (asDefinitionElem && !(asDefinitionElem instanceof RecipeDefinitionElement)) {\n this.context.remapElement(id, id);\n }\n }\n return id;\n })\n .filter((sourceReferenceId: Id64String | undefined): sourceReferenceId is Id64String => {\n if (sourceReferenceId === undefined)\n return false;\n const referenceInTargetId = this.context.findTargetElementId(sourceReferenceId);\n const isInTarget = Id64.isValid(referenceInTargetId);\n return !isInTarget;\n });\n })\n .flat();\n\n if (unresolvedReferences.length > 0) {\n for (const reference of unresolvedReferences) {\n const processState = this.getElemTransformState(reference);\n // must export element first\n if (processState.needsElemImport)\n await this.exporter.exportElement(reference);\n if (processState.needsModelImport)\n await this.exporter.exportModel(reference);\n }\n }\n }\n\n private getElemTransformState(elementId: Id64String) {\n const dbHasModel = (db: IModelDb, id: Id64String) => {\n const maybeModelId = EntityReferences.fromEntityType(id, ConcreteEntityTypes.Model);\n return EntityUnifier.exists(db, { entityReference: maybeModelId });\n };\n const isSubModeled = dbHasModel(this.sourceDb, elementId);\n const idOfElemInTarget = this.context.findTargetElementId(elementId);\n const isElemInTarget = Id64.invalid !== idOfElemInTarget;\n const needsModelImport = isSubModeled && (!isElemInTarget || !dbHasModel(this.targetDb, idOfElemInTarget));\n return { needsElemImport: !isElemInTarget, needsModelImport };\n }\n\n /** Override of [IModelExportHandler.onExportElement]($transformer) that imports an element into the target iModel when it is exported from the source iModel.\n * This override calls [[onTransformElement]] and then [IModelImporter.importElement]($transformer) to update the target iModel.\n */\n public override onExportElement(sourceElement: Element): void {\n let targetElementId: Id64String | undefined;\n let targetElementProps: ElementProps;\n if (this._options.preserveElementIdsForFiltering) {\n targetElementId = sourceElement.id;\n targetElementProps = this.onTransformElement(sourceElement);\n } else if (this._options.wasSourceIModelCopiedToTarget) {\n targetElementId = sourceElement.id;\n targetElementProps = this.targetDb.elements.getElementProps(targetElementId);\n } else {\n targetElementId = this.context.findTargetElementId(sourceElement.id);\n targetElementProps = this.onTransformElement(sourceElement);\n }\n // if an existing remapping was not yet found, check by Code as long as the CodeScope is valid (invalid means a missing reference so not worth checking)\n if (!Id64.isValidId64(targetElementId) && Id64.isValidId64(targetElementProps.code.scope)) {\n // respond the same way to undefined code value as the @see Code class, but don't use that class because is trims\n // whitespace from the value, and there are iModels out there with untrimmed whitespace that we ought not to trim\n targetElementProps.code.value = targetElementProps.code.value ?? \"\";\n targetElementId = this.targetDb.elements.queryElementIdByCode(targetElementProps.code as Required<CodeProps>);\n if (undefined !== targetElementId) {\n const targetElement: Element = this.targetDb.elements.getElement(targetElementId);\n if (targetElement.classFullName === targetElementProps.classFullName) { // ensure code remapping doesn't change the target class\n this.context.remapElement(sourceElement.id, targetElementId); // record that the targetElement was found by Code\n } else {\n targetElementId = undefined;\n targetElementProps.code = Code.createEmpty(); // clear out invalid code\n }\n }\n }\n if (undefined !== targetElementId && Id64.isValidId64(targetElementId)) {\n // compare LastMod of sourceElement to ExternalSourceAspect of targetElement to see there are changes to import\n if (!this.hasElementChanged(sourceElement, targetElementId)) {\n return;\n }\n }\n\n this.collectUnmappedReferences(sourceElement);\n\n // TODO: untangle targetElementId state...\n if (targetElementId === Id64.invalid)\n targetElementId = undefined;\n\n targetElementProps.id = targetElementId; // targetElementId will be valid (indicating update) or undefined (indicating insert)\n if (!this._options.wasSourceIModelCopiedToTarget) {\n this.importer.importElement(targetElementProps); // don't need to import if iModel was copied\n }\n this.context.remapElement(sourceElement.id, targetElementProps.id!); // targetElementProps.id assigned by importElement\n // now that we've mapped this elem we can fix unmapped references to it\n this.resolvePendingReferences(sourceElement);\n\n if (!this._options.noProvenance) {\n const aspectProps: ExternalSourceAspectProps = this.initElementProvenance(sourceElement.id, targetElementProps.id!);\n let aspectId = this.queryExternalSourceAspectId(aspectProps);\n if (aspectId === undefined) {\n aspectId = this.provenanceDb.elements.insertAspect(aspectProps);\n } else {\n this.provenanceDb.elements.updateAspect(aspectProps);\n }\n aspectProps.id = aspectId;\n this.markLastProvenance(aspectProps as MarkRequired<ExternalSourceAspectProps, \"id\">, { isRelationship: false });\n }\n }\n\n private resolvePendingReferences(entity: ConcreteEntity) {\n for (const referencer of this._pendingReferences.getReferencers(entity)) {\n const key = PendingReference.from(referencer, entity);\n const pendingRef = this._pendingReferences.get(key);\n if (!pendingRef)\n continue;\n pendingRef.resolveReference(EntityReferences.from(entity));\n this._pendingReferences.delete(key);\n }\n }\n\n /** Override of [IModelExportHandler.onDeleteElement]($transformer) that is called when [IModelExporter]($transformer) detects that an Element has been deleted from the source iModel.\n * This override propagates the delete to the target iModel via [IModelImporter.deleteElement]($transformer).\n */\n public override onDeleteElement(sourceElementId: Id64String): void {\n const targetElementId: Id64String = this.context.findTargetElementId(sourceElementId);\n if (Id64.isValidId64(targetElementId)) {\n this.importer.deleteElement(targetElementId);\n }\n }\n\n /** Override of [IModelExportHandler.onExportModel]($transformer) that is called when a Model should be exported from the source iModel.\n * This override calls [[onTransformModel]] and then [IModelImporter.importModel]($transformer) to update the target iModel.\n */\n public override onExportModel(sourceModel: Model): void {\n if (IModel.repositoryModelId === sourceModel.id) {\n return; // The RepositoryModel should not be directly imported\n }\n const targetModeledElementId: Id64String = this.context.findTargetElementId(sourceModel.id);\n const targetModelProps: ModelProps = this.onTransformModel(sourceModel, targetModeledElementId);\n this.importer.importModel(targetModelProps);\n this.resolvePendingReferences(sourceModel);\n }\n\n /** Override of [IModelExportHandler.onDeleteModel]($transformer) that is called when [IModelExporter]($transformer) detects that a [Model]($backend) has been deleted from the source iModel. */\n public override onDeleteModel(sourceModelId: Id64String): void {\n // It is possible and apparently occasionally sensical to delete a model without deleting its underlying element.\n // - If only the model is deleted, [[initFromExternalSourceAspects]] will have already remapped the underlying element since it still exists.\n // - If both were deleted, [[remapDeletedSourceElements]] will find and remap the deleted element making this operation valid\n const targetModelId: Id64String = this.context.findTargetElementId(sourceModelId);\n if (Id64.isValidId64(targetModelId)) {\n this.importer.deleteModel(targetModelId);\n }\n }\n\n /** Cause the model container, contents, and sub-models to be exported from the source iModel and imported into the target iModel.\n * @param sourceModeledElementId Import this [Model]($backend) from the source IModelDb.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processModel(sourceModeledElementId: Id64String): Promise<void> {\n await this.initialize();\n return this.exporter.exportModel(sourceModeledElementId);\n }\n\n /** Cause the model contents to be exported from the source iModel and imported into the target iModel.\n * @param sourceModelId Import the contents of this model from the source IModelDb.\n * @param targetModelId Import into this model in the target IModelDb. The target model must exist prior to this call.\n * @param elementClassFullName Optional classFullName of an element subclass to limit import query against the source model.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processModelContents(sourceModelId: Id64String, targetModelId: Id64String, elementClassFullName: string = Element.classFullName): Promise<void> {\n await this.initialize();\n this.targetDb.models.getModel(targetModelId); // throws if Model does not exist\n this.context.remapElement(sourceModelId, targetModelId); // set remapping in case importModelContents is called directly\n return this.exporter.exportModelContents(sourceModelId, elementClassFullName);\n }\n\n /** Cause all sub-models that recursively descend from the specified Subject to be exported from the source iModel and imported into the target iModel. */\n private async processSubjectSubModels(sourceSubjectId: Id64String): Promise<void> {\n await this.initialize();\n // import DefinitionModels first\n const childDefinitionPartitionSql = `SELECT ECInstanceId FROM ${DefinitionPartition.classFullName} WHERE Parent.Id=:subjectId`;\n await this.sourceDb.withPreparedStatement(childDefinitionPartitionSql, async (statement: ECSqlStatement) => {\n statement.bindId(\"subjectId\", sourceSubjectId);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n await this.processModel(statement.getValue(0).getId());\n }\n });\n // import other partitions next\n const childPartitionSql = `SELECT ECInstanceId FROM ${InformationPartitionElement.classFullName} WHERE Parent.Id=:subjectId`;\n await this.sourceDb.withPreparedStatement(childPartitionSql, async (statement: ECSqlStatement) => {\n statement.bindId(\"subjectId\", sourceSubjectId);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n const modelId: Id64String = statement.getValue(0).getId();\n const model: Model = this.sourceDb.models.getModel(modelId);\n if (!(model instanceof DefinitionModel)) {\n await this.processModel(modelId);\n }\n }\n });\n // recurse into child Subjects\n const childSubjectSql = `SELECT ECInstanceId FROM ${Subject.classFullName} WHERE Parent.Id=:subjectId`;\n await this.sourceDb.withPreparedStatement(childSubjectSql, async (statement: ECSqlStatement) => {\n statement.bindId(\"subjectId\", sourceSubjectId);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n await this.processSubjectSubModels(statement.getValue(0).getId());\n }\n });\n }\n\n /** Transform the specified sourceModel into ModelProps for the target iModel.\n * @param sourceModel The Model from the source iModel to be transformed.\n * @param targetModeledElementId The transformed Model will *break down* or *detail* this Element in the target iModel.\n * @returns ModelProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n */\n public onTransformModel(sourceModel: Model, targetModeledElementId: Id64String): ModelProps {\n const targetModelProps: ModelProps = sourceModel.toJSON();\n // don't directly edit deep object since toJSON performs a shallow clone\n targetModelProps.modeledElement = { ...targetModelProps.modeledElement, id: targetModeledElementId };\n targetModelProps.id = targetModeledElementId;\n targetModelProps.parentModel = this.context.findTargetElementId(targetModelProps.parentModel!);\n return targetModelProps;\n }\n\n /** Import elements that were deferred in a prior pass.\n * @deprecated in 3.x. This method is no longer necessary since the transformer no longer needs to defer elements\n */\n public async processDeferredElements(_numRetries: number = 3): Promise<void> {}\n\n private finalizeTransformation() {\n if (this._partiallyCommittedEntities.size > 0) {\n Logger.logWarning(\n loggerCategory,\n [\n \"The following elements were never fully resolved:\",\n [...this._partiallyCommittedEntities.keys()].join(\",\"),\n \"This indicates that either some references were excluded from the transformation\",\n \"or the source has dangling references.\",\n ].join(\"\\n\")\n );\n for (const partiallyCommittedElem of this._partiallyCommittedEntities.values()) {\n partiallyCommittedElem.forceComplete();\n }\n }\n }\n\n /** Imports all relationships that subclass from the specified base class.\n * @param baseRelClassFullName The specified base relationship class.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processRelationships(baseRelClassFullName: string): Promise<void> {\n await this.initialize();\n return this.exporter.exportRelationships(baseRelClassFullName);\n }\n\n /** Override of [IModelExportHandler.shouldExportRelationship]($transformer) that is called to determine if a [Relationship]($backend) should be exported.\n * @note Reaching this point means that the relationship has passed the standard exclusion checks in [IModelExporter]($transformer).\n */\n public override shouldExportRelationship(_sourceRelationship: Relationship): boolean { return true; }\n\n /** Override of [IModelExportHandler.onExportRelationship]($transformer) that imports a relationship into the target iModel when it is exported from the source iModel.\n * This override calls [[onTransformRelationship]] and then [IModelImporter.importRelationship]($transformer) to update the target iModel.\n */\n public override onExportRelationship(sourceRelationship: Relationship): void {\n const targetRelationshipProps: RelationshipProps = this.onTransformRelationship(sourceRelationship);\n const targetRelationshipInstanceId: Id64String = this.importer.importRelationship(targetRelationshipProps);\n if (!this._options.noProvenance && Id64.isValidId64(targetRelationshipInstanceId)) {\n const aspectProps: ExternalSourceAspectProps = this.initRelationshipProvenance(sourceRelationship, targetRelationshipInstanceId);\n if (undefined === aspectProps.id) {\n aspectProps.id = this.provenanceDb.elements.insertAspect(aspectProps);\n }\n assert(aspectProps.id !== undefined);\n this.markLastProvenance(aspectProps as MarkRequired<ExternalSourceAspectProps, \"id\">, { isRelationship: true });\n }\n }\n\n /** Override of [IModelExportHandler.onDeleteRelationship]($transformer) that is called when [IModelExporter]($transformer) detects that a [Relationship]($backend) has been deleted from the source iModel.\n * This override propagates the delete to the target iModel via [IModelImporter.deleteRelationship]($transformer).\n */\n public override onDeleteRelationship(sourceRelInstanceId: Id64String): void {\n const sql = `SELECT ECInstanceId,JsonProperties FROM ${ExternalSourceAspect.classFullName} aspect` +\n ` WHERE aspect.Scope.Id=:scopeId AND aspect.Kind=:kind AND aspect.Identifier=:identifier LIMIT 1`;\n this.targetDb.withPreparedStatement(sql, (statement: ECSqlStatement): void => {\n statement.bindId(\"scopeId\", this.targetScopeElementId);\n statement.bindString(\"kind\", ExternalSourceAspect.Kind.Relationship);\n statement.bindString(\"identifier\", sourceRelInstanceId);\n if (DbResult.BE_SQLITE_ROW === statement.step()) {\n const json: any = JSON.parse(statement.getValue(1).getString());\n if (undefined !== json.targetRelInstanceId) {\n const targetRelationship = this.targetDb.relationships.tryGetInstance(ElementRefersToElements.classFullName, json.targetRelInstanceId);\n if (targetRelationship) {\n this.importer.deleteRelationship(targetRelationship.toJSON());\n }\n this.targetDb.elements.deleteAspect(statement.getValue(0).getId());\n }\n }\n });\n }\n\n private _yieldManager = new YieldManager();\n\n /** Detect Relationship deletes using ExternalSourceAspects in the target iModel and a *brute force* comparison against relationships in the source iModel.\n * @see processChanges\n * @note This method is called from [[processAll]] and is not needed by [[processChanges]], so it only needs to be called directly when processing a subset of an iModel.\n * @throws [[IModelError]] If the required provenance information is not available to detect deletes.\n */\n public async detectRelationshipDeletes(): Promise<void> {\n if (this._options.isReverseSynchronization) {\n throw new IModelError(IModelStatus.BadRequest, \"Cannot detect deletes when isReverseSynchronization=true\");\n }\n const aspectDeleteIds: Id64String[] = [];\n const sql = `SELECT ECInstanceId,Identifier,JsonProperties FROM ${ExternalSourceAspect.classFullName} aspect WHERE aspect.Scope.Id=:scopeId AND aspect.Kind=:kind`;\n await this.targetDb.withPreparedStatement(sql, async (statement: ECSqlStatement) => {\n statement.bindId(\"scopeId\", this.targetScopeElementId);\n statement.bindString(\"kind\", ExternalSourceAspect.Kind.Relationship);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n const sourceRelInstanceId: Id64String = Id64.fromJSON(statement.getValue(1).getString());\n if (undefined === this.sourceDb.relationships.tryGetInstanceProps(ElementRefersToElements.classFullName, sourceRelInstanceId)) {\n const json: any = JSON.parse(statement.getValue(2).getString());\n if (undefined !== json.targetRelInstanceId) {\n const targetRelationship: Relationship = this.targetDb.relationships.getInstance(ElementRefersToElements.classFullName, json.targetRelInstanceId);\n this.importer.deleteRelationship(targetRelationship.toJSON());\n }\n aspectDeleteIds.push(statement.getValue(0).getId());\n }\n await this._yieldManager.allowYield();\n }\n });\n this.targetDb.elements.deleteAspect(aspectDeleteIds);\n }\n\n /** Transform the specified sourceRelationship into RelationshipProps for the target iModel.\n * @param sourceRelationship The Relationship from the source iModel to be transformed.\n * @returns RelationshipProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n */\n protected onTransformRelationship(sourceRelationship: Relationship): RelationshipProps {\n const targetRelationshipProps: RelationshipProps = sourceRelationship.toJSON();\n targetRelationshipProps.sourceId = this.context.findTargetElementId(sourceRelationship.sourceId);\n targetRelationshipProps.targetId = this.context.findTargetElementId(sourceRelationship.targetId);\n sourceRelationship.forEachProperty((propertyName: string, propertyMetaData: PropertyMetaData) => {\n if ((PrimitiveTypeCode.Long === propertyMetaData.primitiveType) && (\"Id\" === propertyMetaData.extendedType)) {\n (targetRelationshipProps as any)[propertyName] = this.context.findTargetElementId(sourceRelationship.asAny[propertyName]);\n }\n });\n return targetRelationshipProps;\n }\n\n /** Override of [IModelExportHandler.onExportElementUniqueAspect]($transformer) that imports an ElementUniqueAspect into the target iModel when it is exported from the source iModel.\n * This override calls [[onTransformElementAspect]] and then [IModelImporter.importElementUniqueAspect]($transformer) to update the target iModel.\n */\n public override onExportElementUniqueAspect(sourceAspect: ElementUniqueAspect): void {\n const targetElementId: Id64String = this.context.findTargetElementId(sourceAspect.element.id);\n const targetAspectProps = this.onTransformElementAspect(sourceAspect, targetElementId);\n this.collectUnmappedReferences(sourceAspect);\n const targetId = this.importer.importElementUniqueAspect(targetAspectProps);\n this.context.remapElementAspect(sourceAspect.id, targetId);\n this.resolvePendingReferences(sourceAspect);\n }\n\n /** Override of [IModelExportHandler.onExportElementMultiAspects]($transformer) that imports ElementMultiAspects into the target iModel when they are exported from the source iModel.\n * This override calls [[onTransformElementAspect]] for each ElementMultiAspect and then [IModelImporter.importElementMultiAspects]($transformer) to update the target iModel.\n * @note ElementMultiAspects are handled as a group to make it easier to differentiate between insert, update, and delete.\n */\n public override onExportElementMultiAspects(sourceAspects: ElementMultiAspect[]): void {\n const targetElementId: Id64String = this.context.findTargetElementId(sourceAspects[0].element.id);\n // Transform source ElementMultiAspects into target ElementAspectProps\n const targetAspectPropsArray = sourceAspects.map((srcA) => this.onTransformElementAspect(srcA, targetElementId));\n sourceAspects.forEach((a) => this.collectUnmappedReferences(a));\n // const targetAspectsToImport = targetAspectPropsArray.filter((targetAspect, i) => hasEntityChanged(sourceAspects[i], targetAspect));\n const targetIds = this.importer.importElementMultiAspects(targetAspectPropsArray, (a) => {\n const isExternalSourceAspectFromTransformer = a instanceof ExternalSourceAspect && a.scope?.id === this.targetScopeElementId;\n return !this._options.includeSourceProvenance || !isExternalSourceAspectFromTransformer;\n });\n for (let i = 0; i < targetIds.length; ++i) {\n this.context.remapElementAspect(sourceAspects[i].id, targetIds[i]);\n this.resolvePendingReferences(sourceAspects[i]);\n }\n }\n\n /** Transform the specified sourceElementAspect into ElementAspectProps for the target iModel.\n * @param sourceElementAspect The ElementAspect from the source iModel to be transformed.\n * @param _targetElementId The ElementId of the target Element that will own the ElementAspects after transformation.\n * @returns ElementAspectProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n */\n protected onTransformElementAspect(sourceElementAspect: ElementAspect, _targetElementId: Id64String): ElementAspectProps {\n const targetElementAspectProps = this.context.cloneElementAspect(sourceElementAspect);\n return targetElementAspectProps;\n }\n\n /** The directory where schemas will be exported, a random temporary directory */\n protected _schemaExportDir: string = path.join(KnownLocations.tmpdir, Guid.createValue());\n\n /** Override of [IModelExportHandler.shouldExportSchema]($transformer) that is called to determine if a schema should be exported\n * @note the default behavior doesn't import schemas older than those already in the target\n */\n public override shouldExportSchema(schemaKey: ECSchemaMetaData.SchemaKey): boolean {\n const versionInTarget = this.targetDb.querySchemaVersion(schemaKey.name);\n if (versionInTarget === undefined)\n return true;\n return Semver.gt(`${schemaKey.version.read}.${schemaKey.version.write}.${schemaKey.version.minor}`, Schema.toSemverString(versionInTarget));\n }\n\n private _longNamedSchemasMap = new Map<string, string>();\n\n /** Override of [IModelExportHandler.onExportSchema]($transformer) that serializes a schema to disk for [[processSchemas]] to import into\n * the target iModel when it is exported from the source iModel.\n * @returns {Promise<ExportSchemaResult>} Although the type is possibly void for backwards compatibility of subclasses,\n * `IModelTransformer.onExportSchema` always returns an[[IModelExportHandler.ExportSchemaResult]]\n * with a defined `schemaPath` property, for subclasses to know where the schema was written.\n * Schemas are *not* guaranteed to be written to [[IModelTransformer._schemaExportDir]] by a\n * known pattern derivable from the schema's name, so you must use this to find it.\n */\n public override async onExportSchema(schema: ECSchemaMetaData.Schema): Promise<void | ExportSchemaResult> {\n const ext = \".ecschema.xml\";\n let schemaFileName = schema.name + ext;\n // many file systems have a max file-name/path-segment size of 255, so we workaround that on all systems\n const systemMaxPathSegmentSize = 255;\n if (schemaFileName.length > systemMaxPathSegmentSize) {\n // this name should be well under 255 bytes\n // ( 100 + (Number.MAX_SAFE_INTEGER.toString().length = 16) + (ext.length = 13) ) = 129 which is less than 255\n // You'd have to be past 2**53-1 (Number.MAX_SAFE_INTEGER) long named schemas in order to hit decimal formatting,\n // and that's on the scale of at least petabytes. `Map.prototype.size` shouldn't return floating points, and even\n // if they do they're in scientific notation, size bound and contain no invalid windows path chars\n schemaFileName = `${schema.name.slice(0, 100)}${this._longNamedSchemasMap.size}${ext}`;\n nodeAssert(schemaFileName.length <= systemMaxPathSegmentSize, \"Schema name was still long. This is a bug.\");\n this._longNamedSchemasMap.set(schema.name, schemaFileName);\n }\n this.sourceDb.nativeDb.exportSchema(schema.name, this._schemaExportDir, schemaFileName);\n return { schemaPath: path.join(this._schemaExportDir, schemaFileName) };\n }\n\n private _makeLongNameResolvingSchemaCtx(): ECSchemaXmlContext {\n const result = new ECSchemaXmlContext();\n result.setSchemaLocater((key) => {\n const match = this._longNamedSchemasMap.get(key.name);\n if (match !== undefined)\n return path.join(this._schemaExportDir, match);\n return undefined;\n });\n return result;\n }\n\n /** Cause all schemas to be exported from the source iModel and imported into the target iModel.\n * @note For performance reasons, it is recommended that [IModelDb.saveChanges]($backend) be called after `processSchemas` is complete.\n * It is more efficient to process *data* changes after the schema changes have been saved.\n */\n public async processSchemas(): Promise<void> {\n // we do not need to initialize for this since no entities are exported\n try {\n IModelJsFs.mkdirSync(this._schemaExportDir);\n this._longNamedSchemasMap.clear();\n await this.exporter.exportSchemas();\n const exportedSchemaFiles = IModelJsFs.readdirSync(this._schemaExportDir);\n if (exportedSchemaFiles.length === 0)\n return;\n const schemaFullPaths = exportedSchemaFiles.map((s) => path.join(this._schemaExportDir, s));\n const maybeLongNameResolvingSchemaCtx = this._longNamedSchemasMap.size > 0\n ? this._makeLongNameResolvingSchemaCtx()\n : undefined;\n return await this.targetDb.importSchemas(schemaFullPaths, { ecSchemaXmlContext: maybeLongNameResolvingSchemaCtx });\n } finally {\n IModelJsFs.removeSync(this._schemaExportDir);\n this._longNamedSchemasMap.clear();\n }\n }\n\n /** Cause all fonts to be exported from the source iModel and imported into the target iModel.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processFonts(): Promise<void> {\n // we do not need to initialize for this since no entities are exported\n await this.initialize();\n return this.exporter.exportFonts();\n }\n\n /** Override of [IModelExportHandler.onExportFont]($transformer) that imports a font into the target iModel when it is exported from the source iModel. */\n public override onExportFont(font: FontProps, _isUpdate: boolean | undefined): void {\n this.context.importFont(font.id);\n }\n\n /** Cause all CodeSpecs to be exported from the source iModel and imported into the target iModel.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processCodeSpecs(): Promise<void> {\n await this.initialize();\n return this.exporter.exportCodeSpecs();\n }\n\n /** Cause a single CodeSpec to be exported from the source iModel and imported into the target iModel.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processCodeSpec(codeSpecName: string): Promise<void> {\n await this.initialize();\n return this.exporter.exportCodeSpecByName(codeSpecName);\n }\n\n /** Override of [IModelExportHandler.shouldExportCodeSpec]($transformer) that is called to determine if a CodeSpec should be exported from the source iModel.\n * @note Reaching this point means that the CodeSpec has passed the standard exclusion checks in [IModelExporter]($transformer).\n */\n public override shouldExportCodeSpec(_sourceCodeSpec: CodeSpec): boolean { return true; }\n\n /** Override of [IModelExportHandler.onExportCodeSpec]($transformer) that imports a CodeSpec into the target iModel when it is exported from the source iModel. */\n public override onExportCodeSpec(sourceCodeSpec: CodeSpec): void {\n this.context.importCodeSpec(sourceCodeSpec.id);\n }\n\n /** Recursively import all Elements and sub-Models that descend from the specified Subject */\n public async processSubject(sourceSubjectId: Id64String, targetSubjectId: Id64String): Promise<void> {\n await this.initialize();\n this.sourceDb.elements.getElement(sourceSubjectId, Subject); // throws if sourceSubjectId is not a Subject\n this.targetDb.elements.getElement(targetSubjectId, Subject); // throws if targetSubjectId is not a Subject\n this.context.remapElement(sourceSubjectId, targetSubjectId);\n await this.processChildElements(sourceSubjectId);\n await this.processSubjectSubModels(sourceSubjectId);\n return this.processDeferredElements(); // eslint-disable-line deprecation/deprecation\n }\n\n /** state to prevent reinitialization, @see [[initialize]] */\n private _initialized = false;\n\n /**\n * Initialize prerequisites of processing, you must initialize with an [[InitFromExternalSourceAspectsArgs]] if you\n * are intending process changes, but prefer using [[processChanges]]\n * Called by all `process*` functions implicitly.\n * Overriders must call `super.initialize()` first\n */\n public async initialize(args?: InitFromExternalSourceAspectsArgs) {\n if (this._initialized)\n return;\n await this.context.initialize();\n // eslint-disable-next-line deprecation/deprecation\n await this.initFromExternalSourceAspects(args);\n this._initialized = true;\n }\n\n /** Export everything from the source iModel and import the transformed entities into the target iModel.\n * @note [[processSchemas]] is not called automatically since the target iModel may want a different collection of schemas.\n */\n public async processAll(): Promise<void> {\n Logger.logTrace(loggerCategory, \"processAll()\");\n this.logSettings();\n this.validateScopeProvenance();\n await this.initialize();\n await this.exporter.exportCodeSpecs();\n await this.exporter.exportFonts();\n // The RepositoryModel and root Subject of the target iModel should not be transformed.\n await this.exporter.exportChildElements(IModel.rootSubjectId); // start below the root Subject\n await this.exporter.exportModelContents(IModel.repositoryModelId, Element.classFullName, true); // after the Subject hierarchy, process the other elements of the RepositoryModel\n await this.exporter.exportSubModels(IModel.repositoryModelId); // start below the RepositoryModel\n await this.exporter.exportRelationships(ElementRefersToElements.classFullName);\n await this.processDeferredElements(); // eslint-disable-line deprecation/deprecation\n if (this.shouldDetectDeletes()) {\n await this.detectElementDeletes();\n await this.detectRelationshipDeletes();\n }\n\n if (this._options.optimizeGeometry)\n this.importer.optimizeGeometry(this._options.optimizeGeometry);\n\n this.importer.computeProjectExtents();\n this.finalizeTransformation();\n }\n\n private _lastProvenanceEntityInfo = nullLastProvenanceEntityInfo;\n\n private markLastProvenance(sourceAspect: MarkRequired<ExternalSourceAspectProps, \"id\">, { isRelationship = false }) {\n this._lastProvenanceEntityInfo = {\n entityId: sourceAspect.element.id,\n aspectId: sourceAspect.id,\n aspectVersion: sourceAspect.version ?? \"\",\n aspectKind: isRelationship ? ExternalSourceAspect.Kind.Relationship : ExternalSourceAspect.Kind.Element,\n };\n }\n\n /** @internal the name of the table where javascript state of the transformer is serialized in transformer state dumps */\n public static readonly jsStateTable = \"TransformerJsState\";\n\n /** @internal the name of the table where the target state heuristics is serialized in transformer state dumps */\n public static readonly lastProvenanceEntityInfoTable = \"LastProvenanceEntityInfo\";\n\n /**\n * Load the state of the active transformation from an open SQLiteDb\n * You can override this if you'd like to load from custom tables in the resumable dump state, but you should call\n * this super implementation\n * @note the SQLiteDb must be open\n */\n protected loadStateFromDb(db: SQLiteDb): void {\n const lastProvenanceEntityInfo: IModelTransformer[\"_lastProvenanceEntityInfo\"] = db.withSqliteStatement(\n `SELECT entityId, aspectId, aspectVersion, aspectKind FROM ${IModelTransformer.lastProvenanceEntityInfoTable}`,\n (stmt) => {\n if (DbResult.BE_SQLITE_ROW !== stmt.step())\n throw Error(\n \"expected row when getting lastProvenanceEntityId from target state table\"\n );\n return {\n entityId: stmt.getValueString(0),\n aspectId: stmt.getValueString(1),\n aspectVersion: stmt.getValueString(2),\n aspectKind: stmt.getValueString(3) as ExternalSourceAspect.Kind,\n };\n }\n );\n const targetHasCorrectLastProvenance =\n // ignore provenance check if it's null since we can't bind those ids\n !Id64.isValidId64(lastProvenanceEntityInfo.aspectId) ||\n !Id64.isValidId64(lastProvenanceEntityInfo.entityId) ||\n this.provenanceDb.withPreparedStatement(`\n SELECT Version FROM ${ExternalSourceAspect.classFullName}\n WHERE Scope.Id=:scopeId\n AND ECInstanceId=:aspectId\n AND Kind=:kind\n AND Element.Id=:entityId\n `,\n (statement: ECSqlStatement): boolean => {\n statement.bindId(\"scopeId\", this.targetScopeElementId);\n statement.bindId(\"aspectId\", lastProvenanceEntityInfo.aspectId);\n statement.bindString(\"kind\", lastProvenanceEntityInfo.aspectKind);\n statement.bindId(\"entityId\", lastProvenanceEntityInfo.entityId);\n const stepResult = statement.step();\n switch (stepResult) {\n case DbResult.BE_SQLITE_ROW:\n const version = statement.getValue(0).getString();\n return version === lastProvenanceEntityInfo.aspectVersion;\n case DbResult.BE_SQLITE_DONE:\n return false;\n default:\n throw new IModelError(IModelStatus.SQLiteError, `got sql error ${stepResult}`);\n }\n });\n if (!targetHasCorrectLastProvenance)\n throw Error([\n \"Target for resuming from does not have the expected provenance \",\n \"from the target that the resume state was made with\",\n ].join(\"\\n\"));\n this._lastProvenanceEntityInfo = lastProvenanceEntityInfo;\n\n const state = db.withSqliteStatement(`SELECT data FROM ${IModelTransformer.jsStateTable}`, (stmt) => {\n if (DbResult.BE_SQLITE_ROW !== stmt.step())\n throw Error(\"expected row when getting data from js state table\");\n return JSON.parse(stmt.getValueString(0)) as TransformationJsonState;\n });\n if (state.transformerClass !== this.constructor.name)\n throw Error(\"resuming from a differently named transformer class, it is not necessarily valid to resume with a different transformer class\");\n // force assign to readonly options since we do not know how the transformer subclass takes options to pass to the superclass\n (this as any)._options = state.options;\n this.context.loadStateFromDb(db);\n this.importer.loadStateFromJson(state.importerState);\n this.exporter.loadStateFromJson(state.exporterState);\n this.loadAdditionalStateJson(state.additionalState);\n }\n\n /**\n * Return a new transformer instance with the same remappings state as saved from a previous [[IModelTransformer.saveStateToFile]] call.\n * This allows you to \"resume\" an iModel transformation, you will have to call [[IModelTransformer.processChanges]]/[[IModelTransformer.processAll]]\n * again but the remapping state will cause already mapped elements to be skipped.\n * To \"resume\" an iModel Transformation you need:\n * - the sourceDb at the same changeset\n * - the same targetDb in the state in which it was before\n * @param statePath the path to the serialized state of the transformer, use [[IModelTransformer.saveStateToFile]] to get this from an existing transformer instance\n * @param constructorArgs remaining arguments that you would normally pass to the Transformer subclass you are using, usually (sourceDb, targetDb)\n * @note custom transformers with custom state may need to override this method in order to handle loading their own custom state somewhere\n */\n public static resumeTransformation<SubClass extends new(...a: any[]) => IModelTransformer = typeof IModelTransformer>(\n this: SubClass,\n statePath: string,\n ...constructorArgs: ConstructorParameters<SubClass>\n ): InstanceType<SubClass> {\n const transformer = new this(...constructorArgs);\n const db = new SQLiteDb();\n db.openDb(statePath, OpenMode.Readonly);\n try {\n transformer.loadStateFromDb(db);\n } finally {\n db.closeDb();\n }\n return transformer as InstanceType<SubClass>;\n }\n\n /**\n * You may override this to store arbitrary json state in a transformer 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 * Save the state of the active transformation to an open SQLiteDb\n * You can override this if you'd like to write custom tables to the resumable dump state, but you should call\n * this super implementation\n * @note the SQLiteDb must be open\n */\n protected saveStateToDb(db: SQLiteDb): void {\n const jsonState: TransformationJsonState = {\n transformerClass: this.constructor.name,\n options: this._options,\n importerState: this.importer.saveStateToJson(),\n exporterState: this.exporter.saveStateToJson(),\n additionalState: this.getAdditionalStateJson(),\n };\n\n this.context.saveStateToDb(db);\n if (DbResult.BE_SQLITE_DONE !== db.executeSQL(`CREATE TABLE ${IModelTransformer.jsStateTable} (data TEXT)`))\n throw Error(\"Failed to create the js state table in the state database\");\n\n if (DbResult.BE_SQLITE_DONE !== db.executeSQL(`\n CREATE TABLE ${IModelTransformer.lastProvenanceEntityInfoTable} (\n -- because we cannot bind the invalid id which we use for our null state, we actually store the id as a hex string\n entityId TEXT,\n aspectId TEXT,\n aspectVersion TEXT,\n aspectKind TEXT\n )\n `))\n throw Error(\"Failed to create the target state table in the state database\");\n\n db.saveChanges();\n db.withSqliteStatement(\n `INSERT INTO ${IModelTransformer.jsStateTable} (data) VALUES (?)`,\n (stmt) => {\n stmt.bindString(1, JSON.stringify(jsonState));\n if (DbResult.BE_SQLITE_DONE !== stmt.step())\n throw Error(\"Failed to insert options into the state database\");\n });\n\n db.withSqliteStatement(\n `INSERT INTO ${IModelTransformer.lastProvenanceEntityInfoTable} (entityId, aspectId, aspectVersion, aspectKind) VALUES (?,?,?,?)`,\n (stmt) => {\n stmt.bindString(1, this._lastProvenanceEntityInfo.entityId);\n stmt.bindString(2, this._lastProvenanceEntityInfo.aspectId);\n stmt.bindString(3, this._lastProvenanceEntityInfo.aspectVersion);\n stmt.bindString(4, this._lastProvenanceEntityInfo.aspectKind);\n if (DbResult.BE_SQLITE_DONE !== stmt.step())\n throw Error(\"Failed to insert options into the state database\");\n });\n\n db.saveChanges();\n }\n\n /**\n * Save the state of the active transformation to a file path, if a file at the path already exists, it will be overwritten\n * This state can be used by [[IModelTransformer.resumeTransformation]] to resume a transformation from this point.\n * The serialization format is a custom sqlite database.\n * @note custom transformers with custom state may override [[IModelTransformer.saveStateToDb]] or [[IModelTransformer.getAdditionalStateJson]]\n * and [[IModelTransformer.loadStateFromDb]] (with a super call) or [[IModelTransformer.loadAdditionalStateJson]]\n * if they have custom state that needs to be stored with\n * potentially inside the same sqlite file in separate tables\n */\n public saveStateToFile(nativeStatePath: string): void {\n const db = new SQLiteDb();\n if (IModelJsFs.existsSync(nativeStatePath))\n IModelJsFs.unlinkSync(nativeStatePath);\n db.createDb(nativeStatePath);\n try {\n this.saveStateToDb(db);\n db.saveChanges();\n } finally {\n db.closeDb();\n }\n }\n\n /** Export changes from the source iModel and import the transformed entities into the target iModel.\n * @note To form a range of versions to process, set `startChangesetId` for the start (inclusive)\n * of the desired range and open the source iModel as of the end (inclusive) of the desired range.\n */\n public async processChanges(args: ProcessChangesOptions): Promise<void>;\n /** @deprecated in 0.1.x, use a single [[ProcessChangesOptions]] object instead */\n public async processChanges(accessToken: AccessToken, startChangesetId?: string): Promise<void>;\n public async processChanges(accessTokenOrArgs: AccessToken | ProcessChangesOptions, startChangesetId?: string): Promise<void> {\n Logger.logTrace(loggerCategory, \"processChanges()\");\n this.logSettings();\n this.validateScopeProvenance();\n\n const options: ProcessChangesOptions = typeof accessTokenOrArgs === \"string\"\n ? {\n accessToken: accessTokenOrArgs,\n startChangeset: startChangesetId ? { id: startChangesetId } : this.sourceDb.changeset,\n changedInstanceIds: undefined,\n }\n : accessTokenOrArgs;\n\n await this.initialize(options);\n await this.exporter.exportChanges(options);\n await this.processDeferredElements(); // eslint-disable-line deprecation/deprecation\n\n if (this._options.optimizeGeometry)\n this.importer.optimizeGeometry(this._options.optimizeGeometry);\n\n this.importer.computeProjectExtents();\n this.finalizeTransformation();\n }\n}\n\n/** @internal the json part of a transformation's state */\ninterface TransformationJsonState {\n transformerClass: string;\n options: IModelTransformOptions;\n importerState: IModelImporterState;\n exporterState: IModelExporterState;\n additionalState?: any;\n}\n\n/** IModelTransformer that clones the contents of a template model.\n * @beta\n */\nexport class TemplateModelCloner extends IModelTransformer {\n /** The Placement to apply to the template. */\n private _transform3d?: Transform;\n /** Accumulates the mapping of sourceElementIds to targetElementIds from the elements in the template model that were cloned. */\n private _sourceIdToTargetIdMap?: Map<Id64String, Id64String>;\n /** Construct a new TemplateModelCloner\n * @param sourceDb The source IModelDb that contains the templates to clone\n * @param targetDb Optionally specify the target IModelDb where the cloned template will be inserted.\n * Typically this is left unspecified, and the default is to use the sourceDb as the target\n * @note The expectation is that the template definitions are within the same iModel where instances will be placed.\n */\n public constructor(sourceDb: IModelDb, targetDb: IModelDb = sourceDb) {\n const target = new IModelImporter(targetDb, {\n autoExtendProjectExtents: false, // autoExtendProjectExtents is intended for transformation service use cases, not template --> instance cloning\n });\n super(sourceDb, target, { noProvenance: true }); // WIP: need to decide the proper way to handle provenance\n }\n /** Place a template from the sourceDb at the specified placement in the target model within the targetDb.\n * @param sourceTemplateModelId The Id of the template model in the sourceDb\n * @param targetModelId The Id of the target model (must be a subclass of GeometricModel3d) where the cloned component will be inserted.\n * @param placement The placement for the cloned component.\n * @note *Required References* like the SpatialCategory must be remapped before calling this method.\n * @returns The mapping of sourceElementIds from the template model to the instantiated targetElementIds in the targetDb in case further processing is required.\n */\n public async placeTemplate3d(sourceTemplateModelId: Id64String, targetModelId: Id64String, placement: Placement3d): Promise<Map<Id64String, Id64String>> {\n this.context.remapElement(sourceTemplateModelId, targetModelId);\n this._transform3d = Transform.createOriginAndMatrix(placement.origin, placement.angles.toMatrix3d());\n this._sourceIdToTargetIdMap = new Map<Id64String, Id64String>();\n await this.exporter.exportModelContents(sourceTemplateModelId);\n // Note: the source --> target mapping was needed during the template model cloning phase (remapping parent/child, for example), but needs to be reset afterwards\n for (const sourceElementId of this._sourceIdToTargetIdMap.keys()) {\n const targetElementId = this.context.findTargetElementId(sourceElementId);\n this._sourceIdToTargetIdMap.set(sourceElementId, targetElementId);\n this.context.removeElement(sourceElementId); // clear the underlying native remapping context for the next clone operation\n }\n return this._sourceIdToTargetIdMap; // return the sourceElementId -> targetElementId Map in case further post-processing is required.\n }\n\n /** Place a template from the sourceDb at the specified placement in the target model within the targetDb.\n * @param sourceTemplateModelId The Id of the template model in the sourceDb\n * @param targetModelId The Id of the target model (must be a subclass of GeometricModel2d) where the cloned component will be inserted.\n * @param placement The placement for the cloned component.\n * @note *Required References* like the DrawingCategory must be remapped before calling this method.\n * @returns The mapping of sourceElementIds from the template model to the instantiated targetElementIds in the targetDb in case further processing is required.\n */\n public async placeTemplate2d(sourceTemplateModelId: Id64String, targetModelId: Id64String, placement: Placement2d): Promise<Map<Id64String, Id64String>> {\n this.context.remapElement(sourceTemplateModelId, targetModelId);\n this._transform3d = Transform.createOriginAndMatrix(Point3d.createFrom(placement.origin), placement.rotation);\n this._sourceIdToTargetIdMap = new Map<Id64String, Id64String>();\n await this.exporter.exportModelContents(sourceTemplateModelId);\n // Note: the source --> target mapping was needed during the template model cloning phase (remapping parent/child, for example), but needs to be reset afterwards\n for (const sourceElementId of this._sourceIdToTargetIdMap.keys()) {\n const targetElementId = this.context.findTargetElementId(sourceElementId);\n this._sourceIdToTargetIdMap.set(sourceElementId, targetElementId);\n this.context.removeElement(sourceElementId); // clear the underlying native remapping context for the next clone operation\n }\n return this._sourceIdToTargetIdMap; // return the sourceElementId -> targetElementId Map in case further post-processing is required.\n }\n\n /** Cloning from a template requires this override of onTransformElement. */\n public override onTransformElement(sourceElement: Element): ElementProps {\n // eslint-disable-next-line deprecation/deprecation\n const referenceIds = sourceElement.getReferenceConcreteIds();\n referenceIds.forEach((referenceId) => {\n // FIXME: consider going through all definition elements at once and remapping them to themselves\n if (!EntityReferences.isValid(this.context.findTargetEntityId(referenceId))) {\n if (this.context.isBetweenIModels) {\n throw new IModelError(IModelStatus.BadRequest, `Remapping for source dependency ${referenceId} not found for target iModel`);\n } else {\n const definitionElement = this.sourceDb.elements.tryGetElement<DefinitionElement>(referenceId, DefinitionElement);\n if (definitionElement && !(definitionElement instanceof RecipeDefinitionElement)) {\n this.context.remapElement(referenceId, referenceId); // when in the same iModel, can use existing DefinitionElements without remapping\n } else {\n throw new IModelError(IModelStatus.BadRequest, `Remapping for dependency ${referenceId} not found`);\n }\n }\n }\n });\n\n const targetElementProps: ElementProps = super.onTransformElement(sourceElement);\n targetElementProps.federationGuid = Guid.createValue(); // clone from template should create a new federationGuid\n targetElementProps.code = Code.createEmpty(); // clone from template should not maintain codes\n if (sourceElement instanceof GeometricElement3d) {\n const placement = Placement3d.fromJSON((targetElementProps as GeometricElement3dProps).placement);\n if (placement.isValid) {\n placement.multiplyTransform(this._transform3d!);\n (targetElementProps as GeometricElement3dProps).placement = placement;\n }\n } else if (sourceElement instanceof GeometricElement2d) {\n const placement = Placement2d.fromJSON((targetElementProps as GeometricElement2dProps).placement);\n if (placement.isValid) {\n placement.multiplyTransform(this._transform3d!);\n (targetElementProps as GeometricElement2dProps).placement = placement;\n }\n }\n this._sourceIdToTargetIdMap!.set(sourceElement.id, Id64.invalid); // keep track of (source) elementIds from the template model, but the target hasn't been inserted yet\n return targetElementProps;\n }\n}\n"]}
1
+ {"version":3,"file":"IModelTransformer.js","sourceRoot":"","sources":["../../src/IModelTransformer.ts"],"names":[],"mappings":";;;AAAA;;;+FAG+F;AAC/F;;GAEG;AACH,6BAA6B;AAC7B,iCAAiC;AACjC,qCAAqC;AACrC,sDAG6B;AAE7B,wDAA0D;AAC1D,sDAM6B;AAC7B,oDAI4B;AAC5B,qDAA2J;AAC3J,qDAAgG;AAChG,2EAAwE;AACxE,+DAA8E;AAC9E,2CAAmD;AACnD,6DAA0D;AAC1D,mDAAgD;AAChD,iCAAmD;AAEnD,MAAM,cAAc,GAAW,qDAAyB,CAAC,iBAAiB,CAAC;AAE3E,MAAM,4BAA4B,GAAG;IACnC,QAAQ,EAAE,mBAAI,CA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C,CAAC,yBAAW,CAAC,CAAC,CAAC,yBAAW,CAAC;YACxD,MAAM,SAAS,GAAG,CAAC,cAAc,CAAC,CAAC,QAAQ,CAAE,kBAA4C,CAAC,SAAgB,CAAC,CAAC;YAC5G,IAAI,SAAS,CAAC,OAAO,EAAE;gBACrB,UAAU,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;gBAC9B,SAAS,CAAC,iBAAiB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;gBAC9C,kBAA4C,CAAC,SAAS,GAAG,SAAS,CAAC;aACrE;SACF;QACD,IAAI,CAAC,sBAAuB,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE,EAAE,mBAAI,CAAC,OAAO,CAAC,CAAC,CAAC,qGAAqG;QACvK,OAAO,kBAAkB,CAAC;IAC5B,CAAC;CACF;AAjGD,kDAiGC;AAED,SAAS,gBAAgB,CAAC,EAAY,EAAE,MAAkB;IACxD,OAAO,EAAE,CAAC,qBAAqB,CAAC;;;;GAI/B,EAAE,CAAC,IAAI,EAAE,EAAE;QACV,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QACvB,IAAA,qBAAM,EAAC,IAAI,CAAC,IAAI,EAAE,KAAK,uBAAQ,CAAC,aAAa,CAAC,CAAC;QAC/C,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC;QAC1C,IAAA,qBAAM,EAAC,IAAI,CAAC,IAAI,EAAE,KAAK,uBAAQ,CAAC,cAAc,CAAC,CAAC;QAChD,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\n* See LICENSE.md in the project root for license terms and full copyright notice.\n*--------------------------------------------------------------------------------------------*/\n/** @packageDocumentation\n * @module iModels\n */\nimport * as path from \"path\";\nimport * as Semver from \"semver\";\nimport * as nodeAssert from \"assert\";\nimport {\n AccessToken, assert, CompressedId64Set, DbResult, Guid, GuidString, Id64, Id64Array, Id64String, IModelStatus, Logger, MarkRequired,\n OpenMode, YieldManager,\n} from \"@itwin/core-bentley\";\nimport * as ECSchemaMetaData from \"@itwin/ecschema-metadata\";\nimport { Point3d, Transform } from \"@itwin/core-geometry\";\nimport {\n ChangeSummaryManager,\n ChannelRootAspect, ConcreteEntity, DefinitionElement, DefinitionModel, DefinitionPartition, ECSchemaXmlContext, ECSqlStatement, ECSqlValue, Element, ElementAspect, ElementMultiAspect, ElementOwnsExternalSourceAspects,\n ElementRefersToElements, ElementUniqueAspect, Entity, EntityReferences, ExternalSource, ExternalSourceAspect, ExternalSourceAttachment,\n FolderLink, GeometricElement, GeometricElement3d, IModelDb, IModelHost, IModelJsFs, InformationPartitionElement, KnownLocations, Model,\n RecipeDefinitionElement, Relationship, RelationshipProps, Schema, SQLiteDb, Subject, SynchronizationConfigLink,\n} from \"@itwin/core-backend\";\nimport {\n ChangeOpCode, ChangesetIndexAndId, Code, CodeProps, CodeSpec, ConcreteEntityTypes, ElementAspectProps, ElementProps, EntityReference, EntityReferenceSet,\n ExternalSourceAspectProps, FontProps, GeometricElementProps, IModel, IModelError, ModelProps,\n Placement2d, Placement3d, PrimitiveTypeCode, PropertyMetaData, RelatedElement, SourceAndTarget,\n} from \"@itwin/core-common\";\nimport { ExportChangesOptions, ExporterInitOptions, ExportSchemaResult, IModelExporter, IModelExporterState, IModelExportHandler } from \"./IModelExporter\";\nimport { IModelImporter, IModelImporterState, OptimizeGeometryOptions } from \"./IModelImporter\";\nimport { TransformerLoggerCategory } from \"./TransformerLoggerCategory\";\nimport { PendingReference, PendingReferenceMap } from \"./PendingReferenceMap\";\nimport { EntityKey, EntityMap } from \"./EntityMap\";\nimport { IModelCloneContext } from \"./IModelCloneContext\";\nimport { EntityUnifier } from \"./EntityUnifier\";\nimport { rangesFromRangeAndSkipped } from \"./Algo\";\n\nconst loggerCategory: string = TransformerLoggerCategory.IModelTransformer;\n\nconst nullLastProvenanceEntityInfo = {\n entityId: Id64.invalid,\n aspectId: Id64.invalid,\n aspectVersion: \"\",\n aspectKind: ExternalSourceAspect.Kind.Element,\n};\n\ntype LastProvenanceEntityInfo = typeof nullLastProvenanceEntityInfo;\n\ntype EntityTransformHandler = (entity: ConcreteEntity) => ElementProps | ModelProps | RelationshipProps | ElementAspectProps;\n\n/** Options provided to the [[IModelTransformer]] constructor.\n * @beta\n * @note if adding an option, you must explicitly add its serialization to [[IModelTransformer.saveStateToFile]]!\n */\nexport interface IModelTransformOptions {\n /** The Id of the Element in the **target** iModel that represents the **source** repository as a whole and scopes its [ExternalSourceAspect]($backend) instances.\n * It is always a good idea to define this, although particularly necessary in any multi-source scenario such as multiple branches that reverse synchronize\n * or physical consolidation.\n */\n targetScopeElementId?: Id64String;\n\n /** Set to `true` if IModelTransformer should not record its provenance.\n * Provenance tracks a target element back to its corresponding source element and is essential for [[IModelTransformer.processChanges]] to work properly.\n * Turning off IModelTransformer provenance is really only relevant for producing snapshots or another one time transformations.\n * @note See the [[includeSourceProvenance]] option for determining whether existing source provenance is cloned into the target.\n * @note The default is `false` which means that new IModelTransformer provenance will be recorded.\n */\n noProvenance?: boolean;\n\n /** Set to `true` to clone existing source provenance into the target.\n * @note See the [[noProvenance]] option for determining whether new IModelTransformer provenance is recorded.\n * @note The default is `false` which means that existing provenance in the source will not be carried into the target.\n */\n includeSourceProvenance?: boolean;\n\n /** Flag that indicates that the target iModel was created by copying the source iModel.\n * This is common when the target iModel is intended to be a *branch* of the source iModel.\n * This *hint* is essential to properly initialize the source to target element mapping and to cause provenance to be recorded for future synchronizations.\n * @note This *hint* is typically only set for the first synchronization after the iModel was copied since every other synchronization can utilize the provenance.\n */\n wasSourceIModelCopiedToTarget?: boolean;\n\n // FIXME: deprecate this, we should now be able to detect it from the external source aspect data\n /** Flag that indicates that the current source and target iModels are now synchronizing in the reverse direction from a prior synchronization.\n * The most common example is to first synchronize master to branch, make changes to the branch, and then reverse directions to synchronize from branch to master.\n * This means that the provenance on the (current) source is used instead.\n * @note This also means that only [[IModelTransformer.processChanges]] can detect deletes.\n */\n isReverseSynchronization?: boolean;\n\n /** Flag that indicates whether or not the transformation process needs to consider the source geometry before cloning/transforming.\n * For standard cases, it is not required to load the source GeometryStream in JavaScript since the cloning happens in native code.\n * Also, the target GeometryStream will be available in JavaScript prior to insert.\n * @note If the source geometry affects the class mapping or transformation logic, then this flag should be set to `true`. The default is `false`.\n * @see [IModelExporter.wantGeometry]($transformer)\n */\n loadSourceGeometry?: boolean;\n\n /** Flag that indicates whether or not the transformation process should clone using binary geometry.\n *\n * Prefer to never to set this flag. If you need geometry changes, instead override [[IModelTransformer.onTransformElement]]\n * and provide an [ElementGeometryBuilderParams]($common) to the `elementGeometryBuilderParams`\n * property of [ElementProps]($common) instead, it is much faster. You can read geometry during the transformation by setting the\n * [[IModelTransformOptions.loadSourceGeometry]] property to `true`, and passing that to a [GeometryStreamIterator]($common)\n * @note this flag will be deprecated when `elementGeometryBuilderParams` is no longer an alpha API\n *\n * @default true\n */\n cloneUsingBinaryGeometry?: boolean;\n\n /** Flag that indicates that ids should be preserved while copying elements to the target\n * Intended only for pure-filter transforms, so you can keep parts of the source, while deleting others,\n * and element ids are guaranteed to be the same, (other entity ids are not, however)\n * @note The target must be empty.\n * @note It is invalid to insert elements during the transformation, do not use this with transformers that try to.\n * @note This does not preserve the ids of non-element entities such as link table relationships, or aspects, etc.\n * @default false\n * @beta\n */\n preserveElementIdsForFiltering?: boolean;\n\n /** The behavior to use when an element reference (id) is found stored as a reference on an element in the source,\n * but the referenced element does not actually exist in the source.\n * It is possible to craft an iModel with dangling references/invalidated relationships by, e.g., deleting certain\n * elements without fixing up references.\n *\n * @note \"reject\" will throw an error and reject the transformation upon finding this case.\n * @note \"ignore\" passes the issue down to consuming applications, iModels that have invalid element references\n * like this can cause errors, and you should consider adding custom logic in your transformer to remove the\n * reference depending on your use case.\n * @default \"reject\"\n * @beta\n * @deprecated in 3.x. use [[danglingReferencesBehavior]] instead, the use of the term *predecessors* was confusing and became inaccurate when the transformer could handle cycles\n */\n danglingPredecessorsBehavior?: \"reject\" | \"ignore\";\n\n /** The behavior to use when an element reference (id) is found stored as a reference on an element in the source,\n * but the referenced element does not actually exist in the source.\n * It is possible to craft an iModel with dangling references/invalidated relationships by, e.g., deleting certain\n * elements without fixing up references.\n *\n * @note \"reject\" will throw an error and reject the transformation upon finding this case.\n * @note \"ignore\" passes the issue down to consuming applications, iModels that have invalid element references\n * like this can cause errors, and you should consider adding custom logic in your transformer to remove the\n * reference depending on your use case.\n * @default \"reject\"\n * @beta\n */\n danglingReferencesBehavior?: \"reject\" | \"ignore\";\n\n /** If defined, options to be supplied to [[IModelImporter.optimizeGeometry]] by [[IModelTransformer.processChanges]] and [[IModelTransformer.processAll]]\n * as a post-processing step to optimize the geometry in the iModel.\n * @beta\n */\n optimizeGeometry?: OptimizeGeometryOptions;\n\n /**\n * force the insertion of external source aspects to provide provenance, even if there are federation guids\n * in the source that we can use. This can make some operations (like transforming new elements or initializing forks)\n * much slower due to needing to insert aspects, but prevents requiring change information for future merges.\n * @default false\n */\n forceExternalSourceAspectProvenance?: boolean;\n\n // FIXME: test changecache reusage.\n /**\n * Do not detach the change cache that we build. Use this if you want to do multiple transformations to\n * the same iModels, to avoid the performance cost of reinitializing the change cache which can be\n * expensive. You should only use this if you know the cache will be reused.\n * @note You must detach the change cache yourself.\n * @default false\n */\n noDetachChangeCache?: boolean;\n\n // FIXME: consider \"deprecating\"\n /**\n * Do not check that processChanges is called from the next changeset index.\n * This is an unsafe option (e.g. it can cause data loss in future branch operations)\n * and you should not use it.\n * @default false\n */\n ignoreMissingChangesetsInSynchronizations?: boolean;\n}\n\n/**\n * A container for tracking the state of a partially committed entity and finalizing it when it's ready to be fully committed\n * @internal\n */\nclass PartiallyCommittedEntity {\n public constructor(\n /**\n * A set of \"model|element ++ ID64\" pairs, (e.g. `model0x11` or `element0x12`)\n * It is possible for the submodel of an element to be separately resolved from the actual element,\n * so its resolution must be tracked separately\n */\n private _missingReferences: EntityReferenceSet,\n private _onComplete: () => void\n ) {}\n public resolveReference(id: EntityReference) {\n this._missingReferences.delete(id);\n if (this._missingReferences.size === 0)\n this._onComplete();\n }\n public forceComplete() {\n this._onComplete();\n }\n}\n\ninterface TargetScopeProvenanceJsonProps {\n pendingReverseSyncChangesetIndices: number[];\n pendingSyncChangesetIndices: number[];\n reverseSyncVersion: string;\n}\n\n/**\n * Apply a function to each Id64 in a supported container type of Id64s.\n * Currently only supports raw Id64String or RelatedElement-like objects containing an `id` property that is a Id64String,\n * which matches the possible containers of references in [Element.requiredReferenceKeys]($backend).\n * @internal\n */\nfunction mapId64<R>(\n idContainer: Id64String | { id: Id64String } | undefined,\n func: (id: Id64String) => R\n): R[] {\n const isId64String = (arg: any): arg is Id64String => {\n const isString = typeof arg === \"string\";\n assert(() => !isString || Id64.isValidId64(arg));\n return isString;\n };\n const isRelatedElem = (arg: any): arg is RelatedElement =>\n arg && typeof arg === \"object\" && \"id\" in arg;\n\n const results = [];\n\n // is a string if compressed or singular id64, but check for singular just checks if it's a string so do this test first\n if (idContainer === undefined) {\n // nothing\n } else if (isId64String(idContainer)) {\n results.push(func(idContainer));\n } else if (isRelatedElem(idContainer)) {\n results.push(func(idContainer.id));\n } else {\n throw Error([\n `Id64 container '${idContainer}' is unsupported.`,\n \"Currently only singular Id64 strings or prop-like objects containing an 'id' property are supported.\",\n ].join(\"\\n\"));\n }\n return results;\n}\n\n/** Arguments you can pass to [[IModelTransformer.initialize]]\n * @beta\n */\nexport interface InitOptions {\n accessToken?: AccessToken;\n /**\n * Include changes from this changeset up through and including the current changeset.\n * @note To form a range of versions to process, set `startChangeset` for the start (inclusive)\n * of the desired range and open the source iModel as of the end (inclusive) of the desired range.\n * @default the current changeset of the sourceDb, if undefined\n */\n startChangeset?: {\n id?: string;\n index?: number;\n };\n}\n\n/**\n * Arguments for [[IModelTransformer.processChanges]]\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface ProcessChangesOptions extends ExportChangesOptions {}\n\ntype ChangeDataState = \"uninited\" | \"has-changes\" | \"no-changes\" | \"unconnected\";\n\n/** Arguments you can pass to [[IModelTransformer.initExternalSourceAspects]]\n * @deprecated in 0.1.0. Use [[InitOptions]] (and [[IModelTransformer.initialize]]) instead.\n */\nexport type InitFromExternalSourceAspectsArgs = InitOptions;\n\n/** Base class used to transform a source iModel into a different target iModel.\n * @see [iModel Transformation and Data Exchange]($docs/learning/transformer/index.md), [IModelExporter]($transformer), [IModelImporter]($transformer)\n * @beta\n */\nexport class IModelTransformer extends IModelExportHandler {\n /** The IModelExporter that will export from the source iModel. */\n public readonly exporter: IModelExporter;\n /** The IModelImporter that will import into the target iModel. */\n public readonly importer: IModelImporter;\n /** The normally read-only source iModel.\n * @note The source iModel will need to be read/write when provenance is being stored during a reverse synchronization.\n */\n public readonly sourceDb: IModelDb;\n /** The read/write target iModel. */\n public readonly targetDb: IModelDb;\n /** The IModelTransformContext for this IModelTransformer. */\n public readonly context: IModelCloneContext;\n /** The Id of the Element in the **target** iModel that represents the **source** repository as a whole and scopes its [ExternalSourceAspect]($backend) instances. */\n public get targetScopeElementId(): Id64String {\n return this._options.targetScopeElementId;\n }\n\n /** map of (unprocessed element, referencing processed element) pairs to the partially committed element that needs the reference resolved\n * and have some helper methods below for now */\n protected _pendingReferences = new PendingReferenceMap<PartiallyCommittedEntity>();\n\n /** a set of elements for which source provenance will be explicitly tracked by ExternalSourceAspects */\n protected _elementsWithExplicitlyTrackedProvenance = new Set<Id64String>();\n\n /** map of partially committed entities to their partial commit progress */\n protected _partiallyCommittedEntities = new EntityMap<PartiallyCommittedEntity>();\n\n /** the options that were used to initialize this transformer */\n private readonly _options: MarkRequired<IModelTransformOptions, \"targetScopeElementId\" | \"danglingReferencesBehavior\">;\n\n private _isSynchronization = false;\n\n private get _isReverseSynchronization() {\n return this._isSynchronization && this._options.isReverseSynchronization;\n }\n\n private get _isForwardSynchronization() {\n return this._isSynchronization && !this._options.isReverseSynchronization;\n }\n\n private _changesetRanges: [number, number][] | undefined = undefined;\n\n /** Set if it can be determined whether this is the first source --> target synchronization. */\n private _isFirstSynchronization?: boolean;\n\n /** The element classes that are considered to define provenance in the iModel */\n public static get provenanceElementClasses(): (typeof Entity)[] {\n return [FolderLink, SynchronizationConfigLink, ExternalSource, ExternalSourceAttachment];\n }\n\n /** The element aspect classes that are considered to define provenance in the iModel */\n public static get provenanceElementAspectClasses(): (typeof Entity)[] {\n return [ExternalSourceAspect];\n }\n\n /** Set of entity keys which were not exported and don't need to be tracked for pending reference resolution.\n * @note Currently only tracks elements which were not exported.\n */\n protected _skippedEntities = new Set<EntityKey>();\n\n /** Construct a new IModelTransformer\n * @param source Specifies the source IModelExporter or the source IModelDb that will be used to construct the source IModelExporter.\n * @param target Specifies the target IModelImporter or the target IModelDb that will be used to construct the target IModelImporter.\n * @param options The options that specify how the transformation should be done.\n */\n public constructor(source: IModelDb | IModelExporter, target: IModelDb | IModelImporter, options?: IModelTransformOptions) {\n super();\n // initialize IModelTransformOptions\n this._options = {\n ...options,\n // non-falsy defaults\n cloneUsingBinaryGeometry: options?.cloneUsingBinaryGeometry ?? true,\n targetScopeElementId: options?.targetScopeElementId ?? IModel.rootSubjectId,\n // eslint-disable-next-line deprecation/deprecation\n danglingReferencesBehavior: options?.danglingReferencesBehavior ?? options?.danglingPredecessorsBehavior ?? \"reject\",\n };\n this._isFirstSynchronization = this._options.wasSourceIModelCopiedToTarget ? true : undefined;\n // initialize exporter and sourceDb\n if (source instanceof IModelDb) {\n this.exporter = new IModelExporter(source);\n } else {\n this.exporter = source;\n }\n this.sourceDb = this.exporter.sourceDb;\n this.exporter.registerHandler(this);\n this.exporter.wantGeometry = options?.loadSourceGeometry ?? false; // optimization to not load source GeometryStreams by default\n if (!this._options.includeSourceProvenance) { // clone provenance from the source iModel into the target iModel?\n IModelTransformer.provenanceElementClasses.forEach((cls) => this.exporter.excludeElementClass(cls.classFullName));\n IModelTransformer.provenanceElementAspectClasses.forEach((cls) => this.exporter.excludeElementAspectClass(cls.classFullName));\n }\n this.exporter.excludeElementAspectClass(ChannelRootAspect.classFullName); // Channel boundaries within the source iModel are not relevant to the target iModel\n this.exporter.excludeElementAspectClass(\"BisCore:TextAnnotationData\"); // This ElementAspect is auto-created by the BisCore:TextAnnotation2d/3d element handlers\n // initialize importer and targetDb\n if (target instanceof IModelDb) {\n this.importer = new IModelImporter(target, { preserveElementIdsForFiltering: this._options.preserveElementIdsForFiltering });\n } else {\n this.importer = target;\n /* eslint-disable deprecation/deprecation */\n if (Boolean(this._options.preserveElementIdsForFiltering) !== this.importer.preserveElementIdsForFiltering) {\n Logger.logWarning(\n loggerCategory,\n [\n \"A custom importer was passed as a target but its 'preserveElementIdsForFiltering' option is out of sync with the transformer's option.\",\n \"The custom importer target's option will be force updated to use the transformer's value.\",\n \"This behavior is deprecated and will be removed in a future version, throwing an error if they are out of sync.\",\n ].join(\"\\n\")\n );\n this.importer.preserveElementIdsForFiltering = Boolean(this._options.preserveElementIdsForFiltering);\n }\n /* eslint-enable deprecation/deprecation */\n }\n this.targetDb = this.importer.targetDb;\n // create the IModelCloneContext, it must be initialized later\n this.context = new IModelCloneContext(this.sourceDb, this.targetDb);\n this._startingTargetChangesetIndex = this.targetDb?.changeset.index;\n }\n\n /** Dispose any native resources associated with this IModelTransformer. */\n public dispose(): void {\n Logger.logTrace(loggerCategory, \"dispose()\");\n this.context.dispose();\n }\n\n /** Log current settings that affect IModelTransformer's behavior. */\n private logSettings(): void {\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.visitElements=${this.exporter.visitElements}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.visitRelationships=${this.exporter.visitRelationships}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.wantGeometry=${this.exporter.wantGeometry}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.wantSystemSchemas=${this.exporter.wantSystemSchemas}`);\n Logger.logInfo(TransformerLoggerCategory.IModelExporter, `this.exporter.wantTemplateModels=${this.exporter.wantTemplateModels}`);\n Logger.logInfo(loggerCategory, `this.targetScopeElementId=${this.targetScopeElementId}`);\n Logger.logInfo(loggerCategory, `this._noProvenance=${this._options.noProvenance}`);\n Logger.logInfo(loggerCategory, `this._includeSourceProvenance=${this._options.includeSourceProvenance}`);\n Logger.logInfo(loggerCategory, `this._cloneUsingBinaryGeometry=${this._options.cloneUsingBinaryGeometry}`);\n Logger.logInfo(loggerCategory, `this._wasSourceIModelCopiedToTarget=${this._options.wasSourceIModelCopiedToTarget}`);\n Logger.logInfo(loggerCategory, `this._isReverseSynchronization=${this._options.isReverseSynchronization}`);\n Logger.logInfo(TransformerLoggerCategory.IModelImporter, `this.importer.autoExtendProjectExtents=${this.importer.options.autoExtendProjectExtents}`);\n Logger.logInfo(TransformerLoggerCategory.IModelImporter, `this.importer.simplifyElementGeometry=${this.importer.options.simplifyElementGeometry}`);\n }\n\n /** Return the IModelDb where IModelTransformer will store its provenance.\n * @note This will be [[targetDb]] except when it is a reverse synchronization. In that case it be [[sourceDb]].\n */\n public get provenanceDb(): IModelDb {\n return this._options.isReverseSynchronization ? this.sourceDb : this.targetDb;\n }\n\n /** Return the IModelDb where IModelTransformer looks for entities referred to by stored provenance.\n * @note This will be [[sourceDb]] except when it is a reverse synchronization. In that case it be [[targetDb]].\n */\n public get provenanceSourceDb(): IModelDb {\n return this._options.isReverseSynchronization ? this.targetDb : this.sourceDb;\n }\n\n /** Create an ExternalSourceAspectProps in a standard way for an Element in an iModel --> iModel transformation. */\n public static initElementProvenanceOptions(\n sourceElementId: Id64String,\n targetElementId: Id64String,\n args: {\n sourceDb: IModelDb;\n isReverseSynchronization: boolean;\n targetScopeElementId: Id64String;\n },\n ): ExternalSourceAspectProps {\n const elementId = args.isReverseSynchronization ? sourceElementId : targetElementId;\n const aspectIdentifier = args.isReverseSynchronization ? targetElementId : sourceElementId;\n const aspectProps: ExternalSourceAspectProps = {\n classFullName: ExternalSourceAspect.classFullName,\n element: { id: elementId, relClassName: ElementOwnsExternalSourceAspects.classFullName },\n scope: { id: args.targetScopeElementId },\n identifier: aspectIdentifier,\n kind: ExternalSourceAspect.Kind.Element,\n version: args.sourceDb.elements.queryLastModifiedTime(sourceElementId),\n };\n return aspectProps;\n }\n\n // FIXME: add test using this\n /**\n * Previously the transformer would insert provenance always pointing to the \"target\" relationship.\n * It should (and now by default does) instead insert provenance pointing to the provenanceSource\n * SEE: https://github.com/iTwin/imodel-transformer/issues/54\n * This exists only to facilitate testing that the transformer can handle the older, flawed method\n */\n private _forceOldRelationshipProvenanceMethod = false;\n\n /** Create an ExternalSourceAspectProps in a standard way for an Element in an iModel --> iModel transformation. */\n private initElementProvenance(sourceElementId: Id64String, targetElementId: Id64String): ExternalSourceAspectProps {\n return IModelTransformer.initElementProvenanceOptions(\n sourceElementId,\n targetElementId,\n {\n // FIXME: deprecate isReverseSync option and instead detect from targetScopeElement provenance\n isReverseSynchronization: !!this._options.isReverseSynchronization,\n targetScopeElementId: this.targetScopeElementId,\n sourceDb: this.sourceDb,\n },\n );\n }\n\n /** Create an ExternalSourceAspectProps in a standard way for a Relationship in an iModel --> iModel transformations.\n * The ExternalSourceAspect is meant to be owned by the Element in the target iModel that is the `sourceId` of transformed relationship.\n * The `identifier` property of the ExternalSourceAspect will be the ECInstanceId of the relationship in the source iModel.\n * The ECInstanceId of the relationship in the target iModel will be stored in the JsonProperties of the ExternalSourceAspect.\n */\n private initRelationshipProvenance(sourceRelationship: Relationship, targetRelInstanceId: Id64String): ExternalSourceAspectProps {\n const elementId = this._options.isReverseSynchronization\n ? sourceRelationship.sourceId\n : this.targetDb.withPreparedStatement(\n \"SELECT SourceECInstanceId FROM Bis.ElementRefersToElements WHERE ECInstanceId=?\",\n (stmt) => {\n stmt.bindId(1, targetRelInstanceId);\n nodeAssert(stmt.step() === DbResult.BE_SQLITE_ROW);\n return stmt.getValue(0).getId();\n },\n );\n const aspectIdentifier = this._options.isReverseSynchronization ? targetRelInstanceId : sourceRelationship.id;\n const jsonProperties\n = this._forceOldRelationshipProvenanceMethod\n ? { targetRelInstanceId }\n : { provenanceRelInstanceId: this._isReverseSynchronization\n ? sourceRelationship.id\n : targetRelInstanceId,\n };\n\n const aspectProps: ExternalSourceAspectProps = {\n classFullName: ExternalSourceAspect.classFullName,\n element: { id: elementId, relClassName: ElementOwnsExternalSourceAspects.classFullName },\n scope: { id: this.targetScopeElementId },\n identifier: aspectIdentifier,\n kind: ExternalSourceAspect.Kind.Relationship,\n jsonProperties: JSON.stringify(jsonProperties),\n };\n return aspectProps;\n }\n\n /** NOTE: the json properties must be converted to string before insertion */\n private _targetScopeProvenanceProps:\n Omit<ExternalSourceAspectProps, \"jsonProperties\"> & { jsonProperties: TargetScopeProvenanceJsonProps }\n | undefined\n = undefined;\n\n /**\n * Index of the changeset that the transformer was at when the transformation begins (was constructed).\n * Used to determine at the end which changesets were part of a synchronization.\n */\n private _startingTargetChangesetIndex: number | undefined = undefined;\n\n private _cachedSynchronizationVersion: ChangesetIndexAndId | undefined = undefined;\n\n /** the changeset in the scoping element's source version found for this transformation\n * @note: the version depends on whether this is a reverse synchronization or not, as\n * it is stored separately for both synchronization directions\n * @note: empty string and -1 for changeset and index if it has never been transformed\n */\n private get _synchronizationVersion(): ChangesetIndexAndId {\n if (!this._cachedSynchronizationVersion) {\n nodeAssert(this._targetScopeProvenanceProps, \"_targetScopeProvenanceProps was not set yet\");\n const version = this._options.isReverseSynchronization\n ? this._targetScopeProvenanceProps.jsonProperties.reverseSyncVersion\n : this._targetScopeProvenanceProps.version;\n\n nodeAssert(version !== undefined, \"no version contained in target scope\");\n\n const [id, index] = version === \"\"\n ? [\"\", -1]\n : version.split(\";\");\n this._cachedSynchronizationVersion = { index: Number(index), id };\n nodeAssert(!Number.isNaN(this._cachedSynchronizationVersion.index), \"bad parse: invalid index in version\");\n }\n return this._cachedSynchronizationVersion;\n }\n\n /**\n * Make sure there are no conflicting other scope-type external source aspects on the *target scope element*,\n * If there are none at all, insert one, then this must be a first synchronization.\n * @returns the last synced version (changesetId) on the target scope's external source aspect,\n * if this was a [BriefcaseDb]($backend)\n */\n private initScopeProvenance(): void {\n const aspectProps = {\n id: undefined as string | undefined,\n version: undefined as string | undefined,\n classFullName: ExternalSourceAspect.classFullName,\n element: { id: this.targetScopeElementId, relClassName: ElementOwnsExternalSourceAspects.classFullName },\n scope: { id: IModel.rootSubjectId }, // the root Subject scopes scope elements\n identifier: this.provenanceSourceDb.iModelId,\n kind: ExternalSourceAspect.Kind.Scope,\n jsonProperties: undefined as TargetScopeProvenanceJsonProps | undefined,\n };\n\n // FIXME: handle older transformed iModels which do NOT have the version\n // or reverseSyncVersion set correctly\n const externalSource = this.queryScopeExternalSource(aspectProps, { getJsonProperties: true }); // this query includes \"identifier\"\n aspectProps.id = externalSource.aspectId;\n aspectProps.version = externalSource.version;\n aspectProps.jsonProperties = externalSource.jsonProperties ? JSON.parse(externalSource.jsonProperties) : {};\n\n if (undefined === aspectProps.id) {\n aspectProps.version = \"\"; // empty since never before transformed. Will be updated in [[finalizeTransformation]]\n aspectProps.jsonProperties = {\n pendingReverseSyncChangesetIndices: [],\n pendingSyncChangesetIndices: [],\n reverseSyncVersion: \"\", // empty since never before transformed. Will be updated in first reverse sync\n };\n\n // this query does not include \"identifier\" to find possible conflicts\n const sql = `\n SELECT ECInstanceId\n FROM ${ExternalSourceAspect.classFullName}\n WHERE Element.Id=:elementId\n AND Scope.Id=:scopeId\n AND Kind=:kind\n LIMIT 1\n `;\n\n const hasConflictingScope = this.provenanceDb.withPreparedStatement(sql, (statement: ECSqlStatement): boolean => {\n statement.bindId(\"elementId\", aspectProps.element.id);\n statement.bindId(\"scopeId\", aspectProps.scope.id); // this scope.id can never be invalid, we create it above\n statement.bindString(\"kind\", aspectProps.kind);\n return DbResult.BE_SQLITE_ROW === statement.step();\n });\n\n if (hasConflictingScope) {\n throw new IModelError(IModelStatus.InvalidId, \"Provenance scope conflict\");\n }\n if (!this._options.noProvenance) {\n this.provenanceDb.elements.insertAspect({\n ...aspectProps,\n jsonProperties: JSON.stringify(aspectProps.jsonProperties) as any,\n });\n }\n }\n\n this._targetScopeProvenanceProps = aspectProps as typeof this._targetScopeProvenanceProps;\n }\n\n /**\n * @returns the id and version of an aspect with the given element, scope, kind, and identifier\n * May also return a reverseSyncVersion from json properties if requested\n */\n private queryScopeExternalSource(aspectProps: ExternalSourceAspectProps, { getJsonProperties = false } = {}): {\n aspectId?: Id64String;\n version?: string;\n /** stringified json */\n jsonProperties?: string;\n } {\n const sql = `\n SELECT ECInstanceId, Version\n ${getJsonProperties ? \", JsonProperties\" : \"\"}\n FROM ${ExternalSourceAspect.classFullName}\n WHERE Element.Id=:elementId\n AND Scope.Id=:scopeId\n AND Kind=:kind\n AND Identifier=:identifier\n LIMIT 1\n `;\n const emptyResult = { aspectId: undefined, version: undefined, jsonProperties: undefined };\n return this.provenanceDb.withPreparedStatement(sql, (statement: ECSqlStatement) => {\n statement.bindId(\"elementId\", aspectProps.element.id);\n if (aspectProps.scope === undefined)\n return emptyResult; // return undefined instead of binding an invalid id\n statement.bindId(\"scopeId\", aspectProps.scope.id);\n statement.bindString(\"kind\", aspectProps.kind);\n statement.bindString(\"identifier\", aspectProps.identifier);\n if (DbResult.BE_SQLITE_ROW !== statement.step())\n return emptyResult;\n const aspectId = statement.getValue(0).getId();\n const version = statement.getValue(1).getString();\n const jsonProperties = getJsonProperties ? statement.getValue(2).getString() : undefined;\n return { aspectId, version, jsonProperties };\n });\n }\n\n /**\n * Iterate all matching federation guids and ExternalSourceAspects in the provenance iModel (target unless reverse sync)\n * and call a function for each one.\n * @note provenance is done by federation guids where possible\n * @note this may execute on each element more than once! Only use in cases where that is handled\n */\n public static forEachTrackedElement(args: {\n provenanceSourceDb: IModelDb;\n provenanceDb: IModelDb;\n targetScopeElementId: Id64String;\n isReverseSynchronization: boolean;\n fn: (sourceElementId: Id64String, targetElementId: Id64String) => void;\n }): void {\n if (args.provenanceDb === args.provenanceSourceDb)\n return;\n\n if (!args.provenanceDb.containsClass(ExternalSourceAspect.classFullName)) {\n throw new IModelError(IModelStatus.BadSchema, \"The BisCore schema version of the target database is too old\");\n }\n\n const sourceDb = args.isReverseSynchronization ? args.provenanceDb : args.provenanceSourceDb;\n const targetDb = args.isReverseSynchronization ? args.provenanceSourceDb : args.provenanceDb;\n\n // query for provenanceDb\n const elementIdByFedGuidQuery = `\n SELECT e.ECInstanceId, FederationGuid\n FROM bis.Element e\n WHERE e.ECInstanceId NOT IN (0x1, 0xe, 0x10) -- special static elements\n ORDER BY FederationGuid\n `;\n\n // iterate through sorted list of fed guids from both dbs to get the intersection\n // NOTE: if we exposed the native attach database support,\n // we could get the intersection of fed guids in one query, not sure if it would be faster\n // OR we could do a raw sqlite query...\n sourceDb.withStatement(elementIdByFedGuidQuery, (sourceStmt) => targetDb.withStatement(elementIdByFedGuidQuery, (targetStmt) => {\n if (sourceStmt.step() !== DbResult.BE_SQLITE_ROW)\n return;\n let sourceRow = sourceStmt.getRow() as { federationGuid?: GuidString, id: Id64String };\n if (targetStmt.step() !== DbResult.BE_SQLITE_ROW)\n return;\n let targetRow = targetStmt.getRow() as { federationGuid?: GuidString, id: Id64String };\n\n // NOTE: these comparisons rely upon the lowercase of the guid,\n // and the fact that '0' < '9' < a' < 'f' in ascii/utf8\n while (true) {\n const currSourceRow = sourceRow, currTargetRow = targetRow;\n if (currSourceRow.federationGuid !== undefined\n && currTargetRow.federationGuid !== undefined\n && currSourceRow.federationGuid === currTargetRow.federationGuid\n ) {\n // data flow direction is always sourceDb -> targetDb and it does not depend on where the explicit element provenance is stored\n args.fn(sourceRow.id, targetRow.id);\n }\n if (currTargetRow.federationGuid === undefined\n || (currSourceRow.federationGuid !== undefined\n && currSourceRow.federationGuid >= currTargetRow.federationGuid)\n ) {\n if (targetStmt.step() !== DbResult.BE_SQLITE_ROW)\n return;\n targetRow = targetStmt.getRow();\n }\n if (currSourceRow.federationGuid === undefined\n || (currTargetRow.federationGuid !== undefined\n && currSourceRow.federationGuid <= currTargetRow.federationGuid)\n ) {\n if (sourceStmt.step() !== DbResult.BE_SQLITE_ROW)\n return;\n sourceRow = sourceStmt.getRow();\n }\n }\n }));\n\n // query for provenanceDb\n const provenanceAspectsQuery = `\n SELECT esa.Identifier, Element.Id\n FROM bis.ExternalSourceAspect esa\n WHERE Scope.Id=:scopeId\n AND Kind=:kind\n `;\n\n // Technically this will a second time call the function (as documented) on\n // victims of the old provenance method that have both fedguids and an inserted aspect.\n // But this is a private function with one known caller where that doesn't matter\n args.provenanceDb.withPreparedStatement(provenanceAspectsQuery, (stmt): void => {\n const runFnInDataFlowDirection = (sourceId: Id64String, targetId: Id64String) =>\n args.isReverseSynchronization ? args.fn(sourceId, targetId) : args.fn(targetId, sourceId);\n stmt.bindId(\"scopeId\", args.targetScopeElementId);\n stmt.bindString(\"kind\", ExternalSourceAspect.Kind.Element);\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\n // ExternalSourceAspect.Identifier is of type string\n const aspectIdentifier: Id64String = stmt.getValue(0).getString();\n const elementId: Id64String = stmt.getValue(1).getId();\n runFnInDataFlowDirection(elementId, aspectIdentifier);\n }\n });\n }\n\n private forEachTrackedElement(fn: (sourceElementId: Id64String, targetElementId: Id64String) => void): void {\n return IModelTransformer.forEachTrackedElement({\n provenanceSourceDb: this.provenanceSourceDb,\n provenanceDb: this.provenanceDb,\n targetScopeElementId: this.targetScopeElementId,\n isReverseSynchronization: !!this._options.isReverseSynchronization,\n fn,\n });\n }\n\n /** Initialize the source to target Element mapping from ExternalSourceAspects in the target iModel.\n * @note This method is called from all `process*` functions and should never need to be called directly.\n * @deprecated in 3.x. call [[initialize]] instead, it does the same thing among other initialization\n * @note Passing an [[InitFromExternalSourceAspectsArgs]] is required when processing changes, to remap any elements that may have been deleted.\n * You must await the returned promise as well in this case. The synchronous behavior has not changed but is deprecated and won't process everything.\n */\n public initFromExternalSourceAspects(args?: InitOptions): void | Promise<void> {\n this.forEachTrackedElement((sourceElementId: Id64String, targetElementId: Id64String) => {\n this.context.remapElement(sourceElementId, targetElementId);\n });\n\n if (args)\n return this.remapDeletedSourceEntities();\n }\n\n /**\n * Scan changesets for deleted entities, if in a reverse synchronization, provenance has\n * already been deleted, so we must scan for that as well.\n */\n private async remapDeletedSourceEntities() {\n // we need a connected iModel with changes to remap elements with deletions\n const notConnectedModel = this.sourceDb.iTwinId === undefined;\n const noChanges = this._synchronizationVersion.index === this.sourceDb.changeset.index;\n if (notConnectedModel || noChanges)\n return;\n\n this._deletedSourceRelationshipData = new Map();\n\n nodeAssert(this._changeSummaryIds, \"change summaries should be initialized before we get here\");\n nodeAssert(this._changeSummaryIds.length > 0, \"change summaries should have at least one\");\n\n const alreadyImportedElementInserts = new Set<Id64String> ();\n const alreadyImportedModelInserts = new Set<Id64String> ();\n this.exporter.sourceDbChanges?.element.insertIds.forEach((insertedSourceElementId) => {\n const targetElementId = this.context.findTargetElementId(insertedSourceElementId);\n if (Id64.isValid(targetElementId))\n alreadyImportedElementInserts.add(targetElementId);\n });\n this.exporter.sourceDbChanges?.model.insertIds.forEach((insertedSourceModelId) => {\n const targetModelId = this.context.findTargetElementId(insertedSourceModelId);\n if (Id64.isValid(targetModelId))\n alreadyImportedModelInserts.add(targetModelId);\n });\n\n // optimization: if we have provenance, use it to avoid more querying later\n // eventually when itwin.js supports attaching a second iModelDb in JS,\n // this won't have to be a conditional part of the query, and we can always have it by attaching\n const queryCanAccessProvenance = this.sourceDb === this.provenanceDb;\n\n const deletedEntitySql = `\n SELECT\n 1 AS IsElemNotRel,\n ic.ChangedInstance.Id AS InstanceId,\n NULL AS InstId2, -- need these columns for relationship ends in the unioned query\n NULL AS InstId3,\n ec.FederationGuid AS FedGuid,\n NULL AS FedGuid2,\n ic.ChangedInstance.ClassId AS ClassId\n ${queryCanAccessProvenance ? `\n , coalesce(esa.Identifier, esac.Identifier) AS Identifier1\n , NULL AS Identifier2\n ` : \"\"}\n FROM ecchange.change.InstanceChange ic\n LEFT JOIN bis.Element.Changes(:changeSummaryId, 'BeforeDelete') ec\n ON ic.ChangedInstance.Id=ec.ECInstanceId\n ${queryCanAccessProvenance ? `\n LEFT JOIN bis.ExternalSourceAspect esa\n ON ec.ECInstanceId=esa.Element.Id\n LEFT JOIN bis.ExternalSourceAspect.Changes(:changeSummaryId, 'BeforeDelete') esac\n ON ec.ECInstanceId=esac.Element.Id\n ` : \"\"\n }\n WHERE ic.OpCode=:opDelete\n AND ic.Summary.Id=:changeSummaryId\n AND ic.ChangedInstance.ClassId IS (BisCore.Element)\n ${queryCanAccessProvenance ? `\n AND (esa.Scope.Id=:targetScopeElement OR esa.Scope.Id IS NULL)\n AND (esa.Kind='Element' OR esa.Kind IS NULL)\n AND (esac.Scope.Id=:targetScopeElement OR esac.Scope.Id IS NULL)\n AND (esac.Kind='Element' OR esac.Kind IS NULL)\n ` : \"\"\n }\n\n UNION ALL\n\n SELECT\n 0 AS IsElemNotRel,\n ic.ChangedInstance.Id AS InstanceId,\n coalesce(se.ECInstanceId, sec.ECInstanceId) AS InstId2,\n coalesce(te.ECInstanceId, tec.ECInstanceId) AS InstId3,\n coalesce(se.FederationGuid, sec.FederationGuid) AS FedGuid1,\n coalesce(te.FederationGuid, tec.FederationGuid) AS FedGuid2,\n ic.ChangedInstance.ClassId AS ClassId\n ${queryCanAccessProvenance ? `\n , coalesce(sesa.Identifier, sesac.Identifier) AS Identifier1\n , coalesce(tesa.Identifier, tesac.Identifier) AS Identifier2\n ` : \"\"}\n FROM ecchange.change.InstanceChange ic\n LEFT JOIN bis.ElementRefersToElements.Changes(:changeSummaryId, 'BeforeDelete') ertec\n ON ic.ChangedInstance.Id=ertec.ECInstanceId\n -- FIXME: test a deletion of both an element and a relationship at the same time\n LEFT JOIN bis.Element se\n ON se.ECInstanceId=ertec.SourceECInstanceId\n LEFT JOIN bis.Element te\n ON te.ECInstanceId=ertec.TargetECInstanceId\n LEFT JOIN bis.Element.Changes(:changeSummaryId, 'BeforeDelete') sec\n ON sec.ECInstanceId=ertec.SourceECInstanceId\n LEFT JOIN bis.Element.Changes(:changeSummaryId, 'BeforeDelete') tec\n ON tec.ECInstanceId=ertec.TargetECInstanceId\n ${queryCanAccessProvenance ? `\n -- NOTE: need to join on both se/te and sec/tec incase the element was deleted\n LEFT JOIN bis.ExternalSourceAspect sesa\n ON se.ECInstanceId=sesa.Element.Id -- don't use *esac*.Identifier because it's a string\n LEFT JOIN bis.ExternalSourceAspect.Changes(:changeSummaryId, 'BeforeDelete') sesac\n ON sec.ECInstanceId=sesac.Element.Id\n LEFT JOIN bis.ExternalSourceAspect tesa\n ON te.ECInstanceId=tesa.Element.Id\n LEFT JOIN bis.ExternalSourceAspect.Changes(:changeSummaryId, 'BeforeDelete') tesac\n ON tec.ECInstanceId=tesac.Element.Id\n ` : \"\"\n }\n WHERE ic.OpCode=:opDelete\n AND ic.Summary.Id=:changeSummaryId\n AND ic.ChangedInstance.ClassId IS (BisCore.ElementRefersToElements)\n ${queryCanAccessProvenance ? `\n AND (sesa.Scope.Id=:targetScopeElement OR sesa.Scope.Id IS NULL)\n AND (sesa.Kind='Relationship' OR sesa.Kind IS NULL)\n AND (sesac.Scope.Id=:targetScopeElement OR sesac.Scope.Id IS NULL)\n AND (sesac.Kind='Relationship' OR sesac.Kind IS NULL)\n AND (tesa.Scope.Id=:targetScopeElement OR tesa.Scope.Id IS NULL)\n AND (tesa.Kind='Relationship' OR tesa.Kind IS NULL)\n AND (tesac.Scope.Id=:targetScopeElement OR tesac.Scope.Id IS NULL)\n AND (tesac.Kind='Relationship' OR tesac.Kind IS NULL)\n ` : \"\"\n }\n `;\n\n for (const changeSummaryId of this._changeSummaryIds) {\n // FIXME: test deletion in both forward and reverse sync\n this.sourceDb.withPreparedStatement(deletedEntitySql, (stmt) => {\n stmt.bindInteger(\"opDelete\", ChangeOpCode.Delete);\n if (queryCanAccessProvenance)\n stmt.bindId(\"targetScopeElement\", this.targetScopeElementId);\n stmt.bindId(\"changeSummaryId\", changeSummaryId);\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\n const isElemNotRel = stmt.getValue(0).getBoolean();\n const instId = stmt.getValue(1).getId();\n\n if (isElemNotRel) {\n const sourceElemFedGuid = stmt.getValue(4).getGuid();\n // \"Identifier\" is a string, so null value returns '' which doesn't work with ??, and I don't like ||\n let identifierValue: ECSqlValue;\n\n // TODO: if I could attach the second db, will probably be much faster to get target id\n // as part of the whole query rather than with _queryElemIdByFedGuid\n const targetId =\n (queryCanAccessProvenance\n && (identifierValue = stmt.getValue(7))\n && !identifierValue.isNull\n && identifierValue.getString())\n // maybe batching these queries would perform better but we should\n // try to attach the second db and query both together anyway\n || (sourceElemFedGuid && this._queryElemIdByFedGuid(this.targetDb, sourceElemFedGuid))\n // FIXME: describe why it's safe to assume nothing has been deleted in provenanceDb\n || this._queryProvenanceForElement(instId);\n\n // since we are processing one changeset at a time, we can see local source deletes\n // of entities that were never synced and can be safely ignored\n const deletionNotInTarget = !targetId;\n if (deletionNotInTarget)\n continue;\n\n this.context.remapElement(instId, targetId);\n // If an entity insert and an entity delete both point to the same entity in target iModel, that means that entity was recreated.\n // In such case an entity update will be triggered and we no longer need to delete the entity.\n if (alreadyImportedElementInserts.has(targetId)) {\n this.exporter.sourceDbChanges?.element.deleteIds.delete(instId);\n }\n if (alreadyImportedModelInserts.has(targetId)) {\n this.exporter.sourceDbChanges?.model.deleteIds.delete(instId);\n }\n\n } else { // is deleted relationship\n const classFullName = stmt.getValue(6).getClassNameForClassId();\n const [sourceIdInTarget, targetIdInTarget] = [\n { guidColumn: 4, identifierColumn: 7, isTarget: false },\n { guidColumn: 5, identifierColumn: 8, isTarget: true },\n ].map(({ guidColumn, identifierColumn }) => {\n const fedGuid = stmt.getValue(guidColumn).getGuid();\n let identifierValue: ECSqlValue;\n return (\n (queryCanAccessProvenance\n // FIXME: this is really far from idiomatic, try to undo that\n && (identifierValue = stmt.getValue(identifierColumn))\n && !identifierValue.isNull\n && identifierValue.getString())\n // maybe batching these queries would perform better but we should\n // try to attach the second db and query both together anyway\n || (fedGuid && this._queryElemIdByFedGuid(this.targetDb, fedGuid))\n );\n });\n\n // since we are processing one changeset at a time, we can see local source deletes\n // of entities that were never synced and can be safely ignored\n if (sourceIdInTarget && targetIdInTarget) {\n this._deletedSourceRelationshipData!.set(instId, {\n classFullName,\n sourceIdInTarget,\n targetIdInTarget,\n });\n } else {\n // FIXME: describe why it's safe to assume nothing has been deleted in provenanceDb\n const relProvenance = this._queryProvenanceForRelationship(instId, {\n classFullName,\n sourceId: stmt.getValue(2).getId(),\n targetId: stmt.getValue(3).getId(),\n });\n if (relProvenance && relProvenance.relationshipId)\n this._deletedSourceRelationshipData!.set(instId, {\n classFullName,\n relId: relProvenance.relationshipId,\n provenanceAspectId: relProvenance.aspectId,\n });\n }\n }\n }\n // NEXT: remap sourceId and targetId to target, get provenance there\n // NOTE: it is possible during a forward sync for the target to already have deleted\n // something that the source deleted, in which case we can safely ignore the gone provenance\n });\n }\n }\n\n private _queryProvenanceForElement(entityInProvenanceSourceId: Id64String): Id64String | undefined {\n return this.provenanceDb.withPreparedStatement(`\n SELECT esa.Element.Id\n FROM Bis.ExternalSourceAspect esa\n WHERE esa.Kind=?\n AND esa.Scope.Id=?\n AND esa.Identifier=?\n `, (stmt) => {\n stmt.bindString(1, ExternalSourceAspect.Kind.Element);\n stmt.bindId(2, this.targetScopeElementId);\n stmt.bindString(3, entityInProvenanceSourceId);\n if (stmt.step() === DbResult.BE_SQLITE_ROW)\n return stmt.getValue(0).getId();\n else\n return undefined;\n });\n }\n\n private _queryProvenanceForRelationship(\n entityInProvenanceSourceId: Id64String,\n sourceRelInfo: {\n classFullName: string;\n sourceId: Id64String;\n targetId: Id64String;\n }): {\n aspectId: Id64String;\n /** if undefined, the relationship could not be found, perhaps it was deleted */\n relationshipId: Id64String | undefined;\n } | undefined {\n return this.provenanceDb.withPreparedStatement(`\n SELECT\n ECInstanceId,\n JSON_EXTRACT(JsonProperties, '$.targetRelInstanceId'),\n JSON_EXTRACT(JsonProperties, '$.provenanceRelInstanceId')\n FROM Bis.ExternalSourceAspect\n WHERE Kind=?\n AND Scope.Id=?\n AND Identifier=?\n `, (stmt) => {\n stmt.bindString(1, ExternalSourceAspect.Kind.Relationship);\n stmt.bindId(2, this.targetScopeElementId);\n stmt.bindString(3, entityInProvenanceSourceId);\n if (stmt.step() !== DbResult.BE_SQLITE_ROW)\n return undefined;\n\n const aspectId = stmt.getValue(0).getId();\n const provenanceRelInstIdVal = stmt.getValue(2);\n const provenanceRelInstanceId\n = !provenanceRelInstIdVal.isNull\n ? provenanceRelInstIdVal.getString()\n : this._queryTargetRelId(sourceRelInfo);\n return {\n aspectId,\n relationshipId: provenanceRelInstanceId,\n };\n });\n }\n\n private _queryTargetRelId(sourceRelInfo: {\n classFullName: string;\n sourceId: Id64String;\n targetId: Id64String;\n }): Id64String | undefined {\n const targetRelInfo = {\n sourceId: this.context.findTargetElementId(sourceRelInfo.sourceId),\n targetId: this.context.findTargetElementId(sourceRelInfo.targetId),\n };\n if (targetRelInfo.sourceId === undefined || targetRelInfo.targetId === undefined)\n return undefined; // couldn't find an element, rel is invalid or deleted\n return this.targetDb.withPreparedStatement(`\n SELECT ECInstanceId\n FROM bis.ElementRefersToElements\n WHERE SourceECInstanceId=?\n AND TargetECInstanceId=?\n AND ECClassId=?\n `, (stmt) => {\n stmt.bindId(1, targetRelInfo.sourceId);\n stmt.bindId(2, targetRelInfo.targetId);\n stmt.bindId(3, this._targetClassNameToClassId(sourceRelInfo.classFullName));\n if (stmt.step() !== DbResult.BE_SQLITE_ROW)\n return undefined;\n return stmt.getValue(0).getId();\n });\n }\n\n private _targetClassNameToClassIdCache = new Map<string, string>();\n\n private _targetClassNameToClassId(classFullName: string): Id64String {\n let classId = this._targetClassNameToClassIdCache.get(classFullName);\n if (classId === undefined) {\n classId = this._getRelClassId(this.targetDb, classFullName);\n this._targetClassNameToClassIdCache.set(classFullName, classId);\n }\n return classId;\n }\n\n // NOTE: this doesn't handle remapped element classes,\n // but is only used for relationships rn\n private _getRelClassId(db: IModelDb, classFullName: string): Id64String {\n return db.withPreparedStatement(`\n SELECT c.ECInstanceId\n FROM ECDbMeta.ECClassDef c\n JOIN ECDbMeta.ECSchemaDef s ON c.Schema.Id=s.ECInstanceId\n WHERE s.Name=? AND c.Name=?\n `, (stmt) => {\n const [schemaName, className] = classFullName.split(\".\");\n stmt.bindString(1, schemaName);\n stmt.bindString(2, className);\n if (stmt.step() === DbResult.BE_SQLITE_ROW)\n return stmt.getValue(0).getId();\n assert(false, \"relationship was not found\");\n }\n );\n }\n\n private _queryElemIdByFedGuid(db: IModelDb, fedGuid: GuidString): Id64String | undefined {\n return db.withPreparedStatement(\"SELECT ECInstanceId FROM Bis.Element WHERE FederationGuid=?\", (stmt) => {\n stmt.bindGuid(1, fedGuid);\n if (stmt.step() === DbResult.BE_SQLITE_ROW)\n return stmt.getValue(0).getId();\n else\n return undefined;\n });\n }\n\n /** Returns `true` if *brute force* delete detections should be run.\n * @note Not relevant for processChanges when change history is known.\n */\n private shouldDetectDeletes(): boolean {\n // FIXME: all synchronizations should mark this as false\n if (this._isFirstSynchronization)\n return false; // not necessary the first time since there are no deletes to detect\n\n if (this._options.isReverseSynchronization)\n return false; // not possible for a reverse synchronization since provenance will be deleted when element is deleted\n\n return true;\n }\n\n /**\n * Detect Element deletes using ExternalSourceAspects in the target iModel and a *brute force* comparison against Elements\n * in the source iModel.\n * @deprecated in 0.1.x. This method is only called during [[processAll]] when the option\n * [[IModelTransformerOptions.forceExternalSourceAspectProvenance]] is enabled. It is not\n * necessary when using [[processChanges]] since changeset information is sufficient.\n * @note you do not need to call this directly unless processing a subset of an iModel.\n * @throws [[IModelError]] If the required provenance information is not available to detect deletes.\n */\n public async detectElementDeletes(): Promise<void> {\n const sql = `\n SELECT Identifier, Element.Id\n FROM BisCore.ExternalSourceAspect\n WHERE Scope.Id=:scopeId\n AND Kind=:kind\n `;\n\n nodeAssert(\n !this._options.isReverseSynchronization,\n \"synchronizations with processChagnes already detect element deletes, don't call detectElementDeletes\"\n );\n\n this.provenanceDb.withPreparedStatement(sql, (stmt) => {\n stmt.bindId(\"scopeId\", this.targetScopeElementId);\n stmt.bindString(\"kind\", ExternalSourceAspect.Kind.Element);\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\n // ExternalSourceAspect.Identifier is of type string\n const aspectIdentifier = stmt.getValue(0).getString();\n if (!Id64.isId64(aspectIdentifier)) {\n continue;\n }\n const targetElemId = stmt.getValue(1).getId();\n const wasDeletedInSource = !EntityUnifier.exists(this.sourceDb, { entityReference: `e${aspectIdentifier}` });\n if (wasDeletedInSource)\n this.importer.deleteElement(targetElemId);\n }\n });\n }\n\n /**\n * @deprecated in 3.x, this no longer has any effect except emitting a warning\n */\n protected skipElement(_sourceElement: Element): void {\n Logger.logWarning(loggerCategory, `Tried to defer/skip an element, which is no longer necessary`);\n }\n\n /** Transform the specified sourceElement into ElementProps for the target iModel.\n * @param sourceElement The Element from the source iModel to transform.\n * @returns ElementProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n * @note This can be called more than once for an element in arbitrary order, so it should not have side-effects.\n */\n public onTransformElement(sourceElement: Element): ElementProps {\n Logger.logTrace(loggerCategory, `onTransformElement(${sourceElement.id}) \"${sourceElement.getDisplayLabel()}\"`);\n const targetElementProps: ElementProps = this.context.cloneElement(sourceElement, { binaryGeometry: this._options.cloneUsingBinaryGeometry });\n if (sourceElement instanceof Subject) {\n if (targetElementProps.jsonProperties?.Subject?.Job) {\n // don't propagate source channels into target (legacy bridge case)\n targetElementProps.jsonProperties.Subject.Job = undefined;\n }\n }\n return targetElementProps;\n }\n\n // if undefined, it can be initialized by calling [[this._cacheSourceChanges]]\n private _hasElementChangedCache?: Set<Id64String> = undefined;\n private _deletedSourceRelationshipData?: Map<Id64String, {\n sourceIdInTarget?: Id64String;\n targetIdInTarget?: Id64String;\n classFullName: Id64String;\n relId?: Id64String;\n provenanceAspectId?: Id64String;\n }> = undefined;\n\n // FIXME: this is a PoC, see if we minimize memory usage\n private _cacheSourceChanges() {\n nodeAssert(this._changeSummaryIds && this._changeSummaryIds.length > 0, \"should have changeset data by now\");\n this._hasElementChangedCache = new Set();\n\n const query = `\n SELECT\n ic.ChangedInstance.Id AS InstId\n FROM ecchange.change.InstanceChange ic\n JOIN iModelChange.Changeset imc ON ic.Summary.Id=imc.Summary.Id\n -- FIXME: do relationship entities also need this cache optimization?\n WHERE ic.ChangedInstance.ClassId IS (BisCore.Element)\n AND InVirtualSet(:changeSummaryIds, ic.Summary.Id)\n -- ignore deleted, we take care of those in remapDeletedSourceEntities\n -- include inserted since inserted code-colliding elements should be considered\n -- a change so that the colliding element is exported to the target\n AND ic.OpCode<>:opDelete\n `;\n\n // there is a single mega-query multi-join+coalescing hack that I used originally to get around\n // only being able to run table.Changes() on one changeset at once, but sqlite only supports up to 64\n // tables in a join. Need to talk to core about .Changes being able to take a set of changesets\n // You can find this version in the `federation-guid-optimization-megaquery` branch\n // I wouldn't use it unless we prove via profiling that it speeds things up significantly\n // And even then let's first try scanning the raw changesets instead of applying them as these queries\n // require\n this.sourceDb.withPreparedStatement(query,\n (stmt) => {\n stmt.bindInteger(\"opDelete\", ChangeOpCode.Delete);\n stmt.bindIdSet(\"changeSummaryIds\", this._changeSummaryIds!);\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\n const instId = stmt.getValue(0).getId();\n this._hasElementChangedCache!.add(instId);\n }\n }\n );\n }\n\n /** Returns true if a change within sourceElement is detected.\n * @param sourceElement The Element from the source iModel\n * @param targetElementId The Element from the target iModel to compare against.\n * @note A subclass can override this method to provide custom change detection behavior.\n */\n protected hasElementChanged(sourceElement: Element, _targetElementId: Id64String): boolean {\n if (this._sourceChangeDataState === \"no-changes\")\n return false;\n if (this._sourceChangeDataState === \"unconnected\")\n return true;\n nodeAssert(this._sourceChangeDataState === \"has-changes\", \"change data should be initialized by now\");\n if (this._hasElementChangedCache === undefined)\n this._cacheSourceChanges();\n return this._hasElementChangedCache!.has(sourceElement.id);\n }\n\n private static transformCallbackFor(transformer: IModelTransformer, entity: ConcreteEntity): EntityTransformHandler {\n if (entity instanceof Element)\n return transformer.onTransformElement as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else if (entity instanceof Element)\n return transformer.onTransformModel as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else if (entity instanceof Relationship)\n return transformer.onTransformRelationship as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else if (entity instanceof ElementAspect)\n return transformer.onTransformElementAspect as EntityTransformHandler; // eslint-disable-line @typescript-eslint/unbound-method\n else\n assert(false, `unreachable; entity was '${entity.constructor.name}' not an Element, Relationship, or ElementAspect`);\n }\n\n /** callback to perform when a partial element says it's ready to be completed\n * transforms the source element with all references now valid, then updates the partial element with the results\n */\n private makePartialEntityCompleter(\n sourceEntity: ConcreteEntity\n ) {\n return () => {\n const targetId = this.context.findTargetEntityId(EntityReferences.from(sourceEntity));\n if (!EntityReferences.isValid(targetId))\n throw Error(`${sourceEntity.id} has not been inserted into the target yet, the completer is invalid. This is a bug.`);\n const onEntityTransform = IModelTransformer.transformCallbackFor(this, sourceEntity);\n const updateEntity = EntityUnifier.updaterFor(this.targetDb, sourceEntity);\n const targetProps = onEntityTransform.call(this, sourceEntity);\n if (sourceEntity instanceof Relationship) {\n (targetProps as RelationshipProps).sourceId = this.context.findTargetElementId(sourceEntity.sourceId);\n (targetProps as RelationshipProps).targetId = this.context.findTargetElementId(sourceEntity.targetId);\n }\n updateEntity({ ...targetProps, id: EntityReferences.toId64(targetId) });\n this._partiallyCommittedEntities.delete(sourceEntity);\n };\n }\n\n /** collect references this entity has that are yet to be mapped, and if there are any\n * create a [[PartiallyCommittedEntity]] to track resolution of those references\n */\n private collectUnmappedReferences(entity: ConcreteEntity) {\n const missingReferences = new EntityReferenceSet();\n let thisPartialElem: PartiallyCommittedEntity | undefined;\n\n // eslint-disable-next-line deprecation/deprecation\n for (const referenceId of entity.getReferenceConcreteIds()) {\n // TODO: probably need to rename from 'id' to 'ref' so these names aren't so ambiguous\n const referenceIdInTarget = this.context.findTargetEntityId(referenceId);\n const alreadyProcessed = EntityReferences.isValid(referenceIdInTarget) || this._skippedEntities.has(referenceId);\n if (alreadyProcessed)\n continue;\n Logger.logTrace(loggerCategory, `Deferring resolution of reference '${referenceId}' of element '${entity.id}'`);\n const referencedExistsInSource = EntityUnifier.exists(this.sourceDb, { entityReference: referenceId });\n if (!referencedExistsInSource) {\n Logger.logWarning(loggerCategory, `Source ${EntityUnifier.getReadableType(entity)} (${entity.id}) has a dangling reference to (${referenceId})`);\n switch (this._options.danglingReferencesBehavior) {\n case \"ignore\":\n continue;\n case \"reject\":\n throw new IModelError(\n IModelStatus.NotFound,\n [\n `Found a reference to an element \"${referenceId}\" that doesn't exist while looking for references of \"${entity.id}\".`,\n \"This must have been caused by an upstream application that changed the iModel.\",\n \"You can set the IModelTransformerOptions.danglingReferencesBehavior option to 'ignore' to ignore this, but this will leave the iModel\",\n \"in a state where downstream consuming applications will need to handle the invalidity themselves. In some cases, writing a custom\",\n \"transformer to remove the reference and fix affected elements may be suitable.\",\n ].join(\"\\n\")\n );\n }\n }\n if (thisPartialElem === undefined) {\n thisPartialElem = new PartiallyCommittedEntity(missingReferences, this.makePartialEntityCompleter(entity));\n if (!this._partiallyCommittedEntities.has(entity))\n this._partiallyCommittedEntities.set(entity, thisPartialElem);\n }\n missingReferences.add(referenceId);\n const entityReference = EntityReferences.from(entity);\n this._pendingReferences.set({ referenced: referenceId, referencer: entityReference }, thisPartialElem);\n }\n }\n\n /** Cause the specified Element and its child Elements (if applicable) to be exported from the source iModel and imported into the target iModel.\n * @param sourceElementId Identifies the Element from the source iModel to import.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processElement(sourceElementId: Id64String): Promise<void> {\n await this.initialize();\n if (sourceElementId === IModel.rootSubjectId) {\n throw new IModelError(IModelStatus.BadRequest, \"The root Subject should not be directly imported\");\n }\n return this.exporter.exportElement(sourceElementId);\n }\n\n /** Import child elements into the target IModelDb\n * @param sourceElementId Import the child elements of this element in the source IModelDb.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processChildElements(sourceElementId: Id64String): Promise<void> {\n await this.initialize();\n return this.exporter.exportChildElements(sourceElementId);\n }\n\n /** Override of [IModelExportHandler.shouldExportElement]($transformer) that is called to determine if an element should be exported from the source iModel.\n * @note Reaching this point means that the element has passed the standard exclusion checks in IModelExporter.\n */\n public override shouldExportElement(_sourceElement: Element): boolean { return true; }\n\n public override onSkipElement(sourceElementId: Id64String): void {\n if (this.context.findTargetElementId(sourceElementId) !== Id64.invalid) {\n // element already has provenance\n return;\n }\n\n Logger.logInfo(loggerCategory, `Element '${sourceElementId}' won't be exported. Marking its references as resolved`);\n const elementKey: EntityKey = `e${sourceElementId}`;\n this._skippedEntities.add(elementKey);\n\n // Mark any existing pending references to the skipped element as resolved.\n for (const referencer of this._pendingReferences.getReferencersByEntityKey(elementKey)) {\n const key = PendingReference.from(referencer, elementKey);\n const pendingRef = this._pendingReferences.get(key);\n if (!pendingRef)\n continue;\n pendingRef.resolveReference(elementKey);\n this._pendingReferences.delete(key);\n }\n }\n\n /**\n * If they haven't been already, import all of the required references\n * @internal do not call, override or implement this, it will be removed\n */\n public override async preExportElement(sourceElement: Element): Promise<void> {\n const elemClass = sourceElement.constructor as typeof Element;\n\n const unresolvedReferences = elemClass.requiredReferenceKeys\n .map((referenceKey) => {\n const idContainer = sourceElement[referenceKey as keyof Element];\n const referenceType = elemClass.requiredReferenceKeyTypeMap[referenceKey];\n // For now we just consider all required references to be elements (as they are in biscore), and do not support\n // entities that refuse to be inserted without a different kind of entity (e.g. aspect or relationship) first being inserted\n assert(referenceType === ConcreteEntityTypes.Element || referenceType === ConcreteEntityTypes.Model);\n return mapId64(idContainer, (id) => {\n if (id === Id64.invalid || id === IModel.rootSubjectId)\n return undefined; // not allowed to directly export the root subject\n if (!this.context.isBetweenIModels) {\n // Within the same iModel, can use existing DefinitionElements without remapping\n // This is relied upon by the TemplateModelCloner\n // TODO: extract this out to only be in the TemplateModelCloner\n const asDefinitionElem = this.sourceDb.elements.tryGetElement(id, DefinitionElement);\n if (asDefinitionElem && !(asDefinitionElem instanceof RecipeDefinitionElement)) {\n this.context.remapElement(id, id);\n }\n }\n return id;\n })\n .filter((sourceReferenceId: Id64String | undefined): sourceReferenceId is Id64String => {\n if (sourceReferenceId === undefined)\n return false;\n const referenceInTargetId = this.context.findTargetElementId(sourceReferenceId);\n const isInTarget = Id64.isValid(referenceInTargetId);\n return !isInTarget;\n });\n })\n .flat();\n\n if (unresolvedReferences.length > 0) {\n for (const reference of unresolvedReferences) {\n const processState = this.getElemTransformState(reference);\n // must export element first\n if (processState.needsElemImport)\n await this.exporter.exportElement(reference);\n if (processState.needsModelImport)\n await this.exporter.exportModel(reference);\n }\n }\n }\n\n private getElemTransformState(elementId: Id64String) {\n const dbHasModel = (db: IModelDb, id: Id64String) => {\n const maybeModelId = EntityReferences.fromEntityType(id, ConcreteEntityTypes.Model);\n return EntityUnifier.exists(db, { entityReference: maybeModelId });\n };\n const isSubModeled = dbHasModel(this.sourceDb, elementId);\n const idOfElemInTarget = this.context.findTargetElementId(elementId);\n const isElemInTarget = Id64.invalid !== idOfElemInTarget;\n const needsModelImport = isSubModeled && (!isElemInTarget || !dbHasModel(this.targetDb, idOfElemInTarget));\n return { needsElemImport: !isElemInTarget, needsModelImport };\n }\n\n /** Override of [IModelExportHandler.onExportElement]($transformer) that imports an element into the target iModel when it is exported from the source iModel.\n * This override calls [[onTransformElement]] and then [IModelImporter.importElement]($transformer) to update the target iModel.\n */\n public override onExportElement(sourceElement: Element): void {\n let targetElementId: Id64String;\n let targetElementProps: ElementProps;\n if (this._options.preserveElementIdsForFiltering) {\n targetElementId = sourceElement.id;\n targetElementProps = this.onTransformElement(sourceElement);\n } else if (this._options.wasSourceIModelCopiedToTarget) {\n targetElementId = sourceElement.id;\n targetElementProps = this.targetDb.elements.getElementProps(targetElementId);\n } else {\n targetElementId = this.context.findTargetElementId(sourceElement.id);\n targetElementProps = this.onTransformElement(sourceElement);\n }\n\n // if an existing remapping was not yet found, check by FederationGuid\n if (this.context.isBetweenIModels && !Id64.isValid(targetElementId) && sourceElement.federationGuid !== undefined) {\n targetElementId = this._queryElemIdByFedGuid(this.targetDb, sourceElement.federationGuid) ?? Id64.invalid;\n if (Id64.isValid(targetElementId))\n this.context.remapElement(sourceElement.id, targetElementId); // record that the targetElement was found\n }\n\n // if an existing remapping was not yet found, check by Code as long as the CodeScope is valid (invalid means a missing reference so not worth checking)\n if (!Id64.isValid(targetElementId) && Id64.isValidId64(targetElementProps.code.scope)) {\n // respond the same way to undefined code value as the @see Code class, but don't use that class because is trims\n // whitespace from the value, and there are iModels out there with untrimmed whitespace that we ought not to trim\n targetElementProps.code.value = targetElementProps.code.value ?? \"\";\n const maybeTargetElementId = this.targetDb.elements.queryElementIdByCode(targetElementProps.code as Required<CodeProps>);\n if (undefined !== maybeTargetElementId) {\n const maybeTargetElem = this.targetDb.elements.getElement(maybeTargetElementId);\n if (maybeTargetElem.classFullName === targetElementProps.classFullName) { // ensure code remapping doesn't change the target class\n targetElementId = maybeTargetElementId;\n this.context.remapElement(sourceElement.id, targetElementId); // record that the targetElement was found by Code\n } else {\n targetElementProps.code = Code.createEmpty(); // clear out invalid code\n }\n }\n }\n\n if (Id64.isValid(targetElementId) && !this.hasElementChanged(sourceElement, targetElementId))\n return;\n\n this.collectUnmappedReferences(sourceElement);\n\n // targetElementId will be valid (indicating update) or undefined (indicating insert)\n targetElementProps.id\n = Id64.isValid(targetElementId)\n ? targetElementId\n : undefined;\n\n if (!this._options.wasSourceIModelCopiedToTarget) {\n this.importer.importElement(targetElementProps); // don't need to import if iModel was copied\n }\n this.context.remapElement(sourceElement.id, targetElementProps.id!); // targetElementProps.id assigned by importElement\n // now that we've mapped this elem we can fix unmapped references to it\n this.resolvePendingReferences(sourceElement);\n\n // the transformer does not currently 'split' or 'join' any elements, therefore, it does not\n // insert external source aspects because federation guids are sufficient for this.\n // Other transformer subclasses must insert the appropriate aspect (as provided by a TBD API)\n // when splitting/joining elements\n // physical consolidation is an example of a 'joining' transform\n // FIXME: document this externally!\n // verify at finalization time that we don't lose provenance on new elements\n // make public and improve `initElementProvenance` API for usage by consolidators\n if (!this._options.noProvenance) {\n let provenance: Parameters<typeof this.markLastProvenance>[0] | undefined\n = this._options.forceExternalSourceAspectProvenance || this._elementsWithExplicitlyTrackedProvenance.has(sourceElement.id)\n ? undefined\n : sourceElement.federationGuid;\n if (!provenance) {\n const aspectProps = this.initElementProvenance(sourceElement.id, targetElementProps.id!);\n const aspectId = this.queryScopeExternalSource(aspectProps).aspectId;\n if (aspectId === undefined) {\n aspectProps.id = this.provenanceDb.elements.insertAspect(aspectProps);\n } else {\n aspectProps.id = aspectId;\n this.provenanceDb.elements.updateAspect(aspectProps);\n }\n provenance = aspectProps as MarkRequired<ExternalSourceAspectProps, \"id\">;\n }\n this.markLastProvenance(provenance, { isRelationship: false });\n }\n }\n\n private resolvePendingReferences(entity: ConcreteEntity) {\n for (const referencer of this._pendingReferences.getReferencers(entity)) {\n const key = PendingReference.from(referencer, entity);\n const pendingRef = this._pendingReferences.get(key);\n if (!pendingRef)\n continue;\n pendingRef.resolveReference(EntityReferences.from(entity));\n this._pendingReferences.delete(key);\n }\n }\n\n /** Override of [IModelExportHandler.onDeleteElement]($transformer) that is called when [IModelExporter]($transformer) detects that an Element has been deleted from the source iModel.\n * This override propagates the delete to the target iModel via [IModelImporter.deleteElement]($transformer).\n */\n public override onDeleteElement(sourceElementId: Id64String): void {\n const targetElementId: Id64String = this.context.findTargetElementId(sourceElementId);\n if (Id64.isValidId64(targetElementId)) {\n this.importer.deleteElement(targetElementId);\n }\n }\n\n /** Override of [IModelExportHandler.onExportModel]($transformer) that is called when a Model should be exported from the source iModel.\n * This override calls [[onTransformModel]] and then [IModelImporter.importModel]($transformer) to update the target iModel.\n */\n public override onExportModel(sourceModel: Model): void {\n if (IModel.repositoryModelId === sourceModel.id) {\n return; // The RepositoryModel should not be directly imported\n }\n const targetModeledElementId: Id64String = this.context.findTargetElementId(sourceModel.id);\n const targetModelProps: ModelProps = this.onTransformModel(sourceModel, targetModeledElementId);\n this.importer.importModel(targetModelProps);\n this.resolvePendingReferences(sourceModel);\n }\n\n /** Override of [IModelExportHandler.onDeleteModel]($transformer) that is called when [IModelExporter]($transformer) detects that a [Model]($backend) has been deleted from the source iModel. */\n public override onDeleteModel(sourceModelId: Id64String): void {\n // It is possible and apparently occasionally sensical to delete a model without deleting its underlying element.\n // - If only the model is deleted, [[initFromExternalSourceAspects]] will have already remapped the underlying element since it still exists.\n // - If both were deleted, [[remapDeletedSourceEntities]] will find and remap the deleted element making this operation valid\n const targetModelId: Id64String = this.context.findTargetElementId(sourceModelId);\n if (Id64.isValidId64(targetModelId)) {\n this.importer.deleteModel(targetModelId);\n }\n }\n\n /** Cause the model container, contents, and sub-models to be exported from the source iModel and imported into the target iModel.\n * @param sourceModeledElementId Import this [Model]($backend) from the source IModelDb.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processModel(sourceModeledElementId: Id64String): Promise<void> {\n await this.initialize();\n return this.exporter.exportModel(sourceModeledElementId);\n }\n\n /** Cause the model contents to be exported from the source iModel and imported into the target iModel.\n * @param sourceModelId Import the contents of this model from the source IModelDb.\n * @param targetModelId Import into this model in the target IModelDb. The target model must exist prior to this call.\n * @param elementClassFullName Optional classFullName of an element subclass to limit import query against the source model.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processModelContents(sourceModelId: Id64String, targetModelId: Id64String, elementClassFullName: string = Element.classFullName): Promise<void> {\n await this.initialize();\n this.targetDb.models.getModel(targetModelId); // throws if Model does not exist\n this.context.remapElement(sourceModelId, targetModelId); // set remapping in case importModelContents is called directly\n return this.exporter.exportModelContents(sourceModelId, elementClassFullName);\n }\n\n /** Cause all sub-models that recursively descend from the specified Subject to be exported from the source iModel and imported into the target iModel. */\n private async processSubjectSubModels(sourceSubjectId: Id64String): Promise<void> {\n await this.initialize();\n // import DefinitionModels first\n const childDefinitionPartitionSql = `SELECT ECInstanceId FROM ${DefinitionPartition.classFullName} WHERE Parent.Id=:subjectId`;\n await this.sourceDb.withPreparedStatement(childDefinitionPartitionSql, async (statement: ECSqlStatement) => {\n statement.bindId(\"subjectId\", sourceSubjectId);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n await this.processModel(statement.getValue(0).getId());\n }\n });\n // import other partitions next\n const childPartitionSql = `SELECT ECInstanceId FROM ${InformationPartitionElement.classFullName} WHERE Parent.Id=:subjectId`;\n await this.sourceDb.withPreparedStatement(childPartitionSql, async (statement: ECSqlStatement) => {\n statement.bindId(\"subjectId\", sourceSubjectId);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n const modelId: Id64String = statement.getValue(0).getId();\n const model: Model = this.sourceDb.models.getModel(modelId);\n if (!(model instanceof DefinitionModel)) {\n await this.processModel(modelId);\n }\n }\n });\n // recurse into child Subjects\n const childSubjectSql = `SELECT ECInstanceId FROM ${Subject.classFullName} WHERE Parent.Id=:subjectId`;\n await this.sourceDb.withPreparedStatement(childSubjectSql, async (statement: ECSqlStatement) => {\n statement.bindId(\"subjectId\", sourceSubjectId);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n await this.processSubjectSubModels(statement.getValue(0).getId());\n }\n });\n }\n\n /** Transform the specified sourceModel into ModelProps for the target iModel.\n * @param sourceModel The Model from the source iModel to be transformed.\n * @param targetModeledElementId The transformed Model will *break down* or *detail* this Element in the target iModel.\n * @returns ModelProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n */\n public onTransformModel(sourceModel: Model, targetModeledElementId: Id64String): ModelProps {\n const targetModelProps: ModelProps = sourceModel.toJSON();\n // don't directly edit deep object since toJSON performs a shallow clone\n targetModelProps.modeledElement = { ...targetModelProps.modeledElement, id: targetModeledElementId };\n targetModelProps.id = targetModeledElementId;\n targetModelProps.parentModel = this.context.findTargetElementId(targetModelProps.parentModel!);\n return targetModelProps;\n }\n\n /** Import elements that were deferred in a prior pass.\n * @deprecated in 3.x. This method is no longer necessary since the transformer no longer needs to defer elements\n */\n public async processDeferredElements(_numRetries: number = 3): Promise<void> {}\n\n /** called at the end ([[finalizeTransformation]]) of a transformation,\n * updates the target scope element to say that transformation up through the\n * source's changeset has been performed.\n */\n private _updateSynchronizationVersion() {\n if (this._sourceChangeDataState !== \"has-changes\" && !this._isFirstSynchronization)\n return;\n\n nodeAssert(this._targetScopeProvenanceProps);\n\n const sourceVersion = `${this.sourceDb.changeset.id};${this.sourceDb.changeset.index}`;\n\n if (this._isFirstSynchronization) {\n const targetVersion = `${this.targetDb.changeset.id};${this.targetDb.changeset.index}`;\n this._targetScopeProvenanceProps.version = sourceVersion;\n this._targetScopeProvenanceProps.jsonProperties.reverseSyncVersion = targetVersion;\n } else if (this._options.isReverseSynchronization) {\n const oldVersion = this._targetScopeProvenanceProps.jsonProperties.reverseSyncVersion;\n Logger.logInfo(loggerCategory, `updating reverse version from ${oldVersion} to ${sourceVersion}`);\n this._targetScopeProvenanceProps.jsonProperties.reverseSyncVersion = sourceVersion;\n } else if (!this._options.isReverseSynchronization) {\n Logger.logInfo(loggerCategory, `updating sync version from ${this._targetScopeProvenanceProps.version} to ${sourceVersion}`);\n this._targetScopeProvenanceProps.version = sourceVersion;\n }\n\n if (this._isSynchronization) {\n assert(\n this.targetDb.changeset.index !== undefined && this._startingTargetChangesetIndex !== undefined,\n \"_updateSynchronizationVersion was called without change history\",\n );\n\n const jsonProps = this._targetScopeProvenanceProps.jsonProperties;\n\n Logger.logTrace(loggerCategory, `previous pendingReverseSyncChanges: ${jsonProps.pendingReverseSyncChangesetIndices}`);\n Logger.logTrace(loggerCategory, `previous pendingSyncChanges: ${jsonProps.pendingSyncChangesetIndices}`);\n\n const [syncChangesetsToClear, syncChangesetsToUpdate]\n = this._isReverseSynchronization\n ? [jsonProps.pendingReverseSyncChangesetIndices, jsonProps.pendingSyncChangesetIndices]\n : [jsonProps.pendingSyncChangesetIndices, jsonProps.pendingReverseSyncChangesetIndices];\n\n // NOTE that as documented in [[processChanges]], this assumes that right after\n // transformation finalization, the work will be saved immediately, otherwise we've\n // just marked this changeset as a synchronization to ignore, and the user can add other\n // stuff to it which would break future synchronizations\n // FIXME: force save for the user to prevent that\n for (let i = this._startingTargetChangesetIndex + 1; i <= this.targetDb.changeset.index + 1; i++)\n syncChangesetsToUpdate.push(i);\n syncChangesetsToClear.length = 0;\n\n Logger.logTrace(loggerCategory, `new pendingReverseSyncChanges: ${jsonProps.pendingReverseSyncChangesetIndices}`);\n Logger.logTrace(loggerCategory, `new pendingSyncChanges: ${jsonProps.pendingSyncChangesetIndices}`);\n }\n\n this.provenanceDb.elements.updateAspect({\n ...this._targetScopeProvenanceProps,\n jsonProperties: JSON.stringify(this._targetScopeProvenanceProps.jsonProperties) as any,\n });\n }\n\n // FIXME: is this necessary when manually using lowlevel transform APIs?\n private finalizeTransformation() {\n this._updateSynchronizationVersion();\n\n if (this._partiallyCommittedEntities.size > 0) {\n Logger.logWarning(\n loggerCategory,\n [\n \"The following elements were never fully resolved:\",\n [...this._partiallyCommittedEntities.keys()].join(\",\"),\n \"This indicates that either some references were excluded from the transformation\",\n \"or the source has dangling references.\",\n ].join(\"\\n\")\n );\n for (const partiallyCommittedElem of this._partiallyCommittedEntities.values()) {\n partiallyCommittedElem.forceComplete();\n }\n }\n\n // FIXME: make processAll have a try {} finally {} that cleans this up\n if (!this._options.noDetachChangeCache) {\n if (ChangeSummaryManager.isChangeCacheAttached(this.sourceDb))\n ChangeSummaryManager.detachChangeCache(this.sourceDb);\n }\n }\n\n /** Imports all relationships that subclass from the specified base class.\n * @param baseRelClassFullName The specified base relationship class.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processRelationships(baseRelClassFullName: string): Promise<void> {\n await this.initialize();\n return this.exporter.exportRelationships(baseRelClassFullName);\n }\n\n /** Override of [IModelExportHandler.shouldExportRelationship]($transformer) that is called to determine if a [Relationship]($backend) should be exported.\n * @note Reaching this point means that the relationship has passed the standard exclusion checks in [IModelExporter]($transformer).\n */\n public override shouldExportRelationship(_sourceRelationship: Relationship): boolean { return true; }\n\n /** Override of [IModelExportHandler.onExportRelationship]($transformer) that imports a relationship into the target iModel when it is exported from the source iModel.\n * This override calls [[onTransformRelationship]] and then [IModelImporter.importRelationship]($transformer) to update the target iModel.\n */\n public override onExportRelationship(sourceRelationship: Relationship): void {\n const sourceFedGuid = queryElemFedGuid(this.sourceDb, sourceRelationship.sourceId);\n const targetFedGuid = queryElemFedGuid(this.sourceDb, sourceRelationship.targetId);\n const targetRelationshipProps = this.onTransformRelationship(sourceRelationship);\n const targetRelationshipInstanceId = this.importer.importRelationship(targetRelationshipProps);\n\n if (!this._options.noProvenance && Id64.isValid(targetRelationshipInstanceId)) {\n let provenance: Parameters<typeof this.markLastProvenance>[0] | undefined\n = !this._options.forceExternalSourceAspectProvenance\n ? sourceFedGuid && targetFedGuid && `${sourceFedGuid}/${targetFedGuid}`\n : undefined;\n if (!provenance) {\n const aspectProps = this.initRelationshipProvenance(sourceRelationship, targetRelationshipInstanceId);\n aspectProps.id = this.queryScopeExternalSource(aspectProps).aspectId;\n if (undefined === aspectProps.id) {\n aspectProps.id = this.provenanceDb.elements.insertAspect(aspectProps);\n }\n provenance = aspectProps as MarkRequired<ExternalSourceAspectProps, \"id\">;\n }\n this.markLastProvenance(provenance, { isRelationship: true });\n }\n }\n\n /** Override of [IModelExportHandler.onDeleteRelationship]($transformer) that is called when [IModelExporter]($transformer) detects that a [Relationship]($backend) has been deleted from the source iModel.\n * This override propagates the delete to the target iModel via [IModelImporter.deleteRelationship]($transformer).\n */\n public override onDeleteRelationship(sourceRelInstanceId: Id64String): void {\n nodeAssert(this._deletedSourceRelationshipData, \"should be defined at initialization by now\");\n\n const deletedRelData = this._deletedSourceRelationshipData.get(sourceRelInstanceId);\n if (!deletedRelData) {\n // this can occur if both the source and target deleted it\n Logger.logWarning(loggerCategory, \"tried to delete a relationship that wasn't in change data\");\n return;\n }\n\n const relArg = deletedRelData.relId ?? {\n sourceId: deletedRelData.sourceIdInTarget,\n targetId: deletedRelData.targetIdInTarget,\n } as SourceAndTarget;\n //\n // FIXME: make importer.deleteRelationship not need full props\n const targetRelationship = this.targetDb.relationships.tryGetInstance(\n deletedRelData.classFullName,\n relArg,\n );\n\n if (targetRelationship) {\n this.importer.deleteRelationship(targetRelationship.toJSON());\n }\n\n if (deletedRelData.provenanceAspectId) {\n this.provenanceDb.elements.deleteAspect(deletedRelData.provenanceAspectId);\n }\n }\n\n private _yieldManager = new YieldManager();\n\n /** Detect Relationship deletes using ExternalSourceAspects in the target iModel and a *brute force* comparison against relationships in the source iModel.\n * @deprecated\n * @see processChanges\n * @note This method is called from [[processAll]] and is not needed by [[processChanges]], so it only needs to be called directly when processing a subset of an iModel.\n * @throws [[IModelError]] If the required provenance information is not available to detect deletes.\n */\n public async detectRelationshipDeletes(): Promise<void> {\n if (this._options.isReverseSynchronization) {\n throw new IModelError(IModelStatus.BadRequest, \"Cannot detect deletes when isReverseSynchronization=true\");\n }\n const aspectDeleteIds: Id64String[] = [];\n const sql = `\n SELECT ECInstanceId, Identifier, JsonProperties\n FROM ${ExternalSourceAspect.classFullName} aspect\n WHERE aspect.Scope.Id=:scopeId\n AND aspect.Kind=:kind\n `;\n await this.targetDb.withPreparedStatement(sql, async (statement: ECSqlStatement) => {\n statement.bindId(\"scopeId\", this.targetScopeElementId);\n statement.bindString(\"kind\", ExternalSourceAspect.Kind.Relationship);\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\n const sourceRelInstanceId: Id64String = Id64.fromJSON(statement.getValue(1).getString());\n if (undefined === this.sourceDb.relationships.tryGetInstanceProps(ElementRefersToElements.classFullName, sourceRelInstanceId)) {\n // FIXME: make sure matches new provenance-based method\n // FIXME: use sql JSON_EXTRACT\n const json: any = JSON.parse(statement.getValue(2).getString());\n if (undefined !== json.targetRelInstanceId) {\n const targetRelationship: Relationship = this.targetDb.relationships.getInstance(ElementRefersToElements.classFullName, json.targetRelInstanceId);\n this.importer.deleteRelationship(targetRelationship.toJSON());\n }\n aspectDeleteIds.push(statement.getValue(0).getId());\n }\n await this._yieldManager.allowYield();\n }\n });\n this.targetDb.elements.deleteAspect(aspectDeleteIds);\n }\n\n /** Transform the specified sourceRelationship into RelationshipProps for the target iModel.\n * @param sourceRelationship The Relationship from the source iModel to be transformed.\n * @returns RelationshipProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n */\n protected onTransformRelationship(sourceRelationship: Relationship): RelationshipProps {\n const targetRelationshipProps: RelationshipProps = sourceRelationship.toJSON();\n targetRelationshipProps.sourceId = this.context.findTargetElementId(sourceRelationship.sourceId);\n targetRelationshipProps.targetId = this.context.findTargetElementId(sourceRelationship.targetId);\n // TODO: move to cloneRelationship in IModelCloneContext\n sourceRelationship.forEachProperty((propertyName: string, propertyMetaData: PropertyMetaData) => {\n if ((PrimitiveTypeCode.Long === propertyMetaData.primitiveType) && (\"Id\" === propertyMetaData.extendedType)) {\n (targetRelationshipProps as any)[propertyName] = this.context.findTargetElementId(sourceRelationship.asAny[propertyName]);\n }\n });\n return targetRelationshipProps;\n }\n\n /** Override of [IModelExportHandler.onExportElementUniqueAspect]($transformer) that imports an ElementUniqueAspect into the target iModel when it is exported from the source iModel.\n * This override calls [[onTransformElementAspect]] and then [IModelImporter.importElementUniqueAspect]($transformer) to update the target iModel.\n */\n public override onExportElementUniqueAspect(sourceAspect: ElementUniqueAspect): void {\n const targetElementId: Id64String = this.context.findTargetElementId(sourceAspect.element.id);\n const targetAspectProps = this.onTransformElementAspect(sourceAspect, targetElementId);\n this.collectUnmappedReferences(sourceAspect);\n const targetId = this.importer.importElementUniqueAspect(targetAspectProps);\n this.context.remapElementAspect(sourceAspect.id, targetId);\n this.resolvePendingReferences(sourceAspect);\n }\n\n /** Override of [IModelExportHandler.onExportElementMultiAspects]($transformer) that imports ElementMultiAspects into the target iModel when they are exported from the source iModel.\n * This override calls [[onTransformElementAspect]] for each ElementMultiAspect and then [IModelImporter.importElementMultiAspects]($transformer) to update the target iModel.\n * @note ElementMultiAspects are handled as a group to make it easier to differentiate between insert, update, and delete.\n */\n public override onExportElementMultiAspects(sourceAspects: ElementMultiAspect[]): void {\n const targetElementId: Id64String = this.context.findTargetElementId(sourceAspects[0].element.id);\n // Transform source ElementMultiAspects into target ElementAspectProps\n const targetAspectPropsArray = sourceAspects.map((srcA) => this.onTransformElementAspect(srcA, targetElementId));\n sourceAspects.forEach((a) => this.collectUnmappedReferences(a));\n // const targetAspectsToImport = targetAspectPropsArray.filter((targetAspect, i) => hasEntityChanged(sourceAspects[i], targetAspect));\n const targetIds = this.importer.importElementMultiAspects(targetAspectPropsArray, (a) => {\n const isExternalSourceAspectFromTransformer = a instanceof ExternalSourceAspect && a.scope?.id === this.targetScopeElementId;\n return !this._options.includeSourceProvenance || !isExternalSourceAspectFromTransformer;\n });\n for (let i = 0; i < targetIds.length; ++i) {\n this.context.remapElementAspect(sourceAspects[i].id, targetIds[i]);\n this.resolvePendingReferences(sourceAspects[i]);\n }\n }\n\n /** Transform the specified sourceElementAspect into ElementAspectProps for the target iModel.\n * @param sourceElementAspect The ElementAspect from the source iModel to be transformed.\n * @param _targetElementId The ElementId of the target Element that will own the ElementAspects after transformation.\n * @returns ElementAspectProps for the target iModel.\n * @note A subclass can override this method to provide custom transform behavior.\n */\n protected onTransformElementAspect(sourceElementAspect: ElementAspect, _targetElementId: Id64String): ElementAspectProps {\n const targetElementAspectProps = this.context.cloneElementAspect(sourceElementAspect);\n return targetElementAspectProps;\n }\n\n /** The directory where schemas will be exported, a random temporary directory */\n protected _schemaExportDir: string = path.join(KnownLocations.tmpdir, Guid.createValue());\n\n /** Override of [IModelExportHandler.shouldExportSchema]($transformer) that is called to determine if a schema should be exported\n * @note the default behavior doesn't import schemas older than those already in the target\n */\n public override shouldExportSchema(schemaKey: ECSchemaMetaData.SchemaKey): boolean {\n const versionInTarget = this.targetDb.querySchemaVersion(schemaKey.name);\n if (versionInTarget === undefined)\n return true;\n return Semver.gt(`${schemaKey.version.read}.${schemaKey.version.write}.${schemaKey.version.minor}`, Schema.toSemverString(versionInTarget));\n }\n\n private _longNamedSchemasMap = new Map<string, string>();\n\n /** Override of [IModelExportHandler.onExportSchema]($transformer) that serializes a schema to disk for [[processSchemas]] to import into\n * the target iModel when it is exported from the source iModel.\n * @returns {Promise<ExportSchemaResult>} Although the type is possibly void for backwards compatibility of subclasses,\n * `IModelTransformer.onExportSchema` always returns an[[IModelExportHandler.ExportSchemaResult]]\n * with a defined `schemaPath` property, for subclasses to know where the schema was written.\n * Schemas are *not* guaranteed to be written to [[IModelTransformer._schemaExportDir]] by a\n * known pattern derivable from the schema's name, so you must use this to find it.\n */\n public override async onExportSchema(schema: ECSchemaMetaData.Schema): Promise<void | ExportSchemaResult> {\n const ext = \".ecschema.xml\";\n let schemaFileName = schema.name + ext;\n // many file systems have a max file-name/path-segment size of 255, so we workaround that on all systems\n const systemMaxPathSegmentSize = 255;\n if (schemaFileName.length > systemMaxPathSegmentSize) {\n // this name should be well under 255 bytes\n // ( 100 + (Number.MAX_SAFE_INTEGER.toString().length = 16) + (ext.length = 13) ) = 129 which is less than 255\n // You'd have to be past 2**53-1 (Number.MAX_SAFE_INTEGER) long named schemas in order to hit decimal formatting,\n // and that's on the scale of at least petabytes. `Map.prototype.size` shouldn't return floating points, and even\n // if they do they're in scientific notation, size bound and contain no invalid windows path chars\n schemaFileName = `${schema.name.slice(0, 100)}${this._longNamedSchemasMap.size}${ext}`;\n nodeAssert(schemaFileName.length <= systemMaxPathSegmentSize, \"Schema name was still long. This is a bug.\");\n this._longNamedSchemasMap.set(schema.name, schemaFileName);\n }\n this.sourceDb.nativeDb.exportSchema(schema.name, this._schemaExportDir, schemaFileName);\n return { schemaPath: path.join(this._schemaExportDir, schemaFileName) };\n }\n\n private _makeLongNameResolvingSchemaCtx(): ECSchemaXmlContext {\n const result = new ECSchemaXmlContext();\n result.setSchemaLocater((key) => {\n const match = this._longNamedSchemasMap.get(key.name);\n if (match !== undefined)\n return path.join(this._schemaExportDir, match);\n return undefined;\n });\n return result;\n }\n\n /** Cause all schemas to be exported from the source iModel and imported into the target iModel.\n * @note For performance reasons, it is recommended that [IModelDb.saveChanges]($backend) be called after `processSchemas` is complete.\n * It is more efficient to process *data* changes after the schema changes have been saved.\n */\n public async processSchemas(): Promise<void> {\n // we do not need to initialize for this since no entities are exported\n try {\n IModelJsFs.mkdirSync(this._schemaExportDir);\n this._longNamedSchemasMap.clear();\n await this.exporter.exportSchemas();\n const exportedSchemaFiles = IModelJsFs.readdirSync(this._schemaExportDir);\n if (exportedSchemaFiles.length === 0)\n return;\n const schemaFullPaths = exportedSchemaFiles.map((s) => path.join(this._schemaExportDir, s));\n const maybeLongNameResolvingSchemaCtx = this._longNamedSchemasMap.size > 0\n ? this._makeLongNameResolvingSchemaCtx()\n : undefined;\n return await this.targetDb.importSchemas(schemaFullPaths, { ecSchemaXmlContext: maybeLongNameResolvingSchemaCtx });\n } finally {\n IModelJsFs.removeSync(this._schemaExportDir);\n this._longNamedSchemasMap.clear();\n }\n }\n\n /** Cause all fonts to be exported from the source iModel and imported into the target iModel.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processFonts(): Promise<void> {\n // we do not need to initialize for this since no entities are exported\n await this.initialize();\n return this.exporter.exportFonts();\n }\n\n /** Override of [IModelExportHandler.onExportFont]($transformer) that imports a font into the target iModel when it is exported from the source iModel. */\n public override onExportFont(font: FontProps, _isUpdate: boolean | undefined): void {\n this.context.importFont(font.id);\n }\n\n /** Cause all CodeSpecs to be exported from the source iModel and imported into the target iModel.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processCodeSpecs(): Promise<void> {\n await this.initialize();\n return this.exporter.exportCodeSpecs();\n }\n\n /** Cause a single CodeSpec to be exported from the source iModel and imported into the target iModel.\n * @note This method is called from [[processChanges]] and [[processAll]], so it only needs to be called directly when processing a subset of an iModel.\n */\n public async processCodeSpec(codeSpecName: string): Promise<void> {\n await this.initialize();\n return this.exporter.exportCodeSpecByName(codeSpecName);\n }\n\n /** Override of [IModelExportHandler.shouldExportCodeSpec]($transformer) that is called to determine if a CodeSpec should be exported from the source iModel.\n * @note Reaching this point means that the CodeSpec has passed the standard exclusion checks in [IModelExporter]($transformer).\n */\n public override shouldExportCodeSpec(_sourceCodeSpec: CodeSpec): boolean { return true; }\n\n /** Override of [IModelExportHandler.onExportCodeSpec]($transformer) that imports a CodeSpec into the target iModel when it is exported from the source iModel. */\n public override onExportCodeSpec(sourceCodeSpec: CodeSpec): void {\n this.context.importCodeSpec(sourceCodeSpec.id);\n }\n\n /** Recursively import all Elements and sub-Models that descend from the specified Subject */\n public async processSubject(sourceSubjectId: Id64String, targetSubjectId: Id64String): Promise<void> {\n await this.initialize();\n this.sourceDb.elements.getElement(sourceSubjectId, Subject); // throws if sourceSubjectId is not a Subject\n this.targetDb.elements.getElement(targetSubjectId, Subject); // throws if targetSubjectId is not a Subject\n this.context.remapElement(sourceSubjectId, targetSubjectId);\n await this.processChildElements(sourceSubjectId);\n await this.processSubjectSubModels(sourceSubjectId);\n return this.processDeferredElements(); // eslint-disable-line deprecation/deprecation\n }\n\n /** state to prevent reinitialization, @see [[initialize]] */\n private _initialized = false;\n\n /** length === 0 when _changeDataState = \"no-change\", length > 0 means \"has-changes\", otherwise undefined */\n private _changeSummaryIds?: Id64String[] = undefined;\n private _sourceChangeDataState: ChangeDataState = \"uninited\";\n\n /**\n * Initialize prerequisites of processing, you must initialize with an [[InitOptions]] if you\n * are intending to process changes, but prefer using [[processChanges]] explicitly since it calls this.\n * @note Called by all `process*` functions implicitly.\n * Overriders must call `super.initialize()` first\n */\n public async initialize(args?: InitOptions): Promise<void> {\n if (this._initialized)\n return;\n\n await this.context.initialize();\n await this._tryInitChangesetData(args);\n\n await this.exporter.initialize(this.getExportInitOpts(args ?? {}));\n\n // Exporter must be initialized prior to `initFromExternalSourceAspects` in order to handle entity recreations.\n // eslint-disable-next-line deprecation/deprecation\n await this.initFromExternalSourceAspects(args);\n\n this._initialized = true;\n }\n\n private async _tryInitChangesetData(args?: InitOptions) {\n if (!args || this.sourceDb.iTwinId === undefined || this.sourceDb.changeset.index === undefined) {\n this._sourceChangeDataState = \"unconnected\";\n return;\n }\n\n const noChanges = this._synchronizationVersion.index === this.sourceDb.changeset.index;\n if (noChanges) {\n this._sourceChangeDataState = \"no-changes\";\n this._changeSummaryIds = [];\n return;\n }\n\n // NOTE: that we do NOT download the changesummary for the last transformed version, we want\n // to ignore those already processed changes\n const startChangesetIndexOrId\n = args.startChangeset?.index\n ?? args.startChangeset?.id\n ?? this._synchronizationVersion.index + 1;\n const endChangesetId = this.sourceDb.changeset.id;\n\n const [startChangesetIndex, endChangesetIndex] = await Promise.all(\n ([startChangesetIndexOrId, endChangesetId])\n .map(async (indexOrId) => typeof indexOrId === \"number\"\n ? indexOrId\n : IModelHost.hubAccess\n .queryChangeset({\n iModelId: this.sourceDb.iModelId,\n // eslint-disable-next-line deprecation/deprecation\n changeset: { id: indexOrId },\n accessToken: args.accessToken,\n })\n .then((changeset) => changeset.index)\n )\n );\n\n const missingChangesets = startChangesetIndex > this._synchronizationVersion.index + 1;\n // FIXME: add an option to ignore this check\n if (\n !this._options.ignoreMissingChangesetsInSynchronizations\n && startChangesetIndex !== this._synchronizationVersion.index + 1\n && this._synchronizationVersion.index !== -1\n ) {\n throw Error(`synchronization is ${missingChangesets ? \"missing changesets\" : \"\"},`\n + \" startChangesetId should be\"\n + \" exactly the first changeset *after* the previous synchronization to not miss data.\"\n + ` You specified '${startChangesetIndexOrId}' which is changeset #${startChangesetIndex}`\n + ` but the previous synchronization for this targetScopeElement was '${this._synchronizationVersion.id}'`\n + ` which is changeset #${this._synchronizationVersion.index}. The transformer expected`\n + ` #${this._synchronizationVersion.index + 1}.`\n );\n }\n\n nodeAssert(this._targetScopeProvenanceProps, \"_targetScopeProvenanceProps should be set by now\");\n\n const changesetsToSkip = this._isReverseSynchronization\n ? this._targetScopeProvenanceProps.jsonProperties.pendingReverseSyncChangesetIndices\n : this._targetScopeProvenanceProps.jsonProperties.pendingSyncChangesetIndices;\n\n Logger.logTrace(loggerCategory, `changesets to skip: ${changesetsToSkip}`);\n this._changesetRanges = rangesFromRangeAndSkipped(startChangesetIndex, endChangesetIndex, changesetsToSkip);\n Logger.logTrace(loggerCategory, `ranges: ${this._changesetRanges}`);\n\n for (const [first, end] of this._changesetRanges) {\n this._changeSummaryIds = await ChangeSummaryManager.createChangeSummaries({\n accessToken: args.accessToken,\n iModelId: this.sourceDb.iModelId,\n iTwinId: this.sourceDb.iTwinId,\n range: { first, end },\n });\n }\n\n ChangeSummaryManager.attachChangeCache(this.sourceDb);\n this._sourceChangeDataState = \"has-changes\";\n }\n\n /** Export everything from the source iModel and import the transformed entities into the target iModel.\n * @note [[processSchemas]] is not called automatically since the target iModel may want a different collection of schemas.\n */\n public async processAll(): Promise<void> {\n this.logSettings();\n this.initScopeProvenance();\n await this.initialize();\n await this.exporter.exportCodeSpecs();\n await this.exporter.exportFonts();\n // The RepositoryModel and root Subject of the target iModel should not be transformed.\n await this.exporter.exportChildElements(IModel.rootSubjectId); // start below the root Subject\n await this.exporter.exportModelContents(IModel.repositoryModelId, Element.classFullName, true); // after the Subject hierarchy, process the other elements of the RepositoryModel\n await this.exporter.exportSubModels(IModel.repositoryModelId); // start below the RepositoryModel\n await this.exporter.exportRelationships(ElementRefersToElements.classFullName);\n await this.processDeferredElements(); // eslint-disable-line deprecation/deprecation\n if (this.shouldDetectDeletes()) {\n await this.detectElementDeletes();\n await this.detectRelationshipDeletes();\n }\n\n if (this._options.optimizeGeometry)\n this.importer.optimizeGeometry(this._options.optimizeGeometry);\n\n this.importer.computeProjectExtents();\n this.finalizeTransformation();\n }\n\n /** previous provenance, either a federation guid, a `${sourceFedGuid}/${targetFedGuid}` pair, or required aspect props */\n private _lastProvenanceEntityInfo: string | LastProvenanceEntityInfo = nullLastProvenanceEntityInfo;\n\n private markLastProvenance(sourceAspect: string | MarkRequired<ExternalSourceAspectProps, \"id\">, { isRelationship = false }) {\n this._lastProvenanceEntityInfo\n = typeof sourceAspect === \"string\"\n ? sourceAspect\n : {\n entityId: sourceAspect.element.id,\n aspectId: sourceAspect.id,\n aspectVersion: sourceAspect.version ?? \"\",\n aspectKind: isRelationship ? ExternalSourceAspect.Kind.Relationship : ExternalSourceAspect.Kind.Element,\n };\n }\n\n /** @internal the name of the table where javascript state of the transformer is serialized in transformer state dumps */\n public static readonly jsStateTable = \"TransformerJsState\";\n\n /** @internal the name of the table where the target state heuristics is serialized in transformer state dumps */\n public static readonly lastProvenanceEntityInfoTable = \"LastProvenanceEntityInfo\";\n\n /**\n * Load the state of the active transformation from an open SQLiteDb\n * You can override this if you'd like to load from custom tables in the resumable dump state, but you should call\n * this super implementation\n * @note the SQLiteDb must be open\n */\n protected loadStateFromDb(db: SQLiteDb): void {\n const lastProvenanceEntityInfo: IModelTransformer[\"_lastProvenanceEntityInfo\"] = db.withSqliteStatement(\n `SELECT entityId, aspectId, aspectVersion, aspectKind FROM ${IModelTransformer.lastProvenanceEntityInfoTable}`,\n (stmt) => {\n if (DbResult.BE_SQLITE_ROW !== stmt.step())\n throw Error(\n \"expected row when getting lastProvenanceEntityId from target state table\"\n );\n const entityId = stmt.getValueString(0);\n const isGuidOrGuidPair = entityId.includes(\"-\");\n return isGuidOrGuidPair\n ? entityId\n : {\n entityId,\n aspectId: stmt.getValueString(1),\n aspectVersion: stmt.getValueString(2),\n aspectKind: stmt.getValueString(3) as ExternalSourceAspect.Kind,\n };\n }\n );\n\n /*\n // TODO: maybe save transformer state resumption state based on target changset and require calls\n // to saveChanges\n if () {\n const [sourceFedGuid, targetFedGuid, relClassFullName] = lastProvenanceEntityInfo.split(\"/\");\n const isRelProvenance = targetFedGuid !== undefined;\n const instanceId = isRelProvenance\n ? this.targetDb.elements.getElement({federationGuid: sourceFedGuid})\n : \"\";\n //const classId =\n if (isRelProvenance) {\n }\n }\n */\n\n const targetHasCorrectLastProvenance =\n typeof lastProvenanceEntityInfo === \"string\" ||\n // ignore provenance check if it's null since we can't bind those ids\n !Id64.isValidId64(lastProvenanceEntityInfo.entityId) ||\n !Id64.isValidId64(lastProvenanceEntityInfo.aspectId) ||\n this.provenanceDb.withPreparedStatement(`\n SELECT Version FROM ${ExternalSourceAspect.classFullName}\n WHERE Scope.Id=:scopeId\n AND ECInstanceId=:aspectId\n AND Kind=:kind\n AND Element.Id=:entityId\n `,\n (statement: ECSqlStatement): boolean => {\n statement.bindId(\"scopeId\", this.targetScopeElementId);\n statement.bindId(\"aspectId\", lastProvenanceEntityInfo.aspectId);\n statement.bindString(\"kind\", lastProvenanceEntityInfo.aspectKind);\n statement.bindId(\"entityId\", lastProvenanceEntityInfo.entityId);\n const stepResult = statement.step();\n switch (stepResult) {\n case DbResult.BE_SQLITE_ROW:\n const version = statement.getValue(0).getString();\n return version === lastProvenanceEntityInfo.aspectVersion;\n case DbResult.BE_SQLITE_DONE:\n return false;\n default:\n throw new IModelError(IModelStatus.SQLiteError, `got sql error ${stepResult}`);\n }\n });\n\n if (!targetHasCorrectLastProvenance)\n throw Error([\n \"Target for resuming from does not have the expected provenance \",\n \"from the target that the resume state was made with\",\n ].join(\"\\n\"));\n this._lastProvenanceEntityInfo = lastProvenanceEntityInfo;\n\n const state = db.withSqliteStatement(`SELECT data FROM ${IModelTransformer.jsStateTable}`, (stmt) => {\n if (DbResult.BE_SQLITE_ROW !== stmt.step())\n throw Error(\"expected row when getting data from js state table\");\n return JSON.parse(stmt.getValueString(0)) as TransformationJsonState;\n });\n if (state.transformerClass !== this.constructor.name)\n throw Error(\"resuming from a differently named transformer class, it is not necessarily valid to resume with a different transformer class\");\n // force assign to readonly options since we do not know how the transformer subclass takes options to pass to the superclass\n (this as any)._options = state.options;\n this.context.loadStateFromDb(db);\n this.importer.loadStateFromJson(state.importerState);\n this.exporter.loadStateFromJson(state.exporterState);\n this._elementsWithExplicitlyTrackedProvenance = CompressedId64Set.decompressSet(state.explicitlyTrackedElements);\n this.loadAdditionalStateJson(state.additionalState);\n }\n\n /**\n * @deprecated in 0.1.x, this is buggy, and it is now equivalently efficient to simply restart the transformation\n * from the original changeset\n *\n * Return a new transformer instance with the same remappings state as saved from a previous [[IModelTransformer.saveStateToFile]] call.\n * This allows you to \"resume\" an iModel transformation, you will have to call [[IModelTransformer.processChanges]]/[[IModelTransformer.processAll]]\n * again but the remapping state will cause already mapped elements to be skipped.\n * To \"resume\" an iModel Transformation you need:\n * - the sourceDb at the same changeset\n * - the same targetDb in the state in which it was before\n * @param statePath the path to the serialized state of the transformer, use [[IModelTransformer.saveStateToFile]] to get this from an existing transformer instance\n * @param constructorArgs remaining arguments that you would normally pass to the Transformer subclass you are using, usually (sourceDb, targetDb)\n * @note custom transformers with custom state may need to override this method in order to handle loading their own custom state somewhere\n */\n public static resumeTransformation<SubClass extends new(...a: any[]) => IModelTransformer = typeof IModelTransformer>(\n this: SubClass,\n statePath: string,\n ...constructorArgs: ConstructorParameters<SubClass>\n ): InstanceType<SubClass> {\n const transformer = new this(...constructorArgs);\n const db = new SQLiteDb();\n db.openDb(statePath, OpenMode.Readonly);\n try {\n transformer.loadStateFromDb(db);\n } finally {\n db.closeDb();\n }\n return transformer as InstanceType<SubClass>;\n }\n\n /**\n * You may override this to store arbitrary json state in a transformer 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 * Save the state of the active transformation to an open SQLiteDb\n * You can override this if you'd like to write custom tables to the resumable dump state, but you should call\n * this super implementation\n * @note the SQLiteDb must be open\n */\n protected saveStateToDb(db: SQLiteDb): void {\n const jsonState: TransformationJsonState = {\n transformerClass: this.constructor.name,\n options: this._options,\n explicitlyTrackedElements: CompressedId64Set.compressSet(this._elementsWithExplicitlyTrackedProvenance),\n importerState: this.importer.saveStateToJson(),\n exporterState: this.exporter.saveStateToJson(),\n additionalState: this.getAdditionalStateJson(),\n };\n\n this.context.saveStateToDb(db);\n if (DbResult.BE_SQLITE_DONE !== db.executeSQL(`CREATE TABLE ${IModelTransformer.jsStateTable} (data TEXT)`))\n throw Error(\"Failed to create the js state table in the state database\");\n\n if (DbResult.BE_SQLITE_DONE !== db.executeSQL(`\n CREATE TABLE ${IModelTransformer.lastProvenanceEntityInfoTable} (\n -- either the invalid id for null provenance state, federation guid (or pair for rels) of the entity, or a hex element id\n entityId TEXT,\n -- the following are only valid if the above entityId is a hex id representation\n aspectId TEXT,\n aspectVersion TEXT,\n aspectKind TEXT\n )\n `))\n throw Error(\"Failed to create the target state table in the state database\");\n\n db.saveChanges();\n db.withSqliteStatement(\n `INSERT INTO ${IModelTransformer.jsStateTable} (data) VALUES (?)`,\n (stmt) => {\n stmt.bindString(1, JSON.stringify(jsonState));\n if (DbResult.BE_SQLITE_DONE !== stmt.step())\n throw Error(\"Failed to insert options into the state database\");\n });\n\n db.withSqliteStatement(\n `INSERT INTO ${IModelTransformer.lastProvenanceEntityInfoTable} (entityId, aspectId, aspectVersion, aspectKind) VALUES (?,?,?,?)`,\n (stmt) => {\n const lastProvenanceEntityInfo = this._lastProvenanceEntityInfo as LastProvenanceEntityInfo;\n stmt.bindString(1, lastProvenanceEntityInfo?.entityId ?? this._lastProvenanceEntityInfo as string);\n stmt.bindString(2, lastProvenanceEntityInfo?.aspectId ?? \"\");\n stmt.bindString(3, lastProvenanceEntityInfo?.aspectVersion ?? \"\");\n stmt.bindString(4, lastProvenanceEntityInfo?.aspectKind ?? \"\");\n if (DbResult.BE_SQLITE_DONE !== stmt.step())\n throw Error(\"Failed to insert options into the state database\");\n });\n\n db.saveChanges();\n }\n\n /**\n * @deprecated in 0.1.x, this is buggy, and it is now equivalently efficient to simply restart the transformation\n * from the original changeset\n *\n * Save the state of the active transformation to a file path, if a file at the path already exists, it will be overwritten\n * This state can be used by [[IModelTransformer.resumeTransformation]] to resume a transformation from this point.\n * The serialization format is a custom sqlite database.\n * @note custom transformers with custom state may override [[IModelTransformer.saveStateToDb]] or [[IModelTransformer.getAdditionalStateJson]]\n * and [[IModelTransformer.loadStateFromDb]] (with a super call) or [[IModelTransformer.loadAdditionalStateJson]]\n * if they have custom state that needs to be stored with\n * potentially inside the same sqlite file in separate tables\n */\n public saveStateToFile(nativeStatePath: string): void {\n const db = new SQLiteDb();\n if (IModelJsFs.existsSync(nativeStatePath))\n IModelJsFs.unlinkSync(nativeStatePath);\n db.createDb(nativeStatePath);\n try {\n this.saveStateToDb(db);\n db.saveChanges();\n } finally {\n db.closeDb();\n }\n }\n\n // FIXME: force saveChanges after processChanges to prevent people accidentally lumping in other data\n /** Export changes from the source iModel and import the transformed entities into the target iModel.\n * Inserts, updates, and deletes are determined by inspecting the changeset(s).\n * @note the transformer assumes that you saveChanges after processing changes. You should not\n * modify the iModel after processChanges until saveChanges, failure to do so may result in corrupted\n * data loss in future branch operations\n * @param accessToken A valid access token string\n * @param startChangesetId Include changes from this changeset up through and including the current changeset.\n * If this parameter is not provided, then just the current changeset will be exported.\n * @note To form a range of versions to process, set `startChangesetId` for the start (inclusive) of the desired range and open the source iModel as of the end (inclusive) of the desired range.\n */\n public async processChanges(options: ProcessChangesOptions): Promise<void>;\n /**\n * @deprecated in 0.1.x, use a single [[ProcessChangesOptions]] object instead\n * This overload follows the older behavior of defaulting an undefined startChangesetId to the\n * current changeset.\n */\n public async processChanges(accessToken: AccessToken, startChangesetId?: string): Promise<void>;\n public async processChanges(optionsOrAccessToken: AccessToken | ProcessChangesOptions, startChangesetId?: string): Promise<void> {\n this._isSynchronization = true;\n const args: ProcessChangesOptions =\n typeof optionsOrAccessToken === \"string\"\n ? {\n accessToken: optionsOrAccessToken,\n startChangeset: startChangesetId\n ? { id: startChangesetId }\n : this.sourceDb.changeset,\n }\n : optionsOrAccessToken\n ;\n this.logSettings();\n // FIXME: we used to validateScopeProvenance... does initing it cover that?\n this.initScopeProvenance();\n await this.initialize(args);\n // must wait for initialization of synchronization provenance data\n await this.exporter.exportChanges(this.getExportInitOpts(args));\n await this.processDeferredElements(); // eslint-disable-line deprecation/deprecation\n\n if (this._options.optimizeGeometry)\n this.importer.optimizeGeometry(this._options.optimizeGeometry);\n\n this.importer.computeProjectExtents();\n this.finalizeTransformation();\n }\n\n /** Changeset data must be initialized in order to build correct changeOptions.\n * Call [[IModelTransformer.initialize]] for initialization of synchronization provenance data\n */\n private getExportInitOpts(opts: InitOptions): ExporterInitOptions {\n if (!this._isSynchronization)\n return {};\n\n return {\n accessToken: opts.accessToken,\n ...this._changesetRanges\n ? { changesetRanges: this._changesetRanges }\n : opts.startChangeset\n ? { startChangeset: opts.startChangeset }\n : { startChangeset: { index: this._synchronizationVersion.index + 1 } },\n };\n }\n\n /** Combine an array of source elements into a single target element.\n * All source and target elements must be created before calling this method.\n * The \"combine\" operation is a remap and no properties from the source elements will be exported into the target\n * and provenance will be explicitly tracked by ExternalSourceAspects\n */\n public combineElements(sourceElementIds: Id64Array, targetElementId: Id64String) {\n for (const elementId of sourceElementIds) {\n this.context.remapElement(elementId, targetElementId);\n this._elementsWithExplicitlyTrackedProvenance.add(elementId);\n }\n }\n}\n\n// FIXME: update this... although resumption is broken regardless\n/** @internal the json part of a transformation's state */\ninterface TransformationJsonState {\n transformerClass: string;\n options: IModelTransformOptions;\n importerState: IModelImporterState;\n exporterState: IModelExporterState;\n explicitlyTrackedElements: CompressedId64Set;\n additionalState?: any;\n}\n\n/** IModelTransformer that clones the contents of a template model.\n * @beta\n */\nexport class TemplateModelCloner extends IModelTransformer {\n /** The Placement to apply to the template. */\n private _transform3d?: Transform;\n /** Accumulates the mapping of sourceElementIds to targetElementIds from the elements in the template model that were cloned. */\n private _sourceIdToTargetIdMap?: Map<Id64String, Id64String>;\n /** Construct a new TemplateModelCloner\n * @param sourceDb The source IModelDb that contains the templates to clone\n * @param targetDb Optionally specify the target IModelDb where the cloned template will be inserted.\n * Typically this is left unspecified, and the default is to use the sourceDb as the target\n * @note The expectation is that the template definitions are within the same iModel where instances will be placed.\n */\n public constructor(sourceDb: IModelDb, targetDb: IModelDb = sourceDb) {\n const target = new IModelImporter(targetDb, {\n autoExtendProjectExtents: false, // autoExtendProjectExtents is intended for transformation service use cases, not template --> instance cloning\n });\n super(sourceDb, target, { noProvenance: true }); // WIP: need to decide the proper way to handle provenance\n }\n /** Place a template from the sourceDb at the specified placement in the target model within the targetDb.\n * @param sourceTemplateModelId The Id of the template model in the sourceDb\n * @param targetModelId The Id of the target model (must be a subclass of GeometricModel3d) where the cloned component will be inserted.\n * @param placement The placement for the cloned component.\n * @note *Required References* like the SpatialCategory must be remapped before calling this method.\n * @returns The mapping of sourceElementIds from the template model to the instantiated targetElementIds in the targetDb in case further processing is required.\n */\n public async placeTemplate3d(sourceTemplateModelId: Id64String, targetModelId: Id64String, placement: Placement3d): Promise<Map<Id64String, Id64String>> {\n await this.initialize();\n this.context.remapElement(sourceTemplateModelId, targetModelId);\n this._transform3d = Transform.createOriginAndMatrix(placement.origin, placement.angles.toMatrix3d());\n this._sourceIdToTargetIdMap = new Map<Id64String, Id64String>();\n await this.exporter.exportModelContents(sourceTemplateModelId);\n // Note: the source --> target mapping was needed during the template model cloning phase (remapping parent/child, for example), but needs to be reset afterwards\n for (const sourceElementId of this._sourceIdToTargetIdMap.keys()) {\n const targetElementId = this.context.findTargetElementId(sourceElementId);\n this._sourceIdToTargetIdMap.set(sourceElementId, targetElementId);\n this.context.removeElement(sourceElementId); // clear the underlying native remapping context for the next clone operation\n }\n return this._sourceIdToTargetIdMap; // return the sourceElementId -> targetElementId Map in case further post-processing is required.\n }\n\n /** Place a template from the sourceDb at the specified placement in the target model within the targetDb.\n * @param sourceTemplateModelId The Id of the template model in the sourceDb\n * @param targetModelId The Id of the target model (must be a subclass of GeometricModel2d) where the cloned component will be inserted.\n * @param placement The placement for the cloned component.\n * @note *Required References* like the DrawingCategory must be remapped before calling this method.\n * @returns The mapping of sourceElementIds from the template model to the instantiated targetElementIds in the targetDb in case further processing is required.\n */\n public async placeTemplate2d(sourceTemplateModelId: Id64String, targetModelId: Id64String, placement: Placement2d): Promise<Map<Id64String, Id64String>> {\n await this.initialize();\n this.context.remapElement(sourceTemplateModelId, targetModelId);\n this._transform3d = Transform.createOriginAndMatrix(Point3d.createFrom(placement.origin), placement.rotation);\n this._sourceIdToTargetIdMap = new Map<Id64String, Id64String>();\n await this.exporter.exportModelContents(sourceTemplateModelId);\n // Note: the source --> target mapping was needed during the template model cloning phase (remapping parent/child, for example), but needs to be reset afterwards\n for (const sourceElementId of this._sourceIdToTargetIdMap.keys()) {\n const targetElementId = this.context.findTargetElementId(sourceElementId);\n this._sourceIdToTargetIdMap.set(sourceElementId, targetElementId);\n this.context.removeElement(sourceElementId); // clear the underlying native remapping context for the next clone operation\n }\n return this._sourceIdToTargetIdMap; // return the sourceElementId -> targetElementId Map in case further post-processing is required.\n }\n\n /** Cloning from a template requires this override of onTransformElement. */\n public override onTransformElement(sourceElement: Element): ElementProps {\n // eslint-disable-next-line deprecation/deprecation\n const referenceIds = sourceElement.getReferenceConcreteIds();\n referenceIds.forEach((referenceId) => {\n // FIXME: consider going through all definition elements at once and remapping them to themselves\n if (!EntityReferences.isValid(this.context.findTargetEntityId(referenceId))) {\n if (this.context.isBetweenIModels) {\n throw new IModelError(IModelStatus.BadRequest, `Remapping for source dependency ${referenceId} not found for target iModel`);\n } else {\n const definitionElement = this.sourceDb.elements.tryGetElement<DefinitionElement>(referenceId, DefinitionElement);\n if (definitionElement && !(definitionElement instanceof RecipeDefinitionElement)) {\n this.context.remapElement(referenceId, referenceId); // when in the same iModel, can use existing DefinitionElements without remapping\n } else {\n throw new IModelError(IModelStatus.BadRequest, `Remapping for dependency ${referenceId} not found`);\n }\n }\n }\n });\n\n const targetElementProps: ElementProps = super.onTransformElement(sourceElement);\n targetElementProps.federationGuid = Guid.createValue(); // clone from template should create a new federationGuid\n targetElementProps.code = Code.createEmpty(); // clone from template should not maintain codes\n if (sourceElement instanceof GeometricElement) {\n const is3d = sourceElement instanceof GeometricElement3d;\n const placementClass = is3d ? Placement3d : Placement2d;\n const placement = (placementClass).fromJSON((targetElementProps as GeometricElementProps).placement as any);\n if (placement.isValid) {\n nodeAssert(this._transform3d);\n placement.multiplyTransform(this._transform3d);\n (targetElementProps as GeometricElementProps).placement = placement;\n }\n }\n this._sourceIdToTargetIdMap!.set(sourceElement.id, Id64.invalid); // keep track of (source) elementIds from the template model, but the target hasn't been inserted yet\n return targetElementProps;\n }\n}\n\nfunction queryElemFedGuid(db: IModelDb, elemId: Id64String) {\n return db.withPreparedStatement(`\n SELECT FederationGuid\n FROM bis.Element\n WHERE ECInstanceId=?\n `, (stmt) => {\n stmt.bindId(1, elemId);\n assert(stmt.step() === DbResult.BE_SQLITE_ROW);\n const result = stmt.getValue(0).getGuid();\n assert(stmt.step() === DbResult.BE_SQLITE_DONE);\n return result;\n });\n}\n\n"]}