@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.
- package/CHANGELOG.md +1981 -0
- package/LICENSE +21 -0
- package/README.md +848 -2
- package/bin/run.js +8 -0
- package/dist/command-ids.d.ts +10 -0
- package/dist/command-ids.js +10 -0
- package/dist/commands/workflows/abort.d.ts +29 -0
- package/dist/commands/workflows/abort.js +50 -0
- package/dist/commands/workflows/blueprints/generate.d.ts +12 -0
- package/dist/commands/workflows/blueprints/generate.js +46 -0
- package/dist/commands/workflows/codemod/packages.d.ts +13 -0
- package/dist/commands/workflows/codemod/packages.js +41 -0
- package/dist/commands/workflows/definitions/delete.d.ts +44 -0
- package/dist/commands/workflows/definitions/delete.js +74 -0
- package/dist/commands/workflows/definitions/diff.d.ts +23 -0
- package/dist/commands/workflows/definitions/diff.js +55 -0
- package/dist/commands/workflows/definitions/list.d.ts +52 -0
- package/dist/commands/workflows/definitions/list.js +139 -0
- package/dist/commands/workflows/definitions/show.d.ts +66 -0
- package/dist/commands/workflows/definitions/show.js +129 -0
- package/dist/commands/workflows/definitions/validate.d.ts +14 -0
- package/dist/commands/workflows/definitions/validate.js +50 -0
- package/dist/commands/workflows/deploy.d.ts +117 -0
- package/dist/commands/workflows/deploy.js +266 -0
- package/dist/commands/workflows/diagnose.d.ts +53 -0
- package/dist/commands/workflows/diagnose.js +195 -0
- package/dist/commands/workflows/fire-action.d.ts +53 -0
- package/dist/commands/workflows/fire-action.js +182 -0
- package/dist/commands/workflows/list.d.ts +79 -0
- package/dist/commands/workflows/list.js +249 -0
- package/dist/commands/workflows/nuke.d.ts +73 -0
- package/dist/commands/workflows/nuke.js +175 -0
- package/dist/commands/workflows/reset-activity.d.ts +32 -0
- package/dist/commands/workflows/reset-activity.js +60 -0
- package/dist/commands/workflows/show.d.ts +30 -0
- package/dist/commands/workflows/show.js +156 -0
- package/dist/commands/workflows/start.d.ts +57 -0
- package/dist/commands/workflows/start.js +196 -0
- package/dist/commands/workflows/tail.d.ts +24 -0
- package/dist/commands/workflows/tail.js +83 -0
- package/dist/commands/workflows/whoami.d.ts +16 -0
- package/dist/commands/workflows/whoami.js +53 -0
- package/dist/help.d.ts +13 -0
- package/dist/help.js +50 -0
- package/dist/hooks/finally/telemetry.d.ts +3 -0
- package/dist/hooks/finally/telemetry.js +10 -0
- package/dist/hooks/prerun/telemetry.d.ts +33 -0
- package/dist/hooks/prerun/telemetry.js +52 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/lib/base-command.d.ts +14 -0
- package/dist/lib/base-command.js +41 -0
- package/dist/lib/blueprint-emit.d.ts +56 -0
- package/dist/lib/blueprint-emit.js +233 -0
- package/dist/lib/blueprint-needs.d.ts +5 -0
- package/dist/lib/blueprint-needs.js +284 -0
- package/dist/lib/blueprint-stacks.d.ts +6 -0
- package/dist/lib/blueprint-stacks.js +118 -0
- package/dist/lib/cause-detail.d.ts +9 -0
- package/dist/lib/cause-detail.js +112 -0
- package/dist/lib/client.d.ts +27 -0
- package/dist/lib/client.js +45 -0
- package/dist/lib/codemod/ast.d.ts +17 -0
- package/dist/lib/codemod/ast.js +14 -0
- package/dist/lib/codemod/export-rename.d.ts +19 -0
- package/dist/lib/codemod/export-rename.js +337 -0
- package/dist/lib/codemod/manifest-rewrite.d.ts +17 -0
- package/dist/lib/codemod/manifest-rewrite.js +133 -0
- package/dist/lib/codemod/package-map.d.ts +27 -0
- package/dist/lib/codemod/package-map.js +99 -0
- package/dist/lib/codemod/report.d.ts +4 -0
- package/dist/lib/codemod/report.js +51 -0
- package/dist/lib/codemod/run.d.ts +25 -0
- package/dist/lib/codemod/run.js +108 -0
- package/dist/lib/codemod/source-rewrite.d.ts +20 -0
- package/dist/lib/codemod/source-rewrite.js +150 -0
- package/dist/lib/command-context.d.ts +20 -0
- package/dist/lib/command-context.js +24 -0
- package/dist/lib/command-telemetry.d.ts +54 -0
- package/dist/lib/command-telemetry.js +82 -0
- package/dist/lib/context.d.ts +151 -0
- package/dist/lib/context.js +263 -0
- package/dist/lib/default-partition.d.ts +23 -0
- package/dist/lib/default-partition.js +47 -0
- package/dist/lib/definition-files.d.ts +14 -0
- package/dist/lib/definition-files.js +60 -0
- package/dist/lib/definitions.d.ts +63 -0
- package/dist/lib/definitions.js +84 -0
- package/dist/lib/diff.d.ts +12 -0
- package/dist/lib/diff.js +93 -0
- package/dist/lib/env.d.ts +7 -0
- package/dist/lib/env.js +8 -0
- package/dist/lib/fail.d.ts +36 -0
- package/dist/lib/fail.js +55 -0
- package/dist/lib/failure-kind.d.ts +7 -0
- package/dist/lib/failure-kind.js +66 -0
- package/dist/lib/flags.d.ts +53 -0
- package/dist/lib/flags.js +127 -0
- package/dist/lib/follow-up-command.d.ts +18 -0
- package/dist/lib/follow-up-command.js +12 -0
- package/dist/lib/history-rows.d.ts +3 -0
- package/dist/lib/history-rows.js +44 -0
- package/dist/lib/load-config.d.ts +51 -0
- package/dist/lib/load-config.js +108 -0
- package/dist/lib/nuke.d.ts +124 -0
- package/dist/lib/nuke.js +206 -0
- package/dist/lib/operation-args.d.ts +42 -0
- package/dist/lib/operation-args.js +21 -0
- package/dist/lib/ops-report.d.ts +45 -0
- package/dist/lib/ops-report.js +31 -0
- package/dist/lib/params.d.ts +3 -0
- package/dist/lib/params.js +21 -0
- package/dist/lib/pick-resource.d.ts +13 -0
- package/dist/lib/pick-resource.js +82 -0
- package/dist/lib/prompt.d.ts +35 -0
- package/dist/lib/prompt.js +11 -0
- package/dist/lib/read-fanout.d.ts +45 -0
- package/dist/lib/read-fanout.js +45 -0
- package/dist/lib/resource-target.d.ts +10 -0
- package/dist/lib/resource-target.js +12 -0
- package/dist/lib/select-deployment.d.ts +31 -0
- package/dist/lib/select-deployment.js +91 -0
- package/dist/lib/share-definitions.d.ts +101 -0
- package/dist/lib/share-definitions.js +188 -0
- package/dist/lib/telemetry-setup.d.ts +77 -0
- package/dist/lib/telemetry-setup.js +117 -0
- package/dist/lib/telemetry.d.ts +81 -0
- package/dist/lib/telemetry.js +90 -0
- package/dist/lib/ui.d.ts +88 -0
- package/dist/lib/ui.js +114 -0
- package/dist/standalone-argv.d.ts +14 -0
- package/dist/standalone-argv.js +57 -0
- package/oclif.manifest.json +1894 -0
- package/package.json +118 -3
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { type WorkflowClient, type WorkflowDeployment, type WorkflowResource } from '@sanity/workflows';
|
|
2
|
+
/** A resource a nuke may delete from, with the client that reads/writes it and
|
|
3
|
+
* whether it is the engine's own resource — the only one that holds instances
|
|
4
|
+
* and definitions (guards can co-locate with subjects in any resource). */
|
|
5
|
+
export interface NukeTarget {
|
|
6
|
+
resource: WorkflowResource;
|
|
7
|
+
client: WorkflowClient;
|
|
8
|
+
holdsEngineDocs: boolean;
|
|
9
|
+
}
|
|
10
|
+
/** One resolved resource of a {@link NukePlan}: the ids to delete, by doc type. */
|
|
11
|
+
export interface NukeResourcePlan {
|
|
12
|
+
resource: WorkflowResource;
|
|
13
|
+
/** The `<type>:<id>` resource address the plan shows this resource as, and,
|
|
14
|
+
* in tag mode, the one the operator confirms by: it holds no whitespace. */
|
|
15
|
+
label: string;
|
|
16
|
+
client: WorkflowClient;
|
|
17
|
+
holdsEngineDocs: boolean;
|
|
18
|
+
instanceIds: string[];
|
|
19
|
+
definitionIds: string[];
|
|
20
|
+
guardIds: string[];
|
|
21
|
+
}
|
|
22
|
+
/** Which selector resolved a plan. Decides the delete wave order — see
|
|
23
|
+
* {@link WAVE_ORDER} — so it travels with the plan rather than being re-derived. */
|
|
24
|
+
export type NukeMode = 'partition' | 'instance';
|
|
25
|
+
export interface NukePlan {
|
|
26
|
+
partition: string;
|
|
27
|
+
mode: NukeMode;
|
|
28
|
+
resources: NukeResourcePlan[];
|
|
29
|
+
}
|
|
30
|
+
/** Per-doc-type totals across the whole plan, plus the count of resources that
|
|
31
|
+
* actually hold something to delete ({@link involvedTargets}). */
|
|
32
|
+
export interface PlanCounts {
|
|
33
|
+
instances: number;
|
|
34
|
+
definitions: number;
|
|
35
|
+
guards: number;
|
|
36
|
+
datasets: number;
|
|
37
|
+
total: number;
|
|
38
|
+
}
|
|
39
|
+
/** Every resource a deployment's nuke sweeps: its own workflow resource (which
|
|
40
|
+
* holds instances + definitions + guards) plus each alias-bound resource
|
|
41
|
+
* (guards co-locate with the subjects they lock). */
|
|
42
|
+
export declare function sweptResources(deployment: WorkflowDeployment): WorkflowResource[];
|
|
43
|
+
/**
|
|
44
|
+
* Fail before any nuke work when another same-tag deployment sweeps a resource
|
|
45
|
+
* the selected one does. Guard document ids embed only the partition
|
|
46
|
+
* (`temp.system.guard.<tag>.wf-instance.*`), so within a shared resource the
|
|
47
|
+
* sweep cannot tell such deployments' guards apart — nuking one would delete
|
|
48
|
+
* the others' live locks, invisibly to the plan. Config validation already
|
|
49
|
+
* forbids sharing tag + workflow resource, so an overlap can only arrive
|
|
50
|
+
* through alias bindings.
|
|
51
|
+
*/
|
|
52
|
+
export declare function refuseOverlappingNuke(deployments: WorkflowDeployment[], selected: WorkflowDeployment): void;
|
|
53
|
+
/**
|
|
54
|
+
* Resolve what a tag-scoped nuke would delete, per resource — the dry-run plan
|
|
55
|
+
* printed before any deletion. Instances and definitions are read only from the
|
|
56
|
+
* engine's own resource; guards are read from every target, since a guard
|
|
57
|
+
* co-locates with the subject it locks and may live in a foreign dataset.
|
|
58
|
+
*
|
|
59
|
+
* Every read uses the raw perspective, so a draft-form or otherwise
|
|
60
|
+
* perspective-hidden copy is still surfaced (and swept).
|
|
61
|
+
*/
|
|
62
|
+
export declare function resolveNukePlan(args: {
|
|
63
|
+
partition: string;
|
|
64
|
+
targets: NukeTarget[];
|
|
65
|
+
}): Promise<NukePlan>;
|
|
66
|
+
/** An instance a caller has already located: its id plus the resource whose
|
|
67
|
+
* document the locate actually read. The plan derives its instance row from
|
|
68
|
+
* that resource rather than assuming the engine one holds it, so a plan can
|
|
69
|
+
* only ever claim an instance the caller really found. */
|
|
70
|
+
export interface LocatedInstance {
|
|
71
|
+
id: string;
|
|
72
|
+
resource: WorkflowResource;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Resolve what deleting ONE located instance sweeps, per resource — the
|
|
76
|
+
* single-instance sibling of {@link resolveNukePlan}. The instance document is
|
|
77
|
+
* deleted from the resource that held it; its guards are read from every target,
|
|
78
|
+
* since a guard co-locates with the subject it locks and may live in an
|
|
79
|
+
* alias-bound dataset. Definitions are never in scope. Raw perspective, like the
|
|
80
|
+
* tag-scoped plan.
|
|
81
|
+
*/
|
|
82
|
+
export declare function resolveInstanceNukePlan(args: {
|
|
83
|
+
instance: LocatedInstance;
|
|
84
|
+
partition: string;
|
|
85
|
+
targets: NukeTarget[];
|
|
86
|
+
}): Promise<NukePlan>;
|
|
87
|
+
/** The `<type>:<id>` labels of resources the plan actually deletes from. A
|
|
88
|
+
* resource with nothing to delete is not "involved" and is omitted. Tag mode
|
|
89
|
+
* makes the operator type this set back; instance mode confirms with a plain
|
|
90
|
+
* y/N and consumes it only for the dataset count in its summary. */
|
|
91
|
+
export declare function involvedTargets(plan: NukePlan): string[];
|
|
92
|
+
/** Roll the plan up into per-doc-type totals for the summary and the
|
|
93
|
+
* nothing-to-do short-circuit. */
|
|
94
|
+
export declare function planCounts(plan: NukePlan): PlanCounts;
|
|
95
|
+
/**
|
|
96
|
+
* Does the operator's typed confirmation name every involved target, and only
|
|
97
|
+
* those? Order-independent, whitespace-tolerant set equality: the operator
|
|
98
|
+
* pastes back all `<type>:<id>` targets the plan listed.
|
|
99
|
+
*/
|
|
100
|
+
export declare function confirmationMatches(input: string, targets: string[]): boolean;
|
|
101
|
+
/** The dry-run plan as printable lines: a heading, the content-safety
|
|
102
|
+
* invariant, the API host the deletes will hit (plan rows alone can't tell
|
|
103
|
+
* same-named projects on different environments apart), and a per-resource,
|
|
104
|
+
* per-doc-type count table. A guard-only foreign resource shows `—` for the
|
|
105
|
+
* engine-only columns, since those docs can't live there. */
|
|
106
|
+
export declare function renderNukePlan(plan: NukePlan, { apiHost, heading }: {
|
|
107
|
+
apiHost: string;
|
|
108
|
+
heading?: string;
|
|
109
|
+
}): string[];
|
|
110
|
+
/** The line printed before a partition delete is confirmed or forced. */
|
|
111
|
+
export declare function formatNukePreview(partition: string, counts: PlanCounts): string;
|
|
112
|
+
/** The success line for a partition delete. */
|
|
113
|
+
export declare function formatNukeSummary(partition: string, counts: PlanCounts): string;
|
|
114
|
+
/** The success line for a single-instance delete; guards are named only when some were deleted. */
|
|
115
|
+
export declare function formatInstanceNukeSummary(instanceId: string, counts: Pick<PlanCounts, 'guards'>): string;
|
|
116
|
+
/**
|
|
117
|
+
* Delete exactly what the plan printed, in uniform waves over every resource,
|
|
118
|
+
* ordered by the plan's mode ({@link WAVE_ORDER}). Non-engine resources simply
|
|
119
|
+
* carry empty instance/definition lists. Idempotent: an empty plan deletes
|
|
120
|
+
* nothing.
|
|
121
|
+
*/
|
|
122
|
+
export declare function executeNuke(plan: NukePlan): Promise<void>;
|
|
123
|
+
/** The `definitions:` line under the plan table; undefined when there are no definitions. */
|
|
124
|
+
export declare function definitionNamesLine(definitionIds: string[]): string | undefined;
|
package/dist/lib/nuke.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { styleText } from 'node:util';
|
|
2
|
+
import { GUARD_DOC_TYPE, partitionScopeFilter, resourceGdr, WORKFLOW_DEFINITION_TYPE, WORKFLOW_INSTANCE_TYPE, } from '@sanity/workflows';
|
|
3
|
+
import { fail } from './fail.js';
|
|
4
|
+
import { deploymentLabel } from './select-deployment.js';
|
|
5
|
+
import { formatTable, pluralize, sectionHeader } from './ui.js';
|
|
6
|
+
const CHUNK = 200;
|
|
7
|
+
const DEFINITION_ID_TAIL = /([^.]+)\.v(\d+)$/;
|
|
8
|
+
const REQUEST_TAG = 'nuke';
|
|
9
|
+
export function sweptResources(deployment) {
|
|
10
|
+
return [
|
|
11
|
+
deployment.workflowResource,
|
|
12
|
+
...(deployment.resourceAliases ?? []).map((binding) => binding.resource),
|
|
13
|
+
];
|
|
14
|
+
}
|
|
15
|
+
export function refuseOverlappingNuke(deployments, selected) {
|
|
16
|
+
const swept = new Set(sweptResources(selected).map(resourceGdr));
|
|
17
|
+
const clashing = deployments.filter((candidate) => candidate.name !== selected.name &&
|
|
18
|
+
candidate.partition === selected.partition &&
|
|
19
|
+
sweptResources(candidate).some((resource) => swept.has(resourceGdr(resource))));
|
|
20
|
+
if (clashing.length === 0) {
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
fail(`Refusing to nuke "${deploymentLabel(selected)}" — its guards are indistinguishable ` +
|
|
24
|
+
`from ${clashing.map(deploymentLabel).join(', ')}'s in the shared resource(s).`, `Guard ids embed only the partition, and these deployments share partition "${selected.partition}" plus ` +
|
|
25
|
+
"a swept resource — the sweep would delete the other deployments' live guards. " +
|
|
26
|
+
'Give them distinct partitions first.');
|
|
27
|
+
}
|
|
28
|
+
export async function resolveNukePlan(args) {
|
|
29
|
+
const { partition, targets } = args;
|
|
30
|
+
const resources = await Promise.all(targets.map((target) => resolveResourcePlan({ partition, target })));
|
|
31
|
+
return { partition, mode: 'partition', resources };
|
|
32
|
+
}
|
|
33
|
+
async function resolveResourcePlan(args) {
|
|
34
|
+
const { partition, target } = args;
|
|
35
|
+
const { client, holdsEngineDocs } = target;
|
|
36
|
+
const noIds = [];
|
|
37
|
+
const [instanceIds, definitionIds, guardIds] = await Promise.all([
|
|
38
|
+
holdsEngineDocs ? engineDocIds({ client, type: WORKFLOW_INSTANCE_TYPE, partition }) : noIds,
|
|
39
|
+
holdsEngineDocs ? engineDocIds({ client, type: WORKFLOW_DEFINITION_TYPE, partition }) : noIds,
|
|
40
|
+
partitionGuardIds({ client, partition }),
|
|
41
|
+
]);
|
|
42
|
+
return resourcePlan(target, { instanceIds, definitionIds, guardIds });
|
|
43
|
+
}
|
|
44
|
+
function resourcePlan(target, ids) {
|
|
45
|
+
return {
|
|
46
|
+
resource: target.resource,
|
|
47
|
+
label: resourceGdr(target.resource),
|
|
48
|
+
client: target.client,
|
|
49
|
+
holdsEngineDocs: target.holdsEngineDocs,
|
|
50
|
+
...ids,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
export async function resolveInstanceNukePlan(args) {
|
|
54
|
+
const { instance, partition, targets } = args;
|
|
55
|
+
const resources = await Promise.all(targets.map((target) => resolveInstanceResourcePlan({ instance, target })));
|
|
56
|
+
return { partition, mode: 'instance', resources };
|
|
57
|
+
}
|
|
58
|
+
async function resolveInstanceResourcePlan(args) {
|
|
59
|
+
const { instance, target } = args;
|
|
60
|
+
const guardIds = await instanceGuardIds({ client: target.client, instanceId: instance.id });
|
|
61
|
+
const holdsInstance = resourceGdr(target.resource) === resourceGdr(instance.resource);
|
|
62
|
+
return resourcePlan(target, {
|
|
63
|
+
instanceIds: holdsInstance ? [instance.id] : [],
|
|
64
|
+
definitionIds: [],
|
|
65
|
+
guardIds,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
function instanceGuardIds(args) {
|
|
69
|
+
return guardIdsMatching({
|
|
70
|
+
client: args.client,
|
|
71
|
+
match: 'sourceInstanceId == $instanceId || string::startsWith(_id, $guardIdPrefix)',
|
|
72
|
+
params: {
|
|
73
|
+
instanceId: args.instanceId,
|
|
74
|
+
guardIdPrefix: `${GUARD_DOC_TYPE}.${args.instanceId}.`,
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
function engineDocIds(args) {
|
|
79
|
+
return args.client.fetch(`*[_type == $type && ${partitionScopeFilter()}]._id`, { type: args.type, tag: args.partition }, { perspective: 'raw', tag: REQUEST_TAG });
|
|
80
|
+
}
|
|
81
|
+
function partitionGuardIds(args) {
|
|
82
|
+
const instancePrefix = `${args.partition}.wf-instance.`;
|
|
83
|
+
return guardIdsMatching({
|
|
84
|
+
client: args.client,
|
|
85
|
+
match: 'string::startsWith(sourceInstanceId, $instancePrefix) || string::startsWith(_id, $guardIdPrefix)',
|
|
86
|
+
params: { instancePrefix, guardIdPrefix: `${GUARD_DOC_TYPE}.${instancePrefix}` },
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
function guardIdsMatching(args) {
|
|
90
|
+
return args.client.fetch(`*[_type == $type && (${args.match})]._id`, { type: GUARD_DOC_TYPE, ...args.params }, { perspective: 'raw', tag: REQUEST_TAG });
|
|
91
|
+
}
|
|
92
|
+
export function involvedTargets(plan) {
|
|
93
|
+
return plan.resources
|
|
94
|
+
.filter((resource) => resourceTotal(resource) > 0)
|
|
95
|
+
.map((resource) => resource.label);
|
|
96
|
+
}
|
|
97
|
+
function resourceTotal(resource) {
|
|
98
|
+
return resource.instanceIds.length + resource.definitionIds.length + resource.guardIds.length;
|
|
99
|
+
}
|
|
100
|
+
export function planCounts(plan) {
|
|
101
|
+
const totals = plan.resources.reduce((acc, resource) => ({
|
|
102
|
+
instances: acc.instances + resource.instanceIds.length,
|
|
103
|
+
definitions: acc.definitions + resource.definitionIds.length,
|
|
104
|
+
guards: acc.guards + resource.guardIds.length,
|
|
105
|
+
}), { instances: 0, definitions: 0, guards: 0 });
|
|
106
|
+
return {
|
|
107
|
+
...totals,
|
|
108
|
+
datasets: involvedTargets(plan).length,
|
|
109
|
+
total: totals.instances + totals.definitions + totals.guards,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
export function confirmationMatches(input, targets) {
|
|
113
|
+
const typed = new Set(input.trim().split(/\s+/).filter(Boolean));
|
|
114
|
+
const expected = new Set(targets);
|
|
115
|
+
return typed.size === expected.size && [...expected].every((target) => typed.has(target));
|
|
116
|
+
}
|
|
117
|
+
export function renderNukePlan(plan, { apiHost, heading = `nuke — partition "${plan.partition}"` }) {
|
|
118
|
+
const rows = plan.resources.map((resource) => [
|
|
119
|
+
resource.label,
|
|
120
|
+
resource.holdsEngineDocs ? String(resource.instanceIds.length) : styleText('dim', '—'),
|
|
121
|
+
resource.holdsEngineDocs ? String(resource.definitionIds.length) : styleText('dim', '—'),
|
|
122
|
+
String(resource.guardIds.length),
|
|
123
|
+
]);
|
|
124
|
+
const definitionsLine = definitionNamesLine(plan.resources.flatMap((resource) => resource.definitionIds));
|
|
125
|
+
return [
|
|
126
|
+
sectionHeader(heading),
|
|
127
|
+
styleText('dim', 'engine-owned documents only — content is never touched'),
|
|
128
|
+
styleText('dim', `API host: ${apiHost}`),
|
|
129
|
+
...formatTable(['target', 'instances', 'definitions', 'guards'], rows),
|
|
130
|
+
...(definitionsLine === undefined ? [] : [definitionsLine]),
|
|
131
|
+
];
|
|
132
|
+
}
|
|
133
|
+
function countsPhrase(counts) {
|
|
134
|
+
const parts = [
|
|
135
|
+
[counts.instances, 'instance'],
|
|
136
|
+
[counts.definitions, 'definition'],
|
|
137
|
+
[counts.guards, 'guard'],
|
|
138
|
+
];
|
|
139
|
+
return new Intl.ListFormat('en', { type: 'conjunction' }).format(parts.filter(([count]) => count > 0).map(([count, noun]) => pluralize(count, noun)));
|
|
140
|
+
}
|
|
141
|
+
export function formatNukePreview(partition, counts) {
|
|
142
|
+
return `This will delete ${countsPhrase(counts)} from partition "${partition}".`;
|
|
143
|
+
}
|
|
144
|
+
export function formatNukeSummary(partition, counts) {
|
|
145
|
+
return `Deleted from partition "${partition}": ${countsPhrase(counts)}.`;
|
|
146
|
+
}
|
|
147
|
+
export function formatInstanceNukeSummary(instanceId, counts) {
|
|
148
|
+
if (counts.guards === 0) {
|
|
149
|
+
return `Deleted instance ${instanceId}.`;
|
|
150
|
+
}
|
|
151
|
+
const guards = counts.guards === 1 ? 'its guard' : `its ${counts.guards} guards`;
|
|
152
|
+
return `Deleted instance ${instanceId} and ${guards}.`;
|
|
153
|
+
}
|
|
154
|
+
const WAVE_ORDER = {
|
|
155
|
+
instance: ['guardIds', 'definitionIds', 'instanceIds'],
|
|
156
|
+
partition: ['instanceIds', 'definitionIds', 'guardIds'],
|
|
157
|
+
};
|
|
158
|
+
export async function executeNuke(plan) {
|
|
159
|
+
for (const idField of WAVE_ORDER[plan.mode]) {
|
|
160
|
+
for (const resource of plan.resources) {
|
|
161
|
+
await deleteIds(resource.client, resource[idField]);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
async function deleteIds(client, ids) {
|
|
166
|
+
for (let start = 0; start < ids.length; start += CHUNK) {
|
|
167
|
+
const tx = client.transaction();
|
|
168
|
+
for (const id of ids.slice(start, start + CHUNK))
|
|
169
|
+
tx.delete(id);
|
|
170
|
+
await tx.commit({ tag: REQUEST_TAG });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
function versionRanges(versions) {
|
|
174
|
+
const runs = [];
|
|
175
|
+
for (const version of [...new Set(versions)].sort((a, b) => a - b)) {
|
|
176
|
+
const run = runs.at(-1);
|
|
177
|
+
if (run !== undefined && version === run.last + 1) {
|
|
178
|
+
run.last = version;
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
runs.push({ first: version, last: version });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return runs
|
|
185
|
+
.map(({ first, last }) => (first === last ? `v${first}` : `v${first}–v${last}`))
|
|
186
|
+
.join(', ');
|
|
187
|
+
}
|
|
188
|
+
export function definitionNamesLine(definitionIds) {
|
|
189
|
+
const versionsByName = new Map();
|
|
190
|
+
for (const id of definitionIds) {
|
|
191
|
+
const [, name, version] = DEFINITION_ID_TAIL.exec(id) ?? [];
|
|
192
|
+
if (name === undefined || version === undefined) {
|
|
193
|
+
throw new Error(`Unexpected definition id "${id}"`);
|
|
194
|
+
}
|
|
195
|
+
const versions = versionsByName.get(name) ?? [];
|
|
196
|
+
versions.push(Number(version));
|
|
197
|
+
versionsByName.set(name, versions);
|
|
198
|
+
}
|
|
199
|
+
if (versionsByName.size === 0) {
|
|
200
|
+
return undefined;
|
|
201
|
+
}
|
|
202
|
+
const entries = [...versionsByName.keys()]
|
|
203
|
+
.sort()
|
|
204
|
+
.map((name) => `${name} (${versionRanges(versionsByName.get(name) ?? [])})`);
|
|
205
|
+
return `definitions: ${entries.join(', ')}`;
|
|
206
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type Engine, type EngineScopeArgs, type WorkflowClient, type OperationArgs, type WorkflowTelemetryLogger } from '@sanity/workflows';
|
|
2
|
+
/**
|
|
3
|
+
* The engine-scope a CLI verb needs: which partition and which resource
|
|
4
|
+
* the engine's own data lives in, plus the clients for the resources the
|
|
5
|
+
* deployment binds in `resourceAliases`; {@link EngineScopeArgs} minus the
|
|
6
|
+
* client. Runtime-supplied refs may target the workflow resource or an
|
|
7
|
+
* alias-bound resource. `resourceClients` is required because an engine
|
|
8
|
+
* without it accepts refs into any addressable resource.
|
|
9
|
+
*/
|
|
10
|
+
export type EngineScope = Pick<EngineScopeArgs, 'partition' | 'workflowResource'> & Required<Pick<EngineScopeArgs, 'resourceClients'>>;
|
|
11
|
+
/**
|
|
12
|
+
* The engine args every CLI verb shares: partition scope, workflow resource,
|
|
13
|
+
* the CLI's declared execution context — the advisory "via what" stamped
|
|
14
|
+
* on history; identity itself is always the token behind the client
|
|
15
|
+
* (`/users/me`), never injected — and the invocation's telemetry logger,
|
|
16
|
+
* so the engine's adoption vocabulary flows from CLI-driven operations
|
|
17
|
+
* (the raw-verb equivalent of `createEngine({telemetry})`). Spread by the
|
|
18
|
+
* instance verbs ({@link buildOperationArgs}), the definition verbs
|
|
19
|
+
* (e.g. `definitions delete`), and reads like `diagnose`.
|
|
20
|
+
*/
|
|
21
|
+
export declare function baseEngineArgs(scope: EngineScope): EngineScope & Pick<EngineScopeArgs, 'executionContext'> & {
|
|
22
|
+
telemetry: WorkflowTelemetryLogger;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* {@link baseEngineArgs} plus the instance-operation fields (everything
|
|
26
|
+
* but the client and the verb-specific fields). The `reason` is spread
|
|
27
|
+
* conditionally because the engine's optional field rejects an explicit
|
|
28
|
+
* `undefined` under `exactOptionalPropertyTypes`.
|
|
29
|
+
*/
|
|
30
|
+
export declare function buildOperationArgs({ scope, instanceId, reason, }: {
|
|
31
|
+
scope: EngineScope;
|
|
32
|
+
instanceId: string;
|
|
33
|
+
reason: string | undefined;
|
|
34
|
+
}): OperationArgs & ReturnType<typeof baseEngineArgs> & {
|
|
35
|
+
reason?: string;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* The engine the instance write commands (`start`, `fire-action`, `abort`)
|
|
39
|
+
* run their verb on. Its writes go to the project's Workflows service when
|
|
40
|
+
* the client's token cannot write instances, as for any engine.
|
|
41
|
+
*/
|
|
42
|
+
export declare function cliEngine(client: WorkflowClient, scope: EngineScope): Engine;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { createEngine, EXECUTION_KINDS, } from '@sanity/workflows';
|
|
2
|
+
import { cliTelemetry } from './telemetry.js';
|
|
3
|
+
export function baseEngineArgs(scope) {
|
|
4
|
+
return {
|
|
5
|
+
partition: scope.partition,
|
|
6
|
+
workflowResource: scope.workflowResource,
|
|
7
|
+
resourceClients: scope.resourceClients,
|
|
8
|
+
executionContext: { kind: EXECUTION_KINDS.cli, id: 'workflow-cli' },
|
|
9
|
+
telemetry: cliTelemetry().logger,
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
export function buildOperationArgs({ scope, instanceId, reason, }) {
|
|
13
|
+
return {
|
|
14
|
+
...baseEngineArgs(scope),
|
|
15
|
+
instanceId,
|
|
16
|
+
...(reason !== undefined ? { reason } : {}),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export function cliEngine(client, scope) {
|
|
20
|
+
return createEngine({ client, ...baseEngineArgs(scope) });
|
|
21
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** A single engine primitive that ran during a write commit — the
|
|
2
|
+
* reportable subset of the engine's `OpAppliedSummary`. */
|
|
3
|
+
export interface RanOp {
|
|
4
|
+
opType: string;
|
|
5
|
+
target?: {
|
|
6
|
+
scope: string;
|
|
7
|
+
field: string;
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
/** Empty when nothing ran, so callers append it unconditionally. */
|
|
11
|
+
export declare function opsAppliedLines(ranOps: RanOp[] | undefined): string[];
|
|
12
|
+
/** The subset of an engine `OperationResult` the write-verb reports read. */
|
|
13
|
+
export interface WriteOutcome {
|
|
14
|
+
changed: boolean;
|
|
15
|
+
cascaded: number;
|
|
16
|
+
instance: {
|
|
17
|
+
currentStage: string;
|
|
18
|
+
};
|
|
19
|
+
ranOps?: RanOp[];
|
|
20
|
+
}
|
|
21
|
+
/** The spinner message + ops block a write verb prints once its engine
|
|
22
|
+
* call returns. {@link opsAppliedLines} builds `opsLines`; verbs whose
|
|
23
|
+
* commits never run ops omit it. */
|
|
24
|
+
export interface WriteReport {
|
|
25
|
+
changed: boolean;
|
|
26
|
+
message: string;
|
|
27
|
+
opsLines?: string[];
|
|
28
|
+
}
|
|
29
|
+
/** The ", then cascaded N auto-transition(s)" suffix a write report appends
|
|
30
|
+
* when the commit cascaded the instance onward; empty when it didn't. */
|
|
31
|
+
export declare function cascadeTail(cascaded: number): string;
|
|
32
|
+
/**
|
|
33
|
+
* Run a write verb behind its spinner: start it, run the engine call, and
|
|
34
|
+
* emit the report — warn and bail on a no-op (`changed: false`), otherwise
|
|
35
|
+
* succeed and print the ops block. A throw fails the spinner and exits
|
|
36
|
+
* through {@link failOn}.
|
|
37
|
+
*/
|
|
38
|
+
export declare function runWriteVerb<T>({ startLabel, failLabel, failHeadline, run, report, log, }: {
|
|
39
|
+
startLabel: string;
|
|
40
|
+
failLabel: string;
|
|
41
|
+
failHeadline: string;
|
|
42
|
+
run: () => Promise<T>;
|
|
43
|
+
report: (result: T) => WriteReport;
|
|
44
|
+
log: (line: string) => void;
|
|
45
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { styleText } from 'node:util';
|
|
2
|
+
import logSymbols from 'log-symbols';
|
|
3
|
+
import ora from 'ora';
|
|
4
|
+
import { failOn } from './fail.js';
|
|
5
|
+
export function opsAppliedLines(ranOps) {
|
|
6
|
+
const details = (ranOps ?? []).map((op) => {
|
|
7
|
+
const target = op.target ? styleText('dim', ` → ${op.target.scope}.${op.target.field}`) : '';
|
|
8
|
+
return ` ${logSymbols.info} ${op.opType}${target}`;
|
|
9
|
+
});
|
|
10
|
+
return details.length > 0 ? ['', styleText('dim', 'ops applied:'), ...details] : [];
|
|
11
|
+
}
|
|
12
|
+
export function cascadeTail(cascaded) {
|
|
13
|
+
return cascaded > 0 ? `, then cascaded ${cascaded} auto-transition(s)` : '';
|
|
14
|
+
}
|
|
15
|
+
export async function runWriteVerb({ startLabel, failLabel, failHeadline, run, report, log, }) {
|
|
16
|
+
const spinner = ora(startLabel).start();
|
|
17
|
+
try {
|
|
18
|
+
const result = await run();
|
|
19
|
+
const emitted = report(result);
|
|
20
|
+
if (!emitted.changed) {
|
|
21
|
+
spinner.warn(emitted.message);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
spinner.succeed(emitted.message);
|
|
25
|
+
emitted.opsLines?.forEach(log);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
spinner.fail(failLabel);
|
|
29
|
+
failOn(error, failHeadline);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export function coerceValue(raw) {
|
|
2
|
+
try {
|
|
3
|
+
return JSON.parse(raw);
|
|
4
|
+
}
|
|
5
|
+
catch {
|
|
6
|
+
return raw;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
function splitPair(pair) {
|
|
10
|
+
const eq = pair.indexOf('=');
|
|
11
|
+
if (eq < 1) {
|
|
12
|
+
throw new Error(`expected key=value, got "${pair}"`);
|
|
13
|
+
}
|
|
14
|
+
return [pair.slice(0, eq), pair.slice(eq + 1)];
|
|
15
|
+
}
|
|
16
|
+
export function splitParams(pairs) {
|
|
17
|
+
return Object.fromEntries(pairs.map(splitPair));
|
|
18
|
+
}
|
|
19
|
+
export function parseParams(pairs) {
|
|
20
|
+
return Object.fromEntries(Object.entries(splitParams(pairs)).map(([key, raw]) => [key, coerceValue(raw)]));
|
|
21
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { SanityClient } from '@sanity/client';
|
|
2
|
+
import { type WorkflowResource } from '@sanity/workflows';
|
|
3
|
+
import { selectOnStderr } from './prompt.ts';
|
|
4
|
+
export declare const RESOURCE_FLAGS_HINT = "Pass --workflow-resource <type>:<id> (or --project-id with --dataset) to read one resource without a config.";
|
|
5
|
+
type Select = typeof selectOnStderr;
|
|
6
|
+
/** Ask for a resource type, then one resource of it that this login can access. */
|
|
7
|
+
export declare function pickResource(token: string, { client, select, }?: {
|
|
8
|
+
client?: SanityClient;
|
|
9
|
+
select?: Select;
|
|
10
|
+
}): Promise<WorkflowResource>;
|
|
11
|
+
/** The resource ids a `{data: [{id}]}` list answer names. Throws for any other answer. */
|
|
12
|
+
export declare function listedIds(answer: unknown, listPath: string): string[];
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { styleText } from 'node:util';
|
|
2
|
+
import { isResourceType, RESOURCE_TYPES, resourceGdr, resourceLabel, resourceListPath, } from '@sanity/workflows';
|
|
3
|
+
import logSymbols from 'log-symbols';
|
|
4
|
+
import { globalClient } from './client.js';
|
|
5
|
+
import { fail } from './fail.js';
|
|
6
|
+
import { selectOnStderr } from './prompt.js';
|
|
7
|
+
export const RESOURCE_FLAGS_HINT = 'Pass --workflow-resource <type>:<id> (or --project-id with --dataset) to read one resource without a config.';
|
|
8
|
+
export async function pickResource(token, { client = globalClient(token), select = selectOnStderr, } = {}) {
|
|
9
|
+
const type = await select({
|
|
10
|
+
message: 'Select a resource type to read',
|
|
11
|
+
choices: RESOURCE_TYPES.map((value) => ({ name: capitalized(resourceLabel(value)), value })),
|
|
12
|
+
});
|
|
13
|
+
const resource = await pickOfType({ client, select, type: requireListedType(type) });
|
|
14
|
+
process.stderr.write(`${logSymbols.info} To read this resource again without the prompt, pass: ${styleText('bold', `--workflow-resource ${resourceGdr(resource)}`)}\n`);
|
|
15
|
+
return resource;
|
|
16
|
+
}
|
|
17
|
+
function capitalized(text) {
|
|
18
|
+
return `${text.charAt(0).toUpperCase()}${text.slice(1)}`;
|
|
19
|
+
}
|
|
20
|
+
function requireListedType(value) {
|
|
21
|
+
if (!isResourceType(value))
|
|
22
|
+
throw new Error(`Unexpected resource type choice "${value}".`);
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
function pickOfType({ client, select, type, }) {
|
|
26
|
+
const listPath = resourceListPath(type);
|
|
27
|
+
return listPath === undefined
|
|
28
|
+
? pickDataset(client, select)
|
|
29
|
+
: pickListed({ client, select, type, listPath });
|
|
30
|
+
}
|
|
31
|
+
async function pickListed({ client, select, type, listPath, }) {
|
|
32
|
+
const label = resourceLabel(type);
|
|
33
|
+
const ids = listedIds(await client.request({ url: listPath }), listPath);
|
|
34
|
+
if (ids.length === 0) {
|
|
35
|
+
fail(`No ${label} resources found for this login.`, RESOURCE_FLAGS_HINT);
|
|
36
|
+
}
|
|
37
|
+
const id = await select({
|
|
38
|
+
message: `Select a ${label} to read`,
|
|
39
|
+
choices: ids.map((value) => ({ name: value, value })),
|
|
40
|
+
});
|
|
41
|
+
return { type, id };
|
|
42
|
+
}
|
|
43
|
+
function listRows(answer) {
|
|
44
|
+
if (typeof answer !== 'object' || answer === null || !('data' in answer))
|
|
45
|
+
return undefined;
|
|
46
|
+
return Array.isArray(answer.data) ? answer.data : undefined;
|
|
47
|
+
}
|
|
48
|
+
function rowId(row) {
|
|
49
|
+
return typeof row === 'object' && row !== null && 'id' in row && typeof row.id === 'string'
|
|
50
|
+
? row.id
|
|
51
|
+
: undefined;
|
|
52
|
+
}
|
|
53
|
+
export function listedIds(answer, listPath) {
|
|
54
|
+
const ids = listRows(answer)?.map(rowId);
|
|
55
|
+
if (ids === undefined || ids.includes(undefined)) {
|
|
56
|
+
throw new Error(`${listPath} answered with something other than a {data: [{id}]} list.`);
|
|
57
|
+
}
|
|
58
|
+
return ids.filter((id) => id !== undefined);
|
|
59
|
+
}
|
|
60
|
+
async function pickDataset(client, select) {
|
|
61
|
+
const projects = await client.projects.list({ includeMembers: false });
|
|
62
|
+
if (projects.length === 0) {
|
|
63
|
+
fail('No Sanity projects found for this login.', RESOURCE_FLAGS_HINT);
|
|
64
|
+
}
|
|
65
|
+
const projectId = await select({
|
|
66
|
+
message: 'Select a project to read',
|
|
67
|
+
choices: projects.map((project) => ({
|
|
68
|
+
name: project.displayName,
|
|
69
|
+
value: project.id,
|
|
70
|
+
description: project.id,
|
|
71
|
+
})),
|
|
72
|
+
});
|
|
73
|
+
const datasets = await client.withConfig({ projectId }).datasets.list();
|
|
74
|
+
if (datasets.length === 0) {
|
|
75
|
+
fail(`Project ${projectId} has no datasets.`, RESOURCE_FLAGS_HINT);
|
|
76
|
+
}
|
|
77
|
+
const dataset = await select({
|
|
78
|
+
message: 'Select a dataset to read',
|
|
79
|
+
choices: datasets.map(({ name }) => ({ name, value: name })),
|
|
80
|
+
});
|
|
81
|
+
return { type: 'dataset', id: `${projectId}.${dataset}` };
|
|
82
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Can this process ask a question on stderr? A strict superset of the
|
|
3
|
+
* {@link isInteractive} gate cli-core's own prompts enforce (stdin TTY,
|
|
4
|
+
* `TERM` not dumb, no `CI` — so its `NonInteractiveError` can never escape a
|
|
5
|
+
* caller that checked here first), adding stderr-TTY because this package's
|
|
6
|
+
* prompts render on stderr: a redirected stderr must refuse rather than block
|
|
7
|
+
* on stdin with the question swallowed. It classifies whether definition
|
|
8
|
+
* sharing can show its full first-run disclosure and guards interactive
|
|
9
|
+
* prompts such as nuke's confirmation.
|
|
10
|
+
*/
|
|
11
|
+
export declare function canPromptOnStderr(): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Ask a `select` question on stderr — the channel this package renders prompts
|
|
14
|
+
* on so a redirected stdout can't swallow the question (the display side of the
|
|
15
|
+
* {@link canPromptOnStderr} gate). The single site that routes a `select` to
|
|
16
|
+
* stderr, so no `select` prompt can silently regress to stdout.
|
|
17
|
+
*/
|
|
18
|
+
export declare function selectOnStderr(config: {
|
|
19
|
+
message: string;
|
|
20
|
+
choices: readonly {
|
|
21
|
+
name: string;
|
|
22
|
+
value: string;
|
|
23
|
+
description?: string;
|
|
24
|
+
}[];
|
|
25
|
+
/** The value the cursor starts on — e.g. an instance's current stage, so the
|
|
26
|
+
* picker opens where it already is. */
|
|
27
|
+
default?: string;
|
|
28
|
+
}): Promise<string>;
|
|
29
|
+
/**
|
|
30
|
+
* Ask a yes/no question on stderr — the {@link selectOnStderr} sibling.
|
|
31
|
+
* `defaultAnswer` is what a bare Enter returns and sets the `y/N` or `Y/n`
|
|
32
|
+
* hint. Keep it `false` for a destructive confirmation, so proceeding always
|
|
33
|
+
* takes a deliberate keystroke.
|
|
34
|
+
*/
|
|
35
|
+
export declare function confirmOnStderr(message: string, defaultAnswer?: boolean): Promise<boolean>;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { isInteractive } from '@sanity/cli-core';
|
|
2
|
+
import { confirm, select } from '@sanity/cli-core/ux';
|
|
3
|
+
export function canPromptOnStderr() {
|
|
4
|
+
return isInteractive() && process.stderr.isTTY === true;
|
|
5
|
+
}
|
|
6
|
+
export function selectOnStderr(config) {
|
|
7
|
+
return select(config, { output: process.stderr });
|
|
8
|
+
}
|
|
9
|
+
export function confirmOnStderr(message, defaultAnswer = false) {
|
|
10
|
+
return confirm({ message, default: defaultAnswer }, { output: process.stderr });
|
|
11
|
+
}
|