@strapi/upgrade 5.9.0 → 5.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1599 @@
1
+ import path$1 from 'node:path';
2
+ import assert from 'node:assert';
3
+ import semver from 'semver';
4
+ import chalk from 'chalk';
5
+ import { packageManager } from '@strapi/utils';
6
+ import fse from 'fs-extra';
7
+ import fastglob from 'fast-glob';
8
+ import { run } from 'jscodeshift/src/Runner';
9
+ import { cloneDeep, get, has, merge, set, omit, isEqual, groupBy, size } from 'lodash/fp';
10
+ import { register } from 'esbuild-register/dist/node';
11
+ import simpleGit from 'simple-git';
12
+ import CliTable3 from 'cli-table3';
13
+
14
+ class Timer {
15
+ get elapsedMs() {
16
+ const { start, end } = this.interval;
17
+ return end ? end - start : Date.now() - start;
18
+ }
19
+ get end() {
20
+ return this.interval.end;
21
+ }
22
+ get start() {
23
+ return this.interval.start;
24
+ }
25
+ stop() {
26
+ this.interval.end = Date.now();
27
+ return this.elapsedMs;
28
+ }
29
+ reset() {
30
+ this.interval = {
31
+ start: Date.now(),
32
+ end: null
33
+ };
34
+ return this;
35
+ }
36
+ constructor(){
37
+ this.reset();
38
+ }
39
+ }
40
+ const timerFactory = ()=>new Timer();
41
+
42
+ const ONE_SECOND_MS = 1000;
43
+
44
+ var constants$4 = /*#__PURE__*/Object.freeze({
45
+ __proto__: null,
46
+ ONE_SECOND_MS: ONE_SECOND_MS
47
+ });
48
+
49
+ const path = (path)=>chalk.blue(path);
50
+ const version = (version)=>{
51
+ return chalk.italic.yellow(`v${version}`);
52
+ };
53
+ const codemodUID = (uid)=>{
54
+ return chalk.bold.cyan(uid);
55
+ };
56
+ const projectDetails = (project)=>{
57
+ return `Project: TYPE=${projectType(project.type)}; CWD=${path(project.cwd)}; PATHS=${project.paths.map(path)}`;
58
+ };
59
+ const projectType = (type)=>chalk.cyan(type);
60
+ const versionRange = (range)=>chalk.italic.yellow(range.raw);
61
+ const transform = (transformFilePath)=>chalk.cyan(transformFilePath);
62
+ const highlight = (arg)=>chalk.bold.underline(arg);
63
+ const upgradeStep = (text, step)=>{
64
+ return chalk.bold(`(${step[0]}/${step[1]}) ${text}...`);
65
+ };
66
+ const reports = (reports)=>{
67
+ const rows = reports.map(({ codemod, report }, i)=>{
68
+ const fIndex = chalk.grey(i);
69
+ const fVersion = chalk.magenta(codemod.version);
70
+ const fKind = chalk.yellow(codemod.kind);
71
+ const fFormattedTransformPath = chalk.cyan(codemod.format());
72
+ const fTimeElapsed = i === 0 ? `${report.timeElapsed}s ${chalk.dim.italic('(cold start)')}` : `${report.timeElapsed}s`;
73
+ const fAffected = report.ok > 0 ? chalk.green(report.ok) : chalk.grey(0);
74
+ const fUnchanged = report.ok === 0 ? chalk.red(report.nochange) : chalk.grey(report.nochange);
75
+ return [
76
+ fIndex,
77
+ fVersion,
78
+ fKind,
79
+ fFormattedTransformPath,
80
+ fAffected,
81
+ fUnchanged,
82
+ fTimeElapsed
83
+ ];
84
+ });
85
+ const table = new CliTable3({
86
+ style: {
87
+ compact: true
88
+ },
89
+ head: [
90
+ chalk.bold.grey('N°'),
91
+ chalk.bold.magenta('Version'),
92
+ chalk.bold.yellow('Kind'),
93
+ chalk.bold.cyan('Name'),
94
+ chalk.bold.green('Affected'),
95
+ chalk.bold.red('Unchanged'),
96
+ chalk.bold.blue('Duration')
97
+ ]
98
+ });
99
+ table.push(...rows);
100
+ return table.toString();
101
+ };
102
+ const codemodList = (codemods)=>{
103
+ const rows = codemods.map((codemod, index)=>{
104
+ const fIndex = chalk.grey(index);
105
+ const fVersion = chalk.magenta(codemod.version);
106
+ const fKind = chalk.yellow(codemod.kind);
107
+ const fName = chalk.blue(codemod.format());
108
+ const fUID = codemodUID(codemod.uid);
109
+ return [
110
+ fIndex,
111
+ fVersion,
112
+ fKind,
113
+ fName,
114
+ fUID
115
+ ];
116
+ });
117
+ const table = new CliTable3({
118
+ style: {
119
+ compact: true
120
+ },
121
+ head: [
122
+ chalk.bold.grey('N°'),
123
+ chalk.bold.magenta('Version'),
124
+ chalk.bold.yellow('Kind'),
125
+ chalk.bold.blue('Name'),
126
+ chalk.bold.cyan('UID')
127
+ ]
128
+ });
129
+ table.push(...rows);
130
+ return table.toString();
131
+ };
132
+ const durationMs = (elapsedMs)=>{
133
+ const elapsedSeconds = (elapsedMs / ONE_SECOND_MS).toFixed(3);
134
+ return `${elapsedSeconds}s`;
135
+ };
136
+
137
+ const NPM_REGISTRY_URL = 'https://registry.npmjs.org';
138
+
139
+ var ReleaseType;
140
+ (function(ReleaseType) {
141
+ // Classic
142
+ ReleaseType["Major"] = "major";
143
+ ReleaseType["Minor"] = "minor";
144
+ ReleaseType["Patch"] = "patch";
145
+ // Other
146
+ ReleaseType["Latest"] = "latest";
147
+ })(ReleaseType || (ReleaseType = {}));
148
+
149
+ var types = /*#__PURE__*/Object.freeze({
150
+ __proto__: null,
151
+ get ReleaseType () { return ReleaseType; }
152
+ });
153
+
154
+ const semVerFactory = (version)=>{
155
+ return new semver.SemVer(version);
156
+ };
157
+ const isLiteralSemVer = (str)=>{
158
+ const tokens = str.split('.');
159
+ return tokens.length === 3 && tokens.every((token)=>!Number.isNaN(+token) && Number.isInteger(+token));
160
+ };
161
+ const isValidSemVer = (str)=>semver.valid(str) !== null;
162
+ const isSemverInstance = (value)=>{
163
+ return value instanceof semver.SemVer;
164
+ };
165
+ const isSemVerReleaseType = (str)=>{
166
+ return Object.values(ReleaseType).includes(str);
167
+ };
168
+
169
+ const rangeFactory = (range)=>{
170
+ return new semver.Range(range);
171
+ };
172
+ const rangeFromReleaseType = (current, identifier)=>{
173
+ switch(identifier){
174
+ case ReleaseType.Latest:
175
+ {
176
+ // Match anything greater than the current version
177
+ return rangeFactory(`>${current.raw}`);
178
+ }
179
+ case ReleaseType.Major:
180
+ {
181
+ // For example, 4.15.4 returns 5.0.0
182
+ const nextMajor = semVerFactory(current.raw).inc('major');
183
+ // Using only the major version as the upper limit allows any minor,
184
+ // patch, or build version to be taken in the range.
185
+ //
186
+ // For example, if the current version is "4.15.4", incrementing the
187
+ // major version would result in "5.0.0".
188
+ // The generated rule is ">4.15.4 <=5", allowing any version
189
+ // greater than "4.15.4" but less than "6.0.0-0".
190
+ return rangeFactory(`>${current.raw} <=${nextMajor.major}`);
191
+ }
192
+ case ReleaseType.Minor:
193
+ {
194
+ // For example, 4.15.4 returns 5.0.0
195
+ const nextMajor = semVerFactory(current.raw).inc('major');
196
+ // Using the <major>.<minor>.<patch> version as the upper limit allows any minor,
197
+ // patch, or build versions to be taken in the range.
198
+ //
199
+ // For example, if the current version is "4.15.4", incrementing the
200
+ // major version would result in "5.0.0".
201
+ // The generated rule is ">4.15.4 <5.0.0", allowing any version
202
+ // greater than "4.15.4" but less than "5.0.0".
203
+ return rangeFactory(`>${current.raw} <${nextMajor.raw}`);
204
+ }
205
+ case ReleaseType.Patch:
206
+ {
207
+ // For example, 4.15.4 returns 4.16.0
208
+ const nextMinor = semVerFactory(current.raw).inc('minor');
209
+ // Using only the minor version as the upper limit allows any patch
210
+ // or build versions to be taken in the range.
211
+ //
212
+ // For example, if the current version is "4.15.4", incrementing the
213
+ // minor version would result in "4.16.0".
214
+ // The generated rule is ">4.15.4 <4.16.0", allowing any version
215
+ // greater than "4.15.4" but less than "4.16.0".
216
+ return rangeFactory(`>${current.raw} <${nextMinor.raw}`);
217
+ }
218
+ default:
219
+ {
220
+ throw new Error('Not implemented');
221
+ }
222
+ }
223
+ };
224
+ const rangeFromVersions = (currentVersion, target)=>{
225
+ if (isSemverInstance(target)) {
226
+ return rangeFactory(`>${currentVersion.raw} <=${target.raw}`);
227
+ }
228
+ if (isSemVerReleaseType(target)) {
229
+ return rangeFromReleaseType(currentVersion, target);
230
+ }
231
+ throw new Error(`Invalid target set: ${target}`); // TODO: better errors
232
+ };
233
+ const isValidStringifiedRange = (str)=>semver.validRange(str) !== null;
234
+ const isRangeInstance = (range)=>{
235
+ return range instanceof semver.Range;
236
+ };
237
+
238
+ class Package {
239
+ get isLoaded() {
240
+ return this.npmPackage !== null;
241
+ }
242
+ assertPackageIsLoaded(npmPackage) {
243
+ assert(this.isLoaded, 'The package is not loaded yet');
244
+ }
245
+ getVersionsDict() {
246
+ this.assertPackageIsLoaded(this.npmPackage);
247
+ return this.npmPackage.versions;
248
+ }
249
+ getVersionsAsList() {
250
+ this.assertPackageIsLoaded(this.npmPackage);
251
+ return Object.values(this.npmPackage.versions);
252
+ }
253
+ findVersionsInRange(range) {
254
+ const versions = this.getVersionsAsList();
255
+ return versions// Only select versions matching the upgrade range
256
+ .filter((v)=>range.test(v.version))// Only select supported version format (x.x.x)
257
+ .filter((v)=>isLiteralSemVer(v.version))// Sort in ascending order
258
+ .sort((v1, v2)=>semver.compare(v1.version, v2.version));
259
+ }
260
+ findVersion(version) {
261
+ const versions = this.getVersionsAsList();
262
+ return versions.find((npmVersion)=>semver.eq(npmVersion.version, version));
263
+ }
264
+ async refresh() {
265
+ const response = await fetch(this.packageURL);
266
+ // TODO: Use a validation library to make sure the response structure is correct
267
+ assert(response.ok, `Request failed for ${this.packageURL}`);
268
+ this.npmPackage = await response.json();
269
+ return this;
270
+ }
271
+ versionExists(version) {
272
+ return this.findVersion(version) !== undefined;
273
+ }
274
+ constructor(name){
275
+ this.name = name;
276
+ this.packageURL = `${NPM_REGISTRY_URL}/${name}`;
277
+ this.npmPackage = null;
278
+ }
279
+ }
280
+ const npmPackageFactory = (name)=>new Package(name);
281
+
282
+ class FileScanner {
283
+ scan(patterns) {
284
+ // we use fastglob instead of glob because it supports negation patterns
285
+ const filenames = fastglob.sync(patterns, {
286
+ cwd: this.cwd
287
+ });
288
+ // Resolve the full paths for every filename
289
+ return filenames.map((filename)=>path$1.join(this.cwd, filename));
290
+ }
291
+ constructor(cwd){
292
+ this.cwd = cwd;
293
+ }
294
+ }
295
+ const fileScannerFactory = (cwd)=>new FileScanner(cwd);
296
+
297
+ class AbstractRunner {
298
+ async run(codemod, configuration) {
299
+ const isValidCodemod = this.valid(codemod);
300
+ if (!isValidCodemod) {
301
+ throw new Error(`Invalid codemod provided to the runner: ${codemod.filename}`);
302
+ }
303
+ const runConfiguration = {
304
+ ...this.configuration,
305
+ ...configuration
306
+ };
307
+ return this.runner(codemod.path, this.paths, runConfiguration);
308
+ }
309
+ constructor(paths, configuration){
310
+ this.paths = paths;
311
+ this.configuration = configuration;
312
+ }
313
+ }
314
+
315
+ class CodeRunner extends AbstractRunner {
316
+ valid(codemod) {
317
+ return codemod.kind === 'code';
318
+ }
319
+ constructor(...args){
320
+ super(...args);
321
+ this.runner = run;
322
+ }
323
+ }
324
+ const codeRunnerFactory = (paths, configuration)=>{
325
+ return new CodeRunner(paths, configuration);
326
+ };
327
+
328
+ class JSONTransformAPI {
329
+ get(path, defaultValue) {
330
+ if (!path) {
331
+ return this.root();
332
+ }
333
+ return cloneDeep(get(path, this.json) ?? defaultValue);
334
+ }
335
+ has(path) {
336
+ return has(path, this.json);
337
+ }
338
+ merge(other) {
339
+ this.json = merge(other, this.json);
340
+ return this;
341
+ }
342
+ root() {
343
+ return cloneDeep(this.json);
344
+ }
345
+ set(path, value) {
346
+ this.json = set(path, value, this.json);
347
+ return this;
348
+ }
349
+ remove(path) {
350
+ this.json = omit(path, this.json);
351
+ return this;
352
+ }
353
+ constructor(json){
354
+ this.json = cloneDeep(json);
355
+ }
356
+ }
357
+ const createJSONTransformAPI = (object)=>new JSONTransformAPI(object);
358
+
359
+ const readJSON = async (path)=>{
360
+ const buffer = await fse.readFile(path);
361
+ return JSON.parse(buffer.toString());
362
+ };
363
+ const saveJSON = async (path, json)=>{
364
+ const jsonAsString = `${JSON.stringify(json, null, 2)}\n`;
365
+ await fse.writeFile(path, jsonAsString);
366
+ };
367
+
368
+ const transformJSON = async (codemodPath, paths, config)=>{
369
+ const { dry } = config;
370
+ const startTime = process.hrtime();
371
+ const report = {
372
+ ok: 0,
373
+ nochange: 0,
374
+ skip: 0,
375
+ error: 0,
376
+ timeElapsed: '',
377
+ stats: {}
378
+ };
379
+ /**
380
+ * Why do we need to include node_modules (hookIgnoreNodeModules) and specify a matcher (hookMatcher) to esbuild?
381
+ *
382
+ * When using tools like npx or dlx, the execution context is different from when running the program in a local
383
+ * project. npx and dlx run the commands in a temporary installation, which is isolated from local project files.
384
+ *
385
+ * When hookIgnoreNodeModules is not specified (or set to true), esbuild-register instructs
386
+ * Pirates (https://github.com/danez/pirates) to not transpile any files that come from node_modules.
387
+ *
388
+ * Now, when using npx or dlx to run a script, its location can be seen as "external" because it's not part of
389
+ * the temporary environment where npx or dlx execute. Therefore, it's considered to be part of node_modules.
390
+ *
391
+ * Due to this, if hookIgnoreNodeModules is set to true or left unspecified,
392
+ * esbuild-register won't try to compile them upon require.
393
+ *
394
+ * hookMatcher is added to make sure we're not matching anything else than our codemod in external directories.
395
+ */ const esbuildOptions = {
396
+ extensions: [
397
+ '.js',
398
+ '.mjs',
399
+ '.ts'
400
+ ],
401
+ hookIgnoreNodeModules: false,
402
+ hookMatcher: isEqual(codemodPath)
403
+ };
404
+ const { unregister } = register(esbuildOptions);
405
+ const module = require(codemodPath);
406
+ unregister();
407
+ const codemod = typeof module.default === 'function' ? module.default : module;
408
+ assert(typeof codemod === 'function', `Codemod must be a function. Found ${typeof codemod}`);
409
+ for (const path of paths){
410
+ try {
411
+ const json = await readJSON(path);
412
+ // Make sure the JSON value is a JSON object
413
+ assert(typeof json === 'object' && !Array.isArray(json) && json !== null);
414
+ // TODO: Optimize the API to limit parse/stringify operations
415
+ const file = {
416
+ path,
417
+ json
418
+ };
419
+ const params = {
420
+ cwd: config.cwd,
421
+ json: createJSONTransformAPI
422
+ };
423
+ const out = await codemod(file, params);
424
+ if (out === undefined) {
425
+ report.error += 1;
426
+ } else if (!isEqual(json, out)) {
427
+ if (!dry) {
428
+ await saveJSON(path, out);
429
+ }
430
+ report.ok += 1;
431
+ } else {
432
+ report.nochange += 1;
433
+ }
434
+ } catch {
435
+ report.error += 1;
436
+ }
437
+ }
438
+ const endTime = process.hrtime(startTime);
439
+ report.timeElapsed = (endTime[0] + endTime[1] / 1e9).toFixed(3);
440
+ return report;
441
+ };
442
+
443
+ class JSONRunner extends AbstractRunner {
444
+ valid(codemod) {
445
+ return codemod.kind === 'json';
446
+ }
447
+ constructor(...args){
448
+ super(...args);
449
+ this.runner = transformJSON;
450
+ }
451
+ }
452
+ const jsonRunnerFactory = (paths, configuration)=>{
453
+ return new JSONRunner(paths, configuration);
454
+ };
455
+
456
+ const PROJECT_PACKAGE_JSON = 'package.json';
457
+ const PROJECT_APP_ALLOWED_ROOT_PATHS = [
458
+ 'src',
459
+ 'config',
460
+ 'public'
461
+ ];
462
+ const PROJECT_PLUGIN_ALLOWED_ROOT_PATHS = [
463
+ 'admin',
464
+ 'server'
465
+ ];
466
+ const PROJECT_PLUGIN_ROOT_FILES = [
467
+ 'strapi-admin.js',
468
+ 'strapi-server.js'
469
+ ];
470
+ const PROJECT_CODE_EXTENSIONS = [
471
+ // Source files
472
+ 'js',
473
+ 'mjs',
474
+ 'ts',
475
+ // React files
476
+ 'jsx',
477
+ 'tsx'
478
+ ];
479
+ const PROJECT_JSON_EXTENSIONS = [
480
+ 'json'
481
+ ];
482
+ const PROJECT_ALLOWED_EXTENSIONS = [
483
+ ...PROJECT_CODE_EXTENSIONS,
484
+ ...PROJECT_JSON_EXTENSIONS
485
+ ];
486
+ const SCOPED_STRAPI_PACKAGE_PREFIX = '@strapi/';
487
+ const STRAPI_DEPENDENCY_NAME = `${SCOPED_STRAPI_PACKAGE_PREFIX}strapi`;
488
+
489
+ var constants$3 = /*#__PURE__*/Object.freeze({
490
+ __proto__: null,
491
+ PROJECT_ALLOWED_EXTENSIONS: PROJECT_ALLOWED_EXTENSIONS,
492
+ PROJECT_APP_ALLOWED_ROOT_PATHS: PROJECT_APP_ALLOWED_ROOT_PATHS,
493
+ PROJECT_CODE_EXTENSIONS: PROJECT_CODE_EXTENSIONS,
494
+ PROJECT_JSON_EXTENSIONS: PROJECT_JSON_EXTENSIONS,
495
+ PROJECT_PACKAGE_JSON: PROJECT_PACKAGE_JSON,
496
+ PROJECT_PLUGIN_ALLOWED_ROOT_PATHS: PROJECT_PLUGIN_ALLOWED_ROOT_PATHS,
497
+ PROJECT_PLUGIN_ROOT_FILES: PROJECT_PLUGIN_ROOT_FILES,
498
+ SCOPED_STRAPI_PACKAGE_PREFIX: SCOPED_STRAPI_PACKAGE_PREFIX,
499
+ STRAPI_DEPENDENCY_NAME: STRAPI_DEPENDENCY_NAME
500
+ });
501
+
502
+ class Project {
503
+ getFilesByExtensions(extensions) {
504
+ return this.files.filter((filePath)=>{
505
+ const fileExtension = path$1.extname(filePath);
506
+ return extensions.includes(fileExtension);
507
+ });
508
+ }
509
+ refresh() {
510
+ this.refreshPackageJSON();
511
+ this.refreshProjectFiles();
512
+ return this;
513
+ }
514
+ async runCodemods(codemods, options) {
515
+ const runners = this.createProjectCodemodsRunners(options.dry);
516
+ const reports = [];
517
+ for (const codemod of codemods){
518
+ for (const runner of runners){
519
+ if (runner.valid(codemod)) {
520
+ const report = await runner.run(codemod);
521
+ reports.push({
522
+ codemod,
523
+ report
524
+ });
525
+ }
526
+ }
527
+ }
528
+ return reports;
529
+ }
530
+ createProjectCodemodsRunners(dry = false) {
531
+ const jsonExtensions = PROJECT_JSON_EXTENSIONS.map((ext)=>`.${ext}`);
532
+ const codeExtensions = PROJECT_CODE_EXTENSIONS.map((ext)=>`.${ext}`);
533
+ const jsonFiles = this.getFilesByExtensions(jsonExtensions);
534
+ const codeFiles = this.getFilesByExtensions(codeExtensions);
535
+ const codeRunner = codeRunnerFactory(codeFiles, {
536
+ dry,
537
+ parser: 'ts',
538
+ runInBand: true,
539
+ babel: true,
540
+ extensions: PROJECT_CODE_EXTENSIONS.join(','),
541
+ // Don't output any log coming from the runner
542
+ print: false,
543
+ silent: true,
544
+ verbose: 0
545
+ });
546
+ const jsonRunner = jsonRunnerFactory(jsonFiles, {
547
+ dry,
548
+ cwd: this.cwd
549
+ });
550
+ return [
551
+ codeRunner,
552
+ jsonRunner
553
+ ];
554
+ }
555
+ refreshPackageJSON() {
556
+ const packageJSONPath = path$1.join(this.cwd, PROJECT_PACKAGE_JSON);
557
+ try {
558
+ fse.accessSync(packageJSONPath);
559
+ } catch {
560
+ throw new Error(`Could not find a ${PROJECT_PACKAGE_JSON} file in ${this.cwd}`);
561
+ }
562
+ const packageJSONBuffer = fse.readFileSync(packageJSONPath);
563
+ this.packageJSONPath = packageJSONPath;
564
+ this.packageJSON = JSON.parse(packageJSONBuffer.toString());
565
+ }
566
+ refreshProjectFiles() {
567
+ const scanner = fileScannerFactory(this.cwd);
568
+ this.files = scanner.scan(this.paths);
569
+ }
570
+ constructor(cwd, config){
571
+ if (!fse.pathExistsSync(cwd)) {
572
+ throw new Error(`ENOENT: no such file or directory, access '${cwd}'`);
573
+ }
574
+ this.cwd = cwd;
575
+ this.paths = config.paths;
576
+ this.refresh();
577
+ }
578
+ }
579
+ class AppProject extends Project {
580
+ /**
581
+ * Returns an array of allowed file paths for a Strapi application
582
+ *
583
+ * The resulting paths include app default files and the root package.json file.
584
+ */ static get paths() {
585
+ const allowedRootPaths = formatGlobCollectionPattern(PROJECT_APP_ALLOWED_ROOT_PATHS);
586
+ const allowedExtensions = formatGlobCollectionPattern(PROJECT_ALLOWED_EXTENSIONS);
587
+ return [
588
+ // App default files
589
+ `./${allowedRootPaths}/**/*.${allowedExtensions}`,
590
+ `!./**/node_modules/**/*`,
591
+ `!./**/dist/**/*`,
592
+ // Root package.json file
593
+ PROJECT_PACKAGE_JSON
594
+ ];
595
+ }
596
+ refresh() {
597
+ super.refresh();
598
+ this.refreshStrapiVersion();
599
+ return this;
600
+ }
601
+ refreshStrapiVersion() {
602
+ this.strapiVersion = // First try to get the strapi version from the package.json dependencies
603
+ this.findStrapiVersionFromProjectPackageJSON() ?? // If the version found is not a valid SemVer, get the Strapi version from the installed package
604
+ this.findLocallyInstalledStrapiVersion();
605
+ }
606
+ findStrapiVersionFromProjectPackageJSON() {
607
+ const projectName = this.packageJSON.name;
608
+ const version = this.packageJSON.dependencies?.[STRAPI_DEPENDENCY_NAME];
609
+ if (version === undefined) {
610
+ throw new Error(`No version of ${STRAPI_DEPENDENCY_NAME} was found in ${projectName}. Are you in a valid Strapi project?`);
611
+ }
612
+ const isValidSemVer = isLiteralSemVer(version) && semver.valid(version) === version;
613
+ // We return undefined only if a strapi/strapi version is found, but it's not semver compliant
614
+ return isValidSemVer ? semVerFactory(version) : undefined;
615
+ }
616
+ findLocallyInstalledStrapiVersion() {
617
+ const packageSearchText = `${STRAPI_DEPENDENCY_NAME}/package.json`;
618
+ let strapiPackageJSONPath;
619
+ let strapiPackageJSON;
620
+ try {
621
+ strapiPackageJSONPath = require.resolve(packageSearchText, {
622
+ paths: [
623
+ this.cwd
624
+ ]
625
+ });
626
+ strapiPackageJSON = require(strapiPackageJSONPath);
627
+ assert(typeof strapiPackageJSON === 'object');
628
+ } catch {
629
+ throw new Error(`Cannot resolve module "${STRAPI_DEPENDENCY_NAME}" from paths [${this.cwd}]`);
630
+ }
631
+ const strapiVersion = strapiPackageJSON.version;
632
+ if (!isValidSemVer(strapiVersion)) {
633
+ throw new Error(`Invalid ${STRAPI_DEPENDENCY_NAME} version found in ${strapiPackageJSONPath} (${strapiVersion})`);
634
+ }
635
+ return semVerFactory(strapiVersion);
636
+ }
637
+ constructor(cwd){
638
+ super(cwd, {
639
+ paths: AppProject.paths
640
+ });
641
+ this.type = 'application';
642
+ this.refreshStrapiVersion();
643
+ }
644
+ }
645
+ const formatGlobCollectionPattern = (collection)=>{
646
+ assert(collection.length > 0, 'Invalid pattern provided, the given collection needs at least 1 element');
647
+ return collection.length === 1 ? collection[0] : `{${collection}}`;
648
+ };
649
+ class PluginProject extends Project {
650
+ /**
651
+ * Returns an array of allowed file paths for a Strapi plugin
652
+ *
653
+ * The resulting paths include plugin default files, the root package.json file, and plugin-specific files.
654
+ */ static get paths() {
655
+ const allowedRootPaths = formatGlobCollectionPattern(PROJECT_PLUGIN_ALLOWED_ROOT_PATHS);
656
+ const allowedExtensions = formatGlobCollectionPattern(PROJECT_ALLOWED_EXTENSIONS);
657
+ return [
658
+ // Plugin default files
659
+ `./${allowedRootPaths}/**/*.${allowedExtensions}`,
660
+ `!./**/node_modules/**/*`,
661
+ `!./**/dist/**/*`,
662
+ // Root package.json file
663
+ PROJECT_PACKAGE_JSON,
664
+ // Plugin root files
665
+ ...PROJECT_PLUGIN_ROOT_FILES
666
+ ];
667
+ }
668
+ constructor(cwd){
669
+ super(cwd, {
670
+ paths: PluginProject.paths
671
+ });
672
+ this.type = 'plugin';
673
+ }
674
+ }
675
+ const isPlugin = (cwd)=>{
676
+ const packageJSONPath = path$1.join(cwd, PROJECT_PACKAGE_JSON);
677
+ try {
678
+ fse.accessSync(packageJSONPath);
679
+ } catch {
680
+ throw new Error(`Could not find a ${PROJECT_PACKAGE_JSON} file in ${cwd}`);
681
+ }
682
+ const packageJSONBuffer = fse.readFileSync(packageJSONPath);
683
+ const packageJSON = JSON.parse(packageJSONBuffer.toString());
684
+ return packageJSON?.strapi?.kind === 'plugin';
685
+ };
686
+ // TODO: make this async so we can use async file methods
687
+ const projectFactory = (cwd)=>{
688
+ fse.accessSync(cwd);
689
+ return isPlugin(cwd) ? new PluginProject(cwd) : new AppProject(cwd);
690
+ };
691
+
692
+ const isPluginProject = (project)=>{
693
+ return project instanceof PluginProject;
694
+ };
695
+ function assertPluginProject(project) {
696
+ if (!isPluginProject(project)) {
697
+ throw new Error('Project is not a plugin');
698
+ }
699
+ }
700
+ const isApplicationProject = (project)=>{
701
+ return project instanceof AppProject;
702
+ };
703
+ function assertAppProject(project) {
704
+ if (!isApplicationProject(project)) {
705
+ throw new Error('Project is not an application');
706
+ }
707
+ }
708
+
709
+ class UnexpectedError extends Error {
710
+ constructor(){
711
+ super('Unexpected Error');
712
+ }
713
+ }
714
+ class NPMCandidateNotFoundError extends Error {
715
+ constructor(target, message = `Couldn't find a valid NPM candidate for "${target}"`){
716
+ super(message);
717
+ this.target = target;
718
+ }
719
+ }
720
+ class AbortedError extends Error {
721
+ constructor(message = 'Upgrade aborted'){
722
+ super(message);
723
+ }
724
+ }
725
+ const unknownToError = (e)=>{
726
+ if (e instanceof Error) {
727
+ return e;
728
+ }
729
+ if (typeof e === 'string') {
730
+ return new Error(e);
731
+ }
732
+ return new UnexpectedError();
733
+ };
734
+
735
+ const CODEMOD_CODE_SUFFIX = 'code';
736
+ const CODEMOD_JSON_SUFFIX = 'json';
737
+ const CODEMOD_ALLOWED_SUFFIXES = [
738
+ CODEMOD_CODE_SUFFIX,
739
+ CODEMOD_JSON_SUFFIX
740
+ ];
741
+ const CODEMOD_EXTENSION = 'ts';
742
+ const CODEMOD_FILE_REGEXP = new RegExp(`^.+[.](${CODEMOD_ALLOWED_SUFFIXES.join('|')})[.]${CODEMOD_EXTENSION}$`);
743
+
744
+ var constants$2 = /*#__PURE__*/Object.freeze({
745
+ __proto__: null,
746
+ CODEMOD_ALLOWED_SUFFIXES: CODEMOD_ALLOWED_SUFFIXES,
747
+ CODEMOD_CODE_SUFFIX: CODEMOD_CODE_SUFFIX,
748
+ CODEMOD_EXTENSION: CODEMOD_EXTENSION,
749
+ CODEMOD_FILE_REGEXP: CODEMOD_FILE_REGEXP,
750
+ CODEMOD_JSON_SUFFIX: CODEMOD_JSON_SUFFIX
751
+ });
752
+
753
+ class Codemod {
754
+ createUID() {
755
+ const name = this.format({
756
+ stripExtension: true,
757
+ stripKind: true,
758
+ stripHyphens: false
759
+ });
760
+ const kind = this.kind;
761
+ const version = this.version.raw;
762
+ return `${version}-${name}-${kind}`;
763
+ }
764
+ format(options) {
765
+ const { stripExtension = true, stripKind = true, stripHyphens = true } = options ?? {};
766
+ let formatted = this.filename;
767
+ if (stripExtension) {
768
+ formatted = formatted.replace(new RegExp(`\\.${CODEMOD_EXTENSION}$`, 'i'), '');
769
+ }
770
+ if (stripKind) {
771
+ formatted = formatted.replace(`.${CODEMOD_CODE_SUFFIX}`, '').replace(`.${CODEMOD_JSON_SUFFIX}`, '');
772
+ }
773
+ if (stripHyphens) {
774
+ formatted = formatted.replaceAll('-', ' ');
775
+ }
776
+ return formatted;
777
+ }
778
+ constructor(options){
779
+ this.kind = options.kind;
780
+ this.version = options.version;
781
+ this.baseDirectory = options.baseDirectory;
782
+ this.filename = options.filename;
783
+ this.path = path$1.join(this.baseDirectory, this.version.raw, this.filename);
784
+ this.uid = this.createUID();
785
+ }
786
+ }
787
+ const codemodFactory = (options)=>new Codemod(options);
788
+
789
+ const INTERNAL_CODEMODS_DIRECTORY = path$1.join(__dirname, '..', 'resources', 'codemods' // upgrade/resources/codemods
790
+ );
791
+
792
+ var constants$1 = /*#__PURE__*/Object.freeze({
793
+ __proto__: null,
794
+ INTERNAL_CODEMODS_DIRECTORY: INTERNAL_CODEMODS_DIRECTORY
795
+ });
796
+
797
+ class CodemodRepository {
798
+ refresh() {
799
+ this.refreshAvailableVersions();
800
+ this.refreshAvailableFiles();
801
+ return this;
802
+ }
803
+ count(version) {
804
+ return this.findByVersion(version).length;
805
+ }
806
+ versionExists(version) {
807
+ return version.raw in this.groups;
808
+ }
809
+ has(uid) {
810
+ const result = this.find({
811
+ uids: [
812
+ uid
813
+ ]
814
+ });
815
+ if (result.length !== 1) {
816
+ return false;
817
+ }
818
+ const { codemods } = result[0];
819
+ return codemods.length === 1 && codemods[0].uid === uid;
820
+ }
821
+ find(q) {
822
+ const entries = Object.entries(this.groups);
823
+ return entries// Filter by range if provided in the query
824
+ .filter(maybeFilterByRange)// Transform version/codemods tuples into regular objects
825
+ .map(([version, codemods])=>({
826
+ version: semVerFactory(version),
827
+ // Filter by UID if provided in the query
828
+ codemods: codemods.filter(maybeFilterByUIDs)
829
+ }))// Only return groups with at least 1 codemod
830
+ .filter(({ codemods })=>codemods.length > 0);
831
+ function maybeFilterByRange([version]) {
832
+ if (!isRangeInstance(q.range)) {
833
+ return true;
834
+ }
835
+ return q.range.test(version);
836
+ }
837
+ function maybeFilterByUIDs(codemod) {
838
+ if (q.uids === undefined) {
839
+ return true;
840
+ }
841
+ return q.uids.includes(codemod.uid);
842
+ }
843
+ }
844
+ findByVersion(version) {
845
+ const literalVersion = version.raw;
846
+ const codemods = this.groups[literalVersion];
847
+ return codemods ?? [];
848
+ }
849
+ findAll() {
850
+ const entries = Object.entries(this.groups);
851
+ return entries.map(([version, codemods])=>({
852
+ version: semVerFactory(version),
853
+ codemods
854
+ }));
855
+ }
856
+ refreshAvailableVersions() {
857
+ this.versions = fse.readdirSync(this.cwd) // Only keep root directories
858
+ .filter((filename)=>fse.statSync(path$1.join(this.cwd, filename)).isDirectory())// Paths should be valid semver
859
+ .filter((filename)=>semver.valid(filename) !== null)// Transform files names to SemVer instances
860
+ .map((version)=>semVerFactory(version))// Sort versions in ascending order
861
+ .sort(semver.compare);
862
+ return this;
863
+ }
864
+ refreshAvailableFiles() {
865
+ this.groups = {};
866
+ for (const version of this.versions){
867
+ this.refreshAvailableFilesForVersion(version);
868
+ }
869
+ }
870
+ refreshAvailableFilesForVersion(version) {
871
+ const literalVersion = version.raw;
872
+ const versionDirectory = path$1.join(this.cwd, literalVersion);
873
+ // Ignore obsolete versions
874
+ if (!fse.existsSync(versionDirectory)) {
875
+ return;
876
+ }
877
+ this.groups[literalVersion] = fse.readdirSync(versionDirectory)// Make sure the filenames are valid codemod files
878
+ .filter((filename)=>fse.statSync(path$1.join(versionDirectory, filename)).isFile()).filter((filename)=>CODEMOD_FILE_REGEXP.test(filename))// Transform the filenames into Codemod instances
879
+ .map((filename)=>{
880
+ const kind = parseCodemodKindFromFilename(filename);
881
+ const baseDirectory = this.cwd;
882
+ return codemodFactory({
883
+ kind,
884
+ baseDirectory,
885
+ version,
886
+ filename
887
+ });
888
+ });
889
+ }
890
+ constructor(cwd){
891
+ assert(fse.existsSync(cwd), `Invalid codemods directory provided "${cwd}"`);
892
+ this.cwd = cwd;
893
+ this.groups = {};
894
+ this.versions = [];
895
+ }
896
+ }
897
+ const parseCodemodKindFromFilename = (filename)=>{
898
+ const kind = filename.split('.').at(-2);
899
+ assert(kind !== undefined);
900
+ assert(CODEMOD_ALLOWED_SUFFIXES.includes(kind));
901
+ return kind;
902
+ };
903
+ const codemodRepositoryFactory = (cwd = INTERNAL_CODEMODS_DIRECTORY)=>{
904
+ return new CodemodRepository(cwd);
905
+ };
906
+
907
+ class CodemodRunner {
908
+ setRange(range) {
909
+ this.range = range;
910
+ return this;
911
+ }
912
+ setLogger(logger) {
913
+ this.logger = logger;
914
+ return this;
915
+ }
916
+ onSelectCodemods(callback) {
917
+ this.selectCodemodsCallback = callback;
918
+ return this;
919
+ }
920
+ dry(enabled = true) {
921
+ this.isDry = enabled;
922
+ return this;
923
+ }
924
+ createRepository(codemodsDirectory) {
925
+ const repository = codemodRepositoryFactory(codemodsDirectory ?? INTERNAL_CODEMODS_DIRECTORY);
926
+ // Make sure we have access to the latest snapshots of codemods on the system
927
+ repository.refresh();
928
+ return repository;
929
+ }
930
+ async safeRunAndReport(codemods) {
931
+ if (this.isDry) {
932
+ this.logger?.warn?.('Running the codemods in dry mode. No files will be modified during the process.');
933
+ }
934
+ try {
935
+ const reports$1 = await this.project.runCodemods(codemods, {
936
+ dry: this.isDry
937
+ });
938
+ this.logger?.raw?.(reports(reports$1));
939
+ if (!this.isDry) {
940
+ const nbAffectedTotal = reports$1.flatMap((report)=>report.report.ok).reduce((acc, nb)=>acc + nb, 0);
941
+ this.logger?.debug?.(`Successfully ran ${highlight(codemods.length)} codemod(s), ${highlight(nbAffectedTotal)} change(s) have been detected`);
942
+ }
943
+ return successReport$1();
944
+ } catch (e) {
945
+ return erroredReport$1(unknownToError(e));
946
+ }
947
+ }
948
+ async runByUID(uid, codemodsDirectory) {
949
+ const repository = this.createRepository(codemodsDirectory);
950
+ if (!repository.has(uid)) {
951
+ throw new Error(`Unknown codemod UID provided: ${uid}`);
952
+ }
953
+ // Note: Ignore the range when running with a UID
954
+ const codemods = repository.find({
955
+ uids: [
956
+ uid
957
+ ]
958
+ }).flatMap(({ codemods })=>codemods);
959
+ return this.safeRunAndReport(codemods);
960
+ }
961
+ async run(codemodsDirectory) {
962
+ const repository = this.createRepository(codemodsDirectory);
963
+ // Find codemods matching the given range
964
+ const codemodsInRange = repository.find({
965
+ range: this.range
966
+ });
967
+ // If a selection callback is set, use it, else keep every codemods found
968
+ const selectedCodemods = this.selectCodemodsCallback ? await this.selectCodemodsCallback(codemodsInRange) : codemodsInRange;
969
+ // If no codemods have been selected (either manually or automatically)
970
+ // Then ignore and return a successful report
971
+ if (selectedCodemods.length === 0) {
972
+ this.logger?.debug?.(`Found no codemods to run for ${versionRange(this.range)}`);
973
+ return successReport$1();
974
+ }
975
+ // Flatten the collection to a single list of codemods, the original list should already be sorted by version
976
+ const codemods = selectedCodemods.flatMap(({ codemods })=>codemods);
977
+ // Log (debug) the codemods by version
978
+ const codemodsByVersion = groupBy('version', codemods);
979
+ const fRange = versionRange(this.range);
980
+ this.logger?.debug?.(`Found ${highlight(codemods.length)} codemods for ${highlight(size(codemodsByVersion))} version(s) using ${fRange}`);
981
+ for (const [version$1, codemods] of Object.entries(codemodsByVersion)){
982
+ this.logger?.debug?.(`- ${version(semVerFactory(version$1))} (${codemods.length})`);
983
+ }
984
+ return this.safeRunAndReport(codemods);
985
+ }
986
+ constructor(project, range){
987
+ this.project = project;
988
+ this.range = range;
989
+ this.isDry = false;
990
+ this.logger = null;
991
+ this.selectCodemodsCallback = null;
992
+ }
993
+ }
994
+ const codemodRunnerFactory = (project, range)=>{
995
+ return new CodemodRunner(project, range);
996
+ };
997
+ const successReport$1 = ()=>({
998
+ success: true,
999
+ error: null
1000
+ });
1001
+ const erroredReport$1 = (error)=>({
1002
+ success: false,
1003
+ error
1004
+ });
1005
+
1006
+ class Upgrader {
1007
+ getNPMPackage() {
1008
+ return this.npmPackage;
1009
+ }
1010
+ getProject() {
1011
+ return this.project;
1012
+ }
1013
+ getTarget() {
1014
+ return semVerFactory(this.target.raw);
1015
+ }
1016
+ setRequirements(requirements) {
1017
+ this.requirements = requirements;
1018
+ return this;
1019
+ }
1020
+ setTarget(target) {
1021
+ this.target = target;
1022
+ return this;
1023
+ }
1024
+ syncCodemodsTarget() {
1025
+ // Extract the <major>.<minor>.<patch> version from the target and assign it to the codemods target
1026
+ //
1027
+ // This is useful when dealing with alphas, betas or release candidates:
1028
+ // e.g. "5.0.0-beta.951" becomes "5.0.0"
1029
+ //
1030
+ // For experimental versions (e.g. "0.0.0-experimental.hex"), it is necessary to
1031
+ // override the codemods target manually in order to run the appropriate ones.
1032
+ this.codemodsTarget = semVerFactory(`${this.target.major}.${this.target.minor}.${this.target.patch}`);
1033
+ this.logger?.debug?.(`The codemods target has been synced with the upgrade target. The codemod runner will now look for ${version(this.codemodsTarget)}`);
1034
+ return this;
1035
+ }
1036
+ overrideCodemodsTarget(target) {
1037
+ this.codemodsTarget = target;
1038
+ this.logger?.debug?.(`Overriding the codemods target. The codemod runner will now look for ${version(target)}`);
1039
+ return this;
1040
+ }
1041
+ setLogger(logger) {
1042
+ this.logger = logger;
1043
+ return this;
1044
+ }
1045
+ onConfirm(callback) {
1046
+ this.confirmationCallback = callback;
1047
+ return this;
1048
+ }
1049
+ dry(enabled = true) {
1050
+ this.isDry = enabled;
1051
+ return this;
1052
+ }
1053
+ addRequirement(requirement) {
1054
+ this.requirements.push(requirement);
1055
+ const fRequired = requirement.isRequired ? '(required)' : '(optional)';
1056
+ this.logger?.debug?.(`Added a new requirement to the upgrade: ${highlight(requirement.name)} ${fRequired}`);
1057
+ return this;
1058
+ }
1059
+ async upgrade() {
1060
+ this.logger?.info?.(`Upgrading from ${version(this.project.strapiVersion)} to ${version(this.target)}`);
1061
+ if (this.isDry) {
1062
+ this.logger?.warn?.('Running the upgrade in dry mode. No files will be modified during the process.');
1063
+ }
1064
+ const range = rangeFromVersions(this.project.strapiVersion, this.target);
1065
+ const codemodsRange = rangeFromVersions(this.project.strapiVersion, this.codemodsTarget);
1066
+ const npmVersionsMatches = this.npmPackage?.findVersionsInRange(range) ?? [];
1067
+ this.logger?.debug?.(`Found ${highlight(npmVersionsMatches.length)} versions satisfying ${versionRange(range)}`);
1068
+ try {
1069
+ this.logger?.info?.(upgradeStep('Checking requirement', [
1070
+ 1,
1071
+ 4
1072
+ ]));
1073
+ await this.checkRequirements(this.requirements, {
1074
+ npmVersionsMatches,
1075
+ project: this.project,
1076
+ target: this.target
1077
+ });
1078
+ this.logger?.info?.(upgradeStep('Applying the latest code modifications', [
1079
+ 2,
1080
+ 4
1081
+ ]));
1082
+ await this.runCodemods(codemodsRange);
1083
+ // We need to refresh the project files to make sure we have
1084
+ // the latest version of each file (including package.json) for the next steps
1085
+ this.logger?.debug?.('Refreshing project information...');
1086
+ this.project.refresh();
1087
+ this.logger?.info?.(upgradeStep('Upgrading Strapi dependencies', [
1088
+ 3,
1089
+ 4
1090
+ ]));
1091
+ await this.updateDependencies();
1092
+ this.logger?.info?.(upgradeStep('Installing dependencies', [
1093
+ 4,
1094
+ 4
1095
+ ]));
1096
+ await this.installDependencies();
1097
+ } catch (e) {
1098
+ return erroredReport(unknownToError(e));
1099
+ }
1100
+ return successReport();
1101
+ }
1102
+ async confirm(message) {
1103
+ if (typeof this.confirmationCallback !== 'function') {
1104
+ return true;
1105
+ }
1106
+ return this.confirmationCallback(message);
1107
+ }
1108
+ async checkRequirements(requirements, context) {
1109
+ for (const requirement of requirements){
1110
+ const { pass, error } = await requirement.test(context);
1111
+ if (pass) {
1112
+ await this.onSuccessfulRequirement(requirement, context);
1113
+ } else {
1114
+ await this.onFailedRequirement(requirement, error);
1115
+ }
1116
+ }
1117
+ }
1118
+ async onSuccessfulRequirement(requirement, context) {
1119
+ const hasChildren = requirement.children.length > 0;
1120
+ if (hasChildren) {
1121
+ await this.checkRequirements(requirement.children, context);
1122
+ }
1123
+ }
1124
+ async onFailedRequirement(requirement, originalError) {
1125
+ const errorMessage = `Requirement failed: ${originalError.message} (${highlight(requirement.name)})`;
1126
+ const warningMessage = originalError.message;
1127
+ const confirmationMessage = `Ignore optional requirement "${highlight(requirement.name)}" ?`;
1128
+ const error = new Error(errorMessage);
1129
+ if (requirement.isRequired) {
1130
+ throw error;
1131
+ }
1132
+ this.logger?.warn?.(warningMessage);
1133
+ const response = await this.confirmationCallback?.(confirmationMessage);
1134
+ if (!response) {
1135
+ throw error;
1136
+ }
1137
+ }
1138
+ async updateDependencies() {
1139
+ const { packageJSON, packageJSONPath } = this.project;
1140
+ const json = createJSONTransformAPI(packageJSON);
1141
+ const dependencies = json.get('dependencies', {});
1142
+ const strapiDependencies = this.getScopedStrapiDependencies(dependencies);
1143
+ this.logger?.debug?.(`Found ${highlight(strapiDependencies.length)} dependency(ies) to update`);
1144
+ strapiDependencies.forEach((dependency)=>this.logger?.debug?.(`- ${dependency[0]} (${dependency[1]} -> ${this.target})`));
1145
+ if (strapiDependencies.length === 0) {
1146
+ return;
1147
+ }
1148
+ strapiDependencies.forEach(([name])=>json.set(`dependencies.${name}`, this.target.raw));
1149
+ const updatedPackageJSON = json.root();
1150
+ if (this.isDry) {
1151
+ this.logger?.debug?.(`Skipping dependencies update (${chalk.italic('dry mode')})`);
1152
+ return;
1153
+ }
1154
+ await saveJSON(packageJSONPath, updatedPackageJSON);
1155
+ }
1156
+ getScopedStrapiDependencies(dependencies) {
1157
+ const { strapiVersion } = this.project;
1158
+ const strapiDependencies = [];
1159
+ // Find all @strapi/* packages matching the current Strapi version
1160
+ for (const [name, version] of Object.entries(dependencies)){
1161
+ const isScopedStrapiPackage = name.startsWith(SCOPED_STRAPI_PACKAGE_PREFIX);
1162
+ const isOnCurrentStrapiVersion = isValidSemVer(version) && version === strapiVersion.raw;
1163
+ if (isScopedStrapiPackage && isOnCurrentStrapiVersion) {
1164
+ strapiDependencies.push([
1165
+ name,
1166
+ semVerFactory(version)
1167
+ ]);
1168
+ }
1169
+ }
1170
+ return strapiDependencies;
1171
+ }
1172
+ async installDependencies() {
1173
+ const projectPath = this.project.cwd;
1174
+ const packageManagerName = await packageManager.getPreferred(projectPath);
1175
+ this.logger?.debug?.(`Using ${highlight(packageManagerName)} as package manager`);
1176
+ if (this.isDry) {
1177
+ this.logger?.debug?.(`Skipping dependencies installation (${chalk.italic('dry mode')})`);
1178
+ return;
1179
+ }
1180
+ await packageManager.installDependencies(projectPath, packageManagerName, {
1181
+ stdout: this.logger?.stdout,
1182
+ stderr: this.logger?.stderr
1183
+ });
1184
+ }
1185
+ async runCodemods(range) {
1186
+ const codemodRunner = codemodRunnerFactory(this.project, range);
1187
+ codemodRunner.dry(this.isDry);
1188
+ if (this.logger) {
1189
+ codemodRunner.setLogger(this.logger);
1190
+ }
1191
+ await codemodRunner.run();
1192
+ }
1193
+ constructor(project, target, npmPackage){
1194
+ this.project = project;
1195
+ this.npmPackage = npmPackage;
1196
+ this.target = target;
1197
+ this.syncCodemodsTarget();
1198
+ this.isDry = false;
1199
+ this.requirements = [];
1200
+ this.logger = null;
1201
+ this.confirmationCallback = null;
1202
+ }
1203
+ }
1204
+ /**
1205
+ * Resolves the NPM target version based on the given project, target, and NPM package.
1206
+ * If target is a SemVer, it directly finds it. If it's a release type (major, minor, patch),
1207
+ * it calculates the range of versions for this release type and returns the latest version within this range.
1208
+ */ const resolveNPMTarget = (project, target, npmPackage)=>{
1209
+ // Semver
1210
+ if (isSemverInstance(target)) {
1211
+ const version = npmPackage.findVersion(target);
1212
+ if (!version) {
1213
+ throw new NPMCandidateNotFoundError(target);
1214
+ }
1215
+ return version;
1216
+ }
1217
+ // Release Types
1218
+ if (isSemVerReleaseType(target)) {
1219
+ const range = rangeFromVersions(project.strapiVersion, target);
1220
+ const npmVersionsMatches = npmPackage.findVersionsInRange(range);
1221
+ // The targeted version is the latest one that matches the given range
1222
+ const version = npmVersionsMatches.at(-1);
1223
+ if (!version) {
1224
+ throw new NPMCandidateNotFoundError(range, `The project is already up-to-date (${target})`);
1225
+ }
1226
+ return version;
1227
+ }
1228
+ throw new NPMCandidateNotFoundError(target);
1229
+ };
1230
+ const upgraderFactory = (project, target, npmPackage)=>{
1231
+ const npmTarget = resolveNPMTarget(project, target, npmPackage);
1232
+ const semverTarget = semVerFactory(npmTarget.version);
1233
+ if (semver.eq(semverTarget, project.strapiVersion)) {
1234
+ throw new Error(`The project is already using v${semverTarget}`);
1235
+ }
1236
+ return new Upgrader(project, semverTarget, npmPackage);
1237
+ };
1238
+ const successReport = ()=>({
1239
+ success: true,
1240
+ error: null
1241
+ });
1242
+ const erroredReport = (error)=>({
1243
+ success: false,
1244
+ error
1245
+ });
1246
+
1247
+ const STRAPI_PACKAGE_NAME = '@strapi/strapi';
1248
+
1249
+ var constants = /*#__PURE__*/Object.freeze({
1250
+ __proto__: null,
1251
+ STRAPI_PACKAGE_NAME: STRAPI_PACKAGE_NAME
1252
+ });
1253
+
1254
+ class Requirement {
1255
+ setChildren(children) {
1256
+ this.children = children;
1257
+ return this;
1258
+ }
1259
+ addChild(child) {
1260
+ this.children.push(child);
1261
+ return this;
1262
+ }
1263
+ asOptional() {
1264
+ const newInstance = requirementFactory(this.name, this.testCallback, false);
1265
+ newInstance.setChildren(this.children);
1266
+ return newInstance;
1267
+ }
1268
+ asRequired() {
1269
+ const newInstance = requirementFactory(this.name, this.testCallback, true);
1270
+ newInstance.setChildren(this.children);
1271
+ return newInstance;
1272
+ }
1273
+ async test(context) {
1274
+ try {
1275
+ await this.testCallback?.(context);
1276
+ return ok();
1277
+ } catch (e) {
1278
+ if (e instanceof Error) {
1279
+ return errored(e);
1280
+ }
1281
+ if (typeof e === 'string') {
1282
+ return errored(new Error(e));
1283
+ }
1284
+ return errored(new Error('Unknown error'));
1285
+ }
1286
+ }
1287
+ constructor(name, testCallback, isRequired){
1288
+ this.name = name;
1289
+ this.testCallback = testCallback;
1290
+ this.isRequired = isRequired ?? true;
1291
+ this.children = [];
1292
+ }
1293
+ }
1294
+ const ok = ()=>({
1295
+ pass: true,
1296
+ error: null
1297
+ });
1298
+ const errored = (error)=>({
1299
+ pass: false,
1300
+ error
1301
+ });
1302
+ const requirementFactory = (name, testCallback, isRequired)=>new Requirement(name, testCallback, isRequired);
1303
+
1304
+ const REQUIRE_AVAILABLE_NEXT_MAJOR = requirementFactory('REQUIRE_AVAILABLE_NEXT_MAJOR', (context)=>{
1305
+ const { project, target } = context;
1306
+ const currentMajor = project.strapiVersion.major;
1307
+ const targetedMajor = target.major;
1308
+ if (targetedMajor === currentMajor) {
1309
+ throw new Error(`You're already on the latest major version (v${currentMajor})`);
1310
+ }
1311
+ });
1312
+ const REQUIRE_LATEST_FOR_CURRENT_MAJOR = requirementFactory('REQUIRE_LATEST_FOR_CURRENT_MAJOR', (context)=>{
1313
+ const { project, target, npmVersionsMatches } = context;
1314
+ const { major: currentMajor } = project.strapiVersion;
1315
+ const invalidMatches = npmVersionsMatches.filter((match)=>semVerFactory(match.version).major === currentMajor);
1316
+ if (invalidMatches.length > 0) {
1317
+ const invalidVersions = invalidMatches.map((match)=>match.version);
1318
+ const invalidVersionsCount = invalidVersions.length;
1319
+ throw new Error(`Doing a major upgrade requires to be on the latest v${currentMajor} version, but found ${invalidVersionsCount} versions between the current one and ${target}. Please upgrade to ${invalidVersions.at(-1)} and try again.`);
1320
+ }
1321
+ });
1322
+
1323
+ const REQUIRE_GIT_CLEAN_REPOSITORY = requirementFactory('REQUIRE_GIT_CLEAN_REPOSITORY', async (context)=>{
1324
+ const git = simpleGit({
1325
+ baseDir: context.project.cwd
1326
+ });
1327
+ const status = await git.status();
1328
+ if (!status.isClean()) {
1329
+ throw new Error('Repository is not clean. Please commit or stash any changes before upgrading');
1330
+ }
1331
+ });
1332
+ const REQUIRE_GIT_REPOSITORY = requirementFactory('REQUIRE_GIT_REPOSITORY', async (context)=>{
1333
+ const git = simpleGit({
1334
+ baseDir: context.project.cwd
1335
+ });
1336
+ const isRepo = await git.checkIsRepo();
1337
+ if (!isRepo) {
1338
+ throw new Error('Not a git repository (or any of the parent directories)');
1339
+ }
1340
+ }).addChild(REQUIRE_GIT_CLEAN_REPOSITORY.asOptional());
1341
+ const REQUIRE_GIT_INSTALLED = requirementFactory('REQUIRE_GIT_INSTALLED', async (context)=>{
1342
+ const git = simpleGit({
1343
+ baseDir: context.project.cwd
1344
+ });
1345
+ try {
1346
+ await git.version();
1347
+ } catch {
1348
+ throw new Error('Git is not installed');
1349
+ }
1350
+ }).addChild(REQUIRE_GIT_REPOSITORY.asOptional());
1351
+ const REQUIRE_GIT = requirementFactory('REQUIRE_GIT', null).addChild(REQUIRE_GIT_INSTALLED.asOptional());
1352
+
1353
+ /**
1354
+ * Handles the upgrade prompts when using the latest tag.
1355
+ *
1356
+ * - checks if an upgrade involves a major bump, warning and asking for user confirmation before proceeding
1357
+ */ const latest = async (upgrader, options)=>{
1358
+ // Exit if the upgrade target isn't the latest tag
1359
+ if (options.target !== ReleaseType.Latest) {
1360
+ return;
1361
+ }
1362
+ // Retrieve utilities from the upgrader instance
1363
+ const npmPackage = upgrader.getNPMPackage();
1364
+ const target = upgrader.getTarget();
1365
+ const project = upgrader.getProject();
1366
+ const { strapiVersion: current } = project;
1367
+ // Pre-formatted strings used in logs
1368
+ const fTargetMajor = highlight(`v${target.major}`);
1369
+ const fCurrentMajor = highlight(`v${current.major}`);
1370
+ const fTarget = version(target);
1371
+ const fCurrent = version(current);
1372
+ // Flags
1373
+ const isMajorUpgrade = target.major > current.major;
1374
+ // Handle potential major upgrade, warns, and asks for confirmation to proceed
1375
+ if (isMajorUpgrade) {
1376
+ options.logger.warn(`Detected a major upgrade for the "${highlight(ReleaseType.Latest)}" tag: ${fCurrent} > ${fTarget}`);
1377
+ // Find the latest release in between the current one and the next major
1378
+ const newerPackageRelease = npmPackage.findVersionsInRange(rangeFactory(`>${current.raw} <${target.major}`)).at(-1);
1379
+ // If the project isn't on the latest version for the current major, emit a warning
1380
+ if (newerPackageRelease) {
1381
+ const fLatest = version(semVerFactory(newerPackageRelease.version));
1382
+ options.logger.warn(`It's recommended to first upgrade to the latest version of ${fCurrentMajor} (${fLatest}) before upgrading to ${fTargetMajor}.`);
1383
+ }
1384
+ const proceedAnyway = await upgrader.confirm(`I know what I'm doing. Proceed anyway!`);
1385
+ if (!proceedAnyway) {
1386
+ throw new AbortedError();
1387
+ }
1388
+ }
1389
+ };
1390
+
1391
+ const upgrade = async (options)=>{
1392
+ const timer = timerFactory();
1393
+ const { logger, codemodsTarget } = options;
1394
+ // Resolves the correct working directory based on the given input
1395
+ const cwd = path$1.resolve(options.cwd ?? process.cwd());
1396
+ const project = projectFactory(cwd);
1397
+ logger.debug(projectDetails(project));
1398
+ if (!isApplicationProject(project)) {
1399
+ throw new Error(`The "${options.target}" upgrade can only be run on a Strapi project; for plugins, please use "codemods".`);
1400
+ }
1401
+ logger.debug(`Application: VERSION=${version(project.packageJSON.version)}; STRAPI_VERSION=${version(project.strapiVersion)}`);
1402
+ const npmPackage = npmPackageFactory(STRAPI_PACKAGE_NAME);
1403
+ // Load all available versions from the NPM registry
1404
+ await npmPackage.refresh();
1405
+ // Initialize the upgrade instance
1406
+ // Throws during initialization if the provided target is incompatible with the current version
1407
+ const upgrader = upgraderFactory(project, options.target, npmPackage).dry(options.dry ?? false).onConfirm(options.confirm ?? null).setLogger(logger);
1408
+ // Manually override the target version for codemods if it's explicitly provided
1409
+ if (codemodsTarget !== undefined) {
1410
+ upgrader.overrideCodemodsTarget(codemodsTarget);
1411
+ }
1412
+ // Prompt user for confirmation details before upgrading
1413
+ await runUpgradePrompts(upgrader, options);
1414
+ // Add specific requirements before upgrading
1415
+ addUpgradeRequirements(upgrader, options);
1416
+ // Actually run the upgrade process once configured,
1417
+ // The response contains information about the final status: success/error
1418
+ const upgradeReport = await upgrader.upgrade();
1419
+ if (!upgradeReport.success) {
1420
+ throw upgradeReport.error;
1421
+ }
1422
+ timer.stop();
1423
+ logger.info(`Completed in ${durationMs(timer.elapsedMs)}ms`);
1424
+ };
1425
+ const runUpgradePrompts = async (upgrader, options)=>{
1426
+ if (options.target === ReleaseType.Latest) {
1427
+ await latest(upgrader, options);
1428
+ }
1429
+ };
1430
+ const addUpgradeRequirements = (upgrader, options)=>{
1431
+ // Don't add the same requirements when manually targeting a major upgrade
1432
+ // using a semver as it's implied that the users know what they're doing
1433
+ if (options.target === ReleaseType.Major) {
1434
+ upgrader.addRequirement(REQUIRE_AVAILABLE_NEXT_MAJOR).addRequirement(REQUIRE_LATEST_FOR_CURRENT_MAJOR);
1435
+ }
1436
+ // Make sure the git repository is in an optimal state before running the upgrade
1437
+ // Mainly used to ease rollbacks in case the upgrade is corrupted
1438
+ upgrader.addRequirement(REQUIRE_GIT.asOptional());
1439
+ };
1440
+
1441
+ const resolvePath = (cwd)=>path$1.resolve(cwd ?? process.cwd());
1442
+ const getRangeFromTarget = (currentVersion, target)=>{
1443
+ if (isSemverInstance(target)) {
1444
+ return rangeFactory(target);
1445
+ }
1446
+ const { major, minor, patch } = currentVersion;
1447
+ switch(target){
1448
+ case ReleaseType.Latest:
1449
+ throw new Error("Can't use <latest> to create a codemods range: not implemented");
1450
+ case ReleaseType.Major:
1451
+ return rangeFactory(`${major}`);
1452
+ case ReleaseType.Minor:
1453
+ return rangeFactory(`${major}.${minor}`);
1454
+ case ReleaseType.Patch:
1455
+ return rangeFactory(`${major}.${minor}.${patch}`);
1456
+ default:
1457
+ throw new Error(`Invalid target set: ${target}`);
1458
+ }
1459
+ };
1460
+ const findRangeFromTarget = (project, target)=>{
1461
+ // If a range is manually defined, use it
1462
+ if (isRangeInstance(target)) {
1463
+ return target;
1464
+ }
1465
+ // If the current project is a Strapi application
1466
+ // Get the range from the given target
1467
+ if (isApplicationProject(project)) {
1468
+ return getRangeFromTarget(project.strapiVersion, target);
1469
+ }
1470
+ // Else, if the project is a Strapi plugin or anything else
1471
+ // Set the range to match any version
1472
+ return rangeFactory('*');
1473
+ };
1474
+
1475
+ const runCodemods = async (options)=>{
1476
+ const timer = timerFactory();
1477
+ const { logger, uid } = options;
1478
+ // Make sure we're resolving the correct working directory based on the given input
1479
+ const cwd = resolvePath(options.cwd);
1480
+ const project = projectFactory(cwd);
1481
+ const range = findRangeFromTarget(project, options.target);
1482
+ logger.debug(projectDetails(project));
1483
+ logger.debug(`Range: set to ${versionRange(range)}`);
1484
+ const codemodRunner = codemodRunnerFactory(project, range).dry(options.dry ?? false).onSelectCodemods(options.selectCodemods ?? null).setLogger(logger);
1485
+ let report;
1486
+ // If uid is defined, only run the selected codemod
1487
+ if (uid !== undefined) {
1488
+ logger.debug(`Running a single codemod: ${codemodUID(uid)}`);
1489
+ report = await codemodRunner.runByUID(uid);
1490
+ } else {
1491
+ report = await codemodRunner.run();
1492
+ }
1493
+ if (!report.success) {
1494
+ throw report.error;
1495
+ }
1496
+ timer.stop();
1497
+ logger.info(`Completed in ${timer.elapsedMs}`);
1498
+ };
1499
+
1500
+ const listCodemods = async (options)=>{
1501
+ const { logger, target } = options;
1502
+ const cwd = resolvePath(options.cwd);
1503
+ const project = projectFactory(cwd);
1504
+ const range = findRangeFromTarget(project, target);
1505
+ logger.debug(projectDetails(project));
1506
+ logger.debug(`Range: set to ${versionRange(range)}`);
1507
+ // Create a codemod repository targeting the default location of the codemods
1508
+ const repo = codemodRepositoryFactory();
1509
+ // Make sure all the codemods are loaded
1510
+ repo.refresh();
1511
+ // Find groups of codemods matching the given range
1512
+ const groups = repo.find({
1513
+ range
1514
+ });
1515
+ // Flatten the groups into a simple codemod array
1516
+ const codemods = groups.flatMap((collection)=>collection.codemods);
1517
+ // Debug
1518
+ logger.debug(`Found ${highlight(codemods.length)} codemods`);
1519
+ // Don't log an empty table
1520
+ if (codemods.length === 0) {
1521
+ logger.info(`Found no codemods matching ${versionRange(range)}`);
1522
+ return;
1523
+ }
1524
+ // Format the list to a pretty table
1525
+ const fCodemods = codemodList(codemods);
1526
+ logger.raw(fCodemods);
1527
+ };
1528
+
1529
+ class Logger {
1530
+ get isNotSilent() {
1531
+ return !this.isSilent;
1532
+ }
1533
+ get errors() {
1534
+ return this.nbErrorsCalls;
1535
+ }
1536
+ get warnings() {
1537
+ return this.nbWarningsCalls;
1538
+ }
1539
+ get stdout() {
1540
+ return this.isSilent ? undefined : process.stdout;
1541
+ }
1542
+ get stderr() {
1543
+ return this.isSilent ? undefined : process.stderr;
1544
+ }
1545
+ setDebug(debug) {
1546
+ this.isDebug = debug;
1547
+ return this;
1548
+ }
1549
+ setSilent(silent) {
1550
+ this.isSilent = silent;
1551
+ return this;
1552
+ }
1553
+ debug(...args) {
1554
+ const isDebugEnabled = this.isNotSilent && this.isDebug;
1555
+ if (isDebugEnabled) {
1556
+ console.log(chalk.cyan(`[DEBUG]\t[${nowAsISO()}]`), ...args);
1557
+ }
1558
+ return this;
1559
+ }
1560
+ error(...args) {
1561
+ this.nbErrorsCalls += 1;
1562
+ if (this.isNotSilent) {
1563
+ console.error(chalk.red(`[ERROR]\t[${nowAsISO()}]`), ...args);
1564
+ }
1565
+ return this;
1566
+ }
1567
+ info(...args) {
1568
+ if (this.isNotSilent) {
1569
+ console.info(chalk.blue(`[INFO]\t[${new Date().toISOString()}]`), ...args);
1570
+ }
1571
+ return this;
1572
+ }
1573
+ raw(...args) {
1574
+ if (this.isNotSilent) {
1575
+ console.log(...args);
1576
+ }
1577
+ return this;
1578
+ }
1579
+ warn(...args) {
1580
+ this.nbWarningsCalls += 1;
1581
+ if (this.isNotSilent) {
1582
+ console.warn(chalk.yellow(`[WARN]\t[${new Date().toISOString()}]`), ...args);
1583
+ }
1584
+ return this;
1585
+ }
1586
+ constructor(options = {}){
1587
+ // Set verbosity options
1588
+ this.isDebug = options.debug ?? false;
1589
+ this.isSilent = options.silent ?? false;
1590
+ // Initialize counters
1591
+ this.nbErrorsCalls = 0;
1592
+ this.nbWarningsCalls = 0;
1593
+ }
1594
+ }
1595
+ const nowAsISO = ()=>new Date().toISOString();
1596
+ const loggerFactory = (options = {})=>new Logger(options);
1597
+
1598
+ export { codeRunnerFactory as A, jsonRunnerFactory as B, assertAppProject as C, assertPluginProject as D, constants$3 as E, isApplicationProject as F, isPluginProject as G, projectFactory as H, AbortedError as I, unknownToError as J, codemodFactory as K, constants$2 as L, codemodRepositoryFactory as M, NPMCandidateNotFoundError as N, constants$1 as O, constants as P, upgraderFactory as Q, requirementFactory as R, listCodemods as S, runCodemods as T, UnexpectedError as U, upgrade as V, loggerFactory as W, ReleaseType as X, codemodList as a, codemodUID as b, constants$4 as c, durationMs as d, projectDetails as e, projectType as f, transform as g, highlight as h, versionRange as i, types as j, isLiteralSemVer as k, isRangeInstance as l, isSemVerReleaseType as m, isSemverInstance as n, isValidSemVer as o, path as p, isValidStringifiedRange as q, reports as r, rangeFactory as s, timerFactory as t, upgradeStep as u, version as v, rangeFromReleaseType as w, rangeFromVersions as x, semVerFactory as y, fileScannerFactory as z };
1599
+ //# sourceMappingURL=logger-DLKyDz9F.mjs.map