@dickpy/dsh-imagegen 1.0.1 → 1.0.3

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/src/routes.ts CHANGED
@@ -11,7 +11,8 @@ import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'
11
11
  import { SettingsConflictError, settingsNamespace, type SettingsDescriptor } from '@deepseek-ai/dsh-settings'
12
12
  import { generateImage, type UpstreamConfig } from './engine.ts'
13
13
  import { appendHistory, clearHistory, listHistory, readHistoryImage, removeHistory } from './history-store.ts'
14
- import { GENERATE_API, HISTORY_API, IMAGEGEN_SETTINGS_NAMESPACE, SETTINGS_API, type GeneratedImage, type GenerateRequest, type HistoryEntry, type HistoryEntryInput } from './protocol.ts'
14
+ import { checkForUpdate, CURRENT_VERSION, installUpdate } from './updater.ts'
15
+ import { GENERATE_API, HISTORY_API, IMAGEGEN_SETTINGS_NAMESPACE, SETTINGS_API, UPDATE_API, type GeneratedImage, type GenerateRequest, type HistoryEntry, type HistoryEntryInput } from './protocol.ts'
15
16
 
16
17
  /** Cap on JSON request bodies (settings ops and generate payloads are small). */
17
18
  const MAX_JSON_BODY_BYTES = 24 * 1024 * 1024
@@ -304,6 +305,44 @@ export function makeRoutes(deps: ImageGenRoutesDeps): WebRoute[] {
304
305
  }
305
306
  },
306
307
  },
308
+ // ----------------------------------------------- update check
309
+ {
310
+ kind: 'exact',
311
+ path: UPDATE_API.check,
312
+ handler: async (req, res) => {
313
+ if (!guard(req, res, 'POST')) return
314
+ try {
315
+ writeJson(res, 200, { ok: true, update: await checkForUpdate() })
316
+ } catch (error) {
317
+ writeJson(res, 200, { ok: false, code: 'update-check-failed', message: messageOf(error) })
318
+ }
319
+ },
320
+ },
321
+ // ----------------------------------------------- update apply
322
+ {
323
+ kind: 'exact',
324
+ path: UPDATE_API.apply,
325
+ handler: async (req, res) => {
326
+ if (!guard(req, res, 'POST')) return
327
+ const body = await readJsonBody(req)
328
+ const version = body !== undefined && typeof body.version === 'string' ? body.version.trim() : ''
329
+ if (version === '') {
330
+ writeJson(res, 200, { ok: false, code: 'bad-request', message: 'update version is required' })
331
+ return
332
+ }
333
+ try {
334
+ const latest = await checkForUpdate()
335
+ if (!latest.updateAvailable || latest.latestVersion !== version) {
336
+ writeJson(res, 200, { ok: false, code: 'update-not-available', message: `version ${version} is not the latest available release` })
337
+ return
338
+ }
339
+ await installUpdate(version)
340
+ writeJson(res, 200, { ok: true, currentVersion: CURRENT_VERSION, updatedVersion: version, restartRequired: true })
341
+ } catch (error) {
342
+ writeJson(res, 200, { ok: false, code: 'update-failed', message: messageOf(error) })
343
+ }
344
+ },
345
+ },
307
346
  // ----------------------------------------------------- history list
308
347
  {
309
348
  kind: 'exact',
package/src/updater.ts ADDED
@@ -0,0 +1,117 @@
1
+ /** GitHub Release discovery and explicit, user-triggered plugin updates. */
2
+
3
+ import { spawn, type ChildProcess } from 'node:child_process'
4
+ import { PLUGIN_VERSION } from './protocol.ts'
5
+
6
+ /** Keep this in sync with package.json for each published release. */
7
+ export const CURRENT_VERSION = PLUGIN_VERSION
8
+ export const PACKAGE_NAME = '@dickpy/dsh-imagegen'
9
+ export const RELEASES_URL = 'https://api.github.com/repos/dickpy/dsh-imagegen/releases/latest'
10
+
11
+ const CHECK_TIMEOUT_MS = 10_000
12
+ const CACHE_TTL_MS = 15 * 60_000
13
+
14
+ export interface UpdateInfo {
15
+ currentVersion: string
16
+ latestVersion: string
17
+ updateAvailable: boolean
18
+ releaseUrl: string
19
+ publishedAt?: string
20
+ }
21
+
22
+ interface GitHubRelease {
23
+ tag_name?: unknown
24
+ html_url?: unknown
25
+ published_at?: unknown
26
+ draft?: unknown
27
+ prerelease?: unknown
28
+ }
29
+
30
+ let cached: { expiresAt: number; value: UpdateInfo } | undefined
31
+
32
+ /** Compare stable semver triples; returns positive when `left` is newer. */
33
+ export function compareVersions(left: string, right: string): number {
34
+ const parse = (value: string): [number, number, number] => {
35
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(value.trim())
36
+ if (match === null) return [0, 0, 0]
37
+ return [Number(match[1]), Number(match[2]), Number(match[3])]
38
+ }
39
+ const a = parse(left)
40
+ const b = parse(right)
41
+ return a[0] - b[0] || a[1] - b[1] || a[2] - b[2]
42
+ }
43
+
44
+ function normalizedReleaseVersion(tag: unknown): string | undefined {
45
+ if (typeof tag !== 'string' || !/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(tag.trim())) return undefined
46
+ return tag.trim().replace(/^v/, '')
47
+ }
48
+
49
+ /** Read the latest stable GitHub Release, with a short host-side cache. */
50
+ export async function checkForUpdate(fetchFn: typeof fetch = fetch, now = Date.now()): Promise<UpdateInfo> {
51
+ if (cached !== undefined && cached.expiresAt > now) return cached.value
52
+ const response = await fetchFn(RELEASES_URL, {
53
+ headers: {
54
+ accept: 'application/vnd.github+json',
55
+ 'user-agent': 'dsh-imagegen-update-check',
56
+ },
57
+ signal: AbortSignal.timeout(CHECK_TIMEOUT_MS),
58
+ })
59
+ if (!response.ok) throw new Error(`GitHub Releases returned HTTP ${response.status}`)
60
+ const payload: unknown = await response.json()
61
+ if (payload === null || typeof payload !== 'object') throw new Error('GitHub Releases returned malformed JSON')
62
+ const release = payload as GitHubRelease
63
+ if (release.draft === true || release.prerelease === true) throw new Error('latest GitHub Release is not stable')
64
+ const latestVersion = normalizedReleaseVersion(release.tag_name)
65
+ if (latestVersion === undefined) throw new Error('latest GitHub Release has an invalid version tag')
66
+ const releaseUrl = typeof release.html_url === 'string' ? release.html_url : 'https://github.com/dickpy/dsh-imagegen/releases'
67
+ const value: UpdateInfo = {
68
+ currentVersion: CURRENT_VERSION,
69
+ latestVersion,
70
+ updateAvailable: compareVersions(latestVersion, CURRENT_VERSION) > 0,
71
+ releaseUrl,
72
+ ...typeof release.published_at === 'string' ? { publishedAt: release.published_at } : {},
73
+ }
74
+ cached = { expiresAt: now + CACHE_TTL_MS, value }
75
+ return value
76
+ }
77
+
78
+ /** Resolve the profile that launched the current DSH process. */
79
+ export function profileFromProcess(argv: readonly string[] = process.argv, env: NodeJS.ProcessEnv = process.env): string {
80
+ const envProfile = env.DSH_PROFILE?.trim()
81
+ if (envProfile !== undefined && /^[a-zA-Z0-9_-]+$/.test(envProfile)) return envProfile
82
+ const profileIndex = argv.indexOf('--profile')
83
+ const explicit = profileIndex >= 0 ? argv[profileIndex + 1]?.trim() : undefined
84
+ if (explicit !== undefined && /^[a-zA-Z0-9_-]+$/.test(explicit)) return explicit
85
+ if (argv.includes('web')) return 'web'
86
+ return 'web'
87
+ }
88
+
89
+ /** Run the same official command documented for plugin installation. */
90
+ export function installUpdate(
91
+ version: string,
92
+ spawnFn: typeof spawn = spawn,
93
+ argv: readonly string[] = process.argv,
94
+ env: NodeJS.ProcessEnv = process.env,
95
+ ): Promise<void> {
96
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) {
97
+ return Promise.reject(new Error('invalid update version'))
98
+ }
99
+ const profile = profileFromProcess(argv, env)
100
+ const command = process.platform === 'win32' ? 'dsh.cmd' : 'dsh'
101
+ const child = spawnFn(command, ['plugin', '--profile', profile, 'add', `${PACKAGE_NAME}@${version}`], {
102
+ shell: process.platform === 'win32',
103
+ stdio: 'ignore',
104
+ }) as ChildProcess
105
+ return new Promise((resolve, reject) => {
106
+ child.once('error', reject)
107
+ child.once('exit', (code, signal) => {
108
+ if (code === 0) resolve()
109
+ else reject(new Error(signal === null ? `plugin update exited with code ${code ?? 'unknown'}` : `plugin update terminated by ${signal}`))
110
+ })
111
+ })
112
+ }
113
+
114
+ /** Test helper: clear the host-side Release cache. */
115
+ export function clearUpdateCache(): void {
116
+ cached = undefined
117
+ }