Skip to content

Commit

Permalink
get server actions working in DEV (little bit)
Browse files Browse the repository at this point in the history
  • Loading branch information
nksaraf committed Jul 26, 2023
1 parent fb28cf9 commit a63df01
Show file tree
Hide file tree
Showing 12 changed files with 265 additions and 27 deletions.
8 changes: 8 additions & 0 deletions examples/react/rsc/spa/app/actions.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
"use server";

let store = { count: 0 };
export function sayHello() {
console.log("Hello World");
store.count++;
return store.count;
}

export function getStore() {
console.log("getStore", store);
return store.count;
}
4 changes: 3 additions & 1 deletion examples/react/rsc/spa/app/app.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from "react";

import { Counter } from "./Counter";
import { sayHello } from "./actions";
import { getStore, sayHello } from "./actions";
import "./style.css";

export default function App({ assets }) {
Expand All @@ -15,6 +15,8 @@ export default function App({ assets }) {
<section>
<h1>Hello AgentConf with ya asdo!!!</h1>
<div>Hello World</div>

{getStore()}
<Counter onChange={sayHello} />
</section>
</body>
Expand Down
30 changes: 22 additions & 8 deletions examples/react/rsc/spa/app/react-server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,20 @@ export default eventHandler(async (event) => {
// req.pipe(bb);
// args = await reply;
// } else {
args = await decodeReply(event.node.req);
const text = await new Promise((resolve) => {
const requestBody = [];
event.node.req.on("data", (chunks) => {
console.log(chunks);
requestBody.push(chunks);
});
event.node.req.on("end", () => {
resolve(requestBody.join(""));
});
});
console.log(text);

args = await decodeReply(text);
console.log(args, action);
// }
const result = action.apply(null, args);
try {
Expand All @@ -48,25 +61,26 @@ export default eventHandler(async (event) => {
// We handle the error on the client
}
// Refresh the client and return the value
return {};
// return {};
} else {
throw new Error("Invalid request");
}
}
console.log("rendering");
const reactServerManifest = import.meta.env.MANIFEST["rsc"];
const serverAssets = await reactServerManifest.inputs[
reactServerManifest.handler
].assets();
// const serverAssets = await reactServerManifest.inputs[
// reactServerManifest.handler
// ].assets();
const clientManifest = import.meta.env.MANIFEST["client"];
const assets = await clientManifest.inputs[clientManifest.handler].assets();
// const assets = await clientManifest.inputs[clientManifest.handler].assets();

const events = {};
const stream = renderToPipeableStream(
<App
assets={
<Suspense>
{serverAssets.map((m) => renderAsset(m))}
{assets.map((m) => renderAsset(m))}
{/* {serverAssets.map((m) => renderAsset(m))} */}
{/* {assets.map((m) => renderAsset(m))} */}
</Suspense>
}
/>,
Expand Down
13 changes: 8 additions & 5 deletions examples/react/rsc/spa/app/server-component.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { createFromFetch } from "@vinxi/react-server-dom-vite/client";
import {
createFromFetch,
encodeReply,
} from "@vinxi/react-server-dom-vite/client";
import * as React from "react";
import { startTransition, use, useState } from "react";
import ReactDOM from "react-dom/client";
Expand Down Expand Up @@ -41,22 +44,22 @@ export const serverElementCache = /*#__PURE__*/ new Map<
>();

async function callServer(id, args) {
const response = fetch("/", {
const response = fetch("/_rsc", {
method: "POST",
headers: {
Accept: "text/x-component",
"rsc-action": id,
},
// body: await encodeReply(args),
body: await encodeReply(args),
});
const { returnValue, root } = await createFromFetch(response, {
const root = await createFromFetch(response, {
callServer,
});
// Refresh the tree with the new RSC payload.
startTransition(() => {
updateRoot(root);
});
return returnValue;
// return returnValue;
}

export function useServerElement(url: string) {
Expand Down
3 changes: 0 additions & 3 deletions examples/react/rsc/ssr/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,6 @@ function clientComponents() {
),
};

console.log(input);

return {
ssr: {
external: ["react", "react-dom", "@vinxi/react-server-dom-vite"],
Expand All @@ -154,7 +152,6 @@ function clientComponents() {
// },
build: {
rollupOptions: {

// preserve the export names of the server actions in chunks
treeshake: true,
// required otherwise rollup will remove the exports since they are not used
Expand Down
14 changes: 13 additions & 1 deletion examples/react/rsc/ssr/app/react-server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,19 @@ export default eventHandler(async (event) => {
// req.pipe(bb);
// args = await reply;
// } else {
args = await decodeReply(event.node.req);
const text = await new Promise((resolve) => {
const requestBody = [];
event.node.req.on("data", (chunks) => {
requestBody.push(chunks);
});
event.node.req.on("end", () => {
resolve(Buffer.concat(requestBody).toString());
});
});
console.log(text);

args = await decodeReply(text);
console.log(args);
// }
const result = action.apply(null, args);
try {
Expand Down
7 changes: 5 additions & 2 deletions examples/react/rsc/ssr/app/server-component.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { createFromFetch } from "@vinxi/react-server-dom-vite/client";
import {
createFromFetch,
encodeReply,
} from "@vinxi/react-server-dom-vite/client";
import * as React from "react";
import { startTransition, use, useState } from "react";

Expand Down Expand Up @@ -46,7 +49,7 @@ async function callServer(id, args) {
Accept: "text/x-component",
"rsc-action": id,
},
// body: await encodeReply(args),
body: await encodeReply(args),
});
const { returnValue, root } = await createFromFetch(response, {
callServer,
Expand Down
2 changes: 1 addition & 1 deletion examples/react/rsc/ssr/app/server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export default eventHandler(async (event) => {
objectMode: true,
});
readable._read = () => {};
readable.headers = {};
readable.headers = event.node.req.headers;

const writableStream = new Writable({
write(chunk, encoding, callback) {
Expand Down
91 changes: 90 additions & 1 deletion packages/vinxi/lib/app-worker-client.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createRequire } from "node:module";
import { Readable } from "node:stream";
import { Readable, Writable } from "node:stream";
import { ReadableStream } from "node:stream/web";
import { Worker } from "node:worker_threads";

Expand Down Expand Up @@ -174,6 +174,95 @@ export class AppWorkerClient {
return readable;
}

/**
*
* @param {import('h3').H3Event} event
* @returns
*/
handle(event) {
const { req, res } = event.node;
invariant(this.worker, "Worker is not initialize");
const id = Math.random() + "";
const worker = this.worker;
worker.postMessage(
JSON.stringify({
// component,
// props,
req: {
method: req.method,
url: req.url,
headers: req.headers,
},
type: "handle",
id,
}),
);

const writableStream = new Writable({
write(chunk, encoding, callback) {
worker.postMessage(
JSON.stringify({
chunk: new TextDecoder().decode(chunk),
type: "body",
id: id,
}),
);
callback();
},
});

writableStream.on("finish", () => {
worker.postMessage(
JSON.stringify({
chunk: "end",
type: "body",
id,
}),
);
});

// req.on("data", (chunk) => {
// this.worker.postMessage(
// JSON.stringify({
// chunk,
// type: "body",
// id,
// }),
// );
// });

// req.on("end", () => {
// this.worker.postMessage(
// JSON.stringify({
// type: "body-end",
// id,
// }),
// );
// });

req.pipe(writableStream);

let responses = this.responses;
const readable = new Readable({
objectMode: true,
});
readable._read = () => {};

responses.set(id, ({ chunk, data }) => {
if (chunk === "end") {
res.end();
responses.delete(id);
} else if (chunk === "$header") {
console.log("header", data);
res.setHeader(data.key, data.value);
} else if (chunk) {
res.write(chunk);
}
});

return readable;
}

fetch() {
invariant(this.worker, "Worker is not initialize");
const id = Math.random() + "";
Expand Down
Loading

0 comments on commit a63df01

Please sign in to comment.