файл пакета→ .shtukbase/packages/lenses-records/test/serve-fake.ts
test/serve-fake.ts
128 строк, 5.4 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- const packageRoot = new URL("../", import.meta.url);
- const kitRoot = new URL("../../kit-style/pages/design/kit-style/", import.meta.url);
- const client = Bun.file(new URL("../../layout-basic/lens.js", import.meta.url));
- const lensUrl = "/_pkg/lenses-records/lens/";
- const fakeClient = `
- window.shtuk = {
- path: new URLSearchParams(location.search).get("path"),
- async call(action, params) {
- const response = await fetch("/_api", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ do: action, ...params }),
- });
- const { result, error } = await response.json();
- if (error) throw new Error(error);
- return result;
- },
- open(path) {
- location.assign("${lensUrl}record.html?path=" + encodeURIComponent(path));
- },
- ready() {},
- on(event, callback) { window.addEventListener(event, callback); },
- };
- `;
- const collection = {
- path: "/leads.md",
- title: "Заявки",
- icon: "📋",
- properties: {
- status: {
- kind: "select",
- label: "Статус",
- options: [
- { name: "new", label: "Новая", color: "blue" },
- { name: "contacted", label: "Связались", color: "orange" },
- { name: "won", label: "Принята", color: "green" },
- { name: "closed", label: "Закрыта" },
- ],
- },
- source: {
- kind: "select",
- label: "Источник",
- options: [
- { name: "site", label: "Сайт", color: "teal" },
- { name: "referral", label: "Рекомендация", color: "purple" },
- { name: "phone", label: "Звонок", color: "gray" },
- ],
- },
- amount: { kind: "number", label: "Сумма, ₽" },
- contact: { kind: "text", label: "Контакт" },
- next: { kind: "date", label: "Следующий шаг" },
- },
- };
- const samples = [
- ["atlas", "Студия «Атлас»", "new", "site", 45000, "Анна", "2026-12-01"],
- ["bereg", "Кафе «Берег»", "contacted", "referral", 32000, "Михаил", "2026-12-02"],
- ["contour", "Ателье «Контур»", "won", "site", 64000, "Лена", "2026-12-04"],
- ["delta", "Бюро «Дельта»", "contacted", "phone", 27000, "Олег", "2026-12-07"],
- ["etude", "Школа «Этюд»", "new", "referral", null, "Ирина", "2026-12-01"],
- ["forest", "Мастерская «Лес»", "won", "phone", 22000, "Роман", null],
- ["globe", "Клуб «Глобус»", "closed", "site", 0, "Яна", null],
- ["horizon", "Студия «Горизонт»", null, "referral", null, "‹hidden›", null],
- ] as const;
- const items = samples.map(([id, title, status, source, amount, contact, next]) => ({
- path: `/requests/${id}.md`,
- title,
- meta: { type: "Record", title, status, source, amount, contact, next },
- }));
- const tree = [
- { path: collection.path, type: "Collection", title: collection.title, icon: collection.icon },
- ...items.map(({ path, title }) => ({ path, type: "Record", title, icon: null })),
- ];
- const result = (value: unknown) => Response.json({ result: value });
- const failure = (error: string) => Response.json({ error }, { status: 400 });
- async function api(request: Request) {
- const input = await request.json().catch(() => null);
- if (input?.do === "tree") return result(tree);
- if (input?.do === "records.list" && input.collection === collection.path) return result({ collection, items });
- if (input?.do === "records.read") {
- if (input.path === collection.path) {
- const { path, ...meta } = collection;
- return result({ path, meta: { ...meta, type: "Collection", items: { path: "/requests" } }, body: "" });
- }
- const item = items.find(({ path }) => path === input.path);
- if (item) return result({
- path: item.path,
- meta: item.meta,
- body: "Нужна смета на первый этап.\nОбъём уточним после звонка.\n\nПодготовить два варианта.",
- });
- }
- return failure("Unknown request");
- }
- const server = Bun.serve({
- hostname: "127.0.0.1",
- port: Number(process.env.PORT ?? 0),
- async fetch(request) {
- const url = new URL(request.url);
- const { pathname } = url;
- if (pathname === "/_api" && request.method === "POST") return api(request);
- if (pathname === "/") {
- const path = url.searchParams.get("path") ?? collection.path;
- const lens = path === collection.path ? "table" : "record";
- return Response.redirect(new URL(`${lensUrl}${lens}.html?path=${encodeURIComponent(path)}`, url));
- }
- if (pathname === "/favicon.ico") return new Response(null, { status: 204 });
- if (pathname === "/_pkg/layout-basic/lens.js") {
- if (await client.exists()) return new Response(client);
- return new Response(fakeClient, { headers: { "Content-Type": "text/javascript" } });
- }
- const prefix = pathname.startsWith(lensUrl) ? lensUrl : "/_kit/";
- if (pathname.startsWith(prefix)) {
- const relative = pathname.slice(prefix.length);
- if (relative && relative.split("/").every((part) => /^[\w-][\w.-]*$/.test(part))) {
- const root = prefix === lensUrl ? new URL("lens/", packageRoot) : kitRoot;
- const file = Bun.file(new URL(relative, root));
- if (await file.exists()) return new Response(file);
- }
- }
- return new Response("Not found", { status: 404 });
- },
- });
- console.log(new URL(lensUrl + "table.html?path=/leads.md", server.url).href);