@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.
Files changed (126) hide show
  1. package/CHANGELOG.md +1574 -0
  2. package/LICENSE +21 -0
  3. package/README.md +797 -2
  4. package/bin/run.js +8 -0
  5. package/dist/command-ids.d.ts +10 -0
  6. package/dist/command-ids.js +10 -0
  7. package/dist/commands/workflows/abort.d.ts +29 -0
  8. package/dist/commands/workflows/abort.js +50 -0
  9. package/dist/commands/workflows/blueprints/generate.d.ts +12 -0
  10. package/dist/commands/workflows/blueprints/generate.js +46 -0
  11. package/dist/commands/workflows/codemod/packages.d.ts +13 -0
  12. package/dist/commands/workflows/codemod/packages.js +41 -0
  13. package/dist/commands/workflows/definitions/delete.d.ts +44 -0
  14. package/dist/commands/workflows/definitions/delete.js +74 -0
  15. package/dist/commands/workflows/definitions/diff.d.ts +23 -0
  16. package/dist/commands/workflows/definitions/diff.js +55 -0
  17. package/dist/commands/workflows/definitions/list.d.ts +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 +9 -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 +34 -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 +205 -0
  57. package/dist/lib/blueprint-stacks.d.ts +6 -0
  58. package/dist/lib/blueprint-stacks.js +88 -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 +24 -0
  62. package/dist/lib/client.js +40 -0
  63. package/dist/lib/codemod/manifest-rewrite.d.ts +14 -0
  64. package/dist/lib/codemod/manifest-rewrite.js +97 -0
  65. package/dist/lib/codemod/package-map.d.ts +22 -0
  66. package/dist/lib/codemod/package-map.js +72 -0
  67. package/dist/lib/codemod/report.d.ts +5 -0
  68. package/dist/lib/codemod/report.js +43 -0
  69. package/dist/lib/codemod/run.d.ts +23 -0
  70. package/dist/lib/codemod/run.js +103 -0
  71. package/dist/lib/codemod/source-rewrite.d.ts +18 -0
  72. package/dist/lib/codemod/source-rewrite.js +155 -0
  73. package/dist/lib/command-context.d.ts +20 -0
  74. package/dist/lib/command-context.js +24 -0
  75. package/dist/lib/command-telemetry.d.ts +54 -0
  76. package/dist/lib/command-telemetry.js +82 -0
  77. package/dist/lib/context.d.ts +155 -0
  78. package/dist/lib/context.js +268 -0
  79. package/dist/lib/default-partition.d.ts +23 -0
  80. package/dist/lib/default-partition.js +48 -0
  81. package/dist/lib/definition-files.d.ts +11 -0
  82. package/dist/lib/definition-files.js +58 -0
  83. package/dist/lib/definitions.d.ts +63 -0
  84. package/dist/lib/definitions.js +84 -0
  85. package/dist/lib/diff.d.ts +12 -0
  86. package/dist/lib/diff.js +93 -0
  87. package/dist/lib/env.d.ts +7 -0
  88. package/dist/lib/env.js +8 -0
  89. package/dist/lib/fail.d.ts +29 -0
  90. package/dist/lib/fail.js +46 -0
  91. package/dist/lib/flags.d.ts +49 -0
  92. package/dist/lib/flags.js +117 -0
  93. package/dist/lib/follow-up-command.d.ts +18 -0
  94. package/dist/lib/follow-up-command.js +12 -0
  95. package/dist/lib/history-rows.d.ts +3 -0
  96. package/dist/lib/history-rows.js +44 -0
  97. package/dist/lib/load-config.d.ts +46 -0
  98. package/dist/lib/load-config.js +110 -0
  99. package/dist/lib/nuke.d.ts +124 -0
  100. package/dist/lib/nuke.js +206 -0
  101. package/dist/lib/operation-args.d.ts +42 -0
  102. package/dist/lib/operation-args.js +21 -0
  103. package/dist/lib/ops-report.d.ts +47 -0
  104. package/dist/lib/ops-report.js +31 -0
  105. package/dist/lib/params.d.ts +3 -0
  106. package/dist/lib/params.js +21 -0
  107. package/dist/lib/pick-dataset.d.ts +10 -0
  108. package/dist/lib/pick-dataset.js +30 -0
  109. package/dist/lib/prompt.d.ts +35 -0
  110. package/dist/lib/prompt.js +11 -0
  111. package/dist/lib/read-fanout.d.ts +45 -0
  112. package/dist/lib/read-fanout.js +44 -0
  113. package/dist/lib/select-deployment.d.ts +31 -0
  114. package/dist/lib/select-deployment.js +91 -0
  115. package/dist/lib/share-definitions.d.ts +101 -0
  116. package/dist/lib/share-definitions.js +188 -0
  117. package/dist/lib/telemetry-setup.d.ts +81 -0
  118. package/dist/lib/telemetry-setup.js +111 -0
  119. package/dist/lib/telemetry.d.ts +78 -0
  120. package/dist/lib/telemetry.js +90 -0
  121. package/dist/lib/ui.d.ts +91 -0
  122. package/dist/lib/ui.js +116 -0
  123. package/dist/standalone-argv.d.ts +14 -0
  124. package/dist/standalone-argv.js +57 -0
  125. package/oclif.manifest.json +1731 -0
  126. package/package.json +118 -3
@@ -0,0 +1,91 @@
1
+ import { assertReaderModelAcknowledgement, requiredDefinitionReaderModel, resourceAliasesToMap, } from '@sanity/workflows';
2
+ import { fail } from './fail.js';
3
+ import { canPromptOnStderr, selectOnStderr } from './prompt.js';
4
+ export function deploymentLabel({ name, partition, }) {
5
+ return `${name} (${partition})`;
6
+ }
7
+ export async function selectDeployment(config, { name, partition, orAlternative = '', interactive, chooseName = chooseDeploymentName, }) {
8
+ if (name !== undefined) {
9
+ const deployment = config.deployments.find((candidate) => candidate.name === name);
10
+ if (deployment === undefined) {
11
+ fail(`No deployment named "${name}".`, availableDeployments(config));
12
+ }
13
+ return deployment;
14
+ }
15
+ if (partition !== undefined) {
16
+ const matches = deploymentsForPartition(config, partition);
17
+ const [sole, ...rest] = matches;
18
+ if (sole === undefined || rest.length > 0) {
19
+ fail(`Multiple deployments in partition "${partition}" — pass --deployment to choose one.`, availableDeployments(config, matches));
20
+ }
21
+ return sole;
22
+ }
23
+ return selectDefaultDeployment(config, { orAlternative, interactive, chooseName });
24
+ }
25
+ async function selectDefaultDeployment(config, { orAlternative, interactive, chooseName, }) {
26
+ if (config.deployments.length > 1) {
27
+ if (interactive ?? canPromptOnStderr()) {
28
+ const selectedName = await chooseName(config.deployments);
29
+ return selectDeployment(config, { name: selectedName, partition: undefined });
30
+ }
31
+ fail(`Multiple deployments configured — pass --deployment or --partition${orAlternative}.`, availableDeployments(config));
32
+ }
33
+ const [sole] = config.deployments;
34
+ if (sole === undefined) {
35
+ fail('No deployments configured.');
36
+ }
37
+ return sole;
38
+ }
39
+ export function deploymentsForPartition(config, partition) {
40
+ const matches = config.deployments.filter((candidate) => candidate.partition === partition);
41
+ if (matches.length === 0) {
42
+ fail(`No deployment for partition "${partition}".`, availableDeployments(config));
43
+ }
44
+ return matches;
45
+ }
46
+ export async function selectDeployments(config, { name, partition, allPartitions, interactive, chooseName }) {
47
+ if (allPartitions) {
48
+ return config.deployments;
49
+ }
50
+ if (partition !== undefined) {
51
+ return deploymentsForPartition(config, partition);
52
+ }
53
+ return [
54
+ await selectDeployment(config, {
55
+ name,
56
+ partition,
57
+ orAlternative: ', or --all-partitions to deploy every deployment',
58
+ interactive,
59
+ chooseName,
60
+ }),
61
+ ];
62
+ }
63
+ async function chooseDeploymentName(deployments) {
64
+ return selectOnStderr({
65
+ message: 'Select a deployment',
66
+ choices: deployments.map(({ name, partition }) => ({
67
+ name,
68
+ value: name,
69
+ description: `partition: ${partition}`,
70
+ })),
71
+ });
72
+ }
73
+ function availableDeployments(config, deployments = config.deployments) {
74
+ return `Available deployments: ${deployments.map(deploymentLabel).join(', ')}`;
75
+ }
76
+ export function acknowledgeDeployment(deployment, definitions) {
77
+ const expectedMinReaderModel = deployment.expectedMinReaderModel;
78
+ assertReaderModelAcknowledgement(expectedMinReaderModel, {
79
+ context: `Deployment ${deployment.name}`,
80
+ requiredMinReaderModel: requiredDefinitionReaderModel(definitions),
81
+ });
82
+ return { ...deployment, expectedMinReaderModel };
83
+ }
84
+ export function deploymentToTarget(deployment) {
85
+ return {
86
+ expectedMinReaderModel: deployment.expectedMinReaderModel,
87
+ partition: deployment.partition,
88
+ workflowResource: deployment.workflowResource,
89
+ resourceAliases: resourceAliasesToMap(deployment.resourceAliases),
90
+ };
91
+ }
@@ -0,0 +1,101 @@
1
+ /** Consent model: opt-OUT. Sharing new definition versions defaults on; only
2
+ * --no-share-defs turns it off — CI, DO_NOT_TRACK, and non-TTY don't change that. */
3
+ import { type DeployDefinitionResult, type DeployedDefinition, type WorkflowResource } from '@sanity/workflows';
4
+ import { type FollowUpContext } from './follow-up-command.ts';
5
+ import type { UserConfigStore } from './telemetry-setup.ts';
6
+ import { type WorkflowDefinitionSharedData } from './telemetry.ts';
7
+ /** The client slice sharing uses — the read-back of just-deployed
8
+ * documents and the feedback POST, structurally, so a full
9
+ * `SanityClient` satisfies it and tests fake exactly these calls. */
10
+ export interface ShareClient {
11
+ fetch<T>(query: string, params: Record<string, unknown>, options: {
12
+ tag: string;
13
+ }): Promise<T>;
14
+ request<T>(opts: {
15
+ url: string;
16
+ method: string;
17
+ body: unknown;
18
+ tag: string;
19
+ }): Promise<T>;
20
+ }
21
+ /** One successfully deployed deployment's outcome, paired with the client
22
+ * that can read the just-deployed documents back and the resource the
23
+ * entries' deployment coordinates derive from. */
24
+ export interface ShareCandidate {
25
+ client: ShareClient;
26
+ partition: string;
27
+ resource: WorkflowResource;
28
+ results: DeployDefinitionResult[];
29
+ /** The deploy call's run id — the markers carry the same id the engine's
30
+ * deploy events minted, so donated definitions group with their deploy. */
31
+ deployId: string;
32
+ }
33
+ /** Sanity's first-party definition-feedback endpoint (editorial-ai-backend,
34
+ * routed project-agnostically through the API gateway). */
35
+ export declare const SHARE_ENDPOINT_URL = "/workflow/definition-feedback";
36
+ /**
37
+ * The first-run disclosure — a product contract, pinned by test. It must
38
+ * name the recipient (Sanity), state that the document ships VERBATIM with its
39
+ * deployment coordinates and is kept, name what is never shared, and disclose
40
+ * that the notice is remembered machine-wide and name the per-run opt-out.
41
+ * This is a notice, not a choice: sharing is the default unless the invocation
42
+ * supplies `--no-share-defs`.
43
+ */
44
+ export declare const SHARE_FIRST_RUN_NOTICE: string;
45
+ /**
46
+ * The status block printed on every flagless deploy that does not show the
47
+ * first-run disclosure. It keeps the default donation obvious in terminals and
48
+ * unattended logs and names both explicit controls as runnable commands.
49
+ */
50
+ export declare function shareReminder(followUp: FollowUpContext): string;
51
+ /**
52
+ * The content-free telemetry marker for one shared definition — projected
53
+ * from the engine's own deploy-event derivation ({@link definitionDeployedData})
54
+ * so `Workflows CLI Definition Shared` and `Workflows Engine Definition Deployed`
55
+ * can never disagree about one definition's structure. Status is dropped: only
56
+ * newly created versions are ever shared.
57
+ */
58
+ export declare function definitionShareMarker(args: {
59
+ definition: DeployedDefinition;
60
+ contentHash: string;
61
+ deployId: string;
62
+ }): WorkflowDefinitionSharedData;
63
+ /**
64
+ * Whether the invocation's telemetry should send despite the environment
65
+ * denial (CI / `DO_NOT_TRACK`). Every flagless or explicitly enabled deploy
66
+ * that can create versions forces it, because definition donation defaults on
67
+ * in those environments too. Account-level consent is never
68
+ * overridden (the intake still reads `/intake/telemetry-status`).
69
+ *
70
+ * Computed from raw argv because the prerun hook builds the store before oclif
71
+ * parses flags, so it must land on the same value oclif will: repeated
72
+ * `allowNo` booleans are **last-token-wins**, and tokens after `--` aren't
73
+ * flags. `--dry-run` / `--check` never create versions, so they never donate —
74
+ * no telemetry to force. The `share-defs` flag has no char/alias/env source,
75
+ * so `--share-defs` / `--no-share-defs` are its only tokens (add one and this
76
+ * match must learn it too).
77
+ */
78
+ export declare function shouldForceShareTelemetry(args: {
79
+ commandId: string | undefined;
80
+ argv: string[];
81
+ }): boolean;
82
+ /**
83
+ * The whole post-deploy sharing flow. An explicit flag decides directly;
84
+ * otherwise sharing defaults on after emitting either the one-time disclosure
85
+ * or recurring reminder. It always records the content-free per-invocation
86
+ * decision so adoption dashboards can measure opt-out rate. No newly created
87
+ * versions (unchanged re-deploys, dry runs, nothing succeeded) means no
88
+ * decision, notice, or POST.
89
+ *
90
+ * The optional args exist for the flow's dependencies, mirroring
91
+ * `setupCliTelemetry` — omitted, the real process surfaces apply.
92
+ */
93
+ export declare function shareDefinitionsAfterDeploy(args: {
94
+ flag: boolean | undefined;
95
+ followUp: FollowUpContext;
96
+ candidates: ShareCandidate[];
97
+ warn: (message: string) => void;
98
+ interactive?: boolean;
99
+ writeStderr?: (message: string) => void;
100
+ userConfig?: UserConfigStore;
101
+ }): Promise<void>;
@@ -0,0 +1,188 @@
1
+ import { styleText } from 'node:util';
2
+ import { getUserConfig } from '@sanity/cli-core';
3
+ import { assertReadableModel, definitionDeployedData, errorMessage, } from '@sanity/workflows';
4
+ import { WORKFLOWS_DEPLOY_COMMAND_ID } from '../command-ids.js';
5
+ import { buildDefinitionShowQuery } from './definitions.js';
6
+ import { flagTokens } from './flags.js';
7
+ import { followUpCommand } from './follow-up-command.js';
8
+ import { canPromptOnStderr } from './prompt.js';
9
+ import { cliTelemetry, WorkflowDefinitionShared, WorkflowDefinitionSharingDecided, } from './telemetry.js';
10
+ export const SHARE_ENDPOINT_URL = '/workflow/definition-feedback';
11
+ const SHARE_TAG = 'definition.share';
12
+ const SHARE_DECISION_KEY = 'workflowCliDefinitionSharing';
13
+ export const SHARE_FIRST_RUN_NOTICE = `${styleText('bold', 'Sharing new workflow definitions with Sanity')} to improve Workflows.\n` +
14
+ 'They are sent verbatim (structure, names, filters, effect configuration,\n' +
15
+ 'seeded values) with their deployment coordinates, and kept — never your\n' +
16
+ 'content documents, workflow instances, or Sanity auth token. This notice is\n' +
17
+ `shown once on this machine; opt out of any run with ${styleText('cyan', '--no-share-defs')}.\n`;
18
+ export function shareReminder(followUp) {
19
+ const examples = [
20
+ { flags: [], note: 'share by default' },
21
+ { flags: ['--share-defs'], note: 'share explicitly; hide this warning' },
22
+ { flags: ['--no-share-defs'], note: 'opt out' },
23
+ ].map(({ flags, note }) => ({ command: followUpCommand(followUp, 'deploy', ...flags), note }));
24
+ const width = Math.max(...examples.map(({ command }) => command.length));
25
+ return (`${styleText('bold', 'Definition sharing: ON (default)')}\n` +
26
+ 'New workflow definition versions are being shared with Sanity to improve Workflows.\n' +
27
+ 'Examples:\n' +
28
+ examples
29
+ .map(({ command, note }) => ` ${styleText('dim', '$')} ${command.padEnd(width)} ${styleText('dim', `# ${note}`)}\n`)
30
+ .join(''));
31
+ }
32
+ export function definitionShareMarker(args) {
33
+ const { status: _status, ...structural } = definitionDeployedData(args.definition, {
34
+ contentHash: args.contentHash,
35
+ status: 'created',
36
+ deployId: args.deployId,
37
+ });
38
+ return structural;
39
+ }
40
+ export function shouldForceShareTelemetry(args) {
41
+ const { commandId, argv } = args;
42
+ if (commandId !== WORKFLOWS_DEPLOY_COMMAND_ID) {
43
+ return false;
44
+ }
45
+ const tokens = flagTokens(argv);
46
+ if (tokens.includes('--dry-run') || tokens.includes('--check')) {
47
+ return false;
48
+ }
49
+ return (tokens.lastIndexOf('--share-defs') > tokens.lastIndexOf('--no-share-defs') ||
50
+ !tokens.includes('--no-share-defs'));
51
+ }
52
+ async function loadShareEntry(args) {
53
+ const { candidate, result, warn } = args;
54
+ const deployed = await loadDeployedForShare(args);
55
+ if (deployed === undefined) {
56
+ return undefined;
57
+ }
58
+ if (deployed.contentHash === undefined) {
59
+ warn(`${result.name} v${result.version} carries no content hash — not shared.`);
60
+ return undefined;
61
+ }
62
+ return {
63
+ definition: deployed,
64
+ contentHash: deployed.contentHash,
65
+ name: result.name,
66
+ version: result.version,
67
+ resourceType: candidate.resource.type,
68
+ resourceId: candidate.resource.id,
69
+ };
70
+ }
71
+ async function loadDeployedForShare(args) {
72
+ const { candidate, result, warn } = args;
73
+ const { groq, params } = buildDefinitionShowQuery({
74
+ name: result.name,
75
+ partition: candidate.partition,
76
+ version: result.version,
77
+ });
78
+ try {
79
+ const deployed = await candidate.client.fetch(groq, params, {
80
+ tag: SHARE_TAG,
81
+ });
82
+ if (deployed === null) {
83
+ warn(`Could not read back ${result.name} v${result.version} — not shared.`);
84
+ return undefined;
85
+ }
86
+ assertReadableModel(deployed);
87
+ return deployed;
88
+ }
89
+ catch (error) {
90
+ warn(`Could not read back ${result.name} v${result.version} — not shared. ${errorMessage(error)}`);
91
+ return undefined;
92
+ }
93
+ }
94
+ function collectCreated(candidates) {
95
+ return candidates.flatMap((candidate) => candidate.results
96
+ .filter((result) => result.status === 'created')
97
+ .map((result) => ({ candidate, result })));
98
+ }
99
+ function wasShareNoticeShown(userConfig) {
100
+ const value = userConfig.get(SHARE_DECISION_KEY);
101
+ return typeof value === 'boolean';
102
+ }
103
+ function rememberShareNotice(userConfig) {
104
+ try {
105
+ userConfig.set(SHARE_DECISION_KEY, true);
106
+ }
107
+ catch {
108
+ }
109
+ }
110
+ function resolveShareIntent(args) {
111
+ if (args.flag === true) {
112
+ return { share: true, decision: 'opt-in' };
113
+ }
114
+ if (args.flag === false) {
115
+ return { share: false, decision: 'opt-out' };
116
+ }
117
+ if (args.interactive && !wasShareNoticeShown(args.userConfig)) {
118
+ args.writeStderr(SHARE_FIRST_RUN_NOTICE);
119
+ rememberShareNotice(args.userConfig);
120
+ }
121
+ else {
122
+ args.writeStderr(shareReminder(args.followUp));
123
+ }
124
+ return { share: true, decision: 'default' };
125
+ }
126
+ async function donate(args) {
127
+ const shared = [];
128
+ try {
129
+ for (const item of args.created) {
130
+ const entry = await loadShareEntry({ ...item, warn: args.warn });
131
+ if (entry !== undefined) {
132
+ shared.push({ entry, candidate: item.candidate });
133
+ }
134
+ }
135
+ if (shared.length === 0) {
136
+ return false;
137
+ }
138
+ await shared[0].candidate.client.request({
139
+ url: SHARE_ENDPOINT_URL,
140
+ method: 'POST',
141
+ body: { definitions: shared.map(({ entry }) => entry) },
142
+ tag: SHARE_TAG,
143
+ });
144
+ }
145
+ catch (error) {
146
+ args.warn(`Definition sharing failed — nothing shared. ${errorMessage(error)}`);
147
+ return false;
148
+ }
149
+ emitShareMarkers(shared);
150
+ return true;
151
+ }
152
+ function emitShareMarkers(shared) {
153
+ try {
154
+ const { logger } = cliTelemetry();
155
+ for (const { entry, candidate } of shared) {
156
+ logger.log(WorkflowDefinitionShared, definitionShareMarker({ ...entry, deployId: candidate.deployId }));
157
+ }
158
+ }
159
+ catch {
160
+ }
161
+ }
162
+ function emitSharingDecided(data) {
163
+ try {
164
+ cliTelemetry().logger.log(WorkflowDefinitionSharingDecided, data);
165
+ }
166
+ catch {
167
+ }
168
+ }
169
+ export async function shareDefinitionsAfterDeploy(args) {
170
+ const created = collectCreated(args.candidates);
171
+ if (created.length === 0) {
172
+ return;
173
+ }
174
+ try {
175
+ const { share, decision } = resolveShareIntent({
176
+ flag: args.flag,
177
+ followUp: args.followUp,
178
+ interactive: args.interactive ?? canPromptOnStderr(),
179
+ userConfig: args.userConfig ?? getUserConfig(),
180
+ writeStderr: args.writeStderr ?? ((message) => void process.stderr.write(message)),
181
+ });
182
+ const shared = share ? await donate({ created, warn: args.warn }) : false;
183
+ emitSharingDecided({ decision, shared, definitionCount: created.length });
184
+ }
185
+ catch (error) {
186
+ args.warn(`Definition sharing skipped — ${errorMessage(error)}`);
187
+ }
188
+ }
@@ -0,0 +1,81 @@
1
+ /** Discovery is deliberately soft: telemetry must never break or exit a
2
+ * command — a missing/broken config, token, or dataset just leaves it off. */
3
+ import { processShellUserProperties, type TelemetryIntakeClient } from '@sanity/workflows';
4
+ import { type WorkflowCliCommandContext } from './command-context.ts';
5
+ /** The get/set slice of the shared Sanity user config (cli-core's
6
+ * `getUserConfig`) the shell persists flags into — narrow so tests fake
7
+ * exactly what's read and written. */
8
+ export interface UserConfigStore {
9
+ get: (key: string) => unknown;
10
+ set: (key: string, value: unknown) => void;
11
+ }
12
+ /**
13
+ * The one-time transparency notice, mirroring the sanity CLI's
14
+ * `telemetryDisclosure` — both CLIs feed the same pipeline. Written to
15
+ * stderr so it never garbles command output.
16
+ */
17
+ export declare function maybeShowTelemetryDisclosure(args: {
18
+ userConfig: UserConfigStore;
19
+ writeStderr: (message: string) => void;
20
+ }): void;
21
+ /** The project a run's events are attributed to. */
22
+ export interface TelemetryProject {
23
+ projectId: string;
24
+ dataset?: string | undefined;
25
+ }
26
+ type TelemetryTarget = {
27
+ projectId?: string | undefined;
28
+ dataset?: string | undefined;
29
+ };
30
+ /**
31
+ * Assemble and install the invocation's shell: a config-provided
32
+ * `telemetry` logger replaces the built-in shell wholesale (none of its
33
+ * policy applies); otherwise the built-in Sanity-intake store is
34
+ * constructed whenever an auth token exists, with or without a config —
35
+ * mirroring the standard recipe's "not logged in → nothing sent". Events
36
+ * are attributed to the `--project-id` the run names, else the config's
37
+ * first dataset deployment, else to no project.
38
+ *
39
+ * The optional args exist for the hook's dependencies (config path, environment,
40
+ * user config, stderr) — omitted, the real process surfaces apply.
41
+ */
42
+ export declare function setupCliTelemetry(args?: {
43
+ /** The command's `--path`; omitted, the search starts in the working directory. */
44
+ configPath?: string | undefined;
45
+ /** The command's `--project-id` and `--dataset`, which win over the config's project. */
46
+ target?: TelemetryTarget;
47
+ env?: Record<string, string | undefined>;
48
+ userConfig?: UserConfigStore;
49
+ writeStderr?: (message: string) => void;
50
+ /** This package's version — the prerun hook supplies it. */
51
+ cliVersion?: string | undefined;
52
+ /** Override the environment denial (CI / `DO_NOT_TRACK`) — the prerun hook
53
+ * sets this for a deploy that may share definitions, either by default or
54
+ * through `--share-defs`. */
55
+ forceSend?: boolean;
56
+ /** Intake client override — tests inject a fake here, like the other
57
+ * hook dependencies above; omitted, the real project client applies. */
58
+ client?: TelemetryIntakeClient;
59
+ /** Omitted, the trace reports no command path and no flag values. */
60
+ context?: WorkflowCliCommandContext;
61
+ }): Promise<void>;
62
+ /**
63
+ * The invocation's environment user properties — the sanity CLI's precedent
64
+ * set (versions, platform, runtime, and project coordinates when a project is
65
+ * known). `orgId` — which
66
+ * Studio's shell sends and the sanity CLI doesn't yet — attaches separately
67
+ * once {@link resolveOrgId} resolves. Joined to the session's events by
68
+ * sessionId downstream; user identity stays sink-side.
69
+ */
70
+ export declare function cliUserProperties(args: {
71
+ project: TelemetryProject | undefined;
72
+ cliVersion: string | undefined;
73
+ }): ReturnType<typeof processShellUserProperties> & {
74
+ cliVersion?: string;
75
+ projectId?: string;
76
+ dataset?: string;
77
+ };
78
+ /** The intake project's organization id — degrade-soft: a failed, slow, or
79
+ * org-less lookup resolves undefined, never rejects, never breaks a command. */
80
+ export declare function resolveOrgId(client: TelemetryIntakeClient, projectId: string): Promise<string | undefined>;
81
+ export {};
@@ -0,0 +1,111 @@
1
+ import { styleText } from 'node:util';
2
+ import { getUserConfig } from '@sanity/cli-core';
3
+ import { datasetResourceParts, processShellUserProperties, } from '@sanity/workflows';
4
+ import boxen from 'boxen';
5
+ import { globalClient, resolveToken } from './client.js';
6
+ import { commandTraceContext } from './command-context.js';
7
+ import { loadWorkflowConfigIfPresent } from './load-config.js';
8
+ import { createBuiltinTelemetry, raceWithDeadline, setCliTelemetry } from './telemetry.js';
9
+ const DISCLOSURE_KEY = 'workflowCliTelemetryDisclosed';
10
+ const SANITY_CLI_DISCLOSURE_KEY = 'telemetryDisclosed';
11
+ export function maybeShowTelemetryDisclosure(args) {
12
+ const { userConfig, writeStderr } = args;
13
+ if (userConfig.get(DISCLOSURE_KEY) !== undefined ||
14
+ userConfig.get(SANITY_CLI_DISCLOSURE_KEY) !== undefined) {
15
+ return;
16
+ }
17
+ writeStderr(`${boxen(`The Sanity workflow CLI collects telemetry data on general usage and errors.
18
+ This helps us improve workflows and prioritize features.
19
+
20
+ To opt in/out, run ${styleText('cyan', 'npx sanity telemetry enable/disable')}.
21
+ Learn more: https://www.sanity.io/telemetry`, { borderColor: 'yellow', borderStyle: 'round', margin: 1, padding: 1 })}\n`);
22
+ userConfig.set(DISCLOSURE_KEY, Date.now());
23
+ }
24
+ function configProject(config) {
25
+ const resource = config?.deployments
26
+ .map((deployment) => deployment.workflowResource)
27
+ .find((candidate) => candidate.type === 'dataset');
28
+ return resource === undefined ? undefined : datasetResourceParts(resource.id);
29
+ }
30
+ export async function setupCliTelemetry(args) {
31
+ const env = args?.env ?? process.env;
32
+ const context = args?.context ??
33
+ commandTraceContext({
34
+ commandId: undefined,
35
+ argv: process.argv.slice(2),
36
+ flagDefs: undefined,
37
+ commandTelemetry: undefined,
38
+ env,
39
+ });
40
+ try {
41
+ const config = await loadWorkflowConfigIfPresent(args?.configPath).catch(() => undefined);
42
+ if (config?.telemetry !== undefined) {
43
+ setCliTelemetry({ kind: 'provided', logger: config.telemetry }, context);
44
+ return;
45
+ }
46
+ const token = await resolveToken().catch(() => undefined);
47
+ if (token === undefined) {
48
+ return;
49
+ }
50
+ const project = targetProject(args?.target) ?? configProject(config);
51
+ const client = args?.client ?? globalClient(token);
52
+ const telemetry = createBuiltinTelemetry({
53
+ client,
54
+ projectId: project?.projectId,
55
+ env,
56
+ forceSend: args?.forceSend ?? false,
57
+ packageVersion: args?.cliVersion,
58
+ });
59
+ setCliTelemetry(telemetry, context);
60
+ attachBuiltinContext({ telemetry, project, client, deps: args });
61
+ }
62
+ catch {
63
+ }
64
+ }
65
+ function targetProject(target) {
66
+ return target?.projectId === undefined
67
+ ? undefined
68
+ : { projectId: target.projectId, dataset: target.dataset };
69
+ }
70
+ function attachBuiltinContext(args) {
71
+ const { telemetry, project, client, deps } = args;
72
+ if (!telemetry.envDenied || telemetry.forceSend) {
73
+ telemetry.store.logger.updateUserProperties(cliUserProperties({ project, cliVersion: deps?.cliVersion }));
74
+ if (project !== undefined) {
75
+ void resolveOrgId(client, project.projectId).then((orgId) => {
76
+ if (orgId !== undefined)
77
+ telemetry.store.logger.updateUserProperties({ orgId });
78
+ });
79
+ }
80
+ }
81
+ if (!telemetry.envDenied) {
82
+ maybeShowTelemetryDisclosure({
83
+ userConfig: deps?.userConfig ?? getUserConfig(),
84
+ writeStderr: deps?.writeStderr ?? ((message) => void process.stderr.write(message)),
85
+ });
86
+ }
87
+ }
88
+ const ORG_LOOKUP_DEADLINE_MS = 2_000;
89
+ const CONTEXT_TAG = 'telemetry.context';
90
+ export function cliUserProperties(args) {
91
+ const { project, cliVersion } = args;
92
+ return {
93
+ ...processShellUserProperties('cli'),
94
+ ...(cliVersion !== undefined ? { cliVersion } : {}),
95
+ ...(project !== undefined ? { projectId: project.projectId } : {}),
96
+ ...(project?.dataset !== undefined ? { dataset: project.dataset } : {}),
97
+ };
98
+ }
99
+ export async function resolveOrgId(client, projectId) {
100
+ try {
101
+ const project = await raceWithDeadline(client.request({
102
+ url: `/projects/${encodeURIComponent(projectId)}`,
103
+ tag: CONTEXT_TAG,
104
+ timeout: ORG_LOOKUP_DEADLINE_MS,
105
+ }), ORG_LOOKUP_DEADLINE_MS);
106
+ return project?.organizationId ?? undefined;
107
+ }
108
+ catch {
109
+ return undefined;
110
+ }
111
+ }
@@ -0,0 +1,78 @@
1
+ /** Payload policy under https://www.sanity.io/telemetry: option flags as `--name=value`;
2
+ * booleans, redacted, and undeclared flags by name only; never raw argv or error text. */
3
+ import { type DefinedTelemetryTrace, type TelemetryStore } from '@sanity/telemetry';
4
+ import { type DerivedEventData, type TelemetryIntakeClient, type WorkflowDefinitionDeployedData, type WorkflowTelemetryLogger } from '@sanity/workflows';
5
+ import type { WorkflowCliCommandContext } from './command-context.ts';
6
+ export interface WorkflowCliCommandResult {
7
+ success: boolean;
8
+ }
9
+ export declare const WorkflowCliCommandExecuted: DefinedTelemetryTrace<WorkflowCliCommandResult, void>;
10
+ export type WorkflowDefinitionSharedData = Omit<DerivedEventData<WorkflowDefinitionDeployedData>, 'status'>;
11
+ export declare const WorkflowDefinitionShared: import("@sanity/telemetry").DefinedTelemetryLog<WorkflowDefinitionSharedData>;
12
+ /**
13
+ * How the donation decision was reached, and what it was. Paired with `shared`
14
+ * (whether it actually reached the endpoint) this keeps every case distinct —
15
+ * an explicit opt-out vs default sharing, and a chosen share vs a failed POST:
16
+ * - `opt-in` / `opt-out` — an explicit `--share-defs` / `--no-share-defs`.
17
+ * - `default` — no sharing flag; definitions are donated in every environment.
18
+ */
19
+ export type DefinitionSharingDecision = 'opt-in' | 'opt-out' | 'default';
20
+ export interface WorkflowDefinitionSharingDecidedData {
21
+ decision: DefinitionSharingDecision;
22
+ /** Whether the donation actually reached the feedback endpoint — `false` for
23
+ * any non-sharing decision, and also for a chosen share whose POST failed. */
24
+ shared: boolean;
25
+ /** Newly created definition versions this invocation could have donated. */
26
+ definitionCount: number;
27
+ }
28
+ export declare const WorkflowDefinitionSharingDecided: import("@sanity/telemetry").DefinedTelemetryLog<WorkflowDefinitionSharingDecidedData>;
29
+ /**
30
+ * The shell for one CLI invocation. `builtin` is the Sanity-intake store;
31
+ * `provided` is a config-supplied logger that replaces the shell and its
32
+ * policy wholesale; `off` (the default) emits nothing — no config-derived
33
+ * project, no auth token, or telemetry setup failed.
34
+ */
35
+ export type CliTelemetry = {
36
+ kind: 'builtin';
37
+ logger: WorkflowTelemetryLogger;
38
+ store: TelemetryStore<unknown>;
39
+ envDenied: boolean;
40
+ /** The environment denial was overridden ({@link createBuiltinTelemetry}):
41
+ * the store sends despite CI / `DO_NOT_TRACK`, subject only to
42
+ * account consent. */
43
+ forceSend: boolean;
44
+ } | {
45
+ kind: 'provided';
46
+ logger: WorkflowTelemetryLogger;
47
+ } | {
48
+ kind: 'off';
49
+ logger: WorkflowTelemetryLogger;
50
+ };
51
+ export declare function cliTelemetry(): CliTelemetry;
52
+ /** Install the shell and, for the built-in store, start the command trace. */
53
+ export declare function setCliTelemetry(telemetry: Exclude<CliTelemetry, {
54
+ kind: 'off';
55
+ }>, context: WorkflowCliCommandContext): void;
56
+ export declare function clearCliTelemetry(): void;
57
+ /** Build the built-in Sanity-intake shell over an authenticated client. `forceSend` overrides the environment denial
58
+ * (CI / `DO_NOT_TRACK`) when a deploy may share definitions—flagless by
59
+ * default or explicitly enabled. Account-level consent is unaffected: the intake still fetches
60
+ * `/intake/telemetry-status`, so `sanity telemetry disable` still mutes. */
61
+ export declare function createBuiltinTelemetry(args: {
62
+ client: TelemetryIntakeClient;
63
+ projectId: string | undefined;
64
+ env: Record<string, string | undefined>;
65
+ forceSend?: boolean;
66
+ packageVersion?: string | undefined;
67
+ }): Extract<CliTelemetry, {
68
+ kind: 'builtin';
69
+ }>;
70
+ /**
71
+ * Race `work` against a deadline, resolving `undefined` when the deadline
72
+ * wins. The timer is always cleared once the race settles — oclif never
73
+ * force-exits on success, so a pending timer would hold a finished process
74
+ * open. The losing promise's eventual settlement is absorbed by the race.
75
+ */
76
+ export declare function raceWithDeadline<T>(work: Promise<T>, deadlineMs: number): Promise<T | undefined>;
77
+ /** Complete the command trace and flush. A provided logger owns its own delivery. */
78
+ export declare function finishCliTelemetry(result: WorkflowCliCommandResult): Promise<void>;