@sanity/workflows-cli 0.0.0-stage → 0.0.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 +1574 -0
- package/LICENSE +21 -0
- package/README.md +797 -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 +51 -0
- package/dist/commands/workflows/definitions/list.js +139 -0
- package/dist/commands/workflows/definitions/show.d.ts +65 -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 +52 -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 +78 -0
- package/dist/commands/workflows/list.js +248 -0
- package/dist/commands/workflows/nuke.d.ts +73 -0
- package/dist/commands/workflows/nuke.js +176 -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 +29 -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 +23 -0
- package/dist/commands/workflows/tail.js +83 -0
- package/dist/commands/workflows/whoami.d.ts +15 -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 +9 -0
- package/dist/hooks/prerun/telemetry.d.ts +28 -0
- package/dist/hooks/prerun/telemetry.js +37 -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 +34 -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 +205 -0
- package/dist/lib/blueprint-stacks.d.ts +6 -0
- package/dist/lib/blueprint-stacks.js +88 -0
- package/dist/lib/cause-detail.d.ts +9 -0
- package/dist/lib/cause-detail.js +112 -0
- package/dist/lib/client.d.ts +24 -0
- package/dist/lib/client.js +40 -0
- package/dist/lib/codemod/manifest-rewrite.d.ts +14 -0
- package/dist/lib/codemod/manifest-rewrite.js +97 -0
- package/dist/lib/codemod/package-map.d.ts +22 -0
- package/dist/lib/codemod/package-map.js +72 -0
- package/dist/lib/codemod/report.d.ts +5 -0
- package/dist/lib/codemod/report.js +43 -0
- package/dist/lib/codemod/run.d.ts +23 -0
- package/dist/lib/codemod/run.js +103 -0
- package/dist/lib/codemod/source-rewrite.d.ts +18 -0
- package/dist/lib/codemod/source-rewrite.js +155 -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 +155 -0
- package/dist/lib/context.js +268 -0
- package/dist/lib/default-partition.d.ts +23 -0
- package/dist/lib/default-partition.js +48 -0
- package/dist/lib/definition-files.d.ts +11 -0
- package/dist/lib/definition-files.js +58 -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 +29 -0
- package/dist/lib/fail.js +46 -0
- package/dist/lib/flags.d.ts +49 -0
- package/dist/lib/flags.js +117 -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 +46 -0
- package/dist/lib/load-config.js +110 -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 +47 -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-dataset.d.ts +10 -0
- package/dist/lib/pick-dataset.js +30 -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 +44 -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 +81 -0
- package/dist/lib/telemetry-setup.js +111 -0
- package/dist/lib/telemetry.d.ts +78 -0
- package/dist/lib/telemetry.js +90 -0
- package/dist/lib/ui.d.ts +91 -0
- package/dist/lib/ui.js +116 -0
- package/dist/standalone-argv.d.ts +14 -0
- package/dist/standalone-argv.js +57 -0
- package/oclif.manifest.json +1731 -0
- package/package.json +118 -3
package/dist/lib/nuke.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { styleText } from 'node:util';
|
|
2
|
+
import { GUARD_DOC_TYPE, WORKFLOW_DEFINITION_TYPE, WORKFLOW_INSTANCE_TYPE, resourceGdr, partitionScopeFilter, } from '@sanity/workflows';
|
|
3
|
+
import { fail } from './fail.js';
|
|
4
|
+
import { deploymentLabel } from './select-deployment.js';
|
|
5
|
+
import { formatTable, pluralize, resourceLabel, 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: resourceLabel(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 absent when the deployment binds
|
|
8
|
+
* none, or when no configured deployment owns the instance.
|
|
9
|
+
*/
|
|
10
|
+
export type EngineScope = Pick<EngineScopeArgs, 'partition' | 'workflowResource' | '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
|
+
...(scope.resourceClients !== undefined ? { 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,47 @@
|
|
|
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 fail}. The one spinner + report + catch shape every write
|
|
37
|
+
* command (abort, fire-action, start, definitions delete, nuke)
|
|
38
|
+
* shares.
|
|
39
|
+
*/
|
|
40
|
+
export declare function runWriteVerb<T>({ startLabel, failLabel, failHeadline, run, report, log, }: {
|
|
41
|
+
startLabel: string;
|
|
42
|
+
failLabel: string;
|
|
43
|
+
failHeadline: string;
|
|
44
|
+
run: () => Promise<T>;
|
|
45
|
+
report: (result: T) => WriteReport;
|
|
46
|
+
log: (line: string) => void;
|
|
47
|
+
}): 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 { fail, failureDetail } 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
|
+
fail(failHeadline, failureDetail(error));
|
|
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,10 @@
|
|
|
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 --project-id with --dataset, or --media-library-id, to read one resource without a config.";
|
|
5
|
+
type Select = typeof selectOnStderr;
|
|
6
|
+
export declare function pickDataset(token: string, { client, select, }?: {
|
|
7
|
+
client?: SanityClient;
|
|
8
|
+
select?: Select;
|
|
9
|
+
}): Promise<WorkflowResource>;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { styleText } from 'node:util';
|
|
2
|
+
import logSymbols from 'log-symbols';
|
|
3
|
+
import { globalClient } from './client.js';
|
|
4
|
+
import { fail } from './fail.js';
|
|
5
|
+
import { selectOnStderr } from './prompt.js';
|
|
6
|
+
export const RESOURCE_FLAGS_HINT = 'Pass --project-id with --dataset, or --media-library-id, to read one resource without a config.';
|
|
7
|
+
export async function pickDataset(token, { client = globalClient(token), select = selectOnStderr, } = {}) {
|
|
8
|
+
const projects = await client.projects.list({ includeMembers: false });
|
|
9
|
+
if (projects.length === 0) {
|
|
10
|
+
fail('No Sanity projects found for this login.', RESOURCE_FLAGS_HINT);
|
|
11
|
+
}
|
|
12
|
+
const projectId = await select({
|
|
13
|
+
message: 'Select a project to read',
|
|
14
|
+
choices: projects.map((project) => ({
|
|
15
|
+
name: project.displayName,
|
|
16
|
+
value: project.id,
|
|
17
|
+
description: project.id,
|
|
18
|
+
})),
|
|
19
|
+
});
|
|
20
|
+
const datasets = await client.withConfig({ projectId }).datasets.list();
|
|
21
|
+
if (datasets.length === 0) {
|
|
22
|
+
fail(`Project ${projectId} has no datasets.`, RESOURCE_FLAGS_HINT);
|
|
23
|
+
}
|
|
24
|
+
const dataset = await select({
|
|
25
|
+
message: 'Select a dataset to read',
|
|
26
|
+
choices: datasets.map(({ name }) => ({ name, value: name })),
|
|
27
|
+
});
|
|
28
|
+
process.stderr.write(`${logSymbols.info} To read this dataset again without the prompt, pass: ${styleText('bold', `--project-id ${projectId} --dataset ${dataset}`)}\n`);
|
|
29
|
+
return { type: 'dataset', id: `${projectId}.${dataset}` };
|
|
30
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { WorkflowResource } from '@sanity/workflows';
|
|
2
|
+
import type { ReadTarget } from './context.ts';
|
|
3
|
+
/** A read target whose query threw — noted in place and reflected in the
|
|
4
|
+
* command's exit code. */
|
|
5
|
+
export interface ReadFailure {
|
|
6
|
+
resource: WorkflowResource;
|
|
7
|
+
message: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* The `--json` tail of a list command — the structured counterpart of
|
|
11
|
+
* {@link runReadAcrossTargets} + the clipped table: fetch every target's
|
|
12
|
+
* rows, {@link clipToLimit} each target's page, map rows through the
|
|
13
|
+
* command's row view (`toRow`, the structured analogue of the table's
|
|
14
|
+
* `toCells`), annotate each with the resource it came from (the analogue of
|
|
15
|
+
* the banner), and log one `{<key>: rows, truncated}` payload.
|
|
16
|
+
* All-or-nothing, unlike the human path's per-resource tolerance: a script
|
|
17
|
+
* would mistake a listing that silently omitted an unreadable resource for
|
|
18
|
+
* the complete result, so any failure rejects the whole read.
|
|
19
|
+
*/
|
|
20
|
+
export declare function logJsonListing<T, R>({ targets, fetch, toRow, key, limit, log, }: {
|
|
21
|
+
targets: ReadTarget[];
|
|
22
|
+
fetch: (target: ReadTarget) => Promise<{
|
|
23
|
+
rows: T[];
|
|
24
|
+
hasMore: boolean;
|
|
25
|
+
}>;
|
|
26
|
+
toRow: (row: T) => R;
|
|
27
|
+
/** The payload's row key — names what the rows are (`instances`, `definitions`). */
|
|
28
|
+
key: string;
|
|
29
|
+
limit: number;
|
|
30
|
+
log: (line: string) => void;
|
|
31
|
+
}): Promise<void>;
|
|
32
|
+
/**
|
|
33
|
+
* Run a read over every target, grouping output per resource: a banner when
|
|
34
|
+
* the read spans several, then whatever `run` logs for that target. A throw
|
|
35
|
+
* from one target is noted under its banner and the rest still render — a
|
|
36
|
+
* token that can't read one dataset must not sink the whole listing. A
|
|
37
|
+
* single-target run rethrows instead, keeping the plain unprefixed output
|
|
38
|
+
* and clean error rendering at the command boundary. Callers exit non-zero
|
|
39
|
+
* when failures come back.
|
|
40
|
+
*/
|
|
41
|
+
export declare function runReadAcrossTargets({ targets, log, run, }: {
|
|
42
|
+
targets: ReadTarget[];
|
|
43
|
+
log: (line: string) => void;
|
|
44
|
+
run: (target: ReadTarget) => Promise<void>;
|
|
45
|
+
}): Promise<ReadFailure[]>;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import logSymbols from 'log-symbols';
|
|
2
|
+
import { failureDetail } from './fail.js';
|
|
3
|
+
import { clipToLimit, groupBanner, resourceLabel } from './ui.js';
|
|
4
|
+
export async function logJsonListing({ targets, fetch, toRow, key, limit, log, }) {
|
|
5
|
+
const fetched = await Promise.all(targets.map(async (target) => {
|
|
6
|
+
const { rows, hasMore } = await fetch(target);
|
|
7
|
+
return {
|
|
8
|
+
rows: clipToLimit(rows, limit).rows.map((row) => ({
|
|
9
|
+
...toRow(row),
|
|
10
|
+
resource: target.resource,
|
|
11
|
+
})),
|
|
12
|
+
hasMore: hasMore || rows.length > limit,
|
|
13
|
+
};
|
|
14
|
+
}));
|
|
15
|
+
log(JSON.stringify({
|
|
16
|
+
[key]: fetched.flatMap((result) => result.rows),
|
|
17
|
+
truncated: fetched.some((result) => result.hasMore),
|
|
18
|
+
}, null, 2));
|
|
19
|
+
}
|
|
20
|
+
export async function runReadAcrossTargets({ targets, log, run, }) {
|
|
21
|
+
const failures = [];
|
|
22
|
+
for (const [index, target] of targets.entries()) {
|
|
23
|
+
const banner = groupBanner({
|
|
24
|
+
label: resourceLabel(target.resource),
|
|
25
|
+
index,
|
|
26
|
+
total: targets.length,
|
|
27
|
+
});
|
|
28
|
+
if (banner !== undefined) {
|
|
29
|
+
log(banner);
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
await run(target);
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
if (targets.length === 1) {
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
const message = failureDetail(error);
|
|
39
|
+
failures.push({ resource: target.resource, message });
|
|
40
|
+
log(`${logSymbols.error} ${message}`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return failures;
|
|
44
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type AcknowledgedWorkflowDeployment, type DeployTarget, type WorkflowConfig, type WorkflowDefinition, type WorkflowDeployment } from '@sanity/workflows';
|
|
2
|
+
export type ChooseDeploymentName = (deployments: WorkflowDeployment[]) => Promise<string>;
|
|
3
|
+
export interface DeploymentSelectionOptions {
|
|
4
|
+
name: string | undefined;
|
|
5
|
+
partition: string | undefined;
|
|
6
|
+
allPartitions: boolean;
|
|
7
|
+
interactive?: boolean;
|
|
8
|
+
chooseName?: ChooseDeploymentName;
|
|
9
|
+
}
|
|
10
|
+
/** The one identity format for a deployment in output — banners, failure
|
|
11
|
+
* summaries, and "available deployments" listings all render it the same
|
|
12
|
+
* way. */
|
|
13
|
+
export declare function deploymentLabel({ name, partition, }: Pick<WorkflowDeployment, 'name' | 'partition'>): string;
|
|
14
|
+
/** Deployment names are unique across the config; partitions may repeat across resources. */
|
|
15
|
+
export declare function selectDeployment(config: WorkflowConfig, { name, partition, orAlternative, interactive, chooseName, }: {
|
|
16
|
+
name: string | undefined;
|
|
17
|
+
partition: string | undefined;
|
|
18
|
+
orAlternative?: string;
|
|
19
|
+
interactive?: boolean | undefined;
|
|
20
|
+
chooseName?: ChooseDeploymentName | undefined;
|
|
21
|
+
}): Promise<WorkflowDeployment>;
|
|
22
|
+
export declare function deploymentsForPartition(config: WorkflowConfig, partition: string): WorkflowDeployment[];
|
|
23
|
+
export declare function selectDeployments(config: WorkflowConfig, { name, partition, allPartitions, interactive, chooseName }: DeploymentSelectionOptions): Promise<WorkflowDeployment[]>;
|
|
24
|
+
/** The shared acknowledgement boundary for the CLI's definition-submission paths. */
|
|
25
|
+
export declare function acknowledgeDeployment(deployment: WorkflowDeployment, definitions: readonly WorkflowDefinition[]): AcknowledgedWorkflowDeployment;
|
|
26
|
+
/**
|
|
27
|
+
* Project a deployment into the engine's {@link DeployTarget} — the shape the
|
|
28
|
+
* deploy/diff verbs (`deployDefinitions`, `computeDiffEntries`, `diffEntry`)
|
|
29
|
+
* consume — expanding its handle bindings into the alias map in the same step.
|
|
30
|
+
*/
|
|
31
|
+
export declare function deploymentToTarget(deployment: AcknowledgedWorkflowDeployment): DeployTarget;
|