diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 41a9d846..99635869 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,4 +36,7 @@ jobs: run: deno cache --no-check src/cli/deps.ts src/runtime/deps.ts src/server/deps.ts - name: Run tests - run: deno test -A --no-check + run: deno test -A --no-check=remote + + - name: Type check website + run: deno cache --no-check=remote www/main.ts diff --git a/cli.ts b/cli.ts index fd7a4538..cd1e63b0 100644 --- a/cli.ts +++ b/cli.ts @@ -1,6 +1,6 @@ import { parseArgs } from "./src/cli/deps.ts"; import { initSubcommand } from "./src/cli/init.ts"; -import { routesSubcommand } from "./src/cli/routes.ts"; +import { manifestSubcommand } from "./src/cli/manifest.ts"; const VERSION = "0.1.0"; @@ -10,12 +10,12 @@ Preact, but super edgy. To initalize a new project: fresh init ./myproject -To (re-)generate route manifest: - fresh routes +To (re-)generate the manifest file: + fresh manifest SUBCOMMANDS: init Initalize a fresh project - routes (Re-)generate the route manifest file + manifest (Re-)generate the manifest file `; const args = parseArgs(Deno.args, { @@ -34,8 +34,8 @@ switch (subcommand) { case "init": await initSubcommand(args); break; - case "routes": - await routesSubcommand(args); + case "manifest": + await manifestSubcommand(args); break; default: if (args.version) { diff --git a/docs/data-fetching.md b/docs/data-fetching.md index 4a2ca37e..2927733b 100644 --- a/docs/data-fetching.md +++ b/docs/data-fetching.md @@ -4,35 +4,50 @@ Not all pages can be server rendered synchronously - some pages are dynamic and require fetching some data from an external source. This data fetching is often asynchronous. -Fresh supports asynchronous data fetch in server render using suspense. This -allows render to be interupted to wait for a promise to resolve. Once the -promise resolves, the render is retried. +Fresh supports asynchronous data fetching in handlers. This is not done during +rendering, but before rendering in the route +handler. -## `useData` hook +## Fetching data in a `handler` -To make using asynchronous data sources during server render super easy, fresh -exposes the `useData` hook. This hook takes a key and a fetcher function that -can return a promise. It is invoked once on the server. The server will wait -until the promise resolves, at which point it will render the page with the new -data. +To fetch data, you must first define a custom `handler` function. This function +is called when the route is requested. In there you can do some handling, and +then return a `Response` object. If you want to render the page, you can call +the `ctx.render` function. This returns a `Promise` that you can +return from the handler. -The fetcher for the `useData` hook is never run on the client. Instead the data -that was computed on the server during render will be used. +The `ctx.render` function takes a single argument, which is some data that you +want to pass to the page template. The data can be accessed in the template via +the `props.data` property. -Here is a usage example of a `useData` hook where the fetcher fetches the URL -provided as the key as JSON: +Here is a usage example of a `handler` fetches a URL as JSON and provides the +resulting data to the template: ```tsx -import { h, PageProps, useData } from "../deps.ts"; +import { h, Handlers, PageProps, useData } from "../deps.ts"; -export default function Page(_props: PageProps) { - const info = useData("https://cdn.deno.land/std/meta/versions.json", fetcher); +interface ModuleInfo { + latest: string; + versions: string[]; +} - if (info === null) { +export const handler: Handlers = { + async GET(ctx) { + const resp = await fetch("https://cdn.deno.land/std/meta/versions.json"); + let data = null; + if (resp.status === 200) data = await resp.json(); + return ctx.render(data); + }, +}; + +export default function Page(props: PageProps) { + const data = props.data; + + if (data === null) { return
Data not available.
; } - const { latest, versions } = info; + const { latest, versions } = data; return (

The Deno standard library has {versions.length} versions, with {latest} @@ -41,19 +56,7 @@ export default function Page(_props: PageProps) {

); } - -interface ModuleInfo { - latest: string; - versions: string[]; -} - -async function fetcher(url: string): Promise { - const resp = await fetch(url); - if (resp.status === 200) return resp.json(); - return null; -} ``` -The `useData` can not generate data client side. Calling `useData` on the client -with a key that no data was generated for on the server will result in `useData` -throwing an error. +If you want to fetch data client side, inside of an island, you can use +libraries like `"swr"`, or raw `useEffect` and `useState` as you usually would. diff --git a/docs/file-system-routing.md b/docs/file-system-routing.md index cd819df0..34268339 100644 --- a/docs/file-system-routing.md +++ b/docs/file-system-routing.md @@ -1,6 +1,6 @@ # File system routing -The naming and location of files in the `pages` folder is important because +The naming and location of files in the `routes` folder is important because these are used to specify the route where a specific API endpoint or HTML page is available. This concept is called file system routing. diff --git a/docs/getting-started.md b/docs/getting-started.md index d4bfde93..fb4fb428 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -66,13 +66,11 @@ to Deno Deploy with (or an organization you can access from that account). Then follow the setup instructions for GitHub on your machine, and push your code into the repository. -Now go back to GitHub and open the `main.ts` file that you pushed. Copy the URL -in the address bar. It should look something like this: -`https://github.com/lucacasonato/fresh/blob/main/example/main.ts`. Visit your -project on dash.deno.com, enter the URL you copied into the -`Link GitHub repository` input box in the project settings, and press `Link`. -You might need to grant the Deno Deploy app permission to the repository at this -point (follow prompts on the Deno Deploy dashboard). +Visit your project on dash.deno.com, go to the "Git" tab in the settings, select +your organization and repository, select your production branch (usually +`main`), and finally select your entrypoint module (`main.ts`. You might need to +grant the Deno Deploy app permission to the repository at this point (follow +prompts on the Deno Deploy dashboard). Your project is now linked to Deno Deploy and will automatically deployed on every push. Your project now has a URL you can visit to view your site live. diff --git a/docs/project-structure.md b/docs/project-structure.md index 7d40e8ff..60a12f2e 100644 --- a/docs/project-structure.md +++ b/docs/project-structure.md @@ -1,24 +1,24 @@ # Project strcture Initalizing a fresh project will generate multiple files. For now the most -important files are `main.ts`, `routes.gen.ts`, and the pages and api routes in -the `pages` subfolder. +important files are `main.ts`, `fresh.gen.ts`, the route modules in the `routes` +subdirectory, and the islands in the `islands` subdirectory. The `main.ts` file is the entrypoint to your project. It is the file you link in Deno Deploy, or run locally with the `deno` CLI. -The `routes.gen.ts` file is a manifest of all pages and api routes in a project. -When moving around or creating new pages, this file needs to be updated. This is -done automatically when you run the `fresh routes` command. You never have to -edit this file manually. +The `fresh.gen.ts` file is a manifest of all routes and islands in a project. +When moving around or creating new pages or islands, this file needs to be +updated. This is done automatically when you run the `fresh manifest` command. +You never have to edit this file manually. -The files in the `pages` subfolder describe the HTML pages and API endpoints of -your application. All pages can act as both API endpoints and possibly dynamic -HTML pages. More info about how the `pages` subfolder works can be found on the +The files in the `routes` subfolder describe the HTML pages and API endpoints of +your application. All routes can act as both API endpoints and dynamic HTML +pages. More info about how the `routes` subdirectory works can be found on the [file system routing](./file-system-routing.md) page. -Finally there is a `deps.ts` and `api_deps.ts`. These files are the central -location for all external imports. The `deps.ts` file is used for runtime -dependencies (ones that are used both on the server and on the client), and the -`api_deps.ts` file is used for server only dependencies (for example ones used -in API routes). +Finally there is a `client_deps.ts` and `server_deps.ts`. These files are the +central location for all external imports. The `client_deps.ts` file is used for +runtime dependencies (ones that are used both in routes and islands), and the +`server_deps.ts` file is used for server only dependencies (for example ones +used in API routes or middleware). diff --git a/examples/counter/README.md b/examples/counter/README.md new file mode 100644 index 00000000..2e1dece7 --- /dev/null +++ b/examples/counter/README.md @@ -0,0 +1,16 @@ +# fresh project + +### Usage + +Start the project: + +``` +deno run -A --watch main.ts +``` + +After adding, removing, or moving a page in the `routes` or directory, or +adding, removing, or moving an island in the `islands` directory, run: + +``` +fresh manifest +``` diff --git a/examples/todo-app/deps.ts b/examples/counter/client_deps.ts similarity index 50% rename from examples/todo-app/deps.ts rename to examples/counter/client_deps.ts index 4c772c75..3ccecce5 100644 --- a/examples/todo-app/deps.ts +++ b/examples/counter/client_deps.ts @@ -1,2 +1 @@ export * from "../../runtime.ts"; -export * from "../../server.ts"; diff --git a/examples/counter/fresh.gen.ts b/examples/counter/fresh.gen.ts new file mode 100644 index 00000000..cac718f5 --- /dev/null +++ b/examples/counter/fresh.gen.ts @@ -0,0 +1,18 @@ +// DO NOT EDIT. This file is generated by `fresh`. +// This file SHOULD be checked into source version control. +// To update this file, run `fresh routes`. + +import * as $0 from "./routes/index.tsx"; +import * as $$0 from "./islands/Counter.tsx"; + +const manifest = { + routes: { + "./routes/index.tsx": $0, + }, + islands: { + "./islands/Counter.tsx": $$0, + }, + baseUrl: import.meta.url, +}; + +export default manifest; diff --git a/examples/counter/islands/Counter.tsx b/examples/counter/islands/Counter.tsx new file mode 100644 index 00000000..cb298145 --- /dev/null +++ b/examples/counter/islands/Counter.tsx @@ -0,0 +1,21 @@ +/** @jsx h */ +import { h, IS_BROWSER, useState } from "../client_deps.ts"; + +interface CounterProps { + start: number; +} + +export default function Counter(props: CounterProps) { + const [count, setCount] = useState(props.start); + return ( +
+

{count}

+ + +
+ ); +} diff --git a/examples/todo-app/main.ts b/examples/counter/main.ts similarity index 57% rename from examples/todo-app/main.ts rename to examples/counter/main.ts index d65a6340..5886c41c 100644 --- a/examples/todo-app/main.ts +++ b/examples/counter/main.ts @@ -1,11 +1,10 @@ /// /// -/// /// /// /// -import { start } from "../../server.ts"; -import routes from "./routes.gen.ts"; +import { start } from "./server_deps.ts"; +import manifest from "./fresh.gen.ts"; -await start(routes); +await start(manifest); diff --git a/examples/counter/routes/index.tsx b/examples/counter/routes/index.tsx new file mode 100644 index 00000000..39f5ec19 --- /dev/null +++ b/examples/counter/routes/index.tsx @@ -0,0 +1,15 @@ +/** @jsx h */ +import { h } from "../client_deps.ts"; +import Counter from "../islands/Counter.tsx"; + +export default function Home() { + return ( +
+

+ Welcome to `fresh`. Try update this message in the ./routes/index.tsx + file, and refresh. +

+ +
+ ); +} diff --git a/examples/counter/server_deps.ts b/examples/counter/server_deps.ts new file mode 100644 index 00000000..0318a0be --- /dev/null +++ b/examples/counter/server_deps.ts @@ -0,0 +1 @@ +export * from "../../server.ts"; diff --git a/examples/todo-app/.vscode/settings.json b/examples/todo-app/.vscode/settings.json deleted file mode 100644 index e40716fd..00000000 --- a/examples/todo-app/.vscode/settings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "deno.enable": true, - "deno.lint": true, - "deno.unstable": true -} diff --git a/examples/todo-app/README.md b/examples/todo-app/README.md deleted file mode 100644 index 664ae48a..00000000 --- a/examples/todo-app/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# fresh project - -### Usage - -Start the project: - -``` -deno run -A --watch main.ts -``` - -After adding, removing, or moving a page in the `pages` directory, run: - -``` -fresh routes -``` diff --git a/examples/todo-app/pages/index.tsx b/examples/todo-app/pages/index.tsx deleted file mode 100644 index aac69683..00000000 --- a/examples/todo-app/pages/index.tsx +++ /dev/null @@ -1,50 +0,0 @@ -/** @jsx h */ -import { h, HandlerContext, PageConfig, Suspense, useData } from "../deps.ts"; -import { getDatabase, Todo } from "../utils/database.ts"; - -export default function TodoListPage() { - return ( -
-

Your TODOs

- - Loading...

}> - -
-
- ); -} - -function AddTodoForm() { - return ( -
- - -
- ); -} - -function TodoList() { - const todos = useData("todos", async () => { - const db = await getDatabase(); - const todos = await db.listTodos(); - return todos; - }); - return ( -
    - {todos.map((todo) =>
  • {todo.text}
  • )} -
- ); -} - -export const handler = { - async POST(ctx: HandlerContext): Promise { - const form = await ctx.req.formData(); - const text = form.get("text"); - if (typeof text !== "string") { - return new Response("misformed form", { status: 400 }); - } - const db = await getDatabase(); - await db.addTodo(text); - return Response.redirect(ctx.req.url, 303); - }, -}; diff --git a/examples/todo-app/routes.gen.ts b/examples/todo-app/routes.gen.ts deleted file mode 100644 index 5b4125c2..00000000 --- a/examples/todo-app/routes.gen.ts +++ /dev/null @@ -1,14 +0,0 @@ -// DO NOT EDIT. This file is generated by `fresh`. -// This file SHOULD be checked into source version control. -// To update this file, run `fresh routes`. - -import * as $0 from "./pages/index.tsx"; - -const routes = { - pages: { - "./pages/index.tsx": $0, - }, - baseUrl: import.meta.url, -}; - -export default routes; diff --git a/examples/todo-app/utils/database.ts b/examples/todo-app/utils/database.ts deleted file mode 100644 index 8208c206..00000000 --- a/examples/todo-app/utils/database.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { Client } from "https://raw.githubusercontent.com/denodrivers/postgres/72f523cb9d8f863204a3fa02f52d534e7ce30ccf/mod.ts"; - -export interface Todo { - id: number; - text: string; -} - -class Database { - #client: Client; - - constructor(client: Client) { - this.#client = client; - } - - static async connect() { - const client = new Client(Deno.env.get("DATABASE_URL")); - await client.connect(); - await client.queryObject`CREATE TABLE IF NOT EXISTS todos ( - id SERIAL PRIMARY KEY, - text TEXT NOT NULL - )`; - return new Database(client); - } - - async listTodos(): Promise { - const { rows } = await this.#client.queryObject`SELECT * FROM todos`; - return rows; - } - - async addTodo(text: string): Promise { - const { rows } = await this.#client.queryObject` - INSERT INTO todos (text) VALUES (${text}) - RETURNING * - `; - return rows[0]; - } -} - -const db: Database | Promise = Database.connect(); - -export async function getDatabase(): Promise { - return await db; -} diff --git a/makefile b/makefile index 038c60ce..1f976997 100644 --- a/makefile +++ b/makefile @@ -5,7 +5,7 @@ lint: deno lint test: - deno test -A --no-check + deno test -A --no-check=remote dev: deno run -A --watch=www/static --no-check www/main.ts \ No newline at end of file diff --git a/runtime.ts b/runtime.ts index b35eb535..788d9325 100644 --- a/runtime.ts +++ b/runtime.ts @@ -1,7 +1,5 @@ export * from "./src/runtime/deps.ts"; export * from "./src/runtime/types.ts"; -export * from "./src/runtime/suspense.ts"; export * from "./src/runtime/utils.ts"; -export * from "./src/runtime/hooks.ts"; export * from "./src/runtime/head.ts"; export * from "./src/runtime/csp.ts"; diff --git a/src/cli/init.ts b/src/cli/init.ts index 0f9f5e8f..d235ebac 100644 --- a/src/cli/init.ts +++ b/src/cli/init.ts @@ -1,6 +1,6 @@ import { join, resolve } from "./deps.ts"; import { error } from "./error.ts"; -import { routes } from "./routes.ts"; +import { manifest } from "./manifest.ts"; const help = `fresh init @@ -57,30 +57,50 @@ async function init(directory: string) { } } - await Deno.mkdir(join(directory, "pages", "api"), { recursive: true }); - const DEPS_TS = `export * from "${new URL( + await Deno.mkdir(join(directory, "routes", "api"), { recursive: true }); + await Deno.mkdir(join(directory, "islands"), { recursive: true }); + + const CLIENT_DEPS_TS = `export * from "${new URL( "../../runtime.ts", import.meta.url, )}";\n`; - await Deno.writeTextFile(join(directory, "deps.ts"), DEPS_TS); - const PAGES_INDEX_TSX = `/** @jsx h */ -import { h, IS_BROWSER, PageConfig, useState } from "../deps.ts"; + await Deno.writeTextFile(join(directory, "client_deps.ts"), CLIENT_DEPS_TS); + const SERVER_DEPS_TS = `export * from "${new URL( + "../../server.ts", + import.meta.url, + )}";\n`; + await Deno.writeTextFile(join(directory, "server_deps.ts"), SERVER_DEPS_TS); + + const ROUTES_INDEX_TSX = `/** @jsx h */ +import { h } from "../client_deps.ts"; +import Counter from "../islands/Counter.tsx"; export default function Home() { return (

- Welcome to \`fresh\`. Try update this message in the ./pages/index.tsx + Welcome to \`fresh\`. Try update this message in the ./routes/index.tsx file, and refresh.

- -

{IS_BROWSER ? "Viewing browser render." : "Viewing JIT render."}

+
); } +`; + await Deno.writeTextFile( + join(directory, "routes", "index.tsx"), + ROUTES_INDEX_TSX, + ); -function Counter() { - const [count, setCount] = useState(0); + const ISLANDS_COUNTER_TSX = `/** @jsx h */ +import { h, IS_BROWSER, useState } from "../client_deps.ts"; + +interface CounterProps { + start: number; +} + +export default function Counter(props: CounterProps) { + const [count, setCount] = useState(props.start); return (

{count}

@@ -93,31 +113,26 @@ function Counter() {
); } - -export const config: PageConfig = { runtimeJS: true }; - `; await Deno.writeTextFile( - join(directory, "pages", "index.tsx"), - PAGES_INDEX_TSX, + join(directory, "islands", "Counter.tsx"), + ISLANDS_COUNTER_TSX, ); - const PAGES_GREET_TSX = `/** @jsx h */ -import { h } from "../deps.ts"; -interface Props { - params: Record; -} + const ROUTES_GREET_TSX = `/** @jsx h */ +import { h, PageProps } from "../client_deps.ts"; -export default function Greet(props: Props) { +export default function Greet(props: PageProps) { return
Hello {props.params.name}
; } `; await Deno.writeTextFile( - join(directory, "pages", "[name].tsx"), - PAGES_GREET_TSX, + join(directory, "routes", "[name].tsx"), + ROUTES_GREET_TSX, ); - const serverUrl = new URL("../../server.ts", import.meta.url); - const PAGES_API_JOKE_TS = `import { HandlerContext } from "${serverUrl}"; + + const ROUTES_API_JOKE_TS = + `import { HandlerContext } from "../server_deps.ts"; // Jokes courtesy of https://punsandoneliners.com/randomness/programmer-jokes/ const JOKES = [ @@ -140,19 +155,20 @@ export const handler = (_ctx: HandlerContext): Response => { }; `; await Deno.writeTextFile( - join(directory, "pages", "api", "joke.ts"), - PAGES_API_JOKE_TS, + join(directory, "routes", "api", "joke.ts"), + ROUTES_API_JOKE_TS, ); + const MAIN_TS = `/// /// /// /// /// -import { start } from "${serverUrl}"; -import routes from "./routes.gen.ts"; +import { start } from "./server_deps.ts"; +import manifest from "./fresh.gen.ts"; -await start(routes); +await start(manifest); `; await Deno.writeTextFile( join(directory, "main.ts"), @@ -168,10 +184,11 @@ Start the project: deno run -A --watch main.ts \`\`\` -After adding, removing, or moving a page in the \`pages\` directory, run: +After adding, removing, or moving a page in the \`routes\` or directory, or adding, +removing, or moving an island in the \`islands\` directory, run: \`\`\` -fresh routes +fresh manifest \`\`\` `; await Deno.writeTextFile( @@ -179,5 +196,5 @@ fresh routes README_MD, ); - await routes(directory); + await manifest(directory); } diff --git a/src/cli/manifest.ts b/src/cli/manifest.ts new file mode 100644 index 00000000..23d5ffea --- /dev/null +++ b/src/cli/manifest.ts @@ -0,0 +1,137 @@ +import { join, resolve, toFileUrl, walk } from "./deps.ts"; + +const help = `fresh manifest + +Regenerate the fresh.gen.ts manifest for your fresh project. + +To regenerate the mapping in the current directory: + fresh manifest + +To regenerate the mapping in the './foobar' subdirectory: + fresh manifest ./foobar + +USAGE: + fresh manifest [OPTIONS] [DIRECTORY] + +OPTIONS: + -h, --help Prints help information +`; + +export interface Args { + help: boolean; +} + +// deno-lint-ignore no-explicit-any +export async function manifestSubcommand(rawArgs: Record) { + const args: Args = { + help: !!rawArgs.help, + }; + const directory: string | null = typeof rawArgs._[0] === "string" + ? rawArgs._[0] + : Deno.cwd(); + if (args.help) { + console.log(help); + Deno.exit(0); + } + await manifest(directory); +} + +export async function manifest(directory: string) { + directory = resolve(directory); + const routes = []; + try { + const routesDir = join(directory, "./routes"); + const routesUrl = toFileUrl(routesDir); + // TODO(lucacasonato): remove the extranious Deno.readDir when + // https://github.com/denoland/deno_std/issues/1310 is fixed. + for await (const _ of Deno.readDir(routesDir)) { + // do nothing + } + const routesFolder = walk(routesDir, { + includeDirs: false, + includeFiles: true, + exts: ["tsx", "jsx", "ts", "js"], + }); + for await (const entry of routesFolder) { + if (entry.isFile) { + const file = toFileUrl(entry.path).href.substring( + routesUrl.href.length, + ); + routes.push(file); + } + } + } catch (err) { + if (err instanceof Deno.errors.NotFound) { + // Do nothing. + } else { + throw err; + } + } + + const islands = []; + try { + const islandsDir = join(directory, "./islands"); + const islandsUrl = toFileUrl(islandsDir); + // TODO(lucacasonato): remove the extranious Deno.readDir when + // https://github.com/denoland/deno_std/issues/1310 is fixed. + for await (const _ of Deno.readDir(islandsDir)) { + // do nothing + } + const islandsFolder = walk(islandsDir, { + includeDirs: false, + includeFiles: true, + exts: ["tsx", "jsx", "ts", "js"], + }); + for await (const entry of islandsFolder) { + if (entry.isFile) { + const file = toFileUrl(entry.path).href.substring( + islandsUrl.href.length, + ); + islands.push(file); + } + } + } catch (err) { + if (err instanceof Deno.errors.NotFound) { + // Do nothing. + } else { + throw err; + } + } + + const output = `// DO NOT EDIT. This file is generated by \`fresh\`. +// This file SHOULD be checked into source version control. +// To update this file, run \`fresh routes\`. + +${ + routes.map((file, i) => `import * as $${i} from "./routes${file}";`).join( + "\n", + ) + } +${ + islands.map((file, i) => `import * as $$${i} from "./islands${file}";`) + .join("\n") + } + +const manifest = { + routes: { + ${ + routes.map((file, i) => `${JSON.stringify(`./routes${file}`)}: $${i},`) + .join("\n ") + } + }, + islands: { + ${ + islands.map((file, i) => `${JSON.stringify(`./islands${file}`)}: $$${i},`) + .join("\n ") + } + }, + baseUrl: import.meta.url, +}; + +export default manifest; +`; + + const manifestPath = join(directory, "./fresh.gen.ts"); + await Deno.writeTextFile(manifestPath, output); + console.log("Manifest generated and written to", manifestPath); +} diff --git a/src/cli/routes.ts b/src/cli/routes.ts deleted file mode 100644 index b7132e3a..00000000 --- a/src/cli/routes.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { join, resolve, toFileUrl, walk } from "./deps.ts"; - -const help = `fresh routes - -Regenerate the route mapping for your fresh project. - -To regenerate the mapping in the current directory: - fresh routes - -To regenerate the mapping in the './foobar' subdirectory: - fresh routes ./foobar - -USAGE: - fresh routes [OPTIONS] [DIRECTORY] - -OPTIONS: - -h, --help Prints help information -`; - -export interface Args { - help: boolean; -} - -// deno-lint-ignore no-explicit-any -export async function routesSubcommand(rawArgs: Record) { - const args: Args = { - help: !!rawArgs.help, - }; - const directory: string | null = typeof rawArgs._[0] === "string" - ? rawArgs._[0] - : Deno.cwd(); - if (args.help) { - console.log(help); - Deno.exit(0); - } - await routes(directory); -} - -export async function routes(directory: string) { - directory = resolve(directory); - const files = []; - const pagesDir = join(directory, "./pages"); - const pagesUrl = toFileUrl(pagesDir); - const folder = walk(pagesDir, { - includeDirs: false, - includeFiles: true, - exts: ["tsx", "jsx", "ts", "js"], - }); - for await (const entry of folder) { - if (entry.isFile) { - const file = toFileUrl(entry.path).href.substring(pagesUrl.href.length); - files.push(file); - } - } - - const output = `// DO NOT EDIT. This file is generated by \`fresh\`. -// This file SHOULD be checked into source version control. -// To update this file, run \`fresh routes\`. - -${files.map((file, i) => `import * as $${i} from "./pages${file}";`).join("\n")} - -const routes = { - pages: { - ${ - files.map((file, i) => `${JSON.stringify(`./pages${file}`)}: $${i},`) - .join("\n ") - } - }, - baseUrl: import.meta.url, -}; - -export default routes; -`; - - const routeManifestPath = join(directory, "./routes.gen.ts"); - await Deno.writeTextFile(routeManifestPath, output); - console.log("Route manifest generated and written to", routeManifestPath); -} diff --git a/src/runtime/deps.ts b/src/runtime/deps.ts index f4a1658c..81972964 100644 --- a/src/runtime/deps.ts +++ b/src/runtime/deps.ts @@ -1,4 +1,4 @@ -export * from "https://esm.sh/preact@10.5.14"; +export * from "https://esm.sh/preact@10.6.6"; export { useCallback, useContext, @@ -11,7 +11,7 @@ export { useReducer, useRef, useState, -} from "https://esm.sh/preact@10.5.14/hooks"; +} from "https://esm.sh/preact@10.6.6/hooks"; export type { CreateHandle, EffectCallback, @@ -20,4 +20,4 @@ export type { Reducer, Ref, StateUpdater, -} from "https://esm.sh/preact@10.5.14/hooks"; +} from "https://esm.sh/preact@10.6.6/hooks"; diff --git a/src/runtime/hooks.ts b/src/runtime/hooks.ts deleted file mode 100644 index 91ba46ca..00000000 --- a/src/runtime/hooks.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { createContext, useContext } from "./deps.ts"; -import { IS_BROWSER } from "./utils.ts"; - -export const DATA_CONTEXT = createContext(new Map()); - -export type Fetcher = (key: string) => T | Promise; - -/** - * The `useData` hook can be used to fetch some data during JIT rendering. - * On the client the hook will return the data that was computed during JIT - * rendering. If `useData` is called on the client with a different key than - * during JIT rendering, an error will occur. - * - * The fetcher can be asynchronous. The render will be suspended while waiting - * for the asynchronous data to be ready. Once the promise is ready we rerender. - * Because of the suspense it is possible that a page or component can be - * rendered more than once during a JIT render. - * - * ```tsx - * export default function App() { - * const { latest, versions } = useData("https://cdn.deno.land/std/meta/versions.json", fetcher); - * return

The Deno standard library has {versions.length} versions, with {latest} being the most recent.

- * } - * - * async function fetcher(url: string) { - * const resp = await fetch(url); - * return resp.json(); - * } - * ``` - * - * @param key A unique identifier for this data. - * @param fetcher The function used to fetch data based on the above key. - * @returns The the data that the promise returned from `fetcher` resolves to. - */ -export function useData(key: string, fetcher: Fetcher): T { - const DATA_CACHE = useContext(DATA_CONTEXT); - - // If there is no data or pending promise for this key in the data cache yet, - // call the fetcher, store it into the cache, and possibly suspend. - if (!DATA_CACHE.has(key)) { - if (IS_BROWSER) { - throw new Error( - `'useData' can not fetch new data on the client. The JIT render did not generate data for key '${key}'.`, - ); - } - const data = fetcher(key); - if (data instanceof Promise) { - data.then((data) => { - DATA_CACHE.set(key, data); - }); - } - DATA_CACHE.set(key, data); - } - - const data = DATA_CACHE.get(key); - // If the data is a promise, suspend the component. - if (data instanceof Promise) throw data; - // else return the data. - return data as T; -} diff --git a/src/runtime/suspense.ts b/src/runtime/suspense.ts deleted file mode 100644 index 8a8999dd..00000000 --- a/src/runtime/suspense.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { - ComponentChild, - ComponentChildren, - createContext, - Fragment, - h, - useContext, -} from "./deps.ts"; -import { IS_BROWSER } from "./utils.ts"; - -export const SUSPENSE_CONTEXT = createContext([]); - -export interface SuspenseProps { - fallback: ComponentChild; - children: ComponentChildren; -} - -export function Suspense(props: SuspenseProps) { - if (IS_BROWSER) { - throw new Error(`'' is not supported on the client yet.`); - } - - const suspenseData = useContext(SUSPENSE_CONTEXT); - const id = suspenseData.push(props.children); - - return h( - Fragment, - null, - h("template", { id: `S:${id}` }), - props.fallback, - h("template", { id: `E:${id}` }), - ); -} diff --git a/src/runtime/types.ts b/src/runtime/types.ts index 6e8e8829..a9390d93 100644 --- a/src/runtime/types.ts +++ b/src/runtime/types.ts @@ -1,8 +1,7 @@ import { ComponentType } from "./deps.ts"; -export interface PageProps< - T extends Record = Record, -> { +// deno-lint-ignore no-explicit-any +export interface PageProps { /** The URL of the request that resulted in this page being rendered. */ url: URL; @@ -21,10 +20,10 @@ export interface PageProps< params: Record; /** - * Additional data passed into `HandlerContext.render`. Not present by - * default. + * Additional data passed into `HandlerContext.render`. Defaults to + * `undefined`. */ - renderData?: T; + data: T; } export interface AppProps { diff --git a/src/server/bundle.ts b/src/server/bundle.ts index e37897d5..02a01185 100644 --- a/src/server/bundle.ts +++ b/src/server/bundle.ts @@ -1,5 +1,5 @@ import { denoPlugin, esbuild, esbuildTypes, toFileUrl } from "./deps.ts"; -import { Page } from "./types.ts"; +import { Island } from "./types.ts"; let esbuildInitalized: boolean | Promise = false; async function ensureEsbuildInialized() { @@ -20,22 +20,20 @@ async function ensureEsbuildInialized() { } export class Bundler { - #pages: Page[]; + #islands: Island[]; #cache: Map | Promise | undefined = undefined; - #preloads = new Map(); - constructor(pages: Page[]) { - this.#pages = pages; + constructor(islands: Island[]) { + this.#islands = islands; } async bundle() { const entryPoints: Record = {}; - for (const page of this.#pages) { - if (page.component !== undefined && page.runtimeJS) { - entryPoints[page.name] = `fresh:///${page.name}`; - } + for (const island of this.#islands) { + entryPoints[island.id] = `fresh:///${island.id}`; } + const absWorkingDir = Deno.cwd(); await ensureEsbuildInialized(); const bundle = await esbuild.build({ @@ -50,21 +48,21 @@ export class Bundler { absWorkingDir, outfile: "", platform: "neutral", - plugins: [freshPlugin(this.#pages), denoPlugin()], + plugins: [freshPlugin(this.#islands), denoPlugin()], splitting: true, target: ["chrome90", "firefox88", "safari13"], treeShaking: true, write: false, }); - const metafileOutputs = bundle.metafile!.outputs; + // const metafileOutputs = bundle.metafile!.outputs; - for (const path in metafileOutputs) { - const meta = metafileOutputs[path]; - const imports = meta.imports - .filter(({ kind }) => kind === "import-statement") - .map(({ path }) => `/${path}`); - this.#preloads.set(`/${path}`, imports); - } + // for (const path in metafileOutputs) { + // const meta = metafileOutputs[path]; + // const imports = meta.imports + // .filter(({ kind }) => kind === "import-statement") + // .map(({ path }) => `/${path}`); + // this.#preloads.set(`/${path}`, imports); + // } const cache = new Map(); const absDirUrlLength = toFileUrl(absWorkingDir).href.length; @@ -94,18 +92,18 @@ export class Bundler { return cache.get(path) ?? null; } - getPreloads(path: string): string[] { - return this.#preloads.get(path) ?? []; - } + // getPreloads(path: string): string[] { + // return this.#preloads.get(path) ?? []; + // } } -function freshPlugin(pageList: Page[]): esbuildTypes.Plugin { +function freshPlugin(islands: Island[]): esbuildTypes.Plugin { const runtime = new URL("../../runtime.ts", import.meta.url); - const pageMap = new Map(); + const islandMap = new Map(); - for (const page of pageList) { - pageMap.set(`/${page.name}`, page); + for (const island of islands) { + islandMap.set(`/${island.id}`, island); } return { @@ -127,24 +125,21 @@ function freshPlugin(pageList: Page[]): esbuildTypes.Plugin { ): esbuildTypes.OnLoadResult | null | undefined { const url = new URL(args.path); const path = url.pathname; - const page = pageMap.get(path); - if (!page) return null; + const island = islandMap.get(path); + if (!island) return null; const contents = ` -import Page from "${page.url}"; -import { h, render, DATA_CONTEXT } from "${runtime.href}"; +import ${island.name} from "${island.url}"; +import { h, render } from "${runtime.href}"; -addEventListener("DOMContentLoaded", () => { - const { params, data } = JSON.parse(document.getElementById("__FRSH_PROPS")?.textContent ?? "{}"); - try { - render(h(DATA_CONTEXT.Provider, { value: new Map(data ?? []) }, h(Page, { params: params ?? {} })), document.getElementById("__FRSH")); - } catch(err) { - if (err instanceof Promise) { - console.error("Render tried to suspend without a suspense boundary."); - } else { - console.error("Render threw an error:", err); - } +class ${island.name}Island extends HTMLElement { + constructor() { + super(); + const props = JSON.parse(this.getAttribute("props")); + render(h(${island.name}, props), this); } -}); +} + +customElements.define("frsh-${island.id}", ${island.name}Island); `; return { contents, loader: "js" }; }, diff --git a/src/server/client.js b/src/server/client.js deleted file mode 100644 index 9b68876c..00000000 --- a/src/server/client.js +++ /dev/null @@ -1,36 +0,0 @@ -(() => { - /** Replace a suspense component with it's final variant. */ - window.$SR = (id) => { - const targetStart = document.getElementById("S:" + id); - const targetEnd = document.getElementById("E:" + id); - const replacement = document.getElementById("R:" + id); - replacement.parentNode.removeChild(replacement); - while (targetStart.nextSibling !== targetEnd) { - targetStart.parentNode.removeChild(targetStart.nextSibling); - } - while (replacement.firstChild) { - targetStart.parentNode.insertBefore(replacement.firstChild, targetEnd); - } - targetStart.parentNode.removeChild(targetStart); - targetEnd.parentNode.removeChild(targetEnd); - }; - - /** @type {HTMLStyleElement} */ - const sheetElement = document.getElementById("__FRSH_STYLE"); - const rules = sheetElement.childNodes[0]?.textContent.split("\n"); - if (rules !== undefined) { - sheetElement.removeChild(sheetElement.firstChild); - for (const rule of rules) { - sheetElement.append(document.createTextNode(rule)); - } - } - /** Insert new style rules. */ - window.$ST = (inserts) => { - for (const [rule, index] of inserts) { - sheetElement.insertBefore( - document.createTextNode(rule), - sheetElement.childNodes[index], - ); - } - }; -})(); diff --git a/src/server/context.ts b/src/server/context.ts index 8313ca3c..dc2e7096 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -6,7 +6,7 @@ import { toFileUrl, walk, } from "./deps.ts"; -import { Routes } from "./mod.ts"; +import { Manifest } from "./mod.ts"; import { Bundler } from "./bundle.ts"; import { ALIVE_URL, INTERNAL_PREFIX, REFRESH_JS_URL } from "./constants.ts"; import { JS_PREFIX } from "./constants.ts"; @@ -16,6 +16,7 @@ import { ErrorPage, ErrorPageModule, Handler, + Island, Middleware, MiddlewareModule, Page, @@ -26,11 +27,7 @@ import { UnknownPageModule, } from "./types.ts"; import { render as internalRender } from "./render.tsx"; -import { - ContentSecurityPolicy, - ContentSecurityPolicyDirectives, - SELF, -} from "../runtime/csp.ts"; +import { ContentSecurityPolicyDirectives, SELF } from "../runtime/csp.ts"; import { h } from "../runtime/deps.ts"; interface StaticFile { @@ -49,6 +46,7 @@ interface StaticFile { export class ServerContext { #dev: boolean; #pages: Page[]; + #islands: Island[]; #staticFiles: StaticFile[]; #bundler: Bundler; #renderer: Renderer; @@ -59,6 +57,7 @@ export class ServerContext { constructor( pages: Page[], + islands: Island[], staticFiles: StaticFile[], renderer: Renderer, middleware: Middleware, @@ -67,36 +66,38 @@ export class ServerContext { error: ErrorPage, ) { this.#pages = pages; + this.#islands = islands; this.#staticFiles = staticFiles; this.#renderer = renderer; this.#middleware = middleware; this.#app = app; this.#notFound = notFound; this.#error = error; - this.#bundler = new Bundler(pages); + this.#bundler = new Bundler(this.#islands); this.#dev = typeof Deno.env.get("DENO_DEPLOYMENT_ID") !== "string"; // Env var is only set in prod (on Deploy). } /** - * Process the routes into individual components and pages. + * Process the manifest into individual components and pages. */ - static async fromRoutes(routes: Routes): Promise { - // Get the routes' base URL. - const baseUrl = new URL("./", routes.baseUrl).href; + static async fromManifest(manifest: Manifest): Promise { + // Get the manifest' base URL. + const baseUrl = new URL("./", manifest.baseUrl).href; // Extract all routes, and prepare them into the `Page` structure. const pages: Page[] = []; + const islands: Island[] = []; let renderer: Renderer = DEFAULT_RENDERER; let middleware: Middleware = DEFAULT_MIDDLEWARE; let app: AppModule = DEFAULT_APP; let notFound: UnknownPage = DEFAULT_NOT_FOUND; let error: ErrorPage = DEFAULT_ERROR; - for (const [self, module] of Object.entries(routes.pages)) { + for (const [self, module] of Object.entries(manifest.routes)) { const url = new URL(self, baseUrl).href; if (!url.startsWith(baseUrl)) { throw new TypeError("Page is not a child of the basepath."); } - const path = url.substring(baseUrl.length).substring("pages".length); + const path = url.substring(baseUrl.length).substring("routes".length); const baseRoute = path.substring(1, path.length - extname(path).length); const name = baseRoute.replace("/", "-"); if (!path.startsWith("/_")) { @@ -111,7 +112,7 @@ export class ServerContext { component && typeof handler === "object" && handler.GET === undefined ) { - handler.GET = ({ render }) => render!(); + handler.GET = ({ render }) => render(); } const page: Page = { route, @@ -119,7 +120,6 @@ export class ServerContext { name, component, handler, - runtimeJS: Boolean(config?.runtimeJS ?? false), csp: Boolean(config?.csp ?? false), }; pages.push(page); @@ -145,7 +145,7 @@ export class ServerContext { const { default: component, config } = (module as UnknownPageModule); let { handler } = (module as UnknownPageModule); if (component && handler === undefined) { - handler = ({ render }) => render!(); + handler = ({ render }) => render(); } notFound = { @@ -164,7 +164,7 @@ export class ServerContext { const { default: component, config } = (module as ErrorPageModule); let { handler } = (module as ErrorPageModule); if (component && handler === undefined) { - handler = ({ render }) => render!(); + handler = ({ render }) => render(); } error = { @@ -181,9 +181,21 @@ export class ServerContext { } sortRoutes(pages); + for (const [self, module] of Object.entries(manifest.islands)) { + const url = new URL(self, baseUrl).href; + if (!url.startsWith(baseUrl)) { + throw new TypeError("Page is not a child of the basepath."); + } + const path = url.substring(baseUrl.length).substring("islands".length); + const baseRoute = path.substring(1, path.length - extname(path).length); + const name = baseRoute.replace("/", ""); + const id = name.toLowerCase(); + islands.push({ id, name, url, component: module.default }); + } + const staticFiles: StaticFile[] = []; try { - const staticFolder = new URL("./static", routes.baseUrl); + const staticFolder = new URL("./static", manifest.baseUrl); // TODO(lucacasonato): remove the extranious Deno.readDir when // https://github.com/denoland/deno_std/issues/1310 is fixed. for await (const _ of Deno.readDir(fromFileUrl(staticFolder))) { @@ -227,6 +239,7 @@ export class ServerContext { } return new ServerContext( pages, + islands, staticFiles, renderer, middleware, @@ -277,84 +290,67 @@ export class ServerContext { ); } - const genRender = (page: Page, status: number) => { - const bundlePath = `/${page.name}.js`; - const imports = page.runtimeJS ? [bundleAssetUrl(bundlePath)] : []; + const genRender = ( + page: Page | UnknownPage | ErrorPage, + status: number, + ) => { + const imports: string[] = []; if (this.#dev) { imports.push(REFRESH_JS_URL); } return ( req: Request, - params: Record, + params: Record, error?: unknown, ) => { - if (page.component === undefined) return undefined; - return async (renderData?: Record) => { - const preloads = page.runtimeJS - ? this.#bundler.getPreloads(bundlePath).map(bundleAssetUrl) - : []; - const body = internalRender({ - page, - app: this.#app, - imports, - preloads, - renderer: this.#renderer, - url: new URL(req.url), - params, - renderData, - error, - }); - - const headers: Record = { - "content-type": "text/html; charset=utf-8", - }; - let firstChunk: string; - const iterator = body[Symbol.asyncIterator](); + return (data?: Data) => { + if (page.component === undefined) { + throw new Error("This page does not have a component to render."); + } + const preloads: string[] = []; + let resp; try { - const { value, done } = await iterator.next(); - if (done) throw new Error("Body is empty."); - firstChunk = value[0]; - const csp: ContentSecurityPolicy | undefined = value[1]; - if (csp) { - if (this.#dev) { - csp.directives.connectSrc = [ - ...(csp.directives.connectSrc ?? []), - SELF, - ]; - } - const directive = serializeCSPDirectives(csp.directives); - if (csp.reportOnly) { - headers["content-security-policy-report-only"] = directive; - } else { - headers["content-security-policy"] = directive; - } - } + resp = internalRender({ + page, + islands: this.#islands, + app: this.#app, + imports, + preloads, + renderer: this.#renderer, + url: new URL(req.url), + params, + data, + error, + }); } catch (err) { console.error("Error rendering page", err); - throw new Response("500 Internal Server Error", { + return new Response("500 Internal Server Error", { status: 500, headers: { "content-type": "text/plain", }, }); } - const bodyStream = new ReadableStream({ - async start(controller) { - controller.enqueue(new TextEncoder().encode(firstChunk)); - try { - for await (const chunk of body) { - controller.enqueue(new TextEncoder().encode(chunk as string)); - } - } catch (err) { - console.log("Rendering failed:\n", err); - controller.enqueue( - new TextEncoder().encode("500 Internal Server Error"), - ); - } - controller.close(); - }, - }); - return new Response(bodyStream, { status, headers }); + const headers: Record = { + "content-type": "text/html; charset=utf-8", + }; + + const [body, csp] = resp; + if (csp) { + if (this.#dev) { + csp.directives.connectSrc = [ + ...(csp.directives.connectSrc ?? []), + SELF, + ]; + } + const directive = serializeCSPDirectives(csp.directives); + if (csp.reportOnly) { + headers["content-security-policy-report-only"] = directive; + } else { + headers["content-security-policy"] = directive; + } + } + return new Response(body, { status, headers }); }; }; }; @@ -378,17 +374,16 @@ export class ServerContext { const unknownHandlerRender = genRender(this.#notFound, 404); const unknownHandler = (req: Request) => - (this.#notFound.handler as Handler)({ + this.#notFound.handler({ req, - match: {}, render: unknownHandlerRender(req, {}), }); const errorHandlerRender = genRender(this.#error, 500); const errorHandler = (req: Request, error: unknown) => - (this.#notFound.handler as Handler)({ + this.#error.handler({ req, - match: {}, + error, render: errorHandlerRender(req, {}, error), }); @@ -485,10 +480,6 @@ export class ServerContext { }; } -function bundleAssetUrl(path: string) { - return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`; -} - const DEFAULT_RENDERER: Renderer = { render(_ctx, render) { render(); diff --git a/src/server/deps.ts b/src/server/deps.ts index fe5b8119..65a7252f 100644 --- a/src/server/deps.ts +++ b/src/server/deps.ts @@ -1,5 +1,5 @@ // -- preact -- -export { renderToString } from "https://esm.sh/preact-render-to-string@5.1.19?deps=preact@10.5.14"; +export { renderToString } from "https://esm.sh/preact-render-to-string@5.1.20?deps=preact@10.6.6"; // -- std -- export { diff --git a/src/server/mod.ts b/src/server/mod.ts index a47091b6..e0b0a85d 100644 --- a/src/server/mod.ts +++ b/src/server/mod.ts @@ -2,26 +2,35 @@ import { ServerContext } from "./context.ts"; import { listenAndServe } from "./deps.ts"; import { AppModule, + ErrorPageModule, + IslandModule, MiddlewareModule, PageModule, RendererModule, + UnknownPageModule, } from "./types.ts"; export type { Handler, HandlerContext, Handlers } from "./types.ts"; export { RenderContext } from "./render.tsx"; export type { RenderFn } from "./render.tsx"; -export interface Routes { - pages: Record< +export interface Manifest { + routes: Record< string, - PageModule | RendererModule | MiddlewareModule | AppModule + | PageModule + | RendererModule + | MiddlewareModule + | AppModule + | ErrorPageModule + | UnknownPageModule >; + islands: Record; baseUrl: string; } export { ServerContext }; -export async function start(routes: Routes) { - const ctx = await ServerContext.fromRoutes(routes); +export async function start(routes: Manifest) { + const ctx = await ServerContext.fromManifest(routes); console.log("Server listening on http://localhost:8000"); await listenAndServe(":8000", ctx.handler()); } diff --git a/src/server/render.tsx b/src/server/render.tsx index 5097c8f5..4e09c796 100644 --- a/src/server/render.tsx +++ b/src/server/render.tsx @@ -1,29 +1,35 @@ /** @jsx h */ - import { renderToString } from "./deps.ts"; -import { ComponentChildren, h } from "../runtime/deps.ts"; -import { DATA_CONTEXT } from "../runtime/hooks.ts"; -import { AppModule, ErrorPage, Page, Renderer, UnknownPage } from "./types.ts"; import { - ErrorPageProps, - PageProps, - UnknownPageProps, -} from "../runtime/types.ts"; -import { SUSPENSE_CONTEXT } from "../runtime/suspense.ts"; + ComponentChildren, + ComponentType, + h, + options, + VNode, +} from "../runtime/deps.ts"; +import { + AppModule, + ErrorPage, + Island, + Page, + Renderer, + UnknownPage, +} from "./types.ts"; import { HEAD_CONTEXT } from "../runtime/head.ts"; -import { REFRESH_JS_URL } from "./constants.ts"; import { CSP_CONTEXT, nonce, NONE, UNSAFE_INLINE } from "../runtime/csp.ts"; import { ContentSecurityPolicy } from "../runtime/csp.ts"; +import { BUILD_ID, INTERNAL_PREFIX, JS_PREFIX } from "./constants.ts"; -export interface RenderOptions { - page: Page | UnknownPage | ErrorPage; +export interface RenderOptions { + page: Page | UnknownPage | ErrorPage; + islands: Island[]; app: AppModule; imports: string[]; preloads: string[]; url: URL; params: Record; renderer: Renderer; - renderData?: Record; + data?: Data; error?: unknown; } @@ -87,8 +93,6 @@ export class RenderContext { } } -const MAX_SUSPENSE_DEPTH = 10; - function defaultCsp() { return { directives: { defaultSrc: [NONE], styleSrc: [UNSAFE_INLINE] }, @@ -118,14 +122,14 @@ function defaultCsp() { * sent to the client. On the client the HTML will be slotted into the DOM * at the location of the original `` node. */ -export async function* render( - opts: RenderOptions, -): AsyncIterable { +export function render( + opts: RenderOptions, +): [string, ContentSecurityPolicy | undefined] { const props: Record = { params: opts.params, url: opts.url, route: opts.page.route, - renderData: opts.renderData, + data: opts.data, }; if (opts.error) { props.error = opts.error; @@ -134,93 +138,48 @@ export async function* render( const csp: ContentSecurityPolicy | undefined = opts.page.csp ? defaultCsp() : undefined; - const dataCache = new Map(); - const suspenseQueue: ComponentChildren[] = []; const headComponents: ComponentChildren[] = []; const vnode = h(CSP_CONTEXT.Provider, { value: csp, children: h(HEAD_CONTEXT.Provider, { value: headComponents, - children: h(DATA_CONTEXT.Provider, { - value: dataCache, - children: h(SUSPENSE_CONTEXT.Provider, { - value: suspenseQueue, - children: h(opts.app.default, { - Component() { - return h(opts.page.component!, props); - }, - }), - }), + children: h(opts.app.default, { + Component() { + return h(opts.page.component! as ComponentType, props); + }, }), }), }); const ctx = new RenderContext(crypto.randomUUID(), opts.url, opts.page.route); - let suspended = 0; - const renderWithRenderer = (): string | Promise => { - if (csp) { - // Clear the csp - const newCsp = defaultCsp(); - csp.directives = newCsp.directives; - csp.reportOnly = newCsp.reportOnly; - } - // Clear the suspense queue - suspenseQueue.splice(0, suspenseQueue.length); - // Clear the head components - headComponents.splice(0, headComponents.length); + if (csp) { + // Clear the csp + const newCsp = defaultCsp(); + csp.directives = newCsp.directives; + csp.reportOnly = newCsp.reportOnly; + } + // Clear the head components + headComponents.splice(0, headComponents.length); - if (++suspended > MAX_SUSPENSE_DEPTH) { - throw new Error( - `Reached maximum suspense depth of ${MAX_SUSPENSE_DEPTH}.`, - ); - } + // Setup the interesting VNode types + ISLANDS.splice(0, ISLANDS.length, ...opts.islands); - let body: string | null = null; - let promise: Promise | null = null; + // Clear the encountered vnodes + ENCOUNTERED_ISLANDS.clear(); - function render() { - try { - body = renderToString(vnode); - return body; - } catch (e) { - if (e && e.then) { - promise = e; - return ""; - } - throw e; - } - } + let bodyHtml: string | null = null; - opts.renderer.render(ctx, render); - - if (body !== null) { - return body; - } else if (promise !== null) { - return (promise as Promise).then(renderWithRenderer); - } else { - throw new Error("`render` function not called by renderer."); - } - }; - - const bodyHtml = await renderWithRenderer(); - - let templateProps: { - props: PageProps | UnknownPageProps | ErrorPageProps; - data?: [string, unknown][]; - } | undefined = { props, data: [...dataCache.entries()] }; - if (templateProps.data!.length === 0) { - delete templateProps.data; + function render() { + bodyHtml = renderToString(vnode); + return bodyHtml; } - // If this is a static render (runtimeJS is false), then we don't need to - // render the props into the template. - if ( - opts.imports.length === 0 || - (opts.imports.length === 1 && opts.imports[0] === REFRESH_JS_URL) - ) { - templateProps = undefined; + opts.renderer.render(ctx, render); + + if (bodyHtml === null) { + throw new Error("`render` function not called by renderer."); } const imports = opts.imports.map((url) => { @@ -234,120 +193,32 @@ export async function* render( return [url, randomNonce] as const; }); + for (const island of ENCOUNTERED_ISLANDS) { + const randomNonce = crypto.randomUUID().replace(/-/g, ""); + if (csp) { + csp.directives.scriptSrc = [ + ...csp.directives.scriptSrc ?? [], + nonce(randomNonce), + ]; + } + const url = bundleAssetUrl(`/${island.id}.js`); + imports.push([url, randomNonce] as const); + } + const html = template({ bodyHtml, headComponents, imports, preloads: opts.preloads, styles: ctx.styles, - props: templateProps, lang: ctx.lang, }); - const suspenseNonces = suspenseQueue.map(() => { - const randomNonce = crypto.randomUUID().replace(/-/g, ""); - if (csp) { - csp.directives.scriptSrc = [ - ...csp.directives.scriptSrc ?? [], - nonce(randomNonce), - ]; - } - return randomNonce; - }); - - let suspenseScript = ""; - if (suspenseQueue.length > 0) { - const randomNonce = crypto.randomUUID().replace(/-/g, ""); - if (csp) { - csp.directives.scriptSrc = [ - ...csp.directives.scriptSrc ?? [], - nonce(randomNonce), - ]; - } - // minified client-side JS - suspenseScript = ''; - } - - let clientStyles = [...ctx.styles]; - yield [html + suspenseScript, csp]; - - // TODO(lucacasonato): parallelize this - for (const [id, children] of suspenseQueue.entries()) { - let [fragment, script] = await suspenseRender( - opts.renderer, - ctx, - id + 1, - children, - ); - - const cssInserts: [string, number][] = []; - for (const [i, style] of ctx.styles.entries()) { - if (!clientStyles.includes(style)) { - cssInserts.push([style, i]); - } - } - clientStyles = [...ctx.styles]; - - if (cssInserts.length > 0) { - script = `$ST(${JSON.stringify(cssInserts)});\n${script};`; - } - - yield `${fragment}`; - } + return [html, csp]; } -export async function suspenseRender( - renderer: Renderer, - ctx: RenderContext, - id: number, - children: ComponentChildren, -): Promise<[string, string]> { - const dataCache = new Map(); - - const vnode = h(DATA_CONTEXT.Provider, { - value: dataCache, - children, - }); - - let suspended = 0; - const renderWithRenderer = (): string | Promise => { - if (++suspended > MAX_SUSPENSE_DEPTH) { - throw new Error( - `Reached maximum suspense depth of ${MAX_SUSPENSE_DEPTH}.`, - ); - } - - let body: string | null = null; - let promise: Promise | null = null; - - function render() { - try { - body = renderToString(vnode); - return body; - } catch (e) { - if (e && e.then) { - promise = e; - return ""; - } - throw e; - } - } - - renderer.render(ctx, render); - - if (body !== null) { - return body; - } else if (promise !== null) { - return (promise as Promise).then(renderWithRenderer); - } else { - throw new Error("`render` function not called by renderer."); - } - }; - - const html = await renderWithRenderer(); - - return [``, `$SR(${id});`]; +function bundleAssetUrl(path: string) { + return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`; } export interface TemplateOptions { @@ -356,7 +227,6 @@ export interface TemplateOptions { imports: (readonly [string, string])[]; styles: string[]; preloads: string[]; - props: unknown; lang: string; } @@ -377,20 +247,35 @@ export function template(opts: TemplateOptions): string { /> {opts.headComponents} - -
- {opts.props !== undefined - ? ( -