@sanity/workflows-cli 0.0.0-stage → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/CHANGELOG.md +1981 -0
  2. package/LICENSE +21 -0
  3. package/README.md +848 -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 +52 -0
  18. package/dist/commands/workflows/definitions/list.js +139 -0
  19. package/dist/commands/workflows/definitions/show.d.ts +66 -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 +53 -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 +79 -0
  30. package/dist/commands/workflows/list.js +249 -0
  31. package/dist/commands/workflows/nuke.d.ts +73 -0
  32. package/dist/commands/workflows/nuke.js +175 -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 +30 -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 +24 -0
  40. package/dist/commands/workflows/tail.js +83 -0
  41. package/dist/commands/workflows/whoami.d.ts +16 -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 +33 -0
  48. package/dist/hooks/prerun/telemetry.js +52 -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 +284 -0
  57. package/dist/lib/blueprint-stacks.d.ts +6 -0
  58. package/dist/lib/blueprint-stacks.js +118 -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 +19 -0
  66. package/dist/lib/codemod/export-rename.js +337 -0
  67. package/dist/lib/codemod/manifest-rewrite.d.ts +17 -0
  68. package/dist/lib/codemod/manifest-rewrite.js +133 -0
  69. package/dist/lib/codemod/package-map.d.ts +27 -0
  70. package/dist/lib/codemod/package-map.js +99 -0
  71. package/dist/lib/codemod/report.d.ts +4 -0
  72. package/dist/lib/codemod/report.js +51 -0
  73. package/dist/lib/codemod/run.d.ts +25 -0
  74. package/dist/lib/codemod/run.js +108 -0
  75. package/dist/lib/codemod/source-rewrite.d.ts +20 -0
  76. package/dist/lib/codemod/source-rewrite.js +150 -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 +151 -0
  82. package/dist/lib/context.js +263 -0
  83. package/dist/lib/default-partition.d.ts +23 -0
  84. package/dist/lib/default-partition.js +47 -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 +53 -0
  98. package/dist/lib/flags.js +127 -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-resource.d.ts +13 -0
  114. package/dist/lib/pick-resource.js +82 -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 +45 -0
  119. package/dist/lib/resource-target.d.ts +10 -0
  120. package/dist/lib/resource-target.js +12 -0
  121. package/dist/lib/select-deployment.d.ts +31 -0
  122. package/dist/lib/select-deployment.js +91 -0
  123. package/dist/lib/share-definitions.d.ts +101 -0
  124. package/dist/lib/share-definitions.js +188 -0
  125. package/dist/lib/telemetry-setup.d.ts +77 -0
  126. package/dist/lib/telemetry-setup.js +117 -0
  127. package/dist/lib/telemetry.d.ts +81 -0
  128. package/dist/lib/telemetry.js +90 -0
  129. package/dist/lib/ui.d.ts +88 -0
  130. package/dist/lib/ui.js +114 -0
  131. package/dist/standalone-argv.d.ts +14 -0
  132. package/dist/standalone-argv.js +57 -0
  133. package/oclif.manifest.json +1894 -0
  134. package/package.json +118 -3
@@ -0,0 +1,25 @@
1
+ import { type CodemodReport } from './source-rewrite.ts';
2
+ /** One file the codemod changed or has something to report about, relative to the working directory. */
3
+ export interface FileOutcome {
4
+ path: string;
5
+ rewrites: string[];
6
+ reports: CodemodReport[];
7
+ /** Changes the codemod makes that the user may want to undo. */
8
+ notes: string[];
9
+ }
10
+ export interface CodemodRun {
11
+ files: FileOutcome[];
12
+ /** Generated blueprint files left for `blueprints generate` to rewrite. */
13
+ generated: string[];
14
+ }
15
+ /**
16
+ * Rewrites retired Workflows package names and renamed exports under `paths`.
17
+ * `range` is the version range written for each replacement package. With
18
+ * `write: false` nothing is written and the outcome describes what would change.
19
+ */
20
+ export declare function runCodemod(args: {
21
+ paths: readonly string[];
22
+ cwd: string;
23
+ range: string;
24
+ write: boolean;
25
+ }): CodemodRun;
@@ -0,0 +1,108 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
3
+ import { basename, dirname, join, relative, resolve } from 'node:path';
4
+ import { isGeneratedShell } from '@sanity/workflows/blueprints/generate';
5
+ import { rewriteManifest } from './manifest-rewrite.js';
6
+ import { rewriteSource } from './source-rewrite.js';
7
+ const SOURCE_FILE = /\.(?:[cm]?[jt]s|[jt]sx)$/;
8
+ const SKIPPED_DIRECTORIES = new Set(['node_modules', 'dist', '.git']);
9
+ function isCodemodTarget(path) {
10
+ return basename(path) === 'package.json' || SOURCE_FILE.test(path);
11
+ }
12
+ function hasGitAncestor(dir) {
13
+ const parent = dirname(dir);
14
+ return existsSync(join(dir, '.git')) || (parent !== dir && hasGitAncestor(parent));
15
+ }
16
+ function insideWorkTree(dir) {
17
+ try {
18
+ execFileSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: dir, stdio: 'ignore' });
19
+ return true;
20
+ }
21
+ catch (error) {
22
+ if (!hasGitAncestor(dir))
23
+ return false;
24
+ throw new Error(`git cannot read the work tree at ${dir}, so the files it ignores are unknown.`, {
25
+ cause: error,
26
+ });
27
+ }
28
+ }
29
+ function gitFiles(dir) {
30
+ try {
31
+ const listing = execFileSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', '.'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
32
+ return listing
33
+ .split('\0')
34
+ .filter((path) => path !== '')
35
+ .map((path) => join(dir, path))
36
+ .filter((path) => existsSync(path));
37
+ }
38
+ catch (error) {
39
+ throw new Error(`git ls-files failed in ${dir}, so the files git ignores are unknown.`, {
40
+ cause: error,
41
+ });
42
+ }
43
+ }
44
+ function walk(dir) {
45
+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
46
+ if (entry.isDirectory())
47
+ return SKIPPED_DIRECTORIES.has(entry.name) ? [] : walk(join(dir, entry.name));
48
+ return entry.isFile() ? [join(dir, entry.name)] : [];
49
+ });
50
+ }
51
+ function filesUnder(path) {
52
+ if (!statSync(path).isDirectory())
53
+ return [path];
54
+ return (insideWorkTree(path) ? gitFiles(path) : walk(path)).filter((file) => !file.split(/[\\/]/).some((segment) => SKIPPED_DIRECTORIES.has(segment)));
55
+ }
56
+ function isGenerated(path) {
57
+ return existsSync(path) && isGeneratedShell(readFileSync(path, 'utf8'));
58
+ }
59
+ function isGeneratedFile(path) {
60
+ if (basename(path) !== 'package.json')
61
+ return isGenerated(path);
62
+ const dir = dirname(path);
63
+ return isGenerated(join(dir, 'index.ts')) || isGenerated(join(dir, 'sanity.blueprint.ts'));
64
+ }
65
+ function rewriteFile(path, range) {
66
+ const original = readFileSync(path, 'utf8');
67
+ if (basename(path) === 'package.json') {
68
+ const result = rewriteManifest(original, range);
69
+ return {
70
+ source: result.source,
71
+ outcome: {
72
+ rewrites: result.changes,
73
+ reports: result.reports.map((text) => ({ line: 1, kind: 'string', text })),
74
+ notes: result.notes,
75
+ },
76
+ };
77
+ }
78
+ const result = rewriteSource(original, path);
79
+ return {
80
+ source: result.source,
81
+ outcome: {
82
+ rewrites: [
83
+ ...(result.rewrites === 0 ? [] : [`${result.rewrites} module specifiers`]),
84
+ ...(result.renames === 0 ? [] : [`${result.renames} renamed export names`]),
85
+ ],
86
+ reports: result.reports,
87
+ notes: [],
88
+ },
89
+ };
90
+ }
91
+ export function runCodemod(args) {
92
+ const targets = [
93
+ ...new Set(args.paths.flatMap((path) => filesUnder(resolve(args.cwd, path)))),
94
+ ].filter(isCodemodTarget);
95
+ const generated = targets.filter(isGeneratedFile);
96
+ const files = targets
97
+ .filter((path) => !generated.includes(path))
98
+ .toSorted()
99
+ .flatMap((path) => {
100
+ const { source, outcome } = rewriteFile(path, args.range);
101
+ if (args.write && outcome.rewrites.length > 0)
102
+ writeFileSync(path, source);
103
+ return outcome.rewrites.length === 0 && outcome.reports.length === 0
104
+ ? []
105
+ : [{ path: relative(args.cwd, path), ...outcome }];
106
+ });
107
+ return { files, generated: generated.map((path) => relative(args.cwd, path)).toSorted() };
108
+ }
@@ -0,0 +1,20 @@
1
+ import { type RenameReportKind } from './export-rename.ts';
2
+ export type ReportKind = 'unknown-entry' | 'computed-specifier' | 'string' | 'jsx-text' | 'comment' | 'parse-error' | RenameReportKind;
3
+ /** Something the codemod found and left for a person to fix. `line` is 1-based. */
4
+ export interface CodemodReport {
5
+ line: number;
6
+ kind: ReportKind;
7
+ text: string;
8
+ }
9
+ export interface RewriteResult {
10
+ source: string;
11
+ rewrites: number;
12
+ renames: number;
13
+ reports: CodemodReport[];
14
+ }
15
+ /**
16
+ * Rewrites retired package specifiers in one source, renames imports of renamed
17
+ * exports, and reports what it leaves. Edits replace string literals and
18
+ * identifiers or delete merged import specifiers; nothing else is reformatted.
19
+ */
20
+ export declare function rewriteSource(source: string, filename: string): RewriteResult;
@@ -0,0 +1,150 @@
1
+ import { parseSync } from 'oxc-parser';
2
+ import { applyEdits, childEntries, isNode } from './ast.js';
3
+ import { renameExports } from './export-rename.js';
4
+ import { matchSpecifier, retiredNamesIn } from './package-map.js';
5
+ const MOCK_CALLEES = new Set([
6
+ 'vi.mock',
7
+ 'vi.doMock',
8
+ 'vi.unmock',
9
+ 'vi.doUnmock',
10
+ 'vi.importActual',
11
+ 'vi.importMock',
12
+ 'jest.mock',
13
+ 'jest.doMock',
14
+ 'jest.unmock',
15
+ 'jest.requireActual',
16
+ 'jest.requireMock',
17
+ 'require',
18
+ 'require.resolve',
19
+ 'import.meta.resolve',
20
+ ]);
21
+ function calleeName(callee) {
22
+ if (!isNode(callee))
23
+ return undefined;
24
+ if (callee.type === 'Identifier')
25
+ return String(callee['name']);
26
+ if (callee.type === 'MetaProperty')
27
+ return 'import.meta';
28
+ if (callee.type !== 'MemberExpression' || callee['computed'] === true)
29
+ return undefined;
30
+ const object = calleeName(callee['object']);
31
+ const property = isNode(callee['property']) ? callee['property']['name'] : undefined;
32
+ return object === undefined || typeof property !== 'string' ? undefined : `${object}.${property}`;
33
+ }
34
+ const SPECIFIER_PROPERTY = {
35
+ ImportDeclaration: 'source',
36
+ ExportNamedDeclaration: 'source',
37
+ ExportAllDeclaration: 'source',
38
+ ImportExpression: 'source',
39
+ TSImportType: 'source',
40
+ TSExternalModuleReference: 'expression',
41
+ TSModuleDeclaration: 'id',
42
+ };
43
+ function mockedSpecifier(call) {
44
+ const name = calleeName(call['callee']);
45
+ const [first] = Array.isArray(call['arguments']) ? call['arguments'] : [];
46
+ return name !== undefined && MOCK_CALLEES.has(name) ? first : undefined;
47
+ }
48
+ function specifierOf(node) {
49
+ if (node.type === 'CallExpression')
50
+ return mockedSpecifier(node);
51
+ const property = SPECIFIER_PROPERTY[node.type];
52
+ return property === undefined ? undefined : node[property];
53
+ }
54
+ function isStringLiteral(node) {
55
+ return node.type === 'Literal' && typeof node['value'] === 'string';
56
+ }
57
+ function lineStarts(source) {
58
+ return [0, ...[...source.matchAll(/\n/g)].map((match) => match.index + 1)];
59
+ }
60
+ function lineAt(starts, offset) {
61
+ return starts.findLastIndex((start) => start <= offset) + 1;
62
+ }
63
+ function parserLanguage(filename) {
64
+ if (/\.d\.[cm]?ts$/.test(filename))
65
+ return 'dts';
66
+ if (/\.[cm]?ts$/.test(filename))
67
+ return 'ts';
68
+ if (filename.endsWith('.tsx'))
69
+ return 'tsx';
70
+ return 'jsx';
71
+ }
72
+ function firstLine(text) {
73
+ return text.split('\n')[0]?.trim() ?? '';
74
+ }
75
+ export function rewriteSource(source, filename) {
76
+ const parsed = parseSync(filename, source, { lang: parserLanguage(filename) });
77
+ if (parsed.errors.length > 0) {
78
+ const mentions = retiredNamesIn(source);
79
+ const reports = mentions.length === 0
80
+ ? []
81
+ : [
82
+ {
83
+ line: 1,
84
+ kind: 'parse-error',
85
+ text: firstLine(parsed.errors[0]?.message ?? ''),
86
+ },
87
+ ];
88
+ return { source, rewrites: 0, renames: 0, reports };
89
+ }
90
+ const starts = lineStarts(source);
91
+ const specifiers = new Set();
92
+ const edits = [];
93
+ const reports = [];
94
+ const report = (span, entry) => reports.push({ line: lineAt(starts, span.start), ...entry });
95
+ const visitSpecifier = (node) => {
96
+ const match = matchSpecifier(String(node['value']));
97
+ if (match.kind === 'rewrite') {
98
+ const quote = source[node.start];
99
+ edits.push({ start: node.start, end: node.end, text: `${quote}${match.replacement}${quote}` });
100
+ }
101
+ else if (match.kind === 'unknown-entry') {
102
+ report(node, { kind: 'unknown-entry', text: String(node['value']) });
103
+ }
104
+ };
105
+ const visitJsxText = (node) => [...source.slice(node.start, node.end).matchAll(/[^\n]+/g)]
106
+ .filter((line) => retiredNamesIn(line[0]).length > 0)
107
+ .forEach((line) => {
108
+ const start = node.start + line.index;
109
+ report({ start, end: start }, { kind: 'jsx-text', text: line[0].trim() });
110
+ });
111
+ const visitOther = (node) => {
112
+ const text = source.slice(node.start, node.end);
113
+ if (retiredNamesIn(text).length === 0)
114
+ return;
115
+ const kind = specifiers.has(node) ? 'computed-specifier' : 'string';
116
+ report(node, { kind, text: firstLine(text) });
117
+ };
118
+ const visit = (node) => {
119
+ const specifier = specifierOf(node);
120
+ if (specifier !== undefined)
121
+ specifiers.add(specifier);
122
+ if (isStringLiteral(node) && specifiers.has(node)) {
123
+ visitSpecifier(node);
124
+ return;
125
+ }
126
+ if (node.type === 'JSXText') {
127
+ visitJsxText(node);
128
+ return;
129
+ }
130
+ if (isStringLiteral(node) || node.type === 'TemplateLiteral') {
131
+ visitOther(node);
132
+ return;
133
+ }
134
+ childEntries(node).forEach(([, child]) => visit(child));
135
+ };
136
+ const program = parsed.program;
137
+ visit(program);
138
+ const renamed = renameExports(program, source);
139
+ renamed.reports.forEach(({ kind, text, ...span }) => report(span, { kind, text }));
140
+ const kept = edits.filter((edit) => !renamed.edits.some((other) => other.start <= edit.start && edit.end <= other.end));
141
+ parsed.comments
142
+ .filter((comment) => retiredNamesIn(comment.value).length > 0)
143
+ .forEach((comment) => report(comment, { kind: 'comment', text: firstLine(comment.value) }));
144
+ return {
145
+ source: applyEdits(source, [...kept, ...renamed.edits]),
146
+ rewrites: kept.length,
147
+ renames: renamed.edits.length,
148
+ reports: reports.toSorted((a, b) => a.line - b.line),
149
+ };
150
+ }
@@ -0,0 +1,20 @@
1
+ import { type CommandTelemetry, type FlagShape } from './command-telemetry.ts';
2
+ export interface WorkflowCliCommandContext {
3
+ groupOrCommand: string;
4
+ /** `workflows:definitions:list` reports `["definitions", "list"]`. */
5
+ commandArguments: string[];
6
+ /** Flag tokens. Only a declared, unredacted flag keeps its value (`--tag=prod`). */
7
+ extraArguments: string[];
8
+ coreOptions: {
9
+ debug: boolean;
10
+ help: boolean;
11
+ version: boolean;
12
+ };
13
+ }
14
+ export declare function commandTraceContext(args: {
15
+ commandId: string | undefined;
16
+ argv: string[];
17
+ flagDefs: Record<string, FlagShape> | undefined;
18
+ commandTelemetry: CommandTelemetry | undefined;
19
+ env: Record<string, string | undefined>;
20
+ }): WorkflowCliCommandContext;
@@ -0,0 +1,24 @@
1
+ import { WORKFLOWS_TOPIC, WORKFLOWS_TOPIC_PREFIX } from '../command-ids.js';
2
+ import { collectOptionArguments } from './command-telemetry.js';
3
+ export function commandTraceContext(args) {
4
+ const { commandId, argv, flagDefs, commandTelemetry, env } = args;
5
+ return {
6
+ groupOrCommand: WORKFLOWS_TOPIC,
7
+ commandArguments: commandPath(commandId),
8
+ extraArguments: collectOptionArguments({ argv, flagDefs, commandTelemetry }),
9
+ coreOptions: {
10
+ debug: Boolean(env.DEBUG),
11
+ help: argv.includes('help'),
12
+ version: argv.includes('--version'),
13
+ },
14
+ };
15
+ }
16
+ function commandPath(commandId) {
17
+ if (commandId === undefined) {
18
+ return [];
19
+ }
20
+ const path = commandId.startsWith(WORKFLOWS_TOPIC_PREFIX)
21
+ ? commandId.slice(WORKFLOWS_TOPIC_PREFIX.length)
22
+ : commandId;
23
+ return path === '' || path === WORKFLOWS_TOPIC ? [] : path.split(':');
24
+ }
@@ -0,0 +1,54 @@
1
+ import type { Interfaces } from '@oclif/core';
2
+ /** The shape this module reads off an oclif flag definition. */
3
+ export interface FlagShape {
4
+ type?: string | undefined;
5
+ char?: string | undefined;
6
+ aliases?: readonly string[] | undefined;
7
+ charAliases?: readonly string[] | undefined;
8
+ }
9
+ /**
10
+ * A command's telemetry behaviour, read off the command class as
11
+ * `static telemetry`. Mirrors the sanity CLI's own hook, so a flag is excluded
12
+ * the same way on both CLIs.
13
+ */
14
+ export interface CommandTelemetry {
15
+ redacted: readonly string[];
16
+ }
17
+ type OptionFlagName<Flags extends Interfaces.FlagInput> = string & {
18
+ [Name in keyof Flags]: Flags[Name] extends {
19
+ type: 'option';
20
+ } ? Name : never;
21
+ }[keyof Flags];
22
+ /**
23
+ * Declare which of a command's flags must report their name without their
24
+ * value. Names are checked against the command's option flags.
25
+ *
26
+ * Redact any flag whose value can carry free text, a filesystem path,
27
+ * document content, or a credential. A path in particular is one of the few
28
+ * things https://www.sanity.io/telemetry excludes outright.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * static telemetry = defineCommandTelemetry(flags, {redact: ['reason']})
33
+ * ```
34
+ */
35
+ export declare function defineCommandTelemetry<const Flags extends Interfaces.FlagInput>(flags: Flags, config: {
36
+ redact?: readonly OptionFlagName<Flags>[];
37
+ }): CommandTelemetry;
38
+ /**
39
+ * The flags a trace reports, each normalised to its canonical long form so
40
+ * one flag reads the same however it was typed: `--tag=prod`, `--tag prod`,
41
+ * and `-t prod` all report `--tag=prod`.
42
+ *
43
+ * A value is reported only for a flag the command declared and did not
44
+ * redact. A redacted or undeclared flag reports its name alone, and the token
45
+ * after it is withheld when it could be the value. Tokens after the `--`
46
+ * terminator are not reported. Redaction matches declared names, so an
47
+ * undeclared flag's value must never ship: a misspelled `--resaon` would leak.
48
+ */
49
+ export declare function collectOptionArguments(args: {
50
+ argv: string[];
51
+ flagDefs: Record<string, FlagShape> | undefined;
52
+ commandTelemetry: CommandTelemetry | undefined;
53
+ }): string[];
54
+ export {};
@@ -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,151 @@
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
+ import { type ResourceTargetFlags } from './resource-target.ts';
5
+ export interface DeploymentContext {
6
+ deployment: WorkflowDeployment;
7
+ client: SanityClient;
8
+ scope: EngineScope;
9
+ }
10
+ export interface InstanceContext {
11
+ client: SanityClient;
12
+ scope: EngineScope;
13
+ }
14
+ /** Resolve the selected deployment. Deploy, definition-diff, and blueprint provision compare
15
+ * its acknowledgement with submitted definitions; selection alone must not assert a floor. */
16
+ export declare function resolveContext(flags: {
17
+ path?: string | undefined;
18
+ deployment?: string | undefined;
19
+ partition?: string | undefined;
20
+ }): Promise<DeploymentContext>;
21
+ /**
22
+ * The engine scope for an instance a read located. The partition comes from
23
+ * the instance's stored `tag`; alias-bound resource clients come from the
24
+ * configured deployment with that partition on the hit's resource, if any.
25
+ */
26
+ export declare function instanceScope(hit: InstanceHit): EngineScope;
27
+ /** One resource a read inspects, with its authenticated client and the
28
+ * configured deployments on it, which name it in an ambiguity. */
29
+ export interface ReadTarget {
30
+ resource: WorkflowResource;
31
+ client: SanityClient;
32
+ deployments: readonly WorkflowDeployment[];
33
+ }
34
+ export interface ReadScope {
35
+ targets: ReadTarget[];
36
+ partition: string | undefined;
37
+ }
38
+ /** What a lookup does with several hits: ask on stderr, fail naming the
39
+ * candidates, or return none so a wider search decides. */
40
+ export type Ambiguity = 'prompt' | 'fail' | 'defer';
41
+ export declare function ambiguityFor(flags: {
42
+ json?: boolean | undefined;
43
+ }): Ambiguity;
44
+ /**
45
+ * The resolution every READ shares: an authenticated client per resource to
46
+ * inspect, and the partition to filter on. A read lists whatever is in the
47
+ * Content Lake, so without a selector it inherits no deployment's partition or
48
+ * definition set. The command applies the returned partition as a query filter.
49
+ *
50
+ * Without a selector, this is every distinct resource the config mentions.
51
+ * `--partition` narrows to the resources deployed under that partition
52
+ * (partitions may repeat across deployments). `--deployment` narrows to that
53
+ * deployment's resource and partition. `--workflow-resource`, or
54
+ * `--project-id` with `--dataset`, replace the config's resources with the one
55
+ * they name, and no config loads; `--partition` still filters. With no config found, the run
56
+ * reads the resource picked on an interactive terminal. The token resolves once for the
57
+ * run, however many targets it spans.
58
+ */
59
+ export declare function resolveReadTargets(flags: InstanceSelectorFlags): Promise<ReadScope>;
60
+ /** Distinct resources, keyed by their resource-shaped GDR (`<type>:<id>`).
61
+ * The first occurrence wins its position, so a caller-ordered list (e.g. the
62
+ * engine resource first) keeps its lead entry. */
63
+ export declare function dedupeResources(resources: WorkflowResource[]): WorkflowResource[];
64
+ /** The distinct resources a read targets: every resource deployed under the
65
+ * partition (partitions may repeat across deployments), or — without one —
66
+ * every distinct one the config's deployments mention ({@link dedupeResources}). */
67
+ export declare function resolveReadResources(config: WorkflowConfig, partition: string | undefined): WorkflowResource[];
68
+ /**
69
+ * The resolution an instance-id-targeted command shares, read or write: locate
70
+ * the instance by the same cross-resource fan-out the read/list commands use
71
+ * ({@link findInstance}), then hand back an authenticated client for the
72
+ * resource that held it plus a scope whose `partition` comes from the
73
+ * instance's stored `tag` field — never from the config's declared deployments.
74
+ * An instance id is globally unique and carries its own partition, so naming
75
+ * one is enough to act on it: the config only locates candidate resources, and the fan-out's
76
+ * {@link soleHitOrChoose} settles the collision case where several datasets hold
77
+ * the id (the `<partition>.` fast-path may skip that full-set check — safe, ids are
78
+ * collision-free). `--deployment` / `--partition` stay optional narrowers, not
79
+ * required disambiguators.
80
+ *
81
+ * Contrast {@link resolveContext}: the deploy/diff/delete path IS scoped to a
82
+ * declared deployment because it acts on the authored definition set (or a
83
+ * definition name, which — unlike an instance id — isn't unique across partitions).
84
+ */
85
+ export declare function resolveInstanceContext(flags: InstanceSelectorFlags, instanceId: string): Promise<InstanceContext>;
86
+ /** {@link resolveInstanceContext} for a command that only reads, so with no
87
+ * config found it can locate the instance in a resource picked on stderr. */
88
+ export declare function resolveReadInstanceContext(flags: InstanceSelectorFlags, instanceId: string): Promise<InstanceContext>;
89
+ interface InstanceSelectorFlags extends ResourceTargetFlags {
90
+ path?: string | undefined;
91
+ deployment?: string | undefined;
92
+ partition?: string | undefined;
93
+ json?: boolean | undefined;
94
+ }
95
+ /** An instance located without interpreting its shape — the resource that held
96
+ * it and the {@link InstanceStamps} a delete gates on. */
97
+ export interface InstanceStampsContext {
98
+ resource: WorkflowResource;
99
+ stamps: InstanceStamps;
100
+ }
101
+ /**
102
+ * Locate an instance by the same fan-out and `<tag>.` fast-path as
103
+ * {@link resolveInstanceContext}, but reading only a projection — for the one
104
+ * caller that must not be refused by the reader-floor gate. See
105
+ * {@link findInstanceStamps} for why `nuke --instance` is that caller.
106
+ *
107
+ * Returns no client: a projection cannot be acted on through an engine verb, so
108
+ * the caller builds its own write clients from the deployment it resolves.
109
+ */
110
+ export declare function resolveInstanceStamps(flags: InstanceSelectorFlags, instanceId: string): Promise<InstanceStampsContext>;
111
+ /** A read target that turned out to hold the instance being looked up. */
112
+ export interface InstanceHit extends ReadTarget {
113
+ instance: WorkflowInstance;
114
+ }
115
+ export type ChooseCandidate = (choices: {
116
+ name: string;
117
+ value: string;
118
+ description: string;
119
+ }[]) => Promise<string>;
120
+ /** `subject` names the thing looked up in the diagnostic (`Instance <id>`, `Definition "x"`). */
121
+ export declare function soleHitOrChoose<T extends ReadTarget>(hits: T[], args: {
122
+ subject: string;
123
+ partitionOf: (hit: T) => string | undefined;
124
+ ambiguity: Ambiguity;
125
+ choose?: ChooseCandidate;
126
+ }): Promise<T | undefined>;
127
+ /**
128
+ * Look an instance id up across every read target, reading each hit as a full
129
+ * engine-gated instance document — the locate every command that then acts
130
+ * through an engine verb uses. See {@link findAcrossTargets} for the
131
+ * one-hit-wins semantics.
132
+ */
133
+ export declare function findInstance({ targets, instanceId, requestTag, ambiguity, }: {
134
+ targets: ReadTarget[];
135
+ instanceId: string;
136
+ requestTag: string;
137
+ ambiguity: Ambiguity;
138
+ }): Promise<InstanceHit | undefined>;
139
+ /**
140
+ * The four persisted fields a delete needs to decide it may proceed, read
141
+ * WITHOUT interpreting the document's shape: `_type` to prove it is an engine
142
+ * instance and not co-located content, `tag` to locate the owning deployment,
143
+ * and the terminal stamps to prove it has settled.
144
+ */
145
+ export interface InstanceStamps {
146
+ _type: string;
147
+ tag?: string;
148
+ completedAt?: string;
149
+ abortedAt?: string;
150
+ }
151
+ export {};