Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

3.4 KB
Raw Blame
import { readdirSync } from 'node:fs'
import { join, relative } from 'node:path'
import { describe, expect, it } from 'vitest'

import { buildHandlerRoutes, dispatch, type HandlerContext } from './dispatch'
import { HANDLER_GROUPS, type HandlerGroup } from './handler-group-manifest'

// import.meta.dirname is unavailable in the CommonJS build:cli emit.
const HANDLERS_DIR = join(__dirname, 'handlers')

const HANDLER_RECORD_EXPORT = /_HANDLERS?$/

function listHandlerModules(dir: string): string[] {
  return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
    const path = join(dir, entry.name)
    if (entry.isDirectory()) {
      return listHandlerModules(path)
    }
    return entry.name.endsWith('.ts') && !entry.name.endsWith('.test.ts') ? [path] : []
  })
}

function isHandlerRecord(value: unknown): value is Record<string, unknown> {
  return (
    typeof value === 'object' &&
    value !== null &&
    Object.values(value).every((entry) => typeof entry === 'function')
  )
}

describe('handler group manifest', () => {
  it('exposes every declared key as a callable handler', async () => {
    const notCallable: string[] = []
    for (const group of HANDLER_GROUPS) {
      const loaded = await group.load()
      for (const key of group.keys) {
        if (typeof loaded[key] !== 'function') {
          notCallable.push(`${group.name}/${key}`)
        }
      }
    }
    expect(notCallable).toEqual([])
  })

  // Nested modules are spread into parent groups; verify routability rather than group names.
  it('routes every command exported by a handler module', async () => {
    const routes = buildHandlerRoutes(HANDLER_GROUPS)
    const unroutable: string[] = []
    for (const file of listHandlerModules(HANDLERS_DIR)) {
      const exports: Record<string, unknown> = await import(file)
      for (const [name, value] of Object.entries(exports)) {
        if (!HANDLER_RECORD_EXPORT.test(name) || !isHandlerRecord(value)) {
          continue
        }
        for (const key of Object.keys(value)) {
          if (!routes.has(key)) {
            unroutable.push(`${relative(HANDLERS_DIR, file)} ${name}: ${key}`)
          }
        }
      }
    }
    expect(unroutable).toEqual([])
  })
})

describe('duplicate command keys', () => {
  const group = (name: string, keys: string[]): HandlerGroup => ({
    name,
    keys,
    load: async () => ({})
  })

  it('rejects the same key claimed by two groups', () => {
    expect(() =>
      buildHandlerRoutes([group('alpha', ['ship it']), group('beta', ['ship it'])])
    ).toThrow('Duplicate CLI handler registration for "ship it" (alpha and beta)')
  })

  it('rejects a key duplicated inside one group list', () => {
    expect(() => buildHandlerRoutes([group('alpha', ['ship it', 'ship it'])])).toThrow(
      'Duplicate CLI handler registration for "ship it"'
    )
  })

  it('accepts distinct keys across groups', () => {
    const routes = buildHandlerRoutes([group('alpha', ['a']), group('beta', ['b'])])
    expect([...routes.keys()]).toEqual(['a', 'b'])
  })
})

describe('dispatch errors', () => {
  const ctx = {
    flags: new Map(),
    cwd: '/tmp',
    json: false
  } as unknown as HandlerContext

  it('reports an unknown command with the joined path', async () => {
    await expect(dispatch(['not', 'a', 'command'], ctx)).rejects.toMatchObject({
      code: 'invalid_argument',
      message: 'Unknown command: not a command'
    })
  })
})