mirror of
https://github.com/kevin-DL/sapper.git
synced 2026-01-17 13:14:54 +00:00
Compare commits
7 Commits
gh-262-no-
...
v0.15.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b28cdff233 | ||
|
|
7f586ff1a3 | ||
|
|
731d4f535c | ||
|
|
f8c731ca21 | ||
|
|
39eb3be01e | ||
|
|
d0bb728e25 | ||
|
|
58de0f9c99 |
12
CHANGELOG.md
12
CHANGELOG.md
@@ -1,5 +1,17 @@
|
|||||||
# sapper changelog
|
# sapper changelog
|
||||||
|
|
||||||
|
## 0.15.2
|
||||||
|
|
||||||
|
* Collapse component chains where no intermediate layout component is specified ([#312](https://github.com/sveltejs/sapper/issues/312))
|
||||||
|
|
||||||
|
## 0.15.1
|
||||||
|
|
||||||
|
* Prevent confusing error when no root layout is specified
|
||||||
|
|
||||||
|
## 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
|
## 0.14.2
|
||||||
|
|
||||||
* Prevent unsafe replacements ([#307](https://github.com/sveltejs/sapper/pull/307))
|
* Prevent unsafe replacements ([#307](https://github.com/sveltejs/sapper/pull/307))
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "sapper",
|
"name": "sapper",
|
||||||
"version": "0.14.2",
|
"version": "0.15.2",
|
||||||
"description": "Military-grade apps, engineered by Svelte",
|
"description": "Military-grade apps, engineered by Svelte",
|
||||||
"main": "dist/middleware.ts.js",
|
"main": "dist/middleware.ts.js",
|
||||||
"bin": {
|
"bin": {
|
||||||
@@ -12,6 +12,7 @@
|
|||||||
"runtime",
|
"runtime",
|
||||||
"webpack",
|
"webpack",
|
||||||
"sapper",
|
"sapper",
|
||||||
|
"components",
|
||||||
"dist"
|
"dist"
|
||||||
],
|
],
|
||||||
"directories": {
|
"directories": {
|
||||||
@@ -67,7 +68,7 @@
|
|||||||
"cy:open": "cypress open",
|
"cy:open": "cypress open",
|
||||||
"test": "mocha --opts mocha.opts",
|
"test": "mocha --opts mocha.opts",
|
||||||
"pretest": "npm run build",
|
"pretest": "npm run build",
|
||||||
"build": "rollup -c",
|
"build": "rm -rf dist && rollup -c",
|
||||||
"dev": "rollup -cw",
|
"dev": "rollup -cw",
|
||||||
"prepublishOnly": "npm test",
|
"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"
|
"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: [
|
plugins: [
|
||||||
typescript({
|
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 client_manifest = generate_client(routes, path_to_routes, dev_port);
|
||||||
const server_manifest = generate_server(routes, path_to_routes);
|
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/client.js`, client_manifest);
|
||||||
write_if_changed(`${locations.app()}/manifest/server.js`, server_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(
|
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,
|
path_to_routes: string,
|
||||||
dev_port?: number
|
dev_port?: number
|
||||||
) {
|
) {
|
||||||
@@ -58,15 +62,15 @@ function generate_client(
|
|||||||
|
|
||||||
let code = `
|
let code = `
|
||||||
// This file is generated by Sapper — do not edit it!
|
// This file is generated by Sapper — do not edit it!
|
||||||
import root from '${posixify(`${path_to_routes}/index.html`)}';
|
import root from '${get_file(path_to_routes, routes.root)}';
|
||||||
import error from '${posixify(`${path_to_routes}/_error.html`)}';
|
import error from '${posixify(`${path_to_routes}/_error.html`)}';
|
||||||
|
|
||||||
${routes.components.map(component =>
|
${routes.components.map(component =>
|
||||||
`const ${component.name} = () =>
|
`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')}
|
.join('\n')}
|
||||||
|
|
||||||
export const routes = {
|
export const manifest = {
|
||||||
ignore: [${server_routes_to_ignore.map(route => route.pattern).join(', ')}],
|
ignore: [${server_routes_to_ignore.map(route => route.pattern).join(', ')}],
|
||||||
|
|
||||||
pages: [
|
pages: [
|
||||||
@@ -75,6 +79,8 @@ function generate_client(
|
|||||||
pattern: ${page.pattern},
|
pattern: ${page.pattern},
|
||||||
parts: [
|
parts: [
|
||||||
${page.parts.map(part => {
|
${page.parts.map(part => {
|
||||||
|
if (part === null) return 'null';
|
||||||
|
|
||||||
if (part.params.length > 0) {
|
if (part.params.length > 0) {
|
||||||
const props = part.params.map((param, i) => `${param}: match[${i + 1}]`);
|
const props = part.params.map((param, i) => `${param}: match[${i + 1}]`);
|
||||||
return `{ component: ${part.component.name}, params: match => ({ ${props.join(', ')} }) }`;
|
return `{ component: ${part.component.name}, params: match => ({ ${props.join(', ')} }) }`;
|
||||||
@@ -89,7 +95,10 @@ function generate_client(
|
|||||||
root,
|
root,
|
||||||
|
|
||||||
error
|
error
|
||||||
};`.replace(/^\t\t/gm, '').trim();
|
};
|
||||||
|
|
||||||
|
// this is included for legacy reasons
|
||||||
|
export const routes = {};`.replace(/^\t\t/gm, '').trim();
|
||||||
|
|
||||||
if (dev()) {
|
if (dev()) {
|
||||||
const sapper_dev_client = posixify(
|
const sapper_dev_client = posixify(
|
||||||
@@ -109,15 +118,15 @@ function generate_client(
|
|||||||
}
|
}
|
||||||
|
|
||||||
function generate_server(
|
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
|
path_to_routes: string
|
||||||
) {
|
) {
|
||||||
const imports = [].concat(
|
const imports = [].concat(
|
||||||
routes.server_routes.map(route =>
|
routes.server_routes.map(route =>
|
||||||
`import * as ${route.name} from '${posixify(`${path_to_routes}/${route.file}`)}';`),
|
`import * as ${route.name} from '${posixify(`${path_to_routes}/${route.file}`)}';`),
|
||||||
routes.components.map(component =>
|
routes.components.map(component =>
|
||||||
`import ${component.name} from '${posixify(`${path_to_routes}/${component.file}`)}';`),
|
`import ${component.name} from '${get_file(path_to_routes, component)}';`),
|
||||||
`import root from '${posixify(`${path_to_routes}/index.html`)}';`,
|
`import root from '${get_file(path_to_routes, routes.root)}';`,
|
||||||
`import error from '${posixify(`${path_to_routes}/_error.html`)}';`
|
`import error from '${posixify(`${path_to_routes}/_error.html`)}';`
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -125,7 +134,7 @@ function generate_server(
|
|||||||
// This file is generated by Sapper — do not edit it!
|
// This file is generated by Sapper — do not edit it!
|
||||||
${imports.join('\n')}
|
${imports.join('\n')}
|
||||||
|
|
||||||
export const routes = {
|
export const manifest = {
|
||||||
server_routes: [
|
server_routes: [
|
||||||
${routes.server_routes.map(route => `{
|
${routes.server_routes.map(route => `{
|
||||||
// ${route.file}
|
// ${route.file}
|
||||||
@@ -143,6 +152,8 @@ function generate_server(
|
|||||||
pattern: ${page.pattern},
|
pattern: ${page.pattern},
|
||||||
parts: [
|
parts: [
|
||||||
${page.parts.map(part => {
|
${page.parts.map(part => {
|
||||||
|
if (part === null) return 'null';
|
||||||
|
|
||||||
const props = [
|
const props = [
|
||||||
`name: "${part.component.name}"`,
|
`name: "${part.component.name}"`,
|
||||||
`component: ${part.component.name}`
|
`component: ${part.component.name}`
|
||||||
@@ -162,7 +173,18 @@ function generate_server(
|
|||||||
root,
|
root,
|
||||||
|
|
||||||
error
|
error
|
||||||
};`.replace(/^\t\t/gm, '').trim();
|
};
|
||||||
|
|
||||||
|
// this is included for legacy reasons
|
||||||
|
export const routes = {};`.replace(/^\t\t/gm, '').trim();
|
||||||
|
|
||||||
return code;
|
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 { Page, PageComponent, ServerRoute } from '../interfaces';
|
||||||
import { posixify } from './utils';
|
import { posixify } from './utils';
|
||||||
|
|
||||||
|
const default_layout_file = posixify(path.resolve(
|
||||||
|
__dirname,
|
||||||
|
'../components/default-layout.html'
|
||||||
|
));
|
||||||
|
|
||||||
export default function create_routes(cwd = locations.routes()) {
|
export default function create_routes(cwd = locations.routes()) {
|
||||||
const components: PageComponent[] = [];
|
const components: PageComponent[] = [];
|
||||||
const pages: Page[] = [];
|
const pages: Page[] = [];
|
||||||
const server_routes: ServerRoute[] = [];
|
const server_routes: ServerRoute[] = [];
|
||||||
|
|
||||||
|
const default_layout: PageComponent = {
|
||||||
|
default: true,
|
||||||
|
name: '_default_layout',
|
||||||
|
file: null
|
||||||
|
};
|
||||||
|
|
||||||
function walk(
|
function walk(
|
||||||
dir: string,
|
dir: string,
|
||||||
parent_segments: Part[][],
|
parent_segments: Part[][],
|
||||||
@@ -54,9 +65,7 @@ export default function create_routes(cwd = locations.routes()) {
|
|||||||
.sort(comparator);
|
.sort(comparator);
|
||||||
|
|
||||||
items.forEach(item => {
|
items.forEach(item => {
|
||||||
if (item.basename[0] === '_') {
|
if (item.basename[0] === '_') return;
|
||||||
if (item.basename !== (item.is_dir ? '_default' : '_default.html')) return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (item.basename[0] === '.') {
|
if (item.basename[0] === '.') {
|
||||||
if (item.file !== '.well-known') return;
|
if (item.file !== '.well-known') return;
|
||||||
@@ -91,58 +100,28 @@ export default function create_routes(cwd = locations.routes()) {
|
|||||||
params.push(...item.parts.filter(p => p.dynamic).map(p => p.content));
|
params.push(...item.parts.filter(p => p.dynamic).map(p => p.content));
|
||||||
|
|
||||||
if (item.is_dir) {
|
if (item.is_dir) {
|
||||||
const index = path.join(dir, item.basename, 'index.html');
|
const index = path.join(dir, item.basename, '_layout.html');
|
||||||
const component = fs.existsSync(index)
|
|
||||||
? {
|
|
||||||
name: `page_${get_slug(item.file)}`,
|
|
||||||
file: `${item.file}/index.html`
|
|
||||||
}
|
|
||||||
: null;
|
|
||||||
|
|
||||||
if (component) {
|
const component = fs.existsSync(index) && {
|
||||||
components.push(component);
|
name: `${get_slug(item.file)}__layout`,
|
||||||
}
|
file: `${item.file}/_layout.html`
|
||||||
|
};
|
||||||
|
|
||||||
|
if (component) components.push(component);
|
||||||
|
|
||||||
walk(
|
walk(
|
||||||
path.join(dir, item.basename),
|
path.join(dir, item.basename),
|
||||||
segments,
|
segments,
|
||||||
params,
|
params,
|
||||||
stack.concat({
|
component
|
||||||
component: component || {
|
? stack.concat({ component, params })
|
||||||
missing: true,
|
: stack.concat(null)
|
||||||
name: null,
|
|
||||||
file: path.join(item.file, 'index.html')
|
|
||||||
},
|
|
||||||
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) {
|
else if (item.is_page) {
|
||||||
const component = {
|
const component = {
|
||||||
name: `page_${get_slug(item.file)}`,
|
name: get_slug(item.file),
|
||||||
file: item.file
|
file: item.file
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -152,7 +131,7 @@ export default function create_routes(cwd = locations.routes()) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
components.push(component);
|
components.push(component);
|
||||||
if (item.basename === '_default.html') {
|
if (item.basename === 'index.html') {
|
||||||
pages.push({
|
pages.push({
|
||||||
pattern: get_pattern(parent_segments),
|
pattern: get_pattern(parent_segments),
|
||||||
parts
|
parts
|
||||||
@@ -176,21 +155,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, [], [], []);
|
walk(cwd, [], [], []);
|
||||||
|
|
||||||
|
// check for clashes
|
||||||
const seen_pages: Map<string, Page> = new Map();
|
const seen_pages: Map<string, Page> = new Map();
|
||||||
pages.forEach(page => {
|
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();
|
const pattern = page.pattern.toString();
|
||||||
if (seen_pages.has(pattern)) {
|
if (seen_pages.has(pattern)) {
|
||||||
const file = page.parts.pop().component.file;
|
const file = page.parts.pop().component.file;
|
||||||
@@ -215,6 +192,7 @@ export default function create_routes(cwd = locations.routes()) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
root,
|
||||||
components,
|
components,
|
||||||
pages,
|
pages,
|
||||||
server_routes
|
server_routes
|
||||||
@@ -228,9 +206,11 @@ type Part = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
function comparator(
|
function comparator(
|
||||||
a: { 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_dir: 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);
|
const max = Math.max(a.parts.length, b.parts.length);
|
||||||
|
|
||||||
for (let i = 0; i < max; i += 1) {
|
for (let i = 0; i < max; i += 1) {
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ export type Store = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type PageComponent = {
|
export type PageComponent = {
|
||||||
missing?: boolean;
|
default?: boolean;
|
||||||
name: string;
|
name: string;
|
||||||
file: string;
|
file: string;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ type Page = {
|
|||||||
}>
|
}>
|
||||||
};
|
};
|
||||||
|
|
||||||
type RouteObject = {
|
type Manifest = {
|
||||||
server_routes: ServerRoute[];
|
server_routes: ServerRoute[];
|
||||||
pages: Page[];
|
pages: Page[];
|
||||||
root: Component;
|
root: Component;
|
||||||
@@ -39,6 +39,20 @@ type Store = {
|
|||||||
get: () => any
|
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 {
|
interface Req extends ClientRequest {
|
||||||
url: string;
|
url: string;
|
||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
@@ -59,12 +73,19 @@ interface Component {
|
|||||||
preload: (data: any) => any | Promise<any>
|
preload: (data: any) => any | Promise<any>
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function middleware({ routes, store }: {
|
export default function middleware(opts: {
|
||||||
routes: RouteObject,
|
manifest: Manifest,
|
||||||
store: (req: Req) => Store
|
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 output = locations.dest();
|
||||||
|
|
||||||
|
const { manifest, store } = opts;
|
||||||
|
|
||||||
let emitted_basepath = false;
|
let emitted_basepath = false;
|
||||||
|
|
||||||
const middleware = compose_handlers([
|
const middleware = compose_handlers([
|
||||||
@@ -117,8 +138,8 @@ export default function middleware({ routes, store }: {
|
|||||||
cache_control: 'max-age=31536000'
|
cache_control: 'max-age=31536000'
|
||||||
}),
|
}),
|
||||||
|
|
||||||
get_server_route_handler(routes.server_routes),
|
get_server_route_handler(manifest.server_routes),
|
||||||
get_page_handler(routes, store)
|
get_page_handler(manifest, store)
|
||||||
].filter(Boolean));
|
].filter(Boolean));
|
||||||
|
|
||||||
return middleware;
|
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 output = locations.dest();
|
||||||
|
|
||||||
const get_chunks = dev()
|
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')
|
? () => fs.readFileSync(`${locations.app()}/template.html`, 'utf-8')
|
||||||
: (str => () => str)(fs.readFileSync(`${locations.dest()}/template.html`, 'utf-8'));
|
: (str => () => str)(fs.readFileSync(`${locations.dest()}/template.html`, 'utf-8'));
|
||||||
|
|
||||||
const { server_routes, pages } = routes;
|
const { server_routes, pages } = manifest;
|
||||||
const error_route = routes.error;
|
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) {
|
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 get_params = page.parts[page.parts.length - 1].params || (() => ({}));
|
||||||
const match = error ? null : page.pattern.exec(req.path);
|
const match = error ? null : page.pattern.exec(req.path);
|
||||||
|
|
||||||
req.params = error
|
|
||||||
? {}
|
|
||||||
: get_params(match);
|
|
||||||
|
|
||||||
const chunks: Record<string, string | string[]> = get_chunks();
|
const chunks: Record<string, string | string[]> = get_chunks();
|
||||||
|
|
||||||
res.setHeader('Content-Type', 'text/html');
|
res.setHeader('Content-Type', 'text/html');
|
||||||
@@ -266,6 +292,8 @@ function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store
|
|||||||
let preloaded_chunks = Array.isArray(chunks.main) ? chunks.main : [chunks.main];
|
let preloaded_chunks = Array.isArray(chunks.main) ? chunks.main : [chunks.main];
|
||||||
if (!error) {
|
if (!error) {
|
||||||
page.parts.forEach(part => {
|
page.parts.forEach(part => {
|
||||||
|
if (!part) return;
|
||||||
|
|
||||||
// using concat because it could be a string or an array. thanks webpack!
|
// using concat because it could be a string or an array. thanks webpack!
|
||||||
preloaded_chunks = preloaded_chunks.concat(chunks[part.name]);
|
preloaded_chunks = preloaded_chunks.concat(chunks[part.name]);
|
||||||
});
|
});
|
||||||
@@ -279,67 +307,77 @@ function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store
|
|||||||
res.setHeader('Link', link);
|
res.setHeader('Link', link);
|
||||||
|
|
||||||
const store = store_getter ? store_getter(req) : null;
|
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 redirect: { statusCode: number, location: string };
|
||||||
let preload_error: { statusCode: number, message: Error | 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 => {
|
||||||
|
if (!part) return null;
|
||||||
|
|
||||||
return part.component.preload
|
return part.component.preload
|
||||||
? part.component.preload.call({
|
? part.component.preload.call(preload_context, {
|
||||||
redirect: (statusCode: number, location: string) => {
|
path: req.path,
|
||||||
if (redirect && (redirect.statusCode !== statusCode || redirect.location !== location)) {
|
query: req.query,
|
||||||
throw new Error(`Conflicting redirects`);
|
params: part.params ? part.params(match) : {}
|
||||||
}
|
})
|
||||||
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)
|
|
||||||
: {};
|
: {};
|
||||||
})).catch(err => {
|
}))).catch(err => {
|
||||||
preload_error = { statusCode: 500, message: err };
|
preload_error = { statusCode: 500, message: err };
|
||||||
return []; // appease TypeScript
|
return []; // appease TypeScript
|
||||||
}).then(preloaded => {
|
}).then(preloaded => {
|
||||||
@@ -352,47 +390,57 @@ function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (preload_error) {
|
if (preload_error) {
|
||||||
handle_page({
|
handle_error(req, res, preload_error.statusCode, preload_error.message);
|
||||||
pattern: null,
|
|
||||||
parts: [
|
|
||||||
{ name: null, component: error_route }
|
|
||||||
]
|
|
||||||
}, req, res, preload_error.statusCode, preload_error.message);
|
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const serialized = {
|
const serialized = {
|
||||||
preloaded: page.parts.map((part, i) => {
|
preloaded: `[${preloaded.map(data => try_serialize(data)).join(',')}]`,
|
||||||
return part.component.preload ? try_serialize(preloaded[i]) : null;
|
|
||||||
}),
|
|
||||||
store: store && try_serialize(store.get())
|
store: store && try_serialize(store.get())
|
||||||
};
|
};
|
||||||
|
|
||||||
const segments = req.path.split('/').filter(Boolean);
|
const segments = req.path.split('/').filter(Boolean);
|
||||||
|
|
||||||
const data = Object.assign({}, props, { params: req.params }, {
|
const props: Props = {
|
||||||
child: {}
|
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: {
|
||||||
|
segment: segments[0]
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let level = data.child;
|
let level = data.child;
|
||||||
for (let i = 0; i < page.parts.length; i += 1) {
|
for (let i = 0; i < page.parts.length; i += 1) {
|
||||||
const part = page.parts[i];
|
const part = page.parts[i];
|
||||||
|
if (!part) continue;
|
||||||
|
|
||||||
const get_params = part.params || (() => ({}));
|
const get_params = part.params || (() => ({}));
|
||||||
|
|
||||||
Object.assign(level, {
|
Object.assign(level, {
|
||||||
segment: segments[i],
|
|
||||||
component: part.component,
|
component: part.component,
|
||||||
props: Object.assign({}, props, {
|
props: Object.assign({}, props, {
|
||||||
params: get_params(match),
|
params: get_params(match)
|
||||||
query: req.query
|
}, preloaded[i + 1])
|
||||||
}, preloaded[i])
|
|
||||||
});
|
});
|
||||||
|
|
||||||
level.props.child = {};
|
level.props.child = <Props["child"]>{
|
||||||
|
segment: segments[i + 1]
|
||||||
|
};
|
||||||
level = level.props.child;
|
level = level.props.child;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { html, head, css } = routes.root.render(data, {
|
const { html, head, css } = manifest.root.render(data, {
|
||||||
store
|
store
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -403,8 +451,9 @@ function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store
|
|||||||
.join('');
|
.join('');
|
||||||
|
|
||||||
let inline_script = `__SAPPER__={${[
|
let inline_script = `__SAPPER__={${[
|
||||||
|
error && `error:1`,
|
||||||
`baseUrl: "${req.baseUrl}"`,
|
`baseUrl: "${req.baseUrl}"`,
|
||||||
serialized.preloaded && `preloaded: [${serialized.preloaded}]`,
|
serialized.preloaded && `preloaded: ${serialized.preloaded}`,
|
||||||
serialized.store && `store: ${serialized.store}`
|
serialized.store && `store: ${serialized.store}`
|
||||||
].filter(Boolean).join(',')}};`;
|
].filter(Boolean).join(',')}};`;
|
||||||
|
|
||||||
@@ -435,8 +484,13 @@ function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
res.statusCode = 500;
|
if (error) {
|
||||||
res.end(err.message);
|
// 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 +504,7 @@ function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
handle_page({
|
handle_error(req, res, 404, 'Not found');
|
||||||
pattern: null,
|
|
||||||
parts: [
|
|
||||||
{ name: null, component: error_route }
|
|
||||||
]
|
|
||||||
}, req, res, 404, 'Not found');
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -486,3 +535,15 @@ function try_serialize(data: any) {
|
|||||||
return null;
|
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 { 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__;
|
const initial_data = typeof window !== 'undefined' && window.__SAPPER__;
|
||||||
|
|
||||||
export let root: Component;
|
export let root: Component;
|
||||||
let target: Node;
|
let target: Node;
|
||||||
let store: Store;
|
let store: Store;
|
||||||
let routes: Routes;
|
let manifest: Manifest;
|
||||||
let segments: string[] = [];
|
let segments: string[] = [];
|
||||||
|
|
||||||
type RootProps = {
|
type RootProps = {
|
||||||
@@ -56,10 +56,10 @@ function select_route(url: URL): Target {
|
|||||||
const path = url.pathname.slice(initial_data.baseUrl.length);
|
const path = url.pathname.slice(initial_data.baseUrl.length);
|
||||||
|
|
||||||
// avoid accidental clashes between server routes and pages
|
// 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) {
|
for (let i = 0; i < manifest.pages.length; i += 1) {
|
||||||
const page = routes.pages[i];
|
const page = manifest.pages[i];
|
||||||
|
|
||||||
const match = page.pattern.exec(path);
|
const match = page.pattern.exec(path);
|
||||||
if (match) {
|
if (match) {
|
||||||
@@ -77,14 +77,14 @@ function select_route(url: URL): Target {
|
|||||||
|
|
||||||
let current_token: {};
|
let current_token: {};
|
||||||
|
|
||||||
function render(data: any, changed_from: number, scroll: ScrollPosition, token: {}) {
|
function render(data: any, nullable_depth: number, scroll: ScrollPosition, token: {}) {
|
||||||
if (current_token !== token) return;
|
if (current_token !== token) return;
|
||||||
|
|
||||||
if (root) {
|
if (root) {
|
||||||
// first, clear out highest-level root component
|
// first, clear out highest-level root component
|
||||||
let level = data.child;
|
let level = data.child;
|
||||||
for (let i = 0; i < changed_from; i += 1) {
|
for (let i = 0; i < nullable_depth; i += 1) {
|
||||||
if (i === changed_from) break;
|
if (i === nullable_depth) break;
|
||||||
level = level.props.child;
|
level = level.props.child;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,7 +106,9 @@ function render(data: any, changed_from: number, scroll: ScrollPosition, token:
|
|||||||
detach(end);
|
detach(end);
|
||||||
}
|
}
|
||||||
|
|
||||||
root = new routes.root({
|
Object.assign(data, root_data);
|
||||||
|
|
||||||
|
root = new manifest.root({
|
||||||
target,
|
target,
|
||||||
data,
|
data,
|
||||||
store,
|
store,
|
||||||
@@ -126,10 +128,13 @@ function changed(a: Record<string, string | true>, b: Record<string, string | tr
|
|||||||
return JSON.stringify(a) !== JSON.stringify(b);
|
return JSON.stringify(a) !== JSON.stringify(b);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let root_preload: Promise<any>;
|
||||||
|
let root_data: any;
|
||||||
|
|
||||||
function prepare_page(target: Target): Promise<{
|
function prepare_page(target: Target): Promise<{
|
||||||
redirect?: Redirect;
|
redirect?: Redirect;
|
||||||
data?: any;
|
data?: any;
|
||||||
changed_from?: number;
|
nullable_depth?: number;
|
||||||
}> {
|
}> {
|
||||||
if (root) {
|
if (root) {
|
||||||
root.set({ preloading: true });
|
root.set({ preloading: true });
|
||||||
@@ -162,8 +167,19 @@ 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) => {
|
return Promise.all(page.parts.map(async (part, i) => {
|
||||||
if (i < changed_from) return null;
|
if (i < changed_from) return null;
|
||||||
|
if (!part) return null;
|
||||||
|
|
||||||
const { default: Component } = await part.component();
|
const { default: Component } = await part.component();
|
||||||
const req = {
|
const req = {
|
||||||
@@ -172,15 +188,17 @@ function prepare_page(target: Target): Promise<{
|
|||||||
params: part.params ? part.params(target.match) : {}
|
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) : {}
|
? Component.preload ? await Component.preload.call(preload_context, req) : {}
|
||||||
: initial_data.preloaded[i];
|
: initial_data.preloaded[i + 1];
|
||||||
|
|
||||||
return { Component, preloaded };
|
return { Component, preloaded };
|
||||||
})).catch(err => {
|
})).catch(err => {
|
||||||
error = { statusCode: 500, message: err };
|
error = { statusCode: 500, message: err };
|
||||||
return [];
|
return [];
|
||||||
}).then(results => {
|
}).then(async results => {
|
||||||
|
if (!root_data) root_data = await root_preload;
|
||||||
|
|
||||||
if (redirect) {
|
if (redirect) {
|
||||||
return { redirect };
|
return { redirect };
|
||||||
}
|
}
|
||||||
@@ -203,7 +221,7 @@ function prepare_page(target: Target): Promise<{
|
|||||||
data: Object.assign({}, props, {
|
data: Object.assign({}, props, {
|
||||||
preloading: false,
|
preloading: false,
|
||||||
child: {
|
child: {
|
||||||
component: routes.error,
|
component: manifest.error,
|
||||||
props
|
props
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -214,33 +232,43 @@ function prepare_page(target: Target): Promise<{
|
|||||||
const data = {
|
const data = {
|
||||||
path,
|
path,
|
||||||
preloading: false,
|
preloading: false,
|
||||||
child: Object.assign({}, root_props.child)
|
child: Object.assign({}, root_props.child, {
|
||||||
|
segment: new_segments[0]
|
||||||
|
})
|
||||||
};
|
};
|
||||||
if (changed(query, root_props.query)) data.query = query;
|
if (changed(query, root_props.query)) data.query = query;
|
||||||
if (changed(params, root_props.params)) data.params = params;
|
if (changed(params, root_props.params)) data.params = params;
|
||||||
|
|
||||||
let level = data.child;
|
let level = data.child;
|
||||||
|
let nullable_depth = 0;
|
||||||
|
|
||||||
for (let i = 0; i < page.parts.length; i += 1) {
|
for (let i = 0; i < page.parts.length; i += 1) {
|
||||||
const part = page.parts[i];
|
const part = page.parts[i];
|
||||||
|
if (!part) continue;
|
||||||
|
|
||||||
const get_params = part.params || (() => ({}));
|
const get_params = part.params || (() => ({}));
|
||||||
|
|
||||||
if (i < changed_from) {
|
if (i < changed_from) {
|
||||||
level.props.path = path;
|
level.props.path = path;
|
||||||
level.props.query = query;
|
level.props.query = query;
|
||||||
level.props.child = Object.assign({}, level.props.child);
|
level.props.child = Object.assign({}, level.props.child);
|
||||||
|
|
||||||
|
nullable_depth += 1;
|
||||||
} else {
|
} else {
|
||||||
level.segment = new_segments[i];
|
|
||||||
level.component = results[i].Component;
|
level.component = results[i].Component;
|
||||||
level.props = Object.assign({}, level.props, props, {
|
level.props = Object.assign({}, level.props, props, {
|
||||||
params: get_params(target.match),
|
params: get_params(target.match),
|
||||||
}, results[i].preloaded);
|
}, results[i].preloaded);
|
||||||
level.props.child = {};
|
|
||||||
|
level.props.child = {
|
||||||
|
segment: new_segments[i + 1]
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
level = level.props.child;
|
level = level.props.child;
|
||||||
}
|
}
|
||||||
|
|
||||||
return { data, changed_from };
|
return { data, nullable_depth };
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -265,12 +293,12 @@ async function navigate(target: Target, id: number): Promise<any> {
|
|||||||
prefetching = null;
|
prefetching = null;
|
||||||
|
|
||||||
const token = current_token = {};
|
const token = current_token = {};
|
||||||
const { redirect, data, changed_from } = await loaded;
|
const { redirect, data, nullable_depth } = await loaded;
|
||||||
|
|
||||||
if (redirect) {
|
if (redirect) {
|
||||||
await goto(redirect.location, { replaceState: true });
|
await goto(redirect.location, { replaceState: true });
|
||||||
} else {
|
} else {
|
||||||
render(data, changed_from, scroll_history[id], token);
|
render(data, nullable_depth, scroll_history[id], token);
|
||||||
document.activeElement.blur();
|
document.activeElement.blur();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -336,7 +364,7 @@ function handle_popstate(event: PopStateEvent) {
|
|||||||
|
|
||||||
let prefetching: {
|
let prefetching: {
|
||||||
href: string;
|
href: string;
|
||||||
promise: Promise<{ redirect?: Redirect, data?: any, changed_from?: number }>;
|
promise: Promise<{ redirect?: Redirect, data?: any, nullable_depth?: number }>;
|
||||||
} = null;
|
} = null;
|
||||||
|
|
||||||
export function prefetch(href: string) {
|
export function prefetch(href: string) {
|
||||||
@@ -369,13 +397,23 @@ function trigger_prefetch(event: MouseEvent | TouchEvent) {
|
|||||||
let inited: boolean;
|
let inited: boolean;
|
||||||
let ready = false;
|
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) {
|
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`);
|
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;
|
target = opts.target;
|
||||||
routes = opts.routes;
|
manifest = opts.manifest;
|
||||||
|
|
||||||
if (opts && opts.store) {
|
if (opts && opts.store) {
|
||||||
store = opts.store(initial_data.store);
|
store = opts.store(initial_data.store);
|
||||||
@@ -402,8 +440,10 @@ export function init(opts: { App: ComponentConstructor, target: Node, routes: Ro
|
|||||||
|
|
||||||
history.replaceState({ id: uid }, '', href);
|
history.replaceState({ id: uid }, '', href);
|
||||||
|
|
||||||
const target = select_route(new URL(window.location.href));
|
if (!initial_data.error) {
|
||||||
if (target) return navigate(target, uid);
|
const target = select_route(new URL(window.location.href));
|
||||||
|
if (target) return navigate(target, uid);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -423,9 +463,9 @@ export function goto(href: string, opts = { replaceState: false }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function prefetchRoutes(pathnames: string[]) {
|
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 => {
|
.filter(route => {
|
||||||
if (!pathnames) return true;
|
if (!pathnames) return true;
|
||||||
return pathnames.some(pathname => route.pattern.test(pathname));
|
return pathnames.some(pathname => route.pattern.test(pathname));
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ export type Page = {
|
|||||||
}>;
|
}>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type Routes = {
|
export type Manifest = {
|
||||||
ignore: RegExp[];
|
ignore: RegExp[];
|
||||||
root: ComponentConstructor;
|
root: ComponentConstructor;
|
||||||
error: () => Promise<{ default: ComponentConstructor }>;
|
error: () => Promise<{ default: ComponentConstructor }>;
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { init, prefetchRoutes } from '../../../runtime.js';
|
import { init, prefetchRoutes } from '../../../runtime.js';
|
||||||
import { Store } from 'svelte/store.js';
|
import { Store } from 'svelte/store.js';
|
||||||
import { routes } from './manifest/client.js';
|
import { manifest } from './manifest/client.js';
|
||||||
|
|
||||||
window.init = () => {
|
window.init = () => {
|
||||||
return init({
|
return init({
|
||||||
target: document.querySelector('#sapper'),
|
target: document.querySelector('#sapper'),
|
||||||
routes,
|
manifest,
|
||||||
store: data => new Store(data)
|
store: data => new Store(data)
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import express from 'express';
|
|||||||
import serve from 'serve-static';
|
import serve from 'serve-static';
|
||||||
import sapper from '../../../dist/middleware.ts.js';
|
import sapper from '../../../dist/middleware.ts.js';
|
||||||
import { Store } from 'svelte/store.js';
|
import { Store } from 'svelte/store.js';
|
||||||
import { routes } from './manifest/server.js';
|
import { manifest } from './manifest/server.js';
|
||||||
|
|
||||||
let pending;
|
let pending;
|
||||||
let ended;
|
let ended;
|
||||||
@@ -86,7 +86,7 @@ const middlewares = [
|
|||||||
},
|
},
|
||||||
|
|
||||||
sapper({
|
sapper({
|
||||||
routes,
|
manifest,
|
||||||
store: () => {
|
store: () => {
|
||||||
return new Store({
|
return new Store({
|
||||||
title: 'Stored title'
|
title: 'Stored title'
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
<span>x: {segment} {count}</span>
|
|
||||||
<svelte:component this={child.component} {...child.props}/>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
import counts from './_counts.js';
|
|
||||||
|
|
||||||
export default {
|
|
||||||
preload() {
|
|
||||||
return {
|
|
||||||
count: counts.x += 1
|
|
||||||
};
|
|
||||||
},
|
|
||||||
|
|
||||||
oncreate() {
|
|
||||||
this.set({
|
|
||||||
segment: this.get().params.x
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
</script>
|
|
||||||
@@ -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}
|
<svelte:head>
|
||||||
<progress class='preloading-progress' value=0.5/>
|
<title>Sapper project template</title>
|
||||||
{/if}
|
</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/index.html
Normal file
1
test/app/routes/preload-root/index.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.
|
// Client scripts that should show up in the extraction directory.
|
||||||
const expectedClientRegexes = [
|
const expectedClientRegexes = [
|
||||||
/client\/[^/]+\/main(\.\d+)?\.js/,
|
/client\/[^/]+\/main(\.\d+)?\.js/,
|
||||||
/client\/[^/]+\/page_index(\.\d+)?\.js/,
|
/client\/[^/]+\/index(\.\d+)?\.js/,
|
||||||
/client\/[^/]+\/page_about(\.\d+)?\.js/,
|
/client\/[^/]+\/about(\.\d+)?\.js/,
|
||||||
/client\/[^/]+\/page_blog_\$slug(\.\d+)?\.js/,
|
/client\/[^/]+\/blog_\$slug(\.\d+)?\.js/,
|
||||||
/client\/[^/]+\/page_blog(\.\d+)?\.js/,
|
/client\/[^/]+\/blog(\.\d+)?\.js/,
|
||||||
/client\/[^/]+\/page_show\$45url(\.\d+)?\.js/,
|
/client\/[^/]+\/slow\$45preload(\.\d+)?\.js/,
|
||||||
/client\/[^/]+\/page_slow\$45preload(\.\d+)?\.js/,
|
|
||||||
];
|
];
|
||||||
const allPages = walkSync(dest);
|
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', () => {
|
it('calls a delete handler', () => {
|
||||||
return nightmare
|
return nightmare
|
||||||
.goto(`${base}/delete-test`)
|
.goto(`${base}/delete-test`)
|
||||||
@@ -640,7 +629,6 @@ function run({ mode, basepath = '' }) {
|
|||||||
.evaluate(() => document.querySelector('#sapper').textContent)
|
.evaluate(() => document.querySelector('#sapper').textContent)
|
||||||
.then(text => {
|
.then(text => {
|
||||||
assert.deepEqual(text.split('\n').filter(Boolean), [
|
assert.deepEqual(text.split('\n').filter(Boolean), [
|
||||||
'x: foo 1',
|
|
||||||
'y: bar 1',
|
'y: bar 1',
|
||||||
'z: baz 1'
|
'z: baz 1'
|
||||||
]);
|
]);
|
||||||
@@ -653,7 +641,6 @@ function run({ mode, basepath = '' }) {
|
|||||||
})
|
})
|
||||||
.then(text => {
|
.then(text => {
|
||||||
assert.deepEqual(text.split('\n').filter(Boolean), [
|
assert.deepEqual(text.split('\n').filter(Boolean), [
|
||||||
'x: foo 1',
|
|
||||||
'y: bar 1',
|
'y: bar 1',
|
||||||
'z: qux 2'
|
'z: qux 2'
|
||||||
]);
|
]);
|
||||||
@@ -667,6 +654,14 @@ function run({ mode, basepath = '' }) {
|
|||||||
assert.equal(title, 'it works');
|
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', () => {
|
describe('headers', () => {
|
||||||
|
|||||||
@@ -6,48 +6,46 @@ describe('create_routes', () => {
|
|||||||
it('creates routes', () => {
|
it('creates routes', () => {
|
||||||
const { components, pages, server_routes } = create_routes(path.join(__dirname, 'samples/basic'));
|
const { components, pages, server_routes } = create_routes(path.join(__dirname, 'samples/basic'));
|
||||||
|
|
||||||
const page_index = { name: 'page_index', file: '_default.html' };
|
const index = { name: 'index', file: 'index.html' };
|
||||||
const page_about = { name: 'page_about', file: 'about.html' };
|
const about = { name: 'about', file: 'about.html' };
|
||||||
const page_blog = { name: 'page_blog', file: 'blog/index.html' };
|
const blog = { name: 'blog', file: 'blog/index.html' };
|
||||||
const page_blog_index = { name: 'page_blog_index', file: 'blog/_default.html' };
|
const blog_$slug = { name: 'blog_$slug', file: 'blog/[slug].html' };
|
||||||
const page_blog_$slug = { name: 'page_blog_$slug', file: 'blog/[slug].html' };
|
|
||||||
|
|
||||||
assert.deepEqual(components, [
|
assert.deepEqual(components, [
|
||||||
page_index,
|
index,
|
||||||
page_about,
|
about,
|
||||||
page_blog,
|
blog,
|
||||||
page_blog_index,
|
blog_$slug
|
||||||
page_blog_$slug
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
assert.deepEqual(pages, [
|
assert.deepEqual(pages, [
|
||||||
{
|
{
|
||||||
pattern: /^\/?$/,
|
pattern: /^\/?$/,
|
||||||
parts: [
|
parts: [
|
||||||
{ component: page_index, params: [] }
|
{ component: index, params: [] }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
pattern: /^\/about\/?$/,
|
pattern: /^\/about\/?$/,
|
||||||
parts: [
|
parts: [
|
||||||
{ component: page_about, params: [] }
|
{ component: about, params: [] }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
pattern: /^\/blog\/?$/,
|
pattern: /^\/blog\/?$/,
|
||||||
parts: [
|
parts: [
|
||||||
{ component: page_blog, params: [] },
|
null,
|
||||||
{ component: page_blog_index, params: [] }
|
{ component: blog, params: [] }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
|
||||||
{
|
{
|
||||||
pattern: /^\/blog\/([^\/]+?)\/?$/,
|
pattern: /^\/blog\/([^\/]+?)\/?$/,
|
||||||
parts: [
|
parts: [
|
||||||
{ component: page_blog, params: [] },
|
null,
|
||||||
{ component: page_blog_$slug, params: ['slug'] }
|
{ component: blog_$slug, params: ['slug'] }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]);
|
]);
|
||||||
@@ -74,9 +72,9 @@ describe('create_routes', () => {
|
|||||||
|
|
||||||
// had to remove ? and " because windows
|
// had to remove ? and " because windows
|
||||||
|
|
||||||
// const quote = { name: 'page_$34', file: '".html' };
|
// const quote = { name: '$34', file: '".html' };
|
||||||
const hash = { name: 'page_$35', file: '#.html' };
|
const hash = { name: '$35', file: '#.html' };
|
||||||
// const question_mark = { name: 'page_$63', file: '?.html' };
|
// const question_mark = { name: '$63', file: '?.html' };
|
||||||
|
|
||||||
assert.deepEqual(components, [
|
assert.deepEqual(components, [
|
||||||
// quote,
|
// quote,
|
||||||
@@ -104,15 +102,15 @@ describe('create_routes', () => {
|
|||||||
it('sorts routes correctly', () => {
|
it('sorts routes correctly', () => {
|
||||||
const { pages } = create_routes(path.join(__dirname, 'samples/sorting'));
|
const { pages } = create_routes(path.join(__dirname, 'samples/sorting'));
|
||||||
|
|
||||||
assert.deepEqual(pages.map(p => p.parts.map(part => part.component.file)), [
|
assert.deepEqual(pages.map(p => p.parts.map(part => part && part.component.file)), [
|
||||||
['_default.html'],
|
['index.html'],
|
||||||
['about.html'],
|
['about.html'],
|
||||||
['post/index.html', 'post/_default.html'],
|
[null, 'post/index.html'],
|
||||||
['post/index.html', 'post/bar.html'],
|
[null, 'post/bar.html'],
|
||||||
['post/index.html', 'post/foo.html'],
|
[null, 'post/foo.html'],
|
||||||
['post/index.html', 'post/f[xx].html'],
|
[null, 'post/f[xx].html'],
|
||||||
['post/index.html', 'post/[id([0-9-a-z]{3,})].html'],
|
[null, 'post/[id([0-9-a-z]{3,})].html'],
|
||||||
['post/index.html', 'post/[id].html'],
|
[null, 'post/[id].html'],
|
||||||
['[wildcard].html']
|
['[wildcard].html']
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,9 +6,9 @@
|
|||||||
"noEmitOnError": true,
|
"noEmitOnError": true,
|
||||||
"allowJs": true,
|
"allowJs": true,
|
||||||
"lib": ["es5", "es6", "dom"],
|
"lib": ["es5", "es6", "dom"],
|
||||||
"importHelpers": true
|
"importHelpers": true,
|
||||||
|
"target": "ES5"
|
||||||
},
|
},
|
||||||
"target": "ES5",
|
|
||||||
"include": [
|
"include": [
|
||||||
"src"
|
"src"
|
||||||
],
|
],
|
||||||
|
|||||||
Reference in New Issue
Block a user