Skip to content

Commit

Permalink
Revert "chore: remove build step for adapter node (#10041)"
Browse files Browse the repository at this point in the history
This reverts commit 6b99851.
  • Loading branch information
gtm-nayan committed Jul 4, 2023
1 parent a2a42ff commit 82b2b11
Show file tree
Hide file tree
Showing 10 changed files with 114 additions and 107 deletions.
9 changes: 4 additions & 5 deletions packages/adapter-node/ambient.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
declare module 'ENV' {
export function env(key: string, fallback?: any): string;
}

declare module 'HANDLER' {
export const handler: import('polka').Middleware;
}
Expand All @@ -13,11 +17,6 @@ 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: 4 additions & 0 deletions packages/adapter-node/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { Adapter } from '@sveltejs/kit';
import './ambient.js';

declare global {
const ENV_PREFIX: string;
}

interface AdapterOptions {
out?: string;
precompress?: boolean;
Expand Down
95 changes: 25 additions & 70 deletions packages/adapter-node/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
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 { 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';

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

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

async adapt(builder) {
// 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');
const tmp = builder.getBuildDirectory('adapter-node');

builder.rimraf(out);
builder.rimraf(tmp);
Expand Down Expand Up @@ -55,85 +50,45 @@ export default function (opts = {}) {
// will get included in the bundled code
const bundle = await rollup({
input: {
handler: resolve('./src/handler.js'),
index: resolve('./src/index.js')
index: `${tmp}/index.js`,
manifest: `${tmp}/manifest.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(),
merge_sourcemap_plugin(tmp)
json()
]
});

await bundle.write({
dir: out,
dir: `${out}/server`,
format: 'esm',
sourcemap: true,
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
chunkFileNames: 'chunks/[name]-[hash].js'
});
}
};
}

/**
* 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`);
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)
}
});

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 };
// If polyfills aren't wanted then clear the file
if (!polyfill) {
writeFileSync(`${out}/shims.js`, '', 'utf-8');
}
}
};
}
17 changes: 10 additions & 7 deletions packages/adapter-node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,32 +19,35 @@
},
"types": "index.d.ts",
"files": [
"src",
"files",
"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"
"format": "pnpm lint --write",
"prepublishOnly": "pnpm build"
},
"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/pluginutils": "^5.0.2",
"polka": "^1.0.0-next.22",
"rollup": "^3.7.0",
"sirv": "^2.0.2"
"rollup": "^3.7.0"
},
"peerDependencies": {
"@sveltejs/kit": "^1.0.0"
Expand Down
44 changes: 44 additions & 0 deletions packages/adapter-node/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import { builtinModules } from 'node:module';

export default [
{
input: 'src/index.js',
output: {
file: 'files/index.js',
format: 'esm'
},
plugins: [nodeResolve({ preferBuiltins: true }), commonjs(), json()],
external: ['ENV', 'HANDLER', ...builtinModules]
},
{
input: 'src/env.js',
output: {
file: 'files/env.js',
format: 'esm'
},
plugins: [nodeResolve(), commonjs(), json()],
external: ['HANDLER', ...builtinModules]
},
{
input: 'src/handler.js',
output: {
file: 'files/handler.js',
format: 'esm',
inlineDynamicImports: true
},
plugins: [nodeResolve(), commonjs(), json()],
external: ['ENV', 'MANIFEST', 'SERVER', 'SHIMS', ...builtinModules]
},
{
input: 'src/shims.js',
output: {
file: 'files/shims.js',
format: 'esm'
},
plugins: [nodeResolve(), commonjs()],
external: builtinModules
}
];
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 @@
export const ENV_PREFIX = import.meta.ENV_PREFIX;
/* global ENV_PREFIX */

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

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

/* global ENV_PREFIX */

const server = new Server(manifest);
await server.init({ env: process.env });
Expand All @@ -21,7 +20,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 = fileURLToPath(import.meta.SERVER_DIR);
const dir = path.dirname(fileURLToPath(import.meta.url));

/**
* @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.js';
import { env } from './env.js';
import { handler } from 'HANDLER';
import { env } from 'ENV';
import polka from 'polka';

export const path = env('SOCKET_PATH', false);
Expand Down
2 changes: 2 additions & 0 deletions packages/adapter-node/src/shims.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import { installPolyfills } from '@sveltejs/kit/node/polyfills';
installPolyfills();
31 changes: 16 additions & 15 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 82b2b11

Please sign in to comment.