ShtukbaseStandard
package file→ .shtukbase/packages/layout-studio/test/fake-host.ts

test/fake-host.ts

119 lines, 6.5 KB.

The file as it is in the package. Some comments in it may not be in English yet.

  1. // A fake host for layout-studio: serves contract §5 with an in-memory /_api.
  2. // bun apps/standard/packages/layout-studio/test/fake-host.ts [port] (CACHE=long: long cache for /_pkg and /_kit)
  3. import { existsSync } from 'node:fs';
  4. import { join, resolve } from 'node:path';
  5. const here = import.meta.dir;
  6. const pkg = resolve(here, '..');
  7. const packages = resolve(pkg, '..');
  8. const kit = join(packages, 'kit-style/pages/design/kit-style');
  9. const recordsPkg = join(packages, 'lenses-records');
  10. const basicPkg = join(packages, 'layout-basic');
  11. const longCache = process.env.CACHE === 'long';
  12. const useRealLenses = existsSync(join(recordsPkg, 'lens/table.html'));
  13. type Rec = { meta: Record<string, unknown>; body: string };
  14. const files = new Map<string, Rec>();
  15. files.set('/index.md', { meta: { type: 'Page', title: 'Главная', icon: '🏠' }, body: 'Добро пожаловать.' });
  16. files.set('/notes.md', { meta: { type: 'Page', title: 'Заметки', icon: '📝' }, body: 'Заметки.' });
  17. files.set('/notes/ideas.md', { meta: { type: 'Page', title: 'Идеи', icon: '💡' }, body: 'Идеи.' });
  18. files.set('/leads.md', {
  19. meta: {
  20. type: 'Collection', title: 'Заявки', icon: '📥', items: { mode: 'path', path: '/leads' }, writeTo: '/leads',
  21. properties: {
  22. status: { kind: 'select', label: 'Статус', options: [
  23. { name: 'new', label: 'Новая', color: 'blue' }, { name: 'talk', label: 'В работе', color: 'orange' },
  24. { name: 'won', label: 'Сделка', color: 'green' }, { name: 'lost', label: 'Отказ', color: 'gray' }] },
  25. source: { kind: 'select', label: 'Источник', options: [
  26. { name: 'site', label: 'Сайт', color: 'purple' }, { name: 'call', label: 'Звонок', color: 'teal' }] },
  27. amount: { kind: 'number', label: 'Сумма' },
  28. },
  29. },
  30. body: '',
  31. });
  32. const names = ['Acme', 'Ромашка', 'Север', 'Луч', 'Вектор', 'Орбита', 'Гранит', 'Прибой'];
  33. const statuses = ['new', 'talk', 'won', 'lost'];
  34. names.forEach((n, i) => files.set(`/leads/lead-${i + 1}.md`, {
  35. meta: { title: n, status: statuses[i % 4], source: i % 2 ? 'call' : 'site', amount: (i + 1) * 1000 },
  36. body: `Заявка от ${n}.`,
  37. }));
  38. const lenses = useRealLenses
  39. ? [
  40. { id: 'table', package: 'lenses-records', file: 'lens/table.html', title: 'Таблица', for: 'Collection' },
  41. { id: 'board', package: 'lenses-records', file: 'lens/board.html', title: 'Доска', for: 'Collection' },
  42. { id: 'record', package: 'lenses-records', file: 'lens/record.html', title: 'Запись', for: 'Record' },
  43. { id: 'props', package: 'studio-demo', file: 'props.html', title: 'Свойства', for: 'Record', slot: 'panel' },
  44. ]
  45. : [
  46. { id: 'table', package: 'demo', file: 'table.html', title: 'Таблица', for: 'Collection' },
  47. { id: 'board', package: 'demo', file: 'board.html', title: 'Доска', for: 'Collection' },
  48. { id: 'record', package: 'demo', file: 'record.html', title: 'Запись', for: 'Record' },
  49. { id: 'props', package: 'studio-demo', file: 'props.html', title: 'Свойства', for: 'Record', slot: 'panel' },
  50. ];
  51. function title(path: string, r: Rec) { return String(r.meta.title ?? path.split('/').pop()!.replace(/\.md$/, '')); }
  52. const api: Record<string, (p: any) => unknown> = {
  53. 'space.info': () => ({ name: 'Демо-пространство', layout: { package: 'layout-studio', file: 'shell.html' }, lenses,
  54. contributions: [
  55. ...lenses.map((l) => ({ package: l.package, lens: l.id, file: l.file, title: l.title, for: l.for, slot: l.slot ?? 'main' })),
  56. { package: 'studio-demo', lens: 'outline', file: 'props.html', title: 'Структура', slot: 'panel' },
  57. ] }),
  58. tree: () => [...files.keys()].sort().map((path) => {
  59. const r = files.get(path)!;
  60. return { path, type: String(r.meta.type ?? 'Record'), title: title(path, r), icon: r.meta.icon ?? null };
  61. }),
  62. 'records.list': ({ collection }) => {
  63. const c = files.get(collection);
  64. if (!c) throw new Error('no collection ' + collection);
  65. const dir = collection.replace(/\.md$/, '/');
  66. return {
  67. collection: { path: collection, title: title(collection, c), icon: c.meta.icon, properties: c.meta.properties },
  68. items: [...files.keys()].sort().filter((p) => p.startsWith(dir)).map((p) => ({ path: p, meta: files.get(p)!.meta, title: title(p, files.get(p)!) })),
  69. };
  70. },
  71. 'records.read': ({ path }) => {
  72. const r = files.get(path);
  73. if (!r) throw new Error('not found ' + path);
  74. return { path, meta: r.meta, body: r.body };
  75. },
  76. 'records.write': ({ path, meta, body }) => {
  77. const r = files.get(path) ?? { meta: {}, body: '' };
  78. files.set(path, { meta: { ...r.meta, ...(meta ?? {}) }, body: body ?? r.body });
  79. return { path };
  80. },
  81. };
  82. function file(path: string, cache = false) {
  83. if (!existsSync(path)) return new Response('not found', { status: 404 });
  84. const cc = cache && longCache ? 'public, max-age=31536000, immutable' : 'no-cache';
  85. return new Response(Bun.file(path), { headers: { 'cache-control': cc } });
  86. }
  87. const port = Number(process.argv[2] ?? 4321);
  88. Bun.serve({
  89. port,
  90. async fetch(req) {
  91. const url = new URL(req.url);
  92. const p = decodeURIComponent(url.pathname);
  93. if (process.env.LOG) console.log(req.method, url.pathname + url.search, req.headers.get("sec-fetch-site") ?? "");
  94. if (p.includes('..')) return new Response('bad', { status: 400 });
  95. if (p === '/') return file(join(pkg, 'shell.html'));
  96. if (p === '/_api' && req.method === 'POST') {
  97. const { do: action, ...params } = await req.json();
  98. const fn = api[action];
  99. if (!fn) return Response.json({ error: 'unknown action ' + action });
  100. await Bun.sleep(5);
  101. try { return Response.json({ result: fn(params) }); } catch (e) { return Response.json({ error: String((e as Error).message) }); }
  102. }
  103. if (p.startsWith('/_kit/')) return file(join(kit, p.slice(6)), true);
  104. if (p.startsWith('/_pkg/layout-studio/')) return file(join(pkg, p.slice(20)), true);
  105. if (p.startsWith('/_pkg/layout-basic/')) return file(join(basicPkg, p.slice(19)), true);
  106. if (p.startsWith('/_pkg/lenses-records/')) return file(join(recordsPkg, p.slice(21)), true);
  107. if (p.startsWith('/_pkg/studio-demo/')) return file(join(here, 'props-lens.html'), true);
  108. if (p.startsWith('/_pkg/demo/')) return file(join(basicPkg, 'test/demo-lens.html'), true);
  109. return new Response('not found', { status: 404 });
  110. },
  111. });
  112. console.log(`fake host: http://127.0.0.1:${port}/ (lenses: ${useRealLenses ? 'lenses-records' : 'demo'})`);