@dickpy/dsh-imagegen 1.5.6 → 1.5.8

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.
@@ -1,311 +1,311 @@
1
- /**
2
- * Host-persisted gallery (user-curated favorites): mirrors the history store
3
- * (image files + an index.json under ~/.dsh/dsh-imagegen/gallery/) but with no
4
- * size cap — every entry is an explicit user choice. Appends are deduplicated
5
- * by image content so adding the same generated image twice is a no-op.
6
- *
7
- * Framework-free (node:fs + node:crypto only) so the route layer can drive it
8
- * directly.
9
- */
10
-
11
- import { promises as fs } from 'node:fs'
12
- import { createHash } from 'node:crypto'
13
- import path from 'node:path'
14
- import type { GenerateMode, HistoryEntry, HistoryEntryInput } from './protocol.ts'
15
- import { notifyImageSaved } from './storage-sync.ts'
16
- import { imageDataRoot } from './image-storage-path.ts'
17
-
18
- function historyDir(): string { return imageDataRoot() }
19
- function galleryDir(): string { return path.join(imageDataRoot(), 'gallery') }
20
- function indexPath(): string { return path.join(galleryDir(), 'index.json') }
21
- function imagesDir(): string { return path.join(galleryDir(), 'images') }
22
-
23
- /** One gallery entry carries the same wire shape as a history entry. */
24
- export interface GalleryAppendResult {
25
- /** The full gallery list after the append (newest first). */
26
- entries: HistoryEntry[]
27
- /** Whether a new entry was added (false = a content-identical image was
28
- * already in the gallery, so the append was skipped). */
29
- added: boolean
30
- }
31
-
32
- // Gallery mutations read and replace one shared index. Serialize them so
33
- // overlapping requests cannot each read an old index and lose the other's row.
34
- let pendingMutation: Promise<void> = Promise.resolve()
35
-
36
- function mutateGallery<T>(operation: () => Promise<T>): Promise<T> {
37
- const next = pendingMutation.then(operation, operation)
38
- pendingMutation = next.then(() => undefined, () => undefined)
39
- return next
40
- }
41
-
42
- /** One image's on-disk record (file name + mime, never base64). */
43
- interface StoredImage {
44
- file: string
45
- mime: string
46
- revisedPrompt?: string
47
- }
48
-
49
- /** One entry's on-disk record. `hash` fingerprints the first image so the
50
- * store can refuse duplicate appends cheaply. */
51
- interface StoredEntry {
52
- id: string
53
- createdAt: number
54
- mode: GenerateMode
55
- model: string
56
- prompt: string
57
- size: string
58
- quality: string
59
- detail: string
60
- n: number
61
- images: StoredImage[]
62
- hash?: string
63
- refName?: string
64
- tags?: string[]
65
- channelId?: string
66
- channel?: string
67
- workflow?: 'ecommerce'
68
- projectId?: string
69
- projectName?: string
70
- slotKey?: string
71
- slotLabel?: string
72
- canvas?: HistoryEntryInput['canvas']
73
- }
74
-
75
- /** The index.json shape. */
76
- interface IndexFile {
77
- entries: StoredEntry[]
78
- }
79
-
80
- /** File extension for a MIME type (image file names). */
81
- function extensionOf(mime: string): string {
82
- switch (mime.split(';')[0]!.trim()) {
83
- case 'image/jpeg': return 'jpg'
84
- case 'image/webp': return 'webp'
85
- case 'image/gif': return 'gif'
86
- default: return 'png'
87
- }
88
- }
89
-
90
- /** MIME type for a stored image file name (image route responses). */
91
- function mimeOfFile(file: string): string {
92
- const ext = path.extname(file).toLowerCase()
93
- switch (ext) {
94
- case '.jpg':
95
- case '.jpeg': return 'image/jpeg'
96
- case '.webp': return 'image/webp'
97
- case '.gif': return 'image/gif'
98
- default: return 'image/png'
99
- }
100
- }
101
-
102
- /** Sanitize an entry id for use as a file-name prefix. */
103
- function safeId(id: string): string {
104
- const cleaned = id.replace(/[^a-zA-Z0-9-]/g, '-')
105
- return cleaned === '' ? 'entry' : cleaned
106
- }
107
-
108
- /** Short content fingerprint of the entry's first image. */
109
- function fingerprint(input: HistoryEntryInput): string | undefined {
110
- const first = input.images[0]
111
- if (first === undefined) return undefined
112
- return createHash('sha1').update(first.b64).digest('hex')
113
- }
114
-
115
- /** Ensure the storage directories exist. */
116
- async function ensureDirs(): Promise<void> {
117
- await fs.mkdir(imagesDir(), { recursive: true })
118
- }
119
-
120
- /** Read the index, tolerating a missing/corrupt file. */
121
- async function readIndex(): Promise<StoredEntry[]> {
122
- try {
123
- const raw = await fs.readFile(indexPath(), 'utf8')
124
- const parsed: unknown = JSON.parse(raw)
125
- if (parsed === null || typeof parsed !== 'object') return []
126
- const entries = (parsed as { entries?: unknown }).entries
127
- if (!Array.isArray(entries)) return []
128
- return entries.filter(isStoredEntry)
129
- } catch {
130
- return []
131
- }
132
- }
133
-
134
- /** Persist the index. */
135
- async function writeIndex(entries: StoredEntry[]): Promise<void> {
136
- await ensureDirs()
137
- const payload: IndexFile = { entries }
138
- const tmp = `${indexPath()}.tmp-${process.pid}`
139
- await fs.writeFile(tmp, JSON.stringify(payload), 'utf8')
140
- await fs.rename(tmp, indexPath())
141
- }
142
-
143
- /** Structural guard for a stored entry. */
144
- function isStoredEntry(value: unknown): value is StoredEntry {
145
- if (value === null || typeof value !== 'object') return false
146
- const entry = value as Record<string, unknown>
147
- return typeof entry.id === 'string'
148
- && typeof entry.createdAt === 'number'
149
- && (entry.mode === 'text' || entry.mode === 'edit')
150
- && (entry.workflow === undefined || entry.workflow === 'ecommerce')
151
- && (entry.projectId === undefined || typeof entry.projectId === 'string')
152
- && (entry.projectName === undefined || typeof entry.projectName === 'string')
153
- && (entry.slotKey === undefined || typeof entry.slotKey === 'string')
154
- && (entry.slotLabel === undefined || typeof entry.slotLabel === 'string')
155
- && typeof entry.prompt === 'string'
156
- && Array.isArray(entry.images)
157
- && entry.images.every(image => {
158
- if (image === null || typeof image !== 'object') return false
159
- const record = image as Record<string, unknown>
160
- return typeof record.file === 'string' && typeof record.mime === 'string'
161
- })
162
- }
163
-
164
- /** Remove one entry's image files (best effort). */
165
- async function removeEntryFiles(entry: StoredEntry): Promise<void> {
166
- for (const image of entry.images) {
167
- try { await fs.rm(path.join(imagesDir(), image.file), { force: true }) } catch { /* ignore */ }
168
- }
169
- }
170
-
171
- /** Project a stored entry onto the wire shape (image URLs). */
172
- function toWire(entry: StoredEntry): HistoryEntry {
173
- return {
174
- id: entry.id,
175
- createdAt: entry.createdAt,
176
- mode: entry.mode,
177
- model: entry.model,
178
- prompt: entry.prompt,
179
- size: entry.size,
180
- quality: entry.quality,
181
- detail: entry.detail,
182
- n: entry.n,
183
- images: entry.images.map(image => ({
184
- url: `/api/dsh-imagegen/gallery/image/${image.file}`,
185
- mime: image.mime,
186
- ...image.revisedPrompt === undefined ? {} : { revisedPrompt: image.revisedPrompt },
187
- })),
188
- ...entry.refName === undefined ? {} : { refName: entry.refName },
189
- ...entry.tags === undefined ? {} : { tags: entry.tags },
190
- ...entry.channel === undefined ? {} : { channel: entry.channel },
191
- ...entry.channelId === undefined ? {} : { channelId: entry.channelId },
192
- ...entry.workflow === undefined ? {} : { workflow: entry.workflow },
193
- ...entry.projectId === undefined ? {} : { projectId: entry.projectId },
194
- ...entry.projectName === undefined ? {} : { projectName: entry.projectName },
195
- ...entry.slotKey === undefined ? {} : { slotKey: entry.slotKey },
196
- ...entry.slotLabel === undefined ? {} : { slotLabel: entry.slotLabel },
197
- ...entry.canvas === undefined ? {} : { canvas: entry.canvas },
198
- }
199
- }
200
-
201
- /** List the persisted gallery, newest first, as wire entries. */
202
- export async function listGallery(): Promise<HistoryEntry[]> {
203
- const entries = await readIndex()
204
- return entries.map(toWire)
205
- }
206
-
207
- /** Append one image to the gallery. Deduplicates by first-image content —
208
- * appending an image already in the gallery returns `added: false` with the
209
- * list unchanged. No size cap: every entry is an explicit user choice. */
210
- export async function appendGallery(input: HistoryEntryInput): Promise<GalleryAppendResult> {
211
- return mutateGallery(async () => {
212
- await ensureDirs()
213
- const hash = fingerprint(input)
214
- if (hash !== undefined) {
215
- const existing = await readIndex()
216
- if (existing.some(entry => entry.hash === hash)) {
217
- return { entries: existing.map(toWire), added: false }
218
- }
219
- }
220
- const prefix = safeId(input.id)
221
- const storedImages: StoredImage[] = []
222
- try {
223
- for (let index = 0; index < input.images.length; index++) {
224
- const image = input.images[index]!
225
- const file = `${prefix}-${index}.${extensionOf(image.mime)}`
226
- await fs.writeFile(path.join(imagesDir(), file), Buffer.from(image.b64, 'base64'))
227
- notifyImageSaved('gallery', path.join(imagesDir(), file))
228
- storedImages.push({
229
- file,
230
- mime: image.mime,
231
- ...image.revisedPrompt === undefined ? {} : { revisedPrompt: image.revisedPrompt },
232
- })
233
- }
234
- } catch (error) {
235
- await removeEntryFiles({ images: storedImages } as StoredEntry)
236
- throw error
237
- }
238
- const entry: StoredEntry = {
239
- id: input.id,
240
- createdAt: input.createdAt,
241
- mode: input.mode,
242
- model: input.model,
243
- prompt: input.prompt,
244
- size: input.size,
245
- quality: input.quality,
246
- detail: input.detail,
247
- n: input.n,
248
- images: storedImages,
249
- ...hash === undefined ? {} : { hash },
250
- ...input.refName === undefined ? {} : { refName: input.refName },
251
- ...input.channelId === undefined ? {} : { channelId: input.channelId },
252
- ...input.channel === undefined ? {} : { channel: input.channel },
253
- ...input.workflow === undefined ? {} : { workflow: input.workflow },
254
- ...input.projectId === undefined ? {} : { projectId: input.projectId },
255
- ...input.projectName === undefined ? {} : { projectName: input.projectName },
256
- ...input.slotKey === undefined ? {} : { slotKey: input.slotKey },
257
- ...input.slotLabel === undefined ? {} : { slotLabel: input.slotLabel },
258
- ...input.canvas === undefined ? {} : { canvas: input.canvas },
259
- }
260
- const merged = [entry, ...await readIndex()]
261
- await writeIndex(merged)
262
- return { entries: merged.map(toWire), added: true }
263
- })
264
- }
265
-
266
- /** Remove one entry (and its image files). */
267
- export async function removeGallery(id: string): Promise<HistoryEntry[]> {
268
- return mutateGallery(async () => {
269
- const previous = await readIndex()
270
- const target = previous.find(entry => entry.id === id)
271
- if (target !== undefined) await removeEntryFiles(target)
272
- const kept = previous.filter(entry => entry.id !== id)
273
- await writeIndex(kept)
274
- return kept.map(toWire)
275
- })
276
- }
277
-
278
- /** Replace the user-managed labels for one gallery entry. */
279
- export async function updateGalleryTags(id: string, tags: string[]): Promise<HistoryEntry[]> {
280
- return mutateGallery(async () => {
281
- const normalized = [...new Set(tags.map(tag => tag.trim()).filter(Boolean))].slice(0, 20)
282
- const entries = await readIndex()
283
- const target = entries.find(entry => entry.id === id)
284
- if (target !== undefined) target.tags = normalized
285
- await writeIndex(entries)
286
- return entries.map(toWire)
287
- })
288
- }
289
-
290
- /** Remove every entry (and all image files). */
291
- export async function clearGallery(): Promise<HistoryEntry[]> {
292
- return mutateGallery(async () => {
293
- const previous = await readIndex()
294
- for (const entry of previous) await removeEntryFiles(entry)
295
- await writeIndex([])
296
- return []
297
- })
298
- }
299
-
300
- /** Read one stored image file by its (validated) file name. */
301
- export async function readGalleryImage(file: string): Promise<{ data: Buffer; mime: string } | undefined> {
302
- // Only accept <id>-<index>.<png|jpg|jpeg|webp|gif> — the exact names this
303
- // store writes — so the route can never escape the images directory.
304
- if (!/^[a-zA-Z0-9][a-zA-Z0-9-]*-[0-9]+\.(png|jpg|jpeg|webp|gif)$/.test(file)) return undefined
305
- try {
306
- const data = await fs.readFile(path.join(imagesDir(), file))
307
- return { data, mime: mimeOfFile(file) }
308
- } catch {
309
- return undefined
310
- }
311
- }
1
+ /**
2
+ * Host-persisted gallery (user-curated favorites): mirrors the history store
3
+ * (image files + an index.json under ~/.dsh/dsh-imagegen/gallery/) but with no
4
+ * size cap — every entry is an explicit user choice. Appends are deduplicated
5
+ * by image content so adding the same generated image twice is a no-op.
6
+ *
7
+ * Framework-free (node:fs + node:crypto only) so the route layer can drive it
8
+ * directly.
9
+ */
10
+
11
+ import { promises as fs } from 'node:fs'
12
+ import { createHash } from 'node:crypto'
13
+ import path from 'node:path'
14
+ import type { GenerateMode, HistoryEntry, HistoryEntryInput } from './protocol.ts'
15
+ import { notifyImageSaved } from './storage-sync.ts'
16
+ import { imageDataRoot } from './image-storage-path.ts'
17
+
18
+ function historyDir(): string { return imageDataRoot() }
19
+ function galleryDir(): string { return path.join(imageDataRoot(), 'gallery') }
20
+ function indexPath(): string { return path.join(galleryDir(), 'index.json') }
21
+ function imagesDir(): string { return path.join(galleryDir(), 'images') }
22
+
23
+ /** One gallery entry carries the same wire shape as a history entry. */
24
+ export interface GalleryAppendResult {
25
+ /** The full gallery list after the append (newest first). */
26
+ entries: HistoryEntry[]
27
+ /** Whether a new entry was added (false = a content-identical image was
28
+ * already in the gallery, so the append was skipped). */
29
+ added: boolean
30
+ }
31
+
32
+ // Gallery mutations read and replace one shared index. Serialize them so
33
+ // overlapping requests cannot each read an old index and lose the other's row.
34
+ let pendingMutation: Promise<void> = Promise.resolve()
35
+
36
+ function mutateGallery<T>(operation: () => Promise<T>): Promise<T> {
37
+ const next = pendingMutation.then(operation, operation)
38
+ pendingMutation = next.then(() => undefined, () => undefined)
39
+ return next
40
+ }
41
+
42
+ /** One image's on-disk record (file name + mime, never base64). */
43
+ interface StoredImage {
44
+ file: string
45
+ mime: string
46
+ revisedPrompt?: string
47
+ }
48
+
49
+ /** One entry's on-disk record. `hash` fingerprints the first image so the
50
+ * store can refuse duplicate appends cheaply. */
51
+ interface StoredEntry {
52
+ id: string
53
+ createdAt: number
54
+ mode: GenerateMode
55
+ model: string
56
+ prompt: string
57
+ size: string
58
+ quality: string
59
+ detail: string
60
+ n: number
61
+ images: StoredImage[]
62
+ hash?: string
63
+ refName?: string
64
+ tags?: string[]
65
+ channelId?: string
66
+ channel?: string
67
+ workflow?: 'ecommerce'
68
+ projectId?: string
69
+ projectName?: string
70
+ slotKey?: string
71
+ slotLabel?: string
72
+ canvas?: HistoryEntryInput['canvas']
73
+ }
74
+
75
+ /** The index.json shape. */
76
+ interface IndexFile {
77
+ entries: StoredEntry[]
78
+ }
79
+
80
+ /** File extension for a MIME type (image file names). */
81
+ function extensionOf(mime: string): string {
82
+ switch (mime.split(';')[0]!.trim()) {
83
+ case 'image/jpeg': return 'jpg'
84
+ case 'image/webp': return 'webp'
85
+ case 'image/gif': return 'gif'
86
+ default: return 'png'
87
+ }
88
+ }
89
+
90
+ /** MIME type for a stored image file name (image route responses). */
91
+ function mimeOfFile(file: string): string {
92
+ const ext = path.extname(file).toLowerCase()
93
+ switch (ext) {
94
+ case '.jpg':
95
+ case '.jpeg': return 'image/jpeg'
96
+ case '.webp': return 'image/webp'
97
+ case '.gif': return 'image/gif'
98
+ default: return 'image/png'
99
+ }
100
+ }
101
+
102
+ /** Sanitize an entry id for use as a file-name prefix. */
103
+ function safeId(id: string): string {
104
+ const cleaned = id.replace(/[^a-zA-Z0-9-]/g, '-')
105
+ return cleaned === '' ? 'entry' : cleaned
106
+ }
107
+
108
+ /** Short content fingerprint of the entry's first image. */
109
+ function fingerprint(input: HistoryEntryInput): string | undefined {
110
+ const first = input.images[0]
111
+ if (first === undefined) return undefined
112
+ return createHash('sha1').update(first.b64).digest('hex')
113
+ }
114
+
115
+ /** Ensure the storage directories exist. */
116
+ async function ensureDirs(): Promise<void> {
117
+ await fs.mkdir(imagesDir(), { recursive: true })
118
+ }
119
+
120
+ /** Read the index, tolerating a missing/corrupt file. */
121
+ async function readIndex(): Promise<StoredEntry[]> {
122
+ try {
123
+ const raw = await fs.readFile(indexPath(), 'utf8')
124
+ const parsed: unknown = JSON.parse(raw)
125
+ if (parsed === null || typeof parsed !== 'object') return []
126
+ const entries = (parsed as { entries?: unknown }).entries
127
+ if (!Array.isArray(entries)) return []
128
+ return entries.filter(isStoredEntry)
129
+ } catch {
130
+ return []
131
+ }
132
+ }
133
+
134
+ /** Persist the index. */
135
+ async function writeIndex(entries: StoredEntry[]): Promise<void> {
136
+ await ensureDirs()
137
+ const payload: IndexFile = { entries }
138
+ const tmp = `${indexPath()}.tmp-${process.pid}`
139
+ await fs.writeFile(tmp, JSON.stringify(payload), 'utf8')
140
+ await fs.rename(tmp, indexPath())
141
+ }
142
+
143
+ /** Structural guard for a stored entry. */
144
+ function isStoredEntry(value: unknown): value is StoredEntry {
145
+ if (value === null || typeof value !== 'object') return false
146
+ const entry = value as Record<string, unknown>
147
+ return typeof entry.id === 'string'
148
+ && typeof entry.createdAt === 'number'
149
+ && (entry.mode === 'text' || entry.mode === 'edit')
150
+ && (entry.workflow === undefined || entry.workflow === 'ecommerce')
151
+ && (entry.projectId === undefined || typeof entry.projectId === 'string')
152
+ && (entry.projectName === undefined || typeof entry.projectName === 'string')
153
+ && (entry.slotKey === undefined || typeof entry.slotKey === 'string')
154
+ && (entry.slotLabel === undefined || typeof entry.slotLabel === 'string')
155
+ && typeof entry.prompt === 'string'
156
+ && Array.isArray(entry.images)
157
+ && entry.images.every(image => {
158
+ if (image === null || typeof image !== 'object') return false
159
+ const record = image as Record<string, unknown>
160
+ return typeof record.file === 'string' && typeof record.mime === 'string'
161
+ })
162
+ }
163
+
164
+ /** Remove one entry's image files (best effort). */
165
+ async function removeEntryFiles(entry: StoredEntry): Promise<void> {
166
+ for (const image of entry.images) {
167
+ try { await fs.rm(path.join(imagesDir(), image.file), { force: true }) } catch { /* ignore */ }
168
+ }
169
+ }
170
+
171
+ /** Project a stored entry onto the wire shape (image URLs). */
172
+ function toWire(entry: StoredEntry): HistoryEntry {
173
+ return {
174
+ id: entry.id,
175
+ createdAt: entry.createdAt,
176
+ mode: entry.mode,
177
+ model: entry.model,
178
+ prompt: entry.prompt,
179
+ size: entry.size,
180
+ quality: entry.quality,
181
+ detail: entry.detail,
182
+ n: entry.n,
183
+ images: entry.images.map(image => ({
184
+ url: `/api/dsh-imagegen/gallery/image/${image.file}`,
185
+ mime: image.mime,
186
+ ...image.revisedPrompt === undefined ? {} : { revisedPrompt: image.revisedPrompt },
187
+ })),
188
+ ...entry.refName === undefined ? {} : { refName: entry.refName },
189
+ ...entry.tags === undefined ? {} : { tags: entry.tags },
190
+ ...entry.channel === undefined ? {} : { channel: entry.channel },
191
+ ...entry.channelId === undefined ? {} : { channelId: entry.channelId },
192
+ ...entry.workflow === undefined ? {} : { workflow: entry.workflow },
193
+ ...entry.projectId === undefined ? {} : { projectId: entry.projectId },
194
+ ...entry.projectName === undefined ? {} : { projectName: entry.projectName },
195
+ ...entry.slotKey === undefined ? {} : { slotKey: entry.slotKey },
196
+ ...entry.slotLabel === undefined ? {} : { slotLabel: entry.slotLabel },
197
+ ...entry.canvas === undefined ? {} : { canvas: entry.canvas },
198
+ }
199
+ }
200
+
201
+ /** List the persisted gallery, newest first, as wire entries. */
202
+ export async function listGallery(): Promise<HistoryEntry[]> {
203
+ const entries = await readIndex()
204
+ return entries.map(toWire)
205
+ }
206
+
207
+ /** Append one image to the gallery. Deduplicates by first-image content —
208
+ * appending an image already in the gallery returns `added: false` with the
209
+ * list unchanged. No size cap: every entry is an explicit user choice. */
210
+ export async function appendGallery(input: HistoryEntryInput): Promise<GalleryAppendResult> {
211
+ return mutateGallery(async () => {
212
+ await ensureDirs()
213
+ const hash = fingerprint(input)
214
+ if (hash !== undefined) {
215
+ const existing = await readIndex()
216
+ if (existing.some(entry => entry.hash === hash)) {
217
+ return { entries: existing.map(toWire), added: false }
218
+ }
219
+ }
220
+ const prefix = safeId(input.id)
221
+ const storedImages: StoredImage[] = []
222
+ try {
223
+ for (let index = 0; index < input.images.length; index++) {
224
+ const image = input.images[index]!
225
+ const file = `${prefix}-${index}.${extensionOf(image.mime)}`
226
+ await fs.writeFile(path.join(imagesDir(), file), Buffer.from(image.b64, 'base64'))
227
+ notifyImageSaved('gallery', path.join(imagesDir(), file))
228
+ storedImages.push({
229
+ file,
230
+ mime: image.mime,
231
+ ...image.revisedPrompt === undefined ? {} : { revisedPrompt: image.revisedPrompt },
232
+ })
233
+ }
234
+ } catch (error) {
235
+ await removeEntryFiles({ images: storedImages } as StoredEntry)
236
+ throw error
237
+ }
238
+ const entry: StoredEntry = {
239
+ id: input.id,
240
+ createdAt: input.createdAt,
241
+ mode: input.mode,
242
+ model: input.model,
243
+ prompt: input.prompt,
244
+ size: input.size,
245
+ quality: input.quality,
246
+ detail: input.detail,
247
+ n: input.n,
248
+ images: storedImages,
249
+ ...hash === undefined ? {} : { hash },
250
+ ...input.refName === undefined ? {} : { refName: input.refName },
251
+ ...input.channelId === undefined ? {} : { channelId: input.channelId },
252
+ ...input.channel === undefined ? {} : { channel: input.channel },
253
+ ...input.workflow === undefined ? {} : { workflow: input.workflow },
254
+ ...input.projectId === undefined ? {} : { projectId: input.projectId },
255
+ ...input.projectName === undefined ? {} : { projectName: input.projectName },
256
+ ...input.slotKey === undefined ? {} : { slotKey: input.slotKey },
257
+ ...input.slotLabel === undefined ? {} : { slotLabel: input.slotLabel },
258
+ ...input.canvas === undefined ? {} : { canvas: input.canvas },
259
+ }
260
+ const merged = [entry, ...await readIndex()]
261
+ await writeIndex(merged)
262
+ return { entries: merged.map(toWire), added: true }
263
+ })
264
+ }
265
+
266
+ /** Remove one entry (and its image files). */
267
+ export async function removeGallery(id: string): Promise<HistoryEntry[]> {
268
+ return mutateGallery(async () => {
269
+ const previous = await readIndex()
270
+ const target = previous.find(entry => entry.id === id)
271
+ if (target !== undefined) await removeEntryFiles(target)
272
+ const kept = previous.filter(entry => entry.id !== id)
273
+ await writeIndex(kept)
274
+ return kept.map(toWire)
275
+ })
276
+ }
277
+
278
+ /** Replace the user-managed labels for one gallery entry. */
279
+ export async function updateGalleryTags(id: string, tags: string[]): Promise<HistoryEntry[]> {
280
+ return mutateGallery(async () => {
281
+ const normalized = [...new Set(tags.map(tag => tag.trim()).filter(Boolean))].slice(0, 20)
282
+ const entries = await readIndex()
283
+ const target = entries.find(entry => entry.id === id)
284
+ if (target !== undefined) target.tags = normalized
285
+ await writeIndex(entries)
286
+ return entries.map(toWire)
287
+ })
288
+ }
289
+
290
+ /** Remove every entry (and all image files). */
291
+ export async function clearGallery(): Promise<HistoryEntry[]> {
292
+ return mutateGallery(async () => {
293
+ const previous = await readIndex()
294
+ for (const entry of previous) await removeEntryFiles(entry)
295
+ await writeIndex([])
296
+ return []
297
+ })
298
+ }
299
+
300
+ /** Read one stored image file by its (validated) file name. */
301
+ export async function readGalleryImage(file: string): Promise<{ data: Buffer; mime: string } | undefined> {
302
+ // Only accept <id>-<index>.<png|jpg|jpeg|webp|gif> — the exact names this
303
+ // store writes — so the route can never escape the images directory.
304
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9-]*-[0-9]+\.(png|jpg|jpeg|webp|gif)$/.test(file)) return undefined
305
+ try {
306
+ const data = await fs.readFile(path.join(imagesDir(), file))
307
+ return { data, mime: mimeOfFile(file) }
308
+ } catch {
309
+ return undefined
310
+ }
311
+ }