# All files / src/clients/ep transformers.ts

96.57% Statements 169/175
92.41% Branches 207/224
100% Functions 29/29
97.45% Lines 153/157

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498

    470x
    470x
    470x
    470x

    470x
    470x
    470x
    470x

    470x
    470x
    4x

    18x
    1x
    1x
    1x
    1x

    17x
    1x

    2x
    2x
    2x
    2x

    2x

    470x
    470x

    470x
    470x

    470x
    470x

    470x

    470x
    470x
    470x

    13x

    13x
    13x
    1x
    1x

    13x
    13x
    13x

    13x
    7x
    7x
    7x
    7x

    13x

    40x
    40x
    40x
    40x

    40x
    40x

    40x
    7x

    40x

    40x

    82x

    42x
    42x
    42x

    42x
    42x
    42x

    42x
    42x

    42x

    46x

    46x
    176x
    176x

    6x

    46x
    46x
    10x
    10x
    2x

    46x
    46x
    46x
    46x

    46x
    46x
    46x

    46x

    156x
    156x
    156x
    156x
    156x
    156x
    156x

    156x

    156x
    89x

    156x

    156x
    156x
    3x
    1x

    1x
    1x
    2x
    2x

    1x

    112x
    112x
    112x
    112x
    112x
    112x
    112x

    112x

    112x
    14x
    14x

    112x

    39x
    39x
    39x
    39x
    3x
    3x
    3x

    39x
    39x
    39x

    17x
    17x
    17x
    1x
    1x
    1x
    1x
    1x
    1x

    17x

    39x

    39x

    79x
    79x
    79x
    79x
    79x
    79x
    79x

    18x

    17x

    15x
    15x

    15x

    17x
    17x

     /**
     * EP API data transformers.
     *
     * Pure functions that transform raw EP API JSON-LD responses into
     * typed domain objects. Each transformer handles a specific entity type
     * and delegates field extraction to {@link module:clients/ep/jsonLdHelpers}.
     *
     * @module clients/ep/transformers
     */

    import type {
      MEP,
      MEPDetails,
      PlenarySession,
      VotingRecord,
      Committee,
      LegislativeDocument,
      ParliamentaryQuestion,
      Speech,
      Procedure,
      AdoptedText,
      EPEvent,
      MeetingActivity,
      MEPDeclaration,
    } from '../../types/europeanParliament.js';

    import {
      toSafeString,
      firstDefined,
      extractField,
      extractDateValue,
      extractActivityDate,
      extractMultilingualText,
      extractMemberIds,
      extractAuthorId,
      extractDocumentRefs,
      extractLocation,
      extractVoteCount,
      determineVoteOutcome,
      mapDocumentType,
      mapDocumentStatus,
      mapQuestionType,
    } from './jsonLdHelpers.js';

    /** Extract the resolved MEP identifier string. */
    function resolveMEPId(apiData: Record<string, unknown>): string {
      const identifier = firstDefined(apiData, 'identifier', '@id', 'id');
      const idStr = toSafeString(identifier) || toSafeString(apiData['id']) || '';
      const fallbackId = idStr || 'unknown';
      return idStr.includes('/') ? idStr : `person/${fallbackId}`;
    }

    /** Build the MEP display name from available label / name fields. */
    function resolveMEPName(apiData: Record<string, unknown>): string {
      const label = toSafeString(apiData['label']) || '';
      const familyName = toSafeString(firstDefined(apiData, 'familyName', 'family_name')) || '';
      const givenName = toSafeString(firstDefined(apiData, 'givenName', 'given_name')) || '';
      return label || `${givenName} ${familyName}`.trim() || 'Unknown MEP';
    }

    /** Extract committee list from raw API data. */
    function extractMEPCommittees(apiData: Record<string, unknown>): string[] {
      const raw = firstDefined(apiData, 'committees', 'committeeRoles');
      if (!Array.isArray(raw)) return [];
      return raw.map((item: unknown) => toSafeString(item));
    }

    /**
     * Extracts readable codes from an array of EP authority URIs.
     * E.g. `["http://publications.europa.eu/resource/authority/subject-matter/DDLH"]` → `"DDLH"`.
     */
    function extractCodesFromUriArray(field: unknown): string {
      if (typeof field === 'string') {
        const s = toSafeString(field);
        Iif (s === '') return '';
        const lastSlash = s.lastIndexOf('/');
        return lastSlash >= 0 ? s.substring(lastSlash + 1) : s;
      }
      if (!Array.isArray(field)) return '';
      return field
        .map(item => {
          const s = toSafeString(item);
          Iif (s === '') return '';
          const lastSlash = s.lastIndexOf('/');
          return lastSlash >= 0 ? s.substring(lastSlash + 1) : s;
        })
        .filter(s => s !== '')
        .join(', ');
    }

    /**
     * Transforms EP API MEP data to internal {@link MEP} format.
     */
    export function transformMEP(apiData: Record<string, unknown>): MEP {
      const mepId = resolveMEPId(apiData);
      const name = resolveMEPName(apiData);

      const country = toSafeString(firstDefined(apiData, 'api:country-of-representation', 'country', 'citizenship', 'nationality')) || 'Unknown';
      const politicalGroup = toSafeString(firstDefined(apiData, 'api:political-group', 'politicalGroup', 'political_group')) || 'Unknown';

      const emailValue = toSafeString(apiData['email']);
      const termEndValue = toSafeString(firstDefined(apiData, 'termEnd', 'term_end'));

      const mep: MEP = {
        id: mepId,
        name,
        country,
        politicalGroup,
        committees: extractMEPCommittees(apiData),
        active: apiData['active'] === true || apiData['active'] === 'true',
        termStart: toSafeString(firstDefined(apiData, 'termStart', 'term_start')) || '',
      };
      if (emailValue !== '') mep.email = emailValue;
      if (termEndValue !== '') mep.termEnd = termEndValue;
      return mep;
    }

    /**
     * Transforms EP API MEP details data to internal {@link MEPDetails} format.
     */
    export function transformMEPDetails(apiData: Record<string, unknown>): MEPDetails {
      const baseMEP = transformMEP(apiData);

      let country = baseMEP.country;
      if (country.startsWith('http')) {
        const parts = country.split('/');
        country = parts[parts.length - 1] ?? country;
      }

      const bday = toSafeString(apiData['bday']);
      const memberships = apiData['hasMembership'];
      const committees: string[] = [];

      if (Array.isArray(memberships)) {
        for (const membership of memberships) {
          Eif (typeof membership === 'object' && membership !== null) {
            const org = toSafeString((membership as Record<string, unknown>)['organization']);
            if (org !== '') committees.push(org);
          }
        }
      }

      return {
        ...baseMEP,
        country,
        committees: committees.length > 0 ? committees : baseMEP.committees,
        biography: `Born: ${bday !== '' ? bday : 'Unknown'}`,
      };
    }

    /**
     * Transforms EP API plenary session data to internal {@link PlenarySession} format.
     */
    export function transformPlenarySession(apiData: Record<string, unknown>): PlenarySession {
      const id = toSafeString(apiData['activity_id']) || toSafeString(apiData['id']) || '';
      const dateValue = resolveActivityDate(apiData);
      const localityUrl = toSafeString(apiData['hasLocality']);
      const location = extractLocation(localityUrl);

      const rawAttendance = apiData['number_of_attendees'];
      const attendanceCount = typeof rawAttendance === 'number' ? rawAttendance : 0;

      const agendaItems = Array.isArray(apiData['consists_of'])
        ? (apiData['consists_of'] as string[]).map(item => toSafeString(item)).filter(s => s !== '')
        : [];
      const docRefs = extractDocumentRefs(
        apiData['documented_by_a_realization_of'] ?? apiData['recorded_in_a_realization_of']
      );

      return {
        id,
        date: dateValue,
        location,
        agendaItems,
        attendanceCount,
        documents: docRefs,
      };
    }

    /** Extract activity date from EP API, checking plain string first, then eli-dl: prefixed format. */
    function resolveActivityDate(apiData: Record<string, unknown>): string {
      return extractDateValue(apiData['activity_date']) || extractActivityDate(apiData['eli-dl:activity_date']);
    }

    /**
     * Transforms EP API vote result data to internal {@link VotingRecord} format.
     */
    export function transformVoteResult(apiData: Record<string, unknown>, sessionId: string): VotingRecord {
      const id = toSafeString(apiData['activity_id']) || toSafeString(apiData['id']) || '';
      const date = resolveActivityDate(apiData);
      const topic = extractMultilingualText(apiData['activity_label'] ?? apiData['label'] ?? apiData['notation']) || 'Unknown';

      const votesFor = extractVoteCount(apiData['had_voter_favor'] ?? apiData['number_of_votes_favor']);
      const votesAgainst = extractVoteCount(apiData['had_voter_against'] ?? apiData['number_of_votes_against']);
      const abstentions = extractVoteCount(apiData['had_voter_abstention'] ?? apiData['number_of_votes_abstention']);

      const decisionStr = toSafeString(apiData['decision_method'] ?? apiData['had_decision_outcome']);
      const result = determineVoteOutcome(decisionStr, votesFor, votesAgainst);

      return { id, sessionId, topic, date, votesFor, votesAgainst, abstentions, result };
    }

    /**
     * Resolve a full committee display name.
     * Fallback chain: `prefLabel` → `skos:prefLabel` → `altLabel` → `label`.
     * @returns Multilingual text string, or empty string if no field found.
     */
    function resolveCommitteeName(apiData: Record<string, unknown>): string {
      const candidates: unknown[] = [
        apiData['prefLabel'],
        apiData['skos:prefLabel'],
        apiData['altLabel'],
        apiData['label'],
      ];
      for (const candidate of candidates) {
        const text = extractMultilingualText(candidate);
        if (text !== '') return text;
      }
      return '';
    }

    /**
     * Resolve the committee abbreviation code.
     * In the real EP API, `label` is the short code (e.g. "ENVI"); `notation`
     * may also carry it. Falls back to the already-extracted identifier value
     * resolved from `body_id`/`id`/`identifier`.
     */
    function resolveCommitteeAbbreviation(apiData: Record<string, unknown>, id: string): string {
      const fromNotation = extractField(apiData, ['notation', 'skos:notation']);
      if (fromNotation !== '') return fromNotation;
      const label = apiData['label'];
      if (typeof label === 'string' && label !== '') return label;
      return id;
    }

    /**
     * Transforms EP API corporate-body data to internal {@link Committee} format.
     *
     * The real EP API returns `label` as a short abbreviation (e.g. "ENVI") while
     * `prefLabel` contains the full multilingual committee name.  We therefore
     * prefer `prefLabel` → `altLabel` → `label` for the display name, and derive
     * the abbreviation from `label` (always a short code in real responses) with
     * `notation` as a higher-priority override when present.
     *
     * Cyclomatic complexity: 6
     */
    export function transformCorporateBody(apiData: Record<string, unknown>): Committee {
      const id = extractField(apiData, ['body_id', 'id', 'identifier']);
      const name = resolveCommitteeName(apiData);
      const abbreviation = resolveCommitteeAbbreviation(apiData, id);
      const effectiveId = id !== '' ? id : abbreviation;

      const members = extractMemberIds(apiData['hasMembership'] ?? apiData['org:hasMember']);
      const classification = extractField(apiData, ['classification', 'org:classification']);
      const responsibilities = classification !== '' ? [classification.replace(/.*\//, '')] : [];

      return {
        id: effectiveId,
        name: name !== '' ? name : `Committee ${abbreviation}`,
        abbreviation,
        members,
        responsibilities,
      };
    }

    /**
     * Transforms EP API document data to internal {@link LegislativeDocument} format.
     */
    export function transformDocument(apiData: Record<string, unknown>): LegislativeDocument {
      const id = extractField(apiData, ['work_id', 'id', 'identifier']);
      const title = extractMultilingualText(apiData['title_dcterms'] ?? apiData['label'] ?? apiData['title']);
      const mappedType = mapDocumentType(extractField(apiData, ['work_type', 'ep-document-types', 'type']));
      const date = extractDateValue(apiData['document_date'] ?? apiData['work_date_document'] ?? apiData['date_document'] ?? apiData['date']);
      const committeeValue = extractField(apiData, ['was_attributed_to', 'committee']);
      const mappedStatus = mapDocumentStatus(extractField(apiData, ['resource_legal_in-force', 'status']));
      const authors = extractDocumentAuthors(apiData);

      const doc: LegislativeDocument = {
        id,
        type: mappedType,
        title: title !== '' ? title : `Document ${id}`,
        date,
        authors,
        status: mappedStatus,
        summary: title,
      };
      if (committeeValue !== '') {
        doc.committee = committeeValue;
      }
      return doc;
    }

    /**
     * Extract author IDs from EP API document fields.
     *
     * EP API documents expose authors via `was_created_by`, `created_by`, or `author`
     * fields. The value may be a single person URI string, an array of strings, or
     * an array of objects with `@id` / `id` properties. We extract all person IDs
     * and return them as a flat string array for downstream attribution matching.
     */
    function extractDocumentAuthors(apiData: Record<string, unknown>): string[] {
      const raw = apiData['was_created_by'] ?? apiData['created_by'] ?? apiData['author'];
      if (raw === undefined || raw === null) return [];
      if (typeof raw === 'string') return raw !== '' ? [raw] : [];
      Eif (Array.isArray(raw)) return extractAuthorIdsFromArray(raw);
      if (typeof raw === 'object') {
        const id = extractAuthorId(raw);
        return id !== '' ? [id] : [];
      }
      return [];
    }

    /** Extract author IDs from a mixed array of strings and objects. */
    function extractAuthorIdsFromArray(items: unknown[]): string[] {
      const result: string[] = [];
      for (const item of items) {
        const id = extractAuthorId(item);
        Eif (id !== '') result.push(id);
      }
      return result;
    }

    /**
     * Transforms EP API parliamentary question data to internal {@link ParliamentaryQuestion} format.
     */
    export function transformParliamentaryQuestion(apiData: Record<string, unknown>): ParliamentaryQuestion {
      const id = extractField(apiData, ['work_id', 'id', 'identifier']);
      const questionType = mapQuestionType(extractField(apiData, ['work_type', 'ep-document-types']));
      const author = extractAuthorId(firstDefined(apiData, 'was_created_by', 'created_by', 'author'));
      const date = extractDateValue(firstDefined(apiData, 'document_date', 'work_date_document', 'date_document', 'date'));
      const topic = extractMultilingualText(firstDefined(apiData, 'title_dcterms', 'label', 'title'));
      const hasAnswer = apiData['was_realized_by'] != null;
      const topicText = topic !== '' ? topic : `Question ${id}`;

      const result: ParliamentaryQuestion = {
        id,
        type: questionType,
        author: author !== '' ? author : 'Unknown',
        date,
        topic: topicText,
        questionText: topicText,
        status: hasAnswer ? 'ANSWERED' : 'PENDING',
      };
      if (hasAnswer) {
        result.answerText = 'Answer available - see EP document portal for full text';
        result.answerDate = date;
      }
      return result;
    }

    /**
     * Extracts speaker ID and name from EP API participation data.
     * EP API nests speaker info inside `had_participation` object.
     */
    function extractSpeakerInfo(apiData: Record<string, unknown>): { speakerId: string; speakerName: string } {
      const participation = apiData['had_participation'];
      let speakerId = '';
      let speakerName = '';
      if (typeof participation === 'object' && participation !== null && !Array.isArray(participation)) {
        const partObj = participation as Record<string, unknown>;
        speakerId = extractAuthorId(partObj['had_participant_person']);
        speakerName = extractMultilingualText(partObj['participant_label'] ?? '');
      }
      if (speakerId === '') speakerId = extractAuthorId(apiData['had_participant_person'] ?? apiData['was_attributed_to']);
      if (speakerName === '') speakerName = extractMultilingualText(apiData['participant_label'] ?? '');
      return { speakerId, speakerName };
    }

    /**
     * Extracts author MEP ID and name from EP API declaration data.
     * EP API uses `workHadParticipation` array for declaration authors.
     */
    function extractDeclarationAuthor(apiData: Record<string, unknown>): { mepId: string; mepName: string } {
      let mepId = extractAuthorId(apiData['was_attributed_to'] ?? apiData['author']);
      let mepName = extractMultilingualText(apiData['author_label'] ?? '');
      if (mepId === '' && Array.isArray(apiData['workHadParticipation'])) {
        const parts = apiData['workHadParticipation'] as Record<string, unknown>[];
        Eif (parts.length > 0) {
          const first = parts[0];
          Eif (first !== undefined) {
            mepId = extractAuthorId(first['had_participant_person'] ?? first['id']);
            mepName = extractMultilingualText(first['participant_label'] ?? '');
          }
        }
      }
      return { mepId, mepName };
    }

    /**
     * Transforms EP API speech data to internal {@link Speech} format.
     */
    export function transformSpeech(apiData: Record<string, unknown>): Speech {
      const { speakerId, speakerName } = extractSpeakerInfo(apiData);

      return {
        id: extractField(apiData, ['activity_id', 'identifier', 'id']),
        title: extractMultilingualText(apiData['activity_label'] ?? apiData['had_activity_type'] ?? apiData['label'] ?? apiData['title']),
        speakerId,
        speakerName,
        date: extractDateValue(apiData['activity_date'] ?? apiData['date']),
        type: extractField(apiData, ['had_activity_type', 'type']),
        language: extractField(apiData, ['language', 'was_created_in_language']),
        text: extractMultilingualText(apiData['text'] ?? apiData['content'] ?? ''),
        sessionReference: extractAuthorId(apiData['inverse_consists_of'] ?? apiData['was_part_of'] ?? apiData['is_part_of'] ?? apiData['event']),
      };
    }

    /**
     * Transforms EP API procedure data to internal {@link Procedure} format.
     */
    export function transformProcedure(apiData: Record<string, unknown>): Procedure {
      const titleField = firstDefined(apiData, 'title_dcterms', 'label', 'title');
      const dateStartField = firstDefined(apiData, 'process_date_start', 'date_start', 'date');
      const dateUpdateField = firstDefined(apiData, 'process_date_update', 'date_update');
      const subjectField = firstDefined(apiData, 'subject_matter', 'subject');
      const rawType = extractField(apiData, ['process_type', 'type']);
      const typeCode = rawType.includes('/') ? rawType.slice(rawType.lastIndexOf('/') + 1) : rawType;
      return {
        id: extractField(apiData, ['identifier', 'process_id', 'id']),
        title: extractMultilingualText(titleField),
        reference: extractField(apiData, ['identifier', 'process_id']),
        type: typeCode,
        subjectMatter: extractMultilingualText(subjectField),
        stage: extractField(apiData, ['process_stage', 'stage']),
        status: extractField(apiData, ['process_status', 'status']),
        dateInitiated: extractDateValue(dateStartField),
        dateLastActivity: extractDateValue(dateUpdateField),
        responsibleCommittee: extractField(apiData, ['was_attributed_to', 'committee']),
        rapporteur: extractMultilingualText(apiData['rapporteur']),
        documents: extractDocumentRefs(apiData['had_document'] ?? apiData['documents']),
      };
    }

    /**
     * Transforms EP API adopted text data to internal {@link AdoptedText} format.
     */
    export function transformAdoptedText(apiData: Record<string, unknown>): AdoptedText {
      return {
        id: extractField(apiData, ['work_id', 'identifier', 'id']),
        title: extractMultilingualText(apiData['title_dcterms'] ?? apiData['label'] ?? apiData['title']),
        reference: extractField(apiData, ['work_id', 'identifier']),
        type: extractField(apiData, ['work_type', 'type']),
        dateAdopted: extractDateValue(apiData['document_date'] ?? apiData['work_date_document'] ?? apiData['date_document'] ?? apiData['date']),
        procedureReference: extractField(apiData, ['based_on_a_concept_procedure', 'inverse_decided_on_a_realization_of', 'procedure']),
        subjectMatter: extractCodesFromUriArray(apiData['isAboutSubjectMatter']) || extractMultilingualText(apiData['subject_matter'] ?? apiData['subject'] ?? ''),
      };
    }

    /**
     * Transforms EP API event data to internal {@link EPEvent} format.
     */
    export function transformEvent(apiData: Record<string, unknown>): EPEvent {
      return {
        id: extractField(apiData, ['activity_id', 'identifier', 'id']),
        title: extractMultilingualText(apiData['activity_label'] ?? apiData['label'] ?? apiData['title'] ?? ''),
        date: extractDateValue(apiData['activity_start_date'] ?? apiData['activity_date'] ?? apiData['date']),
        endDate: extractDateValue(apiData['activity_end_date'] ?? ''),
        type: extractField(apiData, ['had_activity_type', 'type']),
        location: extractField(apiData, ['had_locality', 'hasLocality', 'location']),
        organizer: extractField(apiData, ['was_organized_by', 'organizer']),
        status: extractField(apiData, ['activity_status', 'status']),
      };
    }

    /**
     * Transforms EP API meeting activity data to internal {@link MeetingActivity} format.
     */
    export function transformMeetingActivity(apiData: Record<string, unknown>): MeetingActivity {
      const orderField = apiData['activity_order'] ?? apiData['order'];
      const orderVal = typeof orderField === 'number' ? orderField : 0;

      return {
        id: extractField(apiData, ['identifier', 'id']),
        title: extractMultilingualText(apiData['label'] ?? apiData['title'] ?? ''),
        type: extractField(apiData, ['had_activity_type', 'type']),
        date: extractDateValue(apiData['activity_date'] ?? apiData['date']),
        order: orderVal,
        reference: extractField(apiData, ['had_document', 'reference']),
        responsibleBody: extractField(apiData, ['was_attributed_to', 'committee']),
      };
    }

    /**
     * Transforms EP API MEP declaration data to internal {@link MEPDeclaration} format.
     */
    export function transformMEPDeclaration(apiData: Record<string, unknown>): MEPDeclaration {
      const { mepId, mepName } = extractDeclarationAuthor(apiData);
      return {
        id: extractField(apiData, ['work_id', 'identifier', 'id']),
        title: extractMultilingualText(apiData['title_dcterms'] ?? apiData['label'] ?? apiData['title']),
        mepId,
        mepName,
        type: extractField(apiData, ['work_type', 'type']),
        dateFiled: extractDateValue(apiData['document_date'] ?? apiData['work_date_document'] ?? apiData['date_document'] ?? apiData['date']),
        status: extractField(apiData, ['resource_legal_in-force', 'status']),
      };
    }