File size: 9,531 Bytes
4514571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
diff --git a/packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js b/packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js
new file mode 100644
index 00000000..54ca42d2
--- /dev/null
+++ b/packages/next-codemod/lib/__tests__/upgrade-non-interactive.test.js
@@ -0,0 +1,277 @@
+/* global jest */
+
+jest.autoMockOff()
+
+const fs = require('fs')
+const os = require('os')
+const path = require('path')
+const { spawnSync } = require('child_process')
+
+const codemodRoot = path.resolve(__dirname, '../..')
+const tsx = path.resolve(codemodRoot, '../../node_modules/.bin/tsx')
+const projects = []
+
+// The verifier setup builds the base revision before applying a candidate patch.
+// Run a source snapshot of the current package so tests see candidate changes
+// instead of stale generated JavaScript while still reusing the prebuilt
+// transforms. Copy the whole package rather than assuming that an implementation
+// must live in bin/ and lib/: a CLI may legitimately import a new source folder,
+// a JavaScript-only helper, or package metadata added by the candidate.
+function createSourceCli() {
+  const root = fs.mkdtempSync(path.join(os.tmpdir(), 'next-codemod-cli-'))
+  projects.push(root)
+
+  const sourceFile = (file) => {
+    const relative = path.relative(codemodRoot, file)
+    const topLevel = relative.split(path.sep)[0]
+    if (topLevel === 'node_modules' || topLevel === 'transforms') return false
+
+    // Ignore a generated artifact only when its source sibling exists. This
+    // keeps candidate-authored JavaScript modules while ensuring tsx loads a
+    // changed TypeScript source file instead of JavaScript built from HEAD.
+    const sourceBase = file.replace(/(?:\.js(?:\.map)?|\.d\.ts(?:\.map)?)$/, '')
+    if (sourceBase !== file) {
+      if (fs.existsSync(`${sourceBase}.ts`)) return false
+      if (fs.existsSync(`${sourceBase}.tsx`)) return false
+    }
+    return true
+  }
+  fs.cpSync(codemodRoot, root, { recursive: true, filter: sourceFile })
+
+  for (const entry of ['node_modules', 'transforms']) {
+    fs.symlinkSync(
+      path.join(codemodRoot, entry),
+      path.join(root, entry),
+      'dir'
+    )
+  }
+
+  return path.join(root, 'bin', 'next-codemod.ts')
+}
+
+function writeJson(file, value) {
+  fs.mkdirSync(path.dirname(file), { recursive: true })
+  fs.writeFileSync(file, JSON.stringify(value, null, 2))
+}
+
+function createProject({
+  installedNext,
+  installedReact,
+  targetNext,
+  targetReact,
+  devScript,
+  pages = false,
+}) {
+  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'next-codemod-upgrade-'))
+  projects.push(dir)
+
+  writeJson(path.join(dir, 'package.json'), {
+    private: true,
+    scripts: { dev: devScript },
+    dependencies: {
+      next: installedNext,
+      react: installedReact,
+      'react-dom': installedReact,
+    },
+  })
+  writeJson(path.join(dir, 'package-lock.json'), {})
+  for (const dependency of ['next', 'react', 'react-dom']) {
+    writeJson(path.join(dir, 'node_modules', dependency, 'package.json'), {
+      name: dependency,
+      version: dependency === 'next' ? installedNext : installedReact,
+    })
+  }
+  if (pages) {
+    fs.mkdirSync(path.join(dir, 'pages'), { recursive: true })
+    fs.writeFileSync(
+      path.join(dir, 'pages', 'index.js'),
+      'export default () => null\n'
+    )
+  }
+
+  const fakeBin = path.join(dir, 'fake-bin')
+  fs.mkdirSync(fakeBin)
+  const npm = `#!/usr/bin/env node
+const fs = require('fs')
+const args = process.argv.slice(2)
+const query = args.find((arg) => arg.includes('@')) || ''
+if (args.includes('view')) {
+  if (query.startsWith('next@') && args.includes('version')) {
+    console.log(JSON.stringify(process.env.TEST_TARGET_NEXT))
+  } else if (query.startsWith('next@')) {
+    console.log(JSON.stringify({ version: process.env.TEST_TARGET_NEXT, peerDependencies: { react: process.env.TEST_REACT_RANGE } }))
+  } else {
+    console.log(JSON.stringify(process.env.TEST_TARGET_REACT))
+  }
+} else {
+  fs.appendFileSync(process.env.TEST_COMMAND_LOG, 'npm ' + args.join(' ') + '\\n')
+}
+`
+  const npx = `#!/usr/bin/env node
+require('fs').appendFileSync(process.env.TEST_COMMAND_LOG, 'npx ' + process.argv.slice(2).join(' ') + '\\n')
+`
+  for (const [name, contents] of [
+    ['npm', npm],
+    ['npx', npx],
+  ]) {
+    const file = path.join(fakeBin, name)
+    fs.writeFileSync(file, contents)
+    fs.chmodSync(file, 0o755)
+  }
+
+  return {
+    dir,
+    cli: createSourceCli(),
+    commandLog: path.join(dir, 'commands.log'),
+    env: {
+      ...process.env,
+      PATH: `${fakeBin}${path.delimiter}${process.env.PATH}`,
+      TEST_TARGET_NEXT: targetNext,
+      TEST_TARGET_REACT: targetReact,
+      TEST_REACT_RANGE: `^${targetReact}`,
+      TEST_COMMAND_LOG: path.join(dir, 'commands.log'),
+      FORCE_COLOR: '0',
+    },
+  }
+}
+
+function runUpgrade(project, args, { tty = false, input } = {}) {
+  if (!tty) {
+    return spawnSync(tsx, [project.cli, 'upgrade', ...args], {
+      cwd: project.dir,
+      env: project.env,
+      encoding: 'utf8',
+      timeout: 15_000,
+    })
+  }
+
+  const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`
+  const command = [tsx, project.cli, 'upgrade', ...args].map(quote).join(' ')
+  return spawnSync('script', ['-q', '-e', '-c', command, '/dev/null'], {
+    cwd: project.dir,
+    env: project.env,
+    encoding: 'utf8',
+    timeout: 15_000,
+    input,
+  })
+}
+
+function outputOf(result) {
+  return `${result.stdout || ''}\n${result.stderr || ''}`
+}
+
+afterEach(() => {
+  while (projects.length) {
+    fs.rmSync(projects.pop(), { recursive: true, force: true })
+  }
+})
+
+test('upgrade help exposes both non-interactive option spellings', () => {
+  const cli = createSourceCli()
+  const result = spawnSync(tsx, [cli, 'upgrade', '--help'], {
+    encoding: 'utf8',
+    timeout: 15_000,
+  })
+
+  expect(result.status).toBe(0)
+  expect(outputOf(result)).toMatch(/-y, --yes\b/)
+})
+
+test('TTY use without --yes remains interactive', () => {
+  const project = createProject({
+    installedNext: '15.0.0-canary.90',
+    installedReact: '19.0.0',
+    targetNext: '15.0.0-canary.100',
+    targetReact: '19.0.0',
+    devScript: 'next dev',
+  })
+
+  // Reject the default Turbopack suggestion. A command that incorrectly forces
+  // non-interactive defaults would update this script instead.
+  const result = runUpgrade(project, ['15.0.0-canary.100'], {
+    tty: true,
+    input: 'n\n',
+  })
+  expect(outputOf(result)).toContain('Enable Turbopack')
+  expect(result.status).toBe(0)
+
+  const manifest = JSON.parse(
+    fs.readFileSync(path.join(project.dir, 'package.json'), 'utf8')
+  )
+  expect(manifest.scripts.dev).toBe('next dev')
+})
+
+test('--yes accepts prompt defaults even when the command has a TTY', () => {
+  const project = createProject({
+    installedNext: '15.0.0-canary.90',
+    installedReact: '18.2.0',
+    targetNext: '15.0.0-canary.100',
+    targetReact: '19.0.0',
+    devScript: 'next dev',
+    pages: true,
+  })
+
+  const result = runUpgrade(project, ['15.0.0-canary.100', '--yes'], {
+    tty: true,
+  })
+  expect(result.status).toBe(0)
+
+  const manifest = JSON.parse(
+    fs.readFileSync(path.join(project.dir, 'package.json'), 'utf8')
+  )
+  expect(manifest.scripts.dev).toContain('next dev --turbo')
+  expect(manifest.dependencies.next).toBe('15.0.0-canary.100')
+  expect(manifest.dependencies.react).toBe('19.0.0')
+  expect(manifest.dependencies['react-dom']).toBe('19.0.0')
+
+  const commands = fs.readFileSync(project.commandLog, 'utf8')
+  expect(commands).toContain('react/19/migration-recipe')
+  expect(commands).toContain('types-react-codemod@latest')
+})
+
+test('piped stdin automatically leaves an unrecognized custom dev script unchanged', () => {
+  const devScript = 'node scripts/start-development.js --inspect'
+  const project = createProject({
+    installedNext: '15.0.0-canary.90',
+    installedReact: '19.0.0',
+    targetNext: '15.0.0-canary.100',
+    targetReact: '19.0.0',
+    devScript,
+  })
+
+  const result = runUpgrade(project, ['15.0.0-canary.100'])
+  expect(result.status).toBe(0)
+  const manifest = JSON.parse(
+    fs.readFileSync(path.join(project.dir, 'package.json'), 'utf8')
+  )
+  expect(manifest.scripts.dev).toBe(devScript)
+  expect(manifest.dependencies.next).toBe('15.0.0-canary.100')
+})
+
+test('piped stdin applies every recommended Next.js codemod', () => {
+  const project = createProject({
+    installedNext: '13.5.0',
+    installedReact: '18.2.0',
+    targetNext: '14.2.0',
+    targetReact: '18.3.1',
+    devScript: 'next dev',
+  })
+  const page = path.join(project.dir, 'app', 'page.tsx')
+  fs.mkdirSync(path.dirname(page), { recursive: true })
+  fs.writeFileSync(
+    page,
+    `import { ImageResponse } from 'next/server'\n\nexport const metadata = {\n  title: 'Keep this title',\n  viewport: { width: 'device-width' },\n  themeColor: 'black',\n}\n\nexport default function Page() { return null }\n`
+  )
+
+  const result = runUpgrade(project, ['14.2.0'])
+  expect(result.status).toBe(0)
+
+  const output = outputOf(result)
+  expect(output).toContain('metadata-to-viewport-export')
+  expect(output).toContain('next-og-import')
+
+  const transformed = fs.readFileSync(page, 'utf8')
+  expect(transformed).toMatch(/from ['"]next\/og['"]/)
+  expect(transformed).toContain('export const viewport')
+  expect(transformed).toContain("title: 'Keep this title'")
+})