ronantakizawa/codereview-bench huggingface dataset:
Repository: nuxt/nuxt
File: packages/nuxt/test/render.bench.ts (TypeScript)

Code before:
import { fileURLToPath } from 'node:url'
import { rm } from 'node:fs/promises'
import { beforeAll, bench, describe, expect } from 'vitest'
import { join, normalize } from 'pathe'
import { withoutTrailingSlash } from 'ufo'
import { build, loadNuxt } from 'nuxt'
import { x } from 'tinyexec'

const basicTestFixtureDir = withoutTrailingSlash(normalize(fileURLToPath(new URL('../../../test/fixtures/basic', import.meta.url))))
const outputDir = fileURLToPath(new URL('../../../node_modules/.test/render', import.meta.url))

describe('render', () => {
  beforeAll(async () => {
    await rm(join(basicTestFixtureDir, 'node_modules/render/.nuxt'), { recursive: true, force: true })
    const nuxt = await loadNuxt({
      cwd: basicTestFixtureDir,
      ready: true,
      overrides: {
        buildDir: join(basicTestFixtureDir, 'node_modules/render/.nuxt'),
        nitro: {
          output: {
            dir: outputDir,
          },
        },
        sourcemap: false,
      },
    })
    nuxt.hook('nitro:build:before', (nitro) => {
      nitro.options.entry = fileURLToPath(new URL('./nitro/render-index', import.meta.url))
    })
    await build(nuxt)
    await nuxt.close()
  }, 200_000)

  bench('index route in the basic test fixture', async () => {
    const res = await x('node', [join(outputDir, 'server/index.mjs')], {
      nodeOptions: { stdio: 'pipe' },

Review comment (suggestion):
```suggestion
describe.todo('render', () => {
```


Code after:
import { fileURLToPath } from 'node:url'
import { rm } from 'node:fs/promises'
import { beforeAll, bench, describe, expect } from 'vitest'
import { join, normalize } from 'pathe'
import { withoutTrailingSlash } from 'ufo'
import { build, loadNuxt } from 'nuxt'
import { x } from 'tinyexec'

const basicTestFixtureDir = withoutTrailingSlash(normalize(fileURLToPath(new URL('../../../test/fixtures/basic', import.meta.url))))
const outputDir = fileURLToPath(new URL('../../../node_modules/.test/render', import.meta.url))

describe.todo('render', () => {
  beforeAll(async () => {
    await rm(join(basicTestFixtureDir, 'node_modules/render/.nuxt'), { recursive: true, force: true })
    const nuxt = await loadNuxt({
      cwd: basicTestFixtureDir,
      ready: true,
      overrides: {
        buildDir: join(basicTestFixtureDir, 'node_modules/render/.nuxt'),
        nitro: {
          output: {
            dir: outputDir,
          },
        },
        sourcemap: false,
      },
    })
    nuxt.hook('nitro:build:before', (nitro) => {
      nitro.options.entry = fileURLToPath(new URL('./nitro/render-index', import.meta.url))
    })
    await build(nuxt)
    await nuxt.close()
  }, 200_000)

  bench('index route in the basic test fixture', async () => {
    const res = await x('node', [join(outputDir, 'server/index.mjs')], {
      nodeOptions: { stdio: 'pipe' },
Repository: nuxt/nuxt
File: test/e2e/hmr.test.ts (TypeScript)

Code before:
import { readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { rm } from 'node:fs/promises'
import { isWindows } from 'std-env'
import { join } from 'pathe'
import { expect, test } from './test-utils'

const isWebpack = process.env.TEST_BUILDER === 'webpack' || process.env.TEST_BUILDER === 'rspack'

const fixtureDir = fileURLToPath(new URL('../fixtures-temp/hmr', import.meta.url))
const sourceDir = fileURLToPath(new URL('../fixtures/hmr', import.meta.url))

test.use({
  nuxt: {
    rootDir: fixtureDir,
    dev: true,
    setupTimeout: (isWindows ? 360 : 120) * 1000,
    env: { TEST: '1' },
    nuxtConfig: {
      test: true,
      builder: isWebpack ? 'webpack' : 'vite',
    },
  },
})

if (process.env.TEST_ENV === 'built' || isWindows) {

Review comment (suggestion):
```suggestion
import { readFileSync, renameSync, writeFileSync } from 'node:fs'
```


Code after:
import { readFileSync, renameSync, writeFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { rm } from 'node:fs/promises'
import { isWindows } from 'std-env'
import { join } from 'pathe'
import { expect, test } from './test-utils'
import { isBuilt, isWebpack } from '../matrix'

const fixtureDir = fileURLToPath(new URL('../fixtures-temp/hmr', import.meta.url))
const sourceDir = fileURLToPath(new URL('../fixtures/hmr', import.meta.url))

test.use({
  nuxt: {
    rootDir: fixtureDir,
    dev: true,
    setupTimeout: (isWindows ? 360 : 120) * 1000,
    env: { TEST: '1' },
    nuxtConfig: {
      test: true,
    },
  },
})

if (isBuilt || isWindows) {
  test.skip('Skipped: HMR tests are skipped on Windows or in built mode', () => {})
} else {
Repository: nuxt/nuxt
File: packages/nuxt/src/app/components/nuxt-error-boundary.vue (Vue)

Code before:
<template>
  <slot
    v-if="error"
    :error="error"
    :clear-error="clearError"
    name="error"
  />

  <slot
    v-else
    name="default"
  />
</template>

<script setup lang="ts">
import { onErrorCaptured, shallowRef } from 'vue'
import { useNuxtApp } from '../nuxt'
import { onNuxtReady } from '../composables/ready'

defineOptions({
  name: 'NuxtErrorBoundary',
  inheritAttrs: false,
})

const emit = defineEmits<{
  error: [error: unknown]
}>()

defineSlots<{
  error: (props: { error: Error | null, clearError: () => void }) => void

Review comment (suggestion):
```suggestion
    v-bind="{ error, clearError }"
```


Code after:
<template>
  <slot
    v-if="error"
    v-bind="{ error, clearError }"
    name="error"
  />

  <slot
    v-else
    name="default"
  />
</template>

<script setup lang="ts">
import { onErrorCaptured, shallowRef } from 'vue'
import { useNuxtApp } from '../nuxt'
import { onNuxtReady } from '../composables/ready'

defineOptions({
  name: 'NuxtErrorBoundary',
  inheritAttrs: false,
})

const emit = defineEmits<{
  error: [error: Error]
}>()

defineSlots<{
  error(props: { error: Error, clearError: () => void }): any
  default(): any
Repository: nuxt/nuxt
File: packages/nuxt/src/app/plugins/view-transitions.client.ts (TypeScript)

Code before:
  let abortTransition: undefined | (() => void)

  const resetTransitionState = () => {
    transition = undefined
    hasUAVisualTransition = false
    abortTransition = undefined
    finishTransition = undefined
  }

  window.addEventListener('popstate', (event) => {
    hasUAVisualTransition = event.hasUAVisualTransition
    if (hasUAVisualTransition) { transition?.skipTransition() }
  })

  const router = useRouter()

  router.beforeResolve(async (to, from) => {
    const viewTransitionMode = to.meta.viewTransition ?? defaultViewTransition
    const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches
    const prefersNoTransition = prefersReducedMotion && viewTransitionMode !== 'always'

    if (
      viewTransitionMode === false ||
      prefersNoTransition ||
      !isChangingPage(to, from) ||
      hasUAVisualTransition
    ) {
      return
    }

    const promise = new Promise<void>((resolve, reject) => {
      finishTransition = resolve
      abortTransition = reject
    })

    let changeRoute: () => void
    const ready = new Promise<void>(resolve => (changeRoute = resolve))

    transition = document.startViewTransition!(() => {
      changeRoute()
      return promise
    })

    transition.finished.then(resetTransitionState)

    await nuxtApp.callHook('page:view-transition:start', transition)

    return ready
  })

  nuxtApp.hook('vue:error', () => {

Review comment (suggestion):
```suggestion
      hasUAVisualTransition ||
      !isChangingPage(to, from)
```

Code after:
  let abortTransition: undefined | (() => void)

  const resetTransitionState = () => {
    transition = undefined
    hasUAVisualTransition = false
    abortTransition = undefined
    finishTransition = undefined
  }

  window.addEventListener('popstate', (event) => {
    hasUAVisualTransition = event.hasUAVisualTransition
    if (hasUAVisualTransition) { transition?.skipTransition() }
  })

  const router = useRouter()

  router.beforeResolve(async (to, from) => {
    const viewTransitionMode = to.meta.viewTransition ?? defaultViewTransition
    const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches
    const prefersNoTransition = prefersReducedMotion && viewTransitionMode !== 'always'

    if (
      viewTransitionMode === false ||
      prefersNoTransition ||
      hasUAVisualTransition ||
      !isChangingPage(to, from)
    ) {
      return
    }

    const promise = new Promise<void>((resolve, reject) => {
      finishTransition = resolve
      abortTransition = reject
    })

    let changeRoute: () => void
    const ready = new Promise<void>(resolve => (changeRoute = resolve))

    transition = document.startViewTransition!(() => {
      changeRoute()
      return promise
    })

    transition.finished.then(resetTransitionState)

    await nuxtApp.callHook('page:view-transition:start', transition)

    return ready
  })

  nuxtApp.hook('vue:error', () => {
Repository: nuxt/nuxt
File: packages/nuxt/src/core/builder.ts (TypeScript)

Code before:
      throw new Error('Could not load `@nuxt/webpack-builder`. You may need to add it to your project dependencies, following the steps in `https://github.com/nuxt/framework/pull/2812`.')
    }

    throw error
  }
}

async function loadBuilder (nuxt: Nuxt, builder: string): Promise<NuxtBuilder> {
  try {
    return await importModule(builder, { url: [directoryToURL(nuxt.options.rootDir), new URL(import.meta.url)] })
  } catch {
    throw new Error(`Loading \`${builder}\` builder failed. You can read more about the nuxt \`builder\` option at: \`https://nuxt.com/docs/api/nuxt-config#builder\``)
  }
}

function resolveDirectoriesToWatch (nuxt: Nuxt) {
  const pathsToWatch = new Set<string>()
  for (const layer of nuxt.options._layers) {
    const dir = layer.config.srcDir || layer.cwd
    if (!dir || isIgnored(dir)) { continue }

    pathsToWatch.add(dir.replace(/[^/]$/, '$&/'))
  }
  for (const pattern of nuxt.options.watch) {
    if (typeof pattern !== 'string') { continue }
    const path = dirname(resolve(nuxt.options.srcDir, pattern)) + '/'
    let shouldAdd = true
    for (const w of pathsToWatch) {
      if (w.startsWith(path)) {
        pathsToWatch.delete(w)
      }
      if (path.startsWith(w)) {
        shouldAdd = false
      }
    }
    if (shouldAdd) {
      pathsToWatch.add(path)
    }
  }
  return pathsToWatch
}


Review comment (suggestion):
Using `dirname` here will watch the parent directory of the resolved pattern rather than the pattern itself. You should watch the full resolved path (with a trailing slash if needed) instead of its parent.

Code after:
      throw new Error('Could not load `@nuxt/webpack-builder`. You may need to add it to your project dependencies, following the steps in `https://github.com/nuxt/framework/pull/2812`.')
    }

    throw error
  }
}

async function loadBuilder (nuxt: Nuxt, builder: string): Promise<NuxtBuilder> {
  try {
    return await importModule(builder, { url: [directoryToURL(nuxt.options.rootDir), new URL(import.meta.url)] })
  } catch {
    throw new Error(`Loading \`${builder}\` builder failed. You can read more about the nuxt \`builder\` option at: \`https://nuxt.com/docs/api/nuxt-config#builder\``)
  }
}

function resolvePathsToWatch (nuxt: Nuxt, opts: { parentDirectories?: boolean } = {}): Set<string> {
  const pathsToWatch = new Set<string>()
  for (const layer of nuxt.options._layers) {
    const dir = layer.config.srcDir || layer.cwd
    if (!dir || isIgnored(dir)) { continue }

    pathsToWatch.add(dir.replace(/[^/]$/, '$&/'))
  }
  for (const pattern of nuxt.options.watch) {
    if (typeof pattern !== 'string') { continue }
    const path = opts?.parentDirectories
      ? join(dirname(resolve(nuxt.options.srcDir, pattern)), '')
      : resolve(nuxt.options.srcDir, pattern)
    let shouldAdd = true
    for (const w of [...pathsToWatch]) {
      if (w.startsWith(path)) {
        pathsToWatch.delete(w)
      }
      if (path.startsWith(w)) {
        shouldAdd = false
      }
    }
    if (shouldAdd) {
      pathsToWatch.add(path)
    }
  }
  return pathsToWatch
}
Repository: nuxt/nuxt
File: packages/nuxt/src/core/builder.ts (TypeScript)

Code before:
    return await importModule(builder, { url: [directoryToURL(nuxt.options.rootDir), new URL(import.meta.url)] })
  } catch {
    throw new Error(`Loading \`${builder}\` builder failed. You can read more about the nuxt \`builder\` option at: \`https://nuxt.com/docs/api/nuxt-config#builder\``)
  }
}

function resolveDirectoriesToWatch (nuxt: Nuxt) {
  const pathsToWatch = new Set<string>()
  for (const layer of nuxt.options._layers) {
    const dir = layer.config.srcDir || layer.cwd
    if (!dir || isIgnored(dir)) { continue }

    pathsToWatch.add(dir.replace(/[^/]$/, '$&/'))
  }
  for (const pattern of nuxt.options.watch) {
    if (typeof pattern !== 'string') { continue }
    const path = dirname(resolve(nuxt.options.srcDir, pattern)) + '/'
    let shouldAdd = true
    for (const w of pathsToWatch) {
      if (w.startsWith(path)) {
        pathsToWatch.delete(w)
      }
      if (path.startsWith(w)) {
        shouldAdd = false
      }
    }
    if (shouldAdd) {
      pathsToWatch.add(path)
    }
  }
  return pathsToWatch
}


Review comment (suggestion):
Mutating `pathsToWatch` (deleting entries) while iterating can lead to skipped items or unpredictable behavior. Consider collecting items to remove in a separate array and deleting them after the loop.
```suggestion
    const itemsToDelete: string[] = [];
    for (const w of pathsToWatch) {
      if (w.startsWith(path)) {
        itemsToDelete.push(w);
      }
      if (path.startsWith(w)) {
        shouldAdd = false;
      }
    }
    for (const item of itemsToDelete) {
      pathsToWatch.delete(item);
    }
```

Code after:
    return await importModule(builder, { url: [directoryToURL(nuxt.options.rootDir), new URL(import.meta.url)] })
  } catch {
    throw new Error(`Loading \`${builder}\` builder failed. You can read more about the nuxt \`builder\` option at: \`https://nuxt.com/docs/api/nuxt-config#builder\``)
  }
}

function resolvePathsToWatch (nuxt: Nuxt, opts: { parentDirectories?: boolean } = {}): Set<string> {
  const pathsToWatch = new Set<string>()
  for (const layer of nuxt.options._layers) {
    const dir = layer.config.srcDir || layer.cwd
    if (!dir || isIgnored(dir)) { continue }

    pathsToWatch.add(dir.replace(/[^/]$/, '$&/'))
  }
  for (const pattern of nuxt.options.watch) {
    if (typeof pattern !== 'string') { continue }
    const path = opts?.parentDirectories
      ? join(dirname(resolve(nuxt.options.srcDir, pattern)), '')
      : resolve(nuxt.options.srcDir, pattern)
    let shouldAdd = true
    for (const w of [...pathsToWatch]) {
      if (w.startsWith(path)) {
        pathsToWatch.delete(w)
      }
      if (path.startsWith(w)) {
        shouldAdd = false
      }
    }
    if (shouldAdd) {
      pathsToWatch.add(path)
    }
  }
  return pathsToWatch
}
Repository: nuxt/nuxt
File: packages/nuxt/src/app/plugins/check-outdated-build.client.ts (TypeScript)

Code before:
import { FetchError } from 'ofetch'
import { defineNuxtPlugin } from '../nuxt'
import { getAppManifest } from '../composables/manifest'
import type { NuxtAppManifestMeta } from '../composables/manifest'
import { onNuxtReady } from '../composables/ready'
// @ts-expect-error virtual file
import { buildAssetsURL } from '#internal/nuxt/paths'
// @ts-expect-error virtual file
import { outdatedBuildInterval } from '#build/nuxt.config.mjs'

export default defineNuxtPlugin((nuxtApp) => {
  if (import.meta.test) { return }

  let timeout: NodeJS.Timeout

  async function getLatestManifest () {
    let currentManifest: NuxtAppManifestMeta | undefined
    try {
      currentManifest = await getAppManifest()
    } catch (e) {
      // The build is already outdated but the manifest is not cached
      if (!(e instanceof FetchError && (e.status === 404 || e.status === 403))) {
        throw e
      }
    }
    if (timeout) { clearTimeout(timeout) }

Review comment (suggestion):
```suggestion
import type { FetchError } from 'ofetch'
```

Code after:
import type { FetchError } from 'ofetch'
import { defineNuxtPlugin } from '../nuxt'
import { getAppManifest } from '../composables/manifest'
import type { NuxtAppManifestMeta } from '../composables/manifest'
import { onNuxtReady } from '../composables/ready'
// @ts-expect-error virtual file
import { buildAssetsURL } from '#internal/nuxt/paths'
// @ts-expect-error virtual file
import { outdatedBuildInterval } from '#build/nuxt.config.mjs'

export default defineNuxtPlugin((nuxtApp) => {
  if (import.meta.test) { return }

  let timeout: ReturnType<typeof setTimeout>

  async function getLatestManifest () {
    let currentManifest: NuxtAppManifestMeta | undefined
    try {
      currentManifest = await getAppManifest()
    } catch (e) {
      const err = e as FetchError | Error
      // The build is already outdated but the manifest was not cached
      if (!('status' in err && (err.status === 404 || err.status === 403))) {
        throw err
      }
    }
Repository: nuxt/nuxt
File: packages/nuxt/src/app/composables/once.ts (TypeScript)

Code before:
  if (!_key || typeof _key !== 'string') {
    throw new TypeError('[nuxt] [callOnce] key must be a string: ' + _key)
  }
  if (fn !== undefined && typeof fn !== 'function') {
    throw new Error('[nuxt] [callOnce] fn must be a function: ' + fn)
  }
  const nuxtApp = useNuxtApp()

  if (options?.mode === 'navigation') {
    const cleanups: Array<() => void> = []
    function callback () {
      nuxtApp.payload.once.delete(_key)
      for (const cleanup of cleanups) {
        cleanup()
      }
    }
    cleanups.push(nuxtApp.hooks.hook('page:start', callback), useRouter().beforeResolve(callback))
  }

  // If key already ran
  if (nuxtApp.payload.once.has(_key)) {
    if (import.meta.dev && _isHmrUpdating) {
      // Allow re-execution during HMR
    } else {
      return
    }
  }

  nuxtApp._once ||= {}
  nuxtApp._once[_key] ||= fn() || true
  await nuxtApp._once[_key]
  nuxtApp.payload.once.add(_key)
  delete nuxtApp._once[_key]
}

if (import.meta.hot) {
  import.meta.hot.on('vite:beforeUpdate', (payload) => {
    if (payload.updates.some((u: any) => u.type === 'js-update')) {
      _isHmrUpdating = true
    }
  })

  import.meta.hot.on('vite:afterUpdate', (payload) => {
    if (payload.updates.some((u: any) => u.type === 'js-update')) {
      _isHmrUpdating = false
    }
  })
}


Review comment (suggestion):
```suggestion
    // Allow re-execution during HMR
    if (!import.meta.dev || !_isHmrUpdating) {
      return
    }
```


Code after:
  if (!_key || typeof _key !== 'string') {
    throw new TypeError('[nuxt] [callOnce] key must be a string: ' + _key)
  }
  if (fn !== undefined && typeof fn !== 'function') {
    throw new Error('[nuxt] [callOnce] fn must be a function: ' + fn)
  }
  const nuxtApp = useNuxtApp()

  if (options?.mode === 'navigation') {
    const cleanups: Array<() => void> = []
    function callback () {
      nuxtApp.payload.once.delete(_key)
      for (const cleanup of cleanups) {
        cleanup()
      }
    }
    cleanups.push(nuxtApp.hooks.hook('page:start', callback), useRouter().beforeResolve(callback))
  }

  // If key already ran
  if (nuxtApp.payload.once.has(_key)) {
    // Allow re-execution during HMR
    if (!import.meta.dev || !_isHmrUpdating) {
      return
    }
  }

  nuxtApp._once ||= {}
  nuxtApp._once[_key] ||= fn() || true
  await nuxtApp._once[_key]
  nuxtApp.payload.once.add(_key)
  delete nuxtApp._once[_key]
}

if (import.meta.hot) {
  import.meta.hot.on('vite:beforeUpdate', (payload) => {
    if (payload.updates.some((u: any) => u.type === 'js-update')) {
      _isHmrUpdating = true
    }
  })

  import.meta.hot.on('vite:afterUpdate', (payload) => {
    if (payload.updates.some((u: any) => u.type === 'js-update')) {
      _isHmrUpdating = false
    }
  })
}
Repository: nuxt/nuxt
File: packages/nuxt/src/head/runtime/components.ts (TypeScript)

Code before:
import { defineComponent, getCurrentInstance, inject, onUnmounted, provide, reactive, watch } from 'vue'
import type { PropType, VNodeNormalizedChildren } from 'vue'
import type {
  BodyAttributes,
  HtmlAttributes,
  Noscript,
  Base as UnheadBase,
  Link as UnheadLink,
  Meta as UnheadMeta,
  Style as UnheadStyle,
} from '@unhead/vue/types'
import type {
  CrossOrigin,
  FetchPriority,
  HTTPEquiv,
  LinkRelationship,
  ReferrerPolicy,
  Target,
} from './types'
import { useHead } from '#app/composables/head'

interface HeadComponents {
  base?: UnheadBase | null
  bodyAttrs?: BodyAttributes | null
  htmlAttrs?: HtmlAttributes | null
  link?: (UnheadLink | null)[]

Review comment (suggestion):
```suggestion
import { defineComponent, getCurrentInstance, inject, onUnmounted, provide, reactive } from 'vue'
```

Code after:
import { defineComponent, getCurrentInstance, inject, onUnmounted, provide, reactive } from 'vue'
import type { PropType, VNodeNormalizedChildren } from 'vue'
import type {
  BodyAttributes,
  HtmlAttributes,
  Noscript,
  Base as UnheadBase,
  Link as UnheadLink,
  Meta as UnheadMeta,
  Style as UnheadStyle,
} from '@unhead/vue/types'
import type {
  CrossOrigin,
  FetchPriority,
  HTTPEquiv,
  LinkRelationship,
  ReferrerPolicy,
  Target,
} from './types'
import { useHead } from '#app/composables/head'

interface HeadComponents {
  base?: UnheadBase | null
  bodyAttrs?: BodyAttributes | null
  htmlAttrs?: HtmlAttributes | null
  link?: (UnheadLink | null)[]