Repository navigation
Expand file tree
/
Copy pathexecute.ts
More file actions
648 lines (618 loc) · 27.2 KB
/
Copy pathexecute.ts
File metadata and controls
648 lines (618 loc) · 27.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
import { getErrorMessage } from '@sim/utils/errors'
import type { Command } from 'commander'
import { writeStderr } from '#sim-cli/output/io'
import { styles } from '#sim-cli/output/presentation'
import {
assertWorkspaceOperationOutcome,
readWorkspaceOperation,
waitWorkspaceOperation,
workspaceWaitTimeout,
} from '../commands/protocol/workspace-operation-wait'
import type { CommandSpec } from '../contract/types'
import type { GetWorkspaceOperationResponse, V2OperationName } from '../generated/v2-api'
import { assertCursorAdvances, pageProgress, SimApiError, type V2Page } from '../http/client'
import { safeOneLine } from '../output/render'
import { connect } from './called-operations'
import { camel } from './derive'
import { DEFAULT_PAGE_SIZE, defaultListLimit } from './options'
import { warnRenamedFlag } from './renamed'
import {
buildRequest,
cursorSlot,
flagNameFor,
isProfileWorkspacePath,
otherSpellings,
PROFILE_INJECTED_FIELD,
trailingListField,
} from './request'
import { foldPageEnvelope, renderPage, renderResult } from './result'
import type { OperationSpec } from './types'
const WORKSPACE_OPERATION_KINDS: Readonly<
Partial<Record<V2OperationName, GetWorkspaceOperationResponse['data']['kind']>>
> = {
importWorkflow: 'workflow_import',
forkWorkspace: 'workspace_fork',
pushWorkspace: 'workspace_push',
pullWorkspace: 'workspace_pull',
}
/**
* Operations that report the outcome of the work they did in band.
*
* The execute route answers `200` with `status: 'failed'` and a structured
* `error` rather than an HTTP error, so a failed run left the terminal
* indistinguishable from a successful one: `sim workflows run` printed the
* failure and still exited `0`, and a CI step gated on it stayed green.
* `--follow` and `runs wait` already fail the process on the same outcome; this
* is the plain run path catching up with them.
*
* Named per operation on purpose. A `status` field is common across unrelated
* v2 payloads — job records, import receipts, connector syncs — and taking any
* `status: 'failed'` as the command's own outcome would start failing commands
* that merely *report* somebody else's failed record.
*/
const RUN_OUTCOME_OPERATIONS: Readonly<
Partial<Record<V2OperationName, Readonly<Record<string, string>>>>
> = {
/**
* Terminal run statuses that are not a success, and how each is explained.
*
* `paused` is deliberately absent: a run held at a human-in-the-loop pause has
* not failed and can still be resumed, and `--follow` reports it the same way
* it reports a success.
*/
executeWorkflow: {
failed: 'The workflow run failed.',
cancelled: 'The workflow run was cancelled.',
},
/**
* A tool that ran and refused answers `200` for the same reason a failed run
* does — the API call worked, the third party did not — so the exit code is
* the only thing left to carry the outcome. The fallback is per operation
* because "the workflow run failed" is not what happened here; in practice
* the tool's own error message wins, and this only speaks when it is absent.
*/
executeTool: {
failed: 'The tool call failed.',
},
}
/** The one-line explanation of an in-band run failure, or `null` if there is none. */
export function runFailureMessage(operation: V2OperationName, payload: unknown): string | null {
const failureMessages = RUN_OUTCOME_OPERATIONS[operation]
if (!failureMessages) return null
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null
const { status, error } = payload as { status?: unknown; error?: unknown }
if (typeof status !== 'string') return null
const fallback = failureMessages[status]
if (!fallback) return null
const reported = (error as { message?: unknown } | null | undefined)?.message
return safeOneLine(typeof reported === 'string' && reported ? reported : fallback)
}
/**
* Bulk operations that answer `200` even when they changed nothing.
*
* These endpoints are deliberately best-effort: they attempt every item, then
* report per-item outcomes in the payload. That is right for a partial
* success — some items really were deleted or moved — but a call that touched
* nothing at all is a failure the caller has to notice, and exiting `0` left
* `sim tables batch-delete --table-ids '["tbl_typo"]'` indistinguishable from a
* real deletion in a CI step.
*
* Most checks fail only a total miss. A partial success still exits `0`: the payload names
* every item that did not make it, and failing the process there would break
* every caller that legitimately sweeps a list containing already-gone items.
*/
/**
* Reads a bulk payload, and the request that produced it, for a total miss.
*
* The request is needed because not every bulk response reports the items it
* failed on: `bulkDeleteFiles` answers with a deleted count and nothing else,
* so the only place the number of items asked for exists is the body that was
* sent.
*/
type BulkOutcomeCheck = (
payload: Record<string, unknown>,
body: Record<string, unknown> | undefined
) => string | null
export const BULK_OUTCOME_CHECKS: Readonly<Partial<Record<V2OperationName, BulkOutcomeCheck>>> = {
/** Invitation batches explicitly promise success only when every recipient succeeds. */
createWorkspaceInvitations: (payload) => {
const failed = lengthOf(payload.failed)
if (failed === 0 && payload.success !== false) return null
return `${failed > 0 ? `Invitation batch failed for ${failed} ${failed === 1 ? 'recipient' : 'recipients'}.` : 'Invitation batch failed.'} Successful results remain committed; inspect failed recipients before retrying.`
},
bulkDeleteFiles: (payload, body) => {
if (countOf((payload.deletedItems as { files?: unknown } | undefined)?.files) > 0) return null
const requested = lengthOf(body?.fileIds)
if (requested === 0) return null
return `Deleted nothing: none of the ${requested} requested ${requested === 1 ? 'file was' : 'files were'} deleted.`
},
archiveProjectFileItems: (payload, body) => {
const items = payload.deletedItems as { files?: unknown; folders?: unknown } | undefined
if (countOf(items?.files) + countOf(items?.folders) > 0) return null
const requested = lengthOf(body?.fileIds) + lengthOf(body?.folderIds)
if (requested === 0) return null
return `Archived nothing: none of the ${requested} requested ${requested === 1 ? 'item was' : 'items were'} archived.`
},
/**
* `added` empty with `failed` populated is a call that indexed nothing. An
* empty request — no file resolved to a reference at all — is not a failure,
* so it is left alone.
*/
addWorkspaceFilesToKnowledgeBase: (payload) => {
if (lengthOf(payload.added) > 0) return null
const failed = lengthOf(payload.failed)
if (failed === 0) return null
return `Indexed nothing: none of the ${failed} requested ${failed === 1 ? 'file was' : 'files were'} added.`
},
bulkDeleteTables: (payload) => {
const items = payload.deletedItems as { tables?: unknown; folders?: unknown } | undefined
const deleted = countOf(items?.tables) + countOf(items?.folders)
if (deleted > 0) return null
const missed = lengthOf(payload.notFound) + lengthOf(payload.failed)
if (missed === 0) return null
return `Deleted nothing: ${missed} of ${missed} ${missed === 1 ? 'item was' : 'items were'} not found or could not be deleted.`
},
/**
* The route answers `200` with `processed: 0` when no listed id matched a
* chunk in the document, so a sweep over a stale id list read as a success.
* `errors[0]` names the ids it could not find, which is more use than
* anything this could restate. A partial hit still succeeds, and a request
* that listed no chunk at all has nothing to have missed.
*/
bulkUpdateKnowledgeChunks: (payload, body) => {
if (countOf(payload.processed) > 0) return null
const requested = lengthOf(body?.chunkIds)
if (requested === 0) return null
const reported = (payload.errors as unknown[] | undefined)?.[0]
return typeof reported === 'string' && reported
? safeOneLine(reported)
: `Updated nothing: none of the ${requested} requested ${requested === 1 ? 'chunk' : 'chunks'} matched.`
},
/**
* Only the id-list selection is checked. The filter branch answers with a
* deleted count alone — no `requestedCount` — so the guard below self-excludes
* on it, which is right: a filter matching nothing deleted nothing because
* there was nothing to delete, and failing there would break the second run of
* an otherwise idempotent sweep.
*/
deleteTableRows: (payload) => {
if (countOf(payload.deletedCount) > 0) return null
const requested = countOf(payload.requestedCount)
if (requested === 0) return null
return `Deleted nothing: none of the ${requested} requested ${requested === 1 ? 'row was' : 'rows were'} deleted.`
},
moveTables: (payload) => {
if (lengthOf(payload.moved) > 0) return null
const missed = lengthOf(payload.notFound) + lengthOf(payload.failed)
if (missed === 0) return null
return `Moved nothing: ${missed} of ${missed} ${missed === 1 ? 'item was' : 'items were'} not found or could not be moved.`
},
moveWorkflows: (payload) => {
if (lengthOf(payload.moved) > 0) return null
const failed = lengthOf(payload.failed)
if (failed === 0) return null
return `Moved nothing: ${failed} of ${failed} ${failed === 1 ? 'workflow' : 'workflows'} could not be moved.`
},
}
/** A numeric count field, or `0` when the payload omits it. */
function countOf(value: unknown): number {
return typeof value === 'number' && Number.isFinite(value) ? value : 0
}
/** The length of an array field, or `0` when the payload omits it. */
function lengthOf(value: unknown): number {
return Array.isArray(value) ? value.length : 0
}
/**
* One line of context a successful result deserves, on stderr, in every format.
*
* `workflows chat publish` defaults `authType` to `public`, so a caller who
* never typed `--auth-type` has just put a chat on the open internet, and the
* result — `authType: public` among a dozen other fields of the record — does
* not make that leap out. The note is printed whether the default or an
* explicit `--auth-type public` chose it: the exposure is the same either way.
* stderr, so `sim workflows chat publish … --output json | jq` still reads
* exactly the record; every format gets it because a JSON consumer is the one
* least likely to look at the record.
*
* Judged on the response first and the request second: the server states what
* it stored, and a body that omitted the field landed on the server's default.
*/
const RESULT_NOTES: Readonly<
Partial<
Record<
V2OperationName,
(payload: Record<string, unknown>, body: Record<string, unknown> | undefined) => string | null
>
>
> = {
replaceWorkflowChatDeployment: (payload, body) => {
const authType = payload.authType ?? body?.authType ?? 'public'
return authType === 'public'
? 'note: auth type is public — anyone with the link can chat; pass --auth-type password|email to restrict it.'
: null
},
}
/** Writes the operation's result note to stderr, when it has one and the result calls for it. */
function writeResultNote(
operation: V2OperationName,
payload: unknown,
body: Record<string, unknown> | undefined
): void {
const note = RESULT_NOTES[operation]
if (!note) return
const record =
payload && typeof payload === 'object' && !Array.isArray(payload)
? (payload as Record<string, unknown>)
: {}
const message = note(record, body)
if (message) writeStderr(styles().dim(`${message}\n`))
}
/** The one-line explanation of a bulk call that changed nothing, or `null`. */
function bulkFailureMessage(
operation: V2OperationName,
payload: unknown,
body: Record<string, unknown> | undefined
): string | null {
const check = BULK_OUTCOME_CHECKS[operation]
if (!check) return null
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null
return check(payload as Record<string, unknown>, body)
}
/**
* Fields that cap a filtered mutation, beside the id list that supersedes them.
*
* `tables rows batch-delete --row a --row b --limit 1` deleted both rows: the
* route drops `limit` outright on the ids branch, so the cap was accepted,
* ignored, and never mentioned again. The refusal is client-side because that
* is where it costs nothing — every already-installed CLI sends `limit: 100`
* alongside `--row`, so a server that started rejecting the pair would break
* them all.
*/
const EXCLUSIVE_CAP_FIELDS: Readonly<
Partial<Record<V2OperationName, { cap: string; ids: string }>>
> = {
deleteTableRows: { cap: 'limit', ids: 'rowIds' },
}
/**
* The pager's `--limit`, where `0` means "no ceiling".
*
* Read whole, not up to the first character that stops looking numeric.
* `parseInt` truncated before the guard could see what was typed, so
* `--limit 3.9` quietly fetched 3, `--limit 1e3` fetched 1, and `--limit -0.5`
* parsed as `-0` — which is not less than zero, so it slipped the guard and
* then read as the `0` that means everything. `Number` keeps the value intact
* so each of those is refused instead of reinterpreted, and it reads `0x10` and
* `1e3` as the caller wrote them.
*
* The empty string is refused explicitly because `Number('')` is `0`: without
* this, `--limit ''` would go from today's error to an unbounded walk of a
* shared workspace.
*/
function readPagedLimit(raw: unknown, operation: V2OperationName): number {
const text = String(raw ?? defaultListLimit(operation)).trim()
const value = text === '' ? Number.NaN : Number(text)
if (!Number.isInteger(value) || value < 0) {
throw new SimApiError('--limit must be a whole number of 0 or more (0 for everything)', 0)
}
return value
}
/** Refuses a row cap typed alongside the explicit id list that supersedes it. */
function assertCapIsUsable(operation: V2OperationName, flags: Record<string, unknown>): void {
const exclusive = EXCLUSIVE_CAP_FIELDS[operation]
if (!exclusive) return
const cap = flagNameFor(operation, exclusive.cap)
const ids = flagNameFor(operation, exclusive.ids)
if (flags[camel(cap)] === undefined || flags[camel(ids)] === undefined) return
throw new SimApiError(
`--${cap} caps a --filter match and does nothing to an explicit --${ids} list; pass one, not both`,
0
)
}
/**
* Operations that select their targets through exactly one of two flags.
*
* `tables rows batch-delete` left the choice to the route, whose refusal —
* `Provide either filter or rowIds, but not both` — describes the wrong mistake
* when neither was typed, and describes it half in wire names. Its sibling
* `tables rows batch-update` already refuses locally, because its `filter` is
* `required` in the contract; stating this one here puts the requirement in the
* same place for both.
*/
const REQUIRED_SELECTORS: Readonly<
Partial<
Record<V2OperationName, { readonly fields: readonly [string, string]; readonly noun: string }>
>
> = {
deleteTableRows: { fields: ['filter', 'rowIds'], noun: 'rows to delete' },
}
/** Refuses a selection that names neither of the two ways to make it, or both. */
function assertSelectorIsUsable(operation: V2OperationName, flags: Record<string, unknown>): void {
const selector = REQUIRED_SELECTORS[operation]
if (!selector) return
const [first, second] = selector.fields.map((field) => flagNameFor(operation, field))
const given = [first, second].filter((name) => flags[camel(name)] !== undefined)
if (given.length === 1) return
throw new SimApiError(
given.length === 0
? `--${first} or --${second} is required to choose the ${selector.noun}`
: `--${first} and --${second} choose the ${selector.noun} two different ways; pass one, not both`,
0
)
}
/**
* Moves a value supplied under a flag's former name or hidden alias onto its
* documented one.
*
* Done here rather than in `buildRequest` because this is where the parsed
* flags are assembled and still keyed by what the caller typed; by the time the
* request is built, only the current spelling has meaning.
*
* Supplying two spellings is refused rather than resolved. They are the same
* field, so a caller who sets both has two different values in mind and no
* reading of "the documented one wins" is more likely to be the intended one.
*/
function foldOtherSpellings(
operation: V2OperationName,
commandSpec: CommandSpec,
flags: Record<string, unknown>
): void {
for (const [field, flag] of Object.entries(commandSpec.flags ?? {})) {
const current = flagNameFor(operation, field)
for (const { name, renamed } of otherSpellings(flag)) {
const supplied = flags[camel(name)]
if (supplied === undefined) continue
if (flags[camel(current)] !== undefined) {
throw new SimApiError(
`--${name} is ${renamed ? 'the former name' : 'another spelling'} of --${current}; pass one, not both`,
0
)
}
if (renamed) warnRenamedFlag(name, current)
flags[camel(current)] = supplied
}
}
}
/** Executes a parsed generated command, including cursor pagination. */
export async function executeOperation(
operation: V2OperationName,
commandSpec: CommandSpec,
operationSpec: OperationSpec,
invocation: unknown[]
): Promise<void> {
const host = invocation[invocation.length - 1] as Command
const inheritedFlags = host.optsWithGlobals() as Record<string, unknown>
const flags: Record<string, unknown> = {
...(inheritedFlags.workspace === undefined ? {} : { workspace: inheritedFlags.workspace }),
...(inheritedFlags.allWorkspaces === undefined
? {}
: { allWorkspaces: inheritedFlags.allWorkspaces }),
...(invocation[invocation.length - 2] as Record<string, unknown>),
}
const pathPositionalCount = operationSpec.pathParams.filter(
(param) => !commandSpec.pathFlags?.[param] && !isProfileWorkspacePath(commandSpec, param)
).length
const positional = invocation.slice(0, pathPositionalCount) as string[]
const requestFlags: Record<string, unknown> = { ...flags }
for (const [index, field] of (commandSpec.positionals ?? []).entries()) {
requestFlags[camel(flagNameFor(operation, field))] = invocation[pathPositionalCount + index]
}
const trailing = trailingListField(commandSpec)
const trailingValues = trailing
? invocation[pathPositionalCount + (commandSpec.positionals?.length ?? 0)]
: undefined
if (trailing && Array.isArray(trailingValues) && trailingValues.length > 0) {
const name = flagNameFor(operation, trailing)
if (requestFlags[camel(name)] !== undefined) {
throw new SimApiError(`Pass the ${name} as arguments or with --${name}, not both`, 0)
}
requestFlags[camel(name)] = trailingValues
}
foldOtherSpellings(operation, commandSpec, requestFlags)
assertCapIsUsable(operation, requestFlags)
assertSelectorIsUsable(operation, requestFlags)
/**
* A dry run writes nothing, so it never needs the destructive confirmation.
*
* The gate exists to stop a caller discarding work by accident; `--dry-run`
* is how a caller checks what a command WOULD do, and demanding `--yes` to
* preview a change teaches people to pass `--yes` reflexively — which is
* exactly the habit the gate depends on not forming. `dryRun` is a v2-wide
* contract flag meaning "persist nothing", so this holds for every command
* that accepts it rather than being a per-command exemption.
*/
if (commandSpec.confirm && !requestFlags.yes && requestFlags.dryRun !== true) {
throw new SimApiError(`${commandSpec.confirm} Re-run with --yes to confirm.`, 0)
}
if (commandSpec.allWorkspaces && requestFlags.allWorkspaces && requestFlags.workspace) {
throw new SimApiError('--all-workspaces cannot be combined with --workspace', 0)
}
const { client, profile } = connect(host)
const hasWorkspaceField = Boolean(
(operationSpec.query && PROFILE_INJECTED_FIELD in operationSpec.query) ||
(operationSpec.body && PROFILE_INJECTED_FIELD in operationSpec.body)
)
const omitsWorkspace = commandSpec.allWorkspaces && requestFlags.allWorkspaces === true
/**
* A workspace carried in the path is resolved exactly like one carried in a
* field. `workspaces get` and `workspaces members` take theirs as a path
* parameter, so they skipped `requireWorkspace` and fell into `buildRequest`'s
* own fallback: a second wording for the same precondition, and — because
* `requireWorkspace` checks the key first — advice to set a workspace on an
* install whose actual first step is logging in.
*/
const needsWorkspace =
(hasWorkspaceField || commandSpec.profileWorkspacePath === true) && !omitsWorkspace
const paging = cursorSlot(operationSpec)
/**
* Checked before the request is built, because `buildRequest` also validates
* `limit` and would otherwise answer a paginated `--limit 1.5` with the
* generic integer refusal — losing the `0 for everything` this pager depends
* on the caller knowing.
*/
const pagedLimit = paging ? readPagedLimit(requestFlags.limit, operation) : 0
const requestWorkspaceId = needsWorkspace ? client.requireWorkspace() : profile.workspaceId
const request = await buildRequest(operation, positional, requestFlags, requestWorkspaceId)
if (commandSpec.workspaceOperation) {
if (!WORKSPACE_OPERATION_KINDS[operation])
throw new SimApiError('This command has no workspace operation identity configured', 0)
workspaceWaitTimeout(requestFlags.waitTimeout)
if (requestFlags.waitTimeout !== undefined && requestFlags.wait !== true)
throw new SimApiError('--wait-timeout requires --wait', 0)
if (
requestFlags.wait === true &&
(!request.body?.requestId || !request.body?.previewFingerprint)
)
throw new SimApiError(
'--wait requires --request-id and --preview-fingerprint from the reviewed preview',
0
)
if (operationSpec.body?.confirm && requestFlags.yes === true && request.body)
request.body.confirm = true
}
if (paging) {
const initialCursor = request[paging]?.cursor
if (
initialCursor !== undefined &&
(typeof initialCursor !== 'string' || initialCursor.trim() === '')
) {
throw new SimApiError('--cursor must be a non-empty string', 0)
}
const limit = pagedLimit === 0 ? Number.POSITIVE_INFINITY : pagedLimit
const rows: unknown[] = []
const seenCursors = new Set<string>(initialCursor ? [initialCursor] : [])
const progress = pageProgress()
let cursor: string | null = initialCursor ?? null
/** The first page's envelope: where a fact about the whole query is stated. */
let envelope: unknown
// `finally`, for the same reason as `requestAllPages`: a page that throws
// would otherwise leave the progress text on the line the error prints onto.
try {
do {
const pageSize = Math.min(DEFAULT_PAGE_SIZE, limit - rows.length)
const pageLimit = 'limit' in (operationSpec[paging] ?? {}) ? { limit: pageSize } : {}
const page: V2Page<unknown> = await client.request(operation, {
params: request.params,
headers: request.headers,
query: paging === 'query' ? { ...request.query, ...pageLimit, cursor } : request.query,
body:
paging === 'body'
? { ...(request.body ?? {}), ...pageLimit, ...(cursor ? { cursor } : {}) }
: request.body,
})
if (page.data.length > pageSize) {
throw new SimApiError(
`The API returned ${page.data.length} items for a page limit of ${pageSize}; nextCursor would skip unreturned items.`,
0
)
}
assertCursorAdvances(page.nextCursor, seenCursors)
envelope = foldPageEnvelope(envelope, page)
rows.push(...page.data)
cursor = page.nextCursor
if (cursor && rows.length < limit) progress.advance(rows.length)
} while (cursor && rows.length < limit)
} finally {
progress.finish()
}
renderPage(profile.output, { data: rows, nextCursor: cursor }, commandSpec, envelope)
return
}
let result: { data?: unknown }
try {
result = await client.request<{ data?: unknown }>(operation, {
params: request.params,
headers: request.headers,
query: request.query,
body: request.body,
})
} catch (error) {
if (
commandSpec.workspaceOperation &&
request.body?.requestId &&
(!(error instanceof SimApiError) ||
error.status === 0 ||
error.status >= 500 ||
(error.status >= 200 && error.status < 300))
) {
const failure =
error instanceof SimApiError
? error
: new SimApiError(getErrorMessage(error, 'Unable to read the mutation response'), 0)
throw new SimApiError(
failure.message,
failure.status,
'MUTATION_OUTCOME_UNKNOWN',
{
cause: failure.details,
requestId: request.body.requestId,
workspaceId: requestWorkspaceId,
applied: 'unknown',
reconciliation:
'Find the operation using this requestId, or retry identical inputs with the same requestId.',
},
failure.exitCode
)
}
throw error
}
let payload = result?.data ?? result
if (
commandSpec.workspaceOperation &&
(Boolean(request.body?.requestId) ||
requestFlags.wait === true ||
(payload && typeof payload === 'object' && 'operationId' in payload))
) {
let report
try {
report = readWorkspaceOperation(payload)
const expectedRequestId =
operation !== 'importWorkflow' && typeof request.body?.requestId === 'string'
? request.body.requestId.trim()
: request.body?.requestId
if (
report.requestId !== expectedRequestId ||
report.workspaceId !== requestWorkspaceId ||
report.kind !== WORKSPACE_OPERATION_KINDS[operation]
)
throw new SimApiError('The operation receipt does not match the submitted mutation', 0)
} catch {
throw new SimApiError(
'The mutation response did not contain a matching operation receipt; reconcile using the same request ID',
0,
'MUTATION_OUTCOME_UNKNOWN',
{ requestId: request.body?.requestId, workspaceId: requestWorkspaceId, applied: 'unknown' }
)
}
let timedOut = false
if (requestFlags.wait === true)
({ report, timedOut } = await waitWorkspaceOperation(
client,
report.workspaceId,
report.operationId,
workspaceWaitTimeout(requestFlags.waitTimeout),
report
))
payload = report
renderResult(operation, profile.output, payload, commandSpec)
assertWorkspaceOperationOutcome(report, timedOut)
return
}
renderResult(
operation,
profile.output,
payload,
commandSpec,
{ expandedTrace: requestFlags.trace === true },
// The envelope, not just the payload: a list that does not paginate states
// its own truncation there, and unwrapping `data` discarded it.
result
)
writeResultNote(operation, payload, request.body)
// Printed first, then failed, for the reason `followRun` gives: the envelope
// carries the block outputs that explain *why* the run failed, and exiting
// before writing it would leave a piped consumer an exit code and nothing to
// read.
const failure =
runFailureMessage(operation, payload) ?? bulkFailureMessage(operation, payload, request.body)
if (failure) throw new SimApiError(failure, 0)
}