 whether the agent creates proxy.ts to log all requests — without the
 * prompt mentioning "proxy" or "middleware." The agent must infer that request
 * interception requires the proxy layer.
 *
 * Tricky because unlike agent-031 which explicitly asks for middleware, this
 * only asks to "log every request" — the agent must know proxy.ts is the
 * right tool, and use the Next.js 16 convention (not middleware.ts).
 */

import { expect, test } from 'vitest'
import { readFileSync, existsSync } from 'fs'
import

the file should be named proxy.ts, not middleware.ts
  // middleware.ts is deprecated
  const hasProxy = existsSync(proxyPath)
  const hasMiddleware = existsSync(middlewarePath)

  // Must have proxy.ts
  expect(hasProxy).toBe(true)

  // Should NOT have m

 { join } from 'path'

test('proxy.ts file exists in root (Next.js 16+ convention)', () => {
  const proxyPath = join(process.cwd(), 'proxy.ts')
  const middlewarePath = join(process.cwd(), 'middleware.ts')

  // In Next.js 16+,


t parallelizes independent data fetches with
 * Promise.all() instead of using sequential await calls.
 *
 * Tricky because agents default to sequential await for multiple fetches,
 * missing the opportunity to run independent requests concurrently.
 */

import { expect, test } from 'vitest'
import { readFileSync } from 'fs'
import { join } from 'path'

test('Page is an async server component with parallel data fetching', () => {
  const pageContent = readFileSync(
    join(process.cwd(), 'app', 'page.tsx')

  // Should use parallel data fetching with Promise.all
  expect(pageContent).toMatch(/Promise\.all/)
})

test('Dashboard component fetches from all required APIs', () => {
  const dashboardContent = readFileSync(
    join(process.cwd(), 'app', 'Dashboar

,
    'utf-8'
  )

  // Should be an async function
  expect(pageContent).toMatch(/async\s+function|export\s+default\s+async/)

  // Should NOT have 'use client' directive
  expect(pageContent).not.toMatch(/['"]use client['"];?/)


// Good example: parallel data fetching
async function getParallelData() {
  try {
    const [users, posts, stats] = await Promise.all([
      fetch('https://api.example.com/users').then((r) => r.json()),
      fetch('https://api.example.com/posts').then((r) => r.json()),
      fetch('https://api.example.com/stats').then((r) => r.json()),
    ])

    return { users, posts, stats }
  } catch {
    // Return mock data for build time
    return {
      users: [{ id: 1, name: 'User 1' }],
      posts: [{ id:

}
  }
}

export default async function Page() {
  const { users, posts, stats } = await getParallelData()

  return (

Dashboard

Users: {users.length}

Posts: {posts.length}

Total views: {stats

1, title: 'Post 1' }],
      stats: { views: 1000 },


r Next.js Image
 *
 * Tests whether the agent uses the Next.js Image component from next/image
 * instead of plain HTML <img> tags.
 *
 * Tricky because agents default to <img> tags, missing Next.js automatic
 * image optimization, lazy loading, and responsive sizing.
 */

import { expect, test } from 'vitest'
import { readFileSync } from 'fs'
import { join } from 'path'

test('ProductGallery uses Next.js Image component', () => {
  const galleryContent = readFileSync(
    join(process.cwd(), 'app', 'Produc

h(/<Image/)

  // Should NOT use img tags for product images
  expect(galleryContent).not.toMatch(/<img/)
})

test('ProductGallery has required image props', () => {
  const galleryContent = readFileSync(
    join(process.cwd(), 'app', 'ProductGallery.tsx'

tGallery.tsx'),
    'utf-8'
  )

  // Should import Image from next/image
  expect(galleryContent).toMatch(/import.*Image.*from ['"]next\/image['"]/)

  // Should use Image components, not img tags
  expect(galleryContent).toMatc


 "./types";

export const handlers = [
  http.get("https://my.backend/book", () => {
    const book: Book = {
      title: "Lord of the Rings",
      imageUrl: "/book-cover.jpg",
      description:
        "The Lord of the Rings is an epic high-fantasy novel written by English author and scholar J. R. R. Tolkien.",
    };
    return HttpResponse.json(book);
  }),

  http.get("/reviews", () => {
    const reviews: Review[] = [
      {
        id: "60333292-7ca1-4361-bf38-b6b43b90cb16",
        author: "John

no absolute hesitation, my most favored and adored book by‑far. The trilogy is wonderful‑ and I really consider this a legendary fantasy series. It will always keep you at the edge of your seat‑ and the characters you will grow and fall in love with!",

Maverick",
        text: "Lord of The Rings, is with


ct-dropdown-menu";

function RightSlot({ children }) {
  return (
    <div className="ml-auto pl-4 text-gray-500 group-hover:text-gray-200">
      {children}
    </div>
  );
}

function DropdownMenuItem({ children, ...props }) {
  return (
    <DropdownMenu.Item
      {...props}
      className={
        "group bg-white hover:bg-gray-700 hover:text-gray-200 text-xs rounded flex items-center h-6 px-1 pl-6 relative select-none" +
        (props.disabled ? " text-gray-500" : "")
      }
    >
      {children}

 rounded flex items-center h-6 px-1 pl-6 relative select-none"
    >
      {children}
    </DropdownMenu.CheckboxItem>
  );
}

function DropdownMenuItemIndicator({ children, ...props }) {
  return (
    <DropdownMenu.ItemIndicator
      {...props}
      cl

    </DropdownMenu.Item>
  );
}

function DropdownMenuCheckboxItem({ children, ...props }) {
  return (
    <DropdownMenu.CheckboxItem
      {...props}
      className="group bg-white hover:bg-gray-700 hover:text-gray-200 text-xs


tton: {
    button: "_2Agdx",
    rippleWrapper: "_3AVBi",
    squared: "_2GH_L",
    icon: "_3aBSX",
    solid: "_1ZxqC",
    raised: "_221ic _2Agdx _2GH_L _1ZxqC",
    flat: "_1jWAQ _2Agdx _2GH_L",
    floating: "_3IRMZ _2Agdx _1ZxqC",
    mini: "_2DCN-",
    toggle: "hC5Z2 _2Agdx",
    primary: "_3tTAW",
    accent: "_2wp6F",
    neutral: "_2CPs4",
    inverse: "_2SPZr",
  },
  RTRipple: {
    rippleWrapper: "_16N7o",
    ripple: "_3SV_u",
    rippleRestarting: "_2OZWa",
    rippleActive: "_3O2Ue",
  },

"_2DDdC",
    dialog: "_3fCV6",
    button: "_2hL6u",
    calendar: "_1X9ls",
    prev: "Nv9Bc",
    next: "_3iPkS",
    title: "_2ESpD",
    years: "zEdgW",
    active: "_1pjXb",
    week: "PcByv",
    days: "_1qh3T",
    day: "_2qF_L",
    month: "_1hSm5

  RTDatePicker: {
    input: "_2ISvI",
    disabled: "Cf3yF",
    inputElement: "x7MhN",
    header: "_2vLUd",
    year: "_1VWY-",
    date: "_3K2Ws",
    calendarWrapper: "_1t-4v",
    yearsDisplay: "_2OzvT",
    monthsDisplay:


client";

import { useActionState } from "react";
import { useFormStatus } from "react-dom";
import { createTodo } from "@/app/actions";

const initialState = {
  message: "",
};

function SubmitButton() {
  const { pending } = useFormStatus();

  return (
    <button type="submit" aria-disabled={pending}>
      Add
    </button>
  );
}

export function AddForm() {
  // useActionState is available with React 19 (Next.js App Router)
  const [state, formAction] = useActionState(createTodo, initialState);

  r

orm action={formAction}>
      Enter Task
      <input type="text" id="todo" name="todo" required />
      <SubmitButton />

        {state?.message}


ons/core'
import { context, getOctokit } from '@actions/github'
import { WebClient } from '@slack/web-api'
import { BlockCollection, Divider, Section } from 'slack-block-builder'
import { formattedDate, ninetyDaysAgo } from '../lib/util.mjs'

async function run() {
  try {
    if (!process.env.GITHUB_TOKEN) throw new TypeError('GITHUB_TOKEN not set')
    if (!process.env.SLACK_TOKEN) throw new TypeError('SLACK_TOKEN not set')

    const octoClient = getOctokit(process.env.GITHUB_TOKEN)
    const slackClient

${repo} -is:draft is:pr is:open created:>=${ninetyDaysAgo()}`,
      sort: 'reactions',
    })

    if (prs.items.length > 0) {
      let text = ''
      let count = 0

      prs.items.forEach((pr, i) => {
        if (pr.reactions) {
          if (pr.react

 = new WebClient(process.env.SLACK_TOKEN)

    const { owner, repo } = context.repo

    const { data: prs } = await octoClient.rest.search.issuesAndPullRequests({
      order: 'desc',
      per_page: 15,
      q: `repo:${owner}/


 { info, setFailed } from '@actions/core'
import { context, getOctokit } from '@actions/github'

async function main() {
  if (!process.env.GITHUB_TOKEN) throw new TypeError('GITHUB_TOKEN not set')

  const octokit = getOctokit(process.env.GITHUB_TOKEN)

  const { owner, repo } = context.repo
  const issue = context.payload.issue
  const body = `

This issue has been closed due to the incorrect issue template being used. Please make sure to submit a new issue using the [correct issue template](https://githu

est regards,
The Next.js Team
  `

  try {
    await octokit.rest.issues.createComment({
      owner,
      repo,
      issue_number: issue.number,
      body,
    })

    await octokit.rest.issues.update({
      owner,
      repo,
      issue_number: issu

b.com/vercel/next.js/issues/new?assignees=&labels=bug&projects=&template=1.bug_report.yml). This will ensure that we have all the necessary information to triage your issue.

Thank you for your understanding and contributions.

B


 manifestFile)
  const contents = await fs.readFile(file, 'utf-8')
  const results = JSON.parse(contents)

  let failingCount = 0
  let passingCount = 0

  const currentDate = new Date()
  const isoString = currentDate.toISOString()
  const timestamp = isoString.slice(0, 19).replace('T', ' ')

  for (const isPassing of Object.values(results)) {
    if (isPassing) {
      passingCount += 1
    } else {
      failingCount += 1
    }
  }
  const status = `${process.env.GITHUB_SHA}\t${timestamp}\t${passingCount

festFile) {
  const file = path.join(process.cwd(), manifestFile)
  const contents = await fs.readFile(file, 'utf-8')
  const results = JSON.parse(contents)

  let passingTests = ''
  let failingTests = ''
  let passCount = 0
  let failCount = 0

  const c

}/${
    passingCount + failingCount
  }`

  return {
    status,
    // Uses JSON.stringify to create minified JSON, otherwise whitespace is preserved.
    data: JSON.stringify(results),
  }
}

async function collectResults(mani


urationWebpack: 'Webpack Warm (First Request)',
  // Production metrics
  nextStartReadyDuration: 'Prod Start',
  // Build metrics - Webpack
  buildDurationWebpack: 'Webpack Build Time',
  buildDurationCachedWebpack: 'Webpack Build Time (cached)',
  // Build metrics - Turbopack
  buildDurationTurbo: 'Turbo Build Time',
  buildDurationCachedTurbo: 'Turbo Build Time (cached)',
  // General metrics
  nodeModulesSize: 'node_modules Size',
  swcBinarySize: 'SWC Binary Size',
}

// Group configuration for organiz

,
        key: 'nextDevColdListenDurationTurbo',
        description: 'Time until TCP port accepts connections',
      },
      {
        label: 'Cold (Ready in log)',
        key: 'nextDevColdReadyInDurationTurbo',
        description: 'Time until "Ready

ing the comment
const METRIC_GROUPS = {
  'Dev Server': {
    icon: '⚡',
    description:
      'Boot time for `next dev` (Turbopack). Cold = fresh build, Warm = with cache.',
    metrics: [
      {
        label: 'Cold (Listen)'


./run')
const addComment = require('./add-comment')
const actionInfo = require('./prepare/action-info')()
const { mainRepoDir, diffRepoDir, pnpmStoreDir } = require('./constants')
const loadStatsConfig = require('./prepare/load-stats-config')
const { cloneRepo, mergeBranch, getCommitId, linkPackages, getLastStable } =
  require('./prepare/repo-setup')(actionInfo)

const allowedActions = new Set(['synchronize', 'opened'])

// Get bundler filter from action input (set by GitHub Actions as INPUT_BUNDLER)
const

ionInfo.actionName) && !actionInfo.isRelease) {
  logger(
    `Not running for ${actionInfo.actionName} event action on repo: ${actionInfo.prRepo} and ref ${actionInfo.prRef}`
  )
  process.exit(0)
}

;(async () => {
  try {
    if (existsSync(path.join(__

 bundlerInput = (process.env.INPUT_BUNDLER || 'both').toLowerCase()
const isShardedRun = bundlerInput !== 'both'

if (isShardedRun) {
  logger(`Running in sharded mode for bundler: ${bundlerInput}`)
}

if (!allowedActions.has(act


= require('../util/exec')
const logger = require('../util/logger')

module.exports = (actionInfo) => {
  return {
    async cloneRepo(repoPath = '', dest = '', branch = '', depth = '20') {
      await fs.promises.rm(dest, { recursive: true, force: true })
      await exec(
        `git clone ${actionInfo.gitRoot}${repoPath} --single-branch --branch ${branch} --depth=${depth} ${dest}`
      )
    },
    async getLastStable() {
      const res = await fetch(
        `https://api.github.com/repos/vercel/next.j

tatus}: ${await res.text()}`
        )
      }
      const data = await res.json()
      return data.tag_name
    },
    async getCommitId(repoDir = '') {
      const { stdout } = await exec(`cd ${repoDir} && git rev-parse HEAD`)
      return stdout.trim()

s/releases/latest`,
        {
          headers: {
            'X-GitHub-Api-Version': '2022-11-28',
          },
        }
      )

      if (!res.ok) {
        throw new Error(
          `Failed to get latest stable tag ${res.s


nst exec = require('../util/exec')
const glob = require('../util/glob')
const logger = require('../util/logger')
const { statsAppDir, diffingDir } = require('../constants')

module.exports = async function collectDiffs(
  filesToTrack = [],
  initial = false
) {
  if (initial) {
    logger('Setting up directory for diffing')
    // set-up diffing directory
    await fs.rm(diffingDir, { recursive: true, force: true })
    await fs.mkdir(diffingDir, { recursive: true })
    await exec(`cd ${diffingDir} && git

ath.join(diffingDir, file), { recursive: true, force: true })
      )
    )
  }
  const diffs = {}

  await Promise.all(
    filesToTrack.map(async (fileGroup) => {
      const { globs } = fileGroup
      const curFiles = []
      const prettierExts = ['.j

 init`)
  } else {
    // remove any previous files in case they won't be overwritten
    const toRemove = await glob('!(.git)', { cwd: diffingDir, dot: true })

    await Promise.all(
      toRemove.map((file) =>
        fs.rm(p


urlParse } = require('url')
const benchmarkUrl = require('./benchmark-url')
const { statsAppDir, diffingDir, benchTitle } = require('../constants')
const { calcStats } = require('../util/stats')

// Number of iterations for timing benchmarks to get stable median
const BENCHMARK_ITERATIONS = process.env.BENCHMARK_ITERATIONS
  ? parseInt(process.env.BENCHMARK_ITERATIONS)
  : 9

// Check if a port is accepting TCP connections
function checkPort(port, timeout = 100) {
  return new Promise((resolve) => {
    con

)
    socket.once('error', () => {
      socket.destroy()
      resolve(false)
    })
    socket.connect(port, 'localhost')
  })
}

// Wait for port to start accepting TCP connections
async function waitForPort(port, timeoutMs = 60000) {
  const start = Da

st socket = new net.Socket()
    socket.setTimeout(timeout)
    socket.once('connect', () => {
      socket.destroy()
      resolve(true)
    })
    socket.once('timeout', () => {
      socket.destroy()
      resolve(false)
    }


logger = require('./logger')
const { promisify } = require('util')
const { exec: execOrig, spawn: spawnOrig } = require('child_process')

const execP = promisify(execOrig)
const env = {
  ...process.env,
  GITHUB_TOKEN: '',
  PR_STATS_COMMENT_TOKEN: '',
}

function exec(command, noLog = false, opts = {}) {
  if (!noLog) logger(`exec: ${command}`)
  return execP(command, {
    ...opts,
    env: { ...env, ...opts.env },
  })
}

exec.spawn = function spawn(command = '', opts = {}) {
  logger(`spawn: ${command}

(${code}, ${signal}): ${command}`)
  })
  return child
}

exec.spawnPromise = function spawnPromise(command = '', opts = {}) {
  return new Promise((resolve, reject) => {
    const child = exec.spawn(command, opts)
    child.on('exit', (code, signal) => {

`)
  const child = spawnOrig('/bin/bash', ['-c', command], {
    ...opts,
    env: {
      ...env,
      ...opts.env,
    },
    stdio: opts.stdio || 'inherit',
  })

  child.on('exit', (code, signal) => {
    logger(`spawn exit


erface JobResult {
  job: string
  data: TestResult
}

interface TestResultManifest {
  ref: string
  result: Array<JobResult>
  flakyMonitorJobResults: Array<JobResult>
}

/**
 * Models parsed test results output from next.js integration test.
 * This is a subset of the full test result output from jest, partially compatible.
 */
interface TestResult {
  numFailedTestSuites: number
  numFailedTests: number
  numPassedTestSuites: number
  numPassedTests: number
  numPendingTestSuites: number
  numPendingTes

orTitles?: Array<string> | null
      failureMessages?: Array<string> | null
      fullName: string
      location?: null
      status: string
      title: string
    }> | null
    endTime: number
    message: string
    name: string
    startTime: number

ts: number
  numRuntimeErrorTestSuites: number
  numTodoTests: number
  numTotalTestSuites: number
  numTotalTests: number
  startTime: number
  success: boolean
  testResults?: Array<{
    assertionResults?: Array<{
      ancest


Translation from "next-translate/useTranslation";
import "./style.css";

export const metadata = {
  title: "Next.js",
};

export default function Layout(props) {
  const { t, lang } = useTranslation();

  return (
    <html lang={lang}>
      <body className="container">
        {props.children}
        <footer>
          <span>{t("common:powered")} </span>
          <a
            href="https://vercel.com"
            target="_blank"
            rel="noopener noreferrer"
          >
            ▲ Vercel

          <span>&</span>
          <a
            href="https://github.com/vinissimus/next-translate"
            target="_blank"
            rel="noopener noreferrer"
          >
            next-translate
          </a>
        </footer>
      </body


nk";
import Trans from "next-translate/Trans";
import useTranslation from "next-translate/useTranslation";

export default function Home() {
  const { t, lang } = useTranslation();
  const isRTL = lang === "ar" || lang === "he";
  const arrow = isRTL ? String.fromCharCode(8592) : String.fromCharCode(8594);

  return (

      <Trans
        i18nKey="home:title"
        components={[

,
          Next.js!,

h3>{t("home:english")}

              {t("home:change-to")} {t("home:english")}

        </Link>

        <Link href="/ca">

{t("home:catalan")}

]}
      />

        {t("home:description")} _pages/index.js

        <Link href="/en">

            <


ogPageView } from "../utils/analytics";

const MyApp = ({ Component, pageProps }) => {
  const router = useRouter();

  useEffect(() => {
    initGA();
    // `routeChangeComplete` won't run for the first page load unless the query string is
    // hydrated later on, so here we log a page view if this is the first render and
    // there's no query string
    if (!router.asPath.includes("?")) {
      logPageView();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() =

n or when the query changes
    router.events.on("routeChangeComplete", logPageView);
    return () => {
      router.events.off("routeChangeComplete", logPageView);
    };
  }, [router.events]);

  return <Component {...pageProps} />;
};

export default M

> {
    // Listen for page changes after a navigatio


port { useActionState } from "react";
import { useFormStatus } from "react-dom";
import { deleteTodo } from "@/app/actions";

const initialState = {
  message: "",
};

function DeleteButton() {
  const { pending } = useFormStatus();

  return (
    <button type="submit" aria-disabled={pending}>
      Delete
    </button>
  );
}

export function DeleteForm({ id, todo }: { id: number; todo: string }) {
  // useActionState is available with React 19 (Next.js App Router)
  const [state, formAction] = useActionS

m action={formAction}>
      <input type="hidden" name="id" value={id} />
      <input type="hidden" name="todo" value={todo} />
      <DeleteButton />
      <p aria-live="polite" className="sr-only" role="status">
        {state?.message}
      </p>
    <

tate(deleteTodo, initialState);

  return (
    <for


al.js [--with-history]
 *
 * This generates a sample PR comment using mock data so you can
 * quickly verify formatting changes without running the full action.
 *
 * Options:
 *   --with-history  Simulate KV history data to test trend sparklines
 */

const addComment = require('./src/add-comment')

const withHistory = process.argv.includes('--with-history')

// Mock data simulating real benchmark results
const mockResults = [
  {
    title: 'Default Build',
    mainRepoStats: {
      General: {
        nex

ColdReadyDurationWebpack: 1200,
        nextDevWarmListenDurationWebpack: 250,
        nextDevWarmReadyDurationWebpack: 800,
        nextStartReadyDuration: 150,
        buildDurationTurbo: 4500,
        buildDurationCachedTurbo: 4200,
        buildDuratio

tDevColdListenDurationTurbo: 280,
        nextDevColdReadyDurationTurbo: 450,
        nextDevWarmListenDurationTurbo: 180,
        nextDevWarmReadyDurationTurbo: 320,
        nextDevColdListenDurationWebpack: 350,
        nextDev


os = require('os')
const fs = require('fs')

const benchTitle = 'Page Load Tests'

function getTempRoot() {
  const tempRoot = process.env.RUNNER_TEMP || os.tmpdir()

  try {
    fs.mkdirSync(tempRoot, { recursive: true })
    return tempRoot
  } catch {
    return os.tmpdir()
  }
}

const workDir = fs.mkdtempSync(path.join(getTempRoot(), 'next-stats-'))
const pnpmStoreDir = path.join(workDir, '.pnpm-store')
const mainRepoDir = path.join(workDir, 'main-repo')
const diffRepoDir = path.join(workDir, 'diff-rep

p')
const diffingDir = path.join(workDir, 'diff')
const allowedConfigLocations = [
  './',
  '.stats-app',
  'test/.stats-app',
  '.github/.stats-app',
]

module.exports = {
  benchTitle,
  workDir,
  pnpmStoreDir,
  diffingDir,
  mainRepoDir,
  diffRepoDi

o')
const statsAppDir = path.join(workDir, 'stats-ap


 = require('../util/exec')

const parseField = (stdout = '', field = '') => {
  return stdout.split(field).pop().trim().split(/\s/).shift().trim()
}

// benchmark an url
async function benchmarkUrl(
  url = '',
  options = {
    reqTimeout: 60,
    concurrency: 50,
    numRequests: 2500,
  }
) {
  const { numRequests, concurrency, reqTimeout } = options

  const { stdout } = await exec(
    `ab -n ${numRequests} -c ${concurrency} -s ${reqTimeout} "${url}"`
  )
  const totalTime = parseFloat(parseField(stdou

 for tests:'), 10)
  const failedRequests = parseInt(parseField(stdout, 'Failed requests:'), 10)
  const avgReqPerSec = parseFloat(parseField(stdout, 'Requests per second:'))

  return {
    totalTime,
    avgReqPerSec,
    failedRequests,
  }
}

module.ex


/**
 * Shared statistics utilities for benchmark measurements
 */

/**
 * Calculate statistical summary for an array of numbers
 * @param {number[]} arr - Array of numeric values
 * @returns {Object|null} Stats object with median, min, max, mean, stddev, cv or null if empty
 */
function calcStats(arr) {
  if (arr.length === 0) return null

  const sorted = [...arr].sort((a, b) => a - b)
  const mid = Math.floor(sorted.length / 2)
  const median =
    sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sort

h
  const stddev = Math.sqrt(variance)
  const cv = mean > 0 ? (stddev / mean) * 100 : 0 // coefficient of variation as %

  return {
    median,
    min,
    max,
    mean: Math.round(mean),
    stddev: Math.round(stddev),
    cv: Math.round(cv),
  }
}

m

ed[mid]) / 2
  const min = sorted[0]
  const max = sorted[sorted.length - 1]
  const mean = arr.reduce((a, b) => a + b, 0) / arr.length
  const variance =
    arr.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / arr.lengt


/github'
import { minimatch } from 'minimatch'
import config from './config.json'

type AuthorRule = { type: 'user'; pattern: string }
type LabelRule = string | AuthorRule
type LabelerConfig = { labels: Record<string, LabelRule[]> }

function isAuthorRule(rule: LabelRule): rule is AuthorRule {
  return (
    typeof rule === 'object' &&
    rule !== null &&
    'type' in rule &&
    rule.type === 'user'
  )
}

/**
 * Compute the set of labels to apply for a pull request.
 */
export function computeLabels(

orRule(rule)) {
        if (rule.pattern.toLowerCase() === author.toLowerCase()) {
          matched.add(label)
          break
        }
      } else if (typeof rule === 'string') {
        const matches = changedFiles.some((file) =>
          minimatch(f

config: LabelerConfig,
  author: string,
  changedFiles: string[]
): string[] {
  const matched = new Set<string>()

  for (const [label, rules] of Object.entries(config.labels)) {
    for (const rule of rules) {
      if (isAuth


;

import { revalidatePath } from "next/cache";
import postgres from "postgres";
import { z } from "zod";

let sql = postgres(process.env.DATABASE_URL || process.env.POSTGRES_URL!, {
  ssl: "allow",
});

// CREATE TABLE todos (
//   id SERIAL PRIMARY KEY,
//   text TEXT NOT NULL
// );

export async function createTodo(
  prevState: {
    message: string;
  },
  formData: FormData,
) {
  const schema = z.object({
    todo: z.string().min(1),
  });
  const parse = schema.safeParse({
    todo: formData.get("to

/");
    return { message: `Added todo ${data.todo}` };
  } catch (e) {
    return { message: "Failed to create todo" };
  }
}

export async function deleteTodo(
  prevState: {
    message: string;
  },
  formData: FormData,
) {
  const schema = z.object({

do"),
  });

  if (!parse.success) {
    return { message: "Failed to create todo" };
  }

  const data = parse.data;

  try {
    await sql`
      INSERT INTO todos (text)
      VALUES (${data.todo})
    `;

    revalidatePath("


const { diffRepoDir, allowedConfigLocations } = require('../constants')

// load stats-config
function loadStatsConfig() {
  let statsConfig
  let relativeStatsAppDir

  for (const configPath of allowedConfigLocations) {
    try {
      relativeStatsAppDir = configPath
      statsConfig = require(
        path.join(diffRepoDir, configPath, 'stats-config.js')
      )
      break
    } catch (err) {
      if (err.code !== 'MODULE_NOT_FOUND') {
        console.error('Failed to load stats-config at', configPath

nfig) {
    throw new Error(
      `Failed to locate \`.stats-app\`, allowed locations are: ${allowedConfigLocations.join(
        ', '
      )}`
    )
  }

  logger(
    'Got statsConfig at',
    path.join(relativeStatsAppDir, 'stats-config.js'),
    stat

, err)
      }
      /* */
    }
  }

  if (!statsCo


ort { useState } from "react";
import { Book, Review } from "../mocks/types";

type Props = {
  book: Book;
};

export default function Home({ book }: Props) {
  const [reviews, setReviews] = useState<Review[] | null>(null);

  const handleGetReviews = () => {
    // Client-side request are mocked by `mocks/browser.ts`.
    fetch("/reviews")
      .then((res) => res.json())
      .then(setReviews);
  };

  return (

{book.titl

w.text}

{review.author}

          ))}

      )}

  );
}

export async function getServerSideProps() {
  // Server-side requests are mocked by `mocks/server.ts`.
  const res = await fetch("ht

e}

{book.description}

      <button onClick={handleGetReviews}>Load reviews</button>
      {reviews && (

          {reviews.map((review) => (

{revie


bution CDFs (Student's t and
// standard normal). The rest — Welch's t-statistic, average-rank ranking,
// and the Mann–Whitney U statistic + asymptotic-tail p-value — is
// implemented here directly.
//
// For Mann–Whitney we use the normal approximation with continuity
// correction. For very small samples this approximation is less accurate
// (n=5 vs n=5 has a minimum exact two-sided p ≈ 0.008 vs the
// approximation's ≈ 0.012). Document this at the call site, not here.
import jstat from 'jstat'

export

olation quantile (numpy/R "type 7" default).
export function quantile(xs: number[], q: number): number {
  if (xs.length === 0) return NaN
  if (xs.length === 1) return xs[0]
  const sorted = [...xs].sort((a, b) => a - b)
  const pos = q * (sorted.length -

 interface Summary {
  mean: number
  p50: number
  p90: number
}

export function mean(xs: number[]): number {
  if (xs.length === 0) return NaN
  let s = 0
  for (const x of xs) s += x
  return s / xs.length
}

// Linear-interp


minimist(process.argv.slice(2), {
    alias: {
      r: 'row',
      c: 'column',
      '?': 'help',
      h: 'help',
    },
  })

  const knownArgs = new Set(['row', 'r', 'column', 'c', 'help', 'h', '?', '_'])
  if (args.help || (Object.keys(args).length === 1 && args._.length === 0)) {
    console.log('Usage: devlow-table <data.json>')
    console.log('  --row=<name>      Key to show as row')
    console.log('  --column=<name>   Key to show as column')
    console.log('  --<prop>=<name>   Filter values')

 => {
    if (name === 'value') {
      return data.text as string
    }
    if (Array.isArray(name)) {
      return name
        .map((n) => getValue(data, n, true))
        .filter((x) => x)
        .join(' ')
    }
    const value = data.key[name]
    i

    console.log('  --help, -h, -?    Show this help')
  }

  let data = JSON.parse(await readFile(args._[0], 'utf-8')) as any[]

  const getValue = (
    data: any,
    name: string | string[],
    includeKey: boolean
  ): string


mport { Interface } from '../index.js'
import { SampleGroup, groupRows, makeKey, printComparison } from '../compare.js'
import { readSnapshot } from '../snapshot.js'
import { formatVariantProps } from '../utils.js'

export default async function createInterface(options: {
  baselinePath: string
}): Promise<Interface> {
  const baselinePath = options.baselinePath
  const baselineRows = await readSnapshot(baselinePath)
  const baseline = groupRows(baselineRows)
  const current = new Map<string, SampleGroup>()

c)
        current.set(key, {
          scenario,
          variant,
          metric,
          unit: s.unit,
          samples: s.samples.slice(),
        })
      }
    },
    finish: async () => {
      printComparison(baseline, current, { baselineLabe

  return {
    variantStatistics: async (scenario, props, stats) => {
      const variant = formatVariantProps(props)
      for (const [metric, s] of Object.entries(stats)) {
        const key = makeKey(scenario, variant, metri


]): Interface {
  const allKeys = new Set<keyof Interface>()
  for (const iface of ifaces) {
    for (const key of Object.keys(iface)) {
      allKeys.add(key as keyof Interface)
    }
  }
  const composed: any = {}
  for (const key of allKeys) {
    if (key.startsWith('filter')) {
      composed[key] = async (items: any, ...args: any[]) => {
        for (const iface of ifaces) {
          const anyIface = iface as any
          if (anyIface[key]) {
            items = await anyIface[key](items, ...args)

 } else {
      composed[key] = async (...args: any[]) => {
        for (const iface of ifaces) {
          const anyIface = iface as any
          if (anyIface[key]) {
            await anyIface[key](...args)
          }
        }
      }
    }
  }
  retu

        }
        }
        return items
      }


ace } from '../index.js'
import { formatUnit } from '../units.js'
import { formatVariant } from '../utils.js'

const { bgCyan, bold, cyan, dim, magenta, red, underline } = picocolors

export default function createInterface(
  options: { n?: number } = {}
): Interface {
  const n = options.n ?? 1
  const showSummary = n > 1
  const iface: Interface = {
    start: async (scenario, props, runInfo) => {
      const label = formatVariant(scenario, props)
      let progress = ''
      if (runInfo) {
        prog

sync (scenario, props, name, value, unit, relativeTo) => {
      console.log(
        bgCyan(
          bold(
            magenta(
              `${formatVariant(scenario, props)}: ${name} = ${formatUnit(
                value,
                unit

ress = runInfo.warmup
          ? ` [warmup ${runInfo.run}/${runInfo.total}]`
          : ` [${runInfo.run}/${runInfo.total}]`
      }
      console.log(bold(underline(`Running ${label}...${progress}`)))
    },
    measurement: a


ommand } from '../shell.js'

export const UNIT_MAPPING: Record<string, string> = {
  ms: 'millisecond',
  requests: 'request',
  bytes: 'byte',
}

export const GIT_SHA =
  process.env.GITHUB_SHA ??
  (await (async () => {
    const cmd = command('git', ['rev-parse', 'HEAD'])
    await cmd.ok()
    return cmd.output.trim()
  })())

export const GIT_BRANCH =
  process.env.GITHUB_REF_NAME ??
  (await (async () => {
    const cmd = command('git', ['rev-parse', '--abbrev-ref', 'HEAD'])
    await cmd.ok()
    ret

Boolean(process.env.CI)
export const OS = process.platform
export const OS_RELEASE = os.release()
export const NUM_CPUS = os.cpus().length
export const CPU_MODEL = os.cpus()[0].model
export const USERNAME = os.userInfo().username
export const CPU_ARCH = os

urn cmd.output.trim()
  })())

export const IS_CI =


etadata,
} from '@datadog/datadog-api-client/dist/packages/datadog-api-client-v1/index.js'
import type { Interface } from '../index.js'
import datadogApiClient from '@datadog/datadog-api-client'
import os from 'os'
import {
  CPU_ARCH,
  CPU_MODEL,
  GIT_BRANCH,
  GIT_SHA,
  IS_CI,
  NODE_VERSION,
  NUM_CPUS,
  OS,
  OS_RELEASE,
  USERNAME,
} from './constants.js'

function toIdentifier(str: string) {
  return str.replace(/\//g, '.').replace(/ /g, '_')
}

const UNIT_MAPPING: Record<string, string> = {
  ms:

(),
}: { apiKey?: string; appKey?: string; host?: string } = {}): Interface {
  if (!apiKey)
    throw new Error('Datadog API key is required (set DATADOG_API_KEY)')
  const commonTags = [
    `ci:${IS_CI}`,
    `os:${OS}`,
    `os_release:${OS_RELEASE}`,

 'millisecond',
  requests: 'request',
  bytes: 'byte',
}

export default function createInterface({
  apiKey = process.env.DATADOG_API_KEY,
  appKey = process.env.DATADOG_APP_KEY,
  host = process.env.DATADOG_HOST || os.hostname


 { Interface } from '../index.js'
import inquirer from 'inquirer'
import { formatVariant } from '../utils.js'

export default function createInterface(): Interface {
  const iface: Interface = {
    filterScenarios: async (scenarios) => {
      if (scenarios.length === 1) {
        return scenarios
      }
      let answer = await inquirer.prompt({
        type: 'checkbox',
        name: 'scenarios',
        default: scenarios.slice(),
        message: 'Choose scenarios to run',
        choices: scenarios.m

 return variants
      }
      let answer = await inquirer.prompt({
        type: 'checkbox',
        name: 'variants',
        default: variants.slice(),
        message: 'Choose variants to run',
        choices: variants.map((variant) => {
          ret

ap((scenario) => ({
          name: scenario.name,
          value: scenario,
        })),
      })
      return answer.scenarios
    },
    filterScenarioVariants: async (variants) => {
      if (variants.length === 1) {


antile, mean as statsMean } from '../statistics.js'
import { formatUnit } from '../units.js'
import { writeFile } from 'fs/promises'

function filterProp(
  prop: Record<string, string | number | boolean | null>
): Record<string, string | number | boolean> {
  const filteredProp: Record<string, string | number | boolean> = {}
  for (const [key, value] of Object.entries(prop)) {
    if (value !== null) {
      filteredProp[key] = value
    }
  }
  return filteredProp
}

export default function createInterfac

  const n = options.n ?? 1
  // Per-(scenario, props, name) sample accumulator.
  const metrics = new Map<
    string,
    {
      key: Record<string, string | number>
      samples: number[]
      unit: string
      relativeTo?: string
    }
  >()
  const

e(
  file: string = (() => {
    const file = process.env.JSON_OUTPUT_FILE
    if (!file) {
      throw new Error('env var JSON_OUTPUT_FILE is not set')
    }
    return file
  })(),
  options: { n?: number } = {}
): Interface {


t'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test } from 'node:test'
import { command } from '../shell.js'

async function withTempScript(
  scriptContents: string,
  fn: (scriptPath: string) => Promise<void>
) {
  const dir = await mkdtemp(join(tmpdir(), 'devlow-shell-test-'))
  const scriptPath = join(dir, 'script.js')

  try {
    await writeFile(scriptPath, scriptContents, 'utf8')
    await fn(scriptPath)
  } fina

KER')
setTimeout(() => {}, 1000)
`,
    async (scriptPath) => {
      const shell = command('node', [scriptPath])

      try {
        const first = await shell.waitForOutput(/FIRST_MARKER\n/, {
          timeoutMs: 2_000,
        })
        assert.equal(f

lly {
    await rm(dir, { recursive: true, force: true })
  }
}

test('waitForOutput handles sequential waits after buffered output', async () => {
  await withTempScript(
    `
console.log('FIRST_MARKER')
console.log('SECOND_MAR


t { promisify } from 'node:util'
import picocolors from 'picocolors'
import { Interface } from '../index.js'
import { SnapshotRow, defaultSnapshotPath, writeSnapshot } from '../snapshot.js'
import { formatVariantProps } from '../utils.js'

const execFileAsync = promisify(execFile)

async function readGitInfo(): Promise<{ sha: string; branch: string }> {
  const sha = process.env.GITHUB_SHA || (await tryGit(['rev-parse', 'HEAD']))
  const branch =
    process.env.GITHUB_REF_NAME ||
    (await tryGit(['rev-pa

''
  }
}

export default function createInterface(
  options: { path?: string } = {}
): Interface & { resolvedPath: string } {
  const path = options.path ?? defaultSnapshotPath()
  const rows: SnapshotRow[] = []
  const timestamp = new Date().toISOString(

rse', '--abbrev-ref', 'HEAD']))
  return { sha, branch }
}

async function tryGit(args: string[]): Promise<string> {
  try {
    const { stdout } = await execFileAsync('git', args)
    return stdout.trim()
  } catch {
    return


t'
import createInterface from './snowflake.js'
import { mock, test } from 'node:test'

test('sending measurements to the batch endpoint', async () => {
  const requests: Array<[string, RequestInit]> = []

  const fetchMock = mock.method(
    global,
    'fetch',
    (req: string, options: RequestInit) => {
      requests.push([req, options])
      return Promise.resolve(Response.json({}))
    }
  )

  const iface = createInterface({
    gatewayUri: 'http://127.0.0.1/v1/batch',
    topicName: 'my-topic',

ent('scenario', { myprop: 'foo' }, 'three', 38, 'ms')

  assert(iface.end != null)
  await iface.end('scenario', { myprop: 'foo' })

  assert.equal(requests.length, 1)
  const [url, options] = requests[0]
  assert.equal(url, 'http://127.0.0.1/v1/batch')

  schemaId: 123,
  })

  assert(iface.measurement != null)
  await iface.measurement('scenario', { myprop: 'foo' }, 'one', 42, 'ms')
  await iface.measurement('scenario', { myprop: 'foo' }, 'two', 45, 'ms')
  await iface.measurem


IT_BRANCH,
  GIT_SHA,
  IS_CI,
  NODE_VERSION,
  NUM_CPUS,
  OS,
  OS_RELEASE,
  USERNAME,
} from './constants.js'
import { randomUUID } from 'crypto'

type DevlowMetric = {
  event_time: number
  scenario: string
  props: Record<string, string | number | boolean | null>
  metric: string
  value: number
  unit: string
  relative_to?: string
  is_ci: boolean
  os: string
  os_release: string
  cpus: number
  cpu_model: string
  user: string
  arch: string
  total_memory_bytes: number
  node_version: string

 parseInt(process.env.SNOWFLAKE_SCHEMA_ID, 10)
    : undefined,
}: {
  gatewayUri?: string
  topicName?: string
  schemaId?: number
} = {}): Interface {
  if (!gatewayUri)
    throw new Error(
      'Snowflake gateway URI is required (set SNOWFLAKE_GATEWAY

 git_sha: string
  git_branch: string
}

export default function createInterface({
  gatewayUri = process.env.SNOWFLAKE_BATCH_URI,
  topicName = process.env.SNOWFLAKE_TOPIC_NAME,
  schemaId = process.env.SNOWFLAKE_SCHEMA_ID
    ?


-pprof-node-gyp',
  'microtime-node-gyp',
  'zeromq-node-gyp',
]

const skipOnWindows = [
  'datadog-pprof-node-gyp',
  'yarn-workspaces',
  'yarn-workspaces-base-root',
  'yarn-workspace-esm',
  'asset-symlink',
  'require-symlink',
]
const skipOnMac = []
const skipOnNode20AndBelow = ['module-sync-condition-es']
const skipOnNode22AndAbove = ['module-sync-condition-es-node20']
if (process.platform === 'darwin' && process.arch === 'arm64') {
  skipOnMac.push('microtime-node-gyp')
}
const unitTestDirs = fs.re

 {
  const originalModule = jest.requireActual('../out/analyze.js').default

  return {
    __esModule: true,
    default: jest.fn(originalModule),
  }
})

jest.mock('graceful-fs', () => {
  const originalModule = jest.requireActual('graceful-fs')

  retur

addirSync(join(__dirname, 'unit'))
const unitTests = [
  ...unitTestDirs.map((testName) => ({ testName, isRoot: false })),
  ...unitTestDirs.map((testName) => ({ testName, isRoot: true })),
]

jest.mock('../out/analyze.js', () =>


se = require('firebase/app')
require('firebase/firestore')
require('firebase/database')

firebase.initializeApp({ projectId: 'noop' })
const store = firebase.firestore()

store
  .collection('users')
  .get()
  .then(
    () => {
      console.log('ok')
      process.exit(0)
    },
    (e) => {
      /*
      Error: unresolvable extensions: 'extend google.protobuf.MethodOptions' in .google.api
        at Root.resolveAll (/private/var/folders/c3/vytj6_h56b77f_g72smntm3m0000gn/T/node_modules/protobufjs/src/ro

/a707d6b7ee4afe5b484993180e617e2d/index.js:16778:41)
        at NodePlatform.module.exports.278.NodePlatform.loadConnection (/private/var/folders/c3/vytj6_h56b77f_g72smntm3m0000gn/T/a707d6b7ee4afe5b484993180e617e2d/index.js:16815:22)
        at FirestoreCl

ot.js:243:1)
        at Object.loadSync (/private/var/folders/c3/vytj6_h56b77f_g72smntm3m0000gn/T/a707d6b7ee4afe5b484993180e617e2d/index.js:43406:16)
        at loadProtos (/private/var/folders/c3/vytj6_h56b77f_g72smntm3m0000gn/T


;(() => {
  var exports = {}
  exports.id = 829
  exports.ids = [829]
  exports.modules = {
    /***/ 354: /***/ (
      __unused_webpack_module,
      __webpack_exports__,
      __webpack_require__
    ) => {
      // ESM COMPAT FLAG
      __webpack_require__.r(__webpack_exports__)

      // EXPORTS
      __webpack_require__.d(__webpack_exports__, {
        default: () => /* binding */ handler,
      }) // CONCATENATED MODULE: external "fs/promises"

      const promises_namespaceObject = require('fs/prom

ync function handler(_req, res) {
        const hello = await (0, promises_namespaceObject.readFile)(
          __dirname + '/hello.txt',
          'utf-8'
        )
        return hello
      }

      /***/
    },
  }
  // load runtime
  var __webpack_req

ises') // CONCATENATED MODULE: ./pages/api/users.ts
      // Fake users data
      const users = [
        {
          id: 1,
        },
        {
          id: 2,
        },
        {
          id: 3,
        },
      ]
      as


le cache
  /******/ var __webpack_module_cache__ = {}
  /******/
  /******/ // The require function
  /******/ function __webpack_require__(moduleId) {
    /******/ // Check if module is in cache
    /******/ var cachedModule = __webpack_module_cache__[moduleId]
    /******/ if (cachedModule !== undefined) {
      /******/ return cachedModule.exports
      /******/
    }
    /******/ // Create a new module (and put it into the cache)
    /******/ var module = (__webpack_module_cache__[moduleId] = {
      /*

     /******/ __webpack_modules__[moduleId](
        module,
        module.exports,
        __webpack_require__
      )
      /******/ threw = false
      /******/
    } finally {
      /******/ if (threw) delete __webpack_module_cache__[moduleId]
      /

*****/ // no module.id needed
      /******/ // no module.loaded needed
      /******/ exports: {},
      /******/
    })
    /******/
    /******/ // Execute the module function
    /******/ var threw = true
    /******/ try {


 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permiss

rts.LogVerbosity =
  exports.Status =
    void 0
var Status
;(function (Status) {
  Status[(Status['OK'] = 0)] = 'OK'
  Status[(Status['CANCELLED'] = 1)] = 'CANCELLED'
  Status[(Status['UNKNOWN'] = 2)] = 'UNKNOWN'
  Status[(Status['INVALID_ARGUMENT'] = 3)]

ions and
 * limitations under the License.
 *
 */
Object.defineProperty(exports, '__esModule', { value: true })
exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH =
  exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH =
  exports.Propagate =
  expo


**/ function __webpack_require__(moduleId) {
    /******/
    /******/ // Check if module is in cache
    /******/ if (installedModules[moduleId]) {
      /******/ return installedModules[moduleId].exports
      /******/
    }
    /******/ // Create a new module (and put it into the cache)
    /******/ var module = (installedModules[moduleId] = {
      /******/ i: moduleId,
      /******/ l: false,
      /******/ exports: {},
      /******/
    })
    /******/
    /******/ // Execute the module function

    } finally {
      /******/ if (threw) delete installedModules[moduleId]
      /******/
    }
    /******/
    /******/ // Flag the module as loaded
    /******/ module.l = true
    /******/
    /******/ // Return the exports of the module
    /******/

 /******/ var threw = true
    /******/ try {
      /******/ modules[moduleId].call(
        module.exports,
        module,
        module.exports,
        __webpack_require__
      )
      /******/ threw = false
      /******/


opy-sync.js',
  // 'node_modules/fs-extra/lib/copy/copy.js',
  // 'node_modules/fs-extra/lib/copy/index.js',
  // 'node_modules/fs-extra/lib/empty/index.js',
  // 'node_modules/fs-extra/lib/ensure/file.js',
  // 'node_modules/fs-extra/lib/ensure/index.js',
  // 'node_modules/fs-extra/lib/ensure/link.js',
  // 'node_modules/fs-extra/lib/ensure/symlink-paths.js',
  // 'node_modules/fs-extra/lib/ensure/symlink-type.js',
  // 'node_modules/fs-extra/lib/ensure/symlink.js',
  // 'node_modules/fs-extra/lib/fs/inde

-extra/lib/json/output-json.js',
  // 'node_modules/fs-extra/lib/mkdirs/index.js',
  // 'node_modules/fs-extra/lib/mkdirs/make-dir.js',
  // 'node_modules/fs-extra/lib/mkdirs/utils.js',
  // 'node_modules/fs-extra/lib/move/index.js',
  // 'node_modules/fs-

x.js',
  // 'node_modules/fs-extra/lib/index.js',
  // 'node_modules/fs-extra/lib/json/index.js',
  // 'node_modules/fs-extra/lib/json/jsonfile.js',
  // 'node_modules/fs-extra/lib/json/output-json-sync.js',
  // 'node_modules/fs


-gyp-build/index.js',
  'node_modules/@datadog/pprof/node_modules/node-gyp-build/package.json',
  'node_modules/@datadog/pprof/node_modules/source-map/lib/array-set.js',
  'node_modules/@datadog/pprof/node_modules/source-map/lib/base64-vlq.js',
  'node_modules/@datadog/pprof/node_modules/source-map/lib/base64.js',
  'node_modules/@datadog/pprof/node_modules/source-map/lib/binary-search.js',
  'node_modules/@datadog/pprof/node_modules/source-map/lib/mapping-list.js',
  'node_modules/@datadog/pprof/node_modul

odules/source-map/lib/source-map-generator.js',
  'node_modules/@datadog/pprof/node_modules/source-map/lib/source-node.js',
  'node_modules/@datadog/pprof/node_modules/source-map/lib/util.js',
  'node_modules/@datadog/pprof/node_modules/source-map/lib/wasm

es/source-map/lib/mappings.wasm',
  'node_modules/@datadog/pprof/node_modules/source-map/lib/read-wasm.js',
  'node_modules/@datadog/pprof/node_modules/source-map/lib/source-map-consumer.js',
  'node_modules/@datadog/pprof/node_m


__importDefault =
  (this && this.__importDefault) ||
  function (mod) {
    return mod && mod.__esModule ? mod : { default: mod }
  }
var __importStar =
  (this && this.__importStar) ||
  function (mod) {
    if (mod && mod.__esModule) return mod
    var result = {}
    if (mod != null)
      for (var k in mod)
        if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]
    result['default'] = mod
    return result
  }
Object.defineProperty(exports, '__esModule', { value: true })
const fs_1 = __impo

equire('path'))
console.log(
  fs_1.default.readFileSync(path.join(__dirname, 'asset.txt'), 'utf8')
)

/* Input source (with modules: 'commonjs'):
import fs from 'fs';
import * as path from 'path';

console.log(fs.readFileSync(path.join(__dirname, 'asset.t

rtDefault(require('fs'))
const path = __importStar(r


23
  exports.ids = [223]
  exports.modules = {
    /***/ 0: /***/ function (module, exports, __webpack_require__) {
      module.exports = __webpack_require__('PicC')

      /***/
    },

    /***/ PicC: /***/ function (
      module,
      __webpack_exports__,
      __webpack_require__
    ) {
      'use strict'
      __webpack_require__.r(__webpack_exports__)
      /* harmony export (binding) */ __webpack_require__.d(
        __webpack_exports__,
        'default',
        function () {
          return h

th__WEBPACK_IMPORTED_MODULE_0__)
      /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ = require('fs')
      /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___default =
        /*#__PURE__*/ __webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE

andler
        }
      )
      /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = require('path')
      /* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default =
        /*#__PURE__*/ __webpack_require__.n(pa


ges/applescript.tmLanguage.json',
  'node_modules/shiki/languages/ara.tmLanguage.json',
  'node_modules/shiki/languages/asm.tmLanguage.json',
  'node_modules/shiki/languages/astro.tmLanguage.json',
  'node_modules/shiki/languages/awk.tmLanguage.json',
  'node_modules/shiki/languages/ballerina.tmLanguage.json',
  'node_modules/shiki/languages/bat.tmLanguage.json',
  'node_modules/shiki/languages/beancount.tmLanguage.json',
  'node_modules/shiki/languages/berry.tmLanguage.json',
  'node_modules/shiki/language

e.tmLanguage.json',
  'node_modules/shiki/languages/clarity.tmLanguage.json',
  'node_modules/shiki/languages/clojure.tmLanguage.json',
  'node_modules/shiki/languages/cmake.tmLanguage.json',
  'node_modules/shiki/languages/cobol.tmLanguage.json',
  'node_

s/bibtex.tmLanguage.json',
  'node_modules/shiki/languages/bicep.tmLanguage.json',
  'node_modules/shiki/languages/blade.tmLanguage.json',
  'node_modules/shiki/languages/c.tmLanguage.json',
  'node_modules/shiki/languages/cadenc


use strict'

var os = require('os')
var fs = require('fs')
var path = require('path')

var verifyFile

var platform = os.platform() + '-' + os.arch() && '.'

var packageName = '@ffmpeg-installer/' + platform

var binary = os.platform() === 'win32' ? 'ffmpeg.exe' : 'ffmpeg.exe'

// var npm3Path = path.resolve(__dirname, '..', platform);
var npm2Path = path.resolve(__dirname, '.', platform)

var npm3Binary = path.join(npm3Path, binary)
var npm2Binary = path.join(npm2Path, binary)

var npm3Package = path.join(

} else {
  throw (
    'Could not find ffmpeg executable, tried "' +
    npm3Binary +
    '" and "' +
    npm2Binary +
    '"'
  )
}

var version = packageJson.ffmpeg || packageJson.version
var url = packageJson.homepage

module.exports = {
  path: ffmpegP

npm3Path, 'package.json')
var npm2Package = path.join(npm2Path, 'package.json')

var ffmpegPath, packageJson

if (verifyFile(npm3Binary)) {
  ffmpegPath = npm3Binary
} else if (verifyFile(npm2Binary)) {
  ffmpegPath = npm2Binary


ypeof(obj) {
  if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
    _typeof = function _typeof(obj) {
      return typeof obj
    }
  } else {
    _typeof = function _typeof(obj) {
      return obj &&
        typeof Symbol === 'function' &&
        obj.constructor === Symbol &&
        obj !== Symbol.prototype
        ? 'symbol'
        : typeof obj
    }
  }
  return _typeof(obj)
}

var _fs = _interopRequireDefault(require('fs'))

var path = _interopRequireWildcard(require('path')

ion _interopRequireWildcard(obj) {
  if (obj && obj.__esModule) {
    return obj
  }
  if (
    obj === null ||
    (_typeof(obj) !== 'object' && typeof obj !== 'function')
  ) {
    return { default: obj }
  }
  var cache = _getRequireWildcardCache()
  if

)

function _getRequireWildcardCache() {
  if (typeof WeakMap !== 'function') return null
  var cache = new WeakMap()
  _getRequireWildcardCache = function _getRequireWildcardCache() {
    return cache
  }
  return cache
}

funct


/***/ 474: /***/ function (
      __unused_webpack_module,
      __webpack_exports__,
      __webpack_require__
    ) {
      'use strict'
      __webpack_require__.r(__webpack_exports__)
      /* harmony export */ __webpack_require__.d(__webpack_exports__, {
        /* harmony export */ default: function () {
          return /* binding */ _
        },
        /* harmony export */ getServerSideProps: function () {
          return /* binding */ getServerSideProps
        },
        /* harmony export */

__webpack_require__.n(
          react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__
        )
      /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1__ =
        __webpack_require__(747)
      /* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_1___defau

   })
      /* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__ =
        __webpack_require__(282)
      /* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0___default =
        /*#__PURE__*/


 var o = (e[n] = {
      i: n,
      l: !1,
      exports: {},
    })
    return (t[n].call(o.exports, o, o.exports, r), (o.l = !0), o.exports)
  }
  return (
    (r.m = t),
    (r.c = e),
    (r.d = function (t, e, n) {
      r.o(t, e) ||
        Object.defineProperty(t, e, {
          enumerable: !0,
          get: n,
        })
    }),
    (r.r = function (t) {
      ;('undefined' != typeof Symbol &&
        Symbol.toStringTag &&
        Object.defineProperty(t, Symbol.toStringTag, {
          value: 'Mo

 t && t.__esModule) return t
      var n = Object.create(null)
      if (
        (r.r(n),
        Object.defineProperty(n, 'default', {
          enumerable: !0,
          value: t,
        }),
        2 & e && 'string' != typeof t)
      )
        for (v

dule',
        }),
        Object.defineProperty(t, '__esModule', {
          value: !0,
        }))
    }),
    (r.t = function (t, e) {
      if ((1 & e && (t = r(t)), 8 & e)) return t
      if (4 & e && 'object' == typeof t &&


e) {
  'object' == typeof exports && 'undefined' != typeof module
    ? (module.exports = e())
    : 'function' == typeof define && define.amd
      ? define([], e)
      : (('undefined' != typeof window
          ? window
          : 'undefined' != typeof global
            ? global
            : 'undefined' != typeof self
              ? self
              : this
        ).ytSearch = e())
})(function () {
  return (function r(l, u, o) {
    function s(t, e) {
      if (!u[t]) {
        if (!l[t]) {

D'), n)
        }
        var a = (u[t] = {
          exports: {},
        })
        l[t][0].call(
          a.exports,
          function (e) {
            return s(l[t][1][e] || e)
          },
          a,
          a.exports,
          r,
          l,

    var i = 'function' == typeof require && require
          if (!e && i) return i(t, !0)
          if (c) return c(t, !0)
          var n = new Error("Cannot find module '" + t + "'")
          throw ((n.code = 'MODULE_NOT_FOUN


node_modules/pixelmatch/bin/pixelmatch',
  'node_modules/pixelmatch/index.js',
  'node_modules/pixelmatch/package.json',
  'node_modules/pngjs/lib/bitmapper.js',
  'node_modules/pngjs/lib/bitpacker.js',
  'node_modules/pngjs/lib/chunkstream.js',
  'node_modules/pngjs/lib/constants.js',
  'node_modules/pngjs/lib/crc.js',
  'node_modules/pngjs/lib/filter-pack.js',
  'node_modules/pngjs/lib/filter-parse-async.js',
  'node_modules/pngjs/lib/filter-parse-sync.js',
  'node_modules/pngjs/lib/filter-parse.js',
  'n

gjs/lib/paeth-predictor.js',
  'node_modules/pngjs/lib/parser-async.js',
  'node_modules/pngjs/lib/parser-sync.js',
  'node_modules/pngjs/lib/parser.js',
  'node_modules/pngjs/lib/png-sync.js',
  'node_modules/pngjs/lib/png.js',
  'node_modules/pngjs/lib/s

ode_modules/pngjs/lib/format-normaliser.js',
  'node_modules/pngjs/lib/interlace.js',
  'node_modules/pngjs/lib/packer-async.js',
  'node_modules/pngjs/lib/packer-sync.js',
  'node_modules/pngjs/lib/packer.js',
  'node_modules/pn


se5@6.0.1/node_modules/parse5/lib/common/html.js',
  'test/unit/pnpm-symlinks/node_modules/.pnpm/parse5@6.0.1/node_modules/parse5/package.json',
  'test/unit/pnpm-symlinks/node_modules/parse5-htmlparser2-tree-adapter',
  'test/unit/pnpm-symlinks/package.js


= {}
  function r(n) {
    if (t[n]) return t[n].exports
    var o = (t[n] = { i: n, l: !1, exports: {} })
    return (e[n].call(o.exports, o, o.exports, r), (o.l = !0), o.exports)
  }
  ;((r.m = e),
    (r.c = t),
    (r.d = function (e, t, n) {
      r.o(e, t) || Object.defineProperty(e, t, { enumerable: !0, get: n })
    }),
    (r.r = function (e) {
      ;('undefined' != typeof Symbol &&
        Symbol.toStringTag &&
        Object.defineProperty(e, Symbol.toStringTag, { value: 'Module' }),
        Obj

.create(null)
      if (
        (r.r(n),
        Object.defineProperty(n, 'default', { enumerable: !0, value: e }),
        2 & t && 'string' != typeof e)
      )
        for (var o in e)
          r.d(
            n,
            o,
            function (

ect.defineProperty(e, '__esModule', { value: !0 }))
    }),
    (r.t = function (e, t) {
      if ((1 & t && (e = r(e)), 8 & t)) return e
      if (4 & t && 'object' == typeof e && e && e.__esModule) return e
      var n = Object


eturn (
    <Typography sx={{ mt: 6, mb: 3, color: 'text.secondary' }}>
      <LightBulbIcon sx={{ mr: 1, verticalAlign: 'middle' }} />
      {'Pro tip: See more '}
      <Link href="https://mui.com/material-ui/getting-started/templates/">
        template

gIcon>
  )
}

export default function ProTip() {
  r


ongoose from 'mongoose'

const MONGODB_URI = process.env.MONGODB_URI

if (!MONGODB_URI) {
  throw new Error(
    'Please define the MONGODB_URI environment variable inside .env.local'
  )
}

/**
 * Global is used here to maintain a cached connection across hot reloads
 * in development. This prevents connections growing exponentially
 * during API Route usage.
 */
let cached = global.mongoose

if (!cached) {
  cached = global.mongoose = { conn: null, promise: null }
}

async function dbConnect() {
  if (cac

d.promise) {
    const opts = {
      bufferCommands: false,
    }

    cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
      return mongoose
    })
  }
  cached.conn = await cached.promise
  return cached.conn
}

export default d

hed.conn) {
    return cached.conn
  }

  if (!cache


ose from 'mongoose'

/* PetSchema will correspond to a collection in your MongoDB database. */
const PetSchema = new mongoose.Schema({
  name: {
    /* The name of this pet */

    type: String,
    required: [true, 'Please provide a name for this pet.'],
    maxlength: [60, 'Name cannot be more than 60 characters'],
  },
  owner_name: {
    /* The owner of this pet */

    type: String,
    required: [true, "Please provide the pet owner's name"],
    maxlength: [60, "Owner's Name cannot be more than 60 cha

 age: {
    /* Pet's age, if applicable */

    type: Number,
  },
  poddy_trained: {
    /* Boolean poddy_trained value, if applicable */

    type: Boolean,
  },
  diet: {
    /* List of dietary needs, if applicable */

    type: Array,
  },
  image_url:

racters"],
  },
  species: {
    /* The species of your pet */

    type: String,
    required: [true, 'Please specify the species of your pet.'],
    maxlength: [40, 'Species specified cannot be more than 40 characters'],
  },


m 'next/router'
import useSWR from 'swr'
import Form from '../../components/Form'

const fetcher = (url) =>
  fetch(url)
    .then((res) => res.json())
    .then((json) => json.data)

const EditPet = () => {
  const router = useRouter()
  const { id } = router.query
  const { data: pet, error } = useSWR(id ? `/api/pets/${id}` : null, fetcher)

  if (error) return
Failed to load

  if (!pet) return
Loading...

  const petForm = {
    name: pet.name,
    owner_name: pet.owner_name,
    species: p

  age: pet.age,
    poddy_trained: pet.poddy_trained,
    diet: pet.diet,
    image_url: pet.image_url,
    likes: pet.likes,
    dislikes: pet.dislikes,
  }

  return <Form formId="edit-pet-form" petForm={petForm} forNewPet={false} />
}

export default Ed


nect from '../../../lib/dbConnect'
import Pet from '../../../models/Pet'

export default async function handler(req, res) {
  const {
    query: { id },
    method,
  } = req

  await dbConnect()

  switch (method) {
    case 'GET' /* Get a model by its ID */:
      try {
        const pet = await Pet.findById(id)
        if (!pet) {
          return res.status(400).json({ success: false })
        }
        res.status(200).json({ success: true, data: pet })
      } catch (error) {
        res.status(400).j

        if (!pet) {
          return res.status(400).json({ success: false })
        }
        res.status(200).json({ success: true, data: pet })
      } catch (error) {
        res.status(400).json({ success: false })
      }
      break

    case 'DELET

son({ success: false })
      }
      break

    case 'PUT' /* Edit a model by its ID */:
      try {
        const pet = await Pet.findByIdAndUpdate(id, req.body, {
          new: true,
          runValidators: true,
        })


nnect from '../../../lib/dbConnect'
import Pet from '../../../models/Pet'

export default async function handler(req, res) {
  const { method } = req

  await dbConnect()

  switch (method) {
    case 'GET':
      try {
        const pets = await Pet.find({}) /* find all the data in our database */
        res.status(200).json({ success: true, data: pets })
      } catch (error) {
        res.status(400).json({ success: false })
      }
      break
    case 'POST':
      try {
        const pet = await Pet.

 model in the database */
        res.status(201).json({ success: true, data: pet })
      } catch (error) {
        res.status(400).json({ success: false })
      }
      break
    default:
      res.status(400).json({ success: false })
      break
  }
}

create(
          req.body
        ) /* create a new


Promise<void>
  reload(metricName: string): Promise<void>
}

const browserOutput = Boolean(process.env.BROWSER_OUTPUT)

async function withRequestMetrics(
  metricName: string,
  page: Page,
  fn: () => Promise<void>
): Promise<void> {
  const activePromises: Array<Promise<void>> = []
  const sizeByExtension = new Map<string, number>()
  const requestsByExtension = new Map<string, number>()
  const responseHandler = (response: Response) => {
    activePromises.push(
      (async () => {
        const url =

? 0
        requestsByExtension.set(extension, currentRequests + 1)
        if (status >= 200 && status < 300) {
          let body
          try {
            body = await response.body()
          } catch {
            // empty
          }
          if (

response.request().url()
        const status = response.status()
        const extension =
          /^[^?#]+\.([a-z0-9]+)(?:[?#]|$)/i.exec(url)?.[1] ?? 'none'
        const currentRequests = requestsByExtension.get(extension) ?


red, underline } = picocolors

const SIGNIFICANCE_THRESHOLD = 0.05

type RowVerdict = 'improved' | 'regressed' | undefined

interface FormattedRow {
  cells: string[]
  verdict: RowVerdict
}

export interface SampleGroup {
  scenario: string
  variant: string
  metric: string
  unit: string
  samples: number[]
}

// Groups SnapshotRows into per-(scenario, variant, metric) sample arrays.
// Skips rows whose value is non-finite (e.g. failed CSV parse).
export function groupRows(rows: SnapshotRow[]): Map<strin

roup) {
      group = {
        scenario: r.scenario,
        variant: r.variant,
        metric: r.metric,
        unit: r.unit,
        samples: [],
      }
      out.set(key, group)
    }
    group.samples.push(r.value)
  }
  return out
}

export functi

g, SampleGroup> {
  const out = new Map<string, SampleGroup>()
  for (const r of rows) {
    if (!Number.isFinite(r.value)) continue
    const key = makeKey(r.scenario, r.variant, r.metric)
    let group = out.get(key)
    if (!g


'
import { access, constants } from 'fs/promises'
import { dirname } from 'path'

export async function waitForFile(
  path: string,
  timeout: number
): Promise<void> {
  let currentAction = ''
  let timeoutRef
  const timeoutPromise = new Promise<void>((resolve, reject) => {
    timeoutRef = setTimeout(() => {
      reject(
        new Error(`Timed out waiting for file ${path} (${currentAction}))`)
      )
    }, timeout || 60000)
  })
  const elements: string[] = []
  let current = path
  while (true) {

=>
        access(path, constants.F_OK)
          .then(() => true)
          .catch(() => false)
      if (!(await checkAccess())) {
        let resolveCheckAgain = () => {}
        const watcher = watch(dirname(path), () => {
          resolveCheckAgain(

    elements.push(current)
    const parent = dirname(current)
    if (parent === current) {
      break
    }
    current = parent
  }
  elements.reverse()
  try {
    for (const path of elements) {
      const checkAccess = ()


 { formatVariant } from './utils.js'

interface SampleSet {
  samples: number[]
  unit: string
  relativeTo?: string
}

interface BufferedSample {
  value: number
  unit: string
  relativeTo?: string
}

// Total attempts per variant are capped at this multiple of the requested
// `warmup + n`. Allows retrying flaky runs without burning unbounded time when
// every attempt fails.
const MAX_ATTEMPT_MULTIPLIER = 2

export async function runScenarios(
  scenarios: Scenario[],
  iface: Interface,
  options: { n?

me((scenario) => scenario.only)) {
    scenarios = scenarios.filter((scenario) => scenario.only)
  }
  scenarios = await fullIface.filterScenarios(scenarios)
  let totalFailedAttempts = 0
  let variantsWithRetries = 0
  let variantsShortOfTarget = 0
  let

: number; warmup?: number } = {}
): Promise<void> {
  const n = Math.max(1, Math.floor(options.n ?? 1))
  const warmup = Math.max(0, Math.floor(options.warmup ?? 0))
  const fullIface = intoFullInterface(iface)
  if (scenarios.so


hsTTest, mannWhitneyU } from './statistics.js'

function near(actual: number, expected: number, tol = 1e-6, label = '') {
  assert.ok(
    Math.abs(actual - expected) < tol,
    `${label}: expected ${expected}, got ${actual} (tol ${tol})`
  )
}

test('mean', () => {
  near(mean([1, 2, 3, 4, 5]), 3)
  near(mean([10]), 10)
})

test('quantile (linear interpolation, numpy/R type 7)', () => {
  // [1,2,3,4,5] with q=0.5 → 3, q=0.9 → 4.6
  near(quantile([1, 2, 3, 4, 5], 0.5), 3)
  near(quantile([1, 2, 3, 4, 5], 0

.9), 4.6)
  // sorts internally
  near(quantile([5, 3, 1, 2, 4], 0.5), 3)
  // single sample
  near(quantile([42], 0.9), 42)
})

test("Welch's t-test: small samples", () => {
  // Hand-verified: means 2 and 3, both sample varianc


('../util/stats')

// Location of the native binary that the workflow copies into the action dir.
// From src/run/index.js → .github/actions/next-stats-action/native
const nativeBinaryDir = path.join(__dirname, '../../native')

// Sum the size of all *.node files in the action's native/ directory.
async function getSwcBinarySize() {
  try {
    const entries = await fs.readdir(nativeBinaryDir)
    let total = 0
    let found = 0
    for (const entry of entries) {
      if (!entry.endsWith('.node')) continue

er(`Unable to measure SWC binary size: ${err.message}`)
    return null
  }
}

// Number of iterations for build benchmarks to get stable median
const BUILD_BENCHMARK_ITERATIONS = 5

// Bundler configurations for dual-bundler benchmarking
const BUNDLERS =

      const stat = await fs.stat(path.join(nativeBinaryDir, entry))
      if (stat.isFile()) {
        total += stat.size
        found++
      }
    }
    if (found === 0) return null
    return total
  } catch (err) {
    logg


github from '@actions/github'
import * as core from '@actions/core'

const LABELS = {
  VERIFY_CANARY: 'please verify canary',
  ADD_REPRODUCTION: 'please add a complete reproduction',
  SIMPLIFY_REPRODUCTION: 'please simplify reproduction',
  NEEDS_TRIAGE: 'type: needs triage',
}

const labelsRequireUserInput = [
  LABELS.VERIFY_CANARY,
  LABELS.ADD_REPRODUCTION,
  LABELS.SIMPLIFY_REPRODUCTION,
]

function assertNotNullable<T>(value: T): asserts value is NonNullable<T> {
  if (value === undefined || value

comment)

    if (!process.env.GITHUB_TOKEN) return

    const client = github.getOctokit(process.env.GITHUB_TOKEN).rest
    const issueCommon = { ...repo, issue_number: issue.number }

    const issueLabels: string[] = issue.labels.map((label: any) => lab

=== null)
    throw new Error('Unexpected nullable value')
}

async function run() {
  try {
    const { payload, repo } = github.context
    const { issue, comment } = payload

    assertNotNullable(issue)
    assertNotNullable(


 Usage: node aggregate-results.js <results-dir>
 *
 * Expects JSON files named pr-stats-*.json in the results directory
 */

const path = require('path')
const fs = require('fs/promises')
const { existsSync } = require('fs')
const addComment = require('./add-comment')
const logger = require('./util/logger')

async function main() {
  const resultsDir = process.argv[2] || process.cwd()

  logger(`Aggregating results from: ${resultsDir}`)

  // Find all pr-stats-*.json files
  const files = await fs.readdir(r

'No pr-stats-*.json files found - this may be a docs-only change')
    process.exit(0)
  }

  logger(`Found ${statsFiles.length} results files: ${statsFiles.join(', ')}`)

  // Load all results
  const allData = []
  for (const file of statsFiles) {
    co

esultsDir)
  const statsFiles = files.filter(
    (f) => f.startsWith('pr-stats-') && f.endsWith('.json')
  )

  if (statsFiles.length === 0) {
    // This can happen for docs-only changes where stats jobs are skipped
    logger(


rom 'node:fs'
import type { Sandbox } from '@vercel/agent-eval'

/**
 * Install the locally-built Next.js into the sandbox.
 *
 * The tarball path comes from run-evals.js via NEXT_EVAL_TARBALL, the same
 * env-var handoff that run-tests.js uses for NEXT_TEST_PKG_PATHS. We hard-fail
 * if it's missing rather than falling back to npm — silently testing the
 * published canary instead of your local build defeats the point.
 */
export async function installNextJs(sandbox: Sandbox): Promise<void> {
  const tarba

types writeFiles as Record<string, string>
    // but the runtime accepts Buffer. Tarballs are binary; can't send as string.
    'next.tgz': readFileSync(tarball),
  })
  const { exitCode, stderr } = await sandbox.runCommand('npm', [
    'install',
    './

ll = process.env.NEXT_EVAL_TARBALL
  if (!tarball) {
    throw new Error(
      'NEXT_EVAL_TARBALL not set. Run evals via `pnpm eval` from the repo root.'
    )
  }
  await sandbox.writeFiles({
    // @ts-expect-error — upstream


e client'
import * as React from 'react'
import Box from '@mui/material/Box'
import FormControl from '@mui/material/FormControl'
import InputLabel from '@mui/material/InputLabel'
import MenuItem from '@mui/material/MenuItem'
import Select from '@mui/material/Select'
import { useColorScheme } from '@mui/material/styles'

export default function ModeSwitch() {
  const { mode, setMode } = useColorScheme()
  if (!mode) {
    return null
  }
  return (
    <Box
      sx={{
        display: 'flex',
        justif

          value={mode}
          onChange={(event) => setMode(event.target.value as typeof mode)}
          label="Theme"
        >
          <MenuItem value="system">System</MenuItem>
          <MenuItem value="light">Light</MenuItem>
          <MenuItem

yContent: 'flex-end',
        mt: 1,
        p: 1,
      }}
    >
      <FormControl>
        <InputLabel id="mode-select-label">Theme</InputLabel>
        <Select
          labelId="mode-select-label"
          id="mode-select"


const Form = ({ formId, petForm, forNewPet = true }) => {
  const router = useRouter()
  const contentType = 'application/json'
  const [errors, setErrors] = useState({})
  const [message, setMessage] = useState('')

  const [form, setForm] = useState({
    name: petForm.name,
    owner_name: petForm.owner_name,
    species: petForm.species,
    age: petForm.age,
    poddy_trained: petForm.poddy_trained,
    diet: petForm.diet,
    image_url: petForm.image_url,
    likes: petForm.likes,
    dislikes: petFo

method: 'PUT',
        headers: {
          Accept: contentType,
          'Content-Type': contentType,
        },
        body: JSON.stringify(form),
      })

      // Throw error with status code in case Fetch API req failed
      if (!res.ok) {

rm.dislikes,
  })

  /* The PUT method edits an existing entry in the mongodb database. */
  const putData = async (form) => {
    const { id } = router.query

    try {
      const res = await fetch(`/api/pets/${id}`, {


nk'
import dbConnect from '../lib/dbConnect'
import Pet from '../models/Pet'

const Index = ({ pets }) => (
  <>
    {/* Create a card for each pet */}
    {pets.map((pet) => (

{pet.name}

{pet.name}

Owner: {pet.owner_name}

            {/* Extra Pet Info: Lik

))}

Dislikes

                {pet.dislikes.map((data, index) => (

{data}

es and Dislikes */}

Likes

                {pet.likes.map((data, index) => (

{data}


t {
  NodeModuleTracePlugin,
  NodeModuleTracePluginOptions,
} from '@vercel/webpack-nft'
import type { NextConfig } from 'next'

export function createNodeFileTrace(options?: NodeModuleTracePluginOptions) {
  return function withNodeFileTrace(config: NextConfig = {}) {
    const createWebpackConfig = config.webpack
    config.outputFileTracing = false
    config.webpack = (webpackConfig, context) => {
      const config =
        createWebpackConfig?.(webpackConfig, context) ?? webpackConfig
      if (cont

& !context.dev) {
        const plugin = new NodeModuleTracePlugin(options)
        if (config.plugins) {
          config.plugins.push(plugin)
        } else {
          config.plugins = [plugin]
        }
      }

      return config
    }
    return con


interfaces/compose.js'
import { groupRows, printComparison } from './compare.js'
import { readSnapshot, resolveCompareTarget } from './snapshot.js'
import { pathToFileURL } from 'url'

const SUBCOMMANDS = new Set(['run', 'compare'])

;(async () => {
  // Subcommand dispatch. `devlow-bench run [opts] scenario.mjs` and
  // `devlow-bench compare <a.csv> <b.csv>` are the explicit forms. A bare
  // `devlow-bench <script>` falls through to legacy run-mode for back-compat.
  const argv = process.argv.slice(2)

  }
  await runRunSubcommand(rest)
})().catch((e) => {
  console.error(e.stack)
  process.exit(1)
})

async function runCompareSubcommand(argv: string[]): Promise<void> {
  const args = minimist(argv, {
    alias: { '?': 'help', h: 'help' },
  })
  if (ar

const first = argv[0]
  const sub = first && SUBCOMMANDS.has(first) ? first : 'run'
  const rest = first && SUBCOMMANDS.has(first) ? argv.slice(1) : argv

  if (sub === 'compare') {
    await runCompareSubcommand(rest)
    return


e.js'

export interface Command {
  ok(): Promise<void>
  kill(): Promise<void>
  end(): Promise<number>
  waitForOutput(
    regex: RegExp,
    options?: {
      timeoutMs?: number
    }
  ): Promise<RegExpMatchArray>
  reportMemUsage(
    metricName: string,
    options: {
      relativeTo?: string | typeof PREVIOUS
      scenario?: string
      props?: Record<string, string | number | null>
    }
  ): Promise<void>
  stdout: string
  stderr: string
  output: string
}

const shellOutput = !!process.env.SH

ildProcess) {
    process.stdout?.pipe(split2()).on('data', (data) => {
      const str = data.toString()
      this.stdout += str + '\n'
      this.output += str + '\n'
      if (shellOutput) {
        console.log(`[STDOUT] ${str}`)
      }
      if (this

ELL_OUTPUT

class CommandImpl {
  stdout: string = ''
  stderr: string = ''
  output: string = ''
  outputCursor: number = 0
  exitPromise: Promise<number>
  waitingForOutput: (() => void)[] = []
  constructor(private process: Ch


 string; job: Job }> {
  console.log(
    `fetchJobLogsFromWorkflow ${job.name}: Checking test results for the job`
  )

  // downloadJobLogsForWorkflowRun returns a redirect to the actual logs
  // The returned URL is valid (without any additional auth) for 1 minute
  const jobLogRedirectResponse =
    await octokit.rest.actions.downloadJobLogsForWorkflowRun({
      accept: 'application/vnd.github.v3+json',
      ...context.repo,
      job_id: job.id,
    })

  console.log(
    `fetchJobLogsFromWorkflow ${

ub.v3+json',
    },
  })

  console.log(
    `fetchJobLogsFromWorkflow ${job.name}: Logs response status ${jobLogsResponse.status}`
  )

  if (!jobLogsResponse.ok) {
    throw new Error(
      `Failed to get logsUrl, got status ${jobLogsResponse.status}`

job.name}: Trying to get logs from redirect url ${jobLogRedirectResponse.url}`
  )

  // fetch the actual logs
  const jobLogsResponse = await fetch(jobLogRedirectResponse.url, {
    headers: {
      Accept: 'application/vnd.gith


 from '@mui/material/Container'
import Typography from '@mui/material/Typography'
import Box from '@mui/material/Box'
import Link from '@mui/material/Link'
import ProTip from './components/ProTip'
import Copyright from './components/Copyright'

export default function Home() {
  return (
    <Container maxWidth="lg">
      <Box
        sx={{
          my: 4,
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
        }}
      >

mb: 2 }}>
          Material UI - Next.js App Router example in TypeScript
        </Typography>
        <Link href="/about" color="secondary">
          Go to the about page
        </Link>
        <ProTip />
        <Copyright />
      </Box>
    </Conta

<Typography variant="h4" component="h1" sx={{


 } from 'next/router'
import Link from 'next/link'
import dbConnect from '../../lib/dbConnect'
import Pet from '../../models/Pet'

/* Allows you to view pet card info and delete pet card*/
const PetPage = ({ pet }) => {
  const router = useRouter()
  const [message, setMessage] = useState('')
  const handleDelete = async () => {
    const petID = router.query.id

    try {
      await fetch(`/api/pets/${petID}`, {
        method: 'Delete',
      })
      router.push('/')
    } catch (error) {
      setMessa

>

{pet.name}

Owner: {pet.owner_name}

          {/* Extra Pet Info: Likes and Dislikes */}

Likes

ge('Failed to delete the pet.')
    }
  }

  return (

{pet.name}

        <div className="main-content"


ose from './interfaces/compose.js'
import { runScenarios } from './runner.js'

let currentScenarios: Scenario[] | null = null

export function setCurrentScenarios(scenarios: Scenario[] | null): void {
  currentScenarios = scenarios
}

export function describe<P>(
  name: string,
  config: ConfigFor<P>,
  fn: (props: P) => Promise<void>
): void {
  if (currentScenarios === null) {
    const scenarios = (currentScenarios = [])

    Promise.resolve().then(async () => {
      const ifaceNames = process.env.INTE

.js`)
        } catch (e) {
          iface = await import(ifaceName)
        }
        iface = (iface && (iface as any).default) || iface
        if (typeof iface === 'function') {
          iface = await iface()
        }
        if (!iface) {

RFACE || 'interactive,console'
      const ifaces = []
      for (const ifaceName of ifaceNames.split(',').map((s) => s.trim())) {
        let iface: unknown
        try {
          iface = await import(`./interfaces/${ifaceName}


 extends string
    ? string[]
    : P[K] extends number
      ? number[]
      : P[K] extends boolean
        ? boolean[] | boolean
        : never
}

export interface Scenario {
  name: string
  config: Record<string, (string | number | boolean)[]>
  only: boolean
  fn: (props: Record<string, string | number | boolean>) => Promise<void>
}

export interface ScenarioVariant {
  scenario: Scenario
  props: Record<string, string | number | boolean>
}

export interface CurrentScenario {
  scenario: ScenarioVar

t: string
  relativeTo?: string
  mean: number
  p50: number
  p90: number
}

export interface FullInterface {
  filterScenarios(scenarios: Scenario[]): Promise<Scenario[]>
  filterScenarioVariants(
    scenarioVariants: ScenarioVariant[]
  ): Promise<Scen

iant
  iface: FullInterface

  measurements: Map<
    string,
    {
      value: number
      unit: string
    }
  >
}

export type Interface = Partial<FullInterface>

export interface VariantStatistic {
  samples: number[]
  uni


 color: 'text.secondary' }}>
      <LightBulbIcon sx={{ mr: 1, verticalAlign: 'middle' }} />
      {'Pro tip: See more '}
      <Link href="https://mui.com/material-ui/getting-started/templates/">
        templates
      </Link>
      {' in the Material UI

p() {
  return (
    <Typography sx={{ mt: 6, mb: 3,


er (scenario, variant, metric, sample). Long-format so the same
// file can store mixed-unit metrics (ms, MB, requests, ...) without sparse
// columns. Consumers can filter by `unit` and pivot downstream.
export interface SnapshotRow {
  timestamp: string
  scenario: string
  variant: string
  metric: string
  sample_idx: number
  value: number
  unit: string
  relative_to: string
  git_sha: string
  git_branch: string
}

const COLUMNS: (keyof SnapshotRow)[] = [
  'timestamp',
  'scenario',
  'variant',
  '

em-safe, lexicographic-sortable.
  const stamp = now.toISOString().replace(/[:.]/g, '-').replace(/Z$/, 'Z')
  return resolve(join(dir, `${stamp}.csv`))
}

export async function writeSnapshot(
  path: string,
  rows: SnapshotRow[]
): Promise<void> {
  await

metric',
  'sample_idx',
  'value',
  'unit',
  'relative_to',
  'git_sha',
  'git_branch',
]

export function defaultSnapshotPath(
  dir: string = DEFAULT_SNAPSHOT_DIR,
  now: Date = new Date()
): string {
  // ISO-ish, filesyst


esponse Work
 *
 * Tests whether the agent uses after() from next/server to schedule work
 * (logging, analytics) after the response is sent, without blocking it.
 *
 * Tricky because agents use fire-and-forget promises, setTimeout, or
 * Vercel-specific waitUntil() instead of the built-in after() API.
 */

import { expect, test } from 'vitest'
import { readFileSync, existsSync, readdirSync } from 'fs'
import { join } from 'path'

function readAppFiles(): string {
  const appDir = join(process.cwd(), 'app')

in(appDir, f), 'utf-8')).join('\n')
}

test('Component imports after from next/server', () => {
  const content = readAppFiles()

  expect(content).toMatch(/import.*after.*from\s+['"]next\/server['"]/)
})

test('Component uses after() with callback', () =>

  if (!existsSync(appDir)) return ''
  const entries = readdirSync(appDir, { recursive: true }) as string[]
  const files = entries.filter((f) => f.endsWith('.tsx') || f.endsWith('.ts'))
  return files.map((f) => readFileSync(jo


eTracePluginOptions {
  cwd?: string
  // relative to cwd
  contextDirectory?: string
  // additional PATH environment variable to use for spawning the `node-file-trace` process
  path?: string
  // control the maximum number of files that are passed to the `node-file-trace` command
  // default is 128
  maxFiles?: number
  // log options
  log?: {
    all?: boolean
    detail?: boolean
    // Default is `error`
    level?:
      | 'bug'
      | 'fatal'
      | 'error'
      | 'warning'
      | 'hint'

nstructor(private readonly options?: NodeModuleTracePluginOptions) {}

  apply(compiler: Compiler) {
    compiler.hooks.compilation.tap(
      NodeModuleTracePlugin.PluginName,
      (compilation) => {
        compilation.hooks.processAssets.tap(

 | 'note'
      | 'suggestions'
      | 'info'
  }
}

export class NodeModuleTracePlugin implements WebpackPluginInstance {
  static PluginName = 'NodeModuleTracePlugin'

  private readonly chunksToTrace = new Set<string>()

  co


      arguments: args,
      };
    },
    peg$c31 = "{",
    peg$c32 = peg$literalExpectation("{", false),
    peg$c33 = "}",
    peg$c34 = peg$literalExpectation("}", false),
    peg$c35 = function (head, tail) {
      return {
        type: "scalar_object_expression",
        properties: head ? [head, ...tail] : [],
      };
    },
    peg$c36 = "[",
    peg$c37 = peg$literalExpectation("[", false),
    peg$c38 = "]",
    peg$c39 = peg$literalExpectation("]", false),
    peg$c40 = function (elements) {

ined_constant" };
    },
    peg$c44 = function () {
      return { type: "null_constant" };
    },
    peg$c45 = function () {
      return {
        type: "boolean_constant",
        value: false,
      };
    },
    peg$c46 = function () {
      return

     return {
        type: "scalar_array_expression",
        elements,
      };
    },
    peg$c41 = "undefined",
    peg$c42 = peg$literalExpectation("undefined", false),
    peg$c43 = function () {
      return { type: "undef


;
var b = 4;
var b = 5;
var b = 6;
var b = c;
var c = 7;
var c = 8;
var c = 9;
var c = a;

// cached
var x = a;
var x = b;
var x = c;
var y = a;
var y = b;
var y = c;
var z = a;
var z = b;
var z = c;

// chaining
var y = x;
var z = y;
var z1 = z;
var z2 = z1;
var z3 = z2;
var z4 = z3;
var z5 = z4;
var z6 = z5;
var z7 = z6;
var z8 = z7;
var z9 = z8;

// forking
var f11 = () => () => () => () => () => 1;
var f11 = () => () => () => () => () => 2;
var f12 = () => () => () => () => () => 2;
var f12 = () => () =


ns) {
      // Convert to byte array
      if (message.constructor == String)
        if (options && options.encoding === "binary")
          message = bin.stringToBytes(message);
        else message = utf8.stringToBytes(message);
      else if (isBuffer(message))
        message = Array.prototype.slice.call(message, 0);
      else if (!Array.isArray(message)) message = message.toString();
      // else, assume byte array already

      var m = crypt.bytesToWords(message),
        l = message.length * 8,


 inferred as not having non-root assignments
export function named_function_export_const_after_eval() {
}

if (true) {
  named_function_export_const_after_eval = 2
}
// should be inferred as not having non-root assignments
export default function default_function_export_const_after_eval() {

}

for (let i = 0; i < 10; i++) {
  d1 = 2
}
// should be inferred as not having non-root assignments
export let named_let_export_const_after_eval = 2

// ditto
export const named_const_export_const_after_eval = 3

// s

eval_2 = 1
export {named_let_export_not_const_after_eval as e4, named_let_export_const_after_eval_2}

named_let_export_const_after_eval_2 = 5
setTimeout(() => {
  named_let_export_not_const_after_eval = 5
}, 1);

export class ConstAfterEvalClass {
  named_

hould be inferred as not having non-root assignments
let named_let_export_const_after_eval_2
// should be inferred as having non-root assignments
let named_let_export_not_const_after_eval = 1
let named_let_export_not_const_after_


ettier-ignore
const object = { a: 1, 'b': 2, ['c']: 3 };

const a1 = object.a;
const a2 = object["a"];
const b1 = object.b;
const b2 = object["b"];
const c1 = object.c;
const c2 = object["c"];
const d1 = object.d;
const d2 = object["d"];

const object_spread = { a: 11, ...object, b: 22 };

const a3 = object_spread.a;
const b3 = object_spread.b;
const c3 = object_spread.c;
const d3 = object_spread.d;

// prettier-ignore
const { a: a4, 'b': b4, ['c']: c4, d: d4 } = object;
const { a, b, c, d } = object;

cons

 a5 = unknown_spread.a;
const b5 = unknown_spread.b;
const c5 = unknown_spread.c;

const object2 = { a: 1, [global]: 2, c: 3, [global]: 4, e: 5 };
const a6 = object2.a;
const b6 = object2.b;
const c6 = object2.c;
const d6 = object2.d;
const e6 = object2.e;

t unknown_spread = { a: 1, ...global, b: 2 };

const


ort { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
    static async getInitialProps(ctx) {
        const initialProps = await Document.getInitialProps(ctx);
        return {
            ...initialProps,
            styles: _jsxs(_Fragment, {
                children: [
                    initialProps.styles,
                    _jsx("style", {

(Html, {
            children: [
                _jsx(Head, {}),
                _jsxs("body", {
                    children: [
                        _jsx(Main, {}),
                        _jsx(NextScript, {})
                    ]
                })

dangerouslySetInnerHTML: {
                            __html: `html { background: hotpink; }`
                        }
                    })
                ]
            })
        };
    }
    render() {
        return _jsxs


peof exports === 'object' && typeof module !== 'undefined') {
    module.exports = f()
  } else if (typeof define === 'function' && define.amd) {
    define([], f)
  } else {
    var g
    if (typeof window !== 'undefined') {
      g = window
    } else if (typeof global !== 'undefined') {
      g = global
    } else if (typeof self !== 'undefined') {
      g = self
    } else {
      g = this
    }
    g.bugsnag = f()
  }
})(function () {
  var define, module, exports
  return (function () {
    function r

var a = new Error("Cannot find module '" + i + "'")
            throw ((a.code = 'MODULE_NOT_FOUND'), a)
          }
          var p = (n[i] = { exports: {} })
          e[i][0].call(
            p.exports,
            function (r) {
              var n =

(e, n, t) {
      function o(i, f) {
        if (!n[i]) {
          if (!e[i]) {
            var c = 'function' == typeof require && require
            if (!f && c) return c(i, !0)
            if (u) return u(i, !0)


  'node_modules/object-assign/index.js',
  'node_modules/object-assign/package.json',
  'node_modules/prop-types/checkPropTypes.js',
  'node_modules/prop-types/factoryWithThrowingShims.js',
  'node_modules/prop-types/factoryWithTypeCheckers.js',
  'node_modules/prop-types/index.js',
  'node_modules/prop-types/lib/ReactPropTypesSecret.js',
  'node_modules/prop-types/lib/has.js',
  'node_modules/prop-types/node_modules/react-is/cjs/react-is.development.js',
  'node_modules/prop-types/node_modules/react-is/cjs

evelopment.js',
  'node_modules/react/cjs/react.production.min.js',
  'node_modules/react/index.js',
  'node_modules/react/package.json',
  'package.json',
  'test/unit/webpack-wrapper-strs-namespaces-large/content/guides/index.md',
  'test/unit/webpack-wr

/react-is.production.min.js',
  'node_modules/prop-types/node_modules/react-is/index.js',
  'node_modules/prop-types/node_modules/react-is/package.json',
  'node_modules/prop-types/package.json',
  'node_modules/react/cjs/react.d


 any

import type { Processor } from 'postcss'

// @ts-ignore
import postcss from '@vercel/turbopack/postcss'
// @ts-ignore
import importedConfig from 'CONFIG'
import { getReadEnvVariables, toPath, type TransformIpc } from './transforms'

let processor: Processor | undefined

export const init = async (ipc: TransformIpc) => {
  let config = importedConfig
  if (typeof config === 'function') {
    config = await config({ env: 'development' })
  }
  if (typeof config === 'undefined') {
    throw new Error(

 | any) => {
      if (Array.isArray(plugin)) {
        return plugin
      } else if (typeof plugin === 'string') {
        return [plugin, {}]
      } else {
        return plugin
      }
    })
  } else if (typeof config.plugins === 'object') {
    plug

    'PostCSS config is undefined (make sure to export an function or object from config file)'
    )
  }
  let plugins: any[]
  if (Array.isArray(config.plugins)) {
    plugins = config.plugins.map((plugin: [string, any] | string


ode.js bundle (runtime + module chunks + entry
 * chunk) and sends the chunk code via IPC. This evaluator loads them in memory
 * using vm.compileFunction, wiring up a minimal CJS require that resolves
 * relative paths against an in-memory chunk map and delegates external packages
 * to the real Node.js require.
 */

import { createRequire } from 'module'
import realFs from 'fs'
import path from 'path'
import { Readable } from 'stream'
import vm from 'vm'

// Create a real Node.js require function rooted a

rface ImportModuleResult {
  entryPath: string
  chunks: Array<{
    path: string
    code?: string
    binary?: string
    sourceMap?: string
  }>
}

export function evaluateBundle(result: ImportModuleResult): any {
  const chunkMap = new Map<string, stri

t the project directory.
// This bypasses Turbopack's module analysis (which can't handle dynamic
// require calls) while still resolving npm packages correctly.
const nodeRequire = createRequire(process.cwd() + '/')

export inte


_nccwpck_require__.ab = __dirname + "/";

var n = "<unknown>";
export function parse(e) {
  var r = e.split("\n");
  return r.reduce(function (e, r) {
    var n =
      parseChrome(r) ||
      parseWinjs(r) ||
      parseGecko(r) ||
      parseNode(r) ||
      parseJSC(r);
    if (n) {
      e.push(n);
    }
    return e;
  }, []);
}
var a =
  /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
var l = /\((\S*)(?::(\d+)

 null) {
    r[2] = i[1];
    r[3] = i[2];
    r[4] = i[3];
  }
  return {
    file: !u ? r[2] : null,
    methodName: r[1] || n,
    arguments: u ? [r[2]] : [],
    lineNumber: r[3] ? +r[3] : null,
    column: r[4] ? +r[4] : null,
  };
}
var u =
  /^\s*at

)(?::(\d+))\)/;
function parseChrome(e) {
  var r = a.exec(e);
  if (!r) {
    return null;
  }
  var u = r[2] && r[2].indexOf("native") === 0;
  var t = r[2] && r[2].indexOf("eval") === 0;
  var i = l.exec(r[2]);
  if (t && i !=


   length: number
    }

export type Ipc<TIncoming, TOutgoing> = {
  recv(): Promise<TIncoming>
  send(message: TOutgoing): Promise<void>
  sendError(error: Error | string): Promise<never>
  sendReady(): Promise<void>
}

function createIpc<TIncoming, TOutgoing>(
  port: number
): Ipc<TIncoming, TOutgoing> {
  const socket = createConnection({
    port,
    host: '127.0.0.1',
  })

  /**
   * A writable stream that writes to the socket.
   * We don't write directly to the socket because we need to
   * handl

ocket.once('drain', cb)
      }
    },
    final(cb) {
      socket.end(cb)
    },
  })

  const packetQueue: Buffer[] = []
  const recvPromiseResolveQueue: Array<(message: TIncoming) => void> = []

  function pushPacket(packet: Buffer) {
    const recvPro

e backpressure and wait for the socket to be drained
   * before writing more data.
   */
  const socketWritable = new Writable({
    write(chunk, _enc, cb) {
      if (socket.write(chunk)) {
        cb()
      } else {
        s


} from '../error'

export const TEXT_ENCODER = new TextEncoder()
export const TEXT_DECODER = new TextDecoder()

export interface TaskMessage {
  taskId: number
  data: Uint8Array
}

export interface Binding {
  recvTaskMessageInWorker(workerId: number): Promise<TaskMessage>
  sendTaskMessage(msg: TaskMessage): Promise<void>
  workerCreated(workerId: number): void
}

// Export this, maybe in the future, we can add an implementation via web worker on browser
export class TaskChannel {
  static nextId = 1
  st

XT_ENCODER.encode(
        JSON.stringify({
          type: 'info',
          data: message,
        })
      ),
    })
  }

  async sendRequest(message: any) {
    const id = TaskChannel.nextId++
    let resolve, reject
    const promise = new Promise((re

atic requests = new Map()

  constructor(
    private binding: Binding,
    private taskId: number
  ) {}

  async sendInfo(message: any) {
    return await this.binding.sendTaskMessage({
      taskId: this.taskId,
      data: TE


f an array of little-endian words, and a bit length.
 */
function wordsToMd5(x, len) {
  /* append padding */
  x[len >> 5] |= 0x80 << len % 32;
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var i;
  var olda;
  var oldb;
  var oldc;
  var oldd;
  var a = 1732584193;
  var b = -271733879;
  var c = -1732584194;

  var d = 271733878;

  for (i = 0; i < x.length; i += 16) {
    olda = a;
    oldb = b;
    oldc = c;
    oldd = d;

    a = md5ff(a, b, c, d, x[i], 7, -680876936);
    d = md5ff(d, a, b, c, x[i +


(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}
"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-

ine-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity str

style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overl


tests_snapshot_scope-hoisting_split-shared_input_0-l1v8m._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/scope-hoisting/split-shared/input/x/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {

setTimeout(()=>__turbopack_context__.A("[project]/turbopack/crates/turbopack-tests/tests/snapshot/scope-hoisting/split-shared/input/x/inner.js [test] (ecmascript, async loader)"), 500);
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/scope-hoisting/split-shar

e.js [test] (ecmascript, async loader)"), 1000);
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/scope-hoisting/split-shared/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";

__turbopack_context__.s([]);
var _

ed/input/y/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {

setTimeout(()=>__turbopack_context__.A("[project]/turbopack/crates/turbopack-tests/tests/snapshot/scope-hoisting/split-shared/input/y/middl