dsh-data-window 0.1.2 → 0.1.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.
@@ -18,6 +18,19 @@ const DW_SIDE_MAX = 720
18
18
  const DW_SIDE_DEFAULT = 268
19
19
  const DW_SIDE_KEY = 'dsh-data-window:side-width'
20
20
 
21
+ /** Bounds for the run log at the bottom of the panel, in pixels. */
22
+ const DW_LOG_MIN = 72
23
+ const DW_LOG_DEFAULT = 132
24
+ const DW_LOG_MAX = 560
25
+ const DW_LOG_KEY = 'dsh-data-window:log-height'
26
+
27
+ /** Stored run-log height, clamped so a bad value cannot hide the workbench. */
28
+ function dwReadLogHeight() {
29
+ const raw = Number(globalThis.localStorage?.getItem(DW_LOG_KEY))
30
+ if (!Number.isFinite(raw) || raw <= 0) return DW_LOG_DEFAULT
31
+ return Math.min(DW_LOG_MAX, Math.max(DW_LOG_MIN, raw))
32
+ }
33
+
21
34
  /** Wide layouts collapse the navigation column; below this the toggle is a drawer. */
22
35
  const DW_WIDE_LAYOUT = 1024
23
36
 
@@ -194,6 +207,8 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
194
207
  const [menu, setMenu] = useState(null)
195
208
  const [editorHeight, setEditorHeight] = useState(168)
196
209
  const [sideWidth, setSideWidth] = useState(() => dwReadSideWidth())
210
+ const [logHeight, setLogHeight] = useState(() => dwReadLogHeight())
211
+ const [logDragging, setLogDragging] = useState(false)
197
212
  const [sidebarHidden, setSidebarHidden] = useState(false)
198
213
  const [aiOpen, setAiOpen] = useState(false)
199
214
  const [manualOpen, setManualOpen] = useState(false)
@@ -201,6 +216,8 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
201
216
  const [ddlTarget, setDdlTarget] = useState(null)
202
217
  const [renameTarget, setRenameTarget] = useState(null)
203
218
  const [removeEnvTarget, setRemoveEnvTarget] = useState(null)
219
+ const [favoriteDraft, setFavoriteDraft] = useState(null)
220
+ const [removeFavoriteTarget, setRemoveFavoriteTarget] = useState(null)
204
221
  const aiPrompted = useRef(false)
205
222
  const panelRef = useRef(null)
206
223
  const logRef = useRef(null)
@@ -219,6 +236,12 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
219
236
  if (detected !== '') store.setDetectedRoot(detected)
220
237
  }, [detected, store])
221
238
 
239
+ // Saved statements are shared by every workspace, so they load once when the
240
+ // panel opens rather than on each discovery.
241
+ useEffect(() => {
242
+ void store.loadFavorites()
243
+ }, [store])
244
+
222
245
  // First open of a workspace the rule-based scan cannot read: offer the model
223
246
  // picker instead of leaving the user with an empty tree and no next step. It
224
247
  // asks once per mount and only while no model has been chosen yet.
@@ -293,6 +316,20 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
293
316
  globalThis.localStorage?.setItem(DW_SIDE_KEY, String(DW_SIDE_DEFAULT))
294
317
  }
295
318
 
319
+ /** Keep the run-log height for the next open; release is the write moment. */
320
+ const persistLogHeight = (height) => {
321
+ try {
322
+ globalThis.localStorage?.setItem(DW_LOG_KEY, String(height))
323
+ } catch (error) {
324
+ void error
325
+ }
326
+ }
327
+
328
+ const resetLogHeight = () => {
329
+ setLogHeight(DW_LOG_DEFAULT)
330
+ persistLogHeight(DW_LOG_DEFAULT)
331
+ }
332
+
296
333
  // Requirement 3: one keystroke from the selected table to its create statement.
297
334
  useEffect(() => {
298
335
  const onKey = (event) => {
@@ -388,29 +425,47 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
388
425
  title: sidebarHidden ? tr('showSidebar') : tr('hideSidebar'),
389
426
  'aria-label': sidebarHidden ? tr('showSidebar') : tr('hideSidebar'),
390
427
  }, h(DwIcon, { name: 'panel', size: 13 })),
391
- h('button', {
392
- key: 'refresh',
393
- type: 'button',
394
- className: 'dw-btn',
395
- disabled: state.root === '' || state.refreshing === true || state.phase === 'loading',
396
- onClick: () => void store.loadDiscovery({ refresh: true }),
397
- title: tr('refreshHint'),
398
- }, [
399
- h(DwIcon, { key: 'i', name: state.refreshing === true || state.phase === 'loading' ? 'spinner' : 'refresh', size: 12 }),
400
- h('span', { key: 't' }, tr('refresh')),
401
- ]),
402
428
  ])
403
429
 
404
430
  const selectedTable = state.selectedNode !== null
405
431
  && state.selectedNode !== undefined
406
432
  && (state.selectedNode.kind === 'table' || state.selectedNode.kind === 'view' || state.selectedNode.kind === 'database')
407
433
 
434
+ // The resource manager has two tabs, like DataGrip's Database window: the
435
+ // configured tree and the saved statements. The tab strip sits above the filter
436
+ // so the same search applies to whichever list is showing.
437
+ const treeTab = state.treeTab === 'favorites' ? 'favorites' : 'databases'
438
+ const treeTabButton = (key, icon, label, count) => h('button', {
439
+ key,
440
+ type: 'button',
441
+ role: 'tab',
442
+ 'aria-selected': treeTab === key,
443
+ className: treeTab === key ? 'dw-tree-tab on' : 'dw-tree-tab',
444
+ onClick: () => store.setTreeTab(key),
445
+ }, [
446
+ h(DwIcon, { key: 'i', name: icon, size: 12 }),
447
+ h('span', { key: 'l' }, label),
448
+ typeof count === 'number' && count > 0
449
+ ? h('span', { key: 'c', className: 'dw-tree-tab-count' }, String(count))
450
+ : null,
451
+ ])
452
+
408
453
  const side = h('aside', { key: 'side', className: 'dw-side', style: { width: sideWidth } }, [
409
454
  h('div', { key: 'head', className: 'dw-side-head' }, [
410
455
  h('span', { key: 't' }, tr('treeTitle')),
411
456
  h('span', { key: 'sp', className: 'dw-spacer' }),
412
457
  selectedTable === true ? h('span', { key: 'n' }, tr('ddlShortcutHint')) : null,
413
- // These two belong to the tree, so they live in the tree's own header.
458
+ // These belong to the explorer, so they live in the explorer's own header:
459
+ // re-read the workspace, let a model look at it, or add a connection.
460
+ h('button', {
461
+ key: 'reload-workspace',
462
+ type: 'button',
463
+ className: 'dw-btn dw-btn-icon',
464
+ disabled: state.root === '' || state.refreshing === true || state.phase === 'loading',
465
+ onClick: () => void store.loadDiscovery({ refresh: true }),
466
+ title: tr('refreshHint'),
467
+ 'aria-label': tr('refresh'),
468
+ }, h(DwIcon, { key: 'i', name: state.refreshing === true || state.phase === 'loading' ? 'spinner' : 'refresh', size: 12 })),
414
469
  h('button', {
415
470
  key: 'ai',
416
471
  type: 'button',
@@ -432,12 +487,27 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
432
487
  'aria-label': tr('manualOpen'),
433
488
  }, h(DwIcon, { key: 'i', name: 'plus', size: 12 })),
434
489
  ]),
490
+ h('div', { key: 'tabs', className: 'dw-tree-tabs', role: 'tablist', 'aria-label': tr('treeTabsLabel') }, [
491
+ treeTabButton('databases', 'database', tr('treeTabDatabases')),
492
+ treeTabButton('favorites', 'star', tr('favoritesTitle'), (state.favorites ?? []).length),
493
+ h('span', { key: 'sp', className: 'dw-spacer' }),
494
+ treeTab === 'favorites'
495
+ ? h('button', {
496
+ key: 'reload-favorites',
497
+ type: 'button',
498
+ className: 'dw-btn dw-btn-icon',
499
+ title: tr('favoritesReload'),
500
+ 'aria-label': tr('favoritesReload'),
501
+ onClick: () => void store.loadFavorites({ force: true }),
502
+ }, h(DwIcon, { key: 'i', name: 'refresh', size: 12 }))
503
+ : null,
504
+ ]),
435
505
  h('div', { key: 'filter', style: { padding: '5px 8px', borderBottom: '1px solid var(--dsw-alias-border-l1)' } }, [
436
506
  h('input', {
437
507
  key: 'i',
438
508
  type: 'search',
439
509
  value: state.filter ?? '',
440
- placeholder: tr('filterPlaceholder'),
510
+ placeholder: tr(treeTab === 'favorites' ? 'filterFavoritesPlaceholder' : 'filterPlaceholder'),
441
511
  onChange: (event) => store.patch({ filter: event.target.value }),
442
512
  style: {
443
513
  width: '100%',
@@ -480,7 +550,28 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
480
550
  ]))
481
551
  } else {
482
552
  main = h('div', { key: 'main', className: 'dw-main' }, [
483
- h(DwTabs, { key: 'tabs', store, state, tr }),
553
+ h(DwTabs, {
554
+ key: 'tabs',
555
+ store,
556
+ state,
557
+ tr,
558
+ // A console tab can be collected whole: the tab knows its schema and table,
559
+ // which is exactly what the favorite has to carry.
560
+ onFavorite: (tab) => {
561
+ const sql = String(tab.sql ?? '').trim()
562
+ if (sql === '') {
563
+ store.pushLog('warn', tr('log.noStatement'))
564
+ return
565
+ }
566
+ setFavoriteDraft({
567
+ sql,
568
+ name: '',
569
+ database: tab.database,
570
+ table: dwTabTableName(tab),
571
+ env: tab.env ?? '',
572
+ })
573
+ },
574
+ }),
484
575
  activeTab === undefined
485
576
  ? h(DwEmpty, { key: 'empty', tr, state, onPick: pickWorkspace, onOpenAi: () => setAiOpen(true), onOpenManual: () => setManualOpen(true) })
486
577
  : h(React.Fragment, { key: activeTab.id }, [
@@ -491,6 +582,7 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
491
582
  tr,
492
583
  height: editorHeight,
493
584
  schema: state.schemas?.get(activeTab.dbId),
585
+ favorites: state.favorites ?? [],
494
586
  onRun: (statement) => void store.runActiveTab(statement),
495
587
  }),
496
588
  h(DwDragHandle, {
@@ -505,7 +597,23 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
505
597
  ])
506
598
  }
507
599
 
508
- const log = h('div', { key: 'log', className: `dw-log${state.logOpen === true ? '' : ' dw-log-collapsed'}` }, [
600
+ // The log grows upward; leave the tab strip plus a usable editor/results area
601
+ // above it, and never exceed the fixed ceiling.
602
+ const panelHeight = panelRef.current?.getBoundingClientRect?.().height ?? (globalThis.innerHeight ?? 800)
603
+ const logMax = Math.max(DW_LOG_MIN + 40, Math.min(DW_LOG_MAX, Math.round(panelHeight - 300)))
604
+ // A window that shrank after the height was stored must not push the workbench
605
+ // out of the panel; the stored value is kept for when there is room again.
606
+ const visibleLogHeight = Math.min(logHeight, logMax)
607
+
608
+ const log = h('div', {
609
+ key: 'log',
610
+ className: `dw-log${state.logOpen === true ? '' : ' dw-log-collapsed'}`,
611
+ // An open log follows the stored height; while dragging, the CSS open/close
612
+ // transition must not lag behind the pointer.
613
+ style: state.logOpen === true
614
+ ? { height: visibleLogHeight, transition: logDragging === true ? 'none' : undefined }
615
+ : undefined,
616
+ }, [
509
617
  h('div', { key: 'bar', className: 'dw-log-bar' }, [
510
618
  h('button', {
511
619
  key: 'toggle',
@@ -559,7 +667,18 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
559
667
  left: Math.max(rect === undefined ? 0 : rect.left, left),
560
668
  top: Math.max(rect === undefined ? 0 : rect.top, top),
561
669
  },
562
- }, dwMenuItems(menu.node, store, tr, () => setMenu(null), (node) => setSchemaTarget(node), (node) => setRenameTarget(node), (node) => setRemoveEnvTarget(node), (node) => setDdlTarget(node))),
670
+ }, dwMenuItems(
671
+ menu.node,
672
+ store,
673
+ tr,
674
+ () => setMenu(null),
675
+ (node) => setSchemaTarget(node),
676
+ (node) => setRenameTarget(node),
677
+ (node) => setRemoveEnvTarget(node),
678
+ (node) => setDdlTarget(node),
679
+ (favorite) => setFavoriteDraft({ ...favorite }),
680
+ (favorite) => setRemoveFavoriteTarget(favorite),
681
+ )),
563
682
  ])
564
683
  }
565
684
 
@@ -579,6 +698,23 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
579
698
  }),
580
699
  main,
581
700
  ]),
701
+ state.logOpen === true
702
+ ? h(DwDragHandle, {
703
+ key: 'log-drag',
704
+ value: visibleLogHeight,
705
+ min: DW_LOG_MIN,
706
+ max: logMax,
707
+ invert: true,
708
+ title: tr('resizeLog'),
709
+ onChange: setLogHeight,
710
+ onStart: () => setLogDragging(true),
711
+ onCommit: (height) => {
712
+ setLogDragging(false)
713
+ persistLogHeight(height)
714
+ },
715
+ onReset: resetLogHeight,
716
+ })
717
+ : null,
582
718
  log,
583
719
  menuLayer,
584
720
  aiOpen ? h(DwAiDialog, {
@@ -632,6 +768,30 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
632
768
  instance: schemaTarget,
633
769
  onClose: () => setSchemaTarget(null),
634
770
  }),
771
+ favoriteDraft === null ? null : h(DwFavoriteDialog, {
772
+ key: 'favorite-dialog',
773
+ store,
774
+ tr,
775
+ draft: favoriteDraft,
776
+ onClose: () => setFavoriteDraft(null),
777
+ onSaved: () => setMenu(null),
778
+ }),
779
+ removeFavoriteTarget === null ? null : h(DwConfirmDialog, {
780
+ key: 'remove-favorite-dialog',
781
+ tr,
782
+ title: tr('removeFavoriteTitle'),
783
+ message: tr('removeFavoriteHint', { name: removeFavoriteTarget.name }),
784
+ confirmLabel: tr('removeFavoriteConfirm'),
785
+ onClose: () => setRemoveFavoriteTarget(null),
786
+ onConfirm: async () => {
787
+ try {
788
+ await store.removeFavorite(removeFavoriteTarget.id)
789
+ } catch (error) {
790
+ store.pushLog('error', tr('log.favoriteRemoveFailed', { message: dwExplainFailure(tr, error) }))
791
+ }
792
+ setRemoveFavoriteTarget(null)
793
+ },
794
+ }),
635
795
  ])
636
796
  }
637
797
 
@@ -643,7 +803,7 @@ function dwClock(date) {
643
803
  }
644
804
 
645
805
  /** The context menu of one node. */
646
- function dwMenuItems(node, store, tr, close, openSchemaDialog, openRenameEnv, openRemoveEnv, openDdlDialog) {
806
+ function dwMenuItems(node, store, tr, close, openSchemaDialog, openRenameEnv, openRemoveEnv, openDdlDialog, openFavoriteDialog, confirmRemoveFavorite) {
647
807
  const items = []
648
808
  const add = (key, label, shortcut, run, tone) => items.push(h('button', {
649
809
  key,
@@ -655,7 +815,18 @@ function dwMenuItems(node, store, tr, close, openSchemaDialog, openRenameEnv, op
655
815
  },
656
816
  }, [h('span', { key: 'l' }, label), shortcut === '' ? null : h('span', { key: 's', className: 'dw-menu-shortcut' }, shortcut)]))
657
817
 
658
- if (node.kind === 'table' || node.kind === 'view') {
818
+ if (node.kind === 'favorite') {
819
+ const favorite = node.favorite
820
+ add('open-favorite', tr('menuOpenFavorite'), '', () => store.openFavorite(favorite))
821
+ add('copy-favorite-sql', tr('menuCopyFavoriteSql'), '', () => {
822
+ const write = globalThis.navigator?.clipboard?.writeText?.(String(favorite.sql ?? ''))
823
+ if (write !== undefined) write.then(() => store.pushLog('info', tr('log.favoriteCopied', { name: favorite.name }))).catch(() => undefined)
824
+ })
825
+ add('edit-favorite', tr('menuEditFavorite'), '', () => openFavoriteDialog(favorite))
826
+ add('remove-favorite', tr('menuRemoveFavorite'), '', () => confirmRemoveFavorite(favorite), 'dw-menu-danger')
827
+ } else if (node.kind === 'favoriteDatabase' || node.kind === 'favoriteTable') {
828
+ add('expand', tr('menuExpand'), '', () => void store.toggleNode(node))
829
+ } else if (node.kind === 'table' || node.kind === 'view') {
659
830
  add('ddl', tr('menuDdl'), 'F4', () => openDdlDialog(node))
660
831
  add('data', tr('menuOpenData'), '', () => {
661
832
  const statement = `SELECT *\nFROM \`${node.database}\`.\`${node.table}\`\nLIMIT 100`
@@ -32,6 +32,7 @@ function DwSchemaDialog({ store, tr, instance, onClose }) {
32
32
  useEffect(() => {
33
33
  const onKey = (event) => {
34
34
  if (event.key !== 'Escape' || savingRef.current) return
35
+ if (dwImeComposing(event)) return
35
36
  onClose()
36
37
  }
37
38
  globalThis.addEventListener('keydown', onKey)
@@ -29,6 +29,7 @@ function DwManualDialog({ store, tr, onClose, onSaved }) {
29
29
  useEffect(() => {
30
30
  const onKey = (event) => {
31
31
  if (event.key !== 'Escape' || savingRef.current) return
32
+ if (dwImeComposing(event)) return
32
33
  onClose()
33
34
  }
34
35
  globalThis.addEventListener('keydown', onKey)
@@ -210,6 +211,7 @@ function DwRenameEnvDialog({ store, tr, label, onClose, onRenamed }) {
210
211
  useEffect(() => {
211
212
  const onKey = (event) => {
212
213
  if (event.key !== 'Escape' || savingRef.current) return
214
+ if (dwImeComposing(event)) return
213
215
  onClose()
214
216
  }
215
217
  globalThis.addEventListener('keydown', onKey)
@@ -263,7 +265,9 @@ function DwRenameEnvDialog({ store, tr, label, onClose, onRenamed }) {
263
265
  autoComplete: 'off',
264
266
  onChange: (event) => setValue(event.target.value),
265
267
  onKeyDown: (event) => {
266
- if (event.key === 'Enter') void save()
268
+ if (event.key !== 'Enter') return
269
+ if (dwImeComposing(event)) return
270
+ void save()
267
271
  },
268
272
  }),
269
273
  ]),
@@ -299,6 +303,7 @@ function DwConfirmDialog({ tr, title, message, confirmLabel, onConfirm, onClose
299
303
  useEffect(() => {
300
304
  const onKey = (event) => {
301
305
  if (event.key !== 'Escape' || busyRef.current) return
306
+ if (dwImeComposing(event)) return
302
307
  onClose()
303
308
  }
304
309
  globalThis.addEventListener('keydown', onKey)
@@ -95,6 +95,7 @@ function DwAiDialog({ store, tr, onClose, onManual }) {
95
95
  const onKey = (event) => {
96
96
  if (event.key !== 'Escape') return
97
97
  if (modeRef.current === 'running') return
98
+ if (dwImeComposing(event)) return
98
99
  onClose()
99
100
  }
100
101
  globalThis.addEventListener('keydown', onKey)
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Saved SQL statements.
3
+ *
4
+ * A statement worth keeping is kept with three facts: the name the user gives it,
5
+ * the schema it was written against, and the table it belongs to. The name is what
6
+ * the workbench indexes behind `@`, and the schema/table pair is what lets the
7
+ * resource tree put the statement back where it came from instead of showing one
8
+ * flat list.
9
+ *
10
+ * The store is shared by every workspace, like the tree itself: a statement written
11
+ * in one project is still a statement the user wants in the next one, and the
12
+ * schema/table pair survives a workspace switch because it is a name, not an id.
13
+ * The file is 0600 and written through a temporary file + rename, so a crash cannot
14
+ * leave a torn document and another process can never read it.
15
+ */
16
+ import { randomUUID } from 'node:crypto'
17
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
18
+ import { join } from 'node:path'
19
+
20
+ /** Bump when the document shape changes so old files are ignored. */
21
+ const FAVORITE_VERSION = 1
22
+
23
+ /** One file for the whole machine: the favorites belong to the tree, not a root. */
24
+ const FAVORITES_FILE = 'favorites.json'
25
+
26
+ /** More favorites than this is a runaway script, not a personal collection. */
27
+ const MAX_FAVORITES = 500
28
+
29
+ /** One statement larger than this cannot be indexed into the `@` list sensibly. */
30
+ const MAX_SQL_BYTES = 128 * 1024
31
+
32
+ /** A name is a search key, so it stays short and printable. */
33
+ const MAX_NAME_LENGTH = 80
34
+
35
+ /** MySQL identifiers are at most 64 characters. */
36
+ const MAX_LABEL_LENGTH = 64
37
+
38
+ /** The name as a comparison key: the same name in another case is the same name. */
39
+ function favoriteNameKey(name) {
40
+ return String(name ?? '').trim().toLowerCase()
41
+ }
42
+
43
+ /** Trim, strip NUL and cap one plain text field. */
44
+ function cleanText(value, limit) {
45
+ const text = String(value ?? '').replace(/\u0000/g, '').trim()
46
+ return text.length > limit ? text.slice(0, limit) : text
47
+ }
48
+
49
+ /** Coerce one stored entry; `undefined` when it cannot be rendered or indexed. */
50
+ function normalizeFavorite(value) {
51
+ if (value === null || typeof value !== 'object') return undefined
52
+ const id = String(value.id ?? '').trim()
53
+ const name = cleanText(value.name, MAX_NAME_LENGTH)
54
+ const sql = String(value.sql ?? '').replace(/\u0000/g, '').trim()
55
+ const database = cleanText(value.database, MAX_LABEL_LENGTH)
56
+ if (!/^[A-Za-z0-9-]{8,64}$/.test(id) || name === '' || sql === '' || database === '') return undefined
57
+ if (Buffer.byteLength(sql) > MAX_SQL_BYTES) return undefined
58
+ const createdAt = Number(value.createdAt)
59
+ const updatedAt = Number(value.updatedAt)
60
+ return {
61
+ id,
62
+ name,
63
+ sql,
64
+ database,
65
+ table: cleanText(value.table, MAX_LABEL_LENGTH),
66
+ env: cleanText(value.env, 40),
67
+ createdAt: Number.isFinite(createdAt) && createdAt > 0 ? createdAt : Date.now(),
68
+ updatedAt: Number.isFinite(updatedAt) && updatedAt > 0 ? updatedAt : Date.now(),
69
+ }
70
+ }
71
+
72
+ /** A failure the RPC layer maps to a status code. */
73
+ function favoriteFailure(code, message) {
74
+ const error = new Error(message)
75
+ error.code = code
76
+ return error
77
+ }
78
+
79
+ /** Saved SQL statements, one tiny JSON document for the whole machine. */
80
+ export class FavoriteStore {
81
+ constructor(directory) {
82
+ this.directory = directory
83
+ if (this.directory !== '') mkdirSync(this.directory, { recursive: true, mode: 0o700 })
84
+ }
85
+
86
+ /** The document every favorite lives in. */
87
+ file() {
88
+ return join(this.directory, FAVORITES_FILE)
89
+ }
90
+
91
+ /** Read every favorite; a missing or unreadable file means "none saved yet". */
92
+ list() {
93
+ if (this.directory === '') return { favorites: [] }
94
+ try {
95
+ const parsed = JSON.parse(readFileSync(this.file(), 'utf8'))
96
+ if (parsed?.version !== FAVORITE_VERSION) return { favorites: [] }
97
+ const favorites = []
98
+ for (const raw of Array.isArray(parsed.favorites) ? parsed.favorites : []) {
99
+ const entry = normalizeFavorite(raw)
100
+ if (entry === undefined) continue
101
+ if (favorites.some((existing) => existing.id === entry.id)) continue
102
+ favorites.push(entry)
103
+ }
104
+ return { favorites: favorites.slice(0, MAX_FAVORITES) }
105
+ } catch (error) {
106
+ return { favorites: [] }
107
+ }
108
+ }
109
+
110
+ /** Replace the document atomically, 0600. */
111
+ save(favorites) {
112
+ if (this.directory === '') {
113
+ throw favoriteFailure('favorite-unavailable', 'saved SQL is unavailable in this build')
114
+ }
115
+ const document = JSON.stringify({
116
+ version: FAVORITE_VERSION,
117
+ savedAt: Date.now(),
118
+ favorites: favorites.slice(0, MAX_FAVORITES),
119
+ })
120
+ const file = this.file()
121
+ const temporary = `${file}.${process.pid}.tmp`
122
+ writeFileSync(temporary, document, { mode: 0o600 })
123
+ renameSync(temporary, file)
124
+ return { saved: true, favorites: favorites.length }
125
+ }
126
+
127
+ /**
128
+ * Create or update one favorite.
129
+ *
130
+ * The name is the user-facing identity, so it is unique without regard to case;
131
+ * the id is what an update (rename included) targets. Both are checked here
132
+ * rather than in the Client because two panels can save at the same time.
133
+ */
134
+ upsert(value) {
135
+ const { favorites } = this.list()
136
+ const id = String(value?.id ?? '').trim()
137
+ const name = cleanText(value?.name, MAX_NAME_LENGTH)
138
+ const sql = String(value?.sql ?? '').replace(/\u0000/g, '').trim()
139
+ const database = cleanText(value?.database, MAX_LABEL_LENGTH)
140
+ const table = cleanText(value?.table, MAX_LABEL_LENGTH)
141
+ const env = cleanText(value?.env, 40)
142
+ if (name === '') throw favoriteFailure('invalid-favorite', 'a favorite needs a name')
143
+ if (database === '') throw favoriteFailure('invalid-favorite', 'a favorite needs a database name')
144
+ if (sql === '') throw favoriteFailure('invalid-favorite', 'a favorite needs a statement')
145
+ if (Buffer.byteLength(sql) > MAX_SQL_BYTES) {
146
+ throw favoriteFailure('favorite-too-large', 'the statement is too large to save')
147
+ }
148
+ const key = favoriteNameKey(name)
149
+ const existing = id === '' ? undefined : favorites.find((entry) => entry.id === id)
150
+ if (id !== '' && existing === undefined) {
151
+ throw favoriteFailure('unknown-favorite', 'no saved SQL uses that id')
152
+ }
153
+ const conflict = favorites.find((entry) => entry.id !== existing?.id && favoriteNameKey(entry.name) === key)
154
+ if (conflict !== undefined) {
155
+ throw favoriteFailure('duplicate-favorite', `a saved statement is already named ${conflict.name}`)
156
+ }
157
+ const now = Date.now()
158
+ if (existing === undefined && favorites.length >= MAX_FAVORITES) {
159
+ throw favoriteFailure('favorite-limit', 'too many saved statements')
160
+ }
161
+ const favorite = {
162
+ id: existing?.id ?? randomUUID(),
163
+ name,
164
+ sql,
165
+ database,
166
+ table,
167
+ env,
168
+ createdAt: existing?.createdAt ?? now,
169
+ updatedAt: now,
170
+ }
171
+ const next = existing === undefined
172
+ ? [...favorites, favorite]
173
+ : favorites.map((entry) => (entry.id === existing.id ? favorite : entry))
174
+ this.save(next)
175
+ return { favorite }
176
+ }
177
+
178
+ /** Drop one favorite; returns whether it was there. */
179
+ remove(id) {
180
+ const target = String(id ?? '').trim()
181
+ if (target === '') return { removed: false }
182
+ const { favorites } = this.list()
183
+ const next = favorites.filter((entry) => entry.id !== target)
184
+ if (next.length === favorites.length) return { removed: false }
185
+ this.save(next)
186
+ return { removed: true }
187
+ }
188
+ }
package/src/host/rpc.js CHANGED
@@ -12,6 +12,7 @@ import { ConnectionCatalog } from './catalog.js'
12
12
  import { DiscoveryCache, fingerprint } from './cache.js'
13
13
  import { ConsoleStore } from './consoles.js'
14
14
  import { discoverProject } from './discovery.js'
15
+ import { FavoriteStore } from './favorites.js'
15
16
  import { ManualStore, manualEnvironments, normalizeManualEntry } from './manual.js'
16
17
  import { stableId } from './discovery.js'
17
18
  import { RememberedStore } from './remembered.js'
@@ -55,6 +56,9 @@ export class DataController {
55
56
  // resource tree is one tree, so its user-owned parts cannot be per workspace.
56
57
  this.manual = options.manual ?? new ManualStore(options.cacheDirectory === undefined || options.cacheDirectory === '' ? '' : join(options.cacheDirectory, 'manual'), { shared: true })
57
58
  this.remembered = options.remembered ?? new RememberedStore(options.cacheDirectory === undefined || options.cacheDirectory === '' ? '' : join(options.cacheDirectory, 'remembered'), { shared: true })
59
+ // Saved statements are shared like the tree: a name and a schema/table pair
60
+ // outlive the workspace that produced them.
61
+ this.favoriteStore = options.favorites ?? new FavoriteStore(options.cacheDirectory === undefined || options.cacheDirectory === '' ? '' : join(options.cacheDirectory, 'favorites'))
58
62
  this.catalog = options.catalog ?? new ConnectionCatalog(options.cacheDirectory ?? '')
59
63
  // `llm` is a getter: the Host may provide the LLM service after this plugin
60
64
  // activates, and the fallback must not pin a service that is still arriving.
@@ -242,6 +246,29 @@ export class DataController {
242
246
  return { forgotten: this.remembered.remove(root, entry) }
243
247
  }
244
248
 
249
+ /** Every saved statement; the Client groups them by schema and table. */
250
+ favorites() {
251
+ return this.favoriteStore.list()
252
+ }
253
+
254
+ /** Create or update one saved statement under a unique name. */
255
+ saveFavorite(payload = {}) {
256
+ try {
257
+ return this.favoriteStore.upsert(payload.favorite ?? payload)
258
+ } catch (error) {
259
+ throw favoriteRouteFailure(error)
260
+ }
261
+ }
262
+
263
+ /** Forget one saved statement by id. */
264
+ removeFavorite(payload = {}) {
265
+ try {
266
+ return this.favoriteStore.remove(payload.id)
267
+ } catch (error) {
268
+ throw favoriteRouteFailure(error)
269
+ }
270
+ }
271
+
245
272
  /**
246
273
  * Save one manually entered connection after proving it.
247
274
  *
@@ -421,6 +448,12 @@ export class DataController {
421
448
  return this.rememberDatabase(payload)
422
449
  case 'forgetDatabase':
423
450
  return this.forgetDatabase(payload)
451
+ case 'favorites':
452
+ return this.favorites()
453
+ case 'saveFavorite':
454
+ return this.saveFavorite(payload)
455
+ case 'removeFavorite':
456
+ return this.removeFavorite(payload)
424
457
  case 'selectDatabases':
425
458
  return this.selectDatabases(payload)
426
459
  case 'ping':
@@ -473,6 +506,24 @@ export class RouteFailure extends Error {
473
506
  }
474
507
  }
475
508
 
509
+ /**
510
+ * Map one saved-SQL failure to the status the route should answer.
511
+ *
512
+ * A duplicate name is the one failure the user can fix in the dialog, so it gets
513
+ * its own code; the Client turns it into a sentence instead of an enum.
514
+ */
515
+ function favoriteRouteFailure(error) {
516
+ const code = typeof error?.code === 'string' ? error.code : 'favorite-failed'
517
+ const status = code === 'duplicate-favorite'
518
+ ? 409
519
+ : code === 'unknown-favorite'
520
+ ? 404
521
+ : code === 'favorite-unavailable'
522
+ ? 503
523
+ : 400
524
+ return new RouteFailure(status, code, error?.message ?? String(error))
525
+ }
526
+
476
527
  /** Map any thrown value into the shape the route writes. */
477
528
  export function toRouteError(error) {
478
529
  if (error instanceof RouteFailure) return { status: error.status, code: error.code, message: error.message }