dsh-tiddlywiki 0.28.7 → 0.28.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.
Files changed (52) hide show
  1. package/README.md +1 -0
  2. package/docs/CHANGELOG.md +1 -0
  3. package/docs/features.md +4 -0
  4. package/docs/usage.md +13 -3
  5. package/lib/client.js +63 -27
  6. package/lib/index.js +10655 -10188
  7. package/lib/index.js.map +1 -1
  8. package/package.json +2 -2
  9. package/src/client/dom.ts +26 -0
  10. package/src/client/index.ts +14 -0
  11. package/src/client/note-widget-draft.ts +154 -0
  12. package/src/client/note-widget-tags.ts +184 -0
  13. package/src/client/note-widget-upload.ts +50 -0
  14. package/src/client/note-widget.ts +19 -348
  15. package/src/client/panel.ts +12 -3
  16. package/src/client/render-fetch.ts +11 -4
  17. package/src/client/scope-seat.ts +117 -0
  18. package/src/client/session-summary.ts +29 -7
  19. package/src/client/settings-icon-picker.ts +238 -0
  20. package/src/client/settings-page-catalog.ts +578 -0
  21. package/src/client/settings-page-config.ts +445 -0
  22. package/src/client/settings-page-runtime.ts +149 -0
  23. package/src/client/settings-page-wikis.ts +432 -0
  24. package/src/client/settings-page.ts +127 -1425
  25. package/src/client/styles.ts +36 -0
  26. package/src/client/tool-views.ts +170 -36
  27. package/src/client/wiki-icon.generated.ts +97 -0
  28. package/src/client/wiki-icon.ts +50 -15
  29. package/src/client/wiki-scope-dock.ts +56 -2
  30. package/src/client/wiki-scope.ts +98 -0
  31. package/src/host/admin-catalog.ts +488 -0
  32. package/src/host/admin-routes.ts +670 -0
  33. package/src/host/admin-secrets.ts +119 -0
  34. package/src/host/admin.ts +3 -1244
  35. package/src/host/clip-bridge.ts +24 -1
  36. package/src/host/config.ts +10 -2
  37. package/src/host/routes-session.ts +617 -0
  38. package/src/host/routes-tw-proxy.ts +390 -0
  39. package/src/host/routes.ts +77 -829
  40. package/src/host/tools-attach.ts +151 -0
  41. package/src/host/tools-git.ts +213 -0
  42. package/src/host/tools-notes.ts +672 -0
  43. package/src/host/tools-read.ts +421 -0
  44. package/src/host/tools-support.ts +513 -0
  45. package/src/host/tools.ts +33 -1814
  46. package/src/host/wiki-registry.ts +25 -4
  47. package/src/host/wiki.ts +55 -5
  48. package/src/index-clip.ts +142 -0
  49. package/src/index-git.ts +196 -0
  50. package/src/index-prompt.ts +139 -0
  51. package/src/index-wikis.ts +353 -0
  52. package/src/index.ts +89 -429
@@ -0,0 +1,353 @@
1
+ /**
2
+ * dsh-tiddlywiki — host half: the knowledge-base VIEW / LOCATION surface.
3
+ *
4
+ * Split out of index.ts (v0.28.8) because these helpers are a self-contained
5
+ * sub-surface: they only read the farm / the control file / the legacy pointer
6
+ * file and never touch the tool registry, the prompt or the routes. index.ts
7
+ * still OWNS the mutable state (the farm, the control-file cache, the
8
+ * `switching` single-flight guard, `disposed`) and hands it in through the
9
+ * `deps` object below — the plugin entry stays the single place where that
10
+ * state lives, so a wiki switch cannot end up with two owners.
11
+ *
12
+ * The factory shape (not a class, not free functions) is deliberate: every hop
13
+ * is an explicit accessor, so this module cannot reach into closure state it
14
+ * cannot see. That is also what keeps the move behaviour-free.
15
+ *
16
+ * @module dsh-tiddlywiki/index-wikis
17
+ */
18
+ import { dshHomePath } from './sdk.ts'
19
+ import type { AdminWikisView } from './host/admin.ts'
20
+ import { isInsidePath, pathComparisonKey } from './host/path-key.ts'
21
+ import {
22
+ clearLocationState,
23
+ expandEnvPath,
24
+ listWikiCandidates,
25
+ locationPath,
26
+ normalizeLocation,
27
+ readLocationState,
28
+ writeLocationState,
29
+ type WikiLocation,
30
+ type WikiLocationInfo,
31
+ type WikiLocationSource,
32
+ } from './host/wiki-location.ts'
33
+ import { switchWiki, type WikiSwitchResult } from './host/wiki-switch.ts'
34
+ import {
35
+ defaultEntry,
36
+ entryPath,
37
+ validateRegistry,
38
+ writeRegistry,
39
+ type WikiEntry,
40
+ type WikiRegistry,
41
+ } from './host/wiki-registry.ts'
42
+ import type { WikiFarm } from './host/wiki-farm.ts'
43
+ import type { WikiInstance } from './host/wiki-instance.ts'
44
+ import { proxyBaseFor } from './host/wiki.ts'
45
+ import type { TiddlywikiConfig } from './index.ts'
46
+
47
+ /**
48
+ * Resolve the DEFAULT wikiRoot: explicit config (env-expanded) else
49
+ * $DSH_HOME/tiddlywiki. The runtime pointer file can override it — see
50
+ * `readLocationState()` in host/wiki-location.ts.
51
+ */
52
+ export function resolveWikiRoot(config: TiddlywikiConfig): string {
53
+ if (config.wikiRoot !== undefined && config.wikiRoot.trim().length > 0) {
54
+ return expandEnvPath(config.wikiRoot.trim())
55
+ }
56
+ return dshHomePath('tiddlywiki')
57
+ }
58
+
59
+ /** The farm, or undefined until the startup task has read the control file. */
60
+ type FarmGetter = () => WikiFarm<WikiInstance> | undefined
61
+
62
+ /** Everything the view/location surface reads from the plugin closure. */
63
+ export interface WikiViewsDeps {
64
+ /** The RAW cordis `config:` block (the single-mode source question reads it). */
65
+ rawConfig: () => TiddlywikiConfig
66
+ /** The cordis-level default location (last resort in the registry chain). */
67
+ defaultLocation: () => WikiLocation
68
+ /** Pointer file the LEGACY single-wiki switch persists (wiki-location.ts). */
69
+ locationStateFile: () => string
70
+ /** The multi-wiki control file: mode + the wiki list + the default id. */
71
+ registryFile: () => string
72
+ /** The farm, or undefined until the startup task has read the control file. */
73
+ farm: FarmGetter
74
+ /** The runtime legacy/agent traffic falls back to (undefined = nothing up). */
75
+ defaultInstance: () => WikiInstance | undefined
76
+ /** The CONTROL FILE as the settings page edits it (see controlRegistryNow). */
77
+ controlRegistryNow: () => WikiRegistry
78
+ /** Where that view came from: 'file' / 'legacy' / 'default'. */
79
+ controlSource: () => 'file' | 'legacy' | 'default'
80
+ /** The control-file read's warnings (empty when clean). */
81
+ controlWarnings: () => string[]
82
+ /** The control-file read's error, when it had one. */
83
+ controlError: () => string | undefined
84
+ /** Single-flight guard: two concurrent switches would fight over the child. */
85
+ isSwitching: () => boolean
86
+ /** Claim / release the single-flight guard (index.ts owns the flag). */
87
+ setSwitching: (value: boolean) => void
88
+ /** Teardown-aware (v0.19.1 / v0.23.5): see the guards inside runSwitch. */
89
+ isDisposed: () => boolean
90
+ /** The prompt section must be rebuilt once the moved wiki's config tiddler loads. */
91
+ applyPrompt: () => void
92
+ }
93
+
94
+ export interface WikiViews {
95
+ /** The folder the default wiki occupies, running or not. */
96
+ defaultPath: () => string
97
+ /** The `{root,name}` the default wiki currently occupies (running or not). */
98
+ defaultCurrentLocation: () => WikiLocation
99
+ /** Source of the CURRENT location, for the settings page. */
100
+ locationSource: () => Promise<WikiLocationSource>
101
+ locationInfo: () => Promise<WikiLocationInfo>
102
+ /** SINGLE mode: the legacy orchestrator, on the farm's default runtime. */
103
+ runSwitch: (target: { root?: unknown; name?: unknown }, persist: (t: WikiLocation) => Promise<void>) => Promise<WikiSwitchResult>
104
+ /** MULTI mode: move the DEFAULT wiki's folder, then let the farm reconcile. */
105
+ repointDefault: (target: { root?: unknown; name?: unknown }) => Promise<WikiSwitchResult>
106
+ /** Switch the DEFAULT wiki to another folder and remember the choice. */
107
+ switchWikiLocation: (target: { root?: unknown; name?: unknown }) => Promise<WikiSwitchResult>
108
+ /** 「恢复为配置默认」 (see the implementation note below). */
109
+ resetWikiLocation: () => Promise<WikiSwitchResult>
110
+ /** The control file's view for the settings page (see controlRegistryNow). */
111
+ buildWikisView: () => AdminWikisView
112
+ }
113
+
114
+ export function createWikiViews(deps: WikiViewsDeps): WikiViews {
115
+ const { farm, defaultInstance, defaultLocation, locationStateFile } = deps
116
+
117
+ /** The folder the default wiki occupies, running or not. */
118
+ const defaultPath = (): string => {
119
+ const running = defaultInstance()
120
+ if (running !== undefined) return running.path
121
+ const live = farm()
122
+ const entry = live === undefined ? undefined : defaultEntry(live.registry)
123
+ return entry === undefined ? locationPath(defaultLocation()) : entryPath(entry)
124
+ }
125
+ /** The `{root,name}` the default wiki currently occupies (running or not). */
126
+ const defaultCurrentLocation = (): WikiLocation => {
127
+ const running = defaultInstance()
128
+ if (running !== undefined) return running.server.currentLocation
129
+ const live = farm()
130
+ const entry = live === undefined ? undefined : defaultEntry(live.registry)
131
+ return entry === undefined ? defaultLocation() : { root: entry.root, name: entry.name }
132
+ }
133
+ /** Source of the CURRENT location, for the settings page. */
134
+ const locationSource = async (): Promise<WikiLocationSource> => {
135
+ const state = await readLocationState(locationStateFile())
136
+ if (state.active !== undefined && locationPath(state.active) === defaultPath()) return 'state'
137
+ const raw = deps.rawConfig()
138
+ return typeof raw.wikiRoot === 'string' && raw.wikiRoot.trim().length > 0 ? 'config' : 'default'
139
+ }
140
+ const locationInfo = async (): Promise<WikiLocationInfo> => {
141
+ const state = await readLocationState(locationStateFile())
142
+ const current = defaultCurrentLocation()
143
+ return {
144
+ current: { ...current, path: defaultPath(), source: await locationSource() },
145
+ default: { ...defaultLocation(), path: locationPath(defaultLocation()) },
146
+ stateFile: locationStateFile(),
147
+ candidates: await listWikiCandidates(current.root),
148
+ ...(state.error !== undefined ? { error: state.error } : {}),
149
+ }
150
+ }
151
+ /** SINGLE mode: the legacy orchestrator, on the farm's default runtime. */
152
+ const runSwitch = async (target: { root?: unknown; name?: unknown }, persist: (t: WikiLocation) => Promise<void>): Promise<WikiSwitchResult> => {
153
+ if (deps.isSwitching()) return { ok: false, error: '正在切换知识库,请稍候再试', rolledBack: true }
154
+ // A switch in flight while the plugin is being disposed (hot reload / dsh web
155
+ // shutdown) would re-arm the committer + fs watcher AFTER teardown ran, and
156
+ // could even spawn a fresh TW child after `stop()` (v0.23.5).
157
+ const disposed = deps.isDisposed()
158
+ if (disposed) return { ok: false, error: '插件正在卸载,已取消切换', rolledBack: false }
159
+ const runtime = defaultInstance()
160
+ if (runtime === undefined) return { ok: false, error: '默认知识库当前没有运行,无法切换位置', rolledBack: false }
161
+ deps.setSwitching(true)
162
+ try {
163
+ const result = await switchWiki({
164
+ currentLocation: () => runtime.server.currentLocation,
165
+ currentPath: () => runtime.path,
166
+ // v0.24.1: ironclad rule #1 lists the knowledge-base switch as a path
167
+ // that MUST drain first; writes still in the OLD wiki's syncer queue were
168
+ // otherwise killed with the child. `drainThenStop` is the shared primitive
169
+ // (owned by the instance since v0.28.0); the rollback path reuses it, and a
170
+ // missing client (child already down) is a no-op.
171
+ stopServer: async () => { await runtime.drainStop() },
172
+ applyLocation: (nextLocation) => {
173
+ // Repoints the server AND drops the cached REST client (whose 2s list
174
+ // cache belongs to the OLD wiki).
175
+ runtime.updateEntry({ ...runtime.entry, root: nextLocation.root, name: nextLocation.name })
176
+ },
177
+ startServer: async () => { await runtime.server.start() },
178
+ teardownExtras: () => runtime.teardownExtras(),
179
+ setupExtras: () => { runtime.setupExtras() },
180
+ reloadConfig: async () => {
181
+ await runtime.config.load(runtime.client())
182
+ // The new wiki carries its own config tiddler → its own prompt.*.
183
+ deps.applyPrompt()
184
+ },
185
+ bootstrap: async () => {
186
+ await runtime.bootstrapWiki()
187
+ await runtime.bootstrapGit()
188
+ },
189
+ savePointer: persist,
190
+ log: (message) => console.warn('[dsh-tiddlywiki]', message),
191
+ }, target)
192
+ // Teardown may have run while the switch was awaiting: the switch itself
193
+ // succeeded, but the extras it re-armed must be released again so we do not
194
+ // leak a committer/watcher past dispose (v0.23.5).
195
+ if (deps.isDisposed()) await runtime.teardownExtras()
196
+ // The farm must agree with the runtime the orchestrator just moved — its
197
+ // registry is what a later `apply()` (add/remove an entry) diffs against.
198
+ const live = farm()
199
+ if (result.ok && live !== undefined) {
200
+ const moved = runtime.entry
201
+ live.syncRegistry({ ...live.registry, wikis: live.registry.wikis.map((entry) => (entry.id === moved.id ? moved : entry)) })
202
+ }
203
+ return result
204
+ } finally {
205
+ deps.setSwitching(false)
206
+ }
207
+ }
208
+ /**
209
+ * MULTI mode: move the DEFAULT wiki to another folder. The farm's reconcile
210
+ * stops the old child, recycles the runtime and starts it on the new folder;
211
+ * the registry is persisted LAST (a failed write costs restart-survival, not
212
+ * the running wiki — same trade-off the pointer file already makes).
213
+ */
214
+ const repointDefault = async (target: { root?: unknown; name?: unknown }): Promise<WikiSwitchResult> => {
215
+ if (deps.isDisposed()) return { ok: false, error: '插件正在卸载,已取消切换', rolledBack: false }
216
+ const live = farm()
217
+ if (live === undefined) return { ok: false, error: '插件尚未就绪,请稍后再试', rolledBack: true }
218
+ if (deps.isSwitching()) return { ok: false, error: '正在切换知识库,请稍候再试', rolledBack: true }
219
+ const normalized = normalizeLocation(target)
220
+ if (normalized.location === undefined) return { ok: false, error: normalized.error ?? '位置非法', rolledBack: true }
221
+ const next = normalized.location
222
+ const current = defaultEntry(live.registry)
223
+ if (current === undefined) return { ok: false, error: '清单里没有默认知识库', rolledBack: true }
224
+ const moved: WikiEntry = { ...current, root: next.root, name: next.name }
225
+ const nextRegistry: WikiRegistry = { ...live.registry, wikis: live.registry.wikis.map((entry) => (entry.id === moved.id ? moved : entry)) }
226
+ // Re-validate: moving a folder can collide with (or nest inside) another
227
+ // registered wiki, and those rules are the whole point of the registry.
228
+ const validated = validateRegistry(nextRegistry)
229
+ if (validated.registry === undefined) return { ok: false, error: validated.fatal.join(';'), rolledBack: true }
230
+ deps.setSwitching(true)
231
+ try {
232
+ await live.apply(validated.registry)
233
+ const applied: WikiSwitchResult = { ok: true, location: { root: moved.root, name: moved.name }, path: entryPath(moved) }
234
+ try {
235
+ await writeRegistry(validated.registry, deps.registryFile())
236
+ } catch (err) {
237
+ return { ...applied, warning: `位置已切换,但清单写入失败(重启 dsh web 后会回到原位置):${err instanceof Error ? err.message : String(err)}` }
238
+ }
239
+ return applied
240
+ } finally {
241
+ deps.setSwitching(false)
242
+ }
243
+ }
244
+ /** Switch the DEFAULT wiki to another folder and remember the choice. */
245
+ const switchWikiLocation = (target: { root?: unknown; name?: unknown }): Promise<WikiSwitchResult> => {
246
+ if (farm()?.registry.mode === 'multi') return repointDefault(target)
247
+ return runSwitch(target, async (t) => { await writeLocationState(t, locationStateFile()) })
248
+ }
249
+ /**
250
+ * 「恢复为配置默认」: single mode drops the pointer and goes back to the cordis
251
+ * default (cleared EVEN when the current folder already IS the default, or the
252
+ * stale pointer wins again after the next restart); multi mode moves the
253
+ * default wiki back to the configured location.
254
+ */
255
+ const resetWikiLocation = async (): Promise<WikiSwitchResult> => {
256
+ if (farm()?.registry.mode === 'multi') return repointDefault(defaultLocation())
257
+ if (locationPath(defaultLocation()) === defaultPath()) {
258
+ await clearLocationState(locationStateFile())
259
+ return { ok: true, location: defaultLocation(), path: defaultPath() }
260
+ }
261
+ return runSwitch(defaultLocation(), async () => { await clearLocationState(locationStateFile()) })
262
+ }
263
+
264
+ /** The control file's view for the settings page (see controlRegistryNow). */
265
+ const buildWikisView = (): AdminWikisView => {
266
+ const registry = deps.controlRegistryNow()
267
+ return {
268
+ mode: registry.mode,
269
+ defaultId: registry.defaultId,
270
+ source: deps.controlSource(),
271
+ registryFile: deps.registryFile(),
272
+ ...(deps.controlError() !== undefined ? { error: deps.controlError() } : {}),
273
+ warnings: deps.controlWarnings(),
274
+ wikis: registry.wikis.map((entry) => {
275
+ const runtime = farm()?.runtime(entry.id)
276
+ return {
277
+ id: entry.id,
278
+ label: entry.label,
279
+ root: entry.root,
280
+ name: entry.name,
281
+ path: entryPath(entry),
282
+ agentVisible: entry.agentVisible,
283
+ autostart: entry.autostart,
284
+ running: runtime !== undefined,
285
+ status: runtime?.server.status().status ?? 'stopped',
286
+ // 每库图标(v0.28.8):设置页的图标选择器发的是 `{ ...wiki, icon }` ——
287
+ // 这里的 `wiki` 就是本函数的输出。漏掉这个字段时 `wiki.icon` 恒为
288
+ // undefined,于是「选完图标、服务端回包一渲染就变回默认」(v0.28.4
289
+ // 引入该选择器时只把 icon 加进了 `/status` 的 wikiSummaries,见下面
290
+ // 1123 行那处,漏了这一处)。
291
+ ...(entry.icon !== undefined ? { icon: entry.icon } : {}),
292
+ }
293
+ }),
294
+ }
295
+ }
296
+
297
+ return {
298
+ defaultPath,
299
+ defaultCurrentLocation,
300
+ locationSource,
301
+ locationInfo,
302
+ runSwitch,
303
+ repointDefault,
304
+ switchWikiLocation,
305
+ resetWikiLocation,
306
+ buildWikisView,
307
+ }
308
+ }
309
+
310
+ /**
311
+ * Restart the RUNNING wikis whose content a pull just changed (v0.28.0).
312
+ *
313
+ * Shared by the agent tool and the browser `/sync` route so the two cannot
314
+ * drift. `dir` is where the pull ran (the repository is resolved from it) and
315
+ * `changedFiles` are repository-relative — which is what makes this correct
316
+ * when several knowledge bases share one repository.
317
+ */
318
+ export async function restartAffectedWikis(
319
+ deps: { farm: FarmGetter; repoRootOf: (dir: string) => Promise<string | undefined> },
320
+ dir: string,
321
+ changedFiles: readonly string[],
322
+ ): Promise<{ restarted: string[]; failed: Array<{ id: string; message: string }> }> {
323
+ const farm = deps.farm()
324
+ if (farm === undefined) return { restarted: [], failed: [] }
325
+ const repoRoot = (await deps.repoRootOf(dir)) ?? dir
326
+ const restarted: string[] = []
327
+ const failed: Array<{ id: string; message: string }> = []
328
+ for (const runtime of farm.affectedBy(repoRoot, changedFiles)) {
329
+ try {
330
+ // `WikiInstance.restart()` drains the syncer queue first (rule #1).
331
+ await runtime.restart()
332
+ restarted.push(runtime.entry.id)
333
+ } catch (err) {
334
+ failed.push({ id: runtime.entry.id, message: err instanceof Error ? err.message : String(err) })
335
+ }
336
+ }
337
+ return { restarted, failed }
338
+ }
339
+
340
+ /** Does this wiki live inside that repository (or is it the repository root)? */
341
+ export function entryIsInRepo(entry: WikiEntry, repoRoot: string): boolean {
342
+ const path = entryPath(entry)
343
+ return pathComparisonKey(path) === pathComparisonKey(repoRoot) || isInsidePath(repoRoot, path)
344
+ }
345
+
346
+ /**
347
+ * The same-origin proxy base a wiki's TW frontend must use (v0.28.0).
348
+ * The rule itself lives in host/wiki.ts (`proxyBaseFor`) so the harness and the
349
+ * host cannot disagree about it — see that function for why it matters.
350
+ */
351
+ export function proxyBaseForEntry(farm: FarmGetter, entry: WikiEntry): string {
352
+ return proxyBaseFor(farm()?.registry.mode ?? 'single', entry.id)
353
+ }