@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,97 @@
1
+ import { DEV_ONLY_PACKAGES, isRecord, replacementPackage, retiredNamesIn } from './package-map.js';
2
+ const DEPENDENCY_FIELDS = [
3
+ 'dependencies',
4
+ 'devDependencies',
5
+ 'peerDependencies',
6
+ 'optionalDependencies',
7
+ ];
8
+ function dependenciesIn(manifest, field) {
9
+ const value = manifest[field];
10
+ if (!isRecord(value))
11
+ return undefined;
12
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === 'string'));
13
+ }
14
+ function indentOf(source) {
15
+ return /^[{[]\r?\n([ \t]+)/.exec(source)?.[1] ?? ' ';
16
+ }
17
+ function targetField(field, replacement) {
18
+ return DEV_ONLY_PACKAGES.has(replacement) && field !== 'peerDependencies'
19
+ ? 'devDependencies'
20
+ : field;
21
+ }
22
+ function withReplacements(args) {
23
+ const entries = Object.entries(args.deps).flatMap(([name, range]) => {
24
+ const replacement = replacementPackage(name);
25
+ if (replacement === undefined)
26
+ return [[name, range]];
27
+ const addedRange = args.added.get(replacement);
28
+ return addedRange === undefined ? [] : [[replacement, addedRange]];
29
+ });
30
+ const present = new Set(entries.map(([name]) => name));
31
+ const appended = [...args.added].filter(([name]) => !present.has(name));
32
+ return Object.fromEntries([...entries, ...appended]);
33
+ }
34
+ function rangeFor(declared, range) {
35
+ return declared?.startsWith('workspace:') ? declared : range;
36
+ }
37
+ function planFields(manifest, range) {
38
+ const plans = new Map(DEPENDENCY_FIELDS.map((field) => [field, { removed: [], added: new Map() }]));
39
+ const placed = new Set();
40
+ const add = (field, [name, addedRange]) => {
41
+ const key = `${field}:${name}`;
42
+ if (placed.has(key) || dependenciesIn(manifest, field)?.[name] !== undefined)
43
+ return;
44
+ placed.add(key);
45
+ plans.get(field)?.added.set(name, addedRange);
46
+ };
47
+ DEPENDENCY_FIELDS.forEach((field) => {
48
+ const deps = dependenciesIn(manifest, field) ?? {};
49
+ Object.keys(deps).forEach((name) => {
50
+ const replacement = replacementPackage(name);
51
+ if (replacement === undefined)
52
+ return;
53
+ plans.get(field)?.removed.push(name);
54
+ add(targetField(field, replacement), [replacement, rangeFor(deps[name], range)]);
55
+ });
56
+ });
57
+ return plans;
58
+ }
59
+ function renamedPeerMeta(meta) {
60
+ if (!isRecord(meta))
61
+ return meta;
62
+ return Object.fromEntries(Object.entries(meta).map(([name, value]) => [replacementPackage(name) ?? name, value]));
63
+ }
64
+ function retiredMentions(manifest) {
65
+ return Object.entries(manifest)
66
+ .filter(([key]) => !DEPENDENCY_FIELDS.includes(key))
67
+ .filter(([key]) => key !== 'peerDependenciesMeta')
68
+ .flatMap(([key, value]) => retiredNamesIn(JSON.stringify(value)).map((name) => `"${key}" mentions ${name}`));
69
+ }
70
+ export function rewriteManifest(source, range) {
71
+ const parsed = JSON.parse(source);
72
+ if (!isRecord(parsed))
73
+ return { source, changes: [], reports: [] };
74
+ const plans = planFields(parsed, range);
75
+ const changes = [...plans].flatMap(([field, plan]) => [
76
+ ...plan.removed.map((name) => `${field}: removed ${name}`),
77
+ ...[...plan.added].map(([name, added]) => `${field}: added ${name}@${added}`),
78
+ ]);
79
+ if (changes.length === 0)
80
+ return { source, changes, reports: retiredMentions(parsed) };
81
+ const rewritten = { ...parsed };
82
+ plans.forEach((plan, field) => {
83
+ const deps = dependenciesIn(parsed, field);
84
+ if (deps === undefined && plan.added.size === 0)
85
+ return;
86
+ rewritten[field] = withReplacements({ deps: deps ?? {}, added: plan.added });
87
+ });
88
+ if (parsed['peerDependenciesMeta'] !== undefined) {
89
+ rewritten['peerDependenciesMeta'] = renamedPeerMeta(parsed['peerDependenciesMeta']);
90
+ }
91
+ const trailing = source.endsWith('\n') ? '\n' : '';
92
+ return {
93
+ source: `${JSON.stringify(rewritten, null, indentOf(source))}${trailing}`,
94
+ changes,
95
+ reports: retiredMentions(parsed),
96
+ };
97
+ }
@@ -0,0 +1,26 @@
1
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
2
+ /** The package that replaces `name`, or `undefined` when `name` was not retired. */
3
+ export declare function replacementPackage(name: string): string | undefined;
4
+ /** The test bench installs as a development dependency, except where a package declares it as a peer. */
5
+ export declare const DEV_ONLY_PACKAGES: ReadonlySet<string>;
6
+ export type SpecifierMatch = {
7
+ kind: 'none';
8
+ } | {
9
+ kind: 'rewrite';
10
+ replacement: string;
11
+ } | {
12
+ kind: 'unknown-entry';
13
+ retired: string;
14
+ };
15
+ /**
16
+ * How the codemod treats a module specifier. Only the exact entry points the
17
+ * retired packages exported are rewritten; any other subpath of a retired
18
+ * package resolved nowhere and is reported instead.
19
+ */
20
+ export declare function matchSpecifier(specifier: string): SpecifierMatch;
21
+ /** Old export name to new, for one entry point. */
22
+ export type ExportRenames = Readonly<Record<string, string>>;
23
+ /** Renames for the entry point `specifier` names; the old and new specifier give the same result. */
24
+ export declare function exportRenamesFor(specifier: string): ExportRenames | undefined;
25
+ /** The retired package names `text` mentions, each as a whole package-name segment. */
26
+ export declare function retiredNamesIn(text: string): string[];
@@ -0,0 +1,90 @@
1
+ const PACKAGE_REPLACEMENTS = {
2
+ '@sanity/workflow-engine': '@sanity/workflows',
3
+ '@sanity/workflow-blueprint': '@sanity/workflows',
4
+ '@sanity/groq-condition-describe': '@sanity/workflows',
5
+ '@sanity/workflow-mcp': '@sanity/workflows',
6
+ '@sanity/workflow-studio-plugin': '@sanity/workflows-ui',
7
+ '@sanity/workflow-studio': '@sanity/workflows-ui',
8
+ '@sanity/workflow-react': '@sanity/workflows-ui',
9
+ '@sanity/workflow-sdk': '@sanity/workflows-ui',
10
+ '@sanity/workflow-components': '@sanity/workflows-ui',
11
+ '@sanity/workflow-diagram': '@sanity/workflows-ui',
12
+ '@sanity/workflow-cli': '@sanity/workflows-cli',
13
+ '@sanity/workflow-engine-test': '@sanity/workflows-test',
14
+ };
15
+ const ENTRY_REPLACEMENTS = {
16
+ '@sanity/workflow-engine': '@sanity/workflows',
17
+ '@sanity/workflow-engine/define': '@sanity/workflows/define',
18
+ '@sanity/workflow-engine/generate': '@sanity/workflows/generate',
19
+ '@sanity/workflow-engine/service': '@sanity/workflows/service',
20
+ '@sanity/workflow-blueprint': '@sanity/workflows/blueprints',
21
+ '@sanity/workflow-blueprint/generate': '@sanity/workflows/blueprints/generate',
22
+ '@sanity/workflow-blueprint/runtime': '@sanity/workflows/blueprints/runtime',
23
+ '@sanity/groq-condition-describe': '@sanity/workflows/describe',
24
+ '@sanity/workflow-mcp': '@sanity/workflows/agents',
25
+ '@sanity/workflow-studio-plugin': '@sanity/workflows-ui/studio-plugin',
26
+ '@sanity/workflow-studio': '@sanity/workflows-ui/studio',
27
+ '@sanity/workflow-react': '@sanity/workflows-ui/react',
28
+ '@sanity/workflow-react/observer': '@sanity/workflows-ui/react/observer',
29
+ '@sanity/workflow-sdk': '@sanity/workflows-ui/sdk',
30
+ '@sanity/workflow-sdk/observer': '@sanity/workflows-ui/sdk/observer',
31
+ '@sanity/workflow-sdk/project-users': '@sanity/workflows-ui/sdk/project-users',
32
+ '@sanity/workflow-components': '@sanity/workflows-ui/components',
33
+ '@sanity/workflow-diagram': '@sanity/workflows-ui/diagram',
34
+ '@sanity/workflow-cli': '@sanity/workflows-cli',
35
+ '@sanity/workflow-engine-test': '@sanity/workflows-test',
36
+ ...Object.fromEntries(Object.entries(PACKAGE_REPLACEMENTS).map(([retired, replacement]) => [
37
+ `${retired}/package.json`,
38
+ `${replacement}/package.json`,
39
+ ])),
40
+ };
41
+ export function isRecord(value) {
42
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
43
+ }
44
+ export function replacementPackage(name) {
45
+ return Object.hasOwn(PACKAGE_REPLACEMENTS, name)
46
+ ? PACKAGE_REPLACEMENTS[name]
47
+ : undefined;
48
+ }
49
+ export const DEV_ONLY_PACKAGES = new Set(['@sanity/workflows-test']);
50
+ function packageNameOf(specifier) {
51
+ const [first = '', second] = specifier.split('/');
52
+ return first.startsWith('@') && second !== undefined ? `${first}/${second}` : first;
53
+ }
54
+ export function matchSpecifier(specifier) {
55
+ const replacement = Object.hasOwn(ENTRY_REPLACEMENTS, specifier)
56
+ ? ENTRY_REPLACEMENTS[specifier]
57
+ : undefined;
58
+ if (replacement !== undefined)
59
+ return { kind: 'rewrite', replacement };
60
+ const name = packageNameOf(specifier);
61
+ return replacementPackage(name) === undefined
62
+ ? { kind: 'none' }
63
+ : { kind: 'unknown-entry', retired: name };
64
+ }
65
+ const EXPORT_RENAMES = {
66
+ '@sanity/workflows-ui/studio-plugin': {
67
+ workflowStudioPlugin: 'workflowsStudioPlugin',
68
+ workflowDefaultDocumentNode: 'workflowsDefaultDocumentNode',
69
+ WorkflowPluginConfig: 'WorkflowsPluginConfig',
70
+ LegacyTagWorkflowPluginConfig: 'LegacyTagWorkflowsPluginConfig',
71
+ },
72
+ '@sanity/workflows-ui/react': { useWorkflowTelemetry: 'useWorkflowsTelemetry' },
73
+ '@sanity/workflows-ui/sdk': {
74
+ useWorkflowTelemetry: 'useWorkflowsTelemetry',
75
+ WorkflowTelemetryProvider: 'WorkflowsTelemetryProvider',
76
+ },
77
+ };
78
+ export function exportRenamesFor(specifier) {
79
+ const match = matchSpecifier(specifier);
80
+ const entry = match.kind === 'rewrite' ? match.replacement : specifier;
81
+ return Object.hasOwn(EXPORT_RENAMES, entry) ? EXPORT_RENAMES[entry] : undefined;
82
+ }
83
+ const RETIRED_NAME_SOURCE = Object.keys(PACKAGE_REPLACEMENTS)
84
+ .sort((a, b) => b.length - a.length)
85
+ .map((name) => name.replaceAll('/', '\\/'))
86
+ .join('|');
87
+ export function retiredNamesIn(text) {
88
+ const pattern = new RegExp(`(?<![\\w@.-])(?:${RETIRED_NAME_SOURCE})(?![\\w-])`, 'g');
89
+ return [...new Set(text.match(pattern) ?? [])];
90
+ }
@@ -0,0 +1,4 @@
1
+ import type { CodemodRun } from './run.ts';
2
+ export declare function codemodLines(args: CodemodRun & {
3
+ dryRun: boolean;
4
+ }): string[];
@@ -0,0 +1,46 @@
1
+ import logSymbols from 'log-symbols';
2
+ import { CLI_PACKAGE_NAME } from '../../hooks/prerun/telemetry.js';
3
+ const REPORT_LABELS = {
4
+ 'unknown-entry': 'not an entry point of the retired package',
5
+ 'computed-specifier': 'built-up module specifier',
6
+ string: 'package name in a string',
7
+ 'jsx-text': 'package name in JSX text',
8
+ comment: 'package name in a comment',
9
+ 'parse-error': 'could not parse the file',
10
+ 'shadowed-rename': 'kept under its old local name because the file reuses it or the new name; works as is',
11
+ 'shadowed-namespace': 'not renamed because the file reuses the namespace name; rename it if it reads the import',
12
+ };
13
+ function rewriteLines(files, verb) {
14
+ const changed = files.filter((file) => file.rewrites.length > 0);
15
+ if (changed.length === 0)
16
+ return [`${logSymbols.info} No imports or dependencies name a retired package.`];
17
+ return [
18
+ `${logSymbols.success} ${verb} ${changed.length} files:`,
19
+ ...changed.map((file) => ` ${file.path}: ${file.rewrites.join(', ')}`),
20
+ ];
21
+ }
22
+ function reportLines(files) {
23
+ const reports = files.flatMap((file) => file.reports.map((report) => ` ${file.path}:${report.line} ${REPORT_LABELS[report.kind]}: ${report.text}`));
24
+ if (reports.length === 0)
25
+ return [];
26
+ return ['', `${logSymbols.warning} Fix these by hand:`, ...reports];
27
+ }
28
+ export function codemodLines(args) {
29
+ const generated = args.generated.length === 0
30
+ ? []
31
+ : ['', `${logSymbols.info} Skipped ${args.generated.length} generated blueprint files.`];
32
+ const next = args.dryRun
33
+ ? []
34
+ : [
35
+ '',
36
+ 'Next: install dependencies, then run',
37
+ ` npx ${CLI_PACKAGE_NAME} blueprints generate (if the project has a generated blueprint)`,
38
+ 'and typecheck.',
39
+ ];
40
+ return [
41
+ ...rewriteLines(args.files, args.dryRun ? 'Would rewrite' : 'Rewrote'),
42
+ ...reportLines(args.files),
43
+ ...generated,
44
+ ...next,
45
+ ];
46
+ }
@@ -0,0 +1,23 @@
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
+ }
8
+ export interface CodemodRun {
9
+ files: FileOutcome[];
10
+ /** Generated blueprint files left for `blueprints generate` to rewrite. */
11
+ generated: string[];
12
+ }
13
+ /**
14
+ * Rewrites retired Workflows package names and renamed exports under `paths`.
15
+ * `range` is the version range written for each replacement package. With
16
+ * `write: false` nothing is written and the outcome describes what would change.
17
+ */
18
+ export declare function runCodemod(args: {
19
+ paths: readonly string[];
20
+ cwd: string;
21
+ range: string;
22
+ write: boolean;
23
+ }): CodemodRun;
@@ -0,0 +1,106 @@
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
+ },
75
+ };
76
+ }
77
+ const result = rewriteSource(original, path);
78
+ return {
79
+ source: result.source,
80
+ outcome: {
81
+ rewrites: [
82
+ ...(result.rewrites === 0 ? [] : [`${result.rewrites} module specifiers`]),
83
+ ...(result.renames === 0 ? [] : [`${result.renames} renamed export names`]),
84
+ ],
85
+ reports: result.reports,
86
+ },
87
+ };
88
+ }
89
+ export function runCodemod(args) {
90
+ const targets = [
91
+ ...new Set(args.paths.flatMap((path) => filesUnder(resolve(args.cwd, path)))),
92
+ ].filter(isCodemodTarget);
93
+ const generated = targets.filter(isGeneratedFile);
94
+ const files = targets
95
+ .filter((path) => !generated.includes(path))
96
+ .toSorted()
97
+ .flatMap((path) => {
98
+ const { source, outcome } = rewriteFile(path, args.range);
99
+ if (args.write && outcome.rewrites.length > 0)
100
+ writeFileSync(path, source);
101
+ return outcome.rewrites.length === 0 && outcome.reports.length === 0
102
+ ? []
103
+ : [{ path: relative(args.cwd, path), ...outcome }];
104
+ });
105
+ return { files, generated: generated.map((path) => relative(args.cwd, path)).toSorted() };
106
+ }
@@ -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. Only string literals and identifiers
18
+ * change, so formatting is kept.
19
+ */
20
+ export declare function rewriteSource(source: string, filename: string): RewriteResult;
@@ -0,0 +1,149 @@
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);
139
+ renamed.reports.forEach(({ kind, text, ...span }) => report(span, { kind, text }));
140
+ parsed.comments
141
+ .filter((comment) => retiredNamesIn(comment.value).length > 0)
142
+ .forEach((comment) => report(comment, { kind: 'comment', text: firstLine(comment.value) }));
143
+ return {
144
+ source: applyEdits(source, [...edits, ...renamed.edits]),
145
+ rewrites: edits.length,
146
+ renames: renamed.edits.length,
147
+ reports: reports.toSorted((a, b) => a.line - b.line),
148
+ };
149
+ }
@@ -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 {};