@sanity/workflows-cli 0.0.0-pr-744-20261109125055

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/CHANGELOG.md +1848 -0
  2. package/LICENSE +21 -0
  3. package/README.md +798 -0
  4. package/bin/run.js +8 -0
  5. package/dist/command-ids.d.ts +10 -0
  6. package/dist/command-ids.js +10 -0
  7. package/dist/commands/workflows/abort.d.ts +29 -0
  8. package/dist/commands/workflows/abort.js +50 -0
  9. package/dist/commands/workflows/blueprints/generate.d.ts +12 -0
  10. package/dist/commands/workflows/blueprints/generate.js +46 -0
  11. package/dist/commands/workflows/codemod/packages.d.ts +13 -0
  12. package/dist/commands/workflows/codemod/packages.js +41 -0
  13. package/dist/commands/workflows/definitions/delete.d.ts +44 -0
  14. package/dist/commands/workflows/definitions/delete.js +74 -0
  15. package/dist/commands/workflows/definitions/diff.d.ts +23 -0
  16. package/dist/commands/workflows/definitions/diff.js +55 -0
  17. package/dist/commands/workflows/definitions/list.d.ts +51 -0
  18. package/dist/commands/workflows/definitions/list.js +139 -0
  19. package/dist/commands/workflows/definitions/show.d.ts +65 -0
  20. package/dist/commands/workflows/definitions/show.js +129 -0
  21. package/dist/commands/workflows/definitions/validate.d.ts +14 -0
  22. package/dist/commands/workflows/definitions/validate.js +50 -0
  23. package/dist/commands/workflows/deploy.d.ts +117 -0
  24. package/dist/commands/workflows/deploy.js +266 -0
  25. package/dist/commands/workflows/diagnose.d.ts +52 -0
  26. package/dist/commands/workflows/diagnose.js +195 -0
  27. package/dist/commands/workflows/fire-action.d.ts +53 -0
  28. package/dist/commands/workflows/fire-action.js +182 -0
  29. package/dist/commands/workflows/list.d.ts +78 -0
  30. package/dist/commands/workflows/list.js +248 -0
  31. package/dist/commands/workflows/nuke.d.ts +73 -0
  32. package/dist/commands/workflows/nuke.js +176 -0
  33. package/dist/commands/workflows/reset-activity.d.ts +32 -0
  34. package/dist/commands/workflows/reset-activity.js +60 -0
  35. package/dist/commands/workflows/show.d.ts +29 -0
  36. package/dist/commands/workflows/show.js +156 -0
  37. package/dist/commands/workflows/start.d.ts +57 -0
  38. package/dist/commands/workflows/start.js +196 -0
  39. package/dist/commands/workflows/tail.d.ts +23 -0
  40. package/dist/commands/workflows/tail.js +83 -0
  41. package/dist/commands/workflows/whoami.d.ts +15 -0
  42. package/dist/commands/workflows/whoami.js +53 -0
  43. package/dist/help.d.ts +13 -0
  44. package/dist/help.js +50 -0
  45. package/dist/hooks/finally/telemetry.d.ts +3 -0
  46. package/dist/hooks/finally/telemetry.js +9 -0
  47. package/dist/hooks/prerun/telemetry.d.ts +28 -0
  48. package/dist/hooks/prerun/telemetry.js +37 -0
  49. package/dist/index.d.ts +1 -0
  50. package/dist/index.js +1 -0
  51. package/dist/lib/base-command.d.ts +14 -0
  52. package/dist/lib/base-command.js +34 -0
  53. package/dist/lib/blueprint-emit.d.ts +56 -0
  54. package/dist/lib/blueprint-emit.js +233 -0
  55. package/dist/lib/blueprint-needs.d.ts +5 -0
  56. package/dist/lib/blueprint-needs.js +205 -0
  57. package/dist/lib/blueprint-stacks.d.ts +6 -0
  58. package/dist/lib/blueprint-stacks.js +88 -0
  59. package/dist/lib/cause-detail.d.ts +9 -0
  60. package/dist/lib/cause-detail.js +112 -0
  61. package/dist/lib/client.d.ts +24 -0
  62. package/dist/lib/client.js +40 -0
  63. package/dist/lib/codemod/manifest-rewrite.d.ts +14 -0
  64. package/dist/lib/codemod/manifest-rewrite.js +97 -0
  65. package/dist/lib/codemod/package-map.d.ts +22 -0
  66. package/dist/lib/codemod/package-map.js +72 -0
  67. package/dist/lib/codemod/report.d.ts +5 -0
  68. package/dist/lib/codemod/report.js +43 -0
  69. package/dist/lib/codemod/run.d.ts +23 -0
  70. package/dist/lib/codemod/run.js +103 -0
  71. package/dist/lib/codemod/source-rewrite.d.ts +18 -0
  72. package/dist/lib/codemod/source-rewrite.js +155 -0
  73. package/dist/lib/command-context.d.ts +20 -0
  74. package/dist/lib/command-context.js +24 -0
  75. package/dist/lib/command-telemetry.d.ts +54 -0
  76. package/dist/lib/command-telemetry.js +82 -0
  77. package/dist/lib/context.d.ts +155 -0
  78. package/dist/lib/context.js +268 -0
  79. package/dist/lib/default-partition.d.ts +23 -0
  80. package/dist/lib/default-partition.js +48 -0
  81. package/dist/lib/definition-files.d.ts +11 -0
  82. package/dist/lib/definition-files.js +58 -0
  83. package/dist/lib/definitions.d.ts +63 -0
  84. package/dist/lib/definitions.js +84 -0
  85. package/dist/lib/diff.d.ts +12 -0
  86. package/dist/lib/diff.js +93 -0
  87. package/dist/lib/env.d.ts +7 -0
  88. package/dist/lib/env.js +8 -0
  89. package/dist/lib/fail.d.ts +29 -0
  90. package/dist/lib/fail.js +46 -0
  91. package/dist/lib/flags.d.ts +49 -0
  92. package/dist/lib/flags.js +117 -0
  93. package/dist/lib/follow-up-command.d.ts +18 -0
  94. package/dist/lib/follow-up-command.js +12 -0
  95. package/dist/lib/history-rows.d.ts +3 -0
  96. package/dist/lib/history-rows.js +44 -0
  97. package/dist/lib/load-config.d.ts +46 -0
  98. package/dist/lib/load-config.js +110 -0
  99. package/dist/lib/nuke.d.ts +124 -0
  100. package/dist/lib/nuke.js +206 -0
  101. package/dist/lib/operation-args.d.ts +42 -0
  102. package/dist/lib/operation-args.js +21 -0
  103. package/dist/lib/ops-report.d.ts +47 -0
  104. package/dist/lib/ops-report.js +31 -0
  105. package/dist/lib/params.d.ts +3 -0
  106. package/dist/lib/params.js +21 -0
  107. package/dist/lib/pick-dataset.d.ts +10 -0
  108. package/dist/lib/pick-dataset.js +30 -0
  109. package/dist/lib/prompt.d.ts +35 -0
  110. package/dist/lib/prompt.js +11 -0
  111. package/dist/lib/read-fanout.d.ts +45 -0
  112. package/dist/lib/read-fanout.js +44 -0
  113. package/dist/lib/select-deployment.d.ts +31 -0
  114. package/dist/lib/select-deployment.js +91 -0
  115. package/dist/lib/share-definitions.d.ts +101 -0
  116. package/dist/lib/share-definitions.js +188 -0
  117. package/dist/lib/telemetry-setup.d.ts +81 -0
  118. package/dist/lib/telemetry-setup.js +111 -0
  119. package/dist/lib/telemetry.d.ts +78 -0
  120. package/dist/lib/telemetry.js +90 -0
  121. package/dist/lib/ui.d.ts +91 -0
  122. package/dist/lib/ui.js +116 -0
  123. package/dist/standalone-argv.d.ts +14 -0
  124. package/dist/standalone-argv.js +57 -0
  125. package/oclif.manifest.json +1731 -0
  126. package/package.json +121 -0
@@ -0,0 +1,156 @@
1
+ import { styleText } from 'node:util';
2
+ import { Args, Flags } from '@oclif/core';
3
+ import { formatDateTime } from '@sanity/cli-core/dates';
4
+ import { abortReason, workflow, errorMessage, terminalState, } from '@sanity/workflows';
5
+ import { WorkflowCommand } from '../../lib/base-command.js';
6
+ import { stuckDiagnosisLines, stuckHeadline, } from '../../lib/cause-detail.js';
7
+ import { findInstance, ambiguityFor, instanceScope, resolveReadTargets, } from '../../lib/context.js';
8
+ import { fail } from '../../lib/fail.js';
9
+ import { instanceFlags, jsonFlags, resourceFlags } from '../../lib/flags.js';
10
+ import { historyRow } from '../../lib/history-rows.js';
11
+ import { baseEngineArgs } from '../../lib/operation-args.js';
12
+ import { formatKeyValue, sectionHeader, activityIcon } from '../../lib/ui.js';
13
+ export default class Show extends WorkflowCommand {
14
+ static description = 'Show the state, activities, and effects of a workflow instance.';
15
+ static examples = [
16
+ '<%= config.bin %> workflows show wf-instance.abc123',
17
+ '<%= config.bin %> workflows show wf-instance.abc123 --include history',
18
+ '<%= config.bin %> workflows show wf-instance.abc123 --json',
19
+ ];
20
+ static args = {
21
+ instanceId: Args.string({
22
+ required: true,
23
+ description: 'Workflow instance document id.',
24
+ }),
25
+ };
26
+ static flags = {
27
+ ...instanceFlags,
28
+ ...resourceFlags,
29
+ include: Flags.string({
30
+ description: 'Optional sections to include in rendered output (--json always carries the full document).',
31
+ options: ['history'],
32
+ multiple: true,
33
+ default: [],
34
+ }),
35
+ ...jsonFlags,
36
+ };
37
+ async run() {
38
+ const { args, flags } = await this.parse(Show);
39
+ const { targets } = await resolveReadTargets(flags);
40
+ const hit = await findInstance({
41
+ targets,
42
+ instanceId: args.instanceId,
43
+ requestTag: 'show',
44
+ ambiguity: ambiguityFor(flags),
45
+ });
46
+ if (!hit) {
47
+ fail(`no instance with id "${args.instanceId}"`);
48
+ }
49
+ const { instance } = hit;
50
+ if (flags.json) {
51
+ this.log(JSON.stringify(instance, null, 2));
52
+ return;
53
+ }
54
+ const diagnostic = await this.diagnostic(hit);
55
+ this.log(instanceHeader(instance));
56
+ this.log('');
57
+ for (const line of describeInstance(instance, {
58
+ includeHistory: flags.include.includes('history'),
59
+ diagnostic,
60
+ })) {
61
+ this.log(line);
62
+ }
63
+ }
64
+ async diagnostic(hit) {
65
+ const { instance } = hit;
66
+ if (terminalState(instance) !== 'in-flight')
67
+ return undefined;
68
+ try {
69
+ const { diagnosis, evaluation, remediations } = await workflow.diagnose({
70
+ client: hit.client,
71
+ ...baseEngineArgs(instanceScope(hit)),
72
+ instanceId: instance._id,
73
+ });
74
+ return { diagnosis, remediations, allMissingDocuments: evaluation.missingDocuments };
75
+ }
76
+ catch (error) {
77
+ this.warn(`Could not evaluate the instance: ${errorMessage(error)}. Showing stored state; reference availability is unknown.`);
78
+ return undefined;
79
+ }
80
+ }
81
+ }
82
+ const HEADER_PAD = 9;
83
+ export function instanceHeader(instance) {
84
+ const title = `${styleText('bold', `${instance.definition} v${instance.pinnedVersion}`)} ${styleText('cyan', instance._id)}`;
85
+ const rows = [
86
+ formatKeyValue({ key: 'Stage', value: instance.currentStage, padTo: HEADER_PAD }),
87
+ formatKeyValue({ key: 'Started', value: formatDateTime(instance.startedAt), padTo: HEADER_PAD }),
88
+ ];
89
+ if (terminalState(instance) === 'aborted' && instance.abortedAt !== undefined) {
90
+ const reason = abortReason(instance);
91
+ const tail = reason ? ` — ${reason}` : '';
92
+ const value = `${formatDateTime(instance.abortedAt)}${tail}`;
93
+ rows.push(formatKeyValue({ key: 'Aborted', value, padTo: HEADER_PAD, emphasis: 'yellow' }));
94
+ }
95
+ else if (instance.completedAt) {
96
+ const value = formatDateTime(instance.completedAt);
97
+ rows.push(formatKeyValue({ key: 'Completed', value, padTo: HEADER_PAD, emphasis: 'green' }));
98
+ }
99
+ else {
100
+ const value = styleText('dim', '—');
101
+ rows.push(formatKeyValue({ key: 'Completed', value, padTo: HEADER_PAD }));
102
+ }
103
+ rows.push(formatKeyValue({ key: 'Partition', value: instance.tag, padTo: HEADER_PAD }));
104
+ return [title, ...rows].join('\n');
105
+ }
106
+ export function describeInstance(instance, options) {
107
+ return [
108
+ ...diagnosticLines(options.diagnostic),
109
+ ...stageLines(instance),
110
+ ...pendingEffectLines(instance),
111
+ ...(options.includeHistory ? historyLines(instance) : []),
112
+ ];
113
+ }
114
+ function diagnosticLines(diagnostic) {
115
+ if (diagnostic?.diagnosis.state !== 'stuck')
116
+ return [];
117
+ return [stuckHeadline(diagnostic.diagnosis.cause), ...stuckDiagnosisLines(diagnostic), ''];
118
+ }
119
+ function stageLines(instance) {
120
+ const settled = terminalState(instance) !== 'in-flight';
121
+ return [
122
+ sectionHeader('Stage history'),
123
+ ...instance.stages.flatMap((stage) => [
124
+ ` • ${stage.name}${stageMarker(stage)}`,
125
+ ...(stage.activities ?? []).map((activity) => activityLine(activity, settled)),
126
+ ]),
127
+ ];
128
+ }
129
+ function activityLine({ name, status }, settled) {
130
+ if (settled && status === 'active') {
131
+ return styleText('dim', ` ◌ ${name} [not finished]`);
132
+ }
133
+ return ` ${activityIcon[status]} ${name} ${styleText('dim', `[${status}]`)}`;
134
+ }
135
+ function stageMarker(stage) {
136
+ return stage.exitedAt
137
+ ? styleText('dim', ` (exited ${formatDateTime(stage.exitedAt)})`)
138
+ : styleText('cyan', ' (current)');
139
+ }
140
+ function pendingEffectLines(instance) {
141
+ if (instance.pendingEffects.length === 0) {
142
+ return [];
143
+ }
144
+ return [
145
+ '',
146
+ sectionHeader('Pending effects'),
147
+ ...instance.pendingEffects.map((eff) => ` • ${eff.name} ${styleText('dim', `(key=${eff._key})`)}`),
148
+ ];
149
+ }
150
+ function historyLines(instance) {
151
+ return [
152
+ '',
153
+ sectionHeader('History'),
154
+ ...instance.history.map((entry) => ` ${styleText('dim', `[${formatDateTime(entry.at)}]`)} ${historyRow(entry)}`),
155
+ ];
156
+ }
@@ -0,0 +1,57 @@
1
+ import { StartNotSettledError, type FieldEntry, type InitialFieldValue, type StartInstanceArgs, type WorkflowDeployment, type WorkflowInstance } from '@sanity/workflows';
2
+ import { WorkflowCommand } from '../../lib/base-command.ts';
3
+ export default class Start extends WorkflowCommand {
4
+ static description: string;
5
+ static examples: string[];
6
+ static args: {
7
+ name: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
8
+ };
9
+ static flags: {
10
+ path: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
+ deployment: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
+ partition: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
13
+ json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
14
+ version: import("@oclif/core/interfaces").OptionFlag<number | undefined, import("@oclif/core/interfaces").CustomOptions>;
15
+ field: import("@oclif/core/interfaces").OptionFlag<string[], import("@oclif/core/interfaces").CustomOptions>;
16
+ 'release-resource': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
17
+ 'instance-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
18
+ };
19
+ static telemetry: import("../../lib/command-telemetry.ts").CommandTelemetry;
20
+ run(): Promise<void>;
21
+ }
22
+ /** A created-but-unprimed failure is resumable — the engine message names
23
+ * the id and the generic remediation; operators need the CLI's own retry
24
+ * spelling appended. Every other error passes through untouched. */
25
+ export declare function withRetryHint(error: unknown): unknown;
26
+ /** The spinner message for a start whose first cascade failed after the
27
+ * instance was created and primed: the run exists — say so, name the cause,
28
+ * and point at the retry rail instead of reporting a rejection. */
29
+ export declare function startNotSettledReport(error: StartNotSettledError): string;
30
+ /** The `--json` payload for a not-settled start — same `instanceId` key as
31
+ * the success payload so scripts can pick up the retry id either way. */
32
+ export declare function startNotSettledJson(error: StartNotSettledError): Record<string, unknown>;
33
+ export declare function startFieldValues({ declared, values, deployment, releaseResource, }: {
34
+ declared: Pick<FieldEntry, 'type' | 'name'>[];
35
+ values: Record<string, string>;
36
+ deployment: Pick<WorkflowDeployment, 'workflowResource' | 'resourceAliases'>;
37
+ releaseResource?: string | undefined;
38
+ }): Record<string, unknown>;
39
+ /**
40
+ * The start-specific args of the engine's `startInstance`. Optionals spread conditionally because the engine's optional args
41
+ * reject an explicit `undefined` under `exactOptionalPropertyTypes`.
42
+ */
43
+ export declare function buildStartArgs({ name, version, initialFields, instanceId, }: {
44
+ name: string;
45
+ version: number | undefined;
46
+ initialFields: InitialFieldValue[];
47
+ /** The start's idempotency key (`--instance-id`) — a retry carrying it
48
+ * resumes the earlier attempt instead of creating a duplicate. */
49
+ instanceId?: string | undefined;
50
+ }): StartInstanceArgs;
51
+ /** The success spinner message. Pure so the in-flight / immediately-terminal
52
+ * permutations can be asserted without driving a real start. */
53
+ export declare function startReport(instance: Pick<WorkflowInstance, '_id' | 'currentStage' | 'completedAt'>): string;
54
+ /** The `--json` payload. Keys follow the CLI's `--json` vocabulary (matching
55
+ * `fire-action`): `instanceId` carries the document `_id`, `version` the
56
+ * pinned definition version; the rest mirror the instance fields. */
57
+ export declare function startResultJson(instance: Pick<WorkflowInstance, '_id' | 'definition' | 'pinnedVersion' | 'currentStage' | 'completedAt'>): Record<string, unknown>;
@@ -0,0 +1,196 @@
1
+ import { styleText } from 'node:util';
2
+ import { Args, Flags } from '@oclif/core';
3
+ import { buildInitialFields, errorMessage, releaseRef, sameResource, StartNotPrimedError, StartNotSettledError, startRefusal, } from '@sanity/workflows';
4
+ import { WorkflowCommand } from '../../lib/base-command.js';
5
+ import { defineCommandTelemetry } from '../../lib/command-telemetry.js';
6
+ import { dedupeResources, resolveContext } from '../../lib/context.js';
7
+ import { fetchDeployedDefinition } from '../../lib/definitions.js';
8
+ import { fail, failOnThrow, failureDetail } from '../../lib/fail.js';
9
+ import { deploymentFlags, jsonFlags } from '../../lib/flags.js';
10
+ import { cliEngine } from '../../lib/operation-args.js';
11
+ import { runWriteVerb } from '../../lib/ops-report.js';
12
+ import { coerceValue, splitParams } from '../../lib/params.js';
13
+ const flags = {
14
+ ...deploymentFlags,
15
+ version: Flags.integer({
16
+ description: 'Definition version to start from (default: highest deployed).',
17
+ }),
18
+ field: Flags.string({
19
+ description: 'Initial value for a declared input-sourced field, as name=value (repeatable). Values ' +
20
+ 'are JSON-parsed, falling back to a string; ref kinds take a JSON object with a GDR ' +
21
+ '`id` and doc `type`. A release ref also takes a bare Content Release name.',
22
+ multiple: true,
23
+ default: [],
24
+ }),
25
+ 'release-resource': Flags.string({
26
+ description: "Resource alias (from the deployment's `resourceAliases`) that bare release names in " +
27
+ '--field point at. Needed when the deployment binds several other resources.',
28
+ helpValue: '<alias>',
29
+ }),
30
+ 'instance-id': Flags.string({
31
+ description: "Start under this instance id — for retries. The id is the start's idempotency key: " +
32
+ 'pass the id of a start that failed partway and the engine resumes it instead of ' +
33
+ 'creating a duplicate (an already-settled start replays as a no-op). Omit to mint ' +
34
+ 'a fresh id.',
35
+ }),
36
+ ...jsonFlags,
37
+ };
38
+ export default class Start extends WorkflowCommand {
39
+ static description = 'Start a workflow instance from a deployed definition. Supply values for the ' +
40
+ "workflow's input-sourced fields with --field (e.g. the subject document ref).";
41
+ static examples = [
42
+ '<%= config.bin %> workflows start product-launch',
43
+ '<%= config.bin %> workflows start article-review --field subject=\'{"id":"dataset:proj:ds:article-1","type":"article"}\'',
44
+ '<%= config.bin %> workflows start release-review --field release=rA1b2C3d4',
45
+ '<%= config.bin %> workflows start release-review --field release=rA1b2C3d4 --release-resource content',
46
+ '<%= config.bin %> workflows start product-launch --version 2 --partition prod',
47
+ '<%= config.bin %> workflows start product-launch --instance-id prod.wf-instance.a1b2c3d4e5f6',
48
+ ];
49
+ static args = {
50
+ name: Args.string({ required: true, description: 'Workflow definition name.' }),
51
+ };
52
+ static flags = flags;
53
+ static telemetry = defineCommandTelemetry(flags, { redact: ['field'] });
54
+ async run() {
55
+ const { args, flags } = await this.parse(Start);
56
+ const { deployment, client, scope } = await resolveContext(flags);
57
+ const values = failOnThrow('Invalid --field:', () => splitParams(flags.field));
58
+ const initialFields = await resolveStartInputs({
59
+ client,
60
+ name: args.name,
61
+ deployment,
62
+ version: flags.version,
63
+ values,
64
+ releaseResource: flags['release-resource'],
65
+ });
66
+ const engine = cliEngine(client, scope);
67
+ const startArgs = buildStartArgs({
68
+ name: args.name,
69
+ version: flags.version,
70
+ initialFields,
71
+ instanceId: flags['instance-id'],
72
+ });
73
+ if (flags.json) {
74
+ const result = await engine.startInstance(startArgs).catch((error) => {
75
+ if (error instanceof StartNotSettledError) {
76
+ this.log(JSON.stringify(startNotSettledJson(error), null, 2));
77
+ return undefined;
78
+ }
79
+ fail('start error:', failureDetail(withRetryHint(error)));
80
+ });
81
+ if (result !== undefined) {
82
+ this.log(JSON.stringify(startResultJson(result.instance), null, 2));
83
+ }
84
+ return;
85
+ }
86
+ await runWriteVerb({
87
+ startLabel: `Starting ${args.name}…`,
88
+ failLabel: 'Start rejected',
89
+ failHeadline: 'start error:',
90
+ run: () => engine.startInstance(startArgs).catch((error) => {
91
+ if (error instanceof StartNotSettledError)
92
+ return error;
93
+ throw withRetryHint(error);
94
+ }),
95
+ report: (result) => result instanceof StartNotSettledError
96
+ ? { changed: false, message: startNotSettledReport(result) }
97
+ : { changed: true, message: startReport(result.instance) },
98
+ log: (line) => this.log(line),
99
+ });
100
+ }
101
+ }
102
+ export function withRetryHint(error) {
103
+ return error instanceof StartNotPrimedError
104
+ ? new Error(`${errorMessage(error)} (--instance-id ${error.instanceId})`)
105
+ : error;
106
+ }
107
+ export function startNotSettledReport(error) {
108
+ const id = styleText('bold', error.instanceId);
109
+ return (`Started ${id} — but its first auto-advance failed: ${errorMessage(error.cause)}. ` +
110
+ `It settles on the next tick, or retry with --instance-id ${error.instanceId}.`);
111
+ }
112
+ export function startNotSettledJson(error) {
113
+ return {
114
+ instanceId: error.instanceId,
115
+ notSettled: true,
116
+ detail: errorMessage(error.cause),
117
+ ...(error.instance !== undefined
118
+ ? { currentStage: error.instance.currentStage, definition: error.instance.definition }
119
+ : {}),
120
+ };
121
+ }
122
+ async function resolveStartInputs({ client, name, deployment, version, values, releaseResource, }) {
123
+ const { partition } = deployment;
124
+ const deployed = await fetchDeployedDefinition({ client, name, partition, version });
125
+ if (deployed === undefined) {
126
+ fail(`No deployed definition "${name}".`);
127
+ }
128
+ const refusal = startRefusal(deployed);
129
+ if (refusal !== undefined) {
130
+ fail('start error:', refusal);
131
+ }
132
+ const declared = deployed.fields ?? [];
133
+ return failOnThrow('start usage error:', () => buildInitialFields({
134
+ declared,
135
+ values: startFieldValues({ declared, values, deployment, releaseResource }),
136
+ }));
137
+ }
138
+ export function startFieldValues({ declared, values, deployment, releaseResource, }) {
139
+ return Object.fromEntries(Object.entries(values).map(([name, raw]) => {
140
+ const value = coerceValue(raw);
141
+ const isRelease = declared.some((f) => f.name === name && f.type === 'release.ref');
142
+ if (!isRelease || typeof value === 'object') {
143
+ return [name, value];
144
+ }
145
+ const releaseName = typeof value === 'string' ? value : raw;
146
+ return [
147
+ name,
148
+ releaseRef({
149
+ res: contentResource({ deployment, field: name, alias: releaseResource }),
150
+ releaseName,
151
+ }),
152
+ ];
153
+ }));
154
+ }
155
+ function contentResource({ deployment, field, alias, }) {
156
+ const bindings = deployment.resourceAliases ?? [];
157
+ if (alias !== undefined) {
158
+ const binding = bindings.find((b) => b.name === alias);
159
+ if (binding === undefined) {
160
+ const names = bindings.map((b) => b.name).join(', ') || 'none';
161
+ throw new Error(`--release-resource "${alias}" is not one of the deployment's resource aliases (${names}).`);
162
+ }
163
+ return binding.resource;
164
+ }
165
+ const foreign = dedupeResources(bindings.map((binding) => binding.resource)).filter((resource) => !sameResource(resource, deployment.workflowResource));
166
+ if (foreign.length > 1) {
167
+ throw new Error(`field "${field}" takes a release, but the deployment binds several resources, so a bare ` +
168
+ `release name is ambiguous. Pass --release-resource <alias>, or the full object: ${field}=` +
169
+ `'{"id":"dataset:<projectId>:<dataset>:_.releases.<name>","type":"system.release","releaseName":"<name>"}'`);
170
+ }
171
+ return foreign[0] ?? deployment.workflowResource;
172
+ }
173
+ export function buildStartArgs({ name, version, initialFields, instanceId, }) {
174
+ return {
175
+ definition: name,
176
+ ...(version !== undefined ? { version } : {}),
177
+ ...(initialFields.length > 0 ? { initialFields } : {}),
178
+ ...(instanceId !== undefined ? { instanceId } : {}),
179
+ };
180
+ }
181
+ export function startReport(instance) {
182
+ const id = styleText('bold', instance._id);
183
+ const stage = styleText('bold', instance.currentStage);
184
+ return instance.completedAt !== undefined
185
+ ? `Started ${id} — completed immediately at ${stage}`
186
+ : `Started ${id} — now at ${stage}`;
187
+ }
188
+ export function startResultJson(instance) {
189
+ return {
190
+ instanceId: instance._id,
191
+ definition: instance.definition,
192
+ version: instance.pinnedVersion,
193
+ currentStage: instance.currentStage,
194
+ ...(instance.completedAt !== undefined ? { completedAt: instance.completedAt } : {}),
195
+ };
196
+ }
@@ -0,0 +1,23 @@
1
+ import { WorkflowCommand } from '../../lib/base-command.ts';
2
+ export default class Tail extends WorkflowCommand {
3
+ static description: string;
4
+ static examples: string[];
5
+ static args: {
6
+ instanceId: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
7
+ };
8
+ static flags: {
9
+ path: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
+ 'project-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
+ dataset: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
+ 'media-library-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
13
+ deployment: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
14
+ partition: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
15
+ };
16
+ run(): Promise<void>;
17
+ /**
18
+ * Fetch the current instance state, print history entries past the
19
+ * given high-water mark, return the new mark. Pulled out so the
20
+ * async work in the subscription's `next` handler stays tidy.
21
+ */
22
+ private printNewEntries;
23
+ }
@@ -0,0 +1,83 @@
1
+ import { styleText } from 'node:util';
2
+ import { Args } from '@oclif/core';
3
+ import { formatDateTime } from '@sanity/cli-core/dates';
4
+ import { assertReadableModel, displayTitle, errorMessage, } from '@sanity/workflows';
5
+ import logSymbols from 'log-symbols';
6
+ import { WorkflowCommand } from '../../lib/base-command.js';
7
+ import { ambiguityFor, findInstance, resolveReadTargets } from '../../lib/context.js';
8
+ import { fail, failureDetail } from '../../lib/fail.js';
9
+ import { instanceFlags, resourceFlags } from '../../lib/flags.js';
10
+ const TAIL_TAG = 'tail';
11
+ export default class Tail extends WorkflowCommand {
12
+ static description = 'Stream new history entries on a workflow instance as they land in the dataset.';
13
+ static examples = ['<%= config.bin %> workflows tail wf-instance.abc123'];
14
+ static args = {
15
+ instanceId: Args.string({
16
+ required: true,
17
+ description: 'Workflow instance id to tail.',
18
+ }),
19
+ };
20
+ static flags = {
21
+ ...instanceFlags,
22
+ ...resourceFlags,
23
+ };
24
+ async run() {
25
+ const { args, flags } = await this.parse(Tail);
26
+ const { targets } = await resolveReadTargets(flags);
27
+ const hit = await findInstance({
28
+ targets,
29
+ instanceId: args.instanceId,
30
+ requestTag: TAIL_TAG,
31
+ ambiguity: ambiguityFor({}),
32
+ });
33
+ if (!hit) {
34
+ fail(`No instance with id "${args.instanceId}"`);
35
+ }
36
+ const { client, instance: initial } = hit;
37
+ this.log(styleText('dim', `tailing ${styleText('bold', args.instanceId)} (${initial.definition} v${initial.pinnedVersion}, ${initial.history.length} prior entries, currently in ${initial.currentStage})`));
38
+ this.log(styleText('dim', 'Ctrl+C to stop'));
39
+ this.log('');
40
+ let rejectListen;
41
+ const listenFailed = new Promise((_, reject) => {
42
+ rejectListen = reject;
43
+ });
44
+ let printChain = Promise.resolve(initial.history.length);
45
+ const subscription = client
46
+ .listen(`*[_id == $id]`, { id: args.instanceId }, {
47
+ includeResult: false,
48
+ visibility: 'query',
49
+ tag: TAIL_TAG,
50
+ })
51
+ .subscribe({
52
+ next: () => {
53
+ printChain = printChain.then((seen) => this.printNewEntries({ client, instanceId: args.instanceId, seen }).catch((err) => {
54
+ process.stderr.write(`${styleText('red', `${logSymbols.error} fetch failed:`)} ${errorMessage(err)}\n`);
55
+ return seen;
56
+ }));
57
+ },
58
+ error: rejectListen,
59
+ });
60
+ const shutdown = () => {
61
+ subscription.unsubscribe();
62
+ process.stderr.write(`\n${styleText('dim', `${logSymbols.info} stopped`)}\n`);
63
+ process.exit(0);
64
+ };
65
+ process.on('SIGINT', shutdown);
66
+ process.on('SIGTERM', shutdown);
67
+ await listenFailed.catch((err) => {
68
+ subscription.unsubscribe();
69
+ fail('Listen subscription error:', failureDetail(err));
70
+ });
71
+ }
72
+ async printNewEntries({ client, instanceId, seen, }) {
73
+ const raw = await client.getDocument(instanceId, { tag: TAIL_TAG });
74
+ if (!raw)
75
+ return seen;
76
+ const next = assertReadableModel(raw);
77
+ const newEntries = next.history.slice(seen);
78
+ for (const entry of newEntries) {
79
+ this.log(`${styleText('dim', `[${formatDateTime(entry.at)}]`)} ${styleText('cyan', displayTitle(entry._type))}`);
80
+ }
81
+ return Math.max(seen, next.history.length);
82
+ }
83
+ }
@@ -0,0 +1,15 @@
1
+ import { WorkflowCommand } from '../../lib/base-command.ts';
2
+ export default class WhoamiCommand extends WorkflowCommand {
3
+ static description: string;
4
+ static examples: string[];
5
+ static flags: {
6
+ path: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
7
+ 'project-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
8
+ dataset: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
9
+ 'media-library-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
+ deployment: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
+ partition: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
+ json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
13
+ };
14
+ run(): Promise<void>;
15
+ }
@@ -0,0 +1,53 @@
1
+ import { classifyPrincipalId, lakePrincipalId, resolveAccess, } from '@sanity/workflows';
2
+ import { WorkflowCommand } from '../../lib/base-command.js';
3
+ import { resolveReadTargets } from '../../lib/context.js';
4
+ import { fail, failureDetail } from '../../lib/fail.js';
5
+ import { jsonFlags, readFlags, resourceFlags } from '../../lib/flags.js';
6
+ import { formatKeyValue, resourceLabel } from '../../lib/ui.js';
7
+ export default class WhoamiCommand extends WorkflowCommand {
8
+ static description = 'Show the user ID Workflows records for your login. Put the Sanity user ID in user assignee fields.';
9
+ static examples = [
10
+ '<%= config.bin %> workflows whoami',
11
+ '<%= config.bin %> workflows whoami --json',
12
+ '<%= config.bin %> workflows whoami --project-id abc123 --dataset production',
13
+ ];
14
+ static flags = {
15
+ ...readFlags,
16
+ ...resourceFlags,
17
+ ...jsonFlags,
18
+ };
19
+ async run() {
20
+ const { flags } = await this.parse(WhoamiCommand);
21
+ const { targets } = await resolveReadTargets(flags);
22
+ const [target, ...rest] = targets;
23
+ if (target === undefined || rest.length > 0) {
24
+ fail('The config names several resources — pass --deployment or --project-id with --dataset to choose one.', targets.map(({ resource }) => resourceLabel(resource)).join('\n'));
25
+ }
26
+ const access = await resolveAccess(target.client).catch((err) => fail('Could not resolve your user:', failureDetail(err)));
27
+ const whoami = whoamiFrom(access, resourceLabel(target.resource));
28
+ if (flags.json) {
29
+ this.log(JSON.stringify(whoami, null, 2));
30
+ return;
31
+ }
32
+ whoamiLines(whoami).forEach((line) => this.log(line));
33
+ }
34
+ }
35
+ function whoamiFrom(access, resource) {
36
+ const { id } = access.actor;
37
+ return {
38
+ kind: classifyPrincipalId(id).namespace === 'robot' ? 'robot' : 'user',
39
+ sanityUserId: id,
40
+ projectUserId: lakePrincipalId(access),
41
+ resource,
42
+ };
43
+ }
44
+ function whoamiLines(whoami) {
45
+ const rows = [
46
+ { key: 'Kind', value: whoami.kind },
47
+ { key: 'Sanity user ID', value: whoami.sanityUserId },
48
+ { key: 'Project user ID', value: whoami.projectUserId },
49
+ { key: 'Resource', value: whoami.resource },
50
+ ];
51
+ const padTo = Math.max(...rows.map(({ key }) => key.length));
52
+ return rows.map((row) => formatKeyValue({ ...row, padTo }));
53
+ }
package/dist/help.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { Help, type Command } from '@oclif/core';
2
+ /** Strip the mount topic so standalone root help can list short forms. */
3
+ export declare const standaloneSurfaceId: (id: string) => string | undefined;
4
+ /** Keep the standalone short surface, including oclif's help command. */
5
+ export declare const keepCommandAtRoot: (id: string) => boolean;
6
+ /** Strip the mount topic from an example rendered by standalone help. */
7
+ export declare const standaloneExample: (example: Command.Example) => Command.Example;
8
+ /** Standalone-binary help that lists topic-scoped commands under their short
9
+ * forms (`deploy`, `definitions list`) rather than the mount ids. */
10
+ export default class WorkflowHelp extends Help {
11
+ showCommandHelp(command: Command.Loadable): Promise<void>;
12
+ protected showRootHelp(): Promise<void>;
13
+ }
package/dist/help.js ADDED
@@ -0,0 +1,50 @@
1
+ import { Help } from '@oclif/core';
2
+ import { WORKFLOWS_TOPIC, WORKFLOWS_TOPIC_PREFIX } from './command-ids.js';
3
+ const CANONICAL_EXAMPLE_PREFIX = `<%= config.bin %> ${WORKFLOWS_TOPIC} `;
4
+ const STANDALONE_EXAMPLE_PREFIX = '<%= config.bin %> ';
5
+ const HELP_COMMAND_ID = 'help';
6
+ export const standaloneSurfaceId = (id) => {
7
+ if (!id.startsWith(WORKFLOWS_TOPIC_PREFIX))
8
+ return undefined;
9
+ return id.slice(WORKFLOWS_TOPIC_PREFIX.length);
10
+ };
11
+ export const keepCommandAtRoot = (id) => id === HELP_COMMAND_ID || standaloneSurfaceId(id) !== undefined;
12
+ export const standaloneExample = (example) => {
13
+ if (typeof example === 'string') {
14
+ return example.replace(CANONICAL_EXAMPLE_PREFIX, STANDALONE_EXAMPLE_PREFIX);
15
+ }
16
+ return {
17
+ ...example,
18
+ command: example.command.replace(CANONICAL_EXAMPLE_PREFIX, STANDALONE_EXAMPLE_PREFIX),
19
+ };
20
+ };
21
+ export default class WorkflowHelp extends Help {
22
+ async showCommandHelp(command) {
23
+ await super.showCommandHelp(withStandaloneSurface(command));
24
+ }
25
+ async showRootHelp() {
26
+ if (this.opts.all) {
27
+ await super.showRootHelp();
28
+ return;
29
+ }
30
+ this.log(this.formatRoot());
31
+ this.log('');
32
+ const commands = this.sortedCommands
33
+ .filter((command) => keepCommandAtRoot(command.id))
34
+ .map((command) => withStandaloneSurface(command));
35
+ if (commands.length > 0) {
36
+ this.log(this.formatCommands(commands));
37
+ this.log('');
38
+ }
39
+ }
40
+ }
41
+ function withStandaloneSurface(command) {
42
+ const shortId = standaloneSurfaceId(command.id);
43
+ if (shortId === undefined)
44
+ return command;
45
+ return {
46
+ ...command,
47
+ id: shortId,
48
+ examples: command.examples?.map((example) => standaloneExample(example)),
49
+ };
50
+ }
@@ -0,0 +1,3 @@
1
+ import type { Hook } from '@oclif/core';
2
+ declare const hook: Hook<'finally'>;
3
+ export default hook;