Full Code of jacob-ebey/federated-rsc for AI

main 8dbf2bfbafa5 cached
102 files
139.3 KB
42.9k tokens
114 symbols
1 requests
Download .txt
Repository: jacob-ebey/federated-rsc
Branch: main
Commit: 8dbf2bfbafa5
Files: 102
Total size: 139.3 KB

Directory structure:
gitextract_hem18noe/

├── .gitignore
├── .vscode/
│   ├── extensions.json
│   └── settings.json
├── README.md
├── biome.json
├── examples/
│   ├── basic/
│   │   ├── app/
│   │   │   ├── components/
│   │   │   │   └── counter.tsx
│   │   │   └── routes/
│   │   │       ├── _public/
│   │   │       │   └── route.tsx
│   │   │       ├── _public.$/
│   │   │       │   └── route.tsx
│   │   │       ├── _public.layout/
│   │   │       │   └── route.tsx
│   │   │       ├── _public.slug.$slug/
│   │   │       │   └── route.tsx
│   │   │       └── weather.$/
│   │   │           ├── route.tsx
│   │   │           └── temperature-switch.tsx
│   │   ├── package.json
│   │   ├── server.mts
│   │   ├── ssr-server.mts
│   │   └── tsconfig.json
│   └── consumer/
│       ├── app/
│       │   ├── components/
│       │   │   └── counter.tsx
│       │   └── routes/
│       │       ├── _public/
│       │       │   └── route.tsx
│       │       ├── _public._index/
│       │       │   └── route.tsx
│       │       ├── _public.about/
│       │       │   └── route.tsx
│       │       └── _public.about.$slug/
│       │           └── route.tsx
│       ├── package.json
│       ├── server.mts
│       ├── ssr-server.mts
│       ├── tsconfig.json
│       └── webpack.config.cjs
├── fixture/
│   ├── marketing/
│   │   ├── app/
│   │   │   ├── components/
│   │   │   │   └── ui/
│   │   │   │       ├── avatar.tsx
│   │   │   │       ├── button.tsx
│   │   │   │       ├── card.tsx
│   │   │   │       ├── input.tsx
│   │   │   │       └── separator.tsx
│   │   │   ├── lib/
│   │   │   │   └── utils.ts
│   │   │   ├── remotes.tsx
│   │   │   └── routes/
│   │   │       ├── _public/
│   │   │       │   ├── route.tsx
│   │   │       │   └── style.css
│   │   │       ├── _public._index/
│   │   │       │   ├── products.tsx
│   │   │       │   └── route.tsx
│   │   │       └── _public.product.$handle/
│   │   │           ├── actions.tsx
│   │   │           ├── client.tsx
│   │   │           ├── form.tsx
│   │   │           ├── product.tsx
│   │   │           ├── reviews.tsx
│   │   │           └── route.tsx
│   │   ├── components.json
│   │   ├── modules.d.ts
│   │   ├── package.json
│   │   ├── postcss.config.cjs
│   │   ├── remotes.cjs
│   │   ├── server.mts
│   │   ├── ssr-server.mts
│   │   ├── tailwind.config.cjs
│   │   ├── tsconfig.json
│   │   └── webpack.config.cjs
│   └── shell/
│       ├── app/
│       │   ├── components/
│       │   │   └── ui/
│       │   │       └── button.tsx
│       │   ├── lib/
│       │   │   └── utils.ts
│       │   ├── remotes.tsx
│       │   └── routes/
│       │       ├── _public/
│       │       │   ├── client.tsx
│       │       │   ├── header.tsx
│       │       │   ├── route.tsx
│       │       │   └── style.css
│       │       ├── _public.$/
│       │       │   └── route.tsx
│       │       ├── _public._index/
│       │       │   └── route.tsx
│       │       ├── _public.product.$handle/
│       │       │   └── route.tsx
│       │       └── api.shell/
│       │           └── route.tsx
│       ├── components.json
│       ├── modules.d.ts
│       ├── package.json
│       ├── postcss.config.cjs
│       ├── remotes.cjs
│       ├── server.mts
│       ├── ssr-server.mts
│       ├── tailwind.config.cjs
│       ├── tsconfig.json
│       └── webpack.config.cjs
├── framework/
│   ├── bin/
│   │   └── remix.cjs
│   ├── cli/
│   │   └── build.mjs
│   ├── entry/
│   │   ├── browser.tsx
│   │   ├── empty.tsx
│   │   ├── server.tsx
│   │   └── ssr.tsx
│   ├── lib/
│   │   ├── framework.browser.tsx
│   │   ├── framework.client.internal.tsx
│   │   ├── framework.client.tsx
│   │   ├── framework.runtime.client.ts
│   │   ├── framework.runtime.server.ts
│   │   ├── framework.server.tsx
│   │   ├── framework.ssr.tsx
│   │   ├── framework.tsx
│   │   ├── framework.webpack.ts
│   │   ├── react.client.browser.tsx
│   │   ├── react.client.node.tsx
│   │   ├── react.server.browser.tsx
│   │   ├── react.server.node.tsx
│   │   ├── utils.ts
│   │   ├── webpack.federation-runtime-plugin.ts
│   │   └── webpack.plugins.ts
│   ├── package.json
│   ├── server-only.js
│   ├── tsconfig.json
│   └── tsconfig.lib.json
├── package.json
└── pnpm-workspace.yaml

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
.DS_Store
dist/
node_modules/

================================================
FILE: .vscode/extensions.json
================================================
{
  "recommendations": [
    "biomejs.biome",
    "csstools.postcss",
    "heybourn.headwind"
  ]
}

================================================
FILE: .vscode/settings.json
================================================
{
	"editor.defaultFormatter": "biomejs.biome",
	"files.associations": {
		"*.css": "postcss"
	},
	"[postcss]": {
		"editor.defaultFormatter": "esbenp.prettier-vscode"
	}
}


================================================
FILE: README.md
================================================
# Federated RSC Reference Architecture

THIS IS SUPERSEDED BY https://github.com/jacob-ebey/fuckin-around

This repository contains the reference architecture for a federated RSC organization architecture. The architecture is based on a few principles:

- HTTP is the API for the "server" layer.
- The "server" layer exposes assets for the "client" layer to consume.
- If you are a "client" and know how to load the assets, you can consume any "server" payload.
- "Server" responses should be composable with "client" components and other "server" responses.
- "Client references" are global.
- How to load a "client reference" is a "client" concern.

## Let's get on the same page

### What is RSC?

RSC is a response format that, among other things, encodes a JSX tree. In that JSX tree there can be "client references". These "references" are boundaries that encode properties for a component, and an ID for "how to load" the component. In this architecture, client reference IDs are global to the application and refer to an export from an exposed module of a remote container.

..."refer to an export from an exposed module of a remote container", hahahah I know.... I'll explain.

### What is a container?

A container is a collection of javascript modules. Imagine an object with keys that point to dynamic imports:

```js
// I'm kinda a remote container...
export const moduleA = () => import("./moduleA.js");
// I'm another exposed module
export const moduleB = () => import("./moduleB.js");
// ...etc...
```

Beyond this, it's a a collection of dynamic imports that can be provided already loaded versions of the dependencies they need to run. To me, this is the **most important** part of module federation. It's globals with guarantees based on semantic versioning at the minimum, and whatever you want it to be at it's best.

The above over simplificated example of a container would fail if a library like React came into the picture that needed to have a single copy of itsself on the page.

If we could express the "sharing" of module federation as a javascript syntax, I'd probably pick import attributes:

```js
// http://other-domain.com/moduleA.js
import * as React from "./react.js";

export function Component() {
  return React.createElement("h1", null, "Hello World");
}
```

```js
// http://other-domain.com/container.js

import * as React from "./react.js";

export const moduleA = () =>
  import("./moduleA.js", {
    with: { shared: { react: React } },
  });
export const moduleB = () =>
  import("./moduleB.js", {
    with: { shared: { react: React } },
  });
```

The `with: { shared: { react: React } }` above means "when moduleB.js imports "react", use this instead.

And if we expand this into a runtime syntax for consuming a module from a container from another domain with it's own copy of React, it might look like this:

```js
import * as React from "./react.js";

const { Component } = await import("http://other-domain.com/container.js", {
  with: {
    shared: { react: React },
    exposed: "moduleA",
  },
});
```

Module federation explained in a nutshell, and the type of runtime syntax I'd love to see in JS runtimes. You can already cross pollute globals, and that's mainly how federaiton is accomplised in the browser for legacy support, so why not make it explicit and predictable for the use-cases where it makes sense in modern browsers and runtimes?

## What is a "Server"?

A "server" (unquoted) from here on out will refer to an HTTP server that responds with a RSC payload. The RSC payload is essentially enahnced JSON with support for JSX trees and "client references".

## What is a "Client"?

A "client" consumes a server response and renders it for display to the user. There are two types of clients we will be talking about; an "ssr client" and a "browser client". These may be refered to as "the browser", "the ssr server", "the ssr client", "the browser client", etc.

Note - if you are not familiar with RSC, SSR and "ssr client" / "client that run on the server" are on in the same. It's "the way you server render a react app before RSC".

## What is a "Client Reference"?

A "client reference" is a boundary in a JSX tree that encodes a "client reference ID" and "client reference properties". The "client reference ID" is a string that is globally unique for that specific component. The "client reference properties" are a set of properties that are passed to the "client reference ID" when it is loaded and rendered in a client, these properties are encoded in the RSC payload.

## The Architecture

### The Server Layer

The server layer is a collection of HTTP endpoints that respond with the RSC format. The RSC format encodes "client references", and also exposes the references for clients to load.

This is the layer in which you would acccess your data sources and render any markup that is not dynamic. This is also the layer in which you would expose your "client references" for clients to consume by simply by importing from a module marked `use client`.

### The Client Layer

React as today but instead of having a single entry point that looks like this:

```jsx
import * as React from "./react.js";
import * as ReactDOM from "./react-dom.js";

// A component that dynamically imports components to render the data based on the URL
import { App } from "./entry.browser.js";

ReactDOM.render(
  React.createElement(App, {
    // Get the data dependencies from the server
    data: fetch(window.location.url, {
      headers: {
        Accept: "application/json",
      },
    }),
    location: window.location.url,
  }),
  document.getElementById("root")
);
```

You have an entrypoint that, in concept, is more like this:

```jsx
import * as React from "./react.js";
import * as ReactDOM from "./react-dom.js";

// A dynamically generated entrypoint based on the URL that considers any data dependencies
const { App } = await import(window.location.url, {
  with: {
    shared: { react: React },
    exposed: "entry.browser.js",
  },
});

ReactDOM.render(React.createElement(App), document.getElementById("root"));
```

### The "Client Reference" Layer

The client references (`use client` modules) are chunked off and given a global ID per application. For example if you had a source module in an app called "test" at `app/components/MyComponents.js` that had a `Counter` component that was refereced by a server module, you'd end up with a container equivilant to this:

```js
//test_container.js
import * as React from "./react.js";

export const MyComponent = () =>
  import("./app/components/MyComponent.js", {
    with: {
      shared: { react: React },
    },
  });
```

And the ID for the bookend encoded into the RSC stream for loading this component would be: `rsc/remote/client/test/MyComponents#Counter`. At build, remote container modules are aliased, both module and chunk IDs to the global ID of the module. So our previous remote container reference module and chunk ID would be avaliable for load at RSC payload decode through: `rsc/remote/client/test/MyComponents`. Where that module is loaded from is a "client" concern and this openes up all sorts of opertunities.

### Composing servers

Composing servers is dooable at both the ingress (SSR client) and data (RSC server) layers. The ingress layer is composable just by knowing how to load the remote containers for the servers you are consuming. The data layer is composable by encoding RSC payloads as properties to a "client references" and decoding the them in the client to a JSX tree.


================================================
FILE: biome.json
================================================
{
	"$schema": "https://biomejs.dev/schemas/1.5.1/schema.json",
	"files": {
		"ignoreUnknown": true,
		"include": [
			"**/*.ts",
			"**/*.mts",
			"**/*.tsx",
			"**/*.js",
			"**/*.mjs",
			"**/*.cjs",
			"**/*.jsx",
			"**/*.json",
			"**/*.md"
		],
		"ignore": ["node_modules", "dist"]
	},
	"organizeImports": {
		"enabled": true
	},
	"linter": {
		"enabled": true,
		"rules": {
			"recommended": true
		}
	},
	"formatter": {
		"enabled": true
	},
	"css": {
		"formatter": {
			"enabled": true
		}
	}
}


================================================
FILE: examples/basic/app/components/counter.tsx
================================================
"use client";

import * as React from "react";

function CounterBasic() {
	const [count, setCount] = React.useState(0);
	return (
		<div>
			<p>Basic count: {count}</p>
			<button type="button" onClick={() => setCount(count - 1)}>
				Decrement
			</button>
			<button type="button" onClick={() => setCount(count + 1)}>
				Increment
			</button>
		</div>
	);
}

export { CounterBasic as Counter };


================================================
FILE: examples/basic/app/routes/_public/route.tsx
================================================
import { getHeaders, getURL } from "framework";

export function Component({ children }: { children: React.ReactNode }) {
	const headers = getHeaders();
	const url = getURL();

	const renderedForHost = headers.get("X-Forwarded-For-Host") || url.host;
	const renderedForURL = new URL(url);
	renderedForURL.host = renderedForHost;
	const renderedFor = renderedForURL.href;

	return (
		<html lang="en">
			<head>
				<title>My App</title>
			</head>
			<body style={{ backgroundColor: "pink", padding: "1rem" }}>
				<header>
					<nav>
						<ul>
							<li>
								<a href="/">Home</a>
							</li>
							<li>
								<a href="/about">About</a>
							</li>
							<li>
								<a href="/about/sub">About Sub</a>
							</li>
							<li>
								<a href="/not-found">Not Found</a>
							</li>
						</ul>
					</nav>
					<p>RENDERED FOR: {renderedFor}</p>
				</header>
				{children}
			</body>
		</html>
	);
}


================================================
FILE: examples/basic/app/routes/_public.$/route.tsx
================================================
import { Counter } from "../../components/counter";

export function Component() {
	return (
		<>
			<h1>Hello Glob</h1>
			<Counter />
		</>
	);
}


================================================
FILE: examples/basic/app/routes/_public.layout/route.tsx
================================================
export function Component({ children }: { children: React.ReactNode }) {
	return children;
}


================================================
FILE: examples/basic/app/routes/_public.slug.$slug/route.tsx
================================================
export function Component() {
	return <h1>Hello Slug</h1>;
}


================================================
FILE: examples/basic/app/routes/weather.$/route.tsx
================================================
import { type Params } from "framework";
import * as React from "react";

import {
	TemperatureDisplay,
	TemperatureSwitch,
	TemperatureToggle,
} from "./temperature-switch";

async function ArtificialDelayExample() {
	await new Promise((resolve) => setTimeout(resolve, 1000));
	return <div>Delayed for 1 second</div>;
}

export async function Component({
	children,
	params,
}: {
	children?: React.ReactNode;
	params: Params<"*">;
}) {
	const query = params["*"];

	if (!query) throw new Error("No query provided");

	const url = new URL(
		"http://api.weatherapi.com/v1/current.json?key=af6582e99cc74f78972230710240501",
	);
	url.searchParams.append("q", query);

	if (query !== "seattle") {
		await new Promise((resolve) => setTimeout(resolve, 1000));
	}

	const weather = await fetch(url.href).then((response) => response.json());

	return (
		<div style={{ backgroundColor: "pink", padding: "1rem" }}>
			{/* <React.Suspense fallback={<div>Artificial delay...</div>}> */}
			<ArtificialDelayExample />
			{/* </React.Suspense> */}
			<TemperatureSwitch>
				<div
					style={{
						padding: "1.5rem",
						borderRadius: "0.5rem",
						border: "2px solid #f3f4f6",
					}}
				>
					<div
						style={{
							display: "flex",
							flexDirection: "column",
						}}
					>
						<div>
							<h2
								style={{
									fontSize: "1.5rem",
									color: "#374151",
								}}
							>
								{weather.location.name}, {weather.location.region}
							</h2>
						</div>
						<TemperatureToggle />
						<div
							style={{
								margin: "1rem 0",
							}}
						>
							<div
								style={{
									display: "flex",
									flexDirection: "row",
									alignItems: "center",
									gap: "1rem",
								}}
							>
								<div>
									<span>
										<img
											height="64"
											width="64"
											alt={weather.current.condition.text}
											src={weather.current.condition.icon}
										/>
									</span>
								</div>
								<div>
									<h4
										style={{
											fontSize: "2rem",
											color: "#374151",
										}}
									>
										<TemperatureDisplay
											c={weather.current.temp_c}
											f={weather.current.temp_f}
										/>
									</h4>
									<p
										style={{
											fontSize: "1rem",
											color: "#374151",
										}}
									>
										Feels like{" "}
										<TemperatureDisplay
											c={weather.current.feelslike_c}
											f={weather.current.feelslike_f}
										/>
									</p>
								</div>
							</div>
						</div>
					</div>
				</div>
			</TemperatureSwitch>
			<React.Suspense fallback={<div>Children loading...</div>}>
				{children}
			</React.Suspense>
		</div>
	);
}

Component.api = true;


================================================
FILE: examples/basic/app/routes/weather.$/temperature-switch.tsx
================================================
"use client";

import { createContext, useCallback, useContext, useState } from "react";

const temperatureContext = createContext<null | {
	state: "c" | "f";
	toggleTemperature(): void;
}>(null);

export function TemperatureSwitch({ children }: { children: React.ReactNode }) {
	const [temperature, setTemperature] = useState<"c" | "f">("c");
	const toggleTemperature = useCallback(() => {
		setTemperature((temperature) => (temperature === "c" ? "f" : "c"));
	}, []);

	return (
		<temperatureContext.Provider
			value={{ state: temperature, toggleTemperature }}
		>
			{children}
		</temperatureContext.Provider>
	);
}

export function TemperatureToggle() {
	const context = useContext(temperatureContext);
	if (!context) throw new Error("No temperature context found");

	const { state, toggleTemperature } = context;

	return (
		<button type="button" onClick={toggleTemperature}>
			Switch to {state === "c" ? "Fahrenheit" : "Celsius"}
		</button>
	);
}

export function TemperatureDisplay({ c, f }: { c: number; f: number }) {
	const context = useContext(temperatureContext);
	if (!context) throw new Error("No temperature context found");

	const { state } = context;

	return (
		<span>
			{state === "c" ? c : f}
			{state === "c" ? "°C" : "°F"}
		</span>
	);
}


================================================
FILE: examples/basic/package.json
================================================
{
  "name": "@example/basic",
  "version": "1.0.0",
  "scripts": {
    "build": "remix build",
    "start": "concurrently \"npm:start:*\"",
    "start:server": "node --no-warnings --loader tsm --conditions=react-server ./server.mts",
    "start:ssr": "node --no-warnings --loader tsm  ./ssr-server.mts"
  },
  "dependencies": {
    "@hono/node-server": "^1.4.0",
    "hono": "^3.12.0",
    "react": "0.0.0-experimental-1d5667a12-20240102",
    "react-dom": "0.0.0-experimental-1d5667a12-20240102"
  },
  "devDependencies": {
    "@types/node": "^20.10.6",
    "@types/react": "^18.2.46",
    "@types/react-dom": "^18.2.18",
    "concurrently": "^8.2.2",
    "framework": "workspace:*",
    "tsm": "^2.3.0"
  }
}


================================================
FILE: examples/basic/server.mts
================================================
import { serve } from "@hono/node-server";
import { serveStatic } from "@hono/node-server/serve-static";
import { Hono } from "hono";
import { cors } from "hono/cors";

import { handler } from "./dist/server/main.js";

const app = new Hono();

app.use(
	"/dist/browser/*",
	cors({ origin: "*", allowMethods: ["HEAD", "GET"] }),
	serveStatic(),
);
app.use("/dist/ssr/*", serveStatic());

app.all("*", async (c) => {
	return handler(c.req.raw);
});

serve(
	{
		...app,
		port: 3001,
	},
	(info) => {
		console.log(`RSC listening on http://localhost:${info.port}`);
	},
);


================================================
FILE: examples/basic/ssr-server.mts
================================================
import dns from "node:dns";

import { serve } from "@hono/node-server";
import { Hono } from "hono";

import { handler } from "./dist/ssr/main.js";

dns.setDefaultResultOrder("ipv4first");

const app = new Hono();

app.use("*", (c) => {
	return handler(c.req.raw, "http://localhost:3001", [
		"http://localhost:3001/dist/browser/main.js",
	]);
});

serve(
	{
		...app,
		port: 3000,
	},
	(info) => {
		console.log(`SSR listening on http://localhost:${info.port}`);
	},
);


================================================
FILE: examples/basic/tsconfig.json
================================================
{
  "exclude": ["node_modules", "dist"],
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "target": "ES2022",
    "lib": ["DOM", "ES2022"],
    "types": ["node", "react/experimental", "react-dom/experimental"],
    "jsx": "react-jsx",
    "allowImportingTsExtensions": true,
    "strict": true,
    "allowJs": true,
    "checkJs": true,
    "noEmit": true,
    "rootDir": "."
  }
}


================================================
FILE: examples/consumer/app/components/counter.tsx
================================================
"use client";

import * as React from "react";

function CounterConsumer() {
	const [count, setCount] = React.useState(0);
	return (
		<div>
			<p>Consumer count: {count}</p>
			<button type="button" onClick={() => setCount(count - 1)}>
				Decrement
			</button>
			<button type="button" onClick={() => setCount(count + 1)}>
				Increment
			</button>
		</div>
	);
}

export { CounterConsumer as Counter };


================================================
FILE: examples/consumer/app/routes/_public/route.tsx
================================================
import { RSCFrame } from "framework";

export function Component({ children }: { children: React.ReactNode }) {
	return (
		<RSCFrame url="http://localhost:3001/layout">
			<div style={{ backgroundColor: "yellow", padding: "1rem" }}>
				<ul>
					<li>Pink = Remote</li>
					<li>Yellow = Host</li>
				</ul>
				{children}
			</div>
		</RSCFrame>
	);
}


================================================
FILE: examples/consumer/app/routes/_public._index/route.tsx
================================================
import { RSCFrame } from "framework";

import { Counter } from "../../components/counter";

export function Component() {
	return (
		<>
			<h1>Hello Index</h1>
			<Counter />
			<div style={{ backgroundColor: "yellow", padding: "1rem" }}>
				<RSCFrame url="http://localhost:3001/weather/seattle">
					<div style={{ backgroundColor: "yellow", padding: "1rem" }}>
						<RSCFrame url="http://localhost:3001/weather/portland" />
					</div>
				</RSCFrame>
			</div>
		</>
	);
}


================================================
FILE: examples/consumer/app/routes/_public.about/route.tsx
================================================
import { Counter } from "../../components/counter";

export function Component({ children }: { children: React.ReactNode }) {
	return (
		<>
			<h1>Hello About</h1>
			<Counter />
			{children}
		</>
	);
}


================================================
FILE: examples/consumer/app/routes/_public.about.$slug/route.tsx
================================================
export function Component() {
	return <h2>Hello About Slug</h2>;
}


================================================
FILE: examples/consumer/package.json
================================================
{
  "name": "@example/consumer",
  "version": "1.0.0",
  "scripts": {
    "build": "remix build",
    "start": "concurrently \"npm:start:*\"",
    "start:server": "node --no-warnings --loader tsm --conditions=react-server ./server.mts",
    "start:ssr": "node --no-warnings --loader tsm  ./ssr-server.mts"
  },
  "dependencies": {
    "@hono/node-server": "^1.4.0",
    "hono": "^3.12.0",
    "react": "0.0.0-experimental-1d5667a12-20240102",
    "react-dom": "0.0.0-experimental-1d5667a12-20240102"
  },
  "devDependencies": {
    "@module-federation/enhanced": "0.0.8",
    "@types/node": "^20.10.6",
    "@types/react": "^18.2.46",
    "@types/react-dom": "^18.2.18",
    "concurrently": "^8.2.2",
    "framework": "workspace:*",
    "tsm": "^2.3.0"
  }
}


================================================
FILE: examples/consumer/server.mts
================================================
import dns from "node:dns";

import { serve } from "@hono/node-server";
import { serveStatic } from "@hono/node-server/serve-static";
import { Hono } from "hono";
import { cors } from "hono/cors";

import { handler } from "./dist/server/main.js";

dns.setDefaultResultOrder("ipv4first");

const app = new Hono();

app.use(
	"/dist/browser/*",
	cors({ origin: "*", allowMethods: ["HEAD", "GET"] }),
	serveStatic(),
);

app.all("*", async (c) => {
	return handler(c.req.raw);
});

serve(
	{
		...app,
		port: 4001,
	},
	(info) => {
		console.log(`RSC listening on http://localhost:${info.port}`);
	},
);


================================================
FILE: examples/consumer/ssr-server.mts
================================================
import dns from "node:dns";

import { serve } from "@hono/node-server";
import { Hono } from "hono";

import { handler } from "./dist/ssr/main.js";

dns.setDefaultResultOrder("ipv4first");

const app = new Hono();

app.use("/", (c) => {
	return handler(c.req.raw, "http://localhost:4001", [
		"http://localhost:4001/dist/browser/main.js",
	]);
});
app.use("/about/*", (c) => {
	return handler(c.req.raw, "http://localhost:4001", [
		"http://localhost:4001/dist/browser/main.js",
	]);
});

app.use("*", (c) => {
	return handler(c.req.raw, "http://localhost:3001", [
		"http://localhost:4001/dist/browser/main.js",
	]);
});

serve(
	{
		...app,
		port: 4000,
	},
	(info) => {
		console.log(`SSR listening on http://localhost:${info.port}`);
	},
);


================================================
FILE: examples/consumer/tsconfig.json
================================================
{
  "exclude": ["node_modules", "dist"],
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "target": "ES2022",
    "lib": ["DOM", "ES2022"],
    "types": ["node", "react/experimental", "react-dom/experimental"],
    "jsx": "react-jsx",
    "allowImportingTsExtensions": true,
    "strict": true,
    "allowJs": true,
    "checkJs": true,
    "noEmit": true,
    "rootDir": "."
  }
}


================================================
FILE: examples/consumer/webpack.config.cjs
================================================
const { ModuleFederationPlugin } = require("@module-federation/enhanced");

/** @type {import("framework/webpack").ConfigFunction} */
module.exports = (config, { build, webpack }) => {
	if (!config.plugins) {
		config.plugins = [];
	}

	switch (build) {
		case "browser":
			config.plugins.push(
				new ModuleFederationPlugin({
					remotes: {
						_example_basic:
							"_example_basic@http://localhost:3001/dist/browser/_example_basic.js",
					},
				}),
			);
			break;
		case "ssr":
			config.plugins.push(
				new ModuleFederationPlugin({
					remotes: {
						_example_basic:
							"commonjs ../../../basic/dist/ssr/_example_basic.js",
					},
				}),
			);
			break;
	}

	return config;
};


================================================
FILE: fixture/marketing/app/components/ui/avatar.tsx
================================================
"use client";

import * as AvatarPrimitive from "@radix-ui/react-avatar";
import * as React from "react";

import { cn } from "@/lib/utils";

const Avatar = ({
	className,
	...props
}: React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>) => (
	<AvatarPrimitive.Root
		className={cn(
			"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
			className,
		)}
		{...props}
	/>
);
Avatar.displayName = AvatarPrimitive.Root.displayName;

const AvatarImage = ({
	className,
	...props
}: React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>) => (
	<AvatarPrimitive.Image
		className={cn("aspect-square h-full w-full", className)}
		{...props}
	/>
);
AvatarImage.displayName = AvatarPrimitive.Image.displayName;

const AvatarFallback = ({
	className,
	...props
}: React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>) => (
	<AvatarPrimitive.Fallback
		className={cn(
			"flex h-full w-full items-center justify-center rounded-full bg-muted",
			className,
		)}
		{...props}
	/>
);
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName;

export { Avatar, AvatarFallback, AvatarImage };


================================================
FILE: fixture/marketing/app/components/ui/button.tsx
================================================
import { Slot } from "@radix-ui/react-slot";
import { type VariantProps, cva } from "class-variance-authority";
import * as React from "react";

import { cn } from "@/lib/utils";

const buttonVariants = cva(
	"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
	{
		variants: {
			variant: {
				default: "bg-primary text-primary-foreground hover:bg-primary/90",
				destructive:
					"bg-destructive text-destructive-foreground hover:bg-destructive/90",
				outline:
					"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
				secondary:
					"bg-secondary text-secondary-foreground hover:bg-secondary/80",
				ghost: "hover:bg-accent hover:text-accent-foreground",
				link: "text-primary underline-offset-4 hover:underline",
			},
			size: {
				default: "h-10 px-4 py-2",
				sm: "h-9 rounded-md px-3",
				lg: "h-11 rounded-md px-8",
				icon: "h-10 w-10",
			},
			disabled: {
				false: "",
				true: "opacity-50 pointer-events-none",
			},
		},
		defaultVariants: {
			disabled: false,
			variant: "default",
			size: "default",
		},
	},
);

export interface ButtonProps
	extends React.ButtonHTMLAttributes<HTMLButtonElement>,
		Omit<VariantProps<typeof buttonVariants>, "disabled"> {
	asChild?: boolean;
}

const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
	({ className, variant, size, asChild = false, disabled, ...props }, ref) => {
		const Comp = asChild ? Slot : "button";
		return (
			<Comp
				className={cn(buttonVariants({ variant, size, className, disabled }))}
				ref={ref}
				disabled={disabled}
				{...props}
			/>
		);
	},
);
Button.displayName = "Button";

export { Button, buttonVariants };


================================================
FILE: fixture/marketing/app/components/ui/card.tsx
================================================
import * as React from "react";

import { cn } from "@/lib/utils";

const Card = React.forwardRef<
	HTMLDivElement,
	React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
	<div
		ref={ref}
		className={cn(
			"rounded-lg border bg-card text-card-foreground shadow-sm",
			className,
		)}
		{...props}
	/>
));
Card.displayName = "Card";

const CardHeader = React.forwardRef<
	HTMLDivElement,
	React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
	<div
		ref={ref}
		className={cn("flex flex-col space-y-1.5 p-6", className)}
		{...props}
	/>
));
CardHeader.displayName = "CardHeader";

const CardTitle = React.forwardRef<
	HTMLParagraphElement,
	React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
	<h3
		ref={ref}
		className={cn(
			"text-2xl font-semibold leading-none tracking-tight",
			className,
		)}
		{...props}
	/>
));
CardTitle.displayName = "CardTitle";

const CardDescription = React.forwardRef<
	HTMLParagraphElement,
	React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
	<p
		ref={ref}
		className={cn("text-sm text-muted-foreground", className)}
		{...props}
	/>
));
CardDescription.displayName = "CardDescription";

const CardContent = React.forwardRef<
	HTMLDivElement,
	React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
	<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
));
CardContent.displayName = "CardContent";

const CardFooter = React.forwardRef<
	HTMLDivElement,
	React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
	<div
		ref={ref}
		className={cn("flex items-center p-6 pt-0", className)}
		{...props}
	/>
));
CardFooter.displayName = "CardFooter";

export {
	Card,
	CardHeader,
	CardFooter,
	CardTitle,
	CardDescription,
	CardContent,
};


================================================
FILE: fixture/marketing/app/components/ui/input.tsx
================================================
import * as React from "react";

import { cn } from "@/lib/utils";

export interface InputProps
	extends React.InputHTMLAttributes<HTMLInputElement> {}

const Input = React.forwardRef<HTMLInputElement, InputProps>(
	({ className, type, ...props }, ref) => {
		return (
			<input
				type={type}
				className={cn(
					"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
					className,
				)}
				ref={ref}
				{...props}
			/>
		);
	},
);
Input.displayName = "Input";

export { Input };


================================================
FILE: fixture/marketing/app/components/ui/separator.tsx
================================================
"use client";

import * as SeparatorPrimitive from "@radix-ui/react-separator";
import * as React from "react";

import { cn } from "@/lib/utils";

const Separator = React.forwardRef<
	React.ElementRef<typeof SeparatorPrimitive.Root>,
	React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(
	(
		{ className, orientation = "horizontal", decorative = true, ...props },
		ref,
	) => (
		<SeparatorPrimitive.Root
			ref={ref}
			decorative={decorative}
			orientation={orientation}
			className={cn(
				"shrink-0 bg-border",
				orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
				className,
			)}
			{...props}
		/>
	),
);
Separator.displayName = SeparatorPrimitive.Root.displayName;

export { Separator };


================================================
FILE: fixture/marketing/app/lib/utils.ts
================================================
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
	return twMerge(clsx(inputs));
}


================================================
FILE: fixture/marketing/app/remotes.tsx
================================================
import { RSCFrame } from "framework";

declare global {
	// biome-ignore lint/style/noVar: <explanation>
	var __REMOTES__: Record<string, string>;
}

const REMOTES = __REMOTES__;

export function FederatedRSCFrame({
	children,
	remote,
	url,
}: {
	children?: React.ReactNode;
	remote: string;
	url: string;
}) {
	const baseURL = REMOTES[remote];
	if (!baseURL) throw new Error(`No remote found for ${remote}`);

	const inputURL = new URL(url, baseURL);
	const frameURL = new URL(inputURL.pathname + inputURL.search, baseURL);

	return <RSCFrame url={frameURL}>{children}</RSCFrame>;
}


================================================
FILE: fixture/marketing/app/routes/_public/route.tsx
================================================
import { Link, getURL } from "framework";

import { FederatedRSCFrame } from "../../remotes";

import styleFile from "./style.css";

export function Component({ children }: { children?: React.ReactNode }) {
	const url = getURL();

	const styleHref = new URL(`/dist/server/${styleFile}`, url).href;

	const toRender = (
		<>
			<Link rel="stylesheet" href={styleHref} />
			{children}
		</>
	);

	if (url.searchParams.get("noshell")) {
		return toRender;
	}

	return (
		<FederatedRSCFrame remote="_fixture_shell" url="/api/shell">
			{toRender}
		</FederatedRSCFrame>
	);
}


================================================
FILE: fixture/marketing/app/routes/_public/style.css
================================================
@tailwind components;
@tailwind utilities;


================================================
FILE: fixture/marketing/app/routes/_public._index/products.tsx
================================================
import {
	Card,
	CardContent,
	CardDescription,
	CardFooter,
	CardHeader,
	CardTitle,
} from "@/components/ui/card";

export function ProductList({
	children,
	description,
	title,
}: {
	children: React.ReactNode;
	description?: string;
	title?: string;
}) {
	return (
		<section className="w-full py-12 md:py-24 lg:py-32">
			<div className="container grid items-center justify-center gap-4 text-center">
				<div className="grid gap-12">
					{(title || description) && (
						<div className="grid gap-2">
							{title && (
								<h2 className="text-2xl font-bold tracking-tighter">{title}</h2>
							)}
							{description && (
								<p className="text-gray-500 dark:text-gray-400 max-w-lg mx-auto">
									{description}
								</p>
							)}
						</div>
					)}
					<div className="grid sm:grid-cols-2 md:grid-cols-3 gap-8">
						{children}
					</div>
				</div>
			</div>
		</section>
	);
}

export function ProductCard({
	description,
	handle,
	image,
	price,
	title,
}: {
	description?: string;
	handle: string;
	image: string;
	price: { amount: string; currencyCode: string };
	title: string;
}) {
	return (
		<Card className="relative flex flex-col">
			<a className="absolute inset-0 z-10" href={`/product/${handle}`}>
				<span className="sr-only">View {title}</span>
			</a>
			<img
				loading="lazy"
				alt=""
				aria-hidden
				className="object-cover w-full aspect-square group-hover:opacity-50 transition-opacity"
				height={600}
				src={`${image}&width=400`}
				width={450}
			/>
			<CardHeader>
				<CardTitle>{title}</CardTitle>
			</CardHeader>
			{description && (
				<CardContent>
					<CardDescription>{truncate(description, 100)}</CardDescription>
				</CardContent>
			)}
			<CardFooter className="mt-auto">
				<span className="inline-flex items-center gap-1">
					<span>${price.amount}</span>
					<span>{price.currencyCode}</span>
				</span>
			</CardFooter>
		</Card>
	);
}

function truncate(str: string, n: number) {
	return str.length > n ? `${str.slice(0, n - 1)}...` : str;
}


================================================
FILE: fixture/marketing/app/routes/_public._index/route.tsx
================================================
import { ProductCard, ProductList } from "./products";

export async function Component() {
	const url = new URL("https://mock.shop/api");
	url.searchParams.set("query", query);
	const request = await fetch(url);
	const response = await request.json();

	if (!response.data) {
		throw new Error("No data");
	}

	return (
		<ProductList
			title={response.data.collection.title}
			description={response.data.collection.description}
		>
			{response.data.collection.products.edges.map(
				// biome-ignore lint/suspicious/noExplicitAny: <explanation>
				({ node }: { node: any }) => (
					<ProductCard
						key={node.handle}
						handle={node.handle}
						title={node.title}
						description={node.description}
						image={node.featuredImage.url}
						price={node.priceRange.minVariantPrice}
					/>
				),
			)}
		</ProductList>
	);
}

const query = `{
	collection(id: "gid://shopify/Collection/429512622102") {
		id
		handle
		title
		description
		products(first: 20) {
			edges {
				node {
					handle
					title
					description
					featuredImage {
						url
					}
					priceRange {
						minVariantPrice {
							amount
							currencyCode
						}
					}
				}
			}
		}
	}
}`;


================================================
FILE: fixture/marketing/app/routes/_public.product.$handle/actions.tsx
================================================
export async function addToCart() {
	"use server";
	console.log("Adding to cart!");
	await new Promise((resolve) => setTimeout(resolve, 1000));
	console.log("Added to cart!");

	return "Added to cart!";
}


================================================
FILE: fixture/marketing/app/routes/_public.product.$handle/client.tsx
================================================
"use client";

import { useLocation } from "framework/client";
import * as React from "react";
import { useFormStatus } from "react-dom";

import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

export function AddToCartButton({
	disabled: _disabled,
}: { disabled?: boolean }) {
	const location = useLocation();
	const formStatus = useFormStatus();

	const diabled =
		_disabled ||
		formStatus.pending ||
		(location.state !== "idle" &&
			location.to.pathname === location.url.pathname);

	return (
		<Button size="lg" disabled={diabled}>
			Add to cart
		</Button>
	);
}

export function Option({
	option,
	pathname,
}: {
	option: {
		id: string;
		name: string;
		values: string[];
	};
	pathname: string;
}) {
	const location = useLocation();

	const selectedOptions = new URLSearchParams(
		location.state === "transitioning" &&
			location.url.pathname === location.to.pathname
			? location.to.search
			: location.url.search,
	);

	const selectedValue = selectedOptions.get(option.name);

	return (
		<div>
			<p className="text-lg">{option.name}</p>
			<div className="flex flex-wrap gap-2">
				{option.values.map((value) => {
					const searchParams = new URLSearchParams(selectedOptions);
					searchParams.set(option.name, value);
					return (
						<Button
							asChild
							key={value}
							size="sm"
							variant={value === selectedValue ? "default" : "outline"}
						>
							<a href={`${pathname}?${searchParams.toString()}`}>{value}</a>
						</Button>
					);
				})}
			</div>
		</div>
	);
}

export function ProductImages({
	images,
}: {
	images: {
		id: string;
		url: string;
		altText: string;
	}[];
}) {
	const [selectedImage, setSelectedImage] = React.useState(images[0]);

	return (
		<>
			<div className="hidden flex-col gap-3 items-start md:flex relative">
				{images.map((image, index) => (
					<button
						key={image.id}
						type="button"
						className={cn(
							"overflow-hidden rounded-lg border-2 p-0.5 transition-colors w-full",
							{
								"border-secondary": image.id !== selectedImage.id,
							},
						)}
						onClick={() => setSelectedImage(image)}
					>
						<img
							loading="lazy"
							alt={image.altText}
							className="aspect-[5/6] object-cover w-full"
							src={`${image.url}&width=160`}
						/>
						<span className="sr-only">View Image {index + 1}</span>
					</button>
				))}
			</div>
			<div className="md:col-span-4">
				<img
					key={selectedImage.id}
					alt="Product"
					className="aspect-[2/3] object-cover border w-full rounded-lg overflow-hidden"
					src={`${selectedImage.url}&width=600`}
				/>
			</div>
		</>
	);
}


================================================
FILE: fixture/marketing/app/routes/_public.product.$handle/form.tsx
================================================
import { getURL } from "framework";

import { Input } from "@/components/ui/input";

import { addToCart } from "./actions";
import { AddToCartButton, Option } from "./client";

export function AddToCartForm({
	message,
	options,
	selectedVariantId,
}: {
	message?: React.ReactNode;
	options: {
		id: string;
		name: string;
		values: string[];
	}[];
	selectedVariantId?: string;
}) {
	const url = getURL();

	return (
		<form action={addToCart} className="grid gap-4 md:gap-10">
			{options.map((option) => {
				return (
					<Option key={option.id} option={option} pathname={url.pathname} />
				);
			})}

			<div className="grid gap-2">
				<p className="text-lg">Quantity</p>
				<Input
					id="quantity"
					name="quantity"
					type="number"
					min={0}
					max={255}
					defaultValue={1}
				/>
			</div>

			<AddToCartButton disabled={!selectedVariantId} />

			{message}
		</form>
	);
}


================================================
FILE: fixture/marketing/app/routes/_public.product.$handle/product.tsx
================================================
export function ProductHeader({
	title,
	description,
	priceRange,
}: {
	title: string;
	description?: string;
	priceRange: {
		maxVariantPrice: {
			amount: string;
		};
		minVariantPrice: {
			amount: string;
			currencyCode: string;
		};
	};
}) {
	let price = <span>${priceRange.minVariantPrice.amount}</span>;
	if (priceRange.maxVariantPrice.amount !== priceRange.minVariantPrice.amount) {
		price = (
			<span>
				{price} - <span>{priceRange.maxVariantPrice.amount}</span>
			</span>
		);
	}
	price = (
		<span>
			{price} <small>{priceRange.minVariantPrice.currencyCode}</small>
		</span>
	);

	return (
		<div className="flex items-start">
			<div className="grid gap-4">
				<h1 className="text-3xl font-bold lg:text-4xl">{title}</h1>
				<div>
					<p>{description}</p>
				</div>
			</div>
			<div className="ml-auto text-2xl font-bold">$99</div>
		</div>
	);
}


================================================
FILE: fixture/marketing/app/routes/_public.product.$handle/reviews.tsx
================================================
import { StarIcon } from "@radix-ui/react-icons";

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Separator } from "@/components/ui/separator";

export function ProductReviews() {
	return (
		<div className="grid gap-4">
			<h2 className="text-lg font-semibold">Product Reviews</h2>
			<div className="grid gap-4">
				<div className="flex gap-4 items-start">
					<Avatar className="w-10 h-10 border">
						<AvatarImage alt="@shadcn" src="/placeholder-user.jpg" />
						<AvatarFallback>CN</AvatarFallback>
					</Avatar>
					<div className="grid gap-4">
						<div className="flex gap-4 items-start">
							<div className="grid gap-0.5 text-sm">
								<h3 className="font-semibold">Sarah Johnson</h3>
								<time className="text-sm text-gray-500 dark:text-gray-400">
									2 days ago
								</time>
							</div>
							<div className="flex items-center gap-0.5 ml-auto">
								<StarIcon className="w-5 h-5 fill-primary" />
								<StarIcon className="w-5 h-5 fill-primary" />
								<StarIcon className="w-5 h-5 fill-primary" />
								<StarIcon className="w-5 h-5 fill-muted stroke-muted-foreground" />
								<StarIcon className="w-5 h-5 fill-muted stroke-muted-foreground" />
							</div>
						</div>
						<div className="text-sm leading-loose text-gray-500 dark:text-gray-400">
							<p>
								I've been experimenting with my LuminaCook Multi-Function Air
								Fryer for a few weeks now, and it's been a versatile addition to
								my kitchen. It's great for making crispy fries, chicken wings,
								and even some healthier options.
							</p>
						</div>
					</div>
				</div>
				<Separator />
				<div className="flex gap-4 items-start">
					<Avatar className="w-10 h-10 border">
						<AvatarImage alt="@shadcn" src="/placeholder-user.jpg" />
						<AvatarFallback>CN</AvatarFallback>
					</Avatar>
					<div className="grid gap-4">
						<div className="flex gap-4 items-start">
							<div className="grid gap-0.5 text-sm">
								<h3 className="font-semibold">Alex Smith</h3>
								<time className="text-sm text-gray-500 dark:text-gray-400">
									3 weeks ago
								</time>
							</div>
							<div className="flex items-center gap-0.5 ml-auto">
								<StarIcon className="w-5 h-5 fill-primary" />
								<StarIcon className="w-5 h-5 fill-primary" />
								<StarIcon className="w-5 h-5 fill-primary" />
								<StarIcon className="w-5 h-5 fill-muted stroke-muted-foreground" />
								<StarIcon className="w-5 h-5 fill-muted stroke-muted-foreground" />
							</div>
						</div>
						<div className="text-sm leading-loose text-gray-500 dark:text-gray-400">
							<p>
								I recently purchased the SparkleShine Home Cleaning Robot, and
								it has been a game-changer in my life. I used to spend hours
								every weekend cleaning my house, but now I can simply turn on
								this little robot and let it do the work. It's incredibly
								efficient, navigating around obstacles with ease. The only
								reason I didn't give it a perfect 5-star rating is that it
								occasionally gets stuck under low furniture. Overall, it's been
								a great addition to my home, saving me time and effort.
							</p>
						</div>
					</div>
				</div>
				<Separator />
				<div className="flex gap-4 items-start">
					<Avatar className="w-10 h-10 border">
						<AvatarImage alt="@shadcn" src="/placeholder-user.jpg" />
						<AvatarFallback>CN</AvatarFallback>
					</Avatar>
					<div className="grid gap-4">
						<div className="flex gap-4 items-start">
							<div className="grid gap-0.5 text-sm">
								<h3 className="font-semibold">Emily Parker</h3>
								<time className="text-sm text-gray-500 dark:text-gray-400">
									2 days ago
								</time>
							</div>
							<div className="flex items-center gap-0.5 ml-auto">
								<StarIcon className="w-5 h-5 fill-primary" />
								<StarIcon className="w-5 h-5 fill-primary" />
								<StarIcon className="w-5 h-5 fill-muted stroke-muted-foreground" />
								<StarIcon className="w-5 h-5 fill-muted stroke-muted-foreground" />
								<StarIcon className="w-5 h-5 fill-muted stroke-muted-foreground" />
							</div>
						</div>
						<div className="text-sm leading-loose text-gray-500 dark:text-gray-400">
							<p>
								The battery life is impressive, lasting me for long-haul flights
								without any issues. They are comfortable to wear for extended
								periods, and I appreciate the sleek design. Worth every penny,
								and I'd recommend these headphones to anyone who values
								high-quality audio and peace and quiet.
							</p>
						</div>
					</div>
				</div>
			</div>
		</div>
	);
}


================================================
FILE: fixture/marketing/app/routes/_public.product.$handle/route.tsx
================================================
import { getActionResult, getURL } from "framework";
import { type RouteProps } from "framework";

import { Separator } from "@/components/ui/separator";

import { addToCart } from "./actions";
import { ProductImages } from "./client";
import { AddToCartForm } from "./form";
import { ProductHeader } from "./product";
import { ProductReviews } from "./reviews";

export async function Component({ params: { handle } }: RouteProps<"handle">) {
	const addToCartResult = getActionResult(addToCart);
	const url = getURL();

	const selectedOptions: { name: string; value: string }[] = [];
	for (const [name, value] of url.searchParams) {
		if (name[0].toLocaleLowerCase() === name[0]) continue;
		selectedOptions.push({ name, value });
	}

	const variables = {
		handle,
		selectedOptions,
	};
	const apiURL = new URL("https://mock.shop/api");
	apiURL.searchParams.set("query", query);
	apiURL.searchParams.set("variables", JSON.stringify(variables));
	const request = await fetch(apiURL);
	const response = await request.json();

	const product = response.data?.product;
	if (!product) {
		throw new Error("No product");
	}

	const header = (
		<ProductHeader
			title={product.title}
			description={product.description}
			priceRange={product.priceRange}
		/>
	);

	return (
		<div className="container grid gap-6 items-start py-6 md:grid-cols-2 lg:gap-12">
			<div className="grid gap-3 items-start md:grid-cols-5">
				<div className="md:hidden">{header}</div>
				<ProductImages
					images={product.images.edges.map(
						(edge: {
							node: {
								id: string;
								url: string;
								altText: string;
							};
						}) => edge.node,
					)}
				/>
			</div>
			<div className="grid gap-4 items-start md:gap-10">
				<div className="hidden md:block">{header}</div>
				<AddToCartForm
					options={product.options}
					message={
						<div key={Date.now()} className="opacity-0 block animate-fade">
							{!addToCartResult ? (
								<>&nbsp;</>
							) : "error" in addToCartResult ? (
								"Failed to add to cart"
							) : (
								"Added to cart"
							)}
						</div>
					}
					selectedVariantId={product.variantBySelectedOptions?.id}
				/>
				<Separator />
				<ProductReviews />
			</div>
		</div>
	);
}

const query = `
  query Product($handle: String, $selectedOptions: [SelectedOptionInput!]!) {
    product(handle: $handle) {
      id
      title
      description
      featuredImage {
        id
        url
      }
      priceRange {
        maxVariantPrice {
          amount
        }
        minVariantPrice {
          amount
          currencyCode
        }
      }
      images(first: 10) {
        edges {
          node {
            id
            url
            altText
          }
        }
      }
      variantBySelectedOptions(selectedOptions: $selectedOptions) {
        id
      }
      variants(first: 250) {
        edges {
          node {
            id
            price {
              amount
              currencyCode
            }
            image {
              id
              url
              altText
            }
          }
        }
      }
      options {
        id
        name
        values
      }
    }
  }
`;


================================================
FILE: fixture/marketing/components.json
================================================
{
	"$schema": "https://ui.shadcn.com/schema.json",
	"style": "new-york",
	"rsc": true,
	"tsx": true,
	"tailwind": {
		"config": "tailwind.config.ts",
		"css": "app/globals.css",
		"baseColor": "slate",
		"cssVariables": true
	},
	"aliases": {
		"components": "@/components",
		"utils": "@/lib/utils"
	}
}


================================================
FILE: fixture/marketing/modules.d.ts
================================================
declare module "*.css" {
	const href: string;
	export default href;
}


================================================
FILE: fixture/marketing/package.json
================================================
{
  "name": "@fixture/marketing",
  "version": "1.0.0",
  "bundler": {
    "include": []
  },
  "scripts": {
    "build": "remix build",
    "start": "concurrently \"npm:start:*\"",
    "start:server": "node --no-warnings --loader tsm --conditions=react-server ./server.mts",
    "start:ssr": "node --no-warnings --loader tsm  ./ssr-server.mts"
  },
  "dependencies": {
    "@hono/node-server": "^1.4.0",
    "@radix-ui/react-avatar": "^1.0.4",
    "@radix-ui/react-icons": "^1.3.0",
    "@radix-ui/react-label": "^2.0.2",
    "@radix-ui/react-radio-group": "^1.1.3",
    "@radix-ui/react-select": "^2.0.0",
    "@radix-ui/react-separator": "^1.0.3",
    "@radix-ui/react-slot": "^1.0.2",
    "class-variance-authority": "^0.7.0",
    "clsx": "^2.1.0",
    "hono": "^3.12.0",
    "react": "0.0.0-experimental-1d5667a12-20240102",
    "react-dom": "0.0.0-experimental-1d5667a12-20240102",
    "tailwind-merge": "^2.2.0"
  },
  "devDependencies": {
    "@module-federation/enhanced": "0.0.8",
    "@types/node": "^20.10.6",
    "@types/react": "^18.2.46",
    "@types/react-dom": "^18.2.18",
    "concurrently": "^8.2.2",
    "framework": "workspace:*",
    "postcss": "^8.4.33",
    "postcss-loader": "^7.3.4",
    "postcss-preset-env": "^9.3.0",
    "tailwindcss": "^3.4.1",
    "tsconfig-paths-webpack-plugin": "^4.1.0",
    "tsm": "^2.3.0",
    "webpack": "^5.89.0"
  }
}


================================================
FILE: fixture/marketing/postcss.config.cjs
================================================
module.exports = {
	plugins: [require("postcss-preset-env"), require("tailwindcss")],
};


================================================
FILE: fixture/marketing/remotes.cjs
================================================
exports.REMOTES = {
	_fixture_shell: {
		require: "../../../shell/dist/ssr/_fixture_shell.js",
		rsc: "http://localhost:3001/",
		url: "http://localhost:3001/dist/browser/_fixture_shell.js",
	},
};


================================================
FILE: fixture/marketing/server.mts
================================================
import * as dns from "node:dns";

import { serve } from "@hono/node-server";
import { serveStatic } from "@hono/node-server/serve-static";
import { Hono } from "hono";
import { compress } from "hono/compress";
import { cors } from "hono/cors";

import { handler } from "./dist/server/main.js";

dns.setDefaultResultOrder("ipv4first");

const app = new Hono();

app.use(
	"/dist/server/*.css",
	cors({ origin: "*", allowMethods: ["HEAD", "GET"] }),
	compress(),
	// artificial delay to simulate network latency
	async (c, next) => {
		await new Promise((r) => setTimeout(r, 100));
		next();
	},
	serveStatic(),
);
app.use(
	"/dist/browser/*",
	cors({ origin: "*", allowMethods: ["HEAD", "GET"] }),
	compress(),
	serveStatic(),
);
app.use("/dist/ssr/*", serveStatic());

app.all("*", async (c) => {
	return handler(c.req.raw);
});

serve(
	{
		...app,
		port: 4001,
	},
	(info) => {
		console.log(`RSC listening on http://localhost:${info.port}`);
	},
);


================================================
FILE: fixture/marketing/ssr-server.mts
================================================
import dns from "node:dns";

import { serve } from "@hono/node-server";
import { Hono } from "hono";

import { handler } from "./dist/ssr/main.js";

dns.setDefaultResultOrder("ipv4first");

const app = new Hono();

app.use("*", (c) => {
	return handler(c.req.raw, "http://localhost:4001", [
		"http://localhost:4001/dist/browser/main.js",
	]);
});

serve(
	{
		...app,
		port: 4000,
	},
	(info) => {
		console.log(`SSR listening on http://localhost:${info.port}`);
	},
);


================================================
FILE: fixture/marketing/tailwind.config.cjs
================================================
/**
 * @type {import('tailwindcss').Config}
 */
module.exports = {
	content: ["./app/**/*.tsx"],
	darkMode: "media",
	theme: {
		container: {
			center: true,
			padding: "2rem",
			screens: {
				"2xl": "1400px",
			},
		},
		extend: {
			colors: {
				border: "hsl(var(--border))",
				input: "hsl(var(--input))",
				ring: "hsl(var(--ring))",
				background: "hsl(var(--background))",
				foreground: "hsl(var(--foreground))",
				primary: {
					DEFAULT: "hsl(var(--primary))",
					foreground: "hsl(var(--primary-foreground))",
				},
				secondary: {
					DEFAULT: "hsl(var(--secondary))",
					foreground: "hsl(var(--secondary-foreground))",
				},
				destructive: {
					DEFAULT: "hsl(var(--destructive))",
					foreground: "hsl(var(--destructive-foreground))",
				},
				muted: {
					DEFAULT: "hsl(var(--muted))",
					foreground: "hsl(var(--muted-foreground))",
				},
				accent: {
					DEFAULT: "hsl(var(--accent))",
					foreground: "hsl(var(--accent-foreground))",
				},
				popover: {
					DEFAULT: "hsl(var(--popover))",
					foreground: "hsl(var(--popover-foreground))",
				},
				card: {
					DEFAULT: "hsl(var(--card))",
					foreground: "hsl(var(--card-foreground))",
				},
			},
			borderRadius: {
				lg: "var(--radius)",
				md: "calc(var(--radius) - 2px)",
				sm: "calc(var(--radius) - 4px)",
			},
			keyframes: {
				"accordion-down": {
					from: { height: "0" },
					to: { height: "var(--radix-accordion-content-height)" },
				},
				"accordion-up": {
					from: { height: "var(--radix-accordion-content-height)" },
					to: { height: "0" },
				},
				fadeOut: {
					"0%": { opacity: "1" },
					"75%": { opacity: "1" },
					"100%": { opacity: "0" },
				},
				progress: {
					"0%": { transform: " translateX(0) scaleX(0)" },
					"40%": { transform: "translateX(0) scaleX(0.4)" },
					"100%": { transform: "translateX(100%) scaleX(0.5)" },
				},
			},
			animation: {
				"accordion-down": "accordion-down 0.2s ease-out",
				"accordion-up": "accordion-up 0.2s ease-out",
				fade: "fadeOut 5s ease-in-out",
				progress: "progress 1s infinite linear",
			},
			transformOrigin: {
				"left-right": "0% 50%",
			},
		},
	},
	plugins: [require("tailwindcss-animate"), require("@tailwindcss/typography")],
};


================================================
FILE: fixture/marketing/tsconfig.json
================================================
{
	"exclude": ["node_modules", "dist"],
	"compilerOptions": {
		"module": "ESNext",
		"moduleResolution": "Bundler",
		"target": "ES2022",
		"lib": ["DOM", "ES2022"],
		"types": ["node", "react/experimental", "react-dom/experimental"],
		"jsx": "react-jsx",
		"allowImportingTsExtensions": true,
		"strict": true,
		"allowJs": true,
		"checkJs": true,
		"noEmit": true,
		"rootDir": ".",
		"baseUrl": ".",
		"paths": {
			"@/*": ["./app/*"]
		}
	}
}


================================================
FILE: fixture/marketing/webpack.config.cjs
================================================
const { ModuleFederationPlugin } = require("@module-federation/enhanced");
const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");

const pkgJson = require("./package.json");
const { REMOTES } = require("./remotes.cjs");

/** @type {import("framework/webpack").ConfigFunction} */
module.exports = (config, { build, webpack }) => {
	config.plugins = config.plugins || [];
	config.resolve = config.resolve || {};
	config.resolve.plugins = config.resolve.plugins || [];
	config.resolve.plugins.push(new TsconfigPathsPlugin());

	switch (build) {
		case "server":
			config.module = config.module || {};
			config.module.rules = config.module.rules || [];
			config.module.rules.push({
				test: /\.css$/,
				exclude: /node_modules/,
				type: "asset/resource",
				use: [require.resolve("postcss-loader")],
			});

			config.plugins.push(
				new webpack.DefinePlugin({
					__REMOTES__: JSON.stringify(
						Object.entries(REMOTES).reduce(
							(acc, [name, remote]) => {
								acc[name] = remote.rsc;
								return acc;
							},
							/** @type {Record<string, string>} */ ({}),
						),
					),
				}),
			);
			break;
		case "browser":
			config.plugins.push(
				new ModuleFederationPlugin({
					remoteType: "script",
					remotes: Object.entries(REMOTES).reduce(
						(acc, [name, remote]) => {
							acc[name] = `${name}@${remote.url}`;
							return acc;
						},
						/** @type {Record<string, string>} */ ({}),
					),
					shared: {
						react: {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						"react/": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						"react-dom": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						"react-dom/": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						framework: { singleton: true, version: "1.0.0" },
						"framework/": { singleton: true, version: "1.0.0" },
						"react-server-dom-webpack/": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
					},
					runtimePlugins: [
						require.resolve("framework/webpack.federation-runtime-plugin"),
					],
				}),
			);
			break;
		case "ssr":
			config.plugins.push(
				new ModuleFederationPlugin({
					remoteType: "commonjs",
					remotes: Object.entries(REMOTES).reduce(
						(acc, [name, remote]) => {
							acc[name] = `commonjs ${remote.require}`;
							return acc;
						},
						/** @type {Record<string, string>} */ ({}),
					),
					shared: {
						react: {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						"react/": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						"react-dom": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						"react-dom/": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						framework: { singleton: true, version: "1.0.0" },
						"framework/": { singleton: true, version: "1.0.0" },
						"react-server-dom-webpack/": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
					},
					runtimePlugins: [
						require.resolve("framework/webpack.federation-runtime-plugin"),
					],
				}),
			);
			break;
	}

	return config;
};


================================================
FILE: fixture/shell/app/components/ui/button.tsx
================================================
import { Slot } from "@radix-ui/react-slot";
import { type VariantProps, cva } from "class-variance-authority";
import * as React from "react";

import { cn } from "@/lib/utils";

const buttonVariants = cva(
	"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors disabled:pointer-events-none disabled:opacity-50",
	{
		variants: {
			variant: {
				default:
					"bg-primary text-primary-foreground shadow hover:bg-primary/90",
				destructive:
					"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
				outline:
					"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
				secondary:
					"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
				ghost: "hover:bg-accent hover:text-accent-foreground",
				link: "text-primary underline-offset-4 hover:underline",
			},
			size: {
				default: "h-9 px-4 py-2",
				sm: "h-8 rounded-md px-3 text-xs",
				lg: "h-10 rounded-md px-8",
				icon: "h-9 w-9",
			},
		},
		defaultVariants: {
			variant: "default",
			size: "default",
		},
	},
);

export interface ButtonProps
	extends React.ButtonHTMLAttributes<HTMLButtonElement>,
		VariantProps<typeof buttonVariants> {
	asChild?: boolean;
}

const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
	({ className, variant, size, asChild = false, ...props }, ref) => {
		const Comp = asChild ? Slot : "button";
		return (
			<Comp
				className={cn(buttonVariants({ variant, size, className }))}
				ref={ref}
				{...props}
			/>
		);
	},
);
Button.displayName = "Button";

export { Button, buttonVariants };


================================================
FILE: fixture/shell/app/lib/utils.ts
================================================
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
	return twMerge(clsx(inputs));
}


================================================
FILE: fixture/shell/app/remotes.tsx
================================================
import { RSCFrame } from "framework";

declare global {
	// biome-ignore lint/style/noVar: <explanation>
	var __REMOTES__: Record<string, string>;
}

const REMOTES = __REMOTES__;

export function FederatedRSCFrame({
	children,
	remote,
	url,
}: {
	children?: React.ReactNode;
	remote: string;
	url: string;
}) {
	const baseURL = REMOTES[remote];
	if (!baseURL) throw new Error(`No remote found for ${remote}`);

	const inputURL = new URL(url, baseURL);
	const frameURL = new URL(inputURL.pathname + inputURL.search, baseURL);
	frameURL.searchParams.append("noshell", "1");

	return <RSCFrame url={frameURL}>{children}</RSCFrame>;
}


================================================
FILE: fixture/shell/app/routes/_public/client.tsx
================================================
"use client";

import { useLocation } from "framework/client";

import { cn } from "@/lib/utils";

export function GlobalStatusIndicator() {
	const location = useLocation();
	const active = location.state === "transitioning";

	return (
		<div
			// biome-ignore lint/a11y/useAriaPropsForRole: <explanation>
			role="progressbar"
			aria-hidden={!active}
			aria-valuetext={active ? "Loading" : undefined}
			className="fixed inset-x-0 top-0 z-50 h-1 animate-pulse"
		>
			<div
				className={cn(
					"h-full bg-gradient-to-r from-primary to-secondary transition-all duration-500 ease-in-out",
					active ? "w-full" : "w-0 opacity-0 transition-none",
				)}
			/>
		</div>
	);
}


================================================
FILE: fixture/shell/app/routes/_public/header.tsx
================================================
import { Button } from "@/components/ui/button";

export function Header() {
	return (
		<header className="w-full">
			<div className="container flex items-center justify-between py-4">
				<div className="flex items-center gap-4">
					<Button asChild variant="outline" size="icon">
						<a href="/">
							<img
								alt="Logo"
								className="h-8 w-auto"
								src="https://remix.run/favicon-32.png"
								width={32}
								height={32}
							/>
						</a>
					</Button>
					<nav className="flex gap-2">
						<Button asChild variant="link" size="sm">
							<a href="/shop">Shop</a>
						</Button>
						<Button asChild variant="link" size="sm">
							<a href="/about">About</a>
						</Button>
						<Button asChild variant="link" size="sm">
							<a href="/contact">Contact</a>
						</Button>
					</nav>
				</div>
				<div className="flex items-center gap-2">
					<Button variant="outline" size="icon">
						<span className="sr-only">Open Cart</span>
						<svg
							xmlns="http://www.w3.org/2000/svg"
							fill="none"
							viewBox="0 0 24 24"
							strokeWidth={1.5}
							stroke="currentColor"
							className="w-4 h-4"
						>
							<title>Cart</title>
							<path
								strokeLinecap="round"
								strokeLinejoin="round"
								d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 0 0-3 3h15.75m-12.75-3h11.218c1.121-2.3 2.1-4.684 2.924-7.138a60.114 60.114 0 0 0-16.536-1.84M7.5 14.25 5.106 5.272M6 20.25a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Zm12.75 0a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Z"
							/>
						</svg>
					</Button>
				</div>
			</div>
		</header>
	);
}


================================================
FILE: fixture/shell/app/routes/_public/route.tsx
================================================
import { Link, getHeaders, getURL } from "framework";

import { GlobalStatusIndicator } from "./client";
import { Header } from "./header";
import styleFile from "./style.css";

export function Component({ children }: { children: React.ReactNode }) {
	const headers = getHeaders();
	const url = getURL();

	const styleHref = new URL(`/dist/server/${styleFile}`, url).href;

	const renderedForHost = headers.get("X-Forwarded-For-Host") || url.host;

	return (
		<html lang="en" className="bg-background text-foreground">
			<head>
				<meta charSet="utf-8" />
				<meta name="viewport" content="width=device-width, initial-scale=1" />
				<title>YAY!</title>
				<Link rel="stylesheet" href={styleHref} />
			</head>
			<body className="bg-background text-foreground">
				<GlobalStatusIndicator />
				<Header />
				{children}
				<footer>
					<p>
						Header rendered from {url.host} for {renderedForHost}
					</p>
				</footer>
			</body>
		</html>
	);
}


================================================
FILE: fixture/shell/app/routes/_public/style.css
================================================
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  :root {
    --background: 0 0% 100%;
    --foreground: 240 10% 3.9%;
    --card: 0 0% 100%;
    --card-foreground: 240 10% 3.9%;
    --popover: 0 0% 100%;
    --popover-foreground: 240 10% 3.9%;
    --primary: 240 5.9% 10%;
    --primary-foreground: 0 0% 98%;
    --secondary: 240 4.8% 95.9%;
    --secondary-foreground: 240 5.9% 10%;
    --muted: 240 4.8% 95.9%;
    --muted-foreground: 240 3.8% 46.1%;
    --accent: 240 4.8% 95.9%;
    --accent-foreground: 240 5.9% 10%;
    --destructive: 0 84.2% 60.2%;
    --destructive-foreground: 0 0% 98%;
    --border: 240 5.9% 90%;
    --input: 240 5.9% 90%;
    --ring: 240 5.9% 10%;
    --radius: 0.3rem;
  }

  @media (prefers-color-scheme: dark) {
    :root {
      --background: 240 10% 3.9%;
      --foreground: 0 0% 98%;
      --card: 240 10% 3.9%;
      --card-foreground: 0 0% 98%;
      --popover: 240 10% 3.9%;
      --popover-foreground: 0 0% 98%;
      --primary: 0 0% 98%;
      --primary-foreground: 240 5.9% 10%;
      --secondary: 240 3.7% 15.9%;
      --secondary-foreground: 0 0% 98%;
      --muted: 240 3.7% 15.9%;
      --muted-foreground: 240 5% 64.9%;
      --accent: 240 3.7% 15.9%;
      --accent-foreground: 0 0% 98%;
      --destructive: 0 62.8% 30.6%;
      --destructive-foreground: 0 0% 98%;
      --border: 240 3.7% 15.9%;
      --input: 240 3.7% 15.9%;
      --ring: 240 4.9% 83.9%;
    }
  }
}


================================================
FILE: fixture/shell/app/routes/_public.$/route.tsx
================================================
export async function Component() {
	return (
		<section className="w-full py-12 md:py-24 lg:py-32">
			<div className="container text-center">
				<div className="flex items-center pt-8">
					<div className="px-4 text-lg text-muted-foreground border-r border-border tracking-wider">
						404
					</div>
					<div className="ml-4 text-lg text-muted-foreground uppercase tracking-wider">
						Not Found
					</div>
				</div>
			</div>
		</section>
	);
}


================================================
FILE: fixture/shell/app/routes/_public._index/route.tsx
================================================
import { FederatedRSCFrame } from "../../remotes";

export async function Component() {
	return <FederatedRSCFrame remote="_fixture_marketing" url="/" />;
}


================================================
FILE: fixture/shell/app/routes/_public.product.$handle/route.tsx
================================================
import { type RouteProps } from "framework";
import { getURL } from "framework";

import { FederatedRSCFrame } from "../../remotes";

export async function Component({ params: { handle } }: RouteProps<"handle">) {
	const url = getURL();

	return (
		<FederatedRSCFrame
			remote="_fixture_marketing"
			url={`/product/${handle}${url.search}`}
		/>
	);
}


================================================
FILE: fixture/shell/app/routes/api.shell/route.tsx
================================================
export { Component } from "../_public/route";


================================================
FILE: fixture/shell/components.json
================================================
{
	"$schema": "https://ui.shadcn.com/schema.json",
	"style": "new-york",
	"rsc": true,
	"tsx": true,
	"tailwind": {
		"config": "tailwind.config.ts",
		"css": "app/globals.css",
		"baseColor": "slate",
		"cssVariables": true
	},
	"aliases": {
		"components": "@/components",
		"utils": "@/lib/utils"
	}
}


================================================
FILE: fixture/shell/modules.d.ts
================================================
declare module "*.css" {
	const href: string;
	export default href;
}


================================================
FILE: fixture/shell/package.json
================================================
{
  "name": "@fixture/shell",
  "version": "1.0.0",
  "scripts": {
    "build": "remix build",
    "start": "concurrently \"npm:start:*\"",
    "start:server": "node --no-warnings --loader tsm --conditions=react-server ./server.mts",
    "start:ssr": "node --no-warnings --loader tsm  ./ssr-server.mts"
  },
  "dependencies": {
    "@hono/node-server": "^1.4.0",
    "@radix-ui/react-slot": "^1.0.2",
    "class-variance-authority": "^0.7.0",
    "clsx": "^2.1.0",
    "hono": "^3.12.0",
    "react": "0.0.0-experimental-1d5667a12-20240102",
    "react-dom": "0.0.0-experimental-1d5667a12-20240102",
    "tailwind-merge": "^2.2.0"
  },
  "devDependencies": {
    "@module-federation/enhanced": "0.0.8",
    "@tailwindcss/typography": "^0.5.10",
    "@types/node": "^20.10.6",
    "@types/react": "^18.2.46",
    "@types/react-dom": "^18.2.18",
    "concurrently": "^8.2.2",
    "framework": "workspace:*",
    "postcss": "^8.4.33",
    "postcss-loader": "^7.3.4",
    "postcss-preset-env": "^9.3.0",
    "tailwindcss": "^3.4.1",
    "tailwindcss-animate": "^1.0.7",
    "tsconfig-paths-webpack-plugin": "^4.1.0",
    "tsm": "^2.3.0",
    "webpack": "^5.89.0"
  }
}


================================================
FILE: fixture/shell/postcss.config.cjs
================================================
module.exports = {
	plugins: [require("postcss-preset-env"), require("tailwindcss")],
};


================================================
FILE: fixture/shell/remotes.cjs
================================================
exports.REMOTES = {
	_fixture_marketing: {
		require: "../../../marketing/dist/ssr/_fixture_marketing.js",
		rsc: "http://localhost:4001/",
		url: "http://localhost:4001/dist/browser/_fixture_marketing.js",
	},
};


================================================
FILE: fixture/shell/server.mts
================================================
import * as dns from "node:dns";

import { serve } from "@hono/node-server";
import { serveStatic } from "@hono/node-server/serve-static";
import { Hono } from "hono";
import { compress } from "hono/compress";
import { cors } from "hono/cors";

import { handler } from "./dist/server/main.js";

dns.setDefaultResultOrder("ipv4first");

const app = new Hono();

app.use(
	"/dist/server/*.css",
	cors({ origin: "*", allowMethods: ["HEAD", "GET"] }),
	compress(),
	serveStatic(),
);
app.use(
	"/dist/browser/*",
	cors({ origin: "*", allowMethods: ["HEAD", "GET"] }),
	compress(),
	serveStatic(),
);
app.use("/dist/ssr/*", serveStatic());

app.all("*", async (c) => {
	return handler(c.req.raw);
});

serve(
	{
		...app,
		port: 3001,
	},
	(info) => {
		console.log(`RSC listening on http://localhost:${info.port}`);
	},
);


================================================
FILE: fixture/shell/ssr-server.mts
================================================
import dns from "node:dns";

import { serve } from "@hono/node-server";
import { Hono } from "hono";

import { handler } from "./dist/ssr/main.js";

dns.setDefaultResultOrder("ipv4first");

const app = new Hono();

app.use("*", (c) => {
	return handler(
		c.req.raw,
		"http://localhost:3001",
		["http://localhost:3001/dist/browser/main.js"],
		{
			_fixture_marketing: "http://localhost:4001",
		},
	);
});

serve(
	{
		...app,
		port: 3000,
	},
	(info) => {
		console.log(`SSR listening on http://localhost:${info.port}`);
	},
);


================================================
FILE: fixture/shell/tailwind.config.cjs
================================================
/**
 * @type {import('tailwindcss').Config}
 */
module.exports = {
	content: ["./app/**/*.tsx"],
	darkMode: "media",
	theme: {
		container: {
			center: true,
			padding: "2rem",
			screens: {
				"2xl": "1400px",
			},
		},
		extend: {
			colors: {
				border: "hsl(var(--border))",
				input: "hsl(var(--input))",
				ring: "hsl(var(--ring))",
				background: "hsl(var(--background))",
				foreground: "hsl(var(--foreground))",
				primary: {
					DEFAULT: "hsl(var(--primary))",
					foreground: "hsl(var(--primary-foreground))",
				},
				secondary: {
					DEFAULT: "hsl(var(--secondary))",
					foreground: "hsl(var(--secondary-foreground))",
				},
				destructive: {
					DEFAULT: "hsl(var(--destructive))",
					foreground: "hsl(var(--destructive-foreground))",
				},
				muted: {
					DEFAULT: "hsl(var(--muted))",
					foreground: "hsl(var(--muted-foreground))",
				},
				accent: {
					DEFAULT: "hsl(var(--accent))",
					foreground: "hsl(var(--accent-foreground))",
				},
				popover: {
					DEFAULT: "hsl(var(--popover))",
					foreground: "hsl(var(--popover-foreground))",
				},
				card: {
					DEFAULT: "hsl(var(--card))",
					foreground: "hsl(var(--card-foreground))",
				},
			},
			borderRadius: {
				lg: "var(--radius)",
				md: "calc(var(--radius) - 2px)",
				sm: "calc(var(--radius) - 4px)",
			},
			keyframes: {
				"accordion-down": {
					from: { height: "0" },
					to: { height: "var(--radix-accordion-content-height)" },
				},
				"accordion-up": {
					from: { height: "var(--radix-accordion-content-height)" },
					to: { height: "0" },
				},
				progress: {
					"0%": { transform: " translateX(0) scaleX(0)" },
					"40%": { transform: "translateX(0) scaleX(0.4)" },
					"100%": { transform: "translateX(100%) scaleX(0.5)" },
				},
			},
			animation: {
				"accordion-down": "accordion-down 0.2s ease-out",
				"accordion-up": "accordion-up 0.2s ease-out",
				progress: "progress 1s infinite linear",
			},
			transformOrigin: {
				"left-right": "0% 50%",
			},
		},
	},
	plugins: [require("tailwindcss-animate"), require("@tailwindcss/typography")],
};


================================================
FILE: fixture/shell/tsconfig.json
================================================
{
  "include": ["**/*.mts", "**/*.ts", "**/*.tsx", "**/*.mjs", "**/*.cjs"],
  "exclude": ["node_modules", "dist"],
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "target": "ES2022",
    "lib": ["DOM", "ES2022"],
    "types": ["node", "react/experimental", "react-dom/experimental"],
    "jsx": "react-jsx",
    "allowImportingTsExtensions": true,
    "strict": true,
    "allowJs": true,
    "checkJs": true,
    "noEmit": true,
    "rootDir": ".",
    "baseUrl": ".",
    "paths": {
      "@/*": ["./app/*"]
    }
  }
}


================================================
FILE: fixture/shell/webpack.config.cjs
================================================
const { ModuleFederationPlugin } = require("@module-federation/enhanced");
const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");

const pkgJson = require("./package.json");
const { REMOTES } = require("./remotes.cjs");

/** @type {import("framework/webpack").ConfigFunction} */
module.exports = (config, { build, webpack }) => {
	config.plugins = config.plugins || [];
	config.resolve = config.resolve || {};
	config.resolve.plugins = config.resolve.plugins || [];
	config.resolve.plugins.push(new TsconfigPathsPlugin());

	switch (build) {
		case "server":
			config.module = config.module || {};
			config.module.rules = config.module.rules || [];
			config.module.rules.push({
				test: /\.css$/,
				exclude: /node_modules/,
				type: "asset/resource",
				use: [require.resolve("postcss-loader")],
			});

			config.plugins.push(
				new webpack.DefinePlugin({
					__REMOTES__: JSON.stringify(
						Object.entries(REMOTES).reduce(
							(acc, [name, remote]) => {
								acc[name] = remote.rsc;
								return acc;
							},
							/** @type {Record<string, string>} */ ({}),
						),
					),
				}),
			);
			break;
		case "browser":
			config.plugins.push(
				new ModuleFederationPlugin({
					remoteType: "script",
					remotes: Object.entries(REMOTES).reduce(
						(acc, [name, remote]) => {
							acc[name] = `${name}@${remote.url}`;
							return acc;
						},
						/** @type {Record<string, string>} */ ({}),
					),
					shared: {
						react: {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						"react/": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						"react-dom": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						"react-dom/": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						framework: { singleton: true, version: "1.0.0" },
						"framework/": { singleton: true, version: "1.0.0" },
						"react-server-dom-webpack/": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
					},
					runtimePlugins: [
						require.resolve("framework/webpack.federation-runtime-plugin"),
					],
				}),
			);
			break;
		case "ssr":
			config.plugins.push(
				new ModuleFederationPlugin({
					remoteType: "commonjs",
					remotes: Object.entries(REMOTES).reduce(
						(acc, [name, remote]) => {
							acc[name] = `commonjs ${remote.require}`;
							return acc;
						},
						/** @type {Record<string, string>} */ ({}),
					),
					shared: {
						react: {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						"react/": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						"react-dom": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						"react-dom/": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
						framework: { singleton: true, version: "1.0.0" },
						"framework/": { singleton: true, version: "1.0.0" },
						"react-server-dom-webpack/": {
							singleton: true,
							version: "0.0.0-experimental-1d5667a12-20240102",
						},
					},
					runtimePlugins: [
						require.resolve("framework/webpack.federation-runtime-plugin"),
					],
				}),
			);
			break;
	}

	return config;
};


================================================
FILE: framework/bin/remix.cjs
================================================
#!/usr/bin/env node

import("../cli/build.mjs")
	.then(({ build }) => build())
	.catch((reason) => {
		if (process.env.DEBUG) {
			console.error(reason);
		}
		process.exit(1);
	});


================================================
FILE: framework/cli/build.mjs
================================================
import * as path from "node:path";

import webpack from "webpack";
// @ts-expect-error
import { formatMessages } from "webpack-format-messages";

import { getWebpackConfig } from "framework/webpack";

export async function build() {
	const cwd = process.cwd();
	const mode =
		process.env.NODE_ENV === "development" ? "development" : "production";

	const clientModules = new Set();
	const serverModules = new Set();
	console.log("🧩 building server bundle...");
	await runWebpack(
		await getWebpackConfig("server", {
			clientModules,
			cwd,
			mode,
			serverModules,
		}),
	);

	const clientModulesArray = Array.from(clientModules);
	console.log(`\nℹ client modules in container: ${clientModulesArray.length}`);
	if (process.env.DEBUG) {
		for (const clientModule of clientModules) {
			console.log(`  - file://${path.relative(cwd, clientModule)}`);
		}
	}
	console.log();

	console.log("🧩 building ssr bundle...");
	console.log("🧩 building browser bundle...");
	console.log();
	await Promise.all([
		runWebpack(
			await getWebpackConfig("ssr", {
				clientModules,
				cwd,
				mode,
				serverModules,
			}),
		),
		runWebpack(
			await getWebpackConfig("browser", {
				clientModules,
				cwd,
				mode,
				serverModules,
			}),
		),
	]);
	console.log();

	console.log("🧩 building server actions bundle...");
	await runWebpack(
		await getWebpackConfig("server-actions", {
			clientModules,
			cwd,
			mode,
			serverModules,
		}),
	);

	const serverModulesArray = Array.from(serverModules);
	console.log(`\nℹ server modules in container: ${serverModulesArray.length}`);
	if (process.env.DEBUG) {
		for (const serverModule of serverModules) {
			console.log(`  - file://${path.relative(cwd, serverModule)}`);
		}
	}
}

/**
 * @param {webpack.Configuration & { name: "server" | "ssr" | "browser" }} config
 * @returns
 */
function runWebpack(config) {
	console.time(`🎉 built ${config.name} bundle in`);
	const endTimer = startTimer();
	return new Promise((resolve, reject) => {
		webpack(config, (err, stats) => {
			if (err) {
				return reject(err);
			}
			if (!stats) {
				return reject(new Error("no stats returned from webpack"));
			}
			const messages = formatMessages(stats);

			const errorsOrWarnings =
				!!messages.errors.length || !!messages.warnings.length;

			if (errorsOrWarnings) console.log("\n\n");
			if (messages.errors.length) {
				for (const e of messages.errors) {
					console.log(e);
				}
				console.log("\n\n");
				return reject(new Error(`${config.name} build failed`));
			}

			if (messages.warnings.length) {
				for (const e of messages.warnings) {
					console.log(e);
				}
			}
			if (errorsOrWarnings) console.log("\n\n");
			resolve(stats);
		});
	})
		.then((stats) => {
			endTimer(`🎉 built ${config.name} bundle in`);
			return stats;
		})
		.catch((err) => {
			endTimer(`❌ built ${config.name} bundle in`);
			throw err;
		});
}

function startTimer() {
	const start = process.hrtime.bigint();
	/**
	 * @param {string} msg
	 */
	return (msg) => {
		const end = process.hrtime.bigint();
		console.log(`${msg} ${(end - start) / 1000000n}ms`);
	};
}


================================================
FILE: framework/entry/browser.tsx
================================================
// @ts-expect-error - no types
import RSDC from "react-server-dom-webpack/client";

import { hydrate } from "framework/browser";

window.callServer = async function callServer(id, args) {
	const body = await RSDC.encodeReply(args);
	const headerName =
		typeof args[0] === "object" &&
		args.length === 1 &&
		args[0] instanceof FormData
			? "Form-Action"
			: "RSC-Action";

	const fetchPromise = fetch(window.location.href, {
		body: body,
		headers: {
			Accept: "text/x-component",
			[headerName]: id,
		},
		method: "POST",
	});

	let response = RSDC.createFromFetch(fetchPromise, {
		callServer: (id: string, args: unknown[]) => window.callServer(id, args),
	});

	if (headerName === "Form-Action") {
		window.setLocation?.(({ url }) => ({
			root: response,
			url,
		}));
		return undefined;
	}

	response = await response;

	if (response.error) {
		throw response.error;
	}

	return response.result;
};

hydrate();


================================================
FILE: framework/entry/empty.tsx
================================================


================================================
FILE: framework/entry/server.tsx
================================================
import { createRequestHandler } from "framework/server";

import { routes } from "#routes";

export const handler = createRequestHandler(routes);


================================================
FILE: framework/entry/ssr.tsx
================================================
import * as stream from "node:stream";
import type * as streamWeb from "node:stream/web";

import * as React from "react";
import RDS from "react-dom/server";
// @ts-expect-error - no types
import RSD from "react-server-dom-webpack/client";

import { INTERNAL_Location } from "framework/client";
import { InlinePayload } from "framework/ssr";

export async function handler(
	request: Request,
	serverOrigin: string,
	bootstrapScripts: string[],
	remotes?: Record<string, string>,
) {
	const url = new URL(request.url);
	const serverUrl = new URL(url.pathname + url.search, serverOrigin);

	const headers = new Headers(request.headers);
	headers.set("Accept", "text/x-component");
	headers.delete("host");
	headers.set(
		"X-Forwarded-For-Host",
		request.headers.get("X-Forwarded-For-Host") ??
			request.headers.get("host") ??
			"",
	);

	const actionId = request.headers.get("RSC-Action");
	if (actionId) {
		const remote = actionId.split(":")[0].slice("rsc/remote/server/".length);
		if (remotes?.[remote]) {
			return fetch(new URL(url.pathname + url.search, remotes[remote]), {
				body: request.body,
				headers,
				method: request.method,
				signal: request.signal,
				// @ts-expect-error - no types
				duplex: "half",
				window: null,
			});
		}
	}

	const response = await fetch(serverUrl, {
		body: request.body,
		headers,
		method: request.method,
		signal: request.signal,
		// @ts-expect-error - no types
		duplex: "half",
		window: null,
	});

	if (request.headers.get("Accept")?.match(/\btext\/x-component\b/)) {
		return response;
	}

	const isComponentResponse = response.headers
		.get("Content-Type")
		?.match(/\btext\/x-component\b/);

	if (!isComponentResponse || !response.body) {
		return new Response(
			isComponentResponse ? "No body found in response" : response.statusText,
			{
				status: isComponentResponse ? 500 : response.status,
				headers: {
					"Content-Type": "text/plain; charset=utf-8",
					Vary: "Accept",
				},
			},
		);
	}

	const [payloadA, payloadB] = response.body.tee();

	const root = RSD.createFromNodeStream(
		stream.Readable.fromWeb(payloadA as streamWeb.ReadableStream<Uint8Array>),
		{
			moduleMap: new Proxy(
				{},
				{
					get(_, id) {
						return new Proxy(
							{},
							{
								get(_, key) {
									return {
										id,
										name: key,
										chunks: [String(id).split("#")[0]],
									};
								},
							},
						);
					},
				},
			),
			moduleLoading: new Proxy(
				{},
				{
					get(_, key) {
						throw new Error("Not implemented");
					},
				},
			),
		},
	);

	return new Promise((resolve, reject) => {
		let shellSent = false;
		const { pipe, abort } = RDS.renderToPipeableStream(
			<>
				<INTERNAL_Location initialRoot={root} initialURL={url} />
				<React.Suspense>
					<InlinePayload readable={payloadB.getReader()} />
				</React.Suspense>
			</>,
			{
				bootstrapScripts,
				onShellReady() {
					shellSent = true;
					resolve(
						new Response(
							stream.Readable.toWeb(
								pipe(new stream.PassThrough()),
							) as ReadableStream<Uint8Array>,
							{
								status: response.status,
								headers: {
									"Content-Type": "text/html; charset=utf-8",
									"Transfer-Encoding": "chunked",
									Vary: "Accept",
								},
							},
						),
					);
				},
				onShellError(error) {
					if (!shellSent) {
						reject(error);
					}
				},
				onError(error) {
					if (shellSent || request.signal.aborted) return;
					console.error(error);
				},
			},
		);
		request.signal.addEventListener("abort", abort, { once: true });
	});
}


================================================
FILE: framework/lib/framework.browser.tsx
================================================
import * as React from "react";
import { hydrateRoot } from "react-dom/client";
// @ts-expect-error - no types
import RSD from "react-server-dom-webpack/client";

import {
	INTERNAL_Location,
	type INTERNAL_LocationState,
} from "framework/client";

declare global {
	// biome-ignore lint/style/noVar: <explanation>
	var __RSC__: {
		stream: ReadableStream<Uint8Array>;
	};
	interface Window {
		setLocation: (
			setter: (
				previousLocation: INTERNAL_LocationState,
			) => INTERNAL_LocationState,
		) => void;
	}
}

export function hydrate() {
	if (typeof __RSC__ !== "undefined") {
		hydrateInternal();
		return;
	}
	addEventListener("rscready", hydrateInternal, { once: true });
}

let abortController: AbortController | undefined;

async function hydrateInternal() {
	addEventListener("click", (event) => {
		if (!window.setLocation || event.defaultPrevented) return;

		let target = event.target as HTMLAnchorElement | null;
		if (target?.tagName !== "A") {
			target = target?.closest("a") ?? null;
		}

		if (target?.tagName === "A") {
			const href = target.getAttribute("href");
			if (href?.startsWith("/") && target.getAttribute("target") !== "_self") {
				window.history.pushState({}, "", href);
				const url = new URL(href, window.location.href);
				const newAbortController = new AbortController();
				const fetchPromise = fetch(href, {
					headers: {
						Accept: "text/x-component",
					},
					signal: newAbortController.signal,
				});
				window.setLocation(() => ({
					root: RSD.createFromFetch(fetchPromise, {
						callServer: window.callServer,
					}) as React.Usable<React.ReactElement>,
					url,
				}));
				// TODO: Abort controller in component to avoid aborting it when it's still mounted.
				abortController?.abort();
				abortController = newAbortController;
				event.preventDefault();
			}
		}
	});

	addEventListener("popstate", (event) => {
		if (!window.setLocation) {
			window.location.reload();
			return;
		}

		const url = new URL(window.location.href);
		const newAbortController = new AbortController();
		const fetchPromise = fetch(url.pathname, {
			headers: {
				Accept: "text/x-component",
			},
			signal: newAbortController.signal,
		});
		window.setLocation(() => ({
			root: RSD.createFromFetch(fetchPromise, {
				callServer: window.callServer,
			}) as React.Usable<React.ReactElement>,
			url,
		}));
		abortController?.abort();
		abortController = newAbortController;
		event.preventDefault();
	});

	addEventListener("submit", (event) => {
		if (!window.setLocation || event.defaultPrevented) return;

		const target = event.target as HTMLFormElement;
		const submitter = event.submitter;
		if (target.tagName !== "FORM") {
			return;
		}
		let action = target.getAttribute("action");
		if (submitter?.hasAttribute("formaction")) {
			action = submitter.getAttribute("formaction");
		}
		if (!action?.startsWith("/")) {
			return;
		}

		let method = target.getAttribute("method");
		if (submitter?.hasAttribute("formmethod")) {
			method = submitter.getAttribute("formmethod");
		}
		if (!method) {
			method = "GET";
		} else {
			method = method.toUpperCase();
		}

		let searchParams: URLSearchParams | undefined;
		const formData = new FormData(target, submitter);
		if (method === "GET") {
			searchParams = new URLSearchParams();
			for (const [key, value] of formData) {
				if (typeof value !== "string") {
					throw new Error("Only string values are supported for GET requests");
				}
				searchParams.append(key, value);
			}
		}

		const url = new URL(action, window.location.href);
		if (method === "GET" && searchParams) {
			url.search = searchParams.toString();
		}

		const newAbortController = new AbortController();
		let body: BodyInit | undefined;
		if (!searchParams) {
			body = formData;
		}
		const fetchPromise = fetch(url.pathname + url.search, {
			method,
			body,
			headers: {
				Accept: "text/x-component",
			},
			signal: newAbortController.signal,
		});
		window.setLocation(() => ({
			root: RSD.createFromFetch(fetchPromise, {
				callServer: window.callServer,
			}) as React.Usable<React.ReactElement>,
			url,
		}));
		// TODO: Abort controller in component to avoid aborting it when it's still mounted.
		abortController?.abort();
		abortController = newAbortController;

		event.preventDefault();
	});

	const initialRoot = RSD.createFromReadableStream(__RSC__.stream, {
		callServer: window.callServer,
	}) as React.Usable<React.ReactElement>;
	const initialURL = new URL(window.location.href);

	React.startTransition(() => {
		hydrateRoot(
			document,
			<React.StrictMode>
				<INTERNAL_Location
					getSetLocation={(_setLocation) => {
						window.setLocation = _setLocation;
					}}
					initialRoot={initialRoot}
					initialURL={initialURL}
				/>
			</React.StrictMode>,
		);
	});
}


================================================
FILE: framework/lib/framework.client.internal.tsx
================================================
"use client";

import * as React from "react";

import {
	INTERNAL_Outlet,
	INTERNAL_OutletProvider,
	INTERNAL_StreamReader,
	Link as INTERNAL_Link,
	type PromiseStream,
	type PromiseStreamItem,
} from "framework/client";

const Outlet = INTERNAL_Outlet;
const OutletProvider = INTERNAL_OutletProvider;
const StreamReader = INTERNAL_StreamReader;
const Link = INTERNAL_Link;

export type { PromiseStream, PromiseStreamItem };
export {
	Outlet as INTERNAL_Outlet,
	OutletProvider as INTERNAL_OutletProvider,
	StreamReader as INTERNAL_StreamReader,
	Link,
};


================================================
FILE: framework/lib/framework.client.tsx
================================================
import * as React from "react";

import { createFromReadableStream } from "framework/react.client";

export type LocationState =
	| {
			state: "idle";
			url: URL;
	  }
	| {
			state: "transitioning";
			to: URL;
			url: URL;
	  };

const INTERNAL_locationContext = React.createContext<null | LocationState>(
	null,
);

function INTERNAL_LocationContextProvider({
	value,
	children,
}: React.ProviderProps<LocationState>) {
	return (
		<INTERNAL_locationContext.Provider value={value}>
			{children}
		</INTERNAL_locationContext.Provider>
	);
}

export interface INTERNAL_LocationState {
	root: React.Usable<React.ReactElement>;
	url: URL;
}

export function INTERNAL_Location({
	getSetLocation,
	initialRoot,
	initialURL,
}: {
	getSetLocation?: (
		setLocation: (
			setter: (location: INTERNAL_LocationState) => INTERNAL_LocationState,
		) => void,
	) => void;
	initialRoot: React.Usable<React.ReactElement>;
	initialURL: URL;
}) {
	// TODO: propagate state
	const [transitioning, startTransition] = React.useTransition();
	const [to, setTo] = React.useState<null | URL>(null);
	const [location, _setLocation] = React.useState<INTERNAL_LocationState>({
		root: initialRoot,
		url: initialURL,
	});
	React.useEffect(() => {
		if (getSetLocation) {
			getSetLocation((setter) => {
				const newLocation = setter(location);
				setTo(newLocation.url);
				startTransition(() => _setLocation(newLocation));
			});
		}
	}, [location, getSetLocation]);

	const locationState = React.useMemo<LocationState>(
		() =>
			transitioning && to
				? {
						state: "transitioning",
						to,
						url: location.url,
				  }
				: {
						state: "idle",
						url: location.url,
				  },
		[location.url, transitioning, to],
	);

	// return React.use(location.root);
	return (
		<INTERNAL_LocationContextProvider value={locationState}>
			{React.use(location.root) as React.JSX.Element}
		</INTERNAL_LocationContextProvider>
	);
}

const outletContext = React.createContext<null | Record<
	string,
	React.ReactNode
>>(null);

export function INTERNAL_Outlet({ id }: { id: string }) {
	const context = React.useContext(outletContext);
	if (!context) throw new Error("No router context found");
	return context[id] ?? null;
}

export interface INTERNAL_OutletProviderProps {
	children: React.ReactNode;
	outlets: Record<string, React.ReactNode>;
}

export function INTERNAL_OutletProvider({
	children,
	outlets,
}: INTERNAL_OutletProviderProps) {
	const parentOutlets = React.useContext(outletContext);
	return (
		<outletContext.Provider value={{ ...parentOutlets, ...outlets }}>
			{children}
		</outletContext.Provider>
	);
}

export type PromiseStreamItem<T> = null | { head: T; tail: PromiseStream<T> };
export type PromiseStream<T> = Promise<PromiseStreamItem<T>>;

export function INTERNAL_StreamReader({
	cache,
	children,
	promiseStream,
}: {
	cache: { current: null | Promise<React.JSX.Element> };
	children?: React.ReactNode;
	promiseStream: PromiseStream<string>;
}) {
	let current: Promise<React.JSX.Element>;
	if (cache.current) {
		current = cache.current;
	} else {
		current = cache.current = createFromReadableStream(
			fromPromiseStream(promiseStream).pipeThrough(
				new TransformStream({
					transform(chunk, controller) {
						// base64 string -> Uint8Array
						controller.enqueue(
							new Uint8Array(
								atob(chunk as string)
									.split("")
									.map((c) => c.charCodeAt(0)),
							),
						);
					},
				}),
			),
		);
	}

	const element = React.use(
		React.use<
			React.ReactElement<
				INTERNAL_OutletProviderProps,
				typeof INTERNAL_OutletProvider
			>
			// @ts-expect-error
		>(current)._payload,
		// biome-ignore lint/suspicious/noExplicitAny: <explanation>
	) as any;

	if (!element?.props?.outlets) throw new Error("No outlets found");

	return React.useMemo(() => {
		return (
			<INTERNAL_OutletProvider
				{...element.props}
				outlets={{
					...element.props.outlets,
					"!": children,
				}}
			/>
		);
	}, [element, children]);
}

function fromPromiseStream<T = unknown>(initialPromise: PromiseStream<T>) {
	let promise = initialPromise;
	return new ReadableStream<T>({
		async pull(controller) {
			const item = await promise;
			if (item) {
				controller.enqueue(item.head);
				promise = item.tail;
			} else {
				controller.close();
			}
		},
	});
}

export function useLocation() {
	const location = React.useContext(INTERNAL_locationContext);
	if (!location) throw new Error("No router context found");
	return location;
}

// TODO: Implement some ref counter or something to remove them from the DOM.
const loadLink = React.cache(
	(rel?: string, href?: string) =>
		new Promise<void>((resolve, reject) => {
			if (rel !== "stylesheet" || !href) return resolve();

			const link = document.createElement("link");
			link.onload = () => {
				resolve();
			};
			link.onerror = (_, __, ___, ____, error) => {
				reject(error);
			};
			link.setAttribute("rel", rel);
			link.setAttribute("href", href);
			document.head.appendChild(link);
		}),
);

export function Link(props: React.ComponentPropsWithoutRef<"link">) {
	const [_loadPromise, setLoadPromise] = React.useState<Promise<void> | null>(
		null,
	);
	let loadPromise = _loadPromise;
	if (typeof document !== "undefined" && !loadPromise) {
		loadPromise = loadLink(props.rel, props.href);
		setLoadPromise(loadPromise);
	}

	if (loadPromise) {
		React.use(loadPromise);
	}

	return <link {...props} />;
}


================================================
FILE: framework/lib/framework.runtime.client.ts
================================================
import { registerServerReference as registerServerReferenceImp } from "framework/react.client";

export function registerServerReference(
	proxy: unknown,
	mod: string,
	exp: string,
) {
	return registerServerReferenceImp(proxy, mod, exp);
}


================================================
FILE: framework/lib/framework.runtime.server.ts
================================================
import {
	registerClientReference as registerClientReferenceImp,
	registerServerReference as registerServerReferenceImp,
} from "framework/react.server";

export function registerClientReference(
	proxy: unknown,
	mod: string,
	exp: string,
) {
	registerClientReferenceImp(proxy, mod, exp);
	return proxy;
}

export function registerServerReference(
	proxy: unknown,
	mod: string,
	exp: string,
) {
	registerServerReferenceImp(proxy, mod, exp);
	return proxy;
}


================================================
FILE: framework/lib/framework.server.tsx
================================================
import {
	createStaticHandler,
	type AgnosticDataRouteObject,
} from "@remix-run/router";
import * as React from "react";
// @ts-expect-error - no types
import RSDS from "react-server-dom-webpack/server";

import {
	INTERNAL_SeverContextProvider,
	type ActionResult,
	type RouteProps,
} from "framework";
import { renderToReadableStream } from "framework/react.server";

import {
	INTERNAL_Outlet,
	INTERNAL_OutletProvider,
} from "framework/client.internal";

declare global {
	// biome-ignore lint/style/noVar: <explanation>
	var ___CONTAINER_NAME___: string;
}

export function createRequestHandler(routes: AgnosticDataRouteObject[]) {
	return async (request: Request) => {
		const handler = createStaticRequestHandler(routes);

		try {
			const context = await handler(request);

			if (context instanceof Response) {
				return context;
			}

			const body = renderToReadableStream(
				context.root,
				new Proxy(
					{},
					{
						get(_, prop, __) {
							const [id, ...rest] = String(prop).split("#");
							const name = rest.join("#");

							return {
								id,
								name,
								chunks: [id.split("#")[0]],
								async: true,
							};
						},
					},
				),
				{
					identifierPrefix: Date.now().toString(36),
					signal: request.signal,
					onError(error: Error) {
						if (request.signal.aborted) return;
						console.error(error);
					},
				},
			);

			return new Response(body, {
				status: context.status,
				headers: context.headers,
			});
		} catch (reason) {
			console.error(reason);
			return new Response("Internal Server Error", {
				status: 500,
				headers: {
					"Content-Type": "text/plain; charset=utf-8",
					Vary: "Accept",
				},
			});
		}
	};
}

export function createStaticRequestHandler(routes: AgnosticDataRouteObject[]) {
	const handler = createStaticHandler(routes, {
		future: { v7_relativeSplatPath: true },
	});

	return async (request: Request) => {
		const actionId = request.headers.get("RSC-Action");
		if (actionId) {
			const [moduleId, ...exportNameRest] = actionId.split("#");
			const exportName = exportNameRest.join("#");
			await __webpack_require__.e(moduleId);
			// @ts-expect-error
			const action = __webpack_require__(moduleId)[exportName];
			const body = request.headers
				.get("Content-Type")
				?.match(/\bmultipart\/form\-data\b/)
				? await request.formData()
				: await request.text();
			const reply = await RSDS.decodeReply(body, {});

			let actionResult: ActionResult;
			try {
				const result = await action(...reply);
				actionResult = { id: actionId, result };
			} catch (error) {
				actionResult = { id: actionId, error };
			}

			return {
				root: actionResult,
				status: "error" in actionResult ? 500 : 200,
				headers: new Headers({
					"Content-Type": "text/x-component; charset=utf-8",
					"Transfer-Encoding": "chunked",
					Vary: "Accept",
				}),
			};
		}

		const context = await handler.query(new Request(request.url));
		if (context instanceof Response) {
			// TODO: re-write redirects
			return context;
		}

		const matches = context.matches as Array<
			(typeof context.matches)[number] & {
				route: {
					Component?: React.FunctionComponent<RouteProps>;
				};
			}
		>;

		let lastRouteId = "!";
		let toRender: string | null = null;
		const routes: Record<string, React.ReactElement> = {};

		for (let i = matches.length - 1; i >= 0; i--) {
			const {
				params,
				route: { Component, id },
			} = matches[i];
			if (Component) {
				const aliasedId = `${___CONTAINER_NAME___}/${id}`;

				routes[aliasedId] = (
					<Component key={aliasedId} params={params}>
						<INTERNAL_Outlet key={lastRouteId} id={lastRouteId} />
					</Component>
				);

				toRender = lastRouteId = aliasedId;
			}
		}

		if (!toRender) {
			return new Response("Not Found", {
				status: 404,
				headers: {
					"Content-Type": "text/plain; charset=utf-8",
					Vary: "Accept",
				},
			});
		}

		let root: React.ReactElement;
		if (typeof toRender === "string") {
			root = (
				<INTERNAL_OutletProvider outlets={routes}>
					<INTERNAL_Outlet key={toRender} id={toRender} />
				</INTERNAL_OutletProvider>
			);
		} else {
			root = toRender;
		}

		// TODO: Plumb through an appContext for the "adapter" layer to provide context to the app through getAppContext()
		root = (
			<INTERNAL_SeverContextProvider request={request}>
				{root}
			</INTERNAL_SeverContextProvider>
		);

		return {
			root,
			status: context.statusCode,
			headers: new Headers({
				"Content-Type": "text/x-component; charset=utf-8",
				"Transfer-Encoding": "chunked",
				Vary: "Accept",
			}),
		};
	};
}


================================================
FILE: framework/lib/framework.ssr.tsx
================================================
import * as React from "react";

export async function InlinePayload({
	decoder,
	readable,
}: {
	decoder?: TextDecoder;
	readable: ReadableStreamDefaultReader<Uint8Array>;
}) {
	let initialScript = null;
	if (!decoder) {
		decoder = new TextDecoder();
		initialScript = (
			<script
				// biome-ignore lint/security/noDangerouslySetInnerHtml: <explanation>
				dangerouslySetInnerHTML={{
					__html: `
            window.__RSC__ = {
              encoder: new TextEncoder(),
            };
            __RSC__.stream = new ReadableStream({
              start(controller) {
                __RSC__.controller = controller;
              },
            });
            __RSC__.chunk = (chunk) => {
              __RSC__.controller.enqueue(
                __RSC__.encoder.encode(chunk)
              );
            };
            __RSC__.done = () => {
              __RSC__.controller.close();
              dispatchEvent(
                new CustomEvent("rscdone", {
                  detail: null,
                })
              );
            };
            dispatchEvent(
              new CustomEvent("rscready", {
                detail: null,
              })
            );
          `,
				}}
			/>
		);
	}

	const { done, value } = await readable.read();

	const decoded = value ? decoder.decode(value, { stream: true }) : null;
	const script = decoded ? (
		<script
			// biome-ignore lint/security/noDangerouslySetInnerHtml: <explanation>
			dangerouslySetInnerHTML={{
				__html: `window.__RSC__.chunk(${sanitize(JSON.stringify(decoded))})`,
			}}
		/>
	) : null;

	if (done) {
		return (
			<>
				{initialScript}
				{script}
				<script
					// biome-ignore lint/security/noDangerouslySetInnerHtml: <explanation>
					dangerouslySetInnerHTML={{ __html: "window.__RSC__.done();" }}
				/>
			</>
		);
	}

	return (
		<>
			{initialScript}
			{script}
			<React.Suspense>
				<InlinePayload decoder={decoder} readable={readable} />
			</React.Suspense>
		</>
	);
}

// Taken from https://github.com/cyco130/vite-rsc/blob/2e3d0ad9915e57c4b2eaa3ea24b46c1b477a4cce/packages/fully-react/src/server/htmlescape.ts#L25C1-L38C2
const TERMINATORS_LOOKUP: Record<string, string> = {
	"\u2028": "\\u2028",
	"\u2029": "\\u2029",
};

const TERMINATORS_REGEX = /[\u2028\u2029]/g;

function sanitizer(match: string | number) {
	return TERMINATORS_LOOKUP[match];
}

export function sanitize(str: string) {
	return str.replace(TERMINATORS_REGEX, sanitizer);
}


================================================
FILE: framework/lib/framework.tsx
================================================
import { type Params } from "@remix-run/router";
import * as React from "react";
// @ts-expect-error - no types
import RSDS from "react-server-dom-webpack/server";

import {
	INTERNAL_StreamReader,
	Link,
	type PromiseStream,
	type PromiseStreamItem,
} from "framework/client.internal";

export { Link, Params };

export interface RouteProps<Param extends string = never> {
	params: Params<Param>;
	children: React.ReactNode;
}

function toPromiseStream<T = unknown>(
	input: ReadableStream<T>,
): PromiseStream<T> {
	const reader = input.getReader();
	async function go(): Promise<PromiseStreamItem<T>> {
		const { done, value: chunk } = await reader.read();
		if (done) {
			return null;
		}
		return { head: chunk, tail: go() };
	}
	return go();
}

export async function RSCFrame({
	children,
	url,
}: {
	children?: React.ReactNode;
	url: string | URL;
}) {
	const serverContextRef = INTERNAL_getServerContextRef();
	if (!serverContextRef.current) {
		throw new Error("No server context found");
	}
	const { actionResult, request } = serverContextRef.current;

	const headers = new Headers(request.headers);
	headers.set("Accept", "text/x-component");
	headers.delete("host");
	headers.set(
		"X-Forwarded-For-Host",
		request.headers.get("X-Forwarded-For-Host") ??
			request.headers.get("host") ??
			"",
	);

	let method = request.method;
	let body = request.body;
	if (actionResult) {
		method = "GET";
		body = null;
		headers.delete("Form-Action");
	}

	const response = await fetch(
		new Request(url, {
			body,
			headers,
			method,
			signal: request.signal,
			// @ts-expect-error - no types
			duplex: "half",
			window: null,
		}),
	);

	if (!response.headers.get("Content-Type")?.match(/\btext\/x-component\b/)) {
		throw new Error(
			`Expected a text/x-component, but received ${response.headers.get(
				"Content-Type",
			)}`,
		);
	}

	if (!response.body) {
		throw new Error("Expected a body");
	}
	return (
		<INTERNAL_StreamReader
			cache={{ current: null }}
			promiseStream={toPromiseStream(
				response.body.pipeThrough(
					new TransformStream({
						transform(chunk, controller) {
							controller.enqueue(
								`${btoa(String.fromCharCode(...new Uint8Array(chunk)))}\n`,
							);
						},
					}),
				),
			)}
		>
			{children}
		</INTERNAL_StreamReader>
	);
}

export type AppContext = unknown;

interface ServerContext {
	actionResult: ActionResult;
	appContext: AppContext;
	request: Request;
}

export type ActionResult =
	| null
	| { id: string; result: unknown }
	| { id: string; error: unknown };

const INTERNAL_getServerContextRef = React.cache(
	(): { current?: ServerContext } => ({}),
);
// @ts-expect-error - idk what this is about
export async function INTERNAL_SeverContextProvider({
	appContext,
	children,
	request,
}: {
	appContext?: AppContext;
	children: React.ReactNode;
	request: Request;
}) {
	const actionId = request.headers.get("Form-Action");
	let actionResult: null | ActionResult = null;
	if (actionId) {
		let action: undefined | ((...args: unknown[]) => unknown) = undefined;
		try {
			const [moduleId, ...exportNameRest] = actionId.split("#");
			const exportName = exportNameRest.join("#");
			await __webpack_require__.e(moduleId);
			// @ts-expect-error
			action = __webpack_require__(moduleId)[exportName];
		} catch (error) {}
		if (action) {
			const body = request.headers
				.get("Content-Type")
				?.match(/\bmultipart\/form\-data\b/)
				? await request.formData()
				: await request.text();
			const reply = await RSDS.decodeReply(body, {});
			try {
				const result = await action(...reply);
				actionResult = { id: actionId, result };
			} catch (error) {
				actionResult = { id: actionId, error };
			}
		}
	}

	console.log({ actionResult });

	const serverContextRef = INTERNAL_getServerContextRef();
	const serverContext: ServerContext = {
		actionResult,
		appContext,
		request,
	};
	serverContextRef.current = serverContext;

	return children;
}

export function getActionResult(action: unknown): ActionResult {
	const serverContextRef = INTERNAL_getServerContextRef();
	if (!serverContextRef.current) {
		throw new Error("No server context found");
	}
	const _action = action as { $$id?: string };
	if (typeof action !== "function" || !_action?.$$id) {
		throw new Error("Expected a `use server` action");
	}
	const result = serverContextRef.current.actionResult;
	if (!result || result.id !== _action.$$id) {
		return null;
	}
	return result;
}

export function getURL(): URL {
	const serverContextRef = INTERNAL_getServerContextRef();
	if (!serverContextRef.current) {
		throw new Error("No server context found");
	}
	return new URL(serverContextRef.current.request.url);
}

export function getHeaders(): Headers {
	const serverContextRef = INTERNAL_getServerContextRef();
	if (!serverContextRef.current) {
		throw new Error("No server context found");
	}
	return new Headers(serverContextRef.current.request.headers);
}

export function getAppContext(): AppContext {
	const serverContextRef = INTERNAL_getServerContextRef();
	if (!serverContextRef.current) {
		throw new Error("No server context found");
	}
	return serverContextRef.current.appContext;
}


================================================
FILE: framework/lib/framework.webpack.ts
================================================
import * as fsp from "node:fs/promises";
import * as path from "node:path";
import { pathToFileURL } from "node:url";

import fg from "fast-glob";
import webpack from "webpack";
import nodeExternals from "webpack-node-externals";
import VirtualModulesPlugin from "webpack-virtual-modules";
// @ts-expect-error
import VisualizerPlugin from "webpack-visualizer-plugin2";
import WebpackBar from "webpackbar";

import {
	ClientRSCPlugin,
	ExternalTemplateRemotesPlugin,
	ServerRSCPlugin,
} from "./webpack.plugins";

export interface ConfigDetails {
	build: "server" | "ssr" | "browser";
	webpack: typeof webpack;
}

export interface ConfigFunction {
	(
		config: webpack.Configuration,
		details: ConfigDetails,
	): Promise<webpack.Configuration> | webpack.Configuration;
}

type WebpackLoader = {
	/**
	 * Unique loader options identifier.
	 */
	ident?: string;
	/**
	 * Loader name.
	 */
	loader?: string;
	/**
	 * Loader options.
	 */
	options?: string | { [index: string]: unknown };
};

export async function getWebpackConfig(
	build: "server" | "server-actions" | "ssr" | "browser",
	{
		clientModules,
		cwd,
		mode,
		serverModules,
	}: {
		clientModules: Set<string>;
		cwd: string;
		mode: "development" | "production";
		serverModules: Set<string>;
	},
): Promise<
	webpack.Configuration & {
		name: "server" | "server-actions" | "ssr" | "browser";
	}
> {
	const devtool = false;
	// mode === "development" ? "eval-cheap-source-map" : "source-map";

	const extensions = [".ts", ".tsx", ".js", ".jsx"];

	const esbuildLoader = {
		loader: require.resolve("esbuild-loader"),
		options: {
			loader: "tsx",
			target: "es2020",
		},
	};

	const pkgJson = JSON.parse(
		await fsp.readFile(path.resolve(cwd, "package.json"), "utf8"),
	);
	const containerName = snakeCase(pkgJson.name);

	let config: webpack.Configuration & {
		name: "server" | "server-actions" | "ssr" | "browser";
	};
	switch (build) {
		case "server": {
			const routesDir = path.resolve(cwd, "app/routes");

			config = await baseServerConfig({
				clientModules,
				containerName,
				cwd,
				esbuildLoader,
				mode,
				devtool,
				extensions,
				routesDir,
				serverModules,
			});
			break;
		}
		case "server-actions": {
			const routesDir = path.resolve(cwd, "app/routes");

			config = await baseServerConfig({
				clientModules,
				containerName,
				cwd,
				esbuildLoader,
				mode,
				devtool,
				extensions,
				routesDir,
				serverModules,
			});
			config.entry = { empty: require.resolve("framework/entry/empty") };
			config.name = "server-actions";
			config.output = config.output || {};

			break;
		}
		case "ssr": {
			config = await baseSSRConfig({
				clientModules,
				containerName,
				cwd,
				esbuildLoader,
				mode,
				devtool,
				extensions,
				pkgJson,
				serverModules,
			});
			break;
		}
		case "browser": {
			config = await baseBrowserConfig({
				clientModules,
				containerName,
				cwd,
				esbuildLoader,
				mode,
				devtool,
				extensions,
				pkgJson,
				serverModules,
			});
			break;
		}
		default:
			throw new Error(`Invalid build type: ${build}`);
	}

	const webpackConfigPath = await findFileIfExists(cwd, [
		"webpack.config.mjs",
		"webpack.config.js",
		"webpack.config.cjs",
	]);

	if (webpackConfigPath) {
		const name = config.name;
		const webpackConfig = await import(pathToFileURL(webpackConfigPath).href);
		/** @type {import("framework/webpack").ConfigFunction | undefined} */
		const configFunc =
			typeof webpackConfig.default === "function"
				? webpackConfig.default
				: typeof webpackConfig === "function"
				  ? webpackConfig
				  : undefined;
		if (configFunc) {
			const newConfig =
				(await configFunc(config, {
					build: name,
					webpack,
				})) || config;
			config = Object.assign(newConfig, { name });
		}
	}

	return config;
}

async function baseServerConfig({
	clientModules,
	containerName,
	cwd,
	devtool,
	esbuildLoader,
	extensions,
	mode,
	routesDir,
	serverModules,
}: {
	clientModules: Set<string>;
	containerName: string;
	cwd: string;
	devtool: string | false;
	esbuildLoader: WebpackLoader;
	extensions: string[];
	mode: "development" | "production";
	routesDir: string;
	serverModules: Set<string>;
}): Promise<webpack.Configuration & { name: "server" }> {
	const bootstrapPath = path.resolve(cwd, "___bootstrap_server.js");
	const routesPath = path.resolve(cwd, "___routes_server.js");

	const serverEntryImport = "framework/entry/server";

	routesDir = path.resolve(cwd, routesDir || "app/routes");

	// TODO: Make this a virtual module, but for now this is nice for debugging the output still.
	const generated = await generateServerRoutes(routesPath, routesDir);

	return {
		name: "server",
		devtool,
		mode,
		entry: bootstrapPath,
		target: "node18",
		externals: [
			nodeExternals({
				allowlist: [
					"framework",
					"framework/server",
					"framework/client.internal",
					"framework/entry/server",
				],
			}),
		],
		resolve: {
			alias: { "#routes": routesPath },
			extensions,
			conditionNames: ["react-server", "webpack", "node", "require", "default"],
		},
		output: {
			library: {
				type: "commonjs-static",
			},
			path: path.resolve(cwd, "./dist/server"),
		},
		module: {
			rules: [
				{
					test: /\.[mc]?[tj]sx?$/,
					use: [esbuildLoader],
				},
			],
		},
		plugins: [
			new webpack.DefinePlugin({
				___CONTAINER_NAME___: JSON.stringify(containerName),
			}),
			new VirtualModulesPlugin({
				[bootstrapPath]: `export const handler = (...args) => import(${JSON.stringify(
					serverEntryImport,
				)}).then(m => m.handler(...args));`,
				[routesPath]: generated,
			}),
			new ServerRSCPlugin({
				clientModules,
				containerName,
				cwd,
				howToLoad: `commonjs ./${containerName}.js`,
				libraryType: "commonjs-static",
				remoteType: "commonjs",
				serverModules,
				shared: {
					react: {
						singleton: true,
						version: "0.0.0-experimental-1d5667a12-20240102",
					},
					"react/": {
						singleton: true,
						version: "0.0.0-experimental-1d5667a12-20240102",
					},
					"react-dom": {
						singleton: true,
						version: "0.0.0-experimental-1d5667a12-20240102",
					},
					"react-dom/": {
						singleton: true,
						version: "0.0.0-experimental-1d5667a12-20240102",
					},
					framework: { singleton: true, version: "1.0.0" },
					"framework/": { singleton: true, version: "1.0.0" },
					"react-server-dom-webpack/": {
						singleton: true,
						version: "0.0.0-experimental-1d5667a12-20240102",
					},
				},
			}),
			!!process.env.PROFILE &&
				new WebpackBar({
					name: "server",
					color: "#008080",
					fancy: false,
					profile: !!process.env.PROFILE,
				}),
		],
	};
}

async function baseSSRConfig({
	clientModules,
	containerName,
	cwd,
	devtool,
	esbuildLoader,
	extensions,
	mode,
	pkgJson,
	serverModules,
}: {
	clientModules: Set<string>;
	containerName: string;
	cwd: string;
	devtool: string | false;
	esbuildLoader: WebpackLoader;
	extensions: string[];
	mode: "development" | "production";
	// biome-ignore lint/suspicious/noExplicitAny: <explanation>
	pkgJson: any;
	serverModules: Set<string>;
}): Promise<webpack.Configuration & { name: "ssr" }> {
	const bootstrapPath = path.resolve(cwd, "___bootstrap_ssr.js");

	const ssrEntryImport = "framework/entry/ssr";

	const rsdResource = require.resolve("react-server-dom-webpack/client.node");

	return {
		optimization: {
			minimize: false,
		},
		name: "ssr",
		devtool,
		mode,
		entry: bootstrapPath,
		target: "node18",
		externals: [
			nodeExternals({
				allowlist: ["framework", /^framework\//, /^react-server-dom-webpack/],
			}),
		],
		resolve: {
			conditionNames: ["webpack", "node", "require", "default"],
			extensions,
		},
		output: {
			library: {
				type: "commonjs-static",
			},
			path: path.resolve(cwd, "./dist/ssr"),
		},
		module: {
			rules: [
				{
					test: /\.[mc]?[tj]sx?$/,
					use: [esbuildLoader],
				},
			],
		},
		plugins: [
			new webpack.DefinePlugin({
				___CONTAINER_NAME___: JSON.stringify(containerName),
			}),
			new VirtualModulesPlugin({
				[bootstrapPath]: `export const handler = (...args) => import(${JSON.stringify(
					ssrEntryImport,
				)}).then(m => m.handler(...args));`,
			}),
			new ClientRSCPlugin({
				clientModules,
				cwd,
				rsdResource,
				libraryType: "commonjs-static",
				remoteType: "commonjs",
				containerName,
				howToLoad: `commonjs ./${containerName}.js`,
				serverModules,
				shared: {
					react: {
						singleton: true,
						version: "0.0.0-experimental-1d5667a12-20240102",
					},
					"react/": {
						singleton: true,
						version: "0.0.0-experimental-1d5667a12-20240102",
					},
					"react-dom": {
						singleton: true,
						version: "0.0.0-experimental-1d5667a12-20240102",
					},
					"react-dom/": {
						singleton: true,
						version: "0.0.0-experimental-1d5667a12-20240102",
					},
					framework: { singleton: true, version: "1.0.0" },
					"framework/": { singleton: true, version: "1.0.0" },
					"react-server-dom-webpack/": {
						singleton: true,
						version: "0.0.0-experimental-1d5667a12-20240102",
					},
				},
			}),
			!!process.env.PROFILE &&
				new WebpackBar({
					name: "ssr",
					color: "blue",
					fancy: false,
					profile: !!process.env.PROFILE,
				}),
			new VisualizerPlugin(),
		],
	};
}

async function baseBrowserConfig({
	clientModules,
	containerName,
	cwd,
	devtool,
	esbuildLoader,
	extensions,
	mode,
	pkgJson,
	serverModules,
}: {
	clientModules: Set<string>;
	containerName: string;
	cwd: string;
	devtool: string | false;
	esbuildLoader: WebpackLoader;
	extensions: string[];
	mode: "development" | "production";
	// biome-ignore lint/suspicious/noExplicitAny: <explanation>
	pkgJson: any;
	serverModules: Set<string>;
}): Promise<webpack.Configuration & { name: "browser" }> {
	const bootstrapPath = path.resolve(cwd, "___bootstrap_browser.js");

	const browserEntryImport = "framework/entry/browser";

	const rsdResource = require.resolve(
		"react-server-dom-webpack/client.browser",
	);

	return {
		name: "browser",
		devtool,
		mode,
		entry: bootstrapPath,
		target: "browserslist:last 2 versions",
		resolve: {
			conditionNames: [
				"browser",
				"webpack",
				"module",
				"import",
				"require",
				"default",
			],
			extensions,
		},
		output: {
			path: path.resolve(cwd, "./dist/browser"),
		},
		module: {
			rules: [
				{
					test: /\.[mc]?[tj]sx?$/,
					use: [esbuildLoader],
				},
			],
		},
		plugins: [
			new webpack.DefinePlugin({
				___CONTAINER_NAME___: JSON.stringify(containerName),
			}),
			new ExternalTemplateRemotesPlugin(),
			new VirtualModulesPlugin({
				[bootstrapPath]: `import(${JSON.stringify(browserEntryImport)})`,
			}),
			new ClientRSCPlugin({
				clientModules,
				cwd,
				rsdResource,
				containerName,
				howToLoad: `${containerName}@[public_path]${containerName}.js`,
				libraryType: "window",
				remoteType: "script",
				serverModules,
				shared: {
					react: {
						singleton: true,
						version: "0.0.0-experimental-1d5667a12-20240102",
					},
					"react/": {
						singleton: true,
						version: "0.0.0-experimental-1d5667a12-20240102",
					},
					"react-dom": {
						singleton: true,
						version: "0.0.0-experimental-1d5667a12-20240102",
					},
					"react-dom/": {
						singleton: true,
						version: "0.0.0-experimental-1d5667a12-20240102",
					},
					framework: { singleton: true, version: "1.0.0" },
					"framework/": { singleton: true, version: "1.0.0" },
					"react-server-dom-webpack/": {
						singleton: true,
						version: "0.0.0-experimental-1d5667a12-20240102",
					},
				},
			}),
			!!process.env.PROFILE &&
				new WebpackBar({
					name: "browser",
					color: "#000080",
					fancy: false,
					profile: !!process.env.PROFILE,
				}),
		],
	};
}

async function findFileIfExists(dir: string, names: string[]) {
	for (const name of names) {
		const file = path.resolve(dir, name);
		try {
			const stats = await fsp.stat(file);
			if (stats.isFile()) {
				return file;
			}
		} catch (err) {
			// @ts-expect-error
			if (err.code !== "ENOENT") {
				throw err;
			}
		}
	}
	return undefined;
}
type Lines = (string | Lines)[];
function indent(lines: Lines, indentLevel = 0): string {
	const indentation = "  ".repeat(indentLevel); // Using two spaces for indentation
	return lines
		.map((line) => {
			if (Array.isArray(line)) {
				// If the line is an array, recursively call indent with increased indentLevel
				return indent(line, indentLevel + 1);
			}
			// If the line is a string, just add the indentation
			return `${indentation}${line}`;
		})
		.join("\n");
}

async function generateServerRoutes(_outFile: string, routesDir: string) {
	const outFile = path.resolve(_outFile);
	const outDir = path.dirname(outFile);

	const routeFiles = await fg("*/*route.{ts,tsx,js,jsx}", {
		cwd: routesDir,
		onlyFiles: true,
	});

	const routeIds = [];
	type Route = {
		relative: string;
		id: string;
		path: string;
		index: boolean;
		children: Route[];
	};
	const routes: Record<string, Route> = {};
	let i = -1;
	for (const routeFile of routeFiles) {
		i++;
		const routeId = makeRouteIdFromRouteFile(routeFile);
		const pathname = makePathnameFromRouteId(routeId);
		const isIndexRoute = routeId === "_index" || routeId.endsWith("._index");

		let relative = path
			.relative(outDir, path.join(routesDir, routeFile))
			.replace(/\\/g, "/");
		relative = relative.startsWith(".") ? relative : `./${relative}`;

		routeIds.push(routeId);
		routes[routeId] = {
			relative,
			id: routeId,
			path: pathname,
			index: isIndexRoute,
			children: [],
		};
	}

	routeIds.sort();

	const rootRoutes = [];
	for (const routeId of routeIds) {
		const route = routes[routeId];
		const split = routeId.split(".");
		let found = false;
		for (let i = split.length - 1; i > 0; i--) {
			const parentId = split.slice(0, i).join(".");
			const parent = routes[parentId];
			if (parent) {
				parent.children.push(route);
				found = true;
				break;
			}
		}
		if (!found) {
			rootRoutes.push(route);
		}
	}

	// biome-ignore lint/suspicious/noExplicitAny: <explanation>
	const createRouteRecursive = (route: Route, inputParentPath = "/"): any[] => {
		const parentPath = inputParentPath.endsWith("/")
			? inputParentPath
			: `${inputParentPath}/`;
		const path = route.path.slice(parentPath.length);
		return [
			"{",
			[
				`id: ${JSON.stringify(route.id)},`,
				...(route.index ? ["index: true,"] : []),
				`path: ${JSON.stringify(path || null)},`,
				`lazy: () => import(${JSON.stringify(route.relative)}),`,
				...(!route.children.length
					? []
					: [
							"children: [",
							...route.children.map((child) =>
								createRouteRecursive(child, route.path),
							),
							"]",
					  ]),
			],
			"},",
		];
	};

	return indent([
		"\nexport const routes = [",
		...rootRoutes.map((route) => createRouteRecursive(route)),
		"];",
		"",
	]);
}

function makeRouteIdFromRouteFile(routeFile: string) {
	const ext = path.extname(routeFile);
	const base = routeFile.slice(0, -ext.length);
	return base.replace(/\\/g, "/").replace(/\/route$/, "");
}

function makePathnameFromRouteId(routeId: string) {
	const segments = `/${routeId}`
		.replace(/\/route$/, "")
		.replace(/\./g, "/")
		.replace(/\/_index$/, "")
		.replace(/^\//, "")
		.split("/");

	let pathname = "";
	for (let segment of segments) {
		if (segment.startsWith("_")) continue;
		if (segment.endsWith("_")) {
			segment = segment.slice(0, -1);
		}
		if (segment === "$") {
			segment = "*";
		}

		const optional = segment.startsWith("(") && segment.endsWith(")");
		if (optional) {
			segment = segment.slice(1, -1);
		}

		if (segment.startsWith("$")) {
			segment = `:${segment.slice(1)}`;
		}

		if (!segment) continue;

		if (optional) {
			segment += "?";
		}

		pathname += `/${segment}`;
	}
	return pathname || "/";
}

function snakeCase(str: string) {
	return str
		.replace(/\W+/g, " ")
		.split(/ |\B(?=[A-Z])/)
		.map((word) => word.toLowerCase())
		.join("_");
}


================================================
FILE: framework/lib/react.client.browser.tsx
================================================
import * as React from "react";
// @ts-expect-error - no types
import RSD from "react-server-dom-webpack/client";

declare global {
	interface Window {
		callServer: (id: string, args: unknown[]) => Promise<unknown>;
	}
}

export function createFromReadableStream(
	readableStream: ReadableStream<Uint8Array>,
) {
	return RSD.createFromReadableStream(readableStream, {
		callServer: (id: string, args: unknown[]) => window.callServer(id, args),
	});
}

export function registerServerReference(
	proxy: unknown,
	mod: string,
	exp: string,
) {
	return RSD.createServerReference(
		`${mod}#${exp}`,
		(id: string, args: unknown[]) => window.callServer(id, args),
	);
}


================================================
FILE: framework/lib/react.client.node.tsx
================================================
import * as stream from "node:stream";
import * as webStream from "node:stream/web";

// @ts-expect-error - no types
import RSD from "react-server-dom-webpack/client";

export function createFromReadableStream(
	readableStream: webStream.ReadableStream<Uint8Array>,
) {
	return RSD.createFromNodeStream(stream.Readable.fromWeb(readableStream), {
		moduleMap: new Proxy(
			{},
			{
				get(_, id) {
					return new Proxy(
						{},
						{
							get(_, key) {
								return {
									id,
									name: key,
									chunks: [String(id).split("#")[0]],
								};
							},
						},
					);
				},
			},
		),
		moduleLoading: new Proxy(
			{},
			{
				get(_, key) {
					throw new Error("Not implemented");
				},
			},
		),
	});
}

export function registerServerReference(
	proxy: unknown,
	mod: string,
	exp: string,
) {
	return RSD.createServerReference(
		`${mod}#${exp}`,
		typeof window !== "undefined" ? window.callServer : undefined,
	);
}


================================================
FILE: framework/lib/react.server.browser.tsx
================================================
// @ts-expect-error - no types
import * as RSDS from "react-server-dom-webpack/server";

export const renderToReadableStream = RSDS.renderToReadableStream;

export const registerServerReference = RSDS.registerServerReference;

export const registerClientReference = RSDS.registerClientReference;


================================================
FILE: framework/lib/react.server.node.tsx
================================================
import * as stream from "node:stream";

// @ts-expect-error - no types
import RSDS from "react-server-dom-webpack/server";

export function renderToReadableStream(
	root: React.ReactNode,
	manifest?: unknown,
	options?: { signal?: AbortSignal; onPostpone?: (...args: unknown[]) => void },
) {
	const { signal, ...sharedOptions } = options ?? {};
	const { pipe, abort } = RSDS.renderToPipeableStream(
		root,
		manifest,
		sharedOptions,
	);

	signal?.addEventListener("abort", abort, { once: true });

	return stream.Readable.toWeb(
		pipe(new stream.PassThrough()),
	) as ReadableStream<Uint8Array>;
}

export const registerServerReference = RSDS.registerServerReference;

export const registerClientReference = RSDS.registerClientReference;


================================================
FILE: framework/lib/utils.ts
================================================
import * as path from "node:path";

export function exposedNameFromResource(cwd: string, resource: string) {
	const relative = path.relative(cwd, resource).replace(/\\/g, "/");

	// TODO: Check if in node_modules and make a deterministic ID
	// if (relative === "../../framework/dist/framework.client.internal.js") {
	// 	return "framework/client.internal";
	// }

	return `./${relative.replace(/\.\.\//g, "__/")}`;
}


================================================
FILE: framework/lib/webpack.federation-runtime-plugin.ts
================================================
import { Module } from "@module-federation/runtime/dist/src/module/index.js";
import type {
	FederationRuntimePlugin,
	Remote,
	RemoteEntryExports,
	ShareScopeMap,
} from "@module-federation/runtime/types";

declare global {
	// biome-ignore lint/style/noVar: <explanation>
	var __webpack_require__: ((id: string) => unknown) & {
		c: Record<string, { exports?: unknown; promise?: Promise<Module> }>;
		e: (chunkId: string | number) => Promise<unknown>;
		p: string;
		S: ShareScopeMap;
		federation: {
			initOptions: {
				name: string;
				remotes: Remote[];
			};
		};
	};

	// biome-ignore lint/style/noVar: <explanation>
	var ___REMOTES___: Record<string, string>;
}

const publicPath = __webpack_require__.p;
const federation = __webpack_require__.federation;
const cache = __webpack_require__.c;
const shareScopeMap = __webpack_require__.S;
const webpackRequire = __webpack_require__;

for (const [remote, external] of Object.entries(___REMOTES___)) {
	if (!federation.initOptions.remotes.find((r) => r.name === remote)) {
		federation.initOptions.remotes.push({
			name: remote,
			alias: remote,
			entry: external,
			version: "latest",
			type: "global",
			entryGlobalName: remote,
		});
	}
}

for (const remote of federation.initOptions.remotes as Remote[]) {
	if ("entry" in remote && remote.entry?.includes("[public_path]")) {
		remote.entry = publicPath + remote.entry.split("[public_path]")[1];
	}
}

const gs = (globalThis ||
	// biome-ignore lint/suspicious/noExplicitAny: <explanation>
	new Function("return globalThis")()) as unknown as Record<string, any>;

const prefix = /^rsc\/remote\/(client|server)\//;
const ogEnsureChunk = __webpack_require__.e;
const containerLoadCache =
	gs.containerLoadCache ||
	// biome-ignore lint/suspicious/noAssignInExpressions: <explanation>
	(gs.containerLoadCache = new Map<string, Promise<RemoteEntryExports>>());

const containerExposedModuleCache =
	gs.containerExposedModuleCache ||
	// biome-ignore lint/suspicious/noAssignInExpressions: <explanation>
	(gs.containerExposedModuleCache = new Map<string, Promise<unknown>>());

function rscFederationEnsureChunk(chunkId: string): Promise<unknown> {
	// biome-ignore lint/style/noNonNullAssertion: <explanation>
	if (cache[chunkId]) return cache[chunkId].promise!;
	const idToSet = chunkId;
	cache[chunkId] = {
		promise: (async () => {
			await new Promise((r) => setTimeout(r, 0));

			const [remoteId, exposedModuleRequest] = idToSet.split(":");
			const containerName = remoteId.replace(prefix, "");
			const exposedModuleCacheId = `${containerName}/${exposedModuleRequest}`;

			const referenceId = `webpack/container/reference/${containerName}`;

			let containerPromise = containerLoadCache.get(referenceId);
			if (!containerPromise) {
				containerPromise = ogEnsureChunk(remoteId).then(async () => {
					const container = (await webpackRequire(
						referenceId,
					)) as RemoteEntryExports & {
						inited?: boolean;
					};

					if (!gs[containerName]) {
						gs[containerName] = container;
					}

					if (!container.inited) {
						await container.init(
							__FEDERATION__.__INSTANCES__[0].shareScopeMap.default,
						);
					}

					return container;
				});
				containerLoadCache.set(referenceId, containerPromise);
			}
			const container = await containerPromise;

			let modPromise = containerExposedModuleCache.get(exposedModuleCacheId);
			if (!modPromise) {
				modPromise = (async () => {
					const factory = await container.get(exposedModuleRequest);
					const mod = await factory();
					cache[idToSet].exports = mod;
					return mod;
				})();
				containerExposedModuleCache.set(exposedModuleCacheId, modPromise);
			}
			return modPromise;
		})(),
	};

	// biome-ignore lint/style/noNonNullAssertion: <explanation>
	return cache[chunkId].promise!;
}

__webpack_require__.e = async (chunkId: string | number) => {
	if (
		typeof chunkId === "string" &&
		prefix.test(chunkId) &&
		chunkId.includes(":")
	) {
		if (cache[chunkId]) return cache[chunkId].promise;
		return rscFederationEnsureChunk(chunkId);
	}
	return ogEnsureChunk(chunkId);
};

export default function (): FederationRuntimePlugin {
	return {
		name: "rsc-internal-plugin",
	};
}


================================================
FILE: framework/lib/webpack.plugins.ts
================================================
import { ModuleFederationPlugin } from "@module-federation/enhanced";
import { rscClientPlugin, rscServerPlugin } from "unplugin-rsc";
import type * as webpack from "webpack";

import { exposedNameFromResource } from "./utils";

export class ServerRSCPlugin {
	constructor(
		private options: {
			clientModules: Set<string>;
			containerName: string;
			cwd: string;
			howToLoad: string;
			libraryType: string;
			remoteType: string;
			serverModules: Set<string>;
			shared: unknown;
		},
	) {}

	apply(compiler: webpack.Compiler) {
		const {
			clientModules,
			containerName,
			cwd,
			howToLoad,
			libraryType,
			remoteType,
			serverModules,
			shared,
		} = this.options;

		const allRemotes: Record<string, unknown> = {};
		// biome-ignore lint/suspicious/noExplicitAny: <explanation>
		const plugins: any[] = [];
		for (const plugin of compiler.options.plugins) {
			if (
				plugin &&
				(plugin.constructor.name === "ModuleFederationPlugin" ||
					plugin.constructor.name === "UniversalFederationPlugin")
			) {
				// @ts-expect-error
				Object.assign(allRemotes, plugin._options.remotes || {});
				plugins.push(plugin);
			}
		}

		const serverRSCContainer = new ModuleFederationPlugin({
			// isServer,
			name: containerName,
			exposes: Array.from(serverModules).reduce(
				(p, c) =>
					Object.assign(p, {
						[exposedNameFromResource(cwd, c)]: c,
					}),
				{},
			),
			remotes: Object.assign(allRemotes, {
				[containerName]: howToLoad,
			}),
			runtimePlugins: [
				require.resolve("framework/webpack.federation-runtime-plugin"),
			],
			shared,
			remoteType,
			library: libraryType
				? {
						name: ["var", "window"].includes(libraryType)
							? containerName
							: undefined,
						type: libraryType,
				  }
				: undefined,
		});
		serverRSCContainer.apply(compiler);

		plugins.push(serverRSCContainer);

		for (const plugin of plugins) {
			Object.assign(plugin._options.remotes, allRemotes);
		}

		const remotes = Object.assign(
			{},
			...plugins.map((p) => p._options.remotes),
		);

		new compiler.webpack.DefinePlugin({
			___REMOTES___: JSON.stringify(remotes),
		}).apply(compiler);

		rscServerPlugin
			.webpack({
				include: /\.[mc]?[tj]sx?$/,
				exclude: "this_should_never_match_anything",
				transformModuleId: (id, type) => {
					return `rsc/remote/${type.replace(
						/^use /,
						"",
					)}/${containerName}:${exposedNameFromResource(cwd, id)}`;
				},
				useClientRuntime: {
					function: "registerClientReference",
					module: "framework/runtime",
				},
				useServerRuntime: {
					function: "registerServerReference",
					module: "framework/runtime",
				},
				onModuleFound(id, type) {
					if (type === "use client") {
						clientModules.add(id);
					} else if (type === "use server") {
						serverModules.add(id);
					}
				},
			})
			.apply(compiler);

		class ContainerReferenceDependency extends compiler.webpack.dependencies
			.ModuleDependency {
			get type() {
				return "container-reference";
			}
		}

		const rsdResource = require.resolve("framework/framework");
		compiler.hooks.compilation.tap(
			"MyPlugin",
			(compilation, { normalModuleFactory }) => {
				compilation.hooks.optimizeModuleIds.tap("MyPlugin", (modules) => {
					for (const mod of modules as webpack.NormalModule[]) {
						if (mod.userRequest?.startsWith("webpack/container/")) {
							compilation.chunkGraph.setModuleId(mod, mod.userRequest);
						}
					}
				});
				compilation.hooks.optimizeChunks.tap("MyPlugin", (chunks) => {
					for (const chunk of chunks) {
						if (
							chunk.name &&
							compilation.chunkGraph
								.getChunkModules(chunk)
								.some((mod) => mod.type === "remote-module")
						) {
							chunk.id = chunk.name;
						}
					}
				});

				compilation.dependencyFactories.set(
					ContainerReferenceDependency,
					normalModuleFactory,
				);
				compilation.dependencyTemplates.set(
					ContainerReferenceDependency,
					new compiler.webpack.dependencies.NullDependency.Template(),
				);

				// biome-ignore lint/suspicious/noExplicitAny: <explanation>
				const handler = (parser: any) => {
					// biome-ignore lint/suspicious/noExplicitAny: <explanation>
					parser.hooks.program.tap("MyPlugin", (ast: any) => {
						const mod =
							/** @type {import("webpack").NormalModule} */ parser.state.module;

						if (mod.resource !== rsdResource) return;

						let attached = 0;
						for (const plugin of plugins) {
							if (plugin._options.remotes) {
								for (const key of Object.keys(plugin._options.remotes)) {
									attached++;
									const name = `rsc/remote/server/${key}`;
									const block = new compiler.webpack.AsyncDependenciesBlock(
										{
											name,
										},
										null,
										name,
									);
									block.addDependency(new ContainerReferenceDependency(key));

									mod.addBlock(block);
								}
							}
						}

						if (process.env.DEBUG === "1") {
							console.debug(
								`ℹ ${compiler.options.name} attached ${attached} remotes to react-server-dom-webpack\n`,
							);
						}
					});
				};

				normalModuleFactory.hooks.parser
					.for("javascript/auto")
					.tap("HarmonyModulesPlugin", handler);

				normalModuleFactory.hooks.parser
					.for("javascript/esm")
					.tap("HarmonyModulesPlugin", handler);

				normalModuleFactory.hooks.parser
					.for("javascript/dynamic")
					.tap("HarmonyModulesPlugin", handler);
			},
		);
	}
}

export class ClientRSCPlugin {
	constructor(
		private options: {
			clientModules: Set<string>;
			containerName: string;
			cwd: string;
			howToLoad: string;
			libraryType: string;
			remoteType: string;
			rsdResource: string;
			serverModules: Set<string>;
			shared: unknown;
		},
	) {}

	apply(compiler: webpack.Compiler) {
		const {
			clientModules,
			containerName,
			cwd,
			howToLoad,
			libraryType,
			remoteType,
			rsdResource,
			serverModules,
			shared,
		} = this.options;

		rscClientPlugin
			.webpack({
				include: /\.[mc]?[tj]sx?$/,
				exclude: "this_should_never_match_anything",
				transformModuleId: (id, type) => {
					return `rsc/remote/${type.replace(
						/^use /,
						"",
					)}/${containerName}:${exposedNameFromResource(cwd, id)}`;
				},
				useServerRuntime: {
					function: "registerServerReference",
					module: "framework/runtime",
				},
				onModuleFound(id, type) {
					if (type === "use server") {
						serverModules.add(id);
					}
				},
			})
			.apply(compiler);

		const allRemotes: Record<string, unknown> = {};
		// biome-ignore lint/suspicious/noExplicitAny: <explanation>
		const plugins: any[] = [];
		for (const plugin of compiler.options.plugins) {
			if (
				plugin &&
				(plugin.constructor.name === "ModuleFederationPlugin" ||
					plugin.constructor.name === "UniversalFederationPlugin")
			) {
				// @ts-expect-error
				Object.assign(allRemotes, plugin._options.remotes || {});
				plugins.push(plugin);
			}
		}

		const clientRSCContainer = new ModuleFederationPlugin({
			// isServer,
			name: containerName,
			exposes: Array.from(clientModules).reduce(
				(p, c) =>
					Object.assign(p, {
						[exposedNameFromResource(cwd, c)]: c,
					}),
				{},
			),
			remotes: Object.assign(allRemotes, {
				[containerName]: howToLoad,
			}),
			runtimePlugins: [
				require.resolve("framework/webpack.federation-runtime-plugin"),
			],
			shared,
			remoteType,
			library: libraryType
				? {
						name: ["var", "window"].includes(libraryType)
							? containerName
							: undefined,
						type: libraryType,
				  }
				: undefined,
		});
		clientRSCContainer.apply(compiler);
		plugins.push(clientRSCContainer);

		for (const plugin of plugins) {
			Object.assign(plugin._options.remotes, allRemotes);
		}

		const remotes = Object.assign(
			{},
			...plugins.map((p) => p._options.remotes),
		);

		new compiler.webpack.DefinePlugin({
			___REMOTES___: JSON.stringify(remotes),
		}).apply(compiler);

		// if (isServer) {
		//   new StreamingTargetPlugin({
		//     // name: this.containerName,
		//   }).apply(compiler);
		// }

		class ContainerReferenceDependency extends compiler.webpack.dependencies
			.ModuleDependency {
			get type() {
				return "container-reference";
			}
		}

		compiler.hooks.compilation.tap(
			"MyPlugin",
			(compilation, { normalModuleFactory }) => {
				compilation.hooks.optimizeModuleIds.tap("MyPlugin", (modules) => {
					for (const mod of modules as webpack.NormalModule[]) {
						if (mod.userRequest?.startsWith("webpack/container/")) {
							compilation.chunkGraph.setModuleId(mod, mod.userRequest);
						}
					}
				});
				compilation.hooks.optimizeChunks.tap("MyPlugin", (chunks) => {
					for (const chunk of chunks) {
						if (
							chunk.name &&
							compilation.chunkGraph
								.getChunkModules(chunk)
								.some((mod) => mod.type === "remote-module")
						) {
							chunk.id = chunk.name;
						}
					}
				});

				compilation.dependencyFactories.set(
					ContainerReferenceDependency,
					normalModuleFactory,
				);
				compilation.dependencyTemplates.set(
					ContainerReferenceDependency,
					new compiler.webpack.dependencies.NullDependency.Template(),
				);

				// biome-ignore lint/suspicious/noExplicitAny: <explanation>
				const handler = (parser: any) => {
					// biome-ignore lint/suspicious/noExplicitAny: <explanation>
					parser.hooks.program.tap("MyPlugin", (ast: any) => {
						const mod =
							/** @type {import("webpack").NormalModule} */ parser.state.module;

						if (mod.resource !== rsdResource) return;

						let attached = 0;
						for (const plugin of plugins) {
							if (plugin._options.remotes) {
								for (const key of Object.keys(plugin._options.remotes)) {
									attached++;
									const name = `rsc/remote/client/${key}`;
									const block = new compiler.webpack.AsyncDependenciesBlock(
										{
											name,
										},
										null,
										name,
									);
									block.addDependency(new ContainerReferenceDependency(key));

									mod.addBlock(block);
								}
							}
						}

						if (process.env.DEBUG === "1") {
							console.debug(
								`ℹ ${compiler.options.name} attached ${attached} remotes to react-server-dom-webpack\n`,
							);
						}
					});
				};

				normalModuleFactory.hooks.parser
					.for("javascript/auto")
					.tap("HarmonyModulesPlugin", handler);

				normalModuleFactory.hooks.parser
					.for("javascript/esm")
					.tap("HarmonyModulesPlugin", handler);

				normalModuleFactory.hooks.parser
					.for("javascript/dynamic")
					.tap("HarmonyModulesPlugin", handler);
			},
		);
	}
}

// Below is from ModuleFederation / universe or somewhere like that and should probably be imported from there instead

export class ExternalTemplateRemotesPlugin {
	static PLUGIN_NAME = "ExternalTemplateRemotesPlugin";
	apply(compiler: webpack.Compiler) {
		compiler.hooks.make.tap(
			ExternalTemplateRemotesPlugin.PLUGIN_NAME,
			(compilation) => {
				const scriptExternalModules: webpack.ExternalModule[] = [];

				compilation.hooks.buildModule.tap(
					ExternalTemplateRemotesPlugin.PLUGIN_NAME,
					(m) => {
						const mod = m as webpack.ExternalModule;
						if (
							mod.constructor.name === "ExternalModule" &&
							mod.externalType === "script"
						) {
							scriptExternalModules.push(mod);
						}
					},
				);
			},
		);
	}
}


================================================
FILE: framework/package.json
================================================
{
	"name": "framework",
	"version": "1.0.0",
	"files": ["bin", "cli", "dist", "entry"],
	"bin": {
		"remix": "./bin/remix.cjs"
	},
	"main": "dist/framework.js",
	"types": "dist/framework.d.ts",
	"exports": {
		".": {
			"types": "./dist/framework.d.ts",
			"react-server": {
				"default": "./dist/framework.js"
			},
			"default": "./server-only.js"
		},
		"./framework": {
			"types": "./dist/framework.d.ts",
			"default": "./dist/framework.js"
		},
		"./browser": {
			"types": "./dist/framework.browser.d.ts",
			"default": "./dist/framework.browser.js"
		},
		"./client": {
			"types": "./dist/framework.client.d.ts",
			"default": "./dist/framework.client.js"
		},
		"./client.internal": {
			"types": "./dist/framework.client.internal.d.ts",
			"default": "./dist/framework.client.internal.js"
		},
		"./server": {
			"types": "./dist/framework.server.d.ts",
			"react-server": {
				"default": "./dist/framework.server.js"
			},
			"default": "./server-only.js"
		},
		"./runtime": {
			"types": "./dist/framework.runtime.d.ts",
			"react-server": {
				"default": "./dist/framework.runtime.server.js"
			},
			"default": "./dist/framework.runtime.client.js"
		},
		"./server-runtime": {
			"types": "./dist/framework.server-runtime.d.ts",
			"react-server": {
				"default": "./dist/framework.server-runtime.server.js"
			},
			"default": "./dist/framework.server-runtime.client.js"
		},
		"./ssr": {
			"types": "./dist/framework.ssr.d.ts",
			"default": "./dist/framework.ssr.js"
		},
		"./react.client": {
			"types": "./dist/react.client.browser.d.ts",
			"browser": "./dist/react.client.browser.js",
			"default": "./dist/react.client.node.js"
		},
		"./react.server": {
			"types": "./dist/react.server.browser.d.ts",
			"browser": "./dist/react.server.browser.js",
			"default": "./dist/react.server.node.js"
		},
		"./webpack": {
			"types": "./dist/framework.webpack.d.ts",
			"default": "./dist/framework.webpack.js"
		},
		"./webpack/plugins": {
			"types": "./dist/webpack.plugins.d.ts",
			"default": "./dist/webpack.plugins.js"
		},
		"./webpack.federation-runtime-plugin": {
			"types": "./dist/webpack.federation-runtime-plugin.d.ts",
			"default": "./dist/webpack.federation-runtime-plugin.js"
		},
		"./entry/browser": "./entry/browser.tsx",
		"./entry/empty": "./entry/empty.tsx",
		"./entry/server": "./entry/server.tsx",
		"./entry/ssr": "./entry/ssr.tsx",
		"./package.json": "./package.json"
	},
	"scripts": {
		"build": "tsc -p tsconfig.lib.json"
	},
	"dependencies": {
		"@module-federation/enhanced": "0.0.8",
		"@module-federation/runtime": "0.0.8",
		"@oxidation-compiler/napi": "^0.2.0",
		"@remix-run/router": "^1.14.1",
		"esbuild-loader": "^4.0.2",
		"fast-glob": "^3.3.2",
		"react": "0.0.0-experimental-1d5667a12-20240102",
		"react-dom": "0.0.0-experimental-1d5667a12-20240102",
		"react-server-dom-webpack": "0.0.0-experimental-1d5667a12-20240102",
		"unplugin-rsc": "0.0.6",
		"webpack": "^5.89.0",
		"webpack-format-messages": "^3.0.1",
		"webpack-node-externals": "^3.0.0",
		"webpack-virtual-modules": "^0.6.1",
		"webpack-visualizer-plugin2": "^1.1.0",
		"webpackbar": "^6.0.0"
	},
	"devDependencies": {
		"@types/node": "^20.10.6",
		"@types/react": "^18.2.46",
		"@types/react-dom": "^18.2.18",
		"@types/webpack-node-externals": "^3.0.4",
		"typescript": "^5.3.3"
	}
}


================================================
FILE: framework/server-only.js
================================================
throw new Error("This module is only meant to be used on the server");


================================================
FILE: framework/tsconfig.json
================================================
{
  "exclude": ["node_modules", "dist"],
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "target": "ES2022",
    "lib": ["DOM", "DOM.Iterable", "ES2022"],
    "types": ["node", "react/experimental", "react-dom/experimental"],
    "jsx": "react",
    "allowImportingTsExtensions": true,
    "strict": true,
    "allowJs": true,
    "checkJs": true,
    "noEmit": true,
    "skipLibCheck": true
  }
}


================================================
FILE: framework/tsconfig.lib.json
================================================
{
	"include": ["./lib/**/*"],
	"compilerOptions": {
		"outDir": "dist",
		"declaration": true,
		"declarationMap": true,
		"module": "Node16",
		"moduleResolution": "Node16",
		"target": "ES2022",
		"lib": ["DOM", "DOM.Iterable", "ES2022"],
		"types": ["node", "react/experimental", "react-dom/experimental"],
		"jsx": "react",
		"strict": true,
		"rootDir": "lib",
		"skipLibCheck": true
	}
}


================================================
FILE: package.json
================================================
{
  "private": true,
  "scripts": {
    "build": "pnpm -r --filter framework --filter @fixture/* build",
    "check": "biome check **/*",
    "start": "pnpm --filter @fixture/* start"
  },
  "pnpm": {
    "overrides": {
      "react": "0.0.0-experimental-1d5667a12-20240102",
      "react-dom": "0.0.0-experimental-1d5667a12-20240102",
      "react-server-dom-webpack": "0.0.0-experimental-1d5667a12-20240102"
    }
  },
  "devDependencies": {
    "@biomejs/biome": "1.5.1"
  }
}


================================================
FILE: pnpm-workspace.yaml
================================================
packages:
  - "examples/*"
  - "fixture/*"
  - "framework"
Download .txt
gitextract_hem18noe/

├── .gitignore
├── .vscode/
│   ├── extensions.json
│   └── settings.json
├── README.md
├── biome.json
├── examples/
│   ├── basic/
│   │   ├── app/
│   │   │   ├── components/
│   │   │   │   └── counter.tsx
│   │   │   └── routes/
│   │   │       ├── _public/
│   │   │       │   └── route.tsx
│   │   │       ├── _public.$/
│   │   │       │   └── route.tsx
│   │   │       ├── _public.layout/
│   │   │       │   └── route.tsx
│   │   │       ├── _public.slug.$slug/
│   │   │       │   └── route.tsx
│   │   │       └── weather.$/
│   │   │           ├── route.tsx
│   │   │           └── temperature-switch.tsx
│   │   ├── package.json
│   │   ├── server.mts
│   │   ├── ssr-server.mts
│   │   └── tsconfig.json
│   └── consumer/
│       ├── app/
│       │   ├── components/
│       │   │   └── counter.tsx
│       │   └── routes/
│       │       ├── _public/
│       │       │   └── route.tsx
│       │       ├── _public._index/
│       │       │   └── route.tsx
│       │       ├── _public.about/
│       │       │   └── route.tsx
│       │       └── _public.about.$slug/
│       │           └── route.tsx
│       ├── package.json
│       ├── server.mts
│       ├── ssr-server.mts
│       ├── tsconfig.json
│       └── webpack.config.cjs
├── fixture/
│   ├── marketing/
│   │   ├── app/
│   │   │   ├── components/
│   │   │   │   └── ui/
│   │   │   │       ├── avatar.tsx
│   │   │   │       ├── button.tsx
│   │   │   │       ├── card.tsx
│   │   │   │       ├── input.tsx
│   │   │   │       └── separator.tsx
│   │   │   ├── lib/
│   │   │   │   └── utils.ts
│   │   │   ├── remotes.tsx
│   │   │   └── routes/
│   │   │       ├── _public/
│   │   │       │   ├── route.tsx
│   │   │       │   └── style.css
│   │   │       ├── _public._index/
│   │   │       │   ├── products.tsx
│   │   │       │   └── route.tsx
│   │   │       └── _public.product.$handle/
│   │   │           ├── actions.tsx
│   │   │           ├── client.tsx
│   │   │           ├── form.tsx
│   │   │           ├── product.tsx
│   │   │           ├── reviews.tsx
│   │   │           └── route.tsx
│   │   ├── components.json
│   │   ├── modules.d.ts
│   │   ├── package.json
│   │   ├── postcss.config.cjs
│   │   ├── remotes.cjs
│   │   ├── server.mts
│   │   ├── ssr-server.mts
│   │   ├── tailwind.config.cjs
│   │   ├── tsconfig.json
│   │   └── webpack.config.cjs
│   └── shell/
│       ├── app/
│       │   ├── components/
│       │   │   └── ui/
│       │   │       └── button.tsx
│       │   ├── lib/
│       │   │   └── utils.ts
│       │   ├── remotes.tsx
│       │   └── routes/
│       │       ├── _public/
│       │       │   ├── client.tsx
│       │       │   ├── header.tsx
│       │       │   ├── route.tsx
│       │       │   └── style.css
│       │       ├── _public.$/
│       │       │   └── route.tsx
│       │       ├── _public._index/
│       │       │   └── route.tsx
│       │       ├── _public.product.$handle/
│       │       │   └── route.tsx
│       │       └── api.shell/
│       │           └── route.tsx
│       ├── components.json
│       ├── modules.d.ts
│       ├── package.json
│       ├── postcss.config.cjs
│       ├── remotes.cjs
│       ├── server.mts
│       ├── ssr-server.mts
│       ├── tailwind.config.cjs
│       ├── tsconfig.json
│       └── webpack.config.cjs
├── framework/
│   ├── bin/
│   │   └── remix.cjs
│   ├── cli/
│   │   └── build.mjs
│   ├── entry/
│   │   ├── browser.tsx
│   │   ├── empty.tsx
│   │   ├── server.tsx
│   │   └── ssr.tsx
│   ├── lib/
│   │   ├── framework.browser.tsx
│   │   ├── framework.client.internal.tsx
│   │   ├── framework.client.tsx
│   │   ├── framework.runtime.client.ts
│   │   ├── framework.runtime.server.ts
│   │   ├── framework.server.tsx
│   │   ├── framework.ssr.tsx
│   │   ├── framework.tsx
│   │   ├── framework.webpack.ts
│   │   ├── react.client.browser.tsx
│   │   ├── react.client.node.tsx
│   │   ├── react.server.browser.tsx
│   │   ├── react.server.node.tsx
│   │   ├── utils.ts
│   │   ├── webpack.federation-runtime-plugin.ts
│   │   └── webpack.plugins.ts
│   ├── package.json
│   ├── server-only.js
│   ├── tsconfig.json
│   └── tsconfig.lib.json
├── package.json
└── pnpm-workspace.yaml
Download .txt
SYMBOL INDEX (114 symbols across 50 files)

FILE: examples/basic/app/components/counter.tsx
  function CounterBasic (line 5) | function CounterBasic() {

FILE: examples/basic/app/routes/_public.$/route.tsx
  function Component (line 3) | function Component() {

FILE: examples/basic/app/routes/_public.layout/route.tsx
  function Component (line 1) | function Component({ children }: { children: React.ReactNode }) {

FILE: examples/basic/app/routes/_public.slug.$slug/route.tsx
  function Component (line 1) | function Component() {

FILE: examples/basic/app/routes/_public/route.tsx
  function Component (line 3) | function Component({ children }: { children: React.ReactNode }) {

FILE: examples/basic/app/routes/weather.$/route.tsx
  function ArtificialDelayExample (line 10) | async function ArtificialDelayExample() {
  function Component (line 15) | async function Component({

FILE: examples/basic/app/routes/weather.$/temperature-switch.tsx
  function TemperatureSwitch (line 10) | function TemperatureSwitch({ children }: { children: React.ReactNode }) {
  function TemperatureToggle (line 25) | function TemperatureToggle() {
  function TemperatureDisplay (line 38) | function TemperatureDisplay({ c, f }: { c: number; f: number }) {

FILE: examples/consumer/app/components/counter.tsx
  function CounterConsumer (line 5) | function CounterConsumer() {

FILE: examples/consumer/app/routes/_public._index/route.tsx
  function Component (line 5) | function Component() {

FILE: examples/consumer/app/routes/_public.about.$slug/route.tsx
  function Component (line 1) | function Component() {

FILE: examples/consumer/app/routes/_public.about/route.tsx
  function Component (line 3) | function Component({ children }: { children: React.ReactNode }) {

FILE: examples/consumer/app/routes/_public/route.tsx
  function Component (line 3) | function Component({ children }: { children: React.ReactNode }) {

FILE: fixture/marketing/app/components/ui/button.tsx
  type ButtonProps (line 41) | interface ButtonProps

FILE: fixture/marketing/app/components/ui/input.tsx
  type InputProps (line 5) | interface InputProps

FILE: fixture/marketing/app/lib/utils.ts
  function cn (line 4) | function cn(...inputs: ClassValue[]) {

FILE: fixture/marketing/app/remotes.tsx
  constant REMOTES (line 8) | const REMOTES = __REMOTES__;
  function FederatedRSCFrame (line 10) | function FederatedRSCFrame({

FILE: fixture/marketing/app/routes/_public._index/products.tsx
  function ProductList (line 10) | function ProductList({
  function ProductCard (line 44) | function ProductCard({
  function truncate (line 89) | function truncate(str: string, n: number) {

FILE: fixture/marketing/app/routes/_public._index/route.tsx
  function Component (line 3) | async function Component() {

FILE: fixture/marketing/app/routes/_public.product.$handle/actions.tsx
  function addToCart (line 1) | async function addToCart() {

FILE: fixture/marketing/app/routes/_public.product.$handle/client.tsx
  function AddToCartButton (line 10) | function AddToCartButton({
  function Option (line 29) | function Option({
  function ProductImages (line 74) | function ProductImages({

FILE: fixture/marketing/app/routes/_public.product.$handle/form.tsx
  function AddToCartForm (line 8) | function AddToCartForm({

FILE: fixture/marketing/app/routes/_public.product.$handle/product.tsx
  function ProductHeader (line 1) | function ProductHeader({

FILE: fixture/marketing/app/routes/_public.product.$handle/reviews.tsx
  function ProductReviews (line 6) | function ProductReviews() {

FILE: fixture/marketing/app/routes/_public.product.$handle/route.tsx
  function Component (line 12) | async function Component({ params: { handle } }: RouteProps<"handle">) {

FILE: fixture/marketing/app/routes/_public/route.tsx
  function Component (line 7) | function Component({ children }: { children?: React.ReactNode }) {

FILE: fixture/shell/app/components/ui/button.tsx
  type ButtonProps (line 37) | interface ButtonProps

FILE: fixture/shell/app/lib/utils.ts
  function cn (line 4) | function cn(...inputs: ClassValue[]) {

FILE: fixture/shell/app/remotes.tsx
  constant REMOTES (line 8) | const REMOTES = __REMOTES__;
  function FederatedRSCFrame (line 10) | function FederatedRSCFrame({

FILE: fixture/shell/app/routes/_public.$/route.tsx
  function Component (line 1) | async function Component() {

FILE: fixture/shell/app/routes/_public._index/route.tsx
  function Component (line 3) | async function Component() {

FILE: fixture/shell/app/routes/_public.product.$handle/route.tsx
  function Component (line 6) | async function Component({ params: { handle } }: RouteProps<"handle">) {

FILE: fixture/shell/app/routes/_public/client.tsx
  function GlobalStatusIndicator (line 7) | function GlobalStatusIndicator() {

FILE: fixture/shell/app/routes/_public/header.tsx
  function Header (line 3) | function Header() {

FILE: fixture/shell/app/routes/_public/route.tsx
  function Component (line 7) | function Component({ children }: { children: React.ReactNode }) {

FILE: framework/cli/build.mjs
  function build (line 9) | async function build() {
  function runWebpack (line 81) | function runWebpack(config) {
  function startTimer (line 125) | function startTimer() {

FILE: framework/entry/ssr.tsx
  function handler (line 12) | async function handler(

FILE: framework/lib/framework.browser.tsx
  type Window (line 16) | interface Window {
  function hydrate (line 25) | function hydrate() {
  function hydrateInternal (line 35) | async function hydrateInternal() {

FILE: framework/lib/framework.client.tsx
  type LocationState (line 5) | type LocationState =
  function INTERNAL_LocationContextProvider (line 20) | function INTERNAL_LocationContextProvider({
  type INTERNAL_LocationState (line 31) | interface INTERNAL_LocationState {
  function INTERNAL_Location (line 36) | function INTERNAL_Location({
  function INTERNAL_Outlet (line 94) | function INTERNAL_Outlet({ id }: { id: string }) {
  type INTERNAL_OutletProviderProps (line 100) | interface INTERNAL_OutletProviderProps {
  function INTERNAL_OutletProvider (line 105) | function INTERNAL_OutletProvider({
  type PromiseStreamItem (line 117) | type PromiseStreamItem<T> = null | { head: T; tail: PromiseStream<T> };
  type PromiseStream (line 118) | type PromiseStream<T> = Promise<PromiseStreamItem<T>>;
  function INTERNAL_StreamReader (line 120) | function INTERNAL_StreamReader({
  function fromPromiseStream (line 177) | function fromPromiseStream<T = unknown>(initialPromise: PromiseStream<T>) {
  function useLocation (line 192) | function useLocation() {
  function Link (line 217) | function Link(props: React.ComponentPropsWithoutRef<"link">) {

FILE: framework/lib/framework.runtime.client.ts
  function registerServerReference (line 3) | function registerServerReference(

FILE: framework/lib/framework.runtime.server.ts
  function registerClientReference (line 6) | function registerClientReference(
  function registerServerReference (line 15) | function registerServerReference(

FILE: framework/lib/framework.server.tsx
  function createRequestHandler (line 26) | function createRequestHandler(routes: AgnosticDataRouteObject[]) {
  function createStaticRequestHandler (line 82) | function createStaticRequestHandler(routes: AgnosticDataRouteObject[]) {

FILE: framework/lib/framework.ssr.tsx
  function InlinePayload (line 3) | async function InlinePayload({
  constant TERMINATORS_LOOKUP (line 87) | const TERMINATORS_LOOKUP: Record<string, string> = {
  constant TERMINATORS_REGEX (line 92) | const TERMINATORS_REGEX = /[\u2028\u2029]/g;
  function sanitizer (line 94) | function sanitizer(match: string | number) {
  function sanitize (line 98) | function sanitize(str: string) {

FILE: framework/lib/framework.tsx
  type RouteProps (line 15) | interface RouteProps<Param extends string = never> {
  function toPromiseStream (line 20) | function toPromiseStream<T = unknown>(
  function RSCFrame (line 34) | async function RSCFrame({
  type AppContext (line 108) | type AppContext = unknown;
  type ServerContext (line 110) | interface ServerContext {
  type ActionResult (line 116) | type ActionResult =
  function INTERNAL_SeverContextProvider (line 125) | async function INTERNAL_SeverContextProvider({
  function getActionResult (line 174) | function getActionResult(action: unknown): ActionResult {
  function getURL (line 190) | function getURL(): URL {
  function getHeaders (line 198) | function getHeaders(): Headers {
  function getAppContext (line 206) | function getAppContext(): AppContext {

FILE: framework/lib/framework.webpack.ts
  type ConfigDetails (line 19) | interface ConfigDetails {
  type ConfigFunction (line 24) | interface ConfigFunction {
  type WebpackLoader (line 31) | type WebpackLoader = {
  function getWebpackConfig (line 46) | async function getWebpackConfig(
  function baseServerConfig (line 183) | async function baseServerConfig({
  function baseSSRConfig (line 303) | async function baseSSRConfig({
  function baseBrowserConfig (line 418) | async function baseBrowserConfig({
  function findFileIfExists (line 529) | async function findFileIfExists(dir: string, names: string[]) {
  type Lines (line 546) | type Lines = (string | Lines)[];
  function indent (line 547) | function indent(lines: Lines, indentLevel = 0): string {
  function generateServerRoutes (line 561) | async function generateServerRoutes(_outFile: string, routesDir: string) {
  function makeRouteIdFromRouteFile (line 657) | function makeRouteIdFromRouteFile(routeFile: string) {
  function makePathnameFromRouteId (line 663) | function makePathnameFromRouteId(routeId: string) {
  function snakeCase (line 701) | function snakeCase(str: string) {

FILE: framework/lib/react.client.browser.tsx
  type Window (line 6) | interface Window {
  function createFromReadableStream (line 11) | function createFromReadableStream(
  function registerServerReference (line 19) | function registerServerReference(

FILE: framework/lib/react.client.node.tsx
  function createFromReadableStream (line 7) | function createFromReadableStream(
  function registerServerReference (line 41) | function registerServerReference(

FILE: framework/lib/react.server.node.tsx
  function renderToReadableStream (line 6) | function renderToReadableStream(

FILE: framework/lib/utils.ts
  function exposedNameFromResource (line 3) | function exposedNameFromResource(cwd: string, resource: string) {

FILE: framework/lib/webpack.federation-runtime-plugin.ts
  function rscFederationEnsureChunk (line 69) | function rscFederationEnsureChunk(chunkId: string): Promise<unknown> {

FILE: framework/lib/webpack.plugins.ts
  class ServerRSCPlugin (line 7) | class ServerRSCPlugin {
    method constructor (line 8) | constructor(
    method apply (line 21) | apply(compiler: webpack.Compiler) {
  class ClientRSCPlugin (line 213) | class ClientRSCPlugin {
    method constructor (line 214) | constructor(
    method apply (line 228) | apply(compiler: webpack.Compiler) {
  class ExternalTemplateRemotesPlugin (line 421) | class ExternalTemplateRemotesPlugin {
    method apply (line 423) | apply(compiler: webpack.Compiler) {
Condensed preview — 102 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (172K chars).
[
  {
    "path": ".gitignore",
    "chars": 29,
    "preview": ".DS_Store\ndist/\nnode_modules/"
  },
  {
    "path": ".vscode/extensions.json",
    "chars": 99,
    "preview": "{\n  \"recommendations\": [\n    \"biomejs.biome\",\n    \"csstools.postcss\",\n    \"heybourn.headwind\"\n  ]\n}"
  },
  {
    "path": ".vscode/settings.json",
    "chars": 172,
    "preview": "{\n\t\"editor.defaultFormatter\": \"biomejs.biome\",\n\t\"files.associations\": {\n\t\t\"*.css\": \"postcss\"\n\t},\n\t\"[postcss]\": {\n\t\t\"edit"
  },
  {
    "path": "README.md",
    "chars": 7547,
    "preview": "# Federated RSC Reference Architecture\n\nTHIS IS SUPERSEDED BY https://github.com/jacob-ebey/fuckin-around\n\nThis reposito"
  },
  {
    "path": "biome.json",
    "chars": 506,
    "preview": "{\n\t\"$schema\": \"https://biomejs.dev/schemas/1.5.1/schema.json\",\n\t\"files\": {\n\t\t\"ignoreUnknown\": true,\n\t\t\"include\": [\n\t\t\t\"*"
  },
  {
    "path": "examples/basic/app/components/counter.tsx",
    "chars": 399,
    "preview": "\"use client\";\n\nimport * as React from \"react\";\n\nfunction CounterBasic() {\n\tconst [count, setCount] = React.useState(0);\n"
  },
  {
    "path": "examples/basic/app/routes/_public/route.tsx",
    "chars": 916,
    "preview": "import { getHeaders, getURL } from \"framework\";\n\nexport function Component({ children }: { children: React.ReactNode }) "
  },
  {
    "path": "examples/basic/app/routes/_public.$/route.tsx",
    "chars": 148,
    "preview": "import { Counter } from \"../../components/counter\";\n\nexport function Component() {\n\treturn (\n\t\t<>\n\t\t\t<h1>Hello Glob</h1>"
  },
  {
    "path": "examples/basic/app/routes/_public.layout/route.tsx",
    "chars": 93,
    "preview": "export function Component({ children }: { children: React.ReactNode }) {\n\treturn children;\n}\n"
  },
  {
    "path": "examples/basic/app/routes/_public.slug.$slug/route.tsx",
    "chars": 61,
    "preview": "export function Component() {\n\treturn <h1>Hello Slug</h1>;\n}\n"
  },
  {
    "path": "examples/basic/app/routes/weather.$/route.tsx",
    "chars": 2742,
    "preview": "import { type Params } from \"framework\";\nimport * as React from \"react\";\n\nimport {\n\tTemperatureDisplay,\n\tTemperatureSwit"
  },
  {
    "path": "examples/basic/app/routes/weather.$/temperature-switch.tsx",
    "chars": 1272,
    "preview": "\"use client\";\n\nimport { createContext, useCallback, useContext, useState } from \"react\";\n\nconst temperatureContext = cre"
  },
  {
    "path": "examples/basic/package.json",
    "chars": 712,
    "preview": "{\n  \"name\": \"@example/basic\",\n  \"version\": \"1.0.0\",\n  \"scripts\": {\n    \"build\": \"remix build\",\n    \"start\": \"concurrentl"
  },
  {
    "path": "examples/basic/server.mts",
    "chars": 571,
    "preview": "import { serve } from \"@hono/node-server\";\nimport { serveStatic } from \"@hono/node-server/serve-static\";\nimport { Hono }"
  },
  {
    "path": "examples/basic/ssr-server.mts",
    "chars": 472,
    "preview": "import dns from \"node:dns\";\n\nimport { serve } from \"@hono/node-server\";\nimport { Hono } from \"hono\";\n\nimport { handler }"
  },
  {
    "path": "examples/basic/tsconfig.json",
    "chars": 419,
    "preview": "{\n  \"exclude\": [\"node_modules\", \"dist\"],\n  \"compilerOptions\": {\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Bundler"
  },
  {
    "path": "examples/consumer/app/components/counter.tsx",
    "chars": 408,
    "preview": "\"use client\";\n\nimport * as React from \"react\";\n\nfunction CounterConsumer() {\n\tconst [count, setCount] = React.useState(0"
  },
  {
    "path": "examples/consumer/app/routes/_public/route.tsx",
    "chars": 354,
    "preview": "import { RSCFrame } from \"framework\";\n\nexport function Component({ children }: { children: React.ReactNode }) {\n\treturn "
  },
  {
    "path": "examples/consumer/app/routes/_public._index/route.tsx",
    "chars": 479,
    "preview": "import { RSCFrame } from \"framework\";\n\nimport { Counter } from \"../../components/counter\";\n\nexport function Component() "
  },
  {
    "path": "examples/consumer/app/routes/_public.about/route.tsx",
    "chars": 206,
    "preview": "import { Counter } from \"../../components/counter\";\n\nexport function Component({ children }: { children: React.ReactNode"
  },
  {
    "path": "examples/consumer/app/routes/_public.about.$slug/route.tsx",
    "chars": 67,
    "preview": "export function Component() {\n\treturn <h2>Hello About Slug</h2>;\n}\n"
  },
  {
    "path": "examples/consumer/package.json",
    "chars": 759,
    "preview": "{\n  \"name\": \"@example/consumer\",\n  \"version\": \"1.0.0\",\n  \"scripts\": {\n    \"build\": \"remix build\",\n    \"start\": \"concurre"
  },
  {
    "path": "examples/consumer/server.mts",
    "chars": 602,
    "preview": "import dns from \"node:dns\";\n\nimport { serve } from \"@hono/node-server\";\nimport { serveStatic } from \"@hono/node-server/s"
  },
  {
    "path": "examples/consumer/ssr-server.mts",
    "chars": 746,
    "preview": "import dns from \"node:dns\";\n\nimport { serve } from \"@hono/node-server\";\nimport { Hono } from \"hono\";\n\nimport { handler }"
  },
  {
    "path": "examples/consumer/tsconfig.json",
    "chars": 419,
    "preview": "{\n  \"exclude\": [\"node_modules\", \"dist\"],\n  \"compilerOptions\": {\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Bundler"
  },
  {
    "path": "examples/consumer/webpack.config.cjs",
    "chars": 702,
    "preview": "const { ModuleFederationPlugin } = require(\"@module-federation/enhanced\");\n\n/** @type {import(\"framework/webpack\").Confi"
  },
  {
    "path": "fixture/marketing/app/components/ui/avatar.tsx",
    "chars": 1129,
    "preview": "\"use client\";\n\nimport * as AvatarPrimitive from \"@radix-ui/react-avatar\";\nimport * as React from \"react\";\n\nimport { cn }"
  },
  {
    "path": "fixture/marketing/app/components/ui/button.tsx",
    "chars": 1896,
    "preview": "import { Slot } from \"@radix-ui/react-slot\";\nimport { type VariantProps, cva } from \"class-variance-authority\";\nimport *"
  },
  {
    "path": "fixture/marketing/app/components/ui/card.tsx",
    "chars": 1832,
    "preview": "import * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\nconst Card = React.forwardRef<\n\tHTMLDivElement,\n\tRea"
  },
  {
    "path": "fixture/marketing/app/components/ui/input.tsx",
    "chars": 789,
    "preview": "import * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport interface InputProps\n\textends React.InputHTML"
  },
  {
    "path": "fixture/marketing/app/components/ui/separator.tsx",
    "chars": 737,
    "preview": "\"use client\";\n\nimport * as SeparatorPrimitive from \"@radix-ui/react-separator\";\nimport * as React from \"react\";\n\nimport "
  },
  {
    "path": "fixture/marketing/app/lib/utils.ts",
    "chars": 168,
    "preview": "import { type ClassValue, clsx } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: C"
  },
  {
    "path": "fixture/marketing/app/remotes.tsx",
    "chars": 585,
    "preview": "import { RSCFrame } from \"framework\";\n\ndeclare global {\n\t// biome-ignore lint/style/noVar: <explanation>\n\tvar __REMOTES_"
  },
  {
    "path": "fixture/marketing/app/routes/_public/route.tsx",
    "chars": 574,
    "preview": "import { Link, getURL } from \"framework\";\n\nimport { FederatedRSCFrame } from \"../../remotes\";\n\nimport styleFile from \"./"
  },
  {
    "path": "fixture/marketing/app/routes/_public/style.css",
    "chars": 43,
    "preview": "@tailwind components;\n@tailwind utilities;\n"
  },
  {
    "path": "fixture/marketing/app/routes/_public._index/products.tsx",
    "chars": 2033,
    "preview": "import {\n\tCard,\n\tCardContent,\n\tCardDescription,\n\tCardFooter,\n\tCardHeader,\n\tCardTitle,\n} from \"@/components/ui/card\";\n\nex"
  },
  {
    "path": "fixture/marketing/app/routes/_public._index/route.tsx",
    "chars": 1193,
    "preview": "import { ProductCard, ProductList } from \"./products\";\n\nexport async function Component() {\n\tconst url = new URL(\"https:"
  },
  {
    "path": "fixture/marketing/app/routes/_public.product.$handle/actions.tsx",
    "chars": 205,
    "preview": "export async function addToCart() {\n\t\"use server\";\n\tconsole.log(\"Adding to cart!\");\n\tawait new Promise((resolve) => setT"
  },
  {
    "path": "fixture/marketing/app/routes/_public.product.$handle/client.tsx",
    "chars": 2657,
    "preview": "\"use client\";\n\nimport { useLocation } from \"framework/client\";\nimport * as React from \"react\";\nimport { useFormStatus } "
  },
  {
    "path": "fixture/marketing/app/routes/_public.product.$handle/form.tsx",
    "chars": 902,
    "preview": "import { getURL } from \"framework\";\n\nimport { Input } from \"@/components/ui/input\";\n\nimport { addToCart } from \"./action"
  },
  {
    "path": "fixture/marketing/app/routes/_public.product.$handle/product.tsx",
    "chars": 873,
    "preview": "export function ProductHeader({\n\ttitle,\n\tdescription,\n\tpriceRange,\n}: {\n\ttitle: string;\n\tdescription?: string;\n\tpriceRan"
  },
  {
    "path": "fixture/marketing/app/routes/_public.product.$handle/reviews.tsx",
    "chars": 4709,
    "preview": "import { StarIcon } from \"@radix-ui/react-icons\";\n\nimport { Avatar, AvatarFallback, AvatarImage } from \"@/components/ui/"
  },
  {
    "path": "fixture/marketing/app/routes/_public.product.$handle/route.tsx",
    "chars": 3197,
    "preview": "import { getActionResult, getURL } from \"framework\";\nimport { type RouteProps } from \"framework\";\n\nimport { Separator } "
  },
  {
    "path": "fixture/marketing/components.json",
    "chars": 305,
    "preview": "{\n\t\"$schema\": \"https://ui.shadcn.com/schema.json\",\n\t\"style\": \"new-york\",\n\t\"rsc\": true,\n\t\"tsx\": true,\n\t\"tailwind\": {\n\t\t\"c"
  },
  {
    "path": "fixture/marketing/modules.d.ts",
    "chars": 70,
    "preview": "declare module \"*.css\" {\n\tconst href: string;\n\texport default href;\n}\n"
  },
  {
    "path": "fixture/marketing/package.json",
    "chars": 1374,
    "preview": "{\n  \"name\": \"@fixture/marketing\",\n  \"version\": \"1.0.0\",\n  \"bundler\": {\n    \"include\": []\n  },\n  \"scripts\": {\n    \"build\""
  },
  {
    "path": "fixture/marketing/postcss.config.cjs",
    "chars": 89,
    "preview": "module.exports = {\n\tplugins: [require(\"postcss-preset-env\"), require(\"tailwindcss\")],\n};\n"
  },
  {
    "path": "fixture/marketing/remotes.cjs",
    "chars": 198,
    "preview": "exports.REMOTES = {\n\t_fixture_shell: {\n\t\trequire: \"../../../shell/dist/ssr/_fixture_shell.js\",\n\t\trsc: \"http://localhost:"
  },
  {
    "path": "fixture/marketing/server.mts",
    "chars": 953,
    "preview": "import * as dns from \"node:dns\";\n\nimport { serve } from \"@hono/node-server\";\nimport { serveStatic } from \"@hono/node-ser"
  },
  {
    "path": "fixture/marketing/ssr-server.mts",
    "chars": 472,
    "preview": "import dns from \"node:dns\";\n\nimport { serve } from \"@hono/node-server\";\nimport { Hono } from \"hono\";\n\nimport { handler }"
  },
  {
    "path": "fixture/marketing/tailwind.config.cjs",
    "chars": 2252,
    "preview": "/**\n * @type {import('tailwindcss').Config}\n */\nmodule.exports = {\n\tcontent: [\"./app/**/*.tsx\"],\n\tdarkMode: \"media\",\n\tth"
  },
  {
    "path": "fixture/marketing/tsconfig.json",
    "chars": 450,
    "preview": "{\n\t\"exclude\": [\"node_modules\", \"dist\"],\n\t\"compilerOptions\": {\n\t\t\"module\": \"ESNext\",\n\t\t\"moduleResolution\": \"Bundler\",\n\t\t\""
  },
  {
    "path": "fixture/marketing/webpack.config.cjs",
    "chars": 3442,
    "preview": "const { ModuleFederationPlugin } = require(\"@module-federation/enhanced\");\nconst TsconfigPathsPlugin = require(\"tsconfig"
  },
  {
    "path": "fixture/shell/app/components/ui/button.tsx",
    "chars": 1658,
    "preview": "import { Slot } from \"@radix-ui/react-slot\";\nimport { type VariantProps, cva } from \"class-variance-authority\";\nimport *"
  },
  {
    "path": "fixture/shell/app/lib/utils.ts",
    "chars": 168,
    "preview": "import { type ClassValue, clsx } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: C"
  },
  {
    "path": "fixture/shell/app/remotes.tsx",
    "chars": 632,
    "preview": "import { RSCFrame } from \"framework\";\n\ndeclare global {\n\t// biome-ignore lint/style/noVar: <explanation>\n\tvar __REMOTES_"
  },
  {
    "path": "fixture/shell/app/routes/_public/client.tsx",
    "chars": 681,
    "preview": "\"use client\";\n\nimport { useLocation } from \"framework/client\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport function Globa"
  },
  {
    "path": "fixture/shell/app/routes/_public/header.tsx",
    "chars": 1634,
    "preview": "import { Button } from \"@/components/ui/button\";\n\nexport function Header() {\n\treturn (\n\t\t<header className=\"w-full\">\n\t\t\t"
  },
  {
    "path": "fixture/shell/app/routes/_public/route.tsx",
    "chars": 961,
    "preview": "import { Link, getHeaders, getURL } from \"framework\";\n\nimport { GlobalStatusIndicator } from \"./client\";\nimport { Header"
  },
  {
    "path": "fixture/shell/app/routes/_public/style.css",
    "chars": 1446,
    "preview": "@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n@layer base {\n  :root {\n    --background: 0 0% 100%;\n    --f"
  },
  {
    "path": "fixture/shell/app/routes/_public.$/route.tsx",
    "chars": 458,
    "preview": "export async function Component() {\n\treturn (\n\t\t<section className=\"w-full py-12 md:py-24 lg:py-32\">\n\t\t\t<div className=\""
  },
  {
    "path": "fixture/shell/app/routes/_public._index/route.tsx",
    "chars": 157,
    "preview": "import { FederatedRSCFrame } from \"../../remotes\";\n\nexport async function Component() {\n\treturn <FederatedRSCFrame remot"
  },
  {
    "path": "fixture/shell/app/routes/_public.product.$handle/route.tsx",
    "chars": 354,
    "preview": "import { type RouteProps } from \"framework\";\nimport { getURL } from \"framework\";\n\nimport { FederatedRSCFrame } from \"../"
  },
  {
    "path": "fixture/shell/app/routes/api.shell/route.tsx",
    "chars": 46,
    "preview": "export { Component } from \"../_public/route\";\n"
  },
  {
    "path": "fixture/shell/components.json",
    "chars": 305,
    "preview": "{\n\t\"$schema\": \"https://ui.shadcn.com/schema.json\",\n\t\"style\": \"new-york\",\n\t\"rsc\": true,\n\t\"tsx\": true,\n\t\"tailwind\": {\n\t\t\"c"
  },
  {
    "path": "fixture/shell/modules.d.ts",
    "chars": 70,
    "preview": "declare module \"*.css\" {\n\tconst href: string;\n\texport default href;\n}\n"
  },
  {
    "path": "fixture/shell/package.json",
    "chars": 1165,
    "preview": "{\n  \"name\": \"@fixture/shell\",\n  \"version\": \"1.0.0\",\n  \"scripts\": {\n    \"build\": \"remix build\",\n    \"start\": \"concurrentl"
  },
  {
    "path": "fixture/shell/postcss.config.cjs",
    "chars": 89,
    "preview": "module.exports = {\n\tplugins: [require(\"postcss-preset-env\"), require(\"tailwindcss\")],\n};\n"
  },
  {
    "path": "fixture/shell/remotes.cjs",
    "chars": 214,
    "preview": "exports.REMOTES = {\n\t_fixture_marketing: {\n\t\trequire: \"../../../marketing/dist/ssr/_fixture_marketing.js\",\n\t\trsc: \"http:"
  },
  {
    "path": "fixture/shell/server.mts",
    "chars": 820,
    "preview": "import * as dns from \"node:dns\";\n\nimport { serve } from \"@hono/node-server\";\nimport { serveStatic } from \"@hono/node-ser"
  },
  {
    "path": "fixture/shell/ssr-server.mts",
    "chars": 533,
    "preview": "import dns from \"node:dns\";\n\nimport { serve } from \"@hono/node-server\";\nimport { Hono } from \"hono\";\n\nimport { handler }"
  },
  {
    "path": "fixture/shell/tailwind.config.cjs",
    "chars": 2104,
    "preview": "/**\n * @type {import('tailwindcss').Config}\n */\nmodule.exports = {\n\tcontent: [\"./app/**/*.tsx\"],\n\tdarkMode: \"media\",\n\tth"
  },
  {
    "path": "fixture/shell/tsconfig.json",
    "chars": 560,
    "preview": "{\n  \"include\": [\"**/*.mts\", \"**/*.ts\", \"**/*.tsx\", \"**/*.mjs\", \"**/*.cjs\"],\n  \"exclude\": [\"node_modules\", \"dist\"],\n  \"co"
  },
  {
    "path": "fixture/shell/webpack.config.cjs",
    "chars": 3442,
    "preview": "const { ModuleFederationPlugin } = require(\"@module-federation/enhanced\");\nconst TsconfigPathsPlugin = require(\"tsconfig"
  },
  {
    "path": "framework/bin/remix.cjs",
    "chars": 182,
    "preview": "#!/usr/bin/env node\n\nimport(\"../cli/build.mjs\")\n\t.then(({ build }) => build())\n\t.catch((reason) => {\n\t\tif (process.env.D"
  },
  {
    "path": "framework/cli/build.mjs",
    "chars": 3105,
    "preview": "import * as path from \"node:path\";\n\nimport webpack from \"webpack\";\n// @ts-expect-error\nimport { formatMessages } from \"w"
  },
  {
    "path": "framework/entry/browser.tsx",
    "chars": 926,
    "preview": "// @ts-expect-error - no types\nimport RSDC from \"react-server-dom-webpack/client\";\n\nimport { hydrate } from \"framework/b"
  },
  {
    "path": "framework/entry/empty.tsx",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "framework/entry/server.tsx",
    "chars": 146,
    "preview": "import { createRequestHandler } from \"framework/server\";\n\nimport { routes } from \"#routes\";\n\nexport const handler = crea"
  },
  {
    "path": "framework/entry/ssr.tsx",
    "chars": 3589,
    "preview": "import * as stream from \"node:stream\";\nimport type * as streamWeb from \"node:stream/web\";\n\nimport * as React from \"react"
  },
  {
    "path": "framework/lib/framework.browser.tsx",
    "chars": 4812,
    "preview": "import * as React from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\n// @ts-expect-error - no types\nimport RS"
  },
  {
    "path": "framework/lib/framework.client.internal.tsx",
    "chars": 557,
    "preview": "\"use client\";\n\nimport * as React from \"react\";\n\nimport {\n\tINTERNAL_Outlet,\n\tINTERNAL_OutletProvider,\n\tINTERNAL_StreamRea"
  },
  {
    "path": "framework/lib/framework.client.tsx",
    "chars": 5435,
    "preview": "import * as React from \"react\";\n\nimport { createFromReadableStream } from \"framework/react.client\";\n\nexport type Locatio"
  },
  {
    "path": "framework/lib/framework.runtime.client.ts",
    "chars": 242,
    "preview": "import { registerServerReference as registerServerReferenceImp } from \"framework/react.client\";\n\nexport function registe"
  },
  {
    "path": "framework/lib/framework.runtime.server.ts",
    "chars": 462,
    "preview": "import {\n\tregisterClientReference as registerClientReferenceImp,\n\tregisterServerReference as registerServerReferenceImp,"
  },
  {
    "path": "framework/lib/framework.server.tsx",
    "chars": 4621,
    "preview": "import {\n\tcreateStaticHandler,\n\ttype AgnosticDataRouteObject,\n} from \"@remix-run/router\";\nimport * as React from \"react\""
  },
  {
    "path": "framework/lib/framework.ssr.tsx",
    "chars": 2462,
    "preview": "import * as React from \"react\";\n\nexport async function InlinePayload({\n\tdecoder,\n\treadable,\n}: {\n\tdecoder?: TextDecoder;"
  },
  {
    "path": "framework/lib/framework.tsx",
    "chars": 5161,
    "preview": "import { type Params } from \"@remix-run/router\";\nimport * as React from \"react\";\n// @ts-expect-error - no types\nimport R"
  },
  {
    "path": "framework/lib/framework.webpack.ts",
    "chars": 15997,
    "preview": "import * as fsp from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\ni"
  },
  {
    "path": "framework/lib/react.client.browser.tsx",
    "chars": 667,
    "preview": "import * as React from \"react\";\n// @ts-expect-error - no types\nimport RSD from \"react-server-dom-webpack/client\";\n\ndecla"
  },
  {
    "path": "framework/lib/react.client.node.tsx",
    "chars": 952,
    "preview": "import * as stream from \"node:stream\";\nimport * as webStream from \"node:stream/web\";\n\n// @ts-expect-error - no types\nimp"
  },
  {
    "path": "framework/lib/react.server.browser.tsx",
    "chars": 296,
    "preview": "// @ts-expect-error - no types\nimport * as RSDS from \"react-server-dom-webpack/server\";\n\nexport const renderToReadableSt"
  },
  {
    "path": "framework/lib/react.server.node.tsx",
    "chars": 743,
    "preview": "import * as stream from \"node:stream\";\n\n// @ts-expect-error - no types\nimport RSDS from \"react-server-dom-webpack/server"
  },
  {
    "path": "framework/lib/utils.ts",
    "chars": 418,
    "preview": "import * as path from \"node:path\";\n\nexport function exposedNameFromResource(cwd: string, resource: string) {\n\tconst rela"
  },
  {
    "path": "framework/lib/webpack.federation-runtime-plugin.ts",
    "chars": 4198,
    "preview": "import { Module } from \"@module-federation/runtime/dist/src/module/index.js\";\nimport type {\n\tFederationRuntimePlugin,\n\tR"
  },
  {
    "path": "framework/lib/webpack.plugins.ts",
    "chars": 11374,
    "preview": "import { ModuleFederationPlugin } from \"@module-federation/enhanced\";\nimport { rscClientPlugin, rscServerPlugin } from \""
  },
  {
    "path": "framework/package.json",
    "chars": 3323,
    "preview": "{\n\t\"name\": \"framework\",\n\t\"version\": \"1.0.0\",\n\t\"files\": [\"bin\", \"cli\", \"dist\", \"entry\"],\n\t\"bin\": {\n\t\t\"remix\": \"./bin/remi"
  },
  {
    "path": "framework/server-only.js",
    "chars": 71,
    "preview": "throw new Error(\"This module is only meant to be used on the server\");\n"
  },
  {
    "path": "framework/tsconfig.json",
    "chars": 437,
    "preview": "{\n  \"exclude\": [\"node_modules\", \"dist\"],\n  \"compilerOptions\": {\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Bundler"
  },
  {
    "path": "framework/tsconfig.lib.json",
    "chars": 394,
    "preview": "{\n\t\"include\": [\"./lib/**/*\"],\n\t\"compilerOptions\": {\n\t\t\"outDir\": \"dist\",\n\t\t\"declaration\": true,\n\t\t\"declarationMap\": true,"
  },
  {
    "path": "package.json",
    "chars": 480,
    "preview": "{\n  \"private\": true,\n  \"scripts\": {\n    \"build\": \"pnpm -r --filter framework --filter @fixture/* build\",\n    \"check\": \"b"
  },
  {
    "path": "pnpm-workspace.yaml",
    "chars": 59,
    "preview": "packages:\n  - \"examples/*\"\n  - \"fixture/*\"\n  - \"framework\"\n"
  }
]

About this extraction

This page contains the full source code of the jacob-ebey/federated-rsc GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 102 files (139.3 KB), approximately 42.9k tokens, and a symbol index with 114 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!