High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor(cli): collapse the apiclient Do* verbs into one executor with print/exit/capture options so a new vocab-carrying route adds an option, not another copy (PIN-423)
Luigi Agosti27d749ee08e4
diff --git a/internal/cli/actions/actions_a11y.go b/internal/cli/actions/actions_a11y.goindex 471461b9..79893cf1 100644--- a/internal/cli/actions/actions_a11y.go+++ b/internal/cli/actions/actions_a11y.go@@ -43,12 +43,12 @@ func A11yAudit(client *http.Client, base, token string, cmd *cobra.Command) {// vocabulary token; capture it the way snapshot does (keyed by the resolved// tab, implicit when no --tab) so a later action on a returned ref echoes the// token the audit minted instead of a stale one the server would refuse 409.- implicit := params.Get("tabId") == ""+ capture := apiclient.CaptureVocab(namedNoTab(cmd))if jsonOutput, _ := cmd.Flags().GetBool("json"); jsonOutput {- apiclient.DoGetCapturingVocab(client, base, token, "/a11y/audit", params, implicit)+ apiclient.DoGet(client, base, token, "/a11y/audit", params, capture)return}- printA11ySummary(apiclient.DoGetRawCapturingVocab(client, base, token, "/a11y/audit", params, implicit))+ printA11ySummary(apiclient.DoGetRaw(client, base, token, "/a11y/audit", params, capture))}// printA11ySummary renders a compact human summary for either engine, fallingdiff --git a/internal/cli/actions/actions_audit.go b/internal/cli/actions/actions_audit.goindex 97b8d538..d5c99b09 100644--- a/internal/cli/actions/actions_audit.go+++ b/internal/cli/actions/actions_audit.go@@ -109,7 +109,7 @@ func loadRunCookies(cmd *cobra.Command) ([]audit.Cookie, error) {// setRunCookies injects cookies through POST /cookies, using a throwaway// blank tab for the required tab context so it works on a fresh browser.func setRunCookies(client *http.Client, base, token, url string, cookies []audit.Cookie) error {- raw, err := apiclient.DoPostRawE(client, base, token, "/tab", map[string]any{"action": "new"})+ raw, err := apiclient.DoRawE(client, base, token, http.MethodPost, "/tab", apiclient.WithBody(map[string]any{"action": "new"}))if err != nil {return err}@@ -120,13 +120,15 @@ func setRunCookies(client *http.Client, base, token, url string, cookies []auditreturn fmt.Errorf("parse temporary tab: %w", err)}if tab.TabID != "" {- defer func() { _, _ = apiclient.DoPostRawE(client, base, token, "/close", map[string]any{"tabId": tab.TabID}) }()+ defer func() {+ _, _ = apiclient.DoRawE(client, base, token, http.MethodPost, "/close", apiclient.WithBody(map[string]any{"tabId": tab.TabID}))+ }()}body := map[string]any{"url": url, "cookies": cookies}if tab.TabID != "" {body["tabId"] = tab.TabID}- raw, err = apiclient.DoPostRawE(client, base, token, "/cookies", body)+ raw, err = apiclient.DoRawE(client, base, token, http.MethodPost, "/cookies", apiclient.WithBody(body))if err != nil {return err}@@ -147,7 +149,7 @@ func setRunCookies(client *http.Client, base, token, url string, cookies []audit// startIsolatedInstance creates an unnamed instance. The orchestrator assigns// these an instance-* profile and removes its profile directory on stop.func startIsolatedInstance(client *http.Client, base, token string) (string, func() error, error) {- raw, err := apiclient.DoPostRawE(client, base, token, "/instances/start", map[string]any{})+ raw, err := apiclient.DoRawE(client, base, token, http.MethodPost, "/instances/start", apiclient.WithBody(map[string]any{}))if err != nil {return "", nil, fmt.Errorf("start isolated instance: %w", err)}@@ -162,7 +164,7 @@ func startIsolatedInstance(client *http.Client, base, token string) (string, funreturn "", nil, fmt.Errorf("start isolated instance: response omitted id or url")}cleanup := func() error {- _, err := apiclient.DoPostRawE(client, base, token, "/instances/"+url.PathEscape(instance.ID)+"/stop", nil)+ _, err := apiclient.DoRawE(client, base, token, http.MethodPost, "/instances/"+url.PathEscape(instance.ID)+"/stop")if err != nil {return fmt.Errorf("stop isolated instance: %w", err)}@@ -186,7 +188,7 @@ func waitForIsolatedInstance(client *http.Client, base, token, instanceID stringpath := "/instances/" + url.PathEscape(instanceID)for {- raw, err := apiclient.DoGetRawE(client, base, token, path, nil)+ raw, err := apiclient.DoRawE(client, base, token, http.MethodGet, path)if err == nil {var instance struct {Status string `json:"status"`@@ -215,7 +217,7 @@ func waitForIsolatedInstance(client *http.Client, base, token, instanceID string// through the orchestrator proxy. Child URLs normally bind to localhost and// are therefore not reachable by remote CLI clients.func resolveProfileBase(client *http.Client, base, token, profile string) (string, error) {- raw, err := apiclient.DoGetRawE(client, base, token, "/instances", nil)+ raw, err := apiclient.DoRawE(client, base, token, http.MethodGet, "/instances")if err != nil {return "", err}@@ -311,7 +313,7 @@ func Audit(client *http.Client, base, token string, cmd *cobra.Command, target s}longClient := &http.Client{Transport: client.Transport, Timeout: auditTimeout}- raw, err := apiclient.DoPostRawE(longClient, base, token, "/audit", body)+ raw, err := apiclient.DoRawE(longClient, base, token, http.MethodPost, "/audit", apiclient.WithBody(body))if err != nil {return err}diff --git a/internal/cli/actions/actions_compare.go b/internal/cli/actions/actions_compare.goindex 11c286e6..bc9a772a 100644--- a/internal/cli/actions/actions_compare.go+++ b/internal/cli/actions/actions_compare.go@@ -59,7 +59,7 @@ func Compare(client *http.Client, base, token string, cmd *cobra.Command, liveBaif concurrency > 0 {body["concurrency"] = concurrency}- raw, err := apiclient.DoPostRawE(longClient, base, token, "/audit", body)+ raw, err := apiclient.DoRawE(longClient, base, token, http.MethodPost, "/audit", apiclient.WithBody(body))if err != nil {return audit.AuditReport{}, err}diff --git a/internal/cli/actions/actions_cookies.go b/internal/cli/actions/actions_cookies.goindex bd59a1e8..d093c8bd 100644--- a/internal/cli/actions/actions_cookies.go+++ b/internal/cli/actions/actions_cookies.go@@ -67,7 +67,7 @@ func CookiesSet(client *http.Client, base, token string, cmd *cobra.Command, nam// CookiesClear clears all browser cookies.func CookiesClear(client *http.Client, base, token string, cmd *cobra.Command) {- result := apiclient.DoDeleteQuiet(client, base, token, "/cookies", nil)+ result := apiclient.DoDelete(client, base, token, "/cookies", nil, apiclient.Quiet())if result == nil {fmt.Fprintln(os.Stderr, "ERROR: cookies: clear failed")os.Exit(2)diff --git a/internal/cli/actions/actions_element.go b/internal/cli/actions/actions_element.goindex ba49d23d..b4300044 100644--- a/internal/cli/actions/actions_element.go+++ b/internal/cli/actions/actions_element.go@@ -2,7 +2,11 @@ package actionsimport ("encoding/json"+ "errors"+ "fmt""net/http"+ "net/url"+ "os""strconv""strings"@@ -128,21 +132,21 @@ func postActionWithHeaders(client *http.Client, base, token string, cmd *cobra.C}}- capture := apiclient.CaptureVocab(tabID == "")+ opts := []apiclient.RequestOption{apiclient.WithHeaders(headers), apiclient.CaptureVocab(namedNoTab(cmd))}jsonOutput, _ := cmd.Flags().GetBool("json")if jsonOutput {- apiclient.DoPostWithHeaders(client, base, token, path, body, headers, capture)+ apiclient.DoPost(client, base, token, path, body, opts...)return}- result := apiclient.DoPostQuietWithHeaders(client, base, token, path, body, headers, capture)+ result := apiclient.DoPostQuiet(client, base, token, path, body, opts...)kind, _ := body["kind"].(string)printActionResult(kind, result)snap, _ := cmd.Flags().GetBool("snap")snapDiff, _ := cmd.Flags().GetBool("snap-diff")if snap || snapDiff {- fetchAndPrintSnapshot(client, base, token, tabID, snapDiff, tabID == "")+ fetchAndPrintSnapshot(client, base, token, cmd, tabID, snapDiff)}text, _ := cmd.Flags().GetBool("text")@@ -151,15 +155,33 @@ func postActionWithHeaders(client *http.Client, base, token string, cmd *cobra.C}}-func fetchAndPrintSnapshot(client *http.Client, base, token, tabID string, diff, implicit bool) {- params := "filter=interactive&format=compact"+func namedNoTab(cmd *cobra.Command) bool {+ tab, _ := cmd.Flags().GetString("tab")+ return tab == ""+}++// fetchAndPrintSnapshot is the --snap / --snap-diff tail. It stays best-effort —+// a transport or HTTP failure warns on stderr and returns, never exits: this tail+// runs after an action that already succeeded, so a cosmetic snapshot failure+// must not turn a successful action into a non-zero exit.+func fetchAndPrintSnapshot(client *http.Client, base, token string, cmd *cobra.Command, tabID string, diff bool) {+ params := url.Values{"filter": {"interactive"}, "format": {"compact"}}if diff {- params += "&diff=true"+ params.Set("diff", "true")}if tabID != "" {- params += "&tabId=" + tabID+ params.Set("tabId", tabID)+ }+ body, err := apiclient.DoRawE(client, base, token, http.MethodGet, "/snapshot", apiclient.WithQuery(params), apiclient.CaptureVocab(namedNoTab(cmd)))+ var statusErr *apiclient.StatusError+ switch {+ case errors.As(err, &statusErr):+ fmt.Fprintf(os.Stderr, "snapshot error %d: %s\n", statusErr.Status, string(statusErr.Body))+ case err != nil:+ fmt.Fprintf(os.Stderr, "snapshot failed: %v\n", errors.Unwrap(err))+ default:+ fmt.Println(string(body))}- apiclient.DoGetRawAndPrintCapturingVocab(client, base, token, "/snapshot?"+params, implicit)}func fetchAndPrintText(client *http.Client, base, token, tabID string) {diff --git a/internal/cli/actions/actions_element_test.go b/internal/cli/actions/actions_element_test.goindex c7fc7162..a6dac75c 100644--- a/internal/cli/actions/actions_element_test.go+++ b/internal/cli/actions/actions_element_test.go@@ -2,6 +2,7 @@ package actionsimport ("encoding/json"+ "net/url""strings""testing"@@ -269,7 +270,7 @@ func TestPressWithSnapDiffFetchesSnapshot(t *testing.T) {if m.requests[1].Path != "/snapshot" {t.Fatalf("snapshot path = %q, want /snapshot", m.requests[1].Path)}- if m.requests[1].Query != "filter=interactive&format=compact&diff=true" {+ if m.requests[1].Query != (url.Values{"filter": {"interactive"}, "format": {"compact"}, "diff": {"true"}}).Encode() {t.Fatalf("snapshot query = %q", m.requests[1].Query)}}diff --git a/internal/cli/actions/actions_navigate.go b/internal/cli/actions/actions_navigate.goindex c817cc7f..9aa4fc00 100644--- a/internal/cli/actions/actions_navigate.go+++ b/internal/cli/actions/actions_navigate.go@@ -69,8 +69,7 @@ func printPostActionOutput(client *http.Client, base, token, tabID string, cmd *snap, _ := cmd.Flags().GetBool("snap")snapDiff, _ := cmd.Flags().GetBool("snap-diff")if snap || snapDiff {- userTab, _ := cmd.Flags().GetString("tab")- fetchAndPrintSnapshot(client, base, token, tabID, snapDiff, userTab == "")+ fetchAndPrintSnapshot(client, base, token, cmd, tabID, snapDiff)}if text, _ := cmd.Flags().GetBool("text"); text {fetchAndPrintText(client, base, token, tabID)diff --git a/internal/cli/actions/actions_scrape.go b/internal/cli/actions/actions_scrape.goindex 6341c0eb..ce491697 100644--- a/internal/cli/actions/actions_scrape.go+++ b/internal/cli/actions/actions_scrape.go@@ -75,7 +75,7 @@ func Scrape(client *http.Client, base, token string, cmd *cobra.Command, target}longClient := &http.Client{Transport: client.Transport, Timeout: scrapeTimeout}- raw, err := apiclient.DoPostRawE(longClient, base, token, "/scrape", body)+ raw, err := apiclient.DoRawE(longClient, base, token, http.MethodPost, "/scrape", apiclient.WithBody(body))if err != nil {return err}diff --git a/internal/cli/actions/actions_snapshot.go b/internal/cli/actions/actions_snapshot.goindex 865d211f..24ffdbad 100644--- a/internal/cli/actions/actions_snapshot.go+++ b/internal/cli/actions/actions_snapshot.go@@ -34,8 +34,7 @@ func Snapshot(client *http.Client, base, token string, cmd *cobra.Command, selecif v, _ := cmd.Flags().GetString("tab"); v != "" {params.Set("tabId", v)}- implicit := params.Get("tabId") == ""- result := apiclient.DoGetCapturingVocab(client, base, token, "/snapshot", params, implicit)+ result := apiclient.DoGet(client, base, token, "/snapshot", params, apiclient.CaptureVocab(namedNoTab(cmd)))apiclient.SuggestNextAction("snapshot", result)}diff --git a/internal/cli/actions/actions_storage.go b/internal/cli/actions/actions_storage.goindex b75dd57b..37e816c3 100644--- a/internal/cli/actions/actions_storage.go+++ b/internal/cli/actions/actions_storage.go@@ -81,5 +81,5 @@ func deleteStorage(client *http.Client, base, token string, cmd *cobra.Command,body["tabId"] = tabID}- requireMap(apiclient.DoDeleteJSON(client, base, token, "/storage", body), 1, "Failed to delete storage")+ requireMap(apiclient.DoDelete(client, base, token, "/storage", nil, apiclient.WithBody(body)), 1, "Failed to delete storage")}diff --git a/internal/cli/apiclient/apierror.go b/internal/cli/apiclient/apierror.goindex 5e34adb7..0eb9bac7 100644--- a/internal/cli/apiclient/apierror.go+++ b/internal/cli/apiclient/apierror.go@@ -21,6 +21,14 @@ func mustRequest(client *http.Client, token string, r request) (int, []byte) {return status, body}+type StatusError struct {+ Status int+ Body []byte+ message string+}++func (e *StatusError) Error() string { return e.message }+// exitOnAPIError is a terminal path: the command is ending, so this is where the// failure is HANDLED rather than formatted, and where the cached tab that produced// a dead id is dropped.diff --git a/internal/cli/apiclient/apierror_test.go b/internal/cli/apiclient/apierror_test.goindex e148f145..3ce8b55d 100644--- a/internal/cli/apiclient/apierror_test.go+++ b/internal/cli/apiclient/apierror_test.go@@ -181,8 +181,8 @@ func TestUnrelatedTabNotFoundGetsNoRemedy(t *testing.T) {}}-// DoGetRawE and DoPostRawE return instead of terminating — one caller polls them-// ten times a second — so rendering their error must leave the cache alone.+// DoRawE returns instead of terminating — one caller polls it+// ten times a second — so rendering its error must leave the cache alone.func TestReturningRequestPathsLeaveTheCacheIntact(t *testing.T) {path := cachedTabFile(t, "CACHED-TAB")srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {@@ -195,9 +195,11 @@ func TestReturningRequestPathsLeaveTheCacheIntact(t *testing.T) {name stringcall func() ([]byte, error)}{- {"DoGetRawE", func() ([]byte, error) { return DoGetRawE(srv.Client(), srv.URL, "", "/tabs/CACHED-TAB/text", nil) }},- {"DoPostRawE", func() ([]byte, error) {- return DoPostRawE(srv.Client(), srv.URL, "", "/action", map[string]any{"kind": "click"})+ {"GET", func() ([]byte, error) {+ return DoRawE(srv.Client(), srv.URL, "", http.MethodGet, "/tabs/CACHED-TAB/text")+ }},+ {"POST", func() ([]byte, error) {+ return DoRawE(srv.Client(), srv.URL, "", http.MethodPost, "/action", WithBody(map[string]any{"kind": "click"}))}},} {t.Run(tc.name, func(t *testing.T) {diff --git a/internal/cli/apiclient/client.go b/internal/cli/apiclient/client.goindex 06f47284..449ff907 100644--- a/internal/cli/apiclient/client.go+++ b/internal/cli/apiclient/client.go@@ -34,17 +34,6 @@ type vocabStore struct {Entries []vocabEntry `json:"entries"`}-// DoGetCapturingVocab performs a GET like DoGet and, on success, persists the-// response's vocabulary token keyed by the tab the server resolved (the-// X-PinchTab-Tab-Id header), not by how the caller spelled --tab. When the-// snapshot was implicit (no --tab), the resolved tab also becomes the store's-// current pointer, so a later implicit action echoes that tab's token. The token-// is delivered as a response header so it survives every snapshot format,-// including the compact text the CLI defaults to.-func DoGetCapturingVocab(client *http.Client, base, token, path string, params url.Values, implicit bool) map[string]any {- return DoGet(client, base, token, path, params, CaptureVocab(implicit))-}-// VocabForAction returns the tab id to tag and the token to echo for an action.// An explicit --tab X uses X's own record; an implicit action uses the current// pointer's tab. The returned tab is sent as VocabTabHeader so the server can@@ -147,153 +136,89 @@ func fileSlug(s string) string {return s}-// doAndRender runs the request with the standard fatal-on-transport-error +-// exit-on-HTTP-error policy, then pretty-prints and decodes the body.-func doAndRender(client *http.Client, token string, r request) map[string]any {+// execute applies the standard fatal-on-transport-error + exit-on-HTTP-error+// policy and returns the body.+func execute(client *http.Client, token string, r request) []byte {status, body := mustRequest(client, token, r)exitOnAPIError(r, status, body)+ return body+}++// executeE is execute's returning twin: long-running commands use it when they+// need to release resources before reporting a request failure.+func executeE(client *http.Client, token string, r request) ([]byte, error) {+ status, body, err := doRequest(client, token, r)+ if err != nil {+ return nil, fmt.Errorf("request failed: %w", err)+ }+ if status >= http.StatusBadRequest {+ return nil, &StatusError{Status: status, Body: body, message: strings.TrimSpace(renderAPIError(r, status, body))}+ }+ return body, nil+}++func render(r request, body []byte) map[string]any {+ if r.quiet {+ return decodeObject(body)+ }return printAndDecode(body)}-func DoGet(client *http.Client, base, token, path string, params url.Values, opts ...RequestOption) map[string]any {- return doAndRender(client, token, newRequest("GET", base, buildURL(base, path, params), nil, nil, opts))+// decodeObject populates a map from an object response; array/scalar responses+// leave it nil, so callers that need a map should branch on result == nil.+func decodeObject(body []byte) map[string]any {+ var result map[string]any+ _ = json.Unmarshal(body, &result)+ return result}-func DoGetRaw(client *http.Client, base, token, path string, params url.Values, opts ...RequestOption) []byte {- r := newRequest("GET", base, buildURL(base, path, params), nil, nil, opts)- status, body := mustRequest(client, token, r)- exitOnAPIError(r, status, body)- return body+func prepend(first RequestOption, opts []RequestOption) []RequestOption {+ return append([]RequestOption{first}, opts...)}-// DoGetRawCapturingVocab is DoGetRaw plus the vocabulary capture of-// DoGetCapturingVocab: it returns the raw body unprinted (for a caller that-// renders its own summary) and persists the response's vocabulary token so a-// later action echoes it. The a11y axe audit needs this: it re-epochs the tab's-// ref cache, so an action on a returned ref would be refused 409 against a stale-// token if the CLI never captured the fresh one.-func DoGetRawCapturingVocab(client *http.Client, base, token, path string, params url.Values, implicit bool) []byte {- return DoGetRaw(client, base, token, path, params, CaptureVocab(implicit))+func DoGet(client *http.Client, base, token, path string, params url.Values, opts ...RequestOption) map[string]any {+ r := newRequest(http.MethodGet, base, path, prepend(WithQuery(params), opts)...)+ return render(r, execute(client, token, r))}-// DoGetRawAndPrintCapturingVocab fetches and prints the raw snapshot body (for the-// --snap / --snap-diff tail) and, on success, persists the response's vocabulary-// token keyed by the resolved tab (implicit when the caller named no tab), so a ref-// the snapshot printed can be acted on without a re-snapshot and without a false-// 409. It stays best-effort — a transport or HTTP failure warns on stderr and-// returns, never exits (unlike DoGetRawCapturingVocab, which calls exitOnAPIError):-// this tail runs after an action that already succeeded, so a cosmetic snapshot-// failure must not turn a successful action into a non-zero exit.-func DoGetRawAndPrintCapturingVocab(client *http.Client, base, token, pathWithQuery string, implicit bool) {- status, body, err := doRequest(client, token, newRequest("GET", base, base+pathWithQuery, nil, nil, []RequestOption{CaptureVocab(implicit)}))- if err != nil {- fmt.Fprintf(os.Stderr, "snapshot failed: %v\n", err)- return- }- if status >= 400 {- fmt.Fprintf(os.Stderr, "snapshot error %d: %s\n", status, string(body))- return- }- fmt.Println(string(body))+func DoGetRaw(client *http.Client, base, token, path string, params url.Values, opts ...RequestOption) []byte {+ return execute(client, token, newRequest(http.MethodGet, base, path, prepend(WithQuery(params), opts)...))}func DoPost(client *http.Client, base, token, path string, body map[string]any, opts ...RequestOption) map[string]any {- return DoPostWithHeaders(client, base, token, path, body, nil, opts...)+ r := newRequest(http.MethodPost, base, path, prepend(WithBody(body), opts)...)+ return render(r, execute(client, token, r))}// DoPostQuiet is like DoPost but does not print the response body. Callers are// responsible for rendering whatever output is appropriate (e.g. a single// field for machine-friendly piping).func DoPostQuiet(client *http.Client, base, token, path string, body map[string]any, opts ...RequestOption) map[string]any {- return DoPostQuietWithHeaders(client, base, token, path, body, nil, opts...)+ return DoPost(client, base, token, path, body, prepend(Quiet(), opts)...)}// DoPostRaw sends a POST and returns the raw response body without printing.// Exits on HTTP errors.-func DoPostRaw(client *http.Client, base, token, path string, body map[string]any) []byte {- statusCode, respBody, _ := doPostQuietWithStatus(client, base, token, path, body, nil)- exitOnAPIError(request{method: "POST", url: base + path, body: body}, statusCode, respBody)- return respBody+func DoPostRaw(client *http.Client, base, token, path string, body map[string]any, opts ...RequestOption) []byte {+ return execute(client, token, newRequest(http.MethodPost, base, path, prepend(WithBody(body), opts)...))}-// DoPostRawE sends a POST and returns an error instead of terminating the-// process. Long-running commands use it when they need to release resources-// before reporting a request failure.-func DoPostRawE(client *http.Client, base, token, path string, body map[string]any) ([]byte, error) {- r := request{method: "POST", url: base + path, body: body}- statusCode, respBody, err := doRequest(client, token, r)- if err != nil {- return nil, fmt.Errorf("request failed: %w", err)- }- if statusCode >= http.StatusBadRequest {- return nil, fmt.Errorf("%s", strings.TrimSpace(renderAPIError(r, statusCode, respBody)))- }- return respBody, nil-}--// DoGetRawE sends a GET and returns an error instead of terminating the-// process. See DoPostRawE.-func DoGetRawE(client *http.Client, base, token, path string, params url.Values) ([]byte, error) {- r := request{method: "GET", url: buildURL(base, path, params)}- statusCode, respBody, err := doRequest(client, token, r)- if err != nil {- return nil, fmt.Errorf("request failed: %w", err)- }- if statusCode >= http.StatusBadRequest {- return nil, fmt.Errorf("%s", strings.TrimSpace(renderAPIError(r, statusCode, respBody)))- }- return respBody, nil-}--func DoPostQuietWithStatus(client *http.Client, base, token, path string, body map[string]any) (int, []byte, map[string]any) {- return doPostQuietWithStatus(client, base, token, path, body, nil)-}--// DoPostQuietWithHeaders is like DoPostQuiet but allows custom headers.-func DoPostQuietWithHeaders(client *http.Client, base, token, path string, body map[string]any, headers map[string]string, opts ...RequestOption) map[string]any {- statusCode, respBody, result := doPostQuietWithStatus(client, base, token, path, body, headers, opts...)- exitOnAPIError(request{method: "POST", url: base + path, body: body, headers: headers}, statusCode, respBody)- return result-}--func doPostQuietWithStatus(client *http.Client, base, token, path string, body map[string]any, headers map[string]string, opts ...RequestOption) (int, []byte, map[string]any) {- status, respBody := mustRequest(client, token, newRequest("POST", base, base+path, body, headers, opts))-+func DoPostQuietWithStatus(client *http.Client, base, token, path string, body map[string]any, opts ...RequestOption) (int, []byte, map[string]any) {+ status, respBody := mustRequest(client, token, newRequest(http.MethodPost, base, path, prepend(WithBody(body), opts)...))var result map[string]any- if status < 400 {- // Object responses populate result; array/scalar responses leave it nil.- // Callers that need a map should branch on result == nil.- _ = json.Unmarshal(respBody, &result)+ if status < http.StatusBadRequest {+ result = decodeObject(respBody)}return status, respBody, result}-func DoPostWithHeaders(client *http.Client, base, token, path string, body map[string]any, headers map[string]string, opts ...RequestOption) map[string]any {- return doAndRender(client, token, newRequest("POST", base, base+path, body, headers, opts))-}--// DoDelete sends a DELETE request with an optional JSON body (e.g. for ?name= query params, pass nil body and handle params in path).-func DoDelete(client *http.Client, base, token, path string, params url.Values) map[string]any {- return doAndRender(client, token, request{method: "DELETE", url: buildURL(base, path, params)})-}--// DoDeleteJSON sends a DELETE request with a JSON body.-func DoDeleteJSON(client *http.Client, base, token, path string, body map[string]any) map[string]any {- return doAndRender(client, token, request{method: "DELETE", url: base + path, body: body})+func DoDelete(client *http.Client, base, token, path string, params url.Values, opts ...RequestOption) map[string]any {+ r := newRequest(http.MethodDelete, base, path, prepend(WithQuery(params), opts)...)+ return render(r, execute(client, token, r))}-// DoDeleteQuiet is like DoDelete but does not print the response body, so a-// self-rendering caller emits its own output exactly once. It keeps DoDelete's-// fatal-on-transport-error + exit-on-HTTP-error policy; a non-object body-// returns a nil map for the caller to branch on.-func DoDeleteQuiet(client *http.Client, base, token, path string, params url.Values) map[string]any {- r := request{method: "DELETE", url: buildURL(base, path, params)}- status, body := mustRequest(client, token, r)- exitOnAPIError(r, status, body)-- var result map[string]any- _ = json.Unmarshal(body, &result)- return result+func DoRawE(client *http.Client, base, token, method, path string, opts ...RequestOption) ([]byte, error) {+ return executeE(client, token, newRequest(method, base, path, opts...))}// ResolveInstanceBase fetches the named instance from the orchestrator and returnsdiff --git a/internal/cli/apiclient/client_test.go b/internal/cli/apiclient/client_test.goindex b07a8c54..1f902a3b 100644--- a/internal/cli/apiclient/client_test.go+++ b/internal/cli/apiclient/client_test.go@@ -186,7 +186,7 @@ func TestSnapTailDoesNotExitWhenSnapshotFails(t *testing.T) {defer srv.httpServer.Close()base, client := srv.httpServer.URL, srv.httpServer.Client()- apiclient.DoGetRawAndPrintCapturingVocab(client, base, "", "/snapshot?filter=interactive&format=compact", true)+ actions.Action(client, base, "", "click", "e0", actionCmd("", true))if tok := apiclient.VocabTokenFor(base, "X"); tok != "" {t.Fatalf("a failed snapshot stored a token %q; nothing should be captured from a non-2xx", tok)diff --git a/internal/cli/apiclient/transport.go b/internal/cli/apiclient/transport.goindex 6b96ca9d..5930668f 100644--- a/internal/cli/apiclient/transport.go+++ b/internal/cli/apiclient/transport.go@@ -18,9 +18,11 @@ import (type request struct {method stringurl string+ query url.Valuesbody map[string]anyheaders map[string]stringbase string+ quiet boolvocab *vocabCapture}@@ -30,15 +32,38 @@ type vocabCapture struct {type RequestOption func(*request)+// CaptureVocab persists a successful response's vocabulary token keyed by the tab+// the server resolved (the X-PinchTab-Tab-Id header), not by how the caller spelled+// --tab. When implicit (no --tab), the resolved tab also becomes the store's+// current pointer, so a later implicit action echoes that tab's token. The token+// is delivered as a response header so it survives every snapshot format,+// including the compact text the CLI defaults to.func CaptureVocab(implicit bool) RequestOption {return func(r *request) { r.vocab = &vocabCapture{implicit: implicit} }}-func newRequest(method, base, url string, body map[string]any, headers map[string]string, opts []RequestOption) request {- r := request{method: method, url: url, body: body, headers: headers, base: base}+func WithQuery(params url.Values) RequestOption {+ return func(r *request) { r.query = params }+}++func WithBody(body map[string]any) RequestOption {+ return func(r *request) { r.body = body }+}++func WithHeaders(headers map[string]string) RequestOption {+ return func(r *request) { r.headers = headers }+}++func Quiet() RequestOption {+ return func(r *request) { r.quiet = true }+}++func newRequest(method, base, path string, opts ...RequestOption) request {+ r := request{method: method, base: base}for _, opt := range opts {opt(&r)}+ r.url = buildURL(base, path, r.query)return r}diff --git a/internal/cli/apiclient/transport_test.go b/internal/cli/apiclient/transport_test.goindex 1551a7e8..0ce99b0c 100644--- a/internal/cli/apiclient/transport_test.go+++ b/internal/cli/apiclient/transport_test.go@@ -76,11 +76,11 @@ func TestAnUnbuildableRequestFailsBeforeTheWire(t *testing.T) {for name, call := range map[string]func() error{"malformed base": func() error {- _, err := DoPostRawE(srv.Client(), "http://bad host:9867", "", "/action", map[string]any{"kind": "click"})+ _, err := DoRawE(srv.Client(), "http://bad host:9867", "", http.MethodPost, "/action", WithBody(map[string]any{"kind": "click"}))return err},"unencodable body": func() error {- _, err := DoPostRawE(srv.Client(), srv.URL, "", "/geolocation", map[string]any{"latitude": math.NaN(), "longitude": 0.0})+ _, err := DoRawE(srv.Client(), srv.URL, "", http.MethodPost, "/geolocation", WithBody(map[string]any{"latitude": math.NaN(), "longitude": 0.0}))return err},} {@@ -113,7 +113,7 @@ func TestCaptureVocabStoresOnlyASuccessfulResponsesToken(t *testing.T) {}))defer srv.Close()- r := newRequest(http.MethodPost, srv.URL, srv.URL+"/find", map[string]any{"query": "x"}, nil, []RequestOption{CaptureVocab(true)})+ r := newRequest(http.MethodPost, srv.URL, "/find", WithBody(map[string]any{"query": "x"}), CaptureVocab(true))if _, _, err := doRequest(srv.Client(), "", r); err != nil {t.Fatal(err)}