modern-cmdk 1.0.2 → 1.1.1

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 (30) hide show
  1. package/dist/codemod/cli.mjs +1 -3
  2. package/dist/codemod/transforms/data-attrs.d.mts +1 -2
  3. package/dist/codemod/transforms/data-attrs.mjs +0 -2
  4. package/dist/codemod/transforms/forward-ref.d.mts +1 -2
  5. package/dist/codemod/transforms/forward-ref.mjs +0 -2
  6. package/dist/codemod/transforms/import-rewrite.d.mts +1 -2
  7. package/dist/codemod/transforms/import-rewrite.mjs +0 -2
  8. package/dist/codemod/transforms/should-filter.d.mts +1 -2
  9. package/dist/codemod/transforms/should-filter.mjs +0 -2
  10. package/dist/core/index.d.mts +568 -2
  11. package/dist/core/index.mjs +1268 -1
  12. package/dist/react/index.d.mts +349 -3
  13. package/dist/react/index.mjs +1292 -209
  14. package/package.json +26 -12
  15. package/dist/codemod/cli.mjs.map +0 -1
  16. package/dist/codemod/transforms/data-attrs.d.mts.map +0 -1
  17. package/dist/codemod/transforms/data-attrs.mjs.map +0 -1
  18. package/dist/codemod/transforms/forward-ref.d.mts.map +0 -1
  19. package/dist/codemod/transforms/forward-ref.mjs.map +0 -1
  20. package/dist/codemod/transforms/import-rewrite.d.mts.map +0 -1
  21. package/dist/codemod/transforms/import-rewrite.mjs.map +0 -1
  22. package/dist/codemod/transforms/should-filter.d.mts.map +0 -1
  23. package/dist/codemod/transforms/should-filter.mjs.map +0 -1
  24. package/dist/core-CgQYpHK3.mjs +0 -1235
  25. package/dist/core-CgQYpHK3.mjs.map +0 -1
  26. package/dist/index-C6g94P7V.d.mts +0 -563
  27. package/dist/index-C6g94P7V.d.mts.map +0 -1
  28. package/dist/react/index.d.mts.map +0 -1
  29. package/dist/react/index.mjs.map +0 -1
  30. /package/{src → dist}/react/styles.css +0 -0
@@ -1,2 +1,1269 @@
1
- import { C as itemId, S as groupId, _ as computeFrecencyBonus, a as createScheduler, b as DEFAULT_MACHINE_OPTIONS, c as scoreItem, d as formatShortcut, f as parseShortcut, g as FrecencyEngine, h as matchesShortcut, i as createCommandMachine, l as CommandRegistry, m as findMatchingShortcut, n as batchScoreItems, o as TypedEmitter, p as detectConflicts, r as scoreItemAsync, s as createSearchEngine, t as createTelemetryMiddleware, u as KeyboardShortcutRegistry, v as MemoryFrecencyStorage, w as IdbFrecencyStorage, x as createInitialState, y as DEFAULT_FRECENCY_DECAY } from "../core-CgQYpHK3.mjs";
1
+ //#region src/core/frecency/idb-storage.ts
2
+ /** Serialize a FrecencyRecord to a JSON-safe format */
3
+ function serializeRecord(record) {
4
+ return {
5
+ frequency: record.frequency,
6
+ lastUsedNs: record.lastUsed.epochNanoseconds.toString()
7
+ };
8
+ }
9
+ /** Deserialize a FrecencyRecord from its JSON-safe form */
10
+ function deserializeRecord(serialized) {
11
+ return {
12
+ frequency: serialized.frequency,
13
+ lastUsed: Temporal.Instant.fromEpochNanoseconds(BigInt(serialized.lastUsedNs))
14
+ };
15
+ }
16
+ /** Serialize FrecencyData for IndexedDB storage — uses Iterator Helpers */
17
+ function serializeData(data) {
18
+ return { records: data.records.entries().map(([id, record]) => [id, serializeRecord(record)]).toArray() };
19
+ }
20
+ /** Deserialize FrecencyData from IndexedDB storage — Iterator passed directly to Map (no .toArray()) */
21
+ function deserializeData(serialized) {
22
+ return { records: new Map(serialized.records.values().map(([id, record]) => [id, deserializeRecord(record)])) };
23
+ }
24
+ /** Build the namespaced IDB key — String.toWellFormed() (ES2026) ensures valid Unicode in key */
25
+ function storageKey(namespace) {
26
+ return `frecency:${namespace.isWellFormed() ? namespace : namespace.toWellFormed()}`;
27
+ }
28
+ let idbModule;
29
+ /**
30
+ * IndexedDB-backed frecency storage using idb-keyval 6.2.2.
31
+ *
32
+ * Persists frecency data across browser sessions. Implements both
33
+ * `Disposable` and `AsyncDisposable` for use with `using` and `await using`.
34
+ *
35
+ * idb-keyval is lazy-loaded on first method call — consumers who import
36
+ * the core module without using IDB frecency pay zero cost.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * await using storage = new IdbFrecencyStorage();
41
+ * const data = await storage.load('my-app');
42
+ * ```
43
+ */
44
+ var IdbFrecencyStorage = class {
45
+ #dbName;
46
+ #storeName;
47
+ #store;
48
+ #disposed = false;
49
+ /**
50
+ * Create an IDB-backed frecency storage.
51
+ *
52
+ * @param dbName — IndexedDB database name (default: 'modern-cmdk')
53
+ * @param storeName — IndexedDB object store name (default: 'frecency')
54
+ */
55
+ constructor(dbName = "modern-cmdk", storeName = "frecency") {
56
+ this.#dbName = dbName;
57
+ this.#storeName = storeName;
58
+ }
59
+ /** Lazy-load idb-keyval module — cached across all instances */
60
+ async #idb() {
61
+ idbModule ??= import("idb-keyval");
62
+ return idbModule;
63
+ }
64
+ /** Lazy-create the IDB store on first access */
65
+ async #getStore() {
66
+ if (!this.#store) {
67
+ const { createStore } = await this.#idb();
68
+ this.#store = createStore(this.#dbName, this.#storeName);
69
+ }
70
+ return this.#store;
71
+ }
72
+ /** Load frecency data from IndexedDB for the given namespace */
73
+ async load(namespace) {
74
+ if (this.#disposed) return { records: /* @__PURE__ */ new Map() };
75
+ const { get } = await this.#idb();
76
+ const store = await this.#getStore();
77
+ const serialized = await get(storageKey(namespace), store);
78
+ if (!serialized) return { records: /* @__PURE__ */ new Map() };
79
+ return deserializeData(serialized);
80
+ }
81
+ /** Save frecency data to IndexedDB for the given namespace */
82
+ async save(namespace, data) {
83
+ if (this.#disposed) return;
84
+ const { set } = await this.#idb();
85
+ const store = await this.#getStore();
86
+ await set(storageKey(namespace), serializeData(data), store);
87
+ }
88
+ /** Delete frecency data for a namespace from IndexedDB */
89
+ async delete(namespace) {
90
+ if (this.#disposed) return;
91
+ const { del } = await this.#idb();
92
+ const store = await this.#getStore();
93
+ await del(storageKey(namespace), store);
94
+ }
95
+ /** Synchronous dispose — marks as disposed (best-effort cleanup) */
96
+ [Symbol.dispose]() {
97
+ this.#disposed = true;
98
+ }
99
+ /** Async dispose — marks as disposed, suitable for `await using` */
100
+ async [Symbol.asyncDispose]() {
101
+ this.#disposed = true;
102
+ }
103
+ };
104
+ //#endregion
105
+ //#region src/core/types.ts
106
+ /** Create a branded {@link ItemId} from a plain string. Ensures well-formed Unicode (ES2026). */
107
+ function itemId(id) {
108
+ return id.isWellFormed() ? id : id.toWellFormed();
109
+ }
110
+ /** Create a branded {@link GroupId} from a plain string. Ensures well-formed Unicode (ES2026). */
111
+ function groupId(id) {
112
+ return id.isWellFormed() ? id : id.toWellFormed();
113
+ }
114
+ /** Default frecency decay configuration */
115
+ const DEFAULT_FRECENCY_DECAY = {
116
+ hourWeight: 4,
117
+ dayWeight: 2,
118
+ weekWeight: 1.5,
119
+ monthWeight: 1,
120
+ olderWeight: .5
121
+ };
122
+ /** Default machine options */
123
+ const DEFAULT_MACHINE_OPTIONS = {
124
+ loop: true,
125
+ virtualizeThreshold: 100,
126
+ open: false
127
+ };
128
+ /** Initial state factory */
129
+ function createInitialState(options) {
130
+ return {
131
+ search: "",
132
+ activeId: null,
133
+ filteredIds: [],
134
+ groupedIds: /* @__PURE__ */ new Map(),
135
+ filteredCount: 0,
136
+ loading: false,
137
+ page: "root",
138
+ pageStack: [],
139
+ open: options?.open ?? false,
140
+ lastUpdated: Temporal.Now.instant()
141
+ };
142
+ }
143
+ //#endregion
144
+ //#region src/core/frecency/memory-storage.ts
145
+ /**
146
+ * In-memory implementation of FrecencyStorage using a Map.
147
+ * Data does not persist across page reloads. Suitable for ephemeral
148
+ * sessions or as the default when no persistent storage is configured.
149
+ */
150
+ var MemoryFrecencyStorage = class {
151
+ #store = /* @__PURE__ */ new Map();
152
+ load(namespace) {
153
+ return this.#store.get(namespace) ?? { records: /* @__PURE__ */ new Map() };
154
+ }
155
+ save(namespace, data) {
156
+ this.#store.set(namespace, data);
157
+ }
158
+ /** Serialize all stored data — Iterator Helpers pipeline (ES2026) */
159
+ toJSON() {
160
+ return Object.fromEntries(this.#store.entries().map(([namespace, data]) => [namespace, { records: data.records.entries().toArray() }]));
161
+ }
162
+ [Symbol.dispose]() {
163
+ this.#store.clear();
164
+ }
165
+ };
166
+ //#endregion
167
+ //#region src/core/frecency/index.ts
168
+ /** Shared empty bonus map — avoids allocation when no frecency records exist */
169
+ const EMPTY_BONUS_MAP = /* @__PURE__ */ new Map();
170
+ /** Pre-computed bucket boundaries in hours — avoids Duration.total() per call */
171
+ const BUCKET_HOURS = {
172
+ hour: 1,
173
+ day: 24,
174
+ week: 168,
175
+ month: 720
176
+ };
177
+ /**
178
+ * Computes a frecency bonus for an item based on usage frequency and recency.
179
+ * Uses Temporal.Duration bucket boundaries (hour/day/week/month) with
180
+ * configurable exponential decay weights per time bucket.
181
+ */
182
+ function computeFrecencyBonus(history, now = Temporal.Now.instant(), config = DEFAULT_FRECENCY_DECAY) {
183
+ const hours = now.since(history.lastUsed).total("hours");
184
+ const { hourWeight = 4, dayWeight = 2, weekWeight = 1.5, monthWeight = 1, olderWeight = .5 } = config;
185
+ const recencyWeight = hours < BUCKET_HOURS.hour ? hourWeight : hours < BUCKET_HOURS.day ? dayWeight : hours < BUCKET_HOURS.week ? weekWeight : hours < BUCKET_HOURS.month ? monthWeight : olderWeight;
186
+ return history.frequency * recencyWeight;
187
+ }
188
+ /**
189
+ * Stateful frecency engine that tracks item selection history and provides
190
+ * ranking boosts for search results. Supports pluggable storage backends
191
+ * and automatic flush on dispose. Uses Temporal.Now.instant() for timestamps.
192
+ */
193
+ var FrecencyEngine = class {
194
+ #storage;
195
+ #namespace;
196
+ #data;
197
+ #config;
198
+ #dirty = false;
199
+ constructor(options) {
200
+ this.#storage = options.storage ?? new MemoryFrecencyStorage();
201
+ this.#namespace = options.namespace ?? "default";
202
+ this.#config = options.decayConfig ?? DEFAULT_FRECENCY_DECAY;
203
+ this.#data = { records: /* @__PURE__ */ new Map() };
204
+ }
205
+ /** Load frecency data from storage */
206
+ async load() {
207
+ this.#data = await this.#storage.load(this.#namespace);
208
+ }
209
+ /** Record a selection event for an item */
210
+ recordSelection(itemId) {
211
+ const now = Temporal.Now.instant();
212
+ const updated = {
213
+ frequency: (this.#data.records.get(itemId)?.frequency ?? 0) + 1,
214
+ lastUsed: now
215
+ };
216
+ this.#data.records.set(itemId, updated);
217
+ this.#dirty = true;
218
+ }
219
+ /** Get frecency bonus for an item */
220
+ getBonus(itemId, now) {
221
+ const record = this.#data.records.get(itemId);
222
+ if (!record) return 0;
223
+ return computeFrecencyBonus(record, now, this.#config);
224
+ }
225
+ /** Get all frecency bonuses as a map — for...of for hot ranking path (no closure overhead) */
226
+ getAllBonuses(now = Temporal.Now.instant()) {
227
+ if (this.#data.records.size === 0) return EMPTY_BONUS_MAP;
228
+ const bonuses = /* @__PURE__ */ new Map();
229
+ for (const [id, record] of this.#data.records) bonuses.set(id, computeFrecencyBonus(record, now, this.#config));
230
+ return bonuses;
231
+ }
232
+ /** Get the decay configuration */
233
+ getConfig() {
234
+ return this.#config;
235
+ }
236
+ /** Update decay configuration at runtime */
237
+ setConfig(config) {
238
+ this.#config = {
239
+ ...this.#config,
240
+ ...config
241
+ };
242
+ }
243
+ /** Flush dirty data to storage */
244
+ async flush() {
245
+ if (!this.#dirty) return;
246
+ await this.#storage.save(this.#namespace, this.#data);
247
+ this.#dirty = false;
248
+ }
249
+ /** Get the raw frecency data */
250
+ getData() {
251
+ return this.#data;
252
+ }
253
+ /** Async dispose — flushes dirty data before cleanup. Use with `await using`. */
254
+ async [Symbol.asyncDispose]() {
255
+ if (this.#dirty) {
256
+ await this.#storage.save(this.#namespace, this.#data);
257
+ this.#dirty = false;
258
+ }
259
+ this.#storage[Symbol.dispose]();
260
+ }
261
+ [Symbol.dispose]() {
262
+ if (this.#dirty) Promise.try(() => this.#storage.save(this.#namespace, this.#data)).catch((err) => {
263
+ console.warn("[modern-cmdk] FrecencyEngine dispose flush failed:", err);
264
+ });
265
+ this.#storage[Symbol.dispose]();
266
+ }
267
+ };
268
+ //#endregion
269
+ //#region src/core/keyboard/matcher.ts
270
+ /**
271
+ * Tests whether a KeyboardEvent exactly matches a ParsedShortcut,
272
+ * comparing all four modifier keys (meta, ctrl, shift, alt) and the primary key.
273
+ */
274
+ function matchesShortcut(event, shortcut) {
275
+ if (shortcut.meta !== event.metaKey) return false;
276
+ if (shortcut.ctrl !== event.ctrlKey) return false;
277
+ if (shortcut.shift !== event.shiftKey) return false;
278
+ if (shortcut.alt !== event.altKey) return false;
279
+ return event.key.toLowerCase() === shortcut.key;
280
+ }
281
+ /** Match a KeyboardEvent against a list of shortcuts — Iterator Helpers .find() */
282
+ function findMatchingShortcut(event, shortcuts) {
283
+ return shortcuts.values().find((shortcut) => matchesShortcut(event, shortcut)) ?? null;
284
+ }
285
+ /**
286
+ * Detects conflicting shortcut bindings by grouping on their normalized form
287
+ * via Map.groupBy (ES2026). Returns only groups with two or more colliding shortcuts.
288
+ * Map.groupBy returns a Map directly — no Object.entries conversion needed.
289
+ */
290
+ function detectConflicts(shortcuts) {
291
+ const grouped = Map.groupBy(shortcuts, (s) => s.normalized);
292
+ return new Map(grouped.entries().filter(([, group]) => group.length > 1));
293
+ }
294
+ //#endregion
295
+ //#region src/core/keyboard/parser.ts
296
+ const isMac = typeof navigator !== "undefined" && (navigator.userAgentData?.platform === "macOS" || /Mac|iPod|iPhone|iPad/.test(navigator.platform));
297
+ /** Modifier aliases — cross-platform Mod resolution */
298
+ const MODIFIER_MAP = {
299
+ mod: isMac ? "meta" : "ctrl",
300
+ meta: "meta",
301
+ cmd: "meta",
302
+ command: "meta",
303
+ ctrl: "ctrl",
304
+ control: "ctrl",
305
+ shift: "shift",
306
+ alt: "alt",
307
+ option: "alt",
308
+ opt: "alt"
309
+ };
310
+ /**
311
+ * Parse a shortcut string like "Mod+Shift+K" into a structured ParsedShortcut.
312
+ * Uses String.isWellFormed() (ES2026) to ensure valid Unicode input.
313
+ */
314
+ function parseShortcut(shortcut) {
315
+ const safeShortcut = shortcut.isWellFormed() ? shortcut : shortcut.toWellFormed();
316
+ const parts = safeShortcut.split("+").map((p) => p.trim().toLowerCase());
317
+ let meta = false;
318
+ let ctrl = false;
319
+ let shift = false;
320
+ let alt = false;
321
+ let key = "";
322
+ for (const part of parts) {
323
+ const modifier = MODIFIER_MAP[part];
324
+ if (modifier) switch (modifier) {
325
+ case "meta":
326
+ meta = true;
327
+ break;
328
+ case "ctrl":
329
+ ctrl = true;
330
+ break;
331
+ case "shift":
332
+ shift = true;
333
+ break;
334
+ case "alt":
335
+ alt = true;
336
+ break;
337
+ }
338
+ else key = part;
339
+ }
340
+ const modifiers = [];
341
+ if (meta) modifiers.push("meta");
342
+ if (ctrl) modifiers.push("ctrl");
343
+ if (shift) modifiers.push("shift");
344
+ if (alt) modifiers.push("alt");
345
+ modifiers.push(key);
346
+ return {
347
+ key,
348
+ meta,
349
+ ctrl,
350
+ shift,
351
+ alt,
352
+ raw: safeShortcut,
353
+ normalized: modifiers.join("+")
354
+ };
355
+ }
356
+ /**
357
+ * Formats a ParsedShortcut for display using platform-appropriate symbols.
358
+ * On macOS: renders glyphs (⌘, ⇧, ⌥, ⌃). On other platforms: text labels joined by "+".
359
+ */
360
+ function formatShortcut(parsed) {
361
+ const parts = [];
362
+ if (parsed.meta) parts.push(isMac ? "⌘" : "Ctrl");
363
+ if (parsed.ctrl && !(!isMac && parsed.meta)) parts.push(isMac ? "⌃" : "Ctrl");
364
+ if (parsed.shift) parts.push(isMac ? "⇧" : "Shift");
365
+ if (parsed.alt) parts.push(isMac ? "⌥" : "Alt");
366
+ const displayKey = parsed.key.length === 1 ? parsed.key.toUpperCase() : parsed.key.charAt(0).toUpperCase() + parsed.key.slice(1);
367
+ parts.push(displayKey);
368
+ return isMac ? parts.join("") : parts.join("+");
369
+ }
370
+ //#endregion
371
+ //#region src/core/keyboard/index.ts
372
+ /**
373
+ * Manages keyboard shortcut bindings with global keydown listening.
374
+ * Supports `using` for automatic cleanup of both individual bindings and the
375
+ * global document listener. Detects conflicts via Map.groupBy (ES2026).
376
+ */
377
+ var KeyboardShortcutRegistry = class {
378
+ #bindings = /* @__PURE__ */ new Map();
379
+ #globalListener = null;
380
+ #enabled = true;
381
+ constructor(options) {
382
+ this.#enabled = options?.enabled ?? true;
383
+ this.#attachGlobalListener();
384
+ }
385
+ /** Register a shortcut binding — returns Disposable for `using` auto-deregister */
386
+ register(shortcutStr, itemId, handler) {
387
+ const shortcut = parseShortcut(shortcutStr);
388
+ this.#bindings.set(shortcut.normalized, {
389
+ shortcut,
390
+ itemId,
391
+ handler
392
+ });
393
+ return { [Symbol.dispose]: () => {
394
+ this.#bindings.delete(shortcut.normalized);
395
+ } };
396
+ }
397
+ /** Unregister a shortcut by its string representation */
398
+ unregister(shortcutStr) {
399
+ const shortcut = parseShortcut(shortcutStr);
400
+ this.#bindings.delete(shortcut.normalized);
401
+ }
402
+ /** Unregister all shortcuts for a given item — Map spec allows deletion during iteration */
403
+ unregisterByItem(itemId) {
404
+ for (const [key, binding] of this.#bindings) if (binding.itemId === itemId) this.#bindings.delete(key);
405
+ }
406
+ /** Check for conflicting shortcuts */
407
+ getConflicts() {
408
+ return detectConflicts(this.#bindings.values().map((b) => b.shortcut).toArray());
409
+ }
410
+ /** Enable or disable global shortcut listening */
411
+ setEnabled(enabled) {
412
+ this.#enabled = enabled;
413
+ }
414
+ /** Get all registered bindings */
415
+ getBindings() {
416
+ return this.#bindings;
417
+ }
418
+ #attachGlobalListener() {
419
+ if (typeof document === "undefined") return;
420
+ this.#globalListener = (event) => {
421
+ if (!this.#enabled) return;
422
+ for (const binding of this.#bindings.values()) if (matchesShortcut(event, binding.shortcut)) {
423
+ event.preventDefault();
424
+ event.stopPropagation();
425
+ binding.handler();
426
+ return;
427
+ }
428
+ };
429
+ document.addEventListener("keydown", this.#globalListener);
430
+ }
431
+ #detachGlobalListener() {
432
+ if (this.#globalListener && typeof document !== "undefined") {
433
+ document.removeEventListener("keydown", this.#globalListener);
434
+ this.#globalListener = null;
435
+ }
436
+ }
437
+ [Symbol.dispose]() {
438
+ this.#detachGlobalListener();
439
+ this.#bindings.clear();
440
+ }
441
+ };
442
+ //#endregion
443
+ //#region src/core/registry.ts
444
+ /**
445
+ * Manages registration and lookup of command items and groups.
446
+ * Uses ES2026 Set methods (union/intersection/difference) for efficient ID operations.
447
+ * All registration methods return Disposable for automatic cleanup via `using`.
448
+ */
449
+ var CommandRegistry = class {
450
+ #items = /* @__PURE__ */ new Map();
451
+ #groups = /* @__PURE__ */ new Map();
452
+ #itemOrder = [];
453
+ #itemOrderSet = /* @__PURE__ */ new Set();
454
+ #cachedItems = null;
455
+ #cachedGroups = null;
456
+ #invalidateCache() {
457
+ this.#cachedItems = null;
458
+ }
459
+ #invalidateGroupCache() {
460
+ this.#cachedGroups = null;
461
+ }
462
+ /** Register an item — returns Disposable for `using` auto-deregister */
463
+ registerItem(item) {
464
+ this.#items.set(item.id, item);
465
+ if (!this.#itemOrderSet.has(item.id)) {
466
+ this.#itemOrder.push(item.id);
467
+ this.#itemOrderSet.add(item.id);
468
+ }
469
+ this.#invalidateCache();
470
+ return { [Symbol.dispose]: () => {
471
+ this.unregisterItem(item.id);
472
+ } };
473
+ }
474
+ /** Register multiple items at once — single Disposable for batch cleanup. for...of for hot path. */
475
+ registerItems(items) {
476
+ for (const item of items) {
477
+ this.#items.set(item.id, item);
478
+ if (!this.#itemOrderSet.has(item.id)) {
479
+ this.#itemOrder.push(item.id);
480
+ this.#itemOrderSet.add(item.id);
481
+ }
482
+ }
483
+ this.#invalidateCache();
484
+ const ids = new Set(items.values().map((i) => i.id));
485
+ return { [Symbol.dispose]: () => {
486
+ this.unregisterItems(ids);
487
+ } };
488
+ }
489
+ /** Unregister a single item — O(1) Map/Set delete, indexOf+toSpliced for order */
490
+ unregisterItem(id) {
491
+ if (!this.#items.has(id)) return;
492
+ this.#items.delete(id);
493
+ this.#itemOrderSet.delete(id);
494
+ const idx = this.#itemOrder.indexOf(id);
495
+ if (idx !== -1) this.#itemOrder = this.#itemOrder.toSpliced(idx, 1);
496
+ this.#invalidateCache();
497
+ }
498
+ /** Bulk unregister using Set.difference (ES2026) — for...of for hot path */
499
+ unregisterItems(ids) {
500
+ for (const id of ids) this.#items.delete(id);
501
+ this.#itemOrderSet = this.#itemOrderSet.difference(ids);
502
+ this.#itemOrder = this.#itemOrder.filter((id) => !ids.has(id));
503
+ this.#invalidateCache();
504
+ }
505
+ /** Register a group */
506
+ registerGroup(group) {
507
+ this.#groups.set(group.id, group);
508
+ this.#invalidateGroupCache();
509
+ return { [Symbol.dispose]: () => {
510
+ this.#groups.delete(group.id);
511
+ this.#invalidateGroupCache();
512
+ } };
513
+ }
514
+ /** Unregister a group */
515
+ unregisterGroup(id) {
516
+ this.#groups.delete(id);
517
+ this.#invalidateGroupCache();
518
+ }
519
+ /** Get an item by ID — O(1) */
520
+ getItem(id) {
521
+ return this.#items.get(id);
522
+ }
523
+ /** Get a group by ID — O(1) */
524
+ getGroup(id) {
525
+ return this.#groups.get(id);
526
+ }
527
+ /** Get all registered items in insertion order — cached between mutations */
528
+ getItems() {
529
+ if (this.#cachedItems !== null) return this.#cachedItems;
530
+ this.#cachedItems = this.#itemOrder.values().map((id) => this.#items.get(id)).filter((item) => item != null).toArray();
531
+ return this.#cachedItems;
532
+ }
533
+ /** Get all registered groups sorted by priority — cached between group mutations */
534
+ getGroups() {
535
+ if (this.#cachedGroups !== null) return this.#cachedGroups;
536
+ this.#cachedGroups = this.#groups.values().toArray().toSorted((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
537
+ return this.#cachedGroups;
538
+ }
539
+ /** Get items grouped by groupId using Map.groupBy (ES2026) — direct Map, no Object.entries conversion */
540
+ getGroupedItems() {
541
+ const items = this.getItems();
542
+ const grouped = Map.groupBy(items, (item) => item.groupId ?? "__ungrouped");
543
+ const result = /* @__PURE__ */ new Map();
544
+ for (const group of this.getGroups()) {
545
+ const groupItems = grouped.get(group.id);
546
+ if (groupItems != null) result.set(group.id, groupItems);
547
+ }
548
+ const ungrouped = grouped.get("__ungrouped");
549
+ if (ungrouped) result.set("__ungrouped", ungrouped);
550
+ return result;
551
+ }
552
+ /** Get item IDs as a Set — returns internal set (O(1), no allocation) */
553
+ getItemIds() {
554
+ return this.#itemOrderSet;
555
+ }
556
+ /** Find intersection of registered items with a candidate set (ES2026 Set.intersection) */
557
+ intersectWith(candidateIds) {
558
+ return this.#itemOrderSet.intersection(candidateIds);
559
+ }
560
+ /** Find items registered but not in a given set (ES2026 Set.difference) */
561
+ differenceFrom(otherIds) {
562
+ return this.#itemOrderSet.difference(otherIds);
563
+ }
564
+ /** Union of registered IDs with another set (ES2026 Set.union) */
565
+ unionWith(otherIds) {
566
+ return this.#itemOrderSet.union(otherIds);
567
+ }
568
+ /** Check if registered items are a subset of the given set (ES2026 Set.isSubsetOf) */
569
+ isSubsetOf(otherIds) {
570
+ return this.#itemOrderSet.isSubsetOf(otherIds);
571
+ }
572
+ /** Check if registered items are a superset of the given set (ES2026 Set.isSupersetOf) */
573
+ isSupersetOf(otherIds) {
574
+ return this.#itemOrderSet.isSupersetOf(otherIds);
575
+ }
576
+ /** Check if registered items share no IDs with the given set (ES2026 Set.isDisjointFrom) */
577
+ isDisjointFrom(otherIds) {
578
+ return this.#itemOrderSet.isDisjointFrom(otherIds);
579
+ }
580
+ /** Symmetric difference between registered IDs and another set (ES2026 Set.symmetricDifference) */
581
+ symmetricDifferenceWith(otherIds) {
582
+ return this.#itemOrderSet.symmetricDifference(otherIds);
583
+ }
584
+ /** Total number of registered items */
585
+ get size() {
586
+ return this.#items.size;
587
+ }
588
+ /** Total number of registered groups */
589
+ get groupCount() {
590
+ return this.#groups.size;
591
+ }
592
+ /** Clear all items and groups */
593
+ clear() {
594
+ this.#items.clear();
595
+ this.#groups.clear();
596
+ this.#itemOrder = [];
597
+ this.#itemOrderSet.clear();
598
+ this.#invalidateCache();
599
+ this.#invalidateGroupCache();
600
+ }
601
+ [Symbol.dispose]() {
602
+ this.clear();
603
+ }
604
+ };
605
+ //#endregion
606
+ //#region src/core/search/default-scorer.ts
607
+ function isWordSeparator(code) {
608
+ return code === 32 || code === 9 || code === 45 || code === 95 || code === 46 || code === 47 || code === 92;
609
+ }
610
+ /**
611
+ * Public API: scores a command item against a search query.
612
+ * Multi-strategy: exact → prefix → substring → word-boundary → fuzzy.
613
+ * Returns null if no match. For batch use, prefer the search engine
614
+ * which pre-caches lowercase and normalizes query once.
615
+ */
616
+ function scoreItem(query, item) {
617
+ if (query === "") return {
618
+ id: item.id,
619
+ score: 1,
620
+ matches: []
621
+ };
622
+ const lowerQuery = query.toLowerCase();
623
+ let bestScore = 0;
624
+ let bestMatches = null;
625
+ const valueResult = scoreTarget(lowerQuery, item.value.toLowerCase());
626
+ if (valueResult !== null) {
627
+ bestScore = valueResult.score;
628
+ bestMatches = valueResult.matches;
629
+ if (bestScore >= 1) return {
630
+ id: item.id,
631
+ score: 1,
632
+ matches: bestMatches
633
+ };
634
+ }
635
+ const kw = item.keywords;
636
+ if (kw !== void 0) for (let i = 0; i < kw.length; i++) {
637
+ const result = scoreTarget(lowerQuery, kw[i].toLowerCase());
638
+ if (result !== null && result.score > bestScore) {
639
+ bestScore = result.score;
640
+ bestMatches = result.matches;
641
+ if (bestScore >= 1) break;
642
+ }
643
+ }
644
+ return bestMatches !== null ? {
645
+ id: item.id,
646
+ score: bestScore,
647
+ matches: bestMatches
648
+ } : null;
649
+ }
650
+ /**
651
+ * Internal fast path: called by search engine with pre-lowered query and targets.
652
+ * Eliminates all toLowerCase() calls on the hot path.
653
+ */
654
+ function scoreItemPreLowered(lowerQuery, id, lowerValue, lowerKeywords) {
655
+ let bestScore = 0;
656
+ let bestMatches = null;
657
+ const valueResult = scoreTarget(lowerQuery, lowerValue);
658
+ if (valueResult !== null) {
659
+ bestScore = valueResult.score;
660
+ bestMatches = valueResult.matches;
661
+ if (bestScore >= 1) return {
662
+ id,
663
+ score: 1,
664
+ matches: bestMatches
665
+ };
666
+ }
667
+ if (lowerKeywords !== void 0) for (let i = 0; i < lowerKeywords.length; i++) {
668
+ const result = scoreTarget(lowerQuery, lowerKeywords[i]);
669
+ if (result !== null && result.score > bestScore) {
670
+ bestScore = result.score;
671
+ bestMatches = result.matches;
672
+ if (bestScore >= 1) break;
673
+ }
674
+ }
675
+ return bestMatches !== null ? {
676
+ id,
677
+ score: bestScore,
678
+ matches: bestMatches
679
+ } : null;
680
+ }
681
+ function scoreTarget(query, lowerTarget) {
682
+ const tLen = lowerTarget.length;
683
+ if (tLen === 0) return null;
684
+ const qLen = query.length;
685
+ if (qLen === 0) return {
686
+ score: 1,
687
+ matches: []
688
+ };
689
+ if (qLen > tLen) return null;
690
+ if (lowerTarget === query) return {
691
+ score: 1,
692
+ matches: [[0, qLen]]
693
+ };
694
+ if (lowerTarget.startsWith(query)) return {
695
+ score: .9 + .1 * (qLen / tLen),
696
+ matches: [[0, qLen]]
697
+ };
698
+ const substringIdx = lowerTarget.indexOf(query);
699
+ if (substringIdx !== -1) {
700
+ const positionBonus = 1 - substringIdx / tLen;
701
+ const lengthRatio = qLen / tLen;
702
+ return {
703
+ score: .5 + .3 * positionBonus + .2 * lengthRatio,
704
+ matches: [[substringIdx, substringIdx + qLen]]
705
+ };
706
+ }
707
+ const wordBoundaryResult = scoreWordBoundary(query, qLen, lowerTarget, tLen);
708
+ if (wordBoundaryResult) return wordBoundaryResult;
709
+ return scoreFuzzy(query, qLen, lowerTarget, tLen);
710
+ }
711
+ function scoreWordBoundary(query, qLen, lowerTarget, tLen) {
712
+ let queryIdx = 0;
713
+ const matches = [];
714
+ let totalWeightedLen = 0;
715
+ let i = 0;
716
+ while (i < tLen && queryIdx < qLen) if ((i === 0 || isWordSeparator(lowerTarget.charCodeAt(i - 1))) && lowerTarget.charCodeAt(i) === query.charCodeAt(queryIdx)) {
717
+ const matchStart = i;
718
+ let matchLen = 0;
719
+ while (queryIdx < qLen && i < tLen && !isWordSeparator(lowerTarget.charCodeAt(i)) && lowerTarget.charCodeAt(i) === query.charCodeAt(queryIdx)) {
720
+ queryIdx++;
721
+ i++;
722
+ matchLen++;
723
+ }
724
+ matches.push([matchStart, matchStart + matchLen]);
725
+ totalWeightedLen += matchLen * 2;
726
+ } else i++;
727
+ if (queryIdx !== qLen) return null;
728
+ const maxPossible = qLen * 2;
729
+ return {
730
+ score: .3 + .4 * (totalWeightedLen / maxPossible),
731
+ matches
732
+ };
733
+ }
734
+ function scoreFuzzy(query, qLen, lowerTarget, tLen) {
735
+ let queryIdx = 0;
736
+ let targetIdx = 0;
737
+ const matches = [];
738
+ let currentMatchStart = -1;
739
+ let contiguityScore = 0;
740
+ while (queryIdx < qLen && targetIdx < tLen) if (query.charCodeAt(queryIdx) === lowerTarget.charCodeAt(targetIdx)) {
741
+ if (currentMatchStart === -1) currentMatchStart = targetIdx;
742
+ queryIdx++;
743
+ targetIdx++;
744
+ } else {
745
+ if (currentMatchStart !== -1) {
746
+ const segmentLen = targetIdx - currentMatchStart;
747
+ matches.push([currentMatchStart, targetIdx]);
748
+ contiguityScore += segmentLen * segmentLen;
749
+ currentMatchStart = -1;
750
+ }
751
+ targetIdx++;
752
+ }
753
+ if (currentMatchStart !== -1) {
754
+ const segmentLen = targetIdx - currentMatchStart;
755
+ matches.push([currentMatchStart, targetIdx]);
756
+ contiguityScore += segmentLen * segmentLen;
757
+ }
758
+ if (queryIdx !== qLen) return null;
759
+ const maxContiguity = qLen * qLen;
760
+ const contiguityRatio = contiguityScore / maxContiguity;
761
+ const positionBonus = 1 - (matches[0]?.[0] ?? 0) / tLen;
762
+ const lengthRatio = qLen / tLen;
763
+ return {
764
+ score: .1 + .3 * contiguityRatio + .15 * positionBonus + .1 * lengthRatio,
765
+ matches
766
+ };
767
+ }
768
+ //#endregion
769
+ //#region src/core/search/index.ts
770
+ const __DEV__ = globalThis.process ? globalThis.process.env.NODE_ENV !== "production" : false;
771
+ let leakRegistry;
772
+ if (__DEV__) leakRegistry = new FinalizationRegistry((label) => {
773
+ console.warn(`[modern-cmdk] ${label} was garbage collected without being disposed. Use \`using\` or call [Symbol.dispose]() to prevent leaks.`);
774
+ });
775
+ /**
776
+ * Creates a search engine with pluggable scorer and incremental filtering.
777
+ * When the query extends the previous one, only prior matches are re-scored.
778
+ * Pre-caches lowercase at index time — zero toLowerCase() calls during search.
779
+ * Uses Iterator Helpers (ES2026) for result pipelines and Set.difference for pruning.
780
+ */
781
+ function createSearchEngine(options) {
782
+ const customScorer = options?.scorer;
783
+ const useDefaultScorer = customScorer === void 0;
784
+ const indexedEntries = /* @__PURE__ */ new Map();
785
+ let previousQuery = "";
786
+ let previousResults = /* @__PURE__ */ new Set();
787
+ const sentinel = {};
788
+ if (__DEV__ && leakRegistry) leakRegistry.register(sentinel, "SearchEngine", sentinel);
789
+ return {
790
+ index(items) {
791
+ for (const item of items) indexedEntries.set(item.id, {
792
+ item,
793
+ lowerValue: item.value.toLowerCase(),
794
+ lowerKeywords: item.keywords?.map((k) => k.toLowerCase())
795
+ });
796
+ previousQuery = "";
797
+ previousResults = /* @__PURE__ */ new Set();
798
+ },
799
+ search(query, items) {
800
+ if (query === "") {
801
+ previousQuery = "";
802
+ previousResults = new Set(items.values().map((i) => i.id));
803
+ return items.values().map((item) => ({
804
+ id: item.id,
805
+ score: 1,
806
+ matches: []
807
+ }));
808
+ }
809
+ const lowerQuery = query.toLowerCase();
810
+ const candidateItems = query.startsWith(previousQuery) && previousQuery.length > 0 ? items.values().filter((item) => previousResults.has(item.id)) : items;
811
+ const results = [];
812
+ if (useDefaultScorer) for (const item of candidateItems) {
813
+ const entry = indexedEntries.get(item.id);
814
+ const result = entry ? scoreItemPreLowered(lowerQuery, item.id, entry.lowerValue, entry.lowerKeywords) : scoreItemPreLowered(lowerQuery, item.id, item.value.toLowerCase(), item.keywords?.map((k) => k.toLowerCase()));
815
+ if (result !== null) results.push(result);
816
+ }
817
+ else for (const item of candidateItems) {
818
+ const result = customScorer(query, item);
819
+ if (result != null) results.push(result);
820
+ }
821
+ results.sort((a, b) => b.score - a.score);
822
+ previousQuery = query;
823
+ previousResults = new Set(results.values().map((r) => r.id));
824
+ return results.values();
825
+ },
826
+ remove(ids) {
827
+ for (const id of ids) indexedEntries.delete(id);
828
+ previousResults = previousResults.difference(ids);
829
+ },
830
+ clear() {
831
+ indexedEntries.clear();
832
+ previousQuery = "";
833
+ previousResults.clear();
834
+ },
835
+ [Symbol.dispose]() {
836
+ indexedEntries.clear();
837
+ previousResults.clear();
838
+ if (__DEV__ && leakRegistry) leakRegistry.unregister(sentinel);
839
+ }
840
+ };
841
+ }
842
+ //#endregion
843
+ //#region src/core/utils/event-emitter.ts
844
+ /**
845
+ * Type-safe event emitter with strong references and Disposable subscriptions.
846
+ * Returns Disposable from `on()` for automatic unsubscription via `using`.
847
+ */
848
+ var TypedEmitter = class {
849
+ #listeners = /* @__PURE__ */ new Map();
850
+ /** Subscribe to an event. Returns a Disposable that removes the listener when disposed. */
851
+ on(event, listener) {
852
+ let set = this.#listeners.get(event);
853
+ if (!set) {
854
+ set = /* @__PURE__ */ new Set();
855
+ this.#listeners.set(event, set);
856
+ }
857
+ const fn = listener;
858
+ set.add(fn);
859
+ return { [Symbol.dispose]: () => {
860
+ set.delete(fn);
861
+ } };
862
+ }
863
+ /** Emit an event to all listeners. Snapshots the set to prevent live-iteration issues. */
864
+ emit(event, data) {
865
+ const set = this.#listeners.get(event);
866
+ if (!set || set.size === 0) return;
867
+ for (const fn of [...set]) fn(data);
868
+ }
869
+ /** Check if any listeners exist for an event */
870
+ has(event) {
871
+ const set = this.#listeners.get(event);
872
+ return set !== void 0 && set.size > 0;
873
+ }
874
+ /** Get count of listeners for an event */
875
+ listenerCount(event) {
876
+ return this.#listeners.get(event)?.size ?? 0;
877
+ }
878
+ /** Remove all listeners */
879
+ removeAll() {
880
+ this.#listeners.clear();
881
+ }
882
+ [Symbol.dispose]() {
883
+ this.#listeners.clear();
884
+ }
885
+ };
886
+ //#endregion
887
+ //#region src/core/utils/scheduler.ts
888
+ /** Whether we're in a browser environment with rAF available */
889
+ const hasRAF = typeof requestAnimationFrame === "function";
890
+ /** Feature detection for cutting-edge scheduling APIs */
891
+ const canYield = typeof globalThis.scheduler?.yield === "function";
892
+ const hasInputPending = typeof navigator?.scheduling?.isInputPending === "function";
893
+ /**
894
+ * Creates a batched update scheduler. Coalesces rapid state updates into a single
895
+ * execution pass using rAF (browser) or queueMicrotask (Node.js).
896
+ */
897
+ function createScheduler() {
898
+ let pending = [];
899
+ let rafId = null;
900
+ let microtaskScheduled = false;
901
+ function executeBatch() {
902
+ const batch = pending;
903
+ pending = [];
904
+ rafId = null;
905
+ microtaskScheduled = false;
906
+ if (batch.length > 10 && hasInputPending && navigator.scheduling?.isInputPending?.()) {
907
+ pending = [...batch, ...pending];
908
+ if (canYield) globalThis.scheduler?.yield?.().then(() => void executeBatch());
909
+ else rafId ??= requestAnimationFrame(() => void executeBatch());
910
+ return;
911
+ }
912
+ for (const update of batch) try {
913
+ update();
914
+ } catch (error) {
915
+ queueMicrotask(() => {
916
+ throw error;
917
+ });
918
+ }
919
+ }
920
+ function flush() {
921
+ if (rafId !== null) {
922
+ cancelAnimationFrame(rafId);
923
+ rafId = null;
924
+ }
925
+ microtaskScheduled = false;
926
+ executeBatch();
927
+ }
928
+ return {
929
+ schedule(update) {
930
+ pending.push(update);
931
+ if (hasRAF) rafId ??= requestAnimationFrame(() => void executeBatch());
932
+ else if (!microtaskScheduled) {
933
+ microtaskScheduled = true;
934
+ queueMicrotask(executeBatch);
935
+ }
936
+ },
937
+ flush,
938
+ [Symbol.dispose]() {
939
+ if (rafId !== null) {
940
+ cancelAnimationFrame(rafId);
941
+ rafId = null;
942
+ }
943
+ microtaskScheduled = false;
944
+ pending = [];
945
+ }
946
+ };
947
+ }
948
+ //#endregion
949
+ //#region src/core/machine.ts
950
+ /**
951
+ * Creates a headless command palette state machine with search, frecency,
952
+ * and keyboard shortcut support. Implements Disposable for `using` cleanup.
953
+ *
954
+ * @example
955
+ * ```ts
956
+ * using machine = createCommandMachine({ items, loop: true });
957
+ * machine.subscribe(() => console.log(machine.getState()));
958
+ * ```
959
+ */
960
+ function createCommandMachine(options = {}) {
961
+ let state = createInitialState(options);
962
+ let filteredIdSet = /* @__PURE__ */ new Set();
963
+ let filteredIdIndex = /* @__PURE__ */ new Map();
964
+ const registry = new CommandRegistry();
965
+ const searchEngine = options.search ?? createSearchEngine(typeof options.filter === "function" ? { scorer: (query, item) => {
966
+ const score = options.filter(item, query);
967
+ if (score === false) return null;
968
+ return {
969
+ id: item.id,
970
+ score,
971
+ matches: []
972
+ };
973
+ } } : void 0);
974
+ const scheduler = createScheduler();
975
+ const emitter = new TypedEmitter();
976
+ const keyboardRegistry = new KeyboardShortcutRegistry();
977
+ let frecencyEngine = null;
978
+ if (options.frecency?.enabled) {
979
+ frecencyEngine = new FrecencyEngine(options.frecency);
980
+ frecencyEngine.load();
981
+ }
982
+ if (options.items) {
983
+ registry.registerItems(options.items);
984
+ searchEngine.index(options.items);
985
+ for (const item of options.items) if (item.shortcut != null && item.onSelect != null) keyboardRegistry.register(item.shortcut, item.id, item.onSelect);
986
+ }
987
+ if (options.groups) for (const group of options.groups) registry.registerGroup(group);
988
+ refilter("");
989
+ function setState(newState) {
990
+ state = newState;
991
+ emitter.emit("stateChange", state);
992
+ }
993
+ function refilter(query) {
994
+ const items = registry.getItems();
995
+ const disableFilter = options.filter === false;
996
+ let filteredIds;
997
+ if (disableFilter || query === "") filteredIds = items.values().filter((i) => !i.disabled).map((i) => i.id).toArray();
998
+ else {
999
+ let results = searchEngine.search(query, items).toArray();
1000
+ if (frecencyEngine) {
1001
+ const bonuses = frecencyEngine.getAllBonuses();
1002
+ results = results.toSorted((a, b) => {
1003
+ const aBonus = bonuses.get(a.id) ?? 0;
1004
+ const bBonus = bonuses.get(b.id) ?? 0;
1005
+ return b.score + bBonus - (a.score + aBonus);
1006
+ });
1007
+ }
1008
+ filteredIds = results.map((r) => r.id);
1009
+ }
1010
+ filteredIdSet = new Set(filteredIds);
1011
+ filteredIdIndex = new Map(filteredIds.entries().map(([i, id]) => [id, i]));
1012
+ const groupedIds = Map.groupBy(filteredIds, (id) => {
1013
+ return registry.getItem(id)?.groupId ?? "__ungrouped";
1014
+ });
1015
+ const activeId = state.activeId && filteredIdSet.has(state.activeId) ? state.activeId : filteredIds[0] ?? null;
1016
+ setState({
1017
+ ...state,
1018
+ search: query,
1019
+ filteredIds,
1020
+ groupedIds,
1021
+ filteredCount: filteredIds.length,
1022
+ activeId,
1023
+ lastUpdated: Temporal.Now.instant()
1024
+ });
1025
+ }
1026
+ function navigate(direction) {
1027
+ const { filteredIds, activeId } = state;
1028
+ if (filteredIds.length === 0) return;
1029
+ if (direction === "first") {
1030
+ const newActiveId = filteredIds[0] ?? null;
1031
+ if (newActiveId !== activeId) {
1032
+ setState({
1033
+ ...state,
1034
+ activeId: newActiveId,
1035
+ lastUpdated: Temporal.Now.instant()
1036
+ });
1037
+ options.onActiveChange?.(newActiveId);
1038
+ }
1039
+ return;
1040
+ }
1041
+ if (direction === "last") {
1042
+ const newActiveId = filteredIds[filteredIds.length - 1] ?? null;
1043
+ if (newActiveId !== activeId) {
1044
+ setState({
1045
+ ...state,
1046
+ activeId: newActiveId,
1047
+ lastUpdated: Temporal.Now.instant()
1048
+ });
1049
+ options.onActiveChange?.(newActiveId);
1050
+ }
1051
+ return;
1052
+ }
1053
+ const loop = options.loop ?? true;
1054
+ const currentIdx = activeId ? filteredIdIndex.get(activeId) ?? -1 : -1;
1055
+ let newIdx;
1056
+ if (direction === "next") if (currentIdx === -1 || currentIdx >= filteredIds.length - 1) newIdx = loop ? 0 : filteredIds.length - 1;
1057
+ else newIdx = currentIdx + 1;
1058
+ else if (currentIdx <= 0) newIdx = loop ? filteredIds.length - 1 : 0;
1059
+ else newIdx = currentIdx - 1;
1060
+ const newActiveId = filteredIds[newIdx] ?? null;
1061
+ if (newActiveId !== activeId) {
1062
+ setState({
1063
+ ...state,
1064
+ activeId: newActiveId,
1065
+ lastUpdated: Temporal.Now.instant()
1066
+ });
1067
+ options.onActiveChange?.(newActiveId);
1068
+ }
1069
+ }
1070
+ function handleEvent(event) {
1071
+ switch (event.type) {
1072
+ case "SEARCH_CHANGE":
1073
+ refilter(event.query);
1074
+ options.onSearchChange?.(event.query);
1075
+ break;
1076
+ case "ITEM_SELECT": {
1077
+ const item = registry.getItem(event.id);
1078
+ if (item && !item.disabled) {
1079
+ item.onSelect?.();
1080
+ frecencyEngine?.recordSelection(event.id);
1081
+ emitter.emit("select", event.id);
1082
+ options.onSelect?.(event.id);
1083
+ }
1084
+ break;
1085
+ }
1086
+ case "ITEM_ACTIVATE":
1087
+ if (filteredIdSet.has(event.id)) {
1088
+ setState({
1089
+ ...state,
1090
+ activeId: event.id,
1091
+ lastUpdated: Temporal.Now.instant()
1092
+ });
1093
+ options.onActiveChange?.(event.id);
1094
+ }
1095
+ break;
1096
+ case "NAVIGATE":
1097
+ navigate(event.direction);
1098
+ break;
1099
+ case "PAGE_PUSH":
1100
+ setState({
1101
+ ...state,
1102
+ page: event.page,
1103
+ pageStack: [...state.pageStack, state.page],
1104
+ lastUpdated: Temporal.Now.instant()
1105
+ });
1106
+ break;
1107
+ case "PAGE_POP": {
1108
+ const prevPage = state.pageStack.at(-1);
1109
+ if (prevPage != null) setState({
1110
+ ...state,
1111
+ page: prevPage,
1112
+ pageStack: state.pageStack.toSpliced(-1, 1),
1113
+ lastUpdated: Temporal.Now.instant()
1114
+ });
1115
+ break;
1116
+ }
1117
+ case "OPEN":
1118
+ setState({
1119
+ ...state,
1120
+ open: true,
1121
+ lastUpdated: Temporal.Now.instant()
1122
+ });
1123
+ emitter.emit("openChange", true);
1124
+ options.onOpenChange?.(true);
1125
+ break;
1126
+ case "CLOSE":
1127
+ setState({
1128
+ ...state,
1129
+ open: false,
1130
+ lastUpdated: Temporal.Now.instant()
1131
+ });
1132
+ emitter.emit("openChange", false);
1133
+ options.onOpenChange?.(false);
1134
+ break;
1135
+ case "TOGGLE": {
1136
+ const newOpen = !state.open;
1137
+ setState({
1138
+ ...state,
1139
+ open: newOpen,
1140
+ lastUpdated: Temporal.Now.instant()
1141
+ });
1142
+ emitter.emit("openChange", newOpen);
1143
+ options.onOpenChange?.(newOpen);
1144
+ break;
1145
+ }
1146
+ case "ITEMS_LOADED":
1147
+ registry.registerItems(event.items);
1148
+ searchEngine.index(event.items);
1149
+ state = {
1150
+ ...state,
1151
+ loading: false
1152
+ };
1153
+ refilter(state.search);
1154
+ break;
1155
+ case "REGISTER_ITEM":
1156
+ registry.registerItem(event.item);
1157
+ searchEngine.index([event.item]);
1158
+ if (event.item.shortcut && event.item.onSelect) keyboardRegistry.register(event.item.shortcut, event.item.id, event.item.onSelect);
1159
+ refilter(state.search);
1160
+ break;
1161
+ case "UNREGISTER_ITEM":
1162
+ registry.unregisterItem(event.id);
1163
+ searchEngine.remove(new Set([event.id]));
1164
+ keyboardRegistry.unregisterByItem(event.id);
1165
+ refilter(state.search);
1166
+ break;
1167
+ case "REGISTER_GROUP":
1168
+ registry.registerGroup(event.group);
1169
+ refilter(state.search);
1170
+ break;
1171
+ case "UNREGISTER_GROUP":
1172
+ registry.unregisterGroup(event.id);
1173
+ refilter(state.search);
1174
+ break;
1175
+ }
1176
+ }
1177
+ return {
1178
+ getState() {
1179
+ return state;
1180
+ },
1181
+ send(event) {
1182
+ scheduler.schedule(() => handleEvent(event));
1183
+ },
1184
+ subscribe(listener) {
1185
+ const disposable = emitter.on("stateChange", listener);
1186
+ return () => disposable[Symbol.dispose]();
1187
+ },
1188
+ subscribeState(listener) {
1189
+ return emitter.on("stateChange", listener);
1190
+ },
1191
+ getRegistry() {
1192
+ return registry;
1193
+ },
1194
+ getKeyboardRegistry() {
1195
+ return keyboardRegistry;
1196
+ },
1197
+ getFilteredIdSet() {
1198
+ return filteredIdSet;
1199
+ },
1200
+ getFilteredIdIndex() {
1201
+ return filteredIdIndex;
1202
+ },
1203
+ [Symbol.dispose]() {
1204
+ scheduler[Symbol.dispose]();
1205
+ registry[Symbol.dispose]();
1206
+ searchEngine[Symbol.dispose]();
1207
+ emitter[Symbol.dispose]();
1208
+ keyboardRegistry[Symbol.dispose]();
1209
+ frecencyEngine?.[Symbol.dispose]();
1210
+ }
1211
+ };
1212
+ }
1213
+ //#endregion
1214
+ //#region src/core/search/fuzzy-scorer.ts
1215
+ /**
1216
+ * Async-safe fuzzy scorer — wraps scoring in Promise.try (ES2026) for error resilience.
1217
+ * Falls back gracefully on error via Promise.try's synchronous-throw capture.
1218
+ */
1219
+ function scoreItemAsync(query, item) {
1220
+ return Promise.try(() => scoreItem(query, item));
1221
+ }
1222
+ /**
1223
+ * Batch score items synchronously inside a single Promise.try (ES2026).
1224
+ * Eliminates per-item microtask overhead from async generators — runs the
1225
+ * entire scoring pipeline in one synchronous pass, wrapped for error safety.
1226
+ */
1227
+ function batchScoreItems(query, items) {
1228
+ return Promise.try(() => items.values().map((item) => scoreItem(query, item)).filter((r) => r != null).toArray().toSorted((a, b) => b.score - a.score));
1229
+ }
1230
+ //#endregion
1231
+ //#region src/core/telemetry.ts
1232
+ /**
1233
+ * Creates a telemetry middleware that measures command palette interactions.
1234
+ * Uses Temporal.Now.instant() (ES2026) for nanosecond-precision timestamps
1235
+ * and Temporal.Instant.since() for accurate duration computation.
1236
+ *
1237
+ * @example
1238
+ * ```ts
1239
+ * const telemetry = createTelemetryMiddleware({
1240
+ * onPaletteOpen: () => analytics.track('palette_opened'),
1241
+ * onItemSelected: (id, query, pos) => analytics.track('item_selected', { id, query, position: pos }),
1242
+ * });
1243
+ * ```
1244
+ */
1245
+ function createTelemetryMiddleware(hooks) {
1246
+ let openTimestamp = null;
1247
+ return {
1248
+ onOpen() {
1249
+ openTimestamp = Temporal.Now.instant();
1250
+ hooks.onPaletteOpen?.();
1251
+ },
1252
+ onClose() {
1253
+ if (openTimestamp != null) {
1254
+ const elapsed = Temporal.Now.instant().since(openTimestamp);
1255
+ hooks.onPaletteClose?.(elapsed.total("milliseconds"));
1256
+ openTimestamp = null;
1257
+ }
1258
+ },
1259
+ onSearch(query, resultCount, startTime) {
1260
+ const elapsed = Temporal.Now.instant().since(startTime);
1261
+ hooks.onSearchComplete?.(query, resultCount, elapsed.total("milliseconds"));
1262
+ },
1263
+ onSelect(itemId, query, position) {
1264
+ hooks.onItemSelected?.(itemId, query, position);
1265
+ }
1266
+ };
1267
+ }
1268
+ //#endregion
2
1269
  export { CommandRegistry, DEFAULT_FRECENCY_DECAY, DEFAULT_MACHINE_OPTIONS, FrecencyEngine, IdbFrecencyStorage, KeyboardShortcutRegistry, MemoryFrecencyStorage, TypedEmitter, batchScoreItems, computeFrecencyBonus, createCommandMachine, createInitialState, createScheduler, createSearchEngine, createTelemetryMiddleware, detectConflicts, findMatchingShortcut, formatShortcut, groupId, itemId, matchesShortcut, parseShortcut, scoreItem, scoreItemAsync };