#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
{
    // create JSON values
    json j_boolean = true;
    json j_number_integer = 17;
    json j_number_float = 23.42;
    json j_object = {{"one", 1}, {"two", 2}};
    json j_object_empty(json::value_t::object);
    json j_array = {1, 2, 4, 8, 16};
    json j_array_empty(json::value_t::array);
    json j_string = "Hello, world";

    // call back()
    std::cout << j_boolean.back() << '\n';
    std::cout << j_number_integer.back() << '\n';
    std::cout << j_number_float.back() << '\n';
    std::cout << j_object.back() << '\n';
    //std::cout << j_object_empty.back() << '\n';  // undefined behavior
    std::cout << j_array.back() << '\n';
    //std::cout << j_array_empty.back() << '\n';   // undefined behavior
    std::cout << j_string.back() << '\n';

    // back() called on a null value
    try
    {
        json j_null;
        j_null.back();
    }
    catch (const json::invalid_iterator& e)
    {
        std::cout << e.what() << '\n';
    }
}


use std::{
    io::{self, Read},
    process,
};

/// An error that can occur while running a command and reading its output.
///
/// This error can be seamlessly converted to an `io::Error` via a `From`
/// implementation.
#[derive(Debug)]
pub struct CommandError {
    kind: CommandErrorKind,
}

#[derive(Debug)]
enum CommandErrorKind {
    Io(io::Error),
    Stderr(Vec<u8>),
}

impl CommandError {
    /// Create an error from an I/O error.
    pub(crate) fn io(ioerr: io::Error) -> CommandError {
        CommandError { kind: CommandErrorKind::Io(ioerr) }
    }

    /// Create an error from the contents of stderr (which may be empty).
    pub(crate) fn stderr(bytes: Vec<u8>) -> CommandError {
        CommandError { kind: CommandErrorKind::Stderr(bytes) }
    }

    /// Returns true if and only if this error has empty data from stderr.
    pub(crate) fn is_empty(&self) -> bool {
        match self.kind {
            CommandErrorKind::Stderr(ref bytes) => bytes.is_empty(),
            _ => false,
        }
    }
}

impl std::error::Error for CommandError {}

impl std::fmt::Display for CommandError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.kind {
            CommandErrorKind::Io(ref e) => e.fmt(f),
            CommandErrorKind::Stderr(ref bytes) => {
                let msg = String::from_utf8_lossy(bytes);
                if msg.trim().is_empty() {
                    write!(f, "<stderr is empty>")
                } else {
                    let div = "-".repeat(79);
                    write!(
                        f,
                        "\n{div}\n{msg}\n{div}",
                        div = div,
                        msg = msg.trim()
                    )
                }
            }
        }
    }
}

impl From<io::Error> for CommandError {
    fn from(ioerr: io::Error) -> CommandError {
        CommandError { kind: CommandErrorKind::Io(ioerr) }
    }
}

impl From<CommandError> for io::Error {
    fn from(cmderr: CommandError) -> io::Error {
        match cmderr.kind {
            CommandErrorKind::Io(ioerr) => ioerr,
            CommandErrorKind::Stderr(_) => {
                io::Error::new(io::ErrorKind::Other, cmderr)
            }
        }
    }
}

/// Configures and builds a streaming reader for process output.
#[derive(Clone, Debug, Default)]
pub struct CommandReaderBuilder {
    async_stderr: bool,
}

impl CommandReaderBuilder {
    /// Create a new builder with the default configuration.
    pub fn new() -> CommandReaderBuilder {
        CommandReaderBuilder::default()
    }

    /// Build a new streaming reader for the given command's output.
    ///
    /// The caller should set everything that's required on the given command
    /// before building a reader, such as its arguments, environment and
    /// current working directory. Settings such as the stdout and stderr (but
    /// not stdin) pipes will be overridden so that they can be controlled by
    /// the reader.
    ///
    /// If there was a problem spawning the given command, then its error is
    /// returned.
    pub fn build(
        &self,
        command: &mut process::Command,
    ) -> Result<CommandReader, CommandError> {
        let mut child = command
            .stdout(process::Stdio::piped())
            .stderr(process::Stdio::piped())
            .spawn()?;
        let stderr = if self.async_stderr {
            StderrReader::r#async(child.stderr.take().unwrap())
        } else {
            StderrReader::sync(child.stderr.take().unwrap())
        };
        Ok(CommandReader { child, stderr, eof: false })
    }

    /// When enabled, the reader will asynchronously read the contents of the
    /// command's stderr output. When disabled, stderr is only read after the
    /// stdout stream has been exhausted (or if the process quits with an error
    /// code).
    ///
    /// Note that when enabled, this may require launching an additional
    /// thread in order to read stderr. This is done so that the process being
    /// executed is never blocked from writing to stdout or stderr. If this is
    /// disabled, then it is possible for the process to fill up the stderr
    /// buffer and deadlock.
    ///
    /// This is enabled by default.
    pub fn async_stderr(&mut self, yes: bool) -> &mut CommandReaderBuilder {
        self.async_stderr = yes;
        self
    }
}

/// A streaming reader for a command's output.
///
/// The purpose of this reader is to provide an easy way to execute processes
/// whose stdout is read in a streaming way while also making the processes'
/// stderr available when the process fails with an exit code. This makes it
/// possible to execute processes while surfacing the underlying failure mode
/// in the case of an error.
///
/// Moreover, by default, this reader will asynchronously read the processes'
/// stderr. This prevents subtle deadlocking bugs for noisy processes that
/// write a lot to stderr. Currently, the entire contents of stderr is read
/// on to the heap.
///
/// # Example
///
/// This example shows how to invoke `gzip` to decompress the contents of a
/// file. If the `gzip` command reports a failing exit status, then its stderr
/// is returned as an error.
///
/// ```no_run
/// use std::{io::Read, process::Command};
///
/// use grep_cli::CommandReader;
///
/// let mut cmd = Command::new("gzip");
/// cmd.arg("-d").arg("-c").arg("/usr/share/man/man1/ls.1.gz");
///
/// let mut rdr = CommandReader::new(&mut cmd)?;
/// let mut contents = vec![];
/// rdr.read_to_end(&mut contents)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct CommandReader {
    child: process::Child,
    stderr: StderrReader,
    /// This is set to true once 'read' returns zero bytes. When this isn't
    /// set and we close the reader, then we anticipate a pipe error when
    /// reaping the child process and silence it.
    eof: bool,
}

impl CommandReader {
    /// Create a new streaming reader for the given command using the default
    /// configuration.
    ///
    /// The caller should set everything that's required on the given command
    /// before building a reader, such as its arguments, environment and
    /// current working directory. Settings such as the stdout and stderr (but
    /// not stdin) pipes will be overridden so that they can be controlled by
    /// the reader.
    ///
    /// If there was a problem spawning the given command, then its error is
    /// returned.
    ///
    /// If the caller requires additional configuration for the reader
    /// returned, then use [`CommandReaderBuilder`].
    pub fn new(
        cmd: &mut process::Command,
    ) -> Result<CommandReader, CommandError> {
        CommandReaderBuilder::new().build(cmd)
    }

    /// Closes the CommandReader, freeing any resources used by its underlying
    /// child process. If the child process exits with a nonzero exit code, the
    /// returned Err value will include its stderr.
    ///
    /// `close` is idempotent, meaning it can be safely called multiple times.
    /// The first call closes the CommandReader and any subsequent calls do
    /// nothing.
    ///
    /// This method should be called after partially reading a file to prevent
    /// resource leakage. However there is no need to call `close` explicitly
    /// if your code always calls `read` to EOF, as `read` takes care of
    /// calling `close` in this case.
    ///
    /// `close` is also called in `drop` as a last line of defense against
    /// resource leakage. Any error from the child process is then printed as a
    /// warning to stderr. This can be avoided by explicitly calling `close`
    /// before the CommandReader is dropped.
    pub fn close(&mut self) -> io::Result<()> {
        // Dropping stdout closes the underlying file descriptor, which should
        // cause a well-behaved child process to exit. If child.stdout is None
        // we assume that close() has already been called and do nothing.
        let stdout = match self.child.stdout.take() {
            None => return Ok(()),
            Some(stdout) => stdout,
        };
        drop(stdout);
        if self.child.wait()?.success() {
            Ok(())
        } else {
            let err = self.stderr.read_to_end();
            // In the specific case where we haven't consumed the full data
            // from the child process, then closing stdout above results in
            // a pipe signal being thrown in most cases. But I don't think
            // there is any reliable and portable way of detecting it. Instead,
            // if we know we haven't hit EOF (so we anticipate a broken pipe
            // error) and if stderr otherwise doesn't have anything on it, then
            // we assume total success.
            if !self.eof && err.is_empty() {
                return Ok(());
            }
            Err(io::Error::from(err))
        }
    }
}

impl Drop for CommandReader {
    fn drop(&mut self) {
        if let Err(error) = self.close() {
            log::warn!("{}", error);
        }
    }
}

impl io::Read for CommandReader {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let stdout = match self.child.stdout {
            None => return Ok(0),
            Some(ref mut stdout) => stdout,
        };
        let nread = stdout.read(buf)?;
        if nread == 0 {
            self.eof = true;
            self.close().map(|_| 0)
        } else {
            Ok(nread)
        }
    }
}

/// A reader that encapsulates the asynchronous or synchronous reading of
/// stderr.
#[derive(Debug)]
enum StderrReader {
    Async(Option<std::thread::JoinHandle<CommandError>>),
    Sync(process::ChildStderr),
}

impl StderrReader {
    /// Create a reader for stderr that reads contents asynchronously.
    fn r#async(mut stderr: process::ChildStderr) -> StderrReader {
        let handle =
            std::thread::spawn(move || stderr_to_command_error(&mut stderr));
        StderrReader::Async(Some(handle))
    }

    /// Create a reader for stderr that reads contents synchronously.
    fn sync(stderr: process::ChildStderr) -> StderrReader {
        StderrReader::Sync(stderr)
    }

    /// Consumes all of stderr on to the heap and returns it as an error.
    ///
    /// If there was a problem reading stderr itself, then this returns an I/O
    /// command error.
    fn read_to_end(&mut self) -> CommandError {
        match *self {
            StderrReader::Async(ref mut handle) => {
                let handle = handle
                    .take()
                    .expect("read_to_end cannot be called more than once");
                handle.join().expect("stderr reading thread does not panic")
            }
            StderrReader::Sync(ref mut stderr) => {
                stderr_to_command_error(stderr)
            }
        }
    }
}

fn stderr_to_command_error(stderr: &mut process::ChildStderr) -> CommandError {
    let mut bytes = vec![];
    match stderr.read_to_end(&mut bytes) {
        Ok(_) => CommandError::stderr(bytes),
        Err(err) => CommandError::io(err),
    }
}


// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.

// Simple test for a fuzzer. The fuzzer must find the string "Hi!".
#include <assert.h>
#include <cstdint>
#include <cstdlib>
#include <cstddef>
#include <iostream>

static volatile int Sink;

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  assert(Data);
  if (Size > 0 && Data[0] == 'H') {
    Sink = 1;
    if (Size > 1 && Data[1] == 'i') {
      Sink = 2;
      if (Size > 2 && Data[2] == '!') {
        std::cout << "BINGO; Found the target, exiting\n";
        exit(0);
      }
    }
  }
  return 0;
}


import path from 'node:path'
import fs from 'node:fs'
import { inspect } from 'node:util'
import { performance } from 'node:perf_hooks'
import { cac } from 'cac'
import colors from 'picocolors'
import { VERSION } from './constants'
import { createBuilder } from './build'
import type { BuildEnvironmentOptions } from './build'
import type { ServerOptions } from './server'
import type { CLIShortcut } from './shortcuts'
import type { LogLevel } from './logger'
import { createLogger } from './logger'
import type { InlineConfig } from './config'

function checkNodeVersion(nodeVersion: string): boolean {
  const currentVersion = nodeVersion.split('.')
  const major = parseInt(currentVersion[0], 10)
  const minor = parseInt(currentVersion[1], 10)
  const isSupported =
    (major === 20 && minor >= 19) || (major === 22 && minor >= 12) || major > 22
  return isSupported
}

if (!checkNodeVersion(process.versions.node)) {
  // eslint-disable-next-line no-console
  console.warn(
    colors.yellow(
      `You are using Node.js ${process.versions.node}. ` +
        `Vite requires Node.js version 20.19+ or 22.12+. ` +
        `Please upgrade your Node.js version.`,
    ),
  )
}

const cli = cac('vite')

// global options
interface GlobalCLIOptions {
  '--'?: string[]
  c?: boolean | string
  config?: string
  base?: string
  l?: LogLevel
  logLevel?: LogLevel
  clearScreen?: boolean
  configLoader?: 'bundle' | 'runner' | 'native'
  d?: boolean | string
  debug?: boolean | string
  f?: string
  filter?: string
  m?: string
  mode?: string
  force?: boolean
  w?: boolean
}

interface ExperimentalDevOptions {
  experimentalBundle?: boolean
}

interface BuilderCLIOptions {
  app?: boolean
}

let profileSession = global.__vite_profile_session
let profileCount = 0

export const stopProfiler = (
  log: (message: string) => void,
): void | Promise<void> => {
  if (!profileSession) return
  return new Promise((res, rej) => {
    profileSession!.post('Profiler.stop', (err, { profile }) => {
      // Write profile to disk, upload, etc.
      if (!err) {
        const outPath = path.resolve(
          `./vite-profile-${profileCount++}.cpuprofile`,
        )
        fs.writeFileSync(outPath, JSON.stringify(profile))
        log(
          colors.yellow(
            `CPU profile written to ${colors.white(colors.dim(outPath))}`,
          ),
        )
        profileSession = undefined
        res()
      } else {
        rej(err)
      }
    })
  })
}

const filterDuplicateOptions = <T extends object>(options: T) => {
  for (const [key, value] of Object.entries(options)) {
    if (Array.isArray(value)) {
      options[key as keyof T] = value[value.length - 1]
    }
  }
}
/**
 * removing global flags before passing as command specific sub-configs
 */
function cleanGlobalCLIOptions<Options extends GlobalCLIOptions>(
  options: Options,
): Omit<Options, keyof GlobalCLIOptions> {
  const ret = { ...options }
  delete ret['--']
  delete ret.c
  delete ret.config
  delete ret.base
  delete ret.l
  delete ret.logLevel
  delete ret.clearScreen
  delete ret.configLoader
  delete ret.d
  delete ret.debug
  delete ret.f
  delete ret.filter
  delete ret.m
  delete ret.mode
  delete ret.force
  delete ret.w

  // convert the sourcemap option to a boolean if necessary
  if ('sourcemap' in ret) {
    const sourcemap = ret.sourcemap as `${boolean}` | 'inline' | 'hidden'
    ret.sourcemap =
      sourcemap === 'true'
        ? true
        : sourcemap === 'false'
          ? false
          : ret.sourcemap
  }
  if ('watch' in ret) {
    const watch = ret.watch
    ret.watch = watch ? {} : undefined
  }

  return ret
}

/**
 * removing builder flags before passing as command specific sub-configs
 */
function cleanBuilderCLIOptions<Options extends BuilderCLIOptions>(
  options: Options,
): Omit<Options, keyof BuilderCLIOptions> {
  const ret = { ...options }
  delete ret.app
  return ret
}

/**
 * host may be a number (like 0), should convert to string
 */
const convertHost = (v: any) => {
  if (typeof v === 'number') {
    return String(v)
  }
  return v
}

/**
 * base may be a number (like 0), should convert to empty string
 */
const convertBase = (v: any) => {
  if (v === 0) {
    return ''
  }
  return v
}

cli
  .option('-c, --config <file>', `[string] use specified config file`)
  .option('--base <path>', `[string] public base path (default: /)`, {
    type: [convertBase],
  })
  .option('-l, --logLevel <level>', `[string] info | warn | error | silent`)
  .option('--clearScreen', `[boolean] allow/disable clear screen when logging`)
  .option(
    '--configLoader <loader>',
    `[string] use 'bundle' to bundle the config with Rolldown, or 'runner' (experimental) to process it on the fly, or 'native' (experimental) to load using the native runtime (default: bundle)`,
  )
  .option('-d, --debug [feat]', `[string | boolean] show debug logs`)
  .option('-f, --filter <filter>', `[string] filter debug logs`)
  .option('-m, --mode <mode>', `[string] set env mode`)

// dev
cli
  .command('[root]', 'start dev server') // default command
  .alias('serve') // the command is called 'serve' in Vite's API
  .alias('dev') // alias to align with the script name
  .option('--host [host]', `[string] specify hostname`, { type: [convertHost] })
  .option('--port <port>', `[number] specify port`)
  .option('--open [path]', `[boolean | string] open browser on startup`)
  .option('--cors', `[boolean] enable CORS`)
  .option('--strictPort', `[boolean] exit if specified port is already in use`)
  .option(
    '--force',
    `[boolean] force the optimizer to ignore the cache and re-bundle`,
  )
  .option(
    '--experimentalBundle',
    `[boolean] use experimental full bundle mode (this is highly experimental)`,
  )
  .action(
    async (
      root: string,
      options: ServerOptions & ExperimentalDevOptions & GlobalCLIOptions,
    ) => {
      filterDuplicateOptions(options)
      // output structure is preserved even after bundling so require()
      // is ok here
      const { createServer } = await import('./server')
      try {
        const server = await createServer({
          root,
          base: options.base,
          mode: options.mode,
          configFile: options.config,
          configLoader: options.configLoader,
          logLevel: options.logLevel,
          clearScreen: options.clearScreen,
          server: cleanGlobalCLIOptions(options),
          forceOptimizeDeps: options.force,
          experimental: {
            bundledDev: options.experimentalBundle,
          },
        })

        if (!server.httpServer) {
          throw new Error('HTTP server not available')
        }

        await server.listen()

        const info = server.config.logger.info

        const modeString =
          options.mode && options.mode !== 'development'
            ? `  ${colors.bgGreen(` ${colors.bold(options.mode)} `)}`
            : ''
        const viteStartTime = global.__vite_start_time ?? false
        const startupDurationString = viteStartTime
          ? colors.dim(
              `ready in ${colors.reset(
                colors.bold(Math.ceil(performance.now() - viteStartTime)),
              )} ms`,
            )
          : ''
        const hasExistingLogs =
          process.stdout.bytesWritten > 0 || process.stderr.bytesWritten > 0

        info(
          `\n  ${colors.green(
            `${colors.bold('VITE')} v${VERSION}`,
          )}${modeString}  ${startupDurationString}\n`,
          {
            clear: !hasExistingLogs,
          },
        )

        server.printUrls()
        const customShortcuts: CLIShortcut<typeof server>[] = []
        if (profileSession) {
          customShortcuts.push({
            key: 'p',
            description: 'start/stop the profiler',
            async action(server) {
              if (profileSession) {
                await stopProfiler(server.config.logger.info)
              } else {
                const inspector = await import('node:inspector').then(
                  (r) => r.default,
                )
                await new Promise<void>((res) => {
                  profileSession = new inspector.Session()
                  profileSession.connect()
                  profileSession.post('Profiler.enable', () => {
                    profileSession!.post('Profiler.start', () => {
                      server.config.logger.info('Profiler started')
                      res()
                    })
                  })
                })
              }
            },
          })
        }
        server.bindCLIShortcuts({ print: true, customShortcuts })
      } catch (e) {
        const logger = createLogger(options.logLevel)
        logger.error(
          colors.red(`error when starting dev server:\n${inspect(e)}`),
          {
            error: e,
          },
        )
        await stopProfiler(logger.info)
        process.exit(1)
      }
    },
  )

// build
cli
  .command('build [root]', 'build for production')
  .option(
    '--target <target>',
    `[string] transpile target (default: 'baseline-widely-available')`,
  )
  .option('--outDir <dir>', `[string] output directory (default: dist)`)
  .option(
    '--assetsDir <dir>',
    `[string] directory under outDir to place assets in (default: assets)`,
  )
  .option(
    '--assetsInlineLimit <number>',
    `[number] static asset base64 inline threshold in bytes (default: 4096)`,
  )
  .option(
    '--ssr [entry]',
    `[string] build specified entry for server-side rendering`,
  )
  .option(
    '--sourcemap [output]',
    `[boolean | "inline" | "hidden"] output source maps for build (default: false)`,
  )
  .option(
    '--minify [minifier]',
    `[boolean | "oxc" | "terser" | "esbuild"] enable/disable minification, ` +
      `or specify minifier to use (default: oxc)`,
  )
  .option('--manifest [name]', `[boolean | string] emit build manifest json`)
  .option('--ssrManifest [name]', `[boolean | string] emit ssr manifest json`)
  .option(
    '--emptyOutDir',
    `[boolean] force empty outDir when it's outside of root`,
  )
  .option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
  .option('--app', `[boolean] same as \`builder: {}\``)
  .action(
    async (
      root: string,
      options: BuildEnvironmentOptions & BuilderCLIOptions & GlobalCLIOptions,
    ) => {
      filterDuplicateOptions(options)

      const buildOptions: BuildEnvironmentOptions = cleanGlobalCLIOptions(
        cleanBuilderCLIOptions(options),
      )

      try {
        const inlineConfig: InlineConfig = {
          root,
          base: options.base,
          mode: options.mode,
          configFile: options.config,
          configLoader: options.configLoader,
          logLevel: options.logLevel,
          clearScreen: options.clearScreen,
          build: buildOptions,
          ...(options.app ? { builder: {} } : {}),
        }
        const builder = await createBuilder(inlineConfig, null)
        await builder.buildApp()
        await builder.runDevTools()
      } catch (e) {
        createLogger(options.logLevel).error(
          colors.red(`error during build:\n${inspect(e)}`),
          { error: e },
        )
        process.exit(1)
      } finally {
        await stopProfiler((message) =>
          createLogger(options.logLevel).info(message),
        )
      }
    },
  )

// optimize
cli
  .command(
    'optimize [root]',
    'pre-bundle dependencies (deprecated, the pre-bundle process runs automatically and does not need to be called)',
  )
  .option(
    '--force',
    `[boolean] force the optimizer to ignore the cache and re-bundle`,
  )
  .action(
    async (root: string, options: { force?: boolean } & GlobalCLIOptions) => {
      filterDuplicateOptions(options)
      const { resolveConfig } = await import('./config')
      const { optimizeDeps } = await import('./optimizer')
      try {
        const config = await resolveConfig(
          {
            root,
            base: options.base,
            configFile: options.config,
            configLoader: options.configLoader,
            logLevel: options.logLevel,
            mode: options.mode,
          },
          'serve',
        )
        await optimizeDeps(config, options.force, true)
      } catch (e) {
        createLogger(options.logLevel).error(
          colors.red(`error when optimizing deps:\n${inspect(e)}`),
          { error: e },
        )
        process.exit(1)
      }
    },
  )

// preview
cli
  .command('preview [root]', 'locally preview production build')
  .option('--host [host]', `[string] specify hostname`, { type: [convertHost] })
  .option('--port <port>', `[number] specify port`)
  .option('--strictPort', `[boolean] exit if specified port is already in use`)
  .option('--open [path]', `[boolean | string] open browser on startup`)
  .option('--outDir <dir>', `[string] output directory (default: dist)`)
  .action(
    async (
      root: string,
      options: {
        host?: string | boolean
        port?: number
        open?: boolean | string
        strictPort?: boolean
        outDir?: string
      } & GlobalCLIOptions,
    ) => {
      filterDuplicateOptions(options)
      const { preview } = await import('./preview')
      try {
        const server = await preview({
          root,
          base: options.base,
          configFile: options.config,
          configLoader: options.configLoader,
          logLevel: options.logLevel,
          mode: options.mode,
          build: {
            outDir: options.outDir,
          },
          preview: {
            port: options.port,
            strictPort: options.strictPort,
            host: options.host,
            open: options.open,
          },
        })
        server.printUrls()
        server.bindCLIShortcuts({ print: true })
      } catch (e) {
        createLogger(options.logLevel).error(
          colors.red(`error when starting preview server:\n${inspect(e)}`),
          { error: e },
        )
        process.exit(1)
      } finally {
        await stopProfiler((message) =>
          createLogger(options.logLevel).info(message),
        )
      }
    },
  )

cli.help()
cli.version(VERSION)

cli.parse()


#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
{
    // create JSON values
    json j_null;
    json j_boolean = true;
    json j_number_integer = 17;
    json j_number_float = 23.42;
    json j_object = {{"one", 1}, {"two", 2}};
    json j_object_empty(json::value_t::object);
    json j_array = {1, 2, 4, 8, 16};
    json j_array_empty(json::value_t::array);
    json j_string = "Hello, world";

    // call front()
    //std::cout << j_null.front() << '\n';          // would throw
    std::cout << j_boolean.front() << '\n';
    std::cout << j_number_integer.front() << '\n';
    std::cout << j_number_float.front() << '\n';
    std::cout << j_object.front() << '\n';
    //std::cout << j_object_empty.front() << '\n';  // undefined behavior
    std::cout << j_array.front() << '\n';
    //std::cout << j_array_empty.front() << '\n';   // undefined behavior
    std::cout << j_string.front() << '\n';
}


import { describe, it } from 'vitest'
import type { ModuleFormat, RolldownOutput } from 'rolldown'
import { build } from '../../../build'
import { modulePreloadPolyfillId } from '../../../plugins/modulePreloadPolyfill'

const buildProject = ({ format = 'es' as ModuleFormat } = {}) =>
  build({
    logLevel: 'silent',
    build: {
      write: false,
      rolldownOptions: {
        input: 'main.js',
        output: {
          format,
        },
        treeshake: {
          moduleSideEffects: false,
        },
      },
      minify: false,
    },
    plugins: [
      {
        name: 'test',
        resolveId(id) {
          if (id === 'main.js') {
            return `\0${id}`
          }
        },
        load(id) {
          if (id === '\0main.js') {
            return `import '${modulePreloadPolyfillId}'`
          }
        },
      },
    ],
  }) as Promise<RolldownOutput>

describe('load', () => {
  it('loads modulepreload polyfill', async ({ expect }) => {
    const { output } = await buildProject()
    expect(output).toHaveLength(1)
    expect(output[0].code).toMatchSnapshot()
  })

  it("doesn't load modulepreload polyfill when format is cjs", async ({
    expect,
  }) => {
    const { output } = await buildProject({ format: 'cjs' })
    expect(output).toHaveLength(1)
    expect(output[0].code).toMatchSnapshot()
  })
})


// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.

// Test that libFuzzer itself does not read out of bounds.
#include <assert.h>
#include <cstdint>
#include <cstring>
#include <cstdlib>
#include <cstddef>
#include <iostream>

static volatile int Sink;

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  if (Size < 5) return 0;
  const char *Ch = reinterpret_cast<const char *>(Data);
  if (Ch[Size - 3] == 'a')
    Sink = strncmp(Ch + Size - 3, "abcdefg", 6);
  return 0;
}


import { onMounted, ref } from 'vue'
import type { Sponsor, SponsorTier } from '@voidzero-dev/vitepress-theme'

interface Sponsors {
  main: Sponsor[]
  partnership: Sponsor[]
  platinum: Sponsor[]
  gold: Sponsor[]
}

// shared data across instances so we load only once.
const data = ref<SponsorTier[]>()

export function useSponsor() {
  onMounted(async () => {
    if (data.value) return

    const result = await fetch('https://sponsors.vite.dev/sponsors.json')
    const sponsors: Sponsors = await result.json()

    data.value = [
      {
        tier: 'Brought to you by',
        size: 'big',
        items: sponsors.main,
      },
      {
        tier: 'In partnership with',
        size: 'big',
        items: sponsors.partnership,
      },
      {
        tier: 'Platinum Sponsors',
        size: 'big',
        items: sponsors.platinum,
      },
      {
        tier: 'Gold Sponsors',
        size: 'medium',
        items: sponsors.gold,
      },
    ]
  })

  return data
}


#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
{
    // tagged byte string
    std::vector<std::uint8_t> vec = {{0xd8, 0x42, 0x44, 0xcA, 0xfe, 0xba, 0xbe}};

    // cbor_tag_handler_t::error throws
    try
    {
        auto b_throw_on_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::error);
    }
    catch (const json::parse_error& e)
    {
        std::cout << e.what() << std::endl;
    }

    // cbor_tag_handler_t::ignore ignores the tag
    auto b_ignore_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::ignore);
    std::cout << b_ignore_tag << std::endl;

    // cbor_tag_handler_t::store stores the tag as binary subtype
    auto b_store_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::store);
    std::cout << b_store_tag << std::endl;
}


import fs from 'node:fs'
import path from 'node:path'
import { defineConfig } from 'vite'

const dirname = import.meta.dirname

export default defineConfig({
  plugins: [
    {
      name: 'copy',
      writeBundle() {
        fs.mkdirSync(path.resolve(dirname, 'dist/views'))
        fs.mkdirSync(path.resolve(dirname, 'dist/files'))
        fs.copyFileSync(
          path.resolve(dirname, 'views/qux.js'),
          path.resolve(dirname, 'dist/views/qux.js'),
        )
        fs.copyFileSync(
          path.resolve(dirname, 'files/mxd.js'),
          path.resolve(dirname, 'dist/files/mxd.js'),
        )
        fs.copyFileSync(
          path.resolve(dirname, 'files/mxd.json'),
          path.resolve(dirname, 'dist/files/mxd.json'),
        )
      },
    },
  ],
  resolve: {
    alias: {
      '@': path.resolve(dirname, 'alias'),
    },
  },
  build: {
    sourcemap: true,
  },
})


# <small>nlohmann::json_pointer::</small>string_t
```cpp
using string_t = RefStringType;
```

The string type used for the reference tokens making up the JSON pointer.

See [`basic_json::string_t`](../basic_json/string_t.md) for more information.

## Examples

??? example

    The example shows the type `string_t` and its relation to `basic_json::string_t`.

    ```cpp
    --8<-- "examples/json_pointer__string_t.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/json_pointer__string_t.output"
    ```

## Version history

- Added in version 3.11.0.


#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

namespace ns
{

enum class Color
{
    red,
    green,
    blue,
    unknown // not mapped in JSON_SERIALIZE_ENUM_STRICT
};

NLOHMANN_JSON_SERIALIZE_ENUM_STRICT(Color,
{
    {Color::red, "red"},
    {Color::green, "green"},
    {Color::blue, "blue"}
})

} // namespace ns

int main()
{
    // invalid serialization
    try
    {
        // ns::color::unknown was not mapped in macro
        json invalid_serialization = ns::Color::unknown;
    }
    catch (const json::exception e)
    {
        std::cout << "deserialization failed: " << e.what() << std::endl;
    }

    // invalid deserialization
    try
    {
        // what does not map to an enum
        json invalid_deserialization("what");
        ns::Color color = invalid_deserialization.get<ns::Color>();
    }
    catch (const json::exception e)
    {
        std::cout << "deserialization failed: " << e.what() << std::endl;
    }

    return 0;
}


// prettier-ignore
function text(el, text) {
  document.querySelector(el).textContent = text
}

let classicWorker = new Worker(
  new URL('../classic-worker.js', import.meta.url) /* , */,
  // test comment
)

// just test for case: ') ... ,' mean no worker options params
classicWorker = new Worker(new URL('../classic-worker.js', import.meta.url))

classicWorker.addEventListener('message', ({ data }) => {
  switch (data.message) {
    case 'ping': {
      text('.classic-worker', data.result)
      break
    }
    case 'test-import': {
      text('.classic-worker-import', data.result)
      break
    }
  }
})
classicWorker.postMessage('ping')
classicWorker.postMessage('test-import')

// prettier-ignore
// test trailing comma
const classicSharedWorker = new SharedWorker(
  new URL('../classic-shared-worker.js', import.meta.url),
  {
    type: 'classic'
  }, // test comment
)
classicSharedWorker.port.addEventListener('message', (ev) => {
  text('.classic-shared-worker', JSON.stringify(ev.data))
})
classicSharedWorker.port.start()


import { basename, resolve } from 'node:path'
import { stripVTControlCharacters } from 'node:util'
import fsp from 'node:fs/promises'
import colors from 'picocolors'
import { afterEach, describe, expect, assert, test, vi } from 'vitest'
import type {
  LogLevel,
  OutputChunk,
  OutputOptions,
  RolldownOptions,
  RolldownOutput,
  RollupLog,
} from 'rolldown'
import type { LibraryFormats, LibraryOptions } from '../build'
import {
  ChunkMetadataMap,
  build,
  createBuilder,
  onRollupLog,
  resolveBuildOutputs,
  resolveLibFilename,
  resolveRolldownOptions,
} from '../build'
import type { Logger } from '../logger'
import { createLogger } from '../logger'
import { BuildEnvironment, resolveConfig } from '..'

const dirname = import.meta.dirname

type FormatsToFileNames = [LibraryFormats, string][]

describe('build', () => {
  test('file hash should change when css changes for dynamic entries', async () => {
    const buildProject = async (cssColor: string) => {
      return (await build({
        root: resolve(dirname, 'packages/build-project'),
        logLevel: 'silent',
        build: {
          write: false,
        },
        plugins: [
          {
            name: 'test',
            resolveId(id) {
              if (
                id === 'entry.js' ||
                id === 'subentry.js' ||
                id === 'foo.css'
              ) {
                return '\0' + id
              }
            },
            load(id) {
              if (id === '\0entry.js') {
                return `window.addEventListener('click', () => { import('subentry.js') });`
              }
              if (id === '\0subentry.js') {
                return `import 'foo.css'`
              }
              if (id === '\0foo.css') {
                return `.foo { color: ${cssColor} }`
              }
            },
          },
        ],
      })) as RolldownOutput
    }
    const result = await Promise.all([
      buildProject('red'),
      buildProject('blue'),
    ])
    expect(getOutputHashChanges(result[0], result[1])).toMatchInlineSnapshot(`
      {
        "changed": [
          "index",
          "_subentry.css",
        ],
        "unchanged": [
          "undefined",
        ],
      }
    `)
    assertOutputHashContentChange(result[0], result[1])
  })

  test('top-level input is used as the default build entry', async () => {
    const result = (await build({
      root: resolve(dirname, 'packages/build-project'),
      logLevel: 'silent',
      input: 'top-level-entry.js',
      build: {
        write: false,
      },
      plugins: [
        {
          name: 'test',
          resolveId(id) {
            if (id.replace(/\\/g, '/').endsWith('top-level-entry.js')) {
              return '\0top-level-entry.js'
            }
          },
          load(id) {
            if (id === '\0top-level-entry.js') {
              return `console.log('from-top-level-input')`
            }
          },
        },
      ],
    })) as RolldownOutput
    const chunk = result.output.find((o) => o.type === 'chunk')
    expect(chunk?.fileName).toContain('top-level-entry')
    expect(chunk?.code).toContain('from-top-level-input')
  })

  test('top-level input can be a virtual module for build', async () => {
    const input = 'virtual:entry'
    const resolvedInput = `\0${input}`
    const result = (await build({
      root: resolve(dirname, 'packages/build-project'),
      logLevel: 'silent',
      input,
      build: {
        write: false,
      },
      plugins: [
        {
          name: 'virtual-entry',
          resolveId(id) {
            if (id === input) {
              return resolvedInput
            }
          },
          load(id) {
            if (id === resolvedInput) {
              return `console.log('from-virtual-top-level-input')`
            }
          },
        },
      ],
    })) as RolldownOutput
    const chunk = result.output.find((o) => o.type === 'chunk')
    expect(chunk?.code).toContain('from-virtual-top-level-input')
  })

  test('file hash should change when pure css chunk changes', async () => {
    const buildProject = async (cssColor: string) => {
      return (await build({
        root: resolve(dirname, 'packages/build-project'),
        logLevel: 'silent',
        build: {
          write: false,
        },
        plugins: [
          {
            name: 'test',
            resolveId(id) {
              if (
                id === 'entry.js' ||
                id === 'foo.js' ||
                id === 'bar.js' ||
                id === 'baz.js' ||
                id === 'foo.css' ||
                id === 'bar.css' ||
                id === 'baz.css'
              ) {
                return '\0' + id
              }
            },
            load(id) {
              if (id === '\0entry.js') {
                return `
                  window.addEventListener('click', () => { import('foo.js') });
                  window.addEventListener('click', () => { import('bar.js') });`
              }
              if (id === '\0foo.js') return `import 'foo.css'; import 'baz.js'`
              if (id === '\0bar.js') return `import 'bar.css'; import 'baz.js'`
              if (id === '\0baz.js') return `import 'baz.css'`
              if (id === '\0foo.css') return `.foo { color: red }`
              if (id === '\0bar.css') return `.foo { color: green }`
              if (id === '\0baz.css') return `.foo { color: ${cssColor} }`
            },
          },
        ],
      })) as RolldownOutput
    }
    const result = await Promise.all([
      buildProject('yellow'),
      buildProject('blue'),
    ])
    expect(getOutputHashChanges(result[0], result[1])).toMatchInlineSnapshot(`
      {
        "changed": [
          "index",
          "_bar",
          "_foo",
          "_baz.css",
        ],
        "unchanged": [
          "_bar.css",
          "_foo.css",
          "undefined",
        ],
      }
    `)
    assertOutputHashContentChange(result[0], result[1])
  })

  test('css entries with the same basename should not cross-link manifest assets', async () => {
    const root = resolve(dirname, 'fixtures/css-entry-same-basename')
    const result = (await build({
      root,
      logLevel: 'silent',
      build: {
        write: false,
        manifest: true,
        assetsInlineLimit: 0,
        rolldownOptions: {
          input: [resolve(root, 'a/index.css'), resolve(root, 'b/index.css')],
        },
      },
    })) as RolldownOutput

    const manifest = JSON.parse(
      (result.output.find((o) => o.fileName === '.vite/manifest.json') as any)
        .source,
    )
    expect(manifest['a/index.css']).toMatchObject({
      isEntry: true,
    })
    expect(manifest['b/index.css']).toMatchObject({
      isEntry: true,
    })
  })

  test.for([
    [true, true],
    [true, false],
    [false, true],
    [false, false],
    ['auto', true],
    ['auto', false],
  ] as const)(
    'large json object files should have tree-shaking (json.stringify: %s, json.namedExports: %s)',
    async ([stringify, namedExports]) => {
      const esBundle = (await build({
        mode: 'development',
        root: resolve(dirname, 'packages/build-project'),
        logLevel: 'silent',
        json: { stringify, namedExports },
        build: {
          minify: false,
          modulePreload: { polyfill: false },
          write: false,
        },
        plugins: [
          {
            name: 'test',
            resolveId(id) {
              if (
                id === 'entry.js' ||
                id === 'object.json' ||
                id === 'array.json'
              ) {
                return '\0' + id
              }
            },
            load(id) {
              if (id === '\0entry.js') {
                return `
                  import object from 'object.json';
                  import array from 'array.json';
                  console.log();
                `
              }
              if (id === '\0object.json') {
                return `
                  {"value": {"${stringify}_${namedExports}":"JSON_OBJ${'_'.repeat(10_000)}"}}
                `
              }
              if (id === '\0array.json') {
                return `
                  ["${stringify}_${namedExports}","JSON_ARR${'_'.repeat(10_000)}"]
                `
              }
            },
          },
        ],
      })) as RolldownOutput

      const foo = esBundle.output.find(
        (chunk) => chunk.type === 'chunk' && chunk.isEntry,
      ) as OutputChunk
      expect(foo.code).not.contains('JSON_ARR')
      expect(foo.code).not.contains('JSON_OBJ')
    },
  )

  test('external modules should not be hoisted in library build', async () => {
    const [esBundle] = (await build({
      logLevel: 'silent',
      build: {
        lib: {
          entry: ['foo.js', 'bar.js'],
          formats: ['es'],
        },
        rolldownOptions: {
          external: 'external',
        },
        write: false,
      },
      plugins: [
        {
          name: 'test',
          resolveId(id) {
            const name = basename(id)
            if (name === 'foo.js' || name === 'bar.js') {
              return name
            }
          },
          load(id) {
            if (id === 'foo.js') {
              return `
                  import bar from 'bar.js'
                  export default bar()
                `
            }
            if (id === 'bar.js') {
              return `
                  import ext from 'external';
                  export default ext();`
            }
          },
        },
      ],
    })) as RolldownOutput[]

    const foo = esBundle.output.find(
      (chunk) => chunk.fileName === 'foo.js',
    ) as OutputChunk
    expect(foo.code).not.contains('import "external"')
  })
})

const baseLibOptions: LibraryOptions = {
  fileName: 'my-lib',
  entry: 'mylib.js',
}

describe('resolveBuildOutputs', () => {
  test('resolves outputs correctly', () => {
    const logger = createLogger()
    const libOptions: LibraryOptions = { ...baseLibOptions }
    const outputs: OutputOptions[] = [{ format: 'es' }]
    const resolvedOutputs = resolveBuildOutputs(outputs, libOptions, logger)

    expect(resolvedOutputs).toEqual([
      {
        format: 'es',
      },
    ])
  })

  test('resolves outputs from lib options', () => {
    const logger = createLogger()
    const libOptions: LibraryOptions = { ...baseLibOptions, name: 'lib' }
    const resolvedOutputs = resolveBuildOutputs(void 0, libOptions, logger)

    expect(resolvedOutputs).toEqual([
      {
        format: 'es',
      },
      {
        format: 'umd',
      },
    ])
  })

  test('does not change outputs when lib options are missing', () => {
    const logger = createLogger()
    const outputs: OutputOptions[] = [{ format: 'es' }]
    const resolvedOutputs = resolveBuildOutputs(outputs, false, logger)

    expect(resolvedOutputs).toEqual(outputs)
  })

  test('logs a warning when outputs is an array and formats are specified', () => {
    const logger = createLogger()
    const loggerSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})
    const libOptions: LibraryOptions = {
      ...baseLibOptions,
      formats: ['iife'],
    }
    const outputs: OutputOptions[] = [{ format: 'es' }]

    resolveBuildOutputs(outputs, libOptions, logger)

    expect(loggerSpy).toHaveBeenCalledWith(
      expect.stringContaining('"build.lib.formats" will be ignored because'),
    )
  })

  test('throws an error when lib.name is missing on iife format', () => {
    const logger = createLogger()
    const libOptions: LibraryOptions = {
      ...baseLibOptions,
      formats: ['iife'],
    }
    const resolveBuild = () => resolveBuildOutputs(void 0, libOptions, logger)

    expect(resolveBuild).toThrowError(/Option "build\.lib\.name" is required/)
  })

  test('throws an error when lib.name is missing on umd format', () => {
    const logger = createLogger()
    const libOptions: LibraryOptions = { ...baseLibOptions, formats: ['umd'] }
    const resolveBuild = () => resolveBuildOutputs(void 0, libOptions, logger)

    expect(resolveBuild).toThrowError(/Option "build\.lib\.name" is required/)
  })

  test('throws an error when output.name is missing on iife format', () => {
    const logger = createLogger()
    const libOptions: LibraryOptions = { ...baseLibOptions }
    const outputs: OutputOptions[] = [{ format: 'iife' }]
    const resolveBuild = () => resolveBuildOutputs(outputs, libOptions, logger)

    expect(resolveBuild).toThrowError(
      /Entries in "build\.rolldownOptions\.output" must specify "name"/,
    )
  })

  test('throws an error when output.name is missing on umd format', () => {
    const logger = createLogger()
    const libOptions: LibraryOptions = { ...baseLibOptions }
    const outputs: OutputOptions[] = [{ format: 'umd' }]
    const resolveBuild = () => resolveBuildOutputs(outputs, libOptions, logger)

    expect(resolveBuild).toThrowError(
      /Entries in "build\.rolldownOptions\.output" must specify "name"/,
    )
  })

  describe('input resolution in resolveRolldownOptions', () => {
    const buildProjectRoot = resolve(dirname, 'packages/build-project')

    test('build.rolldownOptions.input takes precedence over top-level input', async () => {
      const builder = await createBuilder({
        root: buildProjectRoot,
        logLevel: 'silent',
        input: 'top-level-entry.js',
        build: {
          rolldownOptions: { input: 'explicit-entry.js' },
        },
      })
      const options = resolveRolldownOptions(
        builder.environments.client,
        new ChunkMetadataMap(),
      )
      expect(options.input).toBe('explicit-entry.js')
    })

    test('falls back to index.html when no input is set', async () => {
      const builder = await createBuilder({
        root: buildProjectRoot,
        logLevel: 'silent',
      })
      const options = resolveRolldownOptions(
        builder.environments.client,
        new ChunkMetadataMap(),
      )
      expect(options.input).toBe(resolve(buildProjectRoot, 'index.html'))
    })

    test('build.ssr string entry takes precedence over input', async () => {
      const builder = await createBuilder({
        root: buildProjectRoot,
        logLevel: 'silent',
        environments: {
          ssr: {
            input: 'env-input.js',
            build: { ssr: 'ssr-entry.js' },
          },
        },
      })
      const options = resolveRolldownOptions(
        builder.environments.ssr,
        new ChunkMetadataMap(),
      )
      expect(options.input).toBe(resolve(buildProjectRoot, 'ssr-entry.js'))
    })

    test('throws when build.lib is set without entry or top-level input', async () => {
      const builder = await createBuilder({
        root: buildProjectRoot,
        logLevel: 'silent',
        build: {
          lib: { name: 'MyLib', formats: ['es'] },
        },
      })
      expect(() =>
        resolveRolldownOptions(
          builder.environments.client,
          new ChunkMetadataMap(),
        ),
      ).toThrow(
        /Either "build\.lib\.entry" or the top-level "input" option is required/,
      )
    })
  })
})

describe('resolveLibFilename', () => {
  test('custom filename function', () => {
    const filename = resolveLibFilename(
      {
        fileName: (format) => `custom-filename-function.${format}.js`,
        entry: 'mylib.js',
      },
      'es',
      'myLib',
      resolve(dirname, 'packages/name'),
    )

    expect(filename).toBe('custom-filename-function.es.js')
  })

  test('custom filename string', () => {
    const filename = resolveLibFilename(
      {
        fileName: 'custom-filename',
        entry: 'mylib.js',
      },
      'es',
      'myLib',
      resolve(dirname, 'packages/name'),
    )

    expect(filename).toBe('custom-filename.mjs')
  })

  test('package name as filename', () => {
    const filename = resolveLibFilename(
      {
        entry: 'mylib.js',
      },
      'es',
      'myLib',
      resolve(dirname, 'packages/name'),
    )

    expect(filename).toBe('mylib.mjs')
  })

  test('custom filename and no package name', () => {
    const filename = resolveLibFilename(
      {
        fileName: 'custom-filename',
        entry: 'mylib.js',
      },
      'es',
      'myLib',
      resolve(dirname, 'packages/noname'),
    )

    expect(filename).toBe('custom-filename.mjs')
  })

  test('missing filename', () => {
    const filename = resolveLibFilename(
      {
        entry: 'mylib.js',
      },
      'es',
      'myLib',
      resolve(dirname, 'packages/noname'),
    )
    expect(filename).toBe('named-testing-package.mjs')
  })

  test('commonjs package extensions', () => {
    const formatsToFilenames: FormatsToFileNames = [
      ['es', 'my-lib.mjs'],
      ['umd', 'my-lib.umd.js'],
      ['cjs', 'my-lib.js'],
      ['iife', 'my-lib.iife.js'],
    ]

    for (const [format, expectedFilename] of formatsToFilenames) {
      const filename = resolveLibFilename(
        baseLibOptions,
        format,
        'myLib',
        resolve(dirname, 'packages/noname'),
      )

      expect(filename).toBe(expectedFilename)
    }
  })

  test('module package extensions', () => {
    const formatsToFilenames: FormatsToFileNames = [
      ['es', 'my-lib.js'],
      ['umd', 'my-lib.umd.cjs'],
      ['cjs', 'my-lib.cjs'],
      ['iife', 'my-lib.iife.js'],
    ]

    for (const [format, expectedFilename] of formatsToFilenames) {
      const filename = resolveLibFilename(
        baseLibOptions,
        format,
        'myLib',
        resolve(dirname, 'packages/module'),
      )

      expect(expectedFilename).toBe(filename)
    }
  })

  test('multiple entries with aliases', () => {
    const libOptions: LibraryOptions = {
      entry: {
        entryA: 'entryA.js',
        entryB: 'entryB.js',
      },
    }

    const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) =>
      resolveLibFilename(
        libOptions,
        'es',
        entryAlias,
        resolve(dirname, 'packages/name'),
      ),
    )

    expect(fileName1).toBe('entryA.mjs')
    expect(fileName2).toBe('entryB.mjs')
  })

  test('multiple entries with aliases: custom filename function', () => {
    const libOptions: LibraryOptions = {
      entry: {
        entryA: 'entryA.js',
        entryB: 'entryB.js',
      },
      fileName: (format, entryAlias) =>
        `custom-filename-function.${entryAlias}.${format}.js`,
    }

    const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) =>
      resolveLibFilename(
        libOptions,
        'es',
        entryAlias,
        resolve(dirname, 'packages/name'),
      ),
    )

    expect(fileName1).toBe('custom-filename-function.entryA.es.js')
    expect(fileName2).toBe('custom-filename-function.entryB.es.js')
  })

  test('multiple entries with aliases: custom filename string', () => {
    const libOptions: LibraryOptions = {
      entry: {
        entryA: 'entryA.js',
        entryB: 'entryB.js',
      },
      fileName: 'custom-filename',
    }

    const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) =>
      resolveLibFilename(
        libOptions,
        'es',
        entryAlias,
        resolve(dirname, 'packages/name'),
      ),
    )

    expect(fileName1).toBe('custom-filename.mjs')
    expect(fileName2).toBe('custom-filename.mjs')
  })

  test('multiple entries as array', () => {
    const libOptions: LibraryOptions = {
      entry: ['entryA.js', 'entryB.js'],
    }

    const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) =>
      resolveLibFilename(
        libOptions,
        'es',
        entryAlias,
        resolve(dirname, 'packages/name'),
      ),
    )

    expect(fileName1).toBe('entryA.mjs')
    expect(fileName2).toBe('entryB.mjs')
  })

  test('multiple entries as array: custom filename function', () => {
    const libOptions: LibraryOptions = {
      entry: ['entryA.js', 'entryB.js'],
      fileName: (format, entryAlias) =>
        `custom-filename-function.${entryAlias}.${format}.js`,
    }

    const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) =>
      resolveLibFilename(
        libOptions,
        'es',
        entryAlias,
        resolve(dirname, 'packages/name'),
      ),
    )

    expect(fileName1).toBe('custom-filename-function.entryA.es.js')
    expect(fileName2).toBe('custom-filename-function.entryB.es.js')
  })

  test('multiple entries as array: custom filename string', () => {
    const libOptions: LibraryOptions = {
      entry: ['entryA.js', 'entryB.js'],
      fileName: 'custom-filename',
    }

    const [fileName1, fileName2] = ['entryA', 'entryB'].map((entryAlias) =>
      resolveLibFilename(
        libOptions,
        'es',
        entryAlias,
        resolve(dirname, 'packages/name'),
      ),
    )

    expect(fileName1).toBe('custom-filename.mjs')
    expect(fileName2).toBe('custom-filename.mjs')
  })
})

describe('resolveBuildOutputs', () => {
  test('default format: one entry', () => {
    const libOptions: LibraryOptions = {
      entry: 'entryA.js',
      name: 'entryA',
    }

    expect(resolveBuildOutputs(undefined, libOptions, {} as Logger)).toEqual([
      { format: 'es' },
      { format: 'umd' },
    ])
    expect(
      resolveBuildOutputs({ name: 'A' }, libOptions, {} as Logger),
    ).toEqual([
      { format: 'es', name: 'A' },
      { format: 'umd', name: 'A' },
    ])
    expect(
      resolveBuildOutputs([{ name: 'A' }], libOptions, {} as Logger),
    ).toEqual([{ name: 'A' }])
  })

  test('default format: multiple entries', () => {
    const libOptions: LibraryOptions = {
      entry: ['entryA.js', 'entryB.js'],
    }

    expect(resolveBuildOutputs(undefined, libOptions, {} as Logger)).toEqual([
      { format: 'es' },
      { format: 'cjs' },
    ])
    expect(
      resolveBuildOutputs({ name: 'A' }, libOptions, {} as Logger),
    ).toEqual([
      { format: 'es', name: 'A' },
      { format: 'cjs', name: 'A' },
    ])
    expect(
      resolveBuildOutputs([{ name: 'A' }], libOptions, {} as Logger),
    ).toEqual([{ name: 'A' }])
  })

  test('umd or iife: should not support multiple entries', () => {
    ;['umd', 'iife'].forEach((format) => {
      expect(() =>
        resolveBuildOutputs(
          undefined,
          {
            entry: ['entryA.js', 'entryB.js'],
            formats: [format as LibraryFormats],
          },
          {} as Logger,
        ),
      ).toThrow(
        `Multiple entry points are not supported when output formats include "umd" or "iife".`,
      )
    })
  })

  test('umd or iife: should define build.lib.name', () => {
    ;['umd', 'iife'].forEach((format) => {
      expect(() =>
        resolveBuildOutputs(
          undefined,
          {
            entry: 'entryA.js',
            formats: [format as LibraryFormats],
          },
          {} as Logger,
        ),
      ).toThrow(
        `Option "build.lib.name" is required when output formats include "umd" or "iife".`,
      )
    })
  })

  test('array outputs: should ignore build.lib.formats', () => {
    const log = { warn: vi.fn() } as unknown as Logger
    expect(
      resolveBuildOutputs(
        [{ name: 'A' }],
        {
          entry: 'entryA.js',
          formats: ['es'],
        },
        log,
      ),
    ).toEqual([{ name: 'A' }])
    expect(log.warn).toHaveBeenLastCalledWith(
      colors.yellow(
        `"build.lib.formats" will be ignored because "build.rolldownOptions.output" is already an array format.`,
      ),
    )
  })

  test('ssrEmitAssets', async () => {
    const result = await build({
      root: resolve(dirname, 'fixtures/emit-assets'),
      logLevel: 'silent',
      build: {
        ssr: true,
        ssrEmitAssets: true,
        rolldownOptions: {
          input: {
            index: '/entry',
          },
        },
      },
    })
    expect(result).toMatchObject({
      output: [
        {
          fileName: 'index.mjs',
        },
        {
          fileName: expect.stringMatching(/assets\/index-[-\w]{8}\.css/),
        },
      ],
    })
  })

  test('emitAssets', async () => {
    const builder = await createBuilder({
      root: resolve(dirname, 'fixtures/emit-assets'),
      logLevel: 'warn',
      environments: {
        ssr: {
          build: {
            ssr: true,
            emitAssets: true,
            rolldownOptions: {
              input: {
                index: '/entry',
              },
            },
          },
        },
      },
    })
    const result = await builder.build(builder.environments.ssr)
    expect(result).toMatchObject({
      output: [
        {
          fileName: 'index.mjs',
        },
        {
          fileName: expect.stringMatching(/assets\/index-[-\w]{8}\.css/),
        },
      ],
    })
  })

  test('ssr builtin', async () => {
    const builder = await createBuilder({
      root: resolve(dirname, 'fixtures/dynamic-import'),
      logLevel: 'warn',
      environments: {
        ssr: {
          build: {
            ssr: true,
            rolldownOptions: {
              input: {
                index: '/entry',
              },
            },
          },
        },
      },
    })
    const result = await builder.build(builder.environments.ssr)
    expect((result as RolldownOutput).output[0].code).not.toContain('preload')
  })

  test('ssr custom', async () => {
    const builder = await createBuilder({
      root: resolve(dirname, 'fixtures/dynamic-import'),
      logLevel: 'warn',
      environments: {
        custom: {
          build: {
            ssr: true,
            rolldownOptions: {
              input: {
                index: '/entry',
              },
            },
          },
        },
      },
    })
    const result = await builder.build(builder.environments.custom)
    expect((result as RolldownOutput).output[0].code).not.toContain('preload')
  })
})

test('default sharedConfigBuild true on build api', async () => {
  let counter = 0
  await build({
    root: resolve(dirname, 'fixtures/emit-assets'),
    logLevel: 'warn',
    build: {
      ssr: true,
      rolldownOptions: {
        input: {
          index: '/entry',
        },
      },
    },
    plugins: [
      {
        name: 'test-plugin',
        config() {
          counter++
        },
      },
    ],
  })
  expect(counter).toBe(1)
})

test.for([true, false])(
  'minify per environment (builder.sharedPlugins: %s)',
  async (sharedPlugins) => {
    const root = resolve(dirname, 'fixtures/shared-plugins/minify')
    const builder = await createBuilder({
      root,
      logLevel: 'warn',
      environments: {
        client: {
          build: {
            outDir: './dist/client',
            rolldownOptions: {
              input: '/entry.js',
            },
          },
        },
        ssr: {
          build: {
            outDir: './dist/server',
            rolldownOptions: {
              input: '/entry.js',
            },
          },
        },
        custom1: {
          build: {
            minify: true,
            outDir: './dist/custom1',
            rolldownOptions: {
              input: '/entry.js',
            },
          },
        },
        custom2: {
          build: {
            minify: false,
            outDir: './dist/custom2',
            rolldownOptions: {
              input: '/entry.js',
            },
          },
        },
      },
      builder: {
        sharedPlugins,
      },
    })
    const client = await builder.build(builder.environments.client)
    const ssr = await builder.build(builder.environments.ssr)
    const custom1 = await builder.build(builder.environments.custom1)
    const custom2 = await builder.build(builder.environments.custom2)
    expect(
      ([client, ssr, custom1, custom2] as RolldownOutput[]).map(
        (o) => o.output[0].code.split('\n').length,
      ),
    ).toEqual([1, 8, 1, 8])
  },
)

test('chunkImportMap per environment with shared plugins', async () => {
  const root = resolve(dirname, 'fixtures/shared-plugins/chunk-import-map')
  let client: RolldownOutput | undefined
  let ssr: RolldownOutput | undefined
  const builder = await createBuilder({
    root,
    logLevel: 'warn',
    environments: {
      client: {
        build: {
          chunkImportMap: true,
          write: false,
          rolldownOptions: {
            input: '/entry.js',
          },
        },
      },
      ssr: {
        build: {
          chunkImportMap: false,
          ssr: true,
          write: false,
          rolldownOptions: {
            input: '/entry.js',
          },
        },
      },
    },
    builder: {
      sharedPlugins: true,
      async buildApp(builder) {
        client = (await builder.build(
          builder.environments.client,
        )) as RolldownOutput
        ssr = (await builder.build(builder.environments.ssr)) as RolldownOutput
      },
    },
  })

  await builder.buildApp()

  const entry = client!.output.find(
    (output): output is OutputChunk =>
      output.type === 'chunk' && output.isEntry,
  )!
  const css = client!.output.find(
    (output) => output.type === 'asset' && output.fileName.endsWith('.css'),
  )!
  const importMapAsset = client!.output.find(
    (output) => output.type === 'asset' && output.fileName === 'importmap.json',
  )!
  expect(
    ssr!.output.some(
      (output) =>
        output.type === 'asset' && output.fileName === 'importmap.json',
    ),
  ).toBe(false)
  const importMap = JSON.parse(importMapAsset.source.toString())
    .imports as Record<string, string>
  const cssSpecifier = Object.entries(importMap).find(
    ([, fileName]) => fileName === `/${css.fileName}`,
  )![0]
  expect(entry.code).toContain(JSON.stringify(cssSpecifier.slice(1)))
})

test('chunkImportMap is emitted when emitAssets is false', async () => {
  const root = resolve(dirname, 'fixtures/shared-plugins/chunk-import-map')
  const builder = await createBuilder({
    root,
    logLevel: 'warn',
    environments: {
      ssr: {
        build: {
          ssr: true,
          emitAssets: false,
          write: false,
          chunkImportMap: true,
          rolldownOptions: {
            input: '/entry.js',
            experimental: {
              chunkImportMap: {
                fileName: 'custom-importmap.json',
              },
            },
          },
        },
      },
    },
  })

  const result = (await builder.build(
    builder.environments.ssr,
  )) as RolldownOutput

  expect(result.output).toContainEqual(
    expect.objectContaining({
      type: 'asset',
      fileName: 'custom-importmap.json',
    }),
  )
})

test('chunkImportMap is emitted for SSR when enabled', async () => {
  const root = resolve(dirname, 'fixtures/shared-plugins/chunk-import-map')
  const builder = await createBuilder({
    root,
    logLevel: 'warn',
    environments: {
      ssr: {
        build: {
          ssr: true,
          chunkImportMap: true,
          write: false,
          rolldownOptions: {
            input: '/entry.js',
          },
        },
      },
    },
  })

  const result = (await builder.build(
    builder.environments.ssr,
  )) as RolldownOutput

  expect(result.output).toContainEqual(
    expect.objectContaining({
      type: 'asset',
      fileName: 'importmap.json',
    }),
  )
})

test('importmap named asset is not emitted when chunkImportMap is false', async () => {
  const root = resolve(dirname, 'fixtures/shared-plugins/chunk-import-map')
  const builder = await createBuilder({
    root,
    logLevel: 'warn',
    plugins: [
      {
        name: 'emit-importmap-named-asset',
        buildStart() {
          this.emitFile({
            type: 'asset',
            fileName: 'importmap.json',
            source: '{}',
          })
        },
      },
    ],
    environments: {
      ssr: {
        build: {
          ssr: true,
          emitAssets: false,
          write: false,
          rolldownOptions: {
            input: '/entry.js',
          },
        },
      },
    },
  })

  const result = (await builder.build(
    builder.environments.ssr,
  )) as RolldownOutput

  expect(result.output).not.toContainEqual(
    expect.objectContaining({
      type: 'asset',
      fileName: 'importmap.json',
    }),
  )
})

test('sharedConfigBuild and emitAssets', async () => {
  const root = resolve(dirname, 'fixtures/shared-config-build/emitAssets')
  const builder = await createBuilder({
    root,
    logLevel: 'warn',
    configFile: false,
    environments: {
      client: {
        build: {
          outDir: './dist/client',
          emitAssets: true,
          rolldownOptions: {
            input: '/entry.js',
          },
        },
      },
      ssr: {
        build: {
          outDir: './dist/ssr',
          emitAssets: true,
          rolldownOptions: {
            input: '/entry.js',
          },
        },
      },
      custom: {
        build: {
          outDir: './dist/custom',
          emitAssets: true,
          rolldownOptions: {
            input: '/entry.js',
          },
        },
      },
    },
    builder: {
      sharedConfigBuild: true,
    },
  })

  expect(
    ['client', 'ssr', 'custom'].map(
      (name) => builder.environments[name].config.build.emitAssets,
    ),
  ).toEqual([true, true, true])

  await builder.buildApp()

  expect(
    await Promise.all(
      ['client', 'ssr', 'custom'].map((name) =>
        fsp.readdir(
          resolve(
            root,
            builder.environments[name].config.build.outDir,
            'assets',
          ),
        ),
      ),
    ),
  ).toEqual([
    expect.arrayContaining([expect.stringMatching(/\.css$/)]),
    expect.arrayContaining([expect.stringMatching(/\.css$/)]),
    expect.arrayContaining([expect.stringMatching(/\.css$/)]),
  ])
})

test('resolving lib entry from the top-level input does not mutate the user config', async () => {
  const userLib: LibraryOptions = { formats: ['es'] }
  const config = await resolveConfig(
    {
      configFile: false,
      input: 'src/main.ts',
      build: { lib: userLib },
    },
    'build',
  )
  const resolvedLib = config.environments.client.build.lib
  assert(resolvedLib !== false)
  expect(resolvedLib.entry).toBe('src/main.ts')
  expect(userLib.entry).toBeUndefined()
})

describe('onRollupLog', () => {
  const pluginName = 'rollup-plugin-test'
  const msgInfo = 'This is the INFO message.'
  const msgWarn = 'This is the WARN message.'
  const buildProject = async (
    level: LogLevel | 'error',
    message: string | RollupLog,
    logger: Logger,
    options?: Pick<RolldownOptions, 'onLog' | 'onwarn'>,
  ) => {
    await build({
      root: resolve(dirname, 'packages/build-project'),
      logLevel: 'info',
      build: {
        write: false,
        rolldownOptions: {
          ...options,
          logLevel: 'debug',
        },
      },
      customLogger: logger,
      plugins: [
        {
          name: pluginName,
          resolveId(id) {
            this[level](message)
            if (id === 'entry.js') {
              return '\0' + id
            }
          },
          load(id) {
            if (id === '\0entry.js') {
              return `export default "This is test module";`
            }
          },
        },
      ],
    })
  }

  const callOnRollupLog = async (
    logger: Logger,
    level: LogLevel,
    log: RollupLog,
  ) => {
    const config = await resolveConfig(
      { customLogger: logger },
      'build',
      'production',
      'production',
    )
    const buildEnvironment = new BuildEnvironment('client', config)
    onRollupLog(level, log, buildEnvironment)
  }

  afterEach(() => {
    vi.restoreAllMocks()
  })

  test('Rollup logs of info should be handled by vite', async () => {
    const logger = createLogger()
    const loggerSpy = vi.spyOn(logger, 'info').mockImplementation(() => {})

    await buildProject('info', msgInfo, logger)
    const logs = loggerSpy.mock.calls.map((args) =>
      stripVTControlCharacters(args[0]),
    )
    expect(logs).contain(`[plugin ${pluginName}] ${msgInfo}`)
  })

  test('Rollup logs of warn should be handled by vite', async () => {
    const logger = createLogger('silent')
    const loggerSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})

    await buildProject('warn', msgWarn, logger)
    const logs = loggerSpy.mock.calls.map((args) =>
      stripVTControlCharacters(args[0]),
    )
    expect(logs).contain(`[plugin ${pluginName}] ${msgWarn}`)
  })

  test('onLog passed by user is called', async () => {
    const logger = createLogger('silent')

    const onLogInfo = vi.fn((_log: RollupLog) => {})
    await buildProject('info', msgInfo, logger, {
      onLog(level, log) {
        if (level === 'info') {
          onLogInfo(log)
        }
      },
    })
    expect(onLogInfo).toBeCalledWith(
      expect.objectContaining({ message: msgInfo, plugin: pluginName }),
    )
  })

  test('onwarn passed by user is called', async () => {
    const logger = createLogger('silent')

    const onWarn = vi.fn((_log: RollupLog) => {})
    await buildProject('warn', msgWarn, logger, {
      onwarn(warning) {
        onWarn(warning)
      },
    })
    expect(onWarn).toBeCalledWith(
      expect.objectContaining({ message: msgWarn, plugin: pluginName }),
    )
  })

  test('should throw error when warning contains UNRESOLVED_IMPORT', async () => {
    const logger = createLogger()
    await expect(() =>
      callOnRollupLog(logger, 'warn', {
        code: 'UNRESOLVED_IMPORT',
        message: 'test',
      }),
    ).rejects.toThrowError(/Rolldown failed to resolve import/)
  })

  test.each([[`Unsupported expression`], [`statically analyzed`]])(
    'should ignore dynamic import warnings (%s)',
    async (message: string) => {
      const logger = createLogger()
      const loggerSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})

      await callOnRollupLog(logger, 'warn', {
        code: 'PLUGIN_WARNING',
        message: message,
        plugin: 'rollup-plugin-dynamic-import-variables',
      })
      expect(loggerSpy).toBeCalledTimes(0)
    },
  )

  test.each([[`CIRCULAR_DEPENDENCY`], [`THIS_IS_UNDEFINED`]])(
    'should ignore some warnings (%s)',
    async (code: string) => {
      const logger = createLogger()
      const loggerSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})

      await callOnRollupLog(logger, 'warn', {
        code: code,
        message: 'test message',
        plugin: pluginName,
      })
      expect(loggerSpy).toBeCalledTimes(0)
    },
  )
})

test('watch rebuild manifest', async (ctx) => {
  // this doesn't actually test watch rebuild
  // but it simulates something similar by running two builds for the same environment
  const root = resolve(dirname, 'fixtures/watch-rebuild-manifest')
  const builder = await createBuilder({
    root,
    logLevel: 'error',
    environments: {
      client: {
        build: {
          rolldownOptions: {
            input: '/entry.js',
          },
        },
      },
    },
    build: {
      manifest: true,
    },
  })

  function getManifestKeys(output: RolldownOutput) {
    return Object.keys(
      JSON.parse(
        (output.output.find((o) => o.fileName === '.vite/manifest.json') as any)
          .source,
      ),
    )
  }

  const result = await builder.build(builder.environments.client)
  expect(getManifestKeys(result as RolldownOutput)).toMatchInlineSnapshot(`
    [
      "dep.js",
      "entry.js",
    ]
  `)

  const entry = resolve(root, 'entry.js')
  const content = await fsp.readFile(entry, 'utf-8')
  await fsp.writeFile(
    entry,
    content.replace(`import('./dep.js')`, `'dep.js removed'`),
  )
  ctx.onTestFinished(async () => {
    await fsp.writeFile(entry, content)
  })

  const result2 = await builder.build(builder.environments.client)
  expect(getManifestKeys(result2 as RolldownOutput)).toMatchInlineSnapshot(`
    [
      "entry.js",
    ]
  `)
})

test('copies public directory after building same environment with write false first', async (ctx) => {
  const root = resolve(dirname, 'fixtures/public-dir-write-false')
  ctx.onTestFinished(() =>
    fsp.rm(resolve(root, 'dist'), { recursive: true, force: true }),
  )

  const builder = await createBuilder({
    root,
    configFile: false,
    logLevel: 'silent',
  })

  builder.environments.client.config.build.write = false
  await builder.build(builder.environments.client)

  builder.environments.client.config.build.write = true
  await builder.build(builder.environments.client)

  await expect(
    fsp.readFile(resolve(root, 'dist/favicon.svg'), 'utf-8'),
  ).resolves.toBe('<svg></svg>')
})

/**
 * for each chunks in output1, if there's a chunk in output2 with the same fileName,
 * ensure that the chunk code is the same. if not, the chunk hash should have changed.
 */
function assertOutputHashContentChange(
  output1: RolldownOutput,
  output2: RolldownOutput,
) {
  for (const chunk of output1.output) {
    if (chunk.type === 'chunk') {
      const chunk2 = output2.output.find(
        (c) => c.type === 'chunk' && c.fileName === chunk.fileName,
      ) as OutputChunk | undefined
      if (chunk2) {
        expect(
          chunk.code,
          `the ${chunk.fileName} chunk has the same hash but different contents between builds`,
        ).toEqual(chunk2.code)
      }
    }
  }
}

function getOutputHashChanges(
  output1: RolldownOutput,
  output2: RolldownOutput,
) {
  const map1 = Object.fromEntries(
    output1.output.map((o) => [o.name, o.fileName]),
  )
  const map2 = Object.fromEntries(
    output2.output.map((o) => [o.name, o.fileName]),
  )
  const names = Object.keys(map1).filter(Boolean)
  return {
    changed: names.filter((name) => map1[name] !== map2[name]),
    unchanged: names.filter((name) => map1[name] === map2[name]),
  }
}


<!doctype html>

    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + Qwik + TS</title>


import * as all from './deps-all-accepted'
import * as some from './deps-some-accepted'

console.log('loaded:all:' + all.a + all.b + all.c + all.default)
console.log('loaded:some:' + some.a + some.b + some.c + some.default)
console.log('>>> ready <<<')


#include <sstream>
#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
{
    // JSON Lines (see https://jsonlines.org)
    std::stringstream input;
    input << R"({"name": "Gilbert", "wins": [["straight", "7♣"], ["one pair", "10♥"]]}
{"name": "Alexa", "wins": [["two pair", "4♠"], ["two pair", "9♠"]]}
{"name": "May", "wins": []}
{"name": "Deloise", "wins": [["three of a kind", "5♣"]]}
)";

    std::string line;
    while (std::getline(input, line))
    {
        std::cout << json::parse(line) << std::endl;
    }
}


//     __ _____ _____ _____
//  __|  |   __|     |   | |  JSON for Modern C++
// |  |  |__   |  |  | | | |  version 3.12.0
// |_____|_____|_____|_|___|  https://github.com/nlohmann/json
//
// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT

#pragma once

#include <nlohmann/detail/macro_scope.hpp>

NLOHMANN_JSON_NAMESPACE_BEGIN

NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end);

NLOHMANN_JSON_NAMESPACE_END


// nested-directory/nested-file.js
var nested_file_default =
  'Nested file will trigger edge case that used to break sourcemaps'

// entrypoint.js
function entrypoint() {
  console.log(nested_file_default)
  throw new Error('Hello world')
}
export { entrypoint }
//# sourceMappingURL=dist.js.map


//     __ _____ _____ _____
//  __|  |   __|     |   | |  JSON for Modern C++
// |  |  |__   |  |  | | | |  version 3.12.0
// |_____|_____|_____|_|___|  https://github.com/nlohmann/json
//
// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT

#pragma once

#include <type_traits> // conditional, is_same

#include <nlohmann/detail/abi_macros.hpp>

NLOHMANN_JSON_NAMESPACE_BEGIN

/*!
@brief Default base class of the @ref basic_json class.

So that the correct implementations of the copy / move ctors / assign operators
of @ref basic_json do not require complex case distinctions
(no base class / custom base class used as customization point),
@ref basic_json always has a base class.
By default, this class is used because it is empty and thus has no effect
on the behavior of @ref basic_json.

@note This class intentionally lives in namespace @ref nlohmann rather than
      @ref nlohmann::detail. Every @ref basic_json specialization derives from
      it (via @ref detail::json_base_class) unless a custom base class is
      supplied, which makes its namespace an associated namespace of
      @ref basic_json for the purpose of argument-dependent lookup (ADL). If
      it lived in `nlohmann::detail`, that namespace - and with it the
      library's internal `to_json`/`from_json` overloads - would leak into
      ADL for any unqualified `to_json`/`from_json` call a user makes
      involving a @ref basic_json argument, silently shadowing the user's own
      overloads in some cases.
*/
struct json_default_base {};

namespace detail
{

template<class T>
using json_base_class = typename std::conditional <
                        std::is_same<T, void>::value,
                        ::nlohmann::json_default_base,
                        T
                        >::type;

}  // namespace detail
NLOHMANN_JSON_NAMESPACE_END


// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.

// Crash on the N-th execution.
#include <cstdint>
#include <cstddef>
#include <iostream>

static int Counter;

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  if (Counter++ == 1000) {
    std::cout << "BINGO; Found the target, exiting\n";
    exit(1);
  }
  return 0;
}


// this file should re-export only things that don't rely on Node.js or other runner features

export {
  EvaluatedModules,
  normalizeModuleId,
  type EvaluatedModuleNode,
} from './evaluatedModules'
export { ModuleRunner } from './runner'
export { ESModulesEvaluator } from './esmEvaluator'
export {
  createDefaultImportMeta,
  createNodeImportMeta,
} from './createImportMeta'

export { createWebSocketModuleRunnerTransport } from '../shared/moduleRunnerTransport'

export type { FetchFunctionOptions, FetchResult } from '../shared/invokeMethods'
export type {
  ModuleRunnerTransportHandlers,
  ModuleRunnerTransport,
} from '../shared/moduleRunnerTransport'
export type { HMRLogger } from '../shared/hmr'
export type {
  ModuleEvaluator,
  ModuleRunnerContext,
  FetchFunction,
  ResolvedResult,
  SSRImportMetadata,
  ModuleRunnerImportMeta,
  ModuleRunnerOptions,
  ModuleRunnerHmr,
} from './types'
export {
  ssrDynamicImportKey,
  ssrExportAllKey,
  ssrExportNameKey,
  ssrImportKey,
  ssrImportMetaKey,
  ssrModuleExportsKey,
} from './constants'
export type { InterceptorOptions } from './sourcemap/interceptor'


# <small>nlohmann::byte_container_with_subtype::</small>clear_subtype

```cpp
void clear_subtype() noexcept;
```

Clears the binary subtype and flags the value as not having a subtype, which has implications for serialization; for
instance, MessagePack will prefer the bin family over the ext family.

## Exception safety

No-throw guarantee: this function never throws exceptions.

## Complexity

Constant.

## Examples

??? example

    The example below demonstrates how `clear_subtype` can remove subtypes.

    ```cpp
    --8<-- "examples/byte_container_with_subtype__clear_subtype.cpp"
    ```

    Output:

    ```json
    --8<-- "examples/byte_container_with_subtype__clear_subtype.output"
    ```

## Version history

Since version 3.8.0.