modern-cmdk 1.0.1 → 1.1.0

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