matcher.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * The matcher primitive shared by both hook dialects: decide whether a matcher
  3. * pattern selects a given query (a tool name, a session source, …).
  4. *
  5. * The two dialects differ ONLY in how a non-empty pattern is interpreted, so
  6. * that single axis is the {@link MatcherMode} parameter:
  7. * - `claude`: a pattern of purely `[A-Za-z0-9_|]+` is a LITERAL (pipe =
  8. * exact-match alternation, e.g. `Edit|Write`); anything else is a regex.
  9. * - `codex`: every pattern is an unanchored regex (no literal fast path).
  10. *
  11. * Both treat an absent / empty / `'*'` pattern as match-all, and both treat an
  12. * invalid regex as a non-match: a broken matcher selects nothing rather than
  13. * throwing into the loop. This is SILENT — the boolean return cannot distinguish
  14. * "did not match" from "failed to compile", so a typo'd pattern (e.g. `[`)
  15. * quietly disables that matcher with no warning. Surfacing bad config would need
  16. * a diagnostic-returning variant or parse-time validation (`TODO(matcher-diagnostics)`).
  17. *
  18. * @module @deepseek-ai/dsh-hook-protocol/matcher
  19. */
  20. import type { MatcherMode } from './types.ts'
  21. /** True for an absent / empty / `'*'` pattern — the match-all sentinels. */
  22. function isMatchAll(matcher: string | undefined): boolean {
  23. return matcher === undefined || matcher === '' || matcher === '*'
  24. }
  25. /** A Claude-literal pattern is purely word chars + `|` (the regex-vs-literal discriminator). */
  26. const CLAUDE_LITERAL = /^[A-Za-z0-9_|]+$/
  27. /**
  28. * Whether `matcher` selects `query` under the given dialect {@link MatcherMode}.
  29. * Match-all sentinels (absent/`''`/`'*'`) always match. A `claude` literal
  30. * pattern exact-matches the query (splitting `|` into alternatives); every other
  31. * `claude` pattern and ALL `codex` patterns are tested as an unanchored regex.
  32. * An invalid regex matches nothing (never throws).
  33. */
  34. export function matchesMatcher(matcher: string | undefined, query: string, mode: MatcherMode): boolean {
  35. if (isMatchAll(matcher)) return true
  36. // matcher is a non-empty string past the match-all guard.
  37. const pattern = matcher as string
  38. if (mode === 'claude' && CLAUDE_LITERAL.test(pattern)) {
  39. return pattern.split('|').includes(query)
  40. }
  41. try {
  42. return new RegExp(pattern).test(query)
  43. } catch {
  44. // Invalid regex: a broken matcher selects nothing rather than throwing into
  45. // the agent loop. This is silent — callers get `false`, indistinguishable
  46. // from a genuine non-match, so a typo'd pattern quietly disables the matcher.
  47. // Surfacing it needs a diagnostic-returning variant (TODO(matcher-diagnostics)).
  48. return false
  49. }
  50. }