File size: 3,613 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import fs from 'fs'
import path from 'path'
import crypto from 'crypto'
import { promisify } from 'util'
import globOriginal from 'next/dist/compiled/glob'
import { Sema } from 'next/dist/compiled/async-sema'
import type { NextConfigComplete } from '../server/config-shared'
import { getNextConfigEnv, getStaticEnv } from './static-env'

const glob = promisify(globOriginal)

export async function inlineStaticEnv({
  distDir,
  config,
}: {
  distDir: string
  config: NextConfigComplete
}) {
  const nextConfigEnv = getNextConfigEnv(config)
  const staticEnv = getStaticEnv(config)

  const serverDir = path.join(distDir, 'server')
  const serverChunks = await glob('**/*.{js,json,js.map}', {
    cwd: serverDir,
  })
  const clientDir = path.join(distDir, 'static')
  const clientChunks = await glob('**/*.{js,json,js.map}', {
    cwd: clientDir,
  })
  const manifestChunks = await glob('*.{js,json,js.map}', {
    cwd: distDir,
  })

  const inlineSema = new Sema(8)
  const nextConfigEnvKeys = Object.keys(nextConfigEnv).map((item) =>
    item.split('process.env.').pop()
  )

  const builtRegEx = new RegExp(
    `[\\w]{1,}(\\.env)?\\.(?:NEXT_PUBLIC_[\\w]{1,}${nextConfigEnvKeys.length ? '|' + nextConfigEnvKeys.join('|') : ''})`,
    'g'
  )
  const changedClientFiles: Array<{ file: string; content: string }> = []
  const filesToCheck = new Set<string>(
    manifestChunks.map((f) => path.join(distDir, f))
  )

  for (const [parentDir, files] of [
    [serverDir, serverChunks],
    [clientDir, clientChunks],
  ] as const) {
    await Promise.all(
      files.map(async (file) => {
        await inlineSema.acquire()
        const filepath = path.join(parentDir, file)
        const content = await fs.promises.readFile(filepath, 'utf8')
        const newContent = content.replace(builtRegEx, (match) => {
          let normalizedMatch = `process.env.${match.split('.').pop()}`

          if (staticEnv[normalizedMatch]) {
            return JSON.stringify(staticEnv[normalizedMatch])
          }
          return match
        })

        await fs.promises.writeFile(filepath, newContent)

        if (content !== newContent && parentDir === clientDir) {
          changedClientFiles.push({ file, content: newContent })
        }
        filesToCheck.add(filepath)
        inlineSema.release()
      })
    )
  }
  const hashChanges: Array<{
    originalHash: string
    newHash: string
  }> = []

  // hashes need updating for any changed client files
  for (const { file, content } of changedClientFiles) {
    // hash is 16 chars currently for all client chunks
    const originalHash = file.match(/([a-z0-9]{16})\./)?.[1] || ''

    if (!originalHash) {
      throw new Error(
        `Invariant: client chunk changed but failed to detect hash ${file}`
      )
    }
    const newHash = crypto
      .createHash('sha256')
      .update(content)
      .digest('hex')
      .substring(0, 16)

    hashChanges.push({ originalHash, newHash })

    const filepath = path.join(clientDir, file)
    const newFilepath = filepath.replace(originalHash, newHash)

    filesToCheck.delete(filepath)
    filesToCheck.add(newFilepath)

    await fs.promises.rename(filepath, newFilepath)
  }

  // update build-manifest and webpack-runtime with new hashes
  for (let file of filesToCheck) {
    const content = await fs.promises.readFile(file, 'utf-8')
    let newContent = content

    for (const { originalHash, newHash } of hashChanges) {
      newContent = newContent.replaceAll(originalHash, newHash)
    }
    if (content !== newContent) {
      await fs.promises.writeFile(file, newContent)
    }
  }
}