Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-pro-preview-05-06· GoogleHugging Face LMArena Human Preference 140K

libs/common/src/lib/services/flight.service.ts:40:51 - error TS1343: The 'import.meta'…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Metallama-4-maverick-03-26-experimental’s answer.
  1. User

    libs/common/src/lib/services/flight.service.ts:40:51 - error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.

          40    worker = new Worker(new URL('./flight.worker', import.meta.url), { type: 'module' }
    

    service import { HttpClient, HttpParams } from '@angular/common/http'; import { inject, Injectable } from '@angular/core'; import { filter, map, Observable, Subject, tap } from 'rxjs'; import { Flight, FLIGHT_STATUS_DICT, IFlight, IFlightLeg } from '../models/flight.model'; import { DateTime } from 'luxon'; import { flatten, intersection, sortBy } from 'lodash';; import * as FileSaver from 'file-saver'; import * as ExcelJS from 'exceljs'; import { ConfigService } from './config.service'; import { GraphqlService } from './graphql.service'; import { AuthService } from '../core/auth/auth.service'; import { generateClient, GraphQLResult } from 'aws-amplify/api'; import { flightLegSubscription } from './queries/flightleg.subscription'; import { FlightTag } from '../models/tag.model';

    type GetFlightOptions = { startTs: string; endTs: string; flightNumber?: string; };

    @Injectable({ providedIn: 'root', }) export class FlightService { public workerProcessedFlights= new Subject<Flight[]>(); private readonly httpClient = inject(HttpClient); // private readonly thresholdStore = inject(ThresholdStore); private configService = inject(ConfigService); private graphql = inject(GraphqlService); private authService = inject(AuthService); private readonly flightListRealTimeHost = this.configService.config?.flightListRealTimeHost || ''; private client = generateClient({ endpoint: this.flightListRealTimeHost, authMode: 'lambda', authToken: `Bearer{this.authService.accessToken}` });

    worker = new Worker(new URL('./flight.worker', import.meta.url), { type: 'module' });

    constructor() { this.graphql.initializeClient(this.flightListRealTimeHost); }

    public getFlights(opts: GetFlightOptions): Observable<Flight[]> { const url = this.configService.config?.oneuiDOPBaseUrl + "/api/v1/flights";

    const params = new HttpParams()
      .set('startTs', opts.startTs)
      .set('endTs', opts.endTs);
    return this.httpClient.get<Flight[]>(url, {params});
    

    }

    public onFlightListUpdateEvent(): Observable<GraphQLResult<{ observeFlightLeg: Flight }>> { return this.client.graphql({ query: flightLegSubscription }) as Observable<GraphQLResult<{ observeFlightLeg: Flight }>>; } public processFlight(flight: Flight): Flight { flight = { ...flight, notes: flight.notes || [], tags: flight.tags || [], cxScore: +flight.cxScore, communicatorMessages: flight.communicatorMessages || [], lastUpdatedTs: DateTime.fromISO(flight.lastUpdated + 'Z').toISO() || '', diversionLegs: this.generateDiversionLegs(flight), };

    flight.painCategory = this.assignPainCategory(flight);
    
    return flight;
    

    }

    public webWorkerFlightProcess(flights: Flight[]) { const data = { originalFlights: flights, // thresholdData: this.thresholdStore.thresholdEntities(), thresholdData: [] };

    this.worker.postMessage(data);
    
    this.worker.onmessage = ({ data }) => {
      this.workerProcessedFlights$.next(data);
    };
    

    }

    public getFlightUpdates(timestamp: string): Observable<Flight[]> { const url = this.configService.config?.oneuiDOPBaseUrl + flightupdates/${timestamp};

    return this.httpClient.get<Flight[]>(url);
    

    }

    public filterFlights(flights: Flight[], filters: any): Flight[] { const keepActiveStatus = ['MONITOR', 'ACTION'];

    const timeOffset = DateTime.utc().minus({ hours: 12 });
    
    // Filter only painful flights
    flights = flights.filter((flight) => flight.cxScore >= 0);
    
    // Remove Completed +12 Hours
    flights = flights.filter((flight) => {
      if (flight.flightLegStatus !== 'COMPLETE') {
        return true;
      }
    
      if (flight.flightLegStatus === 'COMPLETE') {
        // If for some reason a complete flight doesnt have in IN time show it list
        if (!flight.actualArrivalTimeUtc) {
          return true;
        }
    
        if (
          DateTime.fromISO(flight.actualArrivalTimeUtc) > timeOffset ||
          keepActiveStatus.includes(flight.docStatus)
        ) {
          return true;
        } else {
          return false;
        }
      }
    
      return false;
    });
    
    // Remove Cancelled +12 Hours
    flights = flights.filter((flight) => {
      if (flight.flightLegStatus !== 'CANCELED') {
        return true;
      }
    
      if (flight.flightLegStatus === 'CANCELED') {
        // If no cancel time available include in filter for user to manually hide
        if (flight.cnclDteTmeUtc === null) {
          return true;
        }
    
        if (
          DateTime.fromISO(flight.cnclDteTmeUtc) > timeOffset ||
          keepActiveStatus.includes(flight.docStatus)
        ) {
          return true;
        }
      }
    
      return false;
    });
    
    if (filters.flightNumber) {
      flights = flights.filter((f) => f.flightNumber === filters.flightNumber);
    }
    
    if (filters.originCode) {
      flights = flights.filter(
        (f) => f.originCode.toLowerCase() === filters.originCode.toLowerCase(),
      );
    }
    
    if (filters.destinationCode) {
      flights = flights.filter(
        (f) =>
          f.destinationCode.toLowerCase() ===
          filters.destinationCode.toLowerCase(),
      );
    }
    
    if (filters.originDate && filters.originDate !== 'ALL') {
      flights = flights.filter(
        (flight) =>
          DateTime.fromISO(flight.flightOriginDateLcl).toFormat('dd') ===
          filters.originDate,
      );
    }
    
    if (filters.flightStatus) {
      let activeStatusList = filters.flightStatus.map((statusGroup: keyof typeof FLIGHT_STATUS_DICT) => {
        return FLIGHT_STATUS_DICT[statusGroup];
      });
    
      activeStatusList = flatten(activeStatusList);
    
      flights = flights.filter((flight) => {
        return activeStatusList.map((s: string) => s.toUpperCase()).includes(flight.flightLegStatus);
      });
    }
    
    if (filters.teamStatus && filters.teamStatus.length) {
      flights = flights.filter((f) => {
        const filterArray: string[] = [];
    
        filterArray.push(`DOC:${f.docStatus ? f.docStatus : 'NONE'}`);
        filterArray.push(`ROC:${f.rocStatus ? f.rocStatus : 'NONE'}`);
        filterArray.push(`GAC:${f.gacStatus ? f.gacStatus : 'NONE'}`);
        filterArray.push(`RMO:${f.rmoStatus ? f.rmoStatus : 'NONE'}`);
        filterArray.push(`RES:${f.resOccStatus ? f.resOccStatus : 'NONE'}`);
        filterArray.push(
          `CATERING:${f.occCateringStatus ? f.occCateringStatus : 'NONE'}`,
        );
        filterArray.push(`ACS:${f.acsOccStatus ? f.acsOccStatus : 'NONE'}`);
    
        return intersection(filters.teamStatus, filterArray).length;
      });
    }
    
    if (filters.piLBound) {
      flights = flights.filter((flight) => flight.cxScore >= filters.piLBound);
    }
    
    if (filters.piUBound) {
      flights = flights.filter((flight) => flight.cxScore <= filters.piUBound);
    }
    
    if (filters.painVelocity === 'HIGH') {
      flights = flights.filter((flight) => flight.lastHighPainVelocityCheckTs);
    }
    
    if (filters.carriers && filters.carriers.length > 0) {
      flights = flights.filter((flight) =>
        filters.carriers.includes(flight.operatingCarrierCode),
      );
    }
    
    if (filters.tags && filters.tags.length) {
      flights = (flights || []).filter((flight) => {
        if (flight.tags) {
          const flightTags = flight.tags.map((t: FlightTag) => t.tag);
    
          return intersection(filters.tags, flightTags).length;
        }
        return ['']
      });
    }
    
    if (filters.docCommunicationType && filters.docCommunicationType.length) {
      flights = flights.filter((flight) => {
        if (flight.communicatorMessages) {
          const commTypes = flight.communicatorMessages.map(
            (comm) => comm.type,
          );
    
          return (
            intersection(commTypes, filters.docCommunicationType).length > 0
          );
        }
    
        return false;
      });
    }
    
    return flights;
    

    }

    public addFlightTask(flight: Flight, task: any): Observable { const url = this.configService.config?.oneuiDOPBaseUrl + /api/v1/flights/${flight.flightId}/tasks;

    return this.httpClient.post(url, task);
    

    }

    public createTeamStatus(status: any) { const url = this.configService.config?.oneuiDOPBaseUrl + 'flights/status';

    return this.httpClient.post(url, status);
    

    }

    public updatesTeamStatus(status: { ID: any; }) { const url = this.configService.config?.oneuiDOPBaseUrl + flights/status/${status.ID};

    return this.httpClient.put(url, status);
    

    }

    public getFlightBySK(opts: { sk: string }): Observable { const url = this.configService.config?.oneuiDOPBaseUrl + /api/v1/flights/${opts.sk};

    return this.httpClient.get<Flight>(url).pipe(
      map((flight: Flight) => this.processFlight(flight)),
    );
    

    }

    public lookupFlights(params: GetFlightOptions): Observable<Flight[]> { const url = this.configService.config?.oneuiDOPBaseUrl + /api/v1/flightlookup;

    return this.httpClient.get<Flight[]>(url, { params });
    

    }

    public getScoreBreakdown(flight: Flight): Observable { const url = this.configService.config?.oneuiDOPBaseUrl + flights/${flight.flightId}/scoredetail;

    return this.httpClient.get(url);
    

    }

    public assignPainCategory(flight: Flight): string { const cxScore = flight.cxScore; // const threshold = this.thresholdStore // .thresholdEntities() // .filter((t) => cxScore >= t['lowerBound'] && cxScore < t['upperBound']);

    // if (threshold.length > 0) {
    //   return threshold[0]['name'];
    // } else {
    //   return '--';
    // }
    return '--'
    

    }

    public generateDiversionLegs(flight: Flight) { if (flight.linkedLegs) { return flight.linkedLegs.filter( (leg) => leg.arvl_iop_action_cde === 'DVRT', ); } return []; }

    public downloadStatusChanges(startTs: string, endTs: string) { const url = this.configService.config?.oneuiDOPBaseUrl + statuschange;

    const params = {
      startTs,
      endTs,
    };
    
    this.httpClient.get(url, { params }).subscribe(async (res: any) => {
      if (res) {
        const sheetName = 'OCC DOC Flight Tracker';
        const workbook = new ExcelJS.Workbook();
        const sheet = workbook.addWorksheet(sheetName);
    
        sheet.addRow([
          'Carrier',
          'Flt Num',
          'Orig',
          'Dest',
          'SKD Dep Date',
          'Final PI',
          'Action',
          'Value',
          'Link',
        ]);
    
        const font = { name: 'Arial', size: 12, bold: true };
    
        sheet.getCell('A1').font = font;
        sheet.getCell('B1').font = font;
        sheet.getCell('C1').font = font;
        sheet.getCell('D1').font = font;
        sheet.getCell('E1').font = font;
        sheet.getCell('F1').font = font;
        sheet.getCell('G1').font = font;
        sheet.getCell('H1').font = font;
        sheet.getCell('I1').font = font;
    
        const filteredArray = res.filter((rec: { content: { status: string; }; }) => {
          return (
            rec.content.status === 'ACTION|COMPLETE' ||
            rec.content.status === 'ACTION'
          );
        });
    
        // Massage leg
        filteredArray.forEach((c: { [x: string]: any; content: { status: any; }; }) => {
          const data = c['flightid'].split('::');
    
          c['carrier'] = data[0];
          c['flightNumber'] = data[2];
          c['Orig'] = data[3];
          c['dest'] = data[4];
          c['skd_date'] = DateTime.fromISO(data[1]).toFormat('LL/dd/yy');
          c['content'] = c.content.status;
        });
    
        // Sort By Date
        const sorted_array = sortBy(filteredArray, ['skd_date', 'flightNumber']);
    
        let recsMap: any;
    
        // Keep ACTION / COMPLETE over ACTION
        sorted_array.forEach((item) => {
          if (recsMap[item.flightid]) {
            if (item.content === 'ACTION | COMPLETE') {
              recsMap[item.flightid] = item;
            }
          } else {
            recsMap[item.flightid] = item;
          }
        });
    
        const records: any = Object.values(recsMap);
    
        records.forEach((c: { [x: string]: any; }) => {
          const newRow = sheet.addRow([
            c['carrier'],
            c['flightNumber'],
            c['Orig'],
            c['dest'],
            c['skd_date'],
            c['cxScore'],
            c['action'],
            c['content'],
            {
              text: 'Link',
              hyperlink: `${window.location.origin}/?flight=${c['flightid']}`,
            },
          ]);
    
          newRow.font = { name: 'Arial', size: 10 };
        });
    
        const buffer = await workbook.xlsx.writeBuffer();
        const fileType =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        const fileExtension = '.xlsx';
        const blob = new Blob([buffer], { type: fileType });
    
        FileSaver.saveAs(
          blob,
          `${sheetName}-${DateTime.fromISO(startTs).toFormat('ddLLL')}-${DateTime.fromISO(
            endTs,
          ).toFormat(
            'ddLLL',
          )}-${DateTime.local().toFormat('yyyy-LL-dd HHmm')}.${fileExtension}`,
        );
      }
    });
    

    } }

    worker.json { "extends": "./tsconfig.json", "compilerOptions": { "lib": ["es20222", "webworker"], "target":"es2022", "module": "es2022", "types": [] }, "include": [ "**/*.worker.ts" ] }

    { "name": "@oneui/common", "$schema": "../../node_modules/nx/schemas/project-schema.json", "sourceRoot": "libs/common/src", "prefix": "lib", "projectType": "library", "tags": [], "targets": { "test": { "executor": "@nx/jest:jest", "outputs": ["{workspaceRoot}/coverage/{projectRoot}"], "options": { "jestConfig": "libs/common/jest.config.ts", "webWorkerTsConfig":"tsconfig.worker.json" } }, "lint": { "executor": "@nx/eslint:lint" }, "build" :{ "options": { "webWorkerTsConfig":"tsconfig.worker.json" } } } }

  2. Gemini Assistant

    Okay, the error message is quite clear: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.

    This means that the TypeScript configuration used to compile your flight.service.ts file (and the rest of your common library) does not have its compilerOptions.module set to one of these modern module systems.

    You've correctly configured tsconfig.worker.json for the worker file itself, but that doesn't affect how flight.service.ts is compiled.

    Here's what you need to do:

    1. Identify the correct tsconfig.json for your library: In an Nx workspace, your libs/common library will have its own tsconfig.lib.json (or similar, like tsconfig.json directly in libs/common/) which likely extends a base tsconfig.base.json at the root of your workspace. You need to modify the configuration that applies to the compilation of flight.service.ts.

      • Look for libs/common/tsconfig.lib.json.
      • If it's not there, or if the module option is inherited, check tsconfig.base.json at the root of your Nx workspace.
    2. Modify the compilerOptions.module: Change the module option to es2022 (or esnext, es2020 if you have specific reasons, but es2022 is a good modern default).

      Example (if modifying libs/common/tsconfig.lib.json):

      {
        "extends": "../../tsconfig.base.json", // Or your actual base tsconfig
        "compilerOptions": {
          "outDir": "../../dist/out-tsc",
          "declaration": true,
          "declarationMap": true,
          "inlineSources": true,
          "types": [],
          "module": "es2022", // <--- ADD OR CHANGE THIS LINE
          "forceConsistentCasingInFileNames": true,
          "strict": true,
          "noImplicitOverride": true,
          "noPropertyAccessFromIndexSignature": true,
          "noImplicitReturns": true,
          "noFallthroughCasesInSwitch": true
        },
        "exclude": [
          "src/test-setup.ts",
          "**/*.spec.ts",
          "jest.config.ts",
          "**/*.test.ts",
          "**/*.worker.ts" // Ensure workers are excluded if handled by a separate tsconfig
        ],
        "include": ["**/*.ts"]
      }
      

      Or, if modifying tsconfig.base.json (affects all projects unless overridden):

      {
        "compileOnSave": false,
        "compilerOptions": {
          "rootDir": ".",
          "sourceMap": true,
          "declaration": false,
          "moduleResolution": "node",
          "emitDecoratorMetadata": true,
          "experimentalDecorators": true,
          "importHelpers": true,
          "target": "es2022", // Also ensure target is modern
          "module": "es2022", // <--- ADD OR CHANGE THIS LINE
          "lib": ["es2020", "dom"], // es2022 if target is es2022
          "skipLibCheck": true,
          "skipDefaultLibCheck": true,
          "baseUrl": ".",
          // ... other options
        },
        "exclude": ["node_modules", "tmp"]
      }
      

      Important: When you set module to es2022 or esnext, you should also ensure your target in compilerOptions is also modern, e.g., es2022.

    3. Why this works: import.meta.url is a feature of ES Modules that provides the URL of the current module. To use it, TypeScript needs to know that you're working within an environment that supports this (i.e., you're compiling to a modern ES module format).

    4. Regarding your project.json: The webWorkerTsConfig option in your project.json tells Nx (and the underlying Angular CLI/Webpack) how to compile the worker file itself (flight.worker.ts). This is separate from how the main library code (flight.service.ts) is compiled. Your tsconfig.worker.json looks fine for the worker. The error is in the caller of the worker.

    In summary: The primary fix is to ensure the tsconfig.json file that governs the compilation of libs/common/src/lib/services/flight.service.ts has compilerOptions.module set to es2022 (or another compatible value from the error message) and ideally compilerOptions.target also set to es2022.

    After making the change, you'll likely need to restart your development server or rebuild the library.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.