@absolutejs/absolute 0.1.0

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 @@
1
+ // @bun
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{e as r}from"../build-241dg605.js";import{f as e}from"../utils/networking.js";import"../build-azzc5a4m.js";import{argv as a}from"node:process";var{env:s}=globalThis.Bun;var t=s.HOST??"localhost",o=s.PORT??r,l,c=a,n=c.includes("--host");if(n)l=e(),t="0.0.0.0";var d=(i)=>i.listen({hostname:t,port:o},()=>{if(n)console.log(`Server started on http://localhost:${o}`),console.log(`Server started on network: http://${l}:${o}`);else console.log(`Server started on http://${t}:${o}`)});export{d as networkingPlugin};
@@ -0,0 +1 @@
1
+ // @bun
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{a as i}from"../core/build.js";import"../build-241dg605.js";import"../utils/updateScriptTags.js";import"../build-azzc5a4m.js";var a=await i();
@@ -0,0 +1,8 @@
1
+ export declare const SECONDS_IN_A_MINUTE = 60;
2
+ export declare const MILLISECONDS_IN_A_SECOND = 1000;
3
+ export declare const MILLISECONDS_IN_A_MINUTE: number;
4
+ export declare const MINUTES_IN_AN_HOUR = 60;
5
+ export declare const HOURS_IN_A_DAY = 24;
6
+ export declare const MILLISECONDS_IN_A_DAY: number;
7
+ export declare const TIME_PRECISION = 2;
8
+ export declare const DEFAULT_PORT = 3000;
@@ -0,0 +1 @@
1
+ export declare const build: () => Promise<Record<string, string>>;
@@ -0,0 +1,3 @@
1
+ import { ComponentType } from "react";
2
+ export declare const handleReactPageRequest: (pageComponent: ComponentType, index: string) => Promise<Response>;
3
+ export declare const handleHTMLPageRequest: (html: string) => import("bun").BunFile;
@@ -0,0 +1,21 @@
1
+ import { Elysia } from "elysia";
2
+ export declare const networkingPlugin: (app: Elysia) => Elysia<"", false, {
3
+ decorator: {};
4
+ store: {};
5
+ derive: {};
6
+ resolve: {};
7
+ }, {
8
+ type: {};
9
+ error: {};
10
+ }, {
11
+ schema: {};
12
+ macro: {};
13
+ }, {}, {
14
+ derive: {};
15
+ resolve: {};
16
+ schema: {};
17
+ }, {
18
+ derive: {};
19
+ resolve: {};
20
+ schema: {};
21
+ }>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export declare const getLocalIPAddress: () => string;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Updates <script> tags in all HTML files within htmlDir.
3
+ * For each script tag whose src file base (with or without a hash) is a key in the manifest,
4
+ * the src attribute is replaced with the new hashed file path.
5
+ *
6
+ * @param manifest - An object mapping script base names to the new file path.
7
+ * @param htmlDir - The directory that contains the HTML files.
8
+ */
9
+ export declare const updateScriptTags: (manifest: Record<string, string>, htmlDir: string) => Promise<void>;
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import"../build-azzc5a4m.js";import q from"node:os";var x=()=>{let m=q.networkInterfaces(),j=Object.values(m).flat().filter((g)=>g!==void 0).find((g)=>g.family==="IPv4"&&!g.internal);if(j)return j.address;return console.warn("No IP address found, falling back to localhost"),"localhost"};export{x as getLocalIPAddress};
3
+ export{x as f};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import"../build-azzc5a4m.js";import{readFile as K,writeFile as L}from"node:fs/promises";var{Glob:M}=globalThis.Bun;var W=async(y,z)=>{let A=new M("*.html"),q=[];for await(let j of A.scan({cwd:z,absolute:!0}))q.push(j);for(let j of q){let k=await K(j,"utf8");for(let[B,C]of Object.entries(y)){let E=B.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),H=new RegExp(`(<script[^>]+src=["'])(/?(?:.*\\/)?${E})(?:\\.[^."'/]+)?(\\.js)(["'][^>]*>)`,"g");k=k.replace(H,(O,I,Q,T,J)=>{return`${I}${C}${J}`})}await L(j,k,"utf8")}};export{W as updateScriptTags};
3
+ export{W as g};
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@absolutejs/absolute",
3
+ "version": "0.1.0",
4
+ "description": "A fullstack meta-framework for building web applications with TypeScript",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/alexkahndev/absolutejs.git"
8
+ },
9
+ "main": "dist/index.js",
10
+ "license": "CC BY-NC 4.0",
11
+ "author": "Alex Kahn",
12
+ "scripts": {
13
+ "build": "bun build src/**/* --outdir dist --minify --splitting --target=bun && tsc --emitDeclarationOnly --project tsconfig.json",
14
+ "test": "echo \"Error: no test specified\" && exit 1",
15
+ "format": "prettier --write \"./**/*.{js,jsx,ts,tsx,css}\"",
16
+ "dev": "bun run --watch example/server.ts"
17
+ },
18
+ "dependencies": {
19
+ "@elysiajs/static": "1.0.2",
20
+ "elysia": "1.0.13",
21
+ "react": "19.1.0",
22
+ "react-dom": "19.1.0",
23
+ "svelte": "4.2.15",
24
+ "vue": "3.4.26"
25
+ },
26
+ "devDependencies": {
27
+ "@types/bun": "1.1.1",
28
+ "@types/react": "19.1.0",
29
+ "@types/react-dom": "19.1.2",
30
+ "@types/vue": "2.0.0",
31
+ "typescript": "5.7.2"
32
+ }
33
+ }
@@ -0,0 +1,22 @@
1
+ import svelte from "rollup-plugin-svelte";
2
+ import css from "rollup-plugin-css-only";
3
+ import { terser } from "rollup-plugin-terser";
4
+ import { nodeResolve } from "@rollup/plugin-node-resolve";
5
+
6
+ export default {
7
+ input: "src/svelte/pages/SvelteHome.svelte",
8
+ output: {
9
+ dir: "build/svelte/indexes",
10
+ format: "es" as const
11
+ },
12
+ plugins: [
13
+ nodeResolve(),
14
+ svelte({
15
+ compilerOptions: {
16
+ generate: "ssr"
17
+ }
18
+ }),
19
+ css({ output: "SvelteHome.css" }),
20
+ terser()
21
+ ]
22
+ };
@@ -0,0 +1,13 @@
1
+ export const SECONDS_IN_A_MINUTE = 60;
2
+ export const MILLISECONDS_IN_A_SECOND = 1000;
3
+ export const MILLISECONDS_IN_A_MINUTE =
4
+ MILLISECONDS_IN_A_SECOND * SECONDS_IN_A_MINUTE;
5
+ export const MINUTES_IN_AN_HOUR = 60;
6
+ export const HOURS_IN_A_DAY = 24;
7
+ export const MILLISECONDS_IN_A_DAY =
8
+ MILLISECONDS_IN_A_SECOND *
9
+ SECONDS_IN_A_MINUTE *
10
+ MINUTES_IN_AN_HOUR *
11
+ HOURS_IN_A_DAY;
12
+ export const TIME_PRECISION = 2;
13
+ export const DEFAULT_PORT = 3000;
@@ -0,0 +1,154 @@
1
+ import { rm, mkdir, writeFile } from "node:fs/promises";
2
+ import { join, basename } from "node:path";
3
+ import { exit } from "node:process";
4
+ import { $, build as bunBuild, Glob } from "bun";
5
+ import {
6
+ MILLISECONDS_IN_A_MINUTE,
7
+ MILLISECONDS_IN_A_SECOND,
8
+ TIME_PRECISION
9
+ } from "../constants";
10
+ import { updateScriptTags } from "../utils/updateScriptTags";
11
+
12
+ const projectRoot = join(import.meta.dir, "..", "..");
13
+ const buildDir = join(projectRoot, "example/build");
14
+ const assetsDir = join(projectRoot, "example/assets");
15
+ const reactIndexDir = join(projectRoot, "example/react/indexes");
16
+ const javascriptDir = join(projectRoot, "example/javascript");
17
+ const typeScriptDir = join(projectRoot, "example/typescript");
18
+ const reactPagesDir = join(projectRoot, "example/react/pages");
19
+ const htmlDir = join(projectRoot, "example/html");
20
+
21
+ export const build = async () => {
22
+ const start = performance.now();
23
+
24
+ await rm(buildDir, { force: true, recursive: true });
25
+ await generateReactIndexFiles();
26
+
27
+ const reactEntryGlob = new Glob("*.{tsx,jsx}");
28
+ const reactEntryPaths: string[] = [];
29
+ for await (const file of reactEntryGlob.scan({
30
+ absolute: true,
31
+ cwd: reactIndexDir
32
+ })) {
33
+ reactEntryPaths.push(file);
34
+ }
35
+
36
+ const javascriptEntryGlob = new Glob("*.js");
37
+ const javascriptEntryPaths: string[] = [];
38
+ for await (const file of javascriptEntryGlob.scan({
39
+ absolute: true,
40
+ cwd: javascriptDir
41
+ })) {
42
+ javascriptEntryPaths.push(file);
43
+ }
44
+
45
+ const typeScriptEntryGlob = new Glob("*.ts");
46
+ const typeScriptEntryPaths: string[] = [];
47
+ for await (const file of typeScriptEntryGlob.scan({
48
+ absolute: true,
49
+ cwd: typeScriptDir
50
+ })) {
51
+ typeScriptEntryPaths.push(file);
52
+ }
53
+ const entryPaths = reactEntryPaths
54
+ .concat(javascriptEntryPaths)
55
+ .concat(typeScriptEntryPaths);
56
+
57
+ const { logs, outputs } = await bunBuild({
58
+ entrypoints: entryPaths,
59
+ format: "esm",
60
+ naming: `[dir]/[name].[hash].[ext]`,
61
+ outdir: buildDir
62
+ }).catch((error) => {
63
+ console.error("Build failed:", error);
64
+ exit(1);
65
+ });
66
+
67
+ logs.forEach((log) => {
68
+ if (log.level === "error") console.error(log);
69
+ else if (log.level === "warning") console.warn(log);
70
+ else if (log.level === "info" || log.level === "debug")
71
+ console.info(log);
72
+ });
73
+
74
+ await copyAssetsToBuildDir();
75
+
76
+ // TODO: Find a way to make this type-safe instead of string as the key it should be enumerated with the names of the files
77
+ const manifest = outputs.reduce<Record<string, string>>((acc, artifact) => {
78
+ let relativePath = artifact.path;
79
+
80
+ if (relativePath.startsWith(buildDir)) {
81
+ relativePath = relativePath.slice(buildDir.length);
82
+ }
83
+
84
+ relativePath = relativePath.replace(/^\/+/, "");
85
+
86
+ const baseName = relativePath.split("/").pop();
87
+ if (!baseName) return acc;
88
+
89
+ const hashDelimiter = `.${artifact.hash}.`;
90
+ if (!baseName.includes(hashDelimiter)) {
91
+ throw new Error(
92
+ `Expected hash delimiter ${hashDelimiter} in ${baseName}`
93
+ );
94
+ }
95
+
96
+ const [fileName] = baseName.split(hashDelimiter);
97
+ acc[fileName] = "/" + relativePath;
98
+ return acc;
99
+ }, {});
100
+
101
+ await updateScriptTags(manifest, htmlDir);
102
+
103
+ const end = performance.now();
104
+ const durationMs = end - start;
105
+ let duration;
106
+ if (durationMs < MILLISECONDS_IN_A_SECOND) {
107
+ duration = `${durationMs.toFixed(TIME_PRECISION)}ms`;
108
+ } else if (durationMs < MILLISECONDS_IN_A_MINUTE) {
109
+ duration = `${(durationMs / MILLISECONDS_IN_A_SECOND).toFixed(TIME_PRECISION)}s`;
110
+ } else {
111
+ duration = `${(durationMs / MILLISECONDS_IN_A_MINUTE).toFixed(TIME_PRECISION)}m`;
112
+ }
113
+ console.log(`Build completed in ${duration}`);
114
+
115
+ console.log("Outputs:", outputs);
116
+ console.log("Manifest:", manifest);
117
+
118
+ return manifest;
119
+ };
120
+
121
+ const copyAssetsToBuildDir = async () => {
122
+ await $`cp -R ${assetsDir} ${buildDir}`;
123
+ await mkdir(join(buildDir, "html"));
124
+ await mkdir(join(buildDir, "htmx"));
125
+
126
+ await $`cp -R ${join(projectRoot, "example/html")} ${join(buildDir)}`;
127
+ await $`cp -R ${join(projectRoot, "example/htmx")} ${join(buildDir)}`;
128
+ };
129
+
130
+ const generateReactIndexFiles = async () => {
131
+ await rm(reactIndexDir, { force: true, recursive: true });
132
+ await mkdir(reactIndexDir);
133
+
134
+ const pagesGlob = new Glob("*.*");
135
+ const files: string[] = [];
136
+ for await (const file of pagesGlob.scan({ cwd: reactPagesDir })) {
137
+ files.push(file);
138
+ }
139
+ const promises = files.map(async (file) => {
140
+ const fileName = basename(file);
141
+ const [componentName] = fileName.split(".");
142
+ const content = [
143
+ `import { hydrateRoot } from 'react-dom/client';`,
144
+ `import { ${componentName} } from '../pages/${componentName}';\n`,
145
+ `hydrateRoot(document, <${componentName} />);`
146
+ ].join("\n");
147
+
148
+ return writeFile(
149
+ join(reactIndexDir, `${componentName}Index.tsx`),
150
+ content
151
+ );
152
+ });
153
+ await Promise.all(promises);
154
+ };
@@ -0,0 +1,19 @@
1
+ import { ComponentType, createElement } from "react";
2
+ //@ts-expect-error - TODO: Remove this when we upgrade to React 19
3
+ import { renderToReadableStream } from "react-dom/server.browser";
4
+
5
+ export const handleReactPageRequest = async (
6
+ pageComponent: ComponentType,
7
+ index: string
8
+ ) => {
9
+ const page = createElement(pageComponent);
10
+ const stream = await renderToReadableStream(page, {
11
+ bootstrapModules: [index]
12
+ });
13
+
14
+ return new Response(stream, {
15
+ headers: { "Content-Type": "text/html" }
16
+ });
17
+ };
18
+
19
+ export const handleHTMLPageRequest = (html: string) => Bun.file(html);
@@ -0,0 +1,35 @@
1
+ import { argv } from "node:process";
2
+ import { env } from "bun";
3
+ import { Elysia } from "elysia";
4
+ import { getLocalIPAddress } from "../utils/networking";
5
+ import { DEFAULT_PORT } from "../constants";
6
+
7
+ let host = env.HOST ?? "localhost";
8
+ const port = env.PORT ?? DEFAULT_PORT;
9
+ let localIP: string | undefined;
10
+
11
+ const args = argv;
12
+ const hostFlag = args.includes("--host");
13
+
14
+ if (hostFlag) {
15
+ localIP = getLocalIPAddress();
16
+ host = "0.0.0.0";
17
+ }
18
+
19
+ export const networkingPlugin = (app: Elysia) =>
20
+ app.listen(
21
+ {
22
+ hostname: host,
23
+ port: port
24
+ },
25
+ () => {
26
+ if (hostFlag) {
27
+ console.log(`Server started on http://localhost:${port}`);
28
+ console.log(
29
+ `Server started on network: http://${localIP}:${port}`
30
+ );
31
+ } else {
32
+ console.log(`Server started on http://${host}:${port}`);
33
+ }
34
+ }
35
+ );
@@ -0,0 +1,3 @@
1
+ import { build } from "../core/build";
2
+
3
+ const manifest = await build();
@@ -0,0 +1,19 @@
1
+ import os from "os";
2
+
3
+ export const getLocalIPAddress = () => {
4
+ const interfaces = os.networkInterfaces();
5
+ const addresses = Object.values(interfaces)
6
+ .flat()
7
+ .filter(
8
+ (iface): iface is os.NetworkInterfaceInfo => iface !== undefined
9
+ );
10
+ const ipAddress = addresses.find(
11
+ (iface) => iface.family === "IPv4" && !iface.internal
12
+ );
13
+
14
+ if (ipAddress) return ipAddress.address; // Return the first non-internal IPv4 address
15
+
16
+ console.warn("No IP address found, falling back to localhost");
17
+
18
+ return "localhost"; // Fallback to localhost if no IP found
19
+ };
@@ -0,0 +1,51 @@
1
+ // TODO : this script seems to only work after building twice maybe due to the async nature of it
2
+
3
+ import { readFile, writeFile } from "node:fs/promises";
4
+ import { Glob } from "bun";
5
+
6
+ /**
7
+ * Updates <script> tags in all HTML files within htmlDir.
8
+ * For each script tag whose src file base (with or without a hash) is a key in the manifest,
9
+ * the src attribute is replaced with the new hashed file path.
10
+ *
11
+ * @param manifest - An object mapping script base names to the new file path.
12
+ * @param htmlDir - The directory that contains the HTML files.
13
+ */
14
+ export const updateScriptTags = async (manifest: Record<string, string>, htmlDir: string) => {
15
+ // Use Glob to find all HTML files in the specified directory
16
+ const htmlGlob = new Glob("*.html");
17
+ const htmlFiles: string[] = [];
18
+ for await (const file of htmlGlob.scan({
19
+ cwd: htmlDir,
20
+ absolute: true,
21
+ })) {
22
+ htmlFiles.push(file);
23
+ }
24
+
25
+ // Process each HTML file
26
+ for (const filePath of htmlFiles) {
27
+ let content = await readFile(filePath, "utf8");
28
+
29
+ // For each script in the manifest, update matching <script> tags
30
+ for (const [scriptName, newPath] of Object.entries(manifest)) {
31
+ // Escape special regex characters in the scriptName
32
+ const escapedScriptName = scriptName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
33
+ // The regex explanation:
34
+ // (1) (<script[^>]+src=["']) — capture the opening of the script tag up to the src attribute value
35
+ // (2) (\/?(?:.*\\/)?${escapedScriptName}) — capture any preceding path and the base script name
36
+ // (3) (?:\.[^."'/]+)? — optionally capture a dot and hash (if already hashed)
37
+ // (4) (\.js) — then capture the js extension
38
+ // (5) (["'][^>]*>) — capture the closing quote and remainder of the script tag
39
+ const regex = new RegExp(
40
+ `(<script[^>]+src=["'])(\/?(?:.*\\/)?${escapedScriptName})(?:\\.[^."'/]+)?(\\.js)(["'][^>]*>)`,
41
+ "g"
42
+ );
43
+ // Replace the matched src attribute with the new value from the manifest
44
+ content = content.replace(regex, (_, prefix, _oldBase, _ext, suffix) => {
45
+ return `${prefix}${newPath}${suffix}`;
46
+ });
47
+ }
48
+
49
+ await writeFile(filePath, content, "utf8");
50
+ }
51
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "jsx": "react-jsx",
7
+ "esModuleInterop": true,
8
+ "forceConsistentCasingInFileNames": true,
9
+ "outDir": "dist",
10
+ "strict": true,
11
+ "declaration": true,
12
+ "skipLibCheck": true,
13
+ "lib": ["DOM", "DOM.Iterable", "ESNext"],
14
+ },
15
+ "include": ["src/**/*", "example/**/*"],
16
+ "exclude": ["node_modules"]
17
+ }