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

set Vite's publicDir and base options #5601

Closed
wants to merge 35 commits into from
Closed
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
6e0d0bd
set Vite's publicDir option and change Vite's output dir
benmccann Jul 18, 2022
e1d9529
fixes
benmccann Jul 18, 2022
1eebe2e
fix
benmccann Jul 18, 2022
9600c7b
third time's the charm
benmccann Jul 18, 2022
cc958dd
merge master
benmccann Jul 18, 2022
63724ef
finish merge
benmccann Jul 18, 2022
08edcc6
remove writeStatic
benmccann Jul 18, 2022
3073800
missed a spot
Rich-Harris Jul 18, 2022
8600c38
fix options-2 tests by using Vite's base option
benmccann Jul 18, 2022
da434e9
keep writeStatic, but throw
Rich-Harris Jul 19, 2022
5edd5f3
shruggie
Rich-Harris Jul 19, 2022
e4e9033
update changeset
benmccann Jul 19, 2022
1f65e05
trailing slash + vite base compat
benmccann Jul 19, 2022
9aed215
can't figure this one out. push to CI and see if it gives the same error
benmccann Jul 19, 2022
4521b11
probably don't need this TODO anymore
benmccann Jul 19, 2022
f1e22db
remove outdated test
benmccann Jul 19, 2022
c7bc94e
crawling improvement
benmccann Jul 19, 2022
0c7c581
Revert "crawling improvement"
benmccann Jul 19, 2022
9cbd92c
merge master
benmccann Jul 19, 2022
9ec256e
update changelog
benmccann Jul 19, 2022
f01e437
update changeset
benmccann Jul 19, 2022
ed99a2f
merge master
benmccann Jul 19, 2022
5b62370
cleanup from merging master
benmccann Jul 19, 2022
ded83da
restore TODO
benmccann Jul 19, 2022
ea1bb13
Merge branch 'master' into publicDir
benmccann Jul 19, 2022
c1457a2
format
benmccann Jul 19, 2022
e74f728
fix adapter-static tests
benmccann Jul 19, 2022
a382755
fix unit tests
benmccann Jul 19, 2022
eee66db
fix options test
benmccann Jul 19, 2022
14b7875
format
benmccann Jul 19, 2022
774b70c
prerender updates
benmccann Jul 19, 2022
5ef88c7
restore and update preview message
benmccann Jul 19, 2022
44381e4
restore test
benmccann Jul 20, 2022
2798f9d
Revert "restore test"
benmccann Jul 20, 2022
e1d80c8
move code back to where it was originally
benmccann Jul 20, 2022
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
11 changes: 11 additions & 0 deletions .changeset/four-pandas-push.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@sveltejs/kit': patch
'@sveltejs/adapter-cloudflare-workers': patch
'@sveltejs/adapter-cloudflare': patch
'@sveltejs/adapter-netlify': patch
'@sveltejs/adapter-node': patch
'@sveltejs/adapter-static': patch
'@sveltejs/adapter-vercel': patch
---

[breaking] set Vite's `publicDir` option and change Vite's output dir
1 change: 0 additions & 1 deletion packages/adapter-cloudflare-workers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ export default function () {

builder.log.minor('Copying assets...');
builder.writeClient(site.bucket);
builder.writeStatic(site.bucket);
builder.writePrerendered(site.bucket);
}
};
Expand Down
1 change: 0 additions & 1 deletion packages/adapter-cloudflare/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ export default function () {
builder.rimraf(tmp);
builder.mkdirp(tmp);

builder.writeStatic(dest);
builder.writeClient(dest);
builder.writePrerendered(dest);

Expand Down
3 changes: 1 addition & 2 deletions packages/adapter-netlify/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ export default function ({ split = false, edge = edge_set_in_env_var } = {}) {
builder.log.minor(`Publishing to "${publish}"`);

builder.log.minor('Copying assets...');
builder.writeStatic(publish);
builder.writeClient(publish);
builder.writePrerendered(publish);

Expand Down Expand Up @@ -232,7 +231,7 @@ async function generate_lambda_functions({ builder, publish, split, esm }) {
redirects.push('* /.netlify/functions/render 200');
}

// this should happen at the end, after builder.writeStatic(...),
// this should happen at the end, after builder.writeClient(...),
// so that generated redirects are appended to custom redirects
// rather than replaced by them
builder.log.minor('Writing redirects...');
Expand Down
2 changes: 0 additions & 2 deletions packages/adapter-node/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ export default function (opts = {}) {
builder.log.minor('Copying assets');
builder.writeClient(`${out}/client`);
builder.writeServer(`${out}/server`);
builder.writeStatic(`${out}/static`);
builder.writePrerendered(`${out}/prerendered`);

writeFileSync(
Expand All @@ -51,7 +50,6 @@ export default function (opts = {}) {
if (precompress) {
builder.log.minor('Compressing assets');
await compress(`${out}/client`);
await compress(`${out}/static`);
await compress(`${out}/prerendered`);
}
}
Expand Down
1 change: 0 additions & 1 deletion packages/adapter-static/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ export default function (options) {
builder.rimraf(assets);
builder.rimraf(pages);

builder.writeStatic(assets);
builder.writeClient(assets);
builder.writePrerendered(pages, { fallback });

Expand Down
1 change: 0 additions & 1 deletion packages/adapter-vercel/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,6 @@ export default function ({ external = [], edge, split } = {}) {

builder.log.minor('Copying assets...');

builder.writeStatic(dirs.static);
builder.writeClient(dirs.static);
builder.writePrerendered(dirs.static);

Expand Down
9 changes: 7 additions & 2 deletions packages/kit/src/core/adapt/builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,11 +141,16 @@ export function create_builder({ config, build_data, prerendered, log }) {
return copy(`${config.kit.outDir}/output/server`, dest);
},

// TODO remove these methods for 1.0
// @ts-expect-error
writeStatic(dest) {
return copy(config.kit.files.assets, dest);
throw new Error(
`writeStatic has been removed. Please ensure you are using the latest version of ${
config.kit.adapter.name || 'your adapter'
}`
);
},

// @ts-expect-error
async prerender() {
throw new Error(
'builder.prerender() has been removed. Prerendering now takes place in the build phase — see builder.prerender and builder.writePrerendered'
Expand Down
11 changes: 0 additions & 11 deletions packages/kit/src/core/adapt/builder.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,6 @@ test('copy files', () => {

const dest = join(__dirname, 'output');

rmSync(dest, { recursive: true, force: true });
builder.writeStatic(dest);

assert.equal(
glob('**', {
cwd: /** @type {import('types').ValidatedConfig} */ (mocked).kit.files.assets,
dot: true
}),
glob('**', { cwd: dest, dot: true })
);

rmSync(dest, { recursive: true, force: true });
builder.writeClient(dest);

Expand Down
1 change: 0 additions & 1 deletion packages/kit/src/core/generate_manifest/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ export function generate_manifest({ build_data, relative_path, routes, format =

// prettier-ignore
return `{
appDir: ${s(build_data.app_dir)},
assets: new Set(${s(assets)}),
mimeTypes: ${s(get_mime_lookup(build_data.manifest_data))},
_: {
Expand Down
13 changes: 4 additions & 9 deletions packages/kit/src/core/prerender/prerender.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export async function prerender({ config, entries, files, log }) {
* @param {boolean} is_html
*/
function output_filename(path, is_html) {
const file = path.slice(config.paths.base.length + 1);
const file = path;

if (file === '') {
return 'index.html';
Expand All @@ -109,7 +109,7 @@ export async function prerender({ config, entries, files, log }) {
if (seen.has(decoded)) return;
seen.add(decoded);

const file = decoded.slice(config.paths.base.length + 1);
const file = decoded;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why did you remove this? no wonder the adapter-static tests are failing 😜

Suggested change
const file = decoded;
const file = decoded.slice(config.paths.base.length + 1);

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This means that $page.url.pathname is incorrect — it's missing base

if (files.has(file)) return;

return q.add(() => visit(decoded, encoded || encodeURI(decoded), referrer));
Expand All @@ -121,11 +121,6 @@ export async function prerender({ config, entries, files, log }) {
* @param {string?} referrer
*/
async function visit(decoded, encoded, referrer) {
if (!decoded.startsWith(config.paths.base)) {
error({ status: 404, path: decoded, referrer, referenceType: 'linked' });
return;
}

/** @type {Map<string, import('types').PrerenderDependency>} */
const dependencies = new Map();

Expand Down Expand Up @@ -259,10 +254,10 @@ export async function prerender({ config, entries, files, log }) {
for (const entry of config.prerender.entries) {
if (entry === '*') {
for (const entry of entries) {
enqueue(null, config.paths.base + entry); // TODO can we pre-normalize these?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand what's going on with the removal of config.paths.base. Surely it needs to be there?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also, not sure why you got rid of the comment. it's still a TODO

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't understand the TODO. I thought it was referring to prepending the base

The base would not be needed as Vite's baseMiddleware strips out the base path from the URL as mentioned above #5601 (comment)

enqueue(null, entry);
}
} else {
enqueue(null, config.paths.base + entry);
enqueue(null, entry);
}
}

Expand Down
10 changes: 2 additions & 8 deletions packages/kit/src/runtime/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,6 @@ export async function respond(request, options, state) {
/** @type {Record<string, string>} */
let params = {};

if (options.paths.base && !state.prerendering?.fallback) {
if (!decoded.startsWith(options.paths.base)) {
return new Response('Not found', { status: 404 });
}
decoded = decoded.slice(options.paths.base.length) || '/';
}

const is_data_request = decoded.endsWith(DATA_SUFFIX);

if (is_data_request) {
Expand Down Expand Up @@ -93,13 +86,14 @@ export async function respond(request, options, state) {
const normalized = normalize_path(url.pathname, options.trailing_slash);

if (normalized !== url.pathname && !state.prerendering?.fallback) {
const path = options.paths.base + normalized;
return new Response(undefined, {
status: 301,
headers: {
'x-sveltekit-normalize': '1',
location:
// ensure paths starting with '//' are not treated as protocol-relative
(normalized.startsWith('//') ? url.origin + normalized : normalized) +
(normalized.startsWith('//') ? url.origin + path : path) +
(url.search === '?' ? '' : url.search)
}
});
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/vite/build/build_server.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export class Server {
manifest,
method_override: ${s(config.kit.methodOverride)},
paths: { base, assets },
prefix: assets + '/${config.kit.appDir}/',
prefix: assets + '/',
prerender: {
default: ${config.kit.prerender.default},
enabled: ${config.kit.prerender.enabled}
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/vite/build/build_service_worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export async function build_service_worker(

export const build = [
${Array.from(build)
.map((file) => `${s(`${config.kit.paths.base}/${config.kit.appDir}/${file}`)}`)
.map((file) => `${s(`${config.kit.paths.base}/${file}`)}`)
.join(',\n\t\t\t\t')}
];

Expand Down
12 changes: 5 additions & 7 deletions packages/kit/src/vite/build/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,9 @@ export const get_default_config = function ({ config, input, ssr, outDir }) {
input,
output: {
format: 'esm',
entryFileNames: ssr ? '[name].js' : 'immutable/[name]-[hash].js',
chunkFileNames: 'immutable/chunks/[name]-[hash].js',
assetFileNames: 'immutable/assets/[name]-[hash][extname]'
entryFileNames: ssr ? '[name].js' : `${config.kit.appDir}/immutable/[name]-[hash].js`,
chunkFileNames: `${config.kit.appDir}/immutable/chunks/[name]-[hash].js`,
assetFileNames: `${config.kit.appDir}/immutable/assets/[name]-[hash][extname]`
},
preserveEntrySignatures: 'strict'
},
Expand All @@ -111,9 +111,7 @@ export const get_default_config = function ({ config, input, ssr, outDir }) {
__SVELTEKIT_APP_VERSION_FILE__: JSON.stringify(`${config.kit.appDir}/version.json`),
__SVELTEKIT_APP_VERSION_POLL_INTERVAL__: JSON.stringify(config.kit.version.pollInterval)
},
// prevent Vite copying the contents of `config.kit.files.assets`,
// if it happens to be 'public' instead of 'static'
publicDir: false,
publicDir: ssr ? false : config.kit.files.assets,
resolve: {
alias: get_aliases(config.kit)
},
Expand All @@ -140,7 +138,7 @@ export function assets_base(config) {
// during `svelte-kit preview`, because we use a local asset path. This
// may be fixed in Vite 3: https://github.com/vitejs/vite/issues/2009
const { base, assets } = config.paths;
return `${assets || base}/${config.appDir}/`;
return `${assets || base}/`;
}

/**
Expand Down
55 changes: 0 additions & 55 deletions packages/kit/src/vite/dev/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import fs from 'fs';
import colors from 'kleur';
import path from 'path';
import sirv from 'sirv';
import { URL } from 'url';
import { getRequest, setResponse } from '../../node/index.js';
import { installPolyfills } from '../../node/polyfills.js';
Expand Down Expand Up @@ -173,12 +172,6 @@ export async function dev(vite, vite_config, svelte_config) {
}

const assets = svelte_config.kit.paths.assets ? SVELTE_KIT_ASSETS : svelte_config.kit.paths.base;
const asset_server = sirv(svelte_config.kit.files.assets, {
dev: true,
etag: true,
maxAge: 0,
extensions: []
});

return () => {
const serve_static_middleware = vite.middlewares.stack.find(
Expand All @@ -197,20 +190,6 @@ export async function dev(vite, vite_config, svelte_config) {
}`;

const decoded = decodeURI(new URL(base + req.url).pathname);

if (decoded.startsWith(assets)) {
const pathname = decoded.slice(assets.length);
const file = svelte_config.kit.files.assets + pathname;

if (fs.existsSync(file) && !fs.statSync(file).isDirectory()) {
if (has_correct_case(file, svelte_config.kit.files.assets)) {
req.url = encodeURI(pathname); // don't need query/hash
asset_server(req, res);
return;
}
}
}

const file = posixify(path.resolve(decoded.slice(1)));
const is_file = fs.existsSync(file) && !fs.statSync(file).isDirectory();
const allowed =
Expand All @@ -223,13 +202,6 @@ export async function dev(vite, vite_config, svelte_config) {
return;
}

if (!decoded.startsWith(svelte_config.kit.paths.base)) {
return not_found(
res,
`Not found (did you mean ${svelte_config.kit.paths.base + req.url}?)`
);
}

/** @type {Partial<import('types').Hooks>} */
const user_hooks = resolve_entry(svelte_config.kit.files.hooks)
? await vite.ssrLoadModule(`/${svelte_config.kit.files.hooks}`)
Expand Down Expand Up @@ -383,12 +355,6 @@ export async function dev(vite, vite_config, svelte_config) {
};
}

/** @param {import('http').ServerResponse} res */
function not_found(res, message = 'Not found') {
res.statusCode = 404;
res.end(message);
}

/**
* @param {import('connect').Server} server
*/
Expand Down Expand Up @@ -444,24 +410,3 @@ async function find_deps(vite, node, deps) {

await Promise.all(branches);
}

/**
* Determine if a file is being requested with the correct case,
* to ensure consistent behaviour between dev and prod and across
* operating systems. Note that we can't use realpath here,
* because we don't want to follow symlinks
* @param {string} file
* @param {string} assets
* @returns {boolean}
*/
function has_correct_case(file, assets) {
if (file === assets) return true;

const parent = path.dirname(file);

if (fs.readdirSync(parent).includes(path.basename(file))) {
return has_correct_case(parent, assets);
}

return false;
}
11 changes: 6 additions & 5 deletions packages/kit/src/vite/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ function kit() {
paths = {
build_dir: `${svelte_config.kit.outDir}/build`,
output_dir: `${svelte_config.kit.outDir}/output`,
client_out_dir: `${svelte_config.kit.outDir}/output/client/${svelte_config.kit.appDir}`
client_out_dir: `${svelte_config.kit.outDir}/output/client`
};

if (is_build) {
Expand All @@ -197,7 +197,7 @@ function kit() {
/** @type {import('vite').UserConfig} */
const result = {
appType: 'custom',
base: '/',
base: `${svelte_config.kit.paths.base}/`,
build: {
rollupOptions: {
// Vite dependency crawler needs an explicit JS entry point
Expand All @@ -208,6 +208,7 @@ function kit() {
define: {
__SVELTEKIT_APP_VERSION_POLL_INTERVAL__: '0'
},
publicDir: svelte_config.kit.files.assets,
resolve: {
alias: get_aliases(svelte_config.kit)
},
Expand Down Expand Up @@ -271,7 +272,7 @@ function kit() {
});

fs.writeFileSync(
`${paths.client_out_dir}/version.json`,
`${paths.client_out_dir}/${svelte_config.kit.appDir}/version.json`,
JSON.stringify({ version: svelte_config.kit.version.name })
);

Expand Down Expand Up @@ -316,8 +317,8 @@ function kit() {

const files = new Set([
...static_files,
...chunks.map((chunk) => `${svelte_config.kit.appDir}/${chunk.fileName}`),
...assets.map((chunk) => `${svelte_config.kit.appDir}/${chunk.fileName}`)
...chunks.map((chunk) => chunk.fileName),
...assets.map((chunk) => chunk.fileName)
]);

// TODO is this right?
Expand Down
Loading