@buffcore/cli 0.8.44 → 0.8.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/commands/prototype/browser.d.ts +4 -24
  3. package/dist/commands/prototype/browser.js +13 -76
  4. package/dist/commands/prototype/loaded-garbage.d.ts +10 -0
  5. package/dist/commands/prototype/loaded-garbage.js +20 -0
  6. package/dist/commands/prototype/mark-shot.d.ts +31 -0
  7. package/dist/commands/prototype/mark-shot.js +149 -0
  8. package/dist/commands/prototype/media-ready.d.ts +9 -3
  9. package/dist/commands/prototype/media-ready.js +9 -4
  10. package/dist/commands/prototype/messages.en.d.ts +1 -0
  11. package/dist/commands/prototype/messages.en.js +1 -0
  12. package/dist/commands/prototype/messages.js +1 -0
  13. package/dist/commands/prototype/scene-check.d.ts +37 -0
  14. package/dist/commands/prototype/scene-check.js +68 -0
  15. package/dist/commands/prototype/scene-look.d.ts +14 -0
  16. package/dist/commands/prototype/scene-look.js +89 -0
  17. package/dist/commands/prototype/scene-ready.d.ts +46 -0
  18. package/dist/commands/prototype/scene-ready.js +116 -0
  19. package/dist/commands/prototype/scene.d.ts +22 -1
  20. package/dist/commands/prototype/scene.js +60 -5
  21. package/dist/commands/prototype/snapshot-command.js +20 -10
  22. package/dist/commands/prototype/snapshot-inputs.js +7 -0
  23. package/dist/commands/prototype/snapshot-requests.d.ts +1 -1
  24. package/dist/commands/prototype/snapshot-requests.js +1 -1
  25. package/dist/commands/prototype/snapshot-servers.js +4 -2
  26. package/dist/commands/prototype/snapshot.d.ts +1 -0
  27. package/dist/commands/prototype/snapshot.js +1 -0
  28. package/dist/commands/ui/commands.en.d.ts +3 -0
  29. package/dist/commands/ui/commands.en.js +3 -0
  30. package/dist/commands/ui/commands.es.d.ts +3 -0
  31. package/dist/commands/ui/commands.es.js +3 -0
  32. package/dist/commands/ui/plan-brief.d.ts +13 -0
  33. package/dist/commands/ui/plan-brief.js +91 -0
  34. package/dist/commands/ui/plan-files.d.ts +1 -11
  35. package/dist/commands/ui/plan-files.js +2 -48
  36. package/dist/commands/ui/prototype-main.d.ts +5 -0
  37. package/dist/commands/ui/prototype-shot-route.d.ts +16 -0
  38. package/dist/commands/ui/prototype-shot-route.js +98 -0
  39. package/dist/commands/ui/server-core.js +2 -0
  40. package/dist/commands/ui/server.js +13 -1
  41. package/dist/commands/ui/studio-state.d.ts +5 -0
  42. package/dist/ui/page.js +109 -99
  43. package/docs/PROTOTYPE.md +3 -2
  44. package/docs/WORKBENCH.md +1 -1
  45. package/package.json +11 -11
  46. package/skills/ape-plan-change/SKILL.md +8 -0
  47. package/templates/product/apps/app/app.json +3 -0
  48. package/templates/product/plan/brief.md +29 -0
@@ -0,0 +1,91 @@
1
+ export const withoutComments = (text) => text.replace(/<!--[\s\S]*?(?:-->|$)/g, '');
2
+ // The base readers' grammar, shared by bounded plan previews as well as Brief and Roadmap.
3
+ export const answer = (text) => text
4
+ // Without a closing > the tag alternative cannot match. Keep the original code grammar.
5
+ .replace(text.includes('>') ? /`+([^`]*)`+|<[^>]*>/g : /`+([^`]*)`+/g, (_match, code) => code ?? '')
6
+ .replace(/^\s*(?:[-*+]|\d+[.)])\s*$/gm, '')
7
+ .trim();
8
+ export const plain = (text) => {
9
+ const words = answer(text);
10
+ // The original link expression cannot match without ](. This guard changes no output.
11
+ return (words.includes('](') ? words.replace(/!?\[([^\]]*)\]\((?:[^()]|\([^()]*\))*\)/g, '$1') : words).replace(/\*\*|__|`/g, '');
12
+ };
13
+ /** A newline wraps a paragraph or list item; only a new marker starts another item. */
14
+ export function briefSection(text, words = plain) {
15
+ const lines = [];
16
+ for (const raw of words(text).split(/\r?\n/)) {
17
+ const line = raw.trim();
18
+ const marker = /^(?:[-*+]|\d+[.)])\s+/;
19
+ if (marker.test(line))
20
+ lines.push(line.replace(marker, '- '));
21
+ else if (line && lines.at(-1))
22
+ lines[lines.length - 1] += ` ${line}`;
23
+ else
24
+ lines.push(line);
25
+ }
26
+ return lines.join('\n').trim();
27
+ }
28
+ /** Section spelling, fences and closing hashes follow the original Brief reader. */
29
+ export function planSections(text) {
30
+ return text
31
+ .split(/^##\s+/m)
32
+ .slice(1)
33
+ .map((part) => {
34
+ const [heading = '', ...body] = part.split(/\r?\n/);
35
+ return { heading: heading.trim(), body: body.join('\n') };
36
+ });
37
+ }
38
+ /**
39
+ * A section's short form: `> Summary: one line`, as many as the section needs (one per role). Also
40
+ * `> Resumen:`, and the word in bold.
41
+ */
42
+ const SUMMARY = /^\s*>\s*(?:\*\*|__)?(?:summary|resumen)(?:\*\*|__)?\s*:\s*(?:\*\*|__)?\s*(.*)$/i;
43
+ /**
44
+ * The template's prompts, in their own form: a line (or a list item) that is all `<Words...>`, the
45
+ * first a capital, wrapping onto the next lines with no blank line between, and never holding an
46
+ * address (`://`, `@`) or another `<` or `>`. Nothing else is taken for a tag: `age < 18`,
47
+ * `<https://...>` and `<help@...>` are the person's words, and the studio shows them as text.
48
+ */
49
+ const PROMPT = /^[ \t]*(?:(?:[-*+]|\d+[.)])[ \t]+)?<(?=[A-Z])(?![^>]*:\/\/)[^<>@\n]*(?:\n[ \t]*[^<>@\s][^<>@\n]*)*>[ \t]*$/gm;
50
+ /** The brief's words: the base grammar, without reading `<` and `>` as tags. */
51
+ const briefWords = (text) => text
52
+ .replace(/`+([^`]*)`+/g, '$1')
53
+ .replace(/!?\[([^\]]*)\]\((?:[^()]|\([^()]*\))*\)/g, '$1')
54
+ .replace(/\*\*|__/g, '')
55
+ .replace(/^\s*(?:[-*+]|\d+[.)])\s*$/gm, '')
56
+ .trim();
57
+ /**
58
+ * One section: its summary lines (template prompts and Markdown removed), and the rest as written,
59
+ * without the template's `<prompts>`, for reading.
60
+ */
61
+ function briefPart(heading, body) {
62
+ const lines = body.split(/\r?\n/);
63
+ const summary = lines.flatMap((line) => {
64
+ const words = plain(SUMMARY.exec(line)?.[1] ?? '');
65
+ return words ? [words] : [];
66
+ });
67
+ const rest = lines
68
+ .filter((line) => !SUMMARY.test(line))
69
+ .join('\n')
70
+ .replace(PROMPT, '');
71
+ const text = rest.replace(/\n{3,}/g, '\n\n').trim();
72
+ return { part: { heading, summary, text }, rest };
73
+ }
74
+ /** Section headings stay as written; the template's prompts are not answers. */
75
+ export function parseBrief(text) {
76
+ if (text === null)
77
+ return null;
78
+ const sections = {};
79
+ const parts = [];
80
+ for (const { heading, body } of planSections(withoutComments(text))) {
81
+ const { part, rest } = briefPart(heading, body);
82
+ // A section with only its summary is answered: the summary is its words.
83
+ sections[heading] = briefSection(rest, briefWords) || part.summary.join('\n');
84
+ if (part.text || part.summary.length)
85
+ parts.push(part);
86
+ }
87
+ const kindPart = parts.find((part) => /b2b|b2c|kind/i.test(part.heading));
88
+ const kindWords = kindPart ? `${kindPart.summary.join('\n')}\n${kindPart.text}` : '';
89
+ const kind = /\bb2([bc])\b/i.exec(kindWords)?.[1]?.toLowerCase();
90
+ return { sections, parts, ...(kind ? { kind: kind === 'b' ? 'b2b' : 'b2c' } : {}) };
91
+ }
@@ -1,23 +1,13 @@
1
1
  import type { PlanFacts } from '@buffcore/contracts/workbench';
2
2
  import { type Change } from '../change-file.ts';
3
+ export { answer, briefSection, parseBrief, plain, planSections, withoutComments, } from './plan-brief.ts';
3
4
  export { parseJourneys } from './plan-journeys.ts';
4
- export declare const withoutComments: (text: string) => string;
5
5
  export declare function textAt(root: string, file: string): Promise<string | null>;
6
- export declare const answer: (text: string) => string;
7
- export declare const plain: (text: string) => string;
8
- /** A newline wraps a paragraph or list item; only a new marker starts another item. */
9
- export declare function briefSection(text: string): string;
10
- /** Section spelling, fences and closing hashes follow the original Brief reader. */
11
- export declare function planSections(text: string): {
12
- heading: string;
13
- body: string;
14
- }[];
15
6
  /** The base change reader's list grammar; prose never becomes an inferred step. */
16
7
  export declare function stepItems(text: string, read?: (text: string, index: number) => string): string[];
17
8
  export declare const journeyStepItems: (text: string) => string[];
18
9
  /** Section headings stay as written; the template's prompts are not answers. */
19
10
  export declare function readBrief(root: string): Promise<PlanFacts['brief']>;
20
- export declare function parseBrief(text: string | null): PlanFacts['brief'];
21
11
  /** Only actual milestone headings and their change ids; commented examples stay unanswered. */
22
12
  export declare function readRoadmap(root: string): Promise<PlanFacts['milestones']>;
23
13
  export declare function parseRoadmap(text: string): PlanFacts['milestones'];
@@ -5,14 +5,15 @@ import { readChange } from '../change-file.js';
5
5
  import { fourAtATime, needsPrototype, readTree } from '../change-screens.js';
6
6
  import { resolveMode } from '../design/state.js';
7
7
  import { brandMatches, brandPreview } from './brand-approval.js';
8
+ import { answer, parseBrief, plain, withoutComments } from './plan-brief.js';
8
9
  import { changeDetail } from './plan-details.js';
9
10
  import { planHistory } from './plan-history.js';
10
11
  import { parseJourneys } from './plan-journeys.js';
11
12
  import { readNotThis } from './plan-not.js';
12
13
  import { structureFacts } from './plan-structure.js';
13
14
  import { stepFiles } from './save-ownership.js';
15
+ export { answer, briefSection, parseBrief, plain, planSections, withoutComments, } from './plan-brief.js';
14
16
  export { parseJourneys } from './plan-journeys.js';
15
- export const withoutComments = (text) => text.replace(/<!--[\s\S]*?(?:-->|$)/g, '');
16
17
  async function rawTextAt(root, file) {
17
18
  try {
18
19
  return await readFile(join(root, file), 'utf8');
@@ -25,42 +26,6 @@ export async function textAt(root, file) {
25
26
  const text = await rawTextAt(root, file);
26
27
  return text === null ? null : withoutComments(text);
27
28
  }
28
- // The base readers' grammar, shared by bounded plan previews as well as Brief and Roadmap.
29
- export const answer = (text) => text
30
- // Without a closing > the tag alternative cannot match. Keep the original code grammar.
31
- .replace(text.includes('>') ? /`+([^`]*)`+|<[^>]*>/g : /`+([^`]*)`+/g, (_match, code) => code ?? '')
32
- .replace(/^\s*(?:[-*+]|\d+[.)])\s*$/gm, '')
33
- .trim();
34
- export const plain = (text) => {
35
- const words = answer(text);
36
- // The original link expression cannot match without ](. This guard changes no output.
37
- return (words.includes('](') ? words.replace(/!?\[([^\]]*)\]\((?:[^()]|\([^()]*\))*\)/g, '$1') : words).replace(/\*\*|__|`/g, '');
38
- };
39
- /** A newline wraps a paragraph or list item; only a new marker starts another item. */
40
- export function briefSection(text) {
41
- const lines = [];
42
- for (const raw of plain(text).split(/\r?\n/)) {
43
- const line = raw.trim();
44
- const marker = /^(?:[-*+]|\d+[.)])\s+/;
45
- if (marker.test(line))
46
- lines.push(line.replace(marker, '- '));
47
- else if (line && lines.at(-1))
48
- lines[lines.length - 1] += ` ${line}`;
49
- else
50
- lines.push(line);
51
- }
52
- return lines.join('\n').trim();
53
- }
54
- /** Section spelling, fences and closing hashes follow the original Brief reader. */
55
- export function planSections(text) {
56
- return text
57
- .split(/^##\s+/m)
58
- .slice(1)
59
- .map((part) => {
60
- const [heading = '', ...body] = part.split(/\r?\n/);
61
- return { heading: heading.trim(), body: body.join('\n') };
62
- });
63
- }
64
29
  /** The base change reader's list grammar; prose never becomes an inferred step. */
65
30
  export function stepItems(text, read = plain) {
66
31
  const items = [];
@@ -80,17 +45,6 @@ export const journeyStepItems = (text) => plain(text)
80
45
  export async function readBrief(root) {
81
46
  return parseBrief(await rawTextAt(root, stepFiles.brief[0]));
82
47
  }
83
- export function parseBrief(text) {
84
- if (text === null)
85
- return null;
86
- const sections = {};
87
- for (const { heading, body } of planSections(withoutComments(text))) {
88
- sections[heading] = briefSection(body);
89
- }
90
- const kindSection = Object.entries(sections).find(([heading]) => /b2b|b2c|kind/i.test(heading));
91
- const kind = /\bb2([bc])\b/i.exec(kindSection?.[1] ?? '')?.[1]?.toLowerCase();
92
- return { sections, ...(kind ? { kind: kind === 'b' ? 'b2b' : 'b2c' } : {}) };
93
- }
94
48
  /** Only actual milestone headings and their change ids; commented examples stay unanswered. */
95
49
  export async function readRoadmap(root) {
96
50
  return parseRoadmap((await rawTextAt(root, stepFiles.plan[0])) ?? '');
@@ -6,6 +6,11 @@ export declare function planPrototypeOnMain(root: string, plan: PlanFacts | unde
6
6
  brief: {
7
7
  sections: Record<string, string>;
8
8
  kind?: "b2b" | "b2c" | undefined;
9
+ parts?: {
10
+ heading: string;
11
+ summary: string[];
12
+ text: string;
13
+ }[] | undefined;
9
14
  } | null;
10
15
  milestones: {
11
16
  name: string;
@@ -0,0 +1,16 @@
1
+ import { type MarkShotBody } from '@buffcore/contracts/workbench';
2
+ import { launchBrowser } from '../prototype/browser.ts';
3
+ import { shootMarks } from '../prototype/mark-shot.ts';
4
+ import type { UiRoute } from './routes.ts';
5
+ import type { UiServerOptions } from './server.ts';
6
+ export type Shooter = (url: URL, body: MarkShotBody) => Promise<Buffer>;
7
+ /** At most this many pictures are taken at once; the others wait their turn. */
8
+ export declare const SHOTS_AT_ONCE = 2;
9
+ /**
10
+ * One browser for the studio's pictures, launched once however many ask at the same moment, with
11
+ * at most SHOTS_AT_ONCE pictures taken at a time, and closed when no picture was asked for a while.
12
+ */
13
+ export declare function browserShooter(launch?: typeof launchBrowser, shot?: typeof shootMarks): Shooter & {
14
+ close: () => Promise<void>;
15
+ };
16
+ export declare function prototypeShotRoute(options: Pick<UiServerOptions, 'stack'>, shutdown?: AbortSignal, shoot?: Shooter): UiRoute;
@@ -0,0 +1,98 @@
1
+ // `POST /api/prototype/shot`: a picture of the running app at one marked screen and device, with the
2
+ // marks drawn, for the one message that sends them. The snapshot's own browser (Playwright's
3
+ // headless Chromium) opens only this studio's app address; nothing from the request names a host.
4
+ import { randomUUID } from 'node:crypto';
5
+ import { markShotBody, workbenchApi } from '@buffcore/contracts/workbench';
6
+ import { launchBrowser } from '../prototype/browser.js';
7
+ import { shootMarks, shotAddress } from '../prototype/mark-shot.js';
8
+ import { commandT as t } from './commands.js';
9
+ /** The body: a few marks of numbers; a drawing's points are the largest part. */
10
+ const BODY_LIMIT = 200_000;
11
+ /** A picture past this is not sent (a chat image's limit, in base64 characters). */
12
+ const PICTURE_LIMIT = 5 * 1024 * 1024;
13
+ /** The browser closes when no picture was asked for this long (ms). */
14
+ const IDLE = 60_000;
15
+ /** At most this many pictures are taken at once; the others wait their turn. */
16
+ export const SHOTS_AT_ONCE = 2;
17
+ /**
18
+ * One browser for the studio's pictures, launched once however many ask at the same moment, with
19
+ * at most SHOTS_AT_ONCE pictures taken at a time, and closed when no picture was asked for a while.
20
+ */
21
+ export function browserShooter(launch = launchBrowser, shot = shootMarks) {
22
+ let browser;
23
+ let timer;
24
+ let running = 0;
25
+ const waiting = [];
26
+ const close = async () => {
27
+ const open = browser;
28
+ browser = undefined;
29
+ await (await open?.catch(() => undefined))?.close();
30
+ };
31
+ const opened = async () => {
32
+ const current = browser ?? launch();
33
+ browser = current;
34
+ const ready = await current.catch((error) => {
35
+ if (browser === current)
36
+ browser = undefined;
37
+ throw error;
38
+ });
39
+ if (ready.isConnected())
40
+ return ready;
41
+ // Gone (a crash): the first to see it launches again, the others share that launch.
42
+ if (browser === current)
43
+ browser = launch();
44
+ return opened();
45
+ };
46
+ const shoot = async (url, body) => {
47
+ clearTimeout(timer);
48
+ // A finished shot hands its place straight to the next in line.
49
+ if (running < SHOTS_AT_ONCE)
50
+ running += 1;
51
+ else
52
+ await new Promise((turn) => waiting.push(turn));
53
+ try {
54
+ return await shot(await opened(), url, body);
55
+ }
56
+ finally {
57
+ const next = waiting.shift();
58
+ if (next)
59
+ next();
60
+ else
61
+ running -= 1;
62
+ if (!running) {
63
+ timer = setTimeout(() => void close(), IDLE);
64
+ timer.unref?.();
65
+ }
66
+ }
67
+ };
68
+ return Object.assign(shoot, { close });
69
+ }
70
+ export function prototypeShotRoute(options, shutdown, shoot = browserShooter()) {
71
+ const closable = shoot;
72
+ shutdown?.addEventListener('abort', () => void closable.close?.(), { once: true });
73
+ return {
74
+ method: 'POST',
75
+ path: workbenchApi.prototypeShot,
76
+ right: 'build',
77
+ origin: true,
78
+ handle: async ({ body }) => {
79
+ const request = markShotBody.safeParse(await body(BODY_LIMIT).catch(() => undefined));
80
+ if (!request.success)
81
+ return { status: 400, body: { error: t('ui.shot.invalid') } };
82
+ const stack = options.stack.info();
83
+ if (!stack.answers?.app)
84
+ return { status: 409, body: { error: t('ui.shot.notRunning') } };
85
+ try {
86
+ const png = await shoot(shotAddress(stack.app, request.data, randomUUID()), request.data);
87
+ const data = png.toString('base64');
88
+ if (data.length > PICTURE_LIMIT)
89
+ throw new Error('too large');
90
+ return { status: 200, body: { type: 'image/png', data } };
91
+ }
92
+ catch (error) {
93
+ const reason = (error instanceof Error ? error.message : String(error)).split('\n')[0];
94
+ return { status: 503, body: { error: t('ui.shot.failed', { reason }) } };
95
+ }
96
+ },
97
+ };
98
+ }
@@ -1,6 +1,7 @@
1
1
  import { workbenchApi } from '@buffcore/contracts/workbench';
2
2
  import { z } from 'zod';
3
3
  import { readableFields } from './access.js';
4
+ import { prototypeShotRoute } from './prototype-shot-route.js';
4
5
  import { prototypeSnapshotRoute } from './prototype-snapshot.js';
5
6
  import { runRoute } from './run-route.js';
6
7
  import { visibleRuns } from './snapshot-view.js';
@@ -45,6 +46,7 @@ export function coreRoutes(options, shutdown) {
45
46
  },
46
47
  runRoute(options, snapshot.record),
47
48
  snapshot,
49
+ prototypeShotRoute(options, shutdown),
48
50
  {
49
51
  method: 'POST',
50
52
  path: workbenchApi.stack,
@@ -66,10 +66,22 @@ export function createUiServer(input) {
66
66
  });
67
67
  const key = options.runner.cwd ? runnerKey(options.runner.cwd) : undefined;
68
68
  server.on('listening', () => localListener(options, server.address().port));
69
+ // A browser opens spare connections it may never send a request on. close() ends those at once
70
+ // (Node ends only the idle ones), so it never waits on them, and a server started again on the
71
+ // same port answers the tab's next load.
72
+ const unused = new Set();
73
+ server.on('connection', (socket) => {
74
+ unused.add(socket);
75
+ socket.once('close', () => unused.delete(socket));
76
+ });
77
+ server.on('request', (req) => unused.delete(req.socket));
69
78
  const close = server.close;
70
79
  server.close = function (callback) {
71
80
  shutdown.abort();
72
- return close.call(this, callback);
81
+ const closing = close.call(this, callback);
82
+ for (const socket of unused)
83
+ socket.destroy();
84
+ return closing;
73
85
  };
74
86
  if (key)
75
87
  snapshotRunners.set(key, options.runner);
@@ -171,6 +171,11 @@ export declare function studioState(root: string, options: Pick<UiServerOptions,
171
171
  brief: {
172
172
  sections: Record<string, string>;
173
173
  kind?: "b2b" | "b2c" | undefined;
174
+ parts?: {
175
+ heading: string;
176
+ summary: string[];
177
+ text: string;
178
+ }[] | undefined;
174
179
  } | null;
175
180
  milestones: {
176
181
  name: string;