@react-native-windows/cli 0.0.0-canary.13 → 0.0.0-canary.132

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 (80) hide show
  1. package/README.md +47 -0
  2. package/lib-commonjs/config/configUtils.d.ts +25 -2
  3. package/lib-commonjs/config/configUtils.js +138 -30
  4. package/lib-commonjs/config/configUtils.js.map +1 -1
  5. package/lib-commonjs/config/dependencyConfig.js +104 -43
  6. package/lib-commonjs/config/dependencyConfig.js.map +1 -1
  7. package/lib-commonjs/config/projectConfig.d.ts +4 -1
  8. package/lib-commonjs/config/projectConfig.js +72 -12
  9. package/lib-commonjs/config/projectConfig.js.map +1 -1
  10. package/lib-commonjs/e2etest/autolink.test.d.ts +6 -0
  11. package/lib-commonjs/e2etest/autolink.test.js +386 -0
  12. package/lib-commonjs/e2etest/autolink.test.js.map +1 -0
  13. package/lib-commonjs/e2etest/dependencyConfig.test.d.ts +6 -0
  14. package/lib-commonjs/e2etest/dependencyConfig.test.js +130 -0
  15. package/lib-commonjs/e2etest/dependencyConfig.test.js.map +1 -0
  16. package/lib-commonjs/e2etest/projectConfig.test.d.ts +6 -0
  17. package/lib-commonjs/e2etest/projectConfig.test.js +111 -0
  18. package/lib-commonjs/e2etest/projectConfig.test.js.map +1 -0
  19. package/lib-commonjs/e2etest/projectConfig.utils.d.ts +8 -0
  20. package/lib-commonjs/e2etest/projectConfig.utils.js +77 -0
  21. package/lib-commonjs/e2etest/projectConfig.utils.js.map +1 -0
  22. package/lib-commonjs/e2etest/runWindows.test.d.ts +6 -0
  23. package/lib-commonjs/e2etest/runWindows.test.js +61 -0
  24. package/lib-commonjs/e2etest/runWindows.test.js.map +1 -0
  25. package/lib-commonjs/generator-common/index.d.ts +16 -0
  26. package/lib-commonjs/generator-common/index.js +60 -39
  27. package/lib-commonjs/generator-common/index.js.map +1 -1
  28. package/lib-commonjs/generator-windows/index.d.ts +2 -2
  29. package/lib-commonjs/generator-windows/index.js +265 -182
  30. package/lib-commonjs/generator-windows/index.js.map +1 -1
  31. package/lib-commonjs/healthChecks.d.ts +2 -0
  32. package/lib-commonjs/healthChecks.js +88 -0
  33. package/lib-commonjs/healthChecks.js.map +1 -0
  34. package/lib-commonjs/index.d.ts +5 -0
  35. package/lib-commonjs/index.js +28 -8
  36. package/lib-commonjs/index.js.map +1 -1
  37. package/lib-commonjs/runWindows/runWindows.js +239 -52
  38. package/lib-commonjs/runWindows/runWindows.js.map +1 -1
  39. package/lib-commonjs/runWindows/runWindowsOptions.d.ts +14 -10
  40. package/lib-commonjs/runWindows/runWindowsOptions.js +15 -11
  41. package/lib-commonjs/runWindows/runWindowsOptions.js.map +1 -1
  42. package/lib-commonjs/runWindows/utils/autolink.d.ts +88 -1
  43. package/lib-commonjs/runWindows/utils/autolink.js +593 -260
  44. package/lib-commonjs/runWindows/utils/autolink.js.map +1 -1
  45. package/lib-commonjs/runWindows/utils/build.d.ts +1 -2
  46. package/lib-commonjs/runWindows/utils/build.js +24 -31
  47. package/lib-commonjs/runWindows/utils/build.js.map +1 -1
  48. package/lib-commonjs/runWindows/utils/checkRequirements.js +11 -7
  49. package/lib-commonjs/runWindows/utils/checkRequirements.js.map +1 -1
  50. package/lib-commonjs/runWindows/utils/commandWithProgress.d.ts +11 -3
  51. package/lib-commonjs/runWindows/utils/commandWithProgress.js +58 -22
  52. package/lib-commonjs/runWindows/utils/commandWithProgress.js.map +1 -1
  53. package/lib-commonjs/runWindows/utils/deploy.d.ts +1 -1
  54. package/lib-commonjs/runWindows/utils/deploy.js +168 -82
  55. package/lib-commonjs/runWindows/utils/deploy.js.map +1 -1
  56. package/lib-commonjs/runWindows/utils/info.js +5 -2
  57. package/lib-commonjs/runWindows/utils/info.js.map +1 -1
  58. package/lib-commonjs/runWindows/utils/msbuildtools.d.ts +11 -5
  59. package/lib-commonjs/runWindows/utils/msbuildtools.js +148 -64
  60. package/lib-commonjs/runWindows/utils/msbuildtools.js.map +1 -1
  61. package/lib-commonjs/runWindows/utils/telemetryHelpers.d.ts +29 -0
  62. package/lib-commonjs/runWindows/utils/telemetryHelpers.js +113 -0
  63. package/lib-commonjs/runWindows/utils/telemetryHelpers.js.map +1 -0
  64. package/lib-commonjs/runWindows/utils/version.d.ts +4 -4
  65. package/lib-commonjs/runWindows/utils/version.js.map +1 -1
  66. package/lib-commonjs/runWindows/utils/vsInstalls.d.ts +4 -1
  67. package/lib-commonjs/runWindows/utils/vsInstalls.js +22 -7
  68. package/lib-commonjs/runWindows/utils/vsInstalls.js.map +1 -1
  69. package/lib-commonjs/runWindows/utils/vstools.d.ts +1 -0
  70. package/lib-commonjs/runWindows/utils/vstools.js +40 -27
  71. package/lib-commonjs/runWindows/utils/vstools.js.map +1 -1
  72. package/lib-commonjs/runWindows/utils/winappdeploytool.d.ts +3 -3
  73. package/lib-commonjs/runWindows/utils/winappdeploytool.js +17 -14
  74. package/lib-commonjs/runWindows/utils/winappdeploytool.js.map +1 -1
  75. package/package.json +40 -22
  76. package/powershell/Add-AppDevPackage.ps1 +2 -2
  77. package/powershell/Eval-MsBuildProperties.ps1 +156 -0
  78. package/powershell/WindowsStoreAppUtils.ps1 +10 -0
  79. package/CHANGELOG.json +0 -185
  80. package/CHANGELOG.md +0 -93
@@ -4,128 +4,148 @@
4
4
  * Licensed under the MIT License.
5
5
  * @format
6
6
  */
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || function (mod) {
24
+ if (mod && mod.__esModule) return mod;
25
+ var result = {};
26
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
27
+ __setModuleDefault(result, mod);
28
+ return result;
29
+ };
30
+ var __importDefault = (this && this.__importDefault) || function (mod) {
31
+ return (mod && mod.__esModule) ? mod : { "default": mod };
32
+ };
7
33
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.autoLinkCommand = void 0;
9
- const fs = require("fs");
10
- const path = require("path");
11
- const chalk = require("chalk");
34
+ exports.autoLinkCommand = exports.autolinkOptions = exports.autolinkWindowsInternal = exports.AutolinkWindows = void 0;
35
+ // Types in this file are inaccurate compared to usage in terms of falsiness.
36
+ // We should try to rewrite some of this to do automated schema validation to
37
+ // guarantee correct types
38
+ /* eslint-disable @typescript-eslint/no-unnecessary-condition */
39
+ const fs_1 = __importDefault(require("@react-native-windows/fs"));
40
+ const path_1 = __importDefault(require("path"));
41
+ const chalk_1 = __importDefault(require("chalk"));
12
42
  const perf_hooks_1 = require("perf_hooks");
13
43
  const commandWithProgress_1 = require("./commandWithProgress");
14
- const vstools = require("./vstools");
15
- const generatorCommon = require("../../generator-common");
16
- const configUtils = require("../../config/configUtils");
17
- /**
18
- * Locates the react-native-windows directory containing template files
19
- * @param config project configuration
20
- */
21
- function resolveTemplateRoot(projectConfig) {
22
- const rnwPackage = path.dirname(require.resolve('react-native-windows/package.json', {
23
- paths: [projectConfig.folder],
24
- }));
25
- return path.join(rnwPackage, 'template');
26
- }
27
- /**
28
- * Logs the given message if verbose is True.
29
- * @param message The message to log.
30
- * @param verbose Whether or not verbose logging is enabled.
31
- */
32
- function verboseMessage(message, verbose) {
33
- if (verbose) {
34
- console.log(message);
35
- }
36
- }
37
- /**
38
- * Loads a source template file and performs the given replacements, normalizing CRLF.
39
- * @param srcFile Path to the source file.
40
- * @param replacements e.g. {'TextToBeReplaced': 'Replacement'}
41
- * @return The contents of the file with the replacements applied.
42
- */
43
- function getNormalizedContents(srcFile, replacements) {
44
- // Template files are CRLF, JS-generated replacements are LF, normalize replacements to CRLF
45
- for (var key in replacements) {
46
- replacements[key] = replacements[key].replace(/\n/g, '\r\n');
47
- }
48
- replacements.useMustache = true;
49
- return generatorCommon.resolveContents(srcFile, replacements);
50
- }
51
- /**
52
- * Updates the target file with the expected contents if it's different.
53
- * @param filePath Path to the target file to update.
54
- * @param expectedContents The expected contents of the file.
55
- * @param verbose If true, enable verbose logging.
56
- * @param checkMode It true, don't make any changes.
57
- * @return Whether any changes were necessary.
58
- */
59
- function updateFile(filePath, expectedContents, verbose, checkMode) {
60
- const fileName = chalk.bold(path.basename(filePath));
61
- verboseMessage(`Reading ${fileName}...`, verbose);
62
- const actualContents = fs.existsSync(filePath)
63
- ? fs.readFileSync(filePath).toString()
64
- : '';
65
- const contentsChanged = expectedContents !== actualContents;
66
- if (contentsChanged) {
67
- verboseMessage(chalk.yellow(`${fileName} needs to be updated.`), verbose);
68
- if (!checkMode) {
69
- verboseMessage(`Writing ${fileName}...`, verbose);
70
- fs.writeFileSync(filePath, expectedContents, {
71
- encoding: 'utf8',
72
- flag: 'w',
73
- });
44
+ const vstools = __importStar(require("./vstools"));
45
+ const generatorCommon = __importStar(require("../../generator-common"));
46
+ const configUtils = __importStar(require("../../config/configUtils"));
47
+ const telemetry_1 = require("@react-native-windows/telemetry");
48
+ const telemetryHelpers_1 = require("./telemetryHelpers");
49
+ const xmldom_1 = require("@xmldom/xmldom");
50
+ const formatter = require('xml-formatter');
51
+ class AutolinkWindows {
52
+ constructor(projectConfig, dependenciesConfig, options) {
53
+ this.projectConfig = projectConfig;
54
+ this.dependenciesConfig = dependenciesConfig;
55
+ this.options = options;
56
+ this.changesNecessary = false;
57
+ if (!('windows' in this.projectConfig) ||
58
+ this.projectConfig.windows === null) {
59
+ throw new telemetry_1.CodedError('NoWindowsConfig', 'Windows auto-link only supported on Windows app projects');
74
60
  }
61
+ this.windowsAppConfig = projectConfig.windows;
75
62
  }
76
- else {
77
- verboseMessage(`No changes to ${fileName}.`, verbose);
63
+ areChangesNeeded() {
64
+ return this.changesNecessary;
78
65
  }
79
- return contentsChanged;
80
- }
81
- /**
82
- * Exits the script with the given status code.
83
- * @param statusCode The status code.
84
- * @param loggingWasEnabled Whether or not verbose lossing was enabled.
85
- */
86
- function exitProcessWithStatusCode(statusCode, loggingWasEnabled) {
87
- if (!loggingWasEnabled && statusCode !== 0) {
88
- console.log(`Error: Re-run the command with ${chalk.bold('--logging')} for more information.`);
66
+ getWindowsConfig() {
67
+ return this.windowsAppConfig;
89
68
  }
90
- process.exit(statusCode);
91
- }
92
- /**
93
- * Performs auto-linking for RNW native modules and apps.
94
- * @param args Unprocessed args passed from react-native CLI.
95
- * @param config Config passed from react-native CLI.
96
- * @param options Options passed from react-native CLI.
97
- */
98
- async function updateAutoLink(args, config, options) {
99
- const startTime = perf_hooks_1.performance.now();
100
- const verbose = options.logging;
101
- const checkMode = options.check;
102
- var changesNecessary = false;
103
- const spinner = commandWithProgress_1.newSpinner(checkMode ? 'Checking auto-linked files...' : 'Auto-linking...');
104
- verboseMessage('', verbose);
105
- try {
69
+ getSolutionFile() {
70
+ return path_1.default.join(this.getWindowsConfig().folder, this.getWindowsConfig().sourceDir, this.getWindowsConfig().solutionFile);
71
+ }
72
+ async run(spinner) {
73
+ const verbose = this.options.logging;
74
+ verboseMessage('', verbose);
106
75
  verboseMessage('Parsing project...', verbose);
107
- const projectConfig = config.project;
108
- if (!('windows' in projectConfig) || projectConfig.windows === null) {
109
- throw new Error('Windows auto-link only supported on Windows app projects');
76
+ const rnwRoot = resolveRnwRoot(this.windowsAppConfig);
77
+ const templateRoot = resolveTemplateRoot(this.windowsAppConfig);
78
+ this.fixUpForSlnOption();
79
+ this.fixUpForProjOption();
80
+ verboseMessage('Found Windows app project, config:', verbose);
81
+ verboseMessage(this.windowsAppConfig, verbose);
82
+ this.validateRequiredAppProperties();
83
+ const solutionFile = this.getSolutionFile();
84
+ const windowsAppProjectConfig = this.windowsAppConfig.project;
85
+ this.validateRequiredProjectProperties();
86
+ const projectFile = this.getProjectFile();
87
+ const projectDir = path_1.default.dirname(projectFile);
88
+ const projectLang = windowsAppProjectConfig.projectLang;
89
+ verboseMessage('Parsing dependencies...', verbose);
90
+ this.changesNecessary =
91
+ (await this.ensureXAMLDialect()) || this.changesNecessary;
92
+ // Generating cs/cpp files for app code consumption
93
+ if (projectLang === 'cs') {
94
+ this.changesNecessary =
95
+ (await this.generateCSAutolinking(templateRoot, projectLang, projectDir)) || this.changesNecessary;
96
+ }
97
+ else if (projectLang === 'cpp') {
98
+ this.changesNecessary =
99
+ (await this.generateCppAutolinking(templateRoot, projectLang, projectDir)) || this.changesNecessary;
110
100
  }
111
- const windowsAppConfig = projectConfig.windows;
112
- const templateRoot = resolveTemplateRoot(windowsAppConfig);
113
- if (options.sln) {
114
- const slnFile = path.join(windowsAppConfig.folder, options.sln);
115
- windowsAppConfig.solutionFile = path.relative(path.join(windowsAppConfig.folder, windowsAppConfig.sourceDir), slnFile);
101
+ // Generating props for app project consumption
102
+ let propertiesForProps = '';
103
+ let csModuleNames = [];
104
+ if (projectLang === 'cpp') {
105
+ csModuleNames = this.getCSModules();
106
+ if (csModuleNames.length > 0) {
107
+ propertiesForProps += `
108
+ <!-- Set due to dependency on C# module(s): ${csModuleNames.join()} -->
109
+ <ConsumeCSharpModules Condition="'$(ConsumeCSharpModules)'==''">true</ConsumeCSharpModules>`;
110
+ }
116
111
  }
117
- if (options.proj) {
118
- const projFile = path.join(windowsAppConfig.folder, options.proj);
112
+ this.changesNecessary =
113
+ (await this.generateAutolinkProps(templateRoot, projectDir, propertiesForProps)) || this.changesNecessary;
114
+ // Generating targets for app project consumption
115
+ this.changesNecessary =
116
+ (await this.generateAutolinkTargets(projectDir, templateRoot)) ||
117
+ this.changesNecessary;
118
+ // Generating project entries for solution
119
+ this.changesNecessary =
120
+ this.updateSolution(rnwRoot, solutionFile) || this.changesNecessary;
121
+ spinner.succeed();
122
+ }
123
+ /**
124
+ * Handles the --proj command-line option by consuming its value into the windowsAppConfig
125
+ */
126
+ fixUpForProjOption() {
127
+ if (this.options.proj) {
128
+ const projFile = path_1.default.join(this.windowsAppConfig.folder, this.options.proj);
119
129
  const projectContents = configUtils.readProjectFile(projFile);
120
- windowsAppConfig.project = {
121
- projectFile: path.relative(path.join(windowsAppConfig.folder, windowsAppConfig.sourceDir), projFile),
122
- projectName: configUtils.getProjectName(projectContents),
130
+ this.windowsAppConfig.project = {
131
+ projectFile: path_1.default.relative(path_1.default.join(this.windowsAppConfig.folder, this.windowsAppConfig.sourceDir), projFile),
132
+ projectName: configUtils.getProjectName(projFile, projectContents),
123
133
  projectLang: configUtils.getProjectLanguage(projFile),
124
134
  projectGuid: configUtils.getProjectGuid(projectContents),
125
135
  };
126
136
  }
127
- verboseMessage('Found Windows app project, config:', verbose);
128
- verboseMessage(windowsAppConfig, verbose);
137
+ }
138
+ /**
139
+ * Handles the --sln command-line option by consuming its value into the windowsAppConfig
140
+ */
141
+ fixUpForSlnOption() {
142
+ if (this.options.sln) {
143
+ const slnFile = path_1.default.join(this.windowsAppConfig.folder, this.options.sln);
144
+ this.windowsAppConfig.solutionFile = path_1.default.relative(path_1.default.join(this.windowsAppConfig.folder, this.windowsAppConfig.sourceDir), slnFile);
145
+ }
146
+ }
147
+ /** Validates the all of the required app (solution) properties are present and valid */
148
+ validateRequiredAppProperties() {
129
149
  const alwaysRequired = [
130
150
  'folder',
131
151
  'sourceDir',
@@ -133,16 +153,24 @@ async function updateAutoLink(args, config, options) {
133
153
  'project',
134
154
  ];
135
155
  alwaysRequired.forEach(item => {
136
- if (!(item in windowsAppConfig) || windowsAppConfig[item] === null) {
137
- throw new Error(`${item} is required but not specified by react-native config`);
156
+ if (!(item in this.windowsAppConfig) ||
157
+ this.windowsAppConfig[item] === null) {
158
+ throw new telemetry_1.CodedError('IncompleteConfig', `${item} is required but not specified by react-native config`, { item: item });
138
159
  }
139
- else if (typeof windowsAppConfig[item] === 'string' &&
140
- windowsAppConfig[item].startsWith('Error: ')) {
141
- throw new Error(`${item} invalid. ${windowsAppConfig[item]}`);
160
+ else if (typeof this.windowsAppConfig[item] === 'string' &&
161
+ this.windowsAppConfig[item].startsWith('Error: ')) {
162
+ throw new telemetry_1.CodedError('InvalidConfig', `${item} invalid. ${this.windowsAppConfig[item]}`, { item: item });
142
163
  }
143
164
  });
144
- const solutionFile = path.join(windowsAppConfig.folder, windowsAppConfig.sourceDir, windowsAppConfig.solutionFile);
145
- const windowsAppProjectConfig = windowsAppConfig.project;
165
+ }
166
+ /** @return the full path to the project file (.vcxproj or .csproj) */
167
+ getProjectFile() {
168
+ const windowsAppConfig = this.getWindowsConfig();
169
+ return path_1.default.join(windowsAppConfig.folder, windowsAppConfig.sourceDir, windowsAppConfig.project.projectFile);
170
+ }
171
+ /** Validates that all of the required app _project_ properties are present and valid */
172
+ validateRequiredProjectProperties() {
173
+ const windowsAppProjectConfig = this.windowsAppConfig.project;
146
174
  const projectRequired = [
147
175
  'projectFile',
148
176
  'projectName',
@@ -152,144 +180,213 @@ async function updateAutoLink(args, config, options) {
152
180
  projectRequired.forEach(item => {
153
181
  if (!(item in windowsAppProjectConfig) ||
154
182
  windowsAppProjectConfig[item] === null) {
155
- throw new Error(`project.${item} is required but not specified by react-native config`);
183
+ throw new telemetry_1.CodedError('IncompleteConfig', `project.${item} is required but not specified by react-native config`, { item: item });
156
184
  }
157
185
  else if (typeof windowsAppProjectConfig[item] === 'string' &&
158
186
  windowsAppProjectConfig[item].startsWith('Error: ')) {
159
- throw new Error(`project.${item} invalid. ${windowsAppProjectConfig[item]}`);
187
+ throw new telemetry_1.CodedError('InvalidConfig', `project.${item} invalid. ${windowsAppProjectConfig[item]}`, { item: item });
160
188
  }
161
189
  });
162
- const projectFile = path.join(windowsAppConfig.folder, windowsAppConfig.sourceDir, windowsAppConfig.project.projectFile);
163
- const projectDir = path.dirname(projectFile);
164
- const projectLang = windowsAppConfig.project.projectLang;
165
- verboseMessage('Parsing dependencies...', verbose);
166
- const dependenciesConfig = config.dependencies;
167
- let windowsDependencies = {};
168
- for (const dependencyName in dependenciesConfig) {
169
- const windowsDependency = dependenciesConfig[dependencyName].platforms.windows;
170
- if (windowsDependency) {
171
- verboseMessage(`${chalk.bold(dependencyName)} has Windows implementation, config:`, verbose);
172
- verboseMessage(windowsDependency, verbose);
173
- var dependencyIsValid = true;
174
- dependencyIsValid = !!(dependencyIsValid &&
175
- 'sourceDir' in windowsDependency &&
176
- windowsDependency.sourceDir &&
177
- !windowsDependency.sourceDir.startsWith('Error: '));
178
- if ('projects' in windowsDependency &&
179
- Array.isArray(windowsDependency.projects)) {
180
- windowsDependency.projects.forEach(project => {
181
- const itemsToCheck = [
182
- 'projectFile',
183
- 'directDependency',
184
- ];
185
- itemsToCheck.forEach(item => {
186
- dependencyIsValid = !!(dependencyIsValid &&
187
- item in project &&
188
- project[item] &&
189
- !project[item].toString().startsWith('Error: '));
190
- });
190
+ }
191
+ async generateCppAutolinking(templateRoot, projectLang, projectDir) {
192
+ const { cppPackageProviders, cppIncludes } = this.getCppReplacements();
193
+ const cppFileName = 'AutolinkedNativeModules.g.cpp';
194
+ const srcCppFile = path_1.default.join(templateRoot, `${projectLang}-app`, 'src', cppFileName);
195
+ const destCppFile = path_1.default.join(projectDir, cppFileName);
196
+ verboseMessage(`Calculating ${chalk_1.default.bold(path_1.default.basename(destCppFile))}...`, this.options.logging);
197
+ const cppContents = generatorCommon.resolveContents(srcCppFile, {
198
+ useMustache: true,
199
+ autolinkCppIncludes: cppIncludes,
200
+ autolinkCppPackageProviders: cppPackageProviders,
201
+ });
202
+ return await this.updateFile(destCppFile, cppContents);
203
+ }
204
+ getCppReplacements() {
205
+ let cppIncludes = '';
206
+ let cppPackageProviders = '';
207
+ const windowsDependencies = this.getWindowsDependencies();
208
+ for (const dependencyName of Object.keys(windowsDependencies)) {
209
+ windowsDependencies[dependencyName].projects.forEach(project => {
210
+ if (project.directDependency) {
211
+ cppIncludes += `\n\n// Includes from ${dependencyName}`;
212
+ project.cppHeaders.forEach(header => {
213
+ cppIncludes += `\n#include <${header}>`;
214
+ });
215
+ cppPackageProviders += `\n // IReactPackageProviders from ${dependencyName}`;
216
+ project.cppPackageProviders.forEach(packageProvider => {
217
+ cppPackageProviders += `\n packageProviders.Append(winrt::${packageProvider}());`;
191
218
  });
192
219
  }
193
- if (dependencyIsValid) {
194
- verboseMessage(`Adding ${chalk.bold(dependencyName)}.`, verbose);
195
- windowsDependencies[dependencyName] = windowsDependency;
220
+ });
221
+ }
222
+ if (cppPackageProviders === '') {
223
+ // There are no windows dependencies, this would result in warning. C4100: 'packageProviders': unreferenced formal parameter.
224
+ // therefore add a usage.
225
+ cppPackageProviders = '\n UNREFERENCED_PARAMETER(packageProviders);'; // CODESYNC: vnext\local-cli\generator-windows\index.js
226
+ }
227
+ return { cppPackageProviders, cppIncludes };
228
+ }
229
+ generateCSAutolinking(templateRoot, projectLang, projectDir) {
230
+ const { csUsingNamespaces, csReactPackageProviders } = this.getCsReplacements();
231
+ const csFileName = 'AutolinkedNativeModules.g.cs';
232
+ const srcCsFile = path_1.default.join(templateRoot, `${projectLang}-app`, 'src', csFileName);
233
+ const destCsFile = path_1.default.join(projectDir, csFileName);
234
+ verboseMessage(`Calculating ${chalk_1.default.bold(path_1.default.basename(destCsFile))}...`, this.options.logging);
235
+ const csContents = generatorCommon.resolveContents(srcCsFile, {
236
+ useMustache: true,
237
+ autolinkCsUsingNamespaces: csUsingNamespaces,
238
+ autolinkCsReactPackageProviders: csReactPackageProviders,
239
+ });
240
+ return this.updateFile(destCsFile, csContents);
241
+ }
242
+ getCsReplacements() {
243
+ let csUsingNamespaces = '';
244
+ let csReactPackageProviders = '';
245
+ const windowsDependencies = this.getWindowsDependencies();
246
+ for (const dependencyName of Object.keys(windowsDependencies)) {
247
+ windowsDependencies[dependencyName].projects.forEach(project => {
248
+ if (project.directDependency) {
249
+ csUsingNamespaces += `\n\n// Namespaces from ${dependencyName}`;
250
+ project.csNamespaces.forEach(namespace => {
251
+ csUsingNamespaces += `\nusing ${namespace};`;
252
+ });
253
+ csReactPackageProviders += `\n // IReactPackageProviders from ${dependencyName}`;
254
+ project.csPackageProviders.forEach(packageProvider => {
255
+ csReactPackageProviders += `\n packageProviders.Add(new ${packageProvider}());`;
256
+ });
196
257
  }
197
- }
258
+ });
198
259
  }
199
- // Generating cs/h files for app code consumption
200
- if (projectLang === 'cs') {
201
- let csUsingNamespaces = '';
202
- let csReactPacakgeProviders = '';
203
- for (const dependencyName in windowsDependencies) {
204
- windowsDependencies[dependencyName].projects.forEach(project => {
205
- if (project.directDependency) {
206
- csUsingNamespaces += `\n\n// Namespaces from ${dependencyName}`;
207
- project.csNamespaces.forEach(namespace => {
208
- csUsingNamespaces += `\nusing ${namespace};`;
209
- });
210
- csReactPacakgeProviders += `\n // IReactPackageProviders from ${dependencyName}`;
211
- project.csPackageProviders.forEach(packageProvider => {
212
- csReactPacakgeProviders += `\n packageProviders.Add(new ${packageProvider}());`;
260
+ return { csUsingNamespaces, csReactPackageProviders };
261
+ }
262
+ getWindowsDependencies() {
263
+ if (!this.windowsDependencies) {
264
+ this.windowsDependencies = {};
265
+ for (const dependencyName of Object.keys(this.dependenciesConfig)) {
266
+ const windowsDependency = this.dependenciesConfig[dependencyName].platforms.windows;
267
+ if (windowsDependency) {
268
+ verboseMessage(`${chalk_1.default.bold(dependencyName)} has Windows implementation, config:`, this.options.logging);
269
+ verboseMessage(windowsDependency, this.options.logging);
270
+ let dependencyIsValid = false;
271
+ const hasValidSourceDir = 'sourceDir' in windowsDependency &&
272
+ windowsDependency.sourceDir !== undefined &&
273
+ !windowsDependency.sourceDir.startsWith('Error: ');
274
+ const hasProjectsInProjectsArray = 'projects' in windowsDependency &&
275
+ Array.isArray(windowsDependency.projects) &&
276
+ windowsDependency.projects.length > 0;
277
+ if (hasValidSourceDir && hasProjectsInProjectsArray) {
278
+ // Module is source-based and has projects
279
+ dependencyIsValid = true;
280
+ // Validate each source project
281
+ windowsDependency.projects.forEach(project => {
282
+ const itemsToCheck = [
283
+ 'projectFile',
284
+ 'directDependency',
285
+ ];
286
+ itemsToCheck.forEach(item => {
287
+ dependencyIsValid = !!(dependencyIsValid &&
288
+ item in project &&
289
+ project[item] !== '' &&
290
+ !project[item].toString().startsWith('Error: '));
291
+ });
213
292
  });
214
293
  }
215
- });
294
+ if (dependencyIsValid) {
295
+ verboseMessage(`Adding ${chalk_1.default.bold(dependencyName)}.`, this.options.logging);
296
+ this.windowsDependencies[dependencyName] = windowsDependency;
297
+ }
298
+ else {
299
+ verboseMessage(`Invalid dependency configuration for dependency ${dependencyName}`, this.options.logging);
300
+ }
301
+ }
216
302
  }
217
- const csFileName = 'AutolinkedNativeModules.g.cs';
218
- const srcCsFile = path.join(templateRoot, projectLang, 'src', csFileName);
219
- const destCsFile = path.join(projectDir, csFileName);
220
- verboseMessage(`Calculating ${chalk.bold(path.basename(destCsFile))}...`, verbose);
221
- const csContents = getNormalizedContents(srcCsFile, {
222
- autolinkCsUsingNamespaces: csUsingNamespaces,
223
- autolinkCsReactPacakgeProviders: csReactPacakgeProviders,
224
- });
225
- changesNecessary =
226
- updateFile(destCsFile, csContents, verbose, checkMode) ||
227
- changesNecessary;
228
303
  }
229
- else if (projectLang === 'cpp') {
230
- let cppIncludes = '';
231
- let cppPackageProviders = '';
232
- for (const dependencyName in windowsDependencies) {
233
- windowsDependencies[dependencyName].projects.forEach(project => {
234
- if (project.directDependency) {
235
- cppIncludes += `\n\n// Includes from ${dependencyName}`;
236
- project.cppHeaders.forEach(header => {
237
- cppIncludes += `\n#include <${header}>`;
238
- });
239
- cppPackageProviders += `\n // IReactPackageProviders from ${dependencyName}`;
240
- project.cppPackageProviders.forEach(packageProvider => {
241
- cppPackageProviders += `\n packageProviders.Append(winrt::${packageProvider}());`;
242
- });
243
- }
304
+ return this.windowsDependencies;
305
+ }
306
+ /**
307
+ * Updates the target file with the expected contents if it's different.
308
+ * @param filePath Path to the target file to update.
309
+ * @param expectedContents The expected contents of the file.
310
+ * @return Whether any changes were necessary.
311
+ */
312
+ async updateFile(filePath, expectedContents) {
313
+ const fileName = chalk_1.default.bold(path_1.default.basename(filePath));
314
+ verboseMessage(`Reading ${fileName}...`, this.options.logging);
315
+ const actualContents = fs_1.default.existsSync(filePath)
316
+ ? (await fs_1.default.readFile(filePath)).toString()
317
+ : '';
318
+ const contentsChanged = expectedContents !== actualContents;
319
+ if (contentsChanged) {
320
+ verboseMessage(chalk_1.default.yellow(`${fileName} needs to be updated.`), this.options.logging);
321
+ if (!this.options.check) {
322
+ verboseMessage(`Writing ${fileName}...`, this.options.logging);
323
+ await fs_1.default.writeFile(filePath, expectedContents, {
324
+ encoding: 'utf8',
325
+ flag: 'w',
244
326
  });
245
327
  }
246
- if (cppPackageProviders === '') {
247
- // There are no windows dependencies, this would result in warning. C4100: 'packageProviders': unreferenced formal parameter.
248
- // therefore add a usage.
249
- cppPackageProviders = '\n UNREFERENCED_PARAMETER(packageProviders);'; // CODESYNC: vnext\local-cli\generator-windows\index.js
250
- }
251
- const cppFileName = 'AutolinkedNativeModules.g.cpp';
252
- const srcCppFile = path.join(templateRoot, projectLang, 'src', cppFileName);
253
- const destCppFile = path.join(projectDir, cppFileName);
254
- verboseMessage(`Calculating ${chalk.bold(path.basename(destCppFile))}...`, verbose);
255
- const cppContents = getNormalizedContents(srcCppFile, {
256
- autolinkCppIncludes: cppIncludes,
257
- autolinkCppPackageProviders: cppPackageProviders,
258
- });
259
- changesNecessary =
260
- updateFile(destCppFile, cppContents, verbose, checkMode) ||
261
- changesNecessary;
262
328
  }
263
- // Generating targets for app project consumption
329
+ else {
330
+ verboseMessage(`No changes to ${fileName}.`, this.options.logging);
331
+ }
332
+ return contentsChanged;
333
+ }
334
+ generateAutolinkTargets(projectDir, templateRoot) {
264
335
  let projectReferencesForTargets = '';
265
- for (const dependencyName in windowsDependencies) {
336
+ const windowsDependencies = this.getWindowsDependencies();
337
+ for (const dependencyName of Object.keys(windowsDependencies)) {
266
338
  windowsDependencies[dependencyName].projects.forEach(project => {
267
339
  if (project.directDependency) {
268
- const dependencyProjectFile = path.join(windowsDependencies[dependencyName].folder, windowsDependencies[dependencyName].sourceDir, project.projectFile);
269
- const relDependencyProjectFile = path.relative(projectDir, dependencyProjectFile);
270
- projectReferencesForTargets += `\n <!-- Projects from ${dependencyName} -->`;
271
- projectReferencesForTargets += `\n <ProjectReference Include="$(ProjectDir)${relDependencyProjectFile}">
340
+ const dependencyProjectFile = path_1.default.join(windowsDependencies[dependencyName].folder, windowsDependencies[dependencyName].sourceDir, project.projectFile);
341
+ const relDependencyProjectFile = path_1.default.relative(projectDir, dependencyProjectFile);
342
+ projectReferencesForTargets += `
343
+ <!-- Projects from ${dependencyName} -->
344
+ <ProjectReference Include="$(ProjectDir)${relDependencyProjectFile}">
272
345
  <Project>${project.projectGuid}</Project>
273
346
  </ProjectReference>`;
274
347
  }
275
348
  });
276
349
  }
277
350
  const targetFileName = 'AutolinkedNativeModules.g.targets';
278
- const srcTargetFile = path.join(templateRoot, projectLang, 'src', targetFileName);
279
- const destTargetFile = path.join(projectDir, targetFileName);
280
- verboseMessage(`Calculating ${chalk.bold(path.basename(destTargetFile))}...`, verbose);
281
- const targetContents = getNormalizedContents(srcTargetFile, {
351
+ const srcTargetFile = path_1.default.join(templateRoot, `shared-app`, 'src', targetFileName);
352
+ const destTargetFile = path_1.default.join(projectDir, targetFileName);
353
+ verboseMessage(`Calculating ${chalk_1.default.bold(path_1.default.basename(destTargetFile))}...`, this.options.logging);
354
+ const targetContents = generatorCommon.resolveContents(srcTargetFile, {
355
+ useMustache: true,
282
356
  autolinkProjectReferencesForTargets: projectReferencesForTargets,
283
357
  });
284
- changesNecessary =
285
- updateFile(destTargetFile, targetContents, verbose, checkMode) ||
286
- changesNecessary;
287
- // Generating project entries for solution
288
- let projectsForSolution = [];
289
- for (const dependencyName in windowsDependencies) {
290
- // Process projects
358
+ return this.updateFile(destTargetFile, targetContents);
359
+ }
360
+ generateAutolinkProps(templateRoot, projectDir, propertiesForProps) {
361
+ const propsFileName = 'AutolinkedNativeModules.g.props';
362
+ const srcPropsFile = path_1.default.join(templateRoot, `shared-app`, 'src', propsFileName);
363
+ const destPropsFile = path_1.default.join(projectDir, propsFileName);
364
+ verboseMessage(`Calculating ${chalk_1.default.bold(path_1.default.basename(destPropsFile))}...`, this.options.logging);
365
+ const propsContents = generatorCommon.resolveContents(srcPropsFile, {
366
+ useMustache: true,
367
+ autolinkPropertiesForProps: propertiesForProps,
368
+ });
369
+ return this.updateFile(destPropsFile, propsContents);
370
+ }
371
+ getCSModules() {
372
+ const csModuleNames = [];
373
+ const windowsDependencies = this.getWindowsDependencies();
374
+ for (const dependencyName of Object.keys(windowsDependencies)) {
291
375
  windowsDependencies[dependencyName].projects.forEach(project => {
292
- const dependencyProjectFile = path.join(windowsDependencies[dependencyName].folder, windowsDependencies[dependencyName].sourceDir, project.projectFile);
376
+ if (project.directDependency && project.projectLang === 'cs') {
377
+ csModuleNames.push(project.projectName);
378
+ }
379
+ });
380
+ }
381
+ return csModuleNames;
382
+ }
383
+ updateSolution(rnwRoot, solutionFile) {
384
+ const projectsForSolution = [];
385
+ const windowsDependencies = this.getWindowsDependencies();
386
+ for (const dependencyName of Object.keys(windowsDependencies)) {
387
+ // Process dependency projects
388
+ windowsDependencies[dependencyName].projects.forEach(project => {
389
+ const dependencyProjectFile = path_1.default.join(windowsDependencies[dependencyName].folder, windowsDependencies[dependencyName].sourceDir, project.projectFile);
293
390
  projectsForSolution.push({
294
391
  projectFile: dependencyProjectFile,
295
392
  projectName: project.projectName,
@@ -298,56 +395,292 @@ async function updateAutoLink(args, config, options) {
298
395
  });
299
396
  });
300
397
  }
301
- verboseMessage(`Calculating ${chalk.bold(path.basename(solutionFile))} changes...`, verbose);
398
+ const csModuleNames = this.getCSModules();
399
+ if (csModuleNames.length > 0) {
400
+ // Add managed projects
401
+ projectsForSolution.push({
402
+ projectFile: path_1.default.join(rnwRoot, 'Microsoft.ReactNative.Managed/Microsoft.ReactNative.Managed.csproj'),
403
+ projectName: 'Microsoft.ReactNative.Managed',
404
+ projectLang: 'cs',
405
+ projectGuid: '{F2824844-CE15-4242-9420-308923CD76C3}',
406
+ });
407
+ projectsForSolution.push({
408
+ projectFile: path_1.default.join(rnwRoot, 'Microsoft.ReactNative.Managed.CodeGen//Microsoft.ReactNative.Managed.CodeGen.csproj'),
409
+ projectName: 'Microsoft.ReactNative.Managed.CodeGen',
410
+ projectLang: 'cs',
411
+ projectGuid: '{ADED4FBE-887D-4271-AF24-F0823BCE7961}',
412
+ projectTypeGuid: vstools.dotNetCoreProjectTypeGuid,
413
+ });
414
+ }
415
+ verboseMessage(`Calculating ${chalk_1.default.bold(path_1.default.basename(solutionFile))} changes...`, this.options.logging);
416
+ let changesNecessary = false;
302
417
  projectsForSolution.forEach(project => {
303
- const contentsChanged = vstools.addProjectToSolution(solutionFile, project, verbose, checkMode);
418
+ const contentsChanged = vstools.addProjectToSolution(solutionFile, project, this.options.logging, this.options.check);
304
419
  changesNecessary = changesNecessary || contentsChanged;
305
420
  });
306
- spinner.succeed();
307
- var endTime = perf_hooks_1.performance.now();
308
- if (!changesNecessary) {
309
- console.log(`${chalk.green('Success:')} No auto-linking changes necessary. (${Math.round(endTime - startTime)}ms)`);
421
+ return changesNecessary;
422
+ }
423
+ getExperimentalFeaturesPropsXml() {
424
+ const experimentalFeaturesProps = path_1.default.join(path_1.default.dirname(this.getSolutionFile()), 'ExperimentalFeatures.props');
425
+ if (fs_1.default.existsSync(experimentalFeaturesProps)) {
426
+ const experimentalFeaturesContents = configUtils.readProjectFile(experimentalFeaturesProps);
427
+ return {
428
+ path: experimentalFeaturesProps,
429
+ content: experimentalFeaturesContents,
430
+ };
431
+ }
432
+ return undefined;
433
+ }
434
+ async ensureXAMLDialect() {
435
+ var _a, _b;
436
+ let changesNeeded = false;
437
+ const useWinUI3FromConfig = this.getWindowsConfig().useWinUI3;
438
+ const experimentalFeatures = this.getExperimentalFeaturesPropsXml();
439
+ if (experimentalFeatures) {
440
+ const useWinUI3FromExperimentalFeatures = ((_a = configUtils
441
+ .tryFindPropertyValue(experimentalFeatures.content, 'UseWinUI3')) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === 'true';
442
+ // Check if WinUI2xVersion is specified in experimental features
443
+ const targetWinUI2xVersion = configUtils.tryFindPropertyValue(experimentalFeatures.content, 'WinUI2xVersion');
444
+ // Check if WinUI3Version is specified in experimental features
445
+ const targetWinUI3xVersion = configUtils.tryFindPropertyValue(experimentalFeatures.content, 'WinUI3Version');
446
+ // Use the UseWinUI3 value in react-native.config.js, or if not present, the value from ExperimentalFeatures.props
447
+ changesNeeded = await this.updatePackagesConfigXAMLDialect(useWinUI3FromConfig !== undefined
448
+ ? useWinUI3FromConfig
449
+ : useWinUI3FromExperimentalFeatures, targetWinUI2xVersion, targetWinUI3xVersion);
450
+ if (useWinUI3FromConfig !== undefined) {
451
+ // Make sure ExperimentalFeatures.props matches the value that comes from react-native.config.js
452
+ const node = experimentalFeatures.content.getElementsByTagName('UseWinUI3');
453
+ const newValue = useWinUI3FromConfig ? 'true' : 'false';
454
+ changesNeeded = ((_b = node.item(0)) === null || _b === void 0 ? void 0 : _b.textContent) !== newValue || changesNeeded;
455
+ if (!this.options.check && changesNeeded) {
456
+ node.item(0).textContent = newValue;
457
+ const experimentalFeaturesOutput = new xmldom_1.XMLSerializer().serializeToString(experimentalFeatures.content);
458
+ await this.updateFile(experimentalFeatures.path, experimentalFeaturesOutput);
459
+ }
460
+ }
461
+ }
462
+ return changesNeeded;
463
+ }
464
+ getPackagesConfigXml() {
465
+ const projectFile = this.getProjectFile();
466
+ const packagesConfig = path_1.default.join(path_1.default.dirname(projectFile), 'packages.config');
467
+ if (fs_1.default.existsSync(packagesConfig)) {
468
+ return {
469
+ path: packagesConfig,
470
+ content: configUtils.readProjectFile(packagesConfig),
471
+ };
472
+ }
473
+ return undefined;
474
+ }
475
+ async updatePackagesConfigXAMLDialect(useWinUI3, targetWinUI2xVersion, targetWinUI3xVersion) {
476
+ let changed = false;
477
+ const packagesConfig = this.getPackagesConfigXml();
478
+ if (packagesConfig) {
479
+ // if we don't have a packages.config, then this is a C# project, in which case we use <PackageReference> and dynamically pick the right XAML package.
480
+ const project = this.getWindowsConfig();
481
+ const winUIPropsPath = path_1.default.join(resolveRnwRoot(project), 'PropertySheets/WinUI.props');
482
+ const winuiPropsContents = configUtils.readProjectFile(winUIPropsPath);
483
+ // Use the given WinUI2xVersion, otherwise fallback to WinUI.props
484
+ const winui2xVersion = targetWinUI2xVersion !== null && targetWinUI2xVersion !== void 0 ? targetWinUI2xVersion : configUtils.tryFindPropertyValue(winuiPropsContents, 'WinUI2xVersion');
485
+ // Use the given WinUI3Version, otherwise fallback to WinUI.props
486
+ const winui3Version = targetWinUI3xVersion !== null && targetWinUI3xVersion !== void 0 ? targetWinUI3xVersion : configUtils.tryFindPropertyValue(winuiPropsContents, 'WinUI3Version');
487
+ const dialects = [
488
+ { id: 'Microsoft.WindowsAppSDK', version: winui3Version },
489
+ { id: 'Microsoft.UI.Xaml', version: winui2xVersion },
490
+ ];
491
+ const keepPkg = useWinUI3 ? dialects[0] : dialects[1];
492
+ const removePkg = useWinUI3 ? dialects[1] : dialects[0];
493
+ changed = this.updatePackagesConfig(packagesConfig, [removePkg], [keepPkg]);
494
+ if (!this.options.check && changed) {
495
+ const serializer = new xmldom_1.XMLSerializer();
496
+ const output = serializer.serializeToString(packagesConfig.content);
497
+ const formattedXml = formatter(output, { indentation: ' ' });
498
+ await this.updateFile(packagesConfig.path, formattedXml);
499
+ }
500
+ }
501
+ return changed;
502
+ }
503
+ updatePackagesConfig(packagesConfig, removePkgs, keepPkgs) {
504
+ let changed = false;
505
+ const packageElements = packagesConfig.content.documentElement.getElementsByTagName('package');
506
+ const nodesToRemove = [];
507
+ for (let i = 0; i < packageElements.length; i++) {
508
+ const packageElement = packageElements.item(i);
509
+ const idAttr = packageElement.getAttributeNode('id');
510
+ const id = idAttr.value;
511
+ const keepPkg = keepPkgs.find(pkg => pkg.id === id);
512
+ if (removePkgs.find(pkg => pkg.id === id)) {
513
+ nodesToRemove.push(packageElement);
514
+ changed = true;
515
+ }
516
+ else if (keepPkg) {
517
+ changed =
518
+ changed || keepPkg.version !== packageElement.getAttribute('version');
519
+ packageElement.setAttribute('version', keepPkg.version);
520
+ keepPkgs = keepPkgs.filter(pkg => pkg.id !== keepPkg.id);
521
+ }
522
+ }
523
+ nodesToRemove.forEach(pkg => packagesConfig.content.documentElement.removeChild(pkg));
524
+ keepPkgs.forEach(keepPkg => {
525
+ const newPkg = packagesConfig.content.createElement('package');
526
+ Object.entries(keepPkg).forEach(([attr, value]) => {
527
+ newPkg.setAttribute(attr, value);
528
+ });
529
+ newPkg.setAttribute('targetFramework', 'native');
530
+ packagesConfig.content.documentElement.appendChild(newPkg);
531
+ changed = true;
532
+ });
533
+ return changed;
534
+ }
535
+ /** @return The CLI command to invoke autolink-windows independently */
536
+ getAutolinkWindowsCommand() {
537
+ const folder = this.windowsAppConfig.folder;
538
+ const autolinkCommand = 'npx react-native autolink-windows';
539
+ const autolinkArgs = `--sln "${path_1.default.relative(folder, this.getSolutionFile())}" --proj "${path_1.default.relative(folder, this.getProjectFile())}"`;
540
+ return `${autolinkCommand} ${autolinkArgs}`;
541
+ }
542
+ }
543
+ exports.AutolinkWindows = AutolinkWindows;
544
+ /**
545
+ * Locates the react-native-windows directory
546
+ * @param config project configuration
547
+ */
548
+ function resolveRnwRoot(projectConfig) {
549
+ const rnwPackage = path_1.default.dirname(require.resolve('react-native-windows/package.json', {
550
+ paths: [projectConfig.folder],
551
+ }));
552
+ return rnwPackage;
553
+ }
554
+ /**
555
+ * Locates the react-native-windows directory containing template files
556
+ * @param config project configuration
557
+ */
558
+ function resolveTemplateRoot(projectConfig) {
559
+ const rnwPackage = resolveRnwRoot(projectConfig);
560
+ return path_1.default.join(rnwPackage, 'template');
561
+ }
562
+ /**
563
+ * Logs the given message if verbose is True.
564
+ * @param message The message to log.
565
+ * @param verbose Whether or not verbose logging is enabled.
566
+ */
567
+ function verboseMessage(message, verbose) {
568
+ if (verbose) {
569
+ console.log(message);
570
+ }
571
+ }
572
+ /**
573
+ * Sanitizes the given option for telemetery.
574
+ * @param key The key of the option.
575
+ * @param value The unsanitized value of the option.
576
+ * @returns The sanitized value of the option.
577
+ */
578
+ function optionSanitizer(key, value) {
579
+ // Do not add a default case here.
580
+ // Strings risking PII should just return true if present, false otherwise.
581
+ // All others should return the value (or false if undefined).
582
+ switch (key) {
583
+ case 'sln':
584
+ case 'proj':
585
+ return value === undefined ? false : true; // Strip PII
586
+ case 'logging':
587
+ case 'check':
588
+ case 'telemetry':
589
+ return value === undefined ? false : value; // Return value
590
+ }
591
+ }
592
+ /**
593
+ * Get the extra props to add to the `autolink-windows` telemetry event.
594
+ * @returns The extra props.
595
+ */
596
+ async function getExtraProps() {
597
+ const extraProps = {};
598
+ return extraProps;
599
+ }
600
+ /**
601
+ * The function run when calling `react-native autolink-windows`.
602
+ * @param args Unprocessed args passed from react-native CLI.
603
+ * @param config Config passed from react-native CLI.
604
+ * @param options Options passed from react-native CLI.
605
+ */
606
+ async function autolinkWindows(args, config, options) {
607
+ await (0, telemetryHelpers_1.startTelemetrySession)('autolink-windows', config, options, (0, telemetryHelpers_1.getDefaultOptions)(config, exports.autolinkOptions), optionSanitizer);
608
+ let autolinkWindowsError;
609
+ try {
610
+ await autolinkWindowsInternal(args, config, options);
611
+ }
612
+ catch (ex) {
613
+ autolinkWindowsError =
614
+ ex instanceof Error ? ex : new Error(String(ex));
615
+ telemetry_1.Telemetry.trackException(autolinkWindowsError);
616
+ }
617
+ await (0, telemetryHelpers_1.endTelemetrySession)(autolinkWindowsError, getExtraProps);
618
+ (0, commandWithProgress_1.setExitProcessWithError)(options.logging, autolinkWindowsError);
619
+ }
620
+ /**
621
+ * Performs auto-linking for RNW native modules and apps.
622
+ * @param args Unprocessed args passed from react-native CLI.
623
+ * @param config Config passed from react-native CLI.
624
+ * @param options Options passed from react-native CLI.
625
+ */
626
+ async function autolinkWindowsInternal(args, config, options) {
627
+ const startTime = perf_hooks_1.performance.now();
628
+ const spinner = (0, commandWithProgress_1.newSpinner)(options.check ? 'Checking auto-linked files...' : 'Auto-linking...');
629
+ try {
630
+ const autolink = new AutolinkWindows(config.project, config.dependencies, options);
631
+ await autolink.run(spinner);
632
+ const endTime = perf_hooks_1.performance.now();
633
+ if (!autolink.areChangesNeeded()) {
634
+ console.log(`${chalk_1.default.green('Success:')} No auto-linking changes necessary. (${Math.round(endTime - startTime)}ms)`);
310
635
  }
311
- else if (checkMode) {
312
- console.log(`${chalk.yellow('Warning:')} Auto-linking changes were necessary but ${chalk.bold('--check')} specified. Run ${chalk.bold("'npx react-native autolink-windows'")} to apply the changes. (${Math.round(endTime - startTime)}ms)`);
313
- exitProcessWithStatusCode(0, verbose);
636
+ else if (options.check) {
637
+ const autolinkCommand = autolink.getAutolinkWindowsCommand();
638
+ console.log(`${chalk_1.default.yellow('Warning:')} Auto-linking changes were necessary but ${chalk_1.default.bold('--check')} specified. Run '${chalk_1.default.bold(`${autolinkCommand}`)}' to apply the changes. (${Math.round(endTime - startTime)}ms)`);
639
+ throw new telemetry_1.CodedError('NeedAutolinking', `Auto-linking changes were necessary but --check was specified. Run '${autolinkCommand}' to apply the changes`);
314
640
  }
315
641
  else {
316
- console.log(`${chalk.green('Success:')} Auto-linking changes completed. (${Math.round(endTime - startTime)}ms)`);
642
+ console.log(`${chalk_1.default.green('Success:')} Auto-linking changes completed. (${Math.round(endTime - startTime)}ms)`);
317
643
  }
318
644
  }
319
645
  catch (e) {
320
646
  spinner.fail();
321
- var endTime = perf_hooks_1.performance.now();
322
- console.log(`${chalk.red('Error:')} ${e.toString()}. (${Math.round(endTime - startTime)}ms)`);
323
- exitProcessWithStatusCode(1, verbose);
647
+ const endTime = perf_hooks_1.performance.now();
648
+ console.log(`${chalk_1.default.red('Error:')} ${e.toString()}. (${Math.round(endTime - startTime)}ms)`);
649
+ throw e;
324
650
  }
325
651
  }
652
+ exports.autolinkWindowsInternal = autolinkWindowsInternal;
653
+ exports.autolinkOptions = [
654
+ {
655
+ name: '--logging',
656
+ description: 'Verbose output logging',
657
+ },
658
+ {
659
+ name: '--check',
660
+ description: 'Only check whether any autolinked files need to change',
661
+ },
662
+ {
663
+ name: '--sln [string]',
664
+ description: "Override the app solution file determined by 'react-native config', e.g. windows\\myApp.sln",
665
+ default: undefined,
666
+ },
667
+ {
668
+ name: '--proj [string]',
669
+ description: "Override the app project file determined by 'react-native config', e.g. windows\\myApp\\myApp.vcxproj",
670
+ default: undefined,
671
+ },
672
+ {
673
+ name: '--no-telemetry',
674
+ description: 'Disables sending telemetry that allows analysis of usage and failures of the react-native-windows CLI',
675
+ },
676
+ ];
677
+ /**
678
+ * Performs auto-linking for RNW native modules and apps.
679
+ */
326
680
  exports.autoLinkCommand = {
327
681
  name: 'autolink-windows',
328
682
  description: 'performs autolinking',
329
- func: updateAutoLink,
330
- options: [
331
- {
332
- name: '--logging',
333
- description: 'Verbose output logging',
334
- default: false,
335
- },
336
- {
337
- name: '--check',
338
- description: 'Only check whether any autolinked files need to change',
339
- default: false,
340
- },
341
- {
342
- name: '--sln [string]',
343
- description: "Override the app solution file determined by 'react-native config', e.g. windows\\myApp.sln",
344
- default: undefined,
345
- },
346
- {
347
- name: '--proj [string]',
348
- description: "Override the app project file determined by 'react-native config', e.g. windows\\myApp\\myApp.vcxproj",
349
- default: undefined,
350
- },
351
- ],
683
+ func: autolinkWindows,
684
+ options: exports.autolinkOptions,
352
685
  };
353
686
  //# sourceMappingURL=autolink.js.map