-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathupdate.ts
More file actions
420 lines (331 loc) · 12 KB
/
update.ts
File metadata and controls
420 lines (331 loc) · 12 KB
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import { confirm, intro, isCancel, log, outro } from "@clack/prompts";
import { Command } from "commander";
import { detectPackageManager, installDependencies } from "nypm";
import { dirname, join, resolve } from "path";
import { PackageJson, readPackageJSON, type ResolveOptions, resolvePackageJSON } from "pkg-types";
import { z } from "zod";
import { CommonCommandOptions, OutroCommandError, wrapCommandAction } from "../cli/common.js";
import { chalkError, prettyError, prettyWarning } from "../utilities/cliOutput.js";
import { removeFile, writeJSONFilePreserveOrder } from "../utilities/fileSystem.js";
import { printStandloneInitialBanner, updateCheck } from "../utilities/initialBanner.js";
import { logger } from "../utilities/logger.js";
import { spinner } from "../utilities/windows.js";
import { VERSION } from "../version.js";
import { hasTTY } from "std-env";
import nodeResolve from "resolve";
import * as semver from "semver";
export const UpdateCommandOptions = CommonCommandOptions.pick({
logLevel: true,
skipTelemetry: true,
});
export type UpdateCommandOptions = z.infer<typeof UpdateCommandOptions>;
export function configureUpdateCommand(program: Command) {
return program
.command("update")
.description("Updates all @trigger.dev/* packages to match the CLI version")
.argument("[path]", "The path to the directory that contains the package.json file", ".")
.option(
"-l, --log-level <level>",
"The CLI log level to use (debug, info, log, warn, error, none). This does not effect the log level of your trigger.dev tasks.",
"log"
)
.option("--skip-telemetry", "Opt-out of sending telemetry")
.action(async (path, options) => {
wrapCommandAction("dev", UpdateCommandOptions, options, async (opts) => {
await printStandloneInitialBanner(true);
await updateCommand(path, opts);
});
});
}
const triggerPackageFilter = /^@trigger\.dev/;
export async function updateCommand(dir: string, options: UpdateCommandOptions) {
await updateTriggerPackages(dir, options, false);
}
export async function updateTriggerPackages(
dir: string,
options: UpdateCommandOptions,
embedded?: boolean,
requireUpdate?: boolean
): Promise<boolean> {
let hasOutput = false;
const cliVersion = VERSION;
if (cliVersion.startsWith("0.0.0") && process.env.ENABLE_PRERELEASE_UPDATE_CHECKS !== "1") {
return false;
}
if (!embedded) {
intro("Updating packages");
}
const projectPath = resolve(process.cwd(), dir);
const { packageJson, readonlyPackageJson, packageJsonPath } = await getPackageJson(projectPath);
if (!packageJson) {
log.error("Failed to load package.json. Try to re-run with `-l debug` to see what's going on.");
return false;
}
const newCliVersion = await updateCheck();
if (newCliVersion && !cliVersion.startsWith("0.0.0")) {
prettyWarning(
"You're not running the latest CLI version, please consider updating ASAP",
`Current: ${cliVersion}\nLatest: ${newCliVersion}`,
"Run latest: npx trigger.dev@latest"
);
hasOutput = true;
}
const triggerDependencies = await getTriggerDependencies(packageJson, packageJsonPath);
logger.debug("Resolved trigger deps", { triggerDependencies });
function getVersionMismatches(
deps: Dependency[],
targetVersion: string
): {
mismatches: Dependency[];
isDowngrade: boolean;
} {
logger.debug("Checking for version mismatches", { deps, targetVersion });
const mismatches: Dependency[] = [];
for (const dep of deps) {
if (
dep.version === targetVersion ||
dep.version.startsWith("https://pkg.pr.new") ||
dep.version.startsWith("0.0.0")
) {
continue;
}
mismatches.push(dep);
}
const isDowngrade = mismatches.some((dep) => {
const depMinVersion = semver.minVersion(dep.version);
if (!depMinVersion) {
return false;
}
return semver.gt(depMinVersion, targetVersion);
});
return {
mismatches,
isDowngrade,
};
}
const { mismatches, isDowngrade } = getVersionMismatches(triggerDependencies, cliVersion);
logger.debug("Version mismatches", { mismatches, isDowngrade });
if (mismatches.length === 0) {
if (!embedded) {
outro(`Nothing to update${newCliVersion ? " ..but you should really update your CLI!" : ""}`);
return hasOutput;
}
return hasOutput;
}
if (embedded) {
if (isDowngrade) {
prettyError("Some of the installed @trigger.dev packages are newer than your CLI version");
} else {
if (embedded) {
prettyWarning(
"Mismatch between your CLI version and installed packages",
"We recommend pinned versions for guaranteed compatibility"
);
}
}
}
if (!hasTTY) {
// Running in CI with version mismatch detected
if (embedded) {
outro("Deploy failed");
}
console.log(
`ERROR: Version mismatch detected while running in CI. This won't end well. Aborting.
Please run the dev command locally and check that your CLI version matches the one printed below. Additionally, all \`@trigger.dev/*\` packages also need to match this version.
If your local CLI version doesn't match the one below, you may want to pin the CLI version in this CI step. To do that, just replace \`trigger.dev@beta\` with \`trigger.dev@<FULL_VERSION>\`, for example: \`npx trigger.dev@3.0.0-beta.17 deploy\`
CLI version: ${cliVersion}
Current package versions that don't match the CLI:
${mismatches.map((dep) => `- ${dep.name}@${dep.version}`).join("\n")}\n`
);
process.exit(1);
}
// WARNING: We can only start accepting user input once we know this is a TTY, otherwise, the process will exit with an error in CI
if (isDowngrade && embedded) {
printUpdateTable("Versions", mismatches, cliVersion, "installed", "CLI");
outro("CLI update required!");
logger.log(
`${chalkError(
"X Error:"
)} Please update your CLI. Alternatively, use \`--skip-update-check\` at your own risk.\n`
);
process.exit(1);
}
log.message(""); // spacing
// Always require user confirmation
const userWantsToUpdate = await updateConfirmation(mismatches, cliVersion);
if (isCancel(userWantsToUpdate)) {
throw new OutroCommandError();
}
if (!userWantsToUpdate) {
if (requireUpdate) {
if (embedded) {
outro("You shall not pass!");
logger.log(
`${chalkError(
"X Error:"
)} Update required: Version mismatches are a common source of bugs and errors. Please update or use \`--skip-update-check\` at your own risk.\n`
);
process.exit(1);
} else {
outro("No updates applied");
process.exit(0);
}
}
if (!embedded) {
outro("You've been warned!");
}
return hasOutput;
}
const installSpinner = spinner();
installSpinner.start("Updating dependencies in package.json");
// Backup package.json
const packageJsonBackupPath = `${packageJsonPath}.bak`;
await writeJSONFilePreserveOrder(packageJsonBackupPath, readonlyPackageJson, true);
const exitHandler = async (sig: any) => {
log.warn(
`You may have to manually roll back any package.json changes. Backup written to ${packageJsonBackupPath}`
);
};
// Add exit handler to warn about manual rollback of package.json
// Automatically rolling back can end up overwriting with an empty file instead
process.prependOnceListener("exit", exitHandler);
// Update package.json
mutatePackageJsonWithUpdatedPackages(packageJson, mismatches, cliVersion);
await writeJSONFilePreserveOrder(packageJsonPath, packageJson, true);
async function revertPackageJsonChanges() {
await writeJSONFilePreserveOrder(packageJsonPath, readonlyPackageJson, true);
await removeFile(packageJsonBackupPath);
}
installSpinner.message("Installing new package versions");
const packageManager = await detectPackageManager(projectPath);
try {
installSpinner.message(
`Installing new package versions${packageManager ? ` with ${packageManager.name}` : ""}`
);
await installDependencies({ cwd: projectPath, silent: true });
} catch (error) {
installSpinner.stop(
`Failed to install new package versions${
packageManager ? ` with ${packageManager.name}` : ""
}`
);
// Remove exit handler in case of failure
process.removeListener("exit", exitHandler);
await revertPackageJsonChanges();
throw error;
}
installSpinner.stop("Installed new package versions");
// Remove exit handler once packages have been updated, also delete backup file
process.removeListener("exit", exitHandler);
await removeFile(packageJsonBackupPath);
if (!embedded) {
outro(
`Packages updated${newCliVersion ? " ..but you should really update your CLI too!" : ""}`
);
}
return hasOutput;
}
type Dependency = {
type: "dependencies" | "devDependencies";
name: string;
version: string;
};
async function getTriggerDependencies(
packageJson: PackageJson,
packageJsonPath: string
): Promise<Dependency[]> {
const deps: Dependency[] = [];
for (const type of ["dependencies", "devDependencies"] as const) {
for (const [name, version] of Object.entries(packageJson[type] ?? {})) {
if (!version) {
continue;
}
if (version.startsWith("workspace")) {
continue;
}
if (!triggerPackageFilter.test(name)) {
continue;
}
const ignoredPackages = ["@trigger.dev/companyicons"];
if (ignoredPackages.includes(name)) {
continue;
}
const $version = await tryResolveTriggerPackageVersion(name, dirname(packageJsonPath));
deps.push({ type, name, version: $version ?? version });
}
}
return deps;
}
export async function tryResolveTriggerPackageVersion(
name: string,
basedir?: string
): Promise<string | undefined> {
try {
const resolvedPath = nodeResolve.sync(name, {
basedir,
});
logger.debug(`Resolved ${name} package version path`, { name, resolvedPath });
const { packageJson } = await getPackageJson(dirname(resolvedPath), {
test: (filePath) => {
// We need to skip any type-marker files
if (filePath.includes(join("dist", "commonjs"))) {
return false;
}
if (filePath.includes(join("dist", "esm"))) {
return false;
}
return true;
},
});
if (packageJson.version) {
logger.debug(`Resolved ${name} package version`, { name, version: packageJson.version });
return packageJson.version;
}
return;
} catch (error) {
logger.debug("Failed to resolve package version", { name, error });
return undefined;
}
}
function mutatePackageJsonWithUpdatedPackages(
packageJson: PackageJson,
depsToUpdate: Dependency[],
targetVersion: string
) {
for (const { type, name, version } of depsToUpdate) {
if (!packageJson[type]) {
throw new Error(
`No ${type} entry found in package.json. Please try to upgrade manually instead.`
);
}
packageJson[type]![name] = targetVersion;
}
}
function printUpdateTable(
heading: string,
depsToUpdate: Dependency[],
targetVersion: string,
oldColumn = "old",
newColumn = "new"
): void {
log.message(heading);
const tableData = depsToUpdate.map((dep) => ({
package: dep.name,
[oldColumn]: dep.version,
[newColumn]: targetVersion,
}));
logger.table(tableData);
}
async function updateConfirmation(depsToUpdate: Dependency[], targetVersion: string) {
printUpdateTable("Suggested updates", depsToUpdate, targetVersion);
let confirmMessage = "Would you like to apply those updates?";
return await confirm({
message: confirmMessage,
});
}
export async function getPackageJson(absoluteProjectPath: string, options?: ResolveOptions) {
const packageJsonPath = await resolvePackageJSON(absoluteProjectPath, options);
const readonlyPackageJson = await readPackageJSON(packageJsonPath);
const packageJson = structuredClone(readonlyPackageJson);
return { packageJson, readonlyPackageJson, packageJsonPath };
}