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:
79
demo/fastify.ts
Normal file
79
demo/fastify.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
// Ersatz für Fastify in der Browser-Testversion: dieselben Routen, aber ohne Netzwerk.
|
||||
// Unterstützt nur das, was src/server/app.ts benutzt.
|
||||
|
||||
type Handler = (req: Anfrage, reply: Antwort) => unknown;
|
||||
|
||||
export interface Anfrage {
|
||||
method: string;
|
||||
url: string;
|
||||
params: Record<string, string>;
|
||||
query: Record<string, string>;
|
||||
body: unknown;
|
||||
headers: Record<string, string>;
|
||||
}
|
||||
|
||||
export class Antwort {
|
||||
statusCode = 200;
|
||||
kopf: Record<string, string> = {};
|
||||
inhalt: unknown = undefined;
|
||||
gesendet = false;
|
||||
status(code: number) { this.statusCode = code; return this; }
|
||||
code(code: number) { return this.status(code); }
|
||||
header(name: string, wert: string) { this.kopf[name.toLowerCase()] = wert; return this; }
|
||||
send(inhalt?: unknown) { this.inhalt = inhalt; this.gesendet = true; return this; }
|
||||
sendFile() { return this.status(404).send({ fehler: "Nicht gefunden" }); }
|
||||
}
|
||||
|
||||
interface Route { methode: string; teile: string[]; handler: Handler }
|
||||
|
||||
export default function Fastify(_o?: unknown) {
|
||||
const routen: Route[] = [];
|
||||
let fehlerHandler: (err: unknown, req: Anfrage, reply: Antwort) => unknown = (err, _r, reply) =>
|
||||
reply.status(500).send({ fehler: (err as Error).message });
|
||||
const neu = (methode: string) => (pfad: string, handler: Handler) => { routen.push({ methode, teile: pfad.split("/"), handler }); };
|
||||
|
||||
const app = {
|
||||
log: { error: console.error, warn: console.warn, info: () => {} },
|
||||
get: neu("GET"), post: neu("POST"), put: neu("PUT"), patch: neu("PATCH"), delete: neu("DELETE"),
|
||||
setErrorHandler(fn: typeof fehlerHandler) { fehlerHandler = fn; },
|
||||
setNotFoundHandler() {},
|
||||
async register() {},
|
||||
async close() {},
|
||||
|
||||
/** Bearbeitet eine Anfrage wie der Server und liefert eine fetch-Antwort. */
|
||||
async verarbeite(methode: string, adresse: string, body: unknown, headers: Record<string, string> = {}): Promise<Response> {
|
||||
const u = new URL(adresse, "http://demo");
|
||||
const teile = u.pathname.split("/").map(decodeURIComponent);
|
||||
const reply = new Antwort();
|
||||
let route: Route | undefined;
|
||||
const params: Record<string, string> = {};
|
||||
for (const r of routen) {
|
||||
if (r.methode !== methode || r.teile.length !== teile.length) continue;
|
||||
if (r.teile.every((t, i) => t.startsWith(":") || t === teile[i])) {
|
||||
route = r;
|
||||
r.teile.forEach((t, i) => { if (t.startsWith(":")) params[t.slice(1)] = teile[i]!; });
|
||||
break;
|
||||
}
|
||||
}
|
||||
const req: Anfrage = { method: methode, url: u.pathname + u.search, params, query: Object.fromEntries(u.searchParams), body, headers };
|
||||
if (!route) reply.status(404).send({ fehler: "Nicht gefunden" });
|
||||
else {
|
||||
try {
|
||||
const erg = await route.handler(req, reply);
|
||||
if (!reply.gesendet && erg !== reply) reply.send(erg);
|
||||
} catch (err) {
|
||||
await fehlerHandler(err, req, reply);
|
||||
}
|
||||
}
|
||||
const leer = reply.inhalt === undefined || reply.statusCode === 204;
|
||||
const text = typeof reply.inhalt === "string";
|
||||
return new Response(leer ? null : text ? (reply.inhalt as string) : JSON.stringify(reply.inhalt), {
|
||||
status: reply.statusCode,
|
||||
headers: { "content-type": text ? "text/plain; charset=utf-8" : "application/json", ...reply.kopf },
|
||||
});
|
||||
},
|
||||
};
|
||||
return app;
|
||||
}
|
||||
export type FastifyInstance = ReturnType<typeof Fastify>;
|
||||
export type FastifyRequest = Anfrage;
|
||||
18
demo/index.html
Normal file
18
demo/index.html
Normal file
@@ -0,0 +1,18 @@
|
||||
<title>Betrieb Testversion</title>
|
||||
<style>/*STYLES*/
|
||||
#test-leiste { position: fixed; z-index: 50; right: calc(12px + env(safe-area-inset-right, 0px)); bottom: calc(12px + env(safe-area-inset-bottom, 0px));
|
||||
max-width: min(420px, calc(100vw - 24px)); background: var(--fl); color: var(--text); border: 1px solid var(--linie); border-radius: 10px;
|
||||
padding: 7px 12px; font-size: 13px; box-shadow: 0 2px 10px rgb(0 0 0 / 0.12); display: flex; gap: 8px; align-items: baseline; }
|
||||
#test-leiste b { color: var(--holz); white-space: nowrap; }
|
||||
#test-zustand.ok { color: var(--leise); }
|
||||
#test-zustand.fehler { color: var(--warn); }
|
||||
</style>
|
||||
<aside id="seitenleiste">
|
||||
<div id="marke"><img src="/*LOGO*/" alt="Holzbau Schaarschmidt"></div>
|
||||
<nav id="reiter"></nav>
|
||||
<span id="version"></span>
|
||||
</aside>
|
||||
<main id="inhalt"></main>
|
||||
<div id="dialog-huelle" hidden></div>
|
||||
<div id="test-leiste" role="status"><b>Testversion</b><span id="test-zustand">Programm wird geladen …</span></div>
|
||||
<script type="module">/*APP*/</script>
|
||||
32
demo/kern.ts
Normal file
32
demo/kern.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
// Startet die echte Server-Logik (src/server/app.ts) auf PGlite, ohne Netzwerk.
|
||||
import type { PGlite } from "@electric-sql/pglite";
|
||||
import { baueApp } from "../src/server/app.js";
|
||||
import { alsPool } from "./pool.js";
|
||||
import m001 from "../src/server/migrations/001_grundlage.sql";
|
||||
import m002 from "../src/server/migrations/002_v70_uebernahme.sql";
|
||||
import m003 from "../src/server/migrations/003_vorgangsnummer.sql";
|
||||
import m004 from "../src/server/migrations/004_besetzung.sql";
|
||||
|
||||
const MIGRATIONEN: [string, string][] = [
|
||||
["001_grundlage.sql", m001], ["002_v70_uebernahme.sql", m002], ["003_vorgangsnummer.sql", m003], ["004_besetzung.sql", m004],
|
||||
];
|
||||
|
||||
export async function starte(db: PGlite, v70?: unknown) {
|
||||
await db.exec("create table if not exists schema_version (name text primary key, eingespielt_am timestamptz not null default now())");
|
||||
const da = new Set((await db.query<{ name: string }>("select name from schema_version")).rows.map((r) => r.name));
|
||||
for (const [name, sql] of MIGRATIONEN) {
|
||||
if (da.has(name)) continue;
|
||||
await db.transaction(async (t) => {
|
||||
await t.exec(sql);
|
||||
await t.query("insert into schema_version (name) values ($1)", [name]);
|
||||
});
|
||||
}
|
||||
const app = (await baueApp({ pool: alsPool(db) as any })) as unknown as {
|
||||
verarbeite(methode: string, adresse: string, body?: unknown, headers?: Record<string, string>): Promise<Response>;
|
||||
};
|
||||
if (v70 && (await db.query("select 1 from projekt limit 1")).rows.length === 0) {
|
||||
const r = await app.verarbeite("POST", "/api/import/v70", v70);
|
||||
if (!r.ok) throw new Error(`Übernahme der V70-Daten: ${await r.text()}`);
|
||||
}
|
||||
return app;
|
||||
}
|
||||
2
demo/leer.ts
Normal file
2
demo/leer.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
// Leerer Ersatz für Node-Module, die PGlite nur unter Node benutzt
|
||||
export default {};
|
||||
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;
|
||||
});
|
||||
15
demo/node.ts
Normal file
15
demo/node.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
// Was src/server/app.ts aus Node braucht, für den Browser nachgebaut.
|
||||
export const existsSync = () => false;
|
||||
export const fileURLToPath = (u: string) => u;
|
||||
export default { join: (...t: string[]) => t.join("/"), dirname: (p: string) => p };
|
||||
|
||||
export function randomBytes(n: number) {
|
||||
const b = crypto.getRandomValues(new Uint8Array(n));
|
||||
return { toString: () => btoa(String.fromCharCode(...b)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") };
|
||||
}
|
||||
|
||||
export function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {
|
||||
return a.length === b.length && a.every((x, i) => x === b[i]);
|
||||
}
|
||||
|
||||
(globalThis as any).Buffer ??= { from: (s: string) => new TextEncoder().encode(s) };
|
||||
2
demo/pg.ts
Normal file
2
demo/pg.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
// Ersatz für das Paket pg: die Typumwandlung macht hier die PGlite-Anbindung (pool.ts).
|
||||
export default { types: { setTypeParser() {} }, Pool: class {} };
|
||||
32
demo/pool.ts
Normal file
32
demo/pool.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
// Pool-Schnittstelle von pg auf PGlite (Postgres als WebAssembly im Browser).
|
||||
import { PGlite, types } from "@electric-sql/pglite";
|
||||
|
||||
export const PARSER = {
|
||||
[types.DATE]: (v: string) => v,
|
||||
[types.INT8]: (v: string) => Number(v),
|
||||
[types.NUMERIC]: (v: string) => Number(v),
|
||||
};
|
||||
|
||||
export function alsPool(db: PGlite) {
|
||||
const query = async (sql: string, params?: unknown[]) => {
|
||||
if (!params?.length && /;\s*\S/.test(sql.trim().replace(/;\s*$/, ""))) {
|
||||
await db.exec(sql);
|
||||
return { rows: [], rowCount: 0 };
|
||||
}
|
||||
const r = await db.query(sql, params ?? []);
|
||||
return { rows: r.rows as any[], rowCount: r.affectedRows ?? r.rows.length };
|
||||
};
|
||||
// PGlite hat nur eine Verbindung: Transaktionen laufen nacheinander
|
||||
let kette: Promise<void> = Promise.resolve();
|
||||
return {
|
||||
query,
|
||||
async connect() {
|
||||
let frei!: () => void;
|
||||
const vorher = kette;
|
||||
kette = new Promise<void>((r) => (frei = r));
|
||||
await vorher;
|
||||
return { query, release: () => frei() };
|
||||
},
|
||||
async end() {},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user