Skip to content

Commit

Permalink
[breaking] replace esbuild bundling of adapters with Vite bundling
Browse files Browse the repository at this point in the history
  • Loading branch information
benmccann committed Oct 13, 2021
1 parent 53b3ed3 commit 55f8652
Show file tree
Hide file tree
Showing 18 changed files with 82 additions and 91 deletions.
9 changes: 9 additions & 0 deletions .changeset/tidy-pets-tan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@sveltejs/adapter-cloudflare-workers': patch
'@sveltejs/adapter-netlify': patch
'@sveltejs/adapter-node': patch
'@sveltejs/adapter-vercel': patch
'@sveltejs/kit': patch
---

[breaking] replace esbuild bundling of adapters with Vite bundling
1 change: 1 addition & 0 deletions examples/hn.svelte.dev/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
},
"devDependencies": {
"@sveltejs/adapter-netlify": "workspace:*",
"@sveltejs/adapter-node": "workspace:*",
"@sveltejs/kit": "workspace:*",
"svelte": "^3.43.1"
}
Expand Down
4 changes: 1 addition & 3 deletions examples/hn.svelte.dev/svelte.config.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import netlify from '@sveltejs/adapter-netlify';

export default {
kit: {
adapter: netlify(),
adapter: '@sveltejs/adapter-node',
target: '#svelte'
}
};
5 changes: 3 additions & 2 deletions packages/adapter-cloudflare-workers/files/entry.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// TODO hardcoding the relative location makes this brittle
import { init, render } from '../output/server/app.js';
// @sveltejs/kit-app doesn't exist until the app is built
// @ts-ignore
import { init, render } from '@sveltejs/kit-app';
import { getAssetFromKV, NotFoundError } from '@cloudflare/kv-asset-handler';

init();
Expand Down
5 changes: 3 additions & 2 deletions packages/adapter-netlify/files/entry.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// TODO hardcoding the relative location makes this brittle
import { init, render } from '../output/server/app.js';
// @sveltejs/kit-app doesn't exist until the app is built
// @ts-ignore
import { init, render } from '@sveltejs/kit-app';

init();

Expand Down
13 changes: 1 addition & 12 deletions packages/adapter-node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,7 @@
},
"homepage": "https://kit.svelte.dev",
"type": "module",
"exports": {
".": {
"import": "./index.js"
},
"./package.json": "./package.json"
},
"main": "index.js",
"types": "index.d.ts",
"files": [
"files",
"index.d.ts"
],
"main": "files/index.js",
"scripts": {
"dev": "rollup -cw",
"build": "rollup -c",
Expand Down
4 changes: 2 additions & 2 deletions packages/adapter-node/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export default [
sourcemap: true
},
plugins: [nodeResolve(), commonjs(), json()],
external: ['../output/server/app.js', ...require('module').builtinModules]
external: ['@sveltejs/kit-app', ...require('module').builtinModules]
},
{
input: 'src/index.js',
Expand All @@ -21,7 +21,7 @@ export default [
sourcemap: true
},
plugins: [nodeResolve(), commonjs(), json()],
external: ['./middlewares.js', './env.js', ...require('module').builtinModules]
external: ['./middlewares.js', '@sveltejs/kit-app', ...require('module').builtinModules]
},
{
input: 'src/shims.js',
Expand Down
3 changes: 3 additions & 0 deletions packages/adapter-node/src/env.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const path = process.env['PATH'] || false;
export const host = process.env['HOST'] || '0.0.0.0';
export const port = process.env['PORT'] || (!path && 3000);
5 changes: 2 additions & 3 deletions packages/adapter-node/src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// @ts-ignore
import { path, host, port } from './env.js';
import { assetsMiddleware, kitMiddleware, prerenderedMiddleware } from './middlewares.js';
import { path, host, port } from './env';
import { assetsMiddleware, kitMiddleware, prerenderedMiddleware } from './middlewares';
import compression from 'compression';
import polka from 'polka';

Expand Down
6 changes: 2 additions & 4 deletions packages/adapter-node/src/middlewares.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// TODO hardcoding the relative location makes this brittle
// Also, we need most of the logic in another file for testing because
// ../output/server/app.js doesn't exist when we run the tests
// @sveltejs/kit-app doesn't exist until the app is built
// @ts-ignore
import { init, render } from '../output/server/app.js';
import { init, render } from '@sveltejs/kit-app';
import { create_kit_middleware } from './kit-middleware.js';

import fs from 'fs';
Expand Down
6 changes: 3 additions & 3 deletions packages/adapter-vercel/files/entry.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// @sveltejs/kit-app doesn't exist until the app is built
// @ts-ignore
import { init, render } from '@sveltejs/kit-app';
import { getRawBody } from '@sveltejs/kit/node';

// TODO hardcoding the relative location makes this brittle
import { init, render } from '../output/server/app.js';

init();

export default async (req, res) => {
Expand Down
23 changes: 10 additions & 13 deletions packages/kit/src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,32 +118,29 @@ prog
.command('build')
.describe('Create a production build of your app')
.option('--verbose', 'Log more stuff', false)
.action(async ({ verbose }) => {
.action(async () => {
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
const config = await get_config();

try {
const { build } = await import('./core/build/index.js');
const build_data = await build(config);
await build(config);

console.log(
`\nRun ${colors.bold().cyan('npm run preview')} to preview your production build locally.`
);

if (config.kit.adapter) {
const { adapt } = await import('./core/adapt/index.js');
await adapt(config, build_data, { verbose });
if (!config.kit.adapter) {
console.log(colors.bold().yellow('\nNo adapter specified'));

// this is necessary to close any open db connections, etc
process.exit(0);
// prettier-ignore
console.log(
`See ${colors.bold().cyan('https://kit.svelte.dev/docs#adapters')} to learn how to configure your app to run on the platform of your choosing`
);
}

console.log(colors.bold().yellow('\nNo adapter specified'));

// prettier-ignore
console.log(
`See ${colors.bold().cyan('https://kit.svelte.dev/docs#adapters')} to learn how to configure your app to run on the platform of your choosing`
);
// this is necessary to close any open db connections, etc
process.exit(0);
} catch (error) {
handle_error(error);
}
Expand Down
20 changes: 0 additions & 20 deletions packages/kit/src/core/adapt/index.js

This file was deleted.

29 changes: 19 additions & 10 deletions packages/kit/src/core/build/index.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
import fs from 'fs';
import path from 'path';

import { svelte } from '@sveltejs/vite-plugin-svelte';
import glob from 'tiny-glob/sync.js';
import vite from 'vite';

import { rimraf } from '../../utils/filesystem.js';
import { deep_merge } from '../../utils/object.js';

import { print_config_conflicts } from '../config/index.js';
import { create_app } from '../create_app/index.js';
import create_manifest_data from '../create_manifest_data/index.js';
import { SVELTE_KIT } from '../constants.js';
import { copy_assets, posixify, resolve_entry } from '../utils.js';
import { createRequire } from 'module';

/** @param {any} value */
const s = (value) => JSON.stringify(value);

/** @typedef {Record<string, {
/**
* @typedef {Record<string, {
* file: string;
* css: string[];
* imports: string[];
* }>} ClientManifest */
* }>} ClientManifest
*/

/**
* @param {import('types/config').ValidatedConfig} config
Expand All @@ -32,7 +33,8 @@ const s = (value) => JSON.stringify(value);
* @returns {Promise<import('types/internal').BuildData>}
*/
export async function build(config, { cwd = process.cwd(), runtime = '@sveltejs/kit/ssr' } = {}) {
const build_dir = path.resolve(cwd, `${SVELTE_KIT}/build`);
const raw_build_dir = `${SVELTE_KIT}/node_modules/@sveltejs/kit-app`;
const build_dir = path.resolve(cwd, raw_build_dir);

rimraf(build_dir);

Expand All @@ -53,7 +55,7 @@ export async function build(config, { cwd = process.cwd(), runtime = '@sveltejs/
cwd
}),
output_dir,
client_entry_file: `${SVELTE_KIT}/build/runtime/internal/start.js`,
client_entry_file: `${raw_build_dir}/runtime/internal/start.js`,
service_worker_entry_file: resolve_entry(config.kit.files.serviceWorker)
};

Expand Down Expand Up @@ -225,12 +227,10 @@ async function build_server(
) {
let hooks_file = resolve_entry(config.kit.files.hooks);
if (!hooks_file || !fs.existsSync(hooks_file)) {
hooks_file = path.resolve(cwd, `${SVELTE_KIT}/build/hooks.js`);
hooks_file = path.resolve(build_dir, 'hooks.js');
fs.writeFileSync(hooks_file, '');
}

const app_file = `${build_dir}/app.js`;

/** @type {(file: string) => string} */
const app_relative = (file) => {
const relative_file = path.relative(build_dir, path.resolve(cwd, file));
Expand Down Expand Up @@ -293,6 +293,14 @@ async function build_server(

find_deps(client_entry_file, entry_js, entry_css);

const adapter = config.kit.adapter;
const require = createRequire(import.meta.url);
const pkg_path = require.resolve(`${adapter}/package.json`);
const pkg = JSON.parse(fs.readFileSync(pkg_path, 'utf8'));
const main = path.resolve(pkg_path.substring(0, pkg_path.lastIndexOf('/')), pkg.main);

const app_file = `${build_dir}/app.js`;

// prettier-ignore
fs.writeFileSync(
app_file,
Expand Down Expand Up @@ -466,7 +474,7 @@ async function build_server(
polyfillDynamicImport: false,
rollupOptions: {
input: {
app: app_file
app: main
},
output: {
format: 'esm',
Expand All @@ -488,6 +496,7 @@ async function build_server(
],
resolve: {
alias: {
'@sveltejs/kit-app': path.resolve(`${build_dir}/app.js`),
$app: path.resolve(`${build_dir}/runtime/app`),
$lib: config.kit.files.lib
}
Expand Down
18 changes: 9 additions & 9 deletions packages/kit/src/core/config/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,17 @@ const options = object(
}),

kit: object({
adapter: validate(null, (input, keypath) => {
if (typeof input !== 'object' || !input.adapt) {
let message = `${keypath} should be an object with an "adapt" method`;
adapter: validate(null, (input, _keypath) => {
// if (typeof input !== 'object' || !input.adapt) {
// let message = `${keypath} should be an object with an "adapt" method`;

if (Array.isArray(input) || typeof input === 'string') {
// for the early adapter adopters
message += ', rather than the name of an adapter';
}
// if (Array.isArray(input) || typeof input === 'string') {
// // for the early adapter adopters
// message += ', rather than the name of an adapter';
// }

throw new Error(`${message}. See https://kit.svelte.dev/docs#adapters`);
}
// throw new Error(`${message}. See https://kit.svelte.dev/docs#adapters`);
// }

return input;
}),
Expand Down
18 changes: 11 additions & 7 deletions packages/kit/src/runtime/app/navigation.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { router as router_ } from '../client/singletons.js';
import { get_base_uri } from '../client/utils.js';

const router = /** @type {import('../client/router').Router} */ (router_);

/**
* @param {string} name
*/
Expand All @@ -17,32 +14,39 @@ export const invalidate = import.meta.env.SSR ? guard('invalidate') : invalidate
export const prefetch = import.meta.env.SSR ? guard('prefetch') : prefetch_;
export const prefetchRoutes = import.meta.env.SSR ? guard('prefetchRoutes') : prefetchRoutes_;

async function get_router() {
return /** @type {import('../client/router').Router} */ (
(await import('../client/singletons.js')).router
);
}

/**
* @type {import('$app/navigation').goto}
*/
async function goto_(href, opts) {
return router.goto(href, opts, []);
return (await get_router()).goto(href, opts, []);
}

/**
* @type {import('$app/navigation').invalidate}
*/
async function invalidate_(resource) {
const { href } = new URL(resource, location.href);
return router.renderer.invalidate(href);
return (await get_router()).renderer.invalidate(href);
}

/**
* @type {import('$app/navigation').prefetch}
*/
function prefetch_(href) {
return router.prefetch(new URL(href, get_base_uri(document)));
async function prefetch_(href) {
return (await get_router()).prefetch(new URL(href, get_base_uri(document)));
}

/**
* @type {import('$app/navigation').prefetchRoutes}
*/
async function prefetchRoutes_(pathnames) {
const router = await get_router();
const matching = pathnames
? router.routes.filter((route) => pathnames.some((pathname) => route[0].test(pathname)))
: router.routes;
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ async function main() {

await build(config, {
cwd,
runtime: '../../../../../src/runtime/server/index.js'
runtime: '../../../../../../../src/runtime/server/index.js'
});

context.server = await preview({ port, config, cwd, host: undefined, https: false });
Expand Down
2 changes: 2 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 55f8652

Please sign in to comment.