import { describe, expect, test } from 'vitest'
import { modulePreloadLinkRE } from '../index'

describe('modulePreloadLinkRE', () => {
  const matches: Array<[string, string]> = [
    ['rel first', '<link rel="modulepreload" crossorigin href="/assets/x.js">'],
    [
      'rel after other attributes',
      '<link href="/assets/x.js" rel="modulepreload">',
    ],
    ['rel only', '<link rel="modulepreload">'],
    ['self-closing', '<link rel="modulepreload"/>'],
    ['self-closing with space', '<link rel="modulepreload" />'],
    ['single quotes', "<link rel='modulepreload' href='/assets/x.js'>"],
    [
      'attributes across multiple lines',
      '<link\n  rel="modulepreload"\n  href="/assets/x.js"\n>',
    ],
  ]

  for (const [name, html] of matches) {
    test(`matches: ${name}`, () => {
      expect(html.replace(modulePreloadLinkRE, '')).toBe('')
    })
  }

  const nonMatches: Array<[string, string]> = [
    ['tag name with suffix', '<linkfoo rel="modulepreload">'],
    ['custom element with hyphen', '<link-preview rel="modulepreload">'],
    ['bare link tag', '<link>'],
    ['stylesheet link', '<link rel="stylesheet" href="/assets/x.css">'],
    ['preload (not modulepreload)', '<link rel="preload" href="/assets/x.js">'],
    [
      'attribute name ending in rel',
      '<link xrel="modulepreload" href="/assets/x.js">',
    ],
    ['mismatched quotes', `<link rel="modulepreload'>`],
  ]

  for (const [name, html] of nonMatches) {
    test(`does not match: ${name}`, () => {
      expect(html.replace(modulePreloadLinkRE, '')).toBe(html)
    })
  }
})


//===- FuzzerUtil.cpp - Misc utils ----------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Misc utils.
//===----------------------------------------------------------------------===//

#include "FuzzerUtil.h"
#include "FuzzerIO.h"
#include "FuzzerInternal.h"
#include <cassert>
#include <chrono>
#include <cstring>
#include <errno.h>
#include <signal.h>
#include <sstream>
#include <stdio.h>
#include <sys/types.h>
#include <thread>

namespace fuzzer {

void PrintHexArray(const uint8_t *Data, size_t Size,
                   const char *PrintAfter) {
  for (size_t i = 0; i < Size; i++)
    Printf("0x%x,", (unsigned)Data[i]);
  Printf("%s", PrintAfter);
}

void Print(const Unit &v, const char *PrintAfter) {
  PrintHexArray(v.data(), v.size(), PrintAfter);
}

void PrintASCIIByte(uint8_t Byte) {
  if (Byte == '\\')
    Printf("\\\\");
  else if (Byte == '"')
    Printf("\\\"");
  else if (Byte >= 32 && Byte < 127)
    Printf("%c", Byte);
  else
    Printf("\\x%02x", Byte);
}

void PrintASCII(const uint8_t *Data, size_t Size, const char *PrintAfter) {
  for (size_t i = 0; i < Size; i++)
    PrintASCIIByte(Data[i]);
  Printf("%s", PrintAfter);
}

void PrintASCII(const Unit &U, const char *PrintAfter) {
  PrintASCII(U.data(), U.size(), PrintAfter);
}

bool ToASCII(uint8_t *Data, size_t Size) {
  bool Changed = false;
  for (size_t i = 0; i < Size; i++) {
    uint8_t &X = Data[i];
    auto NewX = X;
    NewX &= 127;
    if (!isspace(NewX) && !isprint(NewX))
      NewX = ' ';
    Changed |= NewX != X;
    X = NewX;
  }
  return Changed;
}

bool IsASCII(const Unit &U) { return IsASCII(U.data(), U.size()); }

bool IsASCII(const uint8_t *Data, size_t Size) {
  for (size_t i = 0; i < Size; i++)
    if (!(isprint(Data[i]) || isspace(Data[i]))) return false;
  return true;
}

bool ParseOneDictionaryEntry(const std::string &Str, Unit *U) {
  U->clear();
  if (Str.empty()) return false;
  size_t L = 0, R = Str.size() - 1;  // We are parsing the range [L,R].
  // Skip spaces from both sides.
  while (L < R && isspace(Str[L])) L++;
  while (R > L && isspace(Str[R])) R--;
  if (R - L < 2) return false;
  // Check the closing "
  if (Str[R] != '"') return false;
  R--;
  // Find the opening "
  while (L < R && Str[L] != '"') L++;
  if (L >= R) return false;
  assert(Str[L] == '\"');
  L++;
  assert(L <= R);
  for (size_t Pos = L; Pos <= R; Pos++) {
    uint8_t V = (uint8_t)Str[Pos];
    if (!isprint(V) && !isspace(V)) return false;
    if (V =='\\') {
      // Handle '\\'
      if (Pos + 1 <= R && (Str[Pos + 1] == '\\' || Str[Pos + 1] == '"')) {
        U->push_back(Str[Pos + 1]);
        Pos++;
        continue;
      }
      // Handle '\xAB'
      if (Pos + 3 <= R && Str[Pos + 1] == 'x'
           && isxdigit(Str[Pos + 2]) && isxdigit(Str[Pos + 3])) {
        char Hex[] = "0xAA";
        Hex[2] = Str[Pos + 2];
        Hex[3] = Str[Pos + 3];
        U->push_back(strtol(Hex, nullptr, 16));
        Pos += 3;
        continue;
      }
      return false;  // Invalid escape.
    } else {
      // Any other character.
      U->push_back(V);
    }
  }
  return true;
}

bool ParseDictionaryFile(const std::string &Text, std::vector<Unit> *Units) {
  if (Text.empty()) {
    Printf("ParseDictionaryFile: file does not exist or is empty\n");
    return false;
  }
  std::istringstream ISS(Text);
  Units->clear();
  Unit U;
  int LineNo = 0;
  std::string S;
  while (std::getline(ISS, S, '\n')) {
    LineNo++;
    size_t Pos = 0;
    while (Pos < S.size() && isspace(S[Pos])) Pos++;  // Skip spaces.
    if (Pos == S.size()) continue;  // Empty line.
    if (S[Pos] == '#') continue;  // Comment line.
    if (ParseOneDictionaryEntry(S, &U)) {
      Units->push_back(U);
    } else {
      Printf("ParseDictionaryFile: error in line %d\n\t\t%s\n", LineNo,
             S.c_str());
      return false;
    }
  }
  return true;
}

std::string Base64(const Unit &U) {
  static const char Table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                              "abcdefghijklmnopqrstuvwxyz"
                              "0123456789+/";
  std::string Res;
  size_t i;
  for (i = 0; i + 2 < U.size(); i += 3) {
    uint32_t x = (U[i] << 16) + (U[i + 1] << 8) + U[i + 2];
    Res += Table[(x >> 18) & 63];
    Res += Table[(x >> 12) & 63];
    Res += Table[(x >> 6) & 63];
    Res += Table[x & 63];
  }
  if (i + 1 == U.size()) {
    uint32_t x = (U[i] << 16);
    Res += Table[(x >> 18) & 63];
    Res += Table[(x >> 12) & 63];
    Res += "==";
  } else if (i + 2 == U.size()) {
    uint32_t x = (U[i] << 16) + (U[i + 1] << 8);
    Res += Table[(x >> 18) & 63];
    Res += Table[(x >> 12) & 63];
    Res += Table[(x >> 6) & 63];
    Res += "=";
  }
  return Res;
}

std::string DescribePC(const char *SymbolizedFMT, uintptr_t PC) {
  if (!EF->__sanitizer_symbolize_pc) return "<can not symbolize>";
  char PcDescr[1024];
  EF->__sanitizer_symbolize_pc(reinterpret_cast<void*>(PC),
                               SymbolizedFMT, PcDescr, sizeof(PcDescr));
  PcDescr[sizeof(PcDescr) - 1] = 0;  // Just in case.
  return PcDescr;
}

void PrintPC(const char *SymbolizedFMT, const char *FallbackFMT, uintptr_t PC) {
  if (EF->__sanitizer_symbolize_pc)
    Printf("%s", DescribePC(SymbolizedFMT, PC).c_str());
  else
    Printf(FallbackFMT, PC);
}

unsigned NumberOfCpuCores() {
  unsigned N = std::thread::hardware_concurrency();
  if (!N) {
    Printf("WARNING: std::thread::hardware_concurrency not well defined for "
           "your platform. Assuming CPU count of 1.\n");
    N = 1;
  }
  return N;
}

bool ExecuteCommandAndReadOutput(const std::string &Command, std::string *Out) {
  FILE *Pipe = OpenProcessPipe(Command.c_str(), "r");
  if (!Pipe) return false;
  char Buff[1024];
  size_t N;
  while ((N = fread(Buff, 1, sizeof(Buff), Pipe)) > 0)
    Out->append(Buff, N);
  return true;
}

}  // namespace fuzzer


# <small>nlohmann::</small>json_pointer

```cpp
template<typename RefStringType>
class json_pointer;
```

A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with
functions [`at`](../basic_json/at.md) and [`operator[]`](../basic_json/operator%5B%5D.md). Furthermore, JSON pointers
are the base for JSON patches.

## Template parameters

`RefStringType`
:   the string type used for the reference tokens making up the JSON pointer

!!! warning "Deprecation"

    For backwards compatibility `RefStringType` may also be a specialization of [`basic_json`](../basic_json/index.md)
    in which case `string_t` will be deduced as [`basic_json::string_t`](../basic_json/string_t.md). This feature is
    deprecated and may be removed in a future major version.

## Member types

- [**string_t**](string_t.md) - the string type used for the reference tokens

## Member functions

- [(constructor)](json_pointer.md)
- [**to_string**](to_string.md) - return a string representation of the JSON pointer
- [**operator string_t**](operator_string_t.md) - return a string representation of the JSON pointer
- [**operator==**](operator_eq.md) - compare: equal
- [**operator!=**](operator_ne.md) - compare: not equal
- [**operator/=**](operator_slasheq.md) - append to the end of the JSON pointer
- [**operator/**](operator_slash.md) - create JSON Pointer by appending
- [**parent_pointer**](parent_pointer.md) - returns the parent of this JSON pointer
- [**pop_back**](pop_back.md) - remove the last reference token
- [**back**](back.md) - return last reference token
- [**push_back**](push_back.md) - append an unescaped token at the end of the pointer
- [**pop_front**](pop_front.md) - remove the first reference token
- [**front**](front.md) - return first reference token
- [**push_front**](push_front.md) - append an unescaped token at the start of the pointer
- [**empty**](empty.md) - return whether the pointer points to the root document

## Literals

- [**operator""_json_pointer**](../operator_literal_json_pointer.md) - user-defined string literal for JSON pointers
## See also

- [RFC 6901](https://datatracker.ietf.org/doc/html/rfc6901)

## Version history

- Added in version 2.0.0.
- Changed template parameter from `basic_json` to string type in version 3.11.0.


ripgrep core
------------
This is the core ripgrep crate. In particular, `main.rs` is where the `main`
function lives.

Most of ripgrep core consists of two things:

* The definition of the CLI interface, including docs for every flag.
* Glue code that brings the `grep-matcher`, `grep-regex`, `grep-searcher` and
  `grep-printer` crates together to actually execute the search.

Currently, there are no plans to make ripgrep core available as an independent
library. However, much of the heavy lifting of ripgrep is done via its
constituent crates, which can be reused independent of ripgrep. Unfortunately,
there is no guide or tutorial to teach folks how to do this yet.


# <small>nlohmann::json_pointer::</small>operator==

```cpp
// until C++20
template<typename RefStringTypeLhs, typename RefStringTypeRhs>
bool operator==(
    const json_pointer<RefStringTypeLhs>& lhs,
    const json_pointer<RefStringTypeRhs>& rhs) noexcept;            // (1)

template<typename RefStringTypeLhs, typename StringType>
bool operator==(
    const json_pointer<RefStringTypeLhs>& lhs,
    const StringType& rhs);                                         // (2)

template<typename RefStringTypeRhs, typename StringType>
bool operator==(
    const StringType& lhs,
    const json_pointer<RefStringTypeRhs>& rhs);                     // (2)

// since C++20
class json_pointer {
    template<typename RefStringTypeRhs>
    bool operator==(
        const json_pointer<RefStringTypeRhs>& rhs) const noexcept;  // (1)

    bool operator==(const string_t& rhs) const;                     // (2)
};
```

1. Compares two JSON pointers for equality by comparing their reference tokens.

2. Compares a JSON pointer and a string or a string and a JSON pointer for equality by converting the string to a JSON
   pointer and comparing the JSON pointers according to 1.

## Template parameters

`RefStringTypeLhs`, `RefStringTypeRhs`
:   the string type of the left-hand side or right-hand side JSON pointer, respectively

`StringType`
:   the string type derived from the `json_pointer` operand ([`json_pointer::string_t`](string_t.md))

## Parameters

`lhs` (in)
:   first value to consider

`rhs` (in)
:   second value to consider

## Return value

whether the values `lhs`/`*this` and `rhs` are equal

## Exception safety

1. No-throw guarantee: this function never throws exceptions.
2. Strong exception safety: if an exception occurs, the original value stays intact.

## Exceptions

1. (none)
2. The function can throw the following exceptions:
   - Throws [parse_error.107](../../home/exceptions.md#jsonexceptionparse_error107) if the given JSON pointer `s` is
     nonempty and does not begin with a slash (`/`); see example below.
   - Throws [parse_error.108](../../home/exceptions.md#jsonexceptionparse_error108) if a tilde (`~`) in the given JSON
     pointer `s` is not followed by `0` (representing `~`) or `1` (representing `/`); see example below.

## Complexity

Constant if `lhs` and `rhs` differ in the number of reference tokens, otherwise linear in the number of reference
tokens.

## Notes

!!! warning "Deprecation"

    Overload 2 is deprecated and will be removed in a future major version release.

## Examples

??? example "Example: (1) Comparing JSON pointers"

    The example demonstrates comparing JSON pointers.

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

    Output:

    ```
    --8<-- "examples/json_pointer__operator__equal.output"
    ```

??? example "Example: (2) Comparing JSON pointers and strings"

    The example demonstrates comparing JSON pointers and strings, and when doing so may raise an exception.

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

    Output:

    ```
    --8<-- "examples/json_pointer__operator__equal_stringtype.output"
    ```

## Version history

1. Added in version 2.1.0. Added C++20 member functions in version 3.11.2.
2. Added for backward compatibility and deprecated in version 3.11.2.


import fs from 'node:fs'
import path from 'node:path'
import { stripVTControlCharacters } from 'node:util'
import { describe, expect, onTestFinished, test } from 'vitest'
import {
  isBuild,
  isBundledDev,
  page,
  readDepOptimizationMetadata,
  readFile,
  serverLogs,
  testDir,
} from '~utils'

test('basic', async () => {
  await page.getByText('hydrated: true').isVisible()
  await page.getByText('Count: 0').isVisible()
  await page.getByRole('button', { name: '+' }).click()
  await page.getByText('Count: 1').isVisible()
})

describe.runIf(!isBuild)('pre-bundling', () => {
  // bundled dev by design: the client environment has no dep optimizer, so
  // there is no .vite/deps folder to read. Dependencies come from the bundle.
  test.skipIf(isBundledDev)('client', async () => {
    const metaJson = readDepOptimizationMetadata()

    expect(metaJson.optimized['react']).toBeTruthy()
    expect(metaJson.optimized['react-dom/client']).toBeTruthy()
    expect(metaJson.optimized['react/jsx-dev-runtime']).toBeTruthy()

    expect(metaJson.optimized['react-dom/server']).toBeFalsy()
  })

  test('ssr', async () => {
    const metaJson = readDepOptimizationMetadata('ssr')

    expect(metaJson.optimized['react']).toBeTruthy()
    expect(metaJson.optimized['react-dom/server']).toBeTruthy()
    expect(metaJson.optimized['react/jsx-dev-runtime']).toBeTruthy()

    expect(metaJson.optimized['react-dom/client']).toBeFalsy()

    // process.env.NODE_ENV should be kept as keepProcessEnv is true
    const depsFiles = fs
      .readdirSync(path.resolve(testDir, 'node_modules/.vite/deps_ssr'), {
        withFileTypes: true,
      })
      .filter((file) => file.isFile() && file.name.endsWith('.js'))
      .map((file) => path.join(file.parentPath, file.name))
    const depsFilesWithProcessEnvNodeEnv = depsFiles.filter((file) =>
      fs.readFileSync(file, 'utf-8').includes('process.env.NODE_ENV'),
    )

    expect(depsFilesWithProcessEnvNodeEnv.length).toBeGreaterThan(0)
  })

  // bundled dev by design: there is no client dep-optimizer metadata to
  // compare before and after. The reload this test checks cannot happen.
  test.skipIf(isBundledDev)('deps reload', async () => {
    const envs = ['client', 'server'] as const

    const clientMeta = readDepOptimizationMetadata('client')
    const ssrMeta = readDepOptimizationMetadata('ssr')
    expect(clientMeta.optimized['react-fake-client']).toBeFalsy()
    expect(clientMeta.optimized['react-fake-server']).toBeFalsy()
    expect(ssrMeta.optimized['react-fake-server']).toBeFalsy()
    expect(ssrMeta.optimized['react-fake-client']).toBeFalsy()

    envs.forEach((env) => {
      const filePath = path.resolve(testDir, `src/entry-${env}.tsx`)
      const originalContent = readFile(filePath)
      fs.writeFileSync(
        filePath,
        `import 'react-fake-${env}'\n${originalContent}`,
        'utf-8',
      )
      onTestFinished(() => {
        fs.writeFileSync(filePath, originalContent, 'utf-8')
      })
    })

    await expect
      .poll(() =>
        serverLogs
          .map(
            (log) =>
              stripVTControlCharacters(log).match(
                /dependenc(?:y|ies) optimized: (react-fake-.*)/,
              )?.[1],
          )
          .filter(Boolean),
      )
      .toStrictEqual(['react-fake-server', 'react-fake-client'])

    const clientMetaNew = readDepOptimizationMetadata('client')
    const ssrMetaNew = readDepOptimizationMetadata('ssr')
    expect(clientMetaNew.optimized['react-fake-client']).toBeTruthy()
    expect(clientMetaNew.optimized['react-fake-server']).toBeFalsy()
    expect(ssrMetaNew.optimized['react-fake-server']).toBeTruthy()
    expect(ssrMetaNew.optimized['react-fake-client']).toBeFalsy()
  })
})


JS Sourcemap

dynamic