@linxin666/dsh-pet 0.4.4 → 0.4.6

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 (54) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +46 -6
  3. package/README.zh.md +46 -6
  4. package/lib/client.js +244 -47
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +287 -28
  7. package/lib/types/announce.d.ts +16 -0
  8. package/lib/types/announce.d.ts.map +1 -1
  9. package/lib/types/announce.js +16 -0
  10. package/lib/types/client/PetDockEntry.d.ts +6 -0
  11. package/lib/types/client/PetDockEntry.d.ts.map +1 -1
  12. package/lib/types/client/PetDockEntry.js +1 -1
  13. package/lib/types/client/PetSettingsCard.d.ts +4 -0
  14. package/lib/types/client/PetSettingsCard.d.ts.map +1 -1
  15. package/lib/types/client/PetSettingsCard.js +16 -1
  16. package/lib/types/client/PetSprite.d.ts +7 -0
  17. package/lib/types/client/PetSprite.d.ts.map +1 -1
  18. package/lib/types/client/PetSprite.js +23 -13
  19. package/lib/types/client/index.d.ts +2 -0
  20. package/lib/types/client/index.d.ts.map +1 -1
  21. package/lib/types/client/index.js +224 -28
  22. package/lib/types/client/locales.d.ts +4 -0
  23. package/lib/types/client/locales.d.ts.map +1 -1
  24. package/lib/types/client/locales.js +4 -0
  25. package/lib/types/index.d.ts +14 -3
  26. package/lib/types/index.d.ts.map +1 -1
  27. package/lib/types/index.js +32 -3
  28. package/lib/types/panel-actions.d.ts +96 -0
  29. package/lib/types/panel-actions.d.ts.map +1 -0
  30. package/lib/types/panel-actions.js +134 -0
  31. package/lib/types/routes.d.ts.map +1 -1
  32. package/lib/types/routes.js +10 -0
  33. package/lib/types/service.d.ts +137 -9
  34. package/lib/types/service.d.ts.map +1 -1
  35. package/lib/types/service.js +163 -21
  36. package/package.json +1 -1
  37. package/src/announce.ts +17 -0
  38. package/src/client/PetDockEntry.test.tsx +1 -0
  39. package/src/client/PetDockEntry.tsx +7 -0
  40. package/src/client/PetSettingsCard.test.tsx +88 -0
  41. package/src/client/PetSettingsCard.tsx +31 -0
  42. package/src/client/PetSprite.test.tsx +197 -0
  43. package/src/client/PetSprite.tsx +56 -12
  44. package/src/client/index.test.tsx +152 -4
  45. package/src/client/index.ts +228 -29
  46. package/src/client/locales.ts +4 -0
  47. package/src/index.test.ts +22 -0
  48. package/src/index.ts +45 -3
  49. package/src/panel-actions.test.ts +130 -0
  50. package/src/panel-actions.ts +182 -0
  51. package/src/registry.test.ts +11 -1
  52. package/src/routes.ts +9 -0
  53. package/src/service.test.ts +128 -0
  54. package/src/service.ts +218 -24
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Hover-panel action contract — the extension point a sibling plugin uses to
3
+ * add its own button to the pet's floating hover panel (issue #6).
4
+ *
5
+ * A plugin registers one action in process through the pet service
6
+ * (`ctx.pet.registerPanelAction({ id, label, onSelect })`); the host validates
7
+ * it into a bounded view, serves the registered actions in the state snapshot
8
+ * (`PetStateView.panelActions`), and the browser half renders one button per
9
+ * entry at the end of the panel's action row. A click travels back through
10
+ * `POST /api/pet/panel-action`, which dispatches to the registering plugin's
11
+ * own callback — the pet owns the row, the plugin owns what the button does.
12
+ *
13
+ * The validation and the registry live in this pure module so the contract has
14
+ * exactly one home and stays testable without the cordis service.
15
+ * @module @linxin666/dsh-pet/panel-actions
16
+ */
17
+
18
+ /** How many plugin actions one hover panel can carry at most. */
19
+ export const MAX_PANEL_ACTIONS = 8
20
+
21
+ /**
22
+ * Action id grammar: a lowercase id in the shape pet and decoration ids use
23
+ * (`^` + kebab/dot segments). The id is what a click travels back on, so it
24
+ * has to be stable, addressable and free of separators the wire would treat as
25
+ * structure.
26
+ */
27
+ const ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/
28
+
29
+ /**
30
+ * Label bound. The action row is compact and wraps beyond a few characters per
31
+ * button, so a plugin names its action (换装, Quota) rather than a sentence;
32
+ * the optional title carries the longer explanation as a tooltip.
33
+ */
34
+ const LABEL_MAX = 24
35
+
36
+ /** Title (tooltip) bound; the same reason voice-pack labels are bounded. */
37
+ const TITLE_MAX = 80
38
+
39
+ /** One registered action as the browser half renders it. */
40
+ export interface PetPanelActionView {
41
+ /** Registration id; the click dispatches back on it. */
42
+ id: string
43
+ /** Button label. */
44
+ label: string
45
+ /** Optional tooltip (the label's longer explanation). */
46
+ title?: string
47
+ /** Sort key within the registered block; ties break on id. */
48
+ order: number
49
+ }
50
+
51
+ /**
52
+ * What a panel action click knows about the pet at the moment it arrives. The
53
+ * registering plugin may read more off the service (`selectedPetId()`), so this
54
+ * stays a read-only snapshot rather than a live handle.
55
+ */
56
+ export interface PetPanelActionContext {
57
+ /** The selected pet id when the click arrived. */
58
+ petId: string
59
+ }
60
+
61
+ /** The callback a registration carries; a click invokes it in the host. */
62
+ export type PetPanelActionHandler = (context: PetPanelActionContext) => void | Promise<void>
63
+
64
+ /** One action a sibling plugin registers into the panel's action row. */
65
+ export interface PetPanelActionRegistration {
66
+ /** Unique, stable id (kebab-case); re-registering the same id replaces it. */
67
+ id: string
68
+ /** Button label (bounded). */
69
+ label: string
70
+ /** Optional tooltip rendered as the button's `title`. */
71
+ title?: string
72
+ /** Sort key within the registered block (default 0; ascending, ties on id). */
73
+ order?: number
74
+ /** Invoked in the host when the browser half dispatches this action. */
75
+ onSelect: PetPanelActionHandler
76
+ }
77
+
78
+ /** A validated registration: the wire view plus the host-side callback. */
79
+ interface PanelActionEntry {
80
+ view: PetPanelActionView
81
+ onSelect: PetPanelActionHandler
82
+ }
83
+
84
+ function boundedString(value: unknown, max: number): string | undefined {
85
+ if (typeof value !== 'string') return undefined
86
+ const trimmed = value.trim()
87
+ if (trimmed === '') return undefined
88
+ return trimmed.length <= max ? trimmed : trimmed.slice(0, max)
89
+ }
90
+
91
+ /**
92
+ * Validate one registration. Returns undefined — never throws — when the shape
93
+ * is unusable: the id must match the id grammar and the label must survive
94
+ * truncation, so a click can always be dispatched back to a known row.
95
+ * @param input - the registration a sibling plugin passed to the service.
96
+ * @returns the wire view, or undefined when the registration is malformed.
97
+ */
98
+ export function normalizePanelAction(input: unknown): PetPanelActionView | undefined {
99
+ if (typeof input !== 'object' || input === null) return undefined
100
+ const data = input as Record<string, unknown>
101
+ // The id is an identity, not copy: an over-long one is refused rather than
102
+ // truncated, because truncating it could silently collapse two plugins'
103
+ // registrations onto one row.
104
+ const id = typeof data.id === 'string' ? data.id.trim() : undefined
105
+ if (id === undefined || !ID_PATTERN.test(id)) return undefined
106
+ const label = boundedString(data.label, LABEL_MAX)
107
+ if (label === undefined) return undefined
108
+ const title = boundedString(data.title, TITLE_MAX)
109
+ const order = typeof data.order === 'number' && Number.isFinite(data.order) ? data.order : 0
110
+ return {
111
+ id,
112
+ label,
113
+ ...(title === undefined ? {} : { title }),
114
+ order,
115
+ }
116
+ }
117
+
118
+ /**
119
+ * The panel's action registry: one bounded, ordered table of plugin actions.
120
+ *
121
+ * Registration is id-wins (a later registration of the same id replaces the
122
+ * earlier one, and the superseded disposer stops touching the table so a
123
+ * disposing plugin can never remove the action that replaced it). The table is
124
+ * in-memory only — it dies with the pet service fiber — and every entry is
125
+ * reclaimed by the disposer the registering plugin runs with its own fiber.
126
+ */
127
+ export class PanelActionRegistry {
128
+ private readonly actions = new Map<string, PanelActionEntry>()
129
+
130
+ /**
131
+ * Register one action.
132
+ * @param input - the registration a sibling plugin passed to the service.
133
+ * @returns a disposer removing this registration.
134
+ * @throws when the registration is malformed. Unlike `announce` — a hot path
135
+ * whose payload a caller may build from untrusted data — a registration is
136
+ * built once at the registering plugin's own apply, so a bad id or label is a
137
+ * wiring mistake that should fail where it was written.
138
+ */
139
+ register(input: unknown): () => void {
140
+ const registration = (typeof input === 'object' && input !== null ? input : {}) as PetPanelActionRegistration
141
+ const view = normalizePanelAction(registration)
142
+ if (view === undefined) throw new Error('[dsh-pet] invalid panel action: id and label are required')
143
+ if (typeof registration.onSelect !== 'function') {
144
+ throw new Error('[dsh-pet] invalid panel action: onSelect must be a function')
145
+ }
146
+ if (!this.actions.has(view.id) && this.actions.size >= MAX_PANEL_ACTIONS) {
147
+ throw new Error('[dsh-pet] panel action limit reached: ' + MAX_PANEL_ACTIONS)
148
+ }
149
+ const entry: PanelActionEntry = { view, onSelect: registration.onSelect }
150
+ this.actions.set(view.id, entry)
151
+ return () => {
152
+ // Only the registration that still owns the id may clear it.
153
+ if (this.actions.get(view.id) === entry) this.actions.delete(view.id)
154
+ }
155
+ }
156
+
157
+ /** The registered actions as the state view serves them, in render order. */
158
+ views(): PetPanelActionView[] {
159
+ return [...this.actions.values()]
160
+ .map(entry => entry.view)
161
+ .sort((a, b) => a.order - b.order || a.id.localeCompare(b.id))
162
+ }
163
+
164
+ /**
165
+ * Dispatch a click to the plugin that registered this id.
166
+ * @param id - the id the browser half reported.
167
+ * @param context - what the pet looked like when the click arrived.
168
+ * @returns whether the id was registered. A handler that throws rejects:
169
+ * the caller decides how a sibling plugin's failure is reported.
170
+ */
171
+ async select(id: string, context: PetPanelActionContext): Promise<boolean> {
172
+ const entry = this.actions.get(id)
173
+ if (entry === undefined) return false
174
+ await entry.onSelect(context)
175
+ return true
176
+ }
177
+
178
+ /** Drop every registration (service teardown; tests). */
179
+ clear(): void {
180
+ this.actions.clear()
181
+ }
182
+ }
@@ -315,7 +315,8 @@ describe('loadPetRegistry', () => {
315
315
  })
316
316
 
317
317
  // The repo checkout also resolves doro and miku (frames2d gameplay pets),
318
- // jyn (frames2d gameplay pet) and starry-doll (community sprite2d pet) from
318
+ // jyn and jyn-foxtail (frames2d gameplay pets), long-niang (sprite2d pet)
319
+ // and starry-doll (community sprite2d pet) from
319
320
  // assets/; the npm files whitelist excludes them (Workshop delivery), so
320
321
  // npm installs see the atlas pets until a Workshop install lands them
321
322
  // under $DSH_HOME/pets. blue-throated-bee-eater ships bundled alongside
@@ -324,6 +325,8 @@ describe('loadPetRegistry', () => {
324
325
  'blue-throated-bee-eater',
325
326
  'doro',
326
327
  'jyn',
328
+ 'jyn-foxtail',
329
+ 'long-niang',
327
330
  'miku',
328
331
  'ouo-neko',
329
332
  'starry-doll',
@@ -341,6 +344,13 @@ describe('loadPetRegistry', () => {
341
344
  displayName: '女仆鲸鱼娘',
342
345
  renderer: 'frames2d',
343
346
  })
347
+ expect(registry.byId('long-niang')).toMatchObject({
348
+ displayName: '龙娘',
349
+ atlasRows: 11,
350
+ columns: 8,
351
+ rows: [6, 8, 8, 4, 5, 8, 6, 6, 6],
352
+ })
353
+ expect(existsSync(petAtlasFile(registry.byId('long-niang')!))).toBe(true)
344
354
  expect(registry.byId('ouo-neko')).toMatchObject({
345
355
  displayName: 'OUO Neko',
346
356
  atlasRows: 11,
package/src/routes.ts CHANGED
@@ -613,6 +613,15 @@ export function makePetRoutes(deps: { service: PetService; ctx: Context; assetCa
613
613
  if (typeof petId !== 'string') return Promise.reject(new Error('invalid-pet'))
614
614
  return service.setPetId(petId)
615
615
  }),
616
+ // Hover-panel action click (issue #6): the browser half owns no plugin
617
+ // callbacks, so a click on a registered action travels back here and the
618
+ // service dispatches it to the plugin that registered it. Same loopback /
619
+ // paired-device guard as every other endpoint in this family.
620
+ postRoute(ctx, PET_API_PREFIX + '/panel-action', (body) => {
621
+ const id = body.id
622
+ if (typeof id !== 'string') return Promise.reject(new Error('invalid-panel-action'))
623
+ return service.selectPanelAction(id)
624
+ }),
616
625
  // Gameplay verbs (miku-pet generalization): touch rolls a named zone's
617
626
  // branch; the omitted-zone form is the plain-click boost during a touch
618
627
  // animation. Mode/tick/buy drive the work, sleep and shop loops.
@@ -0,0 +1,128 @@
1
+ /**
2
+ * The ledger's remark pools are fed from two layers: the pet manifest's own
3
+ * pools (`remarks` in pet.json) and the voice packs (a pet directory's
4
+ * voice.json over the global `$DSH_HOME/pets/.voice.json`). The service seats
5
+ * both layers on startup, on a pet switch, and whenever the settings surface
6
+ * applies a committed section. A call site that passed only the manifest layer
7
+ * dropped every voice-pack line, so a pet whose remarks a voice pack had
8
+ * translated answered from the built-in pools again as soon as the settings
9
+ * surface applied - which is immediately, since it applies on every change.
10
+ */
11
+ import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
12
+ import { tmpdir } from 'node:os'
13
+ import { join } from 'node:path'
14
+ import type { Context } from '@deepseek-ai/cordis'
15
+ import { describe, expect, it } from 'vitest'
16
+ import { loadPetRegistry, petPackageRoot } from './registry.ts'
17
+ import { PetService, type PetSettingsSection } from './service.ts'
18
+
19
+ function tempDir(): string {
20
+ return mkdtempSync(join(tmpdir(), 'dsh-pet-service-'))
21
+ }
22
+
23
+ /** A root context stub: the service registers itself and listens for events. */
24
+ function fakeRootContext(): Context {
25
+ return {
26
+ reflect: { provide: () => {} },
27
+ on: () => () => {},
28
+ get: () => undefined,
29
+ } as unknown as Context
30
+ }
31
+
32
+ /**
33
+ * A service over the shipped pets plus one temporary user directory carrying the
34
+ * given voice-pack remark pools. `petsDir` is disabled so the legacy hatch-pet
35
+ * source cannot leak the machine's own pets into the fixture.
36
+ */
37
+ function serviceWithVoicePack(remarks: Record<string, string[]>): PetService {
38
+ const petsDir = tempDir()
39
+ writeFileSync(join(petsDir, '.voice.json'), JSON.stringify({ voicePackVersion: 1, remarks }))
40
+ const registry = loadPetRegistry({
41
+ packageRoot: petPackageRoot(import.meta.url),
42
+ petsDir: '',
43
+ dshPetsDir: petsDir,
44
+ })
45
+ return new PetService(fakeRootContext(), { registry, persistDir: tempDir() })
46
+ }
47
+
48
+ /**
49
+ * A service over the shipped pets plus one temporary pet directory whose pet.json
50
+ * declares no remark pools and whose voice.json carries them - the writing the
51
+ * voice-pack docs recommend (a pet's lines live in one place). `petsDir` is
52
+ * disabled so the legacy hatch-pet source cannot leak the machine's own pets.
53
+ */
54
+ function serviceWithPetVoicePack(id: string, remarks: Record<string, string[]>): PetService {
55
+ const petsDir = tempDir()
56
+ const petDir = join(petsDir, id)
57
+ mkdirSync(petDir, { recursive: true })
58
+ writeFileSync(join(petDir, 'pet.json'), JSON.stringify({
59
+ petManifestVersion: 2,
60
+ id,
61
+ displayName: 'Mumbler',
62
+ license: 'CC0-1.0',
63
+ renderer: 'sprite2d',
64
+ sprite2d: { spritesheetPath: 'spritesheet.webp' },
65
+ }), 'utf8')
66
+ writeFileSync(join(petDir, 'spritesheet.webp'), 'webp', 'utf8')
67
+ writeFileSync(join(petDir, 'voice.json'), JSON.stringify({ voicePackVersion: 1, remarks }), 'utf8')
68
+ const registry = loadPetRegistry({
69
+ packageRoot: petPackageRoot(import.meta.url),
70
+ petsDir: '',
71
+ dshPetsDir: petsDir,
72
+ })
73
+ return new PetService(fakeRootContext(), { registry, persistDir: tempDir() })
74
+ }
75
+
76
+ /** The display fields the settings surface always commits. */
77
+ function section(petId: string): PetSettingsSection {
78
+ return { petId, visible: true, size: 160, right: 24, bottom: 20 }
79
+ }
80
+
81
+ describe('PetService remark layers', () => {
82
+ it('user keeps the voice-pack remarks after the settings surface applies a section', async () => {
83
+ const voice = { pet: ['Голос: погладили'], noTreats: ['Голос: нет угощений'] }
84
+ const service = serviceWithVoicePack(voice)
85
+
86
+ // The startup path seats both layers: the first petting answers from the
87
+ // voice pack.
88
+ expect((await service.interact('pet')).reaction).toBe(voice.pet[0])
89
+
90
+ // Applying a section re-seats the pools. The voice layer must survive it;
91
+ // this is the regression: the manifest layers alone came back, so the pet
92
+ // answered from the built-in pools again.
93
+ service.applySettingsSection(section(service.selectedPetId()))
94
+ expect((await service.interact('feed')).reaction).toBe(voice.noTreats[0])
95
+ })
96
+
97
+ it('user keeps the voice-pack remarks after switching pets through the RPC', async () => {
98
+ const voice = { pet: ['Голос: погладили'], noTreats: ['Голос: нет угощений'] }
99
+ const service = serviceWithVoicePack(voice)
100
+ // A pet whose own manifest declares no remark pools: the voice pack is its
101
+ // only layer. A manifest-declared pool outranks the voice packs by contract
102
+ // (RemarkPicker: manifest, then voice, then built-in), so such a pet is not
103
+ // what this case pins.
104
+ const other = service
105
+ .registrySnapshot()
106
+ .entries
107
+ .find(entry => entry.id !== service.selectedPetId() && entry.remarks === undefined)
108
+
109
+ expect(other).toBeDefined()
110
+ expect(await service.setPetId(other!.id)).toEqual({ ok: true, petId: other!.id })
111
+ expect((await service.interact('feed')).reaction).toBe(voice.noTreats[0])
112
+ })
113
+
114
+ it('user keeps a pet-directory voice pack remarks after the settings surface applies a section', async () => {
115
+ const voice = { pet: ['呼……好多了'], noTreats: ['现在不困啦~'] }
116
+ const service = serviceWithPetVoicePack('mumbler', voice)
117
+
118
+ // The reported repro (issue #10): the pet declares no remarks in pet.json,
119
+ // so its own voice pack is the only layer, and the settings surface applies
120
+ // a committed section on every change - that apply seats the pet and its
121
+ // pools. The voice layer has to survive it, or the pet answers from the
122
+ // built-in pools while its panel copy stays translated.
123
+ service.applySettingsSection(section('mumbler'))
124
+ expect(service.selectedPetId()).toBe('mumbler')
125
+ expect((await service.interact('pet')).reaction).toBe(voice.pet[0])
126
+ expect((await service.interact('feed')).reaction).toBe(voice.noTreats[0])
127
+ })
128
+ })