ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/chat/test/host.ts

test/host.ts

60 líneas, 4.0 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // A wrapper host for trying the chat lens inside layout-basic's shell (contract §5), modelled
  2. // on layout-basic/test/fake-host.ts. The shell has no panel slot yet, so the chat is offered
  3. // as a lens for pages and collections. space.tools comes from apps/shtuk/src/core/tools.ts.
  4. // bun apps/standard/packages/chat/test/host.ts [port]
  5. import { existsSync } from 'node:fs';
  6. import { join, resolve } from 'node:path';
  7. import { toolAction, tools } from '../../../../shtuk/src/core/tools.ts';
  8. const packages = resolve(import.meta.dir, '../..');
  9. const kit = join(packages, 'kit-style/pages/design/kit-style');
  10. type Rec = { meta: Record<string, unknown>; body: string };
  11. const files = new Map<string, Rec>();
  12. files.set('/index.md', { meta: { type: 'Page', title: 'Главная', icon: '🏠' }, body: 'Добро пожаловать.' });
  13. files.set('/leads.md', { meta: { type: 'Collection', title: 'Заявки', icon: '📥', writeTo: '/leads', properties: {
  14. status: { kind: 'select', options: [{ name: 'new' }, { name: 'won' }] } } }, body: '' });
  15. ['Acme', 'Ромашка', 'Север'].forEach((n, i) => files.set(`/leads/lead-${i + 1}.md`, { meta: { title: n, status: 'new' }, body: `Заявка от ${n}.` }));
  16. const lenses = [
  17. { id: 'chat', package: 'chat', file: 'lens/chat.html', title: 'Чат', for: 'Record' },
  18. { id: 'chat', package: 'chat', file: 'lens/chat.html', title: 'Чат', for: 'Collection' },
  19. { id: 'table', package: 'lenses-records', file: 'lens/table.html', title: 'Таблица', for: 'Collection' },
  20. ];
  21. const title = (p: string, r: Rec) => String(r.meta.title ?? p.split('/').pop()!.replace(/\.md$/, ''));
  22. export const calls: string[] = [];
  23. const api: Record<string, (p: any) => unknown> = {
  24. 'space.info': () => ({ name: 'Демо', layout: { package: 'layout-basic', file: 'shell.html' }, lenses }),
  25. 'space.tools': () => tools.map((t) => ({ ...t, action: toolAction(t.name) })),
  26. tree: () => [...files.keys()].sort().map((path) => ({ path, type: String(files.get(path)!.meta.type ?? 'Record'), title: title(path, files.get(path)!), icon: files.get(path)!.meta.icon ?? null })),
  27. 'records.list': ({ collection }) => {
  28. const c = files.get(collection);
  29. if (!c) throw new Error('no collection ' + collection);
  30. const dir = String(c.meta.writeTo) + '/';
  31. return { collection: { path: collection, title: title(collection, c), properties: c.meta.properties },
  32. items: [...files.keys()].sort().filter((p) => p.startsWith(dir)).map((p) => ({ path: p, meta: files.get(p)!.meta, title: title(p, files.get(p)!) })) };
  33. },
  34. 'records.read': ({ path }) => { const r = files.get(path); if (!r) throw new Error('not found ' + path); return { path, ...r }; },
  35. 'records.write': ({ path, meta, body }) => { const r = files.get(path) ?? { meta: {}, body: '' }; files.set(path, { meta: { ...r.meta, ...(meta ?? {}) }, body: body ?? r.body }); return { path }; },
  36. };
  37. const file = (p: string) => existsSync(p) ? new Response(Bun.file(p), { headers: { 'cache-control': 'no-cache' } }) : new Response('not found', { status: 404 });
  38. const port = Number(process.argv[2] ?? 4331);
  39. Bun.serve({
  40. port,
  41. async fetch(req) {
  42. const url = new URL(req.url);
  43. const p = decodeURIComponent(url.pathname);
  44. if (p.includes('..')) return new Response('bad', { status: 400 });
  45. if (p === '/') return file(join(packages, 'layout-basic/shell.html'));
  46. if (p === '/_api' && req.method === 'POST') {
  47. const { do: action, ...params } = await req.json();
  48. calls.push(action);
  49. if (process.env.LOG) console.log('api', action, JSON.stringify(params));
  50. const fn = api[action];
  51. if (!fn) return Response.json({ error: 'unknown action ' + action });
  52. try { return Response.json({ result: fn(params) }); } catch (e) { return Response.json({ error: (e as Error).message }); }
  53. }
  54. if (p.startsWith('/_kit/')) return file(join(kit, p.slice(6)));
  55. if (p.startsWith('/_pkg/')) return file(join(packages, p.slice(6)));
  56. return new Response('not found', { status: 404 });
  57. },
  58. });
  59. console.log(`chat host: http://127.0.0.1:${port}/?path=/index.md`);