@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
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { assertReadableModel, deploymentResourceClients, resourceGdr, } from '@sanity/workflows';
|
|
2
|
+
import { clientFor, resolveTokenOrFail } from './client.js';
|
|
3
|
+
import { fail } from './fail.js';
|
|
4
|
+
import { loadWorkflowConfig, loadWorkflowConfigIfFound, noConfigFound } from './load-config.js';
|
|
5
|
+
import { pickDataset, RESOURCE_FLAGS_HINT } from './pick-dataset.js';
|
|
6
|
+
import { canPromptOnStderr, selectOnStderr } from './prompt.js';
|
|
7
|
+
import { deploymentsForPartition, selectDeployment } from './select-deployment.js';
|
|
8
|
+
import { resourceLabel } from './ui.js';
|
|
9
|
+
export async function resolveContext(flags) {
|
|
10
|
+
const config = await loadWorkflowConfig(flags.path);
|
|
11
|
+
const deployment = await selectDeployment(config, {
|
|
12
|
+
name: flags.deployment,
|
|
13
|
+
partition: flags.partition,
|
|
14
|
+
});
|
|
15
|
+
const client = clientFor(deployment.workflowResource, await resolveTokenOrFail());
|
|
16
|
+
return { deployment, client, scope: deploymentScope({ client, deployment }) };
|
|
17
|
+
}
|
|
18
|
+
function deploymentScope({ client, deployment, }) {
|
|
19
|
+
const resourceClients = deploymentResourceClients({ client, deployment });
|
|
20
|
+
return {
|
|
21
|
+
partition: deployment.partition,
|
|
22
|
+
workflowResource: deployment.workflowResource,
|
|
23
|
+
...(resourceClients !== undefined ? { resourceClients } : {}),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export function instanceScope(hit) {
|
|
27
|
+
const owner = hit.deployments.find((deployment) => deployment.partition === hit.instance.tag);
|
|
28
|
+
if (owner === undefined) {
|
|
29
|
+
return { partition: hit.instance.tag, workflowResource: hit.resource };
|
|
30
|
+
}
|
|
31
|
+
return { ...deploymentScope({ client: hit.client, deployment: owner }), partition: hit.instance.tag };
|
|
32
|
+
}
|
|
33
|
+
function targetsFor(args) {
|
|
34
|
+
return args.resources.map((resource) => ({
|
|
35
|
+
resource,
|
|
36
|
+
client: clientFor(resource, args.token),
|
|
37
|
+
deployments: args.config.deployments.filter((deployment) => resourceGdr(deployment.workflowResource) === resourceGdr(resource)),
|
|
38
|
+
}));
|
|
39
|
+
}
|
|
40
|
+
function explicitResource(flags) {
|
|
41
|
+
if (flags['media-library-id'] !== undefined) {
|
|
42
|
+
return { type: 'media-library', id: flags['media-library-id'] };
|
|
43
|
+
}
|
|
44
|
+
if (flags['project-id'] !== undefined && flags.dataset !== undefined) {
|
|
45
|
+
return { type: 'dataset', id: `${flags['project-id']}.${flags.dataset}` };
|
|
46
|
+
}
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
function unconfiguredTarget(resource, token) {
|
|
50
|
+
return { resource, client: clientFor(resource, token), deployments: [] };
|
|
51
|
+
}
|
|
52
|
+
export function ambiguityFor(flags) {
|
|
53
|
+
return canAsk(flags) ? 'prompt' : 'fail';
|
|
54
|
+
}
|
|
55
|
+
function canAsk(flags) {
|
|
56
|
+
return flags.json !== true && canPromptOnStderr();
|
|
57
|
+
}
|
|
58
|
+
export async function resolveReadTargets(flags) {
|
|
59
|
+
const source = await readSource(flags, { pick: true });
|
|
60
|
+
if ('resource' in source) {
|
|
61
|
+
return {
|
|
62
|
+
targets: [unconfiguredTarget(source.resource, source.token)],
|
|
63
|
+
partition: flags.partition,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
const { config, token } = source;
|
|
67
|
+
if (flags.deployment !== undefined) {
|
|
68
|
+
const deployment = await selectDeployment(config, {
|
|
69
|
+
name: flags.deployment,
|
|
70
|
+
partition: undefined,
|
|
71
|
+
});
|
|
72
|
+
const resources = [deployment.workflowResource];
|
|
73
|
+
return { targets: targetsFor({ config, resources, token }), partition: deployment.partition };
|
|
74
|
+
}
|
|
75
|
+
const resources = resolveReadResources(config, flags.partition);
|
|
76
|
+
return { targets: targetsFor({ config, resources, token }), partition: flags.partition };
|
|
77
|
+
}
|
|
78
|
+
async function readSource(flags, { pick }) {
|
|
79
|
+
const resource = explicitResource(flags);
|
|
80
|
+
if (resource !== undefined) {
|
|
81
|
+
return { resource, token: await resolveTokenOrFail() };
|
|
82
|
+
}
|
|
83
|
+
if (!pick || flags.path !== undefined || flags.deployment !== undefined) {
|
|
84
|
+
return configSource(flags.path);
|
|
85
|
+
}
|
|
86
|
+
const config = await loadWorkflowConfigIfFound();
|
|
87
|
+
if (config !== undefined) {
|
|
88
|
+
return { config, token: await resolveTokenOrFail() };
|
|
89
|
+
}
|
|
90
|
+
if (!canAsk(flags)) {
|
|
91
|
+
fail(noConfigFound(), RESOURCE_FLAGS_HINT);
|
|
92
|
+
}
|
|
93
|
+
const token = await resolveTokenOrFail();
|
|
94
|
+
return { resource: await pickDataset(token), token };
|
|
95
|
+
}
|
|
96
|
+
async function configSource(path) {
|
|
97
|
+
return { config: await loadWorkflowConfig(path), token: await resolveTokenOrFail() };
|
|
98
|
+
}
|
|
99
|
+
export function dedupeResources(resources) {
|
|
100
|
+
return [...new Map(resources.map((resource) => [resourceGdr(resource), resource])).values()];
|
|
101
|
+
}
|
|
102
|
+
export function resolveReadResources(config, partition) {
|
|
103
|
+
if (partition !== undefined) {
|
|
104
|
+
return dedupeResources(deploymentsForPartition(config, partition).map((deployment) => deployment.workflowResource));
|
|
105
|
+
}
|
|
106
|
+
const resources = dedupeResources(config.deployments.map((d) => d.workflowResource));
|
|
107
|
+
if (resources.length === 0) {
|
|
108
|
+
fail('No deployments configured.');
|
|
109
|
+
}
|
|
110
|
+
return resources;
|
|
111
|
+
}
|
|
112
|
+
const LOCATE_TAG = 'instance.load';
|
|
113
|
+
export function resolveInstanceContext(flags, instanceId) {
|
|
114
|
+
return instanceContext({ flags, instanceId, read: false });
|
|
115
|
+
}
|
|
116
|
+
export function resolveReadInstanceContext(flags, instanceId) {
|
|
117
|
+
return instanceContext({ flags, instanceId, read: true });
|
|
118
|
+
}
|
|
119
|
+
async function instanceContext({ flags, instanceId, read, }) {
|
|
120
|
+
const hit = await locateInstance({
|
|
121
|
+
flags,
|
|
122
|
+
instanceId,
|
|
123
|
+
read,
|
|
124
|
+
find: (targets, ambiguity) => findInstance({ targets, instanceId, requestTag: LOCATE_TAG, ambiguity }),
|
|
125
|
+
});
|
|
126
|
+
if (hit === undefined) {
|
|
127
|
+
fail(`Workflow instance ${instanceId} not found`);
|
|
128
|
+
}
|
|
129
|
+
return { client: hit.client, scope: instanceScope(hit) };
|
|
130
|
+
}
|
|
131
|
+
export async function resolveInstanceStamps(flags, instanceId) {
|
|
132
|
+
const hit = await locateInstance({
|
|
133
|
+
flags,
|
|
134
|
+
instanceId,
|
|
135
|
+
read: false,
|
|
136
|
+
find: (targets, ambiguity) => findInstanceStamps({ targets, instanceId, requestTag: LOCATE_TAG, ambiguity }),
|
|
137
|
+
});
|
|
138
|
+
if (hit === undefined) {
|
|
139
|
+
fail(`Workflow instance ${instanceId} not found`);
|
|
140
|
+
}
|
|
141
|
+
return { resource: hit.resource, stamps: hit.stamps };
|
|
142
|
+
}
|
|
143
|
+
async function locateInstance({ flags, instanceId, read, find, }) {
|
|
144
|
+
const source = await readSource(flags, { pick: read });
|
|
145
|
+
if ('resource' in source) {
|
|
146
|
+
return find([unconfiguredTarget(source.resource, source.token)], ambiguityFor(flags));
|
|
147
|
+
}
|
|
148
|
+
const { config, token } = source;
|
|
149
|
+
const resources = await instanceCandidateResources(config, flags);
|
|
150
|
+
const fanOut = () => find(targetsFor({ config, resources, token }), ambiguityFor(flags));
|
|
151
|
+
const explicit = flags.deployment !== undefined || flags.partition !== undefined;
|
|
152
|
+
const hinted = explicit || resources.length <= 1
|
|
153
|
+
? []
|
|
154
|
+
: hintedResources({ config, instanceId, candidates: resources });
|
|
155
|
+
if (hinted.length === 0 || hinted.length === resources.length) {
|
|
156
|
+
return fanOut();
|
|
157
|
+
}
|
|
158
|
+
const hit = await hintedProbe(() => find(targetsFor({ config, resources: hinted, token }), 'defer'));
|
|
159
|
+
return hit ?? fanOut();
|
|
160
|
+
}
|
|
161
|
+
async function hintedProbe(probe) {
|
|
162
|
+
try {
|
|
163
|
+
return await probe();
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
async function instanceCandidateResources(config, { deployment, partition }) {
|
|
170
|
+
if (deployment !== undefined) {
|
|
171
|
+
return [
|
|
172
|
+
(await selectDeployment(config, { name: deployment, partition: undefined })).workflowResource,
|
|
173
|
+
];
|
|
174
|
+
}
|
|
175
|
+
return resolveReadResources(config, partition);
|
|
176
|
+
}
|
|
177
|
+
function hintedResources({ config, instanceId, candidates, }) {
|
|
178
|
+
const dot = instanceId.indexOf('.');
|
|
179
|
+
if (dot <= 0) {
|
|
180
|
+
return [];
|
|
181
|
+
}
|
|
182
|
+
const prefix = instanceId.slice(0, dot);
|
|
183
|
+
const taggedGdrs = new Set(config.deployments
|
|
184
|
+
.filter((deployment) => deployment.partition === prefix)
|
|
185
|
+
.map((deployment) => resourceGdr(deployment.workflowResource)));
|
|
186
|
+
return candidates.filter((resource) => taggedGdrs.has(resourceGdr(resource)));
|
|
187
|
+
}
|
|
188
|
+
function chooseCandidateOnStderr(choices) {
|
|
189
|
+
return selectOnStderr({ message: 'Select a deployment', choices });
|
|
190
|
+
}
|
|
191
|
+
function candidateName(hit, partition) {
|
|
192
|
+
const deployment = hit.deployments.find((candidate) => candidate.partition === partition);
|
|
193
|
+
if (deployment !== undefined) {
|
|
194
|
+
return deployment.name;
|
|
195
|
+
}
|
|
196
|
+
return partition === undefined ? 'unconfigured' : `partition "${partition}"`;
|
|
197
|
+
}
|
|
198
|
+
export async function soleHitOrChoose(hits, args) {
|
|
199
|
+
const [sole, ...rest] = hits;
|
|
200
|
+
if (rest.length === 0) {
|
|
201
|
+
return sole;
|
|
202
|
+
}
|
|
203
|
+
if (args.ambiguity === 'defer') {
|
|
204
|
+
return undefined;
|
|
205
|
+
}
|
|
206
|
+
const candidates = hits.map((hit, index) => ({
|
|
207
|
+
name: candidateName(hit, args.partitionOf(hit)),
|
|
208
|
+
value: String(index),
|
|
209
|
+
description: resourceLabel(hit.resource),
|
|
210
|
+
}));
|
|
211
|
+
if (args.ambiguity === 'fail') {
|
|
212
|
+
fail(`${args.subject} exists in several deployments — pass --deployment to choose one.`, candidates.map(({ name, description }) => `${name} (${description})`).join('\n'));
|
|
213
|
+
}
|
|
214
|
+
const chosen = await (args.choose ?? chooseCandidateOnStderr)(candidates);
|
|
215
|
+
return hits[Number(chosen)];
|
|
216
|
+
}
|
|
217
|
+
async function findAcrossTargets({ targets, subject, probe, partitionOf, ambiguity, }) {
|
|
218
|
+
const probes = await Promise.allSettled(targets.map(probe));
|
|
219
|
+
const hits = probes
|
|
220
|
+
.filter((settled) => settled.status === 'fulfilled')
|
|
221
|
+
.map((settled) => settled.value)
|
|
222
|
+
.filter((hit) => hit !== undefined);
|
|
223
|
+
const sole = await soleHitOrChoose(hits, { subject, partitionOf, ambiguity });
|
|
224
|
+
if (sole !== undefined) {
|
|
225
|
+
return sole;
|
|
226
|
+
}
|
|
227
|
+
const failedProbe = probes.find((settled) => settled.status === 'rejected');
|
|
228
|
+
if (failedProbe !== undefined) {
|
|
229
|
+
throw failedProbe.reason;
|
|
230
|
+
}
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
export function findInstance({ targets, instanceId, requestTag, ambiguity, }) {
|
|
234
|
+
return findAcrossTargets({
|
|
235
|
+
targets,
|
|
236
|
+
subject: `Instance ${instanceId}`,
|
|
237
|
+
partitionOf: (hit) => hit.instance.tag,
|
|
238
|
+
ambiguity,
|
|
239
|
+
probe: async (target) => {
|
|
240
|
+
const instance = await target.client.getDocument(instanceId, {
|
|
241
|
+
tag: requestTag,
|
|
242
|
+
});
|
|
243
|
+
return instance === undefined
|
|
244
|
+
? undefined
|
|
245
|
+
: { ...target, instance: assertReadableModel(instance) };
|
|
246
|
+
},
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
function findInstanceStamps({ targets, instanceId, requestTag, ambiguity, }) {
|
|
250
|
+
return findAcrossTargets({
|
|
251
|
+
targets,
|
|
252
|
+
subject: `Instance ${instanceId}`,
|
|
253
|
+
partitionOf: (hit) => hit.stamps.tag,
|
|
254
|
+
ambiguity,
|
|
255
|
+
probe: async (target) => {
|
|
256
|
+
const projected = await target.client.fetch(`*[_id == $instanceId][0]{_type, tag, completedAt, abortedAt}`, { instanceId }, { perspective: 'raw', tag: requestTag });
|
|
257
|
+
return projected === null ? undefined : { ...target, stamps: stampsOf(projected) };
|
|
258
|
+
},
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
function stampsOf({ _type, tag, completedAt, abortedAt }) {
|
|
262
|
+
return {
|
|
263
|
+
_type,
|
|
264
|
+
...(tag === null ? {} : { tag }),
|
|
265
|
+
...(completedAt === null ? {} : { completedAt }),
|
|
266
|
+
...(abortedAt === null ? {} : { abortedAt }),
|
|
267
|
+
};
|
|
268
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type WorkflowDeployment } from '@sanity/workflows';
|
|
2
|
+
type PartitionTarget = Pick<WorkflowDeployment, 'name' | 'partition' | 'workflowResource'>;
|
|
3
|
+
/**
|
|
4
|
+
* The warning for a deployment that targets the default partition of a
|
|
5
|
+
* resource whose definitions all live in other partitions, which is what
|
|
6
|
+
* deleting a deployment's `tag` instead of renaming it to `partition` looks
|
|
7
|
+
* like. `undefined` when the deployment targets another partition, the
|
|
8
|
+
* resource is empty, or the default partition already holds definitions.
|
|
9
|
+
*/
|
|
10
|
+
export declare function defaultPartitionWarning(deployment: PartitionTarget, deployedPartitions: readonly string[]): string | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* Print a {@link defaultPartitionWarning} for each deployment that has one,
|
|
13
|
+
* then ask to proceed when the shell can prompt. A dry run or a
|
|
14
|
+
* non-interactive shell only warns. Declining exits before anything is
|
|
15
|
+
* written.
|
|
16
|
+
*/
|
|
17
|
+
export declare function confirmDefaultPartitions<T extends PartitionTarget>({ deployments, deployedPartitions, dryRun, warn, }: {
|
|
18
|
+
deployments: readonly T[];
|
|
19
|
+
deployedPartitions: (deployment: T) => Promise<string[]>;
|
|
20
|
+
dryRun: boolean;
|
|
21
|
+
warn: (message: string) => void;
|
|
22
|
+
}): Promise<void>;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { DEFAULT_PARTITION } from '@sanity/workflows';
|
|
2
|
+
import { fail, isAuthRejection } from './fail.js';
|
|
3
|
+
import { canPromptOnStderr, confirmOnStderr } from './prompt.js';
|
|
4
|
+
import { resourceLabel } from './ui.js';
|
|
5
|
+
export function defaultPartitionWarning(deployment, deployedPartitions) {
|
|
6
|
+
if (deployment.partition !== DEFAULT_PARTITION ||
|
|
7
|
+
deployedPartitions.length === 0 ||
|
|
8
|
+
deployedPartitions.includes(DEFAULT_PARTITION)) {
|
|
9
|
+
return undefined;
|
|
10
|
+
}
|
|
11
|
+
const [only] = deployedPartitions;
|
|
12
|
+
const existing = deployedPartitions.length === 1
|
|
13
|
+
? `This resource's definitions are in partition "${only}". To deploy alongside them instead, set partition: "${only}" on this deployment.`
|
|
14
|
+
: `This resource's definitions are in partitions ${deployedPartitions.join(', ')}. To deploy alongside one of those instead, set partition on this deployment.`;
|
|
15
|
+
return [
|
|
16
|
+
`Partition "${DEFAULT_PARTITION}" of ${resourceLabel(deployment.workflowResource)} has no workflow definitions yet, so deployment "${deployment.name}" will be the first there.`,
|
|
17
|
+
existing,
|
|
18
|
+
].join('\n');
|
|
19
|
+
}
|
|
20
|
+
export async function confirmDefaultPartitions({ deployments, deployedPartitions, dryRun, warn, }) {
|
|
21
|
+
const warnings = await Promise.all(deployments
|
|
22
|
+
.filter((deployment) => deployment.partition === DEFAULT_PARTITION)
|
|
23
|
+
.map((deployment) => lookUpWarning(deployment, deployedPartitions)));
|
|
24
|
+
const found = warnings.filter((warning) => warning !== undefined);
|
|
25
|
+
if (found.length === 0) {
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
for (const warning of found) {
|
|
29
|
+
warn(warning);
|
|
30
|
+
}
|
|
31
|
+
if (dryRun || !canPromptOnStderr()) {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (!(await confirmOnStderr(`Deploy to partition "${DEFAULT_PARTITION}"?`, true))) {
|
|
35
|
+
fail('Cancelled — nothing was deployed.');
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
async function lookUpWarning(deployment, deployedPartitions) {
|
|
39
|
+
try {
|
|
40
|
+
return defaultPartitionWarning(deployment, await deployedPartitions(deployment));
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (isAuthRejection(error)) {
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type ValidateDefinitionInputsResult } from '@sanity/workflows';
|
|
2
|
+
/** One definition read from a JSON file. `label` names its file, and its array index when the file holds several. */
|
|
3
|
+
export interface DefinitionFileEntry {
|
|
4
|
+
label: string;
|
|
5
|
+
definition: Record<string, unknown>;
|
|
6
|
+
}
|
|
7
|
+
export declare function readDefinitionFiles(paths: readonly string[]): Promise<DefinitionFileEntry[]>;
|
|
8
|
+
export declare function describeValidation(entries: readonly DefinitionFileEntry[], report: ValidateDefinitionInputsResult): {
|
|
9
|
+
passed: string[];
|
|
10
|
+
failed: string[];
|
|
11
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { errorMessage } from '@sanity/workflows';
|
|
3
|
+
export async function readDefinitionFiles(paths) {
|
|
4
|
+
const files = await Promise.all(paths.map(async (path) => ({ path, value: parseJson(path, await readFile(path, 'utf8')) })));
|
|
5
|
+
return files.flatMap(({ path, value }) => definitionEntries(path, value));
|
|
6
|
+
}
|
|
7
|
+
export function describeValidation(entries, report) {
|
|
8
|
+
const passed = [];
|
|
9
|
+
const failed = [];
|
|
10
|
+
report.results.forEach((result, index) => {
|
|
11
|
+
const label = entries[index]?.label;
|
|
12
|
+
if (label === undefined) {
|
|
13
|
+
throw new Error(`validation result ${index} has no matching definition entry`);
|
|
14
|
+
}
|
|
15
|
+
if (result.valid) {
|
|
16
|
+
passed.push(`${label}: ${result.definition.name}`);
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
failed.push(`${label}: ${result.error}`);
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
return { passed, failed };
|
|
23
|
+
}
|
|
24
|
+
function parseJson(path, source) {
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(source);
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
throw new Error(`${path}: not valid JSON (${errorMessage(err)})`, { cause: err });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function definitionEntries(path, value) {
|
|
33
|
+
if (!Array.isArray(value)) {
|
|
34
|
+
return [{ label: path, definition: definitionObject(value, path) }];
|
|
35
|
+
}
|
|
36
|
+
if (value.length === 0) {
|
|
37
|
+
throw new Error(`${path}: the array holds no definitions`);
|
|
38
|
+
}
|
|
39
|
+
return value.map((item, index) => {
|
|
40
|
+
const label = `${path}[${index}]`;
|
|
41
|
+
return { label, definition: definitionObject(item, label) };
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
function definitionObject(value, label) {
|
|
45
|
+
if (!isJsonObject(value)) {
|
|
46
|
+
throw new Error(`${label}: expected a workflow definition object, got ${jsonKind(value)}`);
|
|
47
|
+
}
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
function isJsonObject(value) {
|
|
51
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
52
|
+
}
|
|
53
|
+
function jsonKind(value) {
|
|
54
|
+
if (value === null) {
|
|
55
|
+
return 'null';
|
|
56
|
+
}
|
|
57
|
+
return Array.isArray(value) ? 'an array' : typeof value;
|
|
58
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { SanityClient } from '@sanity/client';
|
|
2
|
+
import { type DeployedDefinition, type WorkflowConfig, type WorkflowDefinition } from '@sanity/workflows';
|
|
3
|
+
interface DefinitionShowQueryArgs {
|
|
4
|
+
name: string;
|
|
5
|
+
partition?: string | undefined;
|
|
6
|
+
version?: number | undefined;
|
|
7
|
+
}
|
|
8
|
+
export declare function buildDefinitionShowQuery(flags: DefinitionShowQueryArgs): {
|
|
9
|
+
groq: string;
|
|
10
|
+
params: Record<string, unknown>;
|
|
11
|
+
};
|
|
12
|
+
export declare function buildDefinitionPartitionsQuery(name: string): {
|
|
13
|
+
groq: string;
|
|
14
|
+
params: Record<string, unknown>;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Fetch the deployed definition a command targets — latest unless pinned via
|
|
18
|
+
* `version`. An absent pinned version always fails (the caller asked for
|
|
19
|
+
* something specific); an absent latest returns `undefined` so the caller
|
|
20
|
+
* decides whether that's fatal.
|
|
21
|
+
*/
|
|
22
|
+
export declare function fetchDeployedDefinition({ client, name, partition, version, }: {
|
|
23
|
+
client: SanityClient;
|
|
24
|
+
name: string;
|
|
25
|
+
partition: string;
|
|
26
|
+
version: number | undefined;
|
|
27
|
+
}): Promise<DeployedDefinition | undefined>;
|
|
28
|
+
/**
|
|
29
|
+
* Gate a definition filter against the whole config before a command resolves
|
|
30
|
+
* which deployment it targets — a name that matches no definition anywhere can
|
|
31
|
+
* never deploy, whichever deployment is chosen, so it fails here rather than
|
|
32
|
+
* behind the interactive deployment picker. Membership in the targeted
|
|
33
|
+
* deployment stays with {@link selectDefinitions}, which fails on a name only
|
|
34
|
+
* some other deployment carries.
|
|
35
|
+
*
|
|
36
|
+
* The filter and the deployment selector both take a bare name, so a value
|
|
37
|
+
* naming a deployment is pointed at the flag it belongs to instead of getting a
|
|
38
|
+
* dead-end list of definitions it was never going to be in — in which case the
|
|
39
|
+
* available-definitions hint is replaced, not appended to.
|
|
40
|
+
*/
|
|
41
|
+
export declare function assertKnownDefinition(config: WorkflowConfig, only: string | undefined): void;
|
|
42
|
+
/**
|
|
43
|
+
* Narrow a batch to one definition name (`only`), failing with the available
|
|
44
|
+
* names when there's no match. With `only` unset the whole batch passes through
|
|
45
|
+
* (a fresh array, so callers can mutate without aliasing). `context` prefixes
|
|
46
|
+
* the failure so callers whose run spans several deployments can attribute it.
|
|
47
|
+
*/
|
|
48
|
+
export declare function selectDefinitions(allDefinitions: WorkflowDefinition[], { only, context }: {
|
|
49
|
+
only: string | undefined;
|
|
50
|
+
context?: string;
|
|
51
|
+
}): WorkflowDefinition[];
|
|
52
|
+
/**
|
|
53
|
+
* Per-definition structural/GROQ checks plus one batch-level check the engine
|
|
54
|
+
* doesn't do for us: duplicate `name` within the set. Returns the
|
|
55
|
+
* human-readable error lines; empty means the batch is valid.
|
|
56
|
+
*/
|
|
57
|
+
export declare function collectValidationErrors(defs: WorkflowDefinition[]): string[];
|
|
58
|
+
/** Validate a set of definitions, exiting with the collected errors on any
|
|
59
|
+
* failure. The single validate-then-fail gate `deploy` and `definitions diff`
|
|
60
|
+
* share, so the two can't drift into divergent failure messages. `context`
|
|
61
|
+
* prefixes the failure with the deployment it belongs to in multi-target runs. */
|
|
62
|
+
export declare function validateOrFail(defs: WorkflowDefinition[], context?: string): void;
|
|
63
|
+
export {};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { WORKFLOW_DEFINITION_TYPE, assertReadableModel, definitionPartitionsGroq, errorMessage, partitionScopeFilter, validateDefinition, } from '@sanity/workflows';
|
|
2
|
+
import { fail } from './fail.js';
|
|
3
|
+
export function buildDefinitionShowQuery(flags) {
|
|
4
|
+
const params = { name: flags.name };
|
|
5
|
+
const filters = [`_type == "${WORKFLOW_DEFINITION_TYPE}"`, 'name == $name'];
|
|
6
|
+
if (flags.version !== undefined) {
|
|
7
|
+
params.version = flags.version;
|
|
8
|
+
filters.push('version == $version');
|
|
9
|
+
}
|
|
10
|
+
if (flags.partition) {
|
|
11
|
+
params.tag = flags.partition;
|
|
12
|
+
filters.push(partitionScopeFilter());
|
|
13
|
+
}
|
|
14
|
+
const groq = `*[${filters.join(' && ')}] | order(version desc) [0]`;
|
|
15
|
+
return { groq, params };
|
|
16
|
+
}
|
|
17
|
+
export function buildDefinitionPartitionsQuery(name) {
|
|
18
|
+
return {
|
|
19
|
+
groq: definitionPartitionsGroq(),
|
|
20
|
+
params: { definition: name },
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export async function fetchDeployedDefinition({ client, name, partition, version, }) {
|
|
24
|
+
const { groq, params } = buildDefinitionShowQuery({ name, partition, version });
|
|
25
|
+
const deployed = await client.fetch(groq, params, {
|
|
26
|
+
tag: 'definition.load',
|
|
27
|
+
});
|
|
28
|
+
if (deployed === null && version !== undefined) {
|
|
29
|
+
fail(`No deployed definition "${name}" v${version}.`);
|
|
30
|
+
}
|
|
31
|
+
return deployed === null ? undefined : assertReadableModel(deployed);
|
|
32
|
+
}
|
|
33
|
+
function availableDefinitions(names) {
|
|
34
|
+
return `Available: ${names.join(', ')}`;
|
|
35
|
+
}
|
|
36
|
+
export function assertKnownDefinition(config, only) {
|
|
37
|
+
if (!only) {
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const names = new Set(config.deployments.flatMap((d) => d.definitions.map((def) => def.name)));
|
|
41
|
+
if (names.has(only)) {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
const namesADeployment = config.deployments.some((d) => d.name === only);
|
|
45
|
+
fail(`No definition named "${only}".`, namesADeployment
|
|
46
|
+
? `"${only}" is a deployment — did you mean --deployment ${only}?`
|
|
47
|
+
: availableDefinitions([...names]));
|
|
48
|
+
}
|
|
49
|
+
export function selectDefinitions(allDefinitions, { only, context = '' }) {
|
|
50
|
+
if (!only) {
|
|
51
|
+
return [...allDefinitions];
|
|
52
|
+
}
|
|
53
|
+
const filtered = allDefinitions.filter((d) => d.name === only);
|
|
54
|
+
if (filtered.length === 0) {
|
|
55
|
+
fail(`${context}No definition named "${only}".`, availableDefinitions(allDefinitions.map((d) => d.name)));
|
|
56
|
+
}
|
|
57
|
+
return filtered;
|
|
58
|
+
}
|
|
59
|
+
export function collectValidationErrors(defs) {
|
|
60
|
+
const errors = [];
|
|
61
|
+
const seen = new Map();
|
|
62
|
+
for (const d of defs) {
|
|
63
|
+
const count = (seen.get(d.name) ?? 0) + 1;
|
|
64
|
+
seen.set(d.name, count);
|
|
65
|
+
if (count === 2) {
|
|
66
|
+
errors.push(` · duplicate name "${d.name}" in local batch`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
for (const d of defs) {
|
|
70
|
+
try {
|
|
71
|
+
validateDefinition(d);
|
|
72
|
+
}
|
|
73
|
+
catch (err) {
|
|
74
|
+
errors.push(` · ${d.name}: ${errorMessage(err)}`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return errors;
|
|
78
|
+
}
|
|
79
|
+
export function validateOrFail(defs, context = '') {
|
|
80
|
+
const errors = collectValidationErrors(defs);
|
|
81
|
+
if (errors.length > 0) {
|
|
82
|
+
fail(`${context}Validation failed:`, errors.join('\n'));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { DiffEntry } from '@sanity/workflows';
|
|
2
|
+
/** One summary line per diff entry, tagged create / unchanged, followed by the
|
|
3
|
+
* warnings a deploy would print for it. Definitions are immutable, so a
|
|
4
|
+
* content change is a new version (`create`), never an update. */
|
|
5
|
+
export declare function summaryLines(entries: DiffEntry[]): string[];
|
|
6
|
+
/** Render a JSON diff of `oldObj` → `newObj` as `+`/`-`/context lines, long
|
|
7
|
+
* unchanged runs collapsed to a dim `… N unchanged lines` marker. */
|
|
8
|
+
export declare function diffLines(oldObj: object, newObj: object): string[];
|
|
9
|
+
/** The full diff report: the summary block plus a per-change diff of the
|
|
10
|
+
* authored content — the deploy envelope is stripped from both sides (the
|
|
11
|
+
* version and docId already render on the summary line). */
|
|
12
|
+
export declare function diffReport(entries: DiffEntry[]): string[];
|
package/dist/lib/diff.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { styleText } from 'node:util';
|
|
2
|
+
import { diffJson } from 'diff';
|
|
3
|
+
import logSymbols from 'log-symbols';
|
|
4
|
+
import { sectionHeader, warningLines } from './ui.js';
|
|
5
|
+
export function summaryLines(entries) {
|
|
6
|
+
const tags = {
|
|
7
|
+
create: styleText('green', '+ create '),
|
|
8
|
+
unchanged: styleText('dim', ' unchanged'),
|
|
9
|
+
};
|
|
10
|
+
return entries.flatMap((e) => {
|
|
11
|
+
const head = ` ${tags[e.status]} ${e.name} v${e.version} ${styleText('dim', `(${e.docId})`)}`;
|
|
12
|
+
return [head, ...warningLines(e.warnings)];
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
const CONTEXT_LINES = 3;
|
|
16
|
+
const DEPLOY_STAMPED_KEYS = new Set(['tag', 'version', 'contentHash']);
|
|
17
|
+
function authoredContent(doc) {
|
|
18
|
+
return Object.fromEntries(Object.entries(doc).filter(([key]) => !key.startsWith('_') && !DEPLOY_STAMPED_KEYS.has(key)));
|
|
19
|
+
}
|
|
20
|
+
function chunkKind(chunk) {
|
|
21
|
+
if (chunk.added) {
|
|
22
|
+
return 'added';
|
|
23
|
+
}
|
|
24
|
+
if (chunk.removed) {
|
|
25
|
+
return 'removed';
|
|
26
|
+
}
|
|
27
|
+
return 'context';
|
|
28
|
+
}
|
|
29
|
+
function taggedLines(oldObj, newObj) {
|
|
30
|
+
return diffJson(oldObj, newObj).flatMap((chunk) => {
|
|
31
|
+
const chunkLines = chunk.value.split('\n');
|
|
32
|
+
if (chunkLines.at(-1) === '') {
|
|
33
|
+
chunkLines.pop();
|
|
34
|
+
}
|
|
35
|
+
return chunkLines.map((text) => ({ kind: chunkKind(chunk), text }));
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
function collapseUnchanged(lines, context) {
|
|
39
|
+
const changed = lines.flatMap((line, i) => (line.kind === 'context' ? [] : [i]));
|
|
40
|
+
if (changed.length === 0) {
|
|
41
|
+
return lines;
|
|
42
|
+
}
|
|
43
|
+
const keep = lines.map((_, i) => changed.some((c) => Math.abs(c - i) <= context));
|
|
44
|
+
const out = [];
|
|
45
|
+
let run = [];
|
|
46
|
+
const flushRun = () => {
|
|
47
|
+
if (run.length === 1) {
|
|
48
|
+
out.push(...run);
|
|
49
|
+
}
|
|
50
|
+
else if (run.length > 1) {
|
|
51
|
+
out.push({ kind: 'elision', count: run.length });
|
|
52
|
+
}
|
|
53
|
+
run = [];
|
|
54
|
+
};
|
|
55
|
+
lines.forEach((line, i) => {
|
|
56
|
+
if (keep[i]) {
|
|
57
|
+
flushRun();
|
|
58
|
+
out.push(line);
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
run.push(line);
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
flushRun();
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
function renderLine(line) {
|
|
68
|
+
if (line.kind === 'elision') {
|
|
69
|
+
return styleText('dim', ` … ${line.count} unchanged lines`);
|
|
70
|
+
}
|
|
71
|
+
if (line.kind === 'added') {
|
|
72
|
+
return styleText('green', `+ ${line.text}`);
|
|
73
|
+
}
|
|
74
|
+
if (line.kind === 'removed') {
|
|
75
|
+
return styleText('red', `- ${line.text}`);
|
|
76
|
+
}
|
|
77
|
+
return styleText('dim', ` ${line.text}`);
|
|
78
|
+
}
|
|
79
|
+
export function diffLines(oldObj, newObj) {
|
|
80
|
+
return collapseUnchanged(taggedLines(oldObj, newObj), CONTEXT_LINES).map(renderLine);
|
|
81
|
+
}
|
|
82
|
+
export function diffReport(entries) {
|
|
83
|
+
const lines = ['', sectionHeader('Summary'), ...summaryLines(entries)];
|
|
84
|
+
const changes = entries.filter((e) => e.status !== 'unchanged');
|
|
85
|
+
if (changes.length === 0) {
|
|
86
|
+
lines.push('', `${logSymbols.success} no changes — running deploy would be a no-op`);
|
|
87
|
+
return lines;
|
|
88
|
+
}
|
|
89
|
+
for (const e of changes) {
|
|
90
|
+
lines.push('', styleText('bold', `── ${e.name} v${e.version} ──`), ...diffLines(authoredContent(e.existing ?? {}), authoredContent(e.expected)));
|
|
91
|
+
}
|
|
92
|
+
return lines;
|
|
93
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const ENV: {
|
|
2
|
+
readonly SANITY_AUTH_TOKEN: 'SANITY_AUTH_TOKEN';
|
|
3
|
+
readonly SANITY_API_HOST: 'SANITY_API_HOST';
|
|
4
|
+
};
|
|
5
|
+
/** The explicit env token, or undefined when unset/blank. Token resolution
|
|
6
|
+
* and the auth recovery hint must agree on this. */
|
|
7
|
+
export declare function envAuthToken(): string | undefined;
|
package/dist/lib/env.js
ADDED