dsh-extra-paths 0.2.1 → 0.3.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.
Files changed (52) hide show
  1. package/README.md +189 -28
  2. package/README.zh.md +163 -21
  3. package/lib/argv.js +96 -24
  4. package/lib/argv.js.map +1 -1
  5. package/lib/client.js +1169 -467
  6. package/lib/config.js +140 -44
  7. package/lib/config.js.map +1 -1
  8. package/lib/context.js +48 -12
  9. package/lib/context.js.map +1 -1
  10. package/lib/denial.js +132 -0
  11. package/lib/denial.js.map +1 -0
  12. package/lib/index.js +40 -5
  13. package/lib/index.js.map +1 -1
  14. package/lib/name-rule.js +217 -0
  15. package/lib/name-rule.js.map +1 -0
  16. package/lib/paths.js +155 -27
  17. package/lib/paths.js.map +1 -1
  18. package/lib/pattern.js +128 -62
  19. package/lib/pattern.js.map +1 -1
  20. package/lib/platform.js +325 -0
  21. package/lib/platform.js.map +1 -0
  22. package/lib/preview.js +47 -20
  23. package/lib/preview.js.map +1 -1
  24. package/lib/resolve.js +345 -64
  25. package/lib/resolve.js.map +1 -1
  26. package/lib/schema.js +19 -6
  27. package/lib/schema.js.map +1 -1
  28. package/lib/shell-dialect.js +92 -0
  29. package/lib/shell-dialect.js.map +1 -0
  30. package/lib/tool-guard.js +214 -0
  31. package/lib/tool-guard.js.map +1 -0
  32. package/lib/types/argv.d.ts +50 -12
  33. package/lib/types/config.d.ts +29 -13
  34. package/lib/types/context.d.ts +6 -1
  35. package/lib/types/denial.d.ts +88 -0
  36. package/lib/types/index.d.ts +8 -4
  37. package/lib/types/name-rule.d.ts +112 -0
  38. package/lib/types/paths.d.ts +55 -10
  39. package/lib/types/pattern.d.ts +43 -5
  40. package/lib/types/platform.d.ts +148 -0
  41. package/lib/types/preview.d.ts +39 -3
  42. package/lib/types/resolve.d.ts +129 -23
  43. package/lib/types/schema.d.ts +24 -8
  44. package/lib/types/shell-dialect.d.ts +60 -0
  45. package/lib/types/tool-guard.d.ts +103 -0
  46. package/lib/types/wrap-fs.d.ts +86 -4
  47. package/lib/types/wrap-sandbox.d.ts +26 -6
  48. package/lib/wrap-fs.js +323 -47
  49. package/lib/wrap-fs.js.map +1 -1
  50. package/lib/wrap-sandbox.js +149 -12
  51. package/lib/wrap-sandbox.js.map +1 -1
  52. package/package.json +1 -1
package/lib/client.js CHANGED
@@ -37,56 +37,96 @@ window.__ModuleLoader__.load({
37
37
  summaryUnavailable: "Extra writable paths: not offered by this host",
38
38
  summaryEmpty: "Extra writable paths: not configured yet",
39
39
  summaryCount: "Extra writable paths: {count} saved · writing needs no approval",
40
+ introCollapsed: "Extra writable paths outside the workspace, writable without approval; edit them line by line.",
41
+ expand: "Show details",
42
+ collapse: "Hide details",
40
43
  introBefore: "These paths stay writable outside the session workspace, ",
41
44
  introNoApproval: "without approval",
42
- introAfter: "; both the write tools and the terminal honor the surfaces below.",
45
+ introAfter: "; each rule's access level and surfaces decide what the write tools and the terminal may do.",
43
46
  introRuleBefore: "Relative spellings resolve against the base workspace; enforcement uses ",
44
47
  introRuleEmphasis: "each session's own workspace",
45
- introRuleAfter: ", so one configuration points at different directories in different sessions.",
48
+ introRuleAfter: ", so one configuration points at different directories in different sessions. deny/read rules win over writable ones.",
46
49
  baseWorkspace: "Base workspace",
47
50
  notSelected: "(none selected)",
48
- basePlaceholder: "Absolute path, or start with ~/ (for example ~/projects)",
51
+ basePlaceholder: "Absolute path (drive letters / UNC included), or start with ~/",
49
52
  manualBase: "Type a path",
50
53
  pickBase: "Pick from list",
51
54
  baseHint: "Preview and inline resolution only",
55
+ baseForeign: "This host cannot express that base path (platform mismatch); the same configuration still works on a matching host.",
56
+ baseWaiting: "Waiting for the host platform facts (first preview)…",
52
57
  save: "Save",
53
58
  saving: "Saving…",
54
- addPath: "Add path",
55
- addParent: "Add the workspace parent (..)",
56
- discard: "Discard changes",
57
59
  dirty: "Unsaved changes",
58
60
  synced: "In sync with the configuration",
59
- emptyPaths: "No paths configured yet: start with \"Add path\" or \"Add the workspace parent (..)\" above.",
60
- rowTitle: "Path {index}",
61
- delete: "Remove",
62
- pathPlaceholder: "~/projects/notes/home, ../some-repo, .. (parent), ~/projects/**/.worktrees/.. (pattern)",
63
- patternResolved: "Pattern: the host expands it along the directory structure",
64
- patternMatches: "{count} directories match (see the preview below)",
65
- patternNoMatches: "(no matches yet, or capped by the expansion limit)",
66
- resolvePendingEmpty: "The resolved path appears here once you type a path",
67
- resolveNeedsBase: "A relative path needs a base workspace: choose or type one above",
68
- resolveBaseInvalid: "The base workspace must be an absolute path or start with ~/ (for example ~/projects)",
69
- resolveNeedsHome: "~ needs the host home directory (available after the first preview)",
70
- resolvedAs: "Resolves to",
71
- hostResolved: "(host resolves: {path})",
72
- mode: "Applies under",
73
- surfaces: "Surfaces",
74
- surfaceFs: "Write tools",
75
- surfaceShell: "Terminal",
76
- scopeWrite: "Follows the session mode (denied under read-only)",
77
- scopeAlways: "Always writable (allowed under read-only too)",
61
+ textMode: "Text mode",
62
+ textModeHint: "One rule per line: path | access | surfaces. The last two may be omitted — they then inherit the defaults shown below. Expand \"Examples and supported forms\" for the common spellings.",
63
+ editorDefaults: "Omitted fields use: access = {access}, surfaces = {surfaces} (from the config document: defaultAccess / defaultSurfaces).",
64
+ examplesTitle: "Examples and supported forms",
65
+ examplesBody: `# fs-tools protection only -> bare name (.git / .env)
66
+ # bash must be covered too -> a pattern (**/.git)
67
+ # 1-7 below are grouped by purpose; lines starting with # are comments
68
+
69
+ # 1) writable while the session is workspace-write (fs tools AND bash)
70
+ ~/projects/notes/home
71
+ ../../notes/shared | write | fs+shell
72
+
73
+ # 2) read-only: reads allowed, writes refused (also inside the workspace)
74
+ ../shared/docs | read
75
+
76
+ # 3) deny: content reads, listings and writes are refused (fs tools)
77
+ ~/.ssh | deny
78
+
79
+ # 4) always writable (even under read-only), fs tools only
80
+ <work root>/build | always-write | fs
81
+
82
+ # 5) bare name = name rule: that component at any depth under the
83
+ # workspace and the configured writable roots (fs tools only)
84
+ .git | deny | fs
85
+ .env | read | fs
86
+
87
+ # 6) patterns: * = one level, ** = up to three; both surfaces can be covered
88
+ **/.git | read | fs+shell
89
+ **/.env | deny | fs+shell
90
+ <work root>/*/notes | write | fs
91
+
92
+ # 7) Windows / WSL spellings are recognised or translated per host
93
+ C:\work\shared | write
94
+ /mnt/c/work/shared | write
95
+
96
+ # access: deny | read | write | always-write (omitted -> defaultAccess, default write)
97
+ # surfaces: fs | shell | fs+shell (omitted -> defaultSurfaces, default fs+shell)
98
+ # relative paths resolve against the base workspace; ~ is your home directory;
99
+ # lines starting with # and blank lines are ignored`,
100
+ textModeInvalid: "The text has errors and was not applied:",
101
+ textErrorAtLine: "Line {line}: ",
102
+ textErrorEmptyPath: "the path must not be empty",
103
+ textErrorUnknownAccess: "unknown access level \"{value}\" (use deny, read, write or always-write)",
104
+ textErrorUnknownSurfaces: "unknown surfaces \"{value}\" (use fs, shell or fs+shell)",
105
+ textErrorTooManyFields: "too many fields (at most path | access | surfaces)",
106
+ accessDeny: "Deny access",
107
+ accessRead: "Read-only",
108
+ accessWrite: "Writable (follows session)",
109
+ accessAlways: "Always writable",
78
110
  statusOk: "active",
79
111
  statusMissing: "missing",
80
112
  statusRejected: "rejected",
113
+ statusForeign: "not applicable on this host",
114
+ resolveBaseInvalid: "The base workspace must be absolute (a drive or UNC path on Windows too) or start with ~/; a relative path cannot be the base",
115
+ nameRuleHint: "Name rule: matches this component at any depth under the workspace and all configured writable roots — fs tools only; bash is not restricted by it (use a **/<name> path pattern if bash must be covered)",
116
+ nameRuleMatches: "{count} matches right now",
117
+ nameRuleNoMatches: "No matches right now (it still applies to paths created later)",
81
118
  previewTitle: "Resolution preview",
82
119
  previewDirty: " (including unsaved changes)",
83
- previewEffective: "{count} effective roots",
120
+ previewEffective: "{count} effective writable roots",
121
+ previewReadOnly: "{count} read-only",
122
+ previewDenied: "{count} denied",
84
123
  previewNoBase: "Choose or type a base workspace above and the host's effective roots appear here.",
85
- previewBadBase: "The base workspace must be absolute or start with ~/ (for example ~/projects); a relative path cannot be the base.",
124
+ previewBadBase: "The base workspace must be absolute or start with ~/; a relative path cannot be the base.",
86
125
  previewExpandingHome: "Expanding ~: the host home directory arrives with the first preview.",
87
126
  previewUnavailable: "Preview unavailable (the host did not offer the route, the connection is not ready, or it rejected the base workspace).",
88
127
  previewEmpty: "Nothing to resolve yet.",
89
128
  unresolved: "(unresolved)",
129
+ capabilityShellLimit: "The shell sandbox on this host ({dialect}) cannot enforce deny/read rules: bash will not honor them, but the fs tools still enforce them.",
90
130
  saveRefused: "The host refused the save: this configuration may be overridden by a home patch or a command-line overlay (the settings page only writes the profile cordis.patch.yml). Remove the same-id override from ~/.dsh/cordis.patch.yml, or edit the profile patch and restart."
91
131
  };
92
132
  /** Simplified Chinese copy. */
@@ -96,56 +136,94 @@ window.__ModuleLoader__.load({
96
136
  summaryUnavailable: "额外可写路径:宿主未提供该设置",
97
137
  summaryEmpty: "额外可写路径:尚未配置",
98
138
  summaryCount: "额外可写路径:{count} 条 · 保存即生效,写入无需审批",
139
+ introCollapsed: "工作区之外的额外可写路径,写入无需审批;支持按行批量编辑。",
140
+ expand: "展开",
141
+ collapse: "收起",
99
142
  introBefore: "这些路径在会话工作区之外也可以写,",
100
143
  introNoApproval: "不需要审批",
101
- introAfter: ";写工具与终端都按下面的「作用面」生效。",
144
+ introAfter: ";访问级别与「作用面」决定写工具和终端各自的行为。",
102
145
  introRuleBefore: "相对路径按「基准工作区」解析——执法时用的是",
103
146
  introRuleEmphasis: "各会话自己的工作区",
104
- introRuleAfter: ",所以同一份配置在不同会话会指向不同目录。",
147
+ introRuleAfter: ",所以同一份配置在不同会话会指向不同目录。deny/只读规则优先于可写规则。",
105
148
  baseWorkspace: "基准工作区",
106
149
  notSelected: "(未选择)",
107
- basePlaceholder: "绝对路径,或以 ~/ 开头(例如 ~/projects)",
150
+ basePlaceholder: "绝对路径(含 Windows 盘符/UNC),或以 ~/ 开头",
108
151
  manualBase: "手填",
109
152
  pickBase: "从列表选",
110
153
  baseHint: "仅用于预览与行内解析",
154
+ baseForeign: "当前宿主无法表达这个基准路径(平台不匹配);同一份配置在匹配的宿主上仍然可用。",
155
+ baseWaiting: "正在等待宿主返回平台信息(首次预览)…",
111
156
  save: "保存",
112
157
  saving: "保存中…",
113
- addPath: "添加路径",
114
- addParent: "添加工作区上一层(..)",
115
- discard: "放弃修改",
116
158
  dirty: "有未保存的修改",
117
159
  synced: "已与配置同步",
118
- emptyPaths: "还没有配置路径:用上面的「添加路径」或「添加工作区上一层(..)」开始。",
119
- rowTitle: "路径 {index}",
120
- delete: "删除",
121
- pathPlaceholder: "~/projects/notes/home、../某仓库、..(上一层)、~/projects/**/.worktrees/..(模式)",
122
- patternResolved: "模式:由宿主按目录结构展开",
123
- patternMatches: "当前命中 {count} 个目录(见下方预览)",
124
- patternNoMatches: "(暂无命中,或被展开上限拦截)",
125
- resolvePendingEmpty: "填入路径后这里会显示解析结果",
126
- resolveNeedsBase: "相对路径需要基准工作区:请在上面选择或填写",
127
- resolveBaseInvalid: "基准工作区需要绝对路径,或以 ~/ 开头(例如 ~/projects)",
128
- resolveNeedsHome: "~ 需要宿主的家目录(第一次预览返回后即可解析)",
129
- resolvedAs: "解析为",
130
- hostResolved: "(宿主解析:{path})",
131
- mode: "生效模式",
132
- surfaces: "作用面",
133
- surfaceFs: "写工具",
134
- surfaceShell: "终端",
135
- scopeWrite: "随会话模式(read-only 下拒绝)",
136
- scopeAlways: "始终可写(read-only 下也允许)",
160
+ textMode: "文本模式",
161
+ textModeHint: "每行一条规则:路径 | 访问级别 | 作用面。后两段可省略,省略时使用下方显示的默认值。展开「示例与支持的写法」查看常用形式。",
162
+ editorDefaults: "省略字段时的默认值:访问级别 = {access},作用面 = {surfaces}(来自配置文档的 defaultAccess / defaultSurfaces)。",
163
+ examplesTitle: "示例与支持的写法",
164
+ examplesBody: `# 仅保护 fs 工具 -> 裸名(.git / .env)
165
+ # 要让 bash 也受约束 -> 模式(**/.git)
166
+ # 下面 1-7 按用途分组;# 开头的行都是注释
167
+
168
+ # 1) 可写(随会话):fs 工具与 bash 都放行
169
+ ~/projects/notes/home
170
+ ../../notes/shared | write | fs+shell
171
+
172
+ # 2) 只读:读允许、写拒绝(工作区内的目录也能这样降级)
173
+ ../shared/docs | read
174
+
175
+ # 3) 禁止访问:内容读取、目录列举与写入都拒绝(fs 工具)
176
+ ~/.ssh | deny
177
+
178
+ # 4) 始终可写(read-only 会话也放行),只作用于 fs 工具
179
+ <工作根>/build | always-write | fs
180
+
181
+ # 5) 裸名 = 名称规则:工作区与可写根内任意深度的同名路径(仅 fs 工具)
182
+ .git | deny | fs
183
+ .env | read | fs
184
+
185
+ # 6) 模式:* 一层 / ** 最多三层;可同时覆盖 fs 与 shell
186
+ **/.git | read | fs+shell
187
+ **/.env | deny | fs+shell
188
+ <工作根>/*/notes | write | fs
189
+
190
+ # 7) Windows / WSL 写法会按当前宿主识别或互译
191
+ C:\work\shared | write
192
+ /mnt/c/work/shared | write
193
+
194
+ # 级别:deny | read | write | always-write (省略 -> defaultAccess,默认 write)
195
+ # 作用面:fs | shell | fs+shell (省略 -> defaultSurfaces,默认 fs+shell)
196
+ # 相对路径按「基准工作区」解析;~ 是家目录;# 开头为注释、空行忽略`,
197
+ textModeInvalid: "文本有误,尚未应用:",
198
+ textErrorAtLine: "第 {line} 行:",
199
+ textErrorEmptyPath: "路径不能为空",
200
+ textErrorUnknownAccess: "未知的访问级别「{value}」(可用 deny、read、write、always-write)",
201
+ textErrorUnknownSurfaces: "未知的作用面「{value}」(可用 fs、shell、fs+shell)",
202
+ textErrorTooManyFields: "字段过多(最多 path | access | surfaces 三段)",
203
+ accessDeny: "禁止访问",
204
+ accessRead: "只读",
205
+ accessWrite: "可写(随会话)",
206
+ accessAlways: "始终可写",
137
207
  statusOk: "生效",
138
- statusMissing: "目录不存在",
208
+ statusMissing: "缺失",
139
209
  statusRejected: "已拒绝",
210
+ statusForeign: "当前平台不适用",
211
+ resolveBaseInvalid: "基准工作区需要绝对路径(含 Windows 盘符/UNC),或以 ~/ 开头;相对路径不能当基准用",
212
+ nameRuleHint: "名称规则:工作区与所有可写根内任意深度匹配(仅 fs 工具;bash 不受此规则约束;要让 bash 也生效请改用 **/<名字> 模式)",
213
+ nameRuleMatches: "当前匹配 {count} 处",
214
+ nameRuleNoMatches: "当前暂无匹配(对新建路径仍生效)",
140
215
  previewTitle: "解析预览",
141
216
  previewDirty: "(含未保存修改)",
142
217
  previewEffective: "生效根 {count} 条",
218
+ previewReadOnly: "只读 {count} 条",
219
+ previewDenied: "禁止 {count} 条",
143
220
  previewNoBase: "先在上面选择或填写「基准工作区」,这里就会显示宿主解析出的生效根。",
144
- previewBadBase: "基准工作区需要绝对路径,或以 ~/ 开头(例如 ~/projects);相对路径不能当基准用。",
221
+ previewBadBase: "基准工作区需要绝对路径,或以 ~/ 开头;相对路径不能当基准用。",
145
222
  previewExpandingHome: "正在展开 ~:宿主的家目录会在第一次预览返回后给出。",
146
223
  previewUnavailable: "预览不可用(宿主没提供该路由、连接还没就绪,或基准工作区被宿主拒绝)。",
147
224
  previewEmpty: "还没有可解析的路径。",
148
225
  unresolved: "(未解析)",
226
+ capabilityShellLimit: "当前 shell 沙箱({dialect})无法执行「禁止访问/只读」规则:bash 不受该限制,但 fs 工具仍按规则拦截。",
149
227
  saveRefused: "保存被宿主拒绝:该配置可能被 home patch 或命令行覆盖(设置页只写 profile 的 cordis.patch.yml)。请删掉 ~/.dsh/cordis.patch.yml 里同 id 的覆盖,或直接改 profile patch 后重启。"
150
228
  };
151
229
  /** Fill `{name}` placeholders; unknown names stay verbatim, like the host seat. */
@@ -159,24 +237,79 @@ window.__ModuleLoader__.load({
159
237
  */
160
238
  const fallbackTranslate = (key, params) => format(zh[key], params);
161
239
  //#endregion
162
- //#region src/client/paths.ts
240
+ //#region src/platform.ts
241
+ /** The default WSL drive mount root. */
242
+ const DEFAULT_WSL_MOUNT_ROOT = "/mnt";
243
+ /** Extended-length prefix `\\?\` (and `\\?\UNC\`). */
244
+ const EXTENDED_PREFIX = /^\\\\\?\\/;
245
+ const EXTENDED_UNC_PREFIX = /^\\\\\?\\UNC\\/i;
246
+ /** `C:\` or `C:/` — a drive-rooted absolute path. */
247
+ const WIN_DRIVE_ABSOLUTE = /^[A-Za-z]:[\\/]/;
248
+ /** `C:foo` — drive-RELATIVE (resolved against that drive's current directory). */
249
+ const WIN_DRIVE_RELATIVE = /^[A-Za-z]:(?![\\/])/;
250
+ /** `\\server\share\x` — a UNC path (two leading backslashes, a server name). */
251
+ const WIN_UNC = /^\\\\[^\\]/;
252
+ /** `//server/share/x` — UNC spelled with forward separators. */
253
+ const WIN_UNC_FORWARD = /^\/\/[^/]+\/[^/]+/;
254
+ /** A single leading separator that is neither `\\` nor `/`: `\foo` (current drive). */
255
+ const WIN_CURRENT_DRIVE = /^\\(?!\\)/;
256
+ /** Strip a Windows extended-length prefix, which only adds noise to comparison. */
257
+ function stripWindowsPrefix(spelling) {
258
+ if (EXTENDED_UNC_PREFIX.test(spelling)) return `\\\\${spelling.slice(8)}`;
259
+ if (EXTENDED_PREFIX.test(spelling)) return spelling.slice(4);
260
+ return spelling;
261
+ }
262
+ /** The logical host dialect. */
263
+ function hostDialect(facts) {
264
+ return facts.platform === "win32" ? "windows" : "posix";
265
+ }
266
+ /**
267
+ * Classify one spelling without consulting the host.
268
+ * @param spelling - the raw configured spelling (trimmed by the caller).
269
+ * @returns what kind of path it is.
270
+ */
271
+ function classifySpelling(spelling) {
272
+ if (spelling === "~") return "home";
273
+ if (spelling.startsWith("~/")) return "home";
274
+ if (spelling.startsWith("~\\")) return "windows-home";
275
+ const stripped = stripWindowsPrefix(spelling);
276
+ if (WIN_DRIVE_ABSOLUTE.test(stripped) || WIN_UNC.test(stripped)) return "windows-absolute";
277
+ if (WIN_UNC_FORWARD.test(stripped)) return "windows-absolute";
278
+ if (WIN_DRIVE_RELATIVE.test(stripped)) return "windows-drive-relative";
279
+ if (spelling.startsWith("/")) return "posix-absolute";
280
+ if (WIN_CURRENT_DRIVE.test(stripped)) return "windows-current-drive";
281
+ return "relative";
282
+ }
163
283
  /**
164
- * Lexical path resolution for the settings page's live column. It mirrors the
165
- * host's `expandPath` (a relative entry resolves against the session workspace,
166
- * `~` against the home directory) WITHOUT touching the filesystem, so a
167
- * half-typed row can show where it would land before it is saved.
284
+ * Whether a spelling is a BARE NAME (`.git`, `.env`, `node_modules`): one path
285
+ * component, no separator, no wildcard, not the `.`/`..` relative specials and
286
+ * not a `~` spelling. A bare name is a NAME RULE — it matches that component at
287
+ * any depth under the rule's scope roots rather than naming one literal path.
168
288
  *
169
- * Symbolic links are deliberately not resolved here — the browser cannot
170
- * realpath. The host's own preview is the authoritative answer, and the page
171
- * keeps showing both: this one instantly, the host's on every settled edit.
172
- * @module dsh-extra-paths/client/paths
289
+ * The `./name` spelling is the escape hatch for a literal single-component
290
+ * relative path (it contains a separator, so it stays a normal relative path).
291
+ * @param spelling - the raw configured spelling.
292
+ * @returns true when the spelling is a name rule.
173
293
  */
294
+ function isBareNameSpelling(spelling) {
295
+ if (spelling === "" || spelling === "." || spelling === "..") return false;
296
+ if (spelling.startsWith("~")) return false;
297
+ if (spelling.includes("*")) return false;
298
+ if (/^[A-Za-z]:/.test(spelling)) return false;
299
+ return !spelling.includes("/") && !spelling.includes("\\");
300
+ }
174
301
  /**
175
- * Collapse `.`, `..` and duplicate separators in an absolute POSIX spelling.
176
- * @param path - an absolute spelling (the caller guarantees the leading `/`).
177
- * @returns the collapsed absolute path; `..` above the root is clamped there.
302
+ * Whether a spelling is absolute in its own dialect (a `~` spelling counts:
303
+ * the caller expands home first).
304
+ * @param spelling - the raw configured spelling.
305
+ * @returns true for home, POSIX-absolute and Windows-absolute spellings.
178
306
  */
179
- function collapse(path) {
307
+ function isAbsoluteSpelling(spelling) {
308
+ const kind = classifySpelling(spelling);
309
+ return kind === "home" || kind === "windows-home" || kind === "posix-absolute" || kind === "windows-absolute";
310
+ }
311
+ /** Collapse `.`, `..` and duplicate separators in an absolute POSIX spelling. */
312
+ function collapsePosix(path) {
180
313
  const segments = [];
181
314
  for (const segment of path.split("/")) {
182
315
  if (segment === "" || segment === ".") continue;
@@ -189,36 +322,491 @@ window.__ModuleLoader__.load({
189
322
  return `/${segments.join("/")}`;
190
323
  }
191
324
  /**
192
- * Resolve one configured entry the way the host will, lexically.
193
- * @param entry - the row's raw spelling.
194
- * @param workspaceRoot - the workspace a relative entry resolves against.
195
- * @param home - the host's home directory, once the preview has reported it.
196
- * @returns the absolute path, or undefined when it cannot be resolved yet
197
- * (`~` before the home directory is known, or a relative entry with no usable
198
- * workspace base).
325
+ * Collapse an absolute Windows spelling (drive or UNC) into its native form.
326
+ * The result uses `\` separators; case is preserved (Windows comparison folds
327
+ * case later, but the host's `realpath`/ACL layers still want the real spelling).
328
+ * @param path - an absolute Windows spelling using either separator.
329
+ * @returns the collapsed spelling, e.g. `C:\Users\me\x` or `\\server\share\x`.
330
+ */
331
+ function collapseWindows(path) {
332
+ const stripped = stripWindowsPrefix(path).replaceAll("/", "\\");
333
+ if (WIN_UNC.test(stripped)) {
334
+ const parts = stripped.slice(2).split("\\");
335
+ const server = parts.shift() ?? "";
336
+ const share = parts.shift() ?? "";
337
+ const rest = collapseWindowsSegments(parts);
338
+ return `\\\\${server}\\${share}${rest === "" ? "" : `\\${rest}`}`;
339
+ }
340
+ return `${stripped.slice(0, 2)}\\${collapseWindowsSegments(stripped.slice(2).split("\\"))}`;
341
+ }
342
+ /** Collapse one segment list, clamping `..` at the start. */
343
+ function collapseWindowsSegments(segments) {
344
+ const out = [];
345
+ for (const segment of segments) {
346
+ if (segment === "" || segment === ".") continue;
347
+ if (segment === "..") {
348
+ out.pop();
349
+ continue;
350
+ }
351
+ out.push(segment);
352
+ }
353
+ return out.join("\\");
354
+ }
355
+ /** Join a home directory and a `~`-relative rest in the host's dialect. */
356
+ function homeJoin(home, rest, dialect) {
357
+ const trimmed = rest.replace(dialect === "windows" ? /^[\\/]+/ : /^\/+/, "");
358
+ if (trimmed === "") return dialect === "windows" ? collapseWindows(home) : collapsePosix(home);
359
+ return dialect === "windows" ? collapseWindows(`${home}\\${trimmed}`) : collapsePosix(`${home}/${trimmed}`);
360
+ }
361
+ /** Resolve a relative spelling against the workspace base in one dialect. */
362
+ function resolveRelative(base, spelling, dialect) {
363
+ if (dialect === "windows") return collapseWindows(`${base}\\${spelling}`);
364
+ return collapsePosix(`${base}/${spelling}`);
365
+ }
366
+ /** Build a `foreign` outcome: the spelling has no meaning on this host. */
367
+ function foreign(reason) {
368
+ return {
369
+ ok: false,
370
+ foreign: reason
371
+ };
372
+ }
373
+ /**
374
+ * Translate a Windows absolute spelling into its WSL spelling.
375
+ * @param spelling - a drive-rooted or UNC spelling (any separator).
376
+ * @param mountRoot - the WSL mount root, normally `/mnt`.
377
+ * @returns the POSIX spelling, or undefined for a share UNC path (no mapping).
199
378
  */
200
- function resolveLexically(entry, workspaceRoot, home) {
201
- const trimmed = entry.trim();
202
- if (trimmed === "") return void 0;
203
- if (trimmed === "~" || trimmed.startsWith("~/")) {
204
- if (home === void 0 || home === "") return void 0;
205
- return collapse(trimmed === "~" ? home : `${home}/${trimmed.slice(2)}`);
379
+ function windowsToWsl(spelling, mountRoot = DEFAULT_WSL_MOUNT_ROOT) {
380
+ const stripped = stripWindowsPrefix(spelling).replaceAll("\\", "/");
381
+ const drive = /^([A-Za-z]):(?:\/|$)/.exec(stripped);
382
+ if (drive === null) return void 0;
383
+ const letter = (drive[1] ?? "").toLowerCase();
384
+ const rest = stripped.slice(drive[0].length);
385
+ const root = mountRoot.replace(/\/+$/, "");
386
+ const tail = rest.replace(/^\/+/, "");
387
+ return tail === "" ? `${root}/${letter}` : `${root}/${letter}/${tail}`;
388
+ }
389
+ /**
390
+ * Translate a POSIX spelling that names a Windows drive into its Windows form.
391
+ * Two conventions are recognized: WSL's `/mnt/<letter>/…` and the MSYS/git-bash
392
+ * `/c/…` form. The caller verifies the result by resolving it (existence is the
393
+ * only proof that the drive really exists on this host).
394
+ * @param spelling - an absolute POSIX spelling.
395
+ * @param mountRoot - the WSL drive mount root, normally `/mnt`.
396
+ * @returns the Windows spelling, or undefined when the spelling is not a drive.
397
+ */
398
+ function posixToWindows(spelling, mountRoot = DEFAULT_WSL_MOUNT_ROOT) {
399
+ const root = mountRoot.replace(/\/+$/, "");
400
+ const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
401
+ const mounted = new RegExp(`^${escape(root)}/([A-Za-z])(?:/(.*))?$`).exec(spelling);
402
+ if (mounted !== null) return windowsFromParts(mounted[1] ?? "", mounted[2]);
403
+ const msys = /^\/([A-Za-z])(?:\/(.*))?$/.exec(spelling);
404
+ if (msys !== null) return windowsFromParts(msys[1] ?? "", msys[2]);
405
+ }
406
+ /** Assemble a Windows drive path from a drive letter and a `/`-separated rest. */
407
+ function windowsFromParts(letter, rest) {
408
+ const drive = letter.toUpperCase();
409
+ return rest === void 0 || rest === "" ? `${drive}:\\` : `${drive}:\\${rest.replaceAll("/", "\\")}`;
410
+ }
411
+ /**
412
+ * Resolve one configured spelling to a HOST-NATIVE absolute path.
413
+ *
414
+ * Translation happens only when the spelling's dialect differs from the host's:
415
+ * a Windows spelling inside WSL becomes `/mnt/<drive>/…`, a `/mnt/<drive>/…`
416
+ * spelling on a native Windows host becomes `<Drive>:\…`. A spelling with no
417
+ * mapping on this host is `foreign`: the caller marks the entry inactive with a
418
+ * warning instead of failing the whole configuration.
419
+ * @param spelling - the configured spelling (already trimmed).
420
+ * @param workspaceRoot - the session workspace a relative spelling resolves against.
421
+ * @param facts - host platform facts.
422
+ * @returns the host-native absolute path, or the reason it is foreign.
423
+ */
424
+ function expandPath(spelling, workspaceRoot, facts) {
425
+ const dialect = hostDialect(facts);
426
+ switch (classifySpelling(spelling)) {
427
+ case "home": return {
428
+ ok: true,
429
+ path: homeJoin(facts.home, spelling.slice(1), dialect),
430
+ dialect,
431
+ translated: false
432
+ };
433
+ case "windows-home":
434
+ if (dialect === "windows") return {
435
+ ok: true,
436
+ path: homeJoin(facts.home, spelling.slice(1), dialect),
437
+ dialect,
438
+ translated: false
439
+ };
440
+ return foreign(`the Windows home spelling ${JSON.stringify(spelling)} is only understood on a Windows host`);
441
+ case "posix-absolute":
442
+ if (dialect === "posix") return {
443
+ ok: true,
444
+ path: collapsePosix(spelling),
445
+ dialect,
446
+ translated: false
447
+ };
448
+ {
449
+ const mapped = posixToWindows(spelling, facts.wslMountRoot);
450
+ if (mapped !== void 0) return {
451
+ ok: true,
452
+ path: collapseWindows(mapped),
453
+ dialect,
454
+ translated: true
455
+ };
456
+ return foreign(`the POSIX path ${JSON.stringify(spelling)} cannot be expressed on a Windows host`);
457
+ }
458
+ case "windows-absolute":
459
+ if (dialect === "windows") return {
460
+ ok: true,
461
+ path: collapseWindows(spelling),
462
+ dialect,
463
+ translated: false
464
+ };
465
+ if (facts.wsl) {
466
+ const mapped = windowsToWsl(spelling, facts.wslMountRoot);
467
+ if (mapped !== void 0) return {
468
+ ok: true,
469
+ path: collapsePosix(mapped),
470
+ dialect,
471
+ translated: true
472
+ };
473
+ return foreign(`the UNC path ${JSON.stringify(spelling)} has no reliable WSL mapping`);
474
+ }
475
+ return foreign(`the Windows path ${JSON.stringify(spelling)} is only understood on a Windows host or inside WSL`);
476
+ case "windows-drive-relative": return foreign(`the drive-relative spelling ${JSON.stringify(spelling)} is ambiguous and refused`);
477
+ case "windows-current-drive":
478
+ if (dialect === "windows") return foreign(`the current-drive spelling ${JSON.stringify(spelling)} is ambiguous and refused`);
479
+ return {
480
+ ok: true,
481
+ path: resolveRelative(workspaceRoot, spelling, dialect),
482
+ dialect,
483
+ translated: false
484
+ };
485
+ default: return {
486
+ ok: true,
487
+ path: resolveRelative(workspaceRoot, spelling, dialect),
488
+ dialect,
489
+ translated: false
490
+ };
206
491
  }
207
- if (trimmed.startsWith("/")) return collapse(trimmed);
208
- if (!workspaceRoot.startsWith("/")) return void 0;
209
- return collapse(`${workspaceRoot}/${trimmed}`);
492
+ }
493
+ //#endregion
494
+ //#region src/client/paths.ts
495
+ /** All access levels, in the order the dropdown offers them (strict → permissive). */
496
+ const ACCESSES = [
497
+ "deny",
498
+ "read",
499
+ "write",
500
+ "always-write"
501
+ ];
502
+ /** All enforcement surfaces. */
503
+ const SURFACES = ["fs", "shell"];
504
+ /** The plugin's default surfaces when a stored entry does not say. */
505
+ const DEFAULT_SURFACES = ["fs", "shell"];
506
+ function accessOf(value) {
507
+ return typeof value === "string" && ACCESSES.includes(value) ? value : void 0;
508
+ }
509
+ function surfacesOf(value) {
510
+ if (!Array.isArray(value)) return void 0;
511
+ const surfaces = [];
512
+ for (const item of value) {
513
+ if (typeof item !== "string" || !SURFACES.includes(item)) continue;
514
+ if (!surfaces.includes(item)) surfaces.push(item);
515
+ }
516
+ return surfaces.length > 0 ? surfaces : void 0;
517
+ }
518
+ /**
519
+ * The defaults a stored section declares, with the legacy `defaultScope` alias
520
+ * and the plugin defaults as fallbacks.
521
+ * @param section - the stored section, when the host has one.
522
+ * @returns access + surfaces to use for entries that omit them.
523
+ */
524
+ function defaultsOf(section) {
525
+ return {
526
+ access: accessOf(section?.defaultAccess) ?? accessOf(section?.defaultScope) ?? "write",
527
+ surfaces: surfacesOf(section?.defaultSurfaces) ?? [...DEFAULT_SURFACES]
528
+ };
529
+ }
530
+ /**
531
+ * Turn a stored section into editable rows. Accepts every shape the host half
532
+ * still accepts: a bare string (the defaults apply), an entry with `access`, and
533
+ * the legacy `scope` (mapped onto the same vocabulary). Unknown vocabulary falls
534
+ * back to the defaults instead of crashing the page — the save-time validator is
535
+ * where an invalid document is reported.
536
+ * @param section - the stored section.
537
+ * @returns the editable rows in stored order.
538
+ */
539
+ function rowsOf(section) {
540
+ const defaults = defaultsOf(section);
541
+ const rows = [];
542
+ for (const item of section?.paths ?? []) {
543
+ if (typeof item === "string") {
544
+ rows.push({
545
+ path: item,
546
+ access: defaults.access,
547
+ surfaces: [...defaults.surfaces]
548
+ });
549
+ continue;
550
+ }
551
+ if (item === null || typeof item !== "object") continue;
552
+ rows.push({
553
+ path: typeof item.path === "string" ? item.path : "",
554
+ access: accessOf(item.access) ?? accessOf(item.scope) ?? defaults.access,
555
+ surfaces: surfacesOf(item.surfaces) ?? [...defaults.surfaces]
556
+ });
557
+ }
558
+ return rows;
559
+ }
560
+ /**
561
+ * Serialise the rows into the structured payload the page saves and previews.
562
+ * Empty paths (a row just added and not typed into yet) are dropped, matching
563
+ * the host's own "path must be a non-empty string" rule.
564
+ * @param rows - the editable rows.
565
+ * @returns `{path, access, surfaces}` objects with trimmed paths.
566
+ */
567
+ function payloadOf(rows) {
568
+ const payload = [];
569
+ for (const row of rows) {
570
+ const path = row.path.trim();
571
+ if (path === "") continue;
572
+ payload.push({
573
+ path,
574
+ access: row.access,
575
+ surfaces: [...row.surfaces]
576
+ });
577
+ }
578
+ return payload;
579
+ }
580
+ /** The canonical `+`-joined surface spelling (`fs+shell`). */
581
+ function surfacesText(surfaces) {
582
+ return SURFACES.filter((surface) => surfaces.includes(surface)).join("+");
583
+ }
584
+ /**
585
+ * Render one rule in the EXPLICIT text form: `path | access | surfaces`.
586
+ *
587
+ * The editor deliberately does not omit values that happen to equal the plugin
588
+ * defaults: the user configured those fields in the list view and expects to
589
+ * see them when switching to text mode (a bare `path` looked like the access
590
+ * and surface settings had been lost). Explicit output also round-trips
591
+ * independent of any future default change. The parser still accepts the short
592
+ * forms (`path`, `path | access`) when hand-typing.
593
+ * @param row - one rule.
594
+ * @returns one text-mode line.
595
+ */
596
+ function formatRule(row) {
597
+ return `${row.path.trim()} | ${row.access} | ${surfacesText(row.surfaces)}`;
598
+ }
599
+ /**
600
+ * Render the current rows for the text-mode editor.
601
+ * @param rows - the current rows.
602
+ * @returns one explicit line per non-empty rule.
603
+ */
604
+ function serializeRules(rows) {
605
+ return rows.filter((row) => row.path.trim() !== "").map(formatRule).join("\n");
606
+ }
607
+ /** Parse the optional `| surfaces` field (`fs`, `shell`, `fs+shell`, also `shell+fs`). */
608
+ function parseSurfacesField(value) {
609
+ const parts = value.split(/[+,\s]+/).filter((part) => part !== "");
610
+ const surfaces = [];
611
+ for (const part of parts) {
612
+ if (!SURFACES.includes(part)) return void 0;
613
+ if (!surfaces.includes(part)) surfaces.push(part);
614
+ }
615
+ const ordered = SURFACES.filter((surface) => surfaces.includes(surface));
616
+ return ordered.length > 0 ? ordered : void 0;
617
+ }
618
+ /**
619
+ * Parse the bulk text editor. Blank lines and lines whose first non-space
620
+ * character is `#` are comments/separators and are skipped. A line is
621
+ * `path`, `path | access`, or `path | access | surfaces`.
622
+ * @param text - the editor content.
623
+ * @param defaults - the defaults a missing access/surfaces field inherits.
624
+ * @returns the parsed rules, or every per-line error (nothing is applied then).
625
+ */
626
+ function parseRules(text, defaults = defaultsOf(void 0)) {
627
+ const rules = [];
628
+ const errors = [];
629
+ text.split(/\r?\n/).forEach((line, index) => {
630
+ const lineNo = index + 1;
631
+ const trimmed = line.trim();
632
+ if (trimmed === "" || trimmed.startsWith("#")) return;
633
+ const fields = trimmed.split("|").map((field) => field.trim());
634
+ if (fields.length > 3) {
635
+ errors.push({
636
+ line: lineNo,
637
+ code: "too-many-fields"
638
+ });
639
+ return;
640
+ }
641
+ const path = fields[0] ?? "";
642
+ if (path === "") {
643
+ errors.push({
644
+ line: lineNo,
645
+ code: "empty-path"
646
+ });
647
+ return;
648
+ }
649
+ let access = defaults.access;
650
+ if (fields.length >= 2) {
651
+ const parsed = accessOf(fields[1]);
652
+ if (parsed === void 0) {
653
+ errors.push({
654
+ line: lineNo,
655
+ code: "unknown-access",
656
+ value: fields[1] ?? ""
657
+ });
658
+ return;
659
+ }
660
+ access = parsed;
661
+ }
662
+ let surfaces = [...defaults.surfaces];
663
+ if (fields.length === 3) {
664
+ const parsed = parseSurfacesField(fields[2] ?? "");
665
+ if (parsed === void 0) {
666
+ errors.push({
667
+ line: lineNo,
668
+ code: "unknown-surfaces",
669
+ value: fields[2] ?? ""
670
+ });
671
+ return;
672
+ }
673
+ surfaces = parsed;
674
+ }
675
+ rules.push({
676
+ path,
677
+ access,
678
+ surfaces
679
+ });
680
+ });
681
+ return errors.length > 0 ? {
682
+ ok: false,
683
+ errors
684
+ } : {
685
+ ok: true,
686
+ rules
687
+ };
688
+ }
689
+ /**
690
+ * Whether a configured spelling is a NAME RULE (`.git`, `.env`, `node_modules`):
691
+ * one component, no separator, matched at ANY depth under the session workspace
692
+ * and every configured writable root. It is not a path, so it has no lexical
693
+ * resolution — the host matches it live per call and reports a match count for
694
+ * the preview.
695
+ *
696
+ * The spelling vocabulary is shared with the host half through `../platform`
697
+ * (pure string functions). The node-only rule engine (`../name-rule`) must never
698
+ * be imported here: this module is bundled into the browser client.
699
+ * @param path - the raw configured spelling.
700
+ * @returns true when the host treats the entry as a name rule.
701
+ */
702
+ function isNameRulePath(path) {
703
+ return isBareNameSpelling(path.trim());
704
+ }
705
+ /** The POSIX-ish fallback used before the host reports its real platform. */
706
+ const FALLBACK_FACTS = Object.freeze({
707
+ platform: "unknown",
708
+ wsl: false,
709
+ wslMountRoot: "/mnt",
710
+ home: ""
711
+ });
712
+ /**
713
+ * Build the path facts from a preview payload. Before the first preview there
714
+ * are no facts: the page then assumes a POSIX host for its instant hint and
715
+ * refuses to claim ANY Windows spelling resolves (it waits for the host's platform facts).
716
+ * @param preview - the preview payload, when one has arrived.
717
+ * @returns the facts plus a flag saying whether they came from the host.
718
+ */
719
+ function hostViewOf(preview) {
720
+ const report = preview?.platform;
721
+ if (report === void 0) return {
722
+ facts: FALLBACK_FACTS,
723
+ known: false
724
+ };
725
+ return {
726
+ known: true,
727
+ facts: {
728
+ platform: report.platform,
729
+ wsl: report.wsl,
730
+ wslMountRoot: report.wslMountRoot ?? "/mnt",
731
+ home: preview?.home ?? ""
732
+ }
733
+ };
734
+ }
735
+ /**
736
+ * Resolve the base-workspace field the way the host will. The field accepts an
737
+ * absolute spelling in the HOST's dialect (`C:\…`, `\\server\share\…`), a `~`
738
+ * spelling, and nothing relative.
739
+ * @param spelling - the raw field value.
740
+ * @param host - the host facts view.
741
+ * @returns the host-native absolute base, or why it cannot be used.
742
+ */
743
+ function resolveBase(spelling, host) {
744
+ const trimmed = spelling.trim();
745
+ if (trimmed === "") return {
746
+ ok: false,
747
+ problem: "empty"
748
+ };
749
+ const kind = classifySpelling(trimmed);
750
+ if (kind === "home" || kind === "windows-home") {
751
+ if (host.facts.home === "") return {
752
+ ok: false,
753
+ problem: "waiting"
754
+ };
755
+ } else if (kind === "windows-absolute") {
756
+ if (!host.known) return {
757
+ ok: false,
758
+ problem: "waiting"
759
+ };
760
+ } else if (!isAbsoluteSpelling(trimmed)) return {
761
+ ok: false,
762
+ problem: "relative"
763
+ };
764
+ const outcome = expandPath(trimmed, "", host.facts);
765
+ if (outcome.ok) return {
766
+ ok: true,
767
+ base: outcome.path
768
+ };
769
+ if (!host.known) return {
770
+ ok: false,
771
+ problem: "waiting"
772
+ };
773
+ return {
774
+ ok: false,
775
+ problem: "foreign",
776
+ reason: outcome.foreign
777
+ };
778
+ }
779
+ /**
780
+ * Which base spelling to send with the preview request.
781
+ *
782
+ * Normally it is the resolved host-native base. While the page still waits for
783
+ * the platform facts it sends the RAW absolute spelling instead: the HOST is the
784
+ * one that knows its dialect, so it accepts `C:\…` on Windows, `/mnt/c/…` in
785
+ * WSL and `~` anywhere (expanding it with the real home directory). Without this
786
+ * a Windows workspace candidate would leave the page waiting for facts forever —
787
+ * it refuses to claim the Windows base resolves, but the host can prove it.
788
+ * Relative/empty spellings are never sent (the host rejects them anyway).
789
+ * @param spelling - the raw base field value.
790
+ * @param base - the lexical base outcome.
791
+ * @returns the query value, or '' when there is nothing usable to ask about.
792
+ */
793
+ function previewBaseOf(spelling, base) {
794
+ if (base.ok) return base.base;
795
+ const trimmed = spelling.trim();
796
+ if (base.problem === "waiting" && isAbsoluteSpelling(trimmed)) return trimmed;
797
+ return "";
210
798
  }
211
799
  //#endregion
212
800
  //#region src/client/preview.ts
213
801
  const ROUTE = "/extra-paths/resolved";
214
802
  /**
215
- * Fetch the effective roots for one workspace.
803
+ * Fetch the host's answer for one workspace.
216
804
  *
217
805
  * The unsaved rows travel with the request so the answer describes the DRAFT:
218
806
  * previously the preview only ever described the stored document, which is what
219
807
  * made configuring a relative path a guess-until-you-save exercise.
220
- * @param cwd - the workspace path to resolve against.
221
- * @param paths - the page's current rows (strings or `{path, scope, surfaces}`).
808
+ * @param cwd - the (host-native, absolute) workspace path to resolve against.
809
+ * @param paths - the page's current rows as `{path, access, surfaces}`.
222
810
  * @param signal - optional abort signal.
223
811
  * @returns the preview, or undefined when the route is unavailable.
224
812
  */
@@ -239,15 +827,6 @@ window.__ModuleLoader__.load({
239
827
  //#endregion
240
828
  //#region src/client/styles.ts
241
829
  const box = { boxSizing: "border-box" };
242
- const card = {
243
- ...box,
244
- display: "flex",
245
- flexDirection: "column",
246
- gap: 8,
247
- padding: "10px 12px",
248
- border: "1px solid var(--dsh-color-border, rgba(128,128,128,0.25))",
249
- borderRadius: 8
250
- };
251
830
  const button = {
252
831
  ...box,
253
832
  padding: "4px 10px",
@@ -258,131 +837,114 @@ window.__ModuleLoader__.load({
258
837
  fontSize: 12,
259
838
  cursor: "pointer"
260
839
  };
840
+ ({ ...box });
261
841
  /** The page's style map. */
262
842
  const styles = {
263
843
  page: {
264
844
  display: "flex",
265
845
  flexDirection: "column",
266
- gap: 12,
846
+ gap: 10,
267
847
  padding: "4px 0",
268
- maxWidth: 760
848
+ maxWidth: 860
849
+ },
850
+ introLine: {
851
+ display: "flex",
852
+ gap: 6,
853
+ alignItems: "baseline",
854
+ flexWrap: "wrap"
269
855
  },
270
856
  intro: {
271
857
  fontSize: 12,
272
858
  lineHeight: 1.6,
273
859
  opacity: .75
274
860
  },
861
+ label: {
862
+ fontSize: 12,
863
+ fontWeight: 600,
864
+ opacity: .8,
865
+ whiteSpace: "nowrap"
866
+ },
275
867
  baseRow: {
276
868
  display: "flex",
277
869
  gap: 8,
278
870
  alignItems: "center",
279
871
  flexWrap: "wrap"
280
872
  },
281
- baseField: { width: 380 },
873
+ baseField: {
874
+ ...box,
875
+ width: 380,
876
+ maxWidth: "100%",
877
+ height: 30
878
+ },
282
879
  toolbar: {
283
880
  display: "flex",
284
881
  gap: 8,
285
882
  alignItems: "center",
286
883
  flexWrap: "wrap"
287
884
  },
288
- card,
289
- cardHead: {
885
+ textEditor: {
290
886
  display: "flex",
291
- alignItems: "center",
292
- justifyContent: "space-between",
887
+ flexDirection: "column",
293
888
  gap: 8
294
889
  },
295
- cardHeadRight: {
296
- display: "flex",
297
- alignItems: "center",
298
- gap: 8
890
+ examples: {
891
+ ...box,
892
+ fontSize: 12
299
893
  },
300
- cardTitle: {
301
- fontSize: 12,
302
- fontWeight: 600,
303
- opacity: .75
894
+ examplesSummary: {
895
+ cursor: "pointer",
896
+ opacity: .75,
897
+ userSelect: "none"
898
+ },
899
+ examplesBody: {
900
+ ...box,
901
+ margin: "6px 0 0",
902
+ padding: "8px 10px",
903
+ maxHeight: 260,
904
+ overflow: "auto",
905
+ border: "1px solid var(--dsh-color-border, rgba(128,128,128,0.25))",
906
+ borderRadius: 8,
907
+ background: "var(--dsh-color-surface-secondary, rgba(128,128,128,0.06))",
908
+ fontFamily: "var(--dsh-font-mono, monospace)",
909
+ fontSize: 11.5,
910
+ lineHeight: 1.55,
911
+ whiteSpace: "pre",
912
+ opacity: .9
304
913
  },
305
- pathInput: {
914
+ textarea: {
306
915
  ...box,
307
916
  width: "100%",
308
- padding: "6px 8px",
309
- borderRadius: 6,
917
+ minHeight: 220,
918
+ padding: "8px 10px",
919
+ borderRadius: 8,
310
920
  border: "1px solid var(--dsh-color-border, rgba(128,128,128,0.35))",
311
921
  background: "transparent",
312
922
  color: "inherit",
313
923
  fontFamily: "var(--dsh-font-mono, monospace)",
314
- fontSize: 13
315
- },
316
- resolvedRow: {
317
- display: "flex",
318
- gap: 6,
319
- alignItems: "baseline",
320
- minHeight: 18,
321
- fontSize: 12,
322
- flexWrap: "wrap"
323
- },
324
- code: {
325
- fontFamily: "var(--dsh-font-mono, monospace)",
326
- fontSize: 12,
327
- wordBreak: "break-all"
328
- },
329
- dim: {
330
- opacity: .6,
331
924
  fontSize: 12,
332
- lineHeight: 1.5
925
+ lineHeight: 1.6,
926
+ resize: "vertical"
333
927
  },
334
- controlsRow: {
928
+ textErrors: {
335
929
  display: "flex",
336
- gap: 16,
337
- alignItems: "center",
338
- flexWrap: "wrap"
930
+ flexDirection: "column",
931
+ gap: 2
339
932
  },
340
- field: {
341
- display: "flex",
342
- gap: 6,
343
- alignItems: "center",
933
+ capability: {
934
+ ...box,
935
+ padding: "8px 10px",
936
+ borderRadius: 8,
937
+ border: "1px solid var(--dsh-color-warning, #b45309)",
938
+ background: "var(--dsh-color-warning-soft, rgba(180,83,9,0.08))",
344
939
  fontSize: 12,
345
- opacity: .85
346
- },
347
- select: {
348
- padding: "3px 6px",
349
- borderRadius: 6,
350
- background: "transparent",
351
- color: "inherit",
352
- fontSize: 12
353
- },
354
- pills: {
355
- display: "flex",
356
- gap: 6,
357
- alignItems: "center"
358
- },
359
- pillOn: {
360
- ...button,
361
- borderColor: "var(--dsh-color-accent, #2f6fd0)",
362
- background: "var(--dsh-color-accent-soft, rgba(47,111,208,0.15))"
363
- },
364
- pillOff: {
365
- ...button,
366
- opacity: .55
367
- },
368
- button,
369
- primary: {
370
- ...button,
371
- borderColor: "var(--dsh-color-accent, #2f6fd0)",
372
- fontWeight: 600
373
- },
374
- linkButton: {
375
- ...button,
376
- border: "none",
377
- opacity: .7,
378
- padding: "2px 4px"
940
+ lineHeight: 1.5
379
941
  },
380
942
  panel: {
381
943
  ...box,
382
944
  display: "flex",
383
945
  flexDirection: "column",
384
- gap: 8,
385
- padding: "10px 12px",
946
+ gap: 6,
947
+ padding: "8px 10px",
386
948
  border: "1px solid var(--dsh-color-border, rgba(128,128,128,0.25))",
387
949
  borderRadius: 8
388
950
  },
@@ -395,6 +957,13 @@ window.__ModuleLoader__.load({
395
957
  fontWeight: 600,
396
958
  opacity: .8
397
959
  },
960
+ panelHeadRight: {
961
+ display: "flex",
962
+ alignItems: "center",
963
+ gap: 8,
964
+ whiteSpace: "nowrap",
965
+ fontWeight: 400
966
+ },
398
967
  entry: {
399
968
  display: "flex",
400
969
  gap: 6,
@@ -402,14 +971,34 @@ window.__ModuleLoader__.load({
402
971
  flexWrap: "wrap",
403
972
  fontSize: 12
404
973
  },
405
- statusOk: { color: "var(--dsh-color-success, #15803d)" },
406
- statusMissing: { color: "var(--dsh-color-warning, #b45309)" },
407
- statusRejected: { color: "var(--dsh-color-danger, #b91c1c)" },
974
+ code: {
975
+ fontFamily: "var(--dsh-font-mono, monospace)",
976
+ fontSize: 12,
977
+ wordBreak: "break-all"
978
+ },
979
+ dim: {
980
+ opacity: .6,
981
+ fontSize: 12,
982
+ lineHeight: 1.5
983
+ },
408
984
  warn: {
409
985
  color: "var(--dsh-color-warning, #b45309)",
410
986
  fontSize: 12,
411
987
  lineHeight: 1.5
412
- }
988
+ },
989
+ danger: {
990
+ color: "var(--dsh-color-danger, #b91c1c)",
991
+ fontSize: 12,
992
+ lineHeight: 1.5
993
+ },
994
+ statusOk: { color: "var(--dsh-color-success, #15803d)" },
995
+ statusMissing: { color: "var(--dsh-color-warning, #b45309)" },
996
+ statusRejected: { color: "var(--dsh-color-danger, #b91c1c)" },
997
+ statusForeign: {
998
+ color: "var(--dsh-color-text-secondary, inherit)",
999
+ opacity: .7
1000
+ },
1001
+ button
413
1002
  };
414
1003
  /**
415
1004
  * Interactive states cannot live in a style OBJECT (there is no `:focus` key),
@@ -429,14 +1018,22 @@ window.__ModuleLoader__.load({
429
1018
  font-size: 13px;
430
1019
  transition: border-color 120ms ease, box-shadow 120ms ease;
431
1020
  }
432
- .xp-input:hover, .xp-select:hover { border-color: var(--dsh-color-border-strong, rgba(128,128,128,0.6)); }
433
- .xp-input:focus, .xp-select:focus { outline: none; }
434
- .xp-input:focus-visible, .xp-select:focus-visible {
1021
+ .xp-input:hover, .xp-select:hover, .xp-textarea:hover { border-color: var(--dsh-color-border-strong, rgba(128,128,128,0.6)); }
1022
+ .xp-input:focus, .xp-select:focus, .xp-textarea:focus { outline: none; }
1023
+ .xp-input:focus-visible, .xp-select:focus-visible, .xp-textarea:focus-visible {
435
1024
  outline: none;
436
1025
  border-color: var(--dsh-color-accent, #2f6fd0);
437
1026
  box-shadow: 0 0 0 2px var(--dsh-color-accent-soft, rgba(47,111,208,0.25));
438
1027
  }
439
- .xp-input::placeholder { color: currentColor; opacity: 0.38; }
1028
+ .xp-input::placeholder, .xp-textarea::placeholder { color: currentColor; opacity: 0.38; }
1029
+ .xp-textarea {
1030
+ box-sizing: border-box;
1031
+ border: 1px solid var(--dsh-color-border, rgba(128,128,128,0.35));
1032
+ border-radius: 8px;
1033
+ background: transparent;
1034
+ color: inherit;
1035
+ transition: border-color 120ms ease, box-shadow 120ms ease;
1036
+ }
440
1037
  .xp-button {
441
1038
  box-sizing: border-box;
442
1039
  padding: 4px 10px;
@@ -452,21 +1049,47 @@ window.__ModuleLoader__.load({
452
1049
  .xp-button:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--dsh-color-accent-soft, rgba(47,111,208,0.25)); }
453
1050
  .xp-button:disabled { opacity: 0.45; cursor: default; }
454
1051
  .xp-button-on { border-color: var(--dsh-color-accent, #2f6fd0); background: var(--dsh-color-accent-soft, rgba(47,111,208,0.15)); }
455
- .xp-button-off { opacity: 0.55; }
456
1052
  .xp-link { border: none; background: none; padding: 2px 4px; opacity: 0.7; font-size: 12px; cursor: pointer; color: inherit; }
457
1053
  .xp-link:hover { opacity: 1; text-decoration: underline; }
1054
+
1055
+ /* One column template for a rule row (the row component is kept for tests and
1056
+ compositions; the page itself edits plain text). */
1057
+ display: grid;
1058
+ grid-template-columns: 10px 150px minmax(0, 1fr) 66px 96px 22px;
1059
+ column-gap: 8px;
1060
+ align-items: center;
1061
+ }
1062
+ /* One control height for every cell; the previous flex row mixed 26px buttons
1063
+ with 31px inputs, so nothing sat on one baseline. */
1064
+ .xp-toolbar .xp-button { height: 28px; display: inline-flex; align-items: center; }
1065
+
1066
+ /* Preview entries share their own template: status / access / spelling → resolution. */
1067
+ .xp-entry {
1068
+ display: grid;
1069
+ grid-template-columns: 62px 116px minmax(0, 1fr);
1070
+ column-gap: 8px;
1071
+ align-items: baseline;
1072
+ font-size: 12px;
1073
+ }
1074
+ .xp-entry-paths { display: flex; gap: 6px; flex-wrap: wrap; min-width: 0; }
458
1075
  `;
459
1076
  //#endregion
460
1077
  //#region src/client/page.tsx
461
1078
  /**
462
- * The Extra paths settings page: one card per configured path, localized copy,
463
- * a LIVE lexical resolution per row against a base workspace, quick add
464
- * buttons, and the host's authoritative preview of the DRAFT (unsaved rows).
1079
+ * The Extra paths settings page: ONE plain-text editor for every rule
1080
+ * (`path | access | surfaces` per line, with an always-visible defaults line and
1081
+ * a collapsible examples block), the base-workspace picker used only for the
1082
+ * preview, and the host's authoritative preview of the DRAFT.
1083
+ *
1084
+ * Why the page looks like this: rows and mode switches were removed after the
1085
+ * third round of UI feedback — the text form is the single source of truth, and
1086
+ * Save is the only action. Saving always writes the structured
1087
+ * `{path, access, surfaces}` array; the editor is only a view of it.
465
1088
  *
466
1089
  * Copy follows the host's own language selection: every string comes from the
467
- * dictionaries registered by `../client/index` through the framework-injected
468
- * `t` seat, and the Chinese dictionary is the built-in fallback for a host that
469
- * supplies no seat at all (0.1.5 slots, unit tests).
1090
+ * dictionaries registered by `./index` through the framework-injected `t` seat,
1091
+ * and the Chinese dictionary is the built-in fallback for a host that supplies
1092
+ * no seat at all (0.1.5 slots, unit tests).
470
1093
  *
471
1094
  * The base workspace comes from the shell's standard `useWorkspaces` hook when
472
1095
  * the slot supplies it — a snapshot read once during activation would be
@@ -497,35 +1120,252 @@ window.__ModuleLoader__.load({
497
1120
  }
498
1121
  const NOOP_HOOK = () => void 0;
499
1122
  const IDENTITY = (snapshot) => snapshot;
500
- function itemsOf(value) {
501
- const items = value?.items;
502
- return Array.isArray(items) ? items : [];
503
- }
1123
+ const ACCESS_LABEL = {
1124
+ deny: "accessDeny",
1125
+ read: "accessRead",
1126
+ write: "accessWrite",
1127
+ "always-write": "accessAlways"
1128
+ };
1129
+ const STATUS_LABEL = {
1130
+ ok: "statusOk",
1131
+ missing: "statusMissing",
1132
+ rejected: "statusRejected",
1133
+ foreign: "statusForeign"
1134
+ };
504
1135
  const STATUS_STYLE = {
505
1136
  ok: styles.statusOk,
506
1137
  missing: styles.statusMissing,
507
- rejected: styles.statusRejected
1138
+ rejected: styles.statusRejected,
1139
+ foreign: styles.statusForeign
508
1140
  };
509
- function rowsOf(section) {
510
- const rows = [];
511
- for (const item of section?.paths ?? []) if (typeof item === "string") rows.push({
512
- path: item,
513
- scope: "write",
514
- surfaces: ["fs", "shell"]
1141
+ const TEXT_ERROR_LABEL = {
1142
+ "empty-path": "textErrorEmptyPath",
1143
+ "unknown-access": "textErrorUnknownAccess",
1144
+ "unknown-surfaces": "textErrorUnknownSurfaces",
1145
+ "too-many-fields": "textErrorTooManyFields"
1146
+ };
1147
+ function itemsOf(value) {
1148
+ const items = value?.items;
1149
+ return Array.isArray(items) ? items : [];
1150
+ }
1151
+ /**
1152
+ * Localized one-line message for a rejected text-mode line.
1153
+ * @param tr - the host's translate seat (or the Chinese fallback).
1154
+ * @param error - one parser error with its 1-based line number.
1155
+ * @returns `第 n 行:…` / `Line n: …`.
1156
+ */
1157
+ function textErrorMessage(tr, error) {
1158
+ const params = error.value === void 0 ? void 0 : { value: error.value };
1159
+ return `${tr("textErrorAtLine", { line: error.line })}${tr(TEXT_ERROR_LABEL[error.code], params)}`;
1160
+ }
1161
+ /**
1162
+ * The tooltip of a NAME RULE row: what the spelling means, plus — once the
1163
+ * host's preview has walked the scope roots — how many paths currently match
1164
+ * (zero is a valid answer: the rule still applies to paths created later).
1165
+ * @param tr - the host's translate seat (or the Chinese fallback).
1166
+ * @param hostEntry - the host's preview entry for this row, when it has arrived.
1167
+ * @returns the localized one-line explanation.
1168
+ */
1169
+ function nameRuleText(tr, hostEntry) {
1170
+ const hint = tr("nameRuleHint");
1171
+ const matches = hostEntry?.matches;
1172
+ if (matches === void 0) return hint;
1173
+ return `${hint} · ${matches > 0 ? tr("nameRuleMatches", { count: matches }) : tr("nameRuleNoMatches")}`;
1174
+ }
1175
+ /**
1176
+ * Whether the shell surface cannot enforce a configured restriction on this host.
1177
+ * Before the host reports capabilities (undefined) nothing is claimed.
1178
+ * @param capabilities - the host's shell capability matrix.
1179
+ * @param rows - the current rules.
1180
+ * @returns true when a deny/read rule targets a shell that cannot honor it.
1181
+ */
1182
+ function needsShellLimitWarning(capabilities, rows) {
1183
+ if (capabilities === void 0) return false;
1184
+ if (!rows.some((row) => (row.access === "deny" || row.access === "read") && row.surfaces.includes("shell"))) return false;
1185
+ return !capabilities.shellReadDeny || !capabilities.shellWriteDeny;
1186
+ }
1187
+ /**
1188
+ * The honesty banner: a deny/read rule that targets `shell` on a dialect that
1189
+ * cannot subtract permissions (landlock, Windows ACL) is still enforced for the
1190
+ * fs tools — but bash will not honor it. The page must say that out loud.
1191
+ * @param props - capability matrix, current rules and the translate seat.
1192
+ */
1193
+ function CapabilityBanner({ capabilities, rows, t }) {
1194
+ const tr = t ?? fallbackTranslate;
1195
+ if (!needsShellLimitWarning(capabilities, rows)) return null;
1196
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1197
+ style: styles.capability,
1198
+ role: "status",
1199
+ children: tr("capabilityShellLimit", { dialect: capabilities?.shellDialect ?? "unknown" })
515
1200
  });
516
- else rows.push({
517
- path: item.path ?? "",
518
- scope: item.scope ?? "write",
519
- surfaces: [...item.surfaces ?? ["fs", "shell"]]
1201
+ }
1202
+ /**
1203
+ * The rule editor: the syntax hint, the live defaults line, the collapsible
1204
+ * examples, a monospace textarea and per-line errors. It owns NO action — Save
1205
+ * lives in the page toolbar and parses the whole draft (all-or-nothing), so the
1206
+ * editor can never disagree with the stored configuration.
1207
+ * @param props - editor content, parser errors, defaults copy and the change hook.
1208
+ */
1209
+ function TextModeEditor({ tr, value, errors, defaultsText, onChange }) {
1210
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1211
+ style: styles.textEditor,
1212
+ children: [
1213
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1214
+ style: styles.dim,
1215
+ children: tr("textModeHint")
1216
+ }),
1217
+ defaultsText === void 0 ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1218
+ style: styles.dim,
1219
+ children: defaultsText
1220
+ }),
1221
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("details", {
1222
+ style: styles.examples,
1223
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("summary", {
1224
+ style: styles.examplesSummary,
1225
+ children: tr("examplesTitle")
1226
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
1227
+ style: styles.examplesBody,
1228
+ children: tr("examplesBody")
1229
+ })]
1230
+ }),
1231
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("textarea", {
1232
+ className: "xp-textarea",
1233
+ style: styles.textarea,
1234
+ rows: 12,
1235
+ spellCheck: false,
1236
+ value,
1237
+ "aria-label": tr("textMode"),
1238
+ onChange: (event) => {
1239
+ onChange?.(event.target.value);
1240
+ }
1241
+ }),
1242
+ errors !== void 0 && errors.length > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1243
+ style: styles.textErrors,
1244
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1245
+ style: styles.warn,
1246
+ children: tr("textModeInvalid")
1247
+ }), errors.map((error) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1248
+ style: styles.warn,
1249
+ children: textErrorMessage(tr, error)
1250
+ }, `${error.line}-${error.code}`))]
1251
+ }) : null
1252
+ ]
520
1253
  });
521
- return rows;
522
1254
  }
523
- function payloadOf(rows) {
524
- return rows.filter((row) => row.path.trim() !== "").map((row) => ({
525
- path: row.path.trim(),
526
- scope: row.scope,
527
- surfaces: [...row.surfaces]
528
- }));
1255
+ /** Why the base field cannot be used yet, localized (undefined when it is fine). */
1256
+ function baseProblemText(tr, base) {
1257
+ if (base.ok) return void 0;
1258
+ switch (base.problem) {
1259
+ case "empty": return;
1260
+ case "relative": return tr("resolveBaseInvalid");
1261
+ case "waiting": return tr("baseWaiting");
1262
+ case "foreign": return tr("baseForeign");
1263
+ }
1264
+ }
1265
+ /**
1266
+ * The host's resolution report, collapsed by default: the text editor is the
1267
+ * main view, and the preview is the authoritative detail when the user wants it.
1268
+ * @param props - expansion state, the base outcome, the preview payload and dirty flag.
1269
+ */
1270
+ function PreviewPanel({ tr, expanded, onToggle, typedBase, base, preview, dirty }) {
1271
+ const writable = preview?.writable ?? preview?.effective ?? [];
1272
+ const readOnly = preview?.readOnly ?? [];
1273
+ const denied = preview?.denied ?? [];
1274
+ let body;
1275
+ if (typedBase === "") body = /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1276
+ style: styles.dim,
1277
+ children: tr("previewNoBase")
1278
+ });
1279
+ else if (!base.ok) body = /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1280
+ style: styles.dim,
1281
+ children: base.problem === "relative" ? tr("previewBadBase") : base.problem === "waiting" ? tr("previewExpandingHome") : tr("baseForeign")
1282
+ });
1283
+ else if (preview === void 0) body = /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1284
+ style: styles.dim,
1285
+ children: tr("previewUnavailable")
1286
+ });
1287
+ else if (preview.entries.length === 0 && readOnly.length === 0 && denied.length === 0) body = /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1288
+ style: styles.dim,
1289
+ children: tr("previewEmpty")
1290
+ });
1291
+ else body = /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
1292
+ preview.entries.map((entry, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1293
+ className: "xp-entry",
1294
+ children: [
1295
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1296
+ style: STATUS_STYLE[entry.status],
1297
+ children: [
1298
+ "[",
1299
+ tr(STATUS_LABEL[entry.status]),
1300
+ "]"
1301
+ ]
1302
+ }),
1303
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1304
+ style: styles.dim,
1305
+ children: entry.access === void 0 ? "" : tr(ACCESS_LABEL[entry.access])
1306
+ }),
1307
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1308
+ className: "xp-entry-paths",
1309
+ children: [
1310
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", {
1311
+ style: styles.code,
1312
+ children: entry.raw
1313
+ }),
1314
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1315
+ style: styles.dim,
1316
+ children: "→"
1317
+ }),
1318
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", {
1319
+ style: styles.code,
1320
+ children: entry.resolved !== "" ? entry.resolved : isNameRulePath(entry.raw) ? nameRuleText(tr, entry) : tr("unresolved")
1321
+ })
1322
+ ]
1323
+ })
1324
+ ]
1325
+ }, `${index}-${entry.raw}`)),
1326
+ readOnly.length > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1327
+ style: styles.entry,
1328
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1329
+ style: styles.dim,
1330
+ children: tr("previewReadOnly", { count: readOnly.length })
1331
+ }), readOnly.map((path) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", {
1332
+ style: styles.code,
1333
+ children: path
1334
+ }, path))]
1335
+ }) : null,
1336
+ denied.length > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1337
+ style: styles.entry,
1338
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1339
+ style: styles.dim,
1340
+ children: tr("previewDenied", { count: denied.length })
1341
+ }), denied.map((path) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", {
1342
+ style: styles.code,
1343
+ children: path
1344
+ }, path))]
1345
+ }) : null,
1346
+ preview.warnings.map((warning) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1347
+ style: styles.warn,
1348
+ children: warning
1349
+ }, warning))
1350
+ ] });
1351
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1352
+ style: styles.panel,
1353
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1354
+ style: styles.panelHead,
1355
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: [tr("previewTitle"), dirty ? tr("previewDirty") : ""] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1356
+ style: styles.panelHeadRight,
1357
+ children: [preview === void 0 ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1358
+ style: styles.dim,
1359
+ children: tr("previewEffective", { count: writable.length })
1360
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1361
+ type: "button",
1362
+ className: "xp-link",
1363
+ onClick: onToggle,
1364
+ children: expanded ? tr("collapse") : tr("expand")
1365
+ })]
1366
+ })]
1367
+ }), expanded ? body : null]
1368
+ });
529
1369
  }
530
1370
  function useSnapshot(scope) {
531
1371
  const [snapshot, setSnapshot] = react.useState(() => scope.getSnapshot());
@@ -564,17 +1404,34 @@ window.__ModuleLoader__.load({
564
1404
  const snapshot = useSnapshot(scope);
565
1405
  const fromHook = itemsOf((useWorkspaces ?? NOOP_HOOK)(IDENTITY));
566
1406
  const candidates = (fromHook.length > 0 ? fromHook : itemsOf(getWorkspaces?.()?.list?.getSnapshot?.())).map((item) => item.path).filter((path) => typeof path === "string" && path !== "");
1407
+ const defaults = defaultsOf(snapshot.value);
567
1408
  const [rows, setRows] = react.useState(() => rowsOf(snapshot.value));
1409
+ const [text, setText] = react.useState(() => serializeRules(rowsOf(snapshot.value)));
568
1410
  const [dirty, setDirty] = react.useState(false);
569
1411
  const [busy, setBusy] = react.useState(false);
570
1412
  const [error, setError] = react.useState(void 0);
1413
+ const [textErrors, setTextErrors] = react.useState(void 0);
571
1414
  const [preview, setPreview] = react.useState(void 0);
572
1415
  const [cwd, setCwd] = react.useState(() => candidates[0] ?? "");
573
1416
  const [cwdPinned, setCwdPinned] = react.useState(false);
574
1417
  const [manualBase, setManualBase] = react.useState(false);
1418
+ const [introExpanded, setIntroExpanded] = react.useState(false);
1419
+ const [previewExpanded, setPreviewExpanded] = react.useState(false);
575
1420
  react.useEffect(() => {
576
- if (!dirty) setRows(rowsOf(snapshot.value));
577
- }, [snapshot, dirty]);
1421
+ if (dirty) return;
1422
+ const nextRows = rowsOf(snapshot.value);
1423
+ const parsed = parseRules(text, defaultsOf(snapshot.value));
1424
+ const sameAsStored = parsed.ok && JSON.stringify(payloadOf(parsed.rules)) === JSON.stringify(payloadOf(nextRows));
1425
+ setRows(nextRows);
1426
+ if (!sameAsStored) {
1427
+ setText(serializeRules(nextRows));
1428
+ setTextErrors(void 0);
1429
+ }
1430
+ }, [
1431
+ snapshot,
1432
+ dirty,
1433
+ text
1434
+ ]);
578
1435
  const first = candidates[0];
579
1436
  react.useEffect(() => {
580
1437
  if (!cwdPinned && cwd === "" && first !== void 0) setCwd(first);
@@ -583,16 +1440,18 @@ window.__ModuleLoader__.load({
583
1440
  cwd,
584
1441
  first
585
1442
  ]);
586
- const typedBase = cwd.trim();
587
- const usableBase = typedBase.startsWith("/") || typedBase === "~" || typedBase.startsWith("~/");
588
- const base = typedBase.startsWith("~") ? resolveLexically(typedBase, "", preview?.home) ?? "" : typedBase;
1443
+ const base = resolveBase(cwd, hostViewOf(preview));
1444
+ const previewBase = previewBaseOf(cwd, base);
589
1445
  const request = JSON.stringify(payloadOf(rows));
590
1446
  react.useEffect(() => {
591
- if (base === "") return;
1447
+ if (previewBase === "") {
1448
+ setPreview(void 0);
1449
+ return;
1450
+ }
592
1451
  let live = true;
593
1452
  const timer = setTimeout(() => {
594
1453
  const draft = JSON.parse(request);
595
- fetchPreview(base, draft).then((result) => {
1454
+ fetchPreview(previewBase, draft).then((result) => {
596
1455
  if (live) setPreview(result);
597
1456
  });
598
1457
  }, 250);
@@ -601,57 +1460,71 @@ window.__ModuleLoader__.load({
601
1460
  clearTimeout(timer);
602
1461
  };
603
1462
  }, [
604
- base,
1463
+ previewBase,
605
1464
  request,
606
1465
  snapshot
607
1466
  ]);
608
- const update = (index, patch) => {
609
- setDirty(true);
610
- setRows((current) => current.map((row, i) => i === index ? {
611
- ...row,
612
- ...patch
613
- } : row));
614
- };
615
- const toggleSurface = (index, surface) => {
616
- const row = rows[index];
617
- if (row === void 0) return;
618
- const surfaces = row.surfaces.includes(surface) ? row.surfaces.filter((item) => item !== surface) : [...row.surfaces, surface];
619
- update(index, { surfaces });
620
- };
621
- const append = (path) => {
1467
+ /**
1468
+ * Edit the one text form. A parse failure is reported per line and the last
1469
+ * VALID rows stay in place for the preview; Save refuses until it parses.
1470
+ */
1471
+ const change = (value) => {
622
1472
  setDirty(true);
623
- setRows((current) => [...current, {
624
- path,
625
- scope: "write",
626
- surfaces: ["fs", "shell"]
627
- }]);
628
- };
629
- const reset = () => {
630
- setRows(rowsOf(snapshot.value));
631
- setDirty(false);
1473
+ setText(value);
632
1474
  setError(void 0);
1475
+ const parsed = parseRules(value, defaults);
1476
+ if (parsed.ok) {
1477
+ setRows(parsed.rules);
1478
+ setTextErrors(void 0);
1479
+ } else setTextErrors(parsed.errors);
633
1480
  };
1481
+ /**
1482
+ * The page's only action: parse the whole text (all-or-nothing) and write the
1483
+ * structured `paths` array. A host refusal keeps the text intact.
1484
+ */
634
1485
  const save = () => {
1486
+ const parsed = parseRules(text, defaults);
1487
+ if (!parsed.ok) {
1488
+ setTextErrors(parsed.errors);
1489
+ return;
1490
+ }
635
1491
  setBusy(true);
636
1492
  setError(void 0);
637
- scope.set("paths", payloadOf(rows)).then((accepted) => {
1493
+ scope.set("paths", payloadOf(parsed.rules)).then((accepted) => {
638
1494
  if (accepted === false) setError(tr("saveRefused"));
639
- else setDirty(false);
1495
+ else {
1496
+ setRows(parsed.rules);
1497
+ setDirty(false);
1498
+ setTextErrors(void 0);
1499
+ }
640
1500
  }).catch((cause) => {
641
1501
  setError(isSaveRefused(cause) ? tr("saveRefused") : cause instanceof Error ? cause.message : String(cause));
642
1502
  }).finally(() => {
643
1503
  setBusy(false);
644
1504
  });
645
1505
  };
646
- const hostEntriesOf = (path) => preview?.entries.filter((entry) => entry.raw === path.trim()) ?? [];
647
- const hostEntryOf = (path) => hostEntriesOf(path)[0];
648
1506
  const picker = !manualBase && candidates.length > 0;
649
- const known = candidates.includes(typedBase);
1507
+ const known = candidates.includes(cwd.trim());
1508
+ const baseNotice = baseProblemText(tr, base);
650
1509
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
651
1510
  style: styles.page,
652
1511
  children: [
653
1512
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("style", { children: css }),
654
1513
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1514
+ style: styles.introLine,
1515
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1516
+ style: styles.intro,
1517
+ children: tr("introCollapsed")
1518
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1519
+ type: "button",
1520
+ className: "xp-link",
1521
+ onClick: () => {
1522
+ setIntroExpanded(!introExpanded);
1523
+ },
1524
+ children: introExpanded ? tr("collapse") : tr("expand")
1525
+ })]
1526
+ }),
1527
+ introExpanded ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
655
1528
  style: styles.intro,
656
1529
  children: [
657
1530
  tr("introBefore"),
@@ -661,25 +1534,25 @@ window.__ModuleLoader__.load({
661
1534
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: tr("introRuleEmphasis") }),
662
1535
  tr("introRuleAfter")
663
1536
  ]
664
- }),
1537
+ }) : null,
665
1538
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
666
1539
  style: styles.baseRow,
667
1540
  children: [
668
1541
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
669
- style: styles.cardTitle,
1542
+ style: styles.label,
670
1543
  children: tr("baseWorkspace")
671
1544
  }),
672
1545
  picker ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("select", {
673
1546
  className: "xp-select",
674
1547
  style: styles.baseField,
675
- value: known ? typedBase : "",
1548
+ value: known ? cwd.trim() : "",
676
1549
  onChange: (event) => {
677
1550
  setCwdPinned(true);
678
1551
  setCwd(event.target.value);
679
1552
  },
680
1553
  children: [known ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
681
- value: typedBase,
682
- children: typedBase === "" ? tr("notSelected") : typedBase
1554
+ value: cwd.trim(),
1555
+ children: cwd.trim() === "" ? tr("notSelected") : cwd.trim()
683
1556
  }), candidates.map((path) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
684
1557
  value: path,
685
1558
  children: path
@@ -698,6 +1571,7 @@ window.__ModuleLoader__.load({
698
1571
  type: "button",
699
1572
  className: "xp-link",
700
1573
  onClick: () => {
1574
+ setCwdPinned(true);
701
1575
  setManualBase(!manualBase);
702
1576
  },
703
1577
  children: picker ? tr("manualBase") : tr("pickBase")
@@ -708,225 +1582,53 @@ window.__ModuleLoader__.load({
708
1582
  })
709
1583
  ]
710
1584
  }),
1585
+ baseNotice === void 0 ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1586
+ style: styles.dim,
1587
+ children: baseNotice
1588
+ }),
711
1589
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1590
+ className: "xp-toolbar",
712
1591
  style: styles.toolbar,
713
- children: [
714
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
715
- type: "button",
716
- className: "xp-button xp-button-on",
717
- disabled: busy || !dirty,
718
- onClick: save,
719
- children: busy ? tr("saving") : tr("save")
720
- }),
721
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
722
- type: "button",
723
- className: "xp-button",
724
- onClick: () => {
725
- append("");
726
- },
727
- children: tr("addPath")
728
- }),
729
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
730
- type: "button",
731
- className: "xp-button",
732
- onClick: () => {
733
- append("..");
734
- },
735
- children: tr("addParent")
736
- }),
737
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
738
- type: "button",
739
- className: "xp-button",
740
- disabled: !dirty,
741
- onClick: reset,
742
- children: tr("discard")
743
- }),
744
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
745
- style: styles.dim,
746
- children: dirty ? tr("dirty") : tr("synced")
747
- })
748
- ]
1592
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1593
+ type: "button",
1594
+ className: "xp-button xp-button-on",
1595
+ disabled: busy || !dirty,
1596
+ onClick: save,
1597
+ children: busy ? tr("saving") : tr("save")
1598
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1599
+ style: styles.dim,
1600
+ children: dirty ? tr("dirty") : tr("synced")
1601
+ })]
749
1602
  }),
750
- rows.length === 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
751
- style: styles.dim,
752
- children: tr("emptyPaths")
753
- }) : null,
754
- rows.map((row, index) => {
755
- const patternRow = row.path.includes("*");
756
- const resolved = patternRow ? void 0 : resolveLexically(row.path, base, preview?.home);
757
- const hostMatches = hostEntriesOf(row.path);
758
- const hostEntry = hostEntryOf(row.path);
759
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
760
- style: styles.card,
761
- children: [
762
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
763
- style: styles.cardHead,
764
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
765
- style: styles.cardTitle,
766
- children: tr("rowTitle", { index: index + 1 })
767
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
768
- style: styles.cardHeadRight,
769
- children: [hostEntry !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
770
- style: STATUS_STYLE[hostEntry.status],
771
- children: [
772
- "[",
773
- tr(hostEntry.status === "ok" ? "statusOk" : hostEntry.status === "missing" ? "statusMissing" : "statusRejected"),
774
- hostMatches.length > 1 ? ` ×${hostMatches.length}` : "",
775
- "]"
776
- ]
777
- }) : null, /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
778
- type: "button",
779
- className: "xp-link",
780
- onClick: () => {
781
- setDirty(true);
782
- setRows((current) => current.filter((_, i) => i !== index));
783
- },
784
- children: tr("delete")
785
- })]
786
- })]
787
- }),
788
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
789
- className: "xp-input",
790
- style: styles.pathInput,
791
- value: row.path,
792
- placeholder: tr("pathPlaceholder"),
793
- onChange: (event) => {
794
- update(index, { path: event.target.value });
795
- }
796
- }),
797
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
798
- style: styles.resolvedRow,
799
- children: patternRow ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
800
- style: styles.dim,
801
- children: [
802
- tr("patternResolved"),
803
- " ",
804
- hostMatches.length > 0 ? tr("patternMatches", { count: hostMatches.length }) : tr("patternNoMatches")
805
- ]
806
- }) : resolved === void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
807
- style: styles.dim,
808
- children: row.path.trim() === "" ? tr("resolvePendingEmpty") : typedBase === "" ? tr("resolveNeedsBase") : !usableBase ? tr("resolveBaseInvalid") : tr("resolveNeedsHome")
809
- }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
810
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
811
- style: styles.dim,
812
- children: tr("resolvedAs")
813
- }),
814
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", {
815
- style: styles.code,
816
- children: resolved
817
- }),
818
- hostEntry !== void 0 && hostEntry.resolved !== resolved ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
819
- style: styles.dim,
820
- children: tr("hostResolved", { path: hostEntry.resolved })
821
- }) : null
822
- ] })
823
- }),
824
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
825
- style: styles.controlsRow,
826
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
827
- style: styles.field,
828
- children: [tr("mode"), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("select", {
829
- className: "xp-select",
830
- value: row.scope,
831
- onChange: (event) => {
832
- update(index, { scope: event.target.value });
833
- },
834
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
835
- value: "write",
836
- children: tr("scopeWrite")
837
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
838
- value: "always-write",
839
- children: tr("scopeAlways")
840
- })]
841
- })]
842
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
843
- style: styles.pills,
844
- children: [
845
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
846
- style: styles.dim,
847
- children: tr("surfaces")
848
- }),
849
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
850
- type: "button",
851
- className: row.surfaces.includes("fs") ? "xp-button xp-button-on" : "xp-button xp-button-off",
852
- onClick: () => {
853
- toggleSurface(index, "fs");
854
- },
855
- children: tr("surfaceFs")
856
- }),
857
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
858
- type: "button",
859
- className: row.surfaces.includes("shell") ? "xp-button xp-button-on" : "xp-button xp-button-off",
860
- onClick: () => {
861
- toggleSurface(index, "shell");
862
- },
863
- children: tr("surfaceShell")
864
- })
865
- ]
866
- })]
867
- })
868
- ]
869
- }, index);
1603
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CapabilityBanner, {
1604
+ capabilities: preview?.capabilities,
1605
+ rows,
1606
+ t: tr
870
1607
  }),
871
- error !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
872
- style: styles.warn,
873
- children: error
1608
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TextModeEditor, {
1609
+ tr,
1610
+ value: text,
1611
+ errors: textErrors,
1612
+ defaultsText: tr("editorDefaults", {
1613
+ access: defaults.access,
1614
+ surfaces: defaults.surfaces.join("+")
1615
+ }),
1616
+ onChange: change
874
1617
  }),
875
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
876
- style: styles.panel,
877
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
878
- style: styles.panelHead,
879
- children: [
880
- tr("previewTitle"),
881
- dirty ? tr("previewDirty") : "",
882
- preview !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
883
- style: styles.dim,
884
- children: tr("previewEffective", { count: preview.effective.length })
885
- }) : null
886
- ]
887
- }), typedBase === "" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
888
- style: styles.dim,
889
- children: tr("previewNoBase")
890
- }) : !usableBase ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
891
- style: styles.dim,
892
- children: tr("previewBadBase")
893
- }) : base === "" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
894
- style: styles.dim,
895
- children: tr("previewExpandingHome")
896
- }) : preview === void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
897
- style: styles.dim,
898
- children: tr("previewUnavailable")
899
- }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [preview.entries.length === 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
900
- style: styles.dim,
901
- children: tr("previewEmpty")
902
- }) : preview.entries.map((entry, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
903
- style: styles.entry,
904
- children: [
905
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
906
- style: STATUS_STYLE[entry.status],
907
- children: [
908
- "[",
909
- tr(entry.status === "ok" ? "statusOk" : entry.status === "missing" ? "statusMissing" : "statusRejected"),
910
- "]"
911
- ]
912
- }),
913
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", {
914
- style: styles.code,
915
- children: entry.raw
916
- }),
917
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
918
- style: styles.dim,
919
- children: "→"
920
- }),
921
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", {
922
- style: styles.code,
923
- children: entry.resolved === "" ? tr("unresolved") : entry.resolved
924
- })
925
- ]
926
- }, `${index}-${entry.raw}`)), preview.warnings.map((warning) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
927
- style: styles.warn,
928
- children: warning
929
- }, warning))] })]
1618
+ error !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1619
+ style: styles.danger,
1620
+ children: error
1621
+ }) : null,
1622
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PreviewPanel, {
1623
+ tr,
1624
+ expanded: previewExpanded,
1625
+ onToggle: () => {
1626
+ setPreviewExpanded(!previewExpanded);
1627
+ },
1628
+ typedBase: cwd.trim(),
1629
+ base,
1630
+ preview,
1631
+ dirty
930
1632
  })
931
1633
  ]
932
1634
  });