Compare commits

..

34 Commits

Author SHA1 Message Date
Rich Harris
2319ed9ed3 dont create fallback components 2018-07-21 10:38:53 -04:00
Rich Harris
5d7a715122 emit error event if manifest creation fails 2018-07-21 10:38:25 -04:00
Rich Harris
448e91a970 update find_page API 2018-07-20 11:41:37 -04:00
Rich Harris
d927597c1e doh 2018-07-20 11:41:24 -04:00
Rich Harris
aa92342e71 oops 2018-07-17 18:17:14 -04:00
Rich Harris
99b4cd43b9 minor tweak 2018-07-17 18:00:30 -04:00
Rich Harris
20015d6613 oops 2018-07-17 17:27:48 -04:00
Rich Harris
3d39ef96c2 add segment, params and query to server-rendered pages 2018-07-17 17:21:37 -04:00
Rich Harris
c867f051c2 fix fallback index file 2018-07-17 16:59:13 -04:00
Rich Harris
9e1207cdd7 fix error pages 2018-07-17 16:04:22 -04:00
Rich Harris
f126c6ac6c only replace components for changed segments 2018-07-17 15:42:35 -04:00
Rich Harris
84aaf3be4a please let this work 2018-07-16 20:02:42 -04:00
Rich Harris
e751cbebd5 once more, with feeling 2018-07-16 19:53:32 -04:00
Rich Harris
d2ee6ff3d5 argh 2018-07-16 18:05:13 -04:00
Rich Harris
6c68b3151c maybe fix some windows errors 2018-07-16 17:54:59 -04:00
Rich Harris
5428a7ec95 try locking node version to get tests running on windows 2018-07-16 17:42:54 -04:00
Rich Harris
dd190af904 ugh windows 2018-07-16 16:29:12 -04:00
Rich Harris
1f66e4c530 all tests passing 2018-07-16 16:23:43 -04:00
Rich Harris
b0b8b78c5d set preloading true when appropriate 2018-07-16 15:25:17 -04:00
Rich Harris
7d3e191e46 identify leaf index.html components 2018-07-16 15:10:46 -04:00
Rich Harris
61e3b6c6a0 handle errors in client 2018-07-16 14:57:49 -04:00
Rich Harris
af0bd1580d handle errors 2018-07-16 14:49:47 -04:00
Rich Harris
34cf953fde use serialized preloaded data 2018-07-16 14:27:13 -04:00
Rich Harris
8299c68678 inject fallback index.html where necessary 2018-07-16 14:18:21 -04:00
Rich Harris
f221281f8a client-side rendering 2018-07-16 14:07:06 -04:00
Rich Harris
9dc5ba569f server-side rendering 2018-07-16 12:06:10 -04:00
Rich Harris
969430716f update manifest generation 2018-07-16 11:21:24 -04:00
Rich Harris
624f17364c tidy up 2018-07-15 23:12:14 -04:00
Rich Harris
c90d8ee3cd more tests 2018-07-15 23:11:08 -04:00
Rich Harris
6c5630f281 add more tests 2018-07-15 22:50:53 -04:00
Rich Harris
bf8e56748a change how routes are created 2018-07-15 22:13:30 -04:00
Rich Harris
5b024f2c8d small tidy up 2018-07-15 22:12:47 -04:00
Rich Harris
1af0f13799 Merge branch 'master' into gh-262 2018-07-14 21:59:39 -04:00
Rich Harris
80ece8b148 delete App.html 2018-07-05 09:04:38 -04:00
28 changed files with 331 additions and 421 deletions

View File

@@ -1,17 +1,5 @@
# 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))

View File

@@ -1,6 +1,6 @@
{ {
"name": "sapper", "name": "sapper",
"version": "0.15.2", "version": "0.14.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,7 +12,6 @@
"runtime", "runtime",
"webpack", "webpack",
"sapper", "sapper",
"components",
"dist" "dist"
], ],
"directories": { "directories": {
@@ -68,7 +67,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": "rm -rf dist && rollup -c", "build": "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"

View File

@@ -19,8 +19,7 @@ export default [
}, },
plugins: [ plugins: [
typescript({ typescript({
typescript: require('typescript'), typescript: require('typescript')
target: "ES2017"
}) })
] ]
}, },

View File

@@ -14,10 +14,6 @@ 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);
} }
@@ -48,7 +44,7 @@ function right_pad(str: string, len: number) {
} }
function generate_client( function generate_client(
routes: { root: PageComponent, components: PageComponent[], pages: Page[], server_routes: ServerRoute[] }, routes: { components: PageComponent[], pages: Page[], server_routes: ServerRoute[] },
path_to_routes: string, path_to_routes: string,
dev_port?: number dev_port?: number
) { ) {
@@ -62,15 +58,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 '${get_file(path_to_routes, routes.root)}'; import root from '${posixify(`${path_to_routes}/index.html`)}';
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}" */ '${get_file(path_to_routes, component)}');`) import(/* webpackChunkName: "${component.name}" */ '${posixify(`${path_to_routes}/${component.file}`)}');`)
.join('\n')} .join('\n')}
export const manifest = { export const routes = {
ignore: [${server_routes_to_ignore.map(route => route.pattern).join(', ')}], ignore: [${server_routes_to_ignore.map(route => route.pattern).join(', ')}],
pages: [ pages: [
@@ -79,8 +75,6 @@ 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(', ')} }) }`;
@@ -95,10 +89,7 @@ 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(
@@ -118,15 +109,15 @@ function generate_client(
} }
function generate_server( function generate_server(
routes: { root: PageComponent, components: PageComponent[], pages: Page[], server_routes: ServerRoute[] }, routes: { 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 '${get_file(path_to_routes, component)}';`), `import ${component.name} from '${posixify(`${path_to_routes}/${component.file}`)}';`),
`import root from '${get_file(path_to_routes, routes.root)}';`, `import root from '${posixify(`${path_to_routes}/index.html`)}';`,
`import error from '${posixify(`${path_to_routes}/_error.html`)}';` `import error from '${posixify(`${path_to_routes}/_error.html`)}';`
); );
@@ -134,7 +125,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 manifest = { export const routes = {
server_routes: [ server_routes: [
${routes.server_routes.map(route => `{ ${routes.server_routes.map(route => `{
// ${route.file} // ${route.file}
@@ -152,8 +143,6 @@ 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}`
@@ -173,18 +162,7 @@ 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}`);
} }

View File

@@ -4,22 +4,11 @@ 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[][],
@@ -65,7 +54,9 @@ export default function create_routes(cwd = locations.routes()) {
.sort(comparator); .sort(comparator);
items.forEach(item => { items.forEach(item => {
if (item.basename[0] === '_') return; if (item.basename[0] === '_') {
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;
@@ -100,28 +91,58 @@ 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, '_layout.html'); const index = path.join(dir, item.basename, 'index.html');
const component = fs.existsSync(index)
? {
name: `page_${get_slug(item.file)}`,
file: `${item.file}/index.html`
}
: null;
const component = fs.existsSync(index) && { if (component) {
name: `${get_slug(item.file)}__layout`, components.push(component);
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,
component stack.concat({
? stack.concat({ component, params }) component: component || {
: stack.concat(null) missing: true,
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: get_slug(item.file), name: `page_${get_slug(item.file)}`,
file: item.file file: item.file
}; };
@@ -131,7 +152,7 @@ export default function create_routes(cwd = locations.routes()) {
}); });
components.push(component); components.push(component);
if (item.basename === 'index.html') { if (item.basename === '_default.html') {
pages.push({ pages.push({
pattern: get_pattern(parent_segments), pattern: get_pattern(parent_segments),
parts parts
@@ -155,19 +176,21 @@ 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;
@@ -192,7 +215,6 @@ export default function create_routes(cwd = locations.routes()) {
}); });
return { return {
root,
components, components,
pages, pages,
server_routes server_routes
@@ -206,11 +228,9 @@ type Part = {
}; };
function comparator( function comparator(
a: { basename: string, parts: Part[], file: string, is_index: boolean }, a: { basename: string, parts: Part[], file: string, is_dir: boolean },
b: { basename: string, parts: Part[], file: string, is_index: boolean } b: { basename: string, parts: Part[], file: string, is_dir: 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) {

View File

@@ -21,7 +21,7 @@ export type Store = {
}; };
export type PageComponent = { export type PageComponent = {
default?: boolean; missing?: boolean;
name: string; name: string;
file: string; file: string;
}; };

View File

@@ -26,7 +26,7 @@ type Page = {
}> }>
}; };
type Manifest = { type RouteObject = {
server_routes: ServerRoute[]; server_routes: ServerRoute[];
pages: Page[]; pages: Page[];
root: Component; root: Component;
@@ -39,20 +39,6 @@ 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;
@@ -73,19 +59,12 @@ interface Component {
preload: (data: any) => any | Promise<any> preload: (data: any) => any | Promise<any>
} }
export default function middleware(opts: { export default function middleware({ routes, store }: {
manifest: Manifest, routes: RouteObject,
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([
@@ -138,8 +117,8 @@ export default function middleware(opts: {
cache_control: 'max-age=31536000' cache_control: 'max-age=31536000'
}), }),
get_server_route_handler(manifest.server_routes), get_server_route_handler(routes.server_routes),
get_page_handler(manifest, store) get_page_handler(routes, store)
].filter(Boolean)); ].filter(Boolean));
return middleware; return middleware;
@@ -256,7 +235,7 @@ function get_server_route_handler(routes: ServerRoute[]) {
}; };
} }
function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store) { function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store) {
const output = locations.dest(); const output = locations.dest();
const get_chunks = dev() const get_chunks = dev()
@@ -267,22 +246,17 @@ function get_page_handler(manifest: Manifest, 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 } = manifest; const { server_routes, pages } = routes;
const error_route = manifest.error; const error_route = routes.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');
@@ -292,8 +266,6 @@ function get_page_handler(manifest: Manifest, 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]);
}); });
@@ -307,77 +279,67 @@ function get_page_handler(manifest: Manifest, 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 };
const preload_context = { Promise.all(page.parts.map(part => {
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(preload_context, { ? part.component.preload.call({
path: req.path, redirect: (statusCode: number, location: string) => {
query: req.query, if (redirect && (redirect.statusCode !== statusCode || redirect.location !== location)) {
params: part.params ? part.params(match) : {} 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)
: {}; : {};
}))).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 => {
@@ -390,57 +352,47 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
} }
if (preload_error) { if (preload_error) {
handle_error(req, res, preload_error.statusCode, preload_error.message); handle_page({
pattern: null,
parts: [
{ name: null, component: error_route }
]
}, req, res, preload_error.statusCode, preload_error.message);
return; return;
} }
const serialized = { const serialized = {
preloaded: `[${preloaded.map(data => try_serialize(data)).join(',')}]`, preloaded: page.parts.map((part, i) => {
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 props: Props = { const data = Object.assign({}, props, { params: req.params }, {
path: req.path, child: {}
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),
}, preloaded[i + 1]) query: req.query
}, preloaded[i])
}); });
level.props.child = <Props["child"]>{ level.props.child = {};
segment: segments[i + 1]
};
level = level.props.child; level = level.props.child;
} }
const { html, head, css } = manifest.root.render(data, { const { html, head, css } = routes.root.render(data, {
store store
}); });
@@ -451,9 +403,8 @@ function get_page_handler(manifest: Manifest, 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(',')}};`;
@@ -484,13 +435,8 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
}); });
} }
}).catch(err => { }).catch(err => {
if (error) { res.statusCode = 500;
// we encountered an error while rendering the error page — oops res.end(err.message);
res.statusCode = 500;
res.end(`<pre>${escape_html(err.message)}</pre>`);
} else {
handle_error(req, res, 500, err);
}
}); });
} }
@@ -504,7 +450,12 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
} }
} }
handle_error(req, res, 404, 'Not found'); handle_page({
pattern: null,
parts: [
{ name: null, component: error_route }
]
}, req, res, 404, 'Not found');
}; };
} }
@@ -535,15 +486,3 @@ 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]};`);
}

View File

@@ -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, Manifest, RouteData, ScrollPosition, Store, Target } from './interfaces'; import { Component, ComponentConstructor, Params, Query, Redirect, Routes, 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 manifest: Manifest; let routes: Routes;
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 (manifest.ignore.some(pattern => pattern.test(path))) return; if (routes.ignore.some(pattern => pattern.test(path))) return;
for (let i = 0; i < manifest.pages.length; i += 1) { for (let i = 0; i < routes.pages.length; i += 1) {
const page = manifest.pages[i]; const page = routes.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, nullable_depth: number, scroll: ScrollPosition, token: {}) { function render(data: any, changed_from: 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 < nullable_depth; i += 1) { for (let i = 0; i < changed_from; i += 1) {
if (i === nullable_depth) break; if (i === changed_from) break;
level = level.props.child; level = level.props.child;
} }
@@ -106,9 +106,7 @@ function render(data: any, nullable_depth: number, scroll: ScrollPosition, token
detach(end); detach(end);
} }
Object.assign(data, root_data); root = new routes.root({
root = new manifest.root({
target, target,
data, data,
store, store,
@@ -128,13 +126,10 @@ 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;
nullable_depth?: number; changed_from?: number;
}> { }> {
if (root) { if (root) {
root.set({ preloading: true }); root.set({ preloading: true });
@@ -167,19 +162,8 @@ 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 = {
@@ -188,17 +172,15 @@ 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 + 1] const preloaded = ready || !initial_data.preloaded[i]
? Component.preload ? await Component.preload.call(preload_context, req) : {} ? Component.preload ? await Component.preload.call(preload_context, req) : {}
: initial_data.preloaded[i + 1]; : initial_data.preloaded[i];
return { Component, preloaded }; return { Component, preloaded };
})).catch(err => { })).catch(err => {
error = { statusCode: 500, message: err }; error = { statusCode: 500, message: err };
return []; return [];
}).then(async results => { }).then(results => {
if (!root_data) root_data = await root_preload;
if (redirect) { if (redirect) {
return { redirect }; return { redirect };
} }
@@ -221,7 +203,7 @@ function prepare_page(target: Target): Promise<{
data: Object.assign({}, props, { data: Object.assign({}, props, {
preloading: false, preloading: false,
child: { child: {
component: manifest.error, component: routes.error,
props props
} }
}) })
@@ -232,43 +214,33 @@ 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, nullable_depth }; return { data, changed_from };
}); });
} }
@@ -293,12 +265,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, nullable_depth } = await loaded; const { redirect, data, changed_from } = await loaded;
if (redirect) { if (redirect) {
await goto(redirect.location, { replaceState: true }); await goto(redirect.location, { replaceState: true });
} else { } else {
render(data, nullable_depth, scroll_history[id], token); render(data, changed_from, scroll_history[id], token);
document.activeElement.blur(); document.activeElement.blur();
} }
} }
@@ -364,7 +336,7 @@ function handle_popstate(event: PopStateEvent) {
let prefetching: { let prefetching: {
href: string; href: string;
promise: Promise<{ redirect?: Redirect, data?: any, nullable_depth?: number }>; promise: Promise<{ redirect?: Redirect, data?: any, changed_from?: number }>;
} = null; } = null;
export function prefetch(href: string) { export function prefetch(href: string) {
@@ -397,23 +369,13 @@ function trigger_prefetch(event: MouseEvent | TouchEvent) {
let inited: boolean; let inited: boolean;
let ready = false; let ready = false;
export function init(opts: { export function init(opts: { App: ComponentConstructor, target: Node, routes: Routes, store?: (data: any) => Store }) {
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;
manifest = opts.manifest; routes = opts.routes;
if (opts && opts.store) { if (opts && opts.store) {
store = opts.store(initial_data.store); store = opts.store(initial_data.store);
@@ -440,10 +402,8 @@ export function init(opts: {
history.replaceState({ id: uid }, '', href); history.replaceState({ id: uid }, '', href);
if (!initial_data.error) { const target = select_route(new URL(window.location.href));
const target = select_route(new URL(window.location.href)); if (target) return navigate(target, uid);
if (target) return navigate(target, uid);
}
}); });
} }
@@ -463,9 +423,9 @@ export function goto(href: string, opts = { replaceState: false }) {
} }
export function prefetchRoutes(pathnames: string[]) { export function prefetchRoutes(pathnames: string[]) {
if (!manifest) throw new Error(`You must call init() first`); if (!routes) throw new Error(`You must call init() first`);
return manifest.pages return routes.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));

View File

@@ -23,7 +23,7 @@ export type Page = {
}>; }>;
}; };
export type Manifest = { export type Routes = {
ignore: RegExp[]; ignore: RegExp[];
root: ComponentConstructor; root: ComponentConstructor;
error: () => Promise<{ default: ComponentConstructor }>; error: () => Promise<{ default: ComponentConstructor }>;

View File

@@ -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 { manifest } from './manifest/client.js'; import { routes } from './manifest/client.js';
window.init = () => { window.init = () => {
return init({ return init({
target: document.querySelector('#sapper'), target: document.querySelector('#sapper'),
manifest, routes,
store: data => new Store(data) store: data => new Store(data)
}); });
}; };

View File

@@ -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 { manifest } from './manifest/server.js'; import { routes } from './manifest/server.js';
let pending; let pending;
let ended; let ended;
@@ -86,7 +86,7 @@ const middlewares = [
}, },
sapper({ sapper({
manifest, routes,
store: () => { store: () => {
return new Store({ return new Store({
title: 'Stored title' title: 'Stored title'

View File

@@ -0,0 +1,20 @@
<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>

View File

@@ -0,0 +1,26 @@
<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>

View File

@@ -1,15 +0,0 @@
{#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>

View File

@@ -0,0 +1,25 @@
<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>

View File

@@ -1,25 +1 @@
<svelte:head> <svelte:component this={child.component} {...child.props}/>
<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>

View File

@@ -1,26 +1,6 @@
<svelte:head> {#if preloading}
<title>Sapper project template</title> <progress class='preloading-progress' value=0.5/>
</svelte:head> {/if}
<h1>Great success!</h1> <svelte:component this={child.component} {...child.props}/>
<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>

View File

@@ -1 +0,0 @@
<h1>root preload function ran: {rootPreloadFunctionRan}</h1>

View File

@@ -0,0 +1,9 @@
<p>URL is {url}</p>
<script>
export default {
preload({ url }) {
if (url) return { url };
}
};
</script>

View File

@@ -100,11 +100,12 @@ 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\/[^/]+\/index(\.\d+)?\.js/, /client\/[^/]+\/page_index(\.\d+)?\.js/,
/client\/[^/]+\/about(\.\d+)?\.js/, /client\/[^/]+\/page_about(\.\d+)?\.js/,
/client\/[^/]+\/blog_\$slug(\.\d+)?\.js/, /client\/[^/]+\/page_blog_\$slug(\.\d+)?\.js/,
/client\/[^/]+\/blog(\.\d+)?\.js/, /client\/[^/]+\/page_blog(\.\d+)?\.js/,
/client\/[^/]+\/slow\$45preload(\.\d+)?\.js/, /client\/[^/]+\/page_show\$45url(\.\d+)?\.js/,
/client\/[^/]+\/page_slow\$45preload(\.\d+)?\.js/,
]; ];
const allPages = walkSync(dest); const allPages = walkSync(dest);
@@ -369,6 +370,16 @@ 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`)
@@ -629,6 +640,7 @@ 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'
]); ]);
@@ -641,6 +653,7 @@ 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'
]); ]);
@@ -654,14 +667,6 @@ 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', () => {

View File

@@ -6,46 +6,48 @@ 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 index = { name: 'index', file: 'index.html' }; const page_index = { name: 'page_index', file: '_default.html' };
const about = { name: 'about', file: 'about.html' }; const page_about = { name: 'page_about', file: 'about.html' };
const blog = { name: 'blog', file: 'blog/index.html' }; const page_blog = { name: 'page_blog', file: 'blog/index.html' };
const blog_$slug = { name: 'blog_$slug', file: 'blog/[slug].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' };
assert.deepEqual(components, [ assert.deepEqual(components, [
index, page_index,
about, page_about,
blog, page_blog,
blog_$slug page_blog_index,
page_blog_$slug
]); ]);
assert.deepEqual(pages, [ assert.deepEqual(pages, [
{ {
pattern: /^\/?$/, pattern: /^\/?$/,
parts: [ parts: [
{ component: index, params: [] } { component: page_index, params: [] }
] ]
}, },
{ {
pattern: /^\/about\/?$/, pattern: /^\/about\/?$/,
parts: [ parts: [
{ component: about, params: [] } { component: page_about, params: [] }
] ]
}, },
{ {
pattern: /^\/blog\/?$/, pattern: /^\/blog\/?$/,
parts: [ parts: [
null, { component: page_blog, params: [] },
{ component: blog, params: [] } { component: page_blog_index, params: [] }
] ]
}, },
{ {
pattern: /^\/blog\/([^\/]+?)\/?$/, pattern: /^\/blog\/([^\/]+?)\/?$/,
parts: [ parts: [
null, { component: page_blog, params: [] },
{ component: blog_$slug, params: ['slug'] } { component: page_blog_$slug, params: ['slug'] }
] ]
} }
]); ]);
@@ -72,9 +74,9 @@ describe('create_routes', () => {
// had to remove ? and " because windows // had to remove ? and " because windows
// const quote = { name: '$34', file: '".html' }; // const quote = { name: 'page_$34', file: '".html' };
const hash = { name: '$35', file: '#.html' }; const hash = { name: 'page_$35', file: '#.html' };
// const question_mark = { name: '$63', file: '?.html' }; // const question_mark = { name: 'page_$63', file: '?.html' };
assert.deepEqual(components, [ assert.deepEqual(components, [
// quote, // quote,
@@ -102,15 +104,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 && part.component.file)), [ assert.deepEqual(pages.map(p => p.parts.map(part => part.component.file)), [
['index.html'], ['_default.html'],
['about.html'], ['about.html'],
[null, 'post/index.html'], ['post/index.html', 'post/_default.html'],
[null, 'post/bar.html'], ['post/index.html', 'post/bar.html'],
[null, 'post/foo.html'], ['post/index.html', 'post/foo.html'],
[null, 'post/f[xx].html'], ['post/index.html', 'post/f[xx].html'],
[null, 'post/[id([0-9-a-z]{3,})].html'], ['post/index.html', 'post/[id([0-9-a-z]{3,})].html'],
[null, 'post/[id].html'], ['post/index.html', 'post/[id].html'],
['[wildcard].html'] ['[wildcard].html']
]); ]);
}); });

View File

@@ -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"
], ],