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

Refactor to support changes in sveltekit 280 #19

Merged
merged 2 commits into from
Feb 23, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
29 changes: 21 additions & 8 deletions files/entry.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
import polka from 'polka';
import compression from 'compression';
import {getRequest, setResponse} from '@sveltejs/kit/node';
import path from 'node:path';
// eslint-disable-next-line camelcase
import {__fetch_polyfill} from '@sveltejs/kit/install-fetch';
import {App} from 'APP';
import {manifest} from './manifest.js';
import {getRequest, setResponse} from '@sveltejs/kit/node';
import compression from 'compression';
import {manifest} from 'MANIFEST';
import polka from 'polka';
import sirv from 'sirv';
import {Server} from 'SERVER';

__fetch_polyfill();

const app = new App(manifest);
const app = new Server(manifest);

// eslint-disable-next-line unicorn/prefer-module
const staticServe = sirv(path.join(__dirname, 'storage'), {
etag: true,
maxAge: 0,
immutable: false,
gzip: true,
brotli: true,
});

/** @type {import('polka').Middleware} */
function createKitMiddleware() {
Expand All @@ -22,7 +33,7 @@ function createKitMiddleware() {
return response.end(error.reason || 'Invalid request body');
}

setResponse(response, await app.render(request));
setResponse(response, await app.respond(request));
};
}

Expand All @@ -38,7 +49,9 @@ function getBase(headers) {

const kitMiddleware = createKitMiddleware();

const server = polka().use(compression({threshold: 0}), kitMiddleware);
const server = polka()
.use(staticServe)
.use(compression({threshold: 0}), kitMiddleware);

const port = process.env.PORT || 8080;
const listenOptions = {port};
Expand Down
89 changes: 35 additions & 54 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ export default function entrypoint() {

// Copy server handler
builder.copy(files, temporary, {replace: {
APP: `${relativePath}/app.js`,
SERVER: `${relativePath}/index.js`,
MANIFEST: './manifest.js',
}});

writeFileSync(
Expand All @@ -52,51 +53,18 @@ export default function entrypoint() {

writeFileSync(`${dir}/package.json`, JSON.stringify({type: 'commonjs'}));

const serverRoutes = [];

builder.createEntries(route => {
const parts = [];

for (const segment of route.segments) {
if (segment.rest || segment.dynamic) {
parts.push('.*');
} else {
parts.push(segment.content);
}
}

const id = '/' + parts.join('/');

if (prerenderedPaths.paths.includes(id)) {
const staticPath = join('storage', id, 'index.html');
serverRoutes.push(
{
url: id + '/?$',
// eslint-disable-next-line camelcase
static_files: staticPath,
upload: staticPath,
},
);
} else {
serverRoutes.push(
{
url: id,
secure: 'always',
script: 'auto',
},
);
}

return {
id,
filter: _ => true,
complete: _ => {},
};
});
const prerenderedPages = Array.from(prerenderedPaths.pages, ([src, page]) => ({
url: src + '/?$',
// eslint-disable-next-line camelcase
static_files: 'storage/' + page.file,
upload: 'storage/' + page.file,
}));

if (serverRoutes.length > 99) {
throw new Error('Too many url routes: ' + serverRoutes.length);
}
const prerenderedRedirects = Array.from(prerenderedPaths.redirects, ([src, _]) => ({
url: src,
secure: 'always',
script: 'auto',
}));

// Load existing app.yaml if it exists
let yaml = {};
Expand All @@ -105,21 +73,34 @@ export default function entrypoint() {
yaml = YAML.parse(readFileSync('app.yaml').toString());
}

const serverRoutes = [
...yaml.handlers ?? [],
...prerenderedPages,
...prerenderedRedirects,
{
url: `/${builder.appDir}/.+`,
// eslint-disable-next-line camelcase
static_dir: `storage/${builder.appDir}`,
expiration: '30d 0h',
},
{
url: '/.*',
secure: 'always',
script: 'auto',
},
];

if (serverRoutes.length > 99) {
throw new Error('Too many url routes: ' + serverRoutes.length);
}

writeFileSync(
join(dir, 'app.yaml'),
YAML.stringify({
...yaml,
runtime: 'nodejs16',
entrypoint: 'node index.js',
handlers: [
...yaml.handlers ?? [],
...serverRoutes,
{
url: '/',
// eslint-disable-next-line camelcase
static_dir: 'storage',
},
],
handlers: serverRoutes,
}),
);

Expand Down
50 changes: 50 additions & 0 deletions package-lock.json

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

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"files"
],
"peerDependencies": {
"@sveltejs/kit": ">=1.0.0-next.235"
"@sveltejs/kit": ">=1.0.0-next.280"
},
"devDependencies": {
"chai": "^4.3.4",
Expand All @@ -48,6 +48,7 @@
"compression": "^1.7.4",
"esbuild": "^0.13.4",
"polka": "^1.0.0-next.22",
"sirv": "^2.0.2",
"yaml": "^1.10.2"
},
"xo": {
Expand Down
17 changes: 6 additions & 11 deletions tests/expected_app.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,13 @@ handlers:
static_files: storage/index.html
upload: storage/index.html
- url: /about/?$
static_files: storage/about/index.html
upload: storage/about/index.html
- url: /todos.json
static_files: storage/about.html
upload: storage/about.html
- url: /_app/.+
static_dir: storage/_app
expiration: 30d 0h
- url: /.*
secure: always
script: auto
- url: /todos
secure: always
script: auto
- url: /todos/.*
secure: always
script: auto
- url: /
static_dir: storage
runtime: nodejs16
entrypoint: node index.js
1 change: 0 additions & 1 deletion tests/overwrites/svelte.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import adapter from 'svelte-adapter-appengine';
const config = {
kit: {
adapter: adapter(),
target: '#svelte',
},
};

Expand Down
4 changes: 2 additions & 2 deletions tests/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ describe('Integration test', () => {

it('runs endpoints', done => {
chai.request('http://localhost:8080')
.get('/todos.json')
.get('/todos/__data.json')
.end((error, response) => {
expect(response).to.have.status(200);
expect(response.body).to.deep.equal([]);
expect(response.body).to.deep.equal({todos: []});
done();
});
});
Expand Down
2 changes: 1 addition & 1 deletion tests/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ npm i
npm i "${SCRIPT_PATH}/../"

# These are peer dependencies that need manual install since we install from folder instead of from npm registry
npm install polka@1.0.0-next.22 compression@^1.7.4
npm install polka@1.0.0-next.22 compression@^1.7.4 sirv@^2.0.2

npm run build

Expand Down