@snap/valdi 1.0.7 → 1.0.11

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 (170) hide show
  1. package/.bootstrap/modules/{ios_android_bridge_module → polyglot_bridge_module}/BUILD.bazel.template +16 -1
  2. package/.bootstrap/modules/polyglot_bridge_module/web/Calculator.ts +11 -0
  3. package/.bootstrap/modules/polyglot_bridge_module/web/tsconfig.json +16 -0
  4. package/.bootstrap/modules/polyglot_view_module/BUILD.bazel.template +75 -0
  5. package/.bootstrap/modules/polyglot_view_module/android/PolyglotNativeView.kt.template +41 -0
  6. package/.bootstrap/modules/polyglot_view_module/android/PolyglotNativeViewAttributesBinder.kt.template +17 -0
  7. package/.bootstrap/modules/polyglot_view_module/ios/SCPolyglotView.h +8 -0
  8. package/.bootstrap/modules/polyglot_view_module/ios/SCPolyglotView.m +23 -0
  9. package/.bootstrap/modules/polyglot_view_module/macos/SCPolyglotView.h +8 -0
  10. package/.bootstrap/modules/polyglot_view_module/macos/SCPolyglotView.m +23 -0
  11. package/.bootstrap/modules/polyglot_view_module/src/PolyglotCustomView.tsx.template +23 -0
  12. package/.bootstrap/modules/polyglot_view_module/web/PolyglotWeb.ts.template +30 -0
  13. package/.bootstrap/modules/polyglot_view_module/web/tsconfig.json +16 -0
  14. package/.metadata/AGENTS.md.template +8 -274
  15. package/.metadata/skill-reference.tsx.template +8 -0
  16. package/.metadata/skill-tests-BUILD.bazel.template +21 -0
  17. package/.metadata/skill-tests-README.md.template +17 -0
  18. package/.metadata/skill.md.template +27 -0
  19. package/README.md +12 -3
  20. package/bundled-skills/CONTRIBUTING_SKILLS.md +74 -0
  21. package/bundled-skills/registry.json +21 -0
  22. package/bundled-skills/skills/valdi-android/skill.md +89 -0
  23. package/bundled-skills/skills/valdi-async/skill.md +246 -0
  24. package/bundled-skills/skills/valdi-async/tests/BUILD.bazel +19 -0
  25. package/bundled-skills/skills/valdi-async/tests/README.md +25 -0
  26. package/bundled-skills/skills/valdi-async/tests/src/reference.tsx +210 -0
  27. package/bundled-skills/skills/valdi-async/tests/tsconfig.json +1 -0
  28. package/bundled-skills/skills/valdi-bazel/skill.md +141 -0
  29. package/bundled-skills/skills/valdi-compiler/skill.md +108 -0
  30. package/bundled-skills/skills/valdi-component-tests/skill.md +430 -0
  31. package/bundled-skills/skills/valdi-component-tests/tests/BUILD.bazel +24 -0
  32. package/bundled-skills/skills/valdi-component-tests/tests/README.md +35 -0
  33. package/bundled-skills/skills/valdi-component-tests/tests/src/ProfileCard.tsx +38 -0
  34. package/bundled-skills/skills/valdi-component-tests/tests/test/ProfileCardTest.spec.tsx +107 -0
  35. package/bundled-skills/skills/valdi-component-tests/tests/tsconfig.json +1 -0
  36. package/bundled-skills/skills/valdi-cpp-runtime/skill.md +103 -0
  37. package/bundled-skills/skills/valdi-custom-view/skill.md +64 -0
  38. package/bundled-skills/skills/valdi-inspect/skill.md +199 -0
  39. package/bundled-skills/skills/valdi-ios/skill.md +93 -0
  40. package/bundled-skills/skills/valdi-migrate/skill.md +175 -0
  41. package/bundled-skills/skills/valdi-migrate/tests/BUILD.bazel +23 -0
  42. package/bundled-skills/skills/valdi-migrate/tests/README.md +70 -0
  43. package/bundled-skills/skills/valdi-migrate/tests/check_antipatterns.py +89 -0
  44. package/bundled-skills/skills/valdi-migrate/tests/compose_example.kt +94 -0
  45. package/bundled-skills/skills/valdi-migrate/tests/flutter_example.dart +129 -0
  46. package/bundled-skills/skills/valdi-migrate/tests/react_example.tsx +98 -0
  47. package/bundled-skills/skills/valdi-migrate/tests/src/expected_valdi.tsx +267 -0
  48. package/bundled-skills/skills/valdi-migrate/tests/tsconfig.json +3 -0
  49. package/bundled-skills/skills/valdi-overview/skill.md +63 -0
  50. package/bundled-skills/skills/valdi-perf/skill.md +197 -0
  51. package/bundled-skills/skills/valdi-perf/tests/BUILD.bazel +19 -0
  52. package/bundled-skills/skills/valdi-perf/tests/README.md +26 -0
  53. package/bundled-skills/skills/valdi-perf/tests/src/reference.tsx +202 -0
  54. package/bundled-skills/skills/valdi-perf/tests/tsconfig.json +1 -0
  55. package/bundled-skills/skills/valdi-polyglot-module/skill.md +124 -0
  56. package/bundled-skills/skills/valdi-profile/skill.md +126 -0
  57. package/bundled-skills/skills/valdi-setup/skill.md +129 -0
  58. package/bundled-skills/skills/valdi-testing/skill.md +65 -0
  59. package/bundled-skills/skills/valdi-tsx/skill.md +385 -0
  60. package/bundled-skills/skills/valdi-tsx/tests/BUILD.bazel +19 -0
  61. package/bundled-skills/skills/valdi-tsx/tests/README.md +29 -0
  62. package/bundled-skills/skills/valdi-tsx/tests/src/reference.tsx +173 -0
  63. package/bundled-skills/skills/valdi-tsx/tests/tsconfig.json +1 -0
  64. package/dist/commands/bootstrap.js +0 -7
  65. package/dist/commands/inspect.js +16 -0
  66. package/dist/commands/inspect_commands/contexts.js +55 -0
  67. package/dist/commands/inspect_commands/devices.js +53 -0
  68. package/dist/commands/inspect_commands/heap.js +59 -0
  69. package/dist/commands/inspect_commands/select.js +43 -0
  70. package/dist/commands/inspect_commands/snapshot.js +64 -0
  71. package/dist/commands/inspect_commands/status.js +68 -0
  72. package/dist/commands/inspect_commands/tree.js +86 -0
  73. package/dist/commands/newModule.js +10 -14
  74. package/dist/commands/profile.js +16 -0
  75. package/dist/commands/profile_commands/capture.js +106 -0
  76. package/dist/commands/skills.js +16 -0
  77. package/dist/commands/skills_commands/create.js +125 -0
  78. package/dist/commands/skills_commands/install.js +96 -0
  79. package/dist/commands/skills_commands/list.js +83 -0
  80. package/dist/commands/skills_commands/remove.js +41 -0
  81. package/dist/commands/skills_commands/update.js +59 -0
  82. package/dist/core/constants.js +0 -1
  83. package/dist/core/packageFiles.spec.js +29 -0
  84. package/dist/setup/versions.js +1 -1
  85. package/dist/utils/daemonClient.js +342 -0
  86. package/dist/utils/hermesClient.js +252 -0
  87. package/dist/utils/skillsAdapters.js +140 -0
  88. package/dist/utils/skillsRegistry.js +40 -0
  89. package/dist/utils/stringUtils.spec.js +1 -1
  90. package/package.json +20 -5
  91. package/.bazelignore +0 -2
  92. package/.bootstrap/modules/cpp_bridge_module/BUILD.bazel.template +0 -21
  93. package/.bootstrap/modules/cpp_bridge_module/cpp/CalculatorModuleFactory.cpp.template +0 -28
  94. package/.bootstrap/modules/ios_android_bridge_module/src/Calculator.d.ts +0 -4
  95. package/.bootstrap/modules/ios_android_view_module/BUILD.bazel.template +0 -41
  96. package/.bootstrap/modules/ios_android_view_module/android/CircleView.kt.template +0 -42
  97. package/.bootstrap/modules/ios_android_view_module/android/CircleViewAttributesBinder.kt.template +0 -60
  98. package/.bootstrap/modules/ios_android_view_module/ios/SCCCircleView.h +0 -6
  99. package/.bootstrap/modules/ios_android_view_module/ios/SCCCircleView.m +0 -82
  100. package/.bootstrap/modules/ios_android_view_module/src/Circle.tsx.template +0 -15
  101. package/.config/copyconfig.json +0 -10
  102. package/.editorconfig +0 -21
  103. package/.eslintignore +0 -1
  104. package/.eslintrc.js +0 -72
  105. package/.github/README.md +0 -164
  106. package/.metadata/.cursorrules.template +0 -60
  107. package/.prettierignore +0 -2
  108. package/.prettierrc.json +0 -7
  109. package/LINUX_COMPATIBILITY.md +0 -248
  110. package/prettier.config.js +0 -4
  111. package/scripts/sync-agents-md.sh +0 -44
  112. package/scripts/update-agents-templates.ts +0 -170
  113. package/spec/support/jasmine.json +0 -6
  114. package/src/commands/bootstrap.ts +0 -410
  115. package/src/commands/build.ts +0 -89
  116. package/src/commands/devSetup.ts +0 -17
  117. package/src/commands/doctor.ts +0 -1832
  118. package/src/commands/export.ts +0 -131
  119. package/src/commands/hotreload.ts +0 -108
  120. package/src/commands/install.ts +0 -93
  121. package/src/commands/lint.ts +0 -15
  122. package/src/commands/lint_commands/lintCheck.ts +0 -53
  123. package/src/commands/lint_commands/lintFormat.ts +0 -49
  124. package/src/commands/log.ts +0 -108
  125. package/src/commands/newModule.ts +0 -286
  126. package/src/commands/package.ts +0 -102
  127. package/src/commands/projectsync.ts +0 -488
  128. package/src/commands/test.ts +0 -68
  129. package/src/core/constants.ts +0 -98
  130. package/src/core/errors.ts +0 -10
  131. package/src/index.ts +0 -27
  132. package/src/setup/DevSetupHelper.ts +0 -290
  133. package/src/setup/linuxSetup.ts +0 -261
  134. package/src/setup/macOSSetup.ts +0 -156
  135. package/src/setup/setupEntryPoint.ts +0 -64
  136. package/src/setup/versions.ts +0 -8
  137. package/src/utils/ArgumentsResolver.ts +0 -23
  138. package/src/utils/BazelClient.ts +0 -285
  139. package/src/utils/Digraph.ts +0 -81
  140. package/src/utils/LoadingIndicator.ts +0 -43
  141. package/src/utils/applicationUtils.ts +0 -276
  142. package/src/utils/buildInfo.ts +0 -99
  143. package/src/utils/byString.ts +0 -3
  144. package/src/utils/cliUtils.ts +0 -112
  145. package/src/utils/copyBootstrapFiles.ts +0 -30
  146. package/src/utils/deviceUtils.ts +0 -76
  147. package/src/utils/errorUtils.ts +0 -63
  148. package/src/utils/fileUtils.ts +0 -257
  149. package/src/utils/githubUtils.ts +0 -102
  150. package/src/utils/jsonUtils.ts +0 -30
  151. package/src/utils/lintUtils.ts +0 -190
  152. package/src/utils/linuxDistro.spec.ts +0 -219
  153. package/src/utils/linuxDistro.ts +0 -326
  154. package/src/utils/logUtils.ts +0 -9
  155. package/src/utils/pathUtils.ts +0 -12
  156. package/src/utils/stringUtils.spec.ts +0 -95
  157. package/src/utils/stringUtils.ts +0 -103
  158. package/src/utils/tempDir.ts +0 -24
  159. package/src/utils/zipUtils.ts +0 -14
  160. package/test/ValdiSmokeTest.ts +0 -279
  161. package/test/helpers/AsyncHelpers.ts +0 -113
  162. package/test/helpers/CommandHelpers.ts +0 -37
  163. package/test/helpers/ProjectHelpers.ts +0 -153
  164. package/test/helpers/StreamHelpers.ts +0 -37
  165. package/test/helpers/TypeScriptClient.ts +0 -217
  166. package/tsconfig.dist.json +0 -8
  167. package/tsconfig.json +0 -42
  168. /package/.bootstrap/modules/{ios_android_bridge_module → polyglot_bridge_module}/android/CalculatorModuleFactory.kt.template +0 -0
  169. /package/.bootstrap/modules/{ios_android_bridge_module → polyglot_bridge_module}/ios/SCCCalculatorModuleFactory.m.template +0 -0
  170. /package/.bootstrap/modules/{cpp_bridge_module → polyglot_bridge_module}/src/Calculator.d.ts +0 -0
@@ -1,156 +0,0 @@
1
- import fs from 'fs';
2
- import { CliError } from '../core/errors';
3
- import { checkCommandExists, runCliCommand } from '../utils/cliUtils';
4
- import { DevSetupHelper } from './DevSetupHelper';
5
- import { ANDROID_MACOS_COMMANDLINE_TOOLS } from './versions';
6
-
7
- export async function macOSSetup(): Promise<void> {
8
- const devSetup = new DevSetupHelper();
9
-
10
- // Check if xcode-select command exists
11
- if (!checkCommandExists('xcode-select')) {
12
- throw new CliError(
13
- 'Xcode command line tools are not installed.\n\n' +
14
- 'Please install Xcode from the App Store, then run:\n' +
15
- ' sudo xcode-select -s /Applications/Xcode.app\n\n' +
16
- 'After installation, run valdi dev_setup again.',
17
- );
18
- }
19
-
20
- // Verify Xcode is properly configured
21
- try {
22
- const xcodePathResult = await runCliCommand('xcode-select -p');
23
- const xcodePath = xcodePathResult.stdout.trim();
24
-
25
- if (!xcodePath || !fs.existsSync(xcodePath)) {
26
- throw new CliError(
27
- 'Xcode command line tools path is not configured correctly.\n\n' +
28
- 'Please run:\n' +
29
- ' sudo xcode-select -s /Applications/Xcode.app\n\n' +
30
- 'Or if you have Xcode with a different name (e.g., beta versions):\n' +
31
- ' sudo xcode-select -s /Applications/YourXcode.app\n\n' +
32
- 'After configuration, run valdi dev_setup again.',
33
- );
34
- }
35
-
36
- // Extract Xcode.app path from the Developer path
37
- const xcodeAppPath = xcodePath.replace(/\/Contents\/Developer\/?$/, '');
38
-
39
- // Verify the Xcode app exists
40
- if (!fs.existsSync(xcodeAppPath) || !xcodeAppPath.includes('Xcode')) {
41
- throw new CliError(
42
- 'Xcode installation not found.\n\n' +
43
- `xcode-select points to ${xcodePath}\n` +
44
- `but Xcode app not found at ${xcodeAppPath}\n\n` +
45
- 'Please install Xcode from the App Store:\n' +
46
- ' https://apps.apple.com/us/app/xcode/id497799835\n\n' +
47
- 'Then configure it with:\n' +
48
- ' sudo xcode-select -s /Applications/Xcode.app\n\n' +
49
- 'After installation, run valdi dev_setup again.',
50
- );
51
- }
52
- } catch (error) {
53
- if (error instanceof CliError) {
54
- throw error;
55
- }
56
- throw new CliError(
57
- 'Failed to verify Xcode installation.\n\n' +
58
- 'Please ensure Xcode is installed from the App Store and properly configured:\n' +
59
- ' sudo xcode-select -s /Applications/Xcode.app\n\n' +
60
- 'After setup, run valdi dev_setup again.',
61
- );
62
- }
63
-
64
- if (!checkCommandExists('brew')) {
65
- await devSetup.runShell('Homebrew not found. Installing', [
66
- '/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"',
67
- ]);
68
-
69
- // Configure Homebrew PATH in .zprofile
70
- const homeDir = process.env['HOME'] ?? '';
71
- const zprofilePath = `${homeDir}/.zprofile`;
72
- const brewShellenvLine = 'eval "$(/opt/homebrew/bin/brew shellenv)"';
73
-
74
- try {
75
- let zprofileContent = '';
76
- if (fs.existsSync(zprofilePath)) {
77
- zprofileContent = fs.readFileSync(zprofilePath, 'utf8');
78
- }
79
-
80
- if (!zprofileContent.includes(brewShellenvLine)) {
81
- const newContent = zprofileContent + '\n' + brewShellenvLine + '\n';
82
- fs.writeFileSync(zprofilePath, newContent, 'utf8');
83
- console.log('Added Homebrew to PATH in .zprofile');
84
- }
85
- } catch {
86
- console.log('Note: Could not automatically configure Homebrew PATH in .zprofile');
87
- }
88
- }
89
-
90
- // Install dependencies, skipping already installed ones
91
- const packages = ['npm', 'bazelisk', 'openjdk@17', 'temurin', 'git-lfs', 'watchman', 'ios-webkit-debug-proxy'];
92
- const packagesToInstall: string[] = [];
93
-
94
- for (const pkg of packages) {
95
- try {
96
- // Check if package is already installed (from any tap)
97
- const result = await runCliCommand(`brew list ${pkg}`);
98
- if (result.returnCode !== 0) {
99
- packagesToInstall.push(pkg);
100
- }
101
- } catch {
102
- // Package not installed, add to list
103
- packagesToInstall.push(pkg);
104
- }
105
- }
106
-
107
- if (packagesToInstall.length > 0) {
108
- await devSetup.runShell(
109
- `Installing dependencies from Homebrew (${packagesToInstall.length}/${packages.length})`,
110
- [`brew install ${packagesToInstall.join(' ')}`]
111
- );
112
- } else {
113
- console.log('All Homebrew dependencies are already installed');
114
- }
115
-
116
- await devSetup.setupGitLfs();
117
-
118
- await devSetup.setupShellAutoComplete();
119
-
120
- // Check if JDK symlink exists and points to the correct location
121
- const jdkSymlinkPath = '/Library/Java/JavaVirtualMachines/openjdk-17.jdk';
122
- const jdkSourcePath = '/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk';
123
-
124
- let needsJdkSymlink = false;
125
- if (fs.existsSync(jdkSymlinkPath)) {
126
- try {
127
- const linkTarget = fs.readlinkSync(jdkSymlinkPath);
128
- if (linkTarget !== jdkSourcePath) {
129
- needsJdkSymlink = true;
130
- }
131
- } catch {
132
- // Not a symlink or can't read it, needs to be set up
133
- needsJdkSymlink = true;
134
- }
135
- } else {
136
- needsJdkSymlink = true;
137
- }
138
-
139
- if (needsJdkSymlink) {
140
- console.log('\nSetting up JDK symlink (requires admin password)...');
141
- await devSetup.runShell('Setting up JDK', [
142
- 'sudo ln -sfn /opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-17.jdk',
143
- ]);
144
- }
145
-
146
- await devSetup.writeEnvVariablesToRcFile([
147
- { name: 'PATH', value: '"/opt/homebrew/opt/openjdk@17/bin:$PATH"' },
148
- { name: 'JAVA_HOME', value: '`/usr/libexec/java_home -v 17`' },
149
- ]);
150
-
151
- const javaHome = await runCliCommand('/usr/libexec/java_home');
152
-
153
- await devSetup.setupAndroidSDK(ANDROID_MACOS_COMMANDLINE_TOOLS, javaHome.stdout.trim());
154
-
155
- devSetup.onComplete();
156
- }
@@ -1,64 +0,0 @@
1
- import { ANSI_COLORS } from '../core/constants';
2
- import { wrapInColor } from '../utils/logUtils';
3
- import { linuxSetup } from './linuxSetup';
4
- import { macOSSetup } from './macOSSetup';
5
-
6
- enum OSType {
7
- MACOS = 'macos',
8
- WINDOWS = 'windows',
9
- LINUX = 'linux',
10
- UNKNOWN = 'unknown',
11
- }
12
-
13
- function getOSType(): OSType {
14
- switch (process.platform) {
15
- case 'darwin': {
16
- return OSType.MACOS;
17
- }
18
- case 'win32': {
19
- return OSType.WINDOWS;
20
- }
21
- case 'linux': {
22
- return OSType.LINUX;
23
- }
24
- default: {
25
- return OSType.UNKNOWN;
26
- }
27
- }
28
- }
29
-
30
- export async function beginEnvironmentSetup(): Promise<number> {
31
- const os = getOSType();
32
- const returnCode = 0;
33
-
34
- switch (os) {
35
- case OSType.MACOS: {
36
- console.log(wrapInColor('Setting up development environment for MacOS...', ANSI_COLORS.BLUE_COLOR));
37
- await macOSSetup();
38
- break;
39
- }
40
- case OSType.WINDOWS: {
41
- console.log(wrapInColor('Windows is not a supported operating system...aborting...', ANSI_COLORS.RED_COLOR));
42
- return 1;
43
- }
44
- case OSType.LINUX: {
45
- console.log(wrapInColor('Setting up development environment for Linux...', ANSI_COLORS.BLUE_COLOR));
46
- await linuxSetup();
47
- break;
48
- }
49
- default: {
50
- console.log(
51
- wrapInColor(
52
- 'Could not determine current operating system, skipping automated environment setup...',
53
- ANSI_COLORS.RED_COLOR,
54
- ),
55
- );
56
- console.log(
57
- 'Please see https://github.com/Snapchat/Valdi/blob/main/docs/INSTALL.md for manual setup instructions.',
58
- );
59
- return 1;
60
- }
61
- }
62
-
63
- return returnCode;
64
- }
@@ -1,8 +0,0 @@
1
- export const ANDROID_BUILD_TOOLS_VERSION = '34.0.0';
2
- export const ANDROID_NDK_VERSION = '25.2.9519653';
3
- export const ANDROID_PLATFORM_VERSION = 'android-35';
4
-
5
- export const ANDROID_MACOS_COMMANDLINE_TOOLS =
6
- 'https://dl.google.com/android/repository/commandlinetools-mac-13114758_latest.zip';
7
- export const ANDROID_LINUX_COMMANDLINE_TOOLS =
8
- 'https://dl.google.com/android/repository/commandlinetools-linux-13114758_latest.zip';
@@ -1,23 +0,0 @@
1
- export class ArgumentsResolver<Args> {
2
- additionalResolvedArguments: Partial<Args> = {};
3
-
4
- constructor(readonly args: Args) {}
5
-
6
- getArgument<K extends keyof Args>(key: K): Args[K] {
7
- return this.args[key];
8
- }
9
-
10
- async getArgumentOrResolve<K extends keyof Args>(
11
- key: K,
12
- resolve: () => Promise<NonNullable<Args[K]>>,
13
- ): Promise<NonNullable<Args[K]>> {
14
- const value = this.args[key];
15
- if (value) {
16
- return value;
17
- }
18
-
19
- const resolved = await resolve();
20
- this.additionalResolvedArguments[key] = resolved;
21
- return resolved;
22
- }
23
- }
@@ -1,285 +0,0 @@
1
- import type { StdioOptions } from 'child_process';
2
- import path from 'path';
3
- import { ANSI_COLORS, BAZEL_BIN_ENV, BAZEL_EXECUTABLES } from '../core/constants';
4
- import { CliError } from '../core/errors';
5
- import { Digraph } from './Digraph';
6
- import { LoadingIndicator } from './LoadingIndicator';
7
- import type { CommandResult } from './cliUtils';
8
- import { checkCommandExists, runCliCommand, spawnCliCommand } from './cliUtils';
9
- import { wrapInColor } from './logUtils';
10
-
11
- const BAZEL_QUIET_OPTIONS = '--noshow_progress --noshow_loading_progress --ui_event_filters=-info,-progress';
12
- const BAZEL_PREFIXED_OPTIONS = '--max_idle_secs=5';
13
- const BAZEL_POSTFIXED_OPTIONS = '--color=yes';
14
- const DEFAULT_STDIO_MODE: StdioOptions = ['pipe', 'pipe', 'inherit'];
15
-
16
- let cached_bazel_executable: string | undefined;
17
-
18
- function getBazelCli(): string {
19
- if (!cached_bazel_executable) {
20
- const bazelBinEnv = process.env[BAZEL_BIN_ENV];
21
- if (bazelBinEnv) {
22
- cached_bazel_executable = bazelBinEnv;
23
- return bazelBinEnv;
24
- }
25
-
26
- const found = BAZEL_EXECUTABLES.find(element => checkCommandExists(element));
27
- if (!found) {
28
- throw new Error('Could not find bazel executable (bzl or bazel)');
29
- }
30
- cached_bazel_executable = found;
31
- }
32
-
33
- return cached_bazel_executable;
34
- }
35
-
36
- function getBazelCommandString(baseCommand: string, extraArgs: string, quiet: boolean): string {
37
- return `${getBazelCli()} ${BAZEL_PREFIXED_OPTIONS} ${baseCommand} ${extraArgs} ${quiet ? BAZEL_QUIET_OPTIONS : ''} ${BAZEL_POSTFIXED_OPTIONS}`.trim();
38
- }
39
-
40
- function escapeQuery(str: string): string {
41
- return str.replaceAll('"', '\\"');
42
- }
43
-
44
- export class BazelLabel {
45
- constructor(
46
- readonly repo: string | undefined,
47
- readonly target: string,
48
- readonly name: string | undefined,
49
- ) {}
50
-
51
- static fromString(str: string): BazelLabel {
52
- let repo: string | undefined;
53
- if (str.startsWith('@')) {
54
- const slashSlashIndex = str.indexOf('//');
55
- if (slashSlashIndex <= 0) {
56
- throw new Error(`Expected // after repo name (got ${str})`);
57
- }
58
-
59
- repo = str.slice(1, slashSlashIndex);
60
- str = str.slice(slashSlashIndex);
61
- }
62
- if (str.endsWith('/')) {
63
- str = str.slice(0, -1);
64
- }
65
-
66
- const separatorIndex = str.indexOf(':');
67
- if (separatorIndex >= 0) {
68
- const target = str.slice(0, separatorIndex);
69
- const name = str.slice(separatorIndex + 1);
70
- return new BazelLabel(repo, target, name);
71
- } else {
72
- return new BazelLabel(repo, str, undefined);
73
- }
74
- }
75
-
76
- toString(): string {
77
- const repoPrefix = this.repo ? `@${this.repo}` : '';
78
- if (this.name) {
79
- return `${repoPrefix}${this.target}:${this.name}`;
80
- } else {
81
- return repoPrefix + this.target;
82
- }
83
- }
84
- }
85
-
86
- class BazelCommandCache {
87
- private cache = new Map<string, Promise<string>>();
88
-
89
- constructor(readonly execute: (arg: string) => Promise<string>) {}
90
-
91
- get(args: string): Promise<string> {
92
- const existingPromise = this.cache.get(args);
93
- if (existingPromise) {
94
- return existingPromise;
95
- }
96
-
97
- const ret = this.execute(args);
98
- this.cache.set(args, ret);
99
-
100
- return ret;
101
- }
102
- }
103
-
104
- export class BazelClient {
105
- private workspaceRootCache: BazelCommandCache;
106
- private executionRootCache: BazelCommandCache;
107
-
108
- constructor() {
109
- this.workspaceRootCache = new BazelCommandCache(async () => {
110
- return this.runCommandAndGetTrimmedStdOut('info workspace');
111
- });
112
-
113
- this.executionRootCache = new BazelCommandCache(async () => {
114
- return this.runCommandAndGetTrimmedStdOut('info execution_root');
115
- });
116
- }
117
-
118
- async resolveLabel(str: string): Promise<BazelLabel> {
119
- const unresolvedLabel = BazelLabel.fromString(str);
120
-
121
- const requiresResolve = unresolvedLabel.target.split('/').includes('..');
122
- if (!requiresResolve) {
123
- return unresolvedLabel;
124
- }
125
-
126
- const resolvedTarget = await this.resolveTarget(unresolvedLabel.target);
127
- return new BazelLabel(unresolvedLabel.repo, resolvedTarget, unresolvedLabel.name);
128
- }
129
-
130
- async getWorkspaceRoot(): Promise<string> {
131
- return this.workspaceRootCache.get(process.cwd());
132
- }
133
-
134
- async getExecutionRoot(): Promise<string> {
135
- return this.executionRootCache.get(process.cwd());
136
- }
137
-
138
- async queryTargetsForKinds(kinds: string[]): Promise<string[]> {
139
- const command = `query "kind(${kinds.join('|')}, //...)"`;
140
-
141
- const { stdout: targetStrings } = await this.spawnCommand(command);
142
- const targets = targetStrings.split('\n').filter(target => target.length > 0);
143
-
144
- return targets;
145
- }
146
-
147
- async queryTargetsForTag(kind: string): Promise<string[]> {
148
- const command = `query 'attr("tags", "${kind}", //...)'`;
149
-
150
- const { stdout: targetStrings } = await this.spawnCommand(command);
151
- const targets = targetStrings.split('\n').filter(target => target.length > 0);
152
-
153
- return targets;
154
- }
155
-
156
- async query(queryStr: string): Promise<string[]> {
157
- const command = `query "${escapeQuery(queryStr)}"`;
158
- return await this.runCommandWithLinesOutput(command);
159
- }
160
-
161
- async graphQuery(queryStr: string): Promise<Digraph> {
162
- const command = `query "${escapeQuery(queryStr)}" --output=graph`;
163
- const { stdout } = await this.runCommand(command);
164
-
165
- return Digraph.parse(stdout.trim());
166
- }
167
-
168
- async queryBuildOutputs(targets: readonly string[], extraArgs: string = ''): Promise<string[]> {
169
- const command = `cquery 'set(${targets.join(' ')})' --output files ${extraArgs}`;
170
- const lines = await this.runCommandWithLinesOutput(command);
171
- return lines.sort();
172
- }
173
-
174
- async buildTarget(target: string, extraArgs: string = ''): Promise<CommandResult> {
175
- // Use 'inherit' as the stdio mode by default as usually the output irrelevant
176
- // and only the success/failure matters
177
- const commandBuildTarget = `build ${target} ${extraArgs}`;
178
-
179
- return await this.spawnCommand(commandBuildTarget, 'inherit').catch(() => {
180
- throw new CliError(`Failed to build target: ${target}`);
181
- });
182
- }
183
-
184
- async buildTargets(targets: readonly string[]): Promise<CommandResult> {
185
- // Use 'inherit' as the stdio mode by default as usually the output irrelevant
186
- // and only the success/failure matters
187
-
188
- const allTargets = targets.join(' ');
189
- const commandBuildTarget = `build ${allTargets} --show_result=${targets.length}`;
190
-
191
- return await this.spawnCommand(commandBuildTarget, 'inherit').catch(() => {
192
- throw new CliError(`Failed to build targets: ${targets.join(' ')}`);
193
- });
194
- }
195
-
196
- async runTarget(target: string, extraArgs: string = ''): Promise<CommandResult> {
197
- const commandBuildTarget = `run ${target} ${extraArgs}`;
198
-
199
- return await this.spawnCommand(commandBuildTarget, 'inherit').catch(() => {
200
- throw new CliError(`Failed to run target: ${target}`);
201
- });
202
- }
203
-
204
- // Run bazel query for targets matching queryKind and filtered to match any of the specified
205
- // filters.
206
- async queryTargetsByKindWithFilter(
207
- queryKind: string,
208
- filters?: string[],
209
- stdioMode = DEFAULT_STDIO_MODE,
210
- ): Promise<string[]> {
211
- let command = `query "kind(${queryKind}, //...)"`;
212
-
213
- if (filters !== undefined && filters.length > 0) {
214
- const filtersString = filters.join('|');
215
- command = `query 'filter("${filtersString}", kind("${queryKind}", //...))'`;
216
- }
217
-
218
- return await this.spawnCommand(command, stdioMode).then(result => {
219
- const targets = result.stdout.split('\n').filter(target => target.length > 0);
220
- return targets;
221
- });
222
- }
223
-
224
- async testTargets(targets: string[], extraArgs: string = ''): Promise<CommandResult> {
225
- const targetsString = targets.join(' ');
226
- const commandTestTarget = `test ${targetsString} ${extraArgs}`;
227
-
228
- return await this.spawnCommand(commandTestTarget, 'inherit', extraArgs).catch(() => {
229
- throw new CliError(`Failed to test targets: ${targetsString}`);
230
- });
231
- }
232
-
233
- async getVersion(): Promise<[number, string, string]> {
234
- const commandBazelInfoVersion = `version --gnu_format`;
235
- const {
236
- returnCode: returnCode,
237
- stdout: versionInfo,
238
- stderr: error,
239
- } = await this.runCommand(commandBazelInfoVersion);
240
-
241
- return [returnCode, versionInfo.trim(), String(error)];
242
- }
243
-
244
- private async runCommandWithLinesOutput(command: string): Promise<string[]> {
245
- const { stdout: outputStrings } = await this.runCommand(command);
246
- return outputStrings.split('\n').filter(output => output.length > 0);
247
- }
248
-
249
- private async runCommandAndGetTrimmedStdOut(command: string): Promise<string> {
250
- const { stdout: root } = await this.runCommand(command);
251
-
252
- return root.trim();
253
- }
254
-
255
- private runCommand(command: string): Promise<CommandResult> {
256
- const commandWithOptions = getBazelCommandString(command, '', false);
257
- return LoadingIndicator.fromTask(runCliCommand(commandWithOptions, undefined, true))
258
- .setText(`${wrapInColor('Running Bazel command:', ANSI_COLORS.YELLOW_COLOR)} ${getBazelCli()} ${command}`)
259
- .show();
260
- }
261
-
262
- private async spawnCommand(
263
- command: string,
264
- stdioMode: StdioOptions = DEFAULT_STDIO_MODE,
265
- extraArgs: string = '',
266
- ): Promise<CommandResult> {
267
- const commandWithOptions = getBazelCommandString(command, extraArgs, false);
268
- console.log(
269
- `${wrapInColor('Running Bazel command:', ANSI_COLORS.YELLOW_COLOR)} ${getBazelCli()} ${command} ${extraArgs}`,
270
- );
271
- return await spawnCliCommand(commandWithOptions, undefined, stdioMode, true, true);
272
- }
273
-
274
- private async resolveTarget(pathStr: string): Promise<string> {
275
- const absolutePath = path.resolve(pathStr);
276
- const root = await this.getWorkspaceRoot();
277
- if (!absolutePath.startsWith(root)) {
278
- throw new Error(
279
- `Could not resolve target at relative path, found Bazel workspace root at '${root}', resolved target path at ${absolutePath}`,
280
- );
281
- }
282
-
283
- return '/' + absolutePath.slice(root.length);
284
- }
285
- }
@@ -1,81 +0,0 @@
1
- export interface DigraphNode {
2
- name: string;
3
- edges: DigraphNode[];
4
- }
5
-
6
- function unquote(str: string): string {
7
- return str.slice(1, -1);
8
- }
9
-
10
- export class Digraph {
11
- private nodeByName = new Map<string, DigraphNode>();
12
- private _allNodes: DigraphNode[] = [];
13
-
14
- constructor() {}
15
-
16
- get nodes(): readonly DigraphNode[] {
17
- return this._allNodes;
18
- }
19
-
20
- static parse(str: string): Digraph {
21
- const lines = str.split('\n');
22
- const graph = new Digraph();
23
-
24
- let index = 0;
25
- for (const line of lines) {
26
- const trimmedLine = line.trim();
27
- if (trimmedLine.startsWith('digraph ')) {
28
- if (index !== 0) {
29
- this.throwInvalidGraph();
30
- }
31
- } else if (trimmedLine === '}') {
32
- if (index !== lines.length - 1) {
33
- this.throwInvalidGraph();
34
- }
35
- } else if (trimmedLine.startsWith('node ')) {
36
- // no-op
37
- } else if (trimmedLine.startsWith('"')) {
38
- const edgeIndex = trimmedLine.indexOf('->');
39
- if (edgeIndex >= 0) {
40
- const fromEdge = unquote(trimmedLine.slice(0, edgeIndex).trim());
41
- const toEdge = unquote(trimmedLine.slice(edgeIndex + 2).trim());
42
- graph.addEdge(fromEdge, toEdge);
43
- } else {
44
- graph.getOrCreateNode(unquote(trimmedLine))
45
- }
46
- } else {
47
- this.throwInvalidGraph();
48
- }
49
-
50
- index++;
51
- }
52
-
53
- return graph;
54
- }
55
-
56
- private static throwInvalidGraph(): never {
57
- throw new Error('Could not parse digraph');
58
- }
59
-
60
- getNode(name: string): DigraphNode | undefined {
61
- return this.nodeByName.get(name);
62
- }
63
-
64
- getOrCreateNode(name: string): DigraphNode {
65
- let node = this.nodeByName.get(name);
66
- if (!node) {
67
- node = { name, edges: [] };
68
- this.nodeByName.set(name, node);
69
- this._allNodes.push(node);
70
- }
71
-
72
- return node;
73
- }
74
-
75
- addEdge(from: string, to: string): void {
76
- const fromNode = this.getOrCreateNode(from);
77
- const toNode = this.getOrCreateNode(to);
78
-
79
- fromNode.edges.push(toNode);
80
- }
81
- }
@@ -1,43 +0,0 @@
1
- // We use dynamic imports here because ora uses
2
- // the ES6 import syntax, which cannot be fixed
3
- // with require() style imports on older node js versions.
4
-
5
- // eslint-disable-next-line @typescript-eslint/consistent-type-imports, @typescript-eslint/no-implied-eval
6
- const ora = new Function("return import('ora')") as () => Promise<typeof import('ora')>;
7
-
8
- export class LoadingIndicator<T> {
9
- private text = '';
10
- private successText: string | undefined;
11
- private failureText: string | undefined;
12
-
13
- constructor(private readonly runnable: () => PromiseLike<T>) {}
14
-
15
- static fromTask<T>(task: PromiseLike<T>): LoadingIndicator<T> {
16
- return new LoadingIndicator<T>(() => task);
17
- }
18
-
19
- setText(text: string): LoadingIndicator<T> {
20
- this.text = text;
21
- return this;
22
- }
23
-
24
- setSuccessText(successText: string): LoadingIndicator<T> {
25
- this.successText = successText;
26
- return this;
27
- }
28
-
29
- setFailureText(failureText: string): LoadingIndicator<T> {
30
- this.failureText = failureText;
31
- return this;
32
- }
33
-
34
- show(): Promise<T> {
35
- return ora().then(ora => {
36
- return ora.oraPromise(this.runnable(), {
37
- text: this.text,
38
- successText: this.successText,
39
- failText: this.failureText,
40
- });
41
- });
42
- }
43
- }