@octanejs/codemod 0.1.4 → 0.2.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.
Files changed (58) hide show
  1. package/README.md +295 -4
  2. package/dist/bin.d.ts +2 -0
  3. package/dist/bin.js +162 -0
  4. package/dist/compiler.d.ts +11 -0
  5. package/dist/compiler.js +48 -0
  6. package/dist/effect-receivers.d.ts +11 -0
  7. package/dist/effect-receivers.js +315 -0
  8. package/dist/expression-wrappers.d.ts +6 -0
  9. package/dist/expression-wrappers.js +16 -0
  10. package/dist/forwarded-props.d.ts +27 -0
  11. package/dist/forwarded-props.js +489 -0
  12. package/dist/index.d.ts +6 -0
  13. package/{src → dist}/index.js +1 -0
  14. package/dist/linked-state.d.ts +17 -0
  15. package/dist/linked-state.js +126 -0
  16. package/dist/local-calls.d.ts +20 -0
  17. package/dist/local-calls.js +143 -0
  18. package/dist/local-react-hook.d.ts +15 -0
  19. package/dist/local-react-hook.js +353 -0
  20. package/dist/local-uses.d.ts +13 -0
  21. package/dist/local-uses.js +987 -0
  22. package/dist/mappings.d.ts +57 -0
  23. package/dist/mappings.js +343 -0
  24. package/dist/path-svg.d.ts +60 -0
  25. package/dist/path-svg.js +207 -0
  26. package/dist/project.d.ts +9 -0
  27. package/dist/project.js +1568 -0
  28. package/dist/react-intl.d.ts +4 -0
  29. package/dist/react-intl.js +389 -0
  30. package/dist/react-renderer.d.ts +9 -0
  31. package/dist/react-renderer.js +106 -0
  32. package/dist/scoped-signal.d.ts +4 -0
  33. package/dist/scoped-signal.js +480 -0
  34. package/dist/scoped-store-contract.d.ts +13 -0
  35. package/dist/scoped-store-contract.js +741 -0
  36. package/dist/store-hook-uses.d.ts +18 -0
  37. package/dist/store-hook-uses.js +403 -0
  38. package/dist/store-inputs.d.ts +16 -0
  39. package/dist/store-inputs.js +391 -0
  40. package/dist/strong.d.ts +24 -0
  41. package/dist/strong.js +142 -0
  42. package/dist/transform.d.ts +27 -0
  43. package/dist/transform.js +4890 -0
  44. package/dist/types.d.ts +203 -0
  45. package/dist/types.js +1 -0
  46. package/package.json +18 -6
  47. package/src/path-svg.ts +218 -0
  48. package/templates/octane-path-svg.ts +56 -0
  49. package/templates/octane-store-context.tsrx +49 -0
  50. package/templates/octane-store-hooks.ts +61 -0
  51. package/templates/react-intl.tsrx +116 -0
  52. package/src/bin.js +0 -151
  53. package/src/compiler.js +0 -61
  54. package/src/index.d.ts +0 -95
  55. package/src/mappings.js +0 -429
  56. package/src/project.js +0 -738
  57. package/src/strong.js +0 -149
  58. package/src/transform.js +0 -3455
@@ -0,0 +1,116 @@
1
+ 'use strong';
2
+
3
+ import { createContext, useContext, useMemo, type OctaneNode } from 'octane';
4
+ import { ReactCompat } from 'octane/react';
5
+ import type { ChildrenBlock } from 'octane/tsrx-boundary';
6
+ import {
7
+ createElement as reactElement,
8
+ Fragment,
9
+ type ComponentProps,
10
+ type ReactNode,
11
+ } from 'react';
12
+ import {
13
+ createIntl,
14
+ createIntlCache,
15
+ FormattedMessage as ReactMessage,
16
+ IntlContext,
17
+ type IntlConfig,
18
+ type IntlShape,
19
+ type MessageDescriptor,
20
+ } from 'react-intl';
21
+
22
+ type Children = { children?: OctaneNode | ChildrenBlock };
23
+ const absent = Symbol('no native Intl provider');
24
+ const Locale = createContext<IntlShape | null | undefined | typeof absent>(absent);
25
+ export const intlContexts = [{ source: Locale, target: IntlContext }];
26
+
27
+ export function useIntl(): IntlShape {
28
+ const native = useContext(Locale);
29
+ const intl = native === absent ? useContext(IntlContext) : native;
30
+ if (!intl) {
31
+ throw new Error(
32
+ '[React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.',
33
+ );
34
+ }
35
+ return intl;
36
+ }
37
+
38
+ export function RawIntlProvider({
39
+ value,
40
+ children,
41
+ }: Children & { value: IntlShape | null | undefined }) @{
42
+ <Locale value={value}>{children}</Locale>
43
+ }
44
+
45
+ export function IntlBoundary({ children }: Children) @{
46
+ const value = useIntl();
47
+ <Locale value={value}>{children}</Locale>
48
+ }
49
+
50
+ export function IntlProvider({
51
+ children,
52
+ locale,
53
+ messages,
54
+ timeZone,
55
+ formats,
56
+ defaultLocale,
57
+ defaultFormats,
58
+ fallbackOnEmptyString,
59
+ onError,
60
+ onWarn,
61
+ textComponent,
62
+ wrapRichTextChunksInFragment,
63
+ defaultRichTextElements,
64
+ }: Children & IntlConfig) @{
65
+ const cache = useMemo(() => createIntlCache());
66
+ const intl = useMemo(() => {
67
+ const options = {
68
+ messages,
69
+ timeZone,
70
+ formats,
71
+ defaultLocale,
72
+ defaultFormats,
73
+ fallbackOnEmptyString,
74
+ onError,
75
+ onWarn,
76
+ textComponent,
77
+ wrapRichTextChunksInFragment,
78
+ defaultRichTextElements,
79
+ };
80
+ // Omitting undefined options lets React Intl apply its own defaults.
81
+ const provided = Object.fromEntries(
82
+ Object.entries(options).filter(([, value]) => value !== undefined),
83
+ );
84
+ return createIntl({ locale, ...provided }, cache);
85
+ });
86
+ <Locale value={intl}>{children}</Locale>
87
+ }
88
+
89
+ type MessageProps = MessageDescriptor &
90
+ Pick<ComponentProps<typeof ReactMessage>, 'values' | 'ignoreTag'>;
91
+
92
+ function ReactContent({ content }: { content: ReactNode }) {
93
+ return content;
94
+ }
95
+
96
+ export function FormattedMessage({
97
+ id,
98
+ defaultMessage,
99
+ description,
100
+ values,
101
+ ignoreTag,
102
+ }: MessageProps) @{
103
+ const intl = useIntl();
104
+ const descriptor = { id, defaultMessage, description };
105
+ const { textComponent, formatMessage } = intl;
106
+ // React owns custom wrappers and rich messages. Give it the real formatter.
107
+ const requiresReact =
108
+ (textComponent && textComponent !== Fragment) || intl.defaultRichTextElements;
109
+ const content = requiresReact
110
+ ? reactElement(ReactMessage, { ...descriptor, values, ignoreTag })
111
+ : formatMessage(descriptor, values, { ignoreTag });
112
+ if (typeof content === 'string') return content;
113
+ <Locale value={intl}>
114
+ <ReactCompat component={ReactContent} props={{ content }} contexts={intlContexts} />
115
+ </Locale>
116
+ }
package/src/bin.js DELETED
@@ -1,151 +0,0 @@
1
- #!/usr/bin/env node
2
- import path from 'node:path';
3
- import { parseArgs } from 'node:util';
4
- import colors from 'picocolors';
5
- import { runCodemod } from './project.js';
6
-
7
- const HELP = `octane-codemod — migrate React + TSX/JSX to Octane + TSRX
8
-
9
- Usage: octane-codemod [paths...] [options]
10
-
11
- paths files or directories to migrate (default: .)
12
-
13
- Options:
14
- --strong make each migrated module Strong where the compiler
15
- accepts it; the rest stay in compatibility mode
16
- --force-strong keep "use strong" even where Strong errors remain
17
- --target <tsrx|tsx> tsrx (default) rewrites components as templates;
18
- tsx keeps JSX and only ports the React APIs
19
- --dry-run report without writing
20
- --print print each migrated module (implies --dry-run)
21
- --no-verify skip compiling the result
22
- --json print the result as JSON
23
- -h, --help show this help
24
- `;
25
-
26
- const { values, positionals } = parseArgs({
27
- allowPositionals: true,
28
- allowNegative: true,
29
- options: {
30
- strong: { type: 'boolean', default: false },
31
- 'force-strong': { type: 'boolean', default: false },
32
- target: { type: 'string', default: 'tsrx' },
33
- 'dry-run': { type: 'boolean', default: false },
34
- print: { type: 'boolean', default: false },
35
- verify: { type: 'boolean', default: true },
36
- json: { type: 'boolean', default: false },
37
- help: { type: 'boolean', short: 'h', default: false },
38
- },
39
- });
40
-
41
- if (values.help) {
42
- process.stdout.write(HELP);
43
- process.exit(0);
44
- }
45
- if (values.target !== 'tsrx' && values.target !== 'tsx') {
46
- process.stderr.write(`--target must be tsrx or tsx, got "${values.target}".\n`);
47
- process.exit(2);
48
- }
49
-
50
- const dryRun = values['dry-run'] || values.print;
51
- const result = await runCodemod(positionals.length > 0 ? positionals : ['.'], {
52
- target: /** @type {'tsrx' | 'tsx'} */ (values.target),
53
- strong: values.strong || values['force-strong'],
54
- forceStrong: values['force-strong'],
55
- verify: values.verify,
56
- write: !dryRun,
57
- });
58
-
59
- // The codemod's own notes, at the original file's lines, and the compiler's
60
- // diagnostics, at the written file's, as one list.
61
- const findings = result.files.flatMap((file) => [
62
- ...file.notes
63
- .filter((note) => note.severity !== 'info')
64
- .map((note) => ({ file: file.file, ...note, code: note.rule })),
65
- ...file.diagnostics.map((diagnostic) => ({ file: file.output, ...diagnostic })),
66
- ]);
67
- const errors = findings.filter((finding) => finding.severity === 'error');
68
-
69
- if (values.json) {
70
- const files = result.files.map(({ code, ...file }) => (values.print ? { ...file, code } : file));
71
- process.stdout.write(JSON.stringify({ ...result, files }, null, 2) + '\n');
72
- process.exit(errors.length > 0 ? 1 : 0);
73
- }
74
-
75
- const changed = result.files.filter((file) => file.changed);
76
- for (const file of changed) {
77
- const arrow = file.output === file.file ? '' : ` → ${file.output}`;
78
- const rules = Object.entries(file.rules)
79
- .map(([rule, count]) => (count > 1 ? `${rule}×${count}` : rule))
80
- .join(', ');
81
- const mode =
82
- file.strong === null ? '' : file.strong ? colors.green(' strong') : colors.yellow(' compat');
83
- const mark = errors.some((error) => error.file === file.output)
84
- ? colors.red('✗')
85
- : colors.green('✓');
86
- process.stdout.write(`${mark} ${file.file}${arrow}${mode} ${colors.dim(rules)}\n`);
87
- if (values.print) process.stdout.write(colors.dim('─'.repeat(60)) + '\n' + file.code + '\n');
88
- }
89
-
90
- if (findings.length > 0) {
91
- process.stdout.write(`\n${colors.bold('Needs attention')}\n`);
92
- for (const finding of findings) {
93
- const tag = finding.severity === 'error' ? colors.red : colors.yellow;
94
- const message = finding.message.split('\n')[0];
95
- process.stdout.write(
96
- ` ${finding.file}:${finding.line} ${tag(finding.severity)} ${colors.dim(finding.code)} ${message}\n`,
97
- );
98
- }
99
- }
100
- if (result.packages.length > 0) {
101
- process.stdout.write(`\n${colors.bold('Dependencies')}\n`);
102
- const ranges = new Map(result.dependencies.map(({ name, range }) => [name, range]));
103
- for (const { from, to } of result.packages) {
104
- const range = ranges.get(to);
105
- process.stdout.write(` ${from} → ${to}${range ? colors.dim(` ${range}`) : ''}\n`);
106
- }
107
- if (ranges.size > 0) {
108
- process.stdout.write(
109
- colors.dim(` ${dryRun ? 'Would add' : 'Added'} ${ranges.size} to package.json\n`),
110
- );
111
- }
112
- for (const { name, patch } of result.patched) {
113
- process.stdout.write(
114
- ` ${colors.yellow('warning')} ${name} is patched by ${patch}, which does not apply to its binding: port the patch there.\n`,
115
- );
116
- }
117
- }
118
- if (result.missing.length > 0) {
119
- process.stdout.write(
120
- `\n${colors.bold('No Octane port')} ${colors.dim('(still runs on React)')}\n`,
121
- );
122
- for (const { name, modules, islands, blocked } of result.missing) {
123
- const uses = [
124
- `${modules} module(s)`,
125
- islands > 0 ? `${islands} element(s) in ReactCompat islands` : null,
126
- blocked > 0 ? colors.red(`${blocked} use(s) need a port`) : null,
127
- ].filter(Boolean);
128
- process.stdout.write(` ${name} ${colors.dim(uses.join(', '))}\n`);
129
- }
130
- }
131
- for (const page of result.html) process.stdout.write(`\nUpdated the entry script in ${page}\n`);
132
-
133
- const strong = changed.filter((file) => file.strong !== null);
134
- const summary = [
135
- `${changed.length} module(s) migrated`,
136
- `${changed.filter((file) => file.output !== file.file).length} renamed to .tsrx`,
137
- strong.length > 0
138
- ? `${strong.filter((file) => file.strong).length}/${strong.length} Strong`
139
- : null,
140
- `${errors.length} error(s)`,
141
- ].filter(Boolean);
142
- process.stdout.write(`\n${summary.join(', ')}${dryRun ? colors.dim(' (dry run)') : ''}\n`);
143
- if (changed.length > 0 && !dryRun) {
144
- // A project outside this directory is named in full, not by `../` steps.
145
- const relative = path.relative(process.cwd(), result.root);
146
- const root = relative.startsWith('..') ? result.root : relative || '.';
147
- process.stdout.write(
148
- colors.dim(`Next: run \`npx @octanejs/cli init\` in ${root} to wire Octane into the build.\n`),
149
- );
150
- }
151
- process.exit(errors.length > 0 ? 1 : 0);
package/src/compiler.js DELETED
@@ -1,61 +0,0 @@
1
- import { createRequire } from 'node:module';
2
- import path from 'node:path';
3
- import { pathToFileURL } from 'node:url';
4
-
5
- /**
6
- * @typedef {{ code: string, severity: string, message: string, line: number }} Finding
7
- *
8
- * @typedef {Object} Compiler
9
- * @property {(source: string, filename: string, options?: object) => { diagnostics: any[], error: unknown }} collectDiagnostics
10
- * @property {string} from where the compiler was loaded
11
- */
12
-
13
- /**
14
- * The Octane compiler that judges the migrated code: the project's own when it
15
- * has one, so the result matches what its build will do, else the copy this
16
- * package ships with, since a React project has no Octane installed yet.
17
- *
18
- * @param {string} root
19
- * @returns {Promise<Compiler>}
20
- */
21
- export async function loadCompiler(root) {
22
- for (const base of [path.join(root, 'noop.js'), import.meta.url]) {
23
- let entry;
24
- try {
25
- entry = createRequire(base).resolve('octane/compiler');
26
- } catch {
27
- continue;
28
- }
29
- const module = await import(pathToFileURL(entry).href);
30
- if (typeof module.collectDiagnostics === 'function') {
31
- return { collectDiagnostics: module.collectDiagnostics, from: entry };
32
- }
33
- }
34
- throw new Error('Could not load `octane/compiler`.');
35
- }
36
-
37
- /**
38
- * @param {any} diagnostic a compiler diagnostic
39
- * @returns {Finding}
40
- */
41
- export function finding(diagnostic) {
42
- return {
43
- code: diagnostic.code,
44
- severity: diagnostic.severity,
45
- message: String(diagnostic.message).replace(`[${diagnostic.code}] `, ''),
46
- line: diagnostic.start?.line ?? 1,
47
- };
48
- }
49
-
50
- /**
51
- * @param {any} error what the compiler threw for a module it could not parse
52
- * @returns {Finding}
53
- */
54
- export function thrown(error) {
55
- return {
56
- code: 'COMPILE_ERROR',
57
- severity: 'error',
58
- message: String(error?.message ?? error),
59
- line: error?.loc?.line ?? 1,
60
- };
61
- }
package/src/index.d.ts DELETED
@@ -1,95 +0,0 @@
1
- import type ts from 'typescript';
2
-
3
- interface Note {
4
- rule: string;
5
- severity: 'info' | 'warning' | 'error';
6
- line: number;
7
- message: string;
8
- }
9
- interface TransformOptions {
10
- target?: 'tsx' | 'tsrx';
11
- strong?: boolean;
12
- strictNullChecks?: boolean;
13
- types?: { sourceFile: ts.SourceFile; checker: ts.TypeChecker };
14
- resolveSpecifier?(specifier: string): string | null;
15
- isContext?(specifier: string, name: string): boolean | null;
16
- unported?(specifier: string): string | null;
17
- reactCompat?: boolean;
18
- }
19
- /** A React package with no Octane port, and how migrated code uses it. */
20
- interface Unported {
21
- name: string;
22
- /** Elements now rendered in a `ReactCompat` island. */
23
- islands: number;
24
- /** Uses that only a port can support. */
25
- blocked: number;
26
- }
27
- interface TransformResult {
28
- code: string;
29
- changed: boolean;
30
- template: boolean;
31
- notes: Note[];
32
- rules: Record<string, number>;
33
- exports: {
34
- contexts: string[];
35
- reexports: { specifier: string; names: [string, string][] | null }[];
36
- };
37
- unported: Unported[];
38
- }
39
- interface CodemodOptions {
40
- target?: 'tsrx' | 'tsx';
41
- strong?: boolean;
42
- forceStrong?: boolean;
43
- verify?: boolean;
44
- write?: boolean;
45
- root?: string;
46
- }
47
- interface Finding {
48
- code: string;
49
- severity: string;
50
- message: string;
51
- line: number;
52
- }
53
- interface Compiler {
54
- from: string;
55
- collectDiagnostics: typeof import('octane/compiler').collectDiagnostics;
56
- }
57
- interface FileResult {
58
- file: string;
59
- output: string;
60
- changed: boolean;
61
- rules: Record<string, number>;
62
- notes: Note[];
63
- strong: boolean | null;
64
- strongFixes: string[];
65
- diagnostics: Finding[];
66
- code: string;
67
- }
68
- interface CodemodResult {
69
- root: string;
70
- files: FileResult[];
71
- packages: { from: string; to: string }[];
72
- /** Bindings added to package.json, which the project did not declare. */
73
- dependencies: { name: string; range: string }[];
74
- /** Patches of replaced React packages, which do not reach their bindings. */
75
- patched: { name: string; patch: string }[];
76
- missing: (Unported & { modules: number })[];
77
- html: string[];
78
- compiler: string | null;
79
- }
80
- export declare function runCodemod(
81
- paths: string[],
82
- options?: CodemodOptions,
83
- ): Promise<CodemodResult>;
84
- export declare function transformModule(
85
- source: string,
86
- filename: string,
87
- options?: TransformOptions,
88
- ): TransformResult;
89
- export declare function strengthen(
90
- compiler: Compiler,
91
- code: string,
92
- filename: string,
93
- options?: { force?: boolean },
94
- ): { code: string; strong: boolean; fixed: string[]; blockers: Finding[] };
95
- export declare function loadCompiler(root: string): Promise<Compiler>;