# @embedpdf/plugin-commands — ./internal CommandContext [InterfaceDeclaration] (from packages/plugin/commands/src/contract.ts): export interface CommandContext{ readonly documentId: string | null; readonly args?: unknown; core(): CoreState; get(token: CapabilityToken): T; tryGet(token: CapabilityToken): T | null; } CommandDef [InterfaceDeclaration] (from packages/plugin/commands/src/contract.ts): export interface CommandDef{ readonly id: string; readonly labelKey: string; readonly icon?: string; readonly iconAccent?: (ctx: CommandContext) => IconAccent | null; readonly shortcut?: string | readonly string[]; readonly categories?: readonly string[]; readonly menu?: string; readonly panel?: string |{ readonly id: string; readonly exclusive?: string} ; readonly modal?: string; readonly enabled?: (ctx: CommandContext) => boolean; readonly active?: (ctx: CommandContext) => boolean; readonly visible?: (ctx: CommandContext) => boolean; readonly run?: (context: CommandContext) => void | Promise; } CommandExecutedEvent [InterfaceDeclaration] (from packages/plugin/commands/src/contract.ts): export interface CommandExecutedEvent{ readonly commandId: CommandId; readonly documentId: string | null; readonly args: unknown; } CommandExecutionFailedEvent [InterfaceDeclaration] (from packages/plugin/commands/src/contract.ts): export interface CommandExecutionFailedEvent{ readonly commandId: CommandId; readonly documentId: string | null; readonly error: PluginErrorInfo; } CommandId [TypeAliasDeclaration] (from packages/plugin/commands/src/contract.ts): export type CommandId = string; CommandRegistry [TypeAliasDeclaration] (from packages/plugin/commands/src/registry.ts): export type CommandRegistry = Map; CommandsAction [TypeAliasDeclaration] (from packages/plugin/commands/src/model.ts): export type CommandsAction = |{ type: 'COMMANDS/DISABLE_CATEGORY'; category: string} |{ type: 'COMMANDS/ENABLE_CATEGORY'; category: string} |{ type: 'COMMANDS/SET_DISABLED_CATEGORIES'; categories: readonly string[]} ; CommandsCapability [InterfaceDeclaration] (from packages/plugin/commands/src/contract.ts): export interface CommandsCapability{ registerCommand(def: CommandDef, options?: RegisterCommandOptions): Unsubscribe; registerCommands(defs: readonly CommandDef[], options?: RegisterCommandOptions): Unsubscribe; hasCommand(id: CommandId): boolean; getCommand(id: CommandId): CommandDef | null; listCommandIds(): readonly CommandId[]; resolveCommand(id: CommandId, documentId?: string): ResolvedCommand | null; listCommands(documentId?: string): readonly ResolvedCommand[]; searchCommands(query: string, documentId?: string): readonly ResolvedCommand[]; listShortcuts(): readonly{ commandId: CommandId; shortcut: string} []; execute( id: CommandId, options?:{ documentId?: string; args?: unknown} & OperationOptions, ): Promise; canExecute(id: CommandId, documentId?: string): boolean; getDisabledCategories(): readonly string[]; isCategoryDisabled(category: string): boolean; disableCategory(category: string): void; enableCategory(category: string): void; setDisabledCategories(categories: readonly string[]): void; readonly onExecuted: EventHook; readonly onExecutionFailed: EventHook; } CommandsConfig [InterfaceDeclaration] (from packages/plugin/commands/src/contract.ts): export interface CommandsConfig{ commands?: readonly CommandDef[]; disabledCategories?: readonly string[]; } CommandsHostCapability [InterfaceDeclaration] (from packages/plugin/commands/src/host-contract.ts): export interface CommandsHostCapability extends CommandsCapability{ matchStroke(stroke: KeyStroke, options:{ isMac: boolean} ): CommandId | null; getMenuTarget(id: CommandId):{ menu?: string} | null; } CommandsState [InterfaceDeclaration] (from packages/plugin/commands/src/model.ts): export interface CommandsState{ readonly disabledCategories: readonly string[]; } CommandsToken [VariableDeclaration] (from packages/plugin/commands/src/host-contract.ts): CommandsToken = PublicCommandsToken as unknown as CapabilityToken ExecuteResult [TypeAliasDeclaration] (from packages/plugin/commands/src/contract.ts): export type ExecuteResult = |{ status: 'executed'} |{ status: 'rejected'; reason: 'not-found' | 'disabled' | 'hidden'} ; IconAccent [InterfaceDeclaration] (from packages/plugin/commands/src/contract.ts): export interface IconAccent{ readonly primary?: string; readonly secondary?: string; } RegisterCommandOptions [InterfaceDeclaration] (from packages/plugin/commands/src/contract.ts): export interface RegisterCommandOptions{ replace?: boolean; } RegisteredCommand [InterfaceDeclaration] (from packages/plugin/commands/src/registry.ts): export interface RegisteredCommand{ readonly def: CommandDef; readonly shortcuts: readonly string[]; readonly parsed: readonly ParsedShortcut[]; } ResolvedCommand [InterfaceDeclaration] (from packages/plugin/commands/src/contract.ts): export interface ResolvedCommand{ readonly id: string; readonly label: string; readonly icon?: string; readonly iconAccent?: IconAccent; readonly shortcuts: readonly string[]; readonly menu?: string; readonly enabled: boolean; readonly active: boolean; readonly visible: boolean; readonly categories: readonly string[]; } commandsReducer [FunctionDeclaration] (from packages/plugin/commands/src/model.ts): export function commandsReducer(state: CommandsState, action: CommandsAction): CommandsState{ switch (action.type){ case 'COMMANDS/DISABLE_CATEGORY': return state.disabledCategories.includes(action.category) ? state :{ disabledCategories: [...state.disabledCategories, action.category]} ; case 'COMMANDS/ENABLE_CATEGORY': return state.disabledCategories.includes(action.category) ?{ disabledCategories: state.disabledCategories.filter((c) => c !== action.category)} : state; case 'COMMANDS/SET_DISABLED_CATEGORIES': return{ disabledCategories: [...action.categories]} ; default: return state; } } createCommandsController [FunctionDeclaration] (from packages/plugin/commands/src/controller.ts): export function createCommandsController( ctx: PluginContext, config: CommandsConfig ={ } , ): CommandsHostCapability{ const registry: CommandRegistry = new Map(); for (const def of config.commands ?? []) registerCommand(registry, def); const report = (error: unknown) => globalThis.console?.error('[commands] listener failed:', error); const executed = createEventHook(report); const executionFailed = createEventHook(report); ctx.cleanup(() =>{ executed.dispose(); executionFailed.dispose(); } ); const commandContext = (documentId?: string, args?: unknown): CommandContext =>{ const target = documentId ?? ctx.core().activeId; const get = (token: CapabilityToken): T => target ? ctx.forDocument(token, target) : ctx.get(token); return{ documentId: target, ...(args === undefined ?{ } :{ args} ), core: ctx.core, get, tryGet: (token: CapabilityToken): T | null =>{ try{ return get(token); } catch{ return null; } } , } ; } ; const derive = ( fn: ((c: CommandContext) => boolean) | undefined, c: CommandContext, fallback: boolean, ): boolean =>{ if (!fn) return fallback; try{ return fn(c); } catch{ return fallback; } } ; const deriveAccent = ( fn: ((c: CommandContext) => IconAccent | null) | undefined, c: CommandContext, ): IconAccent | undefined =>{ if (!fn) return undefined; try{ return fn(c) ?? undefined; } catch{ return undefined; } } ; const resolveFresh = (entry: RegisteredCommand, documentId?: string): ResolvedCommand =>{ const{ def} = entry; const c = commandContext(documentId); const disabled = ctx.getState().disabledCategories; const categoryHidden = (def.categories ?? []).some((cat) => disabled.includes(cat)); const i18n = c.tryGet(I18nToken); const label = i18n ? i18n.t(def.labelKey) : def.labelKey; let active: boolean; if (def.active){ active = derive(def.active, c, false); } else{ const shell = c.tryGet(ShellToken); const panel = panelTarget(def); active = shell ? def.menu ? shell.isMenuOpen(def.menu) : panel ? shell.isOpen(panel.id) : def.modal ? shell.isOpen(def.modal) : false : false; } return{ id: def.id, label, icon: def.icon, iconAccent: deriveAccent(def.iconAccent, c), shortcuts: entry.shortcuts, menu: def.menu, enabled: derive(def.enabled, c, true) && !categoryHidden, active, visible: derive(def.visible, c, true) && !categoryHidden, categories: def.categories ?? [], } ; } ; const resolved = new Map(); const resolveCommand = (id: string, documentId?: string): ResolvedCommand | null =>{ const entry = registry.get(id); if (!entry) return null; const key = `${ documentId ?? ''} |${ id} `; const fresh = resolveFresh(entry, documentId); const previous = resolved.get(key); if (previous && resolvedCommandsEqual(previous, fresh)) return previous; resolved.set(key, fresh); return fresh; } ; const listed = new Map(); const listCommands = (documentId?: string): readonly ResolvedCommand[] =>{ const key = documentId ?? ''; const next = [...registry.keys()].flatMap((id) =>{ const r = resolveCommand(id, documentId); return r ? [r] : []; } ); const previous = listed.get(key); if (previous && previous.length === next.length && previous.every((r, i) => r === next[i])){ return previous; } listed.set(key, next); return next; } ; const execute = async ( id: string, options:{ documentId?: string; args?: unknown} ={ } , ): Promise =>{ const entry = registry.get(id); if (!entry) return{ status: 'rejected', reason: 'not-found'} ; const r = resolveCommand(id, options.documentId); if (!r || !r.visible) return{ status: 'rejected', reason: 'hidden'} ; if (!r.enabled) return{ status: 'rejected', reason: 'disabled'} ; const c = commandContext(options.documentId, options.args); try{ if (entry.def.run){ await entry.def.run(c); } else{ const shell = c.tryGet(ShellToken); const panel = panelTarget(entry.def); if (shell){ if (entry.def.menu) shell.toggleMenu(entry.def.menu); else if (panel) shell.toggle(panel.id, { exclusive: panel.exclusive} ); else if (entry.def.modal) shell.toggle(entry.def.modal, { exclusive: 'modal'} ); } } } catch (error){ const failure = toPluginError('commands', error); executionFailed.emit({ commandId: id, documentId: c.documentId, error: toPluginErrorInfo(failure), } ); throw failure; } executed.emit({ commandId: id, documentId: c.documentId, args: options.args} ); return{ status: 'executed'} ; } ; const registerOne = (def: CommandDef, options?:{ replace?: boolean} ): Unsubscribe =>{ const entry = registerCommand(registry, def, options); return () =>{ if (registry.get(def.id) === entry) registry.delete(def.id); } ; } ; return{ registerCommand: registerOne, registerCommands: (defs, options) =>{ const removers = defs.map((def) => registerOne(def, options)); return () => removers.forEach((remove) => remove()); } , hasCommand: (id) => registry.has(id), getCommand: (id) => registry.get(id)?.def ?? null, listCommandIds: () => [...registry.keys()], resolveCommand, listCommands, searchCommands: (query, documentId) =>{ const q = query.trim().toLowerCase(); return listCommands(documentId).filter( (r) => r.visible && (q === '' || r.label.toLowerCase().includes(q) || r.id.includes(q)), ); } , listShortcuts: () => [...registry.values()].flatMap((entry) => entry.shortcuts.map((shortcut) => ({ commandId: entry.def.id, shortcut} )), ), execute, canExecute: (id, documentId) =>{ const r = resolveCommand(id, documentId); return !!r && r.enabled && r.visible; } , getDisabledCategories: () => ctx.getState().disabledCategories, isCategoryDisabled: (category) => ctx.getState().disabledCategories.includes(category), disableCategory: (category) => ctx.dispatch({ type: 'COMMANDS/DISABLE_CATEGORY', category} ), enableCategory: (category) => ctx.dispatch({ type: 'COMMANDS/ENABLE_CATEGORY', category} ), setDisabledCategories: (categories) => ctx.dispatch({ type: 'COMMANDS/SET_DISABLED_CATEGORIES', categories} ), onExecuted: executed.on, onExecutionFailed: executionFailed.on, matchStroke: (stroke: KeyStroke, options) =>{ for (const [id, entry] of registry){ if (entry.parsed.some((p) => matchShortcut(p, stroke, options))) return id; } return null; } , getMenuTarget: (id) =>{ const entry = registry.get(id); return entry ?{ menu: entry.def.menu} : null; } , } satisfies CommandsHostCapability; } initialCommandsState [VariableDeclaration] (from packages/plugin/commands/src/model.ts): initialCommandsState = (disabled: readonly string[] = []): CommandsState => ({ disabledCategories: [...disabled], } ) registerCommand [FunctionDeclaration] (from packages/plugin/commands/src/registry.ts): export function registerCommand( registry: CommandRegistry, def: CommandDef, options: RegisterCommandOptions ={ } , ): RegisteredCommand{ if (registry.has(def.id) && !options.replace){ throw new PluginError('conflict', 'commands', `duplicate command '${ def.id} '`); } const shortcuts = def.shortcut === undefined ? [] : ([] as string[]).concat(def.shortcut); const entry: RegisteredCommand ={ def, shortcuts, parsed: shortcuts.map(parseShortcut)} ; registry.set(def.id, entry); return entry; } resolvedCommandsEqual [VariableDeclaration] (from packages/plugin/commands/src/contract.ts): resolvedCommandsEqual = ( a: ResolvedCommand | null, b: ResolvedCommand | null, ): boolean =>{ if (a === b) return true; if (!a || !b) return false; return ( a.id === b.id && a.label === b.label && a.icon === b.icon && a.iconAccent?.primary === b.iconAccent?.primary && a.iconAccent?.secondary === b.iconAccent?.secondary && a.menu === b.menu && a.enabled === b.enabled && a.active === b.active && a.visible === b.visible && a.shortcuts.length === b.shortcuts.length && a.shortcuts.every((s, i) => s === b.shortcuts[i]) ); }