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

93.96% Statements 109/116
79.62% Branches 86/108
100% Functions 24/24
95.14% Lines 98/103

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

    346x

    31x

    8x

    11x

    16x

    9x

    9x
    9x
    9x
    9x
    9x
    9x

    9x
    9x
    9x
    9x

    9x
    9x
    9x

    9x
    9x
    29x

    9x
    1x
    10x

    9x
    9x

    9x
    9x

    8x
    2x

    6x

    6x
    8x

    8x

    5x
    8x
    8x
    8x

    5x
    2x

    3x

    3x
    5x

    5x

    2x
    5x
    5x
    5x

    5x
    2x

    3x

    3x
    5x

    5x

    3x
    5x
    5x
    5x

    16x
    2x

    14x
    4x

    10x
    16x

    16x

    6x
    16x
    16x
    16x

    10x
    2x

    8x
    4x

    4x
    10x

    10x

    3x
    10x
    10x
    10x

    4x
    2x

    2x

    2x

    6x
    6x

    6x

    6x
    5x
    6x
    6x
    6x

    2x

    4x
    2x

    2x

    2x

     /**
     * @fileoverview Plenary/Meetings sub-client for European Parliament API
     *
     * Handles plenary sessions, meeting activities, meeting decisions,
     * foreseen activities, EP events, and individual meeting/event lookups.
     *
     * @module clients/ep/plenaryClient
     */

    import { auditLogger } from '../../utils/auditLogger.js';
    import type {
      PlenarySession,
      EPEvent,
      MeetingActivity,
      LegislativeDocument,
      PaginatedResponse,
    } from '../../types/europeanParliament.js';
    import {
      transformPlenarySession as _transformPlenarySession,
      transformEvent as _transformEvent,
      transformMeetingActivity as _transformMeetingActivity,
      transformDocument as _transformDocument,
    } from './transformers.js';
    import {
      BaseEPClient,
      APIError,
      type EPClientConfig,
      type EPSharedResources,
      type JSONLDResponse,
    } from './baseClient.js';

    /**
     * Sub-client for plenary sessions and meeting-related EP API endpoints.
     *
     * @extends BaseEPClient
     * @public
     */
    export class PlenaryClient extends BaseEPClient {
      constructor(config: EPClientConfig = {}, shared?: EPSharedResources) {
        super(config, shared);
      }

      private transformPlenarySession(apiData: Record<string, unknown>): PlenarySession {
        return _transformPlenarySession(apiData);
      }

      private transformEvent(apiData: Record<string, unknown>): EPEvent {
        return _transformEvent(apiData);
      }

      private transformMeetingActivity(apiData: Record<string, unknown>): MeetingActivity {
        return _transformMeetingActivity(apiData);
      }

      private transformDocument(apiData: Record<string, unknown>): LegislativeDocument {
        return _transformDocument(apiData);
      }

      /**
       * Maps internal params to EP API query parameters for meetings.
       *
       * The EP API `/meetings` endpoint supports `year` for filtering by
       * calendar year.  The `date-from` / `date-to` parameters are also
       * forwarded when present (useful for sub-year ranges).
       * @private
       */
      private buildMeetingsAPIParams(params: {
        year?: number;
        dateFrom?: string;
        dateTo?: string;
        limit?: number;
        offset?: number;
      }): Record<string, unknown> {
        const apiParams: Record<string, unknown> = {
          format: 'application/ld+json',
        };
        Eif (params.limit !== undefined) apiParams['limit'] = params.limit;
        if (params.offset !== undefined) apiParams['offset'] = params.offset;
        if (params.year !== undefined) apiParams['year'] = params.year;
        Iif (params.dateFrom !== undefined) apiParams['date-from'] = params.dateFrom;
        Iif (params.dateTo !== undefined) apiParams['date-to'] = params.dateTo;
        return apiParams;
      }

      /**
       * Retrieves plenary sessions with year/date and location filtering.
       *
       * **EP API Endpoint:** `GET /meetings`
       *
       * The EP API supports filtering by `year` (recommended for annual counts).
       * `dateFrom` / `dateTo` are also forwarded but may be ignored by the API
       * for certain endpoints.
       *
       * @param params - year, dateFrom, dateTo, location, limit, offset
       * @returns Paginated plenary session list
       */
      async getPlenarySessions(params: {
        year?: number;
        dateFrom?: string;
        dateTo?: string;
        location?: string;
        limit?: number;
        offset?: number;
      }): Promise<PaginatedResponse<PlenarySession>> {
        const action = 'get_plenary_sessions';
        try {
          const limit = params.limit ?? 50;
          const offset = params.offset ?? 0;

          const apiParams = this.buildMeetingsAPIParams(params);
          apiParams['limit'] = limit;
          apiParams['offset'] = offset;

          const response = await this.get<JSONLDResponse>('meetings', apiParams);
          const pageSize = response.data.length;
          let sessions = response.data.map((item) => this.transformPlenarySession(item));

          if (params.location !== undefined && params.location !== '') {
            const locationLower = params.location.toLowerCase();
            sessions = sessions.filter((s) => s.location.toLowerCase().includes(locationLower));
          }
          const hasMore = pageSize === limit;
          const result: PaginatedResponse<PlenarySession> = {
            data: sessions,
            total: offset + pageSize + (hasMore ? 1 : 0),
            limit,
            offset,
            hasMore,
          };

          auditLogger.logDataAccess(action, params, result.data.length);
          return result;
        } catch (error: unknown) {
          auditLogger.logError(
            action,
            params,
            error instanceof Error ? error.message : 'Unknown error'
          );
          throw error;
        }
      }

      /**
       * Returns activities linked to a specific meeting (plenary sitting).
       * **EP API Endpoint:** `GET /meetings/{sitting-id}/activities`
       */
      async getMeetingActivities(
        sittingId: string,
        params: { limit?: number; offset?: number } = {}
      ): Promise<PaginatedResponse<MeetingActivity>> {
        if (sittingId.trim() === '') {
          throw new APIError('Meeting sitting-id is required', 400);
        }
        Iif (/[.\\?#]/.test(sittingId)) {
          throw new APIError('Meeting sitting-id contains invalid characters', 400);
        }
        const limit = params.limit ?? 50;
        const offset = params.offset ?? 0;

        const response = await this.get<JSONLDResponse>(
          `meetings/${sittingId}/activities`,
          { format: 'application/ld+json', offset, limit }
        );

        const items = Array.isArray(response.data) ? response.data : [];
        const activities = items.map((item) => this.transformMeetingActivity(item));
        const hasMore = activities.length === limit;
        return { data: activities, total: activities.length + offset + (hasMore ? 1 : 0), limit, offset, hasMore };
      }

      /**
       * Returns decisions made in a specific meeting (plenary sitting).
       * **EP API Endpoint:** `GET /meetings/{sitting-id}/decisions`
       */
      async getMeetingDecisions(
        sittingId: string,
        params: { limit?: number; offset?: number } = {}
      ): Promise<PaginatedResponse<LegislativeDocument>> {
        if (sittingId.trim() === '') {
          throw new APIError('Meeting sitting-id is required', 400);
        }
        Iif (/[.\\?#]/.test(sittingId)) {
          throw new APIError('Meeting sitting-id contains invalid characters', 400);
        }
        const limit = params.limit ?? 50;
        const offset = params.offset ?? 0;

        const response = await this.get<JSONLDResponse>(
          `meetings/${sittingId}/decisions`,
          { format: 'application/ld+json', offset, limit }
        );

        const items = Array.isArray(response.data) ? response.data : [];
        const decisions = items.map((item) => this.transformDocument(item));
        const hasMore = decisions.length === limit;
        return { data: decisions, total: decisions.length + offset + (hasMore ? 1 : 0), limit, offset, hasMore };
      }

      /**
       * Returns foreseen activities linked to a specific meeting.
       * **EP API Endpoint:** `GET /meetings/{sitting-id}/foreseen-activities`
       */
      async getMeetingForeseenActivities(
        sittingId: string,
        params: { limit?: number; offset?: number } = {}
      ): Promise<PaginatedResponse<MeetingActivity>> {
        if (sittingId.trim() === '') {
          throw new APIError('Meeting sitting-id is required', 400);
        }
        Iif (/[.\\?#]/.test(sittingId)) {
          throw new APIError('Meeting sitting-id contains invalid characters', 400);
        }
        const limit = params.limit ?? 50;
        const offset = params.offset ?? 0;

        const response = await this.get<JSONLDResponse>(
          `meetings/${sittingId}/foreseen-activities`,
          { format: 'application/ld+json', offset, limit }
        );

        const items = Array.isArray(response.data) ? response.data : [];
        const activities = items.map((item) => this.transformMeetingActivity(item));
        const hasMore = activities.length === limit;
        return { data: activities, total: activities.length + offset + (hasMore ? 1 : 0), limit, offset, hasMore };
      }

      /**
       * Returns plenary session documents for a specific meeting.
       * **EP API Endpoint:** `GET /meetings/{sitting-id}/plenary-session-documents`
       */
      async getMeetingPlenarySessionDocuments(
        sittingId: string,
        params: { limit?: number; offset?: number } = {}
      ): Promise<PaginatedResponse<LegislativeDocument>> {
        if (sittingId.trim() === '') {
          throw new APIError('Meeting sitting-id is required', 400);
        }
        if (/[.\\?#]/.test(sittingId)) {
          throw new APIError('Meeting sitting-id contains invalid characters', 400);
        }
        const limit = params.limit ?? 50;
        const offset = params.offset ?? 0;

        const response = await this.get<JSONLDResponse>(
          `meetings/${sittingId}/plenary-session-documents`,
          { format: 'application/ld+json', offset, limit }
        );

        const items = Array.isArray(response.data) ? response.data : [];
        const docs = items.map((item) => this.transformDocument(item));
        const hasMore = docs.length === limit;
        return { data: docs, total: docs.length + offset + (hasMore ? 1 : 0), limit, offset, hasMore };
      }

      /**
       * Returns plenary session document items for a specific meeting.
       * **EP API Endpoint:** `GET /meetings/{sitting-id}/plenary-session-document-items`
       */
      async getMeetingPlenarySessionDocumentItems(
        sittingId: string,
        params: { limit?: number; offset?: number } = {}
      ): Promise<PaginatedResponse<LegislativeDocument>> {
        if (sittingId.trim() === '') {
          throw new APIError('Meeting sitting-id is required', 400);
        }
        if (/[.\\?#]/.test(sittingId)) {
          throw new APIError('Meeting sitting-id contains invalid characters', 400);
        }
        const limit = params.limit ?? 50;
        const offset = params.offset ?? 0;

        const response = await this.get<JSONLDResponse>(
          `meetings/${sittingId}/plenary-session-document-items`,
          { format: 'application/ld+json', offset, limit }
        );

        const items = Array.isArray(response.data) ? response.data : [];
        const docs = items.map((item) => this.transformDocument(item));
        const hasMore = docs.length === limit;
        return { data: docs, total: docs.length + offset + (hasMore ? 1 : 0), limit, offset, hasMore };
      }

      /**
       * Returns a single EP meeting by ID.
       * **EP API Endpoint:** `GET /meetings/{event-id}`
       */
      async getMeetingById(eventId: string): Promise<PlenarySession> {
        if (eventId.trim() === '') {
          throw new APIError('Meeting event ID is required', 400);
        }
        const response = await this.get<Record<string, unknown>>(
          `meetings/${eventId}`,
          { format: 'application/ld+json' }
        );
        return this.transformPlenarySession(response);
      }

      /**
       * Returns EP events (hearings, conferences, etc.).
       * **EP API Endpoint:** `GET /events`
       *
       * **Note:** The EP API `/events` endpoint does **not** support `year`,
       * `date-from`, or `date-to` query parameters — it has no date filtering
       * at all per the OpenAPI spec.  Only pagination (limit/offset) is supported.
       */
      async getEvents(params: {
        limit?: number;
        offset?: number;
      } = {}): Promise<PaginatedResponse<EPEvent>> {
        const limit = params.limit ?? 50;
        const offset = params.offset ?? 0;

        const apiParams: Record<string, unknown> = {
          format: 'application/ld+json',
          offset,
          limit,
        };

        const response = await this.get<JSONLDResponse>('events', apiParams);
        const items = Array.isArray(response.data) ? response.data : [];
        const events = items.map((item) => this.transformEvent(item));
        const hasMore = events.length === limit;
        return { data: events, total: events.length + offset + (hasMore ? 1 : 0), limit, offset, hasMore };
      }

      /**
       * Retrieves recently updated events via the feed endpoint.
       * **EP API Endpoint:** `GET /events/feed`
       *
       * **Note:** The EP API `events/feed` endpoint is significantly slower
       * than other feed endpoints. This method uses the global EP request
       * timeout (no extended slow-feed minimum) and **throws** `APIError` on
       * HTTP failures (including timeouts surfaced as status 408).
       *
       * The MCP tool layer (`handleGetEventsFeed`) converts thrown errors into
       * a machine-readable in-band feed envelope; direct `PlenaryClient` /
       * `EuropeanParliamentClient` consumers should handle `APIError` throws.
       */
      async getEventsFeed(params: {
        timeframe?: string;
        startDate?: string;
        activityType?: string;
      } = {}): Promise<JSONLDResponse> {
        return this.get<JSONLDResponse>('events/feed', {
          format: 'application/ld+json',
          ...(params.timeframe !== undefined ? { timeframe: params.timeframe } : {}),
          ...(params.startDate !== undefined ? { 'start-date': params.startDate } : {}),
          ...(params.activityType !== undefined ? { 'activity-type': params.activityType } : {}),
        });
      }

      /**
       * Returns a single EP event by ID.
       * **EP API Endpoint:** `GET /events/{event-id}`
       */
      async getEventById(eventId: string): Promise<EPEvent> {
        if (eventId.trim() === '') {
          throw new APIError('Event ID is required', 400);
        }
        const response = await this.get<Record<string, unknown>>(
          `events/${eventId}`,
          { format: 'application/ld+json' }
        );
        return this.transformEvent(response);
      }
    }