@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
package/README.md
CHANGED
|
@@ -1,133 +1,80 @@
|
|
|
1
1
|
# @ecopages/codemod
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Codemods that migrate an Ecopages project to the current patterns. Each transform is a [jscodeshift](https://github.com/facebook/jscodeshift) module.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
The package follows the Ecopages release train. Use the version that matches the `@ecopages/core` you upgrade to.
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
pnpm install --filter @ecopages/codemod
|
|
9
|
-
```
|
|
10
|
-
|
|
11
|
-
Run transforms through the workspace package so they use the version from the matching Ecopages checkout. Pass absolute paths to the project files being migrated.
|
|
7
|
+
## Run
|
|
12
8
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
Run this from the Ecopages checkout to migrate components, layouts, includes, and pages in another project:
|
|
9
|
+
From the project root, with no install:
|
|
16
10
|
|
|
17
11
|
```bash
|
|
18
|
-
|
|
19
|
-
pnpm --filter @ecopages/codemod exec jscodeshift \
|
|
20
|
-
-t src/transforms/migrate-to-eco-component.ts \
|
|
21
|
-
--parser tsx \
|
|
22
|
-
--extensions=ts,tsx,js,jsx \
|
|
23
|
-
/path/to/project/src/components \
|
|
24
|
-
/path/to/project/src/layouts \
|
|
25
|
-
/path/to/project/src/includes
|
|
26
|
-
|
|
27
|
-
# Migrate pages
|
|
28
|
-
pnpm --filter @ecopages/codemod exec jscodeshift \
|
|
29
|
-
-t src/transforms/migrate-to-eco-page.ts \
|
|
30
|
-
--parser tsx \
|
|
31
|
-
--extensions=ts,tsx,js,jsx \
|
|
32
|
-
/path/to/project/src/pages
|
|
12
|
+
npx @ecopages/codemod <transform> [paths...]
|
|
33
13
|
```
|
|
34
14
|
|
|
35
|
-
|
|
15
|
+
Paths default to `src`. Extra flags pass through to jscodeshift, so `--dry --print` previews without writing files. `npx @ecopages/codemod --list` prints the transforms. Format the result afterwards, since the raw output indents rewritten lines with extra tabs.
|
|
36
16
|
|
|
37
|
-
|
|
17
|
+
## Transforms
|
|
38
18
|
|
|
39
|
-
|
|
19
|
+
| Transform | Added in | Migrates |
|
|
20
|
+
| --------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
21
|
+
| `migrate-radiant-refs` | 0.10.0 | `@ecopages/radiant` `@query` options and `createQuery` options to `@ref`, `@refAll`, `@query(selector)` and `@queryAll(selector)` (Radiant 0.11.0) |
|
|
22
|
+
| `migrate-radiant-bindings` | 0.10.0 | `@ecopages/radiant` `$name` companion bindings and the `bind` option to `this.$` (Radiant 0.10.0) |
|
|
23
|
+
| `migrate-data-hooks` | 0.9.0 | `staticProps` and `staticPaths` of `eco.page()` to `props` and `paths` |
|
|
24
|
+
| `migrate-to-eco-page` | 0.3.0 | Module-level data exports and `Page.config` to `eco.page()`; runs the one above |
|
|
25
|
+
| `migrate-to-eco-component` | 0.3.0 | `Component.config` assignments to `eco.component()` |
|
|
26
|
+
| `migrate-core-entrypoints` | 0.3.0 | Imports from `@ecopages/core` to the role-based entry points |
|
|
27
|
+
| `migrate-middleware-locals` | 0.10.0 | `ctx.locals` assignments of `FileRouteMiddleware` and `Middleware` to `createMiddleware` and `next({ ... })`, and `locals` read in a page's `render` to `props` |
|
|
40
28
|
|
|
41
|
-
|
|
29
|
+
A transform leaves code it cannot rewrite safely unchanged and reports it, so the old API still fails loudly. Rename those by hand. Transforms leave already-migrated code unchanged, so running one twice is safe.
|
|
42
30
|
|
|
43
|
-
|
|
31
|
+
`migrate-middleware-locals` rewrites a middleware annotated `FileRouteMiddleware` or `Middleware`, on its name or with `satisfies`. It moves only unconditional top-level assignments before a single `return next()`, and only when the body uses `ctx` just to read its fields: code that receives `ctx` itself (a helper called with it, a destructured `locals`) could look for a local that `next()` now provides later. It also refuses when anything between the first assignment and `next()` awaits, returns or throws, since an outer stage could read a local the stage had already set before it left. A synchronous call that throws there is not detected. A value that could change before `next()` runs is bound to a `const` where the assignment was, so it keeps its value and evaluation order. The rewritten middleware is a `createMiddleware` result, not a function, so a middleware the same file calls or stores other than in a `middleware` list is reported, and code in other files that calls it directly, such as a test, needs updating by hand. An annotation with type arguments, an API `Middleware` that reads `ctx.query`, `ctx.render` or `ctx.renderPartial` (a `createMiddleware` stage is typed with the page context, which has none of them), and a file where `createMiddleware` already names something else are reported. Any other function that writes `ctx.locals` is reported too.
|
|
44
32
|
|
|
45
|
-
|
|
46
|
-
npx jscodeshift@17 --parser tsx --extensions=ts,tsx,js,jsx -t https://raw.githubusercontent.com/ecopages/ecopages/refs/tags/v<version>/packages/codemod/src/transforms/migrate-data-hooks.ts src
|
|
47
|
-
```
|
|
33
|
+
It also moves the `locals` a page reads in `render` into a new `props` hook and drops `requires`, since `render` no longer receives `locals`. It does so only for a literal `cache: 'dynamic'` page with a `middleware` list and without `props`, whose `render` destructures `locals` and reads it as member chain values outside any condition, loop, `try`, `await` or nested function, since `props` reads every chain on every request. What `props` returns is sent to the browser, so each chain becomes one prop holding only that value (`locals.session.user` becomes `sessionUser`), never a whole session or user object. A page is reported when it passes, calls, indexes or spreads `locals`, reads both a value and a member of it, reads `locals.params` or `locals.query`, or would need a reserved word as a prop name. It leaves `EcoMiddleware<Context>` annotations, assignments in branches, and every other page that declares `requires` or reads `locals` in `render` unchanged. Recast prints new code one key per line, so run your formatter afterwards. It also reports each `interface RequestLocals` declared in a `declare module '@ecopages/core'` block, since the global interface is removed and the augmentation types nothing; pass the declaration file as a path when it sits outside `src` (`npx @ecopages/codemod migrate-middleware-locals src modules.d.ts`). To finish one, make sure a `createMiddleware` stage provides each local it declared, list that middleware on every page or route that reads them, annotate the locals a shared layout entry reads on its factory parameter, then delete the declaration. When the run ends, the CLI prints a migration brief listing each of those as `file:line`, the docs to read, and a prompt to hand to a coding agent.
|
|
48
34
|
|
|
49
|
-
The
|
|
35
|
+
The release notes of each core version name the transform that goes with its breaking changes.
|
|
50
36
|
|
|
51
|
-
###
|
|
37
|
+
### `migrate-radiant-bindings`
|
|
52
38
|
|
|
53
|
-
|
|
39
|
+
Radiant 0.10.0 removed the `$name` companion of each reactive member and the `bind` option that named it. Run it when you upgrade `@ecopages/radiant` to 0.10.0; it does not need Radiant installed:
|
|
54
40
|
|
|
55
41
|
```bash
|
|
56
|
-
|
|
42
|
+
npx @ecopages/codemod migrate-radiant-bindings src
|
|
57
43
|
```
|
|
58
44
|
|
|
59
|
-
|
|
45
|
+
It rewrites, on classes that extend `RadiantElement`, `RadiantController` or `FormAssociatedElement`:
|
|
60
46
|
|
|
61
|
-
|
|
47
|
+
- `this.$count` to `this.$.count`, in JSX and in plain code, for a `@prop`, `@state`, `@attr` or `@signal` field or a `createReactiveProp` or `createReactiveField` member that had a companion;
|
|
48
|
+
- a read of the name a `bind: 'name'` string gave to `this.$.<field>`;
|
|
49
|
+
- `bind: true`, `bind: false` and `bind: 'name'` out of the options, with an options object left empty when the option is optional (`@attr()`, `@signal()`);
|
|
50
|
+
- a `declare $count` that typed a companion out of the class;
|
|
51
|
+
- the binding shape into the type argument of `extends RadiantElement` or `extends RadiantController`, as `RadiantElement<{ count: number }>`, typed from the field's annotation or literal initializer. A type argument already there is extended, or intersected when it is a named type.
|
|
62
52
|
|
|
63
|
-
|
|
64
|
-
pnpm --filter @ecopages/codemod exec jscodeshift -t src/transforms/migrate-to-eco-component.ts --parser tsx --extensions=ts,tsx,js,jsx /path/to/project/src/components
|
|
65
|
-
```
|
|
53
|
+
It leaves the code as written and prints the file and line for the rest: `ReactiveBindingOption` imports, `defineReactiveBinding` and `shouldAutoBindReactiveMembers`, computed `this[...]` access to a `$` name, a companion written, destructured or read outside its class, a `bind` or options value that is not a literal, a member type it cannot tell, and `$name` reads in a class whose base is in another file. It edits only the text it changes, so the rest of the file keeps its formatting.
|
|
66
54
|
|
|
67
|
-
###
|
|
55
|
+
### `migrate-radiant-refs`
|
|
68
56
|
|
|
69
|
-
|
|
57
|
+
For the ref/query split of `@ecopages/radiant` 0.11.0, which removes the `@query` options object, its `cache` option, the options form of `createQuery`, and the `QueryConfig` type. Run it when you upgrade to 0.11.0; it does not need Radiant installed:
|
|
70
58
|
|
|
71
59
|
```bash
|
|
72
|
-
|
|
73
|
-
-t src/transforms/migrate-core-entrypoints.ts \
|
|
74
|
-
--parser tsx \
|
|
75
|
-
--extensions=ts,tsx,js,jsx \
|
|
76
|
-
/path/to/project/src
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
The transform leaves imports unchanged and reports them when a requested named export is not present in the destination role entry. Review those imports manually. Matching string-literal dynamic `import()` and `require()` calls stay unchanged with a warning, since their accessed names cannot be checked safely. Computed or other nonliteral module paths are left unchanged without a warning. `@ecopages/core/config/write-types` and `@ecopages/core/hmr/client/hmr-runtime` remain unchanged because core loads those entries by path.
|
|
80
|
-
|
|
81
|
-
## Options
|
|
82
|
-
|
|
83
|
-
| Option | Description |
|
|
84
|
-
| --------- | ---------------------------------------- |
|
|
85
|
-
| `--dry` | Preview changes without writing to files |
|
|
86
|
-
| `--print` | Print transformed output to stdout |
|
|
87
|
-
| `-v 2` | Verbose output showing all changes |
|
|
88
|
-
|
|
89
|
-
## Transform Details
|
|
90
|
-
|
|
91
|
-
### Pages
|
|
92
|
-
|
|
93
|
-
**Before:**
|
|
94
|
-
|
|
95
|
-
```tsx
|
|
96
|
-
export const getStaticPaths = async () => ({ paths: [...] });
|
|
97
|
-
export const getStaticProps = async ({ pathname }) => ({ props: {...} });
|
|
98
|
-
export const getMetadata = ({ props }) => ({ title: '...' });
|
|
99
|
-
|
|
100
|
-
const Page: EcoComponent = () => <h1>...</h1>;
|
|
101
|
-
Page.config = { layout: BaseLayout };
|
|
102
|
-
export default Page;
|
|
60
|
+
npx @ecopages/codemod migrate-radiant-refs src
|
|
103
61
|
```
|
|
104
62
|
|
|
105
|
-
|
|
63
|
+
It rewrites each `@query` decorator, whether applied with `@` or called on `Class.prototype`, and each `createQuery` call, without renaming fields:
|
|
106
64
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
})
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
### Components
|
|
65
|
+
| Before | After |
|
|
66
|
+
| ------------------------------------------------- | ------------------------------------------------------------------------------------- |
|
|
67
|
+
| `@query({ ref: 'menubar-root' }) menubarRoot` | `@ref() menubarRoot` |
|
|
68
|
+
| `@query({ ref: 'root' }) rootTarget` | `@ref('root') rootTarget` |
|
|
69
|
+
| `@query({ ref: 'item', all: true }) items` | `@refAll('item') items` |
|
|
70
|
+
| `@query({ selector: 's' }) f` | `@query('s') f` |
|
|
71
|
+
| `@query({ selector: 's', all: true }) fs` | `@queryAll('s') fs` |
|
|
72
|
+
| `createQuery(host, { selector: 's', all: true })` | `createQueryAll(host, 's')` |
|
|
73
|
+
| `createQuery(host, { ref: 'x' })` | `createQuery(host, '[data-ref="x"]')` |
|
|
74
|
+
| `cache: true` or `cache: false` | removed; `cache: true` is reported, since the field now reads the DOM on every access |
|
|
118
75
|
|
|
119
|
-
|
|
76
|
+
`@ref` and `@refAll` take no name when the `ref` equals the field name as an attribute name, as Radiant derives it (`menubarRoot` finds `menubar-root`, `listboxID` finds `listbox-id`), and keep the name as written otherwise: `@query({ ref: 'rangeTrack' }) rangeTrack` becomes `@ref('rangeTrack')`, since a nameless `@ref` would look for `range-track`. `createQuery(host, { ref })` becomes the selector the options form built, which still reaches into nested hosts; use `getRef(name)` on the host instead if you want only the parts the host owns. The imports gain `ref`, `refAll`, `queryAll` and `createQueryAll` from the module that exports them (`@ecopages/radiant`, `@ecopages/radiant/decorators/ref`, `@ecopages/radiant/decorators/query` or `@ecopages/radiant/helpers/create-query`), and lose `query` and `createQuery` once nothing reads them.
|
|
120
77
|
|
|
121
|
-
|
|
122
|
-
export const Counter: EcoComponent<Props> = ({ count }) => <my-counter />;
|
|
123
|
-
Counter.config = { dependencies: { scripts: ['./script.ts'] } };
|
|
124
|
-
```
|
|
78
|
+
It leaves the code as written and prints the file and line for: `QueryConfig` imports; options it cannot read (a spread, a non-literal `all`, an options object held in a constant, both or neither of `selector` and `ref`, a `createQuery` ref that is not a plain string); `getReactiveMember(...).set(...)`, which is now read-only; a `@controller`, `registerController` or `replaceController` identifier with `:`, which now throws; a string `ref` attribute in JSX, which is now a type error and probably meant `data-ref`; and, in a file that registers controllers, a `data-hydration-key` without `:`, since a controller's hydration script is now keyed `id:field`.
|
|
125
79
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
```tsx
|
|
129
|
-
export const Counter = eco.component<Props>({
|
|
130
|
-
dependencies: { scripts: ['./script.ts'] },
|
|
131
|
-
render: ({ count }) => <my-counter />,
|
|
132
|
-
});
|
|
133
|
-
```
|
|
80
|
+
Two changes cannot be seen in the source, and the CLI prints them after the run. `@ref`, `@refAll`, `getRef`, `@onEvent({ ref })` and `@bindTo({ ref })` now see only the parts their own host owns, so an outer host no longer reads a nested host's part of the same name; reach into a nested host with `@query('[data-ref="name"]')`, `@onEvent({ selector })`, `@bindTo({ selector })` or `host.querySelector(...)`. `@onEvent({ ref })` no longer fires for a `data-ref` on the host element itself.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ecopages/codemod",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "Codemods for migrating ecopages to latest patterns",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -15,6 +15,11 @@
|
|
|
15
15
|
"types": "./src/transforms/migrate-data-hooks.d.ts",
|
|
16
16
|
"default": "./src/transforms/migrate-data-hooks.js"
|
|
17
17
|
},
|
|
18
|
+
"./migrate-middleware-locals": {
|
|
19
|
+
"import": "./src/transforms/migrate-middleware-locals.js",
|
|
20
|
+
"types": "./src/transforms/migrate-middleware-locals.d.ts",
|
|
21
|
+
"default": "./src/transforms/migrate-middleware-locals.js"
|
|
22
|
+
},
|
|
18
23
|
"./migrate-to-eco-component": {
|
|
19
24
|
"import": "./src/transforms/migrate-to-eco-component.js",
|
|
20
25
|
"types": "./src/transforms/migrate-to-eco-component.d.ts",
|
|
@@ -25,6 +30,16 @@
|
|
|
25
30
|
"types": "./src/transforms/migrate-to-eco-page.d.ts",
|
|
26
31
|
"default": "./src/transforms/migrate-to-eco-page.js"
|
|
27
32
|
},
|
|
33
|
+
"./migrate-radiant-bindings": {
|
|
34
|
+
"import": "./src/transforms/migrate-radiant-bindings.js",
|
|
35
|
+
"types": "./src/transforms/migrate-radiant-bindings.d.ts",
|
|
36
|
+
"default": "./src/transforms/migrate-radiant-bindings.js"
|
|
37
|
+
},
|
|
38
|
+
"./migrate-radiant-refs": {
|
|
39
|
+
"import": "./src/transforms/migrate-radiant-refs.js",
|
|
40
|
+
"types": "./src/transforms/migrate-radiant-refs.d.ts",
|
|
41
|
+
"default": "./src/transforms/migrate-radiant-refs.js"
|
|
42
|
+
},
|
|
28
43
|
"./migrate-core-entrypoints.ts": {
|
|
29
44
|
"import": "./src/transforms/migrate-core-entrypoints.js",
|
|
30
45
|
"types": "./src/transforms/migrate-core-entrypoints.d.ts",
|
|
@@ -35,6 +50,11 @@
|
|
|
35
50
|
"types": "./src/transforms/migrate-data-hooks.d.ts",
|
|
36
51
|
"default": "./src/transforms/migrate-data-hooks.js"
|
|
37
52
|
},
|
|
53
|
+
"./migrate-middleware-locals.ts": {
|
|
54
|
+
"import": "./src/transforms/migrate-middleware-locals.js",
|
|
55
|
+
"types": "./src/transforms/migrate-middleware-locals.d.ts",
|
|
56
|
+
"default": "./src/transforms/migrate-middleware-locals.js"
|
|
57
|
+
},
|
|
38
58
|
"./migrate-to-eco-component.ts": {
|
|
39
59
|
"import": "./src/transforms/migrate-to-eco-component.js",
|
|
40
60
|
"types": "./src/transforms/migrate-to-eco-component.d.ts",
|
|
@@ -44,8 +64,21 @@
|
|
|
44
64
|
"import": "./src/transforms/migrate-to-eco-page.js",
|
|
45
65
|
"types": "./src/transforms/migrate-to-eco-page.d.ts",
|
|
46
66
|
"default": "./src/transforms/migrate-to-eco-page.js"
|
|
67
|
+
},
|
|
68
|
+
"./migrate-radiant-bindings.ts": {
|
|
69
|
+
"import": "./src/transforms/migrate-radiant-bindings.js",
|
|
70
|
+
"types": "./src/transforms/migrate-radiant-bindings.d.ts",
|
|
71
|
+
"default": "./src/transforms/migrate-radiant-bindings.js"
|
|
72
|
+
},
|
|
73
|
+
"./migrate-radiant-refs.ts": {
|
|
74
|
+
"import": "./src/transforms/migrate-radiant-refs.js",
|
|
75
|
+
"types": "./src/transforms/migrate-radiant-refs.d.ts",
|
|
76
|
+
"default": "./src/transforms/migrate-radiant-refs.js"
|
|
47
77
|
}
|
|
48
78
|
},
|
|
79
|
+
"bin": {
|
|
80
|
+
"ecopages-codemod": "./src/cli.js"
|
|
81
|
+
},
|
|
49
82
|
"publishConfig": {
|
|
50
83
|
"access": "public"
|
|
51
84
|
},
|
|
@@ -60,4 +93,4 @@
|
|
|
60
93
|
"peerDependencies": {
|
|
61
94
|
"typescript": "^5.0.0"
|
|
62
95
|
}
|
|
63
|
-
}
|
|
96
|
+
}
|
package/src/cli.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { type MiddlewareReport } from './transforms/migrate-middleware-locals.js';
|
|
3
|
+
/**
|
|
4
|
+
* Transforms the CLI can run, each described for `--list`.
|
|
5
|
+
*/
|
|
6
|
+
export declare const TRANSFORMS: {
|
|
7
|
+
readonly 'migrate-data-hooks': "staticProps and staticPaths of eco.page() to props and paths";
|
|
8
|
+
readonly 'migrate-to-eco-page': "module-level data exports and Page.config to eco.page()";
|
|
9
|
+
readonly 'migrate-to-eco-component': "Component.config assignments to eco.component()";
|
|
10
|
+
readonly 'migrate-core-entrypoints': "@ecopages/core imports to the role-based entry points";
|
|
11
|
+
readonly 'migrate-middleware-locals': "ctx.locals assignments of middleware to createMiddleware and next({ ... })";
|
|
12
|
+
readonly 'migrate-radiant-bindings': "Radiant $name companion bindings and the bind option to this.$";
|
|
13
|
+
readonly 'migrate-radiant-refs': "Radiant @query options to @ref, @refAll, @query(selector) and @queryAll(selector)";
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Notes printed after a transform runs, for the breaking changes it cannot see in the source.
|
|
17
|
+
*/
|
|
18
|
+
export declare const AFTER_RUN_NOTES: Partial<Record<keyof typeof TRANSFORMS, string>>;
|
|
19
|
+
/**
|
|
20
|
+
* Runs a transform through the bundled jscodeshift and returns its exit code.
|
|
21
|
+
*
|
|
22
|
+
* @remarks
|
|
23
|
+
* The transform file keeps this module's own extension, so the CLI works both from the published
|
|
24
|
+
* `.js` build and from the `.ts` sources.
|
|
25
|
+
*/
|
|
26
|
+
export declare function run(argv: string[]): number;
|
|
27
|
+
/**
|
|
28
|
+
* Builds the migration brief printed after `migrate-middleware-locals`, written for a person and a coding agent.
|
|
29
|
+
*/
|
|
30
|
+
export declare function formatMigrationBrief(reports: readonly MiddlewareReport[]): string;
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { extname, join } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { REPORT_ENV } from './transforms/migrate-middleware-locals.js';
|
|
9
|
+
/**
|
|
10
|
+
* Transforms the CLI can run, each described for `--list`.
|
|
11
|
+
*/
|
|
12
|
+
export const TRANSFORMS = {
|
|
13
|
+
'migrate-data-hooks': 'staticProps and staticPaths of eco.page() to props and paths',
|
|
14
|
+
'migrate-to-eco-page': 'module-level data exports and Page.config to eco.page()',
|
|
15
|
+
'migrate-to-eco-component': 'Component.config assignments to eco.component()',
|
|
16
|
+
'migrate-core-entrypoints': '@ecopages/core imports to the role-based entry points',
|
|
17
|
+
'migrate-middleware-locals': 'ctx.locals assignments of middleware to createMiddleware and next({ ... })',
|
|
18
|
+
'migrate-radiant-bindings': 'Radiant $name companion bindings and the bind option to this.$',
|
|
19
|
+
'migrate-radiant-refs': 'Radiant @query options to @ref, @refAll, @query(selector) and @queryAll(selector)',
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Notes printed after a transform runs, for the breaking changes it cannot see in the source.
|
|
23
|
+
*/
|
|
24
|
+
export const AFTER_RUN_NOTES = {
|
|
25
|
+
'migrate-radiant-refs': [
|
|
26
|
+
'NOTE: Radiant ref/query split',
|
|
27
|
+
'',
|
|
28
|
+
'@ref, @refAll, getRef, @onEvent({ ref }) and @bindTo({ ref }) now see only the data-ref parts their own host owns: an outer host no longer gets a nested host part of the same name, and @refAll and getRef(name, true) leave nested parts out. @onEvent({ ref }) no longer fires for a data-ref on the host element itself. This codemod cannot see either case.',
|
|
29
|
+
'',
|
|
30
|
+
'Check each host that renders another Radiant host inside it. Where the outer host read a part of the inner one, use @query(\'[data-ref="name"]\'), @onEvent({ selector }), @bindTo({ selector }) or host.querySelector(...), which still reach into nested hosts. Move a listener on the host element itself off @onEvent({ ref }).',
|
|
31
|
+
].join('\n'),
|
|
32
|
+
};
|
|
33
|
+
const USAGE = `Usage: ecopages-codemod <transform> [paths...] [jscodeshift options]
|
|
34
|
+
|
|
35
|
+
Runs a transform over the given paths (default: src). Pass --dry --print to preview.
|
|
36
|
+
|
|
37
|
+
Transforms:
|
|
38
|
+
${Object.entries(TRANSFORMS)
|
|
39
|
+
.map(([name, description]) => ` ${name.padEnd(28)}${description}`)
|
|
40
|
+
.join('\n')}
|
|
41
|
+
`;
|
|
42
|
+
/**
|
|
43
|
+
* Runs a transform through the bundled jscodeshift and returns its exit code.
|
|
44
|
+
*
|
|
45
|
+
* @remarks
|
|
46
|
+
* The transform file keeps this module's own extension, so the CLI works both from the published
|
|
47
|
+
* `.js` build and from the `.ts` sources.
|
|
48
|
+
*/
|
|
49
|
+
export function run(argv) {
|
|
50
|
+
const [name, ...rest] = argv;
|
|
51
|
+
if (!name || name === '--help' || name === '-h') {
|
|
52
|
+
process.stdout.write(USAGE);
|
|
53
|
+
return name ? 0 : 1;
|
|
54
|
+
}
|
|
55
|
+
if (name === '--list') {
|
|
56
|
+
process.stdout.write(`${Object.keys(TRANSFORMS).join('\n')}\n`);
|
|
57
|
+
return 0;
|
|
58
|
+
}
|
|
59
|
+
if (!Object.hasOwn(TRANSFORMS, name)) {
|
|
60
|
+
process.stderr.write(`Unknown transform "${name}".\n\n${USAGE}`);
|
|
61
|
+
return 1;
|
|
62
|
+
}
|
|
63
|
+
const transform = fileURLToPath(new URL(`./transforms/${name}${extname(import.meta.url)}`, import.meta.url));
|
|
64
|
+
const jscodeshift = createRequire(import.meta.url).resolve('jscodeshift/bin/jscodeshift.js');
|
|
65
|
+
const hasFlag = (flag) => rest.some((arg) => arg === flag || arg.startsWith(`${flag}=`));
|
|
66
|
+
const hasPath = rest.some((arg) => !arg.startsWith('-'));
|
|
67
|
+
const args = [
|
|
68
|
+
jscodeshift,
|
|
69
|
+
'-t',
|
|
70
|
+
transform,
|
|
71
|
+
...(hasFlag('--parser') ? [] : ['--parser', 'tsx']),
|
|
72
|
+
...(hasFlag('--extensions') ? [] : ['--extensions=ts,tsx,js,jsx']),
|
|
73
|
+
...rest,
|
|
74
|
+
...(hasPath ? [] : ['src']),
|
|
75
|
+
];
|
|
76
|
+
if (name !== 'migrate-middleware-locals') {
|
|
77
|
+
const status = spawnSync(process.execPath, args, { stdio: 'inherit' }).status ?? 1;
|
|
78
|
+
const note = AFTER_RUN_NOTES[name];
|
|
79
|
+
if (note)
|
|
80
|
+
process.stdout.write(`\n${note}\n`);
|
|
81
|
+
return status;
|
|
82
|
+
}
|
|
83
|
+
const reportDir = mkdtempSync(join(tmpdir(), 'ecopages-codemod-'));
|
|
84
|
+
const reportFile = join(reportDir, 'report.jsonl');
|
|
85
|
+
try {
|
|
86
|
+
const status = spawnSync(process.execPath, args, { stdio: 'inherit', env: { ...process.env, [REPORT_ENV]: reportFile } })
|
|
87
|
+
.status ?? 1;
|
|
88
|
+
process.stdout.write(`\n${formatMigrationBrief(readReports(reportFile))}\n`);
|
|
89
|
+
return status;
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
rmSync(reportDir, { recursive: true, force: true });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function readReports(reportFile) {
|
|
96
|
+
try {
|
|
97
|
+
return readFileSync(reportFile, 'utf-8')
|
|
98
|
+
.split('\n')
|
|
99
|
+
.filter(Boolean)
|
|
100
|
+
.map((line) => JSON.parse(line));
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
return [];
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const DOCS = [
|
|
107
|
+
'core/request-locals',
|
|
108
|
+
'server/define-handlers',
|
|
109
|
+
'server/explicit-routing',
|
|
110
|
+
'server/endpoint-files',
|
|
111
|
+
'reference/typescript',
|
|
112
|
+
];
|
|
113
|
+
const CATEGORIES = [
|
|
114
|
+
{ kind: 'eco-middleware', title: 'EcoMiddleware<Context> forms' },
|
|
115
|
+
{ kind: 'locals-assignment', title: 'ctx.locals assignments that were not moved' },
|
|
116
|
+
{ kind: 'page-requires', title: 'Pages that declare requires or read locals in render' },
|
|
117
|
+
{ kind: 'request-locals-augmentation', title: 'RequestLocals declarations' },
|
|
118
|
+
];
|
|
119
|
+
/**
|
|
120
|
+
* Builds the migration brief printed after `migrate-middleware-locals`, written for a person and a coding agent.
|
|
121
|
+
*/
|
|
122
|
+
export function formatMigrationBrief(reports) {
|
|
123
|
+
const manual = reports.length
|
|
124
|
+
? [...reports]
|
|
125
|
+
.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line)
|
|
126
|
+
.map((report) => ` ${report.file}:${report.line} ${report.reason}`)
|
|
127
|
+
.join('\n')
|
|
128
|
+
: ' Nothing reported. The codemod rewrites only what it can prove safe, so review the diff and run the type check.';
|
|
129
|
+
const found = CATEGORIES.filter(({ kind }) => reports.some((report) => report.kind === kind)).map(({ title }) => title);
|
|
130
|
+
return [
|
|
131
|
+
'MIGRATION BRIEF: middleware locals',
|
|
132
|
+
'',
|
|
133
|
+
'What changed in the API: middleware now provides typed locals through next({ ... }) and reads them through ctx.locals. A stage calls next once, and a plain function that overwrites a local an earlier stage provided throws. Listing the same stage twice in a middleware list is an error. EcoMiddleware<Context> and ctx.require are removed. A page is typed from its middleware list, and its locals are exactly what that list provides: the global RequestLocals interface is removed, so a RequestLocals augmentation of @ecopages/core types nothing. requires is removed and render no longer receives locals: a dynamic page reads them in props and render reads what props returned, which is also sent to the browser: return only the values render needs, never a whole session.',
|
|
134
|
+
'',
|
|
135
|
+
'A migrated middleware is a createMiddleware result, not a function: code in other files that calls it directly, such as a test, has to run it through a middleware list instead.',
|
|
136
|
+
'',
|
|
137
|
+
'A page that read locals in render:',
|
|
138
|
+
" Before: eco.page({ cache: 'dynamic', middleware: [auth], requires: ['session'], render: ({ locals }) => <h1>{locals.session.user.name}</h1> })",
|
|
139
|
+
" After: eco.page({ cache: 'dynamic', middleware: [auth], props: ({ locals }) => ({ user: locals.session.user }), render: ({ user }) => <h1>{user.name}</h1> })",
|
|
140
|
+
'',
|
|
141
|
+
'A shared layout entry that read the global locals:',
|
|
142
|
+
' Before: { component: Shell, props: ({ locals }: LayoutPropsContext) => ({ user: locals?.session?.user }) }',
|
|
143
|
+
' After: { component: Shell, props: ({ locals }: { locals: { session: Session } }) => ({ user: locals.session.user }) }',
|
|
144
|
+
'',
|
|
145
|
+
'Needs manual work:',
|
|
146
|
+
manual,
|
|
147
|
+
'',
|
|
148
|
+
'Docs:',
|
|
149
|
+
...DOCS.map((doc) => ` https://ecopages.app/docs/${doc}`),
|
|
150
|
+
'',
|
|
151
|
+
`Agent prompt: Migrate the Ecopages middleware listed under "Needs manual work"${found.length ? ` (${found.join('; ')})` : ''}. For each ctx.locals assignment that was not moved, restructure the middleware so it has one next() call and passes the values through return next({ key: value }); for each EcoMiddleware<Context> form, replace ctx.field = value with createMiddleware and next({ field }), and read it through ctx.locals.field; for each page that declares requires or reads locals in render, add the middleware that provides the locals to the page middleware list, read them in props and return only the values render reads (locals.session.user as user, never a whole session or user object, since what props returns is sent to the browser), make render read the returned value, and drop requires; replace ctx.require(key, onMissing) with an explicit check of ctx.locals.key that returns the response; for each RequestLocals declaration, make sure a createMiddleware stage provides every local it declared, add that middleware to the list of each page or route that reads them, annotate the locals a shared layout entry reads on its factory parameter (a page that does not list the middleware then fails the type check), and delete the declaration. Follow the Docs list, then run the type check.`,
|
|
152
|
+
].join('\n');
|
|
153
|
+
}
|
|
154
|
+
if (import.meta.main) {
|
|
155
|
+
process.exitCode = run(process.argv.slice(2));
|
|
156
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
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 type { API, FileInfo, Options } from 'jscodeshift';
|
|
65
|
+
export declare const parser = "tsx";
|
|
66
|
+
/** The environment variable naming the file a run appends its reports to. */
|
|
67
|
+
export declare const REPORT_ENV = "ECOPAGES_CODEMOD_REPORT";
|
|
68
|
+
/** A case the codemod could not migrate, which a person or agent has to finish. */
|
|
69
|
+
export type MiddlewareReport = {
|
|
70
|
+
kind: 'eco-middleware' | 'locals-assignment' | 'page-requires' | 'request-locals-augmentation';
|
|
71
|
+
file: string;
|
|
72
|
+
line: number;
|
|
73
|
+
reason: string;
|
|
74
|
+
};
|
|
75
|
+
export default function transform(file: FileInfo, api: API, _options: Options): string | null;
|