Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add paths: { base, assets } and appDir config #240

Merged
merged 6 commits into from
Dec 9, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions examples/sandbox/snowpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ module.exports = {
'src/components': '/_components'
},
alias: {
'$components': './src/components'
$components: './src/components'
}
};
};
5 changes: 4 additions & 1 deletion packages/adapter-node/src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ const mutable = (dir) =>
});

const noop_handler = (_req, _res, next) => next();
const static_handler = fs.existsSync(app.paths.static) ? mutable(app.paths.static) : noop_handler;

// TODO how to handle the case where `paths.assets !== ''` and `paths.generated !== '/app'`?
// Does that even make sense in the context of adapter-node?
const static_handler = fs.existsSync(app.files.static) ? mutable(app.files.static) : noop_handler;
const prerendered_handler = fs.existsSync('build/prerendered')
? mutable('build/prerendered')
: noop_handler;
Expand Down
3 changes: 2 additions & 1 deletion packages/kit/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ export default [
'internal/start': 'src/runtime/internal/start.js',
'internal/singletons': 'src/runtime/internal/singletons.js',
'app/navigation': 'src/runtime/app/navigation/index.js',
'app/stores': 'src/runtime/app/stores/index.js'
'app/stores': 'src/runtime/app/stores/index.js',
'app/paths': 'src/runtime/app/paths/index.js'
},
output: {
dir: 'assets/runtime',
Expand Down
72 changes: 40 additions & 32 deletions packages/kit/src/api/build/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -266,38 +266,46 @@ export async function build(config) {
fs.writeFileSync(
`${UNOPTIMIZED}/server/app.js`,
`
import * as renderer from '@sveltejs/kit/dist/renderer';
import root from './_app/assets/generated/root.js';
import * as setup from './_app/setup/index.js';
import manifest from '../../manifest.js';

const template = ({ head, body }) => ${s(fs.readFileSync(config.files.template, 'utf-8'))
.replace('%svelte.head%', '" + head + "')
.replace('%svelte.body%', '" + body + "')};

const client = ${s(client)};

export const paths = {
static: ${s(config.files.static)}
};

export function render(request, { only_prerender = false } = {}) {
return renderer.render(request, {
static_dir: paths.static,
template,
manifest,
target: ${s(config.target)},${
config.startGlobal ? `\n\t\t\t\t\tstart_global: ${s(config.startGlobal)},` : ''
}
client,
root,
setup,
load: (route) => require(\`./routes/\${route.name}.js\`),
dev: false,
only_prerender
});
}
`
import * as renderer from '@sveltejs/kit/dist/renderer';
import root from './_app/assets/generated/root.js';
import { set_paths } from './_app/assets/runtime/internal/singletons.js';
import * as setup from './_app/setup/index.js';
import manifest from '../../manifest.js';

const template = ({ head, body }) => ${s(fs.readFileSync(config.files.template, 'utf-8'))
.replace('%svelte.head%', '" + head + "')
.replace('%svelte.body%', '" + body + "')};

const client = ${s(client)};

set_paths(${s(config.paths)});

// allow paths to be overridden in svelte-kit start
export function init({ paths }) {
set_paths(paths);
}

init({ paths: ${s(config.paths)} });

export function render(request, { paths = ${s(config.paths)}, only_prerender = false } = {}) {
return renderer.render(request, {
static_dir: files.static,
paths,
template,
manifest,
target: ${s(config.target)},${
config.startGlobal ? `\n\t\t\t\t\tstart_global: ${s(config.startGlobal)},` : ''
}
client,
root,
setup,
load: (route) => require(\`./routes/\${route.name}.js\`),
dev: false,
only_prerender,
app_dir: ${s(config.appDir)}
});
}
`
.replace(/^\t{3}/gm, '')
.trim()
);
Expand Down
7 changes: 6 additions & 1 deletion packages/kit/src/api/dev/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,9 @@ class Watcher extends EventEmitter {
async init_server() {
const load = loader(this.snowpack, this.snowpack_config);

const { set_paths } = await load('/_app/assets/runtime/internal/singletons.js');
set_paths(this.config.paths);

const static_handler = sirv(this.config.files.static, {
dev: true
});
Expand Down Expand Up @@ -164,6 +167,7 @@ class Watcher extends EventEmitter {
},
{
static_dir: this.config.files.static,
paths: this.config.paths,
template: ({ head, body }) =>
template.replace('%svelte.head%', () => head).replace('%svelte.body%', () => body),
manifest: this.manifest,
Expand All @@ -177,7 +181,8 @@ class Watcher extends EventEmitter {
setup,
load: (route) => load(route.url.replace(/\.\w+$/, '.js')), // TODO is the replace still necessary?
only_prerender: false,
start_global: this.config.startGlobal
start_global: this.config.startGlobal,
app_dir: this.config.appDir
}
);

Expand Down
40 changes: 38 additions & 2 deletions packages/kit/src/api/load_config/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import relative from 'require-relative';
import { bold, yellow } from 'kleur/colors';
import options from './options';
import * as url from 'url';
import { existsSync, statSync } from 'fs';

function warn(msg) {
console.log(bold(yellow(msg)));
Expand Down Expand Up @@ -42,11 +44,32 @@ function validate(definition, option, keypath) {
return merged;
}

function resolve(from, to) {
// the `./` is weird, but allows `${assets}/images/blah.jpg` to work
Rich-Harris marked this conversation as resolved.
Show resolved Hide resolved
// when `assets` is empty
return remove_trailing_slash(
url.resolve(add_trailing_slash(from), to)
) || '/.';
}

function add_trailing_slash(str) {
return str.endsWith('/') ? str : `${str}/`;
}

function remove_trailing_slash(str) {
return str.endsWith('/') ? str.slice(0, -1) : str;
}

const expected = new Set(['compilerOptions', 'kit', 'preprocess']);

export function load_config({ cwd = process.cwd() } = {}) {
const config = relative('./svelte.config.js', cwd);
return validate_config(config);
const validated = validate_config(config);

// TODO check all the `files` exist when the config is loaded?
// TODO check that `target` is present in the provided template

return validated;
}

export function validate_config(config) {
Expand All @@ -58,5 +81,18 @@ export function validate_config(config) {

const { kit = {} } = config;

return validate(options, kit, 'kit');
const validated = validate(options, kit, 'kit');

if (validated.appDir === '') {
throw new Error('kit.appDir cannot be empty');
}

// resolve paths
if (validated.paths.base !== '' && !validated.paths.base.startsWith('/')) {
throw new Error('kit.paths.base must be a root-relative path');
}

validated.paths.assets = resolve(validated.paths.base, validated.paths.assets);

return validated;
}
101 changes: 99 additions & 2 deletions packages/kit/src/api/load_config/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ test('fills in defaults', () => {
routes: 'src/routes',
setup: 'src/setup',
template: 'src/app.html'
}
},
paths: {
base: '',
assets: '/.'
},
appDir: '_app'
});
});

Expand Down Expand Up @@ -58,8 +63,100 @@ test('fills in partial blanks', () => {
routes: 'src/routes',
setup: 'src/setup',
template: 'src/app.html'
}
},
paths: {
base: '',
assets: '/.'
},
appDir: '_app'
});
});

test('fails if kit.appDir is blank', () => {
assert.throws(() => {
validate_config({
kit: {
appDir: ''
}
});
}, /^kit\.appDir cannot be empty$/);
});

test('fails if paths.base is not root-relative', () => {
assert.throws(() => {
validate_config({
kit: {
paths: {
base: 'https://example.com/somewhere/else'
}
}
});
}, /^kit\.paths\.base must be a root-relative path$/);
});

function validate_paths(name, input, output) {
test(name, () => {
assert.equal(
validate_config({
kit: {
paths: input
}
}).paths,
output
);
});
}

validate_paths('assets relative to empty string', {
assets: 'path/to/assets'
}, {
base: '',
assets: '/path/to/assets'
});

validate_paths('assets relative to base path', {
base: '/path/to/base',
assets: 'path/to/assets'
}, {
base: '/path/to/base',
assets: '/path/to/base/path/to/assets'
});

validate_paths('empty assets relative to base path', {
base: '/path/to/base'
}, {
base: '/path/to/base',
assets: '/path/to/base'
});

validate_paths('root-relative assets', {
assets: '/path/to/assets'
}, {
base: '',
assets: '/path/to/assets'
});

validate_paths('root-relative assets with base path', {
base: '/path/to/base',
assets: '/path/to/assets'
}, {
base: '/path/to/base',
assets: '/path/to/assets'
});

validate_paths('external assets', {
assets: 'https://cdn.example.com'
}, {
base: '',
assets: 'https://cdn.example.com'
});

validate_paths('external assets with base', {
base: '/path/to/base',
assets: 'https://cdn.example.com'
}, {
base: '/path/to/base',
assets: 'https://cdn.example.com'
});

test.run();
13 changes: 10 additions & 3 deletions packages/kit/src/api/load_config/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,28 @@ export default {
}
},

// TODO check that the selector is present in the provided template
target: expect_string(null),

// used for testing
startGlobal: expect_string(null),

files: {
default: {
// TODO check these files exist when the config is loaded?
assets: expect_string('static'),
routes: expect_string('src/routes'),
setup: expect_string('src/setup'),
template: expect_string('src/app.html')
}
}
},

paths: {
default: {
base: expect_string(''),
assets: expect_string('')
}
},

appDir: expect_string('_app')
};

function expect_string(string) {
Expand Down
12 changes: 9 additions & 3 deletions packages/kit/src/api/start/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ const mutable = (dir) =>
maxAge: 0
});

export function start({ port }) {
export function start({ port, config }) {
return new Promise((fulfil) => {
const app = relative('./.svelte/build/optimized/server/app.js');

const static_handler = fs.existsSync(app.paths.static)
? mutable(app.paths.static)
const static_handler = fs.existsSync(config.files.static)
? mutable(config.files.static)
: (_req, _res, next) => next();

const assets_handler = sirv('.svelte/build/optimized/client', {
Expand All @@ -36,6 +36,12 @@ export function start({ port }) {
path: parsed.pathname,
body: await get_body(req),
query: new URLSearchParams(parsed.query || '')
}, {
paths: {
base: '',
assets: '/.',
app: '/_app'
}
});

if (rendered) {
Expand Down
Loading