@ecopages/codemod 0.9.0-rc.0 → 0.9.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 CHANGED
@@ -1,133 +1,28 @@
1
1
  # @ecopages/codemod
2
2
 
3
- Automated code transformations for upgrading Ecopages projects. This is an internal workspace package and is not published to npm. To run a transform, check out the Ecopages repository at the release ref matching the installed `@ecopages/core` version, then run the examples below from that checkout with an absolute path to the project being migrated.
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
- ## Installation
5
+ The package follows the Ecopages release train. Use the version that matches the `@ecopages/core` you upgrade to.
6
6
 
7
- ```bash
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.
12
-
13
- ## Complete Migration Script
14
-
15
- Run this from the Ecopages checkout to migrate components, layouts, includes, and pages in another project:
16
-
17
- ```bash
18
- # Migrate components, layouts, and includes
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
33
- ```
34
-
35
- ## Individual Migrations
36
-
37
- ### Migrate the Page Data Hooks to `props` and `paths`
7
+ ## Run
38
8
 
39
- Renames the `staticProps` and `staticPaths` options of `eco.page({ ... })` to `props` and `paths`, and drops the envelopes they returned: `props` returns the props object instead of `{ props }`, and `paths` returns `[{ params }]` instead of `{ paths }`. Core fails a page that still declares the old names and points here. The transform also renames the `GetStaticProps`, `GetStaticPaths` and `StaticPath` types imported from `@ecopages/*` to `GetProps`, `GetPaths` and `PagePath`. The props context passes `params` where it passed `pathname: { params }`, so it rewrites a `props` parameter written as `{ pathname: { params } }`, `{ pathname }` or `ctx.pathname.params` to read `params`. A hook that reads `pathname` any other way, or already has a `params` binding, keeps its `pathname` and is reported.
40
-
41
- It unwraps an object literal that holds only the envelope key, in an inline hook or a same-file function the option names. Any other return value in an `async` hook becomes `(await value).props` or `(await value).paths`. A hook it cannot unwrap, such as one imported from another file or a synchronous one with a computed return, is left unchanged and reported, so the old name still fails loudly. Rename those by hand.
42
-
43
- This transform is one self-contained file, so a project outside this repository runs it straight from GitHub, with no checkout. Replace `<version>` with the Ecopages version you upgrade to (tags look like `v0.8.0`), and run it from the project root:
9
+ From the project root, with no install:
44
10
 
45
11
  ```bash
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
12
+ npx @ecopages/codemod <transform> [paths...]
47
13
  ```
48
14
 
49
- The raw output indents rewritten lines with extra tabs, so run your formatter afterwards. Inside this repository, run `pnpm --filter @ecopages/codemod exec jscodeshift -t src/transforms/migrate-data-hooks.ts --parser tsx --extensions=ts,tsx,js,jsx /path/to/project/src`.
50
-
51
- ### Migrate Pages to `eco.page()`
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.
52
16
 
53
- Transforms pages from the removed module-level data exports to the `eco.page()` options. Core no longer reads `getStaticPaths`, `getStaticProps` or `getMetadata` exports and fails a page that still has them, so run this on every page before you upgrade. It finishes by running the data hooks migration above, so a migrated page declares `props` and `paths`. It migrates `export const` and `export function` declarations, `export { local as getStaticProps }` lists, the removed `eco.staticPaths()`, `eco.staticProps()` and `eco.metadata()` wrappers, legacy `Page.config` pages, and pages that already call `eco.page()`. A `typeof getStaticProps` type keeps the declaration in the file, unexported:
54
-
55
- ```bash
56
- pnpm --filter @ecopages/codemod exec jscodeshift -t src/transforms/migrate-to-eco-page.ts --parser tsx --extensions=ts,tsx,js,jsx /path/to/project/src/pages
57
- ```
58
-
59
- ### Migrate Components to `eco.component()`
60
-
61
- Transforms components from the legacy `.config` assignment to the consolidated API:
62
-
63
- ```bash
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
- ```
17
+ ## Transforms
66
18
 
67
- ### Migrate Core Entry Points
19
+ | Transform | Added in | Migrates |
20
+ | -------------------------- | -------- | ------------------------------------------------------------------------------- |
21
+ | `migrate-data-hooks` | 0.9.0 | `staticProps` and `staticPaths` of `eco.page()` to `props` and `paths` |
22
+ | `migrate-to-eco-page` | 0.3.0 | Module-level data exports and `Page.config` to `eco.page()`; runs the one above |
23
+ | `migrate-to-eco-component` | 0.3.0 | `Component.config` assignments to `eco.component()` |
24
+ | `migrate-core-entrypoints` | 0.3.0 | Imports from `@ecopages/core` to the role-based entry points |
68
25
 
69
- When upgrading to the role-based `@ecopages/core` exports, rewrite static imports and re-exports whose requested names are present in the destination entry. The transform also rewrites matching string-literal paths in `import.meta.resolve()` and `require.resolve()` calls. It leaves matching string-literal dynamic `import()` and `require()` calls unchanged and reports them for manual review because it cannot verify which exports the caller reads:
26
+ 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.
70
27
 
71
- ```bash
72
- pnpm --filter @ecopages/codemod exec jscodeshift \
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;
103
- ```
104
-
105
- **After:**
106
-
107
- ```tsx
108
- export default eco.page({
109
- layout: BaseLayout,
110
- paths: async () => [...],
111
- props: async ({ params }) => ({...}),
112
- metadata: ({ props }) => ({ title: '...' }),
113
- render: () => <h1>...</h1>,
114
- });
115
- ```
116
-
117
- ### Components
118
-
119
- **Before:**
120
-
121
- ```tsx
122
- export const Counter: EcoComponent<Props> = ({ count }) => <my-counter />;
123
- Counter.config = { dependencies: { scripts: ['./script.ts'] } };
124
- ```
125
-
126
- **After:**
127
-
128
- ```tsx
129
- export const Counter = eco.component<Props>({
130
- dependencies: { scripts: ['./script.ts'] },
131
- render: ({ count }) => <my-counter />,
132
- });
133
- ```
28
+ The release notes of each core version name the transform that goes with its breaking changes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/codemod",
3
- "version": "0.9.0-rc.0",
3
+ "version": "0.9.0",
4
4
  "description": "Codemods for migrating ecopages to latest patterns",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -46,6 +46,9 @@
46
46
  "default": "./src/transforms/migrate-to-eco-page.js"
47
47
  }
48
48
  },
49
+ "bin": {
50
+ "ecopages-codemod": "./src/cli.js"
51
+ },
49
52
  "publishConfig": {
50
53
  "access": "public"
51
54
  },
@@ -60,4 +63,4 @@
60
63
  "peerDependencies": {
61
64
  "typescript": "^5.0.0"
62
65
  }
63
- }
66
+ }
package/src/cli.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Transforms the CLI can run, each described for `--list`.
4
+ */
5
+ export declare const TRANSFORMS: {
6
+ readonly 'migrate-data-hooks': "staticProps and staticPaths of eco.page() to props and paths";
7
+ readonly 'migrate-to-eco-page': "module-level data exports and Page.config to eco.page()";
8
+ readonly 'migrate-to-eco-component': "Component.config assignments to eco.component()";
9
+ readonly 'migrate-core-entrypoints': "@ecopages/core imports to the role-based entry points";
10
+ };
11
+ /**
12
+ * Runs a transform through the bundled jscodeshift and returns its exit code.
13
+ *
14
+ * @remarks
15
+ * The transform file keeps this module's own extension, so the CLI works both from the published
16
+ * `.js` build and from the `.ts` sources.
17
+ */
18
+ export declare function run(argv: string[]): number;
package/src/cli.js ADDED
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from 'node:child_process';
3
+ import { createRequire } from 'node:module';
4
+ import { extname } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ /**
7
+ * Transforms the CLI can run, each described for `--list`.
8
+ */
9
+ export const TRANSFORMS = {
10
+ 'migrate-data-hooks': 'staticProps and staticPaths of eco.page() to props and paths',
11
+ 'migrate-to-eco-page': 'module-level data exports and Page.config to eco.page()',
12
+ 'migrate-to-eco-component': 'Component.config assignments to eco.component()',
13
+ 'migrate-core-entrypoints': '@ecopages/core imports to the role-based entry points',
14
+ };
15
+ const USAGE = `Usage: ecopages-codemod <transform> [paths...] [jscodeshift options]
16
+
17
+ Runs a transform over the given paths (default: src). Pass --dry --print to preview.
18
+
19
+ Transforms:
20
+ ${Object.entries(TRANSFORMS)
21
+ .map(([name, description]) => ` ${name.padEnd(28)}${description}`)
22
+ .join('\n')}
23
+ `;
24
+ /**
25
+ * Runs a transform through the bundled jscodeshift and returns its exit code.
26
+ *
27
+ * @remarks
28
+ * The transform file keeps this module's own extension, so the CLI works both from the published
29
+ * `.js` build and from the `.ts` sources.
30
+ */
31
+ export function run(argv) {
32
+ const [name, ...rest] = argv;
33
+ if (!name || name === '--help' || name === '-h') {
34
+ process.stdout.write(USAGE);
35
+ return name ? 0 : 1;
36
+ }
37
+ if (name === '--list') {
38
+ process.stdout.write(`${Object.keys(TRANSFORMS).join('\n')}\n`);
39
+ return 0;
40
+ }
41
+ if (!Object.hasOwn(TRANSFORMS, name)) {
42
+ process.stderr.write(`Unknown transform "${name}".\n\n${USAGE}`);
43
+ return 1;
44
+ }
45
+ const transform = fileURLToPath(new URL(`./transforms/${name}${extname(import.meta.url)}`, import.meta.url));
46
+ const jscodeshift = createRequire(import.meta.url).resolve('jscodeshift/bin/jscodeshift.js');
47
+ const hasFlag = (flag) => rest.some((arg) => arg === flag || arg.startsWith(`${flag}=`));
48
+ const hasPath = rest.some((arg) => !arg.startsWith('-'));
49
+ const args = [
50
+ jscodeshift,
51
+ '-t',
52
+ transform,
53
+ ...(hasFlag('--parser') ? [] : ['--parser', 'tsx']),
54
+ ...(hasFlag('--extensions') ? [] : ['--extensions=ts,tsx,js,jsx']),
55
+ ...rest,
56
+ ...(hasPath ? [] : ['src']),
57
+ ];
58
+ return spawnSync(process.execPath, args, { stdio: 'inherit' }).status ?? 1;
59
+ }
60
+ if (import.meta.main) {
61
+ process.exitCode = run(process.argv.slice(2));
62
+ }
@@ -9,5 +9,5 @@ export declare function printOptions(source: string): {
9
9
  readonly quote: "single";
10
10
  readonly tabWidth: 2;
11
11
  readonly useTabs: true;
12
- readonly lineTerminator: "\r\n" | "\n";
12
+ readonly lineTerminator: "\n" | "\r\n";
13
13
  };