mirror of
https://github.com/kevin-DL/sapper.git
synced 2026-01-13 11:35:28 +00:00
Compare commits
2 Commits
gh-262-no-
...
v0.15.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d0bb728e25 | ||
|
|
58de0f9c99 |
@@ -1,5 +1,9 @@
|
||||
# sapper changelog
|
||||
|
||||
## 0.15.0
|
||||
|
||||
* Nested routes (consult [migration guide](https://sapper.svelte.technology/guide#0-14-to-0-15) and docs on [layouts](https://sapper.svelte.technology/guide#layouts)) ([#262](https://github.com/sveltejs/sapper/issues/262))
|
||||
|
||||
## 0.14.2
|
||||
|
||||
* Prevent unsafe replacements ([#307](https://github.com/sveltejs/sapper/pull/307))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "sapper",
|
||||
"version": "0.14.2",
|
||||
"version": "0.15.0",
|
||||
"description": "Military-grade apps, engineered by Svelte",
|
||||
"main": "dist/middleware.ts.js",
|
||||
"bin": {
|
||||
@@ -12,6 +12,7 @@
|
||||
"runtime",
|
||||
"webpack",
|
||||
"sapper",
|
||||
"components",
|
||||
"dist"
|
||||
],
|
||||
"directories": {
|
||||
@@ -67,7 +68,7 @@
|
||||
"cy:open": "cypress open",
|
||||
"test": "mocha --opts mocha.opts",
|
||||
"pretest": "npm run build",
|
||||
"build": "rollup -c",
|
||||
"build": "rm -rf dist && rollup -c",
|
||||
"dev": "rollup -cw",
|
||||
"prepublishOnly": "npm test",
|
||||
"update_mime_types": "curl http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types | grep -e \"^[^#]\" > src/middleware/mime-types.md"
|
||||
|
||||
@@ -19,7 +19,8 @@ export default [
|
||||
},
|
||||
plugins: [
|
||||
typescript({
|
||||
typescript: require('typescript')
|
||||
typescript: require('typescript'),
|
||||
target: "ES2017"
|
||||
})
|
||||
]
|
||||
},
|
||||
|
||||
@@ -14,6 +14,10 @@ export function create_main_manifests({ routes, dev_port }: {
|
||||
const client_manifest = generate_client(routes, path_to_routes, dev_port);
|
||||
const server_manifest = generate_server(routes, path_to_routes);
|
||||
|
||||
write_if_changed(
|
||||
`${locations.app()}/manifest/default-layout.html`,
|
||||
`<svelte:component this={child.component} {...child.props}/>`
|
||||
);
|
||||
write_if_changed(`${locations.app()}/manifest/client.js`, client_manifest);
|
||||
write_if_changed(`${locations.app()}/manifest/server.js`, server_manifest);
|
||||
}
|
||||
@@ -44,7 +48,7 @@ function right_pad(str: string, len: number) {
|
||||
}
|
||||
|
||||
function generate_client(
|
||||
routes: { components: PageComponent[], pages: Page[], server_routes: ServerRoute[] },
|
||||
routes: { root: PageComponent, components: PageComponent[], pages: Page[], server_routes: ServerRoute[] },
|
||||
path_to_routes: string,
|
||||
dev_port?: number
|
||||
) {
|
||||
@@ -58,15 +62,15 @@ function generate_client(
|
||||
|
||||
let code = `
|
||||
// This file is generated by Sapper — do not edit it!
|
||||
import root from '${posixify(`${path_to_routes}/index.html`)}';
|
||||
import root from '${posixify(`${path_to_routes}/${routes.root.file}`)}';
|
||||
import error from '${posixify(`${path_to_routes}/_error.html`)}';
|
||||
|
||||
${routes.components.map(component =>
|
||||
`const ${component.name} = () =>
|
||||
import(/* webpackChunkName: "${component.name}" */ '${posixify(`${path_to_routes}/${component.file}`)}');`)
|
||||
import(/* webpackChunkName: "${component.name}" */ '${get_file(path_to_routes, component)}');`)
|
||||
.join('\n')}
|
||||
|
||||
export const routes = {
|
||||
export const manifest = {
|
||||
ignore: [${server_routes_to_ignore.map(route => route.pattern).join(', ')}],
|
||||
|
||||
pages: [
|
||||
@@ -89,7 +93,10 @@ function generate_client(
|
||||
root,
|
||||
|
||||
error
|
||||
};`.replace(/^\t\t/gm, '').trim();
|
||||
};
|
||||
|
||||
// this is included for legacy reasons
|
||||
export const routes = {};`.replace(/^\t\t/gm, '').trim();
|
||||
|
||||
if (dev()) {
|
||||
const sapper_dev_client = posixify(
|
||||
@@ -109,15 +116,15 @@ function generate_client(
|
||||
}
|
||||
|
||||
function generate_server(
|
||||
routes: { components: PageComponent[], pages: Page[], server_routes: ServerRoute[] },
|
||||
routes: { root: PageComponent, components: PageComponent[], pages: Page[], server_routes: ServerRoute[] },
|
||||
path_to_routes: string
|
||||
) {
|
||||
const imports = [].concat(
|
||||
routes.server_routes.map(route =>
|
||||
`import * as ${route.name} from '${posixify(`${path_to_routes}/${route.file}`)}';`),
|
||||
routes.components.map(component =>
|
||||
`import ${component.name} from '${posixify(`${path_to_routes}/${component.file}`)}';`),
|
||||
`import root from '${posixify(`${path_to_routes}/index.html`)}';`,
|
||||
`import ${component.name} from '${get_file(path_to_routes, component)}';`),
|
||||
`import root from '${posixify(`${path_to_routes}/${routes.root.file}`)}';`,
|
||||
`import error from '${posixify(`${path_to_routes}/_error.html`)}';`
|
||||
);
|
||||
|
||||
@@ -125,7 +132,7 @@ function generate_server(
|
||||
// This file is generated by Sapper — do not edit it!
|
||||
${imports.join('\n')}
|
||||
|
||||
export const routes = {
|
||||
export const manifest = {
|
||||
server_routes: [
|
||||
${routes.server_routes.map(route => `{
|
||||
// ${route.file}
|
||||
@@ -162,7 +169,18 @@ function generate_server(
|
||||
root,
|
||||
|
||||
error
|
||||
};`.replace(/^\t\t/gm, '').trim();
|
||||
};
|
||||
|
||||
// this is included for legacy reasons
|
||||
export const routes = {};`.replace(/^\t\t/gm, '').trim();
|
||||
|
||||
return code;
|
||||
}
|
||||
|
||||
function get_file(path_to_routes: string, component: PageComponent) {
|
||||
if (component.default) {
|
||||
return `./default-layout.html`;
|
||||
}
|
||||
|
||||
return posixify(`${path_to_routes}/${component.file}`);
|
||||
}
|
||||
@@ -4,11 +4,22 @@ import { locations } from '../config';
|
||||
import { Page, PageComponent, ServerRoute } from '../interfaces';
|
||||
import { posixify } from './utils';
|
||||
|
||||
const default_layout_file = posixify(path.resolve(
|
||||
__dirname,
|
||||
'../components/default-layout.html'
|
||||
));
|
||||
|
||||
export default function create_routes(cwd = locations.routes()) {
|
||||
const components: PageComponent[] = [];
|
||||
const pages: Page[] = [];
|
||||
const server_routes: ServerRoute[] = [];
|
||||
|
||||
const default_layout: PageComponent = {
|
||||
default: true,
|
||||
name: '_default_layout',
|
||||
file: null
|
||||
};
|
||||
|
||||
function walk(
|
||||
dir: string,
|
||||
parent_segments: Part[][],
|
||||
@@ -54,9 +65,7 @@ export default function create_routes(cwd = locations.routes()) {
|
||||
.sort(comparator);
|
||||
|
||||
items.forEach(item => {
|
||||
if (item.basename[0] === '_') {
|
||||
if (item.basename !== (item.is_dir ? '_default' : '_default.html')) return;
|
||||
}
|
||||
if (item.basename[0] === '_') return;
|
||||
|
||||
if (item.basename[0] === '.') {
|
||||
if (item.file !== '.well-known') return;
|
||||
@@ -91,16 +100,18 @@ export default function create_routes(cwd = locations.routes()) {
|
||||
params.push(...item.parts.filter(p => p.dynamic).map(p => p.content));
|
||||
|
||||
if (item.is_dir) {
|
||||
const index = path.join(dir, item.basename, 'index.html');
|
||||
const component = fs.existsSync(index)
|
||||
const index = path.join(dir, item.basename, '_layout.html');
|
||||
const layout = fs.existsSync(index)
|
||||
? {
|
||||
name: `page_${get_slug(item.file)}`,
|
||||
file: `${item.file}/index.html`
|
||||
name: `${get_slug(item.file)}__layout`,
|
||||
file: `${item.file}/_layout.html`
|
||||
}
|
||||
: null;
|
||||
|
||||
if (component) {
|
||||
components.push(component);
|
||||
if (layout) {
|
||||
components.push(layout);
|
||||
} else if (components.indexOf(default_layout) === -1) {
|
||||
components.push(default_layout);
|
||||
}
|
||||
|
||||
walk(
|
||||
@@ -108,41 +119,15 @@ export default function create_routes(cwd = locations.routes()) {
|
||||
segments,
|
||||
params,
|
||||
stack.concat({
|
||||
component: component || {
|
||||
missing: true,
|
||||
name: null,
|
||||
file: path.join(item.file, 'index.html')
|
||||
},
|
||||
component: layout || default_layout,
|
||||
params
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
else if (item.basename === 'index.html') {
|
||||
const is_branch = items.some(other_item => {
|
||||
if (other_item === item) return false;
|
||||
if (other_item.basename[0] === '_') {
|
||||
return other_item.basename === (other_item.is_dir ? '_default' : '_default.html');
|
||||
}
|
||||
|
||||
if (other_item.is_dir) {
|
||||
return fs.existsSync(path.join(dir, other_item.basename, 'index.html'));
|
||||
}
|
||||
|
||||
return other_item.is_page;
|
||||
});
|
||||
|
||||
if (!is_branch) {
|
||||
pages.push({
|
||||
pattern: get_pattern(parent_segments),
|
||||
parts: stack
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
else if (item.is_page) {
|
||||
const component = {
|
||||
name: `page_${get_slug(item.file)}`,
|
||||
name: get_slug(item.file),
|
||||
file: item.file
|
||||
};
|
||||
|
||||
@@ -152,7 +137,7 @@ export default function create_routes(cwd = locations.routes()) {
|
||||
});
|
||||
|
||||
components.push(component);
|
||||
if (item.basename === '_default.html') {
|
||||
if (item.basename === 'index.html') {
|
||||
pages.push({
|
||||
pattern: get_pattern(parent_segments),
|
||||
parts
|
||||
@@ -176,21 +161,19 @@ export default function create_routes(cwd = locations.routes()) {
|
||||
});
|
||||
}
|
||||
|
||||
const root_file = path.join(cwd, '_layout.html');
|
||||
const root = fs.existsSync(root_file)
|
||||
? {
|
||||
name: 'main',
|
||||
file: '_layout.html'
|
||||
}
|
||||
: default_layout;
|
||||
|
||||
walk(cwd, [], [], []);
|
||||
|
||||
// check for clashes
|
||||
const seen_pages: Map<string, Page> = new Map();
|
||||
pages.forEach(page => {
|
||||
// check for missing intermediate index.html files
|
||||
let i = page.parts.length;
|
||||
const last_part = page.parts[i - 1];
|
||||
while (i--) {
|
||||
const part = page.parts[i];
|
||||
if (part.component.missing) {
|
||||
throw new Error(`Missing ${part.component.file}, which is required for ${last_part.component.file} to be valid`);
|
||||
}
|
||||
}
|
||||
|
||||
// check for clashes
|
||||
const pattern = page.pattern.toString();
|
||||
if (seen_pages.has(pattern)) {
|
||||
const file = page.parts.pop().component.file;
|
||||
@@ -215,6 +198,7 @@ export default function create_routes(cwd = locations.routes()) {
|
||||
});
|
||||
|
||||
return {
|
||||
root,
|
||||
components,
|
||||
pages,
|
||||
server_routes
|
||||
@@ -228,9 +212,11 @@ type Part = {
|
||||
};
|
||||
|
||||
function comparator(
|
||||
a: { basename: string, parts: Part[], file: string, is_dir: boolean },
|
||||
b: { basename: string, parts: Part[], file: string, is_dir: boolean }
|
||||
a: { basename: string, parts: Part[], file: string, is_index: boolean },
|
||||
b: { basename: string, parts: Part[], file: string, is_index: boolean }
|
||||
) {
|
||||
if (a.is_index !== b.is_index) return a.is_index ? -1 : 1;
|
||||
|
||||
const max = Math.max(a.parts.length, b.parts.length);
|
||||
|
||||
for (let i = 0; i < max; i += 1) {
|
||||
|
||||
@@ -21,7 +21,7 @@ export type Store = {
|
||||
};
|
||||
|
||||
export type PageComponent = {
|
||||
missing?: boolean;
|
||||
default?: boolean;
|
||||
name: string;
|
||||
file: string;
|
||||
};
|
||||
|
||||
@@ -26,7 +26,7 @@ type Page = {
|
||||
}>
|
||||
};
|
||||
|
||||
type RouteObject = {
|
||||
type Manifest = {
|
||||
server_routes: ServerRoute[];
|
||||
pages: Page[];
|
||||
root: Component;
|
||||
@@ -39,6 +39,20 @@ type Store = {
|
||||
get: () => any
|
||||
};
|
||||
|
||||
type Props = {
|
||||
path: string;
|
||||
query: Record<string, string>;
|
||||
params: Record<string, string>;
|
||||
error?: { message: string };
|
||||
status?: number;
|
||||
child: {
|
||||
segment: string;
|
||||
component: Component;
|
||||
props: Props;
|
||||
};
|
||||
[key: string]: any;
|
||||
};
|
||||
|
||||
interface Req extends ClientRequest {
|
||||
url: string;
|
||||
baseUrl: string;
|
||||
@@ -59,12 +73,19 @@ interface Component {
|
||||
preload: (data: any) => any | Promise<any>
|
||||
}
|
||||
|
||||
export default function middleware({ routes, store }: {
|
||||
routes: RouteObject,
|
||||
store: (req: Req) => Store
|
||||
export default function middleware(opts: {
|
||||
manifest: Manifest,
|
||||
store: (req: Req) => Store,
|
||||
routes?: any // legacy
|
||||
}) {
|
||||
if (opts.routes) {
|
||||
throw new Error(`As of Sapper 0.15, opts.routes should be opts.manifest`);
|
||||
}
|
||||
|
||||
const output = locations.dest();
|
||||
|
||||
const { manifest, store } = opts;
|
||||
|
||||
let emitted_basepath = false;
|
||||
|
||||
const middleware = compose_handlers([
|
||||
@@ -117,8 +138,8 @@ export default function middleware({ routes, store }: {
|
||||
cache_control: 'max-age=31536000'
|
||||
}),
|
||||
|
||||
get_server_route_handler(routes.server_routes),
|
||||
get_page_handler(routes, store)
|
||||
get_server_route_handler(manifest.server_routes),
|
||||
get_page_handler(manifest, store)
|
||||
].filter(Boolean));
|
||||
|
||||
return middleware;
|
||||
@@ -235,7 +256,7 @@ function get_server_route_handler(routes: ServerRoute[]) {
|
||||
};
|
||||
}
|
||||
|
||||
function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store) {
|
||||
function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store) {
|
||||
const output = locations.dest();
|
||||
|
||||
const get_chunks = dev()
|
||||
@@ -246,17 +267,22 @@ function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store
|
||||
? () => fs.readFileSync(`${locations.app()}/template.html`, 'utf-8')
|
||||
: (str => () => str)(fs.readFileSync(`${locations.dest()}/template.html`, 'utf-8'));
|
||||
|
||||
const { server_routes, pages } = routes;
|
||||
const error_route = routes.error;
|
||||
const { server_routes, pages } = manifest;
|
||||
const error_route = manifest.error;
|
||||
|
||||
function handle_error(req: Req, res: ServerResponse, statusCode: number, error: Error | string) {
|
||||
handle_page({
|
||||
pattern: null,
|
||||
parts: [
|
||||
{ name: null, component: error_route }
|
||||
]
|
||||
}, req, res, statusCode, error);
|
||||
}
|
||||
|
||||
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 || (() => ({}));
|
||||
const match = error ? null : page.pattern.exec(req.path);
|
||||
|
||||
req.params = error
|
||||
? {}
|
||||
: get_params(match);
|
||||
|
||||
const chunks: Record<string, string | string[]> = get_chunks();
|
||||
|
||||
res.setHeader('Content-Type', 'text/html');
|
||||
@@ -279,67 +305,75 @@ function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store
|
||||
res.setHeader('Link', link);
|
||||
|
||||
const store = store_getter ? store_getter(req) : null;
|
||||
const props = { query: req.query, path: req.path };
|
||||
|
||||
if (error) {
|
||||
props.error = error instanceof Error ? error : { message: error };
|
||||
props.status = status;
|
||||
}
|
||||
|
||||
let redirect: { statusCode: number, location: string };
|
||||
let preload_error: { statusCode: number, message: Error | string };
|
||||
|
||||
Promise.all(page.parts.map(part => {
|
||||
const preload_context = {
|
||||
redirect: (statusCode: number, location: string) => {
|
||||
if (redirect && (redirect.statusCode !== statusCode || redirect.location !== location)) {
|
||||
throw new Error(`Conflicting redirects`);
|
||||
}
|
||||
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 + '/' :''}`);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
return fetch(parsed.href, opts);
|
||||
},
|
||||
store
|
||||
};
|
||||
|
||||
const root_preloaded = manifest.root.preload
|
||||
? manifest.root.preload.call(preload_context, {
|
||||
path: req.path,
|
||||
query: req.query,
|
||||
params: {}
|
||||
})
|
||||
: {};
|
||||
|
||||
Promise.all([root_preloaded].concat(page.parts.map(part => {
|
||||
return part.component.preload
|
||||
? part.component.preload.call({
|
||||
redirect: (statusCode: number, location: string) => {
|
||||
if (redirect && (redirect.statusCode !== statusCode || redirect.location !== location)) {
|
||||
throw new Error(`Conflicting redirects`);
|
||||
}
|
||||
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 + '/' :''}`);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
return fetch(parsed.href, opts);
|
||||
},
|
||||
store
|
||||
}, req)
|
||||
? part.component.preload.call(preload_context, {
|
||||
path: req.path,
|
||||
query: req.query,
|
||||
params: part.params ? part.params(match) : {}
|
||||
})
|
||||
: {};
|
||||
})).catch(err => {
|
||||
}))).catch(err => {
|
||||
preload_error = { statusCode: 500, message: err };
|
||||
return []; // appease TypeScript
|
||||
}).then(preloaded => {
|
||||
@@ -352,28 +386,34 @@ function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store
|
||||
}
|
||||
|
||||
if (preload_error) {
|
||||
handle_page({
|
||||
pattern: null,
|
||||
parts: [
|
||||
{ name: null, component: error_route }
|
||||
]
|
||||
}, req, res, preload_error.statusCode, preload_error.message);
|
||||
|
||||
handle_error(req, res, preload_error.statusCode, preload_error.message);
|
||||
return;
|
||||
}
|
||||
|
||||
const serialized = {
|
||||
preloaded: page.parts.map((part, i) => {
|
||||
return part.component.preload ? try_serialize(preloaded[i]) : null;
|
||||
}),
|
||||
preloaded: `[${preloaded.map(data => try_serialize(data)).join(',')}]`,
|
||||
store: store && try_serialize(store.get())
|
||||
};
|
||||
|
||||
const segments = req.path.split('/').filter(Boolean);
|
||||
|
||||
const data = Object.assign({}, props, { params: req.params }, {
|
||||
const props: Props = {
|
||||
path: req.path,
|
||||
query: req.query,
|
||||
params: {},
|
||||
child: null
|
||||
};
|
||||
|
||||
if (error) {
|
||||
props.error = error instanceof Error ? error : { message: error };
|
||||
props.status = status;
|
||||
}
|
||||
|
||||
const data = Object.assign({}, props, preloaded[0], {
|
||||
params: {},
|
||||
child: {}
|
||||
});
|
||||
|
||||
let level = data.child;
|
||||
for (let i = 0; i < page.parts.length; i += 1) {
|
||||
const part = page.parts[i];
|
||||
@@ -383,16 +423,15 @@ function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store
|
||||
segment: segments[i],
|
||||
component: part.component,
|
||||
props: Object.assign({}, props, {
|
||||
params: get_params(match),
|
||||
query: req.query
|
||||
}, preloaded[i])
|
||||
params: get_params(match)
|
||||
}, preloaded[i + 1])
|
||||
});
|
||||
|
||||
level.props.child = {};
|
||||
level.props.child = <Props["child"]>{};
|
||||
level = level.props.child;
|
||||
}
|
||||
|
||||
const { html, head, css } = routes.root.render(data, {
|
||||
const { html, head, css } = manifest.root.render(data, {
|
||||
store
|
||||
});
|
||||
|
||||
@@ -403,8 +442,9 @@ function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store
|
||||
.join('');
|
||||
|
||||
let inline_script = `__SAPPER__={${[
|
||||
error && `error:1`,
|
||||
`baseUrl: "${req.baseUrl}"`,
|
||||
serialized.preloaded && `preloaded: [${serialized.preloaded}]`,
|
||||
serialized.preloaded && `preloaded: ${serialized.preloaded}`,
|
||||
serialized.store && `store: ${serialized.store}`
|
||||
].filter(Boolean).join(',')}};`;
|
||||
|
||||
@@ -435,8 +475,13 @@ function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store
|
||||
});
|
||||
}
|
||||
}).catch(err => {
|
||||
res.statusCode = 500;
|
||||
res.end(err.message);
|
||||
if (error) {
|
||||
// we encountered an error while rendering the error page — oops
|
||||
res.statusCode = 500;
|
||||
res.end(`<pre>${escape_html(err.message)}</pre>`);
|
||||
} else {
|
||||
handle_error(req, res, 500, err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -450,12 +495,7 @@ function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store
|
||||
}
|
||||
}
|
||||
|
||||
handle_page({
|
||||
pattern: null,
|
||||
parts: [
|
||||
{ name: null, component: error_route }
|
||||
]
|
||||
}, req, res, 404, 'Not found');
|
||||
handle_error(req, res, 404, 'Not found');
|
||||
};
|
||||
}
|
||||
|
||||
@@ -486,3 +526,15 @@ function try_serialize(data: any) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function escape_html(html: string) {
|
||||
const chars: Record<string, string> = {
|
||||
'"' : 'quot',
|
||||
"'": '#39',
|
||||
'&': 'amp',
|
||||
'<' : 'lt',
|
||||
'>' : 'gt'
|
||||
};
|
||||
|
||||
return html.replace(/["'&<>]/g, c => `&${chars[c]};`);
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import { detach, findAnchor, scroll_state, which } from './utils';
|
||||
import { Component, ComponentConstructor, Params, Query, Redirect, Routes, RouteData, ScrollPosition, Store, Target } from './interfaces';
|
||||
import { Component, ComponentConstructor, Params, Query, Redirect, Manifest, RouteData, ScrollPosition, Store, Target } from './interfaces';
|
||||
|
||||
const initial_data = typeof window !== 'undefined' && window.__SAPPER__;
|
||||
|
||||
export let root: Component;
|
||||
let target: Node;
|
||||
let store: Store;
|
||||
let routes: Routes;
|
||||
let manifest: Manifest;
|
||||
let segments: string[] = [];
|
||||
|
||||
type RootProps = {
|
||||
@@ -56,10 +56,10 @@ function select_route(url: URL): Target {
|
||||
const path = url.pathname.slice(initial_data.baseUrl.length);
|
||||
|
||||
// avoid accidental clashes between server routes and pages
|
||||
if (routes.ignore.some(pattern => pattern.test(path))) return;
|
||||
if (manifest.ignore.some(pattern => pattern.test(path))) return;
|
||||
|
||||
for (let i = 0; i < routes.pages.length; i += 1) {
|
||||
const page = routes.pages[i];
|
||||
for (let i = 0; i < manifest.pages.length; i += 1) {
|
||||
const page = manifest.pages[i];
|
||||
|
||||
const match = page.pattern.exec(path);
|
||||
if (match) {
|
||||
@@ -106,7 +106,9 @@ function render(data: any, changed_from: number, scroll: ScrollPosition, token:
|
||||
detach(end);
|
||||
}
|
||||
|
||||
root = new routes.root({
|
||||
Object.assign(data, root_data);
|
||||
|
||||
root = new manifest.root({
|
||||
target,
|
||||
data,
|
||||
store,
|
||||
@@ -126,6 +128,9 @@ function changed(a: Record<string, string | true>, b: Record<string, string | tr
|
||||
return JSON.stringify(a) !== JSON.stringify(b);
|
||||
}
|
||||
|
||||
let root_preload: Promise<any>;
|
||||
let root_data: any;
|
||||
|
||||
function prepare_page(target: Target): Promise<{
|
||||
redirect?: Redirect;
|
||||
data?: any;
|
||||
@@ -162,6 +167,16 @@ function prepare_page(target: Target): Promise<{
|
||||
}
|
||||
};
|
||||
|
||||
if (!root_preload) {
|
||||
root_preload = manifest.root.preload
|
||||
? initial_data.preloaded[0] || manifest.root.preload.call(preload_context, {
|
||||
path,
|
||||
query,
|
||||
params: {}
|
||||
})
|
||||
: {};
|
||||
}
|
||||
|
||||
return Promise.all(page.parts.map(async (part, i) => {
|
||||
if (i < changed_from) return null;
|
||||
|
||||
@@ -172,15 +187,17 @@ function prepare_page(target: Target): Promise<{
|
||||
params: part.params ? part.params(target.match) : {}
|
||||
};
|
||||
|
||||
const preloaded = ready || !initial_data.preloaded[i]
|
||||
const preloaded = ready || !initial_data.preloaded[i + 1]
|
||||
? Component.preload ? await Component.preload.call(preload_context, req) : {}
|
||||
: initial_data.preloaded[i];
|
||||
: initial_data.preloaded[i + 1];
|
||||
|
||||
return { Component, preloaded };
|
||||
})).catch(err => {
|
||||
error = { statusCode: 500, message: err };
|
||||
return [];
|
||||
}).then(results => {
|
||||
}).then(async results => {
|
||||
if (!root_data) root_data = await root_preload;
|
||||
|
||||
if (redirect) {
|
||||
return { redirect };
|
||||
}
|
||||
@@ -203,7 +220,7 @@ function prepare_page(target: Target): Promise<{
|
||||
data: Object.assign({}, props, {
|
||||
preloading: false,
|
||||
child: {
|
||||
component: routes.error,
|
||||
component: manifest.error,
|
||||
props
|
||||
}
|
||||
})
|
||||
@@ -369,13 +386,23 @@ function trigger_prefetch(event: MouseEvent | TouchEvent) {
|
||||
let inited: boolean;
|
||||
let ready = false;
|
||||
|
||||
export function init(opts: { App: ComponentConstructor, target: Node, routes: Routes, store?: (data: any) => Store }) {
|
||||
export function init(opts: {
|
||||
App: ComponentConstructor,
|
||||
target: Node,
|
||||
manifest: Manifest,
|
||||
store?: (data: any) => Store,
|
||||
routes?: any // legacy
|
||||
}) {
|
||||
if (opts instanceof HTMLElement) {
|
||||
throw new Error(`The signature of init(...) has changed — see https://sapper.svelte.technology/guide#0-11-to-0-12 for more information`);
|
||||
}
|
||||
|
||||
if (opts.routes) {
|
||||
throw new Error(`As of Sapper 0.15, opts.routes should be opts.manifest`);
|
||||
}
|
||||
|
||||
target = opts.target;
|
||||
routes = opts.routes;
|
||||
manifest = opts.manifest;
|
||||
|
||||
if (opts && opts.store) {
|
||||
store = opts.store(initial_data.store);
|
||||
@@ -402,8 +429,10 @@ export function init(opts: { App: ComponentConstructor, target: Node, routes: Ro
|
||||
|
||||
history.replaceState({ id: uid }, '', href);
|
||||
|
||||
const target = select_route(new URL(window.location.href));
|
||||
if (target) return navigate(target, uid);
|
||||
if (!initial_data.error) {
|
||||
const target = select_route(new URL(window.location.href));
|
||||
if (target) return navigate(target, uid);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -423,9 +452,9 @@ export function goto(href: string, opts = { replaceState: false }) {
|
||||
}
|
||||
|
||||
export function prefetchRoutes(pathnames: string[]) {
|
||||
if (!routes) throw new Error(`You must call init() first`);
|
||||
if (!manifest) throw new Error(`You must call init() first`);
|
||||
|
||||
return routes.pages
|
||||
return manifest.pages
|
||||
.filter(route => {
|
||||
if (!pathnames) return true;
|
||||
return pathnames.some(pathname => route.pattern.test(pathname));
|
||||
|
||||
@@ -23,7 +23,7 @@ export type Page = {
|
||||
}>;
|
||||
};
|
||||
|
||||
export type Routes = {
|
||||
export type Manifest = {
|
||||
ignore: RegExp[];
|
||||
root: ComponentConstructor;
|
||||
error: () => Promise<{ default: ComponentConstructor }>;
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { init, prefetchRoutes } from '../../../runtime.js';
|
||||
import { Store } from 'svelte/store.js';
|
||||
import { routes } from './manifest/client.js';
|
||||
import { manifest } from './manifest/client.js';
|
||||
|
||||
window.init = () => {
|
||||
return init({
|
||||
target: document.querySelector('#sapper'),
|
||||
routes,
|
||||
manifest,
|
||||
store: data => new Store(data)
|
||||
});
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@ import express from 'express';
|
||||
import serve from 'serve-static';
|
||||
import sapper from '../../../dist/middleware.ts.js';
|
||||
import { Store } from 'svelte/store.js';
|
||||
import { routes } from './manifest/server.js';
|
||||
import { manifest } from './manifest/server.js';
|
||||
|
||||
let pending;
|
||||
let ended;
|
||||
@@ -86,7 +86,7 @@ const middlewares = [
|
||||
},
|
||||
|
||||
sapper({
|
||||
routes,
|
||||
manifest,
|
||||
store: () => {
|
||||
return new Store({
|
||||
title: 'Stored title'
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
<svelte:head>
|
||||
<title>Sapper project template</title>
|
||||
</svelte:head>
|
||||
|
||||
<h1>Great success!</h1>
|
||||
|
||||
<a href='.'>home</a>
|
||||
<a href='about'>about</a>
|
||||
<a href='slow-preload'>slow preload</a>
|
||||
<a href='redirect-from'>redirect</a>
|
||||
<a href='blog/nope'>broken link</a>
|
||||
<a href='blog/throw-an-error'>error link</a>
|
||||
<a href='credentials?creds=include'>credentials</a>
|
||||
<a rel=prefetch class='{page === "blog" ? "selected" : ""}' href='blog'>blog</a>
|
||||
|
||||
<div class='hydrate-test'></div>
|
||||
|
||||
<style>
|
||||
h1 {
|
||||
text-align: center;
|
||||
font-size: 2.8em;
|
||||
text-transform: uppercase;
|
||||
font-weight: 700;
|
||||
margin: 0 0 0.5em 0;
|
||||
}
|
||||
</style>
|
||||
15
test/app/routes/_layout.html
Normal file
15
test/app/routes/_layout.html
Normal file
@@ -0,0 +1,15 @@
|
||||
{#if preloading}
|
||||
<progress class='preloading-progress' value=0.5/>
|
||||
{/if}
|
||||
|
||||
<svelte:component this={child.component} {rootPreloadFunctionRan} {...child.props}/>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
preload() {
|
||||
return {
|
||||
rootPreloadFunctionRan: true
|
||||
};
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -1,25 +0,0 @@
|
||||
<svelte:head>
|
||||
<title>Blog</title>
|
||||
</svelte:head>
|
||||
|
||||
<h1>Recent posts</h1>
|
||||
|
||||
<ul>
|
||||
{#each posts as post}
|
||||
<!-- we're using the non-standard `rel=prefetch` attribute to
|
||||
tell Sapper to load the data for the page as soon as
|
||||
the user hovers over the link or taps it, instead of
|
||||
waiting for the 'click' event -->
|
||||
<li><a rel='prefetch' href='blog/{post.slug}'>{post.title}</a></li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
preload({ params, query }) {
|
||||
return fetch(`blog.json`).then(r => r.json()).then(posts => {
|
||||
return { posts };
|
||||
});
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -1 +1,25 @@
|
||||
<svelte:component this={child.component} {...child.props}/>
|
||||
<svelte:head>
|
||||
<title>Blog</title>
|
||||
</svelte:head>
|
||||
|
||||
<h1>Recent posts</h1>
|
||||
|
||||
<ul>
|
||||
{#each posts as post}
|
||||
<!-- we're using the non-standard `rel=prefetch` attribute to
|
||||
tell Sapper to load the data for the page as soon as
|
||||
the user hovers over the link or taps it, instead of
|
||||
waiting for the 'click' event -->
|
||||
<li><a rel='prefetch' href='blog/{post.slug}'>{post.title}</a></li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
preload({ params, query }) {
|
||||
return fetch(`blog.json`).then(r => r.json()).then(posts => {
|
||||
return { posts };
|
||||
});
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -1,6 +1,26 @@
|
||||
{#if preloading}
|
||||
<progress class='preloading-progress' value=0.5/>
|
||||
{/if}
|
||||
<svelte:head>
|
||||
<title>Sapper project template</title>
|
||||
</svelte:head>
|
||||
|
||||
<svelte:component this={child.component} {...child.props}/>
|
||||
<h1>Great success!</h1>
|
||||
|
||||
<a href='.'>home</a>
|
||||
<a href='about'>about</a>
|
||||
<a href='slow-preload'>slow preload</a>
|
||||
<a href='redirect-from'>redirect</a>
|
||||
<a href='blog/nope'>broken link</a>
|
||||
<a href='blog/throw-an-error'>error link</a>
|
||||
<a href='credentials?creds=include'>credentials</a>
|
||||
<a rel=prefetch class='{page === "blog" ? "selected" : ""}' href='blog'>blog</a>
|
||||
|
||||
<div class='hydrate-test'></div>
|
||||
|
||||
<style>
|
||||
h1 {
|
||||
text-align: center;
|
||||
font-size: 2.8em;
|
||||
text-transform: uppercase;
|
||||
font-weight: 700;
|
||||
margin: 0 0 0.5em 0;
|
||||
}
|
||||
</style>
|
||||
1
test/app/routes/preload-root.html
Normal file
1
test/app/routes/preload-root.html
Normal file
@@ -0,0 +1 @@
|
||||
<h1>root preload function ran: {rootPreloadFunctionRan}</h1>
|
||||
@@ -1,9 +0,0 @@
|
||||
<p>URL is {url}</p>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
preload({ url }) {
|
||||
if (url) return { url };
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -100,12 +100,11 @@ describe('sapper', function() {
|
||||
// Client scripts that should show up in the extraction directory.
|
||||
const expectedClientRegexes = [
|
||||
/client\/[^/]+\/main(\.\d+)?\.js/,
|
||||
/client\/[^/]+\/page_index(\.\d+)?\.js/,
|
||||
/client\/[^/]+\/page_about(\.\d+)?\.js/,
|
||||
/client\/[^/]+\/page_blog_\$slug(\.\d+)?\.js/,
|
||||
/client\/[^/]+\/page_blog(\.\d+)?\.js/,
|
||||
/client\/[^/]+\/page_show\$45url(\.\d+)?\.js/,
|
||||
/client\/[^/]+\/page_slow\$45preload(\.\d+)?\.js/,
|
||||
/client\/[^/]+\/index(\.\d+)?\.js/,
|
||||
/client\/[^/]+\/about(\.\d+)?\.js/,
|
||||
/client\/[^/]+\/blog_\$slug(\.\d+)?\.js/,
|
||||
/client\/[^/]+\/blog(\.\d+)?\.js/,
|
||||
/client\/[^/]+\/slow\$45preload(\.\d+)?\.js/,
|
||||
];
|
||||
const allPages = walkSync(dest);
|
||||
|
||||
@@ -370,16 +369,6 @@ function run({ mode, basepath = '' }) {
|
||||
});
|
||||
});
|
||||
|
||||
it('passes entire request object to preload', () => {
|
||||
return nightmare
|
||||
.goto(`${base}/show-url`)
|
||||
.init()
|
||||
.evaluate(() => document.querySelector('p').innerHTML)
|
||||
.then(html => {
|
||||
assert.equal(html, `URL is /show-url`);
|
||||
});
|
||||
});
|
||||
|
||||
it('calls a delete handler', () => {
|
||||
return nightmare
|
||||
.goto(`${base}/delete-test`)
|
||||
@@ -667,6 +656,14 @@ function run({ mode, basepath = '' }) {
|
||||
assert.equal(title, 'it works');
|
||||
});
|
||||
});
|
||||
|
||||
it('runs preload in root component', () => {
|
||||
return nightmare.goto(`${base}/preload-root`)
|
||||
.page.title()
|
||||
.then(title => {
|
||||
assert.equal(title, 'root preload function ran: true');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('headers', () => {
|
||||
|
||||
@@ -2,52 +2,58 @@ const path = require('path');
|
||||
const assert = require('assert');
|
||||
const { create_routes } = require('../../../dist/core.ts.js');
|
||||
|
||||
|
||||
const _default_layout = {
|
||||
default: true,
|
||||
name: '_default_layout',
|
||||
file: null
|
||||
};
|
||||
|
||||
describe('create_routes', () => {
|
||||
it('creates routes', () => {
|
||||
const { components, pages, server_routes } = create_routes(path.join(__dirname, 'samples/basic'));
|
||||
|
||||
const page_index = { name: 'page_index', file: '_default.html' };
|
||||
const page_about = { name: 'page_about', file: 'about.html' };
|
||||
const page_blog = { name: 'page_blog', file: 'blog/index.html' };
|
||||
const page_blog_index = { name: 'page_blog_index', file: 'blog/_default.html' };
|
||||
const page_blog_$slug = { name: 'page_blog_$slug', file: 'blog/[slug].html' };
|
||||
const index = { name: 'index', file: 'index.html' };
|
||||
const about = { name: 'about', file: 'about.html' };
|
||||
const blog = { name: 'blog', file: 'blog/index.html' };
|
||||
const blog_$slug = { name: 'blog_$slug', file: 'blog/[slug].html' };
|
||||
|
||||
assert.deepEqual(components, [
|
||||
page_index,
|
||||
page_about,
|
||||
page_blog,
|
||||
page_blog_index,
|
||||
page_blog_$slug
|
||||
index,
|
||||
about,
|
||||
_default_layout,
|
||||
blog,
|
||||
blog_$slug
|
||||
]);
|
||||
|
||||
assert.deepEqual(pages, [
|
||||
{
|
||||
pattern: /^\/?$/,
|
||||
parts: [
|
||||
{ component: page_index, params: [] }
|
||||
{ component: index, params: [] }
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
pattern: /^\/about\/?$/,
|
||||
parts: [
|
||||
{ component: page_about, params: [] }
|
||||
{ component: about, params: [] }
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
pattern: /^\/blog\/?$/,
|
||||
parts: [
|
||||
{ component: page_blog, params: [] },
|
||||
{ component: page_blog_index, params: [] }
|
||||
{ component: _default_layout, params: [] },
|
||||
{ component: blog, params: [] }
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
pattern: /^\/blog\/([^\/]+?)\/?$/,
|
||||
parts: [
|
||||
{ component: page_blog, params: [] },
|
||||
{ component: page_blog_$slug, params: ['slug'] }
|
||||
{ component: _default_layout, params: [] },
|
||||
{ component: blog_$slug, params: ['slug'] }
|
||||
]
|
||||
}
|
||||
]);
|
||||
@@ -74,9 +80,9 @@ describe('create_routes', () => {
|
||||
|
||||
// had to remove ? and " because windows
|
||||
|
||||
// const quote = { name: 'page_$34', file: '".html' };
|
||||
const hash = { name: 'page_$35', file: '#.html' };
|
||||
// const question_mark = { name: 'page_$63', file: '?.html' };
|
||||
// const quote = { name: '$34', file: '".html' };
|
||||
const hash = { name: '$35', file: '#.html' };
|
||||
// const question_mark = { name: '$63', file: '?.html' };
|
||||
|
||||
assert.deepEqual(components, [
|
||||
// quote,
|
||||
@@ -105,14 +111,14 @@ describe('create_routes', () => {
|
||||
const { pages } = create_routes(path.join(__dirname, 'samples/sorting'));
|
||||
|
||||
assert.deepEqual(pages.map(p => p.parts.map(part => part.component.file)), [
|
||||
['_default.html'],
|
||||
['index.html'],
|
||||
['about.html'],
|
||||
['post/index.html', 'post/_default.html'],
|
||||
['post/index.html', 'post/bar.html'],
|
||||
['post/index.html', 'post/foo.html'],
|
||||
['post/index.html', 'post/f[xx].html'],
|
||||
['post/index.html', 'post/[id([0-9-a-z]{3,})].html'],
|
||||
['post/index.html', 'post/[id].html'],
|
||||
[_default_layout.file, 'post/index.html'],
|
||||
[_default_layout.file, 'post/bar.html'],
|
||||
[_default_layout.file, 'post/foo.html'],
|
||||
[_default_layout.file, 'post/f[xx].html'],
|
||||
[_default_layout.file, 'post/[id([0-9-a-z]{3,})].html'],
|
||||
[_default_layout.file, 'post/[id].html'],
|
||||
['[wildcard].html']
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
"noEmitOnError": true,
|
||||
"allowJs": true,
|
||||
"lib": ["es5", "es6", "dom"],
|
||||
"importHelpers": true
|
||||
"importHelpers": true,
|
||||
"target": "ES5"
|
||||
},
|
||||
"target": "ES5",
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
|
||||
Reference in New Issue
Block a user