Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
3 changes: 3 additions & 0 deletions packages/cli/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
dist
node_modules
*.tsbuildinfo
143 changes: 143 additions & 0 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
# `@saas/cli`

`new-test` — first-class TypeScript CLI for the new-test control
plane. Wraps `@saas/sdk` (the only transport allowed) and surfaces a
small set of read-only commands today; write commands land in Task 0101.

## Install (workspace)

This package is internal to the `new-test` monorepo and is not
published. Build the binary with:

```sh
pnpm --filter @saas/cli build
node packages/cli/dist/cli.js --help
```

## Commands

Auth (Task 0100):

```
new-test login [--api-url=URL] [--token=BEARER]
new-test logout
new-test whoami
```

Reads (Task 0100):

```
new-test org list
new-test org use <org-id>
new-test org members
new-test project list
```

Writes (Task 0101):

```
new-test org invite <email> [--role=ROLE] [--idempotency-key=KEY] [--org=ORG_ID]
new-test project create <name> [--idempotency-key=KEY]
new-test env create <project-id> <name> [--idempotency-key=KEY]
new-test api-key create <name> [--scope=SCOPE] [--idempotency-key=KEY]
new-test webhook create <url> [--event=EVENT[,EVENT2,...]] [--idempotency-key=KEY]
```

Cross-resource reads (Task 0101):

```
new-test usage summary [--metric=METRIC] [--from=ISO] [--to=ISO]
new-test billing summary
new-test audit list [--limit=N] [--cursor=CURSOR] [--category=CAT] [--all]
```

All commands accept `--output=human|json`. JSON mode emits one document
per invocation; on error, `{ "error": { "code", "message", "requestId? } }`.

### Exit codes (`src/errors.ts`)

| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | Generic / unexpected error |
| 2 | Usage error (missing/invalid args or flags) |
| 3 | Not authenticated (no stored credential) |
| 4 | API error (4xx/5xx surfaced from the SDK) |
| 5 | No active organization context |
| 6 | Idempotency replay rejected by api-edge |

### Idempotency

`--idempotency-key=KEY` is forwarded **verbatim** to the API on every
write — Stripe parity. The CLI never auto-generates a key. When you omit
the flag, no `Idempotency-Key` header is sent and the api-edge worker
falls through without replay protection (still safe for read-after-write
flows; required for retry-safe writes).

For `webhook create --event=A,B`, each child subscription gets a
deterministic suffixed key (`KEY:sub:0`, `KEY:sub:1`, …) so the whole
command remains retry-safe under partial failure.

### Active organization

Most write/cross-read commands resolve the org from the persisted
context (`new-test org use <org-id>`). Only `org invite` accepts an
explicit `--org=ORG_ID` override; the others throw "no active
organization" (exit 5) when context is unset.

### Audit pagination

`audit list` without flags returns the first page; `--all` walks every
page until the server returns `cursor: null`. In `--all --output=json`
mode the CLI emits one JSON document per page (JSON Lines) so a
downstream pipeline can stream without buffering.

## Auth

The shipped V1 is **token-paste**: `new-test login` prompts for a
Bearer token, validates it via `client.organizations.list()`, and stores
it. Switching to a device-flow grant once api-edge ships
`/v1/auth/device/{start,poll}` is a one-line dispatch in
`src/auth/login.ts`.

Token storage:
- `KeychainTokenStore` (preferred): macOS Keychain / Windows Credential
Vault / Secret Service via `keytar` (lazy import; in
`optionalDependencies`).
- `FileTokenStore` fallback: `~/.config/new-test/credentials.json`,
mode **0600**, parent directory mode **0700**.

Active organization context lives at
`~/.config/new-test/config.json` (mode 0644, not a secret). Override
both via `NEW_TEST_CONFIG_DIR` (used by tests).

## Output stability

JSON output is deterministic given a deterministic SDK response. The CLI
adds **no** timestamps to JSON envelopes. `formatOutput()` is the only
emission path and is fully covered by tests.

## Hazards / constraints

- Zero hazards under `packages/cli/**`. The hazard set is the same as
the rest of the monorepo: disabled-eslint comments, ts-ignore,
ts-expect-error, and force-cast escape hatches via `as` chains.
- The package index (`src/index.ts`) is loadable in non-Node hosts; the
keychain adapter dynamic-imports `keytar` only when needed.
- Idempotency-Key is **caller-owned**. Task 0101 wires `--idempotency-key`
through to the SDK; the CLI never auto-mints a key.

## Testing

```sh
pnpm --filter @saas/cli typecheck
pnpm --filter @saas/cli lint
pnpm --filter @saas/cli test
pnpm --filter @saas/cli build
```

## Related

- `specs/components/13-cli-and-sdk.md` — surface contract.
- `packages/sdk` — the only allowed transport.
- Task 0101 — write commands + remaining read-only fan-out.
29 changes: 29 additions & 0 deletions packages/cli/component.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
apiVersion: sourceplane.io/v1
kind: Component
metadata:
name: cli
description: First-class TypeScript CLI for the new-test control plane API
spec:
type: turbo-package
lifecycle: production
owner: platform
domain: starter-cli
subscribe:
environments:
- name: dev
profile: quick-check
- name: stage
profile: quick-check
- name: prod
profile: quick-check
parameters:
nodeVersion: "20"
pnpmVersion: "10.12.1"
buildCommand: pnpm exec turbo run build --filter=./
typecheckCommand: pnpm exec turbo run typecheck --filter=./
preBuildCommand: pnpm exec turbo run test --filter=./
labels:
team: platform
layer: shared
surface: cli
# ci: trigger full-component verification (orun v2.12.0 upgrade — PR #183)
9 changes: 9 additions & 0 deletions packages/cli/docs/architecture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# cli — architecture

A `turbo-package` component: TypeScript built by the turbo pipeline
from `packages/cli`.

## Boundaries

A library, not a runtime: it holds no credentials, opens no connections,
and is consumed at build time by the components that depend on it.
13 changes: 13 additions & 0 deletions packages/cli/docs/overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# cli

First-class TypeScript CLI for the new-test control plane API

A workspace package built by the turbo pipeline. It deploys nothing on its own — its lane type-checks, lints, tests, and builds it for the components that depend on it.

## Depends on

- (none)

## Depended on by

- (none)
26 changes: 26 additions & 0 deletions packages/cli/docs/runbook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# cli — runbook

## How it deploys

Merges to `main` converge automatically: CI plans changed components
(`orun plan --changed`) and runs this component's lane via
`orun run --remote-state` with credential-free OIDC auth. The convergence
run is the deployment; the DAG orders this component after everything it
depends on. Failed lanes resume with `gh run rerun --failed`.

## Rollback

Revert the offending commit on `main`; the next convergence applies the
previous desired state. There is no out-of-band mutation to undo — the
repo is the source of truth.

## Verify

The lane itself is the gate: typecheck, lint, test, build. This package
has no deployed surface.

## Common failures

- **A dependent's lane fails to build after a change here**: the change
was source-compatible but not type-compatible — run
`pnpm typecheck` across the workspace before landing.
14 changes: 14 additions & 0 deletions packages/cli/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import baseConfig from "../../tooling/eslint/index.js";

export default [
...baseConfig,
{
files: ["src/**/*.ts"],
rules: {
// CLI prints to stdout/stderr — `console.log` is the legitimate output
// channel here. The base config warns on `console.log`; turn it off
// for this package only.
"no-console": "off",
},
},
];
33 changes: 33 additions & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "@saas/cli",
"version": "0.0.0",
"private": true,
"type": "module",
"bin": {
"new-test": "./dist/cli.js"
},
"exports": {
".": "./src/index.ts"
},
"scripts": {
"build": "tsc --project tsconfig.build.json && node scripts/bundle.mjs",
"typecheck": "tsc --noEmit",
"lint": "eslint src",
"test": "vitest run"
},
"devDependencies": {
"@saas/eslint-config": "workspace:*",
"@saas/tsconfig": "workspace:*",
"@types/node": "^20.14.0",
"esbuild": "^0.25.4",
"typescript": "^5.8.3",
"vitest": "^2.1.9"
},
"dependencies": {
"@saas/sdk": "workspace:*",
"@saas/webhook-verifier": "workspace:*"
},
"optionalDependencies": {
"keytar": "^7.9.0"
}
}
40 changes: 40 additions & 0 deletions packages/cli/scripts/bundle.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#!/usr/bin/env node
// Bundles the CLI directly from TypeScript sources. tsc is reserved for
// type-checking + .d.ts emit; the runtime artifact is produced by esbuild
// so the binary can be executed by Node without resolving sibling
// workspaces (`@saas/sdk` exports raw `.ts`, which Node ESM cannot load
// without a bundler).
//
// Inputs : src/cli.ts
// Output : dist/cli.js (executable, with shebang)
//
// `keytar` is marked external so it remains an optional dependency
// dynamically imported by `token-store/keychain.ts`.

import { build } from "esbuild";
import { chmodSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";

const here = dirname(fileURLToPath(import.meta.url));
const pkgRoot = resolve(here, "..");
const entry = resolve(pkgRoot, "src/cli.ts");
const out = resolve(pkgRoot, "dist/cli.js");

await build({
entryPoints: [entry],
bundle: true,
platform: "node",
format: "esm",
target: "node20",
outfile: out,
external: ["keytar"],
// Source already has a shebang; do not re-emit one via banner.
legalComments: "none",
minify: false,
sourcemap: false,
logLevel: "warning",
});

chmodSync(out, 0o755);

Loading
Loading