Compare commits

...

12 Commits

Author SHA1 Message Date
Rich Harris
c743d11b3b -> v0.11.1 2018-05-04 17:22:34 -04:00
Rich Harris
b525eb6480 get tests passing 2018-05-04 17:19:39 -04:00
Rich Harris
210d03fb06 Merge branch 'collision' of https://github.com/akihikodaki/sapper into akihikodaki-collision 2018-05-04 17:08:55 -04:00
Rich Harris
0685cc4cbe Merge branch 'master' of github.com:sveltejs/sapper 2018-05-04 17:08:47 -04:00
Rich Harris
9e2d0a7fbc Merge branch 'master' into collision 2018-05-04 17:05:18 -04:00
Rich Harris
a751a3b731 Merge pull request #254 from akihikodaki/dot_strict
Ignore files and directories with leading dots except .well-known
2018-05-04 17:04:27 -04:00
Rich Harris
bc7faeeab9 remove unused esm package 2018-05-04 16:55:57 -04:00
Rich Harris
a88c1de2f6 Merge pull request #256 from johnmuhl/esm
replace discontinued @std/esm package with esm
2018-05-04 16:53:35 -04:00
john muhl
a231795c4c replace discontinued @std/esm package with esm 2018-05-04 13:56:17 -05:00
Akihiko Odaki
ba7525c676 Ignore files and directories with leading dots except .well-known 2018-05-04 22:18:23 +09:00
Rich Harris
992d89027d Merge branch 'master' into collision 2018-05-03 21:44:28 -04:00
Akihiko Odaki
917dd60cc3 Allow to have middleware for the path same with a HTML page
HTTP allows to change the type of the content to serve by Accept field in
the request. The middleware for the path same with a HTML page will
be inserted before the HTML renderer, and can take advantage of this
feature, using expressjs's "accepts" method, for example.
2018-04-15 23:11:08 +09:00
7 changed files with 364 additions and 256 deletions

View File

@@ -1,5 +1,10 @@
# sapper changelog # sapper changelog
## 0.11.1
* Limit routes with leading dots to `.well-known` URIs ([#252](https://github.com/sveltejs/sapper/issues/252))
* Allow server routes to sit in front of pages ([#236](https://github.com/sveltejs/sapper/pull/236))
## 0.11.0 ## 0.11.0
* Create launcher file ([#240](https://github.com/sveltejs/sapper/issues/240)) * Create launcher file ([#240](https://github.com/sveltejs/sapper/issues/240))

View File

@@ -1,6 +1,6 @@
{ {
"name": "sapper", "name": "sapper",
"version": "0.11.0", "version": "0.11.1",
"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": {
@@ -40,7 +40,6 @@
"webpack-format-messages": "^1.0.2" "webpack-format-messages": "^1.0.2"
}, },
"devDependencies": { "devDependencies": {
"@std/esm": "^0.26.0",
"@types/glob": "^5.0.34", "@types/glob": "^5.0.34",
"@types/mkdirp": "^0.5.2", "@types/mkdirp": "^0.5.2",
"@types/rimraf": "^2.0.2", "@types/rimraf": "^2.0.2",
@@ -48,7 +47,6 @@
"eslint": "^4.13.1", "eslint": "^4.13.1",
"eslint-plugin-import": "^2.8.0", "eslint-plugin-import": "^2.8.0",
"express": "^4.16.3", "express": "^4.16.3",
"get-port": "^3.2.0",
"mocha": "^5.0.4", "mocha": "^5.0.4",
"nightmare": "^3.0.0", "nightmare": "^3.0.0",
"npm-run-all": "^4.1.2", "npm-run-all": "^4.1.2",
@@ -61,7 +59,6 @@
"serve-static": "^1.13.2", "serve-static": "^1.13.2",
"svelte": "^2.4.4", "svelte": "^2.4.4",
"svelte-loader": "^2.9.0", "svelte-loader": "^2.9.0",
"ts-node": "^6.0.2",
"typescript": "^2.8.3", "typescript": "^2.8.3",
"walk-sync": "^0.3.2", "walk-sync": "^0.3.2",
"webpack": "^4.1.0" "webpack": "^4.1.0"

View File

@@ -45,11 +45,13 @@ function generate_client(routes: Route[], path_to_routes: string, dev_port?: num
export const routes = [ export const routes = [
${routes ${routes
.map(route => { .map(route => {
if (route.type !== 'page') { const page = route.handlers.find(({ type }) => type === 'page');
if (!page) {
return `{ pattern: ${route.pattern}, ignore: true }`; return `{ pattern: ${route.pattern}, ignore: true }`;
} }
const file = posixify(`${path_to_routes}/${route.file}`); const file = posixify(`${path_to_routes}/${page.file}`);
if (route.id === '_4xx' || route.id === '_5xx') { if (route.id === '_4xx' || route.id === '_5xx') {
return `{ error: '${route.id.slice(1)}', load: () => import(/* webpackChunkName: "${route.id}" */ '${file}') }`; return `{ error: '${route.id.slice(1)}', load: () => import(/* webpackChunkName: "${route.id}" */ '${file}') }`;
@@ -85,28 +87,36 @@ function generate_server(routes: Route[], path_to_routes: string) {
let code = ` let code = `
// This file is generated by Sapper — do not edit it! // This file is generated by Sapper — do not edit it!
${routes ${routes
.map(route => { .map(route =>
const file = posixify(`${path_to_routes}/${route.file}`); route.handlers
return route.type === 'page' .map(({ type, file }, index) => {
? `import ${route.id} from '${file}';` const module = posixify(`${path_to_routes}/${file}`);
: `import * as ${route.id} from '${file}';`;
return type === 'page'
? `import ${route.id}${index} from '${module}';`
: `import * as ${route.id}${index} from '${module}';`;
}) })
.join('\n')
)
.join('\n')} .join('\n')}
export const routes = [ export const routes = [
${routes ${routes
.map(route => { .map(route => {
const file = posixify(`../../${route.file}`); const handlers = route.handlers
.map(({ type }, index) =>
`{ type: '${type}', module: ${route.id}${index} }`)
.join(', ');
if (route.id === '_4xx' || route.id === '_5xx') { if (route.id === '_4xx' || route.id === '_5xx') {
return `{ error: '${route.id.slice(1)}', module: ${route.id} }`; return `{ error: '${route.id.slice(1)}', handlers: [${handlers}] }`;
} }
const params = route.params.length === 0 const params = route.params.length === 0
? '{}' ? '{}'
: `{ ${route.params.map((part, i) => `${part}: match[${i + 1}]`).join(', ')} }`; : `{ ${route.params.map((part, i) => `${part}: match[${i + 1}]`).join(', ')} }`;
return `{ id: '${route.id}', type: '${route.type}', pattern: ${route.pattern}, params: ${route.params.length > 0 ? `match` : `()`} => (${params}), module: ${route.id} }`; return `{ id: '${route.id}', pattern: ${route.pattern}, params: ${route.params.length > 0 ? `match` : `()`} => (${params}), handlers: [${handlers}] }`;
}) })
.join(',\n\t') .join(',\n\t')
} }

View File

@@ -5,8 +5,9 @@ import { Route } from '../interfaces';
export default function create_routes({ files } = { files: glob.sync('**/*.*', { cwd: locations.routes(), dot: true, nodir: true }) }) { export default function create_routes({ files } = { files: glob.sync('**/*.*', { cwd: locations.routes(), dot: true, nodir: true }) }) {
const routes: Route[] = files const routes: Route[] = files
.filter((file: string) => !/(^|\/|\\)_/.test(file))
.map((file: string) => { .map((file: string) => {
if (/(^|\/|\\)_/.test(file)) return; if (/(^|\/|\\)(_|\.(?!well-known))/.test(file)) return;
if (/]\[/.test(file)) { if (/]\[/.test(file)) {
throw new Error(`Invalid route ${file} — parameters must be separated`); throw new Error(`Invalid route ${file} — parameters must be separated`);
@@ -16,6 +17,60 @@ export default function create_routes({ files } = { files: glob.sync('**/*.*', {
const parts = base.split('/'); // glob output is always posix-style const parts = base.split('/'); // glob output is always posix-style
if (parts[parts.length - 1] === 'index') parts.pop(); if (parts[parts.length - 1] === 'index') parts.pop();
return {
files: [file],
base,
parts
};
})
.filter(Boolean)
.filter((a, index, array) => {
const found = array.slice(index + 1).find(b => a.base === b.base);
if (found) found.files.push(...a.files);
return !found;
})
.sort((a, b) => {
const max = Math.max(a.parts.length, b.parts.length);
if (max === 1) {
if (a.parts[0] === '4xx' || a.parts[0] === '5xx') return -1;
if (b.parts[0] === '4xx' || b.parts[0] === '5xx') return 1;
}
for (let i = 0; i < max; i += 1) {
const a_part = a.parts[i];
const b_part = b.parts[i];
if (!a_part) return -1;
if (!b_part) return 1;
const a_sub_parts = get_sub_parts(a_part);
const b_sub_parts = get_sub_parts(b_part);
const max = Math.max(a_sub_parts.length, b_sub_parts.length);
for (let i = 0; i < max; i += 1) {
const a_sub_part = a_sub_parts[i];
const b_sub_part = b_sub_parts[i];
if (!a_sub_part) return 1; // b is more specific, so goes first
if (!b_sub_part) return -1;
if (a_sub_part.dynamic !== b_sub_part.dynamic) {
return a_sub_part.dynamic ? 1 : -1;
}
if (!a_sub_part.dynamic && a_sub_part.content !== b_sub_part.content) {
return (
(b_sub_part.content.length - a_sub_part.content.length) ||
(a_sub_part.content < b_sub_part.content ? -1 : 1)
);
}
}
}
throw new Error(`The ${a.base} and ${b.base} routes clash`);
})
.map(({ files, base, parts }) => {
const id = ( const id = (
parts.join('_').replace(/[[\]]/g, '$').replace(/^\d/, '_$&').replace(/[^a-zA-Z0-9_$]/g, '_') parts.join('_').replace(/[[\]]/g, '$').replace(/^\d/, '_$&').replace(/[^a-zA-Z0-9_$]/g, '_')
) || '_'; ) || '_';
@@ -63,54 +118,26 @@ export default function create_routes({ files } = { files: glob.sync('**/*.*', {
return { return {
id, id,
handlers: files.map(file => ({
type: path.extname(file) === '.html' ? 'page' : 'route', type: path.extname(file) === '.html' ? 'page' : 'route',
file, file
})).sort((a, b) => {
if (a.type === 'page' && b.type === 'route') {
return 1;
}
if (a.type === 'route' && b.type === 'page') {
return -1;
}
return 0;
}),
pattern, pattern,
test, test,
exec, exec,
parts, parts,
params params
}; };
})
.filter(Boolean)
.sort((a: Route, b: Route) => {
if (a.file === '4xx.html' || a.file === '5xx.html') return -1;
if (b.file === '4xx.html' || b.file === '5xx.html') return 1;
const max = Math.max(a.parts.length, b.parts.length);
for (let i = 0; i < max; i += 1) {
const a_part = a.parts[i];
const b_part = b.parts[i];
if (!a_part) return -1;
if (!b_part) return 1;
const a_sub_parts = get_sub_parts(a_part);
const b_sub_parts = get_sub_parts(b_part);
const max = Math.max(a_sub_parts.length, b_sub_parts.length);
for (let i = 0; i < max; i += 1) {
const a_sub_part = a_sub_parts[i];
const b_sub_part = b_sub_parts[i];
if (!a_sub_part) return 1; // b is more specific, so goes first
if (!b_sub_part) return -1;
if (a_sub_part.dynamic !== b_sub_part.dynamic) {
return a_sub_part.dynamic ? 1 : -1;
}
if (!a_sub_part.dynamic && a_sub_part.content !== b_sub_part.content) {
return (
(b_sub_part.content.length - a_sub_part.content.length) ||
(a_sub_part.content < b_sub_part.content ? -1 : 1)
);
}
}
}
throw new Error(`The ${a.file} and ${b.file} routes clash`);
}); });
return routes; return routes;

View File

@@ -1,7 +1,9 @@
export type Route = { export type Route = {
id: string; id: string;
handlers: {
type: 'page' | 'route'; type: 'page' | 'route';
file: string; file: string;
}[];
pattern: RegExp; pattern: RegExp;
test: (url: string) => boolean; test: (url: string) => boolean;
exec: (url: string) => Record<string, string>; exec: (url: string) => Record<string, string>;

View File

@@ -143,9 +143,20 @@ function get_route_handler(chunks: Record<string, string>, routes: RouteObject[]
function handle_route(route: RouteObject, req: Req, res: ServerResponse) { function handle_route(route: RouteObject, req: Req, res: ServerResponse) {
req.params = route.params(route.pattern.exec(req.path)); req.params = route.params(route.pattern.exec(req.path));
const mod = route.module; const handlers = route.handlers[Symbol.iterator]();
if (route.type === 'page') { function next() {
try {
const { value: handler, done } = handlers.next();
if (done) {
handle_error(req, res, 404, 'Not found');
return;
}
const mod = handler.module;
if (handler.type === 'page') {
res.setHeader('Content-Type', 'text/html'); res.setHeader('Content-Type', 'text/html');
// preload main.js and current route // preload main.js and current route
@@ -279,8 +290,8 @@ function get_route_handler(chunks: Record<string, string>, routes: RouteObject[]
// 'delete' cannot be exported from a module because it is a keyword, // 'delete' cannot be exported from a module because it is a keyword,
// so check for 'del' instead // so check for 'del' instead
const method_export = method === 'delete' ? 'del' : method; const method_export = method === 'delete' ? 'del' : method;
const handler = mod[method_export]; const handle_method = mod[method_export];
if (handler) { if (handle_method) {
if (process.env.SAPPER_EXPORT) { if (process.env.SAPPER_EXPORT) {
const { write, end, setHeader } = res; const { write, end, setHeader } = res;
const chunks: any[] = []; const chunks: any[] = [];
@@ -318,20 +329,26 @@ function get_route_handler(chunks: Record<string, string>, routes: RouteObject[]
res.statusCode = 500; res.statusCode = 500;
res.end(err.message); res.end(err.message);
} else { } else {
handle_error(req, res, 404, 'Not found'); process.nextTick(next);
} }
}; };
try { try {
handler(req, res, handle_bad_result); handle_method(req, res, handle_bad_result);
} catch (err) { } catch (err) {
handle_bad_result(err); handle_bad_result(err);
} }
} else { } else {
// no matching handler for method — 404 // no matching handler for method
handle_error(req, res, 404, 'Not found'); process.nextTick(next);
} }
} }
} catch (error) {
handle_error(req, res, 500, error);
}
}
next();
} }
const not_found_route = routes.find((route: RouteObject) => route.error === '4xx'); const not_found_route = routes.find((route: RouteObject) => route.error === '4xx');
@@ -349,19 +366,7 @@ function get_route_handler(chunks: Record<string, string>, routes: RouteObject[]
? not_found_route ? not_found_route
: error_route; : error_route;
const title: string = not_found function render_page({ head, css, html }) {
? 'Not found'
: `Internal server error: ${error.message}`;
const rendered = route ? route.module.render({
status: statusCode,
error
}, {
store: store_getter && store_getter(req)
}) : { head: '', css: null, html: title };
const { head, css, html } = rendered;
const page = template() const page = template()
.replace('%sapper.base%', `<base href="${req.baseUrl}/">`) .replace('%sapper.base%', `<base href="${req.baseUrl}/">`)
.replace('%sapper.scripts%', `<script>__SAPPER__={baseUrl: "${req.baseUrl}"}</script><script src='${req.baseUrl}/client/${chunks.main}'></script>`) .replace('%sapper.scripts%', `<script>__SAPPER__={baseUrl: "${req.baseUrl}"}</script><script src='${req.baseUrl}/client/${chunks.main}'></script>`)
@@ -372,16 +377,51 @@ function get_route_handler(chunks: Record<string, string>, routes: RouteObject[]
res.end(page); res.end(page);
} }
function handle_notfound() {
const title: string = not_found
? 'Not found'
: `Internal server error: ${error.message}`;
render_page({ head: '', css: null, html: title });
}
if (route) {
const handlers = route.handlers[Symbol.iterator]();
function next() {
const { value: handler, done } = handlers.next();
if (done) {
handle_notfound();
} else if (handler.type === 'page') {
render_page(handler.module.render({
status: statusCode,
error
}, {
store: store_getter && store_getter(req)
}));
} else {
const handle_method = mod[method_export];
if (handle_method) {
handle_method(req, res, next);
} else {
next();
}
}
}
next();
} else {
handle_notfound();
}
}
return function find_route(req: Req, res: ServerResponse) { return function find_route(req: Req, res: ServerResponse) {
try {
for (const route of routes) { for (const route of routes) {
if (!route.error && route.pattern.test(req.path)) return handle_route(route, req, res); if (!route.error && route.pattern.test(req.path)) return handle_route(route, req, res);
} }
handle_error(req, res, 404, 'Not found'); handle_error(req, res, 404, 'Not found');
} catch (error) {
handle_error(req, res, 500, error);
}
}; };
} }

View File

@@ -2,7 +2,29 @@ const assert = require('assert');
const { create_routes } = require('../../dist/core.ts.js'); const { create_routes } = require('../../dist/core.ts.js');
describe('create_routes', () => { describe('create_routes', () => {
it('encodes caharcters not allowed in path', () => { it('sorts handlers correctly', () => {
const routes = create_routes({
files: ['foo.html', 'foo.js']
});
assert.deepEqual(
routes.map(r => r.handlers),
[
[
{
type: 'route',
file: 'foo.js'
},
{
type: 'page',
file: 'foo.html'
}
]
]
)
});
it('encodes characters not allowed in path', () => {
const routes = create_routes({ const routes = create_routes({
files: [ files: [
'"', '"',
@@ -27,7 +49,7 @@ describe('create_routes', () => {
}); });
assert.deepEqual( assert.deepEqual(
routes.map(r => r.file), routes.map(r => r.handlers[0].file),
[ [
'index.html', 'index.html',
'about.html', 'about.html',
@@ -59,7 +81,7 @@ describe('create_routes', () => {
}); });
assert.deepEqual( assert.deepEqual(
routes.map(r => r.file), routes.map(r => r.handlers[0].file),
[ [
'4xx.html', '4xx.html',
'5xx.html', '5xx.html',
@@ -95,7 +117,7 @@ describe('create_routes', () => {
}); });
assert.deepEqual( assert.deepEqual(
routes.map(r => r.file), routes.map(r => r.handlers[0].file),
[ [
'4xx.html', '4xx.html',
'5xx.html', '5xx.html',
@@ -125,7 +147,7 @@ describe('create_routes', () => {
for (let i = 0; i < routes.length; i += 1) { for (let i = 0; i < routes.length; i += 1) {
const route = routes[i]; const route = routes[i];
if (params = route.exec('/post/123')) { if (params = route.exec('/post/123')) {
file = route.file; file = route.handlers[0].file;
break; break;
} }
} }
@@ -142,7 +164,7 @@ describe('create_routes', () => {
}); });
assert.deepEqual( assert.deepEqual(
routes.map(r => r.file), routes.map(r => r.handlers[0].file),
[ [
'index.html', 'index.html',
'e/f/g/h.html' 'e/f/g/h.html'
@@ -150,6 +172,17 @@ describe('create_routes', () => {
); );
}); });
it('ignores files and directories with leading dots except .well-known', () => {
const routes = create_routes({
files: ['.well-known', '.unknown']
});
assert.deepEqual(
routes.map(r => r.handlers[0].file),
['.well-known']
);
});
it('matches /foo/:bar before /:baz/qux', () => { it('matches /foo/:bar before /:baz/qux', () => {
const a = create_routes({ const a = create_routes({
files: ['foo/[bar].html', '[baz]/qux.html'] files: ['foo/[bar].html', '[baz]/qux.html']
@@ -159,12 +192,12 @@ describe('create_routes', () => {
}); });
assert.deepEqual( assert.deepEqual(
a.map(r => r.file), a.map(r => r.handlers[0].file),
['foo/[bar].html', '[baz]/qux.html'] ['foo/[bar].html', '[baz]/qux.html']
); );
assert.deepEqual( assert.deepEqual(
b.map(r => r.file), b.map(r => r.handlers[0].file),
['foo/[bar].html', '[baz]/qux.html'] ['foo/[bar].html', '[baz]/qux.html']
); );
}); });
@@ -174,13 +207,7 @@ describe('create_routes', () => {
create_routes({ create_routes({
files: ['[foo].html', '[bar]/index.html'] files: ['[foo].html', '[bar]/index.html']
}); });
}, /The \[foo\].html and \[bar\]\/index.html routes clash/); }, /The \[foo\] and \[bar\]\/index routes clash/);
assert.throws(() => {
create_routes({
files: ['foo.html', 'foo.js']
});
}, /The foo.html and foo.js routes clash/);
}); });
it('matches nested routes', () => { it('matches nested routes', () => {
@@ -203,7 +230,7 @@ describe('create_routes', () => {
}); });
assert.deepEqual( assert.deepEqual(
routes.map(r => r.file), routes.map(r => r.handlers[0].file),
['settings.html', 'settings/[submenu].html'] ['settings.html', 'settings/[submenu].html']
); );
}); });