Skip to content

Commit

Permalink
feat(workerd): stream eval
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa committed Apr 15, 2024
1 parent 47870bc commit 99e43c8
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
9 changes: 6 additions & 3 deletions packages/workerd/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,12 @@ export async function createWorkerdDevEnvironment(
JSON.stringify({
entry: ctx.entry,
fnString: ctx.fn.toString(),
stream: ctx.stream,
} satisfies EvalMetadata),
);
const body = JSON.stringify(ctx.data ?? (null as any));
const body: any = ctx.stream
? ctx.data
: JSON.stringify(ctx.data ?? (null as any));
const fetch_ = runnerObject.fetch as any as typeof fetch; // fix web/undici types
const response = await fetch_(ANY_URL + RUNNER_EVAL_PATH, {
method: "POST",
Expand All @@ -217,8 +220,8 @@ export async function createWorkerdDevEnvironment(
duplex: "half",
});
tinyassert(response.ok);
const result = await response.json();
return result as any;
const result: any = ctx.stream ? response.body : await response.json();
return result;
},
};

Expand Down
2 changes: 2 additions & 0 deletions packages/workerd/src/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ export type EvalApi = <In = any, Out = any>(request: {
entry: string;
data?: In;
fn: EvalFn<In, Out>;
stream?: boolean;
}) => Promise<Awaited<Out>>;

export type EvalMetadata = {
entry: string;
fnString: string;
stream?: boolean;
};
4 changes: 2 additions & 2 deletions packages/workerd/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,13 @@ export class RunnerObject implements DurableObject {
request.headers.get("x-vite-eval")!,
) as EvalMetadata;
const mod = await this.#runner.import(meta.entry);
const data = await request.json();
const data = meta.stream ? request.body : await request.json();
const env = objectPickBy(this.#env, (_v, k) => !k.startsWith("__vite"));
const fn: EvalFn = this.#env.__viteUnsafeEval.eval(
`() => ${meta.fnString}`,
)();
const result = await fn({ mod, data, env, runner: this.#runner });
const body = JSON.stringify(result ?? null);
const body = meta.stream ? result : JSON.stringify(result ?? null);
return new Response(body);
}

Expand Down

0 comments on commit 99e43c8

Please sign in to comment.