Compare commits

..

21 Commits

Author SHA1 Message Date
Rich Harris
d1fcd07c92 -> v0.15.4 2018-08-01 08:47:41 -04:00
Rich Harris
47a6d6f662 Merge pull request #326 from lukeed/feat/ignore
Add `ignore` option
2018-08-01 08:46:49 -04:00
Luke Edwards
4b2b6440d0 fix: use more specific ignore pattern;
~> leaked into another test’s route
2018-07-31 16:54:29 -07:00
Rich Harris
fc855f30f8 -> v0.15.3 2018-07-31 15:06:47 -04:00
Rich Harris
4a75fff4ec Merge pull request #329 from sveltejs/parallel-exports
parallelize exports
2018-07-31 15:05:38 -04:00
Rich Harris
7b7b695938 Merge pull request #320 from sveltejs/gh-319
Some dev documentation
2018-07-31 14:59:57 -04:00
Rich Harris
2fca2e295f Merge pull request #328 from sveltejs/export-no-minify-js
don't minify JS when minifying HTML
2018-07-31 14:59:27 -04:00
Rich Harris
eae991d369 parallelize exports 2018-07-31 14:56:29 -04:00
Rich Harris
c2b393d3fd dont minify JS when minifying HTML 2018-07-31 14:43:58 -04:00
Luke Edwards
566addd406 add tests for opts.ignore 2018-07-29 14:17:13 -07:00
Luke Edwards
3d77dacbd6 attach ignore options to test app, w/ matching routes 2018-07-29 14:17:04 -07:00
Luke Edwards
51b4f9cbbf add opts.ignore support 2018-07-29 14:01:44 -07:00
Robert Hall
1d611be83e Using npm 2018-07-25 15:50:56 -06:00
Robert Hall
1782904994 Some dev documentation 2018-07-25 10:10:22 -06:00
Rich Harris
e3ddbfc181 Merge pull request #314 from sveltejs/fix-child-segment
fix child.segment bug
2018-07-23 17:08:25 -04:00
Rich Harris
8e3830b646 fix child.segment bug 2018-07-23 17:02:35 -04:00
Rich Harris
b28cdff233 -> v0.15.2 2018-07-23 16:38:49 -04:00
Rich Harris
7f586ff1a3 Merge pull request #313 from sveltejs/gh-312
Skip layout components where none is provided
2018-07-23 16:37:30 -04:00
Rich Harris
731d4f535c skip layout components where none is provided - fixes #312 2018-07-23 16:31:00 -04:00
Rich Harris
f8c731ca21 failing tests for #312 2018-07-23 14:31:11 -04:00
Rich Harris
39eb3be01e -> v0.15.1 2018-07-22 21:25:33 -04:00
16 changed files with 5151 additions and 85 deletions

View File

@@ -1,5 +1,22 @@
# sapper changelog
## 0.15.4
* Add `ignore` option ([#326](https://github.com/sveltejs/sapper/pull/326))
## 0.15.3
* Crawl pages in parallel when exporting ([#329](https://github.com/sveltejs/sapper/pull/329))
* Don't minify inline JS when exporting ([#328](https://github.com/sveltejs/sapper/pull/328))
## 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))

View File

@@ -31,6 +31,44 @@ npm run build
npm start
```
## Development
Pull requests are encouraged and always welcome. [Pick an issue](https://github.com/sveltejs/sapper/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc) and help us out!
To install and work on Sapper locally:
```bash
git clone git@github.com:sveltejs/sapper.git
cd sapper
npm install
npm run dev
```
### Linking to a Live Project
You can make changes locally to Sapper and test it against a local Sapper project. For a quick project that takes almost no setup, use the default [sapper-template](https://github.com/sveltejs/sapper-template) project. Instruction on setup are found in that project repository.
To link Sapper to your project, from the root of your local Sapper git checkout:
```bash
cd sapper
npm link
```
Then, to link from `sapper-template` (or any other given project):
```bash
cd sapper-template
npm link sapper
```
You should be good to test changes locally.
### Running Tests
```bash
npm run test
```
## License

4954
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "sapper",
"version": "0.15.0",
"version": "0.15.4",
"description": "Military-grade apps, engineered by Svelte",
"main": "dist/middleware.ts.js",
"bin": {
@@ -23,7 +23,7 @@
"cheerio": "^1.0.0-rc.2",
"chokidar": "^2.0.3",
"cookie": "^0.3.1",
"devalue": "^1.0.1",
"devalue": "^1.0.4",
"glob": "^7.1.2",
"html-minifier": "^3.5.16",
"mkdirp": "^0.5.1",

View File

@@ -118,9 +118,7 @@ async function execute(emitter: EventEmitter, {
}
});
for (const url of urls) {
await handle(url);
}
await Promise.all(urls.map(handle));
}
}
}

View File

@@ -8,7 +8,7 @@ export function minify_html(html: string) {
decodeEntities: true,
html5: true,
minifyCSS: true,
minifyJS: true,
minifyJS: false,
removeAttributeQuotes: true,
removeComments: true,
removeOptionalTags: true,

View File

@@ -62,7 +62,7 @@ function generate_client(
let code = `
// This file is generated by Sapper — do not edit it!
import root from '${posixify(`${path_to_routes}/${routes.root.file}`)}';
import root from '${get_file(path_to_routes, routes.root)}';
import error from '${posixify(`${path_to_routes}/_error.html`)}';
${routes.components.map(component =>
@@ -79,6 +79,8 @@ function generate_client(
pattern: ${page.pattern},
parts: [
${page.parts.map(part => {
if (part === null) return 'null';
if (part.params.length > 0) {
const props = part.params.map((param, i) => `${param}: match[${i + 1}]`);
return `{ component: ${part.component.name}, params: match => ({ ${props.join(', ')} }) }`;
@@ -124,7 +126,7 @@ function generate_server(
`import * as ${route.name} from '${posixify(`${path_to_routes}/${route.file}`)}';`),
routes.components.map(component =>
`import ${component.name} from '${get_file(path_to_routes, component)}';`),
`import root from '${posixify(`${path_to_routes}/${routes.root.file}`)}';`,
`import root from '${get_file(path_to_routes, routes.root)}';`,
`import error from '${posixify(`${path_to_routes}/_error.html`)}';`
);
@@ -150,6 +152,8 @@ function generate_server(
pattern: ${page.pattern},
parts: [
${page.parts.map(part => {
if (part === null) return 'null';
const props = [
`name: "${part.component.name}"`,
`component: ${part.component.name}`

View File

@@ -101,27 +101,21 @@ export default function create_routes(cwd = locations.routes()) {
if (item.is_dir) {
const index = path.join(dir, item.basename, '_layout.html');
const layout = fs.existsSync(index)
? {
name: `${get_slug(item.file)}__layout`,
file: `${item.file}/_layout.html`
}
: null;
if (layout) {
components.push(layout);
} else if (components.indexOf(default_layout) === -1) {
components.push(default_layout);
}
const component = fs.existsSync(index) && {
name: `${get_slug(item.file)}__layout`,
file: `${item.file}/_layout.html`
};
if (component) components.push(component);
walk(
path.join(dir, item.basename),
segments,
params,
stack.concat({
component: layout || default_layout,
params
})
component
? stack.concat({ component, params })
: stack.concat(null)
);
}

View File

@@ -73,9 +73,18 @@ interface Component {
preload: (data: any) => any | Promise<any>
}
const IGNORE = '__SAPPER__IGNORE__';
function toIgnore(uri: string, val: any) {
if (Array.isArray(val)) return val.some(x => toIgnore(uri, x));
if (val instanceof RegExp) return val.test(uri);
if (typeof val === 'function') return val(uri);
return uri.startsWith(val.charCodeAt(0) === 47 ? val : `/${val}`);
}
export default function middleware(opts: {
manifest: Manifest,
store: (req: Req) => Store,
ignore?: any,
routes?: any // legacy
}) {
if (opts.routes) {
@@ -84,12 +93,19 @@ export default function middleware(opts: {
const output = locations.dest();
const { manifest, store } = opts;
const { manifest, store, ignore } = opts;
let emitted_basepath = false;
const middleware = compose_handlers([
ignore && ((req: Req, res: ServerResponse, next: () => void) => {
req[IGNORE] = toIgnore(req.path, ignore);
next();
}),
(req: Req, res: ServerResponse, next: () => void) => {
if (req[IGNORE]) return next();
if (req.baseUrl === undefined) {
let { originalUrl } = req;
if (req.url === '/' && originalUrl[originalUrl.length - 1] !== '/') {
@@ -163,6 +179,8 @@ function serve({ prefix, pathname, cache_control }: {
: (file: string) => (cache.has(file) ? cache : cache.set(file, fs.readFileSync(path.resolve(output, file)))).get(file)
return (req: Req, res: ServerResponse, next: () => void) => {
if (req[IGNORE]) return next();
if (filter(req)) {
const type = lookup(req.path);
@@ -245,6 +263,8 @@ function get_server_route_handler(routes: ServerRoute[]) {
}
return function find_route(req: Req, res: ServerResponse, next: () => void) {
if (req[IGNORE]) return next();
for (const route of routes) {
if (route.pattern.test(req.path)) {
handle_route(route, req, res, next);
@@ -292,6 +312,8 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
let preloaded_chunks = Array.isArray(chunks.main) ? chunks.main : [chunks.main];
if (!error) {
page.parts.forEach(part => {
if (!part) return;
// using concat because it could be a string or an array. thanks webpack!
preloaded_chunks = preloaded_chunks.concat(chunks[part.name]);
});
@@ -366,6 +388,8 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
: {};
Promise.all([root_preloaded].concat(page.parts.map(part => {
if (!part) return null;
return part.component.preload
? part.component.preload.call(preload_context, {
path: req.path,
@@ -411,23 +435,28 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
const data = Object.assign({}, props, preloaded[0], {
params: {},
child: {}
child: {
segment: segments[0]
}
});
let level = data.child;
for (let i = 0; i < page.parts.length; i += 1) {
const part = page.parts[i];
if (!part) continue;
const get_params = part.params || (() => ({}));
Object.assign(level, {
segment: segments[i],
component: part.component,
props: Object.assign({}, props, {
params: get_params(match)
}, preloaded[i + 1])
});
level.props.child = <Props["child"]>{};
level.props.child = <Props["child"]>{
segment: segments[i + 1]
};
level = level.props.child;
}
@@ -443,9 +472,9 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
let inline_script = `__SAPPER__={${[
error && `error:1`,
`baseUrl: "${req.baseUrl}"`,
serialized.preloaded && `preloaded: ${serialized.preloaded}`,
serialized.store && `store: ${serialized.store}`
`baseUrl:"${req.baseUrl}"`,
serialized.preloaded && `preloaded:${serialized.preloaded}`,
serialized.store && `store:${serialized.store}`
].filter(Boolean).join(',')}};`;
const has_service_worker = fs.existsSync(path.join(locations.dest(), 'service-worker.js'));
@@ -485,7 +514,9 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
});
}
return function find_route(req: Req, res: ServerResponse) {
return function find_route(req: Req, res: ServerResponse, next: () => void) {
if (req[IGNORE]) return next();
if (!server_routes.some(route => route.pattern.test(req.path))) {
for (const page of pages) {
if (page.pattern.test(req.path)) {

View File

@@ -77,14 +77,14 @@ function select_route(url: URL): Target {
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 (root) {
// first, clear out highest-level root component
let level = data.child;
for (let i = 0; i < changed_from; i += 1) {
if (i === changed_from) break;
for (let i = 0; i < nullable_depth; i += 1) {
if (i === nullable_depth) break;
level = level.props.child;
}
@@ -134,7 +134,7 @@ let root_data: any;
function prepare_page(target: Target): Promise<{
redirect?: Redirect;
data?: any;
changed_from?: number;
nullable_depth?: number;
}> {
if (root) {
root.set({ preloading: true });
@@ -179,6 +179,7 @@ function prepare_page(target: Target): Promise<{
return Promise.all(page.parts.map(async (part, i) => {
if (i < changed_from) return null;
if (!part) return null;
const { default: Component } = await part.component();
const req = {
@@ -231,33 +232,42 @@ function prepare_page(target: Target): Promise<{
const data = {
path,
preloading: false,
child: Object.assign({}, root_props.child)
child: Object.assign({}, root_props.child, {
segment: segments[0]
})
};
if (changed(query, root_props.query)) data.query = query;
if (changed(params, root_props.params)) data.params = params;
let level = data.child;
let nullable_depth = 0;
for (let i = 0; i < page.parts.length; i += 1) {
const part = page.parts[i];
if (!part) continue;
const get_params = part.params || (() => ({}));
if (i < changed_from) {
level.props.path = path;
level.props.query = query;
level.props.child = Object.assign({}, level.props.child);
nullable_depth += 1;
} else {
level.segment = new_segments[i];
level.component = results[i].Component;
level.props = Object.assign({}, level.props, props, {
params: get_params(target.match),
}, results[i].preloaded);
level.props.child = {};
}
level = level.props.child;
level.segment = segments[i + 1];
}
return { data, changed_from };
return { data, nullable_depth };
});
}
@@ -282,12 +292,12 @@ async function navigate(target: Target, id: number): Promise<any> {
prefetching = null;
const token = current_token = {};
const { redirect, data, changed_from } = await loaded;
const { redirect, data, nullable_depth } = await loaded;
if (redirect) {
await goto(redirect.location, { replaceState: true });
} else {
render(data, changed_from, scroll_history[id], token);
render(data, nullable_depth, scroll_history[id], token);
document.activeElement.blur();
}
}
@@ -353,7 +363,7 @@ function handle_popstate(event: PopStateEvent) {
let prefetching: {
href: string;
promise: Promise<{ redirect?: Redirect, data?: any, changed_from?: number }>;
promise: Promise<{ redirect?: Redirect, data?: any, nullable_depth?: number }>;
} = null;
export function prefetch(href: string) {

View File

@@ -91,8 +91,14 @@ const middlewares = [
return new Store({
title: 'Stored title'
});
}
})
},
ignore: [
/foobar/i,
'/buzz',
'fizz',
x => x === '/hello'
]
}),
];
if (BASEPATH) {
@@ -101,4 +107,8 @@ if (BASEPATH) {
app.use(...middlewares);
}
app.listen(PORT);
['foobar', 'buzz', 'fizzer', 'hello'].forEach(uri => {
app.get('/'+uri, (req, res) => res.end(uri));
});
app.listen(PORT);

View File

@@ -1,6 +1,8 @@
<span>y: {segment} {count}</span>
<svelte:component this={child.component} {...child.props}/>
<span>child segment: {child.segment}</span>
<script>
import counts from '../_counts.js';

View File

@@ -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>

View File

@@ -477,6 +477,42 @@ function run({ mode, basepath = '' }) {
});
});
// Ignores are meant for top-level escape.
// ~> Sapper **should** own the entire {basepath} when designated.
if (!basepath) {
it('respects `options.ignore` values (RegExp)', () => {
return nightmare.goto(`${base}/foobar`)
.evaluate(() => document.documentElement.textContent)
.then(text => {
assert.equal(text, 'foobar');
});
});
it('respects `options.ignore` values (String #1)', () => {
return nightmare.goto(`${base}/buzz`)
.evaluate(() => document.documentElement.textContent)
.then(text => {
assert.equal(text, 'buzz');
});
});
it('respects `options.ignore` values (String #2)', () => {
return nightmare.goto(`${base}/fizzer`)
.evaluate(() => document.documentElement.textContent)
.then(text => {
assert.equal(text, 'fizzer');
});
});
it('respects `options.ignore` values (Function)', () => {
return nightmare.goto(`${base}/hello`)
.evaluate(() => document.documentElement.textContent)
.then(text => {
assert.equal(text, 'hello');
});
});
}
it('does not attempt client-side navigation to server routes', () => {
return nightmare.goto(`${base}/blog/how-is-sapper-different-from-next`)
.init()
@@ -629,9 +665,9 @@ function run({ mode, basepath = '' }) {
.evaluate(() => document.querySelector('#sapper').textContent)
.then(text => {
assert.deepEqual(text.split('\n').filter(Boolean), [
'x: foo 1',
'y: bar 1',
'z: baz 1'
'z: baz 1',
'child segment: baz'
]);
return nightmare.click(`a`)
@@ -642,9 +678,9 @@ function run({ mode, basepath = '' }) {
})
.then(text => {
assert.deepEqual(text.split('\n').filter(Boolean), [
'x: foo 1',
'y: bar 1',
'z: qux 2'
'z: qux 2',
'child segment: qux'
]);
});
});

View File

@@ -2,13 +2,6 @@ const path = require('path');
const assert = require('assert');
const { create_routes } = require('../../../dist/core.ts.js');
const _default_layout = {
default: true,
name: '_default_layout',
file: null
};
describe('create_routes', () => {
it('creates routes', () => {
const { components, pages, server_routes } = create_routes(path.join(__dirname, 'samples/basic'));
@@ -21,7 +14,6 @@ describe('create_routes', () => {
assert.deepEqual(components, [
index,
about,
_default_layout,
blog,
blog_$slug
]);
@@ -44,7 +36,7 @@ describe('create_routes', () => {
{
pattern: /^\/blog\/?$/,
parts: [
{ component: _default_layout, params: [] },
null,
{ component: blog, params: [] }
]
},
@@ -52,7 +44,7 @@ describe('create_routes', () => {
{
pattern: /^\/blog\/([^\/]+?)\/?$/,
parts: [
{ component: _default_layout, params: [] },
null,
{ component: blog_$slug, params: ['slug'] }
]
}
@@ -110,15 +102,15 @@ describe('create_routes', () => {
it('sorts routes correctly', () => {
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)), [
['index.html'],
['about.html'],
[_default_layout.file, 'post/index.html'],
[_default_layout.file, 'post/bar.html'],
[_default_layout.file, 'post/foo.html'],
[_default_layout.file, 'post/f[xx].html'],
[_default_layout.file, 'post/[id([0-9-a-z]{3,})].html'],
[_default_layout.file, 'post/[id].html'],
[null, 'post/index.html'],
[null, 'post/bar.html'],
[null, 'post/foo.html'],
[null, 'post/f[xx].html'],
[null, 'post/[id([0-9-a-z]{3,})].html'],
[null, 'post/[id].html'],
['[wildcard].html']
]);
});