This commit is contained in:
Rizky 2024-01-23 08:29:51 +07:00
parent 38814dd5f1
commit 5f07237610
9 changed files with 538 additions and 451 deletions

2
app/web/.gitignore vendored
View File

@ -179,3 +179,5 @@ app/web/.parcel-cache
app/static
.data
.data/*
timestamp.ts

View File

@ -2,6 +2,11 @@ import { Root as ReactRoot } from "react-dom/client";
import { Root } from "./base/root";
import { w } from "./utils/types/general";
import { isLocalhost } from "./utils/ui/is-localhost";
import { version } from "../timestamp";
const state = {
updating: false,
};
export const sworkerRegister = async (react: { root: null | ReactRoot }) => {
if (navigator.serviceWorker) {
@ -16,11 +21,65 @@ export const sworkerRegister = async (react: { root: null | ReactRoot }) => {
type: "add-cache",
url: url,
});
}
},
);
}
};
cacheCurrentPage();
const curver = localStorage.getItem("prasi-version");
const swc = navigator.serviceWorker.controller;
if (version !== curver && curver && react.root && swc) {
react.root.render(
<>
<Root />
<div
className={cx(
css`
position: fixed;
bottom: 20px;
left: 0px;
right: 0px;
z-index: 999;
`,
"flex justify-center cursor-pointer",
)}
onClick={() => {
swc.postMessage({
type: "force-update",
});
if (react.root)
react.root.render(
<>
<Root />
<div
className={cx(
css`
position: fixed;
bottom: 20px;
left: 0px;
right: 0px;
z-index: 999;
`,
"flex justify-center",
)}
>
<div className="bg-blue-400 text-white px-4 py-2 rounded-full text-sm">
Updating App...
</div>
</div>
</>,
);
}}
>
<div className="bg-orange-600 text-white px-4 py-2 rounded-full text-sm select-none">
New Version Available. Click to Update
</div>
</div>
</>,
);
}
navigator.serviceWorker.addEventListener("message", (e) => {
cacheCurrentPage();
if (react.root) {
@ -42,7 +101,7 @@ export const sworkerRegister = async (react: { root: null | ReactRoot }) => {
right: 0px;
z-index: 999;
`,
"flex justify-center cursor-pointer"
"flex justify-center cursor-pointer",
)}
>
<div
@ -52,7 +111,7 @@ export const sworkerRegister = async (react: { root: null | ReactRoot }) => {
Network Failed
</div>
</div>
</>
</>,
);
}
@ -70,14 +129,14 @@ export const sworkerRegister = async (react: { root: null | ReactRoot }) => {
right: 0px;
z-index: 999;
`,
"flex justify-center"
"flex justify-center",
)}
>
<div className="bg-blue-400 text-white px-4 py-2 rounded-full text-sm">
Updating App...
</div>
</div>
</>
</>,
);
sw.unregister().then(() => {
@ -103,7 +162,7 @@ export const sworkerRegister = async (react: { root: null | ReactRoot }) => {
right: 0px;
z-index: 999;
`,
"flex justify-center cursor-pointer"
"flex justify-center cursor-pointer",
)}
>
<div
@ -114,7 +173,7 @@ export const sworkerRegister = async (react: { root: null | ReactRoot }) => {
<span className="opacity-50">{e.data.version}</span>
</div>
</div>
</>
</>,
);
}
}
@ -139,7 +198,7 @@ const registerServiceWorker = async () => {
{
type: "module",
scope: "/",
}
},
);
} catch (error) {
console.error(`Registration failed with ${error}`);
@ -163,7 +222,7 @@ export const sworkerAddCache = (base: string) => {
([k, v]: any) => ({
url: v.url,
name: k,
})
}),
);
swc.postMessage({

View File

@ -1,5 +1,7 @@
import { manifest, version } from "@parcel/service-worker";
import { manifest } from "@parcel/service-worker";
import { RadixRouter, createRouter } from "radix3";
import { version } from "../timestamp";
const g = {
router: null as null | RadixRouter<any>,
offline: false,
@ -31,14 +33,14 @@ async function activate() {
await caches.delete(key);
shouldRefresh = true;
}
})
}),
);
g.broadcast({ type: "activated", shouldRefresh, version });
}
}
addEventListener("activate", (e) =>
(e as ExtendableEvent).waitUntil(activate())
(e as ExtendableEvent).waitUntil(activate()),
);
addEventListener("fetch", async (evt) => {
@ -68,7 +70,7 @@ addEventListener("fetch", async (evt) => {
g.broadcast({ type: "offline" });
return new Response();
}
})()
})(),
);
});
addEventListener("message", async (e) => {
@ -91,5 +93,18 @@ addEventListener("message", async (e) => {
}
await activate();
break;
case "force-update":
{
const keys = await caches.keys();
await Promise.all(
keys.map(async (key) => {
if (key !== version) {
await caches.delete(key);
}
}),
);
await install();
}
break;
}
});

View File

@ -3,7 +3,7 @@ export const isLocalhost = () => {
"localhost",
"127.0.0.1",
"192.168",
"trycloudflare.com",
// "trycloudflare.com",
"ngrok",
].find((e) => location.hostname.includes(e));
};

View File

@ -1,20 +1,19 @@
import { createId } from "@paralleldrive/cuid2";
import brotliPromise from "brotli-wasm";
import { spawn } from "bun";
import { dir } from "dir";
import { fdir } from "fdir";
import { statSync } from "fs";
import {
copyAsync,
existsAsync,
listAsync,
removeAsync,
writeAsync,
} from "fs-jetpack";
import { existsAsync, listAsync, removeAsync, writeAsync } from "fs-jetpack";
const brotli = await brotliPromise;
await removeAsync(dir.path("app/web/.parcel-cache"));
await removeAsync(dir.path("app/static"));
await writeAsync(
dir.path("app/web/timestamp.ts"),
`export const version = "${createId().substring(0, 7)}";`,
);
const args = [
"node",
dir.path("node_modules/.bin/parcel"),
@ -42,18 +41,18 @@ if (!(await existsAsync(public_br))) {
files.map(async (file) => {
const br = brotli.compress(
new Uint8Array(
await Bun.file(dir.path(`app/web/public/${file}`)).arrayBuffer()
await Bun.file(dir.path(`app/web/public/${file}`)).arrayBuffer(),
),
{ quality: 11 }
{ quality: 11 },
);
if (br) {
console.log(`Compressing [public] ${file}`);
await writeAsync(
dir.path(`app/web/public-br/${file}`),
Buffer.from(br)
Buffer.from(br),
);
}
})
}),
);
}
}
@ -62,42 +61,41 @@ const static_br = dir.path("app/static-br");
await removeAsync(static_br);
const files = await listAsync(dir.path("app/static"));
if (files) {
await Promise.all(
files
.filter((file) => statSync(dir.path(`app/static/${file}`)).isFile())
.map(async (file) => {
if (!(await Bun.file(dir.path(`app/static-br/${file}`)).exists())) {
const br = brotli.compress(
new Uint8Array(
await Bun.file(dir.path(`app/static/${file}`)).arrayBuffer()
),
{ quality: 11 }
);
if (br) {
console.log(`Compressing [static] ${file}`);
await writeAsync(
dir.path(`app/static-br/${file}`),
Buffer.from(br)
);
}
}
})
);
const pub = await listAsync(dir.path("app/web/public-br"));
if (pub) {
await Promise.all(
pub.map(async (file) => {
if (await existsAsync(`app/static-br/${file}`)) {
await removeAsync(`app/static-br/${file}`);
}
await copyAsync(
dir.path(`app/web/public-br/${file}`),
dir.path(`app/static-br/${file}`)
);
})
);
}
// await Promise.all(
// files
// .filter((file) => statSync(dir.path(`app/static/${file}`)).isFile())
// .map(async (file) => {
// if (!(await Bun.file(dir.path(`app/static-br/${file}`)).exists())) {
// const br = brotli.compress(
// new Uint8Array(
// await Bun.file(dir.path(`app/static/${file}`)).arrayBuffer(),
// ),
// { quality: 11 },
// );
// if (br) {
// console.log(`Compressing [static] ${file}`);
// await writeAsync(
// dir.path(`app/static-br/${file}`),
// Buffer.from(br),
// );
// }
// }
// }),
// );
// const pub = await listAsync(dir.path("app/web/public-br"));
// if (pub) {
// await Promise.all(
// pub.map(async (file) => {
// if (await existsAsync(`app/static-br/${file}`)) {
// await removeAsync(`app/static-br/${file}`);
// }
// await copyAsync(
// dir.path(`app/web/public-br/${file}`),
// dir.path(`app/static-br/${file}`),
// );
// }),
// );
// }
}
await import("./build-site");

View File

@ -9,10 +9,18 @@ import { syncActionDefinition } from "utils/sync-def";
import { user } from "../../app/srv/ws/sync/entity/user";
import { snapshot } from "../../app/srv/ws/sync/entity/snapshot";
import { initSrv } from "../../app/srv/init";
import { createId } from "@paralleldrive/cuid2";
import { prepareApiRoutes } from "./server/api/api-scan";
import { writeAsync } from "fs-jetpack";
import { dir } from "dir";
g.status = "init";
await writeAsync(
dir.path("app/web/timestamp.ts"),
`export const version = "${createId().substring(0, 7)}";`,
);
if (!g.Y) {
g.Y = await import("yjs");
g.syncronize = (await import("y-pojo")).syncronize;

View File

@ -1,5 +1,5 @@
import { dir } from "dir";
import { inspectTreeAsync } from "fs-jetpack";
import { exists, inspectTreeAsync } from "fs-jetpack";
import { InspectTreeResult } from "fs-jetpack/types";
import { join } from "path";
import { watch } from "fs";
@ -8,9 +8,14 @@ import mime from "mime";
import { g } from "utils/global";
const web = {
brExists: null as null | boolean,
get path() {
if (g.mode === "dev") return "static";
return "static-br";
if (this.brExists === null) {
this.brExists = !!exists(dir.path("app/static-br"));
}
if (this.brExists) return "static-br";
else return "static";
},
};
const cache = {
@ -25,7 +30,7 @@ export const serveStatic = {
const list = await inspectTreeAsync(dir.path(`app/${web.path}`));
const walk = async (
list: InspectTreeResult,
parent?: InspectTreeResult[]
parent?: InspectTreeResult[],
) => {
if (list.type === "dir") {
for (const item of list.children) {

View File

@ -1,5 +1,5 @@
import { $ } from "execa";
import { existsAsync } from "fs-jetpack";
import { exists, existsAsync } from "fs-jetpack";
import { dir } from "./dir";
import { g } from "./global";
@ -8,7 +8,7 @@ export const preparePrisma = async () => {
(await existsAsync(dir.path("app/db/.env"))) ||
process.env.DATABASE_URL
) {
if (g.mode === "prod") {
if (g.mode === "prod" && exists(dir.path("app/static-br"))) {
g.log.info("Prisma: db pull & generate");
await $({ cwd: dir.path(`app/db`) })`bun prisma db pull`;
await $({ cwd: dir.path(`app/db`) })`bun prisma generate`;