@logictan/dsh-stitch-designer 1.0.0 → 2.0.1

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.
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The Stitch design conventions, as the plugin announces them.
3
+ *
4
+ * These are **prose**, and deliberately so. "Did you use TailwindCSS?" and "is
5
+ * this pixel-perfect?" have no computable predicate, so a validator for them
6
+ * would be a lie — it would either pass everything or block correct work. They
7
+ * are delivered the way this repository delivers every other non-computable
8
+ * rule: as an announcement in the system prompt, registered by the plugin that
9
+ * owns the subject, so the model reads it in every session without anyone
10
+ * having to remember to ask.
11
+ *
12
+ * The one convention with a computable predicate — one code project owns one
13
+ * Stitch project — is **not** here. It is enforced in `src/conventions.js`,
14
+ * because a rule the model can silently break is not a rule. This file is only
15
+ * the text.
16
+ *
17
+ * The rules fall in two groups, and the split is the point: rules 4-8 govern
18
+ * how a screen is commissioned (what to ask Stitch for), rules 1-3 govern how
19
+ * the result is implemented. A brief that over-specifies produces a screen that
20
+ * is no better than hand-written code, and a screen containing what cannot be
21
+ * built is a defect discovered only at implementation time — both are cheaper
22
+ * to prevent when the model is told before it writes the prompt.
23
+ *
24
+ * @module @logictan/dsh-stitch-designer/guidance
25
+ */
26
+
27
+ /** Section name in the system prompt; unique across plugins. */
28
+ export const SECTION_NAME = 'plugin:dsh-stitch-designer';
29
+
30
+ /** Order within the tool-guidance band. */
31
+ export const SECTION_ORDER = 150;
32
+
33
+ /**
34
+ * What the model is told about Stitch, and about implementing its designs.
35
+ *
36
+ * Written for a reader who has just been handed a design and is about to write
37
+ * code from it — the moment these rules matter and the only moment they can be
38
+ * acted on.
39
+ */
40
+ export const STITCH_GUIDANCE = [
41
+ '本机已安装 dsh-stitch-designer 插件(Google Stitch AI 界面设计):提供 15 个 `mcp__stitch__*` 工具(建/删/列项目、列/取界面、生成界面、改界面、生成变体、设计系统与设计稿上传)。',
42
+ '',
43
+ '用 Stitch 设计稿实现界面时,遵守以下规范:',
44
+ '1. 一个代码项目只对应一个 Stitch 项目,对应关系记录在该代码项目根目录的 `.stitch.json`。继续沿用已记录的那个项目,不要为同一个代码项目再调 `create_project`——插件会直接报错拒绝,并告知已绑定的项目 id。记录指向的 Stitch 项目已被删除时,插件会自动清掉记录,可重新创建。',
45
+ '2. 实现时使用 TailwindCSS,与 Stitch 生成设计稿的方式保持一致;除非该项目已有架构无法兼容 TailwindCSS,此时先说明是哪一处不兼容、为什么不兼容,再动手。',
46
+ '3. 先导出 Stitch 的设计稿 HTML,照着它实现,尽可能做到像素级还原。设计稿 HTML 落在 `<项目>/docs/design/<screenId>.html`,应提交到版本库。凡实现需要与设计稿不一致的地方,先问用户并给出理由,不要自行偏离。',
47
+ '',
48
+ '下单给 Stitch 时,遵守以下规范:',
49
+ '4. 只告诉它需要什么样的视觉效果、需要展示什么内容,不做其他限制,尽可能让它自我发挥。把布局、间距、配色写死成一份详细规格,等于让它照着抄,产出的稿子不会比你自己写的更好。',
50
+ '5. 设计稿最终要被像素级还原,所以稿子里不得出现无法实现的功能和元素。写提示词时就假定它会被逐像素实现:不要许愿一个做不到的交互、一个实现不了的效果,或一份拿不到的数据。',
51
+ '6. 遵循项目既有的设计语言。本仓库的界面统一按 `@logictan/dsh-macos-theme` 的设计语言出稿;没有另行指定时,就以它为准,不要另起一套视觉体系。',
52
+ '7. 尽可能复用已有组件。出稿前先看项目里已经有什么(宿主组件、共享组件层),让稿子由这些组件拼出来,而不是重画一套长得像的。',
53
+ '8. 每份设计稿都要同时给出暗色版本。暗色不是把亮色反相,而是同一套设计语言在暗色下的取值:颜色、描边、层级都要按暗色重新给。实现时两边共用同一套 token,暗色不另写一份。',
54
+ ].join('\n');
package/lib/index.js CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Google Stitch (AI UI generation) as a first-class part of the harness. It
5
5
  * registers the same 15 `mcp__stitch__*` tools the retired `mcp-stitch` patch
6
- * row used to provide, and serves the preview panel's HTTP API.
6
+ * row used to provide.
7
7
  *
8
8
  * Three design choices are load-bearing, and each replaces something that was
9
9
  * tried and failed elsewhere in this repository:
@@ -13,8 +13,7 @@
13
13
  * 15 input schemas and 13 of 15 output schemas are rejected by
14
14
  * `assertSupportedJsonSchema` — so the bridge has to decide per field what
15
15
  * to keep. Owning the transport is also what keeps the API key out of a
16
- * patch row (see below) and what lets the tools and the panel share one
17
- * client.
16
+ * patch row (see below).
18
17
  *
19
18
  * - **The API key is a credential, not configuration.** It lives in
20
19
  * `$DSH_HOME/.credentials.yaml` under the ref `STITCH_API_KEY`, resolved
@@ -26,22 +25,21 @@
26
25
  * section exports refs from the credentials file), and it never appears in a
27
26
  * patch row.
28
27
  *
29
- * - **Each half waits for the services it needs; `credentials` is read per
30
- * call.** `ctx.get(name)` returns only a service whose providing fiber is
31
- * already ACTIVE, and providers come up asynchronously — `webServer` waits on
32
- * `webStartup`, so at `apply` time it is still `undefined` even though its
33
- * row precedes this one in the patch list. Reading it once in `apply`
34
- * silently dropped the entire panel API. The registrations therefore nest
35
- * under `ctx.inject` so each waits for its own providers; the tools half
36
- * additionally waits for `credentials`, because its first `tools/list` needs
37
- * the key and nothing re-fires that fetch at boot (the initial attempt ran
38
- * before the credential store was live and failed as "key not configured").
39
- * The key itself is read at call time, so setting it later still works.
28
+ * - **The tools half waits for the services it needs.** `ctx.get(name)`
29
+ * returns only a service whose providing fiber is already ACTIVE, and
30
+ * providers come up asynchronously — so a service read once in `apply` can
31
+ * silently be `undefined`. The registration therefore nests under
32
+ * `ctx.inject` so it waits for its own providers; it waits for `credentials`
33
+ * in particular, because its first `tools/list` needs the key and nothing
34
+ * re-fires that fetch at boot (the initial attempt ran before the credential
35
+ * store was live and failed as "key not configured"). The key itself is read
36
+ * at call time, so setting it later still works.
40
37
  *
41
38
  * @module @logictan/dsh-stitch-designer
42
39
  */
43
- import { makeRoutes } from './routes.js';
44
40
  import { createStitchClient } from './stitch.js';
41
+ import { createInvoker } from './conventions.js';
42
+ import { SECTION_NAME, SECTION_ORDER, STITCH_GUIDANCE } from './guidance.js';
45
43
  import { createToolDefinition, publicToolName } from './tools.js';
46
44
 
47
45
  /** Plugin row id; must equal the row id in `cordis.patch.yml`. */
@@ -60,7 +58,7 @@ export const API_KEY_REF = 'STITCH_API_KEY';
60
58
  export const SERVER_NAME = 'stitch';
61
59
 
62
60
  /**
63
- * Register the Stitch tools and the panel API.
61
+ * Register the Stitch tools and announce the design conventions.
64
62
  *
65
63
  * @param ctx - the plugin context.
66
64
  */
@@ -83,6 +81,13 @@ export function apply(ctx) {
83
81
 
84
82
  const stitch = createStitchClient({ resolveApiKey });
85
83
 
84
+ // One code project ↔ one Stitch project is enforced here rather than merely
85
+ // announced: this wrapper is the only seam that sees which code project a
86
+ // call belongs to, and therefore the only one that can refuse a second
87
+ // `create_project`. The other two conventions are prose and live in the
88
+ // system-prompt section below. See `src/conventions.js`.
89
+ const invoke = createInvoker({ stitch });
90
+
86
91
  // ---------------------------------------------------------------- tools
87
92
  // The upstream descriptors ARE the tool contract — names, descriptions and
88
93
  // input schemas all come from Stitch — so registration follows a successful
@@ -109,7 +114,7 @@ export function apply(ctx) {
109
114
  description: tool.description ?? '',
110
115
  inputSchema: tool.inputSchema,
111
116
  outputSchema: tool.outputSchema,
112
- call: (args, exec) => stitch.callTool(tool.name, args, exec),
117
+ call: (args, exec) => invoke(tool.name, args, exec),
113
118
  }),
114
119
  );
115
120
  for (const dispose of disposers) dispose();
@@ -139,15 +144,24 @@ export function apply(ctx) {
139
144
  }, 'stitch-designer: Stitch tools');
140
145
  });
141
146
 
142
- // --------------------------------------------------------------- routes
143
- ctx.inject(['webServer'], (webCtx) => {
144
- const webServer = webCtx.get('webServer');
145
-
146
- webCtx.effect(() => {
147
- const disposers = makeRoutes({ stitch }).map((route) => webServer.register(route));
148
- return () => {
149
- for (const dispose of disposers) dispose();
150
- };
151
- }, 'stitch-designer: panel routes');
152
- });
147
+ // ------------------------------------------------------------- guidance
148
+ // The design conventions that cannot be enforced are announced instead, the
149
+ // way this repository delivers every other non-computable rule. Read through
150
+ // `ctx.get` rather than `inject`: `inject` treats a service as REQUIRED and
151
+ // silently skips the whole plugin when it is missing, which would turn "no
152
+ // system prompt" into "no Stitch tools at all".
153
+ const systemPrompt = ctx.get('systemPrompt');
154
+ if (systemPrompt === undefined || systemPrompt === null) {
155
+ ctx.logger?.warn?.('stitch-designer: the systemPrompt service is unavailable; the design conventions were not announced.');
156
+ return;
157
+ }
158
+ ctx.effect(
159
+ () =>
160
+ systemPrompt.section({
161
+ name: SECTION_NAME,
162
+ order: SECTION_ORDER,
163
+ text: STITCH_GUIDANCE,
164
+ }),
165
+ 'stitch-designer: design conventions',
166
+ );
153
167
  }
package/lib/project.js ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The binding file this plugin keeps inside a code project.
3
+ *
4
+ * `.stitch.json` records which Stitch project a code project owns. It is the
5
+ * project's own file, not plugin state: it belongs to the repository, travels
6
+ * with it through git, and is read by whoever implements the design — this
7
+ * session, a later one, or a teammate on another machine. That is why it is
8
+ * kept per repository rather than in any machine-local cache under `$HOME`.
9
+ *
10
+ * It is deliberately small and hand-editable: it is the escape hatch when a
11
+ * Stitch project was deleted, or when the wrong one was recorded.
12
+ *
13
+ * @module @logictan/dsh-stitch-designer/project
14
+ */
15
+ import { readFile, rm, writeFile } from 'node:fs/promises';
16
+ import { join } from 'node:path';
17
+
18
+ /** The binding file, at the code project's root. */
19
+ export const BINDING_FILE = '.stitch.json';
20
+
21
+ /**
22
+ * Read the code project's binding.
23
+ *
24
+ * A missing or hand-broken file means "not bound yet", which is the normal
25
+ * first-run state — not a failure worth surfacing. The file is user-editable
26
+ * by design, so a bad edit has to degrade to "unbound" rather than break every
27
+ * Stitch tool call in the project.
28
+ *
29
+ * Only the id is kept. The title is not: it would be a second copy of a fact
30
+ * Stitch already owns, and it goes stale the moment the project is renamed
31
+ * upstream — while the binding rule reads the id alone.
32
+ *
33
+ * @param directory - the code project's root.
34
+ * @returns `{ projectId }`, or `undefined` when unbound.
35
+ */
36
+ export async function readBinding(directory) {
37
+ try {
38
+ const parsed = JSON.parse(await readFile(join(directory, BINDING_FILE), 'utf8'));
39
+ const projectId = parsed?.projectId;
40
+ if (typeof projectId !== 'string' || projectId === '') return undefined;
41
+ return { projectId };
42
+ } catch {
43
+ return undefined;
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Record the Stitch project this code project owns.
49
+ *
50
+ * First writer wins. Overwriting would let a stray design silently re-point a
51
+ * code project at a different Stitch project — the exact 1:1 rule this file
52
+ * exists to enforce — so a caller that finds a different project already
53
+ * recorded must report that instead of replacing it.
54
+ *
55
+ * @param directory - the code project's root.
56
+ * @param projectId - the Stitch project id.
57
+ * @returns whether the file was written.
58
+ */
59
+ export async function writeBinding(directory, projectId) {
60
+ if (await readBinding(directory)) return false;
61
+ await writeFile(join(directory, BINDING_FILE), `${JSON.stringify({ projectId }, null, 2)}\n`);
62
+ return true;
63
+ }
64
+
65
+ /**
66
+ * Drop the binding, so the code project can bind again.
67
+ *
68
+ * Called when the recorded Stitch project is gone, or when it is deleted
69
+ * through this plugin. Without it a binding to a deleted project would block
70
+ * `create_project` from that directory forever, with no way back short of
71
+ * hand-editing `.stitch.json`.
72
+ *
73
+ * @param directory - the code project's root.
74
+ */
75
+ export async function clearBinding(directory) {
76
+ await rm(join(directory, BINDING_FILE), { force: true });
77
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@logictan/dsh-stitch-designer",
3
- "version": "1.0.0",
4
- "description": "DSH Stitch designer: Google Stitch AI UI generation as native mcp__stitch__* tools, plus an in-session preview panel with screenshot cache and 1:1 HTML export. DSH Stitch 界面设计子插件。",
3
+ "version": "2.0.1",
4
+ "description": "DSH Stitch designer: Google Stitch AI UI generation as native mcp__stitch__* tools, plus the design conventions that keep one code project bound to one Stitch project. DSH Stitch 界面设计子插件。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "exports": {
@@ -14,6 +14,9 @@
14
14
  "patch": "./cordis.patch.yml"
15
15
  },
16
16
  "client": {
17
+ "external": [
18
+ "@logictan/dsh-plugins-shared-client"
19
+ ],
17
20
  "inject": [
18
21
  "slots",
19
22
  "remote",
@@ -42,8 +45,7 @@
42
45
  "ai-design",
43
46
  "ui-generation",
44
47
  "generative-ui",
45
- "mcp",
46
- "preview"
48
+ "mcp"
47
49
  ],
48
50
  "license": "MIT",
49
51
  "repository": {
@@ -56,7 +58,8 @@
56
58
  },
57
59
  "peerDependencies": {
58
60
  "@deepseek-ai/cordis": "^4.0.2",
59
- "@deepseek-ai/dsh-tools": "^0.1.5-alpha.1 || ^0.1.6-alpha.1 || ^0.1.7-alpha.1 || ^0.1.7-rc.1 || ^0.2.0-rc.1 || ^0.2.0-rc.2"
61
+ "@deepseek-ai/dsh-tools": "^0.1.5-alpha.1 || ^0.1.6-alpha.1 || ^0.1.7-alpha.1 || ^0.1.7-rc.1 || ^0.2.0-rc.1 || ^0.2.0-rc.2",
62
+ "@logictan/dsh-plugins-shared-client": "^0.1.0"
60
63
  },
61
64
  "peerDependenciesMeta": {
62
65
  "@deepseek-ai/cordis": {
@@ -64,6 +67,9 @@
64
67
  },
65
68
  "@deepseek-ai/dsh-tools": {
66
69
  "optional": true
70
+ },
71
+ "@logictan/dsh-plugins-shared-client": {
72
+ "optional": true
67
73
  }
68
74
  },
69
75
  "devDependencies": {
package/lib/routes.js DELETED
@@ -1,250 +0,0 @@
1
- /**
2
- * HTTP routes behind the preview panel.
3
- *
4
- * Four routes, and only the four the panel actually calls (the reference
5
- * plugin's `POST /stitch/api/generate` and `POST /stitch/api/edit` are
6
- * deliberately not ported: they existed so an agent could drive Stitch over
7
- * HTTP, and in this plugin the agent calls `mcp__stitch__*` tools directly, so
8
- * those two routes would have no caller at all).
9
- *
10
- * Two of the four are plain file servers over the local cache, and both take
11
- * their filename from the request path — the only genuinely untrusted input in
12
- * this plugin. Each therefore validates the segment against a strict
13
- * character-class pattern before touching the filesystem, so `..` and any other
14
- * traversal attempt fails as a 404 rather than resolving a path outside
15
- * `~/.stitch`.
16
- *
17
- * @module @logictan/dsh-stitch-designer/routes
18
- */
19
- import { readFile } from 'node:fs/promises';
20
- import { join } from 'node:path';
21
-
22
- import {
23
- HTML_DIR,
24
- SCREENS_DIR,
25
- cacheScreenAssets,
26
- downloadTo,
27
- knownScreenIds,
28
- loadState,
29
- rememberScreenId,
30
- saveState,
31
- toPanelScreen,
32
- } from './store.js';
33
-
34
- /** Path prefix of the panel's JSON API. */
35
- export const STATE_API = '/stitch/api/state';
36
- /** Path prefix of the 1:1 HTML export endpoint. */
37
- export const HTML_API = '/stitch/api/html';
38
- /** Path prefix of the cached screenshot files. */
39
- export const SCREENS_PATH = '/stitch/screens';
40
- /** Path prefix of the exported HTML files. */
41
- export const HTML_PATH = '/stitch/html';
42
-
43
- /** A screen id or file stem: no dots, no slashes, so it cannot escape its directory. */
44
- const SAFE_ID = /^[A-Za-z0-9_-]+$/;
45
-
46
- /**
47
- * Write a JSON response.
48
- *
49
- * `no-store` matters: the panel polls this while a design is being generated,
50
- * and a cached response would show a stale project.
51
- *
52
- * @param res - the response.
53
- * @param status - HTTP status.
54
- * @param value - the JSON body.
55
- */
56
- function json(res, status, value) {
57
- res.writeHead(status, {
58
- 'Content-Type': 'application/json; charset=utf-8',
59
- 'Cache-Control': 'no-store',
60
- });
61
- res.end(JSON.stringify(value));
62
- }
63
-
64
- /**
65
- * Write a file from the local cache.
66
- *
67
- * @param res - the response.
68
- * @param dir - the cache directory the file must live in.
69
- * @param file - the validated file name.
70
- * @param contentType - the response content type.
71
- */
72
- async function serveFile(res, dir, file, contentType) {
73
- try {
74
- const body = await readFile(join(dir, file));
75
- res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': 'no-store' });
76
- res.end(body);
77
- } catch {
78
- res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
79
- res.end('not found');
80
- }
81
- }
82
-
83
- /** Extract the last path segment after a prefix. */
84
- function segmentAfter(url, prefix) {
85
- const path = String(url ?? '').split('?')[0];
86
- if (!path.startsWith(`${prefix}/`)) return undefined;
87
- return path.slice(prefix.length + 1);
88
- }
89
-
90
- /**
91
- * Build the plugin's routes.
92
- *
93
- * @param options - the Stitch client.
94
- * @returns the route list.
95
- */
96
- export function makeRoutes(options) {
97
- const { stitch } = options;
98
-
99
- /** List every project the account can see, flattened for the picker. */
100
- const listProjects = async () => {
101
- const result = await stitch.callTool('list_projects', {}, undefined);
102
- const projects = result?.structuredContent?.projects;
103
- return Array.isArray(projects) ? projects : [];
104
- };
105
-
106
- /** List one project's screens. */
107
- const listScreens = async (projectId) => {
108
- const result = await stitch.callTool('list_screens', { projectId }, undefined);
109
- const screens = result?.structuredContent?.screens;
110
- return Array.isArray(screens) ? screens : [];
111
- };
112
-
113
- /** Fetch one screen directly, which works before the index catches up. */
114
- const getScreen = async (projectId, screenId) => {
115
- const result = await stitch.callTool('get_screen', { name: `projects/${projectId}/screens/${screenId}` }, undefined);
116
- return result?.structuredContent?.screen ?? result?.structuredContent;
117
- };
118
-
119
- return [
120
- // ------------------------------------------------- state (prefix)
121
- {
122
- kind: 'prefix',
123
- path: STATE_API,
124
- handler: async (req, res) => {
125
- try {
126
- const url = new URL(String(req.url ?? ''), 'http://localhost');
127
- const wanted = url.searchParams.get('projectId') ?? '';
128
-
129
- const projects = (await listProjects().catch(() => []))
130
- .map((project) => ({
131
- id: String(project?.name ?? '').split('/').pop(),
132
- name: project?.name ?? '',
133
- title: project?.title ?? '',
134
- deviceType: project?.deviceType ?? '',
135
- updateTime: project?.updateTime ?? '',
136
- }))
137
- .filter((project) => project.id !== '');
138
-
139
- const state = await loadState();
140
- const targetId = wanted || state.projectId || projects[0]?.id || '';
141
-
142
- const seen = new Set();
143
- const items = [];
144
- const adopt = async (screen) => {
145
- const row = toPanelScreen(screen);
146
- if (row === undefined || seen.has(row.id)) return;
147
- seen.add(row.id);
148
- await rememberScreenId(targetId, row.id);
149
- await cacheScreenAssets(screen);
150
- items.push(row);
151
- };
152
-
153
- for (const screen of await listScreens(targetId).catch(() => [])) await adopt(screen);
154
-
155
- // `list_screens` lags generation by up to a couple of minutes, so any
156
- // id this machine has already seen is re-fetched directly. Without
157
- // this the panel shows an empty project right after a design lands.
158
- const fallbackIds = knownScreenIds(state, targetId);
159
- if (state.lastScreenId && !fallbackIds.includes(state.lastScreenId)) fallbackIds.unshift(state.lastScreenId);
160
- for (const screenId of fallbackIds) {
161
- if (seen.has(screenId) || !SAFE_ID.test(screenId)) continue;
162
- await getScreen(targetId, screenId)
163
- .then((screen) => adopt(screen))
164
- .catch(() => {});
165
- }
166
-
167
- await saveState({ projectId: targetId });
168
- const target = projects.find((project) => project.id === targetId);
169
- json(res, 200, {
170
- ok: true,
171
- projectId: targetId,
172
- projectTitle: target?.title ?? '',
173
- lastScreenId: state.lastScreenId ?? '',
174
- projects,
175
- screens: items,
176
- });
177
- } catch (error) {
178
- json(res, 500, { ok: false, error: String(error?.message ?? error) });
179
- }
180
- },
181
- },
182
-
183
- // ------------------------------------------------- HTML export (prefix)
184
- {
185
- kind: 'prefix',
186
- path: HTML_API,
187
- handler: async (req, res) => {
188
- try {
189
- const screenId = segmentAfter(req.url, HTML_API);
190
- if (screenId === undefined || !SAFE_ID.test(screenId)) {
191
- json(res, 404, { ok: false, error: 'screen 不存在' });
192
- return;
193
- }
194
- // The panel can ask for a screen from any project, so the owning
195
- // project is resolved from the state and then from the project list
196
- // rather than assumed to be the currently selected one.
197
- const state = await loadState();
198
- const candidates = [state.projectId, ...(await listProjects().catch(() => [])).map((p) => String(p?.name ?? '').split('/').pop())];
199
- let screen;
200
- for (const projectId of candidates) {
201
- if (!projectId) continue;
202
- screen = await getScreen(projectId, screenId).catch(() => undefined);
203
- if (screen?.htmlCode?.downloadUrl) break;
204
- screen = undefined;
205
- }
206
- if (screen?.htmlCode?.downloadUrl === undefined) {
207
- json(res, 404, { ok: false, error: 'screen 不存在' });
208
- return;
209
- }
210
- await downloadTo(screen.htmlCode.downloadUrl, join(HTML_DIR, `${screenId}.html`));
211
- json(res, 200, { ok: true, html: `${HTML_PATH}/${screenId}.html` });
212
- } catch (error) {
213
- json(res, 500, { ok: false, error: String(error?.message ?? error) });
214
- }
215
- },
216
- },
217
-
218
- // ------------------------------------------------- screenshots (prefix)
219
- {
220
- kind: 'prefix',
221
- path: SCREENS_PATH,
222
- handler: async (req, res) => {
223
- const file = segmentAfter(req.url, SCREENS_PATH);
224
- const match = /^([A-Za-z0-9_-]+)\.png$/.exec(file ?? '');
225
- if (match === null) {
226
- res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
227
- res.end('not found');
228
- return;
229
- }
230
- await serveFile(res, SCREENS_DIR, `${match[1]}.png`, 'image/png');
231
- },
232
- },
233
-
234
- // ------------------------------------------------- exported HTML (prefix)
235
- {
236
- kind: 'prefix',
237
- path: HTML_PATH,
238
- handler: async (req, res) => {
239
- const file = segmentAfter(req.url, HTML_PATH);
240
- const match = /^([A-Za-z0-9_-]+)\.html$/.exec(file ?? '');
241
- if (match === null) {
242
- res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
243
- res.end('not found');
244
- return;
245
- }
246
- await serveFile(res, HTML_DIR, `${match[1]}.html`, 'text/html; charset=utf-8');
247
- },
248
- },
249
- ];
250
- }