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.8 KB
Raw Blame
import type { z } from 'zod'

type JsonSchema = z.core.JSONSchema.BaseSchema
type JsonSchemaNode = z.core.JSONSchema._JSONSchema

type FieldRow = { path: string; schema: JsonSchema; required: boolean }

const DEF_PREFIX = '#/$defs/'

function asSchema(node: JsonSchemaNode | undefined): JsonSchema {
  return typeof node === 'object' ? node : {}
}

function defName(ref: string): string {
  return ref.startsWith(DEF_PREFIX) ? ref.slice(DEF_PREFIX.length) : ref
}

function cell(text: string): string {
  return text.replace(/\|/g, '\\|').replace(/\n/g, ' ')
}

function typeLabel(schema: JsonSchema): string {
  if (schema.$ref) {
    const name = defName(schema.$ref)
    return `[${name}](#${name.toLowerCase()})`
  }
  if (schema.const !== undefined) {
    return `\`${JSON.stringify(schema.const)}\``
  }
  if (schema.enum) {
    return schema.enum.map((value) => `\`${JSON.stringify(value)}\``).join(' \\| ')
  }
  if (schema.type === 'array' && !Array.isArray(schema.items)) {
    const item = typeLabel(asSchema(schema.items))
    return item.includes(' \\| ') ? `(${item})[]` : `${item}[]`
  }
  if (schema.anyOf) {
    return [...new Set(schema.anyOf.map(typeLabel))].join(' \\| ')
  }
  if (Array.isArray(schema.type)) {
    return schema.type.join(' \\| ')
  }
  return schema.type ?? 'any'
}

/** Nested plain objects flatten into dotted rows; named fragments get their own section. */
function fieldRows(schema: JsonSchema, prefix: string): FieldRow[] {
  const required = new Set(schema.required ?? [])
  return Object.entries(schema.properties ?? {}).flatMap(([key, node]) => {
    const field = asSchema(node)
    const row = { path: `${prefix}${key}`, schema: field, required: required.has(key) }
    return field.type === 'object' && field.properties
      ? [row, ...fieldRows(field, `${row.path}.`)]
      : [row]
  })
}

function describe(schema: JsonSchema, defs: Record<string, JsonSchema>): string {
  // Why: a fragment reference carries no prose of its own; reuse the fragment's summary.
  const description = schema.$ref ? defs[defName(schema.$ref)]?.description : schema.description
  const parts = [description ?? '']
  if (schema.examples?.length) {
    parts.push(`Example: \`${JSON.stringify(schema.examples[0])}\``)
  }
  return parts.filter(Boolean).join(' ')
}

function since(schema: JsonSchema): string {
  const value = schema['x-orca-since']
  return typeof value === 'string' ? value : ''
}

function fieldTable(schema: JsonSchema, defs: Record<string, JsonSchema>): string[] {
  return [
    '| Field | Type | Required | Since | Description |',
    '| --- | --- | --- | --- | --- |',
    ...fieldRows(schema, '').map(
      (row) =>
        `| \`${row.path}\` | ${typeLabel(row.schema)} | ${row.required ? 'yes' : 'no'} | ${since(row.schema)} | ${cell(describe(row.schema, defs))} |`
    )
  ]
}

/** Author reference rendered from the published JSON Schema, so prose and schema never drift. */
export function renderPluginSchemaReference(
  schema: JsonSchema,
  options: { file: string; schemaFile: string; sinceNote: string; appendix?: readonly string[] }
): string {
  const defs = schema.$defs ?? {}
  const lines = [
    `# ${schema.title ?? options.file} reference`,
    '',
    `<!-- Generated by \`pnpm generate:plugin-schemas\` from src/shared/plugins. Do not edit. -->`,
    '',
    schema.description ?? '',
    '',
    `Add \`"$schema": "${schema.$id ?? options.schemaFile}"\` to \`${options.file}\` for completion and inline errors in your editor.`,
    options.sinceNote,
    '',
    '## Fields',
    '',
    ...fieldTable(schema, defs)
  ]
  for (const [name, fragment] of Object.entries(defs)) {
    lines.push('', `## ${name}`, '', fragment.description ?? '', '', ...fieldTable(fragment, defs))
  }
  if (options.appendix) {
    lines.push('', ...options.appendix)
  }
  return `${lines.join('\n')}\n`
}