File size: 1,700 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
import type { API, FileInfo } from 'jscodeshift'
import { createParserFromPath } from '../lib/parser'

const importToChange = 'ImageResponse'

export default function transformer(file: FileInfo, _api: API) {
  const j = createParserFromPath(file.path)

  // Find import declarations that match the pattern
  file.source = j(file.source)
    .find(j.ImportDeclaration, {
      source: {
        value: 'next/server',
      },
    })
    .forEach((path) => {
      const importSpecifiers = path.node.specifiers
      const importNamesToChange = importSpecifiers.filter(
        (specifier) => specifier.local.name === importToChange
      )
      const importsNamesRemained = importSpecifiers.filter(
        (specifier) => specifier.local.name !== importToChange
      )

      // If the import includes the specified import name, create a new import for it from 'next/og'

      if (importNamesToChange.length > 0) {
        // Replace the original import with the remaining specifiers
        // path.node.specifiers = remainingSpecifiers
        const newImportStatement = j.importDeclaration(
          importNamesToChange,
          j.stringLiteral('next/og')
        )
        path.insertBefore(newImportStatement)
      }
      if (importsNamesRemained.length > 0) {
        const remainingSpecifiers = importSpecifiers.filter(
          (specifier) => specifier.local.name !== importToChange
        )

        const nextServerRemainImportsStatement = j.importDeclaration(
          remainingSpecifiers,
          j.stringLiteral('next/server')
        )
        path.insertBefore(nextServerRemainImportsStatement)
      }
      j(path).remove()
    })
    .toSource()

  return file.source
}