Skip to content

Strong codemod can move store reads that dispatch to React hooks into native SSR #2441

Closed

Description

@domgan-oai

The scoped-store codemod identifies a handle constructed by an authentic factory from a linked workspace package. Two small programs show how the implementation invoked by a store read can still belong to React. Both programs use this component.

import { useSnapshot } from 'observer';
import { reading } from './reading';

export function Pane() {
  const store = useSnapshot();
  return <b>{String(store.get(reading))}</b>;
}

1. A module replaces a method on the handle. The first component also imports ./configure for its side effect. Its store calls handle.read().

// Core factory, exported by observer/core
export function key(value: string) { return {read: () => value}; }

// reading.ts
import {key} from 'observer/core';
export const reading = key('literal');

// configure.ts
import {createContext, useContext} from 'react';
import {reading} from './reading';
const state = createContext('present');
reading.read = () => useContext(state);

2. The active provider owns the lookup. Here the factory returns the immutable string 'stable-key'. The component imports only the hook and the key. A stock Map and a frozen subclass both satisfy the context’s Map<string, string> type. The active provider chooses which implementation runs.

import {createContext, useContext} from 'react';
import {reading} from './reading';
const state = createContext('present');
const readers = new Map<string, () => string>([[reading, () => useContext(state)]]);

class DispatchMap extends Map<string, string> {
  override get(key: string) { return readers.get(key)?.(); }
}

export const data = new Map([[reading, 'present']]);
export const dispatch = Object.freeze(new DispatchMap());

The script gives the same provider instance to the original React component and the generated native component. All React imports resolve to the same installation.

Store used at render Codemod Original React SSR Generated native SSR
Store calls the replaced handle method Strong, zero errors <b>present</b> Throws reading useContext from a null dispatcher
Stock Map, immutable key Strong, zero errors <b>present</b> <b>present</b>
Frozen Map subclass, same key Strong, zero errors <b>present</b> Throws reading useContext from a null dispatcher

Expected. A clean migration should preserve SSR for the active provider or keep a bindings diagnostic when render-time execution can enter a React hook. Resolving the factory identifies the origin of the input. The implementation called during render can come from either the current handle or the current provider.

Correction to consider. Require evidence about the read operation as well as its input before treating the call as renderer-independent. A package can supply a native snapshot reader that consumes data published by the original owner. Until equivalent behavior is established, keep a diagnostic for render-time reads with replaceable dispatch. A check for a visible side-effect mutation would address the first example and still admit the second.

Reproduce

Verified the same results on merged main 597eecc4165954598d4cfaa9709725251ff0554f and PR #2428 head fe62c19f8c0d2b2a9412c5ab5e7c15bf1515e242. Both revisions contain the same Octane runtime and compiler source. The run used Node 26.12.1, TypeScript 5.9.3, React and React DOM 19.2.7, Octane 0.16.7 and esbuild 0.28.1.

In an Octane checkout, install the workspace at the pinned main commit. Save the following script outside the checkout as repro.mjs. It creates and removes its own temporary project. Each invocation reaches the failing native SSR assertion on the affected revisions.

git switch --detach 597eecc4165954598d4cfaa9709725251ff0554f
pnpm install --frozen-lockfile
pnpm --filter @octanejs/codemod build
node /path/to/repro.mjs . --case=handle
node /path/to/repro.mjs . --case=provider
Standalone repro.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import os from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';

const repo = path.resolve(process.argv[2] || '.');
const require = createRequire(path.join(repo, 'packages/codemod/package.json'));
const types = createRequire(path.join(repo, 'packages/octane/package.json'));
const rest = process.argv.slice(3);
const scenario = rest.find(arg => arg.startsWith('--case='))?.slice(7) ?? 'handle';
assert.ok(['handle', 'provider'].includes(scenario), 'use --case=handle or --case=provider');
const codemodRepo = path.resolve(rest.find(arg => !arg.startsWith('--')) || repo);
const { runCodemod } = await import(pathToFileURL(path.join(codemodRepo, 'packages/codemod/dist/index.js')));
const { compile } = await import(pathToFileURL(require.resolve('octane/compiler')));
const { build } = require('esbuild');
const React = require('react');
const { renderToStaticMarkup } = require('react-dom/server');
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'octane-store-repro-'));
const app = path.join(root, 'app');

const pane = `import {useSnapshot} from 'observer';
import {reading} from './reading';
${scenario === 'handle' ? "import './configure';" : ''}
export function Pane() {
  const current = useSnapshot();
  return <b>{String(current.get(reading))}</b>;
}`;
const files = {
  'observer/package.json': JSON.stringify({name:'observer',version:'1.0.0',peerDependencies:{react:'^19.2.0'},exports:{'.':'./entry.ts','./core':'./core.ts'}}),
  'observer/entry.ts': "export * from './core'; export {useSnapshot} from './hooks';",
  'observer/core.ts': "export {key, identity} from './state';",
  'observer/state.ts': 'export function key(value: string) {return {read: () => value}} export function identity<T>(v:T){return v}',
  'observer/context.ts': "import {createContext} from 'react';export const current=createContext({get(handle:{read():string}) {return handle.read()}});",
  'observer/hooks.ts': "import {use} from 'react';import {current} from './context';import {identity} from './state';export function useSnapshot(){return identity(use(current))}",
  'app/package.json': JSON.stringify({type:'module',dependencies:{observer:'workspace:*',react:'19.2.7','react-dom':'19.2.7',octane:'0.16.7'}}),
  'app/tsconfig.json': JSON.stringify({compilerOptions:{strict:true,target:'ESNext',module:'ESNext',moduleResolution:'Bundler',jsx:'react-jsx',lib:['ESNext','DOM','DOM.Iterable']}}),
  'app/src/reading.ts': "import {key} from 'observer/core';export const reading=key('literal');",
  'app/src/configure.ts': "import {createContext,useContext} from 'react';import {reading} from './reading';const state=createContext('present');reading.read=()=>useContext(state);",
  'app/src/pane.tsx': pane,
  'app/src/original.tsx': pane
};
if (scenario === 'provider') {
  files['observer/state.ts'] =
    "export function key(){return 'stable-key' as const} export function identity<T>(v:T){return v}";
  files['observer/context.ts'] =
    "import {createContext} from 'react'; export const current=createContext(new Map<string,string>());";
  files['app/src/reading.ts'] =
    "import {key} from 'observer/core'; export const reading=key();";
  delete files['app/src/configure.ts'];
  files['app/src/stores.ts'] = `import {createContext, useContext} from 'react';
import {reading} from './reading';
const state = createContext('present');
const readers = new Map<string, () => string>([[reading, () => useContext(state)]]);
class DispatchMap extends Map<string, string> {
  override get(key: string) {return readers.get(key)?.();}
}
export const dispatch = Object.freeze(new DispatchMap());
export const data = new Map([[reading, 'present']]);`;
}
function write(file,text) {
  const name=path.join(root,file);
  fs.mkdirSync(path.dirname(name),{recursive:true});
  fs.writeFileSync(name,text);
}
function link(from,to) {
  const target=path.join(root,to);
  fs.mkdirSync(path.dirname(target),{recursive:true});
  fs.symlinkSync(from,target,'dir');
}
try {
  for(const [file,body] of Object.entries(files)) write(file,body);
  for(const pkg of ['react','react-dom'])
    link(path.dirname(require.resolve(pkg+'/package.json')), 'node_modules/'+pkg);
  link(path.dirname(types.resolve('@types/react/package.json')), 'node_modules/@types/react');
  link(path.join(repo,'packages/octane'),'node_modules/octane');
  link(path.join(root,'observer'),'app/node_modules/observer');

  const input=path.join(app,'src/pane.tsx');
  const result=await runCodemod([input],{root:app,strong:true,verify:true,write:true,projectTypes:true});
  const file=result.files.find(f=>f.file==='src/pane.tsx');
  const errors=[...file.notes,...file.diagnostics].filter(n=>n.severity==='error').map(n=>n.message);
  console.log(JSON.stringify({scenario,strong:file.strong,errors}));
  if(errors.length===0) {
    write('app/src/native.tsrx', `import {NativeStoreProvider} from './octane-store-context.tsrx';
import {current} from '../../observer/context';
import {Pane} from './pane.tsrx';
export function Root({store}) @{ <NativeStoreProvider context={current} value={store}><Pane/></NativeStoreProvider> }`);
    const outfile=path.join(app,'server.mjs');
    await build({stdin:{resolveDir:app,contents:`export {Root} from './src/native.tsrx';
export {Pane as Original} from './src/original.tsx';
export {current} from '../observer/context';
export {renderToString} from 'octane/server';
${scenario === 'provider' ? "export {dispatch, data} from './src/stores';" : ''}`},
      outfile,bundle:true,platform:'node',format:'esm',external:['react','react-dom','react-dom/*'],
      plugins:[{name:'tsrx',setup(b){b.onLoad({filter:/\.tsrx$/},({path:file})=>({
        contents:compile(fs.readFileSync(file,'utf8'),file,{mode:'server'}).code,
        loader:'js',resolveDir:path.dirname(file)
      }));}}]
    });
    const mod=await import(pathToFileURL(outfile));
    const renderReact = store => renderToStaticMarkup(
      React.createElement(mod.current.Provider,{value:store},React.createElement(mod.Original))
    );
    const renderNative = store => mod.renderToString(mod.Root,{store}).html;
    const withoutComments = html => html.replace(/<!--[\s\S]*?-->/g, '');
    if (scenario === 'provider') {
      const plain = {original:renderReact(mod.data),native:withoutComments(renderNative(mod.data))};
      assert.equal(plain.original,'<b>present</b>');
      assert.equal(plain.native,plain.original);
      assert.ok(Object.isFrozen(mod.dispatch));
      console.log(JSON.stringify({plainMap:plain}));
    }
    const store=scenario === 'provider' ? mod.dispatch : {get(handle){return handle.read()}};
    const original=renderReact(store);
    assert.equal(original,'<b>present</b>');
    let native, error;
    try{native=withoutComments(renderNative(store));}catch(e){error=e.message;}
    console.log(JSON.stringify({scenario,original,native,error}));
    assert.equal(error,undefined,'the renderer rejected a store read that the codemod marked safe');
    assert.equal(native,original);
  }
} finally {
  fs.rmSync(root,{recursive:true,force:true});
}

Activity

  1. added
    bug
    agent-authored
    on Nov 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    agent-authoredbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions