@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,488 @@
1
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
2
+ /* eslint-disable @typescript-eslint/no-explicit-any */
3
+ /* eslint-disable @typescript-eslint/no-unsafe-assignment */
4
+ /* eslint-disable @typescript-eslint/no-unsafe-member-access */
5
+ import fsSync from 'fs';
6
+ import fs from 'fs/promises';
7
+ import type { JSONPath } from 'jsonc-parser';
8
+ import path from 'path';
9
+ import type { Argv } from 'yargs';
10
+ import { CliError } from '../core/errors';
11
+ import type { ArgumentsResolver } from '../utils/ArgumentsResolver';
12
+ import { BazelClient, BazelLabel } from '../utils/BazelClient';
13
+ import { byString } from '../utils/byString';
14
+ import { logReproduceThisCommandIfNeeded, makeCommandHandler } from '../utils/errorUtils';
15
+ import { JSONCFile } from '../utils/jsonUtils';
16
+ import { relativePathTo } from '../utils/pathUtils';
17
+
18
+ const VALDI_BASE_TARGET = BazelLabel.fromString('@valdi//modules:valdi_base');
19
+ const VALDI_CORE_TARGET = BazelLabel.fromString('@valdi//src/valdi_modules/valdi_core:valdi_core');
20
+
21
+ interface VSCodeLaunchConfiguration {
22
+ name: string;
23
+ type: string;
24
+ request: string;
25
+ websocketAddress: string;
26
+ sourceMapPathOverrides: { [key: string]: string };
27
+ sourceMaps: boolean;
28
+ restart: boolean;
29
+ resolveSourceMapLocations: unknown[];
30
+ }
31
+
32
+ interface VSCodeLaunchInfo {
33
+ version?: string;
34
+ configurations?: VSCodeLaunchConfiguration[];
35
+ }
36
+
37
+ const VSCODE_VALDI_LAUNCH_CONFIGURATION: VSCodeLaunchConfiguration = {
38
+ name: 'Valdi attach',
39
+ type: 'node',
40
+ request: 'attach',
41
+ websocketAddress: 'ws://localhost:13595',
42
+ sourceMapPathOverrides: {},
43
+ sourceMaps: true,
44
+ restart: false,
45
+ //This empty value is important so that vscode-js-debug just uses the inline source maps
46
+ resolveSourceMapLocations: [],
47
+ };
48
+
49
+ const DEFAULT_VSCODE_LAUNCH_JSON: VSCodeLaunchInfo = {
50
+ version: '0.2.0',
51
+ configurations: [VSCODE_VALDI_LAUNCH_CONFIGURATION],
52
+ };
53
+
54
+ interface CommandParameters {
55
+ target: string[] | undefined;
56
+ vscode_launch_path: string | undefined;
57
+ }
58
+
59
+ interface TargetDescription {
60
+ label: BazelLabel;
61
+ paths: readonly string[];
62
+ }
63
+
64
+ interface TsConfigMatchedTarget {
65
+ target: TargetDescription;
66
+ dependencies: TargetDescription[];
67
+ }
68
+
69
+ interface TsConfigDir {
70
+ dir: string;
71
+ matchedTargets: TsConfigMatchedTarget[];
72
+ }
73
+
74
+ interface BazelWorkspaceInfo {
75
+ workspaceName: string;
76
+ workspaceRoot: string;
77
+ executionRoot: string;
78
+ }
79
+
80
+ interface ProjectSyncOutput {
81
+ target: BazelLabel;
82
+ dependencies: BazelLabel[];
83
+ tsGeneratedDir: string | undefined;
84
+ }
85
+
86
+ interface ProjectSyncOutputJSON {
87
+ target: string;
88
+ dependencies: string[];
89
+ ts_generated_dir: string | undefined;
90
+ }
91
+
92
+ async function parseProjectSyncJSON(jsonFilePath: string): Promise<ProjectSyncOutput> {
93
+ const jsonFilePathContent = await fs.readFile(jsonFilePath);
94
+ const json = JSON.parse(jsonFilePathContent.toString('utf8')) as ProjectSyncOutputJSON;
95
+ let tsGeneratedDir: string | undefined;
96
+
97
+ if (json.ts_generated_dir) {
98
+ const dir = path.dirname(jsonFilePath);
99
+
100
+ tsGeneratedDir = path.resolve(dir, json.ts_generated_dir);
101
+ }
102
+
103
+ return {
104
+ target: BazelLabel.fromString(json.target),
105
+ dependencies: json.dependencies.map(d => BazelLabel.fromString(d)),
106
+ tsGeneratedDir,
107
+ };
108
+ }
109
+
110
+ function isExternalLabel(workspaceInfo: BazelWorkspaceInfo, label: BazelLabel): boolean {
111
+ return !!label.repo && label.repo !== workspaceInfo.workspaceName;
112
+ }
113
+
114
+ function getSymlinkedBazelExecutionRoot(workspaceInfo: BazelWorkspaceInfo): string {
115
+ return path.join(workspaceInfo.workspaceRoot, `bazel-${workspaceInfo.workspaceName}`);
116
+ }
117
+
118
+ function bazelLabelToAbsolutePath(workspaceInfo: BazelWorkspaceInfo, label: BazelLabel): string {
119
+ const targetPath = label.target.slice(2);
120
+ if (isExternalLabel(workspaceInfo, label)) {
121
+ return path.join(getSymlinkedBazelExecutionRoot(workspaceInfo), 'external', label.repo!, targetPath);
122
+ } else {
123
+ return path.join(workspaceInfo.workspaceRoot, targetPath);
124
+ }
125
+ }
126
+
127
+ async function buildProjectSyncs(bazel: BazelClient, workspaceRoot: string, projectSyncTargets: readonly string[]) {
128
+ await bazel.buildTargets(projectSyncTargets);
129
+ const buildOutputs = await bazel.queryBuildOutputs(projectSyncTargets);
130
+ const filteredBuildOutputs = buildOutputs.filter(c => c.endsWith('/projectsync.json')).sort(byString(v => v));
131
+
132
+ return await Promise.all(filteredBuildOutputs.map(b => parseProjectSyncJSON(path.resolve(workspaceRoot, b))));
133
+ }
134
+
135
+ async function syncPathsByLabel(
136
+ client: BazelClient,
137
+ workspaceInfo: BazelWorkspaceInfo,
138
+ pathsByLabel: Map<string, string[]>,
139
+ projectSyncOutputs: readonly ProjectSyncOutput[],
140
+ ) {
141
+ for (const projectSyncOutput of projectSyncOutputs) {
142
+ const paths: string[] = [];
143
+ paths.push(bazelLabelToAbsolutePath(workspaceInfo, projectSyncOutput.target));
144
+
145
+ if (projectSyncOutput.tsGeneratedDir) {
146
+ paths.push(projectSyncOutput.tsGeneratedDir);
147
+ }
148
+
149
+ pathsByLabel.set(projectSyncOutput.target.toString(), paths);
150
+ }
151
+
152
+ // TODO(simon): Refactor projectsync bzl rule so that it recursively resolves
153
+ // all of these without us having to take care of it.
154
+ const missingTargets = new Set<string>();
155
+
156
+ for (const projectSyncOutput of projectSyncOutputs) {
157
+ for (const dependency of projectSyncOutput.dependencies) {
158
+ const target = dependency.toString();
159
+ if (!pathsByLabel.has(target)) {
160
+ missingTargets.add(target);
161
+ }
162
+ }
163
+ }
164
+
165
+ if (missingTargets.size > 0) {
166
+ const targets = [...missingTargets.values()].sort().map(f => `${f}_projectsync`);
167
+ const newProjectSyncOutputs = await buildProjectSyncs(client, workspaceInfo.workspaceRoot, targets);
168
+ await syncPathsByLabel(client, workspaceInfo, pathsByLabel, newProjectSyncOutputs);
169
+ }
170
+ }
171
+
172
+ async function collectTsConfigDirs(
173
+ bazel: BazelClient,
174
+ workspaceInfo: BazelWorkspaceInfo,
175
+ projectSyncOutputs: readonly ProjectSyncOutput[],
176
+ ): Promise<TsConfigDir[]> {
177
+ const pathsByLabel = new Map<string, string[]>();
178
+
179
+ await syncPathsByLabel(bazel, workspaceInfo, pathsByLabel, projectSyncOutputs);
180
+
181
+ const makeTargetDescription = (label: BazelLabel): TargetDescription => {
182
+ const target = label.toString();
183
+ const paths = pathsByLabel.get(target);
184
+
185
+ if (!paths) {
186
+ throw new CliError(`Could not resolve TypeScript import paths for target ${target}`);
187
+ }
188
+ return {
189
+ label,
190
+ paths,
191
+ };
192
+ };
193
+
194
+ const tsConfigDirs = new Map<string, TsConfigDir>();
195
+
196
+ for (const projectSyncOutput of projectSyncOutputs) {
197
+ if (projectSyncOutput.target.repo) {
198
+ // Ignore external repo deps
199
+ continue;
200
+ }
201
+
202
+ const tsConfigDirPath = bazelLabelToAbsolutePath(workspaceInfo, projectSyncOutput.target);
203
+ let tsConfigDir = tsConfigDirs.get(tsConfigDirPath);
204
+ if (!tsConfigDir) {
205
+ tsConfigDir = { dir: tsConfigDirPath, matchedTargets: [] };
206
+ tsConfigDirs.set(tsConfigDirPath, tsConfigDir);
207
+ }
208
+
209
+ const dependencies = projectSyncOutput.dependencies.map(d => makeTargetDescription(d));
210
+
211
+ tsConfigDir.matchedTargets.push({
212
+ target: makeTargetDescription(projectSyncOutput.target),
213
+ dependencies: dependencies,
214
+ });
215
+ }
216
+
217
+ return [...tsConfigDirs.values()].sort(byString(v => v.dir));
218
+ }
219
+
220
+ function removeTsFileExtension(path: string): string {
221
+ if (path.endsWith('.d.ts')) {
222
+ return path.slice(0, -5);
223
+ } else if (path.endsWith('.ts')) {
224
+ return path.slice(0, -3);
225
+ }
226
+ return path;
227
+ }
228
+
229
+ function computeTsCompilerOptions(
230
+ existingTsConfigFile: any,
231
+ tsConfigDir: string,
232
+ matchedTargets: readonly TsConfigMatchedTarget[],
233
+ baseTsFiles: readonly string[],
234
+ ): unknown {
235
+ let compilerOptions: any;
236
+ if (existingTsConfigFile) {
237
+ compilerOptions = { ...existingTsConfigFile };
238
+ } else {
239
+ compilerOptions = {};
240
+ }
241
+
242
+ compilerOptions.paths = {};
243
+ const rootDirs: string[] = [];
244
+ let valdiCoreTarget: TargetDescription | undefined;
245
+ for (const matchedTarget of matchedTargets) {
246
+ const targetRootDirs = matchedTarget.target.paths.map(p => relativePathTo(tsConfigDir, path.dirname(p)));
247
+
248
+ for (const targetRootDir of targetRootDirs) {
249
+ if (!rootDirs.includes(targetRootDir)) {
250
+ rootDirs.push(targetRootDir);
251
+ }
252
+ }
253
+
254
+ const selfName = matchedTarget.target.label.name ?? '';
255
+ const selfInclude = `${selfName}/*`;
256
+
257
+ const selfImportPaths = matchedTarget.target.paths.map(p => `${relativePathTo(tsConfigDir, p)}/*`);
258
+
259
+ compilerOptions.paths[selfInclude] = selfImportPaths;
260
+
261
+ for (const dependency of matchedTarget.dependencies) {
262
+ if (!dependency.label.name || compilerOptions.paths[dependency.label.name]) {
263
+ // Already present
264
+ continue;
265
+ }
266
+
267
+ if (dependency.label.name === 'valdi_core') {
268
+ valdiCoreTarget = dependency;
269
+ }
270
+
271
+ const importPaths = dependency.paths.map(p => `${relativePathTo(tsConfigDir, p)}/*`);
272
+
273
+ const key = `${dependency.label.name}/*`;
274
+ compilerOptions.paths[key] = importPaths;
275
+ }
276
+ }
277
+
278
+ if (valdiCoreTarget) {
279
+ // Add tslib dep
280
+ compilerOptions.paths['tslib'] = valdiCoreTarget.paths.map(p =>
281
+ relativePathTo(tsConfigDir, path.join(p, 'src/tslib')),
282
+ );
283
+ }
284
+
285
+ compilerOptions.types = baseTsFiles.map(p => relativePathTo(tsConfigDir, removeTsFileExtension(p)));
286
+
287
+ compilerOptions.rootDirs = rootDirs;
288
+
289
+ return compilerOptions;
290
+ }
291
+
292
+ function getBaseTsConfigFile(valdiBaseAbsoluteFilePaths: string[]): string | undefined {
293
+ return valdiBaseAbsoluteFilePaths.find(p => path.basename(p) === 'base.tsconfig.json');
294
+ }
295
+
296
+ function updateTsConfigFile(file: JSONCFile<any>, path: JSONPath, value: any): JSONCFile<any> {
297
+ return file.updating(path, value, {
298
+ formattingOptions: {
299
+ insertSpaces: true,
300
+ },
301
+ });
302
+ }
303
+
304
+ async function processTsConfigDir(
305
+ tsConfigDir: TsConfigDir,
306
+ baseTsConfigFilePath: string | undefined,
307
+ baseTsFiles: readonly string[],
308
+ ): Promise<void> {
309
+ const tsConfigPath = path.join(tsConfigDir.dir, 'tsconfig.json');
310
+
311
+ let tsConfigFile: JSONCFile<any>;
312
+ if (fsSync.existsSync(tsConfigPath)) {
313
+ const fileContent = await fs.readFile(tsConfigPath);
314
+ tsConfigFile = JSONCFile.parse(fileContent.toString('utf8'));
315
+ } else {
316
+ tsConfigFile = JSONCFile.fromObject({});
317
+ }
318
+
319
+ const tsCompilerOptions = computeTsCompilerOptions(
320
+ tsConfigFile?.value?.compilerOptions,
321
+ tsConfigDir.dir,
322
+ tsConfigDir.matchedTargets,
323
+ baseTsFiles,
324
+ );
325
+
326
+ if (baseTsConfigFilePath) {
327
+ const resolvedBaseTsConfigFilePath = relativePathTo(tsConfigDir.dir, baseTsConfigFilePath);
328
+ if (tsConfigFile?.value?.extends !== resolvedBaseTsConfigFilePath) {
329
+ tsConfigFile = updateTsConfigFile(tsConfigFile, ['extends'], resolvedBaseTsConfigFilePath);
330
+ }
331
+ }
332
+
333
+ tsConfigFile = updateTsConfigFile(tsConfigFile, ['compilerOptions'], tsCompilerOptions);
334
+
335
+ await fs.writeFile(tsConfigPath, tsConfigFile.toJSONString());
336
+ }
337
+
338
+ function computeSourceMapPathOverrides(
339
+ bazelWorkspaceRoot: string,
340
+ tsConfigDirs: readonly TsConfigDir[],
341
+ ): { [key: string]: string } {
342
+ const output: { [key: string]: string } = {};
343
+
344
+ for (const tsConfigDir of tsConfigDirs) {
345
+ for (const matchedTarget of tsConfigDir.matchedTargets) {
346
+ if (matchedTarget.target.label.name) {
347
+ const key = `/${matchedTarget.target.label.name}/*`;
348
+ const relativePath = relativePathTo(bazelWorkspaceRoot, tsConfigDir.dir);
349
+ const expected = `\${workspaceRoot}/${relativePath}/*`;
350
+
351
+ const existing = output[key];
352
+ if (existing && existing !== expected) {
353
+ console.error(`Conflicting target name ${matchedTarget.target.label.name}: '${expected}' vs ${existing}`);
354
+ } else {
355
+ output[key] = expected;
356
+ }
357
+ }
358
+ }
359
+ }
360
+
361
+ return output;
362
+ }
363
+
364
+ async function processLaunchJSONFile(
365
+ launchJsonFilePath: string | undefined,
366
+ bazel: BazelClient,
367
+ tsConfigDirs: readonly TsConfigDir[],
368
+ ): Promise<void> {
369
+ const workspaceRoot = await bazel.getWorkspaceRoot();
370
+ if (!launchJsonFilePath) {
371
+ launchJsonFilePath = path.join(workspaceRoot, '.vscode/launch.json');
372
+ }
373
+
374
+ let launchJsonFile: JSONCFile<VSCodeLaunchInfo>;
375
+ if (fsSync.existsSync(launchJsonFilePath)) {
376
+ const launchJsonFileContent = await fs.readFile(launchJsonFilePath, 'utf8');
377
+ launchJsonFile = JSONCFile.parse(launchJsonFileContent);
378
+ } else {
379
+ launchJsonFile = JSONCFile.fromObject(DEFAULT_VSCODE_LAUNCH_JSON);
380
+ }
381
+
382
+ const valdiLaunchConfigurationIndex =
383
+ launchJsonFile.value.configurations?.findIndex(c => c.name === VSCODE_VALDI_LAUNCH_CONFIGURATION.name) ?? -1;
384
+ let valdiLaunchConfiguration =
385
+ valdiLaunchConfigurationIndex >= 0
386
+ ? launchJsonFile.value.configurations![valdiLaunchConfigurationIndex]!
387
+ : VSCODE_VALDI_LAUNCH_CONFIGURATION;
388
+ valdiLaunchConfiguration = { ...valdiLaunchConfiguration };
389
+ valdiLaunchConfiguration.sourceMapPathOverrides = computeSourceMapPathOverrides(workspaceRoot, tsConfigDirs);
390
+
391
+ if (valdiLaunchConfigurationIndex >= 0) {
392
+ launchJsonFile = launchJsonFile.updating(
393
+ ['configurations', valdiLaunchConfigurationIndex],
394
+ valdiLaunchConfiguration,
395
+ {
396
+ formattingOptions: { insertSpaces: true },
397
+ },
398
+ );
399
+ } else if (launchJsonFile.value.configurations) {
400
+ launchJsonFile = launchJsonFile.updating(
401
+ ['configurations', launchJsonFile.value.configurations.length],
402
+ valdiLaunchConfiguration,
403
+ {
404
+ formattingOptions: { insertSpaces: true },
405
+ isArrayInsertion: true,
406
+ },
407
+ );
408
+ } else {
409
+ launchJsonFile = launchJsonFile.updating(['configurations'], [valdiLaunchConfiguration], {
410
+ formattingOptions: { insertSpaces: true },
411
+ });
412
+ }
413
+
414
+ const launchJsonFileDir = path.dirname(launchJsonFilePath);
415
+ if (!fsSync.existsSync(launchJsonFileDir)) {
416
+ await fs.mkdir(launchJsonFileDir, { recursive: true });
417
+ }
418
+ await fs.writeFile(launchJsonFilePath, launchJsonFile.toJSONString());
419
+ }
420
+
421
+ export async function getAllProjectSyncTargets(bazel: BazelClient): Promise<string[]> {
422
+ console.log('Searching for Valdi targets in current workspace...');
423
+ return await bazel.query(`kind('valdi_projectsync', //...)`);
424
+ }
425
+
426
+ export async function runProjectSync(
427
+ bazel: BazelClient,
428
+ inputTargets: string[],
429
+ vscodeLaunchPath: string | undefined,
430
+ generateLaunchJSONFile: boolean,
431
+ ): Promise<void> {
432
+ console.log('Resolving dependencies of resolved Valdi targets...');
433
+ const workspaceRoot = await bazel.getWorkspaceRoot();
434
+ const executionRoot = await bazel.getExecutionRoot();
435
+
436
+ const allProjectSyncOutputs = await buildProjectSyncs(bazel, workspaceRoot, inputTargets);
437
+
438
+ console.log('Generating tsconfig.json files...');
439
+
440
+ const workspaceName = path.basename(executionRoot);
441
+ const workspaceInfo: BazelWorkspaceInfo = { workspaceName, workspaceRoot, executionRoot };
442
+
443
+ const valdiBaseRelativeFilePaths = await bazel.queryBuildOutputs([VALDI_BASE_TARGET.toString()]);
444
+ const valdiBaseAbsoluteFilePaths = valdiBaseRelativeFilePaths.map(v => {
445
+ if (isExternalLabel(workspaceInfo, VALDI_BASE_TARGET)) {
446
+ return path.resolve(getSymlinkedBazelExecutionRoot(workspaceInfo), v);
447
+ } else {
448
+ return path.resolve(workspaceRoot, v);
449
+ }
450
+ });
451
+ const baseTsConfigFilePath = getBaseTsConfigFile(valdiBaseAbsoluteFilePaths);
452
+ const baseTsFiles = valdiBaseAbsoluteFilePaths.filter(v => v.endsWith('.ts'));
453
+
454
+ const tsConfigDirs = await collectTsConfigDirs(bazel, workspaceInfo, allProjectSyncOutputs);
455
+
456
+ await Promise.all(tsConfigDirs.map(v => processTsConfigDir(v, baseTsConfigFilePath, baseTsFiles)));
457
+
458
+ if (generateLaunchJSONFile) {
459
+ console.log('Generating VSCode launch.json file...');
460
+ await processLaunchJSONFile(vscodeLaunchPath, bazel, tsConfigDirs);
461
+ }
462
+ }
463
+
464
+ async function projectSync(args: ArgumentsResolver<CommandParameters>): Promise<void> {
465
+ const bazel = new BazelClient();
466
+ const inputTargets = await args.getArgumentOrResolve('target', () => getAllProjectSyncTargets(bazel));
467
+ await runProjectSync(bazel, inputTargets, args.getArgument('vscode_launch_path'), true);
468
+
469
+ logReproduceThisCommandIfNeeded(args);
470
+ }
471
+
472
+ export const command = 'projectsync [--target target]';
473
+ export const describe = 'Synchronize VSCode project for the given targets';
474
+ export const builder = (yargs: Argv<CommandParameters>) => {
475
+ yargs.option('target', {
476
+ describe: 'targets for which to synchronize the VSCode project for',
477
+ type: 'string',
478
+ array: true,
479
+ requiresArg: false,
480
+ });
481
+ yargs.option('vscode_launch_path', {
482
+ describe:
483
+ 'A the path to there launch.json file used by VSCode. Will be inferred as .vscode/launch.json from the Bazel workspace root if not specified',
484
+ type: 'string',
485
+ });
486
+ };
487
+
488
+ export const handler = makeCommandHandler(projectSync);
@@ -0,0 +1,68 @@
1
+ import type { Argv } from 'yargs';
2
+ import { ANSI_COLORS } from '../core/constants';
3
+ import type { ArgumentsResolver } from '../utils/ArgumentsResolver';
4
+ import { BazelClient } from '../utils/BazelClient';
5
+ import { LoadingIndicator } from '../utils/LoadingIndicator';
6
+ import { makeCommandHandler } from '../utils/errorUtils';
7
+ import { wrapInColor } from '../utils/logUtils';
8
+
9
+ interface CommandParameters {
10
+ module: string[] | undefined;
11
+ target: string[] | undefined;
12
+ bazel_args: string | undefined;
13
+ }
14
+
15
+ async function getTestTargetsByModuleNames(client: BazelClient, modules?: string[]): Promise<string[]> {
16
+ return await client.queryTargetsByKindWithFilter('test', modules ?? [], 'pipe');
17
+ }
18
+
19
+ async function valdiTest(argv: ArgumentsResolver<CommandParameters>) {
20
+ const bazelClient = new BazelClient();
21
+
22
+ const targets = await argv.getArgumentOrResolve('target', () => {
23
+ return LoadingIndicator.fromTask(getTestTargetsByModuleNames(bazelClient, argv.getArgument('module') ?? []))
24
+ .setText(wrapInColor('Collecting targets for tests...', ANSI_COLORS.YELLOW_COLOR))
25
+ .setSuccessText(wrapInColor('Finished collecting test targets.', ANSI_COLORS.GREEN_COLOR))
26
+ .setFailureText(wrapInColor('Failed to collect targets.', ANSI_COLORS.RED_COLOR))
27
+ .show();
28
+ });
29
+
30
+ if (targets === undefined || targets.length === 0) {
31
+ console.log('No test targets found.');
32
+ return;
33
+ }
34
+
35
+ console.log('Starting tests for targets:');
36
+ console.log(
37
+ targets
38
+ .map(target => {
39
+ return ` ${wrapInColor(target, ANSI_COLORS.GREEN_COLOR)}`;
40
+ })
41
+ .join('\n'),
42
+ );
43
+
44
+ await bazelClient.testTargets(targets, argv.getArgument('bazel_args'));
45
+ }
46
+
47
+ export const command = 'test [--module module_name] [--target target_name]';
48
+ export const describe =
49
+ 'Runs tests for given module(s) or target(s). Runs all tests if no module or target is specified.';
50
+ export const builder = (yargs: Argv<CommandParameters>) => {
51
+ yargs
52
+ .option('module', {
53
+ describe: 'name of the module to test',
54
+ type: 'array',
55
+ requiresArg: true,
56
+ })
57
+ .option('target', {
58
+ describe: 'Bazel target path to test',
59
+ type: 'array',
60
+ requiresArg: true,
61
+ })
62
+ .option('bazel_args', {
63
+ describe: `Additional arguments to pass to bazel build. Use format ${wrapInColor('--bazel_args="<args>"', ANSI_COLORS.YELLOW_COLOR)}.`,
64
+ type: 'string',
65
+ requiresArg: true,
66
+ });
67
+ };
68
+ export const handler = makeCommandHandler(valdiTest);
@@ -0,0 +1,95 @@
1
+ import path from 'path';
2
+
3
+ export const VALDI_CONFIG_PATHS: string[] = ['~/.valdi/config.yaml', '~/.valdi/config.yml'];
4
+ export const BAZEL_BIN_ENV = 'BAZEL_BIN';
5
+ export const BAZEL_EXECUTABLES: string[] = ['bazel', 'bzl', 'bazelisk'];
6
+
7
+ // Console color ANSI escape sequences
8
+ export enum ANSI_COLORS {
9
+ RESET_COLOR = '\u001B[0m',
10
+ RED_COLOR = '\u001B[31m',
11
+ GREEN_COLOR = '\u001B[32m',
12
+ YELLOW_COLOR = '\u001B[33m',
13
+ BLUE_COLOR = '\u001B[34m',
14
+ GRAY_COLOR = '\u001B[90m',
15
+ }
16
+
17
+ export enum PLATFORM {
18
+ IOS = 'ios',
19
+ ANDROID = 'android',
20
+ MACOS = 'macos',
21
+ CLI = 'cli',
22
+ }
23
+
24
+ export enum Architecture {
25
+ ARM64,
26
+ ARMV7,
27
+ X86_64,
28
+ }
29
+
30
+ export const ALL_ARCHITECTURES: Architecture[] = [Architecture.ARMV7, Architecture.ARM64, Architecture.X86_64];
31
+
32
+ // Relative path starts at .metadata
33
+ export enum TEMPLATE_BASE_PATHS {
34
+ WORKSPACE = 'WORKSPACE.template',
35
+ BAZEL_RC = '.bazelrc.template',
36
+ BAZEL_VERSION = '.bazelversion.template',
37
+ USER_CONFIG = 'config.yaml.template',
38
+ PRETTIER_CONFIG = '.prettierrc.json.template',
39
+ ESLINT_CONFIG = '.eslintrc.js.template',
40
+ ESLINT_PACKAGE_JSON_CONFIG = 'package.json.template',
41
+ README = 'README.md.template',
42
+ WATCHMAN_CONFIG = '.watchmanconfig.template',
43
+ GIT_IGNORE = '.gitignore.template',
44
+ }
45
+
46
+ export const VALID_PLATFORMS: string[] = [PLATFORM.ANDROID, PLATFORM.IOS, PLATFORM.MACOS, PLATFORM.CLI];
47
+
48
+ export interface UserConfig {
49
+ logs_output_dir: string | undefined;
50
+ }
51
+
52
+ // TODO: Replace with Valdi defined bazel rule targets
53
+ export const IOS_BAZEL_APPLICATION_TAG = 'valdi_ios_application';
54
+ export const ANDROID_BAZEL_APPLICATION_TAG = 'valdi_android_application';
55
+ export const MACOS_BAZEL_APPLICATION_TAG = 'valdi_macos_application';
56
+ export const CLI_BAZEL_APPLICATION_TAG = 'valdi_cli_application';
57
+
58
+ export const IOS_EXPORTED_LIBRARY_TAG = 'valdi_ios_exported_library';
59
+ export const ANDROID_EXPORTED_LIBRARY_TAG = 'valdi_android_exported_library';
60
+
61
+ // Paths
62
+ // eslint-disable-next-line unicorn/prefer-module
63
+ export const CLI_ROOT = path.join(__dirname, '../..');
64
+ export const CONFIG_DIR_PATH = path.join(CLI_ROOT, '.config');
65
+ export const META_DIR_PATH = path.join(CLI_ROOT, '.metadata');
66
+ export const BOOTSTRAP_DIR_PATH = path.join(CLI_ROOT, '.bootstrap');
67
+ export const SETUP_SCRIPT_DIR_PATH = path.join(CLI_ROOT, 'src/setup');
68
+ export const MACOS_SETUP_SCRIPT_DIR_PATH = path.join(SETUP_SCRIPT_DIR_PATH, 'macos');
69
+ export const LINUX_SETUP_SCRIPT_DIR_PATH = path.join(SETUP_SCRIPT_DIR_PATH, 'linux');
70
+
71
+ export const COPY_CONFIG_PATH = path.join(CONFIG_DIR_PATH, 'copyconfig.json');
72
+
73
+ export const ANDROID_BUILD_FLAGS = ['--copt=-DANDROID_WITH_JNI', '--repo_env=VALDI_PLATFORM_DEPENDENCIES=android'];
74
+
75
+ function androidCpuFlags(cpu: string): readonly string[] {
76
+ return [`--fat_apk_cpu=${cpu}`, `--android_cpu=${cpu}`];
77
+ }
78
+
79
+ export const ANDROID_ARM64_BUILD_FLAGS = ['--define', 'client_repo_arm64=true', ...androidCpuFlags('arm64-v8a')];
80
+ export const ANDROID_ARMV7_BUILD_FLAGS = ['--define', 'client_repo_arm32=true', ...androidCpuFlags('armeabi-v7a')];
81
+ export const ANDROID_X86_64_BUILD_FLAGS = ['--define', 'client_repo_x86_64=true', ...androidCpuFlags('x86_64')];
82
+
83
+ export const ENABLE_RUNTIME_LOGS_BUILD_FLAGS = ['--@valdi//bzl/runtime_flags:enable_logging'];
84
+ export const ENABLE_RUNTIME_TRACES_BUILD_FLAGS = ['--@valdi//bzl/runtime_flags:enable_tracing'];
85
+ export const DEBUG_BUILD_FLAGS = ['--snap_flavor=platform_development'];
86
+ export const RELEASE_BUILD_FLAGS = ['--snap_flavor=production', '-c opt'];
87
+
88
+ export const IOS_DEVICE_BUILD_FLAGS = '--ios_multi_cpus=arm64';
89
+ export const IOS_BUILD_FLAGS = '--repo_env=VALDI_PLATFORM_DEPENDENCIES=ios';
90
+
91
+ const INLINE_ASSETS_BUILD_FLAGS = ['--@valdi//bzl/valdi:assets_mode=inline'];
92
+
93
+ export const MACOS_BUILD_FLAGS = [...INLINE_ASSETS_BUILD_FLAGS, '--repo_env=VALDI_PLATFORM_DEPENDENCIES=macos'];
94
+ export const CLI_BUILD_FLAGS = [...INLINE_ASSETS_BUILD_FLAGS, '--repo_env=VALDI_PLATFORM_DEPENDENCIES=cli'];
95
+ export const TEST_BUILD_FLAGS = INLINE_ASSETS_BUILD_FLAGS;
@@ -0,0 +1,10 @@
1
+ import { ANSI_COLORS } from './constants';
2
+
3
+ export class CliError extends Error {
4
+ textColor: ANSI_COLORS;
5
+
6
+ constructor(message: string, textColor: ANSI_COLORS = ANSI_COLORS.RED_COLOR) {
7
+ super(message);
8
+ this.textColor = textColor;
9
+ }
10
+ }
package/src/index.ts ADDED
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env node
2
+
3
+ import yargs from 'yargs';
4
+ import { hideBin } from 'yargs/helpers';
5
+ import { version } from '../package.json';
6
+
7
+ function main() {
8
+ void yargs(hideBin(process.argv))
9
+ .completion()
10
+ .commandDir('commands', {
11
+ extensions: ['js', 'ts'],
12
+ })
13
+ .demandCommand(1, 'Need at least one command to execute')
14
+ .recommendCommands()
15
+ .strict()
16
+ .version('version', 'Show version number', version)
17
+ .scriptName('valdi')
18
+ .wrap(yargs.terminalWidth())
19
+ .help().argv;
20
+ }
21
+
22
+ main();