Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

keybindings.ts

708 lines24.4 KB

1/**
2 * Keybindings - Keybinding configuration service definitions.
3 *
4 * Owns parsing, validation, merge, and persistence of user keybinding
5 * configuration consumed by the server runtime.
6 *
7 * @module Keybindings
8 */
9import {
10 KeybindingRule,
11 KeybindingsConfig,
12 KeybindingsConfigError,
13 KeybindingShortcut,
14 KeybindingWhenNode,
15 MAX_KEYBINDINGS_COUNT,
16 ResolvedKeybindingRule,
17 ResolvedKeybindingsConfig,
18 type ServerRemoveKeybindingInput,
19 type ServerUpsertKeybindingInput,
20 type ServerConfigIssue,
21} from "@t3tools/contracts";
22import * as Array from "effect/Array";
23import * as Cache from "effect/Cache";
24import * as Cause from "effect/Cause";
25import * as Deferred from "effect/Deferred";
26import * as Duration from "effect/Duration";
27import * as Effect from "effect/Effect";
28import * as Exit from "effect/Exit";
29import * as FileSystem from "effect/FileSystem";
30import * as Path from "effect/Path";
31import * as Layer from "effect/Layer";
32import * as Predicate from "effect/Predicate";
33import * as PubSub from "effect/PubSub";
34import * as Result from "effect/Result";
35import * as Schema from "effect/Schema";
36import * as SchemaIssue from "effect/SchemaIssue";
37import * as SchemaTransformation from "effect/SchemaTransformation";
38import * as Ref from "effect/Ref";
39import * as Context from "effect/Context";
40import * as Scope from "effect/Scope";
41import * as Stream from "effect/Stream";
42import * as Semaphore from "effect/Semaphore";
43import * as ServerConfig from "./config.ts";
44import { writeFileStringAtomically } from "./atomicWrite.ts";
45import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
46import {
47 DEFAULT_KEYBINDINGS,
48 DEFAULT_RESOLVED_KEYBINDINGS,
49 compileResolvedKeybindingRule,
50 compileResolvedKeybindingsConfig,
51 parseKeybindingShortcut,
52} from "@t3tools/shared/keybindings";
53​
54export {
55 DEFAULT_KEYBINDINGS,
56 compileResolvedKeybindingRule,
57 compileResolvedKeybindingsConfig,
58 parseKeybindingShortcut,
59};
60​
61export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
62 Schema.decodeTo(
63 Schema.toType(ResolvedKeybindingRule),
64 SchemaTransformation.transformOrFail({
65 decode: (rule) =>
66 Effect.succeed(compileResolvedKeybindingRule(rule)).pipe(
67 Effect.filterOrFail(
68 Predicate.isNotNull,
69 () =>
70 new SchemaIssue.InvalidValue({
71 message: "Invalid keybinding rule",
72 }),
73 ),
74 Effect.map((resolved) => resolved),
75 ),
76​
77 encode: (resolved) =>
78 Effect.gen(function* () {
79 const key = encodeShortcut(resolved.shortcut);
80 if (!key) {
81 return yield* Effect.fail(
82 new SchemaIssue.InvalidValue({
83 message: "Resolved shortcut cannot be encoded to key string",
84 }),
85 );
86 }
87​
88 const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined;
89 return {
90 key,
91 command: resolved.command,
92 when,
93 };
94 }),
95 }),
96 ),
97);
98​
99export const ResolvedKeybindingsFromConfig = Schema.Array(ResolvedKeybindingFromConfig).check(
100 Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),
101);
102​
103function isSameKeybindingRule(left: KeybindingRule, right: KeybindingRule): boolean {
104 return (
105 left.command === right.command &&
106 left.key === right.key &&
107 (left.when ?? undefined) === (right.when ?? undefined)
108 );
110​
111function keybindingShortcutContext(rule: KeybindingRule): string | null {
112 const parsed = parseKeybindingShortcut(rule.key);
113 if (!parsed) return null;
114 const encoded = encodeShortcut(parsed);
115 if (!encoded) return null;
116 return `${encoded}\u0000${rule.when ?? ""}`;
118​
119function hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): boolean {
120 const leftContext = keybindingShortcutContext(left);
121 const rightContext = keybindingShortcutContext(right);
122 if (!leftContext || !rightContext) return false;
123 return leftContext === rightContext;
125​
126function keybindingRuleFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule {
127 return input.when === undefined
128 ? { key: input.key, command: input.command }
129 : { key: input.key, command: input.command, when: input.when };
131​
132function replaceTargetFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule | null {
133 if (!input.replace) return null;
134 return input.replace.when === undefined
135 ? { key: input.replace.key, command: input.replace.command }
136 : { key: input.replace.key, command: input.replace.command, when: input.replace.when };
138​
139function keybindingRuleFromRemoveInput(input: ServerRemoveKeybindingInput): KeybindingRule {
140 return input.when === undefined
141 ? { key: input.key, command: input.command }
142 : { key: input.key, command: input.command, when: input.when };
144​
145function encodeShortcut(shortcut: KeybindingShortcut): string | null {
146 const modifiers: string[] = [];
147 if (shortcut.modKey) modifiers.push("mod");
148 if (shortcut.metaKey) modifiers.push("meta");
149 if (shortcut.ctrlKey) modifiers.push("ctrl");
150 if (shortcut.altKey) modifiers.push("alt");
151 if (shortcut.shiftKey) modifiers.push("shift");
152 if (!shortcut.key) return null;
153 if (shortcut.key !== "+" && shortcut.key.includes("+")) return null;
154 const key = shortcut.key === " " ? "space" : shortcut.key;
155 return [...modifiers, key].join("+");
157​
158function encodeWhenAst(node: KeybindingWhenNode): string {
159 switch (node.type) {
160 case "identifier":
161 return node.name;
162 case "not":
163 return `!(${encodeWhenAst(node.node)})`;
164 case "and":
165 return `(${encodeWhenAst(node.left)} && ${encodeWhenAst(node.right)})`;
166 case "or":
167 return `(${encodeWhenAst(node.left)} || ${encodeWhenAst(node.right)})`;
168 }
170​
171const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
172const KeybindingsConfigPrettyJson = fromJsonStringPretty(KeybindingsConfig);
173const decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule);
174const decodeResolvedKeybindingFromConfigExit = Schema.decodeExit(ResolvedKeybindingFromConfig);
175const decodeRawKeybindingsEntriesExit = Schema.decodeUnknownExit(RawKeybindingsEntries);
176const encodeKeybindingsConfigPrettyJson = Schema.encodeEffect(KeybindingsConfigPrettyJson);
177​
178export interface KeybindingsConfigState {
179 readonly keybindings: ResolvedKeybindingsConfig;
180 readonly issues: readonly ServerConfigIssue[];
182​
183export interface KeybindingsChangeEvent {
184 readonly keybindings: ResolvedKeybindingsConfig;
185 readonly issues: readonly ServerConfigIssue[];
187​
188function trimIssueMessage(message: string): string {
189 const trimmed = message.trim();
190 return trimmed.length > 0 ? trimmed : "Invalid keybindings configuration.";
192​
193function malformedConfigIssue(detail: string): ServerConfigIssue {
194 return {
195 kind: "keybindings.malformed-config",
196 message: trimIssueMessage(detail),
197 };
199​
200function invalidEntryIssue(index: number, detail: string): ServerConfigIssue {
201 return {
202 kind: "keybindings.invalid-entry",
203 index,
204 message: trimIssueMessage(detail),
205 };
207​
208function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
209 if (custom.length === 0) {
210 return [...DEFAULT_RESOLVED_KEYBINDINGS];
211 }
212​
213 const overriddenCommands = new Set(custom.map((binding) => binding.command));
214 const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
215 (binding) => !overriddenCommands.has(binding.command),
216 );
217 const merged = [...retainedDefaults, ...custom];
218​
219 if (merged.length <= MAX_KEYBINDINGS_COUNT) {
220 return merged;
221 }
222​
223 // Keep the latest rules when the config exceeds max size; later rules have higher precedence.
224 return merged.slice(-MAX_KEYBINDINGS_COUNT);
226​
227/**
228 * Keybindings - Service tag for keybinding configuration operations.
229 */
230export class Keybindings extends Context.Service<
231 Keybindings,
232 {
233 /**
234 * Start the keybindings runtime and attach file watching.
235 *
236 * Safe to call multiple times. The first successful call establishes the
237 * runtime; later calls await the same startup.
238 */
239 readonly start: Effect.Effect<void, KeybindingsConfigError>;
240​
241 /**
242 * Await keybindings runtime readiness.
243 *
244 * Readiness means the config directory exists, the watcher is attached, the
245 * startup sync has completed, and the current snapshot has been loaded.
246 */
247 readonly ready: Effect.Effect<void, KeybindingsConfigError>;
248​
249 /**
250 * Ensure the on-disk keybindings file exists and includes all default
251 * commands so newly-added defaults are backfilled on startup.
252 */
253 readonly syncDefaultKeybindingsOnStartup: Effect.Effect<void, KeybindingsConfigError>;
254​
255 /**
256 * Load runtime keybindings state along with non-fatal configuration issues.
257 */
258 readonly loadConfigState: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
259​
260 /**
261 * Read the latest keybindings snapshot from cache/disk.
262 */
263 readonly getSnapshot: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
264​
265 /**
266 * Stream of keybindings config change events.
267 */
268 readonly streamChanges: Stream.Stream<KeybindingsChangeEvent>;
269​
270 /**
271 * Upsert a keybinding rule and persist the resulting configuration.
272 *
273 * Writes config atomically and enforces the max rule count by truncating
274 * oldest entries when needed.
275 */
276 readonly upsertKeybindingRule: (
277 input: ServerUpsertKeybindingInput,
278 ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
279​
280 /**
281 * Remove a single persisted keybinding rule by exact key/command/when match.
282 */
283 readonly removeKeybindingRule: (
284 input: ServerRemoveKeybindingInput,
285 ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
286 }
287>()("t3/keybindings") {}
288​
289const make = Effect.gen(function* () {
290 const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
291 const fs = yield* FileSystem.FileSystem;
292 const path = yield* Path.Path;
293 const upsertSemaphore = yield* Semaphore.make(1);
294 const resolvedConfigCacheKey = "resolved" as const;
295 const changesPubSub = yield* PubSub.unbounded<KeybindingsChangeEvent>();
296 const startedRef = yield* Ref.make(false);
297 const startedDeferred = yield* Deferred.make<void, KeybindingsConfigError>();
298 const watcherScope = yield* Scope.make("sequential");
299 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
300 const emitChange = (configState: KeybindingsConfigState) =>
301 PubSub.publish(changesPubSub, configState).pipe(Effect.asVoid);
302​
303 const readConfigExists = fs.exists(keybindingsConfigPath).pipe(
304 Effect.mapError(
305 (cause) =>
306 new KeybindingsConfigError({
307 configPath: keybindingsConfigPath,
308 detail: "failed to access keybindings config",
309 cause,
310 }),
311 ),
312 );
313​
314 const readRawConfig = fs.readFileString(keybindingsConfigPath).pipe(
315 Effect.mapError(
316 (cause) =>
317 new KeybindingsConfigError({
318 configPath: keybindingsConfigPath,
319 detail: "failed to read keybindings config",
320 cause,
321 }),
322 ),
323 );
324​
325 const loadWritableCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
326 readonly KeybindingRule[],
327 KeybindingsConfigError
328 > {
329 if (!(yield* readConfigExists)) {
330 return [];
331 }
332​
333 const rawConfig = yield* readRawConfig.pipe(
334 Effect.flatMap(Schema.decodeEffect(RawKeybindingsEntries)),
335 Effect.mapError(
336 (cause) =>
337 new KeybindingsConfigError({
338 configPath: keybindingsConfigPath,
339 detail: "expected JSON array",
340 cause,
341 }),
342 ),
343 );
344​
345 return yield* Effect.forEach(rawConfig, (entry) =>
346 Effect.gen(function* () {
347 const decodedRule = decodeKeybindingRuleExit(entry);
348 if (decodedRule._tag === "Failure") {
349 yield* Effect.logWarning("ignoring invalid keybinding entry", {
350 path: keybindingsConfigPath,
351 entry,
352 error: Cause.pretty(decodedRule.cause),
353 });
354 return null;
355 }
356 const resolved = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
357 if (resolved._tag === "Failure") {
358 yield* Effect.logWarning("ignoring invalid keybinding entry", {
359 path: keybindingsConfigPath,
360 entry,
361 error: Cause.pretty(resolved.cause),
362 });
363 return null;
364 }
365 return decodedRule.value;
366 }),
367 ).pipe(Effect.map(Array.filter(Predicate.isNotNull)));
368 });
369​
370 const loadRuntimeCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
371 {
372 readonly keybindings: readonly KeybindingRule[];
373 readonly issues: readonly ServerConfigIssue[];
374 },
375 KeybindingsConfigError
376 > {
377 if (!(yield* readConfigExists)) {
378 return { keybindings: [], issues: [] };
379 }
380​
381 const rawConfig = yield* readRawConfig;
382 const decodedEntries = decodeRawKeybindingsEntriesExit(rawConfig);
383 if (decodedEntries._tag === "Failure") {
384 const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
385 return {
386 keybindings: [],
387 issues: [malformedConfigIssue(detail)],
388 };
389 }
390​
391 const keybindings: KeybindingRule[] = [];
392 const issues: ServerConfigIssue[] = [];
393 for (const [index, entry] of decodedEntries.value.entries()) {
394 const decodedRule = decodeKeybindingRuleExit(entry);
395 if (decodedRule._tag === "Failure") {
396 const detail = Cause.pretty(decodedRule.cause);
397 issues.push(invalidEntryIssue(index, detail));
398 yield* Effect.logWarning("ignoring invalid keybinding entry", {
399 path: keybindingsConfigPath,
400 index,
401 entry,
402 error: detail,
403 });
404 continue;
405 }
406​
407 const resolvedRule = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
408 if (resolvedRule._tag === "Failure") {
409 const detail = Cause.pretty(resolvedRule.cause);
410 issues.push(invalidEntryIssue(index, detail));
411 yield* Effect.logWarning("ignoring invalid keybinding entry", {
412 path: keybindingsConfigPath,
413 index,
414 entry,
415 error: detail,
416 });
417 continue;
418 }
419 keybindings.push(decodedRule.value);
420 }
421​
422 return { keybindings, issues };
423 });
424​
425 const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
426 return encodeKeybindingsConfigPrettyJson(rules).pipe(
427 Effect.map((encoded) => `${encoded}\n`),
428 Effect.flatMap((encoded) =>
429 writeFileStringAtomically({
430 filePath: keybindingsConfigPath,
431 contents: encoded,
432 }).pipe(
433 Effect.provideService(FileSystem.FileSystem, fs),
434 Effect.provideService(Path.Path, path),
435 ),
436 ),
437 Effect.mapError(
438 (cause) =>
439 new KeybindingsConfigError({
440 configPath: keybindingsConfigPath,
441 detail: "failed to write keybindings config",
442 cause,
443 }),
444 ),
445 );
446 };
447​
448 const loadConfigStateFromDisk = loadRuntimeCustomKeybindingsConfig().pipe(
449 Effect.map(({ keybindings, issues }) => ({
450 keybindings: mergeWithDefaultKeybindings(compileResolvedKeybindingsConfig(keybindings)),
451 issues,
452 })),
453 );
454​
455 const resolvedConfigCache = yield* Cache.make<
456 typeof resolvedConfigCacheKey,
457 KeybindingsConfigState,
458 KeybindingsConfigError
459 >({
460 capacity: 1,
461 lookup: () => loadConfigStateFromDisk,
462 });
463​
464 const loadConfigStateFromCacheOrDisk = Cache.get(resolvedConfigCache, resolvedConfigCacheKey);
465​
466 const revalidateAndEmit = upsertSemaphore.withPermits(1)(
467 Effect.gen(function* () {
468 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
469 const configState = yield* loadConfigStateFromCacheOrDisk;
470 yield* emitChange(configState);
471 }),
472 );
473​
474 const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)(
475 Effect.gen(function* () {
476 const configExists = yield* readConfigExists;
477 if (!configExists) {
478 yield* writeConfigAtomically(DEFAULT_KEYBINDINGS);
479 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
480 return;
481 }
482​
483 const runtimeConfig = yield* loadRuntimeCustomKeybindingsConfig();
484 if (runtimeConfig.issues.length > 0) {
485 yield* Effect.logWarning(
486 "skipping startup keybindings default sync because config has issues",
487 {
488 path: keybindingsConfigPath,
489 issues: runtimeConfig.issues,
490 },
491 );
492 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
493 return;
494 }
495 const customConfig = runtimeConfig.keybindings;
496 const existingCommands = new Set(customConfig.map((entry) => entry.command));
497 const missingDefaults: KeybindingRule[] = [];
498 const shortcutConflictWarnings: Array<{
499 defaultCommand: KeybindingRule["command"];
500 conflictingCommand: KeybindingRule["command"];
501 key: string;
502 when: string | null;
503 }> = [];
504 for (const defaultRule of DEFAULT_KEYBINDINGS) {
505 if (existingCommands.has(defaultRule.command)) {
506 continue;
507 }
508 const conflictingEntry = customConfig.find((entry) =>
509 hasSameShortcutContext(entry, defaultRule),
510 );
511 if (conflictingEntry) {
512 shortcutConflictWarnings.push({
513 defaultCommand: defaultRule.command,
514 conflictingCommand: conflictingEntry.command,
515 key: defaultRule.key,
516 when: defaultRule.when ?? null,
517 });
518 continue;
519 }
520 missingDefaults.push(defaultRule);
521 }
522 for (const conflict of shortcutConflictWarnings) {
523 yield* Effect.logWarning("skipping default keybinding due to shortcut conflict", {
524 path: keybindingsConfigPath,
525 defaultCommand: conflict.defaultCommand,
526 conflictingCommand: conflict.conflictingCommand,
527 key: conflict.key,
528 when: conflict.when,
529 reason: "shortcut context already used by existing rule",
530 });
531 }
532 if (missingDefaults.length === 0) {
533 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
534 return;
535 }
536​
537 const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) =>
538 customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule))
539 ? Result.succeed(defaultRule.command)
540 : Result.failVoid,
541 );
542 if (matchingDefaults.length > 0) {
543 yield* Effect.logWarning("default keybinding rule already defined in user config", {
544 path: keybindingsConfigPath,
545 commands: matchingDefaults,
546 });
547 }
548​
549 // Startup backfill must never evict persisted user rules: append only
550 // the defaults that fit and skip the rest.
551 const availableSlots = Math.max(0, MAX_KEYBINDINGS_COUNT - customConfig.length);
552 const defaultsToAppend = missingDefaults.slice(0, availableSlots);
553 const skippedDefaults = missingDefaults.slice(availableSlots);
554 if (skippedDefaults.length > 0) {
555 yield* Effect.logWarning("skipping default keybinding backfill at max entries", {
556 path: keybindingsConfigPath,
557 maxEntries: MAX_KEYBINDINGS_COUNT,
558 commands: skippedDefaults.map((rule) => rule.command),
559 });
560 }
561 if (defaultsToAppend.length === 0) {
562 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
563 return;
564 }
565​
566 yield* writeConfigAtomically([...customConfig, ...defaultsToAppend]);
567 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
568 }),
569 );
570​
571 const startWatcher = Effect.gen(function* () {
572 const keybindingsConfigDir = path.dirname(keybindingsConfigPath);
573 const keybindingsConfigFile = path.basename(keybindingsConfigPath);
574 const keybindingsConfigPathResolved = path.resolve(keybindingsConfigPath);
575​
576 yield* fs.makeDirectory(keybindingsConfigDir, { recursive: true }).pipe(
577 Effect.mapError(
578 (cause) =>
579 new KeybindingsConfigError({
580 configPath: keybindingsConfigPath,
581 detail: "failed to prepare keybindings config directory",
582 cause,
583 }),
584 ),
585 );
586​
587 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
588​
589 // Debounce watch events so the file is fully written before we read it.
590 // Editors emit multiple events per save (truncate, write, rename) and
591 // `fs.watch` can fire before the content has been flushed to disk.
592 const debouncedKeybindingsEvents = fs.watch(keybindingsConfigDir).pipe(
593 Stream.filter((event) => {
594 return (
595 event.path === keybindingsConfigFile ||
596 event.path === keybindingsConfigPath ||
597 path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved
598 );
599 }),
600 Stream.debounce(Duration.millis(100)),
601 );
602​
603 yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe(
604 Effect.ignoreCause({ log: true }),
605 Effect.forkIn(watcherScope),
606 Effect.asVoid,
607 );
608 });
609​
610 const start = Effect.gen(function* () {
611 const alreadyStarted = yield* Ref.get(startedRef);
612 if (alreadyStarted) {
613 return yield* Deferred.await(startedDeferred);
614 }
615​
616 yield* Ref.set(startedRef, true);
617 const startup = Effect.gen(function* () {
618 yield* startWatcher;
619 yield* syncDefaultKeybindingsOnStartup;
620 yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
621 yield* loadConfigStateFromCacheOrDisk;
622 });
623​
624 const startupExit = yield* Effect.exit(startup);
625 if (startupExit._tag === "Failure") {
626 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
627 return yield* Effect.failCause(startupExit.cause);
628 }
629​
630 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
631 });
632​
633 return {
634 start,
635 ready: Deferred.await(startedDeferred),
636 syncDefaultKeybindingsOnStartup,
637 loadConfigState: loadConfigStateFromCacheOrDisk,
638 getSnapshot: loadConfigStateFromCacheOrDisk,
639 get streamChanges() {
640 return Stream.fromPubSub(changesPubSub);
641 },
642 upsertKeybindingRule: (input) =>
643 upsertSemaphore.withPermits(1)(
644 Effect.gen(function* () {
645 const customConfig = yield* loadWritableCustomKeybindingsConfig();
646 const rule = keybindingRuleFromUpsertInput(input);
647 const replaceTarget = replaceTargetFromUpsertInput(input);
648 const nextConfig = [
649 ...customConfig.filter((entry) => {
650 if (replaceTarget) {
651 return (
652 !isSameKeybindingRule(entry, replaceTarget) && !isSameKeybindingRule(entry, rule)
653 );
654 }
655 return !isSameKeybindingRule(entry, rule);
656 }),
657 rule,
658 ];
659 const cappedConfig =
660 nextConfig.length > MAX_KEYBINDINGS_COUNT
661 ? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)
662 : nextConfig;
663 if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {
664 yield* Effect.logWarning("truncating keybindings config to max entries", {
665 path: keybindingsConfigPath,
666 maxEntries: MAX_KEYBINDINGS_COUNT,
667 });
668 }
669 yield* writeConfigAtomically(cappedConfig);
670 const nextResolved = mergeWithDefaultKeybindings(
671 compileResolvedKeybindingsConfig(cappedConfig),
672 );
673 yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
674 keybindings: nextResolved,
675 issues: [],
676 });
677 yield* emitChange({
678 keybindings: nextResolved,
679 issues: [],
680 });
681 return nextResolved;
682 }),
683 ),
684 removeKeybindingRule: (input) =>
685 upsertSemaphore.withPermits(1)(
686 Effect.gen(function* () {
687 const customConfig = yield* loadWritableCustomKeybindingsConfig();
688 const target = keybindingRuleFromRemoveInput(input);
689 const nextConfig = customConfig.filter((entry) => !isSameKeybindingRule(entry, target));
690 yield* writeConfigAtomically(nextConfig);
691 const nextResolved = mergeWithDefaultKeybindings(
692 compileResolvedKeybindingsConfig(nextConfig),
693 );
694 yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
695 keybindings: nextResolved,
696 issues: [],
697 });
698 yield* emitChange({
699 keybindings: nextResolved,
700 issues: [],
701 });
702 return nextResolved;
703 }),
704 ),
705 } satisfies Keybindings["Service"];
706});
707​
708export const layer = Layer.effect(Keybindings, make);