mirror of
https://github.com/kevin-DL/sapper.git
synced 2026-01-22 23:25:20 +00:00
server-side rendering
This commit is contained in:
@@ -11,13 +11,25 @@ import sourceMapSupport from 'source-map-support';
|
|||||||
|
|
||||||
sourceMapSupport.install();
|
sourceMapSupport.install();
|
||||||
|
|
||||||
type RouteObject = {
|
type ServerRoute = {
|
||||||
id: string;
|
|
||||||
type: 'page' | 'route';
|
|
||||||
pattern: RegExp;
|
pattern: RegExp;
|
||||||
|
handlers: Record<string, Handler>;
|
||||||
params: (match: RegExpMatchArray) => Record<string, string>;
|
params: (match: RegExpMatchArray) => Record<string, string>;
|
||||||
module: Component;
|
};
|
||||||
error?: string;
|
|
||||||
|
type Page = {
|
||||||
|
pattern: RegExp;
|
||||||
|
parts: Array<{
|
||||||
|
component: Component;
|
||||||
|
params?: (match: RegExpMatchArray) => Record<string, string>;
|
||||||
|
}>
|
||||||
|
};
|
||||||
|
|
||||||
|
type RouteObject = {
|
||||||
|
server_routes: ServerRoute[];
|
||||||
|
pages: Page[];
|
||||||
|
root: Component;
|
||||||
|
error: Component;
|
||||||
}
|
}
|
||||||
|
|
||||||
type Handler = (req: Req, res: ServerResponse, next: () => void) => void;
|
type Handler = (req: Req, res: ServerResponse, next: () => void) => void;
|
||||||
@@ -33,6 +45,7 @@ interface Req extends ClientRequest {
|
|||||||
method: string;
|
method: string;
|
||||||
path: string;
|
path: string;
|
||||||
params: Record<string, string>;
|
params: Record<string, string>;
|
||||||
|
query: Record<string, string>;
|
||||||
headers: Record<string, string>;
|
headers: Record<string, string>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,7 +59,7 @@ interface Component {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function middleware({ routes, store }: {
|
export default function middleware({ routes, store }: {
|
||||||
routes: RouteObject[],
|
routes: RouteObject,
|
||||||
store: (req: Req) => Store
|
store: (req: Req) => Store
|
||||||
}) {
|
}) {
|
||||||
const output = locations.dest();
|
const output = locations.dest();
|
||||||
@@ -147,8 +160,8 @@ function serve({ prefix, pathname, cache_control }: {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function get_server_route_handler(routes: RouteObject[]) {
|
function get_server_route_handler(routes: ServerRoute[]) {
|
||||||
function handle_route(route, req, res, next) {
|
function handle_route(route: ServerRoute, req: Req, res: ServerResponse, next: () => void) {
|
||||||
req.params = route.params(route.pattern.exec(req.path));
|
req.params = route.params(route.pattern.exec(req.path));
|
||||||
|
|
||||||
const method = req.method.toLowerCase();
|
const method = req.method.toLowerCase();
|
||||||
@@ -210,7 +223,7 @@ function get_server_route_handler(routes: RouteObject[]) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return function find_route(req: Req, res: ServerResponse, next) {
|
return function find_route(req: Req, res: ServerResponse, next: () => void) {
|
||||||
for (const route of routes) {
|
for (const route of routes) {
|
||||||
if (route.pattern.test(req.path)) {
|
if (route.pattern.test(req.path)) {
|
||||||
handle_route(route, req, res, next);
|
handle_route(route, req, res, next);
|
||||||
@@ -222,7 +235,7 @@ function get_server_route_handler(routes: RouteObject[]) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Store) {
|
function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store) {
|
||||||
const output = locations.dest();
|
const output = locations.dest();
|
||||||
|
|
||||||
const get_chunks = dev()
|
const get_chunks = dev()
|
||||||
@@ -236,10 +249,11 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
|||||||
const { server_routes, pages } = routes;
|
const { server_routes, pages } = routes;
|
||||||
const error_route = routes.error;
|
const error_route = routes.error;
|
||||||
|
|
||||||
function handle_route(route: RouteObject, req: Req, res: ServerResponse, status = 200, error: Error | string = null) {
|
function handle_page(page: Page, req: Req, res: ServerResponse, status = 200, error: Error | string = null) {
|
||||||
|
const get_params = page.parts[page.parts.length - 1].params || (() => ({}));
|
||||||
req.params = error
|
req.params = error
|
||||||
? {}
|
? {}
|
||||||
: route.params(route.pattern.exec(req.path));
|
: get_params(page.pattern.exec(req.path));
|
||||||
|
|
||||||
const chunks: Record<string, string> = get_chunks();
|
const chunks: Record<string, string> = get_chunks();
|
||||||
|
|
||||||
@@ -248,7 +262,8 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
|||||||
// preload main.js and current route
|
// preload main.js and current route
|
||||||
// TODO detect other stuff we can preload? images, CSS, fonts?
|
// TODO detect other stuff we can preload? images, CSS, fonts?
|
||||||
const link = []
|
const link = []
|
||||||
.concat(chunks.main, chunks[route.id] || chunks._error) // TODO this is gross
|
// TODO reinstate this!
|
||||||
|
// .concat(chunks.main, chunks[page.id] || chunks._error) // TODO this is gross
|
||||||
.filter(file => !file.match(/\.map$/))
|
.filter(file => !file.match(/\.map$/))
|
||||||
.map(file => `<${req.baseUrl}/client/${file}>;rel="preload";as="script"`)
|
.map(file => `<${req.baseUrl}/client/${file}>;rel="preload";as="script"`)
|
||||||
.join(', ');
|
.join(', ');
|
||||||
@@ -258,61 +273,68 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
|||||||
const store = store_getter ? store_getter(req) : null;
|
const store = store_getter ? store_getter(req) : null;
|
||||||
const props = { params: req.params, query: req.query, path: req.path };
|
const props = { params: req.params, query: req.query, path: req.path };
|
||||||
|
|
||||||
if (route.error) {
|
// TODO reinstate this!
|
||||||
props.error = error instanceof Error ? error : { message: error };
|
// if (page.error) {
|
||||||
props.status = status;
|
// props.error = error instanceof Error ? error : { message: error };
|
||||||
}
|
// props.status = status;
|
||||||
|
// }
|
||||||
|
|
||||||
let redirect: { statusCode: number, location: string };
|
let redirect: { statusCode: number, location: string };
|
||||||
let preload_error: { statusCode: number, message: Error | string };
|
let preload_error: { statusCode: number, message: Error | string };
|
||||||
|
|
||||||
Promise.resolve(
|
Promise.all(page.parts.map(part => {
|
||||||
route.handler.preload ? route.handler.preload.call({
|
return part.component.preload
|
||||||
redirect: (statusCode: number, location: string) => {
|
? part.component.preload.call({
|
||||||
redirect = { statusCode, location };
|
redirect: (statusCode: number, location: string) => {
|
||||||
},
|
if (redirect && redirect.statusCode !== statusCode || redirect.location !== location) {
|
||||||
error: (statusCode: number, message: Error | string) => {
|
throw new Error(`Conflicting redirects`);
|
||||||
preload_error = { statusCode, message };
|
|
||||||
},
|
|
||||||
fetch: (url: string, opts?: any) => {
|
|
||||||
const parsed = new URL(url, `http://127.0.0.1:${process.env.PORT}${req.baseUrl ? req.baseUrl + '/' :''}`);
|
|
||||||
|
|
||||||
if (opts) {
|
|
||||||
opts = Object.assign({}, opts);
|
|
||||||
|
|
||||||
const include_cookies = (
|
|
||||||
opts.credentials === 'include' ||
|
|
||||||
opts.credentials === 'same-origin' && parsed.origin === `http://127.0.0.1:${process.env.PORT}`
|
|
||||||
);
|
|
||||||
|
|
||||||
if (include_cookies) {
|
|
||||||
const cookies: Record<string, string> = {};
|
|
||||||
if (!opts.headers) opts.headers = {};
|
|
||||||
|
|
||||||
const str = []
|
|
||||||
.concat(
|
|
||||||
cookie.parse(req.headers.cookie || ''),
|
|
||||||
cookie.parse(opts.headers.cookie || ''),
|
|
||||||
cookie.parse(res.getHeader('Set-Cookie') || '')
|
|
||||||
)
|
|
||||||
.map(cookie => {
|
|
||||||
return Object.keys(cookie)
|
|
||||||
.map(name => `${name}=${encodeURIComponent(cookie[name])}`)
|
|
||||||
.join('; ');
|
|
||||||
})
|
|
||||||
.filter(Boolean)
|
|
||||||
.join(', ');
|
|
||||||
|
|
||||||
opts.headers.cookie = str;
|
|
||||||
}
|
}
|
||||||
}
|
redirect = { statusCode, location };
|
||||||
|
},
|
||||||
|
error: (statusCode: number, message: Error | string) => {
|
||||||
|
preload_error = { statusCode, message };
|
||||||
|
},
|
||||||
|
fetch: (url: string, opts?: any) => {
|
||||||
|
const parsed = new URL(url, `http://127.0.0.1:${process.env.PORT}${req.baseUrl ? req.baseUrl + '/' :''}`);
|
||||||
|
|
||||||
return fetch(parsed.href, opts);
|
if (opts) {
|
||||||
},
|
opts = Object.assign({}, opts);
|
||||||
store
|
|
||||||
}, req) : {}
|
const include_cookies = (
|
||||||
).catch(err => {
|
opts.credentials === 'include' ||
|
||||||
|
opts.credentials === 'same-origin' && parsed.origin === `http://127.0.0.1:${process.env.PORT}`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (include_cookies) {
|
||||||
|
const cookies: Record<string, string> = {};
|
||||||
|
if (!opts.headers) opts.headers = {};
|
||||||
|
|
||||||
|
const str = []
|
||||||
|
.concat(
|
||||||
|
cookie.parse(req.headers.cookie || ''),
|
||||||
|
cookie.parse(opts.headers.cookie || ''),
|
||||||
|
cookie.parse(res.getHeader('Set-Cookie') || '')
|
||||||
|
)
|
||||||
|
.map(cookie => {
|
||||||
|
return Object.keys(cookie)
|
||||||
|
.map(name => `${name}=${encodeURIComponent(cookie[name])}`)
|
||||||
|
.join('; ');
|
||||||
|
})
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(', ');
|
||||||
|
|
||||||
|
opts.headers.cookie = str;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return fetch(parsed.href, opts);
|
||||||
|
},
|
||||||
|
store
|
||||||
|
}, req)
|
||||||
|
: {};
|
||||||
|
})).catch(err => {
|
||||||
preload_error = { statusCode: 500, message: err };
|
preload_error = { statusCode: 500, message: err };
|
||||||
|
return []; // appease TypeScript
|
||||||
}).then(preloaded => {
|
}).then(preloaded => {
|
||||||
if (redirect) {
|
if (redirect) {
|
||||||
res.statusCode = redirect.statusCode;
|
res.statusCode = redirect.statusCode;
|
||||||
@@ -323,20 +345,37 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (preload_error) {
|
if (preload_error) {
|
||||||
handle_route(error_route, req, res, preload_error.statusCode, preload_error.message);
|
// TODO reinstate this!
|
||||||
|
// handle_page(error_route, req, res, preload_error.statusCode, preload_error.message);
|
||||||
|
res.end('oops');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const serialized = {
|
const serialized = {
|
||||||
preloaded: route.handler.preload && try_serialize(preloaded),
|
preloaded: page.parts.map((part, i) => {
|
||||||
|
return part.component.preload && try_serialize(preloaded[i]);
|
||||||
|
}),
|
||||||
store: store && try_serialize(store.get())
|
store: store && try_serialize(store.get())
|
||||||
};
|
};
|
||||||
Object.assign(props, preloaded);
|
|
||||||
|
|
||||||
res.end('TODO');
|
const data = Object.assign({}, props, {
|
||||||
return;
|
child: {}
|
||||||
|
});
|
||||||
|
let level = data.child;
|
||||||
|
for (let i = 0; i < page.parts.length; i += 1) {
|
||||||
|
const part = page.parts[i];
|
||||||
|
Object.assign(level, {
|
||||||
|
// TODO segment
|
||||||
|
props: Object.assign({}, props, preloaded[i]),
|
||||||
|
component: part.component
|
||||||
|
});
|
||||||
|
if (i < preloaded.length - 1) {
|
||||||
|
level.props.child = {};
|
||||||
|
}
|
||||||
|
level = level.props.child;
|
||||||
|
}
|
||||||
|
|
||||||
const { html, head, css } = App.render({ Page: route.handler, props }, {
|
const { html, head, css } = routes.root.render(data, {
|
||||||
store
|
store
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -357,7 +396,7 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
|||||||
inline_script += `if ('serviceWorker' in navigator) navigator.serviceWorker.register('${req.baseUrl}/service-worker.js');`;
|
inline_script += `if ('serviceWorker' in navigator) navigator.serviceWorker.register('${req.baseUrl}/service-worker.js');`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const page = template()
|
const body = template()
|
||||||
.replace('%sapper.base%', () => `<base href="${req.baseUrl}/">`)
|
.replace('%sapper.base%', () => `<base href="${req.baseUrl}/">`)
|
||||||
.replace('%sapper.scripts%', () => `<script>${inline_script}</script>${scripts}`)
|
.replace('%sapper.scripts%', () => `<script>${inline_script}</script>${scripts}`)
|
||||||
.replace('%sapper.html%', () => html)
|
.replace('%sapper.html%', () => html)
|
||||||
@@ -365,7 +404,7 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
|||||||
.replace('%sapper.styles%', () => (css && css.code ? `<style>${css.code}</style>` : ''));
|
.replace('%sapper.styles%', () => (css && css.code ? `<style>${css.code}</style>` : ''));
|
||||||
|
|
||||||
res.statusCode = status;
|
res.statusCode = status;
|
||||||
res.end(page);
|
res.end(body);
|
||||||
|
|
||||||
if (process.send) {
|
if (process.send) {
|
||||||
process.send({
|
process.send({
|
||||||
@@ -375,7 +414,7 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
|||||||
method: req.method,
|
method: req.method,
|
||||||
status: 200,
|
status: 200,
|
||||||
type: 'text/html',
|
type: 'text/html',
|
||||||
body: page
|
body
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -385,13 +424,13 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
|||||||
if (!server_routes.some(route => route.pattern.test(req.path))) {
|
if (!server_routes.some(route => route.pattern.test(req.path))) {
|
||||||
for (const page of pages) {
|
for (const page of pages) {
|
||||||
if (page.pattern.test(req.path)) {
|
if (page.pattern.test(req.path)) {
|
||||||
handle_route(page, req, res);
|
handle_page(page, req, res);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
handle_route(error_route, req, res, 404, 'Not found');
|
handle_page(error_route, req, res, 404, 'Not found');
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user