@octanejs/codemod 0.0.0 → 0.1.1

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
@@ -21,9 +21,12 @@ dependencies over to Octane.
21
21
 
22
22
  | Rule | React | Octane |
23
23
  | --- | --- | --- |
24
- | `imports` | `react`, `react-dom`, `react-dom/client` | `octane`, merged into one import |
25
- | `imports` | `React.useState`, `React.FC` | named imports |
24
+ | `imports` | `react`, `react-dom`, `react-dom/client`, `use-sync-external-store/shim` | `octane`, merged into one import |
25
+ | `imports` | `React.useState`, `React.FC`, and `React.ReactNode` with no import (the global namespace React's types declare) | named imports |
26
+ | `imports` | `declare module 'react' { namespace JSX { … } }` (custom elements) | `declare module 'octane/jsx-runtime'` |
26
27
  | `imports` | React libraries with a binding (`@tanstack/react-query`, ...) | `@octanejs/*` |
28
+ | `imports` | `@radix-ui/react-<primitive>` (`import * as DialogPrimitive from '@radix-ui/react-dialog'`) | that primitive's namespace of `@octanejs/radix` (`import { Dialog as DialogPrimitive } from '@octanejs/radix'`) |
29
+ | `imports` | `@tanstack/react-table`, `@tanstack/react-hotkeys`, `@tanstack/react-pacer` | TanStack's own `@tanstack/octane-*` adapters, with `Octane` for `React` in type names |
27
30
  | `template-component` | `function C() { …; return <div /> }` | `function C() @{ …; <div /> }` |
28
31
  | `template-if` | `{a ? <A /> : <B />}`, `{a > 0 && <A />}` (also through a `const`) | `@if (a) { <A /> } @else { <B /> }` |
29
32
  | `template-if` | `if (a) return <A />; …; return <B />` in a component | `@if (a) { <A /> } @else { …; <B /> }` |
@@ -32,15 +35,18 @@ dependencies over to Octane.
32
35
  | `template-text` | `{title}` with `title: string`, `{count}` with `count: number` | `{title as string}`, `{String(count)}`: text bindings, not renderable holes |
33
36
  | `hook-dependencies` | `useEffect(fn)` (runs every render) | `useEffect(fn, null)`: an omitted list is inferred in Octane |
34
37
  | `forward-ref` | `forwardRef((props, ref) => …)` | `({ ref, ...props }) => …` |
38
+ | `descriptor-children` | a component that clones or inspects `children` (`render={children}`, `cloneElement`, `Children.only`) | `descriptorChildren(…)`, so callers pass elements as React does |
35
39
  | `context-provider` | `<Ctx.Provider value>` | `<Ctx value>` |
36
40
  | `context-consumer` | `<Ctx.Consumer>{(v) => …}</Ctx.Consumer>` | `@{ const v = useContext(Ctx); … }` |
37
41
  | `native-text-change` | `onChange` on a text `<input>` / `<textarea>` | `onInput` (native `change` fires on blur) |
38
- | `event-object` | `e.nativeEvent`, `e.persist()`, `e.target` on a control | `e`, removed, `e.currentTarget` |
42
+ | `native-text-change` | `function Input({ ...props }) { return <input {...props} /> }` | `function Input({ onChange, ...props }) @{ <input onInput={onChange} {...props} /> }` |
43
+ | `event-object` | `e.nativeEvent`, `e.persist()`, `e.target` on a control, also through a component typed for one | `e`, removed, `e.currentTarget` |
39
44
  | `class-attribute` | `className` on an HTML element | `class` |
40
45
  | `legacy-root` | `ReactDOM.render(el, c)` | `createRoot(c).render(el)` |
41
46
  | `root-render` | `root.render(<App a={1} />)`, `hydrateRoot(c, createElement(App, p))` | `root.render(App, { a: 1 })`, `hydrateRoot(c, App, p)`: no generic element renderer |
42
47
  | `server-render` | `renderToString(<App />)` | `renderToString(App).html`: Octane returns `{ html, css }` |
43
48
  | `strict-mode` | `<StrictMode>…</StrictMode>` | its children (Octane's is a pass-through) |
49
+ | `react-compat` | `<Toaster position="top-right" />` from a React package with no Octane port | `<ReactCompat><Toaster position="top-right" /></ReactCompat>`, rendered by React |
44
50
 
45
51
  Every rewrite keeps React's behavior. Where it cannot be proven equal, the code
46
52
  is left alone: `{count && <X />}` stays a hole, because React renders `0` there
@@ -72,9 +78,19 @@ anyway.
72
78
 
73
79
  ## What it reports
74
80
 
75
- Class components, `createRef`, `defaultProps`, unported React libraries, and
76
- anything else without an automatic rewrite are listed under **Needs attention**
77
- with a file and line. The process exits with status 1 when any error remains.
81
+ Class components, `createRef`, `defaultProps`, and anything else without an
82
+ automatic rewrite are listed under **Needs attention** with a file and line.
83
+ The process exits with status 1 when any error remains.
84
+
85
+ A React package with no Octane binding still runs on React, so React stays a
86
+ dependency, and a comment above each import of it says so. When the project
87
+ has React and React DOM 19.2 or newer in the React 19 series, a component of that package renders in
88
+ its own React root through `ReactCompat` if its element gives React nothing
89
+ Octane renders: text children and props without elements. The package's hooks
90
+ and contexts, and its components that take Octane children or render
91
+ callbacks, are reported where they are used. **No Octane port** lists each such
92
+ package with the modules that import it, the elements hosted in islands, and
93
+ the uses that need a port.
78
94
 
79
95
  ## Options
80
96
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@octanejs/codemod",
3
- "version": "0.0.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=22.22.2"
@@ -39,8 +39,8 @@
39
39
  "./package.json": "./package.json"
40
40
  },
41
41
  "dependencies": {
42
- "@octanejs/cli": "0.2.4",
43
- "octane": "0.16.3",
42
+ "@octanejs/cli": "0.3.1",
43
+ "octane": "0.16.5",
44
44
  "picocolors": "^1.1.1",
45
45
  "typescript": "^5.9.3"
46
46
  },
package/src/bin.js CHANGED
@@ -101,6 +101,19 @@ if (result.packages.length > 0) {
101
101
  process.stdout.write(`\n${colors.bold('Dependencies')}\n`);
102
102
  for (const { from, to } of result.packages) process.stdout.write(` ${from} → ${to}\n`);
103
103
  }
104
+ if (result.missing.length > 0) {
105
+ process.stdout.write(
106
+ `\n${colors.bold('No Octane port')} ${colors.dim('(still runs on React)')}\n`,
107
+ );
108
+ for (const { name, modules, islands, blocked } of result.missing) {
109
+ const uses = [
110
+ `${modules} module(s)`,
111
+ islands > 0 ? `${islands} element(s) in ReactCompat islands` : null,
112
+ blocked > 0 ? colors.red(`${blocked} use(s) need a port`) : null,
113
+ ].filter(Boolean);
114
+ process.stdout.write(` ${name} ${colors.dim(uses.join(', '))}\n`);
115
+ }
116
+ }
104
117
  for (const page of result.html) process.stdout.write(`\nUpdated the entry script in ${page}\n`);
105
118
 
106
119
  const strong = changed.filter((file) => file.strong !== null);
package/src/index.d.ts CHANGED
@@ -13,6 +13,16 @@ interface TransformOptions {
13
13
  types?: { sourceFile: ts.SourceFile; checker: ts.TypeChecker };
14
14
  resolveSpecifier?(specifier: string): string | null;
15
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;
16
26
  }
17
27
  interface TransformResult {
18
28
  code: string;
@@ -24,6 +34,7 @@ interface TransformResult {
24
34
  contexts: string[];
25
35
  reexports: { specifier: string; names: [string, string][] | null }[];
26
36
  };
37
+ unported: Unported[];
27
38
  }
28
39
  interface CodemodOptions {
29
40
  target?: 'tsrx' | 'tsx';
@@ -58,7 +69,7 @@ interface CodemodResult {
58
69
  root: string;
59
70
  files: FileResult[];
60
71
  packages: { from: string; to: string }[];
61
- missing: string[];
72
+ missing: (Unported & { modules: number })[];
62
73
  html: string[];
63
74
  compiler: string | null;
64
75
  }
package/src/mappings.js CHANGED
@@ -146,16 +146,197 @@ export const REACT_MODULES = {
146
146
  'react-dom/test-utils': 'octane',
147
147
  'react/jsx-runtime': 'octane/jsx-runtime',
148
148
  'react/jsx-dev-runtime': 'octane/jsx-dev-runtime',
149
+ // React's `useSyncExternalStore` for React 17 and earlier.
150
+ 'use-sync-external-store': 'octane',
151
+ 'use-sync-external-store/shim': 'octane',
149
152
  };
150
153
 
151
154
  /**
152
- * React framework packages an Octane framework integration serves. They are
153
- * not bindings, so the shared binding catalog leaves them out.
155
+ * What `@octanejs/radix` exports in each namespace. A namespace ports the
156
+ * `@radix-ui/react-*` package it names, as `Dialog` ports
157
+ * `@radix-ui/react-dialog`, except `Slot`, whose exports are the binding's own.
158
+ * A codemod test checks it against the binding and the Radix packages.
159
+ *
160
+ * @type {Record<string, Set<string>>}
161
+ */
162
+ const RADIX = Object.fromEntries(
163
+ Object.entries({
164
+ AccessibleIcon: 'AccessibleIcon Root',
165
+ Accordion: 'Accordion Content Header Item Root Trigger createAccordionScope',
166
+ AlertDialog:
167
+ 'Action AlertDialog Cancel Content Description Overlay Portal Root Title Trigger createAlertDialogScope',
168
+ Arrow: 'Arrow Root',
169
+ AspectRatio: 'AspectRatio Root',
170
+ Avatar: 'Avatar AvatarFallback AvatarImage Fallback Image Root createAvatarScope',
171
+ Checkbox:
172
+ 'BubbleInput Checkbox CheckboxBubbleInput CheckboxIndicator CheckboxProvider CheckboxTrigger CheckedState Indicator Provider Root Trigger createCheckboxScope',
173
+ Collapsible:
174
+ 'Collapsible Content Root Trigger createCollapsibleContext createCollapsibleScope useCollapsibleContext',
175
+ ContextMenu:
176
+ 'Arrow CheckboxItem Content ContextMenu ContextMenuContent ContextMenuItem ContextMenuTrigger Group Item ItemIndicator Label Portal RadioGroup RadioItem Root Separator Sub SubContent SubTrigger Trigger createContextMenuScope',
177
+ Dialog:
178
+ 'Close Content Description Dialog Overlay Portal Root Title Trigger createDialogContext createDialogScope',
179
+ Direction: 'DirectionProvider Provider useDirection',
180
+ DropdownMenu:
181
+ 'Arrow CheckboxItem Content DropdownMenu DropdownMenuContent DropdownMenuItem DropdownMenuTrigger Group Item ItemIndicator Label Portal RadioGroup RadioItem Root Separator Sub SubContent SubTrigger Trigger createDropdownMenuScope',
182
+ Form: 'Control Field Form FormControl FormField FormLabel FormMessage FormSubmit FormValidityState Label Message Root Submit ValidityState createFormScope',
183
+ HoverCard:
184
+ 'Arrow Content HoverCard HoverCardContent HoverCardTrigger Portal Root Trigger createHoverCardScope',
185
+ Label: 'Label Root',
186
+ Menu: 'Anchor Arrow CheckboxItem Content Group Item ItemIndicator Label Menu MenuAnchor MenuContent MenuItem Portal RadioGroup RadioItem Root Separator Sub SubContent SubTrigger createMenuScope',
187
+ Menubar:
188
+ 'Arrow CheckboxItem Content Group Item ItemIndicator Label Menu Menubar MenubarArrow MenubarCheckboxItem MenubarContent MenubarGroup MenubarItem MenubarItemIndicator MenubarLabel MenubarMenu MenubarPortal MenubarRadioGroup MenubarRadioItem MenubarSeparator MenubarSub MenubarSubContent MenubarSubTrigger MenubarTrigger Portal RadioGroup RadioItem Root Separator Sub SubContent SubTrigger Trigger createMenubarScope',
189
+ NavigationMenu:
190
+ 'Content Indicator Item Link List NavigationMenu NavigationMenuContent NavigationMenuIndicator NavigationMenuItem NavigationMenuLink NavigationMenuList NavigationMenuSub NavigationMenuTrigger NavigationMenuViewport Root Sub Trigger Viewport createNavigationMenuScope',
191
+ OneTimePasswordField:
192
+ 'HiddenInput Input InputValidationType OneTimePasswordField OneTimePasswordFieldHiddenInput OneTimePasswordFieldInput Root createOneTimePasswordFieldScope',
193
+ PasswordToggleField:
194
+ 'Icon Input PasswordToggleField PasswordToggleFieldIcon PasswordToggleFieldInput PasswordToggleFieldSlot PasswordToggleFieldToggle Root Slot Toggle createPasswordToggleFieldScope',
195
+ Popover:
196
+ 'Anchor Arrow Close Content Popover PopoverAnchor PopoverTrigger Portal Root Trigger createPopoverScope',
197
+ Popper:
198
+ 'ALIGN_OPTIONS Anchor Arrow Content Popper PopperAnchor PopperArrow PopperContent Root SIDE_OPTIONS createPopperScope',
199
+ Portal: 'Portal Root',
200
+ Progress: 'Indicator Progress ProgressIndicator Root createProgressScope',
201
+ RadioGroup:
202
+ 'Indicator Item RadioGroup RadioGroupIndicator RadioGroupItem RadioGroupItemBubbleInput RadioGroupItemProvider RadioGroupItemTrigger Root createRadioGroupScope',
203
+ RovingFocus:
204
+ 'Item Root RovingFocusGroup RovingFocusGroupItem createRovingFocusGroupContext createRovingFocusGroupScope',
205
+ ScrollArea:
206
+ 'Corner Root ScrollArea ScrollAreaCorner ScrollAreaScrollbar ScrollAreaThumb ScrollAreaViewport Scrollbar Thumb Viewport createScrollAreaScope',
207
+ Select:
208
+ 'Arrow BubbleInput Content Group Icon Item ItemIndicator ItemText Label Portal Provider Root ScrollDownButton ScrollUpButton Select SelectArrow SelectBubbleInput SelectContent SelectGroup SelectIcon SelectItem SelectItemIndicator SelectItemText SelectLabel SelectPortal SelectProvider SelectScrollDownButton SelectScrollUpButton SelectSeparator SelectTrigger SelectValue SelectViewport Separator Trigger Value Viewport createSelectScope',
209
+ Separator: 'Root Separator',
210
+ Slider:
211
+ 'BubbleInput Range Root Slider SliderBubbleInput SliderRange SliderThumb SliderThumbProvider SliderThumbTrigger SliderTrack Thumb Track createSliderScope',
212
+ Slot: 'Slot Slottable',
213
+ Switch:
214
+ 'BubbleInput Provider Root Switch SwitchBubbleInput SwitchProvider SwitchThumb SwitchTrigger Thumb Trigger createSwitchScope',
215
+ Tabs: 'Content List Root Tabs Trigger createTabsScope',
216
+ Toast:
217
+ 'Action Close Description Provider Root Title Toast ToastAction ToastClose ToastDescription ToastProvider ToastTitle ToastViewport Viewport createToastScope',
218
+ Toggle: 'Root Toggle',
219
+ ToggleGroup: 'Item Root ToggleGroup ToggleGroupItem createToggleGroupScope',
220
+ Toolbar:
221
+ 'Button Link Root Separator ToggleGroup ToggleItem Toolbar ToolbarButton ToolbarLink createToolbarScope',
222
+ Tooltip:
223
+ 'Arrow Content Portal Provider Root Tooltip TooltipProvider Trigger createTooltipScope',
224
+ VisuallyHidden: 'Root VISUALLY_HIDDEN_STYLES VisuallyHidden',
225
+ }).map(([namespace, names]) => [namespace, new Set(names.split(' '))]),
226
+ );
227
+
228
+ /** The types among them, which a named import reads as an alias, not a value. */
229
+ export const RADIX_TYPES = new Set(['CheckedState', 'InputValidationType']);
230
+
231
+ /** Each Radix package the binding ports, and its namespace. */
232
+ const RADIX_PACKAGES = new Map(
233
+ Object.keys(RADIX).map((namespace) => [
234
+ `@radix-ui/react-${namespace.replace(/[A-Z]/g, (c, i) => (i ? '-' : '') + c.toLowerCase())}`,
235
+ namespace,
236
+ ]),
237
+ );
238
+
239
+ /**
240
+ * The adapters TanStack publishes for Octane, by the React adapter each
241
+ * replaces, with the exports each lacks and what to do instead.
242
+ *
243
+ * @type {Record<string, Record<string, string>>}
154
244
  */
155
- export const FRAMEWORK_PACKAGES = /** @type {Record<string, string>} */ ({
245
+ const TANSTACK_ADAPTERS = {
246
+ '@tanstack/react-hotkeys': {},
247
+ '@tanstack/react-pacer': {
248
+ usePacerContext:
249
+ "`@tanstack/octane-pacer` has no `usePacerContext`; read the provider's options with `useDefaultPacerOptions()`.",
250
+ },
251
+ '@tanstack/react-table': Object.fromEntries(
252
+ (
253
+ 'getCoreRowModel getExpandedRowModel getFacetedMinMaxValues getFacetedRowModel ' +
254
+ 'getFacetedUniqueValues getFilteredRowModel getGroupedRowModel getPaginationRowModel ' +
255
+ 'getSortedRowModel legacyCreateColumnHelper sortingFns useLegacyTable useReactTable'
256
+ )
257
+ .split(' ')
258
+ .map((name) => [
259
+ name,
260
+ `\`${name}\` is TanStack Table v8's API, which \`@tanstack/octane-table\` does not adapt: move to v9's \`useTable\`, with \`_features\` and \`_rowModels\`, first.`,
261
+ ]),
262
+ ),
263
+ };
264
+
265
+ /**
266
+ * React packages ported outside the binding catalog: a framework integration,
267
+ * TanStack's own adapters, and Radix's primitive packages, which
268
+ * `@octanejs/radix` serves as namespaces.
269
+ */
270
+ export const PORTED_PACKAGES = /** @type {Record<string, string>} */ ({
156
271
  '@tanstack/react-start': '@octanejs/tanstack-start',
272
+ ...Object.fromEntries(
273
+ Object.keys(TANSTACK_ADAPTERS).map((name) => [name, name.replace('/react-', '/octane-')]),
274
+ ),
275
+ ...Object.fromEntries([...RADIX_PACKAGES.keys()].map((name) => [name, '@octanejs/radix'])),
157
276
  });
158
277
 
278
+ /**
279
+ * The `@octanejs/radix` namespace a Radix package's imports become, or null.
280
+ * `@radix-ui/react-slot` has none: its exports are the binding's own.
281
+ *
282
+ * @param {string} module
283
+ */
284
+ export function radixNamespace(module) {
285
+ const namespace = RADIX_PACKAGES.get(module) ?? null;
286
+ return namespace === 'Slot' ? null : namespace;
287
+ }
288
+
289
+ /**
290
+ * The name an export of a ported package has in its port, or null when the
291
+ * port has none. Other packages keep every name.
292
+ *
293
+ * @param {string} module
294
+ * @param {string} name
295
+ * @returns {string | null}
296
+ */
297
+ export function mapPackageExport(module, name) {
298
+ const namespace = RADIX_PACKAGES.get(module);
299
+ if (namespace !== undefined) {
300
+ const names = RADIX[namespace];
301
+ if (names.has(name)) return name;
302
+ // Radix exports each part twice, as `Content` and `DialogContent`, with
303
+ // `Root` as `Dialog`, and a part still in preview as `unstable_Content`.
304
+ const prefix = new RegExp(`^(?:unstable_)?(?:${namespace}(?![a-z]))?`);
305
+ const part = (/** @type {string} */ name) => name.replace(prefix, '') || 'Root';
306
+ const wanted = part(name);
307
+ if (names.has(wanted)) return wanted;
308
+ return [...names].find((candidate) => part(candidate) === wanted) ?? null;
309
+ }
310
+ const adapter = adapterOf(module);
311
+ if (adapter === undefined) return name;
312
+ if (Object.hasOwn(adapter, name)) return null;
313
+ // The adapters name their framework in their types: `ReactTable` is `OctaneTable`.
314
+ return name.replace(/React(?=[A-Z])/, 'Octane');
315
+ }
316
+
317
+ /**
318
+ * Why the port of a ported package has no `name`.
319
+ *
320
+ * @param {string} module
321
+ * @param {string} name
322
+ */
323
+ export function missingExport(module, name) {
324
+ const adapter = adapterOf(module);
325
+ if (adapter !== undefined) return adapter[name];
326
+ const namespace = RADIX_PACKAGES.get(module);
327
+ return `\`@octanejs/radix\` has no \`${namespace === 'Slot' ? name : `${namespace}.${name}`}\`.`;
328
+ }
329
+
330
+ /**
331
+ * The TanStack adapter a specifier imports, by its package.
332
+ *
333
+ * @param {string} module
334
+ */
335
+ function adapterOf(module) {
336
+ const name = module.split('/', 2).join('/');
337
+ return Object.hasOwn(TANSTACK_ADAPTERS, name) ? TANSTACK_ADAPTERS[name] : undefined;
338
+ }
339
+
159
340
  /**
160
341
  * React values with no Octane export, each with what to do instead. A value
161
342
  * listed here is never imported from Octane; the codemod either rewrites its
package/src/project.js CHANGED
@@ -1,11 +1,10 @@
1
1
  import fs from 'node:fs';
2
- import { createRequire } from 'node:module';
3
2
  import path from 'node:path';
4
- import { findRoot, scanSourceFiles } from '@octanejs/cli';
3
+ import { findRoot, readInstalled, scanSourceFiles } from '@octanejs/cli';
5
4
  import { DATA } from '@octanejs/cli/data';
6
5
  import ts from 'typescript';
7
6
  import { finding, loadCompiler, thrown } from './compiler.js';
8
- import { FRAMEWORK_PACKAGES } from './mappings.js';
7
+ import { PORTED_PACKAGES } from './mappings.js';
9
8
  import { strengthen } from './strong.js';
10
9
  import { transformModule } from './transform.js';
11
10
 
@@ -41,15 +40,18 @@ import { transformModule } from './transform.js';
41
40
  * @property {FileResult[]} files
42
41
  * @property {{ from: string, to: string }[]} packages React packages the
43
42
  * migrated code now imports as Octane bindings
44
- * @property {string[]} missing React packages the code imports that have no
45
- * Octane binding
43
+ * @property {Missing[]} missing React packages the code imports that have no
44
+ * Octane port, and how it uses them
46
45
  * @property {string[]} html entry pages whose script reference was updated
47
46
  * @property {string | null} compiler where the verifying compiler came from
47
+ *
48
+ * @typedef {import('./transform.js').Unported & { modules: number }} Missing
49
+ * with how many modules import it
48
50
  */
49
51
 
50
52
  const SOURCE = /\.(?:[cm]?[jt]sx?)$/;
51
53
  /** React packages and the Octane package that replaces each. */
52
- const CATALOG = { ...DATA.reactPackages, ...FRAMEWORK_PACKAGES };
54
+ const CATALOG = { ...DATA.reactPackages, ...PORTED_PACKAGES };
53
55
  /** A package that, by its name, renders through React. */
54
56
  const REACT_PACKAGE = /^(?:react-|@[^/]+\/react(?:-|\/|$)|[^/]+\/react$)|-react(?:\/|$)/;
55
57
 
@@ -89,20 +91,23 @@ export async function runCodemod(paths, options = {}) {
89
91
  const compiler = verify || strong ? await loadCompiler(root) : null;
90
92
  /** @type {Map<string, string>} */
91
93
  const packages = new Map();
92
- /** @type {Set<string>} */
93
- const missing = new Set();
94
+ /** @type {Map<string, Missing>} */
95
+ const missing = new Map();
96
+ // `ReactCompat` hosts a component from a package with no port in a React
97
+ // root, from 19.2 within the React 19 series it supports.
98
+ const reactCompat = ['react', 'react-dom'].every((name) =>
99
+ /^19\.(?:[2-9]|\d{2,})\./.test(readInstalled(root, name)?.version ?? ''),
100
+ );
94
101
  /** @type {FileResult[]} */
95
102
  const results = [];
96
103
  for (const file of files) {
97
104
  const source = fs.readFileSync(file, 'utf8');
98
105
  /** @type {Note[]} */
99
106
  const extra = [];
100
- /** @type {Set<string>} */
101
- const unmapped = new Set();
102
107
  const resolveSpecifier = (/** @type {string} */ specifier) =>
103
108
  resolveRelative(file, specifier, known, renames) ??
104
109
  resolveAlias(file, specifier, renames, config) ??
105
- resolveBinding(file, specifier, packages, extra, unmapped);
110
+ resolveBinding(specifier, packages, extra);
106
111
  const isContext = (/** @type {string} */ specifier, /** @type {string} */ name) => {
107
112
  if (!specifier.startsWith('.')) return null;
108
113
  const target = resolveModule(file, specifier, known);
@@ -116,15 +121,20 @@ export async function runCodemod(paths, options = {}) {
116
121
  types: sourceFile && checker && { sourceFile, checker },
117
122
  resolveSpecifier,
118
123
  isContext,
124
+ unported: (specifier) => unportedName(specifier, file),
125
+ reactCompat,
119
126
  });
120
- for (const name of unmapped) {
121
- missing.add(name);
122
- extra.push({
123
- rule: 'bindings',
124
- severity: 'error',
125
- line: 1,
126
- message: `No Octane binding for \`${name}\`, a React package; port it or replace it.`,
127
- });
127
+ for (const port of result.unported) {
128
+ const entry = missing.get(port.name) ?? {
129
+ name: port.name,
130
+ modules: 0,
131
+ islands: 0,
132
+ blocked: 0,
133
+ };
134
+ entry.modules++;
135
+ entry.islands += port.islands;
136
+ entry.blocked += port.blocked;
137
+ missing.set(port.name, entry);
128
138
  }
129
139
  const output = renames.get(file) ?? file;
130
140
  let code = result.code;
@@ -203,7 +213,7 @@ export async function runCodemod(paths, options = {}) {
203
213
  root,
204
214
  files: results,
205
215
  packages: [...packages].map(([from, to]) => ({ from, to })),
206
- missing: [...missing].sort(),
216
+ missing: [...missing.values()].sort((a, b) => a.name.localeCompare(b.name)),
207
217
  html,
208
218
  compiler: compiler?.from ?? null,
209
219
  };
@@ -211,12 +221,13 @@ export async function runCodemod(paths, options = {}) {
211
221
 
212
222
  /**
213
223
  * Whether Octane compiles this module: `.tsrx`, JSX, or a module that imports
214
- * the runtime.
224
+ * the runtime. A declaration file is only types.
215
225
  *
216
226
  * @param {string} file
217
227
  * @param {string} code
218
228
  */
219
229
  function isCompiled(file, code) {
230
+ if (file.endsWith('.d.ts')) return false;
220
231
  return /\.(?:tsrx|[jt]sx)$/.test(file) || /from\s+['"]octane['"]/.test(code);
221
232
  }
222
233
 
@@ -301,7 +312,7 @@ function projectProgram(options, files) {
301
312
  * @param {string} name
302
313
  */
303
314
  function isSource(name) {
304
- return SOURCE.test(name) && !name.endsWith('.d.ts') && !/\.config\.[cm]?[jt]s$/.test(name);
315
+ return SOURCE.test(name) && !/\.config\.[cm]?[jt]s$/.test(name);
305
316
  }
306
317
 
307
318
  /**
@@ -395,38 +406,19 @@ function contextIndex(exports, files) {
395
406
  * The binding that replaces a React package import, recorded so the report
396
407
  * can list the dependency changes.
397
408
  *
398
- * @param {string} from the importing module
399
409
  * @param {string} specifier
400
410
  * @param {Map<string, string>} packages
401
411
  * @param {Note[]} notes
402
- * @param {Set<string>} unmapped React packages with no binding
403
412
  */
404
- function resolveBinding(from, specifier, packages, notes, unmapped) {
405
- if (specifier.startsWith('.') || specifier.startsWith('/')) return null;
406
- // The catalog keys some bindings by subpath (`better-auth/react`), so the
407
- // longest matching prefix wins.
408
- const parts = specifier.split('/');
409
- let name = '';
410
- for (let length = parts.length; length > 0 && name === ''; length--) {
411
- const candidate = parts.slice(0, length).join('/');
412
- if (candidate in CATALOG) name = candidate;
413
- }
414
- if (name === '') {
415
- const root = specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
416
- // Any package's `/react` entry renders with React (`@tanstack/markdown/react`).
417
- if (/\/react(?:\/|$)/.test(specifier.slice(root.length))) unmapped.add(specifier);
418
- else if (rendersWithReact(root, from)) unmapped.add(root);
419
- return null;
420
- }
413
+ function resolveBinding(specifier, packages, notes) {
414
+ const name = catalogName(specifier);
415
+ if (name === null) return null;
421
416
  const binding = CATALOG[name];
422
417
  packages.set(name, binding);
423
418
  // An aggregate binding (`@octanejs/visx`, for `@visx/visx`) serves each
424
419
  // package of its scope from a subpath: `@visx/hierarchy` is
425
420
  // `@octanejs/visx/hierarchy`.
426
- const upstream = DATA.bindings.find(
427
- (/** @type {{ name: string, upstream?: { package?: string } }} */ entry) =>
428
- entry.name === binding,
429
- )?.upstream?.package;
421
+ const upstream = DATA.bindings.find((entry) => entry.name === binding)?.upstream?.package;
430
422
  const aggregate = upstream?.match(/^@([^/]+)\/\1$/);
431
423
  if (aggregate && name !== upstream && name.startsWith(`@${aggregate[1]}/`)) {
432
424
  return `${binding}/${name.slice(aggregate[1].length + 2)}${specifier.slice(name.length)}`;
@@ -443,25 +435,56 @@ function resolveBinding(from, specifier, packages, notes, unmapped) {
443
435
  return binding + subpath;
444
436
  }
445
437
 
438
+ /**
439
+ * The catalog entry for a package specifier, or null. The catalog keys some
440
+ * bindings by subpath (`better-auth/react`), so the longest matching prefix
441
+ * wins.
442
+ *
443
+ * @param {string} specifier
444
+ */
445
+ function catalogName(specifier) {
446
+ if (specifier.startsWith('.') || specifier.startsWith('/')) return null;
447
+ const parts = specifier.split('/');
448
+ for (let length = parts.length; length > 0; length--) {
449
+ const candidate = parts.slice(0, length).join('/');
450
+ if (candidate in CATALOG) return candidate;
451
+ }
452
+ return null;
453
+ }
454
+
455
+ /**
456
+ * The React package a specifier names when Octane has no binding for it, or
457
+ * null.
458
+ *
459
+ * @param {string} specifier
460
+ * @param {string} from the importing module
461
+ */
462
+ function unportedName(specifier, from) {
463
+ if (specifier.startsWith('.') || specifier.startsWith('/') || catalogName(specifier) !== null)
464
+ return null;
465
+ const parts = specifier.split('/');
466
+ const root = specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
467
+ // Any package's `/react` entry renders with React (`@tanstack/markdown/react`).
468
+ if (/\/react(?:\/|$)/.test(specifier.slice(root.length))) return specifier;
469
+ return rendersWithReact(root, from) ? root : null;
470
+ }
471
+
446
472
  /**
447
473
  * Whether a package renders through React: it declares `react` as a peer or
448
- * dependency when installed, or its name says so when it is not.
474
+ * dependency when installed, or its name says so when it is not. A package
475
+ * with a `./react` entry (`@pierre/trees/react`) renders through React there,
476
+ * which the caller matches by subpath; its other entries need no binding. An
477
+ * optional peer alone does not say which entries use React.
449
478
  *
450
479
  * @param {string} name
451
480
  * @param {string} from
452
481
  */
453
482
  function rendersWithReact(name, from) {
454
483
  if (name === 'octane' || name.startsWith('@octanejs/') || name.startsWith('node:')) return false;
455
- try {
456
- const manifest = JSON.parse(
457
- fs.readFileSync(createRequire(from).resolve(`${name}/package.json`), 'utf8'),
458
- );
459
- return ['peerDependencies', 'dependencies'].some(
460
- (field) => manifest[field]?.react !== undefined,
461
- );
462
- } catch {
463
- return REACT_PACKAGE.test(name);
464
- }
484
+ const manifest = readInstalled(path.dirname(from), name)?.manifest;
485
+ if (!manifest) return REACT_PACKAGE.test(name);
486
+ if (manifest.exports?.['./react']) return false;
487
+ return ['peerDependencies', 'dependencies'].some((field) => manifest[field]?.react !== undefined);
465
488
  }
466
489
 
467
490
  /**