hunk.code_window:  * found in the LICENSE file at https://angular.io/license
    */
   /**
    * This uses a dynamic import to load a module which may be ESM.
    * CommonJS code can load ESM code via a dynamic import. Unfortunately, TypeScript
  
hunk.labels: keep keep add keep keep keep
hunk.after_edit: /**
    * Lazily compiled dynamic import loader function.
    */
   let load: (<T>(modulePath: string | URL) => Promise<T>) | undefined;
  
hunk.file_path: packages/angular/cli/src/utilities/load-esm.ts
hunk.type: add
file: /**
   * @license
   * Copyright Google LLC All Rights Reserved.
   *
   * Use of this source code is governed by an MIT-style license that can be
   * found in the LICENSE file at https://angular.io/license
   */
  
  import remapping, { SourceMapInput } from '@ampproject/remapping';
  import type { BuilderContext } from '@angular-devkit/architect';
  import type { json, logging } from '@angular-devkit/core';
  import type { Plugin } from 'esbuild';
  import { lookup as lookupMimeType } from 'mrmime';
  import assert from 'node:assert';
  import { randomUUID } from 'node:crypto';
  import { readFile } from 'node:fs/promises';
  import { ServerResponse } from 'node:http';
  import path from 'node:path';
  import type { Connect, DepOptimizationConfig, InlineConfig, ViteDevServer } from 'vite';
  import { BuildOutputFile, BuildOutputFileType } from '../../tools/esbuild/bundler-context';
  import { JavaScriptTransformer } from '../../tools/esbuild/javascript-transformer';
  import { createRxjsEsmResolutionPlugin } from '../../tools/esbuild/rxjs-esm-resolution-plugin';
  import { getFeatureSupport, transformSupportedBrowsersToTargets } from '../../tools/esbuild/utils';
  import { createAngularLocaleDataPlugin } from '../../tools/vite/i18n-locale-plugin';
  import { renderPage } from '../../utils/server-rendering/render-page';
  import { getSupportedBrowsers } from '../../utils/supported-browsers';
  import { getIndexOutputFile } from '../../utils/webpack-browser-config';
  import { buildApplicationInternal } from '../application';
  import { buildEsbuildBrowser } from '../browser-esbuild';
  import { Schema as BrowserBuilderOptions } from '../browser-esbuild/schema';
  import { loadProxyConfiguration } from './load-proxy-config';
  import type { NormalizedDevServerOptions } from './options';
  import type { DevServerBuilderOutput } from './webpack-server';
  
  interface OutputFileRecord {
    contents: Uint8Array;
    size: number;
    hash?: string;
    updated: boolean;
    servable: boolean;
  }
  
  export async function* serveWithVite(
    serverOptions: NormalizedDevServerOptions,
    builderName: string,
    context: BuilderContext,
    plugins?: Plugin[],
  ): AsyncIterableIterator<DevServerBuilderOutput> {
    // Get the browser configuration from the target name.
    const rawBrowserOptions = (await context.getTargetOptions(
      serverOptions.buildTarget,
    )) as json.JsonObject & BrowserBuilderOptions;
  
    const browserOptions = (await context.validateOptions(
      {
        ...rawBrowserOptions,
        watch: serverOptions.watch,
        poll: serverOptions.poll,
        verbose: serverOptions.verbose,
      } as json.JsonObject & BrowserBuilderOptions,
      builderName,
    )) as json.JsonObject & BrowserBuilderOptions;
  
    if (browserOptions.prerender) {
      // Disable prerendering if enabled and force SSR.
      // This is so instead of prerendering all the routes for every change, the page is "prerendered" when it is requested.
      browserOptions.ssr = true;
      browserOptions.prerender = false;
  
      // https://nodejs.org/api/process.html#processsetsourcemapsenabledval
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (process as any).setSourceMapsEnabled(true);
    }
  
    // Set all packages as external to support Vite's prebundle caching
    browserOptions.externalPackages = serverOptions.cacheOptions.enabled;
  
    if (serverOptions.servePath === undefined && browserOptions.baseHref !== undefined) {
      serverOptions.servePath = browserOptions.baseHref;
    }
  
    // The development server currently only supports a single locale when localizing.
    // This matches the behavior of the Webpack-based development server but could be expanded in the future.
    if (
      browserOptions.localize === true ||
      (Array.isArray(browserOptions.localize) && browserOptions.localize.length > 1)
    ) {
      context.logger.warn(
        'Localization (`localize` option) has been disabled. The development server only supports localizing a single locale per build.',
      );
      browserOptions.localize = false;
    } else if (browserOptions.localize) {
      // When localization is enabled with a single locale, force a flat path to maintain behavior with the existing Webpack-based dev server.
      browserOptions.forceI18nFlatOutput = true;
    }
  
    // Setup the prebundling transformer that will be shared across Vite prebundling requests
    const prebundleTransformer = new JavaScriptTransformer(
      // Always enable JIT linking to support applications built with and without AOT.
      // In a development environment the additional scope information does not
      // have a negative effect unlike production where final output size is relevant.
      { sourcemap: true, jit: true },
      1,
    );
  
    // Extract output index from options
    // TODO: Provide this info from the build results
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const htmlIndexPath = getIndexOutputFile(browserOptions.index as any);
  
    // dynamically import Vite for ESM compatibility
    const { createServer, normalizePath } = await import('vite');
  
    let server: ViteDevServer | undefined;
    let serverUrl: URL | undefined;
    let hadError = false;
    const generatedFiles = new Map<string, OutputFileRecord>();
    const assetFiles = new Map<string, string>();
    const externalMetadata: { implicit: string[]; explicit: string[] } = {
      implicit: [],
      explicit: [],
    };
    const build =
      builderName === '@angular-devkit/build-angular:application'
        ? buildApplicationInternal
        : buildEsbuildBrowser;
  
    // TODO: Switch this to an architect schedule call when infrastructure settings are supported
    for await (const result of build(
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      browserOptions as any,
      context,
      {
        write: false,
      },
      plugins,
    )) {
      assert(result.outputFiles, 'Builder did not provide result files.');
  
      // If build failed, nothing to serve
      if (!result.success) {
        // If server is active, send an error notification
        if (result.errors?.length && server) {
          hadError = true;
          server.ws.send({
            type: 'error',
            err: {
              message: result.errors[0].text,
              stack: '',
              loc: result.errors[0].location,
            },
          });
        }
        continue;
      } else if (hadError && server) {
        hadError = false;
        // Send an empty update to clear the error overlay
        server.ws.send({
          'type': 'update',
          updates: [],
        });
      }
  
      // Analyze result files for changes
      analyzeResultFiles(normalizePath, htmlIndexPath, result.outputFiles, generatedFiles);
  
      assetFiles.clear();
      if (result.assetFiles) {
        for (const asset of result.assetFiles) {
          assetFiles.set('/' + normalizePath(asset.destination), asset.source);
        }
      }
  
      // To avoid disconnecting the array objects from the option, these arrays need to be mutated
      // instead of replaced.
      // TODO: split explicit imports by platform to avoid having Vite optimize server-only/browser-only
      // dependencies twice when SSR is enabled.
      if (result.externalMetadata) {
        if (result.externalMetadata.explicit) {
          externalMetadata.explicit.push(...result.externalMetadata.explicit);
        }
        if (result.externalMetadata.implicit) {
          externalMetadata.implicit.push(...result.externalMetadata.implicit);
        }
      }
  
      if (server) {
        handleUpdate(normalizePath, generatedFiles, server, serverOptions, context.logger);
      } else {
        const projectName = context.target?.project;
        if (!projectName) {
          throw new Error('The builder requires a target.');
        }
  
        const { root = '' } = await context.getProjectMetadata(projectName);
        const projectRoot = path.join(context.workspaceRoot, root as string);
        const browsers = getSupportedBrowsers(projectRoot, context.logger);
        const target = transformSupportedBrowsersToTargets(browsers);
  
        // Setup server and start listening
        const serverConfiguration = await setupServer(
          serverOptions,
          generatedFiles,
          assetFiles,
          browserOptions.preserveSymlinks,
          externalMetadata,
          !!browserOptions.ssr,
          prebundleTransformer,
          target,
        );
  
        server = await createServer(serverConfiguration);
  
        await server.listen();
        const urls = server.resolvedUrls;
        if (urls && (urls.local.length || urls.network.length)) {
          serverUrl = new URL(urls.local[0] ?? urls.network[0]);
        }
  
        // log connection information
        server.printUrls();
      }
  
      // TODO: adjust output typings to reflect both development servers
      yield {
        success: true,
        port: serverUrl?.port,
        baseUrl: serverUrl?.href,
      } as unknown as DevServerBuilderOutput;
    }
  
    // Add cleanup logic via a builder teardown
    let deferred: () => void;
    context.addTeardown(async () => {
      await server?.close();
      await prebundleTransformer.close();
      deferred?.();
    });
    await new Promise<void>((resolve) => (deferred = resolve));
  }
  
  function handleUpdate(
    normalizePath: (id: string) => string,
    generatedFiles: Map<string, OutputFileRecord>,
    server: ViteDevServer,
    serverOptions: NormalizedDevServerOptions,
    logger: logging.LoggerApi,
  ): void {
    const updatedFiles: string[] = [];
  
    // Invalidate any updated files
    for (const [file, record] of generatedFiles) {
      if (record.updated) {
        updatedFiles.push(file);
        const updatedModules = server.moduleGraph.getModulesByFile(
          normalizePath(path.join(server.config.root, file)),
        );
        updatedModules?.forEach((m) => server?.moduleGraph.invalidateModule(m));
      }
    }
  
    if (!updatedFiles.length) {
      return;
    }
  
    if (serverOptions.liveReload || serverOptions.hmr) {
      if (updatedFiles.every((f) => f.endsWith('.css'))) {
        const timestamp = Date.now();
        server.ws.send({
          type: 'update',
          updates: updatedFiles.map((filePath) => {
            return {
              type: 'css-update',
              timestamp,
              path: filePath,
              acceptedPath: filePath,
            };
          }),
        });
  
        logger.info('HMR update sent to client(s)...');
  
        return;
      }
    }
  
    // Send reload command to clients
    if (serverOptions.liveReload) {
      logger.info('Reloading client(s)...');
  
      server.ws.send({
        type: 'full-reload',
        path: '*',
      });
    }
  }
  
  function analyzeResultFiles(
    normalizePath: (id: string) => string,
    htmlIndexPath: string,
    resultFiles: BuildOutputFile[],
    generatedFiles: Map<string, OutputFileRecord>,
  ) {
    const seen = new Set<string>(['/index.html']);
    for (const file of resultFiles) {
      let filePath;
      if (file.path === htmlIndexPath) {
        // Convert custom index output path to standard index path for dev-server usage.
        // This mimics the Webpack dev-server behavior.
        filePath = '/index.html';
      } else {
        filePath = normalizePath(file.path);
      }
      seen.add(filePath);
  
      // Skip analysis of sourcemaps
      if (filePath.endsWith('.map')) {
        generatedFiles.set(filePath, {
          contents: file.contents,
          servable:
            file.type === BuildOutputFileType.Browser || file.type === BuildOutputFileType.Media,
          size: file.contents.byteLength,
          updated: false,
        });
  
        continue;
      }
  
      const existingRecord = generatedFiles.get(filePath);
      if (
        existingRecord &&
        existingRecord.size === file.contents.byteLength &&
        existingRecord.hash === file.hash
      ) {
        // Same file
        existingRecord.updated = false;
        continue;
      }
  
      // New or updated file
      generatedFiles.set(filePath, {
        contents: file.contents,
        size: file.contents.byteLength,
        hash: file.hash,
        updated: true,
        servable:
          file.type === BuildOutputFileType.Browser || file.type === BuildOutputFileType.Media,
      });
    }
  
    // Clear stale output files
    for (const file of generatedFiles.keys()) {
      if (!seen.has(file)) {
        generatedFiles.delete(file);
      }
    }
  }
  
  // eslint-disable-next-line max-lines-per-function
  export async function setupServer(
    serverOptions: NormalizedDevServerOptions,
    outputFiles: Map<string, OutputFileRecord>,
    assets: Map<string, string>,
    preserveSymlinks: boolean | undefined,
    externalMetadata: { implicit: string[]; explicit: string[] },
    ssr: boolean,
    prebundleTransformer: JavaScriptTransformer,
    target: string[],
  ): Promise<InlineConfig> {
    const proxy = await loadProxyConfiguration(
      serverOptions.workspaceRoot,
      serverOptions.proxyConfig,
      true,
    );
  
    // dynamically import Vite for ESM compatibility
    const { normalizePath } = await import('vite');
  
    // Path will not exist on disk and only used to provide separate path for Vite requests
    const virtualProjectRoot = normalizePath(
      path.join(serverOptions.workspaceRoot, `.angular/vite-root/${randomUUID()}/`),
    );
  
    const { builtinModules } = await import('node:module');
  
    const configuration: InlineConfig = {
      configFile: false,
      envFile: false,
      cacheDir: path.join(serverOptions.cacheOptions.path, 'vite'),
      root: virtualProjectRoot,
      publicDir: false,
      esbuild: false,
      mode: 'development',
      appType: 'spa',
      css: {
        devSourcemap: true,
      },
      base: serverOptions.servePath,
      resolve: {
        mainFields: ['es2020', 'browser', 'module', 'main'],
        preserveSymlinks,
      },
      server: {
        port: serverOptions.port,
        strictPort: true,
        host: serverOptions.host,
        open: serverOptions.open,
        headers: serverOptions.headers,
        proxy,
        // Currently does not appear to be a way to disable file watching directly so ignore all files
        watch: {
          ignored: ['**/*'],
        },
        // This is needed when `externalDependencies` is used to prevent Vite load errors.
        // NOTE: If Vite adds direct support for externals, this can be removed.
        preTransformRequests: externalMetadata.explicit.length === 0,
      },
      ssr: {
        // Note: `true` and `/.*/` have different sematics. When true, the `external` option is ignored.
        noExternal: /.*/,
        // Exclude any Node.js built in module and provided dependencies (currently build defined externals)
        external: [...builtinModules, ...externalMetadata.explicit],
        optimizeDeps: getDepOptimizationConfig({
          // Only enable with caching since it causes prebundle dependencies to be cached
          disabled: !serverOptions.cacheOptions.enabled,
          // Exclude any explicitly defined dependencies (currently build defined externals)
          exclude: externalMetadata.explicit,
          // Include all implict dependencies from the external packages internal option
          include: externalMetadata.implicit,
          ssr: true,
          prebundleTransformer,
          target,
        }),
      },
      plugins: [
        createAngularLocaleDataPlugin(),
        {
          name: 'vite:angular-memory',
          // Ensures plugin hooks run before built-in Vite hooks
          enforce: 'pre',
          async resolveId(source, importer) {
            // Prevent vite from resolving an explicit external dependency (`externalDependencies` option)
            if (externalMetadata.explicit.includes(source)) {
              // This is still not ideal since Vite will still transform the import specifier to
              // `/@id/${source}` but is currently closer to a raw external than a resolved file path.
              return source;
            }
  
            if (importer && source[0] === '.' && importer.startsWith(virtualProjectRoot)) {
              // Remove query if present
              const [importerFile] = importer.split('?', 1);
  
              source = normalizePath(
                path.join(path.dirname(path.relative(virtualProjectRoot, importerFile)), source),
              );
            }
            if (source[0] === '/') {
              source = source.slice(1);
            }
            const [file] = source.split('?', 1);
            if (outputFiles.has(file)) {
              return path.join(virtualProjectRoot, source);
            }
          },
          load(id) {
            const [file] = id.split('?', 1);
            const relativeFile = normalizePath(path.relative(virtualProjectRoot, file));
            const codeContents = outputFiles.get(relativeFile)?.contents;
            if (codeContents === undefined) {
              if (relativeFile.endsWith('/node_modules/vite/dist/client/client.mjs')) {
                return loadViteClientCode(file);
              }
  
              return;
            }
  
            const code = Buffer.from(codeContents).toString('utf-8');
            const mapContents = outputFiles.get(relativeFile + '.map')?.contents;
  
            return {
              // Remove source map URL comments from the code if a sourcemap is present.
              // Vite will inline and add an additional sourcemap URL for the sourcemap.
              code: mapContents ? code.replace(/^\/\/# sourceMappingURL=[^\r\n]*/gm, '') : code,
              map: mapContents && Buffer.from(mapContents).toString('utf-8'),
            };
          },
          configureServer(server) {
            const originalssrTransform = server.ssrTransform;
            server.ssrTransform = async (code, map, url, originalCode) => {
              const result = await originalssrTransform(code, null, url, originalCode);
              if (!result) {
                return null;
              }
  
              let transformedCode = result.code;
              if (result.map && map) {
                transformedCode +=
                  `\n//# sourceMappingURL=` +
                  `data:application/json;base64,${Buffer.from(
                    JSON.stringify(
                      remapping([result.map as SourceMapInput, map as SourceMapInput], () => null),
                    ),
                  ).toString('base64')}`;
              }
  
              return {
                ...result,
                map: null,
                code: transformedCode,
              };
            };
  
            // Assets and resources get handled first
            server.middlewares.use(function angularAssetsMiddleware(req, res, next) {
              if (req.url === undefined || res.writableEnded) {
                return;
              }
  
              // Parse the incoming request.
              // The base of the URL is unused but required to parse the URL.
              const pathname = pathnameWithoutServePath(req.url, serverOptions);
              const extension = path.extname(pathname);
  
              // Rewrite all build assets to a vite raw fs URL
              const assetSourcePath = assets.get(pathname);
              if (assetSourcePath !== undefined) {
                // The encoding needs to match what happens in the vite static middleware.
                // ref: https://github.com/vitejs/vite/blob/d4f13bd81468961c8c926438e815ab6b1c82735e/packages/vite/src/node/server/middlewares/static.ts#L163
                req.url = `/@fs/${encodeURI(assetSourcePath)}`;
                next();
  
                return;
              }
  
              // Resource files are handled directly.
              // Global stylesheets (CSS files) are currently considered resources to workaround
              // dev server sourcemap issues with stylesheets.
              if (extension !== '.js' && extension !== '.html') {
                const outputFile = outputFiles.get(pathname);
                if (outputFile?.servable) {
                  const mimeType = lookupMimeType(extension);
                  if (mimeType) {
                    res.setHeader('Content-Type', mimeType);
                  }
                  res.setHeader('Cache-Control', 'no-cache');
                  if (serverOptions.headers) {
                    Object.entries(serverOptions.headers).forEach(([name, value]) =>
                      res.setHeader(name, value),
                    );
                  }
                  res.end(outputFile.contents);
  
                  return;
                }
              }
  
              next();
            });
  
            // Returning a function, installs middleware after the main transform middleware but
            // before the built-in HTML middleware
            return () => {
              function angularSSRMiddleware(
                req: Connect.IncomingMessage,
                res: ServerResponse,
                next: Connect.NextFunction,
              ) {
                const url = req.originalUrl;
                if (!url || url.endsWith('.html')) {
                  next();
  
                  return;
                }
  
                const rawHtml = outputFiles.get('index.server.html')?.contents;
                if (!rawHtml) {
                  next();
  
                  return;
                }
  
                transformIndexHtmlAndAddHeaders(url, rawHtml, res, next, async (html) => {
                  const protocol = serverOptions.ssl ? 'https' : 'http';
                  const route = `${protocol}://${req.headers.host}${req.originalUrl}`;
                  const { content } = await renderPage({
                    document: html,
                    route,
                    serverContext: 'ssr',
                    loadBundle: (path: string) =>
                      // eslint-disable-next-line @typescript-eslint/no-explicit-any
                      server.ssrLoadModule(path.slice(1)) as any,
                    // Files here are only needed for critical CSS inlining.
                    outputFiles: {},
                    // TODO: add support for critical css inlining.
                    inlineCriticalCss: false,
                  });
  
                  return content;
                });
              }
  
              if (ssr) {
                server.middlewares.use(angularSSRMiddleware);
              }
  
              server.middlewares.use(function angularIndexMiddleware(req, res, next) {
                if (!req.url) {
                  next();
  
                  return;
                }
  
                // Parse the incoming request.
                // The base of the URL is unused but required to parse the URL.
                const pathname = pathnameWithoutServePath(req.url, serverOptions);
  
                if (pathname === '/' || pathname === `/index.html`) {
                  const rawHtml = outputFiles.get('/index.html')?.contents;
                  if (rawHtml) {
                    transformIndexHtmlAndAddHeaders(req.url, rawHtml, res, next);
  
                    return;
                  }
                }
  
                next();
              });
            };
  
            function transformIndexHtmlAndAddHeaders(
              url: string,
              rawHtml: Uint8Array,
              res: ServerResponse<import('http').IncomingMessage>,
              next: Connect.NextFunction,
              additionalTransformer?: (html: string) => Promise<string | undefined>,
            ) {
              server
                .transformIndexHtml(url, Buffer.from(rawHtml).toString('utf-8'))
                .then(async (processedHtml) => {
                  if (additionalTransformer) {
                    const content = await additionalTransformer(processedHtml);
                    if (!content) {
                      next();
  
                      return;
                    }
  
                    processedHtml = content;
                  }
  
                  res.setHeader('Content-Type', 'text/html');
                  res.setHeader('Cache-Control', 'no-cache');
                  if (serverOptions.headers) {
                    Object.entries(serverOptions.headers).forEach(([name, value]) =>
                      res.setHeader(name, value),
                    );
                  }
                  res.end(processedHtml);
                })
                .catch((error) => next(error));
            }
          },
        },
      ],
      // Browser only optimizeDeps. (This does not run for SSR dependencies).
      optimizeDeps: getDepOptimizationConfig({
        // Only enable with caching since it causes prebundle dependencies to be cached
        disabled: !serverOptions.cacheOptions.enabled,
        // Exclude any explicitly defined dependencies (currently build defined externals)
        exclude: externalMetadata.explicit,
        // Include all implict dependencies from the external packages internal option
        include: externalMetadata.implicit,
        ssr: false,
        prebundleTransformer,
        target,
      }),
    };
  
    if (serverOptions.ssl) {
      if (serverOptions.sslCert && serverOptions.sslKey) {
        // server configuration is defined above
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        configuration.server!.https = {
          cert: await readFile(serverOptions.sslCert),
          key: await readFile(serverOptions.sslKey),
        };
      } else {
        const { default: basicSslPlugin } = await import('@vitejs/plugin-basic-ssl');
        configuration.plugins ??= [];
        configuration.plugins.push(basicSslPlugin());
      }
    }
  
    return configuration;
  }
  
  /**
   * Reads the resolved Vite client code from disk and updates the content to remove
   * an unactionable suggestion to update the Vite configuration file to disable the
   * error overlay. The Vite configuration file is not present when used in the Angular
   * CLI.
   * @param file The absolute path to the Vite client code.
   * @returns
   */
  async function loadViteClientCode(file: string) {
    const originalContents = await readFile(file, 'utf-8');
    let contents = originalContents.replace('You can also disable this overlay by setting', '');
    contents = contents.replace(
      // eslint-disable-next-line max-len
      '<code part="config-option-name">server.hmr.overlay</code> to <code part="config-option-value">false</code> in <code part="config-file-name">vite.config.js.</code>',
      '',
    );
  
    assert(originalContents !== contents, 'Failed to update Vite client error overlay text.');
  
    return contents;
  }
  
  function pathnameWithoutServePath(url: string, serverOptions: NormalizedDevServerOptions): string {
    const parsedUrl = new URL(url, 'http://localhost');
    let pathname = decodeURIComponent(parsedUrl.pathname);
    if (serverOptions.servePath && pathname.startsWith(serverOptions.servePath)) {
      pathname = pathname.slice(serverOptions.servePath.length);
      if (pathname[0] !== '/') {
        pathname = '/' + pathname;
      }
    }
  
    return pathname;
  }
  
  type ViteEsBuildPlugin = NonNullable<
    NonNullable<DepOptimizationConfig['esbuildOptions']>['plugins']
  >[0];
  
  function getDepOptimizationConfig({
    disabled,
    exclude,
    include,
    target,
    prebundleTransformer,
    ssr,
  }: {
    disabled: boolean;
    exclude: string[];
    include: string[];
    target: string[];
    prebundleTransformer: JavaScriptTransformer;
    ssr: boolean;
  }): DepOptimizationConfig {
    const plugins: ViteEsBuildPlugin[] = [
      {
        name: `angular-vite-optimize-deps${ssr ? '-ssr' : ''}`,
        setup(build) {
          build.onLoad({ filter: /\.[cm]?js$/ }, async (args) => {
            return {
              contents: await prebundleTransformer.transformFile(args.path),
              loader: 'js',
            };
          });
        },
      },
    ];
  
    if (ssr) {
      plugins.unshift(createRxjsEsmResolutionPlugin() as ViteEsBuildPlugin);
    }
  
    return {
      // Only enable with caching since it causes prebundle dependencies to be cached
      disabled,
      // Exclude any explicitly defined dependencies (currently build defined externals)
      exclude,
      // Include all implict dependencies from the external packages internal option
      include,
      // Add an esbuild plugin to run the Angular linker on dependencies
      esbuildOptions: {
        // Set esbuild supported targets.
        target,
        supported: getFeatureSupport(target),
        plugins,
      },
    };
  }
  