-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathindex.ts
More file actions
158 lines (134 loc) · 4.58 KB
/
index.ts
File metadata and controls
158 lines (134 loc) · 4.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import type { Adapter, Builder } from '@sveltejs/kit';
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { rolldown } from 'rolldown';
interface AdapterOptions {
out?: string;
precompress?: boolean;
envPrefix?: string;
serveAssets?: boolean;
}
const files = fileURLToPath(new URL('./files', import.meta.url).href);
export default function (options: AdapterOptions = {}): Adapter {
const {
out = 'build',
precompress = true,
envPrefix = '',
serveAssets = true,
} = options;
return {
name: 'svelte-adapter-bun',
async adapt(builder: Builder) {
const tmp = builder.getBuildDirectory('adapter-bun');
builder.rimraf(out);
builder.rimraf(tmp);
builder.mkdirp(tmp);
builder.log.minor('Copying assets');
builder.writeClient(`${out}/client${builder.config.kit.paths.base}`);
builder.writePrerendered(
`${out}/prerendered${builder.config.kit.paths.base}`
);
if (precompress) {
builder.log.minor('Compressing assets');
await Promise.all([
builder.compress(`${out}/client`),
builder.compress(`${out}/prerendered`),
]);
}
builder.log.minor('Building server');
builder.writeServer(tmp);
writeFileSync(
`${tmp}/manifest.js`,
[
`export const manifest = ${builder.generateManifest({ relativePath: './' })};`,
`export const prerendered = new Set(${JSON.stringify(builder.prerendered.paths)});`,
`export const base = ${JSON.stringify(builder.config.kit.paths.base)};`,
].join('\n\n')
);
const pkg = JSON.parse(readFileSync('package.json', 'utf-8'));
const entrypoints: Record<string, string> = {
index: `${tmp}/index.js`,
manifest: `${tmp}/manifest.js`,
};
if (builder.hasServerInstrumentationFile?.()) {
entrypoints['instrumentation.server'] =
`${tmp}/instrumentation.server.js`;
}
// ! Bun.build is not working for some reason
// ! It will build successfully but the server will throw [500] GET / Error: https://svelte.dev/e/lifecycle_outside_component
// const result = await Bun.build({
// entrypoints: Object.values(entrypoints),
// external: [
// // dependencies could have deep exports, so we need a regex
// ...Object.keys(pkg.dependencies || {}).map((d) => new RegExp(`^${d}(\\/.*)?$`).toString())
// ],
// target: 'bun',
// minify: false,
// outdir: `${out}/server`,
// });
// if (!result.success) {
// console.error('Build failed:', result.logs);
// process.exit(1);
// }
const bundle = await rolldown({
input: entrypoints,
external: [
// dependencies could have deep exports, so we need a regex
...Object.keys(pkg.dependencies || {}).map(
d => new RegExp(`^${d}(\\/.*)?$`)
),
// Node.js built-in modules
/^node:/,
],
});
await bundle.write({
dir: `${out}/server`,
format: 'esm',
sourcemap: true,
chunkFileNames: 'chunks/[name]-[hash].js',
});
await patchServerWebsocketHandler(`${out}/server/index.js`);
builder.copy(files, out, {
replace: {
ENV: './env.js',
HANDLER: './handler.js',
MANIFEST: './server/manifest.js',
SERVER: './server/index.js',
ENV_PREFIX: JSON.stringify(envPrefix),
BUILD_OPTIONS: JSON.stringify({ serveAssets }),
},
});
if (builder.hasServerInstrumentationFile?.()) {
builder.instrument?.({
entrypoint: `${out}/index.js`,
instrumentation: `${out}/server/instrumentation.server.js`,
module: {
exports: ['path', 'host', 'port', 'server'],
},
});
}
},
supports: {
read: () => true,
instrumentation: () => true,
},
};
}
/**
* Patch sveltekit server to return the websocket handler
*/
async function patchServerWebsocketHandler(path: string) {
const content = readFileSync(path, 'utf-8');
const result = content
.replace(
/(const (.*?) = await get_hooks\(\);)\s+(this\.#options\.hooks\s+=\s+{)/,
'$1$3websocket: $2.websocket || null,'
)
.replace(/(async function get_hooks\(\) {)/, '$1let websocket;')
.replace(/(\({handle,)((.|\s)*?return {)/, '$1websocket,$2websocket,')
.replace(
/(async init\({ env, read }\) {)/,
'websocket() {return this.#options.hooks.websocket}\n$1'
);
writeFileSync(path, result);
}