reburn-ui 0.1.6 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ import type { Adapter } from '@sveltejs/kit';
2
+ import type { AdapterOptions } from './index.js';
3
+ export default function (opts?: AdapterOptions): Adapter;
@@ -0,0 +1,63 @@
1
+ import { writeFileSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ const files = fileURLToPath(new URL('./files', import.meta.url).href);
4
+ export default function (opts = {}) {
5
+ const { out = 'build', precompress = false, envPrefix = '' } = opts;
6
+ return {
7
+ name: 'svelte-adapter-bun',
8
+ async adapt(builder) {
9
+ const tmp = builder.getBuildDirectory('adapter-bun');
10
+ builder.rimraf(out);
11
+ builder.rimraf(tmp);
12
+ builder.mkdirp(tmp);
13
+ builder.log.minor('Copying assets');
14
+ builder.writeClient(`${out}/client${builder.config.kit.paths.base}`);
15
+ builder.writePrerendered(`${out}/prerendered${builder.config.kit.paths.base}`);
16
+ if (precompress) {
17
+ builder.log.minor('Compressing assets');
18
+ await Promise.all([builder.compress(`${out}/client`), builder.compress(`${out}/prerendered`)]);
19
+ }
20
+ builder.log.minor('Building server');
21
+ builder.writeServer(tmp);
22
+ writeFileSync(`${tmp}/manifest.js`, [
23
+ `export const manifest = ${builder.generateManifest({ relativePath: './' })};`,
24
+ `export const prerendered = new Set(${JSON.stringify(builder.prerendered.paths)});`,
25
+ `export const base = ${JSON.stringify(builder.config.kit.paths.base)};`,
26
+ ].join('\n\n'));
27
+ builder.log.minor('Patching server (websocket support)');
28
+ // we bundle the Vite output so that deployments only need
29
+ // their production dependencies. Anything in devDependencies
30
+ // will get included in the bundled code
31
+ const res = await Bun.build({
32
+ entrypoints: [`${tmp}/index.js`, `${tmp}/manifest.js`],
33
+ format: 'esm',
34
+ target: 'bun',
35
+ sourcemap: 'inline',
36
+ outdir: `${out}/server`,
37
+ splitting: true,
38
+ naming: {
39
+ entry: '[name].[ext]',
40
+ chunk: 'chunks/[name]-[hash].[ext]',
41
+ },
42
+ });
43
+ const hooksFile = res.outputs.find((file) => file.path.includes('hooks.server'));
44
+ const replacement = hooksFile.path.split('/').pop();
45
+ builder.copy(files, out, {
46
+ replace: {
47
+ ENV: './env.js',
48
+ HANDLER: './handler.js',
49
+ MANIFEST: './server/manifest.js',
50
+ SERVER: './server/index.js',
51
+ SHIMS: './shims.js',
52
+ ENV_PREFIX: JSON.stringify(envPrefix),
53
+ SERVER_HOOKS: `./server/chunks/${replacement}`,
54
+ },
55
+ });
56
+ builder.log.success(`Start server with: bun ./${out}/index.js`);
57
+ process.exit(0);
58
+ },
59
+ supports: {
60
+ read: () => true,
61
+ },
62
+ };
63
+ }
@@ -0,0 +1,35 @@
1
+ import type { Adapter } from '@sveltejs/kit';
2
+ import type { Server, WebSocketHandler } from 'bun';
3
+
4
+ declare global {
5
+ const ENV_PREFIX: string;
6
+ }
7
+
8
+ interface MimeTypes {
9
+ [key: string]: string;
10
+ }
11
+
12
+ export interface AdapterOptions {
13
+ /**
14
+ * The directory to build the server to. It defaults to build — i.e. node build would start the server locally after it has been created.
15
+ * @default "build"
16
+ */
17
+ out?: string;
18
+ /**
19
+ * Enables precompressing using gzip and brotli for assets and prerendered pages. It defaults to false.
20
+ * @default false
21
+ */
22
+ precompress?: boolean;
23
+
24
+ /**
25
+ * If you need to change the name of the environment variables used to configure the deployment (for example, to deconflict with environment variables you don't control), you can specify a prefix: envPrefix: 'MY_CUSTOM_';
26
+ * @default ''
27
+ */
28
+ envPrefix?: string;
29
+ }
30
+
31
+ export interface KitWebSocketHandler<T = undefined> extends WebSocketHandler<T> {
32
+ upgrade: (request: Request, server: Server) => boolean | Promise<boolean>;
33
+ }
34
+
35
+ export default function plugin(options?: AdapterOptions): Adapter;
@@ -0,0 +1,21 @@
1
+ declare module 'ENV' {
2
+ export function env<T>(key: string, fallback?: T): T | string;
3
+ }
4
+
5
+ declare module 'MANIFEST' {
6
+ import { SSRManifest } from '@sveltejs/kit';
7
+
8
+ export const base: string;
9
+ export const manifest: SSRManifest;
10
+ export const prerendered: Set<string>;
11
+ }
12
+
13
+ declare module 'SERVER' {
14
+ export { Server } from '@sveltejs/kit';
15
+ }
16
+
17
+ declare module 'SERVER_HOOKS' {
18
+ export const handle: import('@sveltejs/kit').Handle;
19
+ export const handleWebsocket: import('./index').KitWebSocketHandler;
20
+ export const WS_PATH: string;
21
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @param {string} name
3
+ * @param {any} fallback
4
+ */
5
+ export declare function env<T>(name: string, fallback: T): string | T;
@@ -0,0 +1,36 @@
1
+ /* global ENV_PREFIX */
2
+ import process from 'node:process';
3
+ const expected = new Set([
4
+ 'SOCKET_PATH',
5
+ 'HOST',
6
+ 'PORT',
7
+ 'ORIGIN',
8
+ 'XFF_DEPTH',
9
+ 'ADDRESS_HEADER',
10
+ 'PROTOCOL_HEADER',
11
+ 'HOST_HEADER',
12
+ 'PORT_HEADER',
13
+ 'BODY_SIZE_LIMIT',
14
+ 'SHUTDOWN_TIMEOUT',
15
+ 'IDLE_TIMEOUT',
16
+ ]);
17
+ const expected_unprefixed = new Set(['LISTEN_PID', 'LISTEN_FDS']);
18
+ if (ENV_PREFIX) {
19
+ for (const name in process.env) {
20
+ if (name.startsWith(ENV_PREFIX)) {
21
+ const unprefixed = name.slice(ENV_PREFIX.length);
22
+ if (!expected.has(unprefixed)) {
23
+ throw new Error(`You should change envPrefix (${ENV_PREFIX}) to avoid conflicts with existing environment variables — unexpectedly saw ${name}`);
24
+ }
25
+ }
26
+ }
27
+ }
28
+ /**
29
+ * @param {string} name
30
+ * @param {any} fallback
31
+ */
32
+ export function env(name, fallback) {
33
+ const prefix = expected_unprefixed.has(name) ? '' : ENV_PREFIX;
34
+ const prefixed = prefix + name;
35
+ return prefixed in process.env ? process.env[prefixed] : fallback;
36
+ }
@@ -0,0 +1 @@
1
+ export default function ssr(request: Request, bunServer: Bun.Server): Promise<Response>;
@@ -0,0 +1,57 @@
1
+ import { createReadableStream } from '@sveltejs/kit/node';
2
+ import { fileURLToPath } from 'bun';
3
+ import { base, manifest } from 'MANIFEST';
4
+ import path from 'node:path';
5
+ import { Server } from 'SERVER';
6
+ import { env } from './env.js';
7
+ import { parse_as_bytes } from './utils.js';
8
+ const server = new Server(manifest);
9
+ const xff_depth = parseInt(env('XFF_DEPTH', '1'));
10
+ const address_header = env('ADDRESS_HEADER', '').toLowerCase();
11
+ const host_header = env('HOST_HEADER', 'host').toLowerCase();
12
+ const body_size_limit = parse_as_bytes(env('BODY_SIZE_LIMIT', '512K'));
13
+ if (isNaN(body_size_limit)) {
14
+ throw new Error(`Invalid BODY_SIZE_LIMIT: '${env('BODY_SIZE_LIMIT', '')}'. Please provide a numeric value.`);
15
+ }
16
+ const dir = path.dirname(fileURLToPath(import.meta.url));
17
+ const asset_dir = `${dir}/client${base}`;
18
+ await server.init({
19
+ env: process.env,
20
+ read: (file) => createReadableStream(`${asset_dir}/${file}`),
21
+ });
22
+ export default function ssr(request, bunServer) {
23
+ if (address_header && request.headers.get(host_header) !== '127.0.0.1' && !request.headers.has(address_header)) {
24
+ throw new Error(`Address header was specified with ${ENV_PREFIX + 'ADDRESS_HEADER'}=${address_header} but is absent from request`);
25
+ }
26
+ return server.respond(request, {
27
+ getClientAddress: () => {
28
+ if (address_header) {
29
+ if (!request.headers.has(address_header)) {
30
+ throw new Error(`Address header was specified with ${ENV_PREFIX + 'ADDRESS_HEADER'}=${address_header} but is absent from request`);
31
+ }
32
+ const value = request.headers.get(address_header) || '';
33
+ if (address_header === 'x-forwarded-for') {
34
+ const addresses = value.split(',');
35
+ if (xff_depth < 1) {
36
+ throw new Error(`${ENV_PREFIX + 'XFF_DEPTH'} must be a positive integer`);
37
+ }
38
+ if (xff_depth > addresses.length) {
39
+ throw new Error(`${ENV_PREFIX + 'XFF_DEPTH'} is ${xff_depth}, but only found ${addresses.length} addresses`);
40
+ }
41
+ return addresses[addresses.length - xff_depth].trim();
42
+ }
43
+ return value;
44
+ }
45
+ return (bunServer.requestIP(request)?.address ||
46
+ request.connection?.remoteAddress ||
47
+ request.connection?.socket?.remoteAddress ||
48
+ request.socket?.remoteAddress ||
49
+ request.info?.remoteAddress);
50
+ },
51
+ platform: {
52
+ isBun() {
53
+ return true;
54
+ },
55
+ },
56
+ });
57
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,90 @@
1
+ import { serve } from 'bun';
2
+ import fs from 'fs';
3
+ import path from 'node:path';
4
+ import url from 'node:url';
5
+ import * as websocketHooks from 'SERVER_HOOKS';
6
+ import { env } from './env.js';
7
+ import handler from './handler.js';
8
+ const hostname = env('HOST', '0.0.0.0');
9
+ const port = parseInt(env('PORT', '3000'));
10
+ const maxRequestBodySize = parseInt(env('BODY_SIZE_LIMIT', 1024 * 1024 * 2048)); // 2GB
11
+ const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
12
+ const staticPath = path.join(__dirname, './client');
13
+ const prerenderedPath = path.join(__dirname, './prerendered');
14
+ const allStaticFiles = {};
15
+ function getAllFiles(dirPath, arrayOfFiles = []) {
16
+ const files = fs.readdirSync(dirPath);
17
+ files.forEach((file) => {
18
+ const fullPath = path.join(dirPath, file);
19
+ if (fs.statSync(fullPath).isDirectory()) {
20
+ arrayOfFiles = getAllFiles(fullPath, arrayOfFiles);
21
+ }
22
+ else {
23
+ arrayOfFiles.push(fullPath);
24
+ }
25
+ });
26
+ return arrayOfFiles;
27
+ }
28
+ async function staticHTMLFile(file, url) {
29
+ allStaticFiles['/' + url] = new Response(await Bun.file(file).bytes(), {
30
+ headers: {
31
+ 'Content-Type': 'text/html',
32
+ 'Cache-Control': 'public, max-age=0, s-maxage=0',
33
+ },
34
+ });
35
+ }
36
+ // Get all static files
37
+ try {
38
+ const staticFiles = getAllFiles(staticPath);
39
+ for await (const file of staticFiles) {
40
+ const relativePath = path.relative(staticPath, file);
41
+ const readFile = Bun.file(file);
42
+ const stats = await readFile.stat();
43
+ allStaticFiles['/' + relativePath] = new Response(await readFile.bytes(), {
44
+ headers: {
45
+ 'Content-Type': readFile.type,
46
+ Etag: `W/"${readFile.size}-${stats.mtime.getTime()}"`,
47
+ 'Last-Modified': stats.mtime.toUTCString(),
48
+ 'Cache-Control': 'public, max-age=31536000, immutable',
49
+ ...(relativePath.endsWith('.gz') ? { 'Content-Encoding': 'gzip' } : {}),
50
+ ...(relativePath.endsWith('.br') ? { 'Content-Encoding': 'br' } : {}),
51
+ },
52
+ });
53
+ }
54
+ if (fs.existsSync(prerenderedPath)) {
55
+ const prerenderedFiles = getAllFiles(prerenderedPath);
56
+ for await (const file of prerenderedFiles) {
57
+ const relativePath = path.relative(prerenderedPath, file);
58
+ await staticHTMLFile(file, relativePath);
59
+ await staticHTMLFile(file, relativePath.replace('.html', ''));
60
+ if (relativePath === 'index.html') {
61
+ await staticHTMLFile(file, '');
62
+ }
63
+ }
64
+ }
65
+ }
66
+ catch (error) {
67
+ console.warn('No static files found:', error);
68
+ }
69
+ serve({
70
+ routes: { ...allStaticFiles, ...(websocketHooks.WS_PATH ? { [websocketHooks.WS_PATH]: websocketHooks.handleWebsocket.upgrade } : {}) },
71
+ fetch(req, bunServer) {
72
+ /**
73
+ * This is a temporary workaround since at one point in the app https goes to http (for some reason)
74
+ */
75
+ const originHeader = req.headers.get('origin');
76
+ if (originHeader) {
77
+ req.headers.set('origin', originHeader.replace('https://', 'http://'));
78
+ }
79
+ return handler(req, bunServer);
80
+ },
81
+ websocket: websocketHooks.handleWebsocket ? websocketHooks.handleWebsocket : undefined,
82
+ hostname,
83
+ port,
84
+ development: false,
85
+ error(error) {
86
+ console.error(error);
87
+ return new Response('Uh oh!!', { status: 500 });
88
+ },
89
+ maxRequestBodySize: isNaN(maxRequestBodySize) ? undefined : maxRequestBodySize,
90
+ });
@@ -0,0 +1,27 @@
1
+ import type { Stats } from 'node:fs';
2
+ type Arrayable<T> = T | T[];
3
+ type NextHandler = () => void | Promise<void>;
4
+ export type SirvRequestHandler = (req: Request, next?: NextHandler) => Response;
5
+ export interface SirvFiles {
6
+ [key: string]: SirvData;
7
+ }
8
+ export interface SirvData {
9
+ abs: string;
10
+ stats: Stats;
11
+ headers: Headers;
12
+ }
13
+ export interface SirvOptions {
14
+ dev?: boolean;
15
+ etag?: boolean;
16
+ maxAge?: number;
17
+ immutable?: boolean;
18
+ single?: string | boolean;
19
+ ignores?: false | Arrayable<string | RegExp>;
20
+ extensions?: string[];
21
+ dotfiles?: boolean;
22
+ brotli?: boolean;
23
+ gzip?: boolean;
24
+ onNoMatch?: (req: Request) => Response;
25
+ setHeaders?: (headers: Headers, pathname: string, stats: Stats) => Headers;
26
+ }
27
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Parses the given value into number of bytes.
3
+ *
4
+ * @param {string} value - Size in bytes. Can also be specified with a unit suffix kilobytes (K), megabytes (M), or gigabytes (G).
5
+ * @returns {number}
6
+ */
7
+ export declare function parse_as_bytes(value: string): number;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Parses the given value into number of bytes.
3
+ *
4
+ * @param {string} value - Size in bytes. Can also be specified with a unit suffix kilobytes (K), megabytes (M), or gigabytes (G).
5
+ * @returns {number}
6
+ */
7
+ export function parse_as_bytes(value) {
8
+ const multiplier = {
9
+ K: 1024,
10
+ M: 1024 * 1024,
11
+ G: 1024 * 1024 * 1024,
12
+ }[value[value.length - 1]?.toUpperCase()] ?? 1;
13
+ return Number(multiplier != 1 ? value.substring(0, value.length - 1) : value) * multiplier;
14
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "allowJs": true,
4
+ "checkJs": true,
5
+ "noEmit": true,
6
+ "noImplicitAny": true,
7
+ "allowSyntheticDefaultImports": true,
8
+ "target": "es2022",
9
+ "module": "node16",
10
+ "moduleResolution": "node16",
11
+ "baseUrl": "."
12
+ },
13
+ "include": ["adapter.ts", "internal.d.ts", "src/**/*.ts", "src/**/*.js"],
14
+ "exclude": []
15
+ }
@@ -0,0 +1 @@
1
+ export { default as adapter } from './adapter-bun/adapter.js';
@@ -0,0 +1 @@
1
+ export { default as adapter } from './adapter-bun/adapter.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "reburn-ui",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "scripts": {
@@ -33,6 +33,11 @@
33
33
  "svelte": "./dist/tools/index.js",
34
34
  "default": "./dist/tools/index.js"
35
35
  },
36
+ "./adapter": {
37
+ "types": "./dist/adapter/index.d.ts",
38
+ "svelte": "./dist/adapter/index.js",
39
+ "default": "./dist/adapter/index.js"
40
+ },
36
41
  "./styles/baseline.css": "./dist/styles/baseline.css",
37
42
  "./styles/default-css-variables.css": "./dist/styles/default-css-variables.css",
38
43
  "./styles/global.css": "./dist/styles/global.css",