@olenbetong/appframe-vite 1.0.0-alpha.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.
package/lib/build.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { UserConfig } from "vite";
2
+ /**
3
+ * Node.js doesn't support JSON imports yet, so this is a simple
4
+ * function that reads a JSON file from disk and returns the parsed
5
+ * content.
6
+ */
7
+ export declare function importJson(url: string, useCwd?: boolean): Promise<any>;
8
+ export declare function addAppframeBuildConfig(config: UserConfig): Promise<UserConfig>;
package/lib/build.js ADDED
@@ -0,0 +1,55 @@
1
+ import { viteExternalsPlugin } from "vite-plugin-externals";
2
+ import { visualizer } from "rollup-plugin-visualizer";
3
+ import { readFile } from "node:fs/promises";
4
+ /**
5
+ * Node.js doesn't support JSON imports yet, so this is a simple
6
+ * function that reads a JSON file from disk and returns the parsed
7
+ * content.
8
+ */
9
+ export async function importJson(url, useCwd = false) {
10
+ let completeUrl = new URL(url, useCwd ? `file://${process.cwd()}/` : import.meta.url);
11
+ console.log(completeUrl);
12
+ return JSON.parse(await readFile(completeUrl, "utf-8"));
13
+ }
14
+ export async function addAppframeBuildConfig(config) {
15
+ var _a, _b;
16
+ let appPkg = await importJson("./package.json", true);
17
+ let { appframe } = appPkg;
18
+ config.build = (_a = config.build) !== null && _a !== void 0 ? _a : {};
19
+ config.build = {
20
+ ...config.build,
21
+ manifest: true,
22
+ sourcemap: true,
23
+ cssCodeSplit: false,
24
+ };
25
+ config.plugins = (_b = config.plugins) !== null && _b !== void 0 ? _b : [];
26
+ if (appframe.build.externals !== false) {
27
+ config.plugins.push(viteExternalsPlugin({
28
+ react: "React",
29
+ "react-dom": "ReactDOM",
30
+ }));
31
+ }
32
+ config.plugins.push(visualizer({ filename: "./dist/stats.html", gzipSize: true }));
33
+ config.build.rollupOptions = {
34
+ output: {
35
+ globals: appframe.build.externals !== false
36
+ ? {
37
+ react: "React",
38
+ "react-dom": "ReactDOM",
39
+ "react-dom/client": "ReactDOM",
40
+ }
41
+ : {},
42
+ entryFileNames: (info) => {
43
+ return `file/article/script/${appframe.article.id}/main.[hash].min.js`;
44
+ },
45
+ chunkFileNames: (chunkInfo) => {
46
+ let { name } = chunkInfo;
47
+ if (name === "main") {
48
+ return `file/article/script/${appframe.article.id}/[name].[hash].min.js`;
49
+ }
50
+ return `file/article/script/${appframe.article.id}/[name].[hash].chunk.min.js`;
51
+ },
52
+ },
53
+ };
54
+ return config;
55
+ }
@@ -0,0 +1,5 @@
1
+ import { Application } from "express";
2
+ import { ViteDevServer } from "vite";
3
+ export declare function addProxyRoutes(app: Application): Promise<void>;
4
+ export declare function addAppframeDevRoutes(app: Application, vite: ViteDevServer): Promise<void>;
5
+ export declare function startDevServer(app: Application): Promise<void>;
@@ -0,0 +1,99 @@
1
+ import dotenv from "dotenv";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import open from "open";
5
+ import tcpPortUsed from "tcp-port-used";
6
+ import { Client } from "@olenbetong/data-object";
7
+ import { importJson } from "./importJson.js";
8
+ import { createAppframeProxy } from "./proxy.js";
9
+ dotenv.config();
10
+ let appPkg = await importJson("./package.json");
11
+ let { appframe } = appPkg;
12
+ let userSession = null;
13
+ async function getUserSession(hostname, username, password) {
14
+ if (userSession) {
15
+ return userSession;
16
+ }
17
+ let client = new Client(hostname);
18
+ await client.login(username, password);
19
+ let userResult = await client.afFetch("/api/system/usersession", {
20
+ timeout: 5000
21
+ });
22
+ userSession = await userResult.json();
23
+ return userSession;
24
+ }
25
+ export async function addProxyRoutes(app) {
26
+ var _a, _b, _c, _d, _e;
27
+ const hostname = (_d = (_b = (_a = appframe.proxy) === null || _a === void 0 ? void 0 : _a.hostname) !== null && _b !== void 0 ? _b : (_c = appframe.deploy) === null || _c === void 0 ? void 0 : _c.hostname) !== null && _d !== void 0 ? _d : "dev.obet.no";
28
+ const { APPFRAME_LOGIN: username, APPFRAME_PWD: password } = process.env;
29
+ if (!username || !password) {
30
+ throw new Error("Your Appframe credentials are not set in the environment variables. Username should be set in APPFRAME_LOGIN and password in APPFRAME_PWD.");
31
+ }
32
+ const proxy = await createAppframeProxy({ hostname, username, password });
33
+ const proxyRoutes = [
34
+ "/api/*",
35
+ "/file/*",
36
+ "/filestore/*",
37
+ "/static/dbimages*",
38
+ "/static/images*",
39
+ "/destroy/*",
40
+ "/create/*",
41
+ "/update/*",
42
+ "/retrieve/*",
43
+ "/exec/*",
44
+ "/report/*",
45
+ "/rowcount/*",
46
+ "/lib/*"
47
+ ];
48
+ if ((_e = appframe.proxy) === null || _e === void 0 ? void 0 : _e.routes) {
49
+ proxyRoutes.push(...appframe.proxy.routes);
50
+ }
51
+ proxyRoutes.forEach(route => {
52
+ app.use(route, proxy);
53
+ });
54
+ }
55
+ export async function addAppframeDevRoutes(app, vite) {
56
+ var _a, _b, _c, _d;
57
+ const hostname = (_d = (_b = (_a = appframe.proxy) === null || _a === void 0 ? void 0 : _a.hostname) !== null && _b !== void 0 ? _b : (_c = appframe.deploy) === null || _c === void 0 ? void 0 : _c.hostname) !== null && _d !== void 0 ? _d : "dev.obet.no";
58
+ const { APPFRAME_LOGIN: username, APPFRAME_PWD: password } = process.env;
59
+ if (!username || !password) {
60
+ throw new Error("Your Appframe credentials are not set in the environment variables. Username should be set in APPFRAME_LOGIN and password in APPFRAME_PWD.");
61
+ }
62
+ app.use("*", async (req, res, next) => {
63
+ const url = req.originalUrl;
64
+ try {
65
+ let template = await fs.readFile(path.resolve(process.cwd(), "index.html"), "utf-8");
66
+ template = await vite.transformIndexHtml(url, template);
67
+ let userSession = await getUserSession(hostname, username, password);
68
+ let html = template
69
+ .replace("<!-- {Appframe} -->", `<script>
70
+ af = globalThis.af ?? {};
71
+ af.userSession = ${JSON.stringify(userSession)};
72
+ </script>
73
+ <script src="/file/article/static-script/${appframe.article.id}.js"></script>`)
74
+ .replace(`<!-- {Theme} -->`, `<link rel="stylesheet" href="/file/site/style/ob.theme.base.less" />
75
+ <link rel="stylesheet" href="/file/site/style/ob.theme.betongost.less" />
76
+ <link rel="stylesheet" href="/file/site/style/ob.theme.forsand.less" />
77
+ <link rel="stylesheet" href="/file/site/style/ob.theme.olenbetong.less" />
78
+ <link rel="stylesheet" href="/file/site/style/ob.theme.ribe.less" />
79
+ <link rel="stylesheet" href="/file/site/style/ob.theme.sjb.less" />
80
+ <link rel="stylesheet" href="/file/site/style/ob.es.application.min.css" />`);
81
+ res.status(200).set({ "Content-Type": "text/html" }).end(html);
82
+ }
83
+ catch (error) {
84
+ vite.ssrFixStacktrace(error);
85
+ next(error);
86
+ }
87
+ });
88
+ }
89
+ export async function startDevServer(app) {
90
+ let port = 3000;
91
+ let used = true;
92
+ do {
93
+ used = await tcpPortUsed.check(port);
94
+ if (used)
95
+ port++;
96
+ } while (used);
97
+ app.listen(port);
98
+ open(`http://localhost:${port}/${appframe.article.id}`);
99
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Node.js doesn't support JSON imports yet, so this is a simple
3
+ * function that reads a JSON file from disk and returns the parsed
4
+ * content.
5
+ */
6
+ export declare function importJson(url: any, useCwd?: boolean): Promise<any>;
@@ -0,0 +1,10 @@
1
+ import fs from "node:fs/promises";
2
+ /**
3
+ * Node.js doesn't support JSON imports yet, so this is a simple
4
+ * function that reads a JSON file from disk and returns the parsed
5
+ * content.
6
+ */
7
+ export async function importJson(url, useCwd = false) {
8
+ let completeUrl = new URL(url, useCwd ? `file://${process.cwd()}/` : import.meta.url);
9
+ return JSON.parse(await fs.readFile(completeUrl, "utf-8"));
10
+ }
package/lib/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./build.js";
2
+ export * from "./devServer.js";
package/lib/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./build.js";
2
+ export * from "./devServer.js";
package/lib/proxy.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ /// <reference types="qs" />
2
+ /// <reference types="express" />
3
+ export declare function login(hostname: string, username: string, password: string): Promise<Record<string, string>>;
4
+ export declare type createProxyOptions = {
5
+ /**
6
+ * If true, will wait for the first login request to complete before returning.
7
+ */
8
+ autoLogin?: boolean;
9
+ hostname: string;
10
+ username: string;
11
+ password: string;
12
+ protocol?: "http" | "https";
13
+ };
14
+ export declare function createAppframeProxy(options: createProxyOptions): Promise<import("express").RequestHandler<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>>;
package/lib/proxy.js ADDED
@@ -0,0 +1,89 @@
1
+ import expressProxy from "express-http-proxy";
2
+ import https from "node:https";
3
+ const lastLogin = new Map();
4
+ let currentLogin = null;
5
+ export async function login(hostname, username, password) {
6
+ if (currentLogin) {
7
+ return await currentLogin;
8
+ }
9
+ let loginPromise = new Promise((resolve, reject) => {
10
+ if (lastLogin.has(hostname)) {
11
+ let { timestamp, authCookies } = lastLogin.get(hostname);
12
+ if (Date.now() - timestamp < 1000 * 60 * 15) {
13
+ resolve(authCookies);
14
+ return;
15
+ }
16
+ else {
17
+ console.log("Renewing authentication cookies...");
18
+ lastLogin.delete(hostname);
19
+ }
20
+ }
21
+ let data = `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&remember=true&RequireTwoFactor=0`;
22
+ let options = {
23
+ hostname,
24
+ port: 443,
25
+ path: "/login",
26
+ method: "POST",
27
+ headers: {
28
+ Accept: "application/json",
29
+ "Content-Type": "application/x-www-form-urlencoded",
30
+ "Content-Length": data.length
31
+ }
32
+ };
33
+ console.log("Authenticating...");
34
+ let request = https.request(options, response => {
35
+ var _a, _b;
36
+ let status = (_a = response.statusCode) !== null && _a !== void 0 ? _a : 600;
37
+ if (status < 400) {
38
+ let cookies = (_b = response.headers["set-cookie"]) !== null && _b !== void 0 ? _b : [];
39
+ let cookieObj = {};
40
+ for (let cookie of cookies) {
41
+ let [keyValue] = cookie.split(";");
42
+ let [key, value] = keyValue.split("=");
43
+ if (["AppframeWebSession", "AppframeWebAuth"].includes(key)) {
44
+ cookieObj[key] = value;
45
+ }
46
+ }
47
+ console.log("Authentication successfull.");
48
+ lastLogin.set(hostname, {
49
+ timestamp: Date.now(),
50
+ authCookies: cookieObj
51
+ });
52
+ resolve(cookieObj);
53
+ }
54
+ else {
55
+ reject(Error(`Authentication failed: ${response.statusCode} ${response.statusMessage}`));
56
+ }
57
+ });
58
+ request.write(data);
59
+ request.end();
60
+ });
61
+ currentLogin = loginPromise;
62
+ let result = await loginPromise;
63
+ currentLogin = null;
64
+ return result;
65
+ }
66
+ export async function createAppframeProxy(options) {
67
+ const { autoLogin = true, hostname, password, protocol = "https", username } = options;
68
+ const proxy = expressProxy(`${protocol}://${hostname}`, {
69
+ proxyReqOptDecorator: async function (proxyReqOpts) {
70
+ var _a, _b;
71
+ if (!((_a = proxyReqOpts.path) === null || _a === void 0 ? void 0 : _a.startsWith("/login"))) {
72
+ let authCookies = await login(hostname, username, password);
73
+ let cookies = [];
74
+ cookies.push(`AppframeWebAuth=${authCookies["AppframeWebAuth"]}`);
75
+ cookies.push(`AppframeWebSession=${authCookies["AppframeWebSession"]}`);
76
+ proxyReqOpts.headers = (_b = proxyReqOpts.headers) !== null && _b !== void 0 ? _b : {};
77
+ proxyReqOpts.headers["cookie"] = cookies.join(";");
78
+ }
79
+ return proxyReqOpts;
80
+ },
81
+ proxyReqPathResolver: function (req) {
82
+ return req.originalUrl;
83
+ }
84
+ });
85
+ if (autoLogin) {
86
+ await login(hostname, username, password);
87
+ }
88
+ return proxy;
89
+ }
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@olenbetong/appframe-vite",
3
+ "version": "1.0.0-alpha.0",
4
+ "description": "Tools to use and deploy Vite applications to Appframe",
5
+ "main": "./lib/index.js",
6
+ "type": "module",
7
+ "types": "./lib/index.d.ts",
8
+ "exports": {
9
+ "default": "./lib/index.js"
10
+ },
11
+ "files": [
12
+ "lib"
13
+ ],
14
+ "scripts": {
15
+ "prepack": "npm run build:tsc",
16
+ "build": "npm run build:tsc",
17
+ "build:tsc": "rm -rf ./lib && tsc"
18
+ },
19
+ "author": "Bjørnar Vister Hansen <bvh@olenbetong.no>",
20
+ "license": "MIT",
21
+ "dependencies": {
22
+ "dotenv": "^16.0.1",
23
+ "rollup-plugin-visualizer": "^5.6.0",
24
+ "vite-plugin-externals": "^0.5.0"
25
+ },
26
+ "devDependencies": {
27
+ "typescript": "^4.6.4"
28
+ },
29
+ "peerDependencies": {
30
+ "express": "^4.18.1",
31
+ "vite": "^2.9.9"
32
+ },
33
+ "optionalDependencies": {
34
+ "@olenbetong/data-object": "^1.0.0-alpha.65",
35
+ "@types/express": "^4.17.13",
36
+ "@types/express-http-proxy": "^1.6.3",
37
+ "@types/tcp-port-used": "^1.0.1",
38
+ "express-http-proxy": "^1.6.3",
39
+ "open": "^8.4.0",
40
+ "tcp-port-used": "^1.0.2"
41
+ }
42
+ }