File size: 7,220 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import fs from 'fs/promises'
import path from 'path'

// NOTE: this should be updated if this loader file is moved.
const PACKAGE_ROOT = path.normalize(path.join(__dirname, '../../..'))
const TEMPLATE_FOLDER = path.join(__dirname, 'templates')
const TEMPLATES_ESM_FOLDER = path.normalize(
  path.join(__dirname, '../../dist/esm/build/templates')
)

/**
 * Load the entrypoint file from the ESM directory and performs string
 * replacements of the template variables specified in the `replacements`
 * argument.
 *
 * For non-string replacements, the template should use the
 * `declare const ${key}: ${type}` syntax. to ensure that the type is correct
 * and the typescript can compile. You may have to use `@ts-expect-error` to
 * handle replacement values that are related to imports.
 *
 * @param entrypoint the entrypoint to load
 * @param replacements string replacements to perform
 * @param injections code injections to perform
 * @param imports optional imports to insert or set to null
 * @returns the loaded file with the replacements
 */
export async function loadEntrypoint(
  entrypoint:
    | 'app-page'
    | 'app-route'
    | 'edge-app-route'
    | 'edge-ssr'
    | 'edge-ssr-app'
    | 'middleware'
    | 'pages'
    | 'pages-api',
  replacements: Record<`VAR_${string}`, string>,
  injections?: Record<string, string>,
  imports?: Record<string, string | null>
): Promise<string> {
  const filepath = path.resolve(
    path.join(TEMPLATES_ESM_FOLDER, `${entrypoint}.js`)
  )

  let file = await fs.readFile(filepath, 'utf8')

  // Update the relative imports to be absolute. This will update any relative
  // imports to be relative to the root of the `next` package.
  let count = 0
  file = file.replaceAll(
    /from '(\..*)'|import '(\..*)'/g,
    function (_, fromRequest, importRequest) {
      count++

      const relative = path
        .relative(
          PACKAGE_ROOT,
          path.resolve(TEMPLATE_FOLDER, fromRequest ?? importRequest)
        )
        // Ensure that we use linux style path separators for node.
        .replace(/\\/g, '/')

      // Verify that the relative import is relative to the `next` package. This
      // will catch cases where the constants at the top of the file were not
      // updated after the file was moved.
      if (!relative.startsWith('next/')) {
        throw new Error(
          `Invariant: Expected relative import to start with "next/", found "${relative}"`
        )
      }

      return fromRequest
        ? `from ${JSON.stringify(relative)}`
        : `import ${JSON.stringify(relative)}`
    }
  )

  // Verify that at least one import was replaced. It's the case today where
  // every template file has at least one import to update, so this ensures that
  // we don't accidentally remove the import replacement code or use the wrong
  // template file.
  if (count === 0) {
    throw new Error('Invariant: Expected to replace at least one import')
  }

  const replaced = new Set<string>()

  // Replace all the template variables with the actual values. If a template
  // variable is missing, throw an error.
  file = file.replaceAll(
    new RegExp(
      `${Object.keys(replacements)
        .map((k) => `'${k}'`)
        .join('|')}`,
      'g'
    ),
    (match) => {
      const key = JSON.parse(match.replace(/'/g, `"`))

      if (!(key in replacements)) {
        throw new Error(`Invariant: Unexpected template variable ${key}`)
      }

      replaced.add(key)

      return JSON.stringify(replacements[key])
    }
  )

  // Check to see if there's any remaining template variables.
  let matches = file.match(/VAR_[A-Z_]+/g)
  if (matches) {
    throw new Error(
      `Invariant: Expected to replace all template variables, found ${matches.join(
        ', '
      )}`
    )
  }

  // Check to see if any template variable was provided but not used.
  if (replaced.size !== Object.keys(replacements).length) {
    // Find the difference between the provided replacements and the replaced
    // template variables. This will let us notify the user of any template
    // variables that were not used but were provided.
    const difference = Object.keys(replacements).filter(
      (key) => !replaced.has(key)
    )

    throw new Error(
      `Invariant: Expected to replace all template variables, missing ${difference.join(
        ', '
      )} in template`
    )
  }

  // Replace the injections.
  const injected = new Set<string>()
  if (injections) {
    // Track all the injections to ensure that we're not missing any.
    file = file.replaceAll(
      new RegExp(`// INJECT:(${Object.keys(injections).join('|')})`, 'g'),
      (_, key) => {
        if (!(key in injections)) {
          throw new Error(`Invariant: Unexpected injection ${key}`)
        }

        injected.add(key)

        return `const ${key} = ${injections[key]}`
      }
    )
  }

  // Check to see if there's any remaining injections.
  matches = file.match(/\/\/ INJECT:[A-Za-z0-9_]+/g)
  if (matches) {
    throw new Error(
      `Invariant: Expected to inject all injections, found ${matches.join(
        ', '
      )}`
    )
  }

  // Check to see if any injection was provided but not used.
  if (injected.size !== Object.keys(injections ?? {}).length) {
    // Find the difference between the provided injections and the injected
    // injections. This will let us notify the user of any injections that were
    // not used but were provided.
    const difference = Object.keys(injections ?? {}).filter(
      (key) => !injected.has(key)
    )

    throw new Error(
      `Invariant: Expected to inject all injections, missing ${difference.join(
        ', '
      )} in template`
    )
  }

  // Replace the optional imports.
  const importsAdded = new Set<string>()
  if (imports) {
    // Track all the imports to ensure that we're not missing any.
    file = file.replaceAll(
      new RegExp(
        `// OPTIONAL_IMPORT:(\\* as )?(${Object.keys(imports).join('|')})`,
        'g'
      ),
      (_, asNamespace = '', key) => {
        if (!(key in imports)) {
          throw new Error(`Invariant: Unexpected optional import ${key}`)
        }

        importsAdded.add(key)

        if (imports[key]) {
          return `import ${asNamespace}${key} from ${JSON.stringify(
            imports[key]
          )}`
        } else {
          return `const ${key} = null`
        }
      }
    )
  }

  // Check to see if there's any remaining imports.
  matches = file.match(/\/\/ OPTIONAL_IMPORT:(\* as )?[A-Za-z0-9_]+/g)
  if (matches) {
    throw new Error(
      `Invariant: Expected to inject all imports, found ${matches.join(', ')}`
    )
  }

  // Check to see if any import was provided but not used.
  if (importsAdded.size !== Object.keys(imports ?? {}).length) {
    // Find the difference between the provided imports and the injected
    // imports. This will let us notify the user of any imports that were
    // not used but were provided.
    const difference = Object.keys(imports ?? {}).filter(
      (key) => !importsAdded.has(key)
    )

    throw new Error(
      `Invariant: Expected to inject all imports, missing ${difference.join(
        ', '
      )} in template`
    )
  }

  return file
}