OverviewFilesCommitsIssuesDocsReleasesPeers

pgh / lib / commands / peer.js

66 lines · javascript ref:
/**
 * pgh peer <subcommand>
 *
 * Subcommands:
 *   call <url> <method> [--param key=value]... [--json <JSON>]
 *     Raw envelope-signed RPC to a pear-git-v3 daemon at <url>. Params
 *     merge from repeated --param key=value (strings) and a single
 *     --json <blob> (parsed). Useful for probing handlers from the
 *     command line before higher-level commands wrap them.
 *
 * Higher-level commands (like `pgh device list --peer <url>`) reuse the
 * PghPeerClient underneath but present nicer output.
 */

import { PghPeerClient } from '../peer-client.js'

export const usage = `pgh peer — raw envelope-signed RPC to a remote daemon

  pgh peer call <url> <method> [--param k=v]... [--json <JSON>]

Params merge from repeated --param key=value (strings) and a single
--json <blob> (parsed). Useful for probing handlers directly.`

export async function run (_client, args, globals = {}) {
  const sub = args[0]
  if (!sub) throw new Error(usage)
  if (sub === 'call') return runCall(args.slice(1), globals)
  throw new Error('unknown peer subcommand: ' + sub + '\n' + usage)
}

async function runCall (args, globals) {
  const url = args[0]
  const method = args[1]
  if (!url || !method) {
    throw new Error('usage: pgh peer call <url> <method> [--param k=v] [--json <JSON>]')
  }

  const params = {}
  for (let i = 2; i < args.length; i++) {
    const a = args[i]
    if (a === '--param' && args[i + 1]) {
      const kv = args[++i]
      const eq = kv.indexOf('=')
      if (eq === -1) throw new Error('--param expects key=value, got: ' + kv)
      params[kv.slice(0, eq)] = kv.slice(eq + 1)
    } else if (a === '--json' && args[i + 1]) {
      const raw = args[++i]
      let parsed
      try { parsed = JSON.parse(raw) } catch (err) {
        throw new Error('--json value is not valid JSON: ' + err.message)
      }
      if (!parsed || typeof parsed !== 'object') {
        throw new Error('--json must decode to an object')
      }
      Object.assign(params, parsed)
    }
  }

  const client = await PghPeerClient.connect({ url })
  try {
    return await client.call(method, params)
  } finally {
    await client.close()
  }
}