@snap/valdi 1.0.1

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 (143) hide show
  1. package/.bazelignore +2 -0
  2. package/.bootstrap/apps/cli_application/AGENTS.md.template +215 -0
  3. package/.bootstrap/apps/cli_application/BUILD.bazel.template +7 -0
  4. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +11 -0
  5. package/.bootstrap/apps/cli_application/modules/{{MODULE_NAME}}/src/index.ts +1 -0
  6. package/.bootstrap/apps/ui_application/.eslint.rc +27 -0
  7. package/.bootstrap/apps/ui_application/AGENTS.md.template +202 -0
  8. package/.bootstrap/apps/ui_application/BUILD.bazel.template +19 -0
  9. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/BUILD.bazel.template +21 -0
  10. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/res/valdi@3x.png +0 -0
  11. package/.bootstrap/apps/ui_application/modules/{{MODULE_NAME}}/src/App.tsx +133 -0
  12. package/.bootstrap/apps/ui_application/package.json +24 -0
  13. package/.bootstrap/modules/cpp_bridge_module/BUILD.bazel.template +21 -0
  14. package/.bootstrap/modules/cpp_bridge_module/cpp/CalculatorModuleFactory.cpp.template +29 -0
  15. package/.bootstrap/modules/cpp_bridge_module/src/Calculator.d.ts +1 -0
  16. package/.bootstrap/modules/ios_android_bridge_module/BUILD.bazel.template +39 -0
  17. package/.bootstrap/modules/ios_android_bridge_module/android/CalculatorModuleFactory.kt.template +18 -0
  18. package/.bootstrap/modules/ios_android_bridge_module/ios/SCCCalculatorModuleFactory.m.template +31 -0
  19. package/.bootstrap/modules/ios_android_bridge_module/src/Calculator.d.ts +4 -0
  20. package/.bootstrap/modules/ios_android_view_module/BUILD.bazel.template +41 -0
  21. package/.bootstrap/modules/ios_android_view_module/android/CircleView.kt.template +42 -0
  22. package/.bootstrap/modules/ios_android_view_module/android/CircleViewAttributesBinder.kt.template +60 -0
  23. package/.bootstrap/modules/ios_android_view_module/ios/SCCCircleView.h +6 -0
  24. package/.bootstrap/modules/ios_android_view_module/ios/SCCCircleView.m +82 -0
  25. package/.bootstrap/modules/ios_android_view_module/src/Circle.tsx.template +15 -0
  26. package/.bootstrap/modules/ui_component/BUILD.bazel.template +34 -0
  27. package/.bootstrap/modules/ui_component/src/NewModuleComponent.tsx +45 -0
  28. package/.config/copyconfig.json +10 -0
  29. package/.editorconfig +21 -0
  30. package/.eslintignore +1 -0
  31. package/.eslintrc.js +72 -0
  32. package/.metadata/.bazelrc.template +91 -0
  33. package/.metadata/.bazelversion.template +1 -0
  34. package/.metadata/.eslintrc.js.template +27 -0
  35. package/.metadata/.gitignore.template +4 -0
  36. package/.metadata/.prettierrc.json.template +7 -0
  37. package/.metadata/.watchmanconfig.template +8 -0
  38. package/.metadata/README.md.template +31 -0
  39. package/.metadata/WORKSPACE.template +57 -0
  40. package/.metadata/config.yaml.template +1 -0
  41. package/.metadata/package.json.template +23 -0
  42. package/.prettierignore +2 -0
  43. package/.prettierrc.json +7 -0
  44. package/README.md +123 -0
  45. package/dist/commands/bootstrap.js +233 -0
  46. package/dist/commands/build.js +67 -0
  47. package/dist/commands/devSetup.js +18 -0
  48. package/dist/commands/doctor.js +892 -0
  49. package/dist/commands/export.js +84 -0
  50. package/dist/commands/hotreload.js +89 -0
  51. package/dist/commands/install.js +71 -0
  52. package/dist/commands/lint.js +18 -0
  53. package/dist/commands/lint_commands/lintCheck.js +31 -0
  54. package/dist/commands/lint_commands/lintFormat.js +31 -0
  55. package/dist/commands/log.js +84 -0
  56. package/dist/commands/newModule.js +208 -0
  57. package/dist/commands/package.js +66 -0
  58. package/dist/commands/projectsync.js +316 -0
  59. package/dist/commands/test.js +54 -0
  60. package/dist/core/constants.js +76 -0
  61. package/dist/core/errors.js +12 -0
  62. package/dist/index.js +22 -0
  63. package/dist/setup/DevSetupHelper.js +146 -0
  64. package/dist/setup/linuxSetup.js +31 -0
  65. package/dist/setup/macOSSetup.js +35 -0
  66. package/dist/setup/setupEntryPoint.js +56 -0
  67. package/dist/setup/versions.js +8 -0
  68. package/dist/utils/ArgumentsResolver.js +23 -0
  69. package/dist/utils/BazelClient.js +219 -0
  70. package/dist/utils/Digraph.js +71 -0
  71. package/dist/utils/LoadingIndicator.js +38 -0
  72. package/dist/utils/applicationUtils.js +201 -0
  73. package/dist/utils/buildInfo.js +60 -0
  74. package/dist/utils/byString.js +6 -0
  75. package/dist/utils/cliUtils.js +93 -0
  76. package/dist/utils/copyBootstrapFiles.js +26 -0
  77. package/dist/utils/deviceUtils.js +72 -0
  78. package/dist/utils/errorUtils.js +55 -0
  79. package/dist/utils/fileUtils.js +204 -0
  80. package/dist/utils/githubUtils.js +8 -0
  81. package/dist/utils/jsonUtils.js +28 -0
  82. package/dist/utils/lintUtils.js +149 -0
  83. package/dist/utils/logUtils.js +8 -0
  84. package/dist/utils/pathUtils.js +12 -0
  85. package/dist/utils/stringUtils.js +17 -0
  86. package/dist/utils/stringUtils.spec.js +18 -0
  87. package/dist/utils/tempDir.js +26 -0
  88. package/dist/utils/zipUtils.js +16 -0
  89. package/package.json +51 -0
  90. package/prettier.config.js +4 -0
  91. package/spec/support/jasmine.json +6 -0
  92. package/src/commands/bootstrap.ts +317 -0
  93. package/src/commands/build.ts +89 -0
  94. package/src/commands/devSetup.ts +17 -0
  95. package/src/commands/doctor.ts +1422 -0
  96. package/src/commands/export.ts +131 -0
  97. package/src/commands/hotreload.ts +108 -0
  98. package/src/commands/install.ts +93 -0
  99. package/src/commands/lint.ts +15 -0
  100. package/src/commands/lint_commands/lintCheck.ts +53 -0
  101. package/src/commands/lint_commands/lintFormat.ts +49 -0
  102. package/src/commands/log.ts +108 -0
  103. package/src/commands/newModule.ts +287 -0
  104. package/src/commands/package.ts +102 -0
  105. package/src/commands/projectsync.ts +488 -0
  106. package/src/commands/test.ts +68 -0
  107. package/src/core/constants.ts +95 -0
  108. package/src/core/errors.ts +10 -0
  109. package/src/index.ts +22 -0
  110. package/src/setup/DevSetupHelper.ts +188 -0
  111. package/src/setup/linuxSetup.ts +38 -0
  112. package/src/setup/macOSSetup.ts +42 -0
  113. package/src/setup/setupEntryPoint.ts +64 -0
  114. package/src/setup/versions.ts +8 -0
  115. package/src/utils/ArgumentsResolver.ts +23 -0
  116. package/src/utils/BazelClient.ts +285 -0
  117. package/src/utils/Digraph.ts +81 -0
  118. package/src/utils/LoadingIndicator.ts +43 -0
  119. package/src/utils/applicationUtils.ts +276 -0
  120. package/src/utils/buildInfo.ts +99 -0
  121. package/src/utils/byString.ts +3 -0
  122. package/src/utils/cliUtils.ts +112 -0
  123. package/src/utils/copyBootstrapFiles.ts +30 -0
  124. package/src/utils/deviceUtils.ts +76 -0
  125. package/src/utils/errorUtils.ts +63 -0
  126. package/src/utils/fileUtils.ts +257 -0
  127. package/src/utils/githubUtils.ts +6 -0
  128. package/src/utils/jsonUtils.ts +30 -0
  129. package/src/utils/lintUtils.ts +190 -0
  130. package/src/utils/logUtils.ts +9 -0
  131. package/src/utils/pathUtils.ts +12 -0
  132. package/src/utils/stringUtils.spec.ts +19 -0
  133. package/src/utils/stringUtils.ts +15 -0
  134. package/src/utils/tempDir.ts +24 -0
  135. package/src/utils/zipUtils.ts +14 -0
  136. package/test/ValdiSmokeTest.ts +278 -0
  137. package/test/helpers/AsyncHelpers.ts +113 -0
  138. package/test/helpers/CommandHelpers.ts +37 -0
  139. package/test/helpers/ProjectHelpers.ts +153 -0
  140. package/test/helpers/StreamHelpers.ts +37 -0
  141. package/test/helpers/TypeScriptClient.ts +217 -0
  142. package/tsconfig.dist.json +8 -0
  143. package/tsconfig.json +42 -0
@@ -0,0 +1,188 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { ANSI_COLORS } from '../core/constants';
4
+ import { LoadingIndicator } from '../utils/LoadingIndicator';
5
+ import { spawnCliCommand } from '../utils/cliUtils';
6
+ import { wrapInColor } from '../utils/logUtils';
7
+ import { withTempDir } from '../utils/tempDir';
8
+ import { decompressTo } from '../utils/zipUtils';
9
+ import { ANDROID_BUILD_TOOLS_VERSION, ANDROID_NDK_VERSION, ANDROID_PLATFORM_VERSION } from './versions';
10
+
11
+ export const HOME_DIR = process.env['HOME'] ?? '';
12
+ const ANDROID_HOME_DIR_SUFFIX = '.valdi/android_home';
13
+ const ANDROID_HOME_TARET_DIR = path.join(HOME_DIR, ANDROID_HOME_DIR_SUFFIX);
14
+
15
+ export interface EnvVariable {
16
+ name: string;
17
+ value: string;
18
+ }
19
+
20
+ export class DevSetupHelper {
21
+ async download(url: string): Promise<ArrayBuffer> {
22
+ return new LoadingIndicator(async () => {
23
+ const response = await fetch(url);
24
+
25
+ return response.arrayBuffer();
26
+ })
27
+ .setText(`${wrapInColor('Downloading', ANSI_COLORS.YELLOW_COLOR)} ${url}...`)
28
+ .show();
29
+ }
30
+
31
+ async downloadToPath(url: string, dest: string): Promise<void> {
32
+ const body = await this.download(url);
33
+
34
+ const dir = path.dirname(dest);
35
+ if (!fs.existsSync(dir)) {
36
+ fs.mkdirSync(dir, { recursive: true });
37
+ }
38
+
39
+ await fs.promises.writeFile(dest, new Uint8Array(body));
40
+ }
41
+
42
+ async runShell(
43
+ guide: string,
44
+ commands: string[],
45
+ additionalEnvVariables: { [key: string]: string } = {},
46
+ ): Promise<string> {
47
+ let command = '';
48
+ for (const key in additionalEnvVariables) {
49
+ command += `export ${key}="${additionalEnvVariables[key] as string}"\n`;
50
+ }
51
+ command += commands.join(' && ');
52
+ console.log(`${wrapInColor(guide, ANSI_COLORS.YELLOW_COLOR)}...`);
53
+ for (const command of commands) {
54
+ console.log(`- ${command}`);
55
+ }
56
+
57
+ const result = await spawnCliCommand(command, undefined, 'inherit', false, true);
58
+ return result.stdout;
59
+ }
60
+
61
+ async writeEnvVariablesToRcFile(envVariables: readonly EnvVariable[]): Promise<void> {
62
+ const expectedEnvVariable = envVariables.map(e => `export ${e.name}=${e.value}`);
63
+ const rcFile = this.getRcFile();
64
+ if (!rcFile) {
65
+ console.log();
66
+ console.log(
67
+ `${wrapInColor(`Unrecognized shell ${process.env['SHELL'] ?? ''}. Please add the following env variables to your shell configuration file manually:`, ANSI_COLORS.RED_COLOR)}`,
68
+ );
69
+ for (const l of expectedEnvVariable) {
70
+ console.log(l);
71
+ }
72
+ console.log();
73
+ return;
74
+ }
75
+
76
+ return new LoadingIndicator(async () => {
77
+ let originalRcLines: readonly string[] = [];
78
+ let rcLines: string[] = [];
79
+ if (fs.existsSync(rcFile)) {
80
+ const fileBody = await fs.promises.readFile(rcFile, 'utf8');
81
+ originalRcLines = fileBody.split('\n');
82
+ rcLines = [...originalRcLines];
83
+ }
84
+
85
+ const valdiConfHeader = `# Valdi configuration end`;
86
+ let insertionIndex = rcLines.indexOf(valdiConfHeader);
87
+
88
+ if (insertionIndex < 0) {
89
+ rcLines.push(`# Valdi configuration begin`, valdiConfHeader);
90
+ insertionIndex = rcLines.length - 1;
91
+ }
92
+
93
+ for (const envVariable of expectedEnvVariable) {
94
+ if (!rcLines.includes(envVariable)) {
95
+ rcLines.splice(insertionIndex++, 0, envVariable);
96
+ }
97
+ }
98
+
99
+ if (rcLines.length !== originalRcLines.length) {
100
+ const content = rcLines.join('\n');
101
+ await fs.promises.writeFile(rcFile, content, 'utf8');
102
+ }
103
+ })
104
+ .setText(
105
+ wrapInColor(
106
+ `Updating ${rcFile} to include ${envVariables.map(e => e.name).join(', ')}...`,
107
+ ANSI_COLORS.YELLOW_COLOR,
108
+ ),
109
+ )
110
+ .show();
111
+ }
112
+
113
+ onComplete(): void {
114
+ let suffix = '';
115
+ const rcFile = this.getRcFile();
116
+
117
+ if (rcFile) {
118
+ suffix += ` Please run ${wrapInColor(`source ${rcFile}`, ANSI_COLORS.YELLOW_COLOR)} or restart your terminal.`;
119
+ }
120
+ console.log(`${wrapInColor('Dev setup completed!', ANSI_COLORS.GREEN_COLOR)}.${suffix}`);
121
+ }
122
+
123
+ async setupAndroidSDK(commandLineToolsURL: string, javaHomeOverride?: string | undefined): Promise<void> {
124
+ console.log(wrapInColor('Setting up Android SDK...', ANSI_COLORS.YELLOW_COLOR));
125
+ if (!process.env['ANDROID_HOME']) {
126
+ await withTempDir(async tempDir => {
127
+ const filename = path.join(tempDir, path.basename(commandLineToolsURL));
128
+ await this.downloadToPath(commandLineToolsURL, filename);
129
+ const targetDir = path.join(ANDROID_HOME_TARET_DIR, 'cmdline-tools');
130
+ await decompressTo(filename, targetDir);
131
+
132
+ const target = path.join(targetDir, 'latest');
133
+ if (fs.existsSync(target)) {
134
+ await fs.promises.rm(target, { recursive: true, force: true });
135
+ }
136
+ fs.renameSync(path.join(targetDir, 'cmdline-tools'), target);
137
+ });
138
+ process.env['ANDROID_HOME'] = path.join(HOME_DIR, ANDROID_HOME_DIR_SUFFIX);
139
+ await this.writeEnvVariablesToRcFile([{ name: 'ANDROID_HOME', value: `"$HOME/${ANDROID_HOME_DIR_SUFFIX}"` }]);
140
+ }
141
+
142
+ const androidHome = process.env['ANDROID_HOME'] ?? '';
143
+ const sdkManagerBin = path.join(androidHome, 'cmdline-tools/latest/bin/sdkmanager');
144
+
145
+ const sdkManagerEnvVariables: { [key: string]: string } = {};
146
+ if (javaHomeOverride) {
147
+ sdkManagerEnvVariables['JAVA_HOME'] = javaHomeOverride;
148
+ }
149
+
150
+ await this.runShell(
151
+ 'Installing Android platform',
152
+ [`${sdkManagerBin} --install 'platforms;${ANDROID_PLATFORM_VERSION}'`],
153
+ sdkManagerEnvVariables,
154
+ );
155
+ await this.runShell(
156
+ 'Installing Android NDK',
157
+ [`${sdkManagerBin} --install 'ndk;${ANDROID_NDK_VERSION}'`],
158
+ sdkManagerEnvVariables,
159
+ );
160
+ await this.runShell(
161
+ 'Installing Android build-tools',
162
+ [`${sdkManagerBin} --install 'build-tools;${ANDROID_BUILD_TOOLS_VERSION}'`],
163
+ sdkManagerEnvVariables,
164
+ );
165
+
166
+ const ndkBundle = path.join(androidHome, 'ndk-bundle');
167
+ if (!fs.existsSync(ndkBundle)) {
168
+ fs.symlinkSync(`ndk/${ANDROID_NDK_VERSION}`, ndkBundle);
169
+ }
170
+ await this.writeEnvVariablesToRcFile([{ name: 'ANDROID_NDK_HOME', value: `"$ANDROID_HOME/ndk-bundle"` }]);
171
+ }
172
+
173
+ private getRcFile(): string | undefined {
174
+ const homeDir = process.env['HOME'] ?? '';
175
+ const shell = process.env['SHELL'] ?? '';
176
+ if (shell.endsWith('/zsh')) {
177
+ return path.join(homeDir, '.zshrc');
178
+ } else if (shell.endsWith('/bash')) {
179
+ return path.join(homeDir, '.bashrc');
180
+ } else if (shell.endsWith('/ksh')) {
181
+ return path.join(homeDir, '.kshrc');
182
+ } else if (shell.endsWith('/tcsh')) {
183
+ return path.join(homeDir, '.tcshrc');
184
+ } else {
185
+ return undefined;
186
+ }
187
+ }
188
+ }
@@ -0,0 +1,38 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { checkCommandExists } from '../utils/cliUtils';
4
+ import { DevSetupHelper, HOME_DIR } from './DevSetupHelper';
5
+ import { ANDROID_LINUX_COMMANDLINE_TOOLS } from './versions';
6
+
7
+ const BAZELISK_URL = 'https://github.com/bazelbuild/bazelisk/releases/download/v1.26.0/bazelisk-linux-amd64';
8
+
9
+ export async function linuxSetup(): Promise<void> {
10
+ const devSetup = new DevSetupHelper();
11
+
12
+ await devSetup.runShell('Installing dependencies from apt', [
13
+ `sudo apt-get install zlib1g-dev git-lfs watchman libfontconfig-dev adb`,
14
+ ]);
15
+
16
+ await devSetup.runShell('Installing libtinfo5', [
17
+ `wget http://security.ubuntu.com/ubuntu/pool/universe/n/ncurses/libtinfo5_6.3-2ubuntu0.1_amd64.deb`,
18
+ `sudo apt install ./libtinfo5_6.3-2ubuntu0.1_amd64.deb`,
19
+ ]);
20
+
21
+ if (!checkCommandExists('java')) {
22
+ await devSetup.runShell('Installing Java Runtime Environment', ['sudo apt install default-jre']);
23
+ }
24
+
25
+ const bazeliskPathSuffix = '.valdi/bin/bazelisk';
26
+ const bazeliskTargetPath = path.join(HOME_DIR, bazeliskPathSuffix);
27
+ await devSetup.downloadToPath(BAZELISK_URL, bazeliskTargetPath);
28
+
29
+ // Add executable permission to the downloaded binary
30
+ const stats = fs.statSync(bazeliskTargetPath);
31
+ fs.chmodSync(bazeliskTargetPath, stats.mode | 0o111);
32
+
33
+ await devSetup.writeEnvVariablesToRcFile([{ name: 'PATH', value: `"$HOME/.valdi/bin:$PATH"` }]);
34
+
35
+ await devSetup.setupAndroidSDK(ANDROID_LINUX_COMMANDLINE_TOOLS);
36
+
37
+ devSetup.onComplete();
38
+ }
@@ -0,0 +1,42 @@
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
+ if (!checkCommandExists('xcode-select')) {
11
+ throw new CliError(
12
+ 'Xcode is not installed. Please install Xcode from the App Store as setup requires Xcode command line tools',
13
+ );
14
+ }
15
+
16
+ if (!checkCommandExists('brew')) {
17
+ await devSetup.runShell('Homebrew not found. Installing', [
18
+ '/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"',
19
+ ]);
20
+ }
21
+
22
+ await devSetup.runShell('Installing dependencies from Homebrew', [
23
+ 'brew install npm bazelisk openjdk@11 temurin git-lfs watchman ios-webkit-debug-proxy',
24
+ ]);
25
+
26
+ if (!fs.existsSync('/Library/Java/JavaVirtualMachines/openjdk-11.jdk')) {
27
+ await devSetup.runShell('Setting up JDK', [
28
+ 'sudo ln -sfn /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-11.jdk',
29
+ ]);
30
+ }
31
+
32
+ await devSetup.writeEnvVariablesToRcFile([
33
+ { name: 'PATH', value: '"/opt/homebrew/opt/openjdk@11/bin:$PATH"' },
34
+ { name: 'JAVA_HOME', value: '`/usr/libexec/java_home -v 11`' },
35
+ ]);
36
+
37
+ const javaHome = await runCliCommand('/usr/libexec/java_home');
38
+
39
+ await devSetup.setupAndroidSDK(ANDROID_MACOS_COMMANDLINE_TOOLS, javaHome.stdout.trim());
40
+
41
+ devSetup.onComplete();
42
+ }
@@ -0,0 +1,64 @@
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
+ }
@@ -0,0 +1,8 @@
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';
@@ -0,0 +1,23 @@
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
+ }
@@ -0,0 +1,285 @@
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
+ }