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
40 changed files with 398 additions and 7818 deletions

View File

@@ -18,4 +18,4 @@ addons:
install:
- export DISPLAY=':99.0'
- Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
- npm ci || npm i
- npm install

View File

@@ -1,32 +1,5 @@
# sapper changelog
## 0.15.5
* Faster `export` with more explanatory output ([#335](https://github.com/sveltejs/sapper/pull/335))
* Only blur `activeElement` if it exists ([#332](https://github.com/sveltejs/sapper/issues/332))
* Don't emit `client_info.json` or `server_info.json` ([#318](https://github.com/sveltejs/sapper/issues/318))
## 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))
## 0.14.2
* Prevent unsafe replacements ([#307](https://github.com/sveltejs/sapper/pull/307))

View File

@@ -31,44 +31,6 @@ 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

View File

@@ -14,7 +14,7 @@ environment:
install:
- ps: Install-Product node $env:nodejs_version
- npm ci
- npm install
test_script:
- node --version && npm --version

7172
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "sapper",
"version": "0.15.5",
"version": "0.14.2",
"description": "Military-grade apps, engineered by Svelte",
"main": "dist/middleware.ts.js",
"bin": {
@@ -12,7 +12,6 @@
"runtime",
"webpack",
"sapper",
"components",
"dist"
],
"directories": {
@@ -23,12 +22,12 @@
"cheerio": "^1.0.0-rc.2",
"chokidar": "^2.0.3",
"cookie": "^0.3.1",
"devalue": "^1.0.4",
"devalue": "^1.0.1",
"glob": "^7.1.2",
"html-minifier": "^3.5.16",
"mkdirp": "^0.5.1",
"node-fetch": "^2.1.1",
"port-authority": "^1.0.5",
"port-authority": "^1.0.2",
"pretty-bytes": "^5.0.0",
"pretty-ms": "^3.1.0",
"require-relative": "^0.8.7",
@@ -68,7 +67,7 @@
"cy:open": "cypress open",
"test": "mocha --opts mocha.opts",
"pretest": "npm run build",
"build": "rm -rf dist && rollup -c",
"build": "rollup -c",
"dev": "rollup -cw",
"prepublishOnly": "npm test",
"update_mime_types": "curl http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types | grep -e \"^[^#]\" > src/middleware/mime-types.md"

View File

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

View File

@@ -4,7 +4,8 @@ import mkdirp from 'mkdirp';
import rimraf from 'rimraf';
import { EventEmitter } from 'events';
import { minify_html } from './utils/minify_html';
import { create_compilers, create_main_manifests, create_routes, create_serviceworker_manifest } from '../core';
import { create_compilers, create_main_manifests, create_routes, create_serviceworker_manifest } from '../core'
import { locations } from '../config';
import * as events from './interfaces';
export function build(opts: {}) {
@@ -61,6 +62,7 @@ async function execute(emitter: EventEmitter, {
});
const client_info = client_stats.toJson();
fs.writeFileSync(path.join(dest, 'client_info.json'), JSON.stringify(client_info));
fs.writeFileSync(path.join(dest, 'client_assets.json'), JSON.stringify(client_info.assetsByChunkName));
const server_stats = await compile(server);

View File

@@ -9,7 +9,6 @@ import format_messages from 'webpack-format-messages';
import { locations } from '../config';
import { EventEmitter } from 'events';
import { create_routes, create_main_manifests, create_compilers, create_serviceworker_manifest } from '../core';
import Deferred from './utils/Deferred';
import * as events from './interfaces';
export function dev(opts) {
@@ -169,6 +168,8 @@ class Watcher extends EventEmitter {
},
result: info => {
fs.writeFileSync(path.join(dest, 'server_info.json'), JSON.stringify(info, null, ' '));
this.deferreds.client.promise.then(() => {
const restart = () => {
log = '';
@@ -251,6 +252,7 @@ class Watcher extends EventEmitter {
},
result: info => {
fs.writeFileSync(path.join(dest, 'client_info.json'), JSON.stringify(info));
fs.writeFileSync(path.join(dest, 'client_assets.json'), JSON.stringify(info.assetsByChunkName, null, ' '));
this.deferreds.client.fulfil();
@@ -399,6 +401,19 @@ function mungeWebpackError(message: string, duplicate: boolean) {
};
}
class Deferred {
promise: Promise<any>;
fulfil: (value?: any) => void;
reject: (error: Error) => void;
constructor() {
this.promise = new Promise((fulfil, reject) => {
this.fulfil = fulfil;
this.reject = reject;
});
}
}
const INTERVAL = 10000;
class DevServer {

View File

@@ -7,7 +7,7 @@ import fetch from 'node-fetch';
import * as ports from 'port-authority';
import { EventEmitter } from 'events';
import { minify_html } from './utils/minify_html';
import Deferred from './utils/Deferred';
import { locations } from '../config';
import * as events from './interfaces';
export function exporter(opts: {}) {
@@ -52,10 +52,6 @@ async function execute(emitter: EventEmitter, {
const origin = `http://localhost:${port}`;
emitter.emit('info', {
message: `Crawling ${origin}`
});
const proc = child_process.fork(path.resolve(`${build}/server.js`), [], {
cwd: process.cwd(),
env: Object.assign({
@@ -68,21 +64,11 @@ async function execute(emitter: EventEmitter, {
const seen = new Set();
const saved = new Set();
const deferreds = new Map();
function get_deferred(pathname: string) {
if (!deferreds.has(pathname)) {
deferreds.set(pathname, new Deferred()) ;
}
return deferreds.get(pathname);
}
proc.on('message', message => {
if (!message.__sapper__ || message.event !== 'file') return;
const pathname = new URL(message.url, origin).pathname;
let file = pathname.slice(1);
let file = new URL(message.url, origin).pathname.slice(1);
let { body } = message;
if (saved.has(file)) return;
@@ -97,26 +83,24 @@ async function execute(emitter: EventEmitter, {
emitter.emit('file', <events.FileEvent>{
file,
size: body.length,
status: message.status
size: body.length
});
sander.writeFileSync(export_dir, file, body);
get_deferred(pathname).fulfil();
});
async function handle(url: URL) {
const pathname = url.pathname || '/';
if (seen.has(pathname)) return;
seen.add(pathname);
const deferred = get_deferred(pathname);
const r = await fetch(url.href);
const range = ~~(r.status / 100);
if (range >= 4) {
emitter.emit('failure', <events.FailureEvent>{
status: r.status,
pathname: url.pathname
});
return;
}
if (range === 2) {
if (r.headers.get('Content-Type') === 'text/html') {
const body = await r.text();
@@ -127,14 +111,18 @@ async function execute(emitter: EventEmitter, {
$('a[href]').each((i: number, $a) => {
const url = new URL($a.attribs.href, base.href);
if (url.origin === origin) urls.push(url);
if (url.origin === origin && !seen.has(url.pathname)) {
seen.add(url.pathname);
urls.push(url);
}
});
await Promise.all(urls.map(handle));
for (const url of urls) {
await handle(url);
}
}
}
await deferred.promise;
}
return ports.wait(port)

View File

@@ -1,12 +0,0 @@
export default class Deferred {
promise: Promise<any>;
fulfil: (value?: any) => void;
reject: (error: Error) => void;
constructor() {
this.promise = new Promise((fulfil, reject) => {
this.fulfil = fulfil;
this.reject = reject;
});
}
}

View File

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

View File

@@ -1,8 +1,11 @@
import * as fs from 'fs';
import * as path from 'path';
import * as child_process from 'child_process';
import sade from 'sade';
import * as colors from 'ansi-colors';
import prettyMs from 'pretty-ms';
// import upgrade from './cli/upgrade';
import * as ports from 'port-authority';
import * as pkg from '../package.json';
const prog = sade('sapper').version(pkg.version);
@@ -62,22 +65,19 @@ prog.command('start [dir]')
prog.command('export [dest]')
.describe('Export your app as static files (if possible)')
.option('--build', '(Re)build app before exporting', true)
.option('--build-dir', 'Specify a custom temporary build directory', '.sapper/prod')
.option('--basepath', 'Specify a base path')
.action(async (dest = 'export', opts: { build: boolean, 'build-dir': string, basepath?: string }) => {
.action(async (dest = 'export', opts: { basepath?: string }) => {
console.log(`> Building...`);
process.env.NODE_ENV = 'production';
process.env.SAPPER_DEST = opts['build-dir'];
process.env.SAPPER_DEST = '.sapper/.export';
const start = Date.now();
try {
if (opts.build) {
console.log(`> Building...`);
const { build } = await import('./cli/build');
await build();
console.error(`\n> Built in ${elapsed(start)}`);
}
const { build } = await import('./cli/build');
await build();
console.error(`\n> Built in ${elapsed(start)}. Crawling site...`);
const { exporter } = await import('./cli/export');
await exporter(dest, opts);

View File

@@ -3,11 +3,6 @@ import * as colors from 'ansi-colors';
import prettyBytes from 'pretty-bytes';
import { locations } from '../config';
function left_pad(str: string, len: number) {
while (str.length < len) str = ` ${str}`;
return str;
}
export function exporter(export_dir: string, { basepath = '' }) {
return new Promise((fulfil, reject) => {
try {
@@ -18,19 +13,11 @@ export function exporter(export_dir: string, { basepath = '' }) {
});
emitter.on('file', event => {
const pb = prettyBytes(event.size);
const size_color = event.size > 150000 ? colors.bold.red : event.size > 50000 ? colors.bold.yellow : colors.bold.gray;
const size_label = size_color(left_pad(prettyBytes(event.size), 10));
const file_label = event.status === 200
? event.file
: colors.bold[event.status >= 400 ? 'red' : 'yellow'](`(${event.status}) ${event.file}`);
console.log(`${size_label} ${file_label}`);
console.log(`${colors.bold.cyan(event.file)} ${colors.gray(`(${prettyBytes(event.size)})`)}`);
});
emitter.on('info', event => {
console.log(colors.bold.cyan(`> ${event.message}`));
emitter.on('failure', event => {
console.log(`${colors.red(`> Received ${event.status} response when fetching ${event.pathname}`)}`);
});
emitter.on('error', event => {

View File

@@ -6,5 +6,5 @@ export const locations = {
base: () => path.resolve(process.env.SAPPER_BASE || ''),
app: () => path.resolve(process.env.SAPPER_BASE || '', process.env.SAPPER_APP || 'app'),
routes: () => path.resolve(process.env.SAPPER_BASE || '', process.env.SAPPER_ROUTES || 'routes'),
dest: () => path.resolve(process.env.SAPPER_BASE || '', process.env.SAPPER_DEST || `.sapper/${dev() ? 'dev' : 'prod'}`)
dest: () => path.resolve(process.env.SAPPER_BASE || '', process.env.SAPPER_DEST || '.sapper')
};

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 server_manifest = generate_server(routes, path_to_routes);
write_if_changed(
`${locations.app()}/manifest/default-layout.html`,
`<svelte:component this={child.component} {...child.props}/>`
);
write_if_changed(`${locations.app()}/manifest/client.js`, client_manifest);
write_if_changed(`${locations.app()}/manifest/server.js`, server_manifest);
}
@@ -48,7 +44,7 @@ function right_pad(str: string, len: number) {
}
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,
dev_port?: number
) {
@@ -62,15 +58,15 @@ function generate_client(
let code = `
// 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`)}';
${routes.components.map(component =>
`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')}
export const manifest = {
export const routes = {
ignore: [${server_routes_to_ignore.map(route => route.pattern).join(', ')}],
pages: [
@@ -79,8 +75,6 @@ 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(', ')} }) }`;
@@ -95,10 +89,7 @@ function generate_client(
root,
error
};
// this is included for legacy reasons
export const routes = {};`.replace(/^\t\t/gm, '').trim();
};`.replace(/^\t\t/gm, '').trim();
if (dev()) {
const sapper_dev_client = posixify(
@@ -118,15 +109,15 @@ function generate_client(
}
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
) {
const imports = [].concat(
routes.server_routes.map(route =>
`import * as ${route.name} from '${posixify(`${path_to_routes}/${route.file}`)}';`),
routes.components.map(component =>
`import ${component.name} from '${get_file(path_to_routes, component)}';`),
`import root from '${get_file(path_to_routes, routes.root)}';`,
`import ${component.name} from '${posixify(`${path_to_routes}/${component.file}`)}';`),
`import root from '${posixify(`${path_to_routes}/index.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!
${imports.join('\n')}
export const manifest = {
export const routes = {
server_routes: [
${routes.server_routes.map(route => `{
// ${route.file}
@@ -152,8 +143,6 @@ 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}`
@@ -173,18 +162,7 @@ function generate_server(
root,
error
};
// this is included for legacy reasons
export const routes = {};`.replace(/^\t\t/gm, '').trim();
};`.replace(/^\t\t/gm, '').trim();
return code;
}
function get_file(path_to_routes: string, component: PageComponent) {
if (component.default) {
return `./default-layout.html`;
}
return posixify(`${path_to_routes}/${component.file}`);
}

View File

@@ -4,22 +4,11 @@ import { locations } from '../config';
import { Page, PageComponent, ServerRoute } from '../interfaces';
import { posixify } from './utils';
const default_layout_file = posixify(path.resolve(
__dirname,
'../components/default-layout.html'
));
export default function create_routes(cwd = locations.routes()) {
const components: PageComponent[] = [];
const pages: Page[] = [];
const server_routes: ServerRoute[] = [];
const default_layout: PageComponent = {
default: true,
name: '_default_layout',
file: null
};
function walk(
dir: string,
parent_segments: Part[][],
@@ -65,7 +54,9 @@ export default function create_routes(cwd = locations.routes()) {
.sort(comparator);
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.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));
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) && {
name: `${get_slug(item.file)}__layout`,
file: `${item.file}/_layout.html`
};
if (component) components.push(component);
if (component) {
components.push(component);
}
walk(
path.join(dir, item.basename),
segments,
params,
component
? stack.concat({ component, params })
: stack.concat(null)
stack.concat({
component: component || {
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) {
const component = {
name: get_slug(item.file),
name: `page_${get_slug(item.file)}`,
file: item.file
};
@@ -131,7 +152,7 @@ export default function create_routes(cwd = locations.routes()) {
});
components.push(component);
if (item.basename === 'index.html') {
if (item.basename === '_default.html') {
pages.push({
pattern: get_pattern(parent_segments),
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, [], [], []);
// check for clashes
const seen_pages: Map<string, Page> = new Map();
pages.forEach(page => {
// check for missing intermediate index.html files
let i = page.parts.length;
const last_part = page.parts[i - 1];
while (i--) {
const part = page.parts[i];
if (part.component.missing) {
throw new Error(`Missing ${part.component.file}, which is required for ${last_part.component.file} to be valid`);
}
}
// check for clashes
const pattern = page.pattern.toString();
if (seen_pages.has(pattern)) {
const file = page.parts.pop().component.file;
@@ -192,7 +215,6 @@ export default function create_routes(cwd = locations.routes()) {
});
return {
root,
components,
pages,
server_routes
@@ -206,11 +228,9 @@ type Part = {
};
function comparator(
a: { basename: string, parts: Part[], file: string, is_index: boolean },
b: { 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_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);
for (let i = 0; i < max; i += 1) {

View File

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

View File

@@ -26,7 +26,7 @@ type Page = {
}>
};
type Manifest = {
type RouteObject = {
server_routes: ServerRoute[];
pages: Page[];
root: Component;
@@ -39,20 +39,6 @@ type Store = {
get: () => any
};
type Props = {
path: string;
query: Record<string, string>;
params: Record<string, string>;
error?: { message: string };
status?: number;
child: {
segment: string;
component: Component;
props: Props;
};
[key: string]: any;
};
interface Req extends ClientRequest {
url: string;
baseUrl: string;
@@ -73,39 +59,16 @@ 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
export default function middleware({ routes, store }: {
routes: RouteObject,
store: (req: Req) => Store
}) {
if (opts.routes) {
throw new Error(`As of Sapper 0.15, opts.routes should be opts.manifest`);
}
const output = locations.dest();
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] !== '/') {
@@ -154,8 +117,8 @@ export default function middleware(opts: {
cache_control: 'max-age=31536000'
}),
get_server_route_handler(manifest.server_routes),
get_page_handler(manifest, store)
get_server_route_handler(routes.server_routes),
get_page_handler(routes, store)
].filter(Boolean));
return middleware;
@@ -179,8 +142,6 @@ 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);
@@ -263,8 +224,6 @@ 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);
@@ -276,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 get_chunks = dev()
@@ -287,22 +246,17 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
? () => fs.readFileSync(`${locations.app()}/template.html`, 'utf-8')
: (str => () => str)(fs.readFileSync(`${locations.dest()}/template.html`, 'utf-8'));
const { server_routes, pages } = manifest;
const error_route = manifest.error;
function handle_error(req: Req, res: ServerResponse, statusCode: number, error: Error | string) {
handle_page({
pattern: null,
parts: [
{ name: null, component: error_route }
]
}, req, res, statusCode, error);
}
const { server_routes, pages } = routes;
const error_route = routes.error;
function handle_page(page: Page, req: Req, res: ServerResponse, status = 200, error: Error | string = null) {
const get_params = page.parts[page.parts.length - 1].params || (() => ({}));
const match = error ? null : page.pattern.exec(req.path);
req.params = error
? {}
: get_params(match);
const chunks: Record<string, string | string[]> = get_chunks();
res.setHeader('Content-Type', 'text/html');
@@ -312,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];
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]);
});
@@ -327,154 +279,120 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
res.setHeader('Link', link);
const store = store_getter ? store_getter(req) : null;
const props = { query: req.query, path: req.path };
if (error) {
props.error = error instanceof Error ? error : { message: error };
props.status = status;
}
let redirect: { statusCode: number, location: string };
let preload_error: { statusCode: number, message: Error | string };
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;
Promise.all(page.parts.map(part => {
return part.component.preload
? part.component.preload.call(preload_context, {
path: req.path,
query: req.query,
params: part.params ? part.params(match) : {}
})
? part.component.preload.call({
redirect: (statusCode: number, location: string) => {
if (redirect && (redirect.statusCode !== statusCode || redirect.location !== location)) {
throw new Error(`Conflicting redirects`);
}
redirect = { statusCode, location };
},
error: (statusCode: number, message: Error | string) => {
preload_error = { statusCode, message };
},
fetch: (url: string, opts?: any) => {
const parsed = new URL(url, `http://127.0.0.1:${process.env.PORT}${req.baseUrl ? req.baseUrl + '/' :''}`);
if (opts) {
opts = Object.assign({}, opts);
const include_cookies = (
opts.credentials === 'include' ||
opts.credentials === 'same-origin' && parsed.origin === `http://127.0.0.1:${process.env.PORT}`
);
if (include_cookies) {
const cookies: Record<string, string> = {};
if (!opts.headers) opts.headers = {};
const str = []
.concat(
cookie.parse(req.headers.cookie || ''),
cookie.parse(opts.headers.cookie || ''),
cookie.parse(res.getHeader('Set-Cookie') || '')
)
.map(cookie => {
return Object.keys(cookie)
.map(name => `${name}=${encodeURIComponent(cookie[name])}`)
.join('; ');
})
.filter(Boolean)
.join(', ');
opts.headers.cookie = str;
}
}
return fetch(parsed.href, opts);
},
store
}, req)
: {};
}))).catch(err => {
})).catch(err => {
preload_error = { statusCode: 500, message: err };
return []; // appease TypeScript
}).then(preloaded => {
if (redirect) {
const location = `${req.baseUrl}/${redirect.location}`;
res.statusCode = redirect.statusCode;
res.setHeader('Location', location);
res.setHeader('Location', `${req.baseUrl}/${redirect.location}`);
res.end();
if (process.send) {
process.send({
__sapper__: true,
event: 'file',
url: req.url,
method: req.method,
status: redirect.statusCode,
type: 'text/html',
body: `<script>window.location.href = "${location}"</script>`
});
}
return;
}
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;
}
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())
};
const segments = req.path.split('/').filter(Boolean);
const props: Props = {
path: req.path,
query: req.query,
params: {},
child: null
};
if (error) {
props.error = error instanceof Error ? error : { message: error };
props.status = status;
}
const data = Object.assign({}, props, preloaded[0], {
params: {},
child: {
segment: segments[0]
}
const data = Object.assign({}, props, { params: req.params }, {
child: {}
});
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])
params: get_params(match),
query: req.query
}, preloaded[i])
});
level.props.child = <Props["child"]>{
segment: segments[i + 1]
};
level.props.child = {};
level = level.props.child;
}
const { html, head, css } = manifest.root.render(data, {
const { html, head, css } = routes.root.render(data, {
store
});
@@ -485,10 +403,9 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
.join('');
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'));
@@ -512,25 +429,18 @@ function get_page_handler(manifest: Manifest, store_getter: (req: Req) => Store)
event: 'file',
url: req.url,
method: req.method,
status,
status: 200,
type: 'text/html',
body
});
}
}).catch(err => {
if (error) {
// we encountered an error while rendering the error page — oops
res.statusCode = 500;
res.end(`<pre>${escape_html(err.message)}</pre>`);
} else {
handle_error(req, res, 500, err);
}
res.statusCode = 500;
res.end(err.message);
});
}
return function find_route(req: Req, res: ServerResponse, next: () => void) {
if (req[IGNORE]) return next();
return function find_route(req: Req, res: ServerResponse) {
if (!server_routes.some(route => route.pattern.test(req.path))) {
for (const page of pages) {
if (page.pattern.test(req.path)) {
@@ -540,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');
};
}
@@ -571,15 +486,3 @@ function try_serialize(data: any) {
return null;
}
}
function escape_html(html: string) {
const chars: Record<string, string> = {
'"' : 'quot',
"'": '#39',
'&': 'amp',
'<' : 'lt',
'>' : 'gt'
};
return html.replace(/["'&<>]/g, c => `&${chars[c]};`);
}

View File

@@ -1,12 +1,12 @@
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__;
export let root: Component;
let target: Node;
let store: Store;
let manifest: Manifest;
let routes: Routes;
let segments: string[] = [];
type RootProps = {
@@ -56,10 +56,10 @@ function select_route(url: URL): Target {
const path = url.pathname.slice(initial_data.baseUrl.length);
// avoid accidental clashes between server routes and pages
if (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) {
const page = manifest.pages[i];
for (let i = 0; i < routes.pages.length; i += 1) {
const page = routes.pages[i];
const match = page.pattern.exec(path);
if (match) {
@@ -77,14 +77,14 @@ function select_route(url: URL): Target {
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 (root) {
// first, clear out highest-level root component
let level = data.child;
for (let i = 0; i < nullable_depth; i += 1) {
if (i === nullable_depth) break;
for (let i = 0; i < changed_from; i += 1) {
if (i === changed_from) break;
level = level.props.child;
}
@@ -106,9 +106,7 @@ function render(data: any, nullable_depth: number, scroll: ScrollPosition, token
detach(end);
}
Object.assign(data, root_data);
root = new manifest.root({
root = new routes.root({
target,
data,
store,
@@ -128,13 +126,10 @@ function changed(a: Record<string, string | true>, b: Record<string, string | tr
return JSON.stringify(a) !== JSON.stringify(b);
}
let root_preload: Promise<any>;
let root_data: any;
function prepare_page(target: Target): Promise<{
redirect?: Redirect;
data?: any;
nullable_depth?: number;
changed_from?: number;
}> {
if (root) {
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) => {
if (i < changed_from) return null;
if (!part) return null;
const { default: Component } = await part.component();
const req = {
@@ -188,17 +172,15 @@ function prepare_page(target: Target): Promise<{
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) : {}
: initial_data.preloaded[i + 1];
: initial_data.preloaded[i];
return { Component, preloaded };
})).catch(err => {
error = { statusCode: 500, message: err };
return [];
}).then(async results => {
if (!root_data) root_data = await root_preload;
}).then(results => {
if (redirect) {
return { redirect };
}
@@ -221,7 +203,7 @@ function prepare_page(target: Target): Promise<{
data: Object.assign({}, props, {
preloading: false,
child: {
component: manifest.error,
component: routes.error,
props
}
})
@@ -232,42 +214,33 @@ function prepare_page(target: Target): Promise<{
const data = {
path,
preloading: false,
child: Object.assign({}, root_props.child, {
segment: segments[0]
})
child: Object.assign({}, root_props.child)
};
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, nullable_depth };
return { data, changed_from };
});
}
@@ -292,13 +265,13 @@ async function navigate(target: Target, id: number): Promise<any> {
prefetching = null;
const token = current_token = {};
const { redirect, data, nullable_depth } = await loaded;
const { redirect, data, changed_from } = await loaded;
if (redirect) {
await goto(redirect.location, { replaceState: true });
} else {
render(data, nullable_depth, scroll_history[id], token);
if (document.activeElement) document.activeElement.blur();
render(data, changed_from, scroll_history[id], token);
document.activeElement.blur();
}
}
@@ -363,7 +336,7 @@ function handle_popstate(event: PopStateEvent) {
let prefetching: {
href: string;
promise: Promise<{ redirect?: Redirect, data?: any, nullable_depth?: number }>;
promise: Promise<{ redirect?: Redirect, data?: any, changed_from?: number }>;
} = null;
export function prefetch(href: string) {
@@ -396,23 +369,13 @@ function trigger_prefetch(event: MouseEvent | TouchEvent) {
let inited: boolean;
let ready = false;
export function init(opts: {
App: ComponentConstructor,
target: Node,
manifest: Manifest,
store?: (data: any) => Store,
routes?: any // legacy
}) {
export function init(opts: { App: ComponentConstructor, target: Node, routes: Routes, store?: (data: any) => Store }) {
if (opts instanceof HTMLElement) {
throw new Error(`The signature of init(...) has changed — see https://sapper.svelte.technology/guide#0-11-to-0-12 for more information`);
}
if (opts.routes) {
throw new Error(`As of Sapper 0.15, opts.routes should be opts.manifest`);
}
target = opts.target;
manifest = opts.manifest;
routes = opts.routes;
if (opts && opts.store) {
store = opts.store(initial_data.store);
@@ -439,10 +402,8 @@ export function init(opts: {
history.replaceState({ id: uid }, '', href);
if (!initial_data.error) {
const target = select_route(new URL(window.location.href));
if (target) return navigate(target, uid);
}
const target = select_route(new URL(window.location.href));
if (target) return navigate(target, uid);
});
}
@@ -462,9 +423,9 @@ export function goto(href: string, opts = { replaceState: false }) {
}
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 => {
if (!pathnames) return true;
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[];
root: ComponentConstructor;
error: () => Promise<{ default: ComponentConstructor }>;

View File

@@ -1,11 +1,11 @@
import { init, prefetchRoutes } from '../../../runtime.js';
import { Store } from 'svelte/store.js';
import { manifest } from './manifest/client.js';
import { routes } from './manifest/client.js';
window.init = () => {
return init({
target: document.querySelector('#sapper'),
manifest,
routes,
store: data => new Store(data)
});
};

View File

@@ -4,7 +4,7 @@ import express from 'express';
import serve from 'serve-static';
import sapper from '../../../dist/middleware.ts.js';
import { Store } from 'svelte/store.js';
import { manifest } from './manifest/server.js';
import { routes } from './manifest/server.js';
let pending;
let ended;
@@ -86,19 +86,13 @@ const middlewares = [
},
sapper({
manifest,
routes,
store: () => {
return new Store({
title: 'Stored title'
});
},
ignore: [
/foobar/i,
'/buzz',
'fizz',
x => x === '/hello'
]
}),
}
})
];
if (BASEPATH) {
@@ -107,8 +101,4 @@ if (BASEPATH) {
app.use(...middlewares);
}
['foobar', 'buzz', 'fizzer', 'hello'].forEach(uri => {
app.get('/'+uri, (req, res) => res.end(uri));
});
app.listen(PORT);
app.listen(PORT);

View File

@@ -1,8 +1,6 @@
<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

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

View File

@@ -1,26 +1,6 @@
<svelte:head>
<title>Sapper project template</title>
</svelte:head>
{#if preloading}
<progress class='preloading-progress' value=0.5/>
{/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.
const expectedClientRegexes = [
/client\/[^/]+\/main(\.\d+)?\.js/,
/client\/[^/]+\/index(\.\d+)?\.js/,
/client\/[^/]+\/about(\.\d+)?\.js/,
/client\/[^/]+\/blog_\$slug(\.\d+)?\.js/,
/client\/[^/]+\/blog(\.\d+)?\.js/,
/client\/[^/]+\/slow\$45preload(\.\d+)?\.js/,
/client\/[^/]+\/page_index(\.\d+)?\.js/,
/client\/[^/]+\/page_about(\.\d+)?\.js/,
/client\/[^/]+\/page_blog_\$slug(\.\d+)?\.js/,
/client\/[^/]+\/page_blog(\.\d+)?\.js/,
/client\/[^/]+\/page_show\$45url(\.\d+)?\.js/,
/client\/[^/]+\/page_slow\$45preload(\.\d+)?\.js/,
];
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', () => {
return nightmare
.goto(`${base}/delete-test`)
@@ -477,42 +488,6 @@ 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()
@@ -665,9 +640,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',
'child segment: baz'
'z: baz 1'
]);
return nightmare.click(`a`)
@@ -678,9 +653,9 @@ function run({ mode, basepath = '' }) {
})
.then(text => {
assert.deepEqual(text.split('\n').filter(Boolean), [
'x: foo 1',
'y: bar 1',
'z: qux 2',
'child segment: qux'
'z: qux 2'
]);
});
});
@@ -692,14 +667,6 @@ function run({ mode, basepath = '' }) {
assert.equal(title, 'it works');
});
});
it('runs preload in root component', () => {
return nightmare.goto(`${base}/preload-root`)
.page.title()
.then(title => {
assert.equal(title, 'root preload function ran: true');
});
});
});
describe('headers', () => {

View File

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

View File

@@ -6,9 +6,9 @@
"noEmitOnError": true,
"allowJs": true,
"lib": ["es5", "es6", "dom"],
"importHelpers": true,
"target": "ES5"
"importHelpers": true
},
"target": "ES5",
"include": [
"src"
],