Testversion im Browser und Sicherung einspielen
Die Testversion bündelt Oberfläche und Server-Logik mit PGlite (Postgres als WebAssembly). POST /api/import/stand spielt einen kompletten Stand mit allen IDs in ein leeres Programm ein; damit ziehen die Daten später auf den Server um. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AmyPfuNc4sCRfaF3oURXZz
This commit is contained in:
135
demo/main.ts
Normal file
135
demo/main.ts
Normal file
@@ -0,0 +1,135 @@
|
||||
// Testversion im Browser: dieselbe Oberfläche und Server-Logik wie Version 0.2.0, Postgres als WebAssembly.
|
||||
// Gespeichert wird im Datenspeicher des Testlinks (db-Fähigkeit), je Datensatz ein Dokument.
|
||||
import { PGlite } from "@electric-sql/pglite";
|
||||
import { starte } from "./kern.js";
|
||||
import { PARSER } from "./pool.js";
|
||||
import { TABELLEN } from "../src/server/tabellen.js";
|
||||
|
||||
type Doc = { id: string; exists: boolean; data(): Record<string, unknown> | undefined };
|
||||
type Query = { where(f: string, op: string, v: unknown): Query; orderBy(f: string): Query; limit(n: number): Query; get(): Promise<{ docs: Doc[] }> };
|
||||
type Speicher = { collection(p: string): Query; doc(p: string): { get(): Promise<Doc>; set(d: Record<string, unknown>): Promise<void>; delete(): Promise<void> } };
|
||||
type Claude = { use(name: string): Promise<any> };
|
||||
const claude = (globalThis as { claude?: Claude }).claude;
|
||||
|
||||
const leiste = document.getElementById("test-leiste")!;
|
||||
const zustand = document.getElementById("test-zustand")!;
|
||||
const melde = (text: string, art = "") => { zustand.textContent = text; zustand.className = art; };
|
||||
|
||||
async function pglite(): Promise<PGlite> {
|
||||
const adresse = (f: string) => new URL(f, document.baseURI).href;
|
||||
const modul = (f: string) => fetch(adresse(f)).then(async (r) => {
|
||||
if (!r.ok) throw new Error(`${f}: ${r.status}`);
|
||||
return WebAssembly.compile(await r.arrayBuffer());
|
||||
});
|
||||
const [wasm, initdb, daten] = await Promise.all([
|
||||
modul("pglite.wasm"),
|
||||
modul("initdb.wasm"),
|
||||
fetch(adresse("pglite.data")).then((r) => { if (!r.ok) throw new Error(`pglite.data: ${r.status}`); return r.blob(); }),
|
||||
]);
|
||||
return PGlite.create({ pgliteWasmModule: wasm, initdbWasmModule: initdb, fsBundle: daten, parsers: PARSER } as ConstructorParameters<typeof PGlite>[1] & object);
|
||||
}
|
||||
|
||||
/** Alle Dokumente einer Sammlung, seitenweise nach id */
|
||||
async function alle(s: Speicher, sammlung: string): Promise<Record<string, unknown>[]> {
|
||||
const aus: Record<string, unknown>[] = [];
|
||||
let letzte = "";
|
||||
for (;;) {
|
||||
let q = s.collection(sammlung).orderBy("id").limit(500);
|
||||
if (letzte) q = q.where("id", ">", letzte);
|
||||
const { docs } = await q.get();
|
||||
for (const d of docs) aus.push(d.data()!);
|
||||
if (docs.length < 500) return aus;
|
||||
letzte = String(aus[aus.length - 1]!.id);
|
||||
}
|
||||
}
|
||||
|
||||
/** Mehrmals versuchen, wenn der Speicher kurz nicht erreichbar ist */
|
||||
async function nochmal<T>(fn: () => Promise<T>): Promise<T> {
|
||||
try { return await fn(); } catch (e) {
|
||||
if ((e as { code?: string }).code !== "unavailable" && (e as { code?: string }).code !== "resource_exhausted") throw e;
|
||||
await new Promise((r) => setTimeout(r, 800 + Math.random() * 800));
|
||||
return fn();
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
melde("Programm wird geladen …");
|
||||
const [db, speicher, laden] = await Promise.all([pglite(), claude?.use("db") as Promise<Speicher | null> ?? null, claude?.use("downloads") ?? null]);
|
||||
const app = await starte(db);
|
||||
|
||||
// gespeicherten Stand holen und einspielen
|
||||
if (speicher) {
|
||||
melde("Deine Daten werden geladen …");
|
||||
const daten: Record<string, Record<string, unknown>[]> = {};
|
||||
for (const t of TABELLEN) daten[t.pfad] = await nochmal(() => alle(speicher, t.pfad));
|
||||
const e = await nochmal(() => speicher.doc("meta/einstellungen").get());
|
||||
if (Object.values(daten).some((z) => z.length) || e.exists) {
|
||||
const r = await app.verarbeite("POST", "/api/import/stand", { programm: "betrieb", einstellungen: e.data()?.daten, daten });
|
||||
if (!r.ok) throw new Error(`Gespeicherte Daten ließen sich nicht einspielen: ${await r.text()}`);
|
||||
}
|
||||
}
|
||||
|
||||
const exportiere = async () => (await (await app.verarbeite("GET", "/api/export")).json()) as { einstellungen: unknown; daten: Record<string, { id: string }[]> };
|
||||
// was zuletzt im Speicher steht, je Dokumentpfad als JSON
|
||||
const stand = new Map<string, string>();
|
||||
const spiegel = (x: Awaited<ReturnType<typeof exportiere>>) => {
|
||||
const m = new Map<string, string>();
|
||||
for (const [pfad, zeilen] of Object.entries(x.daten)) for (const z of zeilen) m.set(`${pfad}/${z.id}`, JSON.stringify(z));
|
||||
m.set("meta/einstellungen", JSON.stringify({ daten: x.einstellungen }));
|
||||
return m;
|
||||
};
|
||||
for (const [k, v] of spiegel(await exportiere())) stand.set(k, v);
|
||||
|
||||
let kette = Promise.resolve();
|
||||
const speichern = () => (kette = kette.then(async () => {
|
||||
if (!speicher) return;
|
||||
const neu = spiegel(await exportiere());
|
||||
const auftraege: (() => Promise<void>)[] = [];
|
||||
for (const [k, v] of neu) if (stand.get(k) !== v) auftraege.push(async () => { await nochmal(() => speicher.doc(k).set(JSON.parse(v))); stand.set(k, v); });
|
||||
for (const k of stand.keys()) if (!neu.has(k)) auftraege.push(async () => { await nochmal(() => speicher.doc(k).delete()); stand.delete(k); });
|
||||
if (!auftraege.length) return;
|
||||
melde("Speichert …");
|
||||
try {
|
||||
for (let i = 0; i < auftraege.length; i += 4) await Promise.all(auftraege.slice(i, i + 4).map((a) => a()));
|
||||
melde("Gespeichert", "ok");
|
||||
} catch (e) {
|
||||
melde(`Speichern fehlgeschlagen: ${(e as Error).message}. Bitte Seite neu laden und die letzte Änderung prüfen.`, "fehler");
|
||||
}
|
||||
}));
|
||||
|
||||
const original = window.fetch.bind(window);
|
||||
window.fetch = async (eingabe: RequestInfo | URL, init?: RequestInit) => {
|
||||
const adresse = typeof eingabe === "string" ? eingabe : eingabe instanceof URL ? eingabe.href : eingabe.url;
|
||||
if (!adresse.startsWith("/api/")) return original(eingabe, init);
|
||||
const methode = (init?.method ?? "GET").toUpperCase();
|
||||
const body = typeof init?.body === "string" ? JSON.parse(init.body) : undefined;
|
||||
const antwort = await app.verarbeite(methode, adresse, body, { "x-benutzer": "henning" });
|
||||
if (methode !== "GET" && antwort.ok) await speichern();
|
||||
return antwort;
|
||||
};
|
||||
|
||||
(globalThis as { betriebTestversion?: unknown }).betriebTestversion = {
|
||||
async sichern() {
|
||||
if (!laden) throw new Error("Speichern als Datei geht in dieser Ansicht nicht.");
|
||||
const datei = JSON.stringify(await exportiere(), null, 1);
|
||||
const tag = new Date().toISOString().slice(0, 10);
|
||||
try {
|
||||
await laden.save({ filename: `betrieb-${tag}.json`, data: datei });
|
||||
return "Datei gesichert.";
|
||||
} catch (e) {
|
||||
if ((e as { code?: string }).code === "declined") return "Abgebrochen.";
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
melde(speicher ? "Gespeichert" : "Nur ansehen: Änderungen werden hier nicht gespeichert.", speicher ? "ok" : "fehler");
|
||||
leiste.hidden = false;
|
||||
await import("../src/web/app.js");
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error(e);
|
||||
melde(`Die Testversion ließ sich nicht starten: ${(e as Error).message}`, "fehler");
|
||||
leiste.hidden = false;
|
||||
});
|
||||
Reference in New Issue
Block a user