@2kog/kacha 0.0.0-stage → 0.1.2

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 (40) hide show
  1. package/README.md +57 -2
  2. package/bin/init-project.js +63 -0
  3. package/bin/kacha.js +51 -0
  4. package/index.html +5 -0
  5. package/package.json +45 -4
  6. package/server/asset-directories.js +65 -0
  7. package/server/asset-watch.js +35 -0
  8. package/server/character-assets.js +399 -0
  9. package/server/image-assets.js +652 -0
  10. package/server/index.js +15 -0
  11. package/server/project-brand.js +56 -0
  12. package/server/project-paths.js +4 -0
  13. package/server/project-settings.js +55 -0
  14. package/src/App.vue +34 -0
  15. package/src/assets/css/workbench.css +272 -0
  16. package/src/assets/img/rabbit-mark.svg +1 -0
  17. package/src/components/AssetDeleteButton.vue +53 -0
  18. package/src/components/AssetHistory.vue +40 -0
  19. package/src/components/AssetStoryEditor.vue +32 -0
  20. package/src/components/AssetTagInput.vue +26 -0
  21. package/src/components/ProjectMarkdown.vue +33 -0
  22. package/src/i18n/en.json +163 -0
  23. package/src/i18n/index.js +40 -0
  24. package/src/layouts/WorkbenchLayout.vue +61 -0
  25. package/src/main.js +7 -0
  26. package/src/router/index.js +38 -0
  27. package/src/service/assets.js +13 -0
  28. package/src/service/project-markdown.js +26 -0
  29. package/src/views/assets/AudioAssets.vue +325 -0
  30. package/src/views/assets/CharacterAssets.vue +412 -0
  31. package/src/views/assets/ImageAssets.vue +456 -0
  32. package/src/views/settings/ProjectSettings.vue +80 -0
  33. package/templates/project/AGENTS.md +14 -0
  34. package/templates/project/README.md +7 -0
  35. package/templates/project/assets/audio/README.md +5 -0
  36. package/templates/project/assets/characters/README.md +5 -0
  37. package/templates/project/assets/other/README.md +3 -0
  38. package/templates/project/assets/props/README.md +3 -0
  39. package/templates/project/assets/scenes/README.md +3 -0
  40. package/vite.config.js +10 -0
@@ -0,0 +1,399 @@
1
+ import * as fs from 'node:fs/promises'
2
+ import { createReadStream } from 'node:fs'
3
+ import path from 'node:path'
4
+ import { assetRoot } from './project-paths.js'
5
+ import { randomUUID } from 'node:crypto'
6
+ import { deleteAssetDirectory, isAssetFolderName, scanAssets } from './asset-directories.js'
7
+
8
+ const root = assetRoot('characters')
9
+ const index = 'index.json'
10
+ const slots = {
11
+ image2d: { stem: '2d-turnaround', legacyStem: '2d', formats: ['png', 'jpg', 'jpeg', 'webp', 'avif'], legacy: '原画三视图.png' },
12
+ image3d: { stem: '3d-turnaround', legacyStem: '3d', formats: ['png', 'jpg', 'jpeg', 'webp', 'avif'], legacy: '3D三视图.png' },
13
+ model3d: { stem: 'model', formats: ['glb'] },
14
+ voice: { stem: 'voice/index', formats: ['mp3', 'wav', 'ogg', 'm4a', 'flac', 'aac'] },
15
+ }
16
+ const types = {
17
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', avif: 'image/avif',
18
+ glb: 'model/gltf-binary', mp3: 'audio/mpeg', wav: 'audio/wav', ogg: 'audio/ogg',
19
+ m4a: 'audio/mp4', flac: 'audio/flac', aac: 'audio/aac',
20
+ }
21
+ const extension = file => path.extname(file).slice(1).toLowerCase()
22
+ const relative = (base, file) => path.relative(base, file).split(path.sep).join('/')
23
+ const url = (dir, file) => file ? '/character-media?file=' + encodeURIComponent(relative(root, path.join(dir, file))) : null
24
+ const inside = (base, file) => file.startsWith(path.resolve(base) + path.sep)
25
+ const fail = (status, message) => Object.assign(new Error(message), { status })
26
+
27
+ async function entries(dir) {
28
+ try {
29
+ return await fs.readdir(dir, { withFileTypes: true })
30
+ } catch (error) {
31
+ if (error.code === 'ENOENT') return []
32
+ throw error
33
+ }
34
+ }
35
+
36
+ async function read(file, fallback) {
37
+ try {
38
+ if (!(await fs.lstat(file)).isFile()) return fallback
39
+ return await fs.readFile(file, 'utf8')
40
+ } catch (error) {
41
+ if (error.code === 'ENOENT') return fallback
42
+ throw error
43
+ }
44
+ }
45
+
46
+ async function metadata(dir) {
47
+ return JSON.parse(await read(path.join(dir, index), '{}'))
48
+ }
49
+
50
+ async function currentFiles(dir, data) {
51
+ const files = {}
52
+ for (const [key, slot] of Object.entries(slots)) {
53
+ const configured = data[key]
54
+ const acceptable = typeof configured === 'string'
55
+ && (key === 'voice' ? /^voice\/index\.[^/\\]+$/.test(configured) : path.basename(configured) === configured && !configured.includes('\\'))
56
+ && slot.formats.includes(extension(configured))
57
+ const candidates = [
58
+ ...(acceptable ? [configured] : []),
59
+ ...slot.formats.map(format => slot.stem + '.' + format),
60
+ ...(slot.legacyStem ? slot.formats.map(format => slot.legacyStem + '.' + format) : []),
61
+ slot.legacy,
62
+ ]
63
+ for (const file of candidates.filter(Boolean)) {
64
+ const absolute = path.join(dir, file)
65
+ const real = await fs.realpath(absolute).catch(() => '')
66
+ if (real === absolute && (await fs.stat(real)).isFile()) {
67
+ files[key] = file
68
+ break
69
+ }
70
+ }
71
+ }
72
+ return files
73
+ }
74
+
75
+ async function describe(dir, groups = []) {
76
+ const data = await metadata(dir)
77
+ const files = await currentFiles(dir, data)
78
+ const hiddenGroupTags = new Set(Array.isArray(data.hiddenGroupTags) ? data.hiddenGroupTags : [])
79
+ const media = {}
80
+ for (const [key, file] of Object.entries(files)) {
81
+ const stat = await fs.stat(path.join(dir, file))
82
+ media[key] = url(dir, file) + '&modified=' + stat.mtimeMs
83
+ }
84
+ const extraVoice = []
85
+ for (const folder of ['voice', '音色参考']) {
86
+ const absolute = path.join(dir, folder)
87
+ if (await fs.realpath(absolute).catch(() => '') !== absolute) continue
88
+ for (const item of await entries(absolute)) {
89
+ const file = folder + '/' + item.name
90
+ if (!item.isFile() || !slots.voice.formats.includes(extension(file)) || file === files.voice) continue
91
+ extraVoice.push({ name: item.name, url: url(dir, file) })
92
+ }
93
+ }
94
+ return {
95
+ id: relative(root, dir),
96
+ name: path.basename(dir),
97
+ tags: [...new Set([...(Array.isArray(data.tags) ? data.tags.filter(tag => typeof tag === 'string') : []), ...groups.filter(tag => !hiddenGroupTags.has(tag))])],
98
+ media,
99
+ main: [data.mainImage, 'image3d', 'image2d'].find(key => ['image2d', 'image3d'].includes(key) && media[key]) || null,
100
+ extraVoice,
101
+ }
102
+ }
103
+
104
+ async function list() {
105
+ const assets = await scanAssets(root)
106
+ const characters = await Promise.all(assets.map(asset => describe(asset.dir, asset.groups)))
107
+ return characters.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'))
108
+ }
109
+
110
+ async function getDirectory(id) {
111
+ const asset = (await scanAssets(root)).find(entry => entry.id === id)
112
+ if (!asset) throw fail(404, '找不到角色目录')
113
+ return asset
114
+ }
115
+
116
+ async function galleryImages(dir, folder, prompts, excluded = new Set()) {
117
+ const absolute = path.resolve(dir, folder)
118
+ if (!inside(dir, absolute) || excluded.has(absolute) || await fs.realpath(absolute).catch(() => '') !== absolute) return []
119
+ if (!(await fs.stat(absolute)).isDirectory()) return []
120
+ const images = []
121
+ for (const item of (await entries(absolute)).sort((a, b) => a.name.localeCompare(b.name, 'zh-CN', { numeric: true }))) {
122
+ if (item.name.startsWith('.') || item.name === 'archive') continue
123
+ const itemPath = path.join(absolute, item.name)
124
+ const file = relative(dir, itemPath)
125
+ if (item.isDirectory()) {
126
+ images.push(...await galleryImages(dir, file, prompts, excluded))
127
+ } else if (item.isFile() && types[extension(item.name)]?.startsWith('image/')) {
128
+ const modified = (await fs.stat(itemPath)).mtimeMs
129
+ images.push({
130
+ file,
131
+ name: path.parse(item.name).name,
132
+ url: url(dir, file) + '&modified=' + modified,
133
+ prompt: typeof prompts?.[file] === 'string' ? prompts[file] : '',
134
+ })
135
+ }
136
+ }
137
+ return images
138
+ }
139
+
140
+ async function characterGalleries(dir, data) {
141
+ const folders = new Set(['skin', 'skins'])
142
+ for (const skin of Array.isArray(data.skins) ? data.skins : []) {
143
+ if (typeof skin?.folder !== 'string') continue
144
+ const fullPath = path.resolve(dir, skin.folder)
145
+ const folder = relative(dir, fullPath)
146
+ if (!inside(dir, fullPath) || folder.split('/').some(part => part === 'archive' || part.startsWith('.'))) continue
147
+ folders.add(folder)
148
+ }
149
+ const images = new Map()
150
+ for (const folder of folders) {
151
+ for (const image of await galleryImages(dir, folder, data.assetPrompts)) images.set(image.file, image)
152
+ }
153
+ const skins = [...images.values()]
154
+ const excluded = new Set([...folders].map(folder => path.join(dir, folder)))
155
+ const portraits = [
156
+ ...await galleryImages(dir, 'portraits', data.assetPrompts, excluded),
157
+ ...await galleryImages(dir, '特写', data.assetPrompts, excluded),
158
+ ]
159
+ return { portraits, skins }
160
+ }
161
+
162
+ async function detail(dir, groups = []) {
163
+ const data = await metadata(dir)
164
+ const archive = path.join(dir, 'archive')
165
+ const history = []
166
+ const versions = Array.isArray(data.history) ? data.history : []
167
+ if (await fs.realpath(archive).catch(() => '') === archive) {
168
+ for (const item of await entries(archive)) {
169
+ if (!item.isDirectory() || item.name === '生成记录' || item.name.startsWith('.')) continue
170
+ const version = path.join(archive, item.name)
171
+ const previous = await metadata(version)
172
+ const listed = versions.find(entry => entry.version === item.name)
173
+ const directoryDate = /^\d{4}-\d{2}-\d{2}(?=-|$)/.exec(item.name)?.[0]
174
+ const createdAt = listed?.archivedAt || directoryDate || (await fs.stat(version)).birthtime.toISOString()
175
+ history.push({
176
+ version: item.name,
177
+ createdAt,
178
+ timeSource: listed?.archivedAt || directoryDate ? 'archive' : 'directory',
179
+ changes: listed?.changes || [],
180
+ prompts: previous.prompts || {},
181
+ files: (await entries(version)).filter(file => file.isFile() && types[extension(file.name)])
182
+ .map(file => ({ name: file.name, url: url(version, file.name), type: types[extension(file.name)] })),
183
+ story: await read(path.join(version, 'README.md'), ''),
184
+ })
185
+ }
186
+ }
187
+ return {
188
+ ...await describe(dir, groups),
189
+ ...await characterGalleries(dir, data),
190
+ note: typeof data.note === 'string' ? data.note : '',
191
+ savedTags: Array.isArray(data.tags) ? data.tags : [],
192
+ story: await read(path.join(dir, 'README.md'), ''),
193
+ prompts: data.prompts || {},
194
+ history: history.sort((a, b) => b.version.localeCompare(a.version, 'en', { numeric: true })),
195
+ }
196
+ }
197
+
198
+ function nameOf(value) {
199
+ const name = typeof value === 'string' ? value.trim() : ''
200
+ if (!name || !isAssetFolderName(name) || /[/\\:\u0000-\u001f]/.test(name)) {
201
+ throw fail(400, '请输入有效的角色名称')
202
+ }
203
+ return name
204
+ }
205
+
206
+ async function ensureAvailable(dir) {
207
+ if (await fs.lstat(dir).catch(error => {
208
+ if (error.code !== 'ENOENT') throw error
209
+ return null
210
+ })) throw fail(409, '已有同名角色目录')
211
+ }
212
+
213
+ async function writeAtomic(file, contents) {
214
+ const temp = path.join(path.dirname(file), '.' + randomUUID() + '.tmp')
215
+ try {
216
+ await fs.writeFile(temp, contents)
217
+ await fs.rename(temp, file)
218
+ } finally {
219
+ await fs.rm(temp, { force: true })
220
+ }
221
+ }
222
+
223
+ const writeIndex = (dir, data) => writeAtomic(path.join(dir, index), JSON.stringify(data, null, 2) + '\n')
224
+
225
+ async function archiveChanges(dir, data, files, patch) {
226
+ const oldStory = await read(path.join(dir, 'README.md'), null)
227
+ const changed = []
228
+ const previous = []
229
+ if (patch.upload) {
230
+ changed.push(patch.upload.slot)
231
+ const oldFile = files[patch.upload.slot]
232
+ if (oldFile) previous.push(oldFile)
233
+ }
234
+ if (typeof patch.story === 'string' && patch.story !== (oldStory || '')) {
235
+ changed.push('story')
236
+ if (oldStory !== null) previous.push('README.md')
237
+ }
238
+ if (patch.prompts && JSON.stringify(patch.prompts) !== JSON.stringify(data.prompts || {})) {
239
+ changed.push('prompts')
240
+ }
241
+ if (!previous.length && !(changed.includes('prompts') && Object.values(data.prompts || {}).some(Boolean))) return
242
+ const date = new Intl.DateTimeFormat('sv-SE', { timeZone: 'Asia/Shanghai' }).format(new Date())
243
+ const archive = path.join(dir, 'archive')
244
+ await fs.mkdir(archive, { recursive: true })
245
+ if (await fs.realpath(archive) !== archive) throw fail(400, '归档目录必须位于角色文件夹内')
246
+ let sequence = 1
247
+ for (const entry of await entries(archive)) {
248
+ const match = /^\d{4}-\d{2}-\d{2}-v(\d+)$/.exec(entry.name)
249
+ if (match) sequence = Math.max(sequence, Number(match[1]) + 1)
250
+ }
251
+ const version = date + '-v' + String(sequence).padStart(3, '0')
252
+ const destination = path.join(archive, version)
253
+ await fs.mkdir(destination)
254
+ for (const oldFile of previous) await fs.copyFile(path.join(dir, oldFile), path.join(destination, path.basename(oldFile)))
255
+ await writeIndex(destination, data)
256
+ data.history = [...(Array.isArray(data.history) ? data.history : []), { version, changes: changed, archivedAt: new Date().toISOString() }]
257
+ }
258
+
259
+ async function update(dir, patch, groups) {
260
+ const data = await metadata(dir)
261
+ const files = await currentFiles(dir, data)
262
+ const name = 'name' in patch ? nameOf(patch.name) : path.basename(dir)
263
+ const next = path.join(path.dirname(dir), name)
264
+ if (next !== dir) await ensureAvailable(next)
265
+ let uploadFile
266
+ if (patch.upload) {
267
+ const slot = Object.hasOwn(slots, patch.upload.slot) && slots[patch.upload.slot]
268
+ const format = typeof patch.upload.filename === 'string' && extension(patch.upload.filename)
269
+ if (!slot || !slot.formats.includes(format) || typeof patch.upload.base64 !== 'string') {
270
+ throw fail(400, '素材类型不受支持')
271
+ }
272
+ uploadFile = slot.stem + '.' + format
273
+ const folder = path.dirname(path.join(dir, uploadFile))
274
+ await fs.mkdir(folder, { recursive: true })
275
+ if (await fs.realpath(folder) !== folder) throw fail(400, '素材目录必须位于角色文件夹内')
276
+ }
277
+ if ('mainImage' in patch && !['image2d', 'image3d'].includes(patch.mainImage)) throw fail(400, '请选择有效主图')
278
+ if ('note' in patch && typeof patch.note !== 'string') throw fail(400, '备注必须是文本')
279
+ if ('tags' in patch && (!Array.isArray(patch.tags) || patch.tags.some(tag => typeof tag !== 'string'))) {
280
+ throw fail(400, '标签必须是文本数组')
281
+ }
282
+ if (patch.upload && typeof patch.upload.prompt === 'string') {
283
+ patch.prompts = { ...(data.prompts || {}), [patch.upload.slot]: patch.upload.prompt }
284
+ }
285
+ if ('prompts' in patch && (!patch.prompts || typeof patch.prompts !== 'object'
286
+ || Object.entries(patch.prompts).some(([key, value]) => !Object.hasOwn(slots, key) || typeof value !== 'string'))) {
287
+ throw fail(400, '生成词格式无效')
288
+ }
289
+ await archiveChanges(dir, data, files, patch)
290
+ if (uploadFile) {
291
+ await writeAtomic(path.join(dir, uploadFile), Buffer.from(patch.upload.base64, 'base64'))
292
+ data[patch.upload.slot] = uploadFile
293
+ }
294
+ if (typeof patch.story === 'string' && patch.story !== await read(path.join(dir, 'README.md'), '')) {
295
+ await writeAtomic(path.join(dir, 'README.md'), patch.story)
296
+ }
297
+ if (patch.prompts) data.prompts = patch.prompts
298
+ if ('note' in patch) data.note = patch.note
299
+ if ('tags' in patch) {
300
+ const tags = [...new Set(patch.tags.map(tag => tag.trim()).filter(Boolean))]
301
+ const savedTags = Array.isArray(data.tags) ? data.tags : []
302
+ data.tags = tags.filter(tag => !groups.includes(tag) || savedTags.includes(tag))
303
+ const hiddenGroupTags = groups.filter(tag => !tags.includes(tag))
304
+ if (hiddenGroupTags.length) data.hiddenGroupTags = hiddenGroupTags
305
+ else delete data.hiddenGroupTags
306
+ }
307
+ if ('mainImage' in patch) data.mainImage = patch.mainImage
308
+ data.name = name
309
+ data.tags ??= []
310
+ await writeIndex(dir, data)
311
+ if (next !== dir) await fs.rename(dir, next)
312
+ return detail(next, groups)
313
+ }
314
+
315
+ async function body(req) {
316
+ const chunks = []
317
+ let size = 0
318
+ for await (const chunk of req) {
319
+ size += chunk.length
320
+ if (size > 81 * 1024 * 1024) throw fail(413, '素材过大,单次上传上限为 60 MB')
321
+ chunks.push(chunk)
322
+ }
323
+ try {
324
+ return JSON.parse(Buffer.concat(chunks))
325
+ } catch {
326
+ throw fail(400, '请求格式无效')
327
+ }
328
+ }
329
+
330
+ export function characterAssets() {
331
+ let mutations = Promise.resolve()
332
+ return {
333
+ name: 'character-assets',
334
+ configureServer(server) {
335
+ server.middlewares.use(async (req, res, next) => {
336
+ const request = new URL(req.url, 'http://localhost')
337
+ if (!['/api/characters', '/character-media'].includes(request.pathname)) return next()
338
+ try {
339
+ if (req.method === 'GET') await mutations
340
+ if (request.pathname === '/character-media' && req.method === 'GET') {
341
+ const file = path.resolve(root, request.searchParams.get('file') || '')
342
+ const real = await fs.realpath(file).catch(() => '')
343
+ const mime = types[extension(file)]
344
+ if (!inside(root, file) || real !== file || !mime || !(await fs.stat(file)).isFile()) throw fail(404, '素材不存在')
345
+ res.setHeader('Content-Type', mime)
346
+ res.setHeader('Cache-Control', 'no-cache')
347
+ createReadStream(file).on('error', () => res.destroy()).pipe(res)
348
+ return
349
+ }
350
+ const id = request.searchParams.get('id')
351
+ let result
352
+ if (req.method === 'GET') {
353
+ if (id) {
354
+ const asset = await getDirectory(id)
355
+ result = await detail(asset.dir, asset.groups)
356
+ } else {
357
+ result = await list()
358
+ }
359
+ } else if (request.pathname === '/api/characters' && ['POST', 'PATCH', 'DELETE'].includes(req.method)) {
360
+ if (req.headers['x-workbench'] !== 'local') throw fail(403, '请求来源无效')
361
+ const patch = req.method === 'DELETE' ? null : await body(req)
362
+ const operation = mutations.then(async () => {
363
+ if (req.method === 'DELETE') {
364
+ const asset = await getDirectory(id)
365
+ return deleteAssetDirectory(root, asset.dir)
366
+ }
367
+ if (req.method === 'PATCH') {
368
+ const asset = await getDirectory(id)
369
+ return update(asset.dir, patch, asset.groups)
370
+ }
371
+ const name = nameOf(patch.name)
372
+ const dir = path.join(root, name)
373
+ await ensureAvailable(dir)
374
+ await fs.mkdir(dir)
375
+ await fs.mkdir(path.join(dir, 'archive'))
376
+ await fs.mkdir(path.join(dir, 'voice'))
377
+ await fs.mkdir(path.join(dir, 'portraits'))
378
+ await fs.mkdir(path.join(dir, 'skin'))
379
+ await writeAtomic(path.join(dir, 'README.md'), '')
380
+ await writeIndex(dir, { name, tags: [], history: [] })
381
+ return detail(dir)
382
+ })
383
+ mutations = operation.catch(() => {})
384
+ result = await operation
385
+ } else {
386
+ throw fail(405, '请求方法不支持')
387
+ }
388
+ res.setHeader('Content-Type', 'application/json; charset=utf-8')
389
+ res.setHeader('Cache-Control', 'no-store')
390
+ res.end(JSON.stringify(result))
391
+ } catch (error) {
392
+ res.statusCode = error.status || 500
393
+ res.setHeader('Content-Type', 'application/json; charset=utf-8')
394
+ res.end(JSON.stringify({ error: error.message }))
395
+ }
396
+ })
397
+ },
398
+ }
399
+ }