@strapi/upgrade 5.0.0-beta.2 → 5.0.0-beta.3
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.
- package/dist/cli.js +1452 -5
- package/dist/cli.js.map +1 -1
- package/dist/index.js +228 -92
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +229 -93
- package/dist/index.mjs.map +1 -1
- package/dist/modules/codemod/codemod.d.ts +4 -2
- package/dist/modules/codemod/codemod.d.ts.map +1 -1
- package/dist/modules/codemod/types.d.ts +8 -1
- package/dist/modules/codemod/types.d.ts.map +1 -1
- package/dist/modules/codemod-repository/constants.d.ts.map +1 -1
- package/dist/modules/codemod-repository/repository.d.ts +5 -5
- package/dist/modules/codemod-repository/repository.d.ts.map +1 -1
- package/dist/modules/codemod-repository/types.d.ts +7 -3
- package/dist/modules/codemod-repository/types.d.ts.map +1 -1
- package/dist/modules/codemod-runner/codemod-runner.d.ts +6 -3
- package/dist/modules/codemod-runner/codemod-runner.d.ts.map +1 -1
- package/dist/modules/codemod-runner/index.d.ts +1 -0
- package/dist/modules/codemod-runner/index.d.ts.map +1 -1
- package/dist/modules/codemod-runner/types.d.ts +1 -0
- package/dist/modules/codemod-runner/types.d.ts.map +1 -1
- package/dist/modules/format/formats.d.ts +5 -0
- package/dist/modules/format/formats.d.ts.map +1 -1
- package/dist/modules/project/project.d.ts +1 -1
- package/dist/modules/project/project.d.ts.map +1 -1
- package/dist/modules/project/types.d.ts +1 -0
- package/dist/modules/project/types.d.ts.map +1 -1
- package/dist/modules/project/utils.d.ts +1 -1
- package/dist/modules/project/utils.d.ts.map +1 -1
- package/dist/modules/upgrader/upgrader.d.ts.map +1 -1
- package/dist/modules/version/range.d.ts +2 -0
- package/dist/modules/version/range.d.ts.map +1 -1
- package/dist/tasks/codemods/index.d.ts +2 -1
- package/dist/tasks/codemods/index.d.ts.map +1 -1
- package/dist/tasks/codemods/list-codemods.d.ts +3 -0
- package/dist/tasks/codemods/list-codemods.d.ts.map +1 -0
- package/dist/tasks/codemods/run-codemods.d.ts +3 -0
- package/dist/tasks/codemods/run-codemods.d.ts.map +1 -0
- package/dist/tasks/codemods/types.d.ts +9 -3
- package/dist/tasks/codemods/types.d.ts.map +1 -1
- package/dist/tasks/codemods/utils.d.ts +6 -0
- package/dist/tasks/codemods/utils.d.ts.map +1 -0
- package/dist/tasks/index.d.ts +1 -1
- package/dist/tasks/index.d.ts.map +1 -1
- package/package.json +6 -6
- package/resources/codemods/5.0.0/entity-service-document-service.code.ts +374 -0
- package/resources/codemods/5.0.0/strapi-public-interface.code.ts +126 -0
- package/resources/codemods/5.0.0/utils-public-interface.code.ts +320 -0
- package/dist/_chunks/codemod-runner-LZugq_Lz.js +0 -798
- package/dist/_chunks/codemod-runner-LZugq_Lz.js.map +0 -1
- package/dist/_chunks/codemods-hZ5fds8U.js +0 -105
- package/dist/_chunks/codemods-hZ5fds8U.js.map +0 -1
- package/dist/_chunks/index-QLH4nPDk.js +0 -103
- package/dist/_chunks/index-QLH4nPDk.js.map +0 -1
- package/dist/_chunks/upgrade-ttCczKsU.js +0 -361
- package/dist/_chunks/upgrade-ttCczKsU.js.map +0 -1
- package/dist/tasks/codemods/codemods.d.ts +0 -3
- package/dist/tasks/codemods/codemods.d.ts.map +0 -1
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,1454 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
require("os");
|
|
3
|
-
require("chalk");
|
|
4
|
-
require("commander");
|
|
5
|
-
require("
|
|
6
|
-
require("semver");
|
|
2
|
+
const os = require("os");
|
|
3
|
+
const chalk = require("chalk");
|
|
4
|
+
const commander = require("commander");
|
|
5
|
+
const prompts = require("prompts");
|
|
6
|
+
const semver = require("semver");
|
|
7
|
+
const path$1 = require("node:path");
|
|
8
|
+
const simpleGit = require("simple-git");
|
|
9
|
+
const utils = require("@strapi/utils");
|
|
10
|
+
const fp = require("lodash/fp");
|
|
11
|
+
const fse = require("fs-extra");
|
|
12
|
+
const assert = require("node:assert");
|
|
13
|
+
const glob = require("glob");
|
|
14
|
+
const Runner = require("jscodeshift/src/Runner");
|
|
15
|
+
const node = require("esbuild-register/dist/node");
|
|
16
|
+
const CliTable3 = require("cli-table3");
|
|
17
|
+
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
|
|
18
|
+
const os__default = /* @__PURE__ */ _interopDefault(os);
|
|
19
|
+
const chalk__default = /* @__PURE__ */ _interopDefault(chalk);
|
|
20
|
+
const prompts__default = /* @__PURE__ */ _interopDefault(prompts);
|
|
21
|
+
const semver__default = /* @__PURE__ */ _interopDefault(semver);
|
|
22
|
+
const path__default = /* @__PURE__ */ _interopDefault(path$1);
|
|
23
|
+
const simpleGit__default = /* @__PURE__ */ _interopDefault(simpleGit);
|
|
24
|
+
const fse__default = /* @__PURE__ */ _interopDefault(fse);
|
|
25
|
+
const assert__default = /* @__PURE__ */ _interopDefault(assert);
|
|
26
|
+
const CliTable3__default = /* @__PURE__ */ _interopDefault(CliTable3);
|
|
27
|
+
class Logger {
|
|
28
|
+
isDebug;
|
|
29
|
+
isSilent;
|
|
30
|
+
nbErrorsCalls;
|
|
31
|
+
nbWarningsCalls;
|
|
32
|
+
constructor(options = {}) {
|
|
33
|
+
this.isDebug = options.debug ?? false;
|
|
34
|
+
this.isSilent = options.silent ?? false;
|
|
35
|
+
this.nbErrorsCalls = 0;
|
|
36
|
+
this.nbWarningsCalls = 0;
|
|
37
|
+
}
|
|
38
|
+
get isNotSilent() {
|
|
39
|
+
return !this.isSilent;
|
|
40
|
+
}
|
|
41
|
+
get errors() {
|
|
42
|
+
return this.nbErrorsCalls;
|
|
43
|
+
}
|
|
44
|
+
get warnings() {
|
|
45
|
+
return this.nbWarningsCalls;
|
|
46
|
+
}
|
|
47
|
+
get stdout() {
|
|
48
|
+
return this.isSilent ? void 0 : process.stdout;
|
|
49
|
+
}
|
|
50
|
+
get stderr() {
|
|
51
|
+
return this.isSilent ? void 0 : process.stderr;
|
|
52
|
+
}
|
|
53
|
+
setDebug(debug) {
|
|
54
|
+
this.isDebug = debug;
|
|
55
|
+
return this;
|
|
56
|
+
}
|
|
57
|
+
setSilent(silent) {
|
|
58
|
+
this.isSilent = silent;
|
|
59
|
+
return this;
|
|
60
|
+
}
|
|
61
|
+
debug(...args) {
|
|
62
|
+
const isDebugEnabled = this.isNotSilent && this.isDebug;
|
|
63
|
+
if (isDebugEnabled) {
|
|
64
|
+
console.log(chalk__default.default.cyan(`[DEBUG] [${nowAsISO()}]`), ...args);
|
|
65
|
+
}
|
|
66
|
+
return this;
|
|
67
|
+
}
|
|
68
|
+
error(...args) {
|
|
69
|
+
this.nbErrorsCalls += 1;
|
|
70
|
+
if (this.isNotSilent) {
|
|
71
|
+
console.error(chalk__default.default.red(`[ERROR] [${nowAsISO()}]`), ...args);
|
|
72
|
+
}
|
|
73
|
+
return this;
|
|
74
|
+
}
|
|
75
|
+
info(...args) {
|
|
76
|
+
if (this.isNotSilent) {
|
|
77
|
+
console.info(chalk__default.default.blue(`[INFO] [${(/* @__PURE__ */ new Date()).toISOString()}]`), ...args);
|
|
78
|
+
}
|
|
79
|
+
return this;
|
|
80
|
+
}
|
|
81
|
+
raw(...args) {
|
|
82
|
+
if (this.isNotSilent) {
|
|
83
|
+
console.log(...args);
|
|
84
|
+
}
|
|
85
|
+
return this;
|
|
86
|
+
}
|
|
87
|
+
warn(...args) {
|
|
88
|
+
this.nbWarningsCalls += 1;
|
|
89
|
+
if (this.isNotSilent) {
|
|
90
|
+
console.warn(chalk__default.default.yellow(`[WARN] [${(/* @__PURE__ */ new Date()).toISOString()}]`), ...args);
|
|
91
|
+
}
|
|
92
|
+
return this;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const nowAsISO = () => (/* @__PURE__ */ new Date()).toISOString();
|
|
96
|
+
const loggerFactory = (options = {}) => new Logger(options);
|
|
97
|
+
var ReleaseType = /* @__PURE__ */ ((ReleaseType2) => {
|
|
98
|
+
ReleaseType2["Major"] = "major";
|
|
99
|
+
ReleaseType2["Minor"] = "minor";
|
|
100
|
+
ReleaseType2["Patch"] = "patch";
|
|
101
|
+
return ReleaseType2;
|
|
102
|
+
})(ReleaseType || {});
|
|
103
|
+
const semVerFactory = (version2) => {
|
|
104
|
+
return new semver__default.default.SemVer(version2);
|
|
105
|
+
};
|
|
106
|
+
const isLiteralSemVer = (str) => {
|
|
107
|
+
const tokens = str.split(".");
|
|
108
|
+
return tokens.length === 3 && tokens.every((token) => !Number.isNaN(+token) && Number.isInteger(+token));
|
|
109
|
+
};
|
|
110
|
+
const isValidSemVer = (str) => semver__default.default.valid(str) !== null;
|
|
111
|
+
const isSemverInstance = (value) => {
|
|
112
|
+
return value instanceof semver__default.default.SemVer;
|
|
113
|
+
};
|
|
114
|
+
const isSemVerReleaseType = (str) => {
|
|
115
|
+
return Object.values(ReleaseType).includes(str);
|
|
116
|
+
};
|
|
117
|
+
const rangeFactory = (range) => {
|
|
118
|
+
return new semver__default.default.Range(range);
|
|
119
|
+
};
|
|
120
|
+
const rangeFromReleaseType = (current, identifier) => {
|
|
121
|
+
switch (identifier) {
|
|
122
|
+
case ReleaseType.Major: {
|
|
123
|
+
const nextMajor = semver__default.default.inc(current, "major");
|
|
124
|
+
return rangeFactory(`>${current.raw} <=${nextMajor}`);
|
|
125
|
+
}
|
|
126
|
+
case ReleaseType.Patch: {
|
|
127
|
+
const minor = semver__default.default.inc(current, "minor");
|
|
128
|
+
return rangeFactory(`>${current.raw} <${minor}`);
|
|
129
|
+
}
|
|
130
|
+
case ReleaseType.Minor: {
|
|
131
|
+
const major = semver__default.default.inc(current, "major");
|
|
132
|
+
return rangeFactory(`>${current.raw} <${major}`);
|
|
133
|
+
}
|
|
134
|
+
default: {
|
|
135
|
+
throw new Error("Not implemented");
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
const rangeFromVersions = (currentVersion, target) => {
|
|
140
|
+
if (isSemverInstance(target)) {
|
|
141
|
+
return rangeFactory(`>${currentVersion.raw} <=${target.raw}`);
|
|
142
|
+
}
|
|
143
|
+
if (isSemVerReleaseType(target)) {
|
|
144
|
+
return rangeFromReleaseType(currentVersion, target);
|
|
145
|
+
}
|
|
146
|
+
throw new Error(`Invalid target set: ${target}`);
|
|
147
|
+
};
|
|
148
|
+
const isValidStringifiedRange = (str) => semver__default.default.validRange(str) !== null;
|
|
149
|
+
const isRangeInstance = (range) => {
|
|
150
|
+
return range instanceof semver__default.default.Range;
|
|
151
|
+
};
|
|
152
|
+
const handleError = (err, isSilent) => {
|
|
153
|
+
if (!isSilent) {
|
|
154
|
+
console.error(
|
|
155
|
+
chalk__default.default.red(`[ERROR] [${(/* @__PURE__ */ new Date()).toISOString()}]`),
|
|
156
|
+
err instanceof Error ? err.message : err
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
process.exit(1);
|
|
160
|
+
};
|
|
161
|
+
class Requirement {
|
|
162
|
+
isRequired;
|
|
163
|
+
name;
|
|
164
|
+
testCallback;
|
|
165
|
+
children;
|
|
166
|
+
constructor(name, testCallback, isRequired) {
|
|
167
|
+
this.name = name;
|
|
168
|
+
this.testCallback = testCallback;
|
|
169
|
+
this.isRequired = isRequired ?? true;
|
|
170
|
+
this.children = [];
|
|
171
|
+
}
|
|
172
|
+
setChildren(children) {
|
|
173
|
+
this.children = children;
|
|
174
|
+
return this;
|
|
175
|
+
}
|
|
176
|
+
addChild(child) {
|
|
177
|
+
this.children.push(child);
|
|
178
|
+
return this;
|
|
179
|
+
}
|
|
180
|
+
asOptional() {
|
|
181
|
+
const newInstance = requirementFactory(this.name, this.testCallback, false);
|
|
182
|
+
newInstance.setChildren(this.children);
|
|
183
|
+
return newInstance;
|
|
184
|
+
}
|
|
185
|
+
asRequired() {
|
|
186
|
+
const newInstance = requirementFactory(this.name, this.testCallback, true);
|
|
187
|
+
newInstance.setChildren(this.children);
|
|
188
|
+
return newInstance;
|
|
189
|
+
}
|
|
190
|
+
async test(context) {
|
|
191
|
+
try {
|
|
192
|
+
await this.testCallback?.(context);
|
|
193
|
+
return ok();
|
|
194
|
+
} catch (e) {
|
|
195
|
+
if (e instanceof Error) {
|
|
196
|
+
return errored(e);
|
|
197
|
+
}
|
|
198
|
+
if (typeof e === "string") {
|
|
199
|
+
return errored(new Error(e));
|
|
200
|
+
}
|
|
201
|
+
return errored(new Error("Unknown error"));
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
const ok = () => ({ pass: true, error: null });
|
|
206
|
+
const errored = (error) => ({ pass: false, error });
|
|
207
|
+
const requirementFactory = (name, testCallback, isRequired) => new Requirement(name, testCallback, isRequired);
|
|
208
|
+
const REQUIRE_AVAILABLE_NEXT_MAJOR = requirementFactory(
|
|
209
|
+
"REQUIRE_AVAILABLE_NEXT_MAJOR",
|
|
210
|
+
(context) => {
|
|
211
|
+
const { project, target } = context;
|
|
212
|
+
const currentMajor = project.strapiVersion.major;
|
|
213
|
+
const targetedMajor = target.major;
|
|
214
|
+
if (targetedMajor === currentMajor) {
|
|
215
|
+
throw new Error(`You're already on the latest major version (v${currentMajor})`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
);
|
|
219
|
+
const REQUIRE_LATEST_FOR_CURRENT_MAJOR = requirementFactory(
|
|
220
|
+
"REQUIRE_LATEST_FOR_CURRENT_MAJOR",
|
|
221
|
+
(context) => {
|
|
222
|
+
const { project, target, npmVersionsMatches } = context;
|
|
223
|
+
if (npmVersionsMatches.length !== 1) {
|
|
224
|
+
const invalidVersions = npmVersionsMatches.slice(0, -1);
|
|
225
|
+
const invalidVersionsAsSemVer = invalidVersions.map((v) => v.version);
|
|
226
|
+
const nbInvalidVersions = npmVersionsMatches.length;
|
|
227
|
+
const currentMajor = project.strapiVersion.major;
|
|
228
|
+
throw new Error(
|
|
229
|
+
`Doing a major upgrade requires to be on the latest v${currentMajor} version, but found ${nbInvalidVersions} versions between the current one and ${target}: ${invalidVersionsAsSemVer}`
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
);
|
|
234
|
+
const REQUIRE_GIT_CLEAN_REPOSITORY = requirementFactory(
|
|
235
|
+
"REQUIRE_GIT_CLEAN_REPOSITORY",
|
|
236
|
+
async (context) => {
|
|
237
|
+
const git = simpleGit__default.default({ baseDir: context.project.cwd });
|
|
238
|
+
const status = await git.status();
|
|
239
|
+
if (!status.isClean()) {
|
|
240
|
+
throw new Error(
|
|
241
|
+
"Repository is not clean. Please commit or stash any changes before upgrading"
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
);
|
|
246
|
+
const REQUIRE_GIT_REPOSITORY = requirementFactory(
|
|
247
|
+
"REQUIRE_GIT_REPOSITORY",
|
|
248
|
+
async (context) => {
|
|
249
|
+
const git = simpleGit__default.default({ baseDir: context.project.cwd });
|
|
250
|
+
const isRepo = await git.checkIsRepo();
|
|
251
|
+
if (!isRepo) {
|
|
252
|
+
throw new Error("Not a git repository (or any of the parent directories)");
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
).addChild(REQUIRE_GIT_CLEAN_REPOSITORY.asOptional());
|
|
256
|
+
const REQUIRE_GIT_INSTALLED = requirementFactory(
|
|
257
|
+
"REQUIRE_GIT_INSTALLED",
|
|
258
|
+
async (context) => {
|
|
259
|
+
const git = simpleGit__default.default({ baseDir: context.project.cwd });
|
|
260
|
+
try {
|
|
261
|
+
await git.version();
|
|
262
|
+
} catch {
|
|
263
|
+
throw new Error("Git is not installed");
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
).addChild(REQUIRE_GIT_REPOSITORY.asOptional());
|
|
267
|
+
const REQUIRE_GIT = requirementFactory("REQUIRE_GIT", null).addChild(
|
|
268
|
+
REQUIRE_GIT_INSTALLED.asOptional()
|
|
269
|
+
);
|
|
270
|
+
class Timer {
|
|
271
|
+
interval;
|
|
272
|
+
constructor() {
|
|
273
|
+
this.reset();
|
|
274
|
+
}
|
|
275
|
+
get elapsedMs() {
|
|
276
|
+
const { start, end } = this.interval;
|
|
277
|
+
return end ? end - start : Date.now() - start;
|
|
278
|
+
}
|
|
279
|
+
get end() {
|
|
280
|
+
return this.interval.end;
|
|
281
|
+
}
|
|
282
|
+
get start() {
|
|
283
|
+
return this.interval.start;
|
|
284
|
+
}
|
|
285
|
+
stop() {
|
|
286
|
+
this.interval.end = Date.now();
|
|
287
|
+
return this.elapsedMs;
|
|
288
|
+
}
|
|
289
|
+
reset() {
|
|
290
|
+
this.interval = { start: Date.now(), end: null };
|
|
291
|
+
return this;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
const timerFactory = () => new Timer();
|
|
295
|
+
const ONE_SECOND_MS = 1e3;
|
|
296
|
+
class JSONTransformAPI {
|
|
297
|
+
json;
|
|
298
|
+
constructor(json) {
|
|
299
|
+
this.json = fp.cloneDeep(json);
|
|
300
|
+
}
|
|
301
|
+
get(path2, defaultValue) {
|
|
302
|
+
if (!path2) {
|
|
303
|
+
return this.root();
|
|
304
|
+
}
|
|
305
|
+
return fp.cloneDeep(fp.get(path2, this.json) ?? defaultValue);
|
|
306
|
+
}
|
|
307
|
+
has(path2) {
|
|
308
|
+
return fp.has(path2, this.json);
|
|
309
|
+
}
|
|
310
|
+
merge(other) {
|
|
311
|
+
this.json = fp.merge(other, this.json);
|
|
312
|
+
return this;
|
|
313
|
+
}
|
|
314
|
+
root() {
|
|
315
|
+
return fp.cloneDeep(this.json);
|
|
316
|
+
}
|
|
317
|
+
set(path2, value) {
|
|
318
|
+
this.json = fp.set(path2, value, this.json);
|
|
319
|
+
return this;
|
|
320
|
+
}
|
|
321
|
+
remove(path2) {
|
|
322
|
+
this.json = fp.omit(path2, this.json);
|
|
323
|
+
return this;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
const createJSONTransformAPI = (object) => new JSONTransformAPI(object);
|
|
327
|
+
const readJSON = async (path2) => {
|
|
328
|
+
const buffer = await fse__default.default.readFile(path2);
|
|
329
|
+
return JSON.parse(buffer.toString());
|
|
330
|
+
};
|
|
331
|
+
const saveJSON = async (path2, json) => {
|
|
332
|
+
const jsonAsString = `${JSON.stringify(json, null, 2)}
|
|
333
|
+
`;
|
|
334
|
+
await fse__default.default.writeFile(path2, jsonAsString);
|
|
335
|
+
};
|
|
336
|
+
class FileScanner {
|
|
337
|
+
cwd;
|
|
338
|
+
constructor(cwd) {
|
|
339
|
+
this.cwd = cwd;
|
|
340
|
+
}
|
|
341
|
+
scan(patterns) {
|
|
342
|
+
const filenames = glob.glob.sync(patterns, { cwd: this.cwd });
|
|
343
|
+
return filenames.map((filename) => path__default.default.join(this.cwd, filename));
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
const fileScannerFactory = (cwd) => new FileScanner(cwd);
|
|
347
|
+
class AbstractRunner {
|
|
348
|
+
paths;
|
|
349
|
+
configuration;
|
|
350
|
+
constructor(paths, configuration) {
|
|
351
|
+
this.paths = paths;
|
|
352
|
+
this.configuration = configuration;
|
|
353
|
+
}
|
|
354
|
+
async run(codemod, configuration) {
|
|
355
|
+
const isValidCodemod = this.valid(codemod);
|
|
356
|
+
if (!isValidCodemod) {
|
|
357
|
+
throw new Error(`Invalid codemod provided to the runner: ${codemod.filename}`);
|
|
358
|
+
}
|
|
359
|
+
const runConfiguration = { ...this.configuration, ...configuration };
|
|
360
|
+
return this.runner(codemod.path, this.paths, runConfiguration);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
class CodeRunner extends AbstractRunner {
|
|
364
|
+
runner = Runner.run;
|
|
365
|
+
valid(codemod) {
|
|
366
|
+
return codemod.kind === "code";
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
const codeRunnerFactory = (paths, configuration) => {
|
|
370
|
+
return new CodeRunner(paths, configuration);
|
|
371
|
+
};
|
|
372
|
+
const transformJSON = async (codemodPath, paths, config) => {
|
|
373
|
+
const { dry } = config;
|
|
374
|
+
const startTime = process.hrtime();
|
|
375
|
+
const report = {
|
|
376
|
+
ok: 0,
|
|
377
|
+
nochange: 0,
|
|
378
|
+
skip: 0,
|
|
379
|
+
error: 0,
|
|
380
|
+
timeElapsed: "",
|
|
381
|
+
stats: {}
|
|
382
|
+
};
|
|
383
|
+
const esbuildOptions = { extensions: [".js", ".mjs", ".ts"] };
|
|
384
|
+
const { unregister } = node.register(esbuildOptions);
|
|
385
|
+
const module = require(codemodPath);
|
|
386
|
+
unregister();
|
|
387
|
+
const codemod = typeof module.default === "function" ? module.default : module;
|
|
388
|
+
assert__default.default(typeof codemod === "function", `Codemod must be a function. Found ${typeof codemod}`);
|
|
389
|
+
for (const path2 of paths) {
|
|
390
|
+
try {
|
|
391
|
+
const json = await readJSON(path2);
|
|
392
|
+
assert__default.default(typeof json === "object" && !Array.isArray(json) && json !== null);
|
|
393
|
+
const file = { path: path2, json };
|
|
394
|
+
const params = { cwd: config.cwd, json: createJSONTransformAPI };
|
|
395
|
+
const out = await codemod(file, params);
|
|
396
|
+
if (out === void 0) {
|
|
397
|
+
report.error += 1;
|
|
398
|
+
} else if (!fp.isEqual(json, out)) {
|
|
399
|
+
if (!dry) {
|
|
400
|
+
await saveJSON(path2, out);
|
|
401
|
+
}
|
|
402
|
+
report.ok += 1;
|
|
403
|
+
} else {
|
|
404
|
+
report.nochange += 1;
|
|
405
|
+
}
|
|
406
|
+
} catch {
|
|
407
|
+
report.error += 1;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
const endTime = process.hrtime(startTime);
|
|
411
|
+
report.timeElapsed = (endTime[0] + endTime[1] / 1e9).toFixed(3);
|
|
412
|
+
return report;
|
|
413
|
+
};
|
|
414
|
+
class JSONRunner extends AbstractRunner {
|
|
415
|
+
runner = transformJSON;
|
|
416
|
+
valid(codemod) {
|
|
417
|
+
return codemod.kind === "json";
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
const jsonRunnerFactory = (paths, configuration) => {
|
|
421
|
+
return new JSONRunner(paths, configuration);
|
|
422
|
+
};
|
|
423
|
+
const PROJECT_PACKAGE_JSON = "package.json";
|
|
424
|
+
const PROJECT_DEFAULT_ALLOWED_ROOT_PATHS = ["src", "config", "public"];
|
|
425
|
+
const PROJECT_DEFAULT_CODE_EXTENSIONS = [
|
|
426
|
+
// Source files
|
|
427
|
+
"js",
|
|
428
|
+
"mjs",
|
|
429
|
+
"ts",
|
|
430
|
+
// React files
|
|
431
|
+
"jsx",
|
|
432
|
+
"tsx"
|
|
433
|
+
];
|
|
434
|
+
const PROJECT_DEFAULT_JSON_EXTENSIONS = ["json"];
|
|
435
|
+
const PROJECT_DEFAULT_ALLOWED_EXTENSIONS = [
|
|
436
|
+
...PROJECT_DEFAULT_CODE_EXTENSIONS,
|
|
437
|
+
...PROJECT_DEFAULT_JSON_EXTENSIONS
|
|
438
|
+
];
|
|
439
|
+
const PROJECT_DEFAULT_PATTERNS = ["package.json"];
|
|
440
|
+
const SCOPED_STRAPI_PACKAGE_PREFIX = "@strapi/";
|
|
441
|
+
const STRAPI_DEPENDENCY_NAME = `${SCOPED_STRAPI_PACKAGE_PREFIX}strapi`;
|
|
442
|
+
class Project {
|
|
443
|
+
cwd;
|
|
444
|
+
// The following properties are assigned during the .refresh() call in the constructor.
|
|
445
|
+
files;
|
|
446
|
+
packageJSONPath;
|
|
447
|
+
packageJSON;
|
|
448
|
+
constructor(cwd) {
|
|
449
|
+
if (!fse__default.default.pathExistsSync(cwd)) {
|
|
450
|
+
throw new Error(`ENOENT: no such file or directory, access '${cwd}'`);
|
|
451
|
+
}
|
|
452
|
+
this.cwd = cwd;
|
|
453
|
+
this.refresh();
|
|
454
|
+
}
|
|
455
|
+
getFilesByExtensions(extensions) {
|
|
456
|
+
return this.files.filter((filePath) => {
|
|
457
|
+
const fileExtension = path__default.default.extname(filePath);
|
|
458
|
+
return extensions.includes(fileExtension);
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
refresh() {
|
|
462
|
+
this.refreshPackageJSON();
|
|
463
|
+
this.refreshProjectFiles();
|
|
464
|
+
return this;
|
|
465
|
+
}
|
|
466
|
+
async runCodemods(codemods, options) {
|
|
467
|
+
const runners = this.createProjectCodemodsRunners(options.dry);
|
|
468
|
+
const reports2 = [];
|
|
469
|
+
for (const codemod of codemods) {
|
|
470
|
+
for (const runner of runners) {
|
|
471
|
+
if (runner.valid(codemod)) {
|
|
472
|
+
const report = await runner.run(codemod);
|
|
473
|
+
reports2.push({ codemod, report });
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
return reports2;
|
|
478
|
+
}
|
|
479
|
+
createProjectCodemodsRunners(dry = false) {
|
|
480
|
+
const jsonExtensions = PROJECT_DEFAULT_JSON_EXTENSIONS.map(
|
|
481
|
+
(ext) => `.${ext}`
|
|
482
|
+
);
|
|
483
|
+
const codeExtensions = PROJECT_DEFAULT_CODE_EXTENSIONS.map(
|
|
484
|
+
(ext) => `.${ext}`
|
|
485
|
+
);
|
|
486
|
+
const jsonFiles = this.getFilesByExtensions(jsonExtensions);
|
|
487
|
+
const codeFiles = this.getFilesByExtensions(codeExtensions);
|
|
488
|
+
const codeRunner = codeRunnerFactory(codeFiles, {
|
|
489
|
+
dry,
|
|
490
|
+
parser: "ts",
|
|
491
|
+
runInBand: true,
|
|
492
|
+
babel: true,
|
|
493
|
+
extensions: PROJECT_DEFAULT_CODE_EXTENSIONS.join(","),
|
|
494
|
+
// Don't output any log coming from the runner
|
|
495
|
+
print: false,
|
|
496
|
+
silent: true,
|
|
497
|
+
verbose: 0
|
|
498
|
+
});
|
|
499
|
+
const jsonRunner = jsonRunnerFactory(jsonFiles, { dry, cwd: this.cwd });
|
|
500
|
+
return [codeRunner, jsonRunner];
|
|
501
|
+
}
|
|
502
|
+
refreshPackageJSON() {
|
|
503
|
+
const packageJSONPath = path__default.default.join(this.cwd, PROJECT_PACKAGE_JSON);
|
|
504
|
+
try {
|
|
505
|
+
fse__default.default.accessSync(packageJSONPath);
|
|
506
|
+
} catch {
|
|
507
|
+
throw new Error(`Could not find a ${PROJECT_PACKAGE_JSON} file in ${this.cwd}`);
|
|
508
|
+
}
|
|
509
|
+
const packageJSONBuffer = fse__default.default.readFileSync(packageJSONPath);
|
|
510
|
+
this.packageJSONPath = packageJSONPath;
|
|
511
|
+
this.packageJSON = JSON.parse(packageJSONBuffer.toString());
|
|
512
|
+
}
|
|
513
|
+
refreshProjectFiles() {
|
|
514
|
+
const allowedRootPaths = formatGlobCollectionPattern(
|
|
515
|
+
PROJECT_DEFAULT_ALLOWED_ROOT_PATHS
|
|
516
|
+
);
|
|
517
|
+
const allowedExtensions = formatGlobCollectionPattern(
|
|
518
|
+
PROJECT_DEFAULT_ALLOWED_EXTENSIONS
|
|
519
|
+
);
|
|
520
|
+
const projectFilesPattern = `./${allowedRootPaths}/**/*.${allowedExtensions}`;
|
|
521
|
+
const patterns = [projectFilesPattern, ...PROJECT_DEFAULT_PATTERNS];
|
|
522
|
+
const scanner = fileScannerFactory(this.cwd);
|
|
523
|
+
this.files = scanner.scan(patterns);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
class AppProject extends Project {
|
|
527
|
+
strapiVersion;
|
|
528
|
+
type = "application";
|
|
529
|
+
constructor(cwd) {
|
|
530
|
+
super(cwd);
|
|
531
|
+
this.refreshStrapiVersion();
|
|
532
|
+
}
|
|
533
|
+
refresh() {
|
|
534
|
+
super.refresh();
|
|
535
|
+
this.refreshStrapiVersion();
|
|
536
|
+
return this;
|
|
537
|
+
}
|
|
538
|
+
refreshStrapiVersion() {
|
|
539
|
+
this.strapiVersion = // First try to get the strapi version from the package.json dependencies
|
|
540
|
+
this.findStrapiVersionFromProjectPackageJSON() ?? // If the version found is not a valid SemVer, get the Strapi version from the installed package
|
|
541
|
+
this.findLocallyInstalledStrapiVersion();
|
|
542
|
+
}
|
|
543
|
+
findStrapiVersionFromProjectPackageJSON() {
|
|
544
|
+
const projectName = this.packageJSON.name;
|
|
545
|
+
const version2 = this.packageJSON.dependencies?.[STRAPI_DEPENDENCY_NAME];
|
|
546
|
+
if (version2 === void 0) {
|
|
547
|
+
throw new Error(
|
|
548
|
+
`No version of ${STRAPI_DEPENDENCY_NAME} was found in ${projectName}. Are you in a valid Strapi project?`
|
|
549
|
+
);
|
|
550
|
+
}
|
|
551
|
+
const isValidSemVer2 = isLiteralSemVer(version2) && semver__default.default.valid(version2) === version2;
|
|
552
|
+
return isValidSemVer2 ? semVerFactory(version2) : void 0;
|
|
553
|
+
}
|
|
554
|
+
findLocallyInstalledStrapiVersion() {
|
|
555
|
+
const packageSearchText = `${STRAPI_DEPENDENCY_NAME}/package.json`;
|
|
556
|
+
let strapiPackageJSONPath;
|
|
557
|
+
let strapiPackageJSON;
|
|
558
|
+
try {
|
|
559
|
+
strapiPackageJSONPath = require.resolve(packageSearchText, { paths: [this.cwd] });
|
|
560
|
+
strapiPackageJSON = require(strapiPackageJSONPath);
|
|
561
|
+
assert__default.default(typeof strapiPackageJSON === "object");
|
|
562
|
+
} catch {
|
|
563
|
+
throw new Error(
|
|
564
|
+
`Cannot resolve module "${STRAPI_DEPENDENCY_NAME}" from paths [${this.cwd}]`
|
|
565
|
+
);
|
|
566
|
+
}
|
|
567
|
+
const strapiVersion = strapiPackageJSON.version;
|
|
568
|
+
if (!isValidSemVer(strapiVersion)) {
|
|
569
|
+
throw new Error(
|
|
570
|
+
`Invalid ${STRAPI_DEPENDENCY_NAME} version found in ${strapiPackageJSONPath} (${strapiVersion})`
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
return semVerFactory(strapiVersion);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
const formatGlobCollectionPattern = (collection) => {
|
|
577
|
+
assert__default.default(
|
|
578
|
+
collection.length > 0,
|
|
579
|
+
"Invalid pattern provided, the given collection needs at least 1 element"
|
|
580
|
+
);
|
|
581
|
+
return collection.length === 1 ? collection[0] : `{${collection}}`;
|
|
582
|
+
};
|
|
583
|
+
class PluginProject extends Project {
|
|
584
|
+
type = "plugin";
|
|
585
|
+
}
|
|
586
|
+
const isPlugin = (cwd) => {
|
|
587
|
+
const packageJSONPath = path__default.default.join(cwd, PROJECT_PACKAGE_JSON);
|
|
588
|
+
try {
|
|
589
|
+
fse__default.default.accessSync(packageJSONPath);
|
|
590
|
+
} catch {
|
|
591
|
+
throw new Error(`Could not find a ${PROJECT_PACKAGE_JSON} file in ${cwd}`);
|
|
592
|
+
}
|
|
593
|
+
const packageJSONBuffer = fse__default.default.readFileSync(packageJSONPath);
|
|
594
|
+
const packageJSON = JSON.parse(packageJSONBuffer.toString());
|
|
595
|
+
return packageJSON?.strapi?.kind === "plugin";
|
|
596
|
+
};
|
|
597
|
+
const projectFactory = (cwd) => {
|
|
598
|
+
fse__default.default.accessSync(cwd);
|
|
599
|
+
if (isPlugin(cwd)) {
|
|
600
|
+
return new PluginProject(cwd);
|
|
601
|
+
}
|
|
602
|
+
return new AppProject(cwd);
|
|
603
|
+
};
|
|
604
|
+
const isApplicationProject = (project) => {
|
|
605
|
+
return project instanceof AppProject;
|
|
606
|
+
};
|
|
607
|
+
class UnexpectedError extends Error {
|
|
608
|
+
constructor() {
|
|
609
|
+
super("Unexpected Error");
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
const unknownToError = (e) => {
|
|
613
|
+
if (e instanceof Error) {
|
|
614
|
+
return e;
|
|
615
|
+
}
|
|
616
|
+
if (typeof e === "string") {
|
|
617
|
+
return new Error(e);
|
|
618
|
+
}
|
|
619
|
+
return new UnexpectedError();
|
|
620
|
+
};
|
|
621
|
+
const path = (path2) => chalk__default.default.blue(path2);
|
|
622
|
+
const version$1 = (version2) => {
|
|
623
|
+
return chalk__default.default.italic.yellow(`v${version2}`);
|
|
624
|
+
};
|
|
625
|
+
const codemodUID = (uid) => {
|
|
626
|
+
return chalk__default.default.bold.cyan(uid);
|
|
627
|
+
};
|
|
628
|
+
const projectType = (type) => chalk__default.default.cyan(type);
|
|
629
|
+
const versionRange = (range) => chalk__default.default.italic.yellow(range.raw);
|
|
630
|
+
const highlight = (arg) => chalk__default.default.bold.underline(arg);
|
|
631
|
+
const upgradeStep = (text, step) => {
|
|
632
|
+
return chalk__default.default.bold(`(${step[0]}/${step[1]}) ${text}...`);
|
|
633
|
+
};
|
|
634
|
+
const reports = (reports2) => {
|
|
635
|
+
const rows = reports2.map(({ codemod, report }, i) => {
|
|
636
|
+
const fIndex = chalk__default.default.grey(i);
|
|
637
|
+
const fVersion = chalk__default.default.magenta(codemod.version);
|
|
638
|
+
const fKind = chalk__default.default.yellow(codemod.kind);
|
|
639
|
+
const fFormattedTransformPath = chalk__default.default.cyan(codemod.format());
|
|
640
|
+
const fTimeElapsed = i === 0 ? `${report.timeElapsed}s ${chalk__default.default.dim.italic("(cold start)")}` : `${report.timeElapsed}s`;
|
|
641
|
+
const fAffected = report.ok > 0 ? chalk__default.default.green(report.ok) : chalk__default.default.grey(0);
|
|
642
|
+
const fUnchanged = report.ok === 0 ? chalk__default.default.red(report.nochange) : chalk__default.default.grey(report.nochange);
|
|
643
|
+
return [fIndex, fVersion, fKind, fFormattedTransformPath, fAffected, fUnchanged, fTimeElapsed];
|
|
644
|
+
});
|
|
645
|
+
const table = new CliTable3__default.default({
|
|
646
|
+
style: { compact: true },
|
|
647
|
+
head: [
|
|
648
|
+
chalk__default.default.bold.grey("N°"),
|
|
649
|
+
chalk__default.default.bold.magenta("Version"),
|
|
650
|
+
chalk__default.default.bold.yellow("Kind"),
|
|
651
|
+
chalk__default.default.bold.cyan("Name"),
|
|
652
|
+
chalk__default.default.bold.green("Affected"),
|
|
653
|
+
chalk__default.default.bold.red("Unchanged"),
|
|
654
|
+
chalk__default.default.bold.blue("Duration")
|
|
655
|
+
]
|
|
656
|
+
});
|
|
657
|
+
table.push(...rows);
|
|
658
|
+
return table.toString();
|
|
659
|
+
};
|
|
660
|
+
const codemodList = (codemods) => {
|
|
661
|
+
const rows = codemods.map((codemod, index) => {
|
|
662
|
+
const fIndex = chalk__default.default.grey(index);
|
|
663
|
+
const fVersion = chalk__default.default.magenta(codemod.version);
|
|
664
|
+
const fKind = chalk__default.default.yellow(codemod.kind);
|
|
665
|
+
const fName = chalk__default.default.blue(codemod.format());
|
|
666
|
+
const fUID = codemodUID(codemod.uid);
|
|
667
|
+
return [fIndex, fVersion, fKind, fName, fUID];
|
|
668
|
+
});
|
|
669
|
+
const table = new CliTable3__default.default({
|
|
670
|
+
style: { compact: true },
|
|
671
|
+
head: [
|
|
672
|
+
chalk__default.default.bold.grey("N°"),
|
|
673
|
+
chalk__default.default.bold.magenta("Version"),
|
|
674
|
+
chalk__default.default.bold.yellow("Kind"),
|
|
675
|
+
chalk__default.default.bold.blue("Name"),
|
|
676
|
+
chalk__default.default.bold.cyan("UID")
|
|
677
|
+
]
|
|
678
|
+
});
|
|
679
|
+
table.push(...rows);
|
|
680
|
+
return table.toString();
|
|
681
|
+
};
|
|
682
|
+
const durationMs = (elapsedMs) => {
|
|
683
|
+
const elapsedSeconds = (elapsedMs / ONE_SECOND_MS).toFixed(3);
|
|
684
|
+
return `${elapsedSeconds}s`;
|
|
685
|
+
};
|
|
686
|
+
const CODEMOD_CODE_SUFFIX = "code";
|
|
687
|
+
const CODEMOD_JSON_SUFFIX = "json";
|
|
688
|
+
const CODEMOD_ALLOWED_SUFFIXES = [CODEMOD_CODE_SUFFIX, CODEMOD_JSON_SUFFIX];
|
|
689
|
+
const CODEMOD_EXTENSION = "ts";
|
|
690
|
+
const CODEMOD_FILE_REGEXP = new RegExp(
|
|
691
|
+
`^.+[.](${CODEMOD_ALLOWED_SUFFIXES.join("|")})[.]${CODEMOD_EXTENSION}$`
|
|
692
|
+
);
|
|
693
|
+
class Codemod {
|
|
694
|
+
uid;
|
|
695
|
+
kind;
|
|
696
|
+
version;
|
|
697
|
+
baseDirectory;
|
|
698
|
+
filename;
|
|
699
|
+
path;
|
|
700
|
+
constructor(options) {
|
|
701
|
+
this.kind = options.kind;
|
|
702
|
+
this.version = options.version;
|
|
703
|
+
this.baseDirectory = options.baseDirectory;
|
|
704
|
+
this.filename = options.filename;
|
|
705
|
+
this.path = path__default.default.join(this.baseDirectory, this.version.raw, this.filename);
|
|
706
|
+
this.uid = this.createUID();
|
|
707
|
+
}
|
|
708
|
+
createUID() {
|
|
709
|
+
const name = this.format({ stripExtension: true, stripKind: true, stripHyphens: false });
|
|
710
|
+
const kind = this.kind;
|
|
711
|
+
const version2 = this.version.raw;
|
|
712
|
+
return `${version2}-${name}-${kind}`;
|
|
713
|
+
}
|
|
714
|
+
format(options) {
|
|
715
|
+
const { stripExtension = true, stripKind = true, stripHyphens = true } = options ?? {};
|
|
716
|
+
let formatted = this.filename;
|
|
717
|
+
if (stripExtension) {
|
|
718
|
+
formatted = formatted.replace(new RegExp(`\\.${CODEMOD_EXTENSION}$`, "i"), "");
|
|
719
|
+
}
|
|
720
|
+
if (stripKind) {
|
|
721
|
+
formatted = formatted.replace(`.${CODEMOD_CODE_SUFFIX}`, "").replace(`.${CODEMOD_JSON_SUFFIX}`, "");
|
|
722
|
+
}
|
|
723
|
+
if (stripHyphens) {
|
|
724
|
+
formatted = formatted.replaceAll("-", " ");
|
|
725
|
+
}
|
|
726
|
+
return formatted;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
const codemodFactory = (options) => new Codemod(options);
|
|
730
|
+
const INTERNAL_CODEMODS_DIRECTORY = path__default.default.join(
|
|
731
|
+
__dirname,
|
|
732
|
+
// upgrade/dist
|
|
733
|
+
"..",
|
|
734
|
+
// upgrade
|
|
735
|
+
"resources",
|
|
736
|
+
// upgrade/resources
|
|
737
|
+
"codemods"
|
|
738
|
+
// upgrade/resources/codemods
|
|
739
|
+
);
|
|
740
|
+
class CodemodRepository {
|
|
741
|
+
groups;
|
|
742
|
+
versions;
|
|
743
|
+
cwd;
|
|
744
|
+
constructor(cwd) {
|
|
745
|
+
assert__default.default(fse__default.default.existsSync(cwd), `Invalid codemods directory provided "${cwd}"`);
|
|
746
|
+
this.cwd = cwd;
|
|
747
|
+
this.groups = {};
|
|
748
|
+
this.versions = [];
|
|
749
|
+
}
|
|
750
|
+
refresh() {
|
|
751
|
+
this.refreshAvailableVersions();
|
|
752
|
+
this.refreshAvailableFiles();
|
|
753
|
+
return this;
|
|
754
|
+
}
|
|
755
|
+
count(version2) {
|
|
756
|
+
return this.findByVersion(version2).length;
|
|
757
|
+
}
|
|
758
|
+
versionExists(version2) {
|
|
759
|
+
return version2.raw in this.groups;
|
|
760
|
+
}
|
|
761
|
+
has(uid) {
|
|
762
|
+
const result = this.find({ uids: [uid] });
|
|
763
|
+
if (result.length !== 1) {
|
|
764
|
+
return false;
|
|
765
|
+
}
|
|
766
|
+
const { codemods } = result[0];
|
|
767
|
+
return codemods.length === 1 && codemods[0].uid === uid;
|
|
768
|
+
}
|
|
769
|
+
find(q) {
|
|
770
|
+
const entries = Object.entries(this.groups);
|
|
771
|
+
return entries.filter(maybeFilterByRange).map(([version2, codemods]) => ({
|
|
772
|
+
version: semVerFactory(version2),
|
|
773
|
+
// Filter by UID if provided in the query
|
|
774
|
+
codemods: codemods.filter(maybeFilterByUIDs)
|
|
775
|
+
})).filter(({ codemods }) => codemods.length > 0);
|
|
776
|
+
function maybeFilterByRange([version2]) {
|
|
777
|
+
if (!isRangeInstance(q.range)) {
|
|
778
|
+
return true;
|
|
779
|
+
}
|
|
780
|
+
return q.range.test(version2);
|
|
781
|
+
}
|
|
782
|
+
function maybeFilterByUIDs(codemod) {
|
|
783
|
+
if (q.uids === void 0) {
|
|
784
|
+
return true;
|
|
785
|
+
}
|
|
786
|
+
return q.uids.includes(codemod.uid);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
findByVersion(version2) {
|
|
790
|
+
const literalVersion = version2.raw;
|
|
791
|
+
const codemods = this.groups[literalVersion];
|
|
792
|
+
return codemods ?? [];
|
|
793
|
+
}
|
|
794
|
+
findAll() {
|
|
795
|
+
const entries = Object.entries(this.groups);
|
|
796
|
+
return entries.map(([version2, codemods]) => ({
|
|
797
|
+
version: semVerFactory(version2),
|
|
798
|
+
codemods
|
|
799
|
+
}));
|
|
800
|
+
}
|
|
801
|
+
refreshAvailableVersions() {
|
|
802
|
+
this.versions = fse__default.default.readdirSync(this.cwd).filter((filename) => fse__default.default.statSync(path__default.default.join(this.cwd, filename)).isDirectory()).filter((filename) => semver__default.default.valid(filename) !== null).map((version2) => semVerFactory(version2)).sort(semver__default.default.compare);
|
|
803
|
+
return this;
|
|
804
|
+
}
|
|
805
|
+
refreshAvailableFiles() {
|
|
806
|
+
this.groups = {};
|
|
807
|
+
for (const version2 of this.versions) {
|
|
808
|
+
this.refreshAvailableFilesForVersion(version2);
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
refreshAvailableFilesForVersion(version2) {
|
|
812
|
+
const literalVersion = version2.raw;
|
|
813
|
+
const versionDirectory = path__default.default.join(this.cwd, literalVersion);
|
|
814
|
+
if (!fse__default.default.existsSync(versionDirectory)) {
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
this.groups[literalVersion] = fse__default.default.readdirSync(versionDirectory).filter((filename) => fse__default.default.statSync(path__default.default.join(versionDirectory, filename)).isFile()).filter((filename) => CODEMOD_FILE_REGEXP.test(filename)).map((filename) => {
|
|
818
|
+
const kind = parseCodemodKindFromFilename(filename);
|
|
819
|
+
const baseDirectory = this.cwd;
|
|
820
|
+
return codemodFactory({ kind, baseDirectory, version: version2, filename });
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
const parseCodemodKindFromFilename = (filename) => {
|
|
825
|
+
const kind = filename.split(".").at(-2);
|
|
826
|
+
assert__default.default(kind !== void 0);
|
|
827
|
+
assert__default.default(CODEMOD_ALLOWED_SUFFIXES.includes(kind));
|
|
828
|
+
return kind;
|
|
829
|
+
};
|
|
830
|
+
const codemodRepositoryFactory = (cwd = INTERNAL_CODEMODS_DIRECTORY) => {
|
|
831
|
+
return new CodemodRepository(cwd);
|
|
832
|
+
};
|
|
833
|
+
class CodemodRunner {
|
|
834
|
+
project;
|
|
835
|
+
range;
|
|
836
|
+
isDry;
|
|
837
|
+
logger;
|
|
838
|
+
selectCodemodsCallback;
|
|
839
|
+
constructor(project, range) {
|
|
840
|
+
this.project = project;
|
|
841
|
+
this.range = range;
|
|
842
|
+
this.isDry = false;
|
|
843
|
+
this.logger = null;
|
|
844
|
+
this.selectCodemodsCallback = null;
|
|
845
|
+
}
|
|
846
|
+
setRange(range) {
|
|
847
|
+
this.range = range;
|
|
848
|
+
return this;
|
|
849
|
+
}
|
|
850
|
+
setLogger(logger) {
|
|
851
|
+
this.logger = logger;
|
|
852
|
+
return this;
|
|
853
|
+
}
|
|
854
|
+
onSelectCodemods(callback) {
|
|
855
|
+
this.selectCodemodsCallback = callback;
|
|
856
|
+
return this;
|
|
857
|
+
}
|
|
858
|
+
dry(enabled = true) {
|
|
859
|
+
this.isDry = enabled;
|
|
860
|
+
return this;
|
|
861
|
+
}
|
|
862
|
+
createRepository(codemodsDirectory) {
|
|
863
|
+
const repository = codemodRepositoryFactory(
|
|
864
|
+
codemodsDirectory ?? INTERNAL_CODEMODS_DIRECTORY
|
|
865
|
+
);
|
|
866
|
+
repository.refresh();
|
|
867
|
+
return repository;
|
|
868
|
+
}
|
|
869
|
+
async safeRunAndReport(codemods) {
|
|
870
|
+
if (this.isDry) {
|
|
871
|
+
this.logger?.warn?.(
|
|
872
|
+
"Running the codemods in dry mode. No files will be modified during the process."
|
|
873
|
+
);
|
|
874
|
+
}
|
|
875
|
+
try {
|
|
876
|
+
const reports$1 = await this.project.runCodemods(codemods, { dry: this.isDry });
|
|
877
|
+
this.logger?.raw?.(reports(reports$1));
|
|
878
|
+
if (!this.isDry) {
|
|
879
|
+
const nbAffectedTotal = reports$1.flatMap((report) => report.report.ok).reduce((acc, nb) => acc + nb, 0);
|
|
880
|
+
this.logger?.debug?.(
|
|
881
|
+
`Successfully ran ${highlight(codemods.length)} codemod(s), ${highlight(nbAffectedTotal)} change(s) have been detected`
|
|
882
|
+
);
|
|
883
|
+
}
|
|
884
|
+
return successReport$1();
|
|
885
|
+
} catch (e) {
|
|
886
|
+
return erroredReport$1(unknownToError(e));
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
async runByUID(uid, codemodsDirectory) {
|
|
890
|
+
const repository = this.createRepository(codemodsDirectory);
|
|
891
|
+
if (!repository.has(uid)) {
|
|
892
|
+
throw new Error(`Unknown codemod UID provided: ${uid}`);
|
|
893
|
+
}
|
|
894
|
+
const codemods = repository.find({ uids: [uid] }).flatMap(({ codemods: codemods2 }) => codemods2);
|
|
895
|
+
return this.safeRunAndReport(codemods);
|
|
896
|
+
}
|
|
897
|
+
async run(codemodsDirectory) {
|
|
898
|
+
const repository = this.createRepository(codemodsDirectory);
|
|
899
|
+
const codemodsInRange = repository.find({ range: this.range });
|
|
900
|
+
const selectedCodemods = this.selectCodemodsCallback ? await this.selectCodemodsCallback(codemodsInRange) : codemodsInRange;
|
|
901
|
+
if (selectedCodemods.length === 0) {
|
|
902
|
+
this.logger?.debug?.(`Found no codemods to run for ${versionRange(this.range)}`);
|
|
903
|
+
return successReport$1();
|
|
904
|
+
}
|
|
905
|
+
const codemods = selectedCodemods.flatMap(({ codemods: codemods2 }) => codemods2);
|
|
906
|
+
const codemodsByVersion = fp.groupBy("version", codemods);
|
|
907
|
+
const fRange = versionRange(this.range);
|
|
908
|
+
this.logger?.debug?.(
|
|
909
|
+
`Found ${highlight(codemods.length)} codemods for ${highlight(fp.size(codemodsByVersion))} version(s) using ${fRange}`
|
|
910
|
+
);
|
|
911
|
+
for (const [version2, codemods2] of Object.entries(codemodsByVersion)) {
|
|
912
|
+
this.logger?.debug?.(`- ${version$1(semVerFactory(version2))} (${codemods2.length})`);
|
|
913
|
+
}
|
|
914
|
+
return this.safeRunAndReport(codemods);
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
const codemodRunnerFactory = (project, range) => {
|
|
918
|
+
return new CodemodRunner(project, range);
|
|
919
|
+
};
|
|
920
|
+
const successReport$1 = () => ({ success: true, error: null });
|
|
921
|
+
const erroredReport$1 = (error) => ({ success: false, error });
|
|
922
|
+
class Upgrader {
|
|
923
|
+
project;
|
|
924
|
+
npmPackage;
|
|
925
|
+
target;
|
|
926
|
+
codemodsTarget;
|
|
927
|
+
isDry;
|
|
928
|
+
logger;
|
|
929
|
+
requirements;
|
|
930
|
+
confirmationCallback;
|
|
931
|
+
constructor(project, target, npmPackage) {
|
|
932
|
+
this.project = project;
|
|
933
|
+
this.npmPackage = npmPackage;
|
|
934
|
+
this.target = target;
|
|
935
|
+
this.syncCodemodsTarget();
|
|
936
|
+
this.isDry = false;
|
|
937
|
+
this.requirements = [];
|
|
938
|
+
this.logger = null;
|
|
939
|
+
this.confirmationCallback = null;
|
|
940
|
+
}
|
|
941
|
+
setRequirements(requirements) {
|
|
942
|
+
this.requirements = requirements;
|
|
943
|
+
return this;
|
|
944
|
+
}
|
|
945
|
+
setTarget(target) {
|
|
946
|
+
this.target = target;
|
|
947
|
+
return this;
|
|
948
|
+
}
|
|
949
|
+
syncCodemodsTarget() {
|
|
950
|
+
this.codemodsTarget = semVerFactory(
|
|
951
|
+
`${this.target.major}.${this.target.minor}.${this.target.patch}`
|
|
952
|
+
);
|
|
953
|
+
this.logger?.debug?.(
|
|
954
|
+
`The codemods target has been synced with the upgrade target. The codemod runner will now look for ${version$1(
|
|
955
|
+
this.codemodsTarget
|
|
956
|
+
)}`
|
|
957
|
+
);
|
|
958
|
+
return this;
|
|
959
|
+
}
|
|
960
|
+
overrideCodemodsTarget(target) {
|
|
961
|
+
this.codemodsTarget = target;
|
|
962
|
+
this.logger?.debug?.(
|
|
963
|
+
`Overriding the codemods target. The codemod runner will now look for ${version$1(target)}`
|
|
964
|
+
);
|
|
965
|
+
return this;
|
|
966
|
+
}
|
|
967
|
+
setLogger(logger) {
|
|
968
|
+
this.logger = logger;
|
|
969
|
+
return this;
|
|
970
|
+
}
|
|
971
|
+
onConfirm(callback) {
|
|
972
|
+
this.confirmationCallback = callback;
|
|
973
|
+
return this;
|
|
974
|
+
}
|
|
975
|
+
dry(enabled = true) {
|
|
976
|
+
this.isDry = enabled;
|
|
977
|
+
return this;
|
|
978
|
+
}
|
|
979
|
+
addRequirement(requirement) {
|
|
980
|
+
this.requirements.push(requirement);
|
|
981
|
+
const fRequired = requirement.isRequired ? "(required)" : "(optional)";
|
|
982
|
+
this.logger?.debug?.(
|
|
983
|
+
`Added a new requirement to the upgrade: ${highlight(requirement.name)} ${fRequired}`
|
|
984
|
+
);
|
|
985
|
+
return this;
|
|
986
|
+
}
|
|
987
|
+
async upgrade() {
|
|
988
|
+
this.logger?.info?.(
|
|
989
|
+
`Upgrading from ${version$1(this.project.strapiVersion)} to ${version$1(this.target)}`
|
|
990
|
+
);
|
|
991
|
+
if (this.isDry) {
|
|
992
|
+
this.logger?.warn?.(
|
|
993
|
+
"Running the upgrade in dry mode. No files will be modified during the process."
|
|
994
|
+
);
|
|
995
|
+
}
|
|
996
|
+
const range = rangeFromVersions(this.project.strapiVersion, this.target);
|
|
997
|
+
const codemodsRange = rangeFromVersions(this.project.strapiVersion, this.codemodsTarget);
|
|
998
|
+
const npmVersionsMatches = this.npmPackage?.findVersionsInRange(range) ?? [];
|
|
999
|
+
this.logger?.debug?.(
|
|
1000
|
+
`Found ${highlight(npmVersionsMatches.length)} versions satisfying ${versionRange(range)}`
|
|
1001
|
+
);
|
|
1002
|
+
try {
|
|
1003
|
+
this.logger?.info?.(upgradeStep("Checking requirement", [1, 4]));
|
|
1004
|
+
await this.checkRequirements(this.requirements, {
|
|
1005
|
+
npmVersionsMatches,
|
|
1006
|
+
project: this.project,
|
|
1007
|
+
target: this.target
|
|
1008
|
+
});
|
|
1009
|
+
this.logger?.info?.(upgradeStep("Applying the latest code modifications", [2, 4]));
|
|
1010
|
+
await this.runCodemods(codemodsRange);
|
|
1011
|
+
this.logger?.debug?.("Refreshing project information...");
|
|
1012
|
+
this.project.refresh();
|
|
1013
|
+
this.logger?.info?.(upgradeStep("Upgrading Strapi dependencies", [3, 4]));
|
|
1014
|
+
await this.updateDependencies();
|
|
1015
|
+
this.logger?.info?.(upgradeStep("Installing dependencies", [4, 4]));
|
|
1016
|
+
await this.installDependencies();
|
|
1017
|
+
} catch (e) {
|
|
1018
|
+
return erroredReport(unknownToError(e));
|
|
1019
|
+
}
|
|
1020
|
+
return successReport();
|
|
1021
|
+
}
|
|
1022
|
+
async checkRequirements(requirements, context) {
|
|
1023
|
+
for (const requirement of requirements) {
|
|
1024
|
+
const { pass, error } = await requirement.test(context);
|
|
1025
|
+
if (pass) {
|
|
1026
|
+
await this.onSuccessfulRequirement(requirement, context);
|
|
1027
|
+
} else {
|
|
1028
|
+
await this.onFailedRequirement(requirement, error);
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
async onSuccessfulRequirement(requirement, context) {
|
|
1033
|
+
const hasChildren = requirement.children.length > 0;
|
|
1034
|
+
if (hasChildren) {
|
|
1035
|
+
await this.checkRequirements(requirement.children, context);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
async onFailedRequirement(requirement, originalError) {
|
|
1039
|
+
const errorMessage = `Requirement failed: ${originalError.message} (${highlight(
|
|
1040
|
+
requirement.name
|
|
1041
|
+
)})`;
|
|
1042
|
+
const warningMessage = originalError.message;
|
|
1043
|
+
const confirmationMessage = `Ignore optional requirement "${highlight(requirement.name)}" ?`;
|
|
1044
|
+
const error = new Error(errorMessage);
|
|
1045
|
+
if (requirement.isRequired) {
|
|
1046
|
+
throw error;
|
|
1047
|
+
}
|
|
1048
|
+
this.logger?.warn?.(warningMessage);
|
|
1049
|
+
const response = await this.confirmationCallback?.(confirmationMessage);
|
|
1050
|
+
if (!response) {
|
|
1051
|
+
throw error;
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
async updateDependencies() {
|
|
1055
|
+
const { packageJSON, packageJSONPath } = this.project;
|
|
1056
|
+
const json = createJSONTransformAPI(packageJSON);
|
|
1057
|
+
const dependencies = json.get("dependencies", {});
|
|
1058
|
+
const strapiDependencies = this.getScopedStrapiDependencies(dependencies);
|
|
1059
|
+
this.logger?.debug?.(
|
|
1060
|
+
`Found ${highlight(strapiDependencies.length)} dependency(ies) to update`
|
|
1061
|
+
);
|
|
1062
|
+
strapiDependencies.forEach(
|
|
1063
|
+
(dependency) => this.logger?.debug?.(`- ${dependency[0]} (${dependency[1]} -> ${this.target})`)
|
|
1064
|
+
);
|
|
1065
|
+
if (strapiDependencies.length === 0) {
|
|
1066
|
+
return;
|
|
1067
|
+
}
|
|
1068
|
+
strapiDependencies.forEach(([name]) => json.set(`dependencies.${name}`, this.target.raw));
|
|
1069
|
+
const updatedPackageJSON = json.root();
|
|
1070
|
+
if (this.isDry) {
|
|
1071
|
+
this.logger?.debug?.(`Skipping dependencies update (${chalk__default.default.italic("dry mode")})`);
|
|
1072
|
+
return;
|
|
1073
|
+
}
|
|
1074
|
+
await saveJSON(packageJSONPath, updatedPackageJSON);
|
|
1075
|
+
}
|
|
1076
|
+
getScopedStrapiDependencies(dependencies) {
|
|
1077
|
+
const { strapiVersion } = this.project;
|
|
1078
|
+
const strapiDependencies = [];
|
|
1079
|
+
for (const [name, version2] of Object.entries(dependencies)) {
|
|
1080
|
+
const isScopedStrapiPackage = name.startsWith(SCOPED_STRAPI_PACKAGE_PREFIX);
|
|
1081
|
+
const isOnCurrentStrapiVersion = isValidSemVer(version2) && version2 === strapiVersion.raw;
|
|
1082
|
+
if (isScopedStrapiPackage && isOnCurrentStrapiVersion) {
|
|
1083
|
+
strapiDependencies.push([name, semVerFactory(version2)]);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
return strapiDependencies;
|
|
1087
|
+
}
|
|
1088
|
+
async installDependencies() {
|
|
1089
|
+
const projectPath = this.project.cwd;
|
|
1090
|
+
const packageManagerName = await utils.packageManager.getPreferred(projectPath);
|
|
1091
|
+
this.logger?.debug?.(`Using ${highlight(packageManagerName)} as package manager`);
|
|
1092
|
+
if (this.isDry) {
|
|
1093
|
+
this.logger?.debug?.(`Skipping dependencies installation (${chalk__default.default.italic("dry mode")}`);
|
|
1094
|
+
return;
|
|
1095
|
+
}
|
|
1096
|
+
await utils.packageManager.installDependencies(projectPath, packageManagerName, {
|
|
1097
|
+
stdout: this.logger?.stdout,
|
|
1098
|
+
stderr: this.logger?.stderr
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
async runCodemods(range) {
|
|
1102
|
+
const codemodRunner = codemodRunnerFactory(this.project, range);
|
|
1103
|
+
codemodRunner.dry(this.isDry);
|
|
1104
|
+
if (this.logger) {
|
|
1105
|
+
codemodRunner.setLogger(this.logger);
|
|
1106
|
+
}
|
|
1107
|
+
await codemodRunner.run();
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
const resolveNPMTarget = (project, target, npmPackage) => {
|
|
1111
|
+
if (isSemverInstance(target)) {
|
|
1112
|
+
return npmPackage.findVersion(target);
|
|
1113
|
+
}
|
|
1114
|
+
if (isSemVerReleaseType(target)) {
|
|
1115
|
+
const range = rangeFromVersions(project.strapiVersion, target);
|
|
1116
|
+
const npmVersionsMatches = npmPackage.findVersionsInRange(range);
|
|
1117
|
+
return npmVersionsMatches.at(-1);
|
|
1118
|
+
}
|
|
1119
|
+
return void 0;
|
|
1120
|
+
};
|
|
1121
|
+
const upgraderFactory = (project, target, npmPackage) => {
|
|
1122
|
+
const targetedNPMVersion = resolveNPMTarget(project, target, npmPackage);
|
|
1123
|
+
if (!targetedNPMVersion) {
|
|
1124
|
+
throw new Error(`Couldn't find a matching version in the NPM registry for "${target}"`);
|
|
1125
|
+
}
|
|
1126
|
+
const semverTarget = semVerFactory(targetedNPMVersion.version);
|
|
1127
|
+
if (semver__default.default.eq(semverTarget, project.strapiVersion)) {
|
|
1128
|
+
throw new Error(`The project is already on ${version$1(semverTarget)}`);
|
|
1129
|
+
}
|
|
1130
|
+
return new Upgrader(project, semverTarget, npmPackage);
|
|
1131
|
+
};
|
|
1132
|
+
const successReport = () => ({ success: true, error: null });
|
|
1133
|
+
const erroredReport = (error) => ({ success: false, error });
|
|
1134
|
+
const STRAPI_PACKAGE_NAME = "@strapi/strapi";
|
|
1135
|
+
const NPM_REGISTRY_URL = "https://registry.npmjs.org";
|
|
1136
|
+
class Package {
|
|
1137
|
+
name;
|
|
1138
|
+
packageURL;
|
|
1139
|
+
npmPackage;
|
|
1140
|
+
constructor(name) {
|
|
1141
|
+
this.name = name;
|
|
1142
|
+
this.packageURL = `${NPM_REGISTRY_URL}/${name}`;
|
|
1143
|
+
this.npmPackage = null;
|
|
1144
|
+
}
|
|
1145
|
+
get isLoaded() {
|
|
1146
|
+
return this.npmPackage !== null;
|
|
1147
|
+
}
|
|
1148
|
+
assertPackageIsLoaded(npmPackage) {
|
|
1149
|
+
assert__default.default(this.isLoaded, "The package is not loaded yet");
|
|
1150
|
+
}
|
|
1151
|
+
getVersionsDict() {
|
|
1152
|
+
this.assertPackageIsLoaded(this.npmPackage);
|
|
1153
|
+
return this.npmPackage.versions;
|
|
1154
|
+
}
|
|
1155
|
+
getVersionsAsList() {
|
|
1156
|
+
this.assertPackageIsLoaded(this.npmPackage);
|
|
1157
|
+
return Object.values(this.npmPackage.versions);
|
|
1158
|
+
}
|
|
1159
|
+
findVersionsInRange(range) {
|
|
1160
|
+
const versions = this.getVersionsAsList();
|
|
1161
|
+
return versions.filter((v) => range.test(v.version)).filter((v) => isLiteralSemVer(v.version)).sort((v1, v2) => semver__default.default.compare(v1.version, v2.version));
|
|
1162
|
+
}
|
|
1163
|
+
findVersion(version2) {
|
|
1164
|
+
const versions = this.getVersionsAsList();
|
|
1165
|
+
return versions.find((npmVersion) => semver__default.default.eq(npmVersion.version, version2));
|
|
1166
|
+
}
|
|
1167
|
+
async refresh() {
|
|
1168
|
+
const response = await fetch(this.packageURL);
|
|
1169
|
+
assert__default.default(response.ok, `Request failed for ${this.packageURL}`);
|
|
1170
|
+
this.npmPackage = await response.json();
|
|
1171
|
+
return this;
|
|
1172
|
+
}
|
|
1173
|
+
versionExists(version2) {
|
|
1174
|
+
return this.findVersion(version2) !== void 0;
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
const npmPackageFactory = (name) => new Package(name);
|
|
1178
|
+
const upgrade$1 = async (options) => {
|
|
1179
|
+
const timer = timerFactory();
|
|
1180
|
+
const { logger, codemodsTarget } = options;
|
|
1181
|
+
const cwd = path__default.default.resolve(options.cwd ?? process.cwd());
|
|
1182
|
+
const project = projectFactory(cwd);
|
|
1183
|
+
if (!isApplicationProject(project)) {
|
|
1184
|
+
throw new Error(
|
|
1185
|
+
`The "${options.target}" upgrade can only be run on a Strapi project; for plugins, please use "codemods".`
|
|
1186
|
+
);
|
|
1187
|
+
}
|
|
1188
|
+
const npmPackage = npmPackageFactory(STRAPI_PACKAGE_NAME);
|
|
1189
|
+
await npmPackage.refresh();
|
|
1190
|
+
const upgrader = upgraderFactory(project, options.target, npmPackage).dry(options.dry ?? false).onConfirm(options.confirm ?? null).setLogger(logger);
|
|
1191
|
+
if (codemodsTarget !== void 0) {
|
|
1192
|
+
upgrader.overrideCodemodsTarget(codemodsTarget);
|
|
1193
|
+
}
|
|
1194
|
+
if (options.target === ReleaseType.Major) {
|
|
1195
|
+
upgrader.addRequirement(REQUIRE_AVAILABLE_NEXT_MAJOR).addRequirement(REQUIRE_LATEST_FOR_CURRENT_MAJOR);
|
|
1196
|
+
}
|
|
1197
|
+
upgrader.addRequirement(REQUIRE_GIT.asOptional());
|
|
1198
|
+
const upgradeReport = await upgrader.upgrade();
|
|
1199
|
+
if (!upgradeReport.success) {
|
|
1200
|
+
throw upgradeReport.error;
|
|
1201
|
+
}
|
|
1202
|
+
timer.stop();
|
|
1203
|
+
logger.info(`Completed in ${durationMs(timer.elapsedMs)}`);
|
|
1204
|
+
};
|
|
1205
|
+
const resolvePath = (cwd) => path__default.default.resolve(cwd ?? process.cwd());
|
|
1206
|
+
const getRangeFromTarget = (currentVersion, target) => {
|
|
1207
|
+
if (isSemverInstance(target)) {
|
|
1208
|
+
return rangeFactory(target);
|
|
1209
|
+
}
|
|
1210
|
+
const { major, minor, patch } = currentVersion;
|
|
1211
|
+
switch (target) {
|
|
1212
|
+
case ReleaseType.Major:
|
|
1213
|
+
return rangeFactory(`${major}`);
|
|
1214
|
+
case ReleaseType.Minor:
|
|
1215
|
+
return rangeFactory(`${major}.${minor}`);
|
|
1216
|
+
case ReleaseType.Patch:
|
|
1217
|
+
return rangeFactory(`${major}.${minor}.${patch}`);
|
|
1218
|
+
default:
|
|
1219
|
+
throw new Error(`Invalid target set: ${target}`);
|
|
1220
|
+
}
|
|
1221
|
+
};
|
|
1222
|
+
const findRangeFromTarget = (project, target) => {
|
|
1223
|
+
if (isRangeInstance(target)) {
|
|
1224
|
+
return target;
|
|
1225
|
+
}
|
|
1226
|
+
if (isApplicationProject(project)) {
|
|
1227
|
+
return getRangeFromTarget(project.strapiVersion, target);
|
|
1228
|
+
}
|
|
1229
|
+
return rangeFactory("*");
|
|
1230
|
+
};
|
|
1231
|
+
const runCodemods$1 = async (options) => {
|
|
1232
|
+
const timer = timerFactory();
|
|
1233
|
+
const { logger, uid } = options;
|
|
1234
|
+
const cwd = resolvePath(options.cwd);
|
|
1235
|
+
const project = projectFactory(cwd);
|
|
1236
|
+
const range = findRangeFromTarget(project, options.target);
|
|
1237
|
+
logger.debug(`Project: ${projectType(project.type)} found in ${path(cwd)}`);
|
|
1238
|
+
logger.debug(`Range: set to ${versionRange(range)}`);
|
|
1239
|
+
const codemodRunner = codemodRunnerFactory(project, range).dry(options.dry ?? false).onSelectCodemods(options.selectCodemods ?? null).setLogger(logger);
|
|
1240
|
+
let report;
|
|
1241
|
+
if (uid !== void 0) {
|
|
1242
|
+
logger.debug(`Running a single codemod: ${codemodUID(uid)}`);
|
|
1243
|
+
report = await codemodRunner.runByUID(uid);
|
|
1244
|
+
} else {
|
|
1245
|
+
report = await codemodRunner.run();
|
|
1246
|
+
}
|
|
1247
|
+
if (!report.success) {
|
|
1248
|
+
throw report.error;
|
|
1249
|
+
}
|
|
1250
|
+
timer.stop();
|
|
1251
|
+
logger.info(`Completed in ${timer.elapsedMs}`);
|
|
1252
|
+
};
|
|
1253
|
+
const listCodemods$1 = async (options) => {
|
|
1254
|
+
const { logger, target } = options;
|
|
1255
|
+
const cwd = resolvePath(options.cwd);
|
|
1256
|
+
const project = projectFactory(cwd);
|
|
1257
|
+
const range = findRangeFromTarget(project, target);
|
|
1258
|
+
logger.debug(`Project: ${projectType(project.type)} found in ${path(cwd)}`);
|
|
1259
|
+
logger.debug(`Range: set to ${versionRange(range)}`);
|
|
1260
|
+
const repo = codemodRepositoryFactory();
|
|
1261
|
+
repo.refresh();
|
|
1262
|
+
const groups = repo.find({ range });
|
|
1263
|
+
const codemods = groups.flatMap((collection) => collection.codemods);
|
|
1264
|
+
logger.debug(`Found ${highlight(codemods.length)} codemods`);
|
|
1265
|
+
if (codemods.length === 0) {
|
|
1266
|
+
logger.info(`Found no codemods matching ${versionRange(range)}`);
|
|
1267
|
+
return;
|
|
1268
|
+
}
|
|
1269
|
+
const fCodemods = codemodList(codemods);
|
|
1270
|
+
logger.raw(fCodemods);
|
|
1271
|
+
};
|
|
1272
|
+
const projectPathOption = new commander.Option(
|
|
1273
|
+
"-p, --project-path <project-path>",
|
|
1274
|
+
"Root path to the Strapi application or plugin"
|
|
1275
|
+
);
|
|
1276
|
+
const dryOption = new commander.Option(
|
|
1277
|
+
"-n, --dry",
|
|
1278
|
+
"Simulate the upgrade without updating any files"
|
|
1279
|
+
).default(false);
|
|
1280
|
+
const debugOption = new commander.Option("-d, --debug", "Get more logs in debug mode").default(false);
|
|
1281
|
+
const silentOption = new commander.Option("-s, --silent", "Don't log anything").default(false);
|
|
1282
|
+
const autoConfirmOption = new commander.Option(
|
|
1283
|
+
"-y, --yes",
|
|
1284
|
+
'Automatically answer "yes" to any prompts that the CLI might print on the command line.'
|
|
1285
|
+
).default(false);
|
|
1286
|
+
const rangeOption = new commander.Option(
|
|
1287
|
+
"-r, --range <range>",
|
|
1288
|
+
"Use a custom semver range for the codemods execution."
|
|
1289
|
+
).argParser((range) => {
|
|
1290
|
+
if (!isValidStringifiedRange(range)) {
|
|
1291
|
+
throw new commander.InvalidArgumentError("Expected a valid semver range");
|
|
1292
|
+
}
|
|
1293
|
+
return rangeFactory(range);
|
|
1294
|
+
});
|
|
1295
|
+
const upgrade = async (options) => {
|
|
1296
|
+
try {
|
|
1297
|
+
const { silent, debug, yes } = options;
|
|
1298
|
+
const logger = loggerFactory({ silent, debug });
|
|
1299
|
+
logger.warn(
|
|
1300
|
+
"Please make sure you've created a backup of your codebase and files before upgrading"
|
|
1301
|
+
);
|
|
1302
|
+
const confirm = async (message) => {
|
|
1303
|
+
if (yes) {
|
|
1304
|
+
return true;
|
|
1305
|
+
}
|
|
1306
|
+
const { confirm: confirm2 } = await prompts__default.default({
|
|
1307
|
+
name: "confirm",
|
|
1308
|
+
type: "confirm",
|
|
1309
|
+
message
|
|
1310
|
+
});
|
|
1311
|
+
return confirm2 ?? false;
|
|
1312
|
+
};
|
|
1313
|
+
await upgrade$1({
|
|
1314
|
+
logger,
|
|
1315
|
+
confirm,
|
|
1316
|
+
dry: options.dry,
|
|
1317
|
+
cwd: options.projectPath,
|
|
1318
|
+
target: options.target,
|
|
1319
|
+
codemodsTarget: options.codemodsTarget
|
|
1320
|
+
});
|
|
1321
|
+
} catch (err) {
|
|
1322
|
+
handleError(err, options.silent);
|
|
1323
|
+
}
|
|
1324
|
+
};
|
|
1325
|
+
const register$1 = (program) => {
|
|
1326
|
+
const addReleaseUpgradeCommand = (releaseType, description) => {
|
|
1327
|
+
program.command(releaseType).description(description).addOption(projectPathOption).addOption(dryOption).addOption(debugOption).addOption(silentOption).addOption(autoConfirmOption).action(async (options) => {
|
|
1328
|
+
return upgrade({ ...options, target: releaseType });
|
|
1329
|
+
});
|
|
1330
|
+
};
|
|
1331
|
+
addReleaseUpgradeCommand(
|
|
1332
|
+
ReleaseType.Major,
|
|
1333
|
+
"Upgrade to the next available major version of Strapi"
|
|
1334
|
+
);
|
|
1335
|
+
addReleaseUpgradeCommand(
|
|
1336
|
+
ReleaseType.Minor,
|
|
1337
|
+
"Upgrade to the latest minor and patch version of Strapi for the current major"
|
|
1338
|
+
);
|
|
1339
|
+
addReleaseUpgradeCommand(
|
|
1340
|
+
ReleaseType.Patch,
|
|
1341
|
+
"Upgrade to latest patch version of Strapi for the current major and minor"
|
|
1342
|
+
);
|
|
1343
|
+
program.command("to <target>", { hidden: true }).description("Upgrade to the specified version of Strapi").addOption(projectPathOption).addOption(dryOption).addOption(debugOption).addOption(silentOption).addOption(autoConfirmOption).addOption(
|
|
1344
|
+
new commander.Option(
|
|
1345
|
+
"-c, --codemods-target <codemodsTarget>",
|
|
1346
|
+
"Use a custom target for the codemods execution. Useful when targeting pre-releases"
|
|
1347
|
+
).argParser((codemodsTarget) => {
|
|
1348
|
+
if (!isLiteralSemVer(codemodsTarget)) {
|
|
1349
|
+
throw new commander.InvalidArgumentError(
|
|
1350
|
+
`Expected a version with the following format: "<number>.<number>.<number>"`
|
|
1351
|
+
);
|
|
1352
|
+
}
|
|
1353
|
+
return semVerFactory(codemodsTarget);
|
|
1354
|
+
})
|
|
1355
|
+
).action(async (target, options) => {
|
|
1356
|
+
if (!isValidSemVer(target)) {
|
|
1357
|
+
console.error(`Invalid target supplied, expected a valid semver but got "${target}"`);
|
|
1358
|
+
process.exit(1);
|
|
1359
|
+
}
|
|
1360
|
+
return upgrade({ ...options, target: semVerFactory(target) });
|
|
1361
|
+
});
|
|
1362
|
+
};
|
|
1363
|
+
const DEFAULT_TARGET = ReleaseType.Major;
|
|
1364
|
+
const runCodemods = async (options) => {
|
|
1365
|
+
const { silent, debug } = options;
|
|
1366
|
+
const logger = loggerFactory({ silent, debug });
|
|
1367
|
+
logger.warn(
|
|
1368
|
+
"Please make sure you've created a backup of your codebase and files before running the codemods"
|
|
1369
|
+
);
|
|
1370
|
+
const confirm = async (message) => {
|
|
1371
|
+
const { confirm: confirm2 } = await prompts__default.default({
|
|
1372
|
+
name: "confirm",
|
|
1373
|
+
type: "confirm",
|
|
1374
|
+
message
|
|
1375
|
+
});
|
|
1376
|
+
return confirm2 ?? false;
|
|
1377
|
+
};
|
|
1378
|
+
const selectCodemods = async (codemods) => {
|
|
1379
|
+
const selectableCodemods = codemods.map(
|
|
1380
|
+
({ version: version2, codemods: codemods2 }) => codemods2.map((codemod) => ({
|
|
1381
|
+
title: `(${version2}) ${codemod.format()}`,
|
|
1382
|
+
value: codemod,
|
|
1383
|
+
selected: true
|
|
1384
|
+
}))
|
|
1385
|
+
).flat();
|
|
1386
|
+
if (selectableCodemods.length === 0) {
|
|
1387
|
+
logger.info("No codemods to run");
|
|
1388
|
+
return [];
|
|
1389
|
+
}
|
|
1390
|
+
const { selectedCodemods } = await prompts__default.default({
|
|
1391
|
+
type: "autocompleteMultiselect",
|
|
1392
|
+
name: "selectedCodemods",
|
|
1393
|
+
message: "Choose the codemods you would like to run:",
|
|
1394
|
+
choices: selectableCodemods
|
|
1395
|
+
});
|
|
1396
|
+
if (!selectedCodemods || selectedCodemods.length === 0) {
|
|
1397
|
+
logger.info("No codemods selected");
|
|
1398
|
+
return [];
|
|
1399
|
+
}
|
|
1400
|
+
return selectedCodemods.map((codemod) => ({
|
|
1401
|
+
version: codemod.version,
|
|
1402
|
+
codemods: [codemod]
|
|
1403
|
+
}));
|
|
1404
|
+
};
|
|
1405
|
+
return runCodemods$1({
|
|
1406
|
+
logger,
|
|
1407
|
+
confirm,
|
|
1408
|
+
selectCodemods,
|
|
1409
|
+
dry: options.dry,
|
|
1410
|
+
cwd: options.projectPath,
|
|
1411
|
+
target: options.range ?? DEFAULT_TARGET,
|
|
1412
|
+
uid: options.uid
|
|
1413
|
+
}).catch((err) => handleError(err, options.silent));
|
|
1414
|
+
};
|
|
1415
|
+
const listCodemods = async (options) => {
|
|
1416
|
+
const { silent, debug } = options;
|
|
1417
|
+
const logger = loggerFactory({ silent, debug });
|
|
1418
|
+
return listCodemods$1({
|
|
1419
|
+
cwd: options.projectPath,
|
|
1420
|
+
target: options.range ?? DEFAULT_TARGET,
|
|
1421
|
+
logger
|
|
1422
|
+
}).catch((err) => handleError(err, options.silent));
|
|
1423
|
+
};
|
|
1424
|
+
const register = (program) => {
|
|
1425
|
+
const codemodsCommand = program.command("codemods");
|
|
1426
|
+
codemodsCommand.command("run [uid]").description(
|
|
1427
|
+
`
|
|
1428
|
+
Executes a set of codemods on the current project.
|
|
1429
|
+
|
|
1430
|
+
If the optional UID argument is provided, the command specifically runs the codemod associated with that UID.
|
|
1431
|
+
Without the UID, the command produces a list of all available codemods for your project.
|
|
1432
|
+
|
|
1433
|
+
By default, when executed on a Strapi application project, it offers codemods matching the current major version of the app.
|
|
1434
|
+
When executed on a Strapi plugin project, it shows every codemods.
|
|
1435
|
+
`
|
|
1436
|
+
).addOption(projectPathOption).addOption(dryOption).addOption(debugOption).addOption(silentOption).addOption(rangeOption).action(async (uid, options) => {
|
|
1437
|
+
return runCodemods({ ...options, uid });
|
|
1438
|
+
});
|
|
1439
|
+
codemodsCommand.command("ls").description(`List available codemods`).addOption(projectPathOption).addOption(debugOption).addOption(silentOption).addOption(rangeOption).action(async (options) => {
|
|
1440
|
+
return listCodemods(options);
|
|
1441
|
+
});
|
|
1442
|
+
};
|
|
1443
|
+
const version = "5.0.0-beta.3";
|
|
1444
|
+
register$1(commander.program);
|
|
1445
|
+
register(commander.program);
|
|
1446
|
+
commander.program.usage("<command> [options]").on("command:*", ([invalidCmd]) => {
|
|
1447
|
+
console.error(
|
|
1448
|
+
chalk__default.default.red(
|
|
1449
|
+
`[ERROR] Invalid command: ${invalidCmd}.${os__default.default.EOL} See --help for a list of available commands.`
|
|
1450
|
+
)
|
|
1451
|
+
);
|
|
1452
|
+
process.exit(1);
|
|
1453
|
+
}).helpOption("-h, --help", "Print command line options").addHelpCommand("help [command]", "Print options for a specific command").version(version).parse(process.argv);
|
|
7
1454
|
//# sourceMappingURL=cli.js.map
|