File size: 2,453 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import type { IncomingMessage, ServerResponse } from 'http'
import type { DevToolsConfig } from '../dev-overlay/shared'

import { existsSync } from 'fs'
import { readFile, writeFile, mkdir } from 'fs/promises'
import { dirname, join } from 'path'

import { middlewareResponse } from './middleware-response'
import { devToolsConfigSchema } from '../shared/devtools-config-schema'
import { deepMerge } from '../shared/deepmerge'

const DEVTOOLS_CONFIG_FILENAME = 'next-devtools-config.json'
const DEVTOOLS_CONFIG_MIDDLEWARE_ENDPOINT = '/__nextjs_devtools_config'

export function devToolsConfigMiddleware({
  distDir,
  sendUpdateSignal,
}: {
  distDir: string
  sendUpdateSignal: (data: DevToolsConfig) => void
}) {
  const configPath = join(distDir, 'cache', DEVTOOLS_CONFIG_FILENAME)

  return async function devToolsConfigMiddlewareHandler(
    req: IncomingMessage,
    res: ServerResponse,
    next: () => void
  ): Promise<void> {
    const { pathname } = new URL(`http://n${req.url}`)

    if (pathname !== DEVTOOLS_CONFIG_MIDDLEWARE_ENDPOINT) {
      return next()
    }

    if (req.method !== 'POST') {
      return middlewareResponse.methodNotAllowed(res)
    }

    const currentConfig = await getDevToolsConfig(distDir)

    const chunks: Buffer[] = []
    for await (const chunk of req) {
      chunks.push(Buffer.from(chunk))
    }

    let body = Buffer.concat(chunks).toString('utf8')
    try {
      body = JSON.parse(body)
    } catch (error) {
      console.error('[Next.js DevTools] Invalid config body passed:', error)
      return middlewareResponse.badRequest(res)
    }

    const validation = devToolsConfigSchema.safeParse(body)
    if (!validation.success) {
      console.error(
        '[Next.js DevTools] Invalid config passed:',
        validation.error.message
      )
      return middlewareResponse.badRequest(res)
    }

    const newConfig = deepMerge(currentConfig, validation.data)
    await writeFile(configPath, JSON.stringify(newConfig, null, 2))

    sendUpdateSignal(newConfig)

    return middlewareResponse.noContent(res)
  }
}

export async function getDevToolsConfig(
  distDir: string
): Promise<DevToolsConfig> {
  const configPath = join(distDir, 'cache', DEVTOOLS_CONFIG_FILENAME)

  if (!existsSync(configPath)) {
    await mkdir(dirname(configPath), { recursive: true })
    await writeFile(configPath, JSON.stringify({}))
    return {}
  }

  return JSON.parse(await readFile(configPath, 'utf8'))
}