From 9b64790a71e5ae88f018aa719675df7e00f3ed2e Mon Sep 17 00:00:00 2001 From: Ben McCann <322311+benmccann@users.noreply.github.com> Date: Sat, 24 Jul 2021 21:16:00 -0700 Subject: [PATCH] [feat] More powerful and configurable rendering options --- .changeset/sharp-hornets-beam.md | 5 ++ documentation/docs/11-ssr-and-javascript.md | 10 ++-- documentation/docs/14-configuration.md | 21 +++++-- documentation/faq/80-integrations.md | 13 ++--- .../test/apps/prerendered/package.json | 6 +- .../adapter-static/test/apps/spa/package.json | 6 +- packages/kit/src/core/build/index.js | 7 ++- packages/kit/src/core/config/index.spec.js | 29 +++++----- packages/kit/src/core/config/options.js | 34 +++++++++-- packages/kit/src/core/config/test/index.js | 23 +++++--- packages/kit/src/core/dev/index.js | 1 + packages/kit/src/runtime/server/index.js | 2 +- .../kit/src/runtime/server/page/render.js | 2 +- .../kit/src/runtime/server/page/respond.js | 58 ++++++++++--------- .../runtime/server/page/respond_with_error.js | 17 ++++-- packages/kit/src/runtime/server/utils.js | 12 ++++ packages/kit/types/config.d.ts | 31 +++++++--- packages/kit/types/internal.d.ts | 14 ++--- 18 files changed, 191 insertions(+), 100 deletions(-) create mode 100644 .changeset/sharp-hornets-beam.md diff --git a/.changeset/sharp-hornets-beam.md b/.changeset/sharp-hornets-beam.md new file mode 100644 index 000000000000..61924bb2eb3c --- /dev/null +++ b/.changeset/sharp-hornets-beam.md @@ -0,0 +1,5 @@ +--- +'@sveltejs/kit': patch +--- + +[feat] More powerful and configurable rendering options diff --git a/documentation/docs/11-ssr-and-javascript.md b/documentation/docs/11-ssr-and-javascript.md index fe9b3e0721a7..b0675a0d844b 100644 --- a/documentation/docs/11-ssr-and-javascript.md +++ b/documentation/docs/11-ssr-and-javascript.md @@ -6,15 +6,17 @@ By default, SvelteKit will render any component first on the server and send it You can control each of these on a per-app or per-page basis. Note that each of the per-page settings use [`context="module"`](https://svelte.dev/docs#script_context_module), and only apply to page components, _not_ [layout](#layouts) components. -If both are specified, per-page settings override per-app settings in case of conflicts. Each setting can be controlled independently, but `ssr` and `hydrate` cannot both be `false` since that would result in nothing being rendered at all. +The app-wide config options take a function, which lets you set configure the option in an advanced manner on a per-request and per-page basis. E.g. you could disable SSR for `/admin` or enable SSR only for search engine crawlers (aka [dynamic rendering](https://developers.google.com/search/docs/advanced/javascript/dynamic-rendering)). + + Each setting can be controlled independently, but `ssr` and `hydrate` cannot both be `false` since that would result in nothing being rendered at all. ### ssr -Disabling [server-side rendering](#appendix-ssr) effectively turns your SvelteKit app into a [**single-page app** or SPA](#appendix-csr-and-spa). +Disabling [server-side rendering](#appendix-ssr) effectively turns your SvelteKit app into a [**single-page app** or SPA](#appendix-csr-and-spa). The default app-wide config option value is a function which reads the page value. Reading the page value causes the page to be loaded on the server. If you'd like to avoid this because you're building a SPA, you will need to set a value such as a boolean for each of the four rendering options which does not access the page-level settings. > In most situations this is not recommended: see [the discussion in the appendix](#appendix-ssr). Consider whether it's truly appropriate to disable and don't simply disable SSR because you've hit an issue with it. -You can disable SSR app-wide with the [`ssr` config option](#configuration-ssr), or a page-level `ssr` export: +SSR can be configured with app-wide [`ssr` config option](#configuration-ssr), or a page-level `ssr` export: ```html ``` diff --git a/packages/adapter-static/test/apps/prerendered/package.json b/packages/adapter-static/test/apps/prerendered/package.json index f92b5976c7bc..cdb392f943a2 100644 --- a/packages/adapter-static/test/apps/prerendered/package.json +++ b/packages/adapter-static/test/apps/prerendered/package.json @@ -2,9 +2,9 @@ "name": "~TODO~", "version": "0.0.1", "scripts": { - "dev": "svelte-kit dev", - "build": "svelte-kit build", - "start": "svelte-kit start" + "dev": "../../../../kit/svelte-kit.js dev", + "build": "../../../../kit/svelte-kit.js build", + "start": "../../../../kit/svelte-kit.js start" }, "devDependencies": { "@sveltejs/kit": "next", diff --git a/packages/adapter-static/test/apps/spa/package.json b/packages/adapter-static/test/apps/spa/package.json index e68cb394eb4b..6cd813fde245 100644 --- a/packages/adapter-static/test/apps/spa/package.json +++ b/packages/adapter-static/test/apps/spa/package.json @@ -2,9 +2,9 @@ "name": "~TODO~", "version": "0.0.1", "scripts": { - "dev": "svelte-kit dev", - "build": "svelte-kit build", - "start": "svelte-kit start" + "dev": "../../../../kit/svelte-kit.js dev", + "build": "../../../../kit/svelte-kit.js build", + "start": "../../../../kit/svelte-kit.js start" }, "devDependencies": { "@sveltejs/adapter-node": "next", diff --git a/packages/kit/src/core/build/index.js b/packages/kit/src/core/build/index.js index b960d3f14cdf..004afdc050d0 100644 --- a/packages/kit/src/core/build/index.js +++ b/packages/kit/src/core/build/index.js @@ -332,16 +332,17 @@ async function build_server( error.stack = options.get_stack(error); }, hooks: get_hooks(user_hooks), - hydrate: ${s(config.kit.hydrate)}, + hydrate: ${config.kit.hydrate}, initiator: undefined, load_component, manifest, paths: settings.paths, + prerender: ${config.kit.prerender && config.kit.prerender.enabled}, read: settings.read, root, service_worker: ${service_worker_entry_file ? "'/service-worker.js'" : 'null'}, - router: ${s(config.kit.router)}, - ssr: ${s(config.kit.ssr)}, + router: ${config.kit.router}, + ssr: ${config.kit.ssr}, target: ${s(config.kit.target)}, template, trailing_slash: ${s(config.kit.trailingSlash)} diff --git a/packages/kit/src/core/config/index.spec.js b/packages/kit/src/core/config/index.spec.js index efddafd97217..45029419bf5e 100644 --- a/packages/kit/src/core/config/index.spec.js +++ b/packages/kit/src/core/config/index.spec.js @@ -4,9 +4,7 @@ import { deep_merge, validate_config } from './index.js'; test('fills in defaults', () => { const validated = validate_config({}); - - // @ts-expect-error - delete validated.kit.vite; + delete_complex_opts(validated); assert.equal(validated, { compilerOptions: null, @@ -27,7 +25,6 @@ test('fills in defaults', () => { floc: false, host: null, hostHeader: null, - hydrate: true, package: { dir: 'package', exports: { @@ -49,14 +46,11 @@ test('fills in defaults', () => { }, prerender: { crawl: true, - enabled: true, // TODO: remove this for the 1.0 release force: undefined, onError: 'fail', pages: ['*'] }, - router: true, - ssr: true, target: null, trailingSlash: 'never' }, @@ -107,8 +101,7 @@ test('fills in partial blanks', () => { assert.equal(validated.kit.vite(), {}); - // @ts-expect-error - delete validated.kit.vite; + delete_complex_opts(validated); assert.equal(validated, { compilerOptions: null, @@ -129,7 +122,6 @@ test('fills in partial blanks', () => { floc: false, host: null, hostHeader: null, - hydrate: true, package: { dir: 'package', exports: { @@ -151,14 +143,11 @@ test('fills in partial blanks', () => { }, prerender: { crawl: true, - enabled: true, // TODO: remove this for the 1.0 release force: undefined, onError: 'fail', pages: ['*'] }, - router: true, - ssr: true, target: null, trailingSlash: 'never' }, @@ -517,3 +506,17 @@ deepMergeSuite('merge including toString', () => { }); deepMergeSuite.run(); + +/** @param {import('types/config').ValidatedConfig} validated */ +function delete_complex_opts(validated) { + // @ts-expect-error + delete validated.kit.vite; + // @ts-expect-error + delete validated.kit.hydrate; + // @ts-expect-error + delete validated.kit.prerender.enabled; + // @ts-expect-error + delete validated.kit.router; + // @ts-expect-error + delete validated.kit.ssr; +} diff --git a/packages/kit/src/core/config/options.js b/packages/kit/src/core/config/options.js index 68f688a4c0fb..ecdb00dda06b 100644 --- a/packages/kit/src/core/config/options.js +++ b/packages/kit/src/core/config/options.js @@ -78,7 +78,10 @@ const options = { hostHeader: expect_string(null), - hydrate: expect_boolean(true), + hydrate: expect_page_scriptable(async ({ page }) => { + const leaf = await page; + return 'hydrate' in leaf ? !!leaf.hydrate : true; + }), serviceWorker: { type: 'branch', children: { @@ -120,7 +123,7 @@ const options = { type: 'branch', children: { crawl: expect_boolean(true), - enabled: expect_boolean(true), + enabled: expect_page_scriptable(async ({ page }) => !!(await page).prerender), // TODO: remove this for the 1.0 release force: { type: 'leaf', @@ -170,9 +173,15 @@ const options = { } }, - router: expect_boolean(true), + router: expect_page_scriptable(async ({ page }) => { + const leaf = await page; + return 'router' in leaf ? !!leaf.router : true; + }), - ssr: expect_boolean(true), + ssr: expect_page_scriptable(async ({ page }) => { + const leaf = await page; + return 'ssr' in leaf ? !!leaf.ssr : true; + }), target: expect_string(null), @@ -259,6 +268,23 @@ function expect_boolean(boolean) { }; } +/** + * @param {import('types/config').ScriptablePageOpt} value + * @returns {ConfigDefinition} + */ +function expect_page_scriptable(value) { + return { + type: 'leaf', + default: value, + validate: (option, keypath) => { + if (typeof option !== 'boolean' && typeof option !== 'function') { + throw new Error(`${keypath} should be a boolean or function that returns one`); + } + return option; + } + }; +} + /** * @param {string[]} options * @returns {ConfigDefinition} diff --git a/packages/kit/src/core/config/test/index.js b/packages/kit/src/core/config/test/index.js index c378835273ad..e26a5f6899ee 100644 --- a/packages/kit/src/core/config/test/index.js +++ b/packages/kit/src/core/config/test/index.js @@ -14,9 +14,7 @@ async function testLoadDefaultConfig(path) { const cwd = join(__dirname, 'fixtures', path); const config = await load_config({ cwd }); - - // @ts-expect-error - delete config.kit.vite; // can't test equality of a function + delete_complex_opts(config); assert.equal(config, { compilerOptions: null, @@ -37,7 +35,6 @@ async function testLoadDefaultConfig(path) { floc: false, host: null, hostHeader: null, - hydrate: true, package: { dir: 'package', exports: { @@ -54,9 +51,7 @@ async function testLoadDefaultConfig(path) { exclude: [] }, paths: { base: '', assets: '/.' }, - prerender: { crawl: true, enabled: true, force: undefined, onError: 'fail', pages: ['*'] }, - router: true, - ssr: true, + prerender: { crawl: true, force: undefined, onError: 'fail', pages: ['*'] }, target: null, trailingSlash: 'never' }, @@ -103,3 +98,17 @@ test('errors on loading config with incorrect default export', async () => { }); test.run(); + +/** @param {import('types/config').ValidatedConfig} validated */ +function delete_complex_opts(validated) { + // @ts-expect-error + delete validated.kit.vite; + // @ts-expect-error + delete validated.kit.hydrate; + // @ts-expect-error + delete validated.kit.prerender.enabled; + // @ts-expect-error + delete validated.kit.router; + // @ts-expect-error + delete validated.kit.ssr; +} diff --git a/packages/kit/src/core/dev/index.js b/packages/kit/src/core/dev/index.js index 039c040e134b..7949a32f2d0b 100644 --- a/packages/kit/src/core/dev/index.js +++ b/packages/kit/src/core/dev/index.js @@ -392,6 +392,7 @@ async function create_handler(vite, config, dir, cwd, manifest) { }; }, manifest, + prerender: config.kit.prerender.enabled, read: (file) => fs.readFileSync(path.join(config.kit.files.assets, file)), root, router: config.kit.router, diff --git a/packages/kit/src/runtime/server/index.js b/packages/kit/src/runtime/server/index.js index 24c8cbb47796..f785475ce306 100644 --- a/packages/kit/src/runtime/server/index.js +++ b/packages/kit/src/runtime/server/index.js @@ -48,7 +48,7 @@ export async function respond(incoming, options, state = {}) { return await render_response({ options, $session: await options.hooks.getSession(request), - page_config: { ssr: false, router: true, hydrate: true }, + page_config: { ssr: false, router: true, hydrate: true, prerender: true }, status: 200, branch: [] }); diff --git a/packages/kit/src/runtime/server/page/render.js b/packages/kit/src/runtime/server/page/render.js index 492d302398fc..7ecf620e155d 100644 --- a/packages/kit/src/runtime/server/page/render.js +++ b/packages/kit/src/runtime/server/page/render.js @@ -10,7 +10,7 @@ const s = JSON.stringify; * @param {{ * options: import('types/internal').SSRRenderOptions; * $session: any; - * page_config: { hydrate: boolean, router: boolean, ssr: boolean }; + * page_config: import('types/config').PageOpts; * status: number; * error?: Error, * branch?: Array; diff --git a/packages/kit/src/runtime/server/page/respond.js b/packages/kit/src/runtime/server/page/respond.js index 59a2a361c6a2..07d775685684 100644 --- a/packages/kit/src/runtime/server/page/respond.js +++ b/packages/kit/src/runtime/server/page/respond.js @@ -1,7 +1,7 @@ import { render_response } from './render.js'; import { load_node } from './load_node.js'; import { respond_with_error } from './respond_with_error.js'; -import { coalesce_to_error } from '../utils.js'; +import { coalesce_to_error, resolve_option } from '../utils.js'; /** @typedef {import('./types.js').Loaded} Loaded */ @@ -27,36 +27,17 @@ export async function respond({ request, options, state, $session, route }) { params }; - let nodes; - - try { - nodes = await Promise.all(route.a.map((id) => options.load_component(id))); - } catch (/** @type {unknown} */ err) { - const error = coalesce_to_error(err); - - options.handle_error(error); - - return await respond_with_error({ - request, - options, - state, - $session, - status: 500, - error - }); - } - - const leaf = nodes[nodes.length - 1].module; + const leaf_promise = options.load_component(route.a[route.a.length - 1]).then((c) => c.module); const page_config = { - ssr: 'ssr' in leaf ? !!leaf.ssr : options.ssr, - router: 'router' in leaf ? !!leaf.router : options.router, - hydrate: 'hydrate' in leaf ? !!leaf.hydrate : options.hydrate + ssr: await resolve_option(options.ssr, { request, page: leaf_promise }), + router: await resolve_option(options.router, { request, page: leaf_promise }), + hydrate: await resolve_option(options.hydrate, { request, page: leaf_promise }), + prerender: await resolve_option(options.prerender, { request, page: leaf_promise }) }; - if (!leaf.prerender && state.prerender && !state.prerender.all) { - // if the page has `export const prerender = true`, continue, - // otherwise bail out at this point + // if prerendering some pages, but not this one + if (state.prerender && !state.prerender.all && !page_config.prerender) { return { status: 204, headers: {}, @@ -74,6 +55,29 @@ export async function respond({ request, options, state, $session, route }) { let error; ssr: if (page_config.ssr) { + /** + * The layout components and page components for a page + * @type {import('types/internal').SSRNode[]} + */ + let nodes; + + try { + nodes = await Promise.all(route.a.map((id) => options.load_component(id))); + } catch (/** @type {unknown} */ err) { + const error = coalesce_to_error(err); + + options.handle_error(error); + + return await respond_with_error({ + request, + options, + state, + $session, + status: 500, + error + }); + } + let context = {}; branch = []; diff --git a/packages/kit/src/runtime/server/page/respond_with_error.js b/packages/kit/src/runtime/server/page/respond_with_error.js index 1bdaa0e20117..990c6931d0a8 100644 --- a/packages/kit/src/runtime/server/page/respond_with_error.js +++ b/packages/kit/src/runtime/server/page/respond_with_error.js @@ -1,6 +1,6 @@ import { render_response } from './render.js'; import { load_node } from './load_node.js'; -import { coalesce_to_error } from '../utils.js'; +import { coalesce_to_error, resolve_option } from '../utils.js'; /** * @param {{ @@ -55,15 +55,20 @@ export async function respond_with_error({ request, options, state, $session, st })) ]; + const leaf_promise = async () => branch[branch.length - 1].node.module; + + const page_config = { + ssr: await resolve_option(options.ssr, { request, page: leaf_promise }), + router: await resolve_option(options.router, { request, page: leaf_promise }), + hydrate: await resolve_option(options.hydrate, { request, page: leaf_promise }), + prerender: await resolve_option(options.prerender, { request, page: leaf_promise }) + }; + try { return await render_response({ options, $session, - page_config: { - hydrate: options.hydrate, - router: options.router, - ssr: options.ssr - }, + page_config, status, error, branch, diff --git a/packages/kit/src/runtime/server/utils.js b/packages/kit/src/runtime/server/utils.js index 74fde8c68a70..b6208023390e 100644 --- a/packages/kit/src/runtime/server/utils.js +++ b/packages/kit/src/runtime/server/utils.js @@ -17,3 +17,15 @@ export function lowercase_keys(obj) { export function coalesce_to_error(err) { return err instanceof Error ? err : new Error(JSON.stringify(err)); } + +/** + * @param {any} opt + * @param {object} ctx + * @returns + */ +export async function resolve_option(opt, ctx) { + if (typeof opt === 'function') { + return await opt(ctx); + } + return opt; +} diff --git a/packages/kit/types/config.d.ts b/packages/kit/types/config.d.ts index 4f97b93d6ef0..16673eb226a3 100644 --- a/packages/kit/types/config.d.ts +++ b/packages/kit/types/config.d.ts @@ -1,3 +1,4 @@ +import { ServerRequest } from './hooks'; import { Logger, TrailingSlash } from './internal'; import { UserConfig as ViteConfig } from 'vite'; @@ -25,6 +26,20 @@ export interface Adapter { adapt: ({ utils, config }: { utils: AdapterUtils; config: ValidatedConfig }) => Promise; } +export interface PageOpts { + ssr: boolean; + router: boolean; + hydrate: boolean; + prerender: boolean; +} + +export interface PageOptsContext { + request: ServerRequest; + page: Promise; +} + +export type ScriptablePageOpt = T | (({ request, page }: PageOptsContext) => Promise); + export interface Config { compilerOptions?: any; extensions?: string[]; @@ -43,7 +58,7 @@ export interface Config { floc?: boolean; host?: string; hostHeader?: string; - hydrate?: boolean; + hydrate?: ScriptablePageOpt; package?: { dir?: string; emitTypes?: boolean; @@ -62,15 +77,15 @@ export interface Config { }; prerender?: { crawl?: boolean; - enabled?: boolean; + enabled?: ScriptablePageOpt; force?: boolean; pages?: string[]; }; - router?: boolean; + router?: ScriptablePageOpt; serviceWorker?: { exclude?: string[]; }; - ssr?: boolean; + ssr?: ScriptablePageOpt; target?: string; trailingSlash?: TrailingSlash; vite?: ViteConfig | (() => ViteConfig); @@ -106,7 +121,7 @@ export interface ValidatedConfig { floc: boolean; host: string; hostHeader: string; - hydrate: boolean; + hydrate: ScriptablePageOpt; package: { dir: string; emitTypes: boolean; @@ -125,15 +140,15 @@ export interface ValidatedConfig { }; prerender: { crawl: boolean; - enabled: boolean; + enabled: ScriptablePageOpt; onError: PrerenderOnErrorValue; pages: string[]; }; - router: boolean; + router: ScriptablePageOpt; serviceWorker: { exclude: string[]; }; - ssr: boolean; + ssr: ScriptablePageOpt; target: string; trailingSlash: TrailingSlash; vite: () => ViteConfig; diff --git a/packages/kit/types/internal.d.ts b/packages/kit/types/internal.d.ts index b76913cf2369..8f532ee10d51 100644 --- a/packages/kit/types/internal.d.ts +++ b/packages/kit/types/internal.d.ts @@ -1,3 +1,4 @@ +import { PageOpts, ScriptablePageOpt, ValidatedConfig } from './config'; import { RequestHandler } from './endpoint'; import { Headers, Location, ParameterizedBody } from './helper'; import { GetSession, Handle, ServerResponse, ServerFetch, StrictBody } from './hooks'; @@ -46,11 +47,7 @@ export interface App { ) => Promise; } -export interface SSRComponent { - ssr?: boolean; - router?: boolean; - hydrate?: boolean; - prerender?: boolean; +export interface SSRComponent extends PageOpts { preload?: any; // TODO remove for 1.0 load: Load; default: { @@ -142,18 +139,19 @@ export interface SSRRenderOptions { get_stack: (error: Error) => string | undefined; handle_error: (error: Error) => void; hooks: Hooks; - hydrate: boolean; + hydrate: ScriptablePageOpt; load_component: (id: PageId) => Promise; manifest: SSRManifest; paths: { base: string; assets: string; }; + prerender: ScriptablePageOpt; read: (file: string) => Buffer; root: SSRComponent['default']; - router: boolean; + router: ScriptablePageOpt; service_worker?: string; - ssr: boolean; + ssr: ScriptablePageOpt; target: string; template: ({ head, body }: { head: string; body: string }) => string; trailing_slash: TrailingSlash;