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

chore: remove build step for adapter node #10041

Merged
merged 20 commits into from
Jun 30, 2023
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
5 changes: 5 additions & 0 deletions .changeset/dirty-dolphins-suffer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/adapter-node': minor
---

chore: remove build step for adapter node
gtm-nayan marked this conversation as resolved.
Show resolved Hide resolved
5 changes: 5 additions & 0 deletions .changeset/three-hotels-share.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/adapter-node': minor
---

feat: load sourcemaps so that they can be merged to point to original sourcefiles
9 changes: 5 additions & 4 deletions packages/adapter-node/ambient.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
declare module 'ENV' {
export function env(key: string, fallback?: any): string;
}

declare module 'HANDLER' {
export const handler: import('polka').Middleware;
}
Expand All @@ -17,6 +13,11 @@ declare module 'SERVER' {
export { Server } from '@sveltejs/kit';
}

interface ImportMeta {
SERVER_DIR: string;
ENV_PREFIX?: string;
}

declare namespace App {
export interface Platform {
/**
Expand Down
4 changes: 0 additions & 4 deletions packages/adapter-node/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import { Adapter } from '@sveltejs/kit';
import './ambient.js';

declare global {
const ENV_PREFIX: string;
Conduitry marked this conversation as resolved.
Show resolved Hide resolved
}

interface AdapterOptions {
out?: string;
precompress?: boolean;
Expand Down
95 changes: 70 additions & 25 deletions packages/adapter-node/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { rollup } from 'rollup';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import { createFilter, normalizePath } from '@rollup/pluginutils';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { rollup } from 'rollup';

const files = fileURLToPath(new URL('./files', import.meta.url).href);
/** @param {string} path */
const resolve = (path) => fileURLToPath(new URL(path, import.meta.url));

/** @type {import('.').default} */
export default function (opts = {}) {
Expand All @@ -15,7 +19,8 @@ export default function (opts = {}) {
name: '@sveltejs/adapter-node',

async adapt(builder) {
const tmp = builder.getBuildDirectory('adapter-node');
// use an adjacent temporary directory so that any relative paths in eg. sourcemaps don't break
const tmp = path.join(path.dirname(builder.getServerDirectory()), 'adapter-node');

builder.rimraf(out);
builder.rimraf(tmp);
Expand Down Expand Up @@ -50,45 +55,85 @@ export default function (opts = {}) {
// will get included in the bundled code
const bundle = await rollup({
input: {
index: `${tmp}/index.js`,
manifest: `${tmp}/manifest.js`
handler: resolve('./src/handler.js'),
index: resolve('./src/index.js')
},
external: [
// dependencies could have deep exports, so we need a regex
...Object.keys(pkg.dependencies || {}).map((d) => new RegExp(`^${d}(\\/.*)?$`))
],
plugins: [
{
name: 'adapter-node-resolve',
resolveId(id) {
switch (id) {
case 'MANIFEST':
return `${tmp}/manifest.js`;
case 'SERVER':
return `${tmp}/index.js`;
case 'SHIMS':
return '\0virtual:SHIMS';
}
},
load(id) {
if (id === '\0virtual:SHIMS') {
return polyfill
? "import { installPolyfills } from '@sveltejs/kit/node/polyfills'; installPolyfills();"
: '';
}
},
resolveImportMeta(property, { chunkId, moduleId }) {
if (property === 'SERVER_DIR' && moduleId === resolve('./src/handler.js')) {
const segments = chunkId.split('/').length - 1;

return `new URL("${'../'.repeat(segments) || '.'}", import.meta.url)`;
} else if (property === 'ENV_PREFIX' && moduleId === resolve('./src/env.js')) {
return JSON.stringify(envPrefix);
}
}
},
nodeResolve({
preferBuiltins: true,
exportConditions: ['node']
}),
commonjs({ strictRequires: true }),
json()
json(),
merge_sourcemap_plugin(tmp)
]
});

await bundle.write({
dir: `${out}/server`,
dir: out,
format: 'esm',
sourcemap: true,
chunkFileNames: 'chunks/[name]-[hash].js'
chunkFileNames: 'server/chunks/[name]-[hash].js',
// without this rollup will insert some imports to try speed up
// module loading but it doesn't really affect anything on the server side
hoistTransitiveImports: false
});
benmccann marked this conversation as resolved.
Show resolved Hide resolved
}
};
}

builder.copy(files, out, {
replace: {
ENV: './env.js',
HANDLER: './handler.js',
MANIFEST: './server/manifest.js',
SERVER: './server/index.js',
SHIMS: './shims.js',
ENV_PREFIX: JSON.stringify(envPrefix)
}
});
/**
* Load sourcemaps for files in the tmp directory so that the final ones
* point to the original source files, instead of the generated files in outDir.
* @param {string} tmp
* @returns {import('rollup').Plugin}
*/
function merge_sourcemap_plugin(tmp) {
const should_process_sourcemaps = createFilter(`${normalizePath(tmp)}/**/*.js`);

// If polyfills aren't wanted then clear the file
if (!polyfill) {
writeFileSync(`${out}/shims.js`, '', 'utf-8');
}
return {
name: 'adapter-node-sourcemap-loader',
async load(id) {
if (!should_process_sourcemaps(id)) return;
if (!existsSync(`${id}.map`)) return;
const [code, map] = await Promise.all([
readFile(id, 'utf-8'),
readFile(`${id}.map`, 'utf-8')
]);
return { code, map };
}
};
}
17 changes: 7 additions & 10 deletions packages/adapter-node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,35 +19,32 @@
},
"types": "index.d.ts",
"files": [
"files",
"src",
"index.js",
"index.d.ts"
],
"scripts": {
"dev": "rimraf files && rollup -cw",
"build": "rimraf files && rollup -c",
"test": "echo \"tests temporarily disabled\" # c8 vitest run",
"check": "tsc",
"lint": "prettier --check . --config ../../.prettierrc --ignore-path .gitignore",
"format": "pnpm lint --write",
"prepublishOnly": "pnpm build"
"format": "pnpm lint --write"
},
"devDependencies": {
"@polka/url": "^1.0.0-next.21",
"@sveltejs/kit": "workspace:^",
"@types/node": "^16.18.6",
"c8": "^8.0.0",
"polka": "^1.0.0-next.22",
"rimraf": "^5.0.0",
"sirv": "^2.0.3",
"typescript": "^4.9.4",
"vitest": "^0.32.2"
},
"dependencies": {
"@polka/url": "^1.0.0-next.21",
"@rollup/plugin-commonjs": "^25.0.0",
"@rollup/plugin-json": "^6.0.0",
"@rollup/plugin-node-resolve": "^15.0.1",
"rollup": "^3.7.0"
"@rollup/pluginutils": "^5.0.2",
"polka": "^1.0.0-next.22",
"rollup": "^3.7.0",
"sirv": "^2.0.2"
},
"peerDependencies": {
"@sveltejs/kit": "^1.0.0"
Expand Down
44 changes: 0 additions & 44 deletions packages/adapter-node/rollup.config.js

This file was deleted.

2 changes: 1 addition & 1 deletion packages/adapter-node/src/env.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* global ENV_PREFIX */
export const ENV_PREFIX = import.meta.ENV_PREFIX;

const expected = new Set([
'SOCKET_PATH',
Expand Down
13 changes: 7 additions & 6 deletions packages/adapter-node/src/handler.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import 'SHIMS';

import fs from 'node:fs';
import path from 'node:path';
import sirv from 'sirv';
import { fileURLToPath } from 'node:url';

import { parse as polka_url_parser } from '@polka/url';
import { getRequest, setResponse } from '@sveltejs/kit/node';
import { Server } from 'SERVER';
import { manifest, prerendered } from 'MANIFEST';
import { env } from 'ENV';
import sirv from 'sirv';

/* global ENV_PREFIX */
import { env, ENV_PREFIX } from './env.js';
import { manifest, prerendered } from 'MANIFEST';
import { Server } from 'SERVER';

const server = new Server(manifest);
await server.init({ env: process.env });
Expand All @@ -20,7 +21,7 @@ const protocol_header = env('PROTOCOL_HEADER', '').toLowerCase();
const host_header = env('HOST_HEADER', 'host').toLowerCase();
const body_size_limit = parseInt(env('BODY_SIZE_LIMIT', '524288'));

const dir = path.dirname(fileURLToPath(import.meta.url));
const dir = fileURLToPath(import.meta.SERVER_DIR);

/**
* @param {string} path
Expand Down
4 changes: 2 additions & 2 deletions packages/adapter-node/src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { handler } from 'HANDLER';
import { env } from 'ENV';
import { handler } from './handler.js';
import { env } from './env.js';
import polka from 'polka';

export const path = env('SOCKET_PATH', false);
Expand Down
2 changes: 0 additions & 2 deletions packages/adapter-node/src/shims.js

This file was deleted.

31 changes: 15 additions & 16 deletions pnpm-lock.yaml

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

Loading