@sanity/workflows-cli 0.0.0-main-039-20261113092657

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/CHANGELOG.md +1936 -0
  2. package/LICENSE +21 -0
  3. package/README.md +814 -0
  4. package/bin/run.js +8 -0
  5. package/dist/command-ids.d.ts +10 -0
  6. package/dist/command-ids.js +10 -0
  7. package/dist/commands/workflows/abort.d.ts +29 -0
  8. package/dist/commands/workflows/abort.js +50 -0
  9. package/dist/commands/workflows/blueprints/generate.d.ts +12 -0
  10. package/dist/commands/workflows/blueprints/generate.js +46 -0
  11. package/dist/commands/workflows/codemod/packages.d.ts +13 -0
  12. package/dist/commands/workflows/codemod/packages.js +41 -0
  13. package/dist/commands/workflows/definitions/delete.d.ts +44 -0
  14. package/dist/commands/workflows/definitions/delete.js +74 -0
  15. package/dist/commands/workflows/definitions/diff.d.ts +23 -0
  16. package/dist/commands/workflows/definitions/diff.js +55 -0
  17. package/dist/commands/workflows/definitions/list.d.ts +51 -0
  18. package/dist/commands/workflows/definitions/list.js +139 -0
  19. package/dist/commands/workflows/definitions/show.d.ts +65 -0
  20. package/dist/commands/workflows/definitions/show.js +129 -0
  21. package/dist/commands/workflows/definitions/validate.d.ts +14 -0
  22. package/dist/commands/workflows/definitions/validate.js +50 -0
  23. package/dist/commands/workflows/deploy.d.ts +117 -0
  24. package/dist/commands/workflows/deploy.js +266 -0
  25. package/dist/commands/workflows/diagnose.d.ts +52 -0
  26. package/dist/commands/workflows/diagnose.js +195 -0
  27. package/dist/commands/workflows/fire-action.d.ts +53 -0
  28. package/dist/commands/workflows/fire-action.js +182 -0
  29. package/dist/commands/workflows/list.d.ts +78 -0
  30. package/dist/commands/workflows/list.js +248 -0
  31. package/dist/commands/workflows/nuke.d.ts +73 -0
  32. package/dist/commands/workflows/nuke.js +176 -0
  33. package/dist/commands/workflows/reset-activity.d.ts +32 -0
  34. package/dist/commands/workflows/reset-activity.js +60 -0
  35. package/dist/commands/workflows/show.d.ts +29 -0
  36. package/dist/commands/workflows/show.js +156 -0
  37. package/dist/commands/workflows/start.d.ts +57 -0
  38. package/dist/commands/workflows/start.js +196 -0
  39. package/dist/commands/workflows/tail.d.ts +23 -0
  40. package/dist/commands/workflows/tail.js +83 -0
  41. package/dist/commands/workflows/whoami.d.ts +15 -0
  42. package/dist/commands/workflows/whoami.js +53 -0
  43. package/dist/help.d.ts +13 -0
  44. package/dist/help.js +50 -0
  45. package/dist/hooks/finally/telemetry.d.ts +3 -0
  46. package/dist/hooks/finally/telemetry.js +10 -0
  47. package/dist/hooks/prerun/telemetry.d.ts +28 -0
  48. package/dist/hooks/prerun/telemetry.js +37 -0
  49. package/dist/index.d.ts +1 -0
  50. package/dist/index.js +1 -0
  51. package/dist/lib/base-command.d.ts +14 -0
  52. package/dist/lib/base-command.js +41 -0
  53. package/dist/lib/blueprint-emit.d.ts +56 -0
  54. package/dist/lib/blueprint-emit.js +233 -0
  55. package/dist/lib/blueprint-needs.d.ts +5 -0
  56. package/dist/lib/blueprint-needs.js +231 -0
  57. package/dist/lib/blueprint-stacks.d.ts +6 -0
  58. package/dist/lib/blueprint-stacks.js +111 -0
  59. package/dist/lib/cause-detail.d.ts +9 -0
  60. package/dist/lib/cause-detail.js +112 -0
  61. package/dist/lib/client.d.ts +27 -0
  62. package/dist/lib/client.js +45 -0
  63. package/dist/lib/codemod/ast.d.ts +17 -0
  64. package/dist/lib/codemod/ast.js +14 -0
  65. package/dist/lib/codemod/export-rename.d.ts +17 -0
  66. package/dist/lib/codemod/export-rename.js +253 -0
  67. package/dist/lib/codemod/manifest-rewrite.d.ts +14 -0
  68. package/dist/lib/codemod/manifest-rewrite.js +97 -0
  69. package/dist/lib/codemod/package-map.d.ts +26 -0
  70. package/dist/lib/codemod/package-map.js +90 -0
  71. package/dist/lib/codemod/report.d.ts +4 -0
  72. package/dist/lib/codemod/report.js +46 -0
  73. package/dist/lib/codemod/run.d.ts +23 -0
  74. package/dist/lib/codemod/run.js +106 -0
  75. package/dist/lib/codemod/source-rewrite.d.ts +20 -0
  76. package/dist/lib/codemod/source-rewrite.js +149 -0
  77. package/dist/lib/command-context.d.ts +20 -0
  78. package/dist/lib/command-context.js +24 -0
  79. package/dist/lib/command-telemetry.d.ts +54 -0
  80. package/dist/lib/command-telemetry.js +82 -0
  81. package/dist/lib/context.d.ts +155 -0
  82. package/dist/lib/context.js +272 -0
  83. package/dist/lib/default-partition.d.ts +23 -0
  84. package/dist/lib/default-partition.js +48 -0
  85. package/dist/lib/definition-files.d.ts +14 -0
  86. package/dist/lib/definition-files.js +60 -0
  87. package/dist/lib/definitions.d.ts +63 -0
  88. package/dist/lib/definitions.js +84 -0
  89. package/dist/lib/diff.d.ts +12 -0
  90. package/dist/lib/diff.js +93 -0
  91. package/dist/lib/env.d.ts +7 -0
  92. package/dist/lib/env.js +8 -0
  93. package/dist/lib/fail.d.ts +36 -0
  94. package/dist/lib/fail.js +55 -0
  95. package/dist/lib/failure-kind.d.ts +7 -0
  96. package/dist/lib/failure-kind.js +66 -0
  97. package/dist/lib/flags.d.ts +49 -0
  98. package/dist/lib/flags.js +117 -0
  99. package/dist/lib/follow-up-command.d.ts +18 -0
  100. package/dist/lib/follow-up-command.js +12 -0
  101. package/dist/lib/history-rows.d.ts +3 -0
  102. package/dist/lib/history-rows.js +44 -0
  103. package/dist/lib/load-config.d.ts +51 -0
  104. package/dist/lib/load-config.js +108 -0
  105. package/dist/lib/nuke.d.ts +124 -0
  106. package/dist/lib/nuke.js +206 -0
  107. package/dist/lib/operation-args.d.ts +42 -0
  108. package/dist/lib/operation-args.js +21 -0
  109. package/dist/lib/ops-report.d.ts +45 -0
  110. package/dist/lib/ops-report.js +31 -0
  111. package/dist/lib/params.d.ts +3 -0
  112. package/dist/lib/params.js +21 -0
  113. package/dist/lib/pick-dataset.d.ts +10 -0
  114. package/dist/lib/pick-dataset.js +30 -0
  115. package/dist/lib/prompt.d.ts +35 -0
  116. package/dist/lib/prompt.js +11 -0
  117. package/dist/lib/read-fanout.d.ts +45 -0
  118. package/dist/lib/read-fanout.js +44 -0
  119. package/dist/lib/select-deployment.d.ts +31 -0
  120. package/dist/lib/select-deployment.js +91 -0
  121. package/dist/lib/share-definitions.d.ts +101 -0
  122. package/dist/lib/share-definitions.js +188 -0
  123. package/dist/lib/telemetry-setup.d.ts +81 -0
  124. package/dist/lib/telemetry-setup.js +111 -0
  125. package/dist/lib/telemetry.d.ts +81 -0
  126. package/dist/lib/telemetry.js +90 -0
  127. package/dist/lib/ui.d.ts +91 -0
  128. package/dist/lib/ui.js +116 -0
  129. package/dist/standalone-argv.d.ts +14 -0
  130. package/dist/standalone-argv.js +57 -0
  131. package/oclif.manifest.json +1731 -0
  132. package/package.json +121 -0
@@ -0,0 +1,82 @@
1
+ import { configFlags, flagTokens } from './flags.js';
2
+ const ALWAYS_REDACTED = Object.keys(configFlags);
3
+ export function defineCommandTelemetry(flags, config) {
4
+ return { redacted: [...(config.redact ?? [])] };
5
+ }
6
+ export function collectOptionArguments(args) {
7
+ const { argv, flagDefs, commandTelemetry } = args;
8
+ const tokens = flagTokens(argv);
9
+ const reported = [];
10
+ let skip = false;
11
+ for (const [index, token] of tokens.entries()) {
12
+ if (skip) {
13
+ skip = false;
14
+ continue;
15
+ }
16
+ if (!token.startsWith('-')) {
17
+ continue;
18
+ }
19
+ const outcome = reportToken({
20
+ token,
21
+ next: tokens[index + 1],
22
+ flagDefs,
23
+ commandTelemetry,
24
+ });
25
+ if (outcome.reported !== undefined) {
26
+ reported.push(outcome.reported);
27
+ }
28
+ skip = outcome.consumedNext;
29
+ }
30
+ return reported;
31
+ }
32
+ function reportToken(args) {
33
+ const { token, next, flagDefs, commandTelemetry } = args;
34
+ const declared = Object.entries(flagDefs ?? {}).find(([name, def]) => matchesFlag({ token, name, def }));
35
+ if (declared === undefined) {
36
+ const reported = nameOnly(token);
37
+ return { reported, consumedNext: reported !== undefined && inlineValue(token) === undefined };
38
+ }
39
+ const [name, def] = declared;
40
+ if (def.type !== 'option') {
41
+ return { reported: token.startsWith('--no-') ? `--no-${name}` : `--${name}`, consumedNext: false };
42
+ }
43
+ const inline = inlineValue(token);
44
+ const spaced = inline === undefined ? next : undefined;
45
+ const value = inline ?? spaced;
46
+ if (isRedacted(name, commandTelemetry) || value === undefined) {
47
+ return { reported: `--${name}`, consumedNext: spaced !== undefined };
48
+ }
49
+ return { reported: `--${name}=${value}`, consumedNext: spaced !== undefined };
50
+ }
51
+ function isRedacted(name, commandTelemetry) {
52
+ return ALWAYS_REDACTED.includes(name) || commandTelemetry?.redacted.includes(name) === true;
53
+ }
54
+ function inlineValue(token) {
55
+ if (token.startsWith('--')) {
56
+ const separator = token.indexOf('=');
57
+ return separator === -1 ? undefined : token.slice(separator + 1);
58
+ }
59
+ if (token.length <= 2) {
60
+ return undefined;
61
+ }
62
+ return token.slice(token[2] === '=' ? 3 : 2);
63
+ }
64
+ function nameOnly(token) {
65
+ const separator = token.indexOf('=');
66
+ const name = token.startsWith('--')
67
+ ? token.slice(0, separator === -1 ? undefined : separator)
68
+ : token.slice(0, 2);
69
+ return /\s/.test(name) ? undefined : name;
70
+ }
71
+ function matchesFlag(args) {
72
+ const { token, name, def } = args;
73
+ const longForms = [name, ...(def.aliases ?? [])];
74
+ const shortForms = [...(def.char === undefined ? [] : [def.char]), ...(def.charAliases ?? [])];
75
+ if (longForms.some((form) => matchesLong(token, form))) {
76
+ return true;
77
+ }
78
+ return shortForms.some((form) => token.startsWith(`-${form}`) && !token.startsWith('--'));
79
+ }
80
+ function matchesLong(token, form) {
81
+ return token === `--${form}` || token.startsWith(`--${form}=`) || token === `--no-${form}`;
82
+ }
@@ -0,0 +1,155 @@
1
+ import type { SanityClient } from '@sanity/client';
2
+ import { type WorkflowConfig, type WorkflowDeployment, type WorkflowInstance, type WorkflowResource } from '@sanity/workflows';
3
+ import type { EngineScope } from './operation-args.ts';
4
+ export interface DeploymentContext {
5
+ deployment: WorkflowDeployment;
6
+ client: SanityClient;
7
+ scope: EngineScope;
8
+ }
9
+ export interface InstanceContext {
10
+ client: SanityClient;
11
+ scope: EngineScope;
12
+ }
13
+ /** Resolve the selected deployment. Deploy, definition-diff, and blueprint provision compare
14
+ * its acknowledgement with submitted definitions; selection alone must not assert a floor. */
15
+ export declare function resolveContext(flags: {
16
+ path?: string | undefined;
17
+ deployment?: string | undefined;
18
+ partition?: string | undefined;
19
+ }): Promise<DeploymentContext>;
20
+ /**
21
+ * The engine scope for an instance a read located. The partition comes from
22
+ * the instance's stored `tag`; alias-bound resource clients come from the
23
+ * configured deployment with that partition on the hit's resource, if any.
24
+ */
25
+ export declare function instanceScope(hit: InstanceHit): EngineScope;
26
+ /** One resource a read inspects, with its authenticated client and the
27
+ * configured deployments on it, which name it in an ambiguity. */
28
+ export interface ReadTarget {
29
+ resource: WorkflowResource;
30
+ client: SanityClient;
31
+ deployments: readonly WorkflowDeployment[];
32
+ }
33
+ interface ResourceTargetFlags {
34
+ 'project-id'?: string | undefined;
35
+ dataset?: string | undefined;
36
+ 'media-library-id'?: string | undefined;
37
+ }
38
+ export interface ReadScope {
39
+ targets: ReadTarget[];
40
+ partition: string | undefined;
41
+ }
42
+ /** What a lookup does with several hits: ask on stderr, fail naming the
43
+ * candidates, or return none so a wider search decides. */
44
+ export type Ambiguity = 'prompt' | 'fail' | 'defer';
45
+ export declare function ambiguityFor(flags: {
46
+ json?: boolean | undefined;
47
+ }): Ambiguity;
48
+ /**
49
+ * The resolution every READ shares: an authenticated client per resource to
50
+ * inspect, and the partition to filter on. A read lists whatever is in the
51
+ * Content Lake, so without a selector it inherits no deployment's partition or
52
+ * definition set. The command applies the returned partition as a query filter.
53
+ *
54
+ * Without a selector, this is every distinct resource the config mentions.
55
+ * `--partition` narrows to the resources deployed under that partition
56
+ * (partitions may repeat across deployments). `--deployment` narrows to that
57
+ * deployment's resource and partition. `--project-id`/`--dataset` or
58
+ * `--media-library-id` replace the config's resources with the one they name, and
59
+ * no config loads; `--partition` still filters. With no config found, the run
60
+ * reads the dataset picked on an interactive terminal. The token resolves once for the
61
+ * run, however many targets it spans.
62
+ */
63
+ export declare function resolveReadTargets(flags: InstanceSelectorFlags): Promise<ReadScope>;
64
+ /** Distinct resources, keyed by their resource-shaped GDR (`<type>:<id>`).
65
+ * The first occurrence wins its position, so a caller-ordered list (e.g. the
66
+ * engine resource first) keeps its lead entry. */
67
+ export declare function dedupeResources(resources: WorkflowResource[]): WorkflowResource[];
68
+ /** The distinct resources a read targets: every resource deployed under the
69
+ * partition (partitions may repeat across deployments), or — without one —
70
+ * every distinct one the config's deployments mention ({@link dedupeResources}). */
71
+ export declare function resolveReadResources(config: WorkflowConfig, partition: string | undefined): WorkflowResource[];
72
+ /**
73
+ * The resolution an instance-id-targeted command shares, read or write: locate
74
+ * the instance by the same cross-resource fan-out the read/list commands use
75
+ * ({@link findInstance}), then hand back an authenticated client for the
76
+ * resource that held it plus a scope whose `partition` comes from the
77
+ * instance's stored `tag` field — never from the config's declared deployments.
78
+ * An instance id is globally unique and carries its own partition, so naming
79
+ * one is enough to act on it: the config only locates candidate resources, and the fan-out's
80
+ * {@link soleHitOrChoose} settles the collision case where several datasets hold
81
+ * the id (the `<partition>.` fast-path may skip that full-set check — safe, ids are
82
+ * collision-free). `--deployment` / `--partition` stay optional narrowers, not
83
+ * required disambiguators.
84
+ *
85
+ * Contrast {@link resolveContext}: the deploy/diff/delete path IS scoped to a
86
+ * declared deployment because it acts on the authored definition set (or a
87
+ * definition name, which — unlike an instance id — isn't unique across partitions).
88
+ */
89
+ export declare function resolveInstanceContext(flags: InstanceSelectorFlags, instanceId: string): Promise<InstanceContext>;
90
+ /** {@link resolveInstanceContext} for a command that only reads, so with no
91
+ * config found it can locate the instance in a dataset picked on stderr. */
92
+ export declare function resolveReadInstanceContext(flags: InstanceSelectorFlags, instanceId: string): Promise<InstanceContext>;
93
+ interface InstanceSelectorFlags extends ResourceTargetFlags {
94
+ path?: string | undefined;
95
+ deployment?: string | undefined;
96
+ partition?: string | undefined;
97
+ json?: boolean | undefined;
98
+ }
99
+ /** An instance located without interpreting its shape — the resource that held
100
+ * it and the {@link InstanceStamps} a delete gates on. */
101
+ export interface InstanceStampsContext {
102
+ resource: WorkflowResource;
103
+ stamps: InstanceStamps;
104
+ }
105
+ /**
106
+ * Locate an instance by the same fan-out and `<tag>.` fast-path as
107
+ * {@link resolveInstanceContext}, but reading only a projection — for the one
108
+ * caller that must not be refused by the reader-floor gate. See
109
+ * {@link findInstanceStamps} for why `nuke --instance` is that caller.
110
+ *
111
+ * Returns no client: a projection cannot be acted on through an engine verb, so
112
+ * the caller builds its own write clients from the deployment it resolves.
113
+ */
114
+ export declare function resolveInstanceStamps(flags: InstanceSelectorFlags, instanceId: string): Promise<InstanceStampsContext>;
115
+ /** A read target that turned out to hold the instance being looked up. */
116
+ export interface InstanceHit extends ReadTarget {
117
+ instance: WorkflowInstance;
118
+ }
119
+ export type ChooseCandidate = (choices: {
120
+ name: string;
121
+ value: string;
122
+ description: string;
123
+ }[]) => Promise<string>;
124
+ /** `subject` names the thing looked up in the diagnostic (`Instance <id>`, `Definition "x"`). */
125
+ export declare function soleHitOrChoose<T extends ReadTarget>(hits: T[], args: {
126
+ subject: string;
127
+ partitionOf: (hit: T) => string | undefined;
128
+ ambiguity: Ambiguity;
129
+ choose?: ChooseCandidate;
130
+ }): Promise<T | undefined>;
131
+ /**
132
+ * Look an instance id up across every read target, reading each hit as a full
133
+ * engine-gated instance document — the locate every command that then acts
134
+ * through an engine verb uses. See {@link findAcrossTargets} for the
135
+ * one-hit-wins semantics.
136
+ */
137
+ export declare function findInstance({ targets, instanceId, requestTag, ambiguity, }: {
138
+ targets: ReadTarget[];
139
+ instanceId: string;
140
+ requestTag: string;
141
+ ambiguity: Ambiguity;
142
+ }): Promise<InstanceHit | undefined>;
143
+ /**
144
+ * The four persisted fields a delete needs to decide it may proceed, read
145
+ * WITHOUT interpreting the document's shape: `_type` to prove it is an engine
146
+ * instance and not co-located content, `tag` to locate the owning deployment,
147
+ * and the terminal stamps to prove it has settled.
148
+ */
149
+ export interface InstanceStamps {
150
+ _type: string;
151
+ tag?: string;
152
+ completedAt?: string;
153
+ abortedAt?: string;
154
+ }
155
+ export {};
@@ -0,0 +1,272 @@
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 {
17
+ deployment,
18
+ client,
19
+ scope: deploymentScope({ client, deployment, partition: deployment.partition }),
20
+ };
21
+ }
22
+ function deploymentScope({ client, deployment, partition, }) {
23
+ return {
24
+ partition,
25
+ workflowResource: deployment.workflowResource,
26
+ resourceClients: deploymentResourceClients({ client, deployment }),
27
+ };
28
+ }
29
+ export function instanceScope(hit) {
30
+ const owner = hit.deployments.find((deployment) => deployment.partition === hit.instance.tag);
31
+ return deploymentScope({
32
+ client: hit.client,
33
+ deployment: owner ?? { workflowResource: hit.resource },
34
+ partition: hit.instance.tag,
35
+ });
36
+ }
37
+ function targetsFor(args) {
38
+ return args.resources.map((resource) => ({
39
+ resource,
40
+ client: clientFor(resource, args.token),
41
+ deployments: args.config.deployments.filter((deployment) => resourceGdr(deployment.workflowResource) === resourceGdr(resource)),
42
+ }));
43
+ }
44
+ function explicitResource(flags) {
45
+ if (flags['media-library-id'] !== undefined) {
46
+ return { type: 'media-library', id: flags['media-library-id'] };
47
+ }
48
+ if (flags['project-id'] !== undefined && flags.dataset !== undefined) {
49
+ return { type: 'dataset', id: `${flags['project-id']}.${flags.dataset}` };
50
+ }
51
+ return undefined;
52
+ }
53
+ function unconfiguredTarget(resource, token) {
54
+ return { resource, client: clientFor(resource, token), deployments: [] };
55
+ }
56
+ export function ambiguityFor(flags) {
57
+ return canAsk(flags) ? 'prompt' : 'fail';
58
+ }
59
+ function canAsk(flags) {
60
+ return flags.json !== true && canPromptOnStderr();
61
+ }
62
+ export async function resolveReadTargets(flags) {
63
+ const source = await readSource(flags, { pick: true });
64
+ if ('resource' in source) {
65
+ return {
66
+ targets: [unconfiguredTarget(source.resource, source.token)],
67
+ partition: flags.partition,
68
+ };
69
+ }
70
+ const { config, token } = source;
71
+ if (flags.deployment !== undefined) {
72
+ const deployment = await selectDeployment(config, {
73
+ name: flags.deployment,
74
+ partition: undefined,
75
+ });
76
+ const resources = [deployment.workflowResource];
77
+ return { targets: targetsFor({ config, resources, token }), partition: deployment.partition };
78
+ }
79
+ const resources = resolveReadResources(config, flags.partition);
80
+ return { targets: targetsFor({ config, resources, token }), partition: flags.partition };
81
+ }
82
+ async function readSource(flags, { pick }) {
83
+ const resource = explicitResource(flags);
84
+ if (resource !== undefined) {
85
+ return { resource, token: await resolveTokenOrFail() };
86
+ }
87
+ if (!pick || flags.path !== undefined || flags.deployment !== undefined) {
88
+ return configSource(flags.path);
89
+ }
90
+ const config = await loadWorkflowConfigIfFound();
91
+ if (config !== undefined) {
92
+ return { config, token: await resolveTokenOrFail() };
93
+ }
94
+ if (!canAsk(flags)) {
95
+ fail(noConfigFound(), RESOURCE_FLAGS_HINT);
96
+ }
97
+ const token = await resolveTokenOrFail();
98
+ return { resource: await pickDataset(token), token };
99
+ }
100
+ async function configSource(path) {
101
+ return { config: await loadWorkflowConfig(path), token: await resolveTokenOrFail() };
102
+ }
103
+ export function dedupeResources(resources) {
104
+ return [...new Map(resources.map((resource) => [resourceGdr(resource), resource])).values()];
105
+ }
106
+ export function resolveReadResources(config, partition) {
107
+ if (partition !== undefined) {
108
+ return dedupeResources(deploymentsForPartition(config, partition).map((deployment) => deployment.workflowResource));
109
+ }
110
+ const resources = dedupeResources(config.deployments.map((d) => d.workflowResource));
111
+ if (resources.length === 0) {
112
+ fail('No deployments configured.');
113
+ }
114
+ return resources;
115
+ }
116
+ const LOCATE_TAG = 'instance.load';
117
+ export function resolveInstanceContext(flags, instanceId) {
118
+ return instanceContext({ flags, instanceId, read: false });
119
+ }
120
+ export function resolveReadInstanceContext(flags, instanceId) {
121
+ return instanceContext({ flags, instanceId, read: true });
122
+ }
123
+ async function instanceContext({ flags, instanceId, read, }) {
124
+ const hit = await locateInstance({
125
+ flags,
126
+ instanceId,
127
+ read,
128
+ find: (targets, ambiguity) => findInstance({ targets, instanceId, requestTag: LOCATE_TAG, ambiguity }),
129
+ });
130
+ if (hit === undefined) {
131
+ fail(`Workflow instance ${instanceId} not found`);
132
+ }
133
+ return { client: hit.client, scope: instanceScope(hit) };
134
+ }
135
+ export async function resolveInstanceStamps(flags, instanceId) {
136
+ const hit = await locateInstance({
137
+ flags,
138
+ instanceId,
139
+ read: false,
140
+ find: (targets, ambiguity) => findInstanceStamps({ targets, instanceId, requestTag: LOCATE_TAG, ambiguity }),
141
+ });
142
+ if (hit === undefined) {
143
+ fail(`Workflow instance ${instanceId} not found`);
144
+ }
145
+ return { resource: hit.resource, stamps: hit.stamps };
146
+ }
147
+ async function locateInstance({ flags, instanceId, read, find, }) {
148
+ const source = await readSource(flags, { pick: read });
149
+ if ('resource' in source) {
150
+ return find([unconfiguredTarget(source.resource, source.token)], ambiguityFor(flags));
151
+ }
152
+ const { config, token } = source;
153
+ const resources = await instanceCandidateResources(config, flags);
154
+ const fanOut = () => find(targetsFor({ config, resources, token }), ambiguityFor(flags));
155
+ const explicit = flags.deployment !== undefined || flags.partition !== undefined;
156
+ const hinted = explicit || resources.length <= 1
157
+ ? []
158
+ : hintedResources({ config, instanceId, candidates: resources });
159
+ if (hinted.length === 0 || hinted.length === resources.length) {
160
+ return fanOut();
161
+ }
162
+ const hit = await hintedProbe(() => find(targetsFor({ config, resources: hinted, token }), 'defer'));
163
+ return hit ?? fanOut();
164
+ }
165
+ async function hintedProbe(probe) {
166
+ try {
167
+ return await probe();
168
+ }
169
+ catch {
170
+ return undefined;
171
+ }
172
+ }
173
+ async function instanceCandidateResources(config, { deployment, partition }) {
174
+ if (deployment !== undefined) {
175
+ return [
176
+ (await selectDeployment(config, { name: deployment, partition: undefined })).workflowResource,
177
+ ];
178
+ }
179
+ return resolveReadResources(config, partition);
180
+ }
181
+ function hintedResources({ config, instanceId, candidates, }) {
182
+ const dot = instanceId.indexOf('.');
183
+ if (dot <= 0) {
184
+ return [];
185
+ }
186
+ const prefix = instanceId.slice(0, dot);
187
+ const taggedGdrs = new Set(config.deployments
188
+ .filter((deployment) => deployment.partition === prefix)
189
+ .map((deployment) => resourceGdr(deployment.workflowResource)));
190
+ return candidates.filter((resource) => taggedGdrs.has(resourceGdr(resource)));
191
+ }
192
+ function chooseCandidateOnStderr(choices) {
193
+ return selectOnStderr({ message: 'Select a deployment', choices });
194
+ }
195
+ function candidateName(hit, partition) {
196
+ const deployment = hit.deployments.find((candidate) => candidate.partition === partition);
197
+ if (deployment !== undefined) {
198
+ return deployment.name;
199
+ }
200
+ return partition === undefined ? 'unconfigured' : `partition "${partition}"`;
201
+ }
202
+ export async function soleHitOrChoose(hits, args) {
203
+ const [sole, ...rest] = hits;
204
+ if (rest.length === 0) {
205
+ return sole;
206
+ }
207
+ if (args.ambiguity === 'defer') {
208
+ return undefined;
209
+ }
210
+ const candidates = hits.map((hit, index) => ({
211
+ name: candidateName(hit, args.partitionOf(hit)),
212
+ value: String(index),
213
+ description: resourceLabel(hit.resource),
214
+ }));
215
+ if (args.ambiguity === 'fail') {
216
+ fail(`${args.subject} exists in several deployments — pass --deployment to choose one.`, candidates.map(({ name, description }) => `${name} (${description})`).join('\n'));
217
+ }
218
+ const chosen = await (args.choose ?? chooseCandidateOnStderr)(candidates);
219
+ return hits[Number(chosen)];
220
+ }
221
+ async function findAcrossTargets({ targets, subject, probe, partitionOf, ambiguity, }) {
222
+ const probes = await Promise.allSettled(targets.map(probe));
223
+ const hits = probes
224
+ .filter((settled) => settled.status === 'fulfilled')
225
+ .map((settled) => settled.value)
226
+ .filter((hit) => hit !== undefined);
227
+ const sole = await soleHitOrChoose(hits, { subject, partitionOf, ambiguity });
228
+ if (sole !== undefined) {
229
+ return sole;
230
+ }
231
+ const failedProbe = probes.find((settled) => settled.status === 'rejected');
232
+ if (failedProbe !== undefined) {
233
+ throw failedProbe.reason;
234
+ }
235
+ return undefined;
236
+ }
237
+ export function findInstance({ targets, instanceId, requestTag, ambiguity, }) {
238
+ return findAcrossTargets({
239
+ targets,
240
+ subject: `Instance ${instanceId}`,
241
+ partitionOf: (hit) => hit.instance.tag,
242
+ ambiguity,
243
+ probe: async (target) => {
244
+ const instance = await target.client.getDocument(instanceId, {
245
+ tag: requestTag,
246
+ });
247
+ return instance === undefined
248
+ ? undefined
249
+ : { ...target, instance: assertReadableModel(instance) };
250
+ },
251
+ });
252
+ }
253
+ function findInstanceStamps({ targets, instanceId, requestTag, ambiguity, }) {
254
+ return findAcrossTargets({
255
+ targets,
256
+ subject: `Instance ${instanceId}`,
257
+ partitionOf: (hit) => hit.stamps.tag,
258
+ ambiguity,
259
+ probe: async (target) => {
260
+ const projected = await target.client.fetch(`*[_id == $instanceId][0]{_type, tag, completedAt, abortedAt}`, { instanceId }, { perspective: 'raw', tag: requestTag });
261
+ return projected === null ? undefined : { ...target, stamps: stampsOf(projected) };
262
+ },
263
+ });
264
+ }
265
+ function stampsOf({ _type, tag, completedAt, abortedAt }) {
266
+ return {
267
+ _type,
268
+ ...(tag === null ? {} : { tag }),
269
+ ...(completedAt === null ? {} : { completedAt }),
270
+ ...(abortedAt === null ? {} : { abortedAt }),
271
+ };
272
+ }
@@ -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,14 @@
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
+ /** A definition file that is not JSON, or holds something other than workflow definitions. */
8
+ export declare class DefinitionFileError extends Error {
9
+ }
10
+ export declare function readDefinitionFiles(paths: readonly string[]): Promise<DefinitionFileEntry[]>;
11
+ export declare function describeValidation(entries: readonly DefinitionFileEntry[], report: ValidateDefinitionInputsResult): {
12
+ passed: string[];
13
+ failed: string[];
14
+ };
@@ -0,0 +1,60 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { errorMessage } from '@sanity/workflows';
3
+ export class DefinitionFileError extends Error {
4
+ }
5
+ export async function readDefinitionFiles(paths) {
6
+ const files = await Promise.all(paths.map(async (path) => ({ path, value: parseJson(path, await readFile(path, 'utf8')) })));
7
+ return files.flatMap(({ path, value }) => definitionEntries(path, value));
8
+ }
9
+ export function describeValidation(entries, report) {
10
+ const passed = [];
11
+ const failed = [];
12
+ report.results.forEach((result, index) => {
13
+ const label = entries[index]?.label;
14
+ if (label === undefined) {
15
+ throw new Error(`validation result ${index} has no matching definition entry`);
16
+ }
17
+ if (result.valid) {
18
+ passed.push(`${label}: ${result.definition.name}`);
19
+ }
20
+ else {
21
+ failed.push(`${label}: ${result.error}`);
22
+ }
23
+ });
24
+ return { passed, failed };
25
+ }
26
+ function parseJson(path, source) {
27
+ try {
28
+ return JSON.parse(source);
29
+ }
30
+ catch (err) {
31
+ throw new DefinitionFileError(`${path}: not valid JSON (${errorMessage(err)})`, { cause: err });
32
+ }
33
+ }
34
+ function definitionEntries(path, value) {
35
+ if (!Array.isArray(value)) {
36
+ return [{ label: path, definition: definitionObject(value, path) }];
37
+ }
38
+ if (value.length === 0) {
39
+ throw new DefinitionFileError(`${path}: the array holds no definitions`);
40
+ }
41
+ return value.map((item, index) => {
42
+ const label = `${path}[${index}]`;
43
+ return { label, definition: definitionObject(item, label) };
44
+ });
45
+ }
46
+ function definitionObject(value, label) {
47
+ if (!isJsonObject(value)) {
48
+ throw new DefinitionFileError(`${label}: expected a workflow definition object, got ${jsonKind(value)}`);
49
+ }
50
+ return value;
51
+ }
52
+ function isJsonObject(value) {
53
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
54
+ }
55
+ function jsonKind(value) {
56
+ if (value === null) {
57
+ return 'null';
58
+ }
59
+ return Array.isArray(value) ? 'an array' : typeof value;
60
+ }