From 5289fc11d8d6591b1a9e26311b3b34fb22e5cd67 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 5 Mar 2018 13:51:11 -0500 Subject: [PATCH 1/7] better CLI, more port control. fixes #169 --- package.json | 4 +- src/cli/build.ts | 13 ++++- src/cli/dev.ts | 15 ++--- src/cli/export.ts | 6 +- src/cli/help.md | 20 ------- src/cli/index.ts | 125 ++++++++++++++++++++++++---------------- src/cli/port-utils.ts | 66 +++++++++++++++++++++ src/cli/utils.ts | 25 -------- src/middleware/index.ts | 10 +--- src/utils.ts | 10 ++++ 10 files changed, 176 insertions(+), 118 deletions(-) delete mode 100644 src/cli/help.md create mode 100644 src/cli/port-utils.ts delete mode 100644 src/cli/utils.ts create mode 100644 src/utils.ts diff --git a/package.json b/package.json index 22ce1b31e..431731873 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,6 @@ "code-frame": "^5.0.0", "escape-html": "^1.0.3", "express": "^4.16.2", - "get-port": "^3.2.0", "glob": "^7.1.2", "locate-character": "^2.0.5", "mkdirp": "^0.5.1", @@ -35,10 +34,11 @@ "relative": "^3.0.2", "require-relative": "^0.8.7", "rimraf": "^2.6.2", + "sade": "^1.4.0", "sander": "^0.6.0", "serialize-javascript": "^1.4.0", "source-map-support": "^0.5.3", - "tslib": "^1.8.1", + "tslib": "^1.9.0", "url-parse": "^1.2.0", "walk-sync": "^0.3.2", "webpack-format-messages": "^1.0.1" diff --git a/src/cli/build.ts b/src/cli/build.ts index 5d0f4642c..823b22b05 100644 --- a/src/cli/build.ts +++ b/src/cli/build.ts @@ -1,5 +1,6 @@ import * as fs from 'fs'; import * as path from 'path'; +import chalk from 'chalk'; import mkdirp from 'mkdirp'; import rimraf from 'rimraf'; import { create_compilers, create_app, create_routes, create_serviceworker } from 'sapper/core.js' @@ -19,9 +20,15 @@ export default async function build() { const { client, server, serviceworker } = create_compilers(); const client_stats = await compile(client); + console.log(chalk.inverse(`\nbuilt client`)); + console.log(client_stats.toString({ colors: true })); fs.writeFileSync(path.join(output, 'client_info.json'), JSON.stringify(client_stats.toJson())); - await compile(server); + const server_stats = await compile(server); + console.log(chalk.inverse(`\nbuilt server`)); + console.log(server_stats.toString({ colors: true })); + + let serviceworker_stats; if (serviceworker) { create_serviceworker({ @@ -30,7 +37,9 @@ export default async function build() { src }); - await compile(serviceworker); + serviceworker_stats = await compile(serviceworker); + console.log(chalk.inverse(`\nbuilt service worker`)); + console.log(serviceworker_stats.toString({ colors: true })); } } diff --git a/src/cli/dev.ts b/src/cli/dev.ts index ac342d66b..b0692dfe6 100644 --- a/src/cli/dev.ts +++ b/src/cli/dev.ts @@ -8,7 +8,7 @@ import mkdirp from 'mkdirp'; import rimraf from 'rimraf'; import format_messages from 'webpack-format-messages'; import prettyMs from 'pretty-ms'; -import { wait_for_port } from './utils'; +import * as port_utils from './port-utils'; import { dest } from '../config'; import { create_compilers, create_app, create_routes, create_serviceworker } from 'sapper/core.js'; @@ -70,15 +70,14 @@ function create_hot_update_server(port: number, interval = 10000) { return { send }; } -export default async function dev() { +export default async function dev(port: number) { process.env.NODE_ENV = 'development'; const dir = dest(); rimraf.sync(dir); mkdirp.sync(dir); - // initial build - const dev_port = await require('get-port')(10000); + const dev_port = await port_utils.find(10000); const routes = create_routes(); create_app({ routes, dev_port }); @@ -109,7 +108,7 @@ export default async function dev() { unique_errors: new Set() }; - function restart_build(filename) { + function restart_build(filename: string) { if (restarting) return; restarting = true; @@ -206,7 +205,7 @@ export default async function dev() { deferreds.client.promise.then(() => { function restart() { - wait_for_port(3000).then(deferreds.server.fulfil); // TODO control port + port_utils.wait(3000).then(deferreds.server.fulfil); // TODO control port } if (proc) { @@ -218,7 +217,9 @@ export default async function dev() { proc = child_process.fork(`${dir}/server.js`, [], { cwd: process.cwd(), - env: Object.assign({}, process.env) + env: Object.assign({ + PORT: port + }, process.env) }); }); } diff --git a/src/cli/export.ts b/src/cli/export.ts index a5af63fca..b3e9625bc 100644 --- a/src/cli/export.ts +++ b/src/cli/export.ts @@ -5,7 +5,7 @@ import express from 'express'; import cheerio from 'cheerio'; import URL from 'url-parse'; import fetch from 'node-fetch'; -import { wait_for_port } from './utils'; +import * as port_utils from './port-utils'; import { dest } from '../config'; const app = express(); @@ -27,7 +27,7 @@ export default async function exporter(export_dir: string) { sander.copyFileSync(build_dir, 'service-worker.js').to(export_dir, 'service-worker.js'); } - const port = await require('get-port')(3000); + const port = await port_utils.find(3000); const origin = `http://localhost:${port}`; @@ -88,7 +88,7 @@ export default async function exporter(export_dir: string) { }); } - wait_for_port(port) + return port_utils.wait(port) .then(() => handle(new URL(origin))) // TODO all static routes .then(() => proc.kill()); } \ No newline at end of file diff --git a/src/cli/help.md b/src/cli/help.md deleted file mode 100644 index 8d52abb7b..000000000 --- a/src/cli/help.md +++ /dev/null @@ -1,20 +0,0 @@ -# sapper v<@version@> - -https://sapper.svelte.technology - -> sapper dev - -Start a development server - -> sapper build - -Creates a production-ready version of your app - -> sapper export - -If possible, exports your app as static files, suitable for hosting on -services like Netlify or Surge - -> sapper --help - -Shows this message \ No newline at end of file diff --git a/src/cli/index.ts b/src/cli/index.ts index a93f017ea..3c3e06b1a 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -1,89 +1,114 @@ import * as path from 'path'; import * as child_process from 'child_process'; +import sade from 'sade'; import mri from 'mri'; import chalk from 'chalk'; +import prettyMs from 'pretty-ms'; import help from './help.md'; import build from './build'; import exporter from './export'; import dev from './dev'; import upgrade from './upgrade'; +import * as port_utils from './port-utils'; +import { exists } from '../utils'; import * as pkg from '../../package.json'; -const opts = mri(process.argv.slice(2), { - alias: { - h: 'help' - } -}); +const prog = sade('sapper'); -if (opts.help) { - const rendered = help - .replace('<@version@>', pkg.version) - .replace(/^(.+)/gm, (m: string, $1: string) => /[#>]/.test(m) ? $1 : ` ${$1}`) - .replace(/^# (.+)/gm, (m: string, $1: string) => chalk.bold.underline($1)) - .replace(/^> (.+)/gm, (m: string, $1: string) => chalk.cyan($1)); +prog.version(pkg.version); - console.log(`\n${rendered}\n`); - process.exit(0); -} +prog.command('dev') + .describe('Start a development server') + .option('-p, --port', 'Specify a port') + .action(async ({ port }: { port: number }) => { + if (port) { + if (!await port_utils.check(port)) { + console.log(chalk.bold.red(`> Port ${port} is unavailable`)); + return; + } + } else { + port = await port_utils.find(3000); + } -const [cmd] = opts._; + dev(port); + }); -const start = Date.now(); +prog.command('build [dest]') + .describe('Create a production-ready version of your app') + .action((dest = 'build') => { + console.log(`> Building...`); -switch (cmd) { - case 'build': process.env.NODE_ENV = 'production'; - process.env.SAPPER_DEST = opts._[1] || 'build'; + process.env.SAPPER_DEST = dest; + + const start = Date.now(); build() .then(() => { const elapsed = Date.now() - start; - console.error(`built in ${elapsed}ms`); // TODO beautify this, e.g. 'built in 4.7 seconds' + console.error(`\n> Finished in ${prettyMs(elapsed)}. Type ${chalk.bold.cyan(dest === 'build' ? 'npx sapper start' : `npx sapper start ${dest}`)} to run the app.`); }) .catch(err => { console.error(err ? err.details || err.stack || err.message || err : 'Unknown error'); }); + }); + +prog.command('start [dir]') + .describe('Start your app') + .option('-p, --port', 'Specify a port') + .action(async (dir = 'build', { port }: { port: number }) => { + const resolved = path.resolve(dir); + const server = path.resolve(dir, 'server.js'); + + if (!exists(server)) { + console.log(chalk.bold.red(`> ${dir}/server.js does not exist — type ${chalk.bold.cyan(dir === 'build' ? `npx sapper build` : `npx sapper build ${dir}`)} to create it`)); + return; + } + + if (port) { + if (!await port_utils.check(port)) { + console.log(chalk.bold.red(`> Port ${port} is unavailable`)); + return; + } + } else { + port = await port_utils.find(3000); + } + + child_process.fork(server, [], { + cwd: process.cwd(), + env: Object.assign({ + NODE_ENV: 'production', + PORT: port, + SAPPER_DEST: dir + }, process.env) + }); + }); - break; +prog.command('export [dest]') + .describe('Export your app as static files (if possible)') + .action((dest = 'export') => { + console.log(`> Building...`); - case 'export': process.env.NODE_ENV = 'production'; + process.env.SAPPER_DEST = '.sapper/.export'; - const export_dir = opts._[1] || 'export'; + const start = Date.now(); build() - .then(() => exporter(export_dir)) .then(() => { const elapsed = Date.now() - start; - console.error(`extracted in ${elapsed}ms`); // TODO beautify this, e.g. 'built in 4.7 seconds' + console.error(`\n> Built in ${prettyMs(elapsed)}. Exporting...`); + }) + .then(() => exporter(dest)) + .then(() => { + const elapsed = Date.now() - start; + console.error(`\n> Finished in ${prettyMs(elapsed)}. Type ${chalk.bold.cyan(`npx serve ${dest}`)} to run the app.`); }) .catch(err => { console.error(err ? err.details || err.stack || err.message || err : 'Unknown error'); }); + }); - break; - - case 'dev': - dev(); - break; - - case 'upgrade': - upgrade(); - break; - - case 'start': - const dir = path.resolve(opts._[1] || 'build'); - - child_process.fork(`${dir}/server.js`, [], { - cwd: process.cwd(), - env: Object.assign({ - NODE_ENV: 'production', - SAPPER_DEST: dir - }, process.env) - }); - - break; +// TODO upgrade - default: - console.log(`unrecognized command ${cmd} — try \`sapper --help\` for more information`); -} \ No newline at end of file +prog.parse(process.argv); \ No newline at end of file diff --git a/src/cli/port-utils.ts b/src/cli/port-utils.ts new file mode 100644 index 000000000..7719171f4 --- /dev/null +++ b/src/cli/port-utils.ts @@ -0,0 +1,66 @@ +import * as net from 'net'; + +export function check(port: number) { + return new Promise(fulfil => { + const server = net.createServer(); + + server.unref(); + + server.on('error', () => { + fulfil(false); + }); + + server.listen({ port }, () => { + server.close(() => { + fulfil(true); + }); + }); + }); +} + +export function find(port: number): Promise { + return new Promise((fulfil) => { + get_port(port, fulfil); + }); +} + +function get_port(port: number, cb: (port: number) => void) { + const server = net.createServer(); + + server.unref(); + + server.on('error', () => { + get_port(port + 1, cb); + }); + + server.listen({ port }, () => { + server.close(() => { + cb(port); + }); + }); +} + +export function wait(port: number, timeout = 5000) { + return new Promise((fulfil, reject) => { + get_connection(port, fulfil); + setTimeout(() => reject(new Error(`timed out waiting for connection`)), timeout); + }); +} + +function get_connection(port: number, cb: () => void) { + const socket = net.connect(port, 'localhost', () => { + cb(); + socket.destroy(); + }); + + socket.on('error', err => { + setTimeout(() => { + get_connection(port, cb); + }, 10); + }); + + setTimeout(() => { + socket.destroy(); + }, 1000); +} + diff --git a/src/cli/utils.ts b/src/cli/utils.ts deleted file mode 100644 index 0c1078e17..000000000 --- a/src/cli/utils.ts +++ /dev/null @@ -1,25 +0,0 @@ -import * as net from 'net'; - -export function wait_for_port(port: number, timeout = 5000) { - return new Promise((fulfil, reject) => { - get_connection(port, fulfil); - setTimeout(() => reject(new Error(`timed out waiting for connection`)), timeout); - }); -} - -export function get_connection(port: number, cb: () => void) { - const socket = net.createConnection(port, 'localhost', () => { - cb(); - socket.destroy(); - }); - - socket.on('error', err => { - setTimeout(() => { - get_connection(port, cb); - }, 10); - }); - - setTimeout(() => { - socket.destroy(); - }, 1000); -} \ No newline at end of file diff --git a/src/middleware/index.ts b/src/middleware/index.ts index 5df33e4b1..bef1cb5de 100644 --- a/src/middleware/index.ts +++ b/src/middleware/index.ts @@ -7,6 +7,7 @@ import serialize from 'serialize-javascript'; import escape_html from 'escape-html'; import { lookup } from './mime'; import { create_routes, templates, create_compilers } from 'sapper/core.js'; +import { exists } from '../utils'; import { dest, dev } from '../config'; import { Route, Template } from '../interfaces'; import sourceMapSupport from 'source-map-support'; @@ -336,13 +337,4 @@ function try_serialize(data: any) { } catch (err) { return null; } -} - -function exists(file: string) { - try { - fs.statSync(file); - return true; - } catch (err) { - return false; - } } \ No newline at end of file diff --git a/src/utils.ts b/src/utils.ts new file mode 100644 index 000000000..be0f7a4b4 --- /dev/null +++ b/src/utils.ts @@ -0,0 +1,10 @@ +import * as fs from 'fs'; + +export function exists(file: string) { + try { + fs.statSync(file); + return true; + } catch (err) { + return false; + } +} \ No newline at end of file From d9d93f41c45b89dee486c20fc4ef9c97a2950f7a Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 5 Mar 2018 13:57:30 -0500 Subject: [PATCH 2/7] add get-port back as dev dependency, for testing --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 431731873..111098fed 100644 --- a/package.json +++ b/package.json @@ -53,6 +53,7 @@ "electron": "^1.8.2", "eslint": "^4.13.1", "eslint-plugin-import": "^2.8.0", + "get-port": "^3.2.0", "mocha": "^4.0.1", "nightmare": "^2.10.0", "npm-run-all": "^4.1.2", From 0f8c04b03d15d6029ed578bb5565ac87ba5a1a97 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 5 Mar 2018 15:09:33 -0500 Subject: [PATCH 3/7] use port-authority --- src/cli/dev.ts | 6 ++-- src/cli/export.ts | 7 +++-- src/cli/index.ts | 10 +++---- src/cli/port-utils.ts | 66 ------------------------------------------- 4 files changed, 12 insertions(+), 77 deletions(-) delete mode 100644 src/cli/port-utils.ts diff --git a/src/cli/dev.ts b/src/cli/dev.ts index b0692dfe6..eef7fb1db 100644 --- a/src/cli/dev.ts +++ b/src/cli/dev.ts @@ -8,7 +8,7 @@ import mkdirp from 'mkdirp'; import rimraf from 'rimraf'; import format_messages from 'webpack-format-messages'; import prettyMs from 'pretty-ms'; -import * as port_utils from './port-utils'; +import * as ports from 'port-authority'; import { dest } from '../config'; import { create_compilers, create_app, create_routes, create_serviceworker } from 'sapper/core.js'; @@ -77,7 +77,7 @@ export default async function dev(port: number) { rimraf.sync(dir); mkdirp.sync(dir); - const dev_port = await port_utils.find(10000); + const dev_port = await ports.find(10000); const routes = create_routes(); create_app({ routes, dev_port }); @@ -205,7 +205,7 @@ export default async function dev(port: number) { deferreds.client.promise.then(() => { function restart() { - port_utils.wait(3000).then(deferreds.server.fulfil); // TODO control port + ports.wait(3000).then(deferreds.server.fulfil); // TODO control port } if (proc) { diff --git a/src/cli/export.ts b/src/cli/export.ts index b3e9625bc..05bf4be1e 100644 --- a/src/cli/export.ts +++ b/src/cli/export.ts @@ -5,7 +5,7 @@ import express from 'express'; import cheerio from 'cheerio'; import URL from 'url-parse'; import fetch from 'node-fetch'; -import * as port_utils from './port-utils'; +import * as ports from 'port-authority'; import { dest } from '../config'; const app = express(); @@ -27,7 +27,7 @@ export default async function exporter(export_dir: string) { sander.copyFileSync(build_dir, 'service-worker.js').to(export_dir, 'service-worker.js'); } - const port = await port_utils.find(3000); + const port = await ports.find(3000); const origin = `http://localhost:${port}`; @@ -36,6 +36,7 @@ export default async function exporter(export_dir: string) { env: { PORT: port, NODE_ENV: 'production', + SAPPER_DEST: build_dir, SAPPER_EXPORT: 'true' } }); @@ -88,7 +89,7 @@ export default async function exporter(export_dir: string) { }); } - return port_utils.wait(port) + return ports.wait(port) .then(() => handle(new URL(origin))) // TODO all static routes .then(() => proc.kill()); } \ No newline at end of file diff --git a/src/cli/index.ts b/src/cli/index.ts index 3c3e06b1a..e96df3a0d 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -9,7 +9,7 @@ import build from './build'; import exporter from './export'; import dev from './dev'; import upgrade from './upgrade'; -import * as port_utils from './port-utils'; +import * as ports from 'port-authority'; import { exists } from '../utils'; import * as pkg from '../../package.json'; @@ -22,12 +22,12 @@ prog.command('dev') .option('-p, --port', 'Specify a port') .action(async ({ port }: { port: number }) => { if (port) { - if (!await port_utils.check(port)) { + if (!await ports.check(port)) { console.log(chalk.bold.red(`> Port ${port} is unavailable`)); return; } } else { - port = await port_utils.find(3000); + port = await ports.find(3000); } dev(port); @@ -66,12 +66,12 @@ prog.command('start [dir]') } if (port) { - if (!await port_utils.check(port)) { + if (!await ports.check(port)) { console.log(chalk.bold.red(`> Port ${port} is unavailable`)); return; } } else { - port = await port_utils.find(3000); + port = await ports.find(3000); } child_process.fork(server, [], { diff --git a/src/cli/port-utils.ts b/src/cli/port-utils.ts deleted file mode 100644 index 7719171f4..000000000 --- a/src/cli/port-utils.ts +++ /dev/null @@ -1,66 +0,0 @@ -import * as net from 'net'; - -export function check(port: number) { - return new Promise(fulfil => { - const server = net.createServer(); - - server.unref(); - - server.on('error', () => { - fulfil(false); - }); - - server.listen({ port }, () => { - server.close(() => { - fulfil(true); - }); - }); - }); -} - -export function find(port: number): Promise { - return new Promise((fulfil) => { - get_port(port, fulfil); - }); -} - -function get_port(port: number, cb: (port: number) => void) { - const server = net.createServer(); - - server.unref(); - - server.on('error', () => { - get_port(port + 1, cb); - }); - - server.listen({ port }, () => { - server.close(() => { - cb(port); - }); - }); -} - -export function wait(port: number, timeout = 5000) { - return new Promise((fulfil, reject) => { - get_connection(port, fulfil); - setTimeout(() => reject(new Error(`timed out waiting for connection`)), timeout); - }); -} - -function get_connection(port: number, cb: () => void) { - const socket = net.connect(port, 'localhost', () => { - cb(); - socket.destroy(); - }); - - socket.on('error', err => { - setTimeout(() => { - get_connection(port, cb); - }, 10); - }); - - setTimeout(() => { - socket.destroy(); - }, 1000); -} - From a66ac00d428ff02a4aec9ad48fd81fd3847f782a Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 5 Mar 2018 15:09:51 -0500 Subject: [PATCH 4/7] tidy up tests --- test/common/test.js | 188 +++++++++++++++++++++++--------------------- 1 file changed, 99 insertions(+), 89 deletions(-) diff --git a/test/common/test.js b/test/common/test.js index 387bb41b4..94cb3647d 100644 --- a/test/common/test.js +++ b/test/common/test.js @@ -5,9 +5,8 @@ const express = require('express'); const serve = require('serve-static'); const walkSync = require('walk-sync'); const fetch = require('node-fetch'); - -run('production'); -run('development'); +const rimraf = require('rimraf'); +const ports = require('port-authority'); Nightmare.action('page', { title(done) { @@ -27,11 +26,94 @@ Nightmare.action('prefetchRoutes', function(done) { this.evaluate_now(() => window.prefetchRoutes(), done); }); +const cli = path.resolve(__dirname, '../../cli.js'); + +describe('sapper', function() { + process.chdir(path.resolve(__dirname, '../app')); + + // clean up after previous test runs + rimraf.sync('export'); + rimraf.sync('build'); + rimraf.sync('.sapper'); + + this.timeout(30000); + + // TODO reinstate dev tests + // run('development'); + run('production'); + + describe('export', () => { + before(() => { + return exec(`node ${cli} export`); + }); + + it('export all pages', () => { + const dest = path.resolve(__dirname, '../app/export'); + + // Pages that should show up in the extraction directory. + const expectedPages = [ + 'index.html', + 'about/index.html', + 'slow-preload/index.html', + + 'blog/index.html', + 'blog/a-very-long-post/index.html', + 'blog/how-can-i-get-involved/index.html', + 'blog/how-is-sapper-different-from-next/index.html', + 'blog/how-to-use-sapper/index.html', + 'blog/what-is-sapper/index.html', + 'blog/why-the-name/index.html', + + 'blog.json', + 'blog/a-very-long-post.json', + 'blog/how-can-i-get-involved.json', + 'blog/how-is-sapper-different-from-next.json', + 'blog/how-to-use-sapper.json', + 'blog/what-is-sapper.json', + 'blog/why-the-name.json', + + 'favicon.png', + 'global.css', + 'great-success.png', + 'manifest.json', + 'service-worker.js', + 'svelte-logo-192.png', + 'svelte-logo-512.png', + ]; + // Client scripts that should show up in the extraction directory. + const expectedClientRegexes = [ + /client\/[^/]+\/_(\.\d+)?\.js/, + /client\/[^/]+\/about(\.\d+)?\.js/, + /client\/[^/]+\/blog_\$slug\$(\.\d+)?\.js/, + /client\/[^/]+\/blog(\.\d+)?\.js/, + /client\/[^/]+\/main(\.\d+)?\.js/, + /client\/[^/]+\/show_url(\.\d+)?\.js/, + /client\/[^/]+\/slow_preload(\.\d+)?\.js/, + ]; + const allPages = walkSync(dest); + + expectedPages.forEach((expectedPage) => { + assert.ok(allPages.includes(expectedPage),`Could not find page matching ${expectedPage}`); + }); + + expectedClientRegexes.forEach((expectedRegex) => { + // Ensure each client page regular expression matches at least one + // generated page. + let matched = false; + for (const page of allPages) { + if (expectedRegex.test(page)) { + matched = true; + break; + } + } + assert.ok(matched, `Could not find client page matching ${expectedRegex}`); + }); + }); + }); +}); + function run(env) { describe(`env=${env}`, function () { - this.timeout(30000); - - let PORT; let proc; let nightmare; let capture; @@ -39,28 +121,23 @@ function run(env) { let base; before(() => { - process.chdir(path.resolve(__dirname, '../app')); - - let exec_promise = Promise.resolve(); - - if (env === 'production') { - const cli = path.resolve(__dirname, '../../cli.js'); - exec_promise = exec(`node ${cli} export`); - } - - return exec_promise.then(() => { - const resolved = require.resolve('../../middleware.js'); - delete require.cache[resolved]; - delete require.cache[require.resolve('../../core.js')]; // TODO remove this + const promise = env === 'production' + ? exec(`node ${cli} build`).then(() => ports.find(3000)) + : ports.find(3000).then(port => { + exec(`node ${cli} dev`); + return ports.wait(port).then(() => port); + }); - return require('get-port')(); - }).then(port => { + return promise.then(port => { base = `http://localhost:${port}`; - proc = require('child_process').fork('.sapper/server.js', { + const dir = env === 'production' ? 'build' : '.sapper'; + + proc = require('child_process').fork(`${dir}/server.js`, { cwd: process.cwd(), env: { NODE_ENV: env, + SAPPER_DEST: dir, PORT: port } }); @@ -430,73 +507,6 @@ function run(env) { }); }); }); - - if (env === 'production') { - describe('export', () => { - it('export all pages', () => { - const dest = path.resolve(__dirname, '../app/export'); - - // Pages that should show up in the extraction directory. - const expectedPages = [ - 'index.html', - 'about/index.html', - 'slow-preload/index.html', - - 'blog/index.html', - 'blog/a-very-long-post/index.html', - 'blog/how-can-i-get-involved/index.html', - 'blog/how-is-sapper-different-from-next/index.html', - 'blog/how-to-use-sapper/index.html', - 'blog/what-is-sapper/index.html', - 'blog/why-the-name/index.html', - - 'blog.json', - 'blog/a-very-long-post.json', - 'blog/how-can-i-get-involved.json', - 'blog/how-is-sapper-different-from-next.json', - 'blog/how-to-use-sapper.json', - 'blog/what-is-sapper.json', - 'blog/why-the-name.json', - - 'favicon.png', - 'global.css', - 'great-success.png', - 'manifest.json', - 'service-worker.js', - 'svelte-logo-192.png', - 'svelte-logo-512.png', - ]; - // Client scripts that should show up in the extraction directory. - const expectedClientRegexes = [ - /client\/[^/]+\/_(\.\d+)?\.js/, - /client\/[^/]+\/about(\.\d+)?\.js/, - /client\/[^/]+\/blog_\$slug\$(\.\d+)?\.js/, - /client\/[^/]+\/blog(\.\d+)?\.js/, - /client\/[^/]+\/main(\.\d+)?\.js/, - /client\/[^/]+\/show_url(\.\d+)?\.js/, - /client\/[^/]+\/slow_preload(\.\d+)?\.js/, - ]; - const allPages = walkSync(dest); - - expectedPages.forEach((expectedPage) => { - assert.ok(allPages.includes(expectedPage),`Could not find page matching ${expectedPage}`); - }); - - expectedClientRegexes.forEach((expectedRegex) => { - // Ensure each client page regular expression matches at least one - // generated page. - let matched = false; - for (const page of allPages) { - if (expectedRegex.test(page)) { - matched = true; - break; - } - } - assert.ok(matched, `Could not find client page matching ${expectedRegex}`); - }); - }); - }); - } }); } From 47b50f2c0ef0c93f814ecd8d0ddb25a194725b00 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 5 Mar 2018 15:09:59 -0500 Subject: [PATCH 5/7] admin --- .gitignore | 1 + package.json | 1 + 2 files changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 2a97c41f4..7ecf62ae0 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ cypress/screenshots test/app/.sapper test/app/app/manifest test/app/export +test/app/build runtime.js runtime.js.map cli.js diff --git a/package.json b/package.json index 111098fed..3fc30037b 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "mkdirp": "^0.5.1", "mri": "^1.1.0", "node-fetch": "^1.7.3", + "port-authority": "^1.0.0", "pretty-ms": "^3.1.0", "relative": "^3.0.2", "require-relative": "^0.8.7", From ffaacb4c9942f554ec4a1a7c2a0d4a04782e2d90 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 5 Mar 2018 15:11:44 -0500 Subject: [PATCH 6/7] use fs.existsSync --- src/cli/index.ts | 4 ++-- src/middleware/index.ts | 5 ++--- src/utils.ts | 10 ---------- 3 files changed, 4 insertions(+), 15 deletions(-) delete mode 100644 src/utils.ts diff --git a/src/cli/index.ts b/src/cli/index.ts index e96df3a0d..bad8a813c 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -1,3 +1,4 @@ +import * as fs from 'fs'; import * as path from 'path'; import * as child_process from 'child_process'; import sade from 'sade'; @@ -10,7 +11,6 @@ import exporter from './export'; import dev from './dev'; import upgrade from './upgrade'; import * as ports from 'port-authority'; -import { exists } from '../utils'; import * as pkg from '../../package.json'; const prog = sade('sapper'); @@ -60,7 +60,7 @@ prog.command('start [dir]') const resolved = path.resolve(dir); const server = path.resolve(dir, 'server.js'); - if (!exists(server)) { + if (!fs.existsSync(server)) { console.log(chalk.bold.red(`> ${dir}/server.js does not exist — type ${chalk.bold.cyan(dir === 'build' ? `npx sapper build` : `npx sapper build ${dir}`)} to create it`)); return; } diff --git a/src/middleware/index.ts b/src/middleware/index.ts index bef1cb5de..6313f2287 100644 --- a/src/middleware/index.ts +++ b/src/middleware/index.ts @@ -7,7 +7,6 @@ import serialize from 'serialize-javascript'; import escape_html from 'escape-html'; import { lookup } from './mime'; import { create_routes, templates, create_compilers } from 'sapper/core.js'; -import { exists } from '../utils'; import { dest, dev } from '../config'; import { Route, Template } from '../interfaces'; import sourceMapSupport from 'source-map-support'; @@ -52,12 +51,12 @@ export default function middleware({ routes }: { next(); }, - exists(path.join(output, 'index.html')) && serve({ + fs.existsSync(path.join(output, 'index.html')) && serve({ pathname: '/index.html', cache_control: 'max-age=600' }), - exists(path.join(output, 'service-worker.js')) && serve({ + fs.existsSync(path.join(output, 'service-worker.js')) && serve({ pathname: '/service-worker.js', cache_control: 'max-age=600' }), diff --git a/src/utils.ts b/src/utils.ts deleted file mode 100644 index be0f7a4b4..000000000 --- a/src/utils.ts +++ /dev/null @@ -1,10 +0,0 @@ -import * as fs from 'fs'; - -export function exists(file: string) { - try { - fs.statSync(file); - return true; - } catch (err) { - return false; - } -} \ No newline at end of file From bc232007c3ed2c4d7d490f47d6a0fabf593a4e68 Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 5 Mar 2018 15:17:34 -0500 Subject: [PATCH 7/7] simplify sade initialisation --- src/cli/index.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/cli/index.ts b/src/cli/index.ts index bad8a813c..c8ad11dd9 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -13,9 +13,7 @@ import upgrade from './upgrade'; import * as ports from 'port-authority'; import * as pkg from '../../package.json'; -const prog = sade('sapper'); - -prog.version(pkg.version); +const prog = sade('sapper').version(pkg.version); prog.command('dev') .describe('Start a development server')