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 app/static
.data .data
.data/* .data/*
timestamp.ts

View File

@ -2,6 +2,11 @@ import { Root as ReactRoot } from "react-dom/client";
import { Root } from "./base/root"; import { Root } from "./base/root";
import { w } from "./utils/types/general"; import { w } from "./utils/types/general";
import { isLocalhost } from "./utils/ui/is-localhost"; import { isLocalhost } from "./utils/ui/is-localhost";
import { version } from "../timestamp";
const state = {
updating: false,
};
export const sworkerRegister = async (react: { root: null | ReactRoot }) => { export const sworkerRegister = async (react: { root: null | ReactRoot }) => {
if (navigator.serviceWorker) { if (navigator.serviceWorker) {
@ -16,11 +21,65 @@ export const sworkerRegister = async (react: { root: null | ReactRoot }) => {
type: "add-cache", type: "add-cache",
url: url, url: url,
}); });
} },
); );
} }
}; };
cacheCurrentPage(); 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) => { navigator.serviceWorker.addEventListener("message", (e) => {
cacheCurrentPage(); cacheCurrentPage();
if (react.root) { if (react.root) {
@ -42,7 +101,7 @@ export const sworkerRegister = async (react: { root: null | ReactRoot }) => {
right: 0px; right: 0px;
z-index: 999; z-index: 999;
`, `,
"flex justify-center cursor-pointer" "flex justify-center cursor-pointer",
)} )}
> >
<div <div
@ -52,7 +111,7 @@ export const sworkerRegister = async (react: { root: null | ReactRoot }) => {
Network Failed Network Failed
</div> </div>
</div> </div>
</> </>,
); );
} }
@ -70,14 +129,14 @@ export const sworkerRegister = async (react: { root: null | ReactRoot }) => {
right: 0px; right: 0px;
z-index: 999; z-index: 999;
`, `,
"flex justify-center" "flex justify-center",
)} )}
> >
<div className="bg-blue-400 text-white px-4 py-2 rounded-full text-sm"> <div className="bg-blue-400 text-white px-4 py-2 rounded-full text-sm">
Updating App... Updating App...
</div> </div>
</div> </div>
</> </>,
); );
sw.unregister().then(() => { sw.unregister().then(() => {
@ -103,7 +162,7 @@ export const sworkerRegister = async (react: { root: null | ReactRoot }) => {
right: 0px; right: 0px;
z-index: 999; z-index: 999;
`, `,
"flex justify-center cursor-pointer" "flex justify-center cursor-pointer",
)} )}
> >
<div <div
@ -114,7 +173,7 @@ export const sworkerRegister = async (react: { root: null | ReactRoot }) => {
<span className="opacity-50">{e.data.version}</span> <span className="opacity-50">{e.data.version}</span>
</div> </div>
</div> </div>
</> </>,
); );
} }
} }
@ -139,7 +198,7 @@ const registerServiceWorker = async () => {
{ {
type: "module", type: "module",
scope: "/", scope: "/",
} },
); );
} catch (error) { } catch (error) {
console.error(`Registration failed with ${error}`); console.error(`Registration failed with ${error}`);
@ -163,7 +222,7 @@ export const sworkerAddCache = (base: string) => {
([k, v]: any) => ({ ([k, v]: any) => ({
url: v.url, url: v.url,
name: k, name: k,
}) }),
); );
swc.postMessage({ 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 { RadixRouter, createRouter } from "radix3";
import { version } from "../timestamp";
const g = { const g = {
router: null as null | RadixRouter<any>, router: null as null | RadixRouter<any>,
offline: false, offline: false,
@ -31,14 +33,14 @@ async function activate() {
await caches.delete(key); await caches.delete(key);
shouldRefresh = true; shouldRefresh = true;
} }
}) }),
); );
g.broadcast({ type: "activated", shouldRefresh, version }); g.broadcast({ type: "activated", shouldRefresh, version });
} }
} }
addEventListener("activate", (e) => addEventListener("activate", (e) =>
(e as ExtendableEvent).waitUntil(activate()) (e as ExtendableEvent).waitUntil(activate()),
); );
addEventListener("fetch", async (evt) => { addEventListener("fetch", async (evt) => {
@ -68,7 +70,7 @@ addEventListener("fetch", async (evt) => {
g.broadcast({ type: "offline" }); g.broadcast({ type: "offline" });
return new Response(); return new Response();
} }
})() })(),
); );
}); });
addEventListener("message", async (e) => { addEventListener("message", async (e) => {
@ -91,5 +93,18 @@ addEventListener("message", async (e) => {
} }
await activate(); await activate();
break; 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", "localhost",
"127.0.0.1", "127.0.0.1",
"192.168", "192.168",
"trycloudflare.com", // "trycloudflare.com",
"ngrok", "ngrok",
].find((e) => location.hostname.includes(e)); ].find((e) => location.hostname.includes(e));
}; };

View File

@ -1,20 +1,19 @@
import { createId } from "@paralleldrive/cuid2";
import brotliPromise from "brotli-wasm"; import brotliPromise from "brotli-wasm";
import { spawn } from "bun"; import { spawn } from "bun";
import { dir } from "dir"; import { dir } from "dir";
import { fdir } from "fdir"; import { fdir } from "fdir";
import { statSync } from "fs"; import { existsAsync, listAsync, removeAsync, writeAsync } from "fs-jetpack";
import {
copyAsync,
existsAsync,
listAsync,
removeAsync,
writeAsync,
} from "fs-jetpack";
const brotli = await brotliPromise; const brotli = await brotliPromise;
await removeAsync(dir.path("app/web/.parcel-cache")); await removeAsync(dir.path("app/web/.parcel-cache"));
await removeAsync(dir.path("app/static")); await removeAsync(dir.path("app/static"));
await writeAsync(
dir.path("app/web/timestamp.ts"),
`export const version = "${createId().substring(0, 7)}";`,
);
const args = [ const args = [
"node", "node",
dir.path("node_modules/.bin/parcel"), dir.path("node_modules/.bin/parcel"),
@ -42,18 +41,18 @@ if (!(await existsAsync(public_br))) {
files.map(async (file) => { files.map(async (file) => {
const br = brotli.compress( const br = brotli.compress(
new Uint8Array( 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) { if (br) {
console.log(`Compressing [public] ${file}`); console.log(`Compressing [public] ${file}`);
await writeAsync( await writeAsync(
dir.path(`app/web/public-br/${file}`), 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); await removeAsync(static_br);
const files = await listAsync(dir.path("app/static")); const files = await listAsync(dir.path("app/static"));
if (files) { if (files) {
await Promise.all( // await Promise.all(
files // files
.filter((file) => statSync(dir.path(`app/static/${file}`)).isFile()) // .filter((file) => statSync(dir.path(`app/static/${file}`)).isFile())
.map(async (file) => { // .map(async (file) => {
if (!(await Bun.file(dir.path(`app/static-br/${file}`)).exists())) { // if (!(await Bun.file(dir.path(`app/static-br/${file}`)).exists())) {
const br = brotli.compress( // const br = brotli.compress(
new Uint8Array( // new Uint8Array(
await Bun.file(dir.path(`app/static/${file}`)).arrayBuffer() // await Bun.file(dir.path(`app/static/${file}`)).arrayBuffer(),
), // ),
{ quality: 11 } // { quality: 11 },
); // );
if (br) { // if (br) {
console.log(`Compressing [static] ${file}`); // console.log(`Compressing [static] ${file}`);
await writeAsync( // await writeAsync(
dir.path(`app/static-br/${file}`), // dir.path(`app/static-br/${file}`),
Buffer.from(br) // Buffer.from(br),
); // );
} // }
} // }
}) // }),
); // );
// const pub = await listAsync(dir.path("app/web/public-br"));
const pub = await listAsync(dir.path("app/web/public-br")); // if (pub) {
if (pub) { // await Promise.all(
await Promise.all( // pub.map(async (file) => {
pub.map(async (file) => { // if (await existsAsync(`app/static-br/${file}`)) {
if (await existsAsync(`app/static-br/${file}`)) { // await removeAsync(`app/static-br/${file}`);
await removeAsync(`app/static-br/${file}`); // }
} // await copyAsync(
await copyAsync( // dir.path(`app/web/public-br/${file}`),
dir.path(`app/web/public-br/${file}`), // dir.path(`app/static-br/${file}`),
dir.path(`app/static-br/${file}`) // );
); // }),
}) // );
); // }
}
} }
await import("./build-site"); 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 { user } from "../../app/srv/ws/sync/entity/user";
import { snapshot } from "../../app/srv/ws/sync/entity/snapshot"; import { snapshot } from "../../app/srv/ws/sync/entity/snapshot";
import { initSrv } from "../../app/srv/init"; import { initSrv } from "../../app/srv/init";
import { createId } from "@paralleldrive/cuid2";
import { prepareApiRoutes } from "./server/api/api-scan"; import { prepareApiRoutes } from "./server/api/api-scan";
import { writeAsync } from "fs-jetpack";
import { dir } from "dir";
g.status = "init"; g.status = "init";
await writeAsync(
dir.path("app/web/timestamp.ts"),
`export const version = "${createId().substring(0, 7)}";`,
);
if (!g.Y) { if (!g.Y) {
g.Y = await import("yjs"); g.Y = await import("yjs");
g.syncronize = (await import("y-pojo")).syncronize; g.syncronize = (await import("y-pojo")).syncronize;

View File

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

View File

@ -1,5 +1,5 @@
import { $ } from "execa"; import { $ } from "execa";
import { existsAsync } from "fs-jetpack"; import { exists, existsAsync } from "fs-jetpack";
import { dir } from "./dir"; import { dir } from "./dir";
import { g } from "./global"; import { g } from "./global";
@ -8,7 +8,7 @@ export const preparePrisma = async () => {
(await existsAsync(dir.path("app/db/.env"))) || (await existsAsync(dir.path("app/db/.env"))) ||
process.env.DATABASE_URL 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"); 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 db pull`;
await $({ cwd: dir.path(`app/db`) })`bun prisma generate`; await $({ cwd: dir.path(`app/db`) })`bun prisma generate`;