@@ -561,14 +561,29 @@ const REFERENCE_TYPE_RE = /(?:^|\/)([A-Za-z]+)\/[A-Za-z0-9\-.]{1,64}(?:\/_histor
561561
562562export const referencedResourceType = ( reference : string ) : string | undefined => REFERENCE_TYPE_RE . exec ( reference ) ?. [ 1 ] ;
563563
564+ /**
565+ * Checks that every reference present names one of the `allowed` resource types.
566+ *
567+ * A repeating element (`Provenance.target`, `Observation.focus`) holds a list of
568+ * References where a single one holds an object, and a Reference is never itself
569+ * an array — so the shape tells the two apart with no help from the caller. One
570+ * error per offending type, not per entry, so a list of ten wrong references of
571+ * the same type reports once.
572+ */
564573export const validateReference = ( res : object , profileName : string , field : string , allowed : string [ ] ) : string [ ] => {
565574 const value = ( res as Record < string , unknown > ) [ field ] ;
566575 if ( value === undefined || value === null ) return [ ] ;
567- const ref = ( value as Record < string , unknown > ) . reference as string | undefined ;
568- if ( ! ref ) return [ ] ;
569- const refType = referencedResourceType ( ref ) ;
570- if ( refType === undefined ) return [ ] ;
571- return allowed . includes ( refType )
572- ? [ ]
573- : [ `${ profileName } : field '${ field } ' references '${ refType } ' but only ${ allowed . join ( ", " ) } are allowed` ] ;
576+ const entries = Array . isArray ( value ) ? value : [ value ] ;
577+ const offending : string [ ] = [ ] ;
578+ for ( const entry of entries ) {
579+ const ref = ( entry as Record < string , unknown > | null ) ?. reference as string | undefined ;
580+ if ( ! ref ) continue ;
581+ const refType = referencedResourceType ( ref ) ;
582+ if ( refType === undefined || allowed . includes ( refType ) ) continue ;
583+ if ( ! offending . includes ( refType ) ) offending . push ( refType ) ;
584+ }
585+ return offending . map (
586+ ( refType ) =>
587+ `${ profileName } : field '${ field } ' references '${ refType } ' but only ${ allowed . join ( ", " ) } are allowed` ,
588+ ) ;
574589} ;
0 commit comments