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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,9 @@ seam devices list > devices.json
seam devices list | jq '.devices[].device_id'
```

The CLI waits for actions to finish by default. To return immediately, pass
`--no-wait-for-action-attempt`.

### Pagination

Every command that paginates accepts `--page-cursor` to select a page of
Expand Down
61 changes: 8 additions & 53 deletions TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,59 +103,14 @@ behavior. The CLI is blueprint-driven and has one chokepoint: preparing a
`SeamHttpRequest` for an endpoint path. The port mirrors that — prepare a
request, inspect it, send it:

```ts
// src/lib/http/api.ts
export interface SeamApiRequest {
readonly url: URL
readonly method: string
readonly body: unknown
fetchResponse: () => Promise<unknown>
}

export interface SeamApi {
createRequest: (options: ApiRequestOptions) => SeamApiRequest
}

export class HttpSeamApi implements SeamApi {
constructor(private readonly seam: SeamHttp) {} // the only place SeamHttp appears

createRequest = ({ path, params, responseKey }: ApiRequestOptions) =>
new SeamHttpRequest(this.seam, {
pathname: path,
method: 'POST',
body: params,
responseKey: responseKey ?? undefined,
})
}
```

The real request object is the SDK's own `SeamHttpRequest`, so the URL is
inspectable before sending and an error status rejects with the SDK's typed
`SeamHttpApiError`. The fake is the in-process mirror of the e2e server — a
routes table plus a capture — and it rejects with those same SDK error
classes, never an imitation:

```ts
// src/lib/http/memory-seam-api.ts
export class MemorySeamApi implements SeamApi {
readonly requests: Array<{ path: string; params: Record<string, unknown> }> =
[]

constructor(private readonly routes: Record<string, MemorySeamApiResponse>) {}

createRequest = ({ path, params }: ApiRequestOptions): SeamApiRequest => ({
url: new URL(`https://memory.seam.example${path}`),
method: 'POST',
body: params,
fetchResponse: async () => {
this.requests.push({ path, params })
const route = this.routes[path]
if (route == null || route.status >= 400) throw toSeamHttpError(route)
return route.data
},
})
}
```
See [`SeamApi` and `HttpSeamApi`](src/lib/http/api.ts) for the authoritative
request contract and SDK integration. The adapter keeps the URL inspectable
before sending and uses the SDK resolver for action-attempt waiting.

[`MemorySeamApi`](src/lib/http/memory-seam-api.ts) runs that same adapter over
an in-memory wire, with a routes table and request capture. SDK request caching,
resolution, and typed errors stay real without an HTTP server or a separate
polling implementation.

This keeps transport separate from presentation: the error-status → exit-code
behavior is a classical test with zero HTTP:
Expand Down
82 changes: 82 additions & 0 deletions src/lib/args/parse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ import type { ParsedArgs } from 'minimist'
import { expect, test } from 'vitest'

import {
getActionAttemptWaitOptions,
getInteractivity,
parseCliArgs,
toArgName,
toArgParams,
toGivenArgName,
toParameterName,
} from './parse.js'
Expand Down Expand Up @@ -73,6 +75,86 @@ test('parseCliArgs: reads a page cursor exactly as given', () => {
).toBe('0755')
})

test.each([
[[], undefined],
[['--wait-for-action-attempt'], true],
[['--no-wait-for-action-attempt'], false],
[['--wait-for-action-attempt', '--no-wait-for-action-attempt'], false],
[['--no-wait-for-action-attempt', '--wait-for-action-attempt'], true],
])(
'parseCliArgs: preserves absent/explicit wait and last-wins order %j',
(flags, expected) => {
// Both the first parse and the endpoint-aware parse use the same CLI controls.
for (const options of [{}, { stringKeys: ['device-id'] }]) {
const args = parseCliArgs(
[...flags, 'locks', 'unlock-door', '--device-id', 'device1'],
options,
)
expect(args._).toEqual(['locks', 'unlock-door'])
expect(args['wait-for-action-attempt']).toBe(expected)
expect(toArgParams(args)).toEqual({ device_id: 'device1' })
expect(getActionAttemptWaitOptions(args)).toEqual(
expected === undefined ? {} : { waitForActionAttempt: expected },
)
}
},
)

test('getActionAttemptWaitOptions: converts seconds once, retaining SDK defaults when absent', () => {
expect(getActionAttemptWaitOptions(parseCliArgs([]))).toEqual({})
expect(
getActionAttemptWaitOptions(
parseCliArgs([
'--action-attempt-timeout',
'2.5',
'--action-attempt-polling-interval',
'0.05',
]),
),
).toEqual({ waitForActionAttempt: { timeout: 2500, pollingInterval: 50 } })
expect(
getActionAttemptWaitOptions(
parseCliArgs([
'--action-attempt-timeout',
'1',
'--action-attempt-timeout',
'3',
]),
),
).toEqual({ waitForActionAttempt: { timeout: 3000 } })
})

test.each(['action-attempt-timeout', 'action-attempt-polling-interval'])(
'getActionAttemptWaitOptions: rejects invalid --%s even with opt-out',
(flag) => {
for (const value of ['', '0', '-1', 'NaN', 'Infinity', 'abc', '1e308']) {
expect(() =>
getActionAttemptWaitOptions(
parseCliArgs(['--no-wait-for-action-attempt', `--${flag}=${value}`]),
),
).toThrow(`--${flag} expects a finite positive number of seconds`)
}
expect(() =>
getActionAttemptWaitOptions(parseCliArgs([`--${flag}`])),
).toThrow()
},
)

test('getActionAttemptWaitOptions: opt-out takes precedence over valid timing controls', () => {
const args = parseCliArgs([
'--wait-for-action-attempt',
'--action-attempt-timeout',
'4',
'--action-attempt-polling-interval',
'.1',
'--no-wait-for-action-attempt',
])
expect(getActionAttemptWaitOptions(args)).toEqual({
waitForActionAttempt: false,
})
expect(toArgParams(args)).toEqual({})
})

test('toArgName: renders a parameter as its argument', () => {
expect(toArgName('device_id')).toBe('--device-id')
expect(toArgName('code')).toBe('--code')
Expand Down
63 changes: 60 additions & 3 deletions src/lib/args/parse.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { SeamHttpRequestOptions } from '@seamapi/http'
import parseArgs, { type ParsedArgs } from 'minimist'

import { UsageError } from 'lib/errors.js'
import type { AuthOverrides } from 'lib/overrides.js'

/**
Expand Down Expand Up @@ -31,6 +33,9 @@ export const interactivityFlags: string[] = [
*/
export const cliFlags: string[] = [
...interactivityFlags,
'wait_for_action_attempt',
'action_attempt_timeout',
'action_attempt_polling_interval',
'endpoint',
'h',
'help',
Expand All @@ -57,13 +62,15 @@ export interface ParseCliArgsOptions {
export const parseCliArgs = (
argv: string[],
{ stringKeys = [], booleanKeys = [] }: ParseCliArgsOptions = {},
): ParsedArgs =>
parseArgs(argv, {
): ParsedArgs => {
const args = parseArgs(argv, {
// A page cursor and a code are opaque even before the endpoint's own
// parameter types are known, so always keep them exactly as given. The
// overrides are read as given for the same reason: a URL or an id is
// never a number, however it happens to be spelled.
string: [
'action-attempt-timeout',
'action-attempt-polling-interval',
'code',
'endpoint',
'page-cursor',
Expand All @@ -72,11 +79,61 @@ export const parseCliArgs = (
'workspace_id',
...stringKeys,
],
boolean: ['non-interactive', 'interactive', 'json', ...booleanKeys],
boolean: [
'non-interactive',
'interactive',
'json',
'wait-for-action-attempt',
...booleanKeys,
],
// Do not confuse minimist's implicit false with an explicit opt-out.
default: { 'wait-for-action-attempt': null },
// Deliberately not aliased to -n, which is reserved for a future
// --dry-run flag.
alias: { 'non-interactive': 'y', interactive: 'i' },
})
if (args['wait-for-action-attempt'] === null) {
delete args['wait-for-action-attempt']
}
return args
}

/** Validate seconds at the CLI boundary and convert to SDK milliseconds once. */
export const getActionAttemptWaitOptions = (
args: ParsedArgs,
): Pick<SeamHttpRequestOptions, 'waitForActionAttempt'> => {
const timeout = readDuration(
args['action-attempt-timeout'],
'action-attempt-timeout',
)
const pollingInterval = readDuration(
args['action-attempt-polling-interval'],
'action-attempt-polling-interval',
)
const wait = args['wait-for-action-attempt'] as boolean | undefined
if (wait === false) return { waitForActionAttempt: false }
if (timeout === undefined && pollingInterval === undefined) {
return wait === undefined ? {} : { waitForActionAttempt: wait }
}
return {
waitForActionAttempt: {
...(timeout === undefined ? {} : { timeout }),
...(pollingInterval === undefined ? {} : { pollingInterval }),
},
}
}

const readDuration = (value: unknown, flag: string): number | undefined => {
if (value === undefined) return undefined
const seconds = Number(Array.isArray(value) ? value.at(-1) : value)
const milliseconds = seconds * 1_000
if (!Number.isFinite(milliseconds) || milliseconds <= 0) {
throw new UsageError(
`--${flag} expects a finite positive number of seconds`,
)
}
return milliseconds
}

/**
* The request params among the parsed arguments: every key normalized to
Expand Down
18 changes: 15 additions & 3 deletions src/lib/commands/api-command.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { isDeepStrictEqual as isEqual } from 'node:util'

import { coerceArgParams } from 'lib/args/coerce.js'
import { parseCliArgs, toArgName, toArgParams } from 'lib/args/parse.js'
import {
getActionAttemptWaitOptions,
parseCliArgs,
toArgName,
toArgParams,
} from 'lib/args/parse.js'
import { assertRequiredParams } from 'lib/args/validate.js'
import {
getCommandBlueprintDef,
Expand Down Expand Up @@ -36,9 +41,11 @@ export const executeApiCommand = async (
const stringKeys = parameters
.filter(({ format }) => format !== 'boolean' && format !== 'number')
.flatMap(({ name }) => [name, name.replace(/_/g, '-')])
const args = parseCliArgs(invocation.argv, { stringKeys })
const waitOptions = getActionAttemptWaitOptions(args)
const { params: argParams, issues } = coerceArgParams(
parameters,
toArgParams(parseCliArgs(invocation.argv, { stringKeys })),
toArgParams(args),
)

if (issues.length > 0) {
Expand Down Expand Up @@ -83,7 +90,12 @@ export const executeApiCommand = async (

const api = await ctx.api()
const body = await requestSeamApi(
{ path: apiPath, params, responseKey: getResponseKey(path, ctx) },
{
path: apiPath,
params,
responseKey: getResponseKey(path, ctx),
...waitOptions,
},
{ api, output: ctx.output },
)

Expand Down
36 changes: 36 additions & 0 deletions src/lib/commands/spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,42 @@ export interface CommandSpec {
}

export const globalFlags: CommandFlag[] = [
{
long: 'wait-for-action-attempt',
short: null,
description:
'Wait for action attempts to succeed or fail (default in all modes).',
values: [],
takesValue: false,
isRequired: false,
},
{
long: 'no-wait-for-action-attempt',
short: null,
description:
'Return the initial action attempt without waiting or polling.',
values: [],
takesValue: false,
isRequired: false,
},
{
long: 'action-attempt-timeout',
short: null,
description:
'Action-attempt wait timeout in seconds (positive number, default 10).',
values: [],
takesValue: true,
isRequired: false,
},
{
long: 'action-attempt-polling-interval',
short: null,
description:
'Action-attempt polling interval in seconds (positive number, default 1; fractions allowed).',
values: [],
takesValue: true,
isRequired: false,
},
{
long: 'endpoint',
short: null,
Expand Down
Loading
Loading