import { v4 as uuidv4 } from 'uuid' ; import { SavedObject , SavedObjectsClientContract , SavedObjectsImportFailure , SavedObjectError , SavedObjectsImportRetry , } from '../../types' ; import type { ImportStateMap } from './types' ; interface CheckConflictsParams { objects : Array < SavedObject < { title ? : string ; } > > ; savedObjectsClient : SavedObjectsClientContract ; namespace ? : string ; ignoreRegularConflicts ? : boolean ; retries ? : SavedObjectsImportRetry [ ] ; createNewCopies ? : boolean ; } const isUnresolvableConflict = ( error ) => error . statusCode === 409 && error . metadata ?. isNotOverwritable ; export async function checkConflicts ( { objects , savedObjectsClient , namespace , ignoreRegularConflicts , retries = [ ] , createNewCopies , } ) { const filteredObjects = [ ] ; const errors = [ ] ; const importStateMap = new Map ( ) ; const pendingOverwrites = new Set < string > ( ) ; if ( objects . length === 0 ) { return { filteredObjects , errors , importStateMap , pendingOverwrites } ; } const retryMap = retries . reduce ( ( acc , cur ) => acc . set ( `${ cur . type }:${ cur . id }` , cur ) , new Map < string , SavedObjectsImportRetry > ( ) ) ; const objectsToCheck = objects . map ( ( x ) => { const id = retryMap . get ( `${ x . type }:${ x . id }` ) ?. destinationId ?? x . id ; return { ... x , id } ; } ) ; const checkConflictsResult = await savedObjectsClient . checkConflicts ( objectsToCheck , { namespace , } ) ; const errorMap = checkConflictsResult . errors . reduce ( ( acc , { type , id , error } ) => acc . set ( `${ type }:${ id }` , error ) , new Map < string , SavedObjectError > ( ) ) ; objects . forEach ( ( object ) => { const { type , id , attributes : { title } , } = object ; const { destinationId , overwrite , createNewCopy } = retryMap . get ( `${ type }:${ id }` ) || { } ; const errorObj = errorMap . get ( `${ type }:${ destinationId ?? id }` ) ; if ( errorObj && isUnresolvableConflict ( errorObj ) ) { const omitOriginId = createNewCopies || createNewCopy ; importStateMap . set ( `${ type }:${ id }` , { destinationId : uuidv4 ( ) , omitOriginId } ) ; filteredObjects . push ( object ) ; } else if ( errorObj && errorObj . statusCode !== 409 ) { errors . push ( { type , id , title , meta : { title } , error : { ... errorObj , type : 'unknown' } } ) ; } else if ( errorObj ?. statusCode === 409 && ! ignoreRegularConflicts && ! overwrite ) { const error = { type : 'conflict' as 'conflict' , ... ( destinationId && { destinationId } ) } ; errors . push ( { type , id , title , meta : { title } , error } ) ; } else { filteredObjects . push ( object ) ; if ( errorObj ?. statusCode === 409 ) { pendingOverwrites . add ( `${ type }:${ id }` ) ; } } } ) ; return { filteredObjects , errors , importStateMap , pendingOverwrites } ; }