@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.
package/lib/store.js DELETED
@@ -1,229 +0,0 @@
1
- /**
2
- * Local asset store behind the preview panel: the screenshot/HTML cache, the
3
- * "last used project" state, and the per-project screen registry.
4
- *
5
- * Stitch's `list_screens` index lags behind generation by up to a couple of
6
- * minutes, and `generate_screen_from_text` returns the finished screen in its
7
- * own payload long before that index catches up. The cache and registry here
8
- * are what let the panel show a design the moment it exists instead of showing
9
- * an empty project — the failure the reference implementation was written to
10
- * fix, and the reason `state.json` is persisted rather than held in memory
11
- * (an in-memory `lastScreenId` is lost on every restart, blanking the panel).
12
- *
13
- * Everything lives under `~/.stitch`, the same location the reference plugin
14
- * used, so an existing cache keeps working. The API key is deliberately NOT
15
- * here: it belongs to the credentials file (see `src/index.js`).
16
- *
17
- * @module @logictan/dsh-stitch-designer/store
18
- */
19
- import { mkdir, readFile, writeFile } from 'node:fs/promises';
20
- import { homedir } from 'node:os';
21
- import { dirname, join } from 'node:path';
22
-
23
- /** Root of the local cache. */
24
- export const STITCH_HOME = join(homedir(), '.stitch');
25
- /** Cached screenshots, served at `/stitch/screens/<id>.png`. */
26
- export const SCREENS_DIR = join(STITCH_HOME, 'screens');
27
- /** Exported 1:1 HTML sources, served at `/stitch/html/<id>.html`. */
28
- export const HTML_DIR = join(STITCH_HOME, 'html');
29
- /** Persisted project/screen state. */
30
- export const STATE_FILE = join(STITCH_HOME, 'state.json');
31
- /** Cap on remembered screen ids per project. */
32
- const MAX_REMEMBERED_SCREENS = 50;
33
-
34
- /**
35
- * Read `state.json`, tolerating absence and corruption.
36
- *
37
- * A missing or malformed file means "no memory yet", which is a normal first
38
- * run — not a failure worth surfacing, and definitely not one worth letting
39
- * abort a panel refresh.
40
- *
41
- * @returns the parsed state, or an empty object.
42
- */
43
- export async function loadState() {
44
- try {
45
- const parsed = JSON.parse(await readFile(STATE_FILE, 'utf8'));
46
- return parsed !== null && typeof parsed === 'object' ? parsed : {};
47
- } catch {
48
- return {};
49
- }
50
- }
51
-
52
- /**
53
- * Merge a patch into `state.json`.
54
- *
55
- * Empty values never overwrite a stored one: callers pass whatever they happen
56
- * to have in hand, and an uninitialised variable would otherwise erase the
57
- * project the panel is supposed to remember.
58
- *
59
- * @param patch - fields to merge.
60
- * @returns the merged state.
61
- */
62
- export async function saveState(patch) {
63
- const previous = await loadState();
64
- const next = { ...previous, ...patch };
65
- if (!patch.projectId && previous.projectId) next.projectId = previous.projectId;
66
- if (!patch.lastScreenId && previous.lastScreenId) next.lastScreenId = previous.lastScreenId;
67
- try {
68
- await mkdir(dirname(STATE_FILE), { recursive: true });
69
- await writeFile(STATE_FILE, JSON.stringify(next, null, 2));
70
- } catch {
71
- // The state file is an optimisation; losing it degrades the panel to
72
- // "whatever Stitch's index reports" and must not fail the request.
73
- }
74
- return next;
75
- }
76
-
77
- /**
78
- * Screen ids this machine has already seen for one project.
79
- *
80
- * @param state - a loaded state object.
81
- * @param projectId - the project id.
82
- * @returns the remembered ids, oldest first.
83
- */
84
- export function knownScreenIds(state, projectId) {
85
- const registry = state?.screensByProject?.[projectId];
86
- return Array.isArray(registry) ? registry : [];
87
- }
88
-
89
- /**
90
- * Record one screen id against its project.
91
- *
92
- * @param projectId - the project id.
93
- * @param screenId - the screen id to remember.
94
- */
95
- export async function rememberScreenId(projectId, screenId) {
96
- if (!projectId || !screenId) return;
97
- const state = await loadState();
98
- const registry = { ...(state.screensByProject ?? {}) };
99
- const list = Array.isArray(registry[projectId]) ? [...registry[projectId]] : [];
100
- if (!list.includes(screenId)) list.push(screenId);
101
- registry[projectId] = list.slice(-MAX_REMEMBERED_SCREENS);
102
- try {
103
- await mkdir(dirname(STATE_FILE), { recursive: true });
104
- await writeFile(STATE_FILE, JSON.stringify({ ...state, screensByProject: registry }, null, 2));
105
- } catch {
106
- // See saveState: a lost registry only costs the index-lag fallback.
107
- }
108
- }
109
-
110
- /**
111
- * Upgrade a Google image URL to full resolution.
112
- *
113
- * Stitch hands out thumbnail URLs; `=s0` asks the image service for the
114
- * original. Applied only when no size directive is already present, so a URL
115
- * that already carries one is left alone.
116
- *
117
- * @param url - the download URL.
118
- * @returns the URL to fetch.
119
- */
120
- export function hdImageUrl(url) {
121
- const value = String(url ?? '');
122
- return value.includes('googleusercontent.com') && !/=[sw]\d+/.test(value) ? `${value}=s0` : value;
123
- }
124
-
125
- /**
126
- * Download a URL to a local path, creating parent directories.
127
- *
128
- * @param url - source URL.
129
- * @param dest - absolute destination path.
130
- * @returns the destination path.
131
- * @throws when the response is not OK or the write fails.
132
- */
133
- export async function downloadTo(url, dest) {
134
- const response = await fetch(hdImageUrl(url));
135
- if (!response.ok) throw new Error(`download failed: HTTP ${response.status}`);
136
- await mkdir(dirname(dest), { recursive: true });
137
- await writeFile(dest, Buffer.from(await response.arrayBuffer()));
138
- return dest;
139
- }
140
-
141
- /**
142
- * Cache one screen's screenshot and HTML source, best effort.
143
- *
144
- * A failed download is not an error: the panel falls back to the remote
145
- * `downloadUrl`, and the next refresh retries. Only the returned record's
146
- * shape matters to callers.
147
- *
148
- * @param screen - a Stitch screen object.
149
- * @returns the screen's id, or `undefined` when it carries none.
150
- */
151
- export async function cacheScreenAssets(screen) {
152
- const screenId = String(screen?.name ?? '').split('/').pop();
153
- if (!screenId) return undefined;
154
- if (screen?.screenshot?.downloadUrl) {
155
- await downloadTo(screen.screenshot.downloadUrl, join(SCREENS_DIR, `${screenId}.png`)).catch(() => {});
156
- }
157
- if (screen?.htmlCode?.downloadUrl) {
158
- await downloadTo(screen.htmlCode.downloadUrl, join(HTML_DIR, `${screenId}.html`)).catch(() => {});
159
- }
160
- return screenId;
161
- }
162
-
163
- /**
164
- * Project one Stitch screen into the panel's row shape.
165
- *
166
- * @param screen - a Stitch screen object.
167
- * @returns the panel row, or `undefined` when the screen carries no id.
168
- */
169
- export function toPanelScreen(screen) {
170
- const screenId = String(screen?.name ?? '').split('/').pop();
171
- if (!screenId) return undefined;
172
- return {
173
- name: screen.name,
174
- id: screenId,
175
- title: screen.title ?? '',
176
- deviceType: screen.deviceType ?? '',
177
- width: screen.width ?? '',
178
- height: screen.height ?? '',
179
- preview: `/stitch/screens/${screenId}.png`,
180
- screenshotUrl: screen.screenshot?.downloadUrl ?? '',
181
- htmlUrl: screen.htmlCode?.downloadUrl ?? '',
182
- };
183
- }
184
-
185
- /**
186
- * Pull the freshly generated screen out of a `generate`/`edit` result.
187
- *
188
- * Stitch returns the finished screen inside
189
- * `structuredContent.outputComponents[].design.screens[]` immediately, which is
190
- * strictly earlier than `list_screens` will report it.
191
- *
192
- * @param result - the MCP result of a generate/edit call.
193
- * @returns the first screen found, or `undefined`.
194
- */
195
- export function extractScreenFromResult(result) {
196
- const components = result?.structuredContent?.outputComponents;
197
- if (!Array.isArray(components)) return undefined;
198
- for (const component of components) {
199
- const screens = component?.design?.screens;
200
- if (Array.isArray(screens) && screens.length > 0) return screens[0];
201
- }
202
- return undefined;
203
- }
204
-
205
- /**
206
- * Adopt a screen into the cache and the persisted state.
207
- *
208
- * @param projectId - the project the screen belongs to.
209
- * @param screen - the Stitch screen object.
210
- * @param source - provenance tag recorded for the panel (`list`, `generate`, ...).
211
- * @returns the panel response, or `undefined` when the screen carries no id.
212
- */
213
- export async function adoptScreen(projectId, screen, source = 'list') {
214
- const screenId = await cacheScreenAssets(screen);
215
- if (screenId === undefined) return undefined;
216
- await rememberScreenId(projectId, screenId);
217
- await saveState({ projectId, lastScreenId: screenId });
218
- return {
219
- ok: true,
220
- screenId,
221
- title: screen.title ?? '',
222
- deviceType: screen.deviceType ?? '',
223
- width: screen.width ?? '',
224
- height: screen.height ?? '',
225
- preview: `/stitch/screens/${screenId}.png`,
226
- html: `/stitch/html/${screenId}.html`,
227
- source,
228
- };
229
- }