@bevel-software/platform-core-frontend 0.1.0
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/LICENSE +202 -0
- package/package.json +70 -0
- package/src/core/CoreAppShell.tsx +444 -0
- package/src/core/__tests__/ShellRoutes.test.tsx +95 -0
- package/src/core/events.ts +29 -0
- package/src/core/registry.ts +336 -0
- package/src/css-side-effect-imports.d.ts +7 -0
- package/src/html-extensions.ts +12 -0
- package/src/index.css +49 -0
- package/src/index.ts +23 -0
- package/src/lib/api.ts +57 -0
- package/src/lib/utils.ts +138 -0
- package/src/modules/access/__tests__/ManageAccessDialog.test.tsx +130 -0
- package/src/modules/access/__tests__/useFileAccess.test.tsx +253 -0
- package/src/modules/access/api.ts +205 -0
- package/src/modules/access/components/AccessRestrictedBanner.tsx +31 -0
- package/src/modules/access/components/ManageAccessDialog.tsx +1232 -0
- package/src/modules/access/components/NodeOwnersBanner.tsx +30 -0
- package/src/modules/access/hooks/useFileAccess.ts +151 -0
- package/src/modules/admin/components/AdminRolesPage.tsx +943 -0
- package/src/modules/admin/components/RolesCorruptedBanner.tsx +74 -0
- package/src/modules/admin/services/admin.api.ts +92 -0
- package/src/modules/admin/services/roles.api.ts +136 -0
- package/src/modules/admin/state/admin.context.tsx +223 -0
- package/src/modules/auth/components/LoginScreen.tsx +135 -0
- package/src/modules/auth/hooks/useAuthState.ts +59 -0
- package/src/modules/auth/services/auth.api.ts +24 -0
- package/src/modules/auth/services/microsoft-oauth.ts +57 -0
- package/src/modules/auth/state/auth.context.ts +18 -0
- package/src/modules/git/__tests__/BranchSwitcher.test.tsx +347 -0
- package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +201 -0
- package/src/modules/git/__tests__/ProtectedBranchBanner.test.tsx +82 -0
- package/src/modules/git/__tests__/PullNeededBanner.test.tsx +441 -0
- package/src/modules/git/__tests__/git.api.test.ts +113 -0
- package/src/modules/git/__tests__/pr.api.test.ts +44 -0
- package/src/modules/git/__tests__/useAutoPullUpdates.test.tsx +212 -0
- package/src/modules/git/components/BranchSwitcher.tsx +527 -0
- package/src/modules/git/components/DiffView.tsx +30 -0
- package/src/modules/git/components/FileComparisonPanel.tsx +377 -0
- package/src/modules/git/components/FileHistoryPanel.tsx +320 -0
- package/src/modules/git/components/ProtectedBranchBanner.tsx +42 -0
- package/src/modules/git/components/PullNeededBanner.tsx +204 -0
- package/src/modules/git/components/PullRequestsForMe.tsx +244 -0
- package/src/modules/git/components/UnifiedDiffView.tsx +37 -0
- package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +99 -0
- package/src/modules/git/hooks/useAutoPullUpdates.ts +121 -0
- package/src/modules/git/hooks/useGitState.ts +335 -0
- package/src/modules/git/services/__tests__/error-messages.test.ts +134 -0
- package/src/modules/git/services/error-messages.ts +257 -0
- package/src/modules/git/services/git.api.ts +163 -0
- package/src/modules/git/services/pr-prompts.ts +159 -0
- package/src/modules/git/services/pr.api.ts +39 -0
- package/src/modules/git/state/auto-update.context.ts +21 -0
- package/src/modules/git/state/git.context.ts +82 -0
- package/src/modules/layout/components/AppLayout.tsx +40 -0
- package/src/modules/layout/components/DemoBanner.tsx +57 -0
- package/src/modules/layout/components/MaintenanceOverlay.tsx +104 -0
- package/src/modules/layout/components/MobileChatLayout.tsx +153 -0
- package/src/modules/layout/components/ResizableThreePaneLayout.tsx +203 -0
- package/src/modules/layout/components/SlideOverlay.tsx +224 -0
- package/src/modules/layout/components/__tests__/MobileChatLayout.test.tsx +77 -0
- package/src/modules/layout/components/__tests__/ResizableThreePaneLayout.test.tsx +57 -0
- package/src/modules/layout/hooks/useMediaQuery.ts +23 -0
- package/src/modules/layout/state/__tests__/layout.context.test.tsx +39 -0
- package/src/modules/layout/state/layout.context.ts +46 -0
- package/src/modules/library/__tests__/DetailDialog.test.tsx +200 -0
- package/src/modules/library/__tests__/diff.test.ts +62 -0
- package/src/modules/library/__tests__/loadout.test.tsx +72 -0
- package/src/modules/library/__tests__/status.test.ts +117 -0
- package/src/modules/library/components/ChangeRequestDock.tsx +47 -0
- package/src/modules/library/components/CompareView.tsx +357 -0
- package/src/modules/library/components/DetailDialog.tsx +566 -0
- package/src/modules/library/components/GearIcon.tsx +12 -0
- package/src/modules/library/components/LibraryCard.tsx +132 -0
- package/src/modules/library/components/LibraryPage.tsx +254 -0
- package/src/modules/library/components/LoadoutSidebar.tsx +156 -0
- package/src/modules/library/components/StatusGem.tsx +21 -0
- package/src/modules/library/components/SuggestChange.tsx +171 -0
- package/src/modules/library/components/particles.ts +50 -0
- package/src/modules/library/hooks/useLibraryData.ts +119 -0
- package/src/modules/library/hooks/useSkillDetail.ts +74 -0
- package/src/modules/library/library.css +320 -0
- package/src/modules/library/services/library.api.ts +164 -0
- package/src/modules/library/state/loadout.tsx +129 -0
- package/src/modules/library/state/toast.tsx +42 -0
- package/src/modules/library/utils/diff.ts +102 -0
- package/src/modules/library/utils/status.ts +116 -0
- package/src/modules/pr/__tests__/PrApprovalBadge.test.tsx +93 -0
- package/src/modules/pr/__tests__/PrCancelButton.test.tsx +158 -0
- package/src/modules/pr/__tests__/PrCancelConfirmDialog.test.tsx +44 -0
- package/src/modules/pr/__tests__/PrMergeButton.test.tsx +360 -0
- package/src/modules/pr/__tests__/bucketize-comments.test.ts +85 -0
- package/src/modules/pr/__tests__/parsePatch.test.ts +104 -0
- package/src/modules/pr/__tests__/usePrViewerState.test.ts +72 -0
- package/src/modules/pr/components/OpenChangeRequestDialog.tsx +193 -0
- package/src/modules/pr/components/PrApprovalBadge.tsx +80 -0
- package/src/modules/pr/components/PrCancelButton.tsx +99 -0
- package/src/modules/pr/components/PrCancelConfirmDialog.tsx +119 -0
- package/src/modules/pr/components/PrCommentComposer.tsx +92 -0
- package/src/modules/pr/components/PrCommentThread.tsx +168 -0
- package/src/modules/pr/components/PrCommentsPanel.tsx +143 -0
- package/src/modules/pr/components/PrDiffPane.tsx +425 -0
- package/src/modules/pr/components/PrFileRow.tsx +164 -0
- package/src/modules/pr/components/PrFilesList.tsx +53 -0
- package/src/modules/pr/components/PrHeader.tsx +45 -0
- package/src/modules/pr/components/PrHeaderOverflowMenu.tsx +58 -0
- package/src/modules/pr/components/PrMergeButton.tsx +268 -0
- package/src/modules/pr/components/PrMergeConfirmDialog.tsx +112 -0
- package/src/modules/pr/components/PrRefreshFromTargetButton.tsx +110 -0
- package/src/modules/pr/components/PrViewer.tsx +364 -0
- package/src/modules/pr/hooks/usePrViewerState.ts +150 -0
- package/src/modules/pr/services/pr-approvals.api.ts +31 -0
- package/src/modules/pr/services/pr-cancel.api.ts +19 -0
- package/src/modules/pr/services/pr-comments.api.ts +45 -0
- package/src/modules/pr/services/pr-detail.api.ts +17 -0
- package/src/modules/pr/services/pr-merge.api.ts +53 -0
- package/src/modules/pr/services/pr-open.api.ts +30 -0
- package/src/modules/pr/state/pr-viewer.context.ts +34 -0
- package/src/modules/pr/utils/bucketize-comments.ts +55 -0
- package/src/modules/pr/utils/parsePatch.ts +57 -0
- package/src/modules/review/__tests__/review.api.test.ts +121 -0
- package/src/modules/review/components/BinaryChangePlaceholder.tsx +15 -0
- package/src/modules/review/components/DiffViewer.tsx +78 -0
- package/src/modules/review/components/MarkdownDiffViewer.tsx +263 -0
- package/src/modules/review/components/ReviewFileRow.tsx +114 -0
- package/src/modules/review/components/ReviewPanel.tsx +260 -0
- package/src/modules/review/components/ReviewPanelSurface.tsx +52 -0
- package/src/modules/review/components/__tests__/ReviewPanel.test.tsx +106 -0
- package/src/modules/review/hooks/__tests__/useReviewState.test.ts +88 -0
- package/src/modules/review/hooks/useReviewState.ts +256 -0
- package/src/modules/review/services/review.api.ts +72 -0
- package/src/modules/review/state/ReviewProvider.tsx +28 -0
- package/src/modules/review/state/review.context.ts +29 -0
- package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +488 -0
- package/src/modules/secrets-vault/components/SecretsPage.tsx +276 -0
- package/src/modules/secrets-vault/components/ToolSecretsPanel.tsx +362 -0
- package/src/modules/secrets-vault/components/__tests__/SecretsPage.test.tsx +51 -0
- package/src/modules/secrets-vault/services/connect.api.ts +113 -0
- package/src/modules/secrets-vault/services/secrets.api.ts +82 -0
- package/src/modules/secrets-vault/services/tool-secrets.api.ts +116 -0
- package/src/modules/toolbar/components/AdminMenu.tsx +250 -0
- package/src/modules/toolbar/components/AppSwitcher.tsx +108 -0
- package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +548 -0
- package/src/modules/toolbar/components/Toolbar.tsx +123 -0
- package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +122 -0
- package/src/modules/toolbar/components/__tests__/Toolbar.test.tsx +353 -0
- package/src/modules/toolbar/services/external-api-keys.api.ts +65 -0
- package/src/modules/tools/ToolsExplorerPage.tsx +380 -0
- package/src/modules/workflow/hooks/useEventBusSubscription.ts +24 -0
- package/src/modules/workflow/hooks/useFileLock.ts +430 -0
- package/src/modules/workflow/services/lock.api.ts +139 -0
- package/src/modules/workflow/state/EventBusFocusBinder.tsx +25 -0
- package/src/modules/workflow/state/EventBusProvider.tsx +232 -0
- package/src/modules/workflow/state/event-bus.context.ts +75 -0
- package/src/modules/workspace/__tests__/testFixtures.ts +54 -0
- package/src/modules/workspace/__tests__/useWorkspaceState.test.ts +91 -0
- package/src/modules/workspace/components/EditorTabs.tsx +384 -0
- package/src/modules/workspace/components/FileExplorer.tsx +1068 -0
- package/src/modules/workspace/components/FileRoute.tsx +392 -0
- package/src/modules/workspace/components/FileViewer.tsx +906 -0
- package/src/modules/workspace/components/__tests__/EditorTabs.test.tsx +241 -0
- package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +666 -0
- package/src/modules/workspace/components/__tests__/FileRoute.test.tsx +330 -0
- package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +492 -0
- package/src/modules/workspace/components/renderers/CsvRenderer.tsx +174 -0
- package/src/modules/workspace/components/renderers/DocxRenderer.tsx +87 -0
- package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +231 -0
- package/src/modules/workspace/components/renderers/ImageRenderer.tsx +50 -0
- package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +287 -0
- package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +252 -0
- package/src/modules/workspace/components/renderers/MermaidDiagram.tsx +268 -0
- package/src/modules/workspace/components/renderers/PdfRenderer.tsx +81 -0
- package/src/modules/workspace/components/renderers/TextRenderer.tsx +86 -0
- package/src/modules/workspace/components/renderers/ToolForm.tsx +404 -0
- package/src/modules/workspace/components/renderers/ToolRenderer.tsx +417 -0
- package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +157 -0
- package/src/modules/workspace/components/renderers/__tests__/CsvRenderer.test.ts +57 -0
- package/src/modules/workspace/components/renderers/__tests__/KbMarkdownView.test.tsx +95 -0
- package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +328 -0
- package/src/modules/workspace/components/renderers/__tests__/PdfRenderer.test.tsx +167 -0
- package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +318 -0
- package/src/modules/workspace/components/renderers/csvUtils.ts +76 -0
- package/src/modules/workspace/components/renderers/htmlSandbox.ts +332 -0
- package/src/modules/workspace/components/renderers/index.ts +39 -0
- package/src/modules/workspace/components/renderers/types.ts +27 -0
- package/src/modules/workspace/hooks/__tests__/useWorkspaceState.test.tsx +298 -0
- package/src/modules/workspace/hooks/useWorkspaceState.ts +1315 -0
- package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +99 -0
- package/src/modules/workspace/routing/kb-routes.ts +266 -0
- package/src/modules/workspace/services/__tests__/workspace.api.test.ts +72 -0
- package/src/modules/workspace/services/workspace.api.ts +185 -0
- package/src/modules/workspace/state/workspace.context.ts +235 -0
- package/src/modules/workspace/utils/__tests__/frontmatter.test.ts +107 -0
- package/src/modules/workspace/utils/diff.ts +53 -0
- package/src/modules/workspace/utils/fileTree.ts +179 -0
- package/src/modules/workspace/utils/frontmatter.ts +80 -0
- package/src/modules/workspace/utils/readDroppedEntries.ts +119 -0
- package/src/modules/workspace/utils/tab-persistence.ts +23 -0
- package/src/shared/components/Dialog.tsx +198 -0
- package/src/shared/components/PageShell.tsx +51 -0
- package/src/shared/components/useModalLayer.ts +35 -0
- package/src/shared/markdown/Markdown.tsx +62 -0
- package/src/test-setup.ts +59 -0
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { createContext, useContext } from 'react';
|
|
2
|
+
import type { FileTreeEntry } from '@bevel-software/platform-shared';
|
|
3
|
+
|
|
4
|
+
export interface UploadError {
|
|
5
|
+
filename: string;
|
|
6
|
+
reason: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* One item the user has handed to the upload pipeline. Either a pre-resolved
|
|
11
|
+
* file (file picker / single-file drag) or a `FileSystemEntry` snapshot
|
|
12
|
+
* captured synchronously in the drop handler (folder drag — walked lazily so
|
|
13
|
+
* uploads start before enumeration finishes).
|
|
14
|
+
*/
|
|
15
|
+
export type UploadInput =
|
|
16
|
+
| { kind: 'files'; files: File[] }
|
|
17
|
+
| { kind: 'items'; entries: FileSystemEntry[] }
|
|
18
|
+
| { kind: 'paths'; items: { file: File; relativePath: string }[] };
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* In-memory record of a file or directory the user has dropped/picked but
|
|
22
|
+
* whose round-trip to the server hasn't landed yet. Rendered alongside the
|
|
23
|
+
* server-sourced file tree so the dropped tree appears in the sidebar within
|
|
24
|
+
* one frame of the drop, not after every commit has pushed.
|
|
25
|
+
*/
|
|
26
|
+
export interface PendingEntry {
|
|
27
|
+
fullPath: string;
|
|
28
|
+
type: 'file' | 'directory';
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface OpenTab {
|
|
32
|
+
path: string;
|
|
33
|
+
/**
|
|
34
|
+
* The user-facing value for this tab. Includes any in-flight edits that
|
|
35
|
+
* haven't been saved yet — preserved across tab switches so typed bytes
|
|
36
|
+
* survive a switch + return. `null` means the cache was invalidated by an
|
|
37
|
+
* `fsRevision` bump (working tree mutated underneath this tab); activating
|
|
38
|
+
* such a tab triggers a refetch.
|
|
39
|
+
*/
|
|
40
|
+
content: string | null;
|
|
41
|
+
/**
|
|
42
|
+
* The bytes currently on disk. The renderer uses this as the baseline for
|
|
43
|
+
* computing dirty state; differs from `content` while the user has unsaved
|
|
44
|
+
* edits. `null` when content was never fetched or has been invalidated.
|
|
45
|
+
*/
|
|
46
|
+
savedContent: string | null;
|
|
47
|
+
isDirty: boolean;
|
|
48
|
+
pendingFileContent: string | null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface WorkspaceContextValue {
|
|
52
|
+
workspaceId: string | null;
|
|
53
|
+
/**
|
|
54
|
+
* Directory name (relative to the workspace root) where the per-user KB
|
|
55
|
+
* clone lives — comes from the backend's `KB_DIR_NAME` env, surfaced via
|
|
56
|
+
* `WorkspaceInfo.kbDirName`. Null until the workspace has bootstrapped.
|
|
57
|
+
* Renderers and chat cards use it to build correct KB-relative paths
|
|
58
|
+
* without hardcoding the repo name.
|
|
59
|
+
*/
|
|
60
|
+
kbDirName: string | null;
|
|
61
|
+
fileTree: FileTreeEntry | null;
|
|
62
|
+
|
|
63
|
+
/** All tabs currently open in the editor strip. */
|
|
64
|
+
openTabs: OpenTab[];
|
|
65
|
+
/** Active tab; null when no tabs are open. */
|
|
66
|
+
activeTab: OpenTab | null;
|
|
67
|
+
/** Filenames of any tabs in `openTabs` that have unsaved edits. */
|
|
68
|
+
dirtyTabFilenames: string[];
|
|
69
|
+
|
|
70
|
+
// Derived from `activeTab` for backward compatibility with existing readers.
|
|
71
|
+
openFilePath: string | null;
|
|
72
|
+
/** Active tab's current value (includes in-flight unsaved edits). */
|
|
73
|
+
openFileContent: string | null;
|
|
74
|
+
/** Active tab's on-disk bytes. Renderers use this to compute dirty state. */
|
|
75
|
+
openFileSavedContent: string | null;
|
|
76
|
+
hasUnsavedFileChanges: boolean;
|
|
77
|
+
pendingFileContent: string | null;
|
|
78
|
+
|
|
79
|
+
/** Internal bridge from file renderers to workspace navigation guards. */
|
|
80
|
+
setHasUnsavedFileChanges?: (hasUnsaved: boolean) => void;
|
|
81
|
+
/**
|
|
82
|
+
* Cache the active tab's in-flight value as the user types. Called by the
|
|
83
|
+
* renderer's `onValueChange` so that switching to a different tab and back
|
|
84
|
+
* preserves typed-but-unsaved bytes.
|
|
85
|
+
*/
|
|
86
|
+
setActiveTabContent: (value: string) => void;
|
|
87
|
+
/**
|
|
88
|
+
* Force-invalidate cached tab content and refetch the active tab. Used by
|
|
89
|
+
* code paths that mutate the working tree externally (e.g. `git revert` from
|
|
90
|
+
* the history panel) where the standard `saveFile`/`createFile`/etc. paths
|
|
91
|
+
* don't fire.
|
|
92
|
+
*/
|
|
93
|
+
bumpFsRevision: () => void;
|
|
94
|
+
/**
|
|
95
|
+
* Set the branch used as part of the localStorage key for tab persistence.
|
|
96
|
+
* The hook's auto-write effect doesn't fire until this is set AND
|
|
97
|
+
* `hydrateTabs` has run for the matching key.
|
|
98
|
+
*/
|
|
99
|
+
setPersistenceBranch: (branch: string | null) => void;
|
|
100
|
+
/**
|
|
101
|
+
* Monotonic counter bumped on every working-tree mutation (create, delete, move,
|
|
102
|
+
* upload, save). Consumers that depend on `git status` (e.g. the App-level refresh
|
|
103
|
+
* effect) watch this to re-poll without coupling this hook to the git module.
|
|
104
|
+
* Also used internally to invalidate cached tab content.
|
|
105
|
+
*/
|
|
106
|
+
fsRevision: number;
|
|
107
|
+
/**
|
|
108
|
+
* Most recent upload error, surfaced inline in the file explorer for both
|
|
109
|
+
* the toolbar button and drag-drop. Cleared on the next successful dispatch
|
|
110
|
+
* or via `clearUploadError`.
|
|
111
|
+
*/
|
|
112
|
+
uploadError: UploadError | null;
|
|
113
|
+
/** True while a `dispatchUpload` call is in flight; gates the toolbar button. */
|
|
114
|
+
isUploading: boolean;
|
|
115
|
+
/**
|
|
116
|
+
* Progress for the in-flight upload (folder drops in particular).
|
|
117
|
+
* `total` starts as `null` while the streaming walker is still discovering
|
|
118
|
+
* files and becomes a concrete number once the walk completes. `uploaded`
|
|
119
|
+
* ticks up per successful file. Null when nothing is uploading.
|
|
120
|
+
*/
|
|
121
|
+
uploadProgress: { uploaded: number; total: number | null } | null;
|
|
122
|
+
/**
|
|
123
|
+
* Files and directories the user has dropped or picked but whose
|
|
124
|
+
* server-side commits haven't echoed back yet. The FileExplorer overlays
|
|
125
|
+
* these onto the server tree so the dropped structure appears immediately.
|
|
126
|
+
* Keyed by full workspace-relative path.
|
|
127
|
+
*/
|
|
128
|
+
pendingUploads: Map<string, PendingEntry>;
|
|
129
|
+
refreshFileTree: () => Promise<FileTreeEntry | null>;
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Open a file in a new tab, or activate an existing tab for it. Never
|
|
133
|
+
* prompts on dirty state — opening more tabs never discards work. Returns
|
|
134
|
+
* `false` if the workspace isn't ready yet or the call was superseded by a
|
|
135
|
+
* newer addTab (older read whose response would otherwise steal focus from
|
|
136
|
+
* the newer open). Throws on read failure so callers can surface
|
|
137
|
+
* "file-missing" / "file-load-failed" UI.
|
|
138
|
+
*/
|
|
139
|
+
addTab: (relativePath: string) => Promise<boolean>;
|
|
140
|
+
/**
|
|
141
|
+
* Close a tab. Prompts via `window.confirm` if the tab has unsaved edits;
|
|
142
|
+
* pass `{ skipConfirm: true }` from bulk-close paths that have already
|
|
143
|
+
* collected one consolidated confirm. If the closed tab was active,
|
|
144
|
+
* activates the tab to its left (or right) and returns its path so the
|
|
145
|
+
* caller can update the URL. Returns `{ closed: false }` when the user
|
|
146
|
+
* cancelled the dirty-confirm.
|
|
147
|
+
*/
|
|
148
|
+
closeTab: (
|
|
149
|
+
tab: OpenTab,
|
|
150
|
+
options?: { skipConfirm?: boolean },
|
|
151
|
+
) => Promise<{ closed: boolean; newActivePath: string | null }>;
|
|
152
|
+
/** Activate a tab without prompting. Triggers a refetch if the tab's cache was invalidated. */
|
|
153
|
+
activateTab: (tab: OpenTab) => void;
|
|
154
|
+
/** Reorder a tab by moving it to a new index in the strip. */
|
|
155
|
+
reorderTab: (tab: OpenTab, toIndex: number) => void;
|
|
156
|
+
/**
|
|
157
|
+
* Close every tab without prompting. Used by `deleteWorkspace` and similar
|
|
158
|
+
* destructive paths where the caller has already confirmed.
|
|
159
|
+
*/
|
|
160
|
+
closeAllTabs: () => void;
|
|
161
|
+
/**
|
|
162
|
+
* Bulk-restore a tab list. Fetches every path in parallel; silently drops
|
|
163
|
+
* paths that 404 (file no longer on this branch) AND paths that 403 (read
|
|
164
|
+
* access denied — the tab auto-closes rather than lingering unreadable).
|
|
165
|
+
* Sets state once and activates `activePath` (or the last surviving path if
|
|
166
|
+
* `activePath` was dropped, or null if everything was dropped). Returns
|
|
167
|
+
* which paths survived, which were dropped, and which were denied — callers
|
|
168
|
+
* surface "file not found" / "no access" for a deeplinked path that didn't
|
|
169
|
+
* make it.
|
|
170
|
+
*/
|
|
171
|
+
hydrateTabs: (
|
|
172
|
+
paths: string[],
|
|
173
|
+
activePath: string | null,
|
|
174
|
+
) => Promise<{ surviving: string[]; dropped: string[]; denied: string[] }>;
|
|
175
|
+
|
|
176
|
+
createFile: (relativePath: string, content?: string) => Promise<void>;
|
|
177
|
+
createDirectory: (relativePath: string) => Promise<void>;
|
|
178
|
+
/**
|
|
179
|
+
* Extract a `.zip` file already in the workspace. Defaults to "unzip here":
|
|
180
|
+
* the archive's parent directory becomes the destination. Refreshes the
|
|
181
|
+
* file tree and bumps `fsRevision` on success. Resolves with the count of
|
|
182
|
+
* extracted entries and the list of entries the backend skipped (macOS
|
|
183
|
+
* noise, invalid names, zip-slip attempts) so the caller can decide
|
|
184
|
+
* whether to surface a banner.
|
|
185
|
+
*/
|
|
186
|
+
unzipHere: (zipRelativePath: string) => Promise<{
|
|
187
|
+
extracted: number;
|
|
188
|
+
skipped: { path: string; reason: string }[];
|
|
189
|
+
destination: string;
|
|
190
|
+
}>;
|
|
191
|
+
/** Low-level primitive — uploads files sequentially to the given target. */
|
|
192
|
+
uploadFiles: (files: File[], targetDirectory: string) => Promise<void>;
|
|
193
|
+
/**
|
|
194
|
+
* UI-facing entry point for uploads from drag-drop and file/folder pickers.
|
|
195
|
+
* Captures errors into `uploadError`, toggles `isUploading`, drives
|
|
196
|
+
* `pendingUploads` for optimistic rendering, and (for `kind: 'items'`)
|
|
197
|
+
* lazily walks dropped FileSystemEntries so uploads start before
|
|
198
|
+
* enumeration finishes. Preserves empty subdirectories from folder drops
|
|
199
|
+
* by creating them server-side after the file upload pass.
|
|
200
|
+
*/
|
|
201
|
+
dispatchUpload: (input: UploadInput, targetDirectory: string) => Promise<void>;
|
|
202
|
+
clearUploadError: () => void;
|
|
203
|
+
deleteEntry: (relativePath: string) => Promise<void>;
|
|
204
|
+
moveEntry: (oldPath: string, newPath: string) => Promise<void>;
|
|
205
|
+
saveFile: (relativePath: string, content: string) => Promise<void>;
|
|
206
|
+
/**
|
|
207
|
+
* Re-read the matching tab's bytes from the server and replace the tab's
|
|
208
|
+
* `content` + `savedContent` with them, clearing dirty + any pending agent
|
|
209
|
+
* preview. Used when taking ownership of a file (clicking Edit) so the
|
|
210
|
+
* user always starts from the canonical on-disk state — even if a
|
|
211
|
+
* teammate's save echo via SSE hasn't landed yet. Silently no-ops if the
|
|
212
|
+
* tab isn't open or the workspace isn't ready.
|
|
213
|
+
*/
|
|
214
|
+
reloadTabFromDisk: (relativePath: string) => Promise<void>;
|
|
215
|
+
/**
|
|
216
|
+
* Called by the chat hook when the agent has written a new version of the
|
|
217
|
+
* currently-active file. Routes to `activeTab.pendingFileContent`. The chat
|
|
218
|
+
* hook captures the active path before its readFile and re-checks it after,
|
|
219
|
+
* so this stays single-arg for v1 — multi-tab agent edits aren't a feature
|
|
220
|
+
* yet.
|
|
221
|
+
*/
|
|
222
|
+
setPendingContent: (content: string) => void;
|
|
223
|
+
/** Accept the active tab's pending agent changes — becomes the new accepted content */
|
|
224
|
+
acceptPendingContent: () => Promise<void>;
|
|
225
|
+
/** Reject the active tab's pending agent changes — reverts the file on disk to the current accepted content */
|
|
226
|
+
rejectPendingContent: () => Promise<void>;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export const WorkspaceContext = createContext<WorkspaceContextValue | null>(null);
|
|
230
|
+
|
|
231
|
+
export function useWorkspace(): WorkspaceContextValue {
|
|
232
|
+
const ctx = useContext(WorkspaceContext);
|
|
233
|
+
if (!ctx) throw new Error('useWorkspace must be used within WorkspaceContext.Provider');
|
|
234
|
+
return ctx;
|
|
235
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { parseFrontmatter, labelFor } from '../frontmatter';
|
|
3
|
+
|
|
4
|
+
describe('parseFrontmatter', () => {
|
|
5
|
+
it('returns the whole content as body when there is no frontmatter', () => {
|
|
6
|
+
const { data, body } = parseFrontmatter('# Just a heading\n\ntext');
|
|
7
|
+
expect(data).toEqual({});
|
|
8
|
+
expect(body).toBe('# Just a heading\n\ntext');
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it('parses simple scalars and strips the block from the body', () => {
|
|
12
|
+
const { data, body } = parseFrontmatter('---\nname: rfi\nversion: 1.4.0\n---\n\n# Body');
|
|
13
|
+
expect(data.name).toBe('rfi');
|
|
14
|
+
expect(data.version).toBe('1.4.0');
|
|
15
|
+
expect(body).toBe('# Body');
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it('parses a YAML block scalar (`|`) as the joined multi-line text, not "|"', () => {
|
|
19
|
+
const src = [
|
|
20
|
+
'---',
|
|
21
|
+
'name: rfi',
|
|
22
|
+
'description: |',
|
|
23
|
+
' Specialist RFI responder. Runs KB-only: every answer is',
|
|
24
|
+
' grounded in a real knowledge-graph node.',
|
|
25
|
+
'allowed-tools:',
|
|
26
|
+
' - Bash',
|
|
27
|
+
' - Read',
|
|
28
|
+
'---',
|
|
29
|
+
'',
|
|
30
|
+
'# Body',
|
|
31
|
+
].join('\n');
|
|
32
|
+
const { data } = parseFrontmatter(src);
|
|
33
|
+
|
|
34
|
+
// The bug: naive parsing stored "|" and turned the colon line into a key.
|
|
35
|
+
expect(data.description).not.toBe('|');
|
|
36
|
+
expect(data.description).toContain('Specialist RFI responder');
|
|
37
|
+
expect(data.description).toContain('grounded in a real knowledge-graph node');
|
|
38
|
+
// No bogus key derived from the "Runs KB-only:" colon inside the scalar.
|
|
39
|
+
expect(Object.keys(data)).toEqual(['name', 'description', 'allowed-tools']);
|
|
40
|
+
// Lists stay arrays.
|
|
41
|
+
expect(data['allowed-tools']).toEqual(['Bash', 'Read']);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('keeps a quoted markdown-link scalar (nodeType) intact', () => {
|
|
45
|
+
const { data } = parseFrontmatter(
|
|
46
|
+
'---\nnodeType: "[Process](../NodeTypes/Process.md)"\n---\n\n# Body',
|
|
47
|
+
);
|
|
48
|
+
expect(data.nodeType).toBe('[Process](../NodeTypes/Process.md)');
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('renders a nested map (metadata) as a readable string', () => {
|
|
52
|
+
const { data } = parseFrontmatter(
|
|
53
|
+
'---\nmetadata:\n author: example-org\n version: "1.0"\n---\n',
|
|
54
|
+
);
|
|
55
|
+
expect(data.metadata).toBe('author: example-org, version: 1.0');
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('does not infinite-loop on a circular YAML anchor/alias', () => {
|
|
59
|
+
// `a: &x { b: *x }` makes toJS() return a cyclic object; rendering it must
|
|
60
|
+
// terminate with a `[circular]` placeholder rather than overflow the stack.
|
|
61
|
+
const { data } = parseFrontmatter('---\na: &x\n b: *x\n---\n\n# Body');
|
|
62
|
+
expect(typeof data.a).toBe('string');
|
|
63
|
+
expect(data.a).toContain('[circular]');
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('falls back safely when toJS throws (alias bomb), keeping the body', () => {
|
|
67
|
+
const src = [
|
|
68
|
+
'---',
|
|
69
|
+
'a: &a [x,x,x,x,x,x,x,x,x,x]',
|
|
70
|
+
'b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a,*a]',
|
|
71
|
+
'c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b,*b]',
|
|
72
|
+
'---',
|
|
73
|
+
'',
|
|
74
|
+
'# Body',
|
|
75
|
+
].join('\n');
|
|
76
|
+
const { data, body } = parseFrontmatter(src);
|
|
77
|
+
expect(data).toEqual({});
|
|
78
|
+
expect(body).toBe('# Body');
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('is resilient: one malformed entry does not drop the valid sibling entries', () => {
|
|
82
|
+
// A malformed `bad` entry must not blank the access entries around it —
|
|
83
|
+
// permissions have to always surface.
|
|
84
|
+
const src = [
|
|
85
|
+
'---',
|
|
86
|
+
'write:',
|
|
87
|
+
' - Admin',
|
|
88
|
+
'bad: [unclosed',
|
|
89
|
+
'download:',
|
|
90
|
+
' - Felix <felix@x.eu>',
|
|
91
|
+
'---',
|
|
92
|
+
'',
|
|
93
|
+
'# Body',
|
|
94
|
+
].join('\n');
|
|
95
|
+
const { data, body } = parseFrontmatter(src);
|
|
96
|
+
expect(data.write).toEqual(['Admin']);
|
|
97
|
+
expect(data.download).toEqual(['Felix <felix@x.eu>']);
|
|
98
|
+
expect(body).toBe('# Body');
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
describe('labelFor', () => {
|
|
103
|
+
it('humanizes camelCase keys', () => {
|
|
104
|
+
expect(labelFor('nodeType')).toBe('Node Type');
|
|
105
|
+
expect(labelFor('name')).toBe('Name');
|
|
106
|
+
});
|
|
107
|
+
});
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export type DiffLine =
|
|
2
|
+
| { type: 'same'; text: string }
|
|
3
|
+
| { type: 'added'; text: string }
|
|
4
|
+
| { type: 'removed'; text: string };
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Compute a line-level diff between two strings using LCS.
|
|
8
|
+
* Returns a flat list of lines tagged as same / added / removed.
|
|
9
|
+
*/
|
|
10
|
+
export function computeDiff(oldText: string, newText: string): DiffLine[] {
|
|
11
|
+
const oldLines = oldText.split('\n');
|
|
12
|
+
const newLines = newText.split('\n');
|
|
13
|
+
const m = oldLines.length;
|
|
14
|
+
const n = newLines.length;
|
|
15
|
+
|
|
16
|
+
// Build LCS table
|
|
17
|
+
const dp: number[][] = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
|
|
18
|
+
for (let i = 1; i <= m; i++) {
|
|
19
|
+
for (let j = 1; j <= n; j++) {
|
|
20
|
+
if (oldLines[i - 1] === newLines[j - 1]) {
|
|
21
|
+
dp[i][j] = dp[i - 1][j - 1] + 1;
|
|
22
|
+
} else {
|
|
23
|
+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Backtrack to build diff
|
|
29
|
+
const result: DiffLine[] = [];
|
|
30
|
+
let i = m;
|
|
31
|
+
let j = n;
|
|
32
|
+
while (i > 0 || j > 0) {
|
|
33
|
+
if (i > 0 && j > 0 && oldLines[i - 1] === newLines[j - 1]) {
|
|
34
|
+
result.unshift({ type: 'same', text: oldLines[i - 1] });
|
|
35
|
+
i--;
|
|
36
|
+
j--;
|
|
37
|
+
} else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
|
|
38
|
+
result.unshift({ type: 'added', text: newLines[j - 1] });
|
|
39
|
+
j--;
|
|
40
|
+
} else {
|
|
41
|
+
result.unshift({ type: 'removed', text: oldLines[i - 1] });
|
|
42
|
+
i--;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return result;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Returns true if two strings differ (ignoring a single terminal newline sequence). */
|
|
50
|
+
export function contentChanged(a: string, b: string): boolean {
|
|
51
|
+
const strip = (s: string) => s.endsWith('\r\n') ? s.slice(0, -2) : s.endsWith('\n') ? s.slice(0, -1) : s;
|
|
52
|
+
return strip(a) !== strip(b);
|
|
53
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AGENTS_DIR,
|
|
3
|
+
DATA_DIR,
|
|
4
|
+
KNOWLEDGE_BASE_DIR,
|
|
5
|
+
PIPELINES_DIR,
|
|
6
|
+
SKILLS_DIR,
|
|
7
|
+
TOOLS_DIR,
|
|
8
|
+
type FileTreeEntry,
|
|
9
|
+
} from '@bevel-software/platform-shared';
|
|
10
|
+
import type { PendingEntry } from '../state/workspace.context';
|
|
11
|
+
|
|
12
|
+
export const KB_ROOT_DIRS = new Set([
|
|
13
|
+
KNOWLEDGE_BASE_DIR,
|
|
14
|
+
DATA_DIR,
|
|
15
|
+
AGENTS_DIR,
|
|
16
|
+
PIPELINES_DIR,
|
|
17
|
+
SKILLS_DIR,
|
|
18
|
+
TOOLS_DIR,
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Descend past the workspace / KB-clone wrapper levels to the node that holds
|
|
23
|
+
* the well-known KB root dirs (`KnowledgeBase/`, `Data/`, `Agents/`, …), or
|
|
24
|
+
* null when the tree predates the split. Shared by the explorer's sectioning
|
|
25
|
+
* and registry-contributed explorer items (e.g. the enterprise Graph view).
|
|
26
|
+
*/
|
|
27
|
+
export function findKbRoot(node: FileTreeEntry | null): FileTreeEntry | null {
|
|
28
|
+
if (!node?.children) return null;
|
|
29
|
+
const holdsSplit = node.children.some(
|
|
30
|
+
(c) => c.type === 'directory' && KB_ROOT_DIRS.has(c.name),
|
|
31
|
+
);
|
|
32
|
+
if (holdsSplit) return node;
|
|
33
|
+
for (const child of node.children) {
|
|
34
|
+
if (child.type === 'directory') {
|
|
35
|
+
const found = findKbRoot(child);
|
|
36
|
+
if (found) return found;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function findEntryByPath(tree: FileTreeEntry | null, relativePath: string): FileTreeEntry | null {
|
|
43
|
+
if (!tree) return null;
|
|
44
|
+
if (tree.relativePath === relativePath) return tree;
|
|
45
|
+
if (tree.children) {
|
|
46
|
+
for (const child of tree.children) {
|
|
47
|
+
const found = findEntryByPath(child, relativePath);
|
|
48
|
+
if (found) return found;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function pathExistsInTree(tree: FileTreeEntry | null, relativePath: string): boolean {
|
|
55
|
+
return findEntryByPath(tree, relativePath) !== null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function collectFilesByBasename(tree: FileTreeEntry | null, basename: string, acc: string[]): void {
|
|
59
|
+
if (!tree) return;
|
|
60
|
+
if (tree.type === 'file' && tree.name === basename) acc.push(tree.relativePath);
|
|
61
|
+
if (tree.children) {
|
|
62
|
+
for (const child of tree.children) collectFilesByBasename(child, basename, acc);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Resolve a candidate path to a concrete workspace-relative path.
|
|
68
|
+
* - Multi-segment candidates (contain `/`) must match an existing entry exactly.
|
|
69
|
+
* - Single-segment candidates (e.g. `positioning.md`) also match if exactly one
|
|
70
|
+
* file in the tree has that basename — handles agent shorthand after a full
|
|
71
|
+
* path was already mentioned in the same turn. Ambiguous basenames stay null.
|
|
72
|
+
*/
|
|
73
|
+
/**
|
|
74
|
+
* Merge optimistic pending-upload entries into a server-sourced file tree
|
|
75
|
+
* so the FileExplorer can render dropped/picked files within one frame of
|
|
76
|
+
* the user's action — well before their server commits have echoed back.
|
|
77
|
+
*
|
|
78
|
+
* Pending entries whose paths already exist on the server are skipped (the
|
|
79
|
+
* real entry wins). Missing parent directories along the way are
|
|
80
|
+
* synthesized as directory entries so a single dropped file inside a brand
|
|
81
|
+
* new folder renders the folder too.
|
|
82
|
+
*
|
|
83
|
+
* Returns a freshly-allocated tree; the input is not mutated. Children at
|
|
84
|
+
* each level are re-sorted so synthesized entries appear in the same order
|
|
85
|
+
* a server refresh would render them: directories first, then files,
|
|
86
|
+
* alphabetical within each group.
|
|
87
|
+
*/
|
|
88
|
+
export function mergePendingIntoTree(
|
|
89
|
+
tree: FileTreeEntry,
|
|
90
|
+
pending: Map<string, PendingEntry>,
|
|
91
|
+
): FileTreeEntry {
|
|
92
|
+
if (pending.size === 0) return tree;
|
|
93
|
+
|
|
94
|
+
const cloneNode = (node: FileTreeEntry): FileTreeEntry => ({
|
|
95
|
+
name: node.name,
|
|
96
|
+
relativePath: node.relativePath,
|
|
97
|
+
type: node.type,
|
|
98
|
+
children: node.children ? node.children.map(cloneNode) : undefined,
|
|
99
|
+
});
|
|
100
|
+
const root = cloneNode(tree);
|
|
101
|
+
|
|
102
|
+
// Walk to (and create) the directory at `path`. Returns null if `path`
|
|
103
|
+
// collides with an existing file along the way.
|
|
104
|
+
const ensureDir = (path: string): FileTreeEntry | null => {
|
|
105
|
+
if (!path || path === '.') return root;
|
|
106
|
+
const parts = path.split('/');
|
|
107
|
+
let node = root;
|
|
108
|
+
for (let i = 0; i < parts.length; i++) {
|
|
109
|
+
const segPath = parts.slice(0, i + 1).join('/');
|
|
110
|
+
if (!node.children) node.children = [];
|
|
111
|
+
let child = node.children.find((c) => c.relativePath === segPath);
|
|
112
|
+
if (!child) {
|
|
113
|
+
child = {
|
|
114
|
+
name: parts[i],
|
|
115
|
+
relativePath: segPath,
|
|
116
|
+
type: 'directory',
|
|
117
|
+
children: [],
|
|
118
|
+
};
|
|
119
|
+
node.children.push(child);
|
|
120
|
+
} else if (child.type !== 'directory') {
|
|
121
|
+
return null;
|
|
122
|
+
} else if (!child.children) {
|
|
123
|
+
child.children = [];
|
|
124
|
+
}
|
|
125
|
+
node = child;
|
|
126
|
+
}
|
|
127
|
+
return node;
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
for (const [fullPath, entry] of pending) {
|
|
131
|
+
const parts = fullPath.split('/');
|
|
132
|
+
const name = parts[parts.length - 1];
|
|
133
|
+
const parentPath = parts.slice(0, -1).join('/');
|
|
134
|
+
const parent = ensureDir(parentPath);
|
|
135
|
+
if (!parent) continue;
|
|
136
|
+
if (!parent.children) parent.children = [];
|
|
137
|
+
if (parent.children.some((c) => c.relativePath === fullPath)) continue;
|
|
138
|
+
parent.children.push({
|
|
139
|
+
name,
|
|
140
|
+
relativePath: fullPath,
|
|
141
|
+
type: entry.type,
|
|
142
|
+
children: entry.type === 'directory' ? [] : undefined,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Re-sort every level so synthesized entries appear in tree order.
|
|
147
|
+
const sort = (node: FileTreeEntry) => {
|
|
148
|
+
if (!node.children) return;
|
|
149
|
+
node.children.sort((a, b) => {
|
|
150
|
+
if (a.type !== b.type) return a.type === 'directory' ? -1 : 1;
|
|
151
|
+
return a.name.localeCompare(b.name);
|
|
152
|
+
});
|
|
153
|
+
for (const c of node.children) sort(c);
|
|
154
|
+
};
|
|
155
|
+
sort(root);
|
|
156
|
+
|
|
157
|
+
return root;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function resolveWorkspacePath(tree: FileTreeEntry | null, candidate: string): string | null {
|
|
161
|
+
if (!tree || !candidate) return null;
|
|
162
|
+
// The agent may emit either raw paths (`Knowledge/0. Current Truth/x.md`) or
|
|
163
|
+
// percent-encoded ones (`Knowledge/0.%20Current%20Truth/x.md`) — react-markdown
|
|
164
|
+
// hands us whatever was inside the link destination, so decode defensively.
|
|
165
|
+
let decoded = candidate;
|
|
166
|
+
try {
|
|
167
|
+
decoded = decodeURIComponent(candidate);
|
|
168
|
+
} catch {
|
|
169
|
+
// Malformed escape sequence — fall back to the raw candidate.
|
|
170
|
+
}
|
|
171
|
+
const normalized = decoded.trim().replace(/^\.\//, '').replace(/^\//, '');
|
|
172
|
+
if (!normalized) return null;
|
|
173
|
+
const entry = findEntryByPath(tree, normalized);
|
|
174
|
+
if (entry?.type === 'file') return normalized;
|
|
175
|
+
if (normalized.includes('/')) return null;
|
|
176
|
+
const matches: string[] = [];
|
|
177
|
+
collectFilesByBasename(tree, normalized, matches);
|
|
178
|
+
return matches.length === 1 ? matches[0] : null;
|
|
179
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { parseDocument } from 'yaml';
|
|
2
|
+
|
|
3
|
+
export type FrontmatterData = Record<string, string | string[]>;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Render a non-string scalar / nested value into a readable string for the
|
|
7
|
+
* frontmatter panel (which only displays `string | string[]`). `seen` guards
|
|
8
|
+
* against circular references — YAML anchors/aliases (`a: &x { b: *x }`) make
|
|
9
|
+
* `toJS()` return a cyclic object, which would otherwise recurse forever.
|
|
10
|
+
*/
|
|
11
|
+
function scalarToString(value: unknown, seen: WeakSet<object> = new WeakSet()): string {
|
|
12
|
+
if (value == null) return '';
|
|
13
|
+
if (typeof value === 'string') return value;
|
|
14
|
+
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
|
|
15
|
+
if (typeof value === 'object') {
|
|
16
|
+
if (seen.has(value)) return '[circular]';
|
|
17
|
+
seen.add(value);
|
|
18
|
+
if (Array.isArray(value)) return value.map((v) => scalarToString(v, seen)).join(', ');
|
|
19
|
+
// Nested map (e.g. `metadata:`) — render as `key: value` pairs.
|
|
20
|
+
return Object.entries(value as Record<string, unknown>)
|
|
21
|
+
.map(([k, v]) => `${k}: ${scalarToString(v, seen)}`)
|
|
22
|
+
.join(', ');
|
|
23
|
+
}
|
|
24
|
+
return String(value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Coerce a parsed YAML value into the panel's `string | string[]` shape. */
|
|
28
|
+
function coerce(value: unknown): string | string[] {
|
|
29
|
+
if (Array.isArray(value)) {
|
|
30
|
+
const seen = new WeakSet<object>([value]);
|
|
31
|
+
return value.map((v) => scalarToString(v, seen));
|
|
32
|
+
}
|
|
33
|
+
return scalarToString(value);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Parse YAML frontmatter from a markdown string using a real YAML parser, so
|
|
38
|
+
* block scalars (`|` / `>`), quoted strings, nested maps and lists all parse
|
|
39
|
+
* correctly. Values are coerced to `string | string[]` for the frontmatter
|
|
40
|
+
* panel. Returns the parsed data and the body without the frontmatter block.
|
|
41
|
+
*
|
|
42
|
+
* Resilient by design: `parseDocument` collects errors instead of throwing, so
|
|
43
|
+
* a single malformed entry never blanks the whole block — the entries that DO
|
|
44
|
+
* parse are still returned. This matters because the same frontmatter shape can
|
|
45
|
+
* carry access entries that must always surface.
|
|
46
|
+
*/
|
|
47
|
+
export function parseFrontmatter(content: string): { data: FrontmatterData; body: string } {
|
|
48
|
+
const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
|
|
49
|
+
if (!match) return { data: {}, body: content };
|
|
50
|
+
|
|
51
|
+
const body = match[2].trimStart();
|
|
52
|
+
const data: FrontmatterData = {};
|
|
53
|
+
|
|
54
|
+
let parsed: unknown;
|
|
55
|
+
try {
|
|
56
|
+
// `parseDocument` collects errors instead of throwing, and `.toJS()` returns
|
|
57
|
+
// the best-effort value of whatever parsed — so a single malformed entry
|
|
58
|
+
// doesn't blank the block. (`.toJS()` itself can still throw, e.g. on an
|
|
59
|
+
// alias bomb; the catch keeps the body readable.)
|
|
60
|
+
parsed = parseDocument(match[1]).toJS();
|
|
61
|
+
} catch {
|
|
62
|
+
return { data: {}, body };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
66
|
+
for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
|
|
67
|
+
data[key] = coerce(value);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return { data, body };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Human-readable label for a camelCase frontmatter key */
|
|
75
|
+
export function labelFor(key: string): string {
|
|
76
|
+
return key
|
|
77
|
+
.replace(/([A-Z])/g, ' $1')
|
|
78
|
+
.replace(/^./, s => s.toUpperCase())
|
|
79
|
+
.trim();
|
|
80
|
+
}
|