@sanity/workflows-cli 0.0.0-stage → 0.39.0

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 (134) hide show
  1. package/CHANGELOG.md +1981 -0
  2. package/LICENSE +21 -0
  3. package/README.md +848 -2
  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 +52 -0
  18. package/dist/commands/workflows/definitions/list.js +139 -0
  19. package/dist/commands/workflows/definitions/show.d.ts +66 -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 +53 -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 +79 -0
  30. package/dist/commands/workflows/list.js +249 -0
  31. package/dist/commands/workflows/nuke.d.ts +73 -0
  32. package/dist/commands/workflows/nuke.js +175 -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 +30 -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 +24 -0
  40. package/dist/commands/workflows/tail.js +83 -0
  41. package/dist/commands/workflows/whoami.d.ts +16 -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 +10 -0
  47. package/dist/hooks/prerun/telemetry.d.ts +33 -0
  48. package/dist/hooks/prerun/telemetry.js +52 -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 +41 -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 +284 -0
  57. package/dist/lib/blueprint-stacks.d.ts +6 -0
  58. package/dist/lib/blueprint-stacks.js +118 -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 +27 -0
  62. package/dist/lib/client.js +45 -0
  63. package/dist/lib/codemod/ast.d.ts +17 -0
  64. package/dist/lib/codemod/ast.js +14 -0
  65. package/dist/lib/codemod/export-rename.d.ts +19 -0
  66. package/dist/lib/codemod/export-rename.js +337 -0
  67. package/dist/lib/codemod/manifest-rewrite.d.ts +17 -0
  68. package/dist/lib/codemod/manifest-rewrite.js +133 -0
  69. package/dist/lib/codemod/package-map.d.ts +27 -0
  70. package/dist/lib/codemod/package-map.js +99 -0
  71. package/dist/lib/codemod/report.d.ts +4 -0
  72. package/dist/lib/codemod/report.js +51 -0
  73. package/dist/lib/codemod/run.d.ts +25 -0
  74. package/dist/lib/codemod/run.js +108 -0
  75. package/dist/lib/codemod/source-rewrite.d.ts +20 -0
  76. package/dist/lib/codemod/source-rewrite.js +150 -0
  77. package/dist/lib/command-context.d.ts +20 -0
  78. package/dist/lib/command-context.js +24 -0
  79. package/dist/lib/command-telemetry.d.ts +54 -0
  80. package/dist/lib/command-telemetry.js +82 -0
  81. package/dist/lib/context.d.ts +151 -0
  82. package/dist/lib/context.js +263 -0
  83. package/dist/lib/default-partition.d.ts +23 -0
  84. package/dist/lib/default-partition.js +47 -0
  85. package/dist/lib/definition-files.d.ts +14 -0
  86. package/dist/lib/definition-files.js +60 -0
  87. package/dist/lib/definitions.d.ts +63 -0
  88. package/dist/lib/definitions.js +84 -0
  89. package/dist/lib/diff.d.ts +12 -0
  90. package/dist/lib/diff.js +93 -0
  91. package/dist/lib/env.d.ts +7 -0
  92. package/dist/lib/env.js +8 -0
  93. package/dist/lib/fail.d.ts +36 -0
  94. package/dist/lib/fail.js +55 -0
  95. package/dist/lib/failure-kind.d.ts +7 -0
  96. package/dist/lib/failure-kind.js +66 -0
  97. package/dist/lib/flags.d.ts +53 -0
  98. package/dist/lib/flags.js +127 -0
  99. package/dist/lib/follow-up-command.d.ts +18 -0
  100. package/dist/lib/follow-up-command.js +12 -0
  101. package/dist/lib/history-rows.d.ts +3 -0
  102. package/dist/lib/history-rows.js +44 -0
  103. package/dist/lib/load-config.d.ts +51 -0
  104. package/dist/lib/load-config.js +108 -0
  105. package/dist/lib/nuke.d.ts +124 -0
  106. package/dist/lib/nuke.js +206 -0
  107. package/dist/lib/operation-args.d.ts +42 -0
  108. package/dist/lib/operation-args.js +21 -0
  109. package/dist/lib/ops-report.d.ts +45 -0
  110. package/dist/lib/ops-report.js +31 -0
  111. package/dist/lib/params.d.ts +3 -0
  112. package/dist/lib/params.js +21 -0
  113. package/dist/lib/pick-resource.d.ts +13 -0
  114. package/dist/lib/pick-resource.js +82 -0
  115. package/dist/lib/prompt.d.ts +35 -0
  116. package/dist/lib/prompt.js +11 -0
  117. package/dist/lib/read-fanout.d.ts +45 -0
  118. package/dist/lib/read-fanout.js +45 -0
  119. package/dist/lib/resource-target.d.ts +10 -0
  120. package/dist/lib/resource-target.js +12 -0
  121. package/dist/lib/select-deployment.d.ts +31 -0
  122. package/dist/lib/select-deployment.js +91 -0
  123. package/dist/lib/share-definitions.d.ts +101 -0
  124. package/dist/lib/share-definitions.js +188 -0
  125. package/dist/lib/telemetry-setup.d.ts +77 -0
  126. package/dist/lib/telemetry-setup.js +117 -0
  127. package/dist/lib/telemetry.d.ts +81 -0
  128. package/dist/lib/telemetry.js +90 -0
  129. package/dist/lib/ui.d.ts +88 -0
  130. package/dist/lib/ui.js +114 -0
  131. package/dist/standalone-argv.d.ts +14 -0
  132. package/dist/standalone-argv.js +57 -0
  133. package/oclif.manifest.json +1894 -0
  134. package/package.json +118 -3
@@ -0,0 +1,117 @@
1
+ import { styleText } from 'node:util';
2
+ import { getUserConfig } from '@sanity/cli-core';
3
+ import { _requestResourceOrganizationId, clientConfigFromResource, processShellUserProperties, } from '@sanity/workflows';
4
+ import boxen from 'boxen';
5
+ import { globalClient, resolveToken } from './client.js';
6
+ import { commandTraceContext } from './command-context.js';
7
+ import { loadWorkflowConfigIfPresent } from './load-config.js';
8
+ import { createBuiltinTelemetry, raceWithDeadline, setCliTelemetry } from './telemetry.js';
9
+ const DISCLOSURE_KEY = 'workflowCliTelemetryDisclosed';
10
+ const SANITY_CLI_DISCLOSURE_KEY = 'telemetryDisclosed';
11
+ export function maybeShowTelemetryDisclosure(args) {
12
+ const { userConfig, writeStderr } = args;
13
+ if (userConfig.get(DISCLOSURE_KEY) !== undefined ||
14
+ userConfig.get(SANITY_CLI_DISCLOSURE_KEY) !== undefined) {
15
+ return;
16
+ }
17
+ writeStderr(`${boxen(`The Sanity workflow CLI collects telemetry data on general usage and errors.
18
+ This helps us improve workflows and prioritize features.
19
+
20
+ To opt in/out, run ${styleText('cyan', 'npx sanity telemetry enable/disable')}.
21
+ Learn more: https://www.sanity.io/telemetry`, { borderColor: 'yellow', borderStyle: 'round', margin: 1, padding: 1 })}\n`);
22
+ userConfig.set(DISCLOSURE_KEY, Date.now());
23
+ }
24
+ function configResource(config, deployment) {
25
+ const deployments = config?.deployments ?? [];
26
+ if (deployment === undefined)
27
+ return deployments[0]?.workflowResource;
28
+ return deployments.find(({ name }) => name === deployment)?.workflowResource;
29
+ }
30
+ export async function setupCliTelemetry(args) {
31
+ const env = args?.env ?? process.env;
32
+ const context = args?.context ??
33
+ commandTraceContext({
34
+ commandId: undefined,
35
+ argv: process.argv.slice(2),
36
+ flagDefs: undefined,
37
+ commandTelemetry: undefined,
38
+ env,
39
+ });
40
+ try {
41
+ const config = await loadWorkflowConfigIfPresent(args?.configPath).catch(() => undefined);
42
+ if (config?.telemetry !== undefined) {
43
+ setCliTelemetry({ kind: 'provided', logger: config.telemetry }, context);
44
+ return;
45
+ }
46
+ const token = await resolveToken().catch(() => undefined);
47
+ if (token === undefined) {
48
+ return;
49
+ }
50
+ const resource = args?.target ?? configResource(config, args?.deployment);
51
+ const client = args?.client ?? globalClient(token);
52
+ const telemetry = createBuiltinTelemetry({
53
+ client,
54
+ projectId: resource === undefined ? undefined : resourceProperties(resource).projectId,
55
+ env,
56
+ forceSend: args?.forceSend ?? false,
57
+ packageVersion: args?.cliVersion,
58
+ });
59
+ setCliTelemetry(telemetry, context);
60
+ attachBuiltinContext({ telemetry, resource, client, deps: args });
61
+ }
62
+ catch {
63
+ }
64
+ }
65
+ function attachBuiltinContext(args) {
66
+ const { telemetry, resource, client, deps } = args;
67
+ if (!telemetry.envDenied || telemetry.forceSend) {
68
+ attachResourceContext({ telemetry, resource, client, cliVersion: deps?.cliVersion });
69
+ }
70
+ if (!telemetry.envDenied) {
71
+ maybeShowTelemetryDisclosure({
72
+ userConfig: deps?.userConfig ?? getUserConfig(),
73
+ writeStderr: deps?.writeStderr ?? ((message) => void process.stderr.write(message)),
74
+ });
75
+ }
76
+ }
77
+ function attachResourceContext(args) {
78
+ const { telemetry, resource, client, cliVersion } = args;
79
+ telemetry.store.logger.updateUserProperties(cliUserProperties({ resource, cliVersion }));
80
+ if (resource === undefined)
81
+ return;
82
+ void resolveOrgId(client, resource).then((orgId) => {
83
+ if (orgId !== undefined)
84
+ telemetry.store.logger.updateUserProperties({ orgId });
85
+ return undefined;
86
+ });
87
+ }
88
+ const ORG_LOOKUP_DEADLINE_MS = 2_000;
89
+ const CONTEXT_TAG = 'telemetry.context';
90
+ export function cliUserProperties(args) {
91
+ const { resource, cliVersion } = args;
92
+ return {
93
+ ...processShellUserProperties('cli'),
94
+ ...(cliVersion !== undefined ? { cliVersion } : {}),
95
+ ...(resource === undefined ? {} : resourceProperties(resource)),
96
+ };
97
+ }
98
+ function resourceProperties(resource) {
99
+ const address = clientConfigFromResource(resource);
100
+ return {
101
+ resourceType: resource.type,
102
+ resourceId: resource.id,
103
+ ...('dataset' in address ? { projectId: address.projectId, dataset: address.dataset } : {}),
104
+ };
105
+ }
106
+ export async function resolveOrgId(client, resource) {
107
+ try {
108
+ return await raceWithDeadline(_requestResourceOrganizationId({
109
+ request: (options) => client.request({ ...options, timeout: ORG_LOOKUP_DEADLINE_MS }),
110
+ resource,
111
+ tag: CONTEXT_TAG,
112
+ }), ORG_LOOKUP_DEADLINE_MS);
113
+ }
114
+ catch {
115
+ return undefined;
116
+ }
117
+ }
@@ -0,0 +1,81 @@
1
+ /** Payload policy under https://www.sanity.io/telemetry: option flags as `--name=value`;
2
+ * booleans, redacted, and undeclared flags by name only; never raw argv or error text. */
3
+ import { type DefinedTelemetryTrace, type TelemetryStore } from '@sanity/telemetry';
4
+ import { type DerivedEventData, type TelemetryIntakeClient, type WorkflowDefinitionDeployedData, type WorkflowTelemetryLogger } from '@sanity/workflows';
5
+ import type { WorkflowCliCommandContext } from './command-context.ts';
6
+ import type { CliFailureKind } from './failure-kind.ts';
7
+ export interface WorkflowCliCommandResult {
8
+ success: boolean;
9
+ /** Present only when `success` is false. */
10
+ failureKind?: CliFailureKind;
11
+ }
12
+ export declare const WorkflowCliCommandExecuted: DefinedTelemetryTrace<WorkflowCliCommandResult, void>;
13
+ export type WorkflowDefinitionSharedData = Omit<DerivedEventData<WorkflowDefinitionDeployedData>, 'status'>;
14
+ export declare const WorkflowDefinitionShared: import("@sanity/telemetry").DefinedTelemetryLog<WorkflowDefinitionSharedData>;
15
+ /**
16
+ * How the donation decision was reached, and what it was. Paired with `shared`
17
+ * (whether it actually reached the endpoint) this keeps every case distinct —
18
+ * an explicit opt-out vs default sharing, and a chosen share vs a failed POST:
19
+ * - `opt-in` / `opt-out` — an explicit `--share-defs` / `--no-share-defs`.
20
+ * - `default` — no sharing flag; definitions are donated in every environment.
21
+ */
22
+ export type DefinitionSharingDecision = 'opt-in' | 'opt-out' | 'default';
23
+ export interface WorkflowDefinitionSharingDecidedData {
24
+ decision: DefinitionSharingDecision;
25
+ /** Whether the donation actually reached the feedback endpoint — `false` for
26
+ * any non-sharing decision, and also for a chosen share whose POST failed. */
27
+ shared: boolean;
28
+ /** Newly created definition versions this invocation could have donated. */
29
+ definitionCount: number;
30
+ }
31
+ export declare const WorkflowDefinitionSharingDecided: import("@sanity/telemetry").DefinedTelemetryLog<WorkflowDefinitionSharingDecidedData>;
32
+ /**
33
+ * The shell for one CLI invocation. `builtin` is the Sanity-intake store;
34
+ * `provided` is a config-supplied logger that replaces the shell and its
35
+ * policy wholesale; `off` (the default) emits nothing — no config-derived
36
+ * project, no auth token, or telemetry setup failed.
37
+ */
38
+ export type CliTelemetry = {
39
+ kind: 'builtin';
40
+ logger: WorkflowTelemetryLogger;
41
+ store: TelemetryStore<unknown>;
42
+ envDenied: boolean;
43
+ /** The environment denial was overridden ({@link createBuiltinTelemetry}):
44
+ * the store sends despite CI / `DO_NOT_TRACK`, subject only to
45
+ * account consent. */
46
+ forceSend: boolean;
47
+ } | {
48
+ kind: 'provided';
49
+ logger: WorkflowTelemetryLogger;
50
+ } | {
51
+ kind: 'off';
52
+ logger: WorkflowTelemetryLogger;
53
+ };
54
+ export declare function cliTelemetry(): CliTelemetry;
55
+ /** Install the shell and, for the built-in store, start the command trace. */
56
+ export declare function setCliTelemetry(telemetry: Exclude<CliTelemetry, {
57
+ kind: 'off';
58
+ }>, context: WorkflowCliCommandContext): void;
59
+ export declare function clearCliTelemetry(): void;
60
+ /** Build the built-in Sanity-intake shell over an authenticated client. `forceSend` overrides the environment denial
61
+ * (CI / `DO_NOT_TRACK`) when a deploy may share definitions—flagless by
62
+ * default or explicitly enabled. Account-level consent is unaffected: the intake still fetches
63
+ * `/intake/telemetry-status`, so `sanity telemetry disable` still mutes. */
64
+ export declare function createBuiltinTelemetry(args: {
65
+ client: TelemetryIntakeClient;
66
+ projectId: string | undefined;
67
+ env: Record<string, string | undefined>;
68
+ forceSend?: boolean;
69
+ packageVersion?: string | undefined;
70
+ }): Extract<CliTelemetry, {
71
+ kind: 'builtin';
72
+ }>;
73
+ /**
74
+ * Race `work` against a deadline, resolving `undefined` when the deadline
75
+ * wins. The timer is always cleared once the race settles — oclif never
76
+ * force-exits on success, so a pending timer would hold a finished process
77
+ * open. The losing promise's eventual settlement is absorbed by the race.
78
+ */
79
+ export declare function raceWithDeadline<T>(work: Promise<T>, deadlineMs: number): Promise<T | undefined>;
80
+ /** Complete the command trace and flush. A provided logger owns its own delivery. */
81
+ export declare function finishCliTelemetry(result: WorkflowCliCommandResult): Promise<void>;
@@ -0,0 +1,90 @@
1
+ import { createBatchedStore, createSessionId, defineEvent, defineTrace, } from '@sanity/telemetry';
2
+ import { createTelemetryIntake, _resolveTelemetryEnvironment, isTelemetryEnvDenied, noopTelemetry, } from '@sanity/workflows';
3
+ export const WorkflowCliCommandExecuted = defineTrace({
4
+ name: 'Workflows CLI Command Executed',
5
+ version: 3,
6
+ description: 'A Workflows CLI command was executed — the trace context carries the command path and each flag used in canonical long form (an option flag as `--name=value`, a boolean as `--name` or `--no-name`, a redacted or undeclared flag as its name only), and the payload carries a success flag plus, on failure, a closed failure kind (an engine error kind, or usage, auth-missing, permission-denied, resource-not-found, request-failed, config-invalid, definition-file-invalid, or other)',
7
+ });
8
+ export const WorkflowDefinitionShared = defineEvent({
9
+ name: 'Workflows CLI Definition Shared',
10
+ version: 1,
11
+ description: 'A newly created workflow definition version was donated to Sanity. Content-free marker: the content hash plus the same structural counts Workflows Engine Definition Deployed carries — the document itself goes to the first-party definition-feedback endpoint, never through telemetry.',
12
+ });
13
+ export const WorkflowDefinitionSharingDecided = defineEvent({
14
+ name: 'Workflows CLI Definition Sharing Decided',
15
+ version: 2,
16
+ description: 'One per deploy invocation that created new definition versions: whether donation followed the default or an explicit flag, whether anything reached the endpoint, and how many versions were eligible. Content-free — measures the true opt-out rate without ever carrying the document.',
17
+ });
18
+ const OFF = { kind: 'off', logger: noopTelemetry };
19
+ let session;
20
+ export function cliTelemetry() {
21
+ return session?.telemetry ?? OFF;
22
+ }
23
+ export function setCliTelemetry(telemetry, context) {
24
+ const trace = telemetry.kind === 'builtin'
25
+ ? telemetry.store.logger.trace(WorkflowCliCommandExecuted, context)
26
+ : undefined;
27
+ trace?.start();
28
+ session = { telemetry, context, trace };
29
+ }
30
+ export function clearCliTelemetry() {
31
+ session = undefined;
32
+ }
33
+ export function createBuiltinTelemetry(args) {
34
+ const { client, projectId, env, forceSend = false, packageVersion } = args;
35
+ const envDenied = isTelemetryEnvDenied(env);
36
+ const store = createBatchedStore(createSessionId(), createTelemetryIntake({
37
+ client,
38
+ projectId: projectId ?? '',
39
+ denied: forceSend ? false : envDenied,
40
+ context: {
41
+ surface: 'cli',
42
+ environment: _resolveTelemetryEnvironment(env.NODE_ENV, 'production'),
43
+ ...(packageVersion !== undefined ? { packageVersion } : {}),
44
+ },
45
+ }));
46
+ return { kind: 'builtin', logger: store.logger, store, envDenied, forceSend };
47
+ }
48
+ function traceAsLogEvent(trace) {
49
+ const { name, version, description } = trace;
50
+ return { type: 'log', name, version, description };
51
+ }
52
+ const FLUSH_DEADLINE_MS = 3_000;
53
+ export async function raceWithDeadline(work, deadlineMs) {
54
+ let deadline;
55
+ try {
56
+ return await Promise.race([
57
+ work,
58
+ new Promise((resolve) => {
59
+ deadline = setTimeout(() => resolve(undefined), deadlineMs);
60
+ }),
61
+ ]);
62
+ }
63
+ finally {
64
+ clearTimeout(deadline);
65
+ }
66
+ }
67
+ export async function finishCliTelemetry(result) {
68
+ if (session === undefined)
69
+ return;
70
+ const { telemetry, context, trace } = session;
71
+ if (telemetry.kind === 'provided') {
72
+ telemetry.logger.log(traceAsLogEvent(WorkflowCliCommandExecuted), {
73
+ ...context,
74
+ ...result,
75
+ });
76
+ return;
77
+ }
78
+ if (trace !== undefined) {
79
+ trace.log(result);
80
+ trace.complete();
81
+ session = { ...session, trace: undefined };
82
+ }
83
+ const { store } = telemetry;
84
+ try {
85
+ await raceWithDeadline(store.flush(), FLUSH_DEADLINE_MS);
86
+ }
87
+ finally {
88
+ store.end();
89
+ }
90
+ }
@@ -0,0 +1,88 @@
1
+ import { styleText } from 'node:util';
2
+ import { type ActivityStatus, type WorkflowResource } from '@sanity/workflows';
3
+ /**
4
+ * A bold `Title:` section heading. Mirrors the Sanity CLI's `sectionHeader`
5
+ * (name + shape) so it folds into the shared helper when this CLI merges in.
6
+ */
7
+ export declare function sectionHeader(title: string): string;
8
+ /**
9
+ * Wraps `lines` to `width` columns, keeping each line's indent (its leading
10
+ * spaces and a list glyph) as the hanging indent of its continuation lines,
11
+ * so a wrapped line stays at its level. Lines pass through untouched when
12
+ * `width` is undefined.
13
+ */
14
+ export declare function wrapLines(lines: readonly string[], width: number | undefined): string[];
15
+ /** The column count of the terminal on stdout; `undefined` when stdout is
16
+ * not a terminal, so piped output is never wrapped. */
17
+ export declare function terminalWidth(): number | undefined;
18
+ /** `1 guard`, `2 guards`: a count with its noun, regular plurals only. */
19
+ export declare function pluralize(count: number, noun: string): string;
20
+ /**
21
+ * A ` key: value` detail row — a dim, padded key then the value. Mirrors
22
+ * the Sanity CLI's `formatKeyValue` so it folds into the shared helper on
23
+ * merge; pass `padTo` (the longest key's length) to align a block of rows.
24
+ *
25
+ * Pass `emphasis` (a {@link styleText} colour) to render the whole row — key
26
+ * and value together — bold in that colour instead of the dim-key default, so
27
+ * a standout row (a terminal instance status) pops from the neutral rows.
28
+ */
29
+ export declare function formatKeyValue({ key, value, indent, padTo, emphasis, }: {
30
+ key: string;
31
+ value: string;
32
+ indent?: number;
33
+ padTo?: number;
34
+ emphasis?: Parameters<typeof styleText>[0];
35
+ }): string;
36
+ /**
37
+ * A borderless column table as printable lines: cyan header row, every
38
+ * column padded to its widest cell, columns joined by three spaces.
39
+ * Mirrors the Sanity CLI's list-table shape (see `projects list`) so it
40
+ * folds into the shared helper when this CLI merges in. Widths count
41
+ * visible characters, so a pre-styled (ANSI) cell still pads correctly.
42
+ */
43
+ export declare function formatTable(headers: string[], rows: string[][]): string[];
44
+ /**
45
+ * Clip a probe-fetched result back to `limit`. The list query builders
46
+ * fetch one row past the display limit; when that probe row comes back,
47
+ * `note` carries the dim "showing the first N" hint to print under the table.
48
+ */
49
+ export declare function clipToLimit<T>(rows: T[], limit: number): {
50
+ rows: T[];
51
+ note?: string;
52
+ };
53
+ /**
54
+ * The shared tail of a list command: {@link clipToLimit} the probe-fetched
55
+ * rows, render them through {@link formatTable}, print every line, and print
56
+ * the clip note (when present) beneath the table.
57
+ */
58
+ export declare function logClippedTable<T>({ rows, limit, moreAvailable, headers, toCells, log, }: {
59
+ rows: T[];
60
+ limit: number;
61
+ moreAvailable?: boolean;
62
+ headers: string[];
63
+ toCells: (row: T) => string[];
64
+ log: (line: string) => void;
65
+ }): void;
66
+ /**
67
+ * The `▸ label` banner printed above a group's output when a run spans
68
+ * several groups (deployments for deploy, resources for fanned-out reads),
69
+ * so each block is attributable. `undefined` for a lone group — it keeps its
70
+ * original unprefixed output. A leading blank line separates every group
71
+ * after the first.
72
+ */
73
+ export declare function groupBanner({ label, index, total, }: {
74
+ label: string;
75
+ index: number;
76
+ total: number;
77
+ }): string | undefined;
78
+ /** Where a read looked, for an empty result: `in partition prod of acme.workflows (deployment prod)`. */
79
+ export declare function searchedScope(args: {
80
+ partition: string | undefined;
81
+ resources: readonly WorkflowResource[];
82
+ deployment: string | undefined;
83
+ }): string;
84
+ /** Status glyph per activity state. log-symbols ship pre-colored (green ✔, red ✖),
85
+ * so those need no extra wrap; the rest carry their own state color. */
86
+ export declare const activityIcon: Record<ActivityStatus, string>;
87
+ /** Advisory warnings indented beneath the definition line they belong to. */
88
+ export declare function warningLines(warnings: readonly string[] | undefined): string[];
package/dist/lib/ui.js ADDED
@@ -0,0 +1,114 @@
1
+ import { stripVTControlCharacters, styleText } from 'node:util';
2
+ import { describeResource } from '@sanity/workflows';
3
+ import logSymbols from 'log-symbols';
4
+ import wrapAnsi from 'wrap-ansi';
5
+ export function sectionHeader(title) {
6
+ return styleText('bold', `${title}:`);
7
+ }
8
+ const MIN_WRAP_WIDTH = 40;
9
+ const LIST_GLYPHS = new Set(['→', '▸', ...Object.values(logSymbols)].map((glyph) => stripVTControlCharacters(glyph)));
10
+ export function wrapLines(lines, width) {
11
+ if (width === undefined)
12
+ return [...lines];
13
+ return lines.flatMap((line) => wrapLine(line, width));
14
+ }
15
+ export function terminalWidth() {
16
+ return process.stdout.isTTY ? process.stdout.columns : undefined;
17
+ }
18
+ function wrapLine(line, width) {
19
+ const hang = hangingIndent(line);
20
+ const [prefix, body] = splitAtVisibleColumn(line, hang.length);
21
+ const wrapped = wrapAnsi(body, Math.max(width - hang.length, MIN_WRAP_WIDTH), { trim: false });
22
+ return wrapped
23
+ .split('\n')
24
+ .map((part, index) => (index === 0 ? prefix + part : hang + part.trimStart()).trimEnd());
25
+ }
26
+ function splitAtVisibleColumn(line, columns) {
27
+ let index = 0;
28
+ let seen = 0;
29
+ while (seen < columns && index < line.length) {
30
+ const escape = styleEscapeLength(line, index);
31
+ if (escape > 0) {
32
+ index += escape;
33
+ continue;
34
+ }
35
+ index += String.fromCodePoint(line.codePointAt(index) ?? 0).length;
36
+ seen += 1;
37
+ }
38
+ return [line.slice(0, index), line.slice(index)];
39
+ }
40
+ const ESCAPE = 0x1b;
41
+ function styleEscapeLength(line, index) {
42
+ if (line.charCodeAt(index) !== ESCAPE || line[index + 1] !== '[')
43
+ return 0;
44
+ const end = line.indexOf('m', index);
45
+ return end === -1 ? 0 : end - index + 1;
46
+ }
47
+ function hangingIndent(line) {
48
+ const [, spaces = '', glyph] = /^( *)(?:(\S) )?/.exec(stripVTControlCharacters(line)) ?? [];
49
+ const glyphWidth = glyph !== undefined && LIST_GLYPHS.has(glyph) ? 2 : 0;
50
+ return ' '.repeat(spaces.length + glyphWidth);
51
+ }
52
+ export function pluralize(count, noun) {
53
+ return `${count} ${noun}${count === 1 ? '' : 's'}`;
54
+ }
55
+ export function formatKeyValue({ key, value, indent = 2, padTo = 0, emphasis, }) {
56
+ const paddedKey = `${key}:`.padEnd(padTo > 0 ? padTo + 1 : key.length + 1);
57
+ const pad = ' '.repeat(indent);
58
+ if (emphasis) {
59
+ return `${pad}${styleText('bold', styleText(emphasis, `${paddedKey} ${value}`))}`;
60
+ }
61
+ return `${pad}${styleText('dim', paddedKey)} ${value}`;
62
+ }
63
+ export function formatTable(headers, rows) {
64
+ const width = (cell) => stripVTControlCharacters(cell).length;
65
+ const widths = headers.map((header, i) => Math.max(width(header), ...rows.map((row) => width(row[i] ?? ''))));
66
+ const formatRow = (row) => widths
67
+ .map((columnWidth, i) => {
68
+ const cell = row[i] ?? '';
69
+ return cell + ' '.repeat(columnWidth - width(cell));
70
+ })
71
+ .join(' ')
72
+ .trimEnd();
73
+ return [styleText('cyan', formatRow(headers)), ...rows.map(formatRow)];
74
+ }
75
+ export function clipToLimit(rows, limit) {
76
+ if (rows.length <= limit) {
77
+ return { rows };
78
+ }
79
+ return {
80
+ rows: rows.slice(0, limit),
81
+ note: styleText('dim', `showing the first ${limit} — raise --limit to see more`),
82
+ };
83
+ }
84
+ export function logClippedTable({ rows, limit, moreAvailable, headers, toCells, log, }) {
85
+ const { rows: clipped, note } = clipToLimit(rows, limit);
86
+ for (const line of formatTable(headers, clipped.map(toCells))) {
87
+ log(line);
88
+ }
89
+ if (note || moreAvailable) {
90
+ log(note ??
91
+ styleText('dim', `searched the first ${limit} candidates — raise --limit to see more`));
92
+ }
93
+ }
94
+ export function groupBanner({ label, index, total, }) {
95
+ if (total <= 1) {
96
+ return undefined;
97
+ }
98
+ const gap = index > 0 ? '\n' : '';
99
+ return `${gap}${styleText('bold', `▸ ${label}`)}`;
100
+ }
101
+ export function searchedScope(args) {
102
+ const partition = args.partition === undefined ? 'any partition' : `partition ${args.partition}`;
103
+ const deployment = args.deployment === undefined ? '' : ` (deployment ${args.deployment})`;
104
+ return `in ${partition} of ${args.resources.map(describeResource).join(', ')}${deployment}`;
105
+ }
106
+ export const activityIcon = {
107
+ done: logSymbols.success,
108
+ active: styleText('cyan', '●'),
109
+ failed: logSymbols.error,
110
+ skipped: styleText('dim', '⊘'),
111
+ };
112
+ export function warningLines(warnings) {
113
+ return (warnings ?? []).map((w) => ` ${logSymbols.warning} ${w}`);
114
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * First argv tokens that belong under {@link WORKFLOWS_TOPIC}.
3
+ * Keep in sync with `src/commands/workflows/` (top-level command
4
+ * files plus the `blueprints`, `codemod`, and `definitions` subtopic directories).
5
+ */
6
+ export declare const STANDALONE_ROOT_COMMANDS: readonly ['abort', 'blueprints', 'codemod', 'definitions', 'deploy', 'diagnose', 'fire-action', 'list', 'nuke', 'reset-activity', 'show', 'start', 'tail', 'whoami'];
7
+ /** Index of the first argv token that is not a flag (and not `--`). */
8
+ export declare function firstPositionalIndex(args: string[]): number;
9
+ /**
10
+ * Rewrite standalone CLI args so short forms resolve to topic-scoped command
11
+ * ids. Idempotent when the topic is already present. Unknown first tokens are
12
+ * left alone so oclif's own "command not found" path still runs.
13
+ */
14
+ export declare function rewriteStandaloneArgv(args: string[]): string[];
@@ -0,0 +1,57 @@
1
+ import { WORKFLOWS_TOPIC } from './command-ids.js';
2
+ export const STANDALONE_ROOT_COMMANDS = [
3
+ 'abort',
4
+ 'blueprints',
5
+ 'codemod',
6
+ 'definitions',
7
+ 'deploy',
8
+ 'diagnose',
9
+ 'fire-action',
10
+ 'list',
11
+ 'nuke',
12
+ 'reset-activity',
13
+ 'show',
14
+ 'start',
15
+ 'tail',
16
+ 'whoami',
17
+ ];
18
+ const STANDALONE_ALIAS_ROOTS = ['blueprint', 'definition'];
19
+ const rootCommandSet = new Set([...STANDALONE_ROOT_COMMANDS, ...STANDALONE_ALIAS_ROOTS]);
20
+ export function firstPositionalIndex(args) {
21
+ for (let i = 0; i < args.length; i++) {
22
+ const token = args[i];
23
+ if (token === undefined)
24
+ continue;
25
+ if (token === '--')
26
+ return i + 1 < args.length ? i + 1 : -1;
27
+ if (!token.startsWith('-'))
28
+ return i;
29
+ }
30
+ return -1;
31
+ }
32
+ function stripScriptArgSeparator(args) {
33
+ return args[0] === '--' ? args.slice(1) : args;
34
+ }
35
+ export function rewriteStandaloneArgv(args) {
36
+ const normalized = stripScriptArgSeparator(args);
37
+ const i = firstPositionalIndex(normalized);
38
+ if (i === -1)
39
+ return normalized;
40
+ const first = normalized[i];
41
+ if (first === undefined || first === WORKFLOWS_TOPIC)
42
+ return normalized;
43
+ if (first === 'help') {
44
+ const commandIndex = firstPositionalIndex(normalized.slice(i + 1));
45
+ if (commandIndex === -1)
46
+ return normalized;
47
+ const absolute = i + 1 + commandIndex;
48
+ const command = normalized[absolute];
49
+ if (command === undefined || command === WORKFLOWS_TOPIC || !rootCommandSet.has(command)) {
50
+ return normalized;
51
+ }
52
+ return [...normalized.slice(0, absolute), WORKFLOWS_TOPIC, ...normalized.slice(absolute)];
53
+ }
54
+ if (!rootCommandSet.has(first))
55
+ return normalized;
56
+ return [...normalized.slice(0, i), WORKFLOWS_TOPIC, ...normalized.slice(i)];
57
+ }