@ecopages/codemod 0.9.0-rc.0 → 0.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.
- package/README.md +47 -100
- package/package.json +35 -2
- package/src/cli.d.ts +30 -0
- package/src/cli.js +156 -0
- package/src/transforms/migrate-middleware-locals.d.ts +75 -0
- package/src/transforms/migrate-middleware-locals.js +949 -0
- package/src/transforms/migrate-radiant-bindings.d.ts +49 -0
- package/src/transforms/migrate-radiant-bindings.js +613 -0
- package/src/transforms/migrate-radiant-refs.d.ts +43 -0
- package/src/transforms/migrate-radiant-refs.js +503 -0
- package/src/transforms/print-options.d.ts +6 -3
- package/src/transforms/print-options.js +9 -3
- package/src/transforms/source-edits.d.ts +61 -0
- package/src/transforms/source-edits.js +93 -0
|
@@ -0,0 +1,949 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codemod: migrate-middleware-locals
|
|
3
|
+
*
|
|
4
|
+
* Moves `ctx.locals.x = value` assignments of an annotated middleware into the `next({ ... })` call of a
|
|
5
|
+
* `createMiddleware` stage.
|
|
6
|
+
*
|
|
7
|
+
* Before:
|
|
8
|
+
* export const auth: FileRouteMiddleware = async (ctx, next) => {
|
|
9
|
+
* const session = await getSession(ctx.request);
|
|
10
|
+
* if (!session) return Response.redirect('/login');
|
|
11
|
+
* ctx.locals.session = session;
|
|
12
|
+
* return next();
|
|
13
|
+
* };
|
|
14
|
+
*
|
|
15
|
+
* After:
|
|
16
|
+
* export const auth = createMiddleware(async (ctx, next) => {
|
|
17
|
+
* const session = await getSession(ctx.request);
|
|
18
|
+
* if (!session) return Response.redirect('/login');
|
|
19
|
+
* return next({ session });
|
|
20
|
+
* });
|
|
21
|
+
*
|
|
22
|
+
* Only a declaration annotated `FileRouteMiddleware` or `Middleware` (imported from `@ecopages/core`, without type
|
|
23
|
+
* arguments, on its name or with `satisfies`) is rewritten, and only when its assignments are top-level statements before
|
|
24
|
+
* the single `return next()` of the body, nothing between the first assignment and `next()` awaits, returns or throws (an
|
|
25
|
+
* outer stage could then have read the local the stage had already set), and the body uses `ctx` only to read its fields
|
|
26
|
+
* other than `ctx.locals`, `ctx.query`, `ctx.render` and `ctx.renderPartial`. Code that receives `ctx` itself could read a
|
|
27
|
+
* local that `next()` now provides later, so it blocks the move. The file may reference the middleware only in a
|
|
28
|
+
* `middleware` list, a `composeMiddleware` call or an export, since the result is no longer a function. A value that
|
|
29
|
+
* could read differently by the time `next()` runs (anything but a literal or a `const` declared before it) is bound to
|
|
30
|
+
* a new `const` where the assignment was, so it is evaluated in the same order. Anything else is left unchanged and
|
|
31
|
+
* reported with its file and line, as is every `EcoMiddleware<Context>` annotation (the removed context-extension form)
|
|
32
|
+
* and every other function that writes a `locals` object.
|
|
33
|
+
*
|
|
34
|
+
* `render` no longer receives `locals` and `requires` is removed, so an `eco.page()` whose `render` reads them moves the
|
|
35
|
+
* read into `props`:
|
|
36
|
+
*
|
|
37
|
+
* Before:
|
|
38
|
+
* eco.page({ cache: 'dynamic', middleware: [auth], requires: ['session'], render: ({ locals }) => <p>{locals.session.user}</p> });
|
|
39
|
+
*
|
|
40
|
+
* After:
|
|
41
|
+
* eco.page({ cache: 'dynamic', middleware: [auth], props: ({ locals }) => ({ sessionUser: locals.session.user }), render: ({ sessionUser }) => <p>{sessionUser}</p> });
|
|
42
|
+
*
|
|
43
|
+
* What `props` returns reaches the browser, so each member chain `render` reads becomes one prop named after its segments
|
|
44
|
+
* and holding only that value, never the object it was read from. Only a literal `cache: 'dynamic'` page with a
|
|
45
|
+
* `middleware` list and without `props` is rewritten, when `render` destructures `locals` without a type annotation and
|
|
46
|
+
* reads it only as member chains used as values (not called, indexed, spread, written or destructured), outside any
|
|
47
|
+
* condition, loop, `try`, `await` or nested function (`props` reads every chain on every request), no chain is a prefix of
|
|
48
|
+
* another, no chain starts with `params` or `query` (render receives those from the route, after the props), and no
|
|
49
|
+
* prop name is a reserved word or clashes with another or with a name in `render`. Any other page that declares
|
|
50
|
+
* `requires` or reads `locals` in `render` is left unchanged and reported.
|
|
51
|
+
*
|
|
52
|
+
* The global `RequestLocals` interface is removed, so a `declare module '@ecopages/core'` block that augments it is
|
|
53
|
+
* reported and left in place: deleting it is only safe once the middleware types each local it declared.
|
|
54
|
+
*
|
|
55
|
+
* @remarks
|
|
56
|
+
* jscodeshift runs transforms in worker processes, so reports are appended as JSON lines to the file named by
|
|
57
|
+
* `ECOPAGES_CODEMOD_REPORT` when it is set; the CLI reads that file once jscodeshift exits and prints the migration
|
|
58
|
+
* brief.
|
|
59
|
+
*
|
|
60
|
+
* A `createMiddleware` stage is typed with the page context, so an API `Middleware` that reads `ctx.query`, `ctx.render`
|
|
61
|
+
* or `ctx.renderPartial` is reported instead of rewritten: a union context would make every stage narrow before reading
|
|
62
|
+
* a field, and an intersection would type fields a page stage never receives.
|
|
63
|
+
*/
|
|
64
|
+
import { appendFileSync } from 'node:fs';
|
|
65
|
+
import { printOptions } from './print-options.js';
|
|
66
|
+
export const parser = 'tsx';
|
|
67
|
+
/** The environment variable naming the file a run appends its reports to. */
|
|
68
|
+
export const REPORT_ENV = 'ECOPAGES_CODEMOD_REPORT';
|
|
69
|
+
const CORE = '@ecopages/core';
|
|
70
|
+
const OLD_TYPES = new Set(['FileRouteMiddleware', 'Middleware']);
|
|
71
|
+
const FUNCTION_TYPES = new Set(['ArrowFunctionExpression', 'FunctionExpression']);
|
|
72
|
+
function isNode(value) {
|
|
73
|
+
return typeof value === 'object' && value !== null && typeof value.type === 'string';
|
|
74
|
+
}
|
|
75
|
+
function lineOf(node) {
|
|
76
|
+
const loc = isNode(node) ? node.loc : undefined;
|
|
77
|
+
return loc?.start?.line ?? 0;
|
|
78
|
+
}
|
|
79
|
+
function unwrapExpression(node) {
|
|
80
|
+
let current = node;
|
|
81
|
+
while (isNode(current) &&
|
|
82
|
+
(current.type === 'ParenthesizedExpression' ||
|
|
83
|
+
current.type === 'TSAsExpression' ||
|
|
84
|
+
current.type === 'TSSatisfiesExpression')) {
|
|
85
|
+
current = current.expression;
|
|
86
|
+
}
|
|
87
|
+
return current;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* The type a declarator is annotated with, on its name or as `satisfies` or `as` on its value, when that type is a
|
|
91
|
+
* reference to a plain identifier.
|
|
92
|
+
*/
|
|
93
|
+
function middlewareAnnotation(declarator) {
|
|
94
|
+
const id = declarator.id;
|
|
95
|
+
const init = declarator.init;
|
|
96
|
+
const type = isNode(id.typeAnnotation)
|
|
97
|
+
? id.typeAnnotation.typeAnnotation
|
|
98
|
+
: isNode(init) && (init.type === 'TSSatisfiesExpression' || init.type === 'TSAsExpression')
|
|
99
|
+
? init.typeAnnotation
|
|
100
|
+
: null;
|
|
101
|
+
if (!isNode(type) || type.type !== 'TSTypeReference' || !isNode(type.typeName))
|
|
102
|
+
return null;
|
|
103
|
+
if (type.typeName.type !== 'Identifier')
|
|
104
|
+
return null;
|
|
105
|
+
return {
|
|
106
|
+
name: type.typeName.name,
|
|
107
|
+
hasTypeArguments: isNode(type.typeParameters) || isNode(type.typeArguments),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/** Whether a node is `locals` itself or a non-computed `x.locals` member. */
|
|
111
|
+
function isLocalsObject(node) {
|
|
112
|
+
if (!isNode(node))
|
|
113
|
+
return false;
|
|
114
|
+
if (node.type === 'Identifier')
|
|
115
|
+
return node.name === 'locals';
|
|
116
|
+
return isMemberNode(node) && !node.computed && isNode(node.property) && node.property.name === 'locals';
|
|
117
|
+
}
|
|
118
|
+
function writesMember(target) {
|
|
119
|
+
return isNode(target) && isMemberNode(target) && isLocalsObject(target.object);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* The first write to a `locals` object under a node: an assignment, update or `delete` of one of its keys, or an
|
|
123
|
+
* `Object.assign` into it. Null when there is none.
|
|
124
|
+
*/
|
|
125
|
+
function firstLocalsWrite(j, node) {
|
|
126
|
+
const found = j(node)
|
|
127
|
+
.find(j.Node)
|
|
128
|
+
.filter((path) => {
|
|
129
|
+
const candidate = path.node;
|
|
130
|
+
switch (candidate.type) {
|
|
131
|
+
case 'AssignmentExpression':
|
|
132
|
+
return writesMember(candidate.left);
|
|
133
|
+
case 'UpdateExpression':
|
|
134
|
+
return writesMember(candidate.argument);
|
|
135
|
+
case 'UnaryExpression':
|
|
136
|
+
return candidate.operator === 'delete' && writesMember(candidate.argument);
|
|
137
|
+
case 'CallExpression': {
|
|
138
|
+
const callee = candidate.callee;
|
|
139
|
+
const isAssign = isMemberNode(callee) &&
|
|
140
|
+
isNode(callee.object) &&
|
|
141
|
+
callee.object.name === 'Object' &&
|
|
142
|
+
isNode(callee.property) &&
|
|
143
|
+
callee.property.name === 'assign';
|
|
144
|
+
return isAssign && isLocalsObject(candidate.arguments[0]);
|
|
145
|
+
}
|
|
146
|
+
default:
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
})
|
|
150
|
+
.nodes();
|
|
151
|
+
return found[0] ?? null;
|
|
152
|
+
}
|
|
153
|
+
/** Names imported from `@ecopages/core`, mapped by their local name to the imported one. */
|
|
154
|
+
function coreImports(j, root) {
|
|
155
|
+
const names = new Map();
|
|
156
|
+
root.find(j.ImportDeclaration, { source: { value: CORE } }).forEach((path) => {
|
|
157
|
+
for (const specifier of path.node.specifiers ?? []) {
|
|
158
|
+
if (specifier.type !== 'ImportSpecifier')
|
|
159
|
+
continue;
|
|
160
|
+
names.set(String(specifier.local?.name ?? specifier.imported.name), String(specifier.imported.name));
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
return names;
|
|
164
|
+
}
|
|
165
|
+
/** Reads `ctx.locals.key` as `[key]` when `node` is such a member on the identifier `ctx`. */
|
|
166
|
+
function localsKey(node, ctx) {
|
|
167
|
+
if (!isNode(node) || (node.type !== 'MemberExpression' && node.type !== 'OptionalMemberExpression'))
|
|
168
|
+
return null;
|
|
169
|
+
const inner = node.object;
|
|
170
|
+
if (!isNode(inner) || inner.type !== 'MemberExpression' || inner.computed)
|
|
171
|
+
return null;
|
|
172
|
+
if (!isNode(inner.object) || inner.object.type !== 'Identifier' || inner.object.name !== ctx)
|
|
173
|
+
return null;
|
|
174
|
+
if (!isNode(inner.property) || inner.property.name !== 'locals')
|
|
175
|
+
return null;
|
|
176
|
+
if (node.computed || !isNode(node.property) || node.property.type !== 'Identifier')
|
|
177
|
+
return null;
|
|
178
|
+
return node.property.name;
|
|
179
|
+
}
|
|
180
|
+
function isLocalsAssignment(node, ctx) {
|
|
181
|
+
return (isNode(node) &&
|
|
182
|
+
node.type === 'AssignmentExpression' &&
|
|
183
|
+
node.operator === '=' &&
|
|
184
|
+
localsKey(node.left, ctx) !== null);
|
|
185
|
+
}
|
|
186
|
+
/** Context fields an API stage receives that a `createMiddleware` stage, typed with the page context, does not. */
|
|
187
|
+
const API_ONLY_FIELDS = new Set(['query', 'render', 'renderPartial']);
|
|
188
|
+
const LITERAL_TYPES = new Set(['StringLiteral', 'NumericLiteral', 'BooleanLiteral', 'NullLiteral', 'BigIntLiteral']);
|
|
189
|
+
const REASONS = {
|
|
190
|
+
apiField: 'reads ctx.query, ctx.render or ctx.renderPartial, which a createMiddleware stage does not receive: it is typed with the page context',
|
|
191
|
+
wholeContext: 'uses ctx other than by reading one of its fields (it passes, aliases or destructures it), so code before next() could look for a local that next() would now provide later',
|
|
192
|
+
readsLocals: 'reads ctx.locals before next()',
|
|
193
|
+
};
|
|
194
|
+
function isMemberNode(node) {
|
|
195
|
+
return node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression';
|
|
196
|
+
}
|
|
197
|
+
/** Whether an identifier is only a name here: a non-computed member property or a non-shorthand object key. */
|
|
198
|
+
function isNameOnly(path) {
|
|
199
|
+
const parent = path.parent.node;
|
|
200
|
+
if (isMemberNode(parent) && parent.property === path.node)
|
|
201
|
+
return !parent.computed;
|
|
202
|
+
const isKey = (parent.type === 'ObjectProperty' || parent.type === 'ObjectMethod') && parent.key === path.node;
|
|
203
|
+
return isKey && !parent.computed && !parent.shorthand;
|
|
204
|
+
}
|
|
205
|
+
/** The names a function references, which a new binding inside it must not take. */
|
|
206
|
+
function referencedNames(j, fn) {
|
|
207
|
+
const names = j(fn)
|
|
208
|
+
.find(j.Identifier)
|
|
209
|
+
.filter((path) => !isNameOnly(path))
|
|
210
|
+
.nodes()
|
|
211
|
+
.map((node) => node.name);
|
|
212
|
+
return new Set(names);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Why one reference to `ctx` blocks the move, or null when it is a field read the move cannot affect.
|
|
216
|
+
*
|
|
217
|
+
* @remarks
|
|
218
|
+
* Only `ctx.field` reads are allowed, and `ctx.locals` only as the target of a moved assignment: any other use can
|
|
219
|
+
* reach `ctx.locals` (a helper given `ctx`, a destructured `locals`) and would no longer see the moved keys.
|
|
220
|
+
*/
|
|
221
|
+
function ctxUseReason(path, targets) {
|
|
222
|
+
const parent = path.parent.node;
|
|
223
|
+
const isFieldRead = isMemberNode(parent) &&
|
|
224
|
+
parent.object === path.node &&
|
|
225
|
+
!parent.computed &&
|
|
226
|
+
isNode(parent.property) &&
|
|
227
|
+
parent.property.type === 'Identifier';
|
|
228
|
+
if (!isFieldRead)
|
|
229
|
+
return REASONS.wholeContext;
|
|
230
|
+
const field = parent.property.name;
|
|
231
|
+
if (API_ONLY_FIELDS.has(field))
|
|
232
|
+
return REASONS.apiField;
|
|
233
|
+
if (field !== 'locals')
|
|
234
|
+
return null;
|
|
235
|
+
return targets.has(path.parent.parent.node) ? null : REASONS.readsLocals;
|
|
236
|
+
}
|
|
237
|
+
function blockingCtxUse(j, body, ctx, assignments) {
|
|
238
|
+
const targets = new Set(assignments.map((path) => path.node.left));
|
|
239
|
+
const reasons = new Set(j(body)
|
|
240
|
+
.find(j.Identifier, { name: ctx })
|
|
241
|
+
.filter((path) => !isNameOnly(path))
|
|
242
|
+
.paths()
|
|
243
|
+
.map((path) => ctxUseReason(path, targets))
|
|
244
|
+
.filter((reason) => reason !== null));
|
|
245
|
+
return [REASONS.apiField, REASONS.wholeContext, REASONS.readsLocals].find((reason) => reasons.has(reason)) ?? null;
|
|
246
|
+
}
|
|
247
|
+
/** The single top-level `return next()` call of the body, or a reason there is none. */
|
|
248
|
+
function findNextReturn(j, body, statements, next) {
|
|
249
|
+
const calls = j(body)
|
|
250
|
+
.find(j.CallExpression, { callee: { type: 'Identifier', name: next } })
|
|
251
|
+
.paths();
|
|
252
|
+
if (calls.length !== 1)
|
|
253
|
+
return 'calls next() from several places';
|
|
254
|
+
const [call] = calls;
|
|
255
|
+
const returnNode = call.parent.node;
|
|
256
|
+
if (returnNode.type !== 'ReturnStatement' || !statements.includes(returnNode)) {
|
|
257
|
+
return 'does not end with a top-level return next()';
|
|
258
|
+
}
|
|
259
|
+
if (call.node.arguments.length > 0)
|
|
260
|
+
return 'already passes values to next()';
|
|
261
|
+
return call;
|
|
262
|
+
}
|
|
263
|
+
/** Names bound by a top-level `const name = ...` before `index`, whose value cannot change before `next()`. */
|
|
264
|
+
function constNamesBefore(statements, index) {
|
|
265
|
+
const names = new Set();
|
|
266
|
+
for (const statement of statements.slice(0, index)) {
|
|
267
|
+
if (statement.type !== 'VariableDeclaration' || statement.kind !== 'const')
|
|
268
|
+
continue;
|
|
269
|
+
for (const declarator of statement.declarations) {
|
|
270
|
+
if (isNode(declarator.id) && declarator.id.type === 'Identifier')
|
|
271
|
+
names.add(declarator.id.name);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return names;
|
|
275
|
+
}
|
|
276
|
+
/** Whether a value reads the same at the `next()` call as at its assignment: a literal or a `const` from before. */
|
|
277
|
+
function isStableValue(value, constNames) {
|
|
278
|
+
if (LITERAL_TYPES.has(value.type))
|
|
279
|
+
return true;
|
|
280
|
+
if (value.type === 'TemplateLiteral')
|
|
281
|
+
return value.expressions.length === 0;
|
|
282
|
+
return value.type === 'Identifier' && constNames.has(value.name);
|
|
283
|
+
}
|
|
284
|
+
/** Words a binding cannot take in a strict-mode module, though an object key can. */
|
|
285
|
+
const RESERVED_WORDS = new Set(`arguments await break case catch class const continue debugger default delete do else enum eval export extends
|
|
286
|
+
false finally for function if implements import in instanceof interface let new null package private protected
|
|
287
|
+
public return static super switch this throw true try typeof var void while with yield`.split(/\s+/));
|
|
288
|
+
function freshName(key, taken) {
|
|
289
|
+
const base = RESERVED_WORDS.has(key) ? `${key}Local` : key;
|
|
290
|
+
let name = base;
|
|
291
|
+
for (let suffix = 2; taken.has(name); suffix++)
|
|
292
|
+
name = `${base}${suffix}`;
|
|
293
|
+
taken.add(name);
|
|
294
|
+
return name;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Plans each moved value.
|
|
298
|
+
*
|
|
299
|
+
* @remarks
|
|
300
|
+
* A value that could read differently at `next()`, or whose evaluation has effects, is bound to a new `const` where
|
|
301
|
+
* the assignment was, so it is evaluated in the same order and `next()` passes that binding.
|
|
302
|
+
*/
|
|
303
|
+
function planMoves(j, fn, statements, ctx, assignments) {
|
|
304
|
+
const taken = referencedNames(j, fn);
|
|
305
|
+
const keys = assignments.map((path) => localsKey(path.node.left, ctx));
|
|
306
|
+
return assignments.map((path, index) => {
|
|
307
|
+
const value = path.node.right;
|
|
308
|
+
const statement = path.parent.node;
|
|
309
|
+
const key = keys[index];
|
|
310
|
+
const stable = isStableValue(value, constNamesBefore(statements, statements.indexOf(statement)));
|
|
311
|
+
if (keys.lastIndexOf(key) !== index)
|
|
312
|
+
return { statement, key, value, hoistAs: null, evaluate: !stable };
|
|
313
|
+
return { statement, key, value, hoistAs: stable ? null : freshName(key, taken), evaluate: false };
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
const EARLY_EXIT_TYPES = ['ReturnStatement', 'ThrowStatement', 'AwaitExpression', 'YieldExpression'];
|
|
317
|
+
const NESTED_FUNCTION_TYPES = new Set([...FUNCTION_TYPES, 'FunctionDeclaration', 'ObjectMethod', 'ClassMethod']);
|
|
318
|
+
/**
|
|
319
|
+
* Whether a statement can end the stage, or settle with an error, while it runs.
|
|
320
|
+
*
|
|
321
|
+
* @remarks
|
|
322
|
+
* Before the move a local assigned earlier was already set when such a statement left the stage, and an outer stage
|
|
323
|
+
* could read it after its own `next()` or in a `catch`; after the move it is never set. Code inside a nested function
|
|
324
|
+
* does not run here, so it does not count. A synchronous call that throws has the same effect and is not detected.
|
|
325
|
+
*/
|
|
326
|
+
function mayLeaveEarly(j, statement) {
|
|
327
|
+
if (EARLY_EXIT_TYPES.includes(statement.type))
|
|
328
|
+
return true;
|
|
329
|
+
return j(statement)
|
|
330
|
+
.find(j.Node)
|
|
331
|
+
.filter((path) => EARLY_EXIT_TYPES.includes(path.node.type))
|
|
332
|
+
.paths()
|
|
333
|
+
.some((path) => {
|
|
334
|
+
for (let current = path.parent; current; current = current.parent) {
|
|
335
|
+
if (current.node === statement)
|
|
336
|
+
return true;
|
|
337
|
+
if (NESTED_FUNCTION_TYPES.has(current.node.type))
|
|
338
|
+
return false;
|
|
339
|
+
}
|
|
340
|
+
return true;
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Decides whether a middleware's assignments can move into its `next()` call.
|
|
345
|
+
*
|
|
346
|
+
* @returns The moves and the `return next()` to rewrite, or a reason the function must stay as written.
|
|
347
|
+
*/
|
|
348
|
+
function planMove(j, fn, ctx, next, assignments) {
|
|
349
|
+
const body = fn.body;
|
|
350
|
+
const statements = body.body;
|
|
351
|
+
const topLevel = assignments.filter((path) => {
|
|
352
|
+
const parent = path.parent.node;
|
|
353
|
+
return parent.type === 'ExpressionStatement' && statements.includes(parent);
|
|
354
|
+
});
|
|
355
|
+
if (topLevel.length !== assignments.length) {
|
|
356
|
+
return 'assigns ctx.locals inside a branch, loop or nested function';
|
|
357
|
+
}
|
|
358
|
+
if (!next)
|
|
359
|
+
return 'has no next parameter to pass the locals to';
|
|
360
|
+
const call = findNextReturn(j, body, statements, next);
|
|
361
|
+
if (typeof call === 'string')
|
|
362
|
+
return call;
|
|
363
|
+
const returnIndex = statements.indexOf(call.parent.node);
|
|
364
|
+
const moved = topLevel.map((path) => statements.indexOf(path.parent.node));
|
|
365
|
+
if (moved.some((index) => index > returnIndex))
|
|
366
|
+
return 'assigns ctx.locals after the next() call';
|
|
367
|
+
const blocked = blockingCtxUse(j, body, ctx, topLevel);
|
|
368
|
+
if (blocked)
|
|
369
|
+
return blocked;
|
|
370
|
+
const first = Math.min(...moved);
|
|
371
|
+
if (statements.slice(first + 1, returnIndex).some((statement) => mayLeaveEarly(j, statement))) {
|
|
372
|
+
return 'awaits, returns or throws between a ctx.locals assignment and next(), where the local would no longer be set';
|
|
373
|
+
}
|
|
374
|
+
return { moves: planMoves(j, fn, statements, ctx, topLevel), nextReturn: call };
|
|
375
|
+
}
|
|
376
|
+
function buildLocalsObject(j, moves) {
|
|
377
|
+
const values = new Map();
|
|
378
|
+
for (const move of moves) {
|
|
379
|
+
values.delete(move.key);
|
|
380
|
+
values.set(move.key, move.hoistAs ? j.identifier(move.hoistAs) : move.value);
|
|
381
|
+
}
|
|
382
|
+
const properties = [...values].map(([key, value]) => {
|
|
383
|
+
const property = j.objectProperty(j.identifier(key), value);
|
|
384
|
+
property.shorthand = value.type === 'Identifier' && value.name === key;
|
|
385
|
+
return property;
|
|
386
|
+
});
|
|
387
|
+
return j.objectExpression(properties);
|
|
388
|
+
}
|
|
389
|
+
/** Replaces each moved assignment with its `const` binding, or removes it when `next()` passes the value itself. */
|
|
390
|
+
function applyMoves(j, body, moves) {
|
|
391
|
+
for (const move of moves) {
|
|
392
|
+
const value = move.value;
|
|
393
|
+
const replacement = move.hoistAs
|
|
394
|
+
? [j.variableDeclaration('const', [j.variableDeclarator(j.identifier(move.hoistAs), value)])]
|
|
395
|
+
: move.evaluate
|
|
396
|
+
? [j.expressionStatement(value)]
|
|
397
|
+
: [];
|
|
398
|
+
body.splice(body.indexOf(move.statement), 1, ...replacement);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
/** Whether `name` is still read anywhere in the file outside import specifiers. */
|
|
402
|
+
function stillUsed(j, root, name) {
|
|
403
|
+
return (root.find(j.Identifier, { name }).filter((path) => {
|
|
404
|
+
const parent = path.parent.node;
|
|
405
|
+
return parent.type !== 'ImportSpecifier' && parent.type !== 'ImportDefaultSpecifier';
|
|
406
|
+
}).length > 0);
|
|
407
|
+
}
|
|
408
|
+
function dropUnusedCoreTypes(j, root) {
|
|
409
|
+
root.find(j.ImportDeclaration, { source: { value: CORE } }).forEach((path) => {
|
|
410
|
+
const specifiers = path.node.specifiers ?? [];
|
|
411
|
+
const kept = specifiers.filter((specifier) => specifier.type !== 'ImportSpecifier' ||
|
|
412
|
+
!OLD_TYPES.has(String(specifier.imported.name)) ||
|
|
413
|
+
stillUsed(j, root, String(specifier.local?.name ?? specifier.imported.name)));
|
|
414
|
+
if (kept.length === specifiers.length)
|
|
415
|
+
return;
|
|
416
|
+
if (kept.length === 0) {
|
|
417
|
+
j(path).remove();
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
path.node.specifiers = kept;
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* The name the file calls `createMiddleware` from `@ecopages/core` by, or null when another binding owns that name.
|
|
425
|
+
*
|
|
426
|
+
* @remarks
|
|
427
|
+
* An existing value import is reused under its local alias; without one, the name must be free so the import this
|
|
428
|
+
* transform adds does not collide with a declaration or another package's `createMiddleware`.
|
|
429
|
+
*/
|
|
430
|
+
function createMiddlewareBinding(j, root) {
|
|
431
|
+
const existing = root
|
|
432
|
+
.find(j.ImportDeclaration, { source: { value: CORE } })
|
|
433
|
+
.filter((path) => path.node.importKind !== 'type')
|
|
434
|
+
.find(j.ImportSpecifier, { imported: { name: 'createMiddleware' } })
|
|
435
|
+
.filter((path) => path.node.importKind !== 'type')
|
|
436
|
+
.nodes();
|
|
437
|
+
if (existing.length > 0)
|
|
438
|
+
return { name: String(existing[0].local?.name ?? 'createMiddleware'), imported: true };
|
|
439
|
+
const taken = root.find(j.Identifier, { name: 'createMiddleware' }).filter((path) => !isNameOnly(path)).length > 0;
|
|
440
|
+
return taken ? null : { name: 'createMiddleware', imported: false };
|
|
441
|
+
}
|
|
442
|
+
function addCreateMiddlewareImport(j, root) {
|
|
443
|
+
const imports = root.find(j.ImportDeclaration, { source: { value: CORE } });
|
|
444
|
+
const valueImport = imports.filter((path) => path.node.importKind !== 'type');
|
|
445
|
+
const specifier = j.importSpecifier(j.identifier('createMiddleware'));
|
|
446
|
+
if (valueImport.length > 0) {
|
|
447
|
+
const target = valueImport.paths()[0].node;
|
|
448
|
+
target.specifiers = [...(target.specifiers ?? []), specifier];
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
const declaration = j.importDeclaration([specifier], j.literal(CORE));
|
|
452
|
+
if (imports.length > 0) {
|
|
453
|
+
j(imports.paths()[0]).insertAfter(declaration);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
root.get().node.program.body.unshift(declaration);
|
|
457
|
+
}
|
|
458
|
+
function pageOptions(call) {
|
|
459
|
+
const [argument] = call.node.arguments;
|
|
460
|
+
if (!isNode(argument) || argument.type !== 'ObjectExpression')
|
|
461
|
+
return null;
|
|
462
|
+
return { argument: argument };
|
|
463
|
+
}
|
|
464
|
+
function pageProperty(options, name) {
|
|
465
|
+
return options.argument.properties.find((property) => (property.type === 'ObjectProperty' || property.type === 'ObjectMethod') &&
|
|
466
|
+
!property.computed &&
|
|
467
|
+
isNode(property.key) &&
|
|
468
|
+
property.key.name === name);
|
|
469
|
+
}
|
|
470
|
+
/** The function node of a `render` option, written as a method or as a function value. */
|
|
471
|
+
function renderFunction(render) {
|
|
472
|
+
if (!render)
|
|
473
|
+
return null;
|
|
474
|
+
if (render.type === 'ObjectMethod')
|
|
475
|
+
return render;
|
|
476
|
+
const value = unwrapExpression(render.value);
|
|
477
|
+
return isNode(value) && FUNCTION_TYPES.has(value.type) ? value : null;
|
|
478
|
+
}
|
|
479
|
+
function isLocalsShorthand(property) {
|
|
480
|
+
return (property.type === 'ObjectProperty' &&
|
|
481
|
+
!property.computed &&
|
|
482
|
+
isNode(property.key) &&
|
|
483
|
+
property.key.name === 'locals' &&
|
|
484
|
+
isNode(property.value) &&
|
|
485
|
+
property.value.type === 'Identifier' &&
|
|
486
|
+
property.value.name === 'locals');
|
|
487
|
+
}
|
|
488
|
+
/** The `{ locals }` entry of an unannotated destructured first parameter, or null when there is none. */
|
|
489
|
+
function localsBinding(fn) {
|
|
490
|
+
const [first] = fn.params;
|
|
491
|
+
if (!first || first.type !== 'ObjectPattern' || first.typeAnnotation)
|
|
492
|
+
return null;
|
|
493
|
+
const properties = first.properties;
|
|
494
|
+
if (properties.some((property) => property.type === 'RestElement'))
|
|
495
|
+
return null;
|
|
496
|
+
const entry = properties.find(isLocalsShorthand);
|
|
497
|
+
return entry ? { pattern: first, entry } : null;
|
|
498
|
+
}
|
|
499
|
+
function isMemberRead(path) {
|
|
500
|
+
const parent = path.parent.node;
|
|
501
|
+
return (isMemberNode(parent) &&
|
|
502
|
+
parent.object === path.node &&
|
|
503
|
+
!parent.computed &&
|
|
504
|
+
isNode(parent.property) &&
|
|
505
|
+
parent.property.type === 'Identifier');
|
|
506
|
+
}
|
|
507
|
+
function isPropertyName(path) {
|
|
508
|
+
const parent = path.parent.node;
|
|
509
|
+
return isMemberNode(parent) && parent.property === path.node && !parent.computed;
|
|
510
|
+
}
|
|
511
|
+
/** Keys `render` receives from the route, which a Page's `props` hook may not return. */
|
|
512
|
+
const ROUTE_KEYS = new Set(['params', 'query']);
|
|
513
|
+
/**
|
|
514
|
+
* Whether the outermost member of a `locals` chain is read as a value, and not called, indexed, spread, written or
|
|
515
|
+
* destructured.
|
|
516
|
+
*
|
|
517
|
+
* @remarks
|
|
518
|
+
* Each of those needs more than the value of the chain (a call needs its receiver, a spread or destructuring reads
|
|
519
|
+
* every key), so the prop would carry more than `render` uses.
|
|
520
|
+
*/
|
|
521
|
+
function isValueRead(top) {
|
|
522
|
+
const parent = top.parent.node;
|
|
523
|
+
const rule = VALUE_READ_RULES[parent.type];
|
|
524
|
+
return rule ? rule(parent, top.node) : true;
|
|
525
|
+
}
|
|
526
|
+
const notOperand = (field) => (parent, node) => parent[field] !== node;
|
|
527
|
+
const notObjectOrTarget = (parent, node) => parent.object !== node && parent.left !== node;
|
|
528
|
+
const never = () => false;
|
|
529
|
+
/** How each parent of a chain's outermost member decides whether the chain is read as a value; others always do. */
|
|
530
|
+
const VALUE_READ_RULES = {
|
|
531
|
+
CallExpression: notOperand('callee'),
|
|
532
|
+
OptionalCallExpression: notOperand('callee'),
|
|
533
|
+
NewExpression: notOperand('callee'),
|
|
534
|
+
TaggedTemplateExpression: notOperand('tag'),
|
|
535
|
+
MemberExpression: notObjectOrTarget,
|
|
536
|
+
OptionalMemberExpression: notObjectOrTarget,
|
|
537
|
+
AssignmentExpression: notObjectOrTarget,
|
|
538
|
+
ForOfStatement: notObjectOrTarget,
|
|
539
|
+
ForInStatement: notObjectOrTarget,
|
|
540
|
+
VariableDeclarator: (parent) => isNode(parent.id) && parent.id.type === 'Identifier',
|
|
541
|
+
UnaryExpression: (parent) => parent.operator !== 'delete',
|
|
542
|
+
UpdateExpression: never,
|
|
543
|
+
SpreadElement: never,
|
|
544
|
+
JSXSpreadAttribute: never,
|
|
545
|
+
TSNonNullExpression: never,
|
|
546
|
+
ParenthesizedExpression: never,
|
|
547
|
+
};
|
|
548
|
+
/** Reads the member chain that starts at one `locals` reference, or null when it is not a value read. */
|
|
549
|
+
function readChain(reference) {
|
|
550
|
+
const segments = [];
|
|
551
|
+
let chain = '';
|
|
552
|
+
let current = reference;
|
|
553
|
+
while (isMemberRead(current)) {
|
|
554
|
+
current = current.parent;
|
|
555
|
+
const member = current.node;
|
|
556
|
+
const name = member.property.name;
|
|
557
|
+
segments.push(name);
|
|
558
|
+
chain += `${member.optional ? '?.' : '.'}${name}`;
|
|
559
|
+
}
|
|
560
|
+
if (segments.length === 0 || !isValueRead(current))
|
|
561
|
+
return null;
|
|
562
|
+
const name = segments
|
|
563
|
+
.map((segment, index) => (index === 0 ? segment : `${segment[0].toUpperCase()}${segment.slice(1)}`))
|
|
564
|
+
.join('');
|
|
565
|
+
return { path: current, chain, name, first: segments[0] };
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* The `locals` reads of `render`, or a reason they cannot become props.
|
|
569
|
+
*
|
|
570
|
+
* @remarks
|
|
571
|
+
* The identifiers of the `{ locals }` entry itself are skipped. Every other reference must start a member chain
|
|
572
|
+
* read as a value; each distinct chain becomes one prop named after its segments, so the prop holds exactly what
|
|
573
|
+
* `render` read and never the object it was read from.
|
|
574
|
+
*/
|
|
575
|
+
function localsReads(j, fn, entry) {
|
|
576
|
+
const references = j(fn)
|
|
577
|
+
.find(j.Identifier, { name: 'locals' })
|
|
578
|
+
.filter((path) => path.parent.node !== entry && !isPropertyName(path))
|
|
579
|
+
.paths();
|
|
580
|
+
if (references.length === 0)
|
|
581
|
+
return null;
|
|
582
|
+
const reads = references.map(readChain);
|
|
583
|
+
if (reads.some((read) => read === null)) {
|
|
584
|
+
return 'render reads locals other than as the value of a member chain (it passes, calls, indexes, spreads, writes or destructures it)';
|
|
585
|
+
}
|
|
586
|
+
const chains = reads.filter((read) => read !== null);
|
|
587
|
+
if (chains.some((read) => isGuarded(read.path, fn))) {
|
|
588
|
+
return 'render reads locals inside a condition, loop, try, await or nested function, which props would read on every request';
|
|
589
|
+
}
|
|
590
|
+
const plain = chains.map((read) => read.chain.replaceAll('?.', '.'));
|
|
591
|
+
if (plain.some((outer) => plain.some((inner) => inner.startsWith(`${outer}.`)))) {
|
|
592
|
+
return 'render reads both a locals value and a member of it, so props would return the whole value';
|
|
593
|
+
}
|
|
594
|
+
return chains;
|
|
595
|
+
}
|
|
596
|
+
/** Node types under which a read may not run on every render, or may run after it could have thrown. */
|
|
597
|
+
const GUARD_TYPES = new Set([
|
|
598
|
+
'ConditionalExpression',
|
|
599
|
+
'LogicalExpression',
|
|
600
|
+
'IfStatement',
|
|
601
|
+
'SwitchStatement',
|
|
602
|
+
'ForStatement',
|
|
603
|
+
'ForInStatement',
|
|
604
|
+
'ForOfStatement',
|
|
605
|
+
'WhileStatement',
|
|
606
|
+
'DoWhileStatement',
|
|
607
|
+
'TryStatement',
|
|
608
|
+
'AwaitExpression',
|
|
609
|
+
...NESTED_FUNCTION_TYPES,
|
|
610
|
+
]);
|
|
611
|
+
/**
|
|
612
|
+
* Whether a read in `render` sits under a node that decides whether it runs.
|
|
613
|
+
*
|
|
614
|
+
* @remarks
|
|
615
|
+
* `props` evaluates every moved chain unconditionally, so a chain `render` only read behind a check such as
|
|
616
|
+
* `locals.session ? locals.session.user : null` would throw, or return the guarded object, on every request.
|
|
617
|
+
*/
|
|
618
|
+
function isGuarded(read, render) {
|
|
619
|
+
for (let current = read.parent; current && current.node !== render; current = current.parent) {
|
|
620
|
+
if (GUARD_TYPES.has(current.node.type))
|
|
621
|
+
return true;
|
|
622
|
+
}
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
/** Why the props named after these reads would not reach `render` as written, or null when they would. */
|
|
626
|
+
function readNamesConflict(j, fn, reads) {
|
|
627
|
+
if (reads.some((read) => ROUTE_KEYS.has(read.first) || ROUTE_KEYS.has(read.name))) {
|
|
628
|
+
return 'render reads locals.params or locals.query, which render receives from the route instead';
|
|
629
|
+
}
|
|
630
|
+
if (reads.some((read) => RESERVED_WORDS.has(read.name))) {
|
|
631
|
+
return 'render reads a local whose prop name is a reserved word, which render could not destructure';
|
|
632
|
+
}
|
|
633
|
+
const chainsByName = new Map();
|
|
634
|
+
for (const read of reads)
|
|
635
|
+
chainsByName.set(read.name, (chainsByName.get(read.name) ?? new Set()).add(read.chain));
|
|
636
|
+
const clash = [...chainsByName].some(([name, chains]) => chains.size > 1 || nameInUse(j, fn, name));
|
|
637
|
+
return clash ? 'render reads locals under a name that another read or render already uses' : null;
|
|
638
|
+
}
|
|
639
|
+
/** Whether a name appears in `render` other than as a member property, so a new binding could shadow it. */
|
|
640
|
+
function nameInUse(j, fn, name) {
|
|
641
|
+
return (j(fn)
|
|
642
|
+
.find(j.Identifier, { name })
|
|
643
|
+
.filter((path) => !isPropertyName(path)).length > 0);
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Decides whether a page's `render` read of `locals` can move into a new `props` hook.
|
|
647
|
+
*
|
|
648
|
+
* @returns The plan, or the reason it cannot move.
|
|
649
|
+
*/
|
|
650
|
+
function planPage(j, options) {
|
|
651
|
+
const cache = pageProperty(options, 'cache');
|
|
652
|
+
const isDynamic = isNode(cache?.value) && cache.value.type === 'StringLiteral' && cache.value.value === 'dynamic';
|
|
653
|
+
if (!isDynamic) {
|
|
654
|
+
return "the page is not cache: 'dynamic', and only a dynamic page's props receives locals: make it cache: 'dynamic', list the middleware that provides them, and read them in props";
|
|
655
|
+
}
|
|
656
|
+
if (pageProperty(options, 'props'))
|
|
657
|
+
return 'the page already has props: read the locals there';
|
|
658
|
+
const fn = renderFunction(pageProperty(options, 'render'));
|
|
659
|
+
const binding = fn ? localsBinding(fn) : null;
|
|
660
|
+
if (!fn || !binding)
|
|
661
|
+
return 'render does not destructure { locals } from an unannotated first parameter';
|
|
662
|
+
const reads = localsReads(j, fn, binding.entry);
|
|
663
|
+
if (reads === null)
|
|
664
|
+
return 'render does not read locals: delete requires';
|
|
665
|
+
if (typeof reads === 'string')
|
|
666
|
+
return reads;
|
|
667
|
+
const conflict = readNamesConflict(j, fn, reads);
|
|
668
|
+
if (conflict)
|
|
669
|
+
return conflict;
|
|
670
|
+
if (!pageProperty(options, 'middleware')) {
|
|
671
|
+
return 'the page lists no middleware, so props would see no typed locals: list the middleware that provides them';
|
|
672
|
+
}
|
|
673
|
+
return { binding, reads };
|
|
674
|
+
}
|
|
675
|
+
function shorthand(j, name, value) {
|
|
676
|
+
const property = j.objectProperty(j.identifier(name), value);
|
|
677
|
+
property.shorthand = true;
|
|
678
|
+
return property;
|
|
679
|
+
}
|
|
680
|
+
function applyPagePlan(j, options, plan) {
|
|
681
|
+
const { properties } = options.argument;
|
|
682
|
+
const values = new Map();
|
|
683
|
+
for (const read of plan.reads) {
|
|
684
|
+
if (!values.has(read.name))
|
|
685
|
+
values.set(read.name, read.path.node);
|
|
686
|
+
}
|
|
687
|
+
const returned = j.objectExpression([...values].map(([name, value]) => j.objectProperty(j.identifier(name), value)));
|
|
688
|
+
const props = j.objectProperty(j.identifier('props'), j.arrowFunctionExpression([j.objectPattern([shorthand(j, 'locals', j.identifier('locals'))])], returned));
|
|
689
|
+
for (const read of plan.reads) {
|
|
690
|
+
read.path.replace(j.identifier(read.name));
|
|
691
|
+
}
|
|
692
|
+
const patternProperties = plan.binding.pattern.properties;
|
|
693
|
+
patternProperties.splice(patternProperties.indexOf(plan.binding.entry), 1, ...[...values.keys()].map((name) => shorthand(j, name, j.identifier(name))));
|
|
694
|
+
const requires = pageProperty(options, 'requires');
|
|
695
|
+
if (requires)
|
|
696
|
+
properties.splice(properties.indexOf(requires), 1);
|
|
697
|
+
const render = pageProperty(options, 'render');
|
|
698
|
+
properties.splice(properties.indexOf(render), 0, props);
|
|
699
|
+
}
|
|
700
|
+
/** The line of a page's `requires`, or of the first `locals` reference in its `render`, or null when neither exists. */
|
|
701
|
+
function pageLocalsLine(j, options) {
|
|
702
|
+
const requires = pageProperty(options, 'requires');
|
|
703
|
+
if (requires)
|
|
704
|
+
return lineOf(requires);
|
|
705
|
+
const fn = renderFunction(pageProperty(options, 'render'));
|
|
706
|
+
if (!fn)
|
|
707
|
+
return null;
|
|
708
|
+
const references = j(fn).find(j.Identifier, { name: 'locals' });
|
|
709
|
+
return references.length > 0 ? lineOf(references.paths()[0].node) : null;
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* Migrates one `eco.page()` call whose `render` reads `locals`, or reports it.
|
|
713
|
+
*
|
|
714
|
+
* @returns Whether the call was rewritten.
|
|
715
|
+
*/
|
|
716
|
+
function migratePage(j, call, filePath, reports) {
|
|
717
|
+
const options = pageOptions(call);
|
|
718
|
+
if (!options)
|
|
719
|
+
return false;
|
|
720
|
+
const plan = planPage(j, options);
|
|
721
|
+
if (typeof plan !== 'string') {
|
|
722
|
+
applyPagePlan(j, options, plan);
|
|
723
|
+
return true;
|
|
724
|
+
}
|
|
725
|
+
const line = pageLocalsLine(j, options);
|
|
726
|
+
if (line !== null) {
|
|
727
|
+
reports.push({
|
|
728
|
+
kind: 'page-requires',
|
|
729
|
+
file: filePath,
|
|
730
|
+
line,
|
|
731
|
+
reason: `requires is removed and render no longer receives locals; not rewritten because ${plan}. Return from props only what render needs, never a whole session or user object`,
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
return false;
|
|
735
|
+
}
|
|
736
|
+
function isEcoPageCall(node) {
|
|
737
|
+
const callee = node.callee;
|
|
738
|
+
return (isNode(callee) &&
|
|
739
|
+
callee.type === 'MemberExpression' &&
|
|
740
|
+
isNode(callee.object) &&
|
|
741
|
+
callee.object.name === 'eco' &&
|
|
742
|
+
isNode(callee.property) &&
|
|
743
|
+
callee.property.name === 'page');
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* Reports each `interface RequestLocals` declared in a `declare module '@ecopages/core'` block.
|
|
747
|
+
*/
|
|
748
|
+
function reportRequestLocalsAugmentations(j, root, filePath, reports) {
|
|
749
|
+
root.find(j.TSModuleDeclaration)
|
|
750
|
+
.filter((path) => isNode(path.node.id) && path.node.id.value === CORE)
|
|
751
|
+
.find(j.TSInterfaceDeclaration, { id: { name: 'RequestLocals' } })
|
|
752
|
+
.forEach((path) => {
|
|
753
|
+
reports.push({
|
|
754
|
+
kind: 'request-locals-augmentation',
|
|
755
|
+
file: filePath,
|
|
756
|
+
line: lineOf(path.node),
|
|
757
|
+
reason: 'the global RequestLocals interface is removed: provide each local with createMiddleware, annotate the locals a shared layout entry reads on its factory parameter, then delete this declaration',
|
|
758
|
+
});
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
function writeReports(reports) {
|
|
762
|
+
const target = process.env[REPORT_ENV];
|
|
763
|
+
if (!target || reports.length === 0)
|
|
764
|
+
return;
|
|
765
|
+
appendFileSync(target, reports.map((report) => `${JSON.stringify(report)}\n`).join(''));
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* The middleware function of a declarator, with the names of its context and `next` parameters.
|
|
769
|
+
*
|
|
770
|
+
* @remarks
|
|
771
|
+
* Returns `null` for anything that is not a block-bodied function whose first parameter is a plain identifier.
|
|
772
|
+
*/
|
|
773
|
+
function middlewareFunction(init) {
|
|
774
|
+
const fn = unwrapExpression(init);
|
|
775
|
+
if (!isNode(fn) || !FUNCTION_TYPES.has(fn.type) || !isNode(fn.body) || fn.body.type !== 'BlockStatement') {
|
|
776
|
+
return null;
|
|
777
|
+
}
|
|
778
|
+
const [first, second] = fn.params;
|
|
779
|
+
if (!first || first.type !== 'Identifier')
|
|
780
|
+
return null;
|
|
781
|
+
return {
|
|
782
|
+
fn,
|
|
783
|
+
ctx: first.name,
|
|
784
|
+
next: second && second.type === 'Identifier' ? second.name : null,
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* Whether a reference to a middleware binding keeps working once the binding is a `createMiddleware` result: an entry
|
|
789
|
+
* of a `middleware: [...]` list, an argument of `composeMiddleware`, an export specifier or a `typeof` query.
|
|
790
|
+
*/
|
|
791
|
+
function acceptsMadeMiddleware(path) {
|
|
792
|
+
const parent = path.parent.node;
|
|
793
|
+
if (parent.type === 'ExportSpecifier' || parent.type === 'TSTypeQuery')
|
|
794
|
+
return true;
|
|
795
|
+
if (parent.type === 'CallExpression') {
|
|
796
|
+
return isNode(parent.callee) && parent.callee.name === 'composeMiddleware' && parent.callee !== path.node;
|
|
797
|
+
}
|
|
798
|
+
if (parent.type !== 'ArrayExpression')
|
|
799
|
+
return false;
|
|
800
|
+
const holder = path.parent.parent.node;
|
|
801
|
+
return holder.type === 'ObjectProperty' && isNode(holder.key) && holder.key.name === 'middleware';
|
|
802
|
+
}
|
|
803
|
+
/** Why a binding cannot become a `createMiddleware` result, judged by how this file references it. */
|
|
804
|
+
function bindingUseReason(j, root, path) {
|
|
805
|
+
const id = path.node.id;
|
|
806
|
+
if (id.type !== 'Identifier')
|
|
807
|
+
return null;
|
|
808
|
+
const misused = root
|
|
809
|
+
.find(j.Identifier, { name: id.name })
|
|
810
|
+
.filter((reference) => reference.node !== id && !isNameOnly(reference) && !acceptsMadeMiddleware(reference));
|
|
811
|
+
if (misused.length === 0)
|
|
812
|
+
return null;
|
|
813
|
+
return `is referenced on line ${lineOf(misused.nodes()[0])} other than in a middleware list, where a createMiddleware result is not a function`;
|
|
814
|
+
}
|
|
815
|
+
function reportAssignments(context, nodes, why) {
|
|
816
|
+
for (const node of nodes) {
|
|
817
|
+
context.reports.push({
|
|
818
|
+
kind: 'locals-assignment',
|
|
819
|
+
file: context.filePath,
|
|
820
|
+
line: lineOf(node),
|
|
821
|
+
reason: `ctx.locals assignment not moved: the middleware ${why}`,
|
|
822
|
+
});
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
/** Why an annotated middleware with these assignments cannot be rewritten, or its plan. */
|
|
826
|
+
function declaratorPlan(context, path, target, assignments, annotation) {
|
|
827
|
+
if (annotation.hasTypeArguments) {
|
|
828
|
+
return `is annotated ${annotation.name}<...>, and a createMiddleware stage does not take its request type`;
|
|
829
|
+
}
|
|
830
|
+
const plan = planMove(context.j, target.fn, target.ctx, target.next, assignments);
|
|
831
|
+
if (typeof plan === 'string')
|
|
832
|
+
return plan;
|
|
833
|
+
if (context.createName === null) {
|
|
834
|
+
return 'is in a file where createMiddleware already names something other than the @ecopages/core export';
|
|
835
|
+
}
|
|
836
|
+
return bindingUseReason(context.j, context.root, path) ?? plan;
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* Migrates one annotated middleware declaration, or reports why it was left alone.
|
|
840
|
+
*
|
|
841
|
+
* @returns Whether the declaration was rewritten.
|
|
842
|
+
*/
|
|
843
|
+
function migrateDeclarator(context, path) {
|
|
844
|
+
const { j, imported } = context;
|
|
845
|
+
const annotation = middlewareAnnotation(path.node);
|
|
846
|
+
if (!annotation || !imported.has(annotation.name))
|
|
847
|
+
return false;
|
|
848
|
+
const original = imported.get(annotation.name);
|
|
849
|
+
const init = unwrapExpression(path.node.init);
|
|
850
|
+
if (original === 'EcoMiddleware') {
|
|
851
|
+
context.handled.add(init);
|
|
852
|
+
context.reports.push({
|
|
853
|
+
kind: 'eco-middleware',
|
|
854
|
+
file: context.filePath,
|
|
855
|
+
line: lineOf(path.node),
|
|
856
|
+
reason: 'EcoMiddleware<Context> is removed; pass the value with next({ field }) and read it from ctx.locals',
|
|
857
|
+
});
|
|
858
|
+
return false;
|
|
859
|
+
}
|
|
860
|
+
if (!original || !OLD_TYPES.has(original))
|
|
861
|
+
return false;
|
|
862
|
+
const write = firstLocalsWrite(j, init);
|
|
863
|
+
if (!write)
|
|
864
|
+
return false;
|
|
865
|
+
context.handled.add(init);
|
|
866
|
+
const target = middlewareFunction(init);
|
|
867
|
+
if (!target) {
|
|
868
|
+
reportAssignments(context, [write], 'is not a block-bodied function whose first parameter is a plain identifier (it destructures the context or returns an expression)');
|
|
869
|
+
return false;
|
|
870
|
+
}
|
|
871
|
+
const assignments = j(target.fn)
|
|
872
|
+
.find(j.AssignmentExpression)
|
|
873
|
+
.filter((candidate) => isLocalsAssignment(candidate.node, target.ctx))
|
|
874
|
+
.paths();
|
|
875
|
+
if (assignments.length === 0) {
|
|
876
|
+
reportAssignments(context, [write], 'writes ctx.locals only through a computed key, Object.assign or delete');
|
|
877
|
+
return false;
|
|
878
|
+
}
|
|
879
|
+
const plan = declaratorPlan(context, path, target, assignments, annotation);
|
|
880
|
+
if (typeof plan === 'string') {
|
|
881
|
+
reportAssignments(context, assignments.map((assignment) => assignment.node), plan);
|
|
882
|
+
return false;
|
|
883
|
+
}
|
|
884
|
+
plan.nextReturn.node.arguments = [buildLocalsObject(j, plan.moves)];
|
|
885
|
+
applyMoves(j, target.fn.body.body, plan.moves);
|
|
886
|
+
path.node.id.typeAnnotation = null;
|
|
887
|
+
path.node.init = j.callExpression(j.identifier(context.createName), [target.fn]);
|
|
888
|
+
return true;
|
|
889
|
+
}
|
|
890
|
+
/**
|
|
891
|
+
* Reports each function left in the file that writes a `locals` object, such as a middleware without a
|
|
892
|
+
* `FileRouteMiddleware` or `Middleware` annotation, whose writes no later stage or page sees in its types.
|
|
893
|
+
*/
|
|
894
|
+
function reportUnannotatedWrites(context) {
|
|
895
|
+
const { j, root } = context;
|
|
896
|
+
root.find(j.Function).forEach((path) => {
|
|
897
|
+
for (let current = path; current; current = current.parent) {
|
|
898
|
+
if (context.handled.has(current.node))
|
|
899
|
+
return;
|
|
900
|
+
}
|
|
901
|
+
const write = firstLocalsWrite(j, path.node);
|
|
902
|
+
if (!write)
|
|
903
|
+
return;
|
|
904
|
+
context.handled.add(path.node);
|
|
905
|
+
context.reports.push({
|
|
906
|
+
kind: 'locals-assignment',
|
|
907
|
+
file: context.filePath,
|
|
908
|
+
line: lineOf(write),
|
|
909
|
+
reason: 'ctx.locals written by a function not annotated FileRouteMiddleware or Middleware from @ecopages/core, so it was not rewritten and no later stage, page or handler sees the value in its types: make it a createMiddleware stage that passes the value to next({ ... })',
|
|
910
|
+
});
|
|
911
|
+
});
|
|
912
|
+
}
|
|
913
|
+
export default function transform(file, api, _options) {
|
|
914
|
+
const j = api.jscodeshift;
|
|
915
|
+
const root = j(file.source);
|
|
916
|
+
const binding = createMiddlewareBinding(j, root);
|
|
917
|
+
const context = {
|
|
918
|
+
j,
|
|
919
|
+
root,
|
|
920
|
+
filePath: file.path,
|
|
921
|
+
imported: coreImports(j, root),
|
|
922
|
+
createName: binding?.name ?? null,
|
|
923
|
+
reports: [],
|
|
924
|
+
handled: new Set(),
|
|
925
|
+
};
|
|
926
|
+
let changed = false;
|
|
927
|
+
root.find(j.VariableDeclarator).forEach((path) => {
|
|
928
|
+
if (migrateDeclarator(context, path))
|
|
929
|
+
changed = true;
|
|
930
|
+
});
|
|
931
|
+
if (changed) {
|
|
932
|
+
dropUnusedCoreTypes(j, root);
|
|
933
|
+
if (!binding?.imported)
|
|
934
|
+
addCreateMiddlewareImport(j, root);
|
|
935
|
+
}
|
|
936
|
+
root.find(j.CallExpression)
|
|
937
|
+
.filter((path) => isEcoPageCall(path.node))
|
|
938
|
+
.forEach((path) => {
|
|
939
|
+
if (migratePage(j, path, file.path, context.reports))
|
|
940
|
+
changed = true;
|
|
941
|
+
});
|
|
942
|
+
reportUnannotatedWrites(context);
|
|
943
|
+
reportRequestLocalsAugmentations(j, root, file.path, context.reports);
|
|
944
|
+
for (const report of context.reports) {
|
|
945
|
+
api.report(`migrate-middleware-locals: ${report.file}:${report.line} ${report.reason}`);
|
|
946
|
+
}
|
|
947
|
+
writeReports(context.reports);
|
|
948
|
+
return changed ? root.toSource(printOptions(file.source)) : null;
|
|
949
|
+
}
|