Compare commits

...

45 Commits

Author SHA1 Message Date
Rich Harris
8240595d70 -> v0.13.2 2018-06-15 10:58:55 -04:00
Rich Harris
658d8dd50c Merge pull request #284 from sveltejs/emit-basepath
Emit basepath event
2018-06-15 10:57:04 -04:00
Rich Harris
9eeeaa24c1 emit a basepath event on first run 2018-06-14 17:20:46 -04:00
Rich Harris
9c4a3592ff remove some unused code 2018-06-14 16:34:16 -04:00
Rich Harris
be7cff4818 -> v0.13.1 2018-06-05 14:41:12 -04:00
Rich Harris
d6632cf312 Merge pull request #281 from sveltejs/gh-276
reinstate ten second interval between heartbeats
2018-06-05 20:40:17 +02:00
Rich Harris
f6e012ec73 reinstate ten second interval between heartbeats - fixes #276 2018-06-05 14:35:37 -04:00
Rich Harris
087acd5765 -> v0.13.0 2018-05-28 19:49:40 -04:00
Rich Harris
43bf6e8d8a Merge pull request #273 from sveltejs/gh-272
[WIP] expose dev, build, export APIs
2018-05-28 19:47:08 -04:00
Rich Harris
78be6aa343 add api.js 2018-05-28 18:04:18 -04:00
Rich Harris
8ba57969c2 oops 2018-05-26 12:39:44 -04:00
Rich Harris
58d2f605fc expose find_page method 2018-05-26 12:31:52 -04:00
Rich Harris
e0b4319c7d preserve webpack stats, write client assets elsewhere 2018-05-26 12:31:43 -04:00
Rich Harris
98d0df4320 work around webpack silliness 2018-05-23 22:05:40 -04:00
Rich Harris
6aa3ce4f05 make stdout etc available via api 2018-05-23 21:56:35 -04:00
Rich Harris
046db325f1 update deps 2018-05-23 20:41:48 -04:00
Rich Harris
1a4bace5f4 add dev API 2018-05-23 09:05:24 -04:00
Rich Harris
0dbf75f100 create API for exporting 2018-05-22 11:57:24 -04:00
Rich Harris
4f49fd8d5c create build API 2018-05-22 11:32:06 -04:00
Rich Harris
86f71e1faf Merge pull request #268 from lukeed/dep/colors
Update colors dep
2018-05-22 08:01:23 -04:00
Luke Edwards
147e2c64b5 update webpack-format-messages 2018-05-17 13:03:25 -07:00
Luke Edwards
9063057b0c swap clorox —> ansi-colors 2018-05-15 09:00:55 -07:00
Rich Harris
25f0d94595 -> v0.12.0 2018-05-05 10:00:58 -04:00
Rich Harris
8155df2e22 Merge branch 'gh-157' 2018-05-05 09:58:12 -04:00
Rich Harris
bb51470004 Merge pull request #259 from sveltejs/gh-157
switch to single App component model
2018-05-05 09:57:28 -04:00
Rich Harris
53446e2ec7 Merge branch 'master' into gh-157 2018-05-05 09:45:04 -04:00
Rich Harris
c4c09550eb Merge pull request #260 from sveltejs/another-sorting-bug
fix sorting
2018-05-05 09:43:16 -04:00
Rich Harris
da47fdec96 fix sorting 2018-05-05 09:38:24 -04:00
Rich Harris
971342ac7a set preloading: true when appropriate 2018-05-04 23:23:41 -04:00
Rich Harris
3becc1cbe2 error on incorrect init args 2018-05-04 23:06:10 -04:00
Rich Harris
8ee5346900 switch to single App component model (#157) 2018-05-04 22:46:41 -04:00
Rich Harris
9e4b79c6ff Merge pull request #258 from sveltejs/gh-208
exit with code 1 if build/export fails
2018-05-04 17:48:29 -04:00
Rich Harris
4ec1c65395 exit with code 1 if build/export fails - fixes #208 2018-05-04 17:42:37 -04:00
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
29 changed files with 1408 additions and 825 deletions

View File

@@ -1,5 +1,27 @@
# sapper changelog # sapper changelog
## 0.13.2
* Emit a `basepath` event ([#284](https://github.com/sveltejs/sapper/pull/284))
## 0.13.1
* Reinstate ten-second interval between dev server heartbeats ([#276](https://github.com/sveltejs/sapper/issues/276))
## 0.13.0
* Expose `dev`, `build`, `export` and `find_page` APIs ([#272](https://github.com/sveltejs/sapper/issues/272))
## 0.12.0
* Each app has a single `<App>` component. See the [migration guide](https://sapper.svelte.technology/guide#0-11-to-0-12) for more information ([#157](https://github.com/sveltejs/sapper/issues/157))
* Process exits with error code 1 if build/export fails ([#208](https://github.com/sveltejs/sapper/issues/208))
## 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))

1
api.js Normal file
View File

@@ -0,0 +1 @@
module.exports = require('./dist/api.ts.js');

View File

@@ -1,6 +1,6 @@
{ {
"name": "sapper", "name": "sapper",
"version": "0.11.0", "version": "0.13.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": {
@@ -18,53 +18,50 @@
"test": "test" "test": "test"
}, },
"dependencies": { "dependencies": {
"ansi-colors": "^2.0.1",
"cheerio": "^1.0.0-rc.2", "cheerio": "^1.0.0-rc.2",
"chokidar": "^2.0.3", "chokidar": "^2.0.3",
"clorox": "^1.0.3",
"cookie": "^0.3.1", "cookie": "^0.3.1",
"devalue": "^1.0.1", "devalue": "^1.0.1",
"glob": "^7.1.2", "glob": "^7.1.2",
"html-minifier": "^3.5.11", "html-minifier": "^3.5.16",
"mkdirp": "^0.5.1", "mkdirp": "^0.5.1",
"node-fetch": "^2.1.1", "node-fetch": "^2.1.1",
"port-authority": "^1.0.2", "port-authority": "^1.0.2",
"pretty-bytes": "^4.0.2", "pretty-bytes": "^5.0.0",
"pretty-ms": "^3.1.0", "pretty-ms": "^3.1.0",
"require-relative": "^0.8.7", "require-relative": "^0.8.7",
"rimraf": "^2.6.2", "rimraf": "^2.6.2",
"sade": "^1.4.0", "sade": "^1.4.1",
"sander": "^0.6.0", "sander": "^0.6.0",
"source-map-support": "^0.5.5", "source-map-support": "^0.5.6",
"tslib": "^1.9.0", "tslib": "^1.9.1",
"url-parse": "^1.2.0", "url-parse": "^1.2.0",
"webpack-format-messages": "^1.0.2" "webpack-format-messages": "^2.0.1"
}, },
"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",
"compression": "^1.7.1", "compression": "^1.7.1",
"eslint": "^4.13.1", "eslint": "^4.13.1",
"eslint-plugin-import": "^2.8.0", "eslint-plugin-import": "^2.12.0",
"express": "^4.16.3", "express": "^4.16.3",
"get-port": "^3.2.0", "mocha": "^5.2.0",
"mocha": "^5.0.4",
"nightmare": "^3.0.0", "nightmare": "^3.0.0",
"npm-run-all": "^4.1.2", "npm-run-all": "^4.1.3",
"polka": "^0.3.4", "polka": "^0.4.0",
"rollup": "^0.58.2", "rollup": "^0.59.2",
"rollup-plugin-commonjs": "^9.1.3", "rollup-plugin-commonjs": "^9.1.3",
"rollup-plugin-json": "^2.3.0", "rollup-plugin-json": "^3.0.0",
"rollup-plugin-string": "^2.0.2", "rollup-plugin-string": "^2.0.2",
"rollup-plugin-typescript": "^0.8.1", "rollup-plugin-typescript": "^0.8.1",
"serve-static": "^1.13.2", "serve-static": "^1.13.2",
"svelte": "^2.4.4", "svelte": "^2.6.3",
"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.8.3"
}, },
"scripts": { "scripts": {
"cy:open": "cypress open", "cy:open": "cypress open",

View File

@@ -25,7 +25,13 @@ export default [
}, },
{ {
input: [`src/cli.ts`, `src/core.ts`, `src/middleware.ts`, `src/webpack.ts`], input: [
`src/api.ts`,
`src/cli.ts`,
`src/core.ts`,
`src/middleware.ts`,
`src/webpack.ts`
],
output: { output: {
dir: 'dist', dir: 'dist',
format: 'cjs', format: 'cjs',

6
src/api.ts Normal file
View File

@@ -0,0 +1,6 @@
import { dev } from './api/dev';
import { build } from './api/build';
import { exporter } from './api/export';
import { find_page } from './api/find_page';
export { dev, build, exporter, find_page };

111
src/api/build.ts Normal file
View File

@@ -0,0 +1,111 @@
import * as fs from 'fs';
import * as path from 'path';
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 { locations } from '../config';
import * as events from './interfaces';
export function build(opts: {}) {
const emitter = new EventEmitter();
execute(emitter, opts).then(
() => {
emitter.emit('done', <events.DoneEvent>{}); // TODO do we need to pass back any info?
},
error => {
emitter.emit('error', <events.ErrorEvent>{
error
});
}
);
return emitter;
}
async function execute(emitter: EventEmitter, {
dest = 'build',
app = 'app',
webpack = 'webpack',
routes = 'routes'
} = {}) {
mkdirp.sync(dest);
rimraf.sync(path.join(dest, '**/*'));
// minify app/template.html
// TODO compile this to a function? could be quicker than str.replace(...).replace(...).replace(...)
const template = fs.readFileSync(`${app}/template.html`, 'utf-8');
// remove this in a future version
if (template.indexOf('%sapper.base%') === -1) {
const error = new Error(`As of Sapper v0.10, your template.html file must include %sapper.base% in the <head>`);
error.code = `missing-sapper-base`;
throw error;
}
fs.writeFileSync(`${dest}/template.html`, minify_html(template));
const route_objects = create_routes();
// create app/manifest/client.js and app/manifest/server.js
create_main_manifests({ routes: route_objects });
const { client, server, serviceworker } = create_compilers({ webpack });
const client_stats = await compile(client);
emitter.emit('build', <events.BuildEvent>{
type: 'client',
// TODO duration/warnings
webpack_stats: client_stats
});
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);
emitter.emit('build', <events.BuildEvent>{
type: 'server',
// TODO duration/warnings
webpack_stats: server_stats
});
let serviceworker_stats;
if (serviceworker) {
create_serviceworker_manifest({
routes: route_objects,
client_files: client_stats.toJson().assets.map((chunk: { name: string }) => `client/${chunk.name}`)
});
serviceworker_stats = await compile(serviceworker);
emitter.emit('build', <events.BuildEvent>{
type: 'serviceworker',
// TODO duration/warnings
webpack_stats: serviceworker_stats
});
}
}
function compile(compiler: any) {
return new Promise((fulfil, reject) => {
compiler.run((err: Error, stats: any) => {
if (err) {
reject(err);
process.exit(1);
}
if (stats.hasErrors()) {
console.error(stats.toString({ colors: true }));
reject(new Error(`Encountered errors while building app`));
}
else {
fulfil(stats);
}
});
});
}

433
src/api/dev.ts Normal file
View File

@@ -0,0 +1,433 @@
import * as path from 'path';
import * as fs from 'fs';
import * as http from 'http';
import * as child_process from 'child_process';
import * as ports from 'port-authority';
import mkdirp from 'mkdirp';
import rimraf from 'rimraf';
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 * as events from './interfaces';
export function dev(opts) {
return new Watcher(opts);
}
class Watcher extends EventEmitter {
dirs: {
app: string;
dest: string;
routes: string;
webpack: string;
}
port: number;
closed: boolean;
dev_server: DevServer;
proc: child_process.ChildProcess;
filewatchers: Array<{ close: () => void }>;
deferreds: {
client: Deferred;
server: Deferred;
};
restarting: boolean;
current_build: {
changed: Set<string>;
rebuilding: Set<string>;
unique_warnings: Set<string>;
unique_errors: Set<string>;
}
constructor({
app = locations.app(),
dest = locations.dest(),
routes = locations.routes(),
webpack = 'webpack',
port = +process.env.PORT
}: {
app: string,
dest: string,
routes: string,
webpack: string,
port: number
}) {
super();
this.dirs = { app, dest, routes, webpack };
this.port = port;
this.closed = false;
this.filewatchers = [];
this.current_build = {
changed: new Set(),
rebuilding: new Set(),
unique_errors: new Set(),
unique_warnings: new Set()
};
// remove this in a future version
const template = fs.readFileSync(path.join(app, 'template.html'), 'utf-8');
if (template.indexOf('%sapper.base%') === -1) {
const error = new Error(`As of Sapper v0.10, your template.html file must include %sapper.base% in the <head>`);
error.code = `missing-sapper-base`;
throw error;
}
process.env.NODE_ENV = 'development';
process.on('exit', () => {
this.close();
});
this.init();
}
async init() {
if (this.port) {
if (!await ports.check(this.port)) {
this.emit('fatal', <events.FatalEvent>{
error: new Error(`Port ${this.port} is unavailable`)
});
return;
}
} else {
this.port = await ports.find(3000);
}
const { dest } = this.dirs;
rimraf.sync(dest);
mkdirp.sync(dest);
const dev_port = await ports.find(10000);
const routes = create_routes();
create_main_manifests({ routes, dev_port });
this.dev_server = new DevServer(dev_port);
this.filewatchers.push(
watch_files(locations.routes(), ['add', 'unlink'], () => {
const routes = create_routes();
create_main_manifests({ routes, dev_port });
}),
watch_files(`${locations.app()}/template.html`, ['change'], () => {
this.dev_server.send({
action: 'reload'
});
})
);
this.deferreds = {
server: new Deferred(),
client: new Deferred()
};
// TODO watch the configs themselves?
const compilers = create_compilers({ webpack: this.dirs.webpack });
this.watch(compilers.server, {
name: 'server',
invalid: filename => {
this.restart(filename, 'server');
this.deferreds.server = new Deferred();
},
result: info => {
fs.writeFileSync(path.join(dest, 'server_info.json'), JSON.stringify(info, null, ' '));
this.deferreds.client.promise.then(() => {
this.dev_server.send({
status: 'completed'
});
const restart = () => {
ports.wait(this.port).then((() => {
this.emit('ready', <events.ReadyEvent>{
port: this.port,
process: this.proc
});
this.deferreds.server.fulfil();
}));
};
if (this.proc) {
this.proc.kill();
this.proc.on('exit', restart);
} else {
restart();
}
this.proc = child_process.fork(`${dest}/server.js`, [], {
cwd: process.cwd(),
env: Object.assign({
PORT: this.port
}, process.env),
stdio: ['ipc']
});
this.proc.on('message', message => {
if (message.__sapper__ && message.event === 'basepath') {
this.emit('basepath', {
basepath: message.basepath
});
}
});
});
}
});
let first = true;
this.watch(compilers.client, {
name: 'client',
invalid: filename => {
this.restart(filename, 'client');
this.deferreds.client = new Deferred();
// TODO we should delete old assets. due to a webpack bug
// i don't even begin to comprehend, this is apparently
// quite difficult
},
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();
const client_files = info.assets.map((chunk: { name: string }) => `client/${chunk.name}`);
create_serviceworker_manifest({
routes: create_routes(),
client_files
});
// we need to wait a beat before watching the service
// worker, because of some webpack nonsense
setTimeout(watch_serviceworker, 100);
}
});
let watch_serviceworker = compilers.serviceworker
? () => {
watch_serviceworker = noop;
this.watch(compilers.serviceworker, {
name: 'service worker',
result: info => {
fs.writeFileSync(path.join(dest, 'serviceworker_info.json'), JSON.stringify(info, null, ' '));
}
});
}
: noop;
}
close() {
if (this.closed) return;
this.closed = true;
this.dev_server.close();
if (this.proc) this.proc.kill();
this.filewatchers.forEach(watcher => {
watcher.close();
});
}
restart(filename: string, type: string) {
if (this.restarting) {
this.current_build.changed.add(filename);
this.current_build.rebuilding.add(type);
} else {
this.restarting = true;
this.current_build = {
changed: new Set(),
rebuilding: new Set(),
unique_warnings: new Set(),
unique_errors: new Set()
};
process.nextTick(() => {
this.emit('invalid', <events.InvalidEvent>{
changed: Array.from(this.current_build.changed),
invalid: {
server: this.current_build.rebuilding.has('server'),
client: this.current_build.rebuilding.has('client'),
serviceworker: this.current_build.rebuilding.has('serviceworker'),
}
});
this.restarting = false;
});
}
}
watch(compiler: any, { name, invalid = noop, result }: {
name: string,
invalid?: (filename: string) => void;
result: (stats: any) => void;
}) {
compiler.hooks.invalid.tap('sapper', (filename: string) => {
invalid(filename);
});
compiler.watch({}, (err: Error, stats: any) => {
if (err) {
this.emit('error', <events.ErrorEvent>{
type: name,
error: err
});
} else {
const messages = format_messages(stats);
const info = stats.toJson();
this.emit('build', {
type: name,
duration: info.time,
errors: messages.errors.map((message: string) => {
const duplicate = this.current_build.unique_errors.has(message);
this.current_build.unique_errors.add(message);
return mungeWebpackError(message, duplicate);
}),
warnings: messages.warnings.map((message: string) => {
const duplicate = this.current_build.unique_warnings.has(message);
this.current_build.unique_warnings.add(message);
return mungeWebpackError(message, duplicate);
}),
});
result(info);
}
});
}
}
const locPattern = /\((\d+):(\d+)\)$/;
function mungeWebpackError(message: string, duplicate: boolean) {
// TODO this is all a bit rube goldberg...
const lines = message.split('\n');
const file = lines.shift()
.replace('', '') // careful — there is a special character at the beginning of this string
.replace('', '')
.replace('./', '');
let line = null;
let column = null;
const match = locPattern.exec(lines[0]);
if (match) {
lines[0] = lines[0].replace(locPattern, '');
line = +match[1];
column = +match[2];
}
return {
file,
line,
column,
message: lines.join('\n'),
originalMessage: message,
duplicate
};
}
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 {
clients: Set<http.ServerResponse>;
interval: NodeJS.Timer;
_: http.Server;
constructor(port: number, interval = 10000) {
this.clients = new Set();
this._ = http.createServer((req, res) => {
if (req.url !== '/__sapper__') return;
req.socket.setKeepAlive(true);
res.writeHead(200, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Cache-Control',
'Content-Type': 'text/event-stream;charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
'Connection': 'keep-alive',
// While behind nginx, event stream should not be buffered:
// http://nginx.org/docs/http/ngx_http_proxy_module.html#proxy_buffering
'X-Accel-Buffering': 'no'
});
res.write('\n');
this.clients.add(res);
req.on('close', () => {
this.clients.delete(res);
});
});
this._.listen(port);
this.interval = setInterval(() => {
this.send(null);
}, INTERVAL);
}
close() {
this._.close();
clearInterval(this.interval);
}
send(data: any) {
this.clients.forEach(client => {
client.write(`data: ${JSON.stringify(data)}\n\n`);
});
}
}
function noop() {}
function watch_files(pattern: string, events: string[], callback: () => void) {
const chokidar = require('chokidar');
const watcher = chokidar.watch(pattern, {
persistent: true,
ignoreInitial: true,
disableGlobbing: true
});
events.forEach(event => {
watcher.on(event, callback);
});
return {
close: () => watcher.close()
};
}

131
src/api/export.ts Normal file
View File

@@ -0,0 +1,131 @@
import * as child_process from 'child_process';
import * as path from 'path';
import * as sander from 'sander';
import cheerio from 'cheerio';
import URL from 'url-parse';
import fetch from 'node-fetch';
import * as ports from 'port-authority';
import { EventEmitter } from 'events';
import { minify_html } from './utils/minify_html';
import { locations } from '../config';
import * as events from './interfaces';
export function exporter(opts: {}) {
const emitter = new EventEmitter();
execute(emitter, opts).then(
() => {
emitter.emit('done', <events.DoneEvent>{}); // TODO do we need to pass back any info?
},
error => {
emitter.emit('error', <events.ErrorEvent>{
error
});
}
);
return emitter;
}
async function execute(emitter: EventEmitter, {
build = 'build',
dest = 'export',
basepath = ''
} = {}) {
const export_dir = path.join(dest, basepath);
// Prep output directory
sander.rimrafSync(export_dir);
sander.copydirSync('assets').to(export_dir);
sander.copydirSync(build, 'client').to(export_dir, 'client');
if (sander.existsSync(build, 'service-worker.js')) {
sander.copyFileSync(build, 'service-worker.js').to(export_dir, 'service-worker.js');
}
if (sander.existsSync(build, 'service-worker.js.map')) {
sander.copyFileSync(build, 'service-worker.js.map').to(export_dir, 'service-worker.js.map');
}
const port = await ports.find(3000);
const origin = `http://localhost:${port}`;
const proc = child_process.fork(path.resolve(`${build}/server.js`), [], {
cwd: process.cwd(),
env: Object.assign({
PORT: port,
NODE_ENV: 'production',
SAPPER_DEST: build,
SAPPER_EXPORT: 'true'
}, process.env)
});
const seen = new Set();
const saved = new Set();
proc.on('message', message => {
if (!message.__sapper__ || message.event !== 'file') return;
let file = new URL(message.url, origin).pathname.slice(1);
let { body } = message;
if (saved.has(file)) return;
saved.add(file);
const is_html = message.type === 'text/html';
if (is_html) {
file = file === '' ? 'index.html' : `${file}/index.html`;
body = minify_html(body);
}
emitter.emit('file', <events.FileEvent>{
file,
size: body.length
});
sander.writeFileSync(export_dir, file, body);
});
async function handle(url: URL) {
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();
const $ = cheerio.load(body);
const urls: URL[] = [];
const base = new URL($('base').attr('href') || '/', url.href);
$('a[href]').each((i: number, $a) => {
const url = new URL($a.attribs.href, base.href);
if (url.origin === origin && !seen.has(url.pathname)) {
seen.add(url.pathname);
urls.push(url);
}
});
for (const url of urls) {
await handle(url);
}
}
}
}
return ports.wait(port)
.then(() => handle(new URL(`/${basepath}`, origin))) // TODO all static routes
.then(() => proc.kill());
}

16
src/api/find_page.ts Normal file
View File

@@ -0,0 +1,16 @@
import * as glob from 'glob';
import { locations } from '../config';
import { create_routes } from '../core';
export function find_page(pathname: string, files: string[] = glob.sync('**/*.*', { cwd: locations.routes(), dot: true, nodir: true })) {
const routes = create_routes({ files });
for (let i = 0; i < routes.length; i += 1) {
const route = routes[i];
if (route.pattern.test(pathname)) {
const page = route.handlers.find(handler => handler.type === 'page');
if (page) return page.file;
}
}
}

43
src/api/interfaces.ts Normal file
View File

@@ -0,0 +1,43 @@
import * as child_process from 'child_process';
export type ReadyEvent = {
port: number;
process: child_process.ChildProcess;
};
export type ErrorEvent = {
type: string;
error: Error;
};
export type FatalEvent = {
error: Error;
};
export type InvalidEvent = {
changed: string[];
invalid: {
client: boolean;
server: boolean;
serviceworker: boolean;
}
};
export type BuildEvent = {
type: string;
errors: Array<{ message: string, duplicate: boolean }>;
warnings: Array<{ message: string, duplicate: boolean }>;
duration: number;
webpack_stats: any;
}
export type FileEvent = {
file: string;
size: number;
}
export type FailureEvent = {
}
export type DoneEvent = {}

View File

@@ -2,7 +2,7 @@ import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
import * as child_process from 'child_process'; import * as child_process from 'child_process';
import sade from 'sade'; import sade from 'sade';
import * as clorox from 'clorox'; import * as colors from 'ansi-colors';
import prettyMs from 'pretty-ms'; import prettyMs from 'pretty-ms';
// import upgrade from './cli/upgrade'; // import upgrade from './cli/upgrade';
import * as ports from 'port-authority'; import * as ports from 'port-authority';
@@ -47,9 +47,10 @@ prog.command('build [dest]')
require('./server.js'); require('./server.js');
`.replace(/^\t+/gm, '').trim()); `.replace(/^\t+/gm, '').trim());
console.error(`\n> Finished in ${elapsed(start)}. Type ${clorox.bold.cyan(`node ${dest}`)} to run the app.`); console.error(`\n> Finished in ${elapsed(start)}. Type ${colors.bold.cyan(`node ${dest}`)} to run the app.`);
} catch (err) { } catch (err) {
console.error(err ? err.details || err.stack || err.message || err : 'Unknown error'); console.error(err ? err.details || err.stack || err.message || err : 'Unknown error');
process.exit(1);
} }
}); });
@@ -80,9 +81,10 @@ prog.command('export [dest]')
const { exporter } = await import('./cli/export'); const { exporter } = await import('./cli/export');
await exporter(dest, opts); await exporter(dest, opts);
console.error(`\n> Finished in ${elapsed(start)}. Type ${clorox.bold.cyan(`npx serve ${dest}`)} to run the app.`); console.error(`\n> Finished in ${elapsed(start)}. Type ${colors.bold.cyan(`npx serve ${dest}`)} to run the app.`);
} catch (err) { } catch (err) {
console.error(err ? err.details || err.stack || err.message || err : 'Unknown error'); console.error(err ? err.details || err.stack || err.message || err : 'Unknown error');
process.exit(1);
} }
}); });
@@ -92,4 +94,4 @@ prog.parse(process.argv);
function elapsed(start: number) { function elapsed(start: number) {
return prettyMs(Date.now() - start); return prettyMs(Date.now() - start);
} }

View File

@@ -1,78 +1,32 @@
import * as fs from 'fs'; import { build as _build } from '../api/build';
import * as path from 'path'; import * as colors from 'ansi-colors';
import * as clorox from 'clorox';
import mkdirp from 'mkdirp';
import rimraf from 'rimraf';
import { minify_html } from './utils/minify_html';
import { create_compilers, create_main_manifests, create_routes, create_serviceworker_manifest } from '../core'
import { locations } from '../config'; import { locations } from '../config';
export async function build() { export function build() {
const output = locations.dest();
mkdirp.sync(output);
rimraf.sync(path.join(output, '**/*'));
// minify app/template.html
// TODO compile this to a function? could be quicker than str.replace(...).replace(...).replace(...)
const template = fs.readFileSync(`${locations.app()}/template.html`, 'utf-8');
// remove this in a future version
if (template.indexOf('%sapper.base%') === -1) {
console.log(`${clorox.bold.red(`> As of Sapper v0.10, your template.html file must include %sapper.base% in the <head>`)}`);
process.exit(1);
}
fs.writeFileSync(`${output}/template.html`, minify_html(template));
const routes = create_routes();
// create app/manifest/client.js and app/manifest/server.js
create_main_manifests({ routes });
const { client, server, serviceworker } = create_compilers();
const client_stats = await compile(client);
console.log(`${clorox.inverse(`\nbuilt client`)}`);
console.log(client_stats.toString({ colors: true }));
fs.writeFileSync(path.join(output, 'client_info.json'), JSON.stringify({
assets: client_stats.toJson().assetsByChunkName
}));
const server_stats = await compile(server);
console.log(`${clorox.inverse(`\nbuilt server`)}`);
console.log(server_stats.toString({ colors: true }));
let serviceworker_stats;
if (serviceworker) {
create_serviceworker_manifest({
routes,
client_files: client_stats.toJson().assets.map((chunk: { name: string }) => `client/${chunk.name}`)
});
serviceworker_stats = await compile(serviceworker);
console.log(`${clorox.inverse(`\nbuilt service worker`)}`);
console.log(serviceworker_stats.toString({ colors: true }));
}
}
function compile(compiler: any) {
return new Promise((fulfil, reject) => { return new Promise((fulfil, reject) => {
compiler.run((err: Error, stats: any) => { try {
if (err) { const emitter = _build({
reject(err); dest: locations.dest(),
process.exit(1); app: locations.app(),
} routes: locations.routes(),
webpack: 'webpack'
});
if (stats.hasErrors()) { emitter.on('build', event => {
console.error(stats.toString({ colors: true })); console.log(colors.inverse(`\nbuilt ${event.type}`));
reject(new Error(`Encountered errors while building app`)); console.log(event.webpack_stats.toString({ colors: true }));
} });
else { emitter.on('error', event => {
fulfil(stats); reject(event.error);
} });
});
emitter.on('done', event => {
fulfil();
});
} catch (err) {
console.log(`${colors.bold.red(`> ${err.message}`)}`);
process.exit(1);
}
}); });
} }

View File

@@ -1,323 +1,77 @@
import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
import * as net from 'net'; import * as colors from 'ansi-colors';
import * as clorox from 'clorox';
import * as child_process from 'child_process'; import * as child_process from 'child_process';
import * as http from 'http';
import mkdirp from 'mkdirp';
import rimraf from 'rimraf';
import format_messages from 'webpack-format-messages';
import prettyMs from 'pretty-ms'; import prettyMs from 'pretty-ms';
import * as ports from 'port-authority'; import { dev as _dev } from '../api/dev';
import { locations } from '../config'; import * as events from '../api/interfaces';
import { create_compilers, create_main_manifests, create_routes, create_serviceworker_manifest } from '../core';
type Deferred = { export function dev(opts: { port: number, open: boolean }) {
promise?: Promise<any>; try {
fulfil?: (value?: any) => void; const watcher = _dev(opts);
reject?: (err: Error) => void;
}
function deferred() { let first = true;
const d: Deferred = {};
d.promise = new Promise((fulfil, reject) => { watcher.on('ready', (event: events.ReadyEvent) => {
d.fulfil = fulfil; if (first) {
d.reject = reject; console.log(`${colors.bold.cyan(`> Listening on http://localhost:${event.port}`)}`);
}); if (opts.open) child_process.exec(`open http://localhost:${event.port}`);
first = false;
}
return d; // TODO clear screen?
}
function create_hot_update_server(port: number, interval = 10000) { event.process.stdout.on('data', data => {
const clients = new Set(); process.stdout.write(data);
});
const server = http.createServer((req, res) => { event.process.stderr.on('data', data => {
if (req.url !== '/__sapper__') return; process.stderr.write(data);
});
req.socket.setKeepAlive(true);
res.writeHead(200, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Cache-Control',
'Content-Type': 'text/event-stream;charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
'Connection': 'keep-alive',
// While behind nginx, event stream should not be buffered:
// http://nginx.org/docs/http/ngx_http_proxy_module.html#proxy_buffering
'X-Accel-Buffering': 'no'
}); });
res.write('\n'); watcher.on('invalid', (event: events.InvalidEvent) => {
const changed = event.changed.map(filename => path.relative(process.cwd(), filename)).join(', ');
clients.add(res); console.log(`\n${colors.bold.cyan(changed)} changed. rebuilding...`);
req.on('close', () => {
clients.delete(res);
});
});
server.listen(port);
function send(data: any) {
clients.forEach(client => {
client.write(`data: ${JSON.stringify(data)}\n\n`);
});
}
setInterval(() => {
send(null)
}, interval);
return { send };
}
export async function dev(opts: { port: number, open: boolean }) {
// remove this in a future version
const template = fs.readFileSync(path.join(locations.app(), 'template.html'), 'utf-8');
if (template.indexOf('%sapper.base%') === -1) {
console.log(`${clorox.bold.red(`> As of Sapper v0.10, your template.html file must include %sapper.base% in the <head>`)}`);
process.exit(1);
}
process.env.NODE_ENV = 'development';
let port = opts.port || +process.env.PORT;
if (port) {
if (!await ports.check(port)) {
console.log(`${clorox.bold.red(`> Port ${port} is unavailable`)}`);
return;
}
} else {
port = await ports.find(3000);
}
const dir = locations.dest();
rimraf.sync(dir);
mkdirp.sync(dir);
const dev_port = await ports.find(10000);
const routes = create_routes();
create_main_manifests({ routes, dev_port });
const hot_update_server = create_hot_update_server(dev_port);
watch_files(locations.routes(), ['add', 'unlink'], () => {
const routes = create_routes();
create_main_manifests({ routes, dev_port });
});
watch_files(`${locations.app()}/template.html`, ['change'], () => {
hot_update_server.send({
action: 'reload'
});
});
let proc: child_process.ChildProcess;
process.on('exit', () => {
// sometimes webpack crashes, so we need to kill our children
if (proc) proc.kill();
});
const deferreds = {
server: deferred(),
client: deferred()
};
let restarting = false;
let build = {
unique_warnings: new Set(),
unique_errors: new Set()
};
function restart_build(filename: string) {
if (restarting) return;
restarting = true;
build = {
unique_warnings: new Set(),
unique_errors: new Set()
};
process.nextTick(() => {
restarting = false;
}); });
console.log(`\n${clorox.bold.cyan(path.relative(process.cwd(), filename))} changed. rebuilding...`); watcher.on('error', (event: events.ErrorEvent) => {
} console.log(`${colors.red(`${event.type}`)}`);
console.log(`${colors.red(event.error.message)}`);
// TODO watch the configs themselves?
const compilers = create_compilers();
function watch(compiler: any, { name, invalid = noop, error = noop, result }: {
name: string,
invalid?: (filename: string) => void;
error?: (error: Error) => void;
result: (stats: any) => void;
}) {
compiler.hooks.invalid.tap('sapper', (filename: string) => {
invalid(filename);
}); });
compiler.watch({}, (err: Error, stats: any) => { watcher.on('fatal', (event: events.FatalEvent) => {
if (err) { console.log(`${colors.bold.red(`> ${event.error.message}`)}`);
console.log(`${clorox.red(`${name}`)}`); });
console.log(`${clorox.red(err.message)}`);
error(err);
} else {
const messages = format_messages(stats);
const info = stats.toJson();
if (messages.errors.length > 0) { watcher.on('build', (event: events.BuildEvent) => {
console.log(`${clorox.bold.red(`${name}`)}`); if (event.errors.length) {
console.log(`${colors.bold.red(`${event.type}`)}`);
const filtered = messages.errors.filter((message: string) => { event.errors.filter(e => !e.duplicate).forEach(error => {
return !build.unique_errors.has(message); console.log(error.message);
}); });
filtered.forEach((message: string) => { const hidden = event.errors.filter(e => e.duplicate).length;
build.unique_errors.add(message); if (hidden > 0) {
console.log(message); console.log(`${hidden} duplicate ${hidden === 1 ? 'error' : 'errors'} hidden\n`);
});
const hidden = messages.errors.length - filtered.length;
if (hidden > 0) {
console.log(`${hidden} duplicate ${hidden === 1 ? 'error' : 'errors'} hidden\n`);
}
} else {
if (messages.warnings.length > 0) {
console.log(`${clorox.bold.yellow(`${name}`)}`);
const filtered = messages.warnings.filter((message: string) => {
return !build.unique_warnings.has(message);
});
filtered.forEach((message: string) => {
build.unique_warnings.add(message);
console.log(`${message}\n`);
});
const hidden = messages.warnings.length - filtered.length;
if (hidden > 0) {
console.log(`${hidden} duplicate ${hidden === 1 ? 'warning' : 'warnings'} hidden\n`);
}
} else {
console.log(`${clorox.bold.green(`${name}`)} ${clorox.gray(`(${prettyMs(info.time)})`)}`);
}
result(info);
} }
} else if (event.warnings.length) {
console.log(`${colors.bold.yellow(`${event.type}`)}`);
event.warnings.filter(e => !e.duplicate).forEach(warning => {
console.log(warning.message);
});
const hidden = event.warnings.filter(e => e.duplicate).length;
if (hidden > 0) {
console.log(`${hidden} duplicate ${hidden === 1 ? 'warning' : 'warnings'} hidden\n`);
}
} else {
console.log(`${colors.bold.green(`${event.type}`)} ${colors.gray(`(${prettyMs(event.duration)})`)}`);
} }
}); });
} catch (err) {
console.log(`${colors.bold.red(`> ${err.message}`)}`);
process.exit(1);
} }
}
watch(compilers.server, {
name: 'server',
invalid: filename => {
restart_build(filename);
// TODO print message
deferreds.server = deferred();
},
result: info => {
// TODO log compile errors/warnings
fs.writeFileSync(path.join(dir, 'server_info.json'), JSON.stringify(info, null, ' '));
deferreds.client.promise.then(() => {
function restart() {
ports.wait(port).then(deferreds.server.fulfil);
}
if (proc) {
proc.kill();
proc.on('exit', restart);
} else {
restart();
}
proc = child_process.fork(`${dir}/server.js`, [], {
cwd: process.cwd(),
env: Object.assign({
PORT: port
}, process.env)
});
});
}
});
let first = true;
watch(compilers.client, {
name: 'client',
invalid: filename => {
restart_build(filename);
deferreds.client = deferred();
// TODO we should delete old assets. due to a webpack bug
// i don't even begin to comprehend, this is apparently
// quite difficult
},
result: info => {
fs.writeFileSync(path.join(dir, 'client_info.json'), JSON.stringify({
assets: info.assetsByChunkName
}, null, ' '));
deferreds.client.fulfil();
const client_files = info.assets.map((chunk: { name: string }) => `client/${chunk.name}`);
deferreds.server.promise.then(() => {
hot_update_server.send({
status: 'completed'
});
if (first) {
first = false;
console.log(`${clorox.bold.cyan(`> Listening on http://localhost:${port}`)}`);
if (opts.open) child_process.exec(`open http://localhost:${port}`);
}
});
create_serviceworker_manifest({
routes: create_routes(),
client_files
});
watch_serviceworker();
}
});
let watch_serviceworker = compilers.serviceworker
? function() {
watch_serviceworker = noop;
watch(compilers.serviceworker, {
name: 'service worker',
result: info => {
fs.writeFileSync(path.join(dir, 'serviceworker_info.json'), JSON.stringify(info, null, ' '));
}
});
}
: noop;
}
function noop() {}
function watch_files(pattern: string, events: string[], callback: () => void) {
const chokidar = require('chokidar');
const watcher = chokidar.watch(pattern, {
persistent: true,
ignoreInitial: true,
disableGlobbing: true
});
events.forEach(event => {
watcher.on(event, callback);
});
}

View File

@@ -1,106 +1,35 @@
import * as child_process from 'child_process'; import { exporter as _exporter } from '../api/export';
import * as path from 'path'; import * as colors from 'ansi-colors';
import * as sander from 'sander';
import * as clorox from 'clorox';
import cheerio from 'cheerio';
import URL from 'url-parse';
import fetch from 'node-fetch';
import * as ports from 'port-authority';
import prettyBytes from 'pretty-bytes'; import prettyBytes from 'pretty-bytes';
import { minify_html } from './utils/minify_html';
import { locations } from '../config'; import { locations } from '../config';
export async function exporter(export_dir: string, { basepath = '' }) { export function exporter(export_dir: string, { basepath = '' }) {
const build_dir = locations.dest(); return new Promise((fulfil, reject) => {
try {
const emitter = _exporter({
build: locations.dest(),
dest: export_dir,
basepath
});
export_dir = path.join(export_dir, basepath); emitter.on('file', event => {
console.log(`${colors.bold.cyan(event.file)} ${colors.gray(`(${prettyBytes(event.size)})`)}`);
});
// Prep output directory emitter.on('failure', event => {
sander.rimrafSync(export_dir); console.log(`${colors.red(`> Received ${event.status} response when fetching ${event.pathname}`)}`);
});
sander.copydirSync('assets').to(export_dir); emitter.on('error', event => {
sander.copydirSync(build_dir, 'client').to(export_dir, 'client'); reject(event.error);
});
if (sander.existsSync(build_dir, 'service-worker.js')) { emitter.on('done', event => {
sander.copyFileSync(build_dir, 'service-worker.js').to(export_dir, 'service-worker.js'); fulfil();
} });
} catch (err) {
if (sander.existsSync(build_dir, 'service-worker.js.map')) { console.log(`${colors.bold.red(`> ${err.message}`)}`);
sander.copyFileSync(build_dir, 'service-worker.js.map').to(export_dir, 'service-worker.js.map'); process.exit(1);
} }
const port = await ports.find(3000);
const origin = `http://localhost:${port}`;
const proc = child_process.fork(path.resolve(`${build_dir}/server.js`), [], {
cwd: process.cwd(),
env: Object.assign({
PORT: port,
NODE_ENV: 'production',
SAPPER_DEST: build_dir,
SAPPER_EXPORT: 'true'
}, process.env)
}); });
}
const seen = new Set();
const saved = new Set();
proc.on('message', message => {
if (!message.__sapper__) return;
let file = new URL(message.url, origin).pathname.slice(1);
let { body } = message;
if (saved.has(file)) return;
saved.add(file);
const is_html = message.type === 'text/html';
if (is_html) {
file = file === '' ? 'index.html' : `${file}/index.html`;
body = minify_html(body);
}
console.log(`${clorox.bold.cyan(file)} ${clorox.gray(`(${prettyBytes(body.length)})`)}`);
sander.writeFileSync(export_dir, file, body);
});
async function handle(url: URL) {
const r = await fetch(url.href);
const range = ~~(r.status / 100);
if (range >= 4) {
console.log(`${clorox.red(`> Received ${r.status} response when fetching ${url.pathname}`)}`);
return;
}
if (range === 2) {
if (r.headers.get('Content-Type') === 'text/html') {
const body = await r.text();
const $ = cheerio.load(body);
const urls: URL[] = [];
const base = new URL($('base').attr('href') || '/', url.href);
$('a[href]').each((i: number, $a) => {
const url = new URL($a.attribs.href, base.href);
if (url.origin === origin && !seen.has(url.pathname)) {
seen.add(url.pathname);
urls.push(url);
}
});
for (const url of urls) {
await handle(url);
}
}
}
}
return ports.wait(port)
.then(() => handle(new URL(`/${basepath}`, origin))) // TODO all static routes
.then(() => proc.kill());
}

View File

@@ -1,7 +1,7 @@
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
import * as child_process from 'child_process'; import * as child_process from 'child_process';
import * as clorox from 'clorox'; import * as colors from 'ansi-colors';
import * as ports from 'port-authority'; import * as ports from 'port-authority';
export async function start(dir: string, opts: { port: number, open: boolean }) { export async function start(dir: string, opts: { port: number, open: boolean }) {
@@ -11,13 +11,13 @@ export async function start(dir: string, opts: { port: number, open: boolean })
const server = path.resolve(dir, 'server.js'); const server = path.resolve(dir, 'server.js');
if (!fs.existsSync(server)) { if (!fs.existsSync(server)) {
console.log(`${clorox.bold.red(`> ${dir}/server.js does not exist — type ${clorox.bold.cyan(dir === 'build' ? `npx sapper build` : `npx sapper build ${dir}`)} to create it`)}`); console.log(`${colors.bold.red(`> ${dir}/server.js does not exist — type ${colors.bold.cyan(dir === 'build' ? `npx sapper build` : `npx sapper build ${dir}`)} to create it`)}`);
return; return;
} }
if (port) { if (port) {
if (!await ports.check(port)) { if (!await ports.check(port)) {
console.log(`${clorox.bold.red(`> Port ${port} is unavailable`)}`); console.log(`${colors.bold.red(`> Port ${port} is unavailable`)}`);
return; return;
} }
} else { } else {
@@ -34,6 +34,6 @@ export async function start(dir: string, opts: { port: number, open: boolean })
}); });
await ports.wait(port); await ports.wait(port);
console.log(`${clorox.bold.cyan(`> Listening on http://localhost:${port}`)}`); console.log(`${colors.bold.cyan(`> Listening on http://localhost:${port}`)}`);
if (opts.open) child_process.exec(`open http://localhost:${port}`); if (opts.open) child_process.exec(`open http://localhost:${port}`);
} }

View File

@@ -1,5 +1,5 @@
import * as fs from 'fs'; import * as fs from 'fs';
import * as clorox from 'clorox'; import * as colors from 'ansi-colors';
export default async function upgrade() { export default async function upgrade() {
const upgraded = [ const upgraded = [
@@ -27,10 +27,10 @@ async function upgrade_sapper_main() {
if (/\%sapper\.main\%/.test(template)) { if (/\%sapper\.main\%/.test(template)) {
if (!pattern.test(template)) { if (!pattern.test(template)) {
console.log(`${clorox.red(`Could not replace %sapper.main% in ${file}`)}`); console.log(`${colors.red(`Could not replace %sapper.main% in ${file}`)}`);
} else { } else {
write(file, template.replace(pattern, `%sapper.scripts%`)); write(file, template.replace(pattern, `%sapper.scripts%`));
console.log(`${clorox.green(`Replaced %sapper.main% in ${file}`)}`); console.log(`${colors.green(`Replaced %sapper.main% in ${file}`)}`);
replaced = true; replaced = true;
} }
} }

View File

@@ -1,21 +1,21 @@
import * as path from 'path'; import * as path from 'path';
import relative from 'require-relative'; import relative from 'require-relative';
export default function create_compilers() { export default function create_compilers({ webpack }: { webpack: string }) {
const webpack = relative('webpack', process.cwd()); const wp = relative('webpack', process.cwd());
const serviceworker_config = try_require(path.resolve('webpack/service-worker.config.js')); const serviceworker_config = try_require(path.resolve(`${webpack}/service-worker.config.js`));
return { return {
client: webpack( client: wp(
require(path.resolve('webpack/client.config.js')) require(path.resolve(`${webpack}/client.config.js`))
), ),
server: webpack( server: wp(
require(path.resolve('webpack/server.config.js')) require(path.resolve(`${webpack}/server.config.js`))
), ),
serviceworker: serviceworker_config && webpack(serviceworker_config) serviceworker: serviceworker_config && wp(serviceworker_config)
}; };
} }

View File

@@ -1,7 +1,6 @@
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
import * as glob from 'glob'; import * as glob from 'glob';
import create_routes from './create_routes';
import { posixify, write_if_changed } from './utils'; import { posixify, write_if_changed } from './utils';
import { dev, locations } from '../config'; import { dev, locations } from '../config';
import { Route } from '../interfaces'; import { Route } from '../interfaces';
@@ -45,11 +44,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 +86,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,58 @@ 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) => {
if (a.parts[0] === '4xx' || a.parts[0] === '5xx') return -1;
if (b.parts[0] === '4xx' || b.parts[0] === '5xx') 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.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 +116,26 @@ export default function create_routes({ files } = { files: glob.sync('**/*.*', {
return { return {
id, id,
type: path.extname(file) === '.html' ? 'page' : 'route', handlers: files.map(file => ({
file, type: path.extname(file) === '.html' ? 'page' : 'route',
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;
type: 'page' | 'route'; handlers: {
file: string; type: 'page' | 'route';
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

@@ -1,16 +1,12 @@
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
import { resolve, URL } from 'url'; import { URL } from 'url';
import { ClientRequest, ServerResponse } from 'http'; import { ClientRequest, ServerResponse } from 'http';
import cookie from 'cookie'; import cookie from 'cookie';
import mkdirp from 'mkdirp';
import rimraf from 'rimraf';
import devalue from 'devalue'; import devalue from 'devalue';
import fetch from 'node-fetch'; import fetch from 'node-fetch';
import { lookup } from './middleware/mime'; import { lookup } from './middleware/mime';
import { create_routes, create_compilers } from './core';
import { locations, dev } from './config'; import { locations, dev } from './config';
import { Route, Template } from './interfaces';
import sourceMapSupport from 'source-map-support'; import sourceMapSupport from 'source-map-support';
sourceMapSupport.install(); sourceMapSupport.install();
@@ -20,14 +16,7 @@ type RouteObject = {
type: 'page' | 'route'; type: 'page' | 'route';
pattern: RegExp; pattern: RegExp;
params: (match: RegExpMatchArray) => Record<string, string>; params: (match: RegExpMatchArray) => Record<string, string>;
module: { module: Component;
render: (data: any, opts: { store: Store }) => {
head: string;
css: { code: string, map: any };
html: string
},
preload: (data: any) => any | Promise<any>
};
error?: string; error?: string;
} }
@@ -47,13 +36,29 @@ interface Req extends ClientRequest {
headers: Record<string, string>; headers: Record<string, string>;
} }
export default function middleware({ routes, store }: { interface Component {
render: (data: any, opts: { store: Store }) => {
head: string;
css: { code: string, map: any };
html: string
},
preload: (data: any) => any | Promise<any>
}
export default function middleware({ App, routes, store }: {
App: Component,
routes: RouteObject[], routes: RouteObject[],
store: (req: Req) => Store store: (req: Req) => Store
}) { }) {
if (!App) {
throw new Error(`As of 0.12, you must supply an App component to Sapper — see https://sapper.svelte.technology/guide#0-11-to-0-12 for more information`);
}
const output = locations.dest(); const output = locations.dest();
const client_info = JSON.parse(fs.readFileSync(path.join(output, 'client_info.json'), 'utf-8')); const client_assets = JSON.parse(fs.readFileSync(path.join(output, 'client_assets.json'), 'utf-8'));
let emitted_basepath = false;
const middleware = compose_handlers([ const middleware = compose_handlers([
(req: Req, res: ServerResponse, next: () => void) => { (req: Req, res: ServerResponse, next: () => void) => {
@@ -63,6 +68,16 @@ export default function middleware({ routes, store }: {
: ''; : '';
} }
if (!emitted_basepath && process.send) {
process.send({
__sapper__: true,
event: 'basepath',
basepath: req.baseUrl
});
emitted_basepath = true;
}
if (req.path === undefined) { if (req.path === undefined) {
req.path = req.url.replace(/\?.*/, ''); req.path = req.url.replace(/\?.*/, '');
} }
@@ -90,7 +105,7 @@ export default function middleware({ routes, store }: {
cache_control: 'max-age=31536000' cache_control: 'max-age=31536000'
}), }),
get_route_handler(client_info.assets, routes, store) get_route_handler(client_assets, App, routes, store)
].filter(Boolean)); ].filter(Boolean));
return middleware; return middleware;
@@ -133,9 +148,7 @@ function serve({ prefix, pathname, cache_control }: {
}; };
} }
const resolved = Promise.resolve(); function get_route_handler(chunks: Record<string, string>, App: Component, routes: RouteObject[], store_getter: (req: Req) => Store) {
function get_route_handler(chunks: Record<string, string>, routes: RouteObject[], store_getter: (req: Req) => Store) {
const template = dev() const template = dev()
? () => 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'));
@@ -143,195 +156,214 @@ 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() {
res.setHeader('Content-Type', 'text/html'); try {
const { value: handler, done } = handlers.next();
// preload main.js and current route if (done) {
// TODO detect other stuff we can preload? images, CSS, fonts? handle_error(req, res, 404, 'Not found');
const link = [] return;
.concat(chunks.main, chunks[route.id]) }
.filter(file => !file.match(/\.map$/))
.map(file => `<${req.baseUrl}/client/${file}>;rel="preload";as="script"`)
.join(', ');
res.setHeader('Link', link); const mod = handler.module;
const store = store_getter ? store_getter(req) : null; if (handler.type === 'page') {
const data = { params: req.params, query: req.query }; res.setHeader('Content-Type', 'text/html');
let redirect: { statusCode: number, location: string }; // preload main.js and current route
let error: { statusCode: number, message: Error | string }; // TODO detect other stuff we can preload? images, CSS, fonts?
const link = []
.concat(chunks.main, chunks[route.id])
.filter(file => !file.match(/\.map$/))
.map(file => `<${req.baseUrl}/client/${file}>;rel="preload";as="script"`)
.join(', ');
Promise.resolve( res.setHeader('Link', link);
mod.preload ? mod.preload.call({
redirect: (statusCode: number, location: string) => {
redirect = { statusCode, location };
},
error: (statusCode: number, message: Error | string) => {
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) { const store = store_getter ? store_getter(req) : null;
opts = Object.assign({}, opts); const props = { params: req.params, query: req.query, path: req.path };
const include_cookies = ( let redirect: { statusCode: number, location: string };
opts.credentials === 'include' || let error: { statusCode: number, message: Error | string };
opts.credentials === 'same-origin' && parsed.origin === `http://127.0.0.1:${process.env.PORT}`
);
if (include_cookies) { Promise.resolve(
const cookies: Record<string, string> = {}; mod.preload ? mod.preload.call({
if (!opts.headers) opts.headers = {}; redirect: (statusCode: number, location: string) => {
redirect = { statusCode, location };
},
error: (statusCode: number, message: Error | string) => {
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 + '/' :''}`);
const str = [] if (opts) {
.concat( opts = Object.assign({}, opts);
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; 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 => {
error = { statusCode: 500, message: err };
}).then(preloaded => {
if (redirect) {
res.statusCode = redirect.statusCode;
res.setHeader('Location', `${req.baseUrl}/${redirect.location}`);
res.end();
return;
} }
return fetch(parsed.href, opts); if (error) {
}, handle_error(req, res, error.statusCode, error.message);
store return;
}, req) : {} }
).catch(err => {
error = { statusCode: 500, message: err };
}).then(preloaded => {
if (redirect) {
res.statusCode = redirect.statusCode;
res.setHeader('Location', `${req.baseUrl}/${redirect.location}`);
res.end();
return; const serialized = {
} preloaded: mod.preload && try_serialize(preloaded),
store: store && try_serialize(store.get())
};
Object.assign(props, preloaded);
if (error) { const { html, head, css } = App.render({ Page: mod, props }, {
handle_error(req, res, error.statusCode, error.message); store
return; });
}
const serialized = { let scripts = []
preloaded: mod.preload && try_serialize(preloaded), .concat(chunks.main) // chunks main might be an array. it might not! thanks, webpack
store: store && try_serialize(store.get()) .filter(file => !file.match(/\.map$/))
}; .map(file => `<script src='${req.baseUrl}/client/${file}'></script>`)
Object.assign(data, preloaded); .join('');
const { html, head, css } = mod.render(data, { let inline_script = `__SAPPER__={${[
store `baseUrl: "${req.baseUrl}"`,
}); serialized.preloaded && `preloaded: ${serialized.preloaded}`,
serialized.store && `store: ${serialized.store}`
].filter(Boolean).join(',')}};`;
let scripts = [] const has_service_worker = fs.existsSync(path.join(locations.dest(), 'service-worker.js'));
.concat(chunks.main) // chunks main might be an array. it might not! thanks, webpack if (has_service_worker) {
.filter(file => !file.match(/\.map$/)) inline_script += `if ('serviceWorker' in navigator) navigator.serviceWorker.register('${req.baseUrl}/service-worker.js');`;
.map(file => `<script src='${req.baseUrl}/client/${file}'></script>`) }
.join('');
let inline_script = `__SAPPER__={${[ const page = template()
`baseUrl: "${req.baseUrl}"`, .replace('%sapper.base%', `<base href="${req.baseUrl}/">`)
serialized.preloaded && `preloaded: ${serialized.preloaded}`, .replace('%sapper.scripts%', `<script>${inline_script}</script>${scripts}`)
serialized.store && `store: ${serialized.store}` .replace('%sapper.html%', html)
].filter(Boolean).join(',')}};`; .replace('%sapper.head%', `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`)
.replace('%sapper.styles%', (css && css.code ? `<style>${css.code}</style>` : ''));
const has_service_worker = fs.existsSync(path.join(locations.dest(), 'service-worker.js')); res.end(page);
if (has_service_worker) {
inline_script += `if ('serviceWorker' in navigator) navigator.serviceWorker.register('${req.baseUrl}/service-worker.js');`;
}
const page = template() if (process.send) {
.replace('%sapper.base%', `<base href="${req.baseUrl}/">`) process.send({
.replace('%sapper.scripts%', `<script>${inline_script}</script>${scripts}`) __sapper__: true,
.replace('%sapper.html%', html) event: 'file',
.replace('%sapper.head%', `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`) url: req.url,
.replace('%sapper.styles%', (css && css.code ? `<style>${css.code}</style>` : '')); method: req.method,
status: 200,
res.end(page); type: 'text/html',
body: page
if (process.send) { });
process.send({ }
__sapper__: true,
url: req.url,
method: req.method,
status: 200,
type: 'text/html',
body: page
}); });
} }
});
}
else { else {
const method = req.method.toLowerCase(); const method = req.method.toLowerCase();
// '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[] = [];
const headers: Record<string, string> = {}; const headers: Record<string, string> = {};
// intercept data so that it can be exported // intercept data so that it can be exported
res.write = function(chunk: any) { res.write = function(chunk: any) {
chunks.push(new Buffer(chunk)); chunks.push(new Buffer(chunk));
write.apply(res, arguments); write.apply(res, arguments);
}; };
res.setHeader = function(name: string, value: string) { res.setHeader = function(name: string, value: string) {
headers[name.toLowerCase()] = value; headers[name.toLowerCase()] = value;
setHeader.apply(res, arguments); setHeader.apply(res, arguments);
}; };
res.end = function(chunk?: any) { res.end = function(chunk?: any) {
if (chunk) chunks.push(new Buffer(chunk)); if (chunk) chunks.push(new Buffer(chunk));
end.apply(res, arguments); end.apply(res, arguments);
process.send({ process.send({
__sapper__: true, __sapper__: true,
url: req.url, event: 'file',
method: req.method, url: req.url,
status: res.statusCode, method: req.method,
type: headers['content-type'], status: res.statusCode,
body: Buffer.concat(chunks).toString() type: headers['content-type'],
}); body: Buffer.concat(chunks).toString()
}; });
} };
}
const handle_bad_result = (err?: Error) => { const handle_bad_result = (err?: Error) => {
if (err) { if (err) {
console.error(err.stack); console.error(err.stack);
res.statusCode = 500; res.statusCode = 500;
res.end(err.message); res.end(err.message);
} else {
process.nextTick(next);
}
};
try {
handle_method(req, res, handle_bad_result);
} catch (err) {
handle_bad_result(err);
}
} else { } else {
handle_error(req, res, 404, 'Not found'); // no matching handler for method
process.nextTick(next);
} }
};
try {
handler(req, res, handle_bad_result);
} catch (err) {
handle_bad_result(err);
} }
} else { } catch (error) {
// no matching handler for method — 404 handle_error(req, res, 500, error);
handle_error(req, res, 404, 'Not found');
} }
} }
next();
} }
const not_found_route = routes.find((route: RouteObject) => route.error === '4xx'); const not_found_route = routes.find((route: RouteObject) => route.error === '4xx');
@@ -349,39 +381,62 @@ 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' const page = template()
: `Internal server error: ${error.message}`; .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.html%', html)
.replace('%sapper.head%', `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`)
.replace('%sapper.styles%', (css && css.code ? `<style>${css.code}</style>` : ''));
const rendered = route ? route.module.render({ res.end(page);
status: statusCode, }
error
}, {
store: store_getter && store_getter(req)
}) : { head: '', css: null, html: title };
const { head, css, html } = rendered; function handle_notfound() {
const title: string = not_found
? 'Not found'
: `Internal server error: ${error.message}`;
const page = template() render_page({ head: '', css: null, html: title });
.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.html%', html)
.replace('%sapper.head%', `<noscript id='sapper-head-start'></noscript>${head}<noscript id='sapper-head-end'></noscript>`)
.replace('%sapper.styles%', (css && css.code ? `<style>${css.code}</style>` : ''));
res.end(page); 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');
} catch (error) {
handle_error(req, res, 500, error);
} }
handle_error(req, res, 404, 'Not found');
}; };
} }
@@ -405,10 +460,6 @@ function compose_handlers(handlers: Handler[]) {
}; };
} }
function read_json(file: string) {
return JSON.parse(fs.readFileSync(file, 'utf-8'));
}
function try_serialize(data: any) { function try_serialize(data: any) {
try { try {
return devalue(data); return devalue(data);

View File

@@ -3,6 +3,7 @@ import { Component, ComponentConstructor, Params, Query, Route, RouteData, Scrol
const manifest = typeof window !== 'undefined' && window.__SAPPER__; const manifest = typeof window !== 'undefined' && window.__SAPPER__;
export let App: ComponentConstructor;
export let component: Component; export let component: Component;
let target: Node; let target: Node;
let store: Store; let store: Store;
@@ -27,10 +28,10 @@ function select_route(url: URL): Target {
if (url.origin !== window.location.origin) return null; if (url.origin !== window.location.origin) return null;
if (!url.pathname.startsWith(manifest.baseUrl)) return null; if (!url.pathname.startsWith(manifest.baseUrl)) return null;
const pathname = url.pathname.slice(manifest.baseUrl.length); const path = url.pathname.slice(manifest.baseUrl.length);
for (const route of routes) { for (const route of routes) {
const match = route.pattern.exec(pathname); const match = route.pattern.exec(path);
if (match) { if (match) {
if (route.ignore) return null; if (route.ignore) return null;
@@ -43,18 +44,24 @@ function select_route(url: URL): Target {
query[key] = value || true; query[key] = value || true;
}) })
} }
return { url, route, data: { params, query } }; return { url, route, props: { params, query, path } };
} }
} }
} }
let current_token: {}; let current_token: {};
function render(Component: ComponentConstructor, data: any, scroll: ScrollPosition, token: {}) { function render(Page: ComponentConstructor, props: any, scroll: ScrollPosition, token: {}) {
if (current_token !== token) return; if (current_token !== token) return;
const data = {
Page,
props,
preloading: false
};
if (component) { if (component) {
component.destroy(); component.set(data);
} else { } else {
// first load — remove SSR'd <head> contents // first load — remove SSR'd <head> contents
const start = document.querySelector('#sapper-head-start'); const start = document.querySelector('#sapper-head-start');
@@ -65,33 +72,39 @@ function render(Component: ComponentConstructor, data: any, scroll: ScrollPositi
detach(start); detach(start);
detach(end); detach(end);
} }
}
component = new Component({ component = new App({
target, target,
data, data,
store, store,
hydrate: !component hydrate: true
}); });
}
if (scroll) { if (scroll) {
window.scrollTo(scroll.x, scroll.y); window.scrollTo(scroll.x, scroll.y);
} }
} }
function prepare_route(Component: ComponentConstructor, data: RouteData) { function prepare_route(Page: ComponentConstructor, props: RouteData) {
let redirect: { statusCode: number, location: string } = null; let redirect: { statusCode: number, location: string } = null;
let error: { statusCode: number, message: Error | string } = null; let error: { statusCode: number, message: Error | string } = null;
if (!Component.preload) { if (!Page.preload) {
return { Component, data, redirect, error }; return { Page, props, redirect, error };
} }
if (!component && manifest.preloaded) { if (!component && manifest.preloaded) {
return { Component, data: Object.assign(data, manifest.preloaded), redirect, error }; return { Page, props: Object.assign(props, manifest.preloaded), redirect, error };
} }
return Promise.resolve(Component.preload.call({ if (component) {
component.set({
preloading: true
});
}
return Promise.resolve(Page.preload.call({
store, store,
fetch: (url: string, opts?: any) => window.fetch(url, opts), fetch: (url: string, opts?: any) => window.fetch(url, opts),
redirect: (statusCode: number, location: string) => { redirect: (statusCode: number, location: string) => {
@@ -100,7 +113,7 @@ function prepare_route(Component: ComponentConstructor, data: RouteData) {
error: (statusCode: number, message: Error | string) => { error: (statusCode: number, message: Error | string) => {
error = { statusCode, message }; error = { statusCode, message };
} }
}, data)).catch(err => { }, props)).catch(err => {
error = { statusCode: 500, message: err }; error = { statusCode: 500, message: err };
}).then(preloaded => { }).then(preloaded => {
if (error) { if (error) {
@@ -108,15 +121,15 @@ function prepare_route(Component: ComponentConstructor, data: RouteData) {
? errors['4xx'] ? errors['4xx']
: errors['5xx']; : errors['5xx'];
return route.load().then(({ default: Component }: { default: ComponentConstructor }) => { return route.load().then(({ default: Page }: { default: ComponentConstructor }) => {
const err = error.message instanceof Error ? error.message : new Error(error.message); const err = error.message instanceof Error ? error.message : new Error(error.message);
Object.assign(data, { status: error.statusCode, error: err }); Object.assign(props, { status: error.statusCode, error: err });
return { Component, data, redirect: null }; return { Page, props, redirect: null };
}); });
} }
Object.assign(data, preloaded) Object.assign(props, preloaded)
return { Component, data, redirect }; return { Page, props, redirect };
}); });
} }
@@ -136,18 +149,18 @@ function navigate(target: Target, id: number) {
const loaded = prefetching && prefetching.href === target.url.href ? const loaded = prefetching && prefetching.href === target.url.href ?
prefetching.promise : prefetching.promise :
target.route.load().then(mod => prepare_route(mod.default, target.data)); target.route.load().then(mod => prepare_route(mod.default, target.props));
prefetching = null; prefetching = null;
const token = current_token = {}; const token = current_token = {};
return loaded.then(({ Component, data, redirect }) => { return loaded.then(({ Page, props, redirect }) => {
if (redirect) { if (redirect) {
return goto(redirect.location, { replaceState: true }); return goto(redirect.location, { replaceState: true });
} }
render(Component, data, scroll_history[id], token); render(Page, props, scroll_history[id], token);
}); });
} }
@@ -208,7 +221,7 @@ function handle_popstate(event: PopStateEvent) {
let prefetching: { let prefetching: {
href: string; href: string;
promise: Promise<{ Component: ComponentConstructor, data: any }>; promise: Promise<{ Page: ComponentConstructor, props: any }>;
} = null; } = null;
export function prefetch(href: string) { export function prefetch(href: string) {
@@ -217,7 +230,7 @@ export function prefetch(href: string) {
if (selected && (!prefetching || href !== prefetching.href)) { if (selected && (!prefetching || href !== prefetching.href)) {
prefetching = { prefetching = {
href, href,
promise: selected.route.load().then(mod => prepare_route(mod.default, selected.data)) promise: selected.route.load().then(mod => prepare_route(mod.default, selected.props))
}; };
} }
} }
@@ -240,12 +253,17 @@ function trigger_prefetch(event: MouseEvent | TouchEvent) {
let inited: boolean; let inited: boolean;
export function init(_target: Node, _routes: Route[], opts?: { store?: (data: any) => Store }) { export function init(opts: { App: ComponentConstructor, target: Node, routes: Route[], store?: (data: any) => Store }) {
target = _target; if (opts instanceof HTMLElement) {
routes = _routes.filter(r => !r.error); throw new Error(`The signature of init(...) has changed — see https://sapper.svelte.technology/guide#0-11-to-0-12 for more information`);
}
App = opts.App;
target = opts.target;
routes = opts.routes.filter(r => !r.error);
errors = { errors = {
'4xx': _routes.find(r => r.error === '4xx'), '4xx': opts.routes.find(r => r.error === '4xx'),
'5xx': _routes.find(r => r.error === '5xx') '5xx': opts.routes.find(r => r.error === '5xx')
}; };
if (opts && opts.store) { if (opts && opts.store) {

View File

@@ -3,11 +3,11 @@ import { Store } from '../interfaces';
export { Store }; export { Store };
export type Params = Record<string, string>; export type Params = Record<string, string>;
export type Query = Record<string, string | true>; export type Query = Record<string, string | true>;
export type RouteData = { params: Params, query: Query }; export type RouteData = { params: Params, query: Query, path: string };
export interface ComponentConstructor { export interface ComponentConstructor {
new (options: { target: Node, data: any, store: Store, hydrate: boolean }): Component; new (options: { target: Node, data: any, store: Store, hydrate: boolean }): Component;
preload: (data: { params: Params, query: Query }) => Promise<any>; preload: (props: { params: Params, query: Query }) => Promise<any>;
}; };
export interface Component { export interface Component {
@@ -30,5 +30,5 @@ export type ScrollPosition = {
export type Target = { export type Target = {
url: URL; url: URL;
route: Route; route: Route;
data: RouteData; props: RouteData;
}; };

6
test/app/app/App.html Normal file
View File

@@ -0,0 +1,6 @@
{#if preloading}
<progress class='preloading-progress' value=0.5/>
{/if}
<svelte:component this={Page} {...props}/>

View File

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

View File

@@ -5,6 +5,7 @@ import serve from 'serve-static';
import sapper from '../../../dist/middleware.ts.js'; import sapper from '../../../dist/middleware.ts.js';
import { Store } from 'svelte/store.js'; import { Store } from 'svelte/store.js';
import { routes } from './manifest/server.js'; import { routes } from './manifest/server.js';
import App from './App.html'
let pending; let pending;
let ended; let ended;
@@ -86,6 +87,7 @@ const middlewares = [
}, },
sapper({ sapper({
App,
routes, routes,
store: () => { store: () => {
return new Store({ return new Store({

View File

@@ -133,6 +133,7 @@ function run({ mode, basepath = '' }) {
let capture; let capture;
let base; let base;
let captured_basepath;
const nightmare = new Nightmare(); const nightmare = new Nightmare();
@@ -179,7 +180,13 @@ function run({ mode, basepath = '' }) {
let handler; let handler;
proc.on('message', message => { proc.on('message', message => {
if (message.__sapper__) return; if (message.__sapper__) {
if (message.event === 'basepath') {
captured_basepath = basepath;
}
return;
}
if (handler) handler(message); if (handler) handler(message);
}); });
@@ -574,6 +581,33 @@ function run({ mode, basepath = '' }) {
assert.ok(html.indexOf('service-worker.js') !== -1); assert.ok(html.indexOf('service-worker.js') !== -1);
}); });
}); });
it('sets preloading true when appropriate', () => {
return nightmare
.goto(base)
.init()
.click('a[href="slow-preload"]')
.wait(100)
.evaluate(() => {
const progress = document.querySelector('progress');
return !!progress;
})
.then(hasProgressIndicator => {
assert.ok(hasProgressIndicator);
})
.then(() => nightmare.evaluate(() => window.fulfil()))
.then(() => nightmare.evaluate(() => {
const progress = document.querySelector('progress');
return !!progress;
}))
.then(hasProgressIndicator => {
assert.ok(!hasProgressIndicator);
});
});
it('emits a basepath', () => {
assert.equal(captured_basepath, basepath);
});
}); });
describe('headers', () => { describe('headers', () => {

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']
); );
}); });