@react-native-windows/codegen 0.0.0-canary.5 → 0.0.0-canary.50

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 (53) hide show
  1. package/CHANGELOG.md +440 -4
  2. package/README.md +1 -1
  3. package/bin.js +0 -0
  4. package/lib-commonjs/Cli.d.ts +7 -0
  5. package/lib-commonjs/Cli.js +74 -0
  6. package/lib-commonjs/Cli.js.map +1 -0
  7. package/lib-commonjs/generators/AliasGen.d.ts +11 -0
  8. package/lib-commonjs/generators/AliasGen.js +72 -0
  9. package/lib-commonjs/generators/AliasGen.js.map +1 -0
  10. package/lib-commonjs/generators/AliasManaging.d.ts +15 -0
  11. package/lib-commonjs/generators/AliasManaging.js +49 -0
  12. package/lib-commonjs/generators/AliasManaging.js.map +1 -0
  13. package/lib-commonjs/generators/GenerateNM2.d.ts +12 -0
  14. package/lib-commonjs/generators/GenerateNM2.js +94 -0
  15. package/lib-commonjs/generators/GenerateNM2.js.map +1 -0
  16. package/lib-commonjs/generators/GenerateTypeScript.d.ts +11 -0
  17. package/lib-commonjs/generators/GenerateTypeScript.js +166 -0
  18. package/lib-commonjs/generators/GenerateTypeScript.js.map +1 -0
  19. package/lib-commonjs/generators/ObjectTypes.d.ts +9 -0
  20. package/lib-commonjs/generators/ObjectTypes.js +73 -0
  21. package/lib-commonjs/generators/ObjectTypes.js.map +1 -0
  22. package/lib-commonjs/generators/ParamTypes.d.ts +11 -0
  23. package/lib-commonjs/generators/ParamTypes.js +135 -0
  24. package/lib-commonjs/generators/ParamTypes.js.map +1 -0
  25. package/lib-commonjs/generators/ReturnTypes.d.ts +9 -0
  26. package/lib-commonjs/generators/ReturnTypes.js +29 -0
  27. package/lib-commonjs/generators/ReturnTypes.js.map +1 -0
  28. package/lib-commonjs/generators/ValidateConstants.d.ts +8 -0
  29. package/lib-commonjs/generators/ValidateConstants.js +38 -0
  30. package/lib-commonjs/generators/ValidateConstants.js.map +1 -0
  31. package/lib-commonjs/generators/ValidateMethods.d.ts +8 -0
  32. package/lib-commonjs/generators/ValidateMethods.js +75 -0
  33. package/lib-commonjs/generators/ValidateMethods.js.map +1 -0
  34. package/lib-commonjs/index.d.ts +39 -0
  35. package/lib-commonjs/index.js +215 -0
  36. package/lib-commonjs/index.js.map +1 -0
  37. package/package.json +37 -19
  38. package/src/Cli.ts +37 -192
  39. package/src/generators/AliasGen.ts +105 -0
  40. package/src/generators/AliasManaging.ts +75 -0
  41. package/src/generators/GenerateNM2.ts +65 -291
  42. package/src/generators/GenerateTypeScript.ts +247 -0
  43. package/src/generators/ObjectTypes.ts +110 -0
  44. package/src/generators/ParamTypes.ts +262 -0
  45. package/src/generators/ReturnTypes.ts +55 -0
  46. package/src/generators/ValidateConstants.ts +50 -0
  47. package/src/generators/ValidateMethods.ts +149 -0
  48. package/src/index.ts +378 -0
  49. package/.eslintrc.js +0 -4
  50. package/.vscode/launch.json +0 -23
  51. package/CHANGELOG.json +0 -477
  52. package/jest.config.js +0 -1
  53. package/tsconfig.json +0 -5
package/src/index.ts ADDED
@@ -0,0 +1,378 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ * Licensed under the MIT License.
4
+ *
5
+ * @format
6
+ */
7
+
8
+ import path from 'path';
9
+ import fs from '@react-native-windows/fs';
10
+ import globby from 'globby';
11
+ import {createNM2Generator} from './generators/GenerateNM2';
12
+ import {
13
+ generateTypeScript,
14
+ setOptionalTurboModule,
15
+ } from './generators/GenerateTypeScript';
16
+ import type {SchemaType} from 'react-native-tscodegen';
17
+
18
+ // Load @react-native/codegen from react-native
19
+ const rnPath = path.dirname(require.resolve('react-native/package.json'));
20
+ const rncodegenPath = path.dirname(
21
+ require.resolve('@react-native/codegen/package.json', {paths: [rnPath]}),
22
+ );
23
+ const FlowParser = require(path.resolve(rncodegenPath, 'lib/parsers/flow'));
24
+ const TypeScriptParser = require(path.resolve(
25
+ rncodegenPath,
26
+ 'lib/parsers/typescript',
27
+ ));
28
+
29
+ const schemaValidator = require(path.resolve(
30
+ rncodegenPath,
31
+ 'lib/schemaValidator',
32
+ ));
33
+
34
+ interface Options {
35
+ libraryName: string;
36
+ methodOnly: boolean;
37
+ modulesCxx: boolean;
38
+ moduleSpecName: string;
39
+ modulesTypeScriptTypes: boolean;
40
+ modulesWindows: boolean;
41
+ namespace: string;
42
+ outputDirectory: string;
43
+ schema: SchemaType;
44
+ }
45
+
46
+ interface Config {
47
+ generators: any[] /*Generators[]*/;
48
+ test?: boolean;
49
+ }
50
+
51
+ function normalizeFileMap(
52
+ map: Map<string, string>,
53
+ outputDir: string,
54
+ outMap: Map<string, string>,
55
+ ): void {
56
+ for (const [fileName, contents] of map) {
57
+ const location = path.join(outputDir, fileName);
58
+ outMap.set(path.normalize(location), contents);
59
+ }
60
+ }
61
+
62
+ function checkFilesForChanges(
63
+ map: Map<string, string>,
64
+ outputDir: string,
65
+ ): boolean {
66
+ let hasChanges = false;
67
+
68
+ outputDir = path.resolve(outputDir);
69
+ const globbyDir = outputDir.replace(/\\/g, '/');
70
+ const allExistingFiles = globby
71
+ .sync([`${globbyDir}/**`, `${globbyDir}/**/.*`], {absolute: true})
72
+ .map(_ => path.normalize(_));
73
+ const allGeneratedFiles = [...map.keys()].map(_ => path.normalize(_)).sort();
74
+
75
+ if (
76
+ allExistingFiles.length !== allGeneratedFiles.length ||
77
+ !allGeneratedFiles.every(filepath =>
78
+ allExistingFiles.includes(
79
+ path.normalize(path.resolve(process.cwd(), filepath)),
80
+ ),
81
+ )
82
+ )
83
+ return true;
84
+
85
+ for (const [fileName, contents] of map) {
86
+ if (!fs.existsSync(fileName)) {
87
+ hasChanges = true;
88
+ continue;
89
+ }
90
+
91
+ const currentContents = fs.readFileSync(fileName, 'utf8');
92
+ if (currentContents !== contents) {
93
+ console.log(`- ${fileName} has changed`);
94
+ hasChanges = true;
95
+ continue;
96
+ }
97
+ }
98
+
99
+ return hasChanges;
100
+ }
101
+
102
+ function writeMapToFiles(map: Map<string, string>, outputDir: string) {
103
+ let success = true;
104
+
105
+ outputDir = path.resolve(outputDir);
106
+ const globbyDir = outputDir.replace(/\\/g, '/');
107
+
108
+ // This ensures that we delete any generated files from modules that have been deleted
109
+ const allExistingFiles = globby.sync(
110
+ [`${globbyDir}/**`, `${globbyDir}/**/.*`],
111
+ {absolute: true},
112
+ );
113
+
114
+ const allGeneratedFiles = [...map.keys()].map(_ => path.normalize(_)).sort();
115
+ allExistingFiles.forEach(existingFile => {
116
+ if (!allGeneratedFiles.includes(path.normalize(existingFile))) {
117
+ console.log('Deleting ', existingFile);
118
+ fs.unlinkSync(existingFile);
119
+ }
120
+ });
121
+
122
+ for (const [fileName, contents] of map) {
123
+ try {
124
+ fs.mkdirSync(path.dirname(fileName), {recursive: true});
125
+
126
+ if (fs.existsSync(fileName)) {
127
+ const currentContents = fs.readFileSync(fileName, 'utf8');
128
+ // Don't update the files if there are no changes as this breaks incremental builds
129
+ if (currentContents === contents) {
130
+ continue;
131
+ }
132
+ }
133
+
134
+ console.log('Writing ', fileName);
135
+ fs.writeFileSync(fileName, contents);
136
+ } catch (error) {
137
+ success = false;
138
+ console.error(`Failed to write ${fileName} to ${fileName}`, error);
139
+ }
140
+ }
141
+
142
+ return success;
143
+ }
144
+
145
+ export function parseFile(filename: string): SchemaType {
146
+ try {
147
+ const isTypeScript =
148
+ path.extname(filename) === '.ts' || path.extname(filename) === '.tsx';
149
+ const contents = fs.readFileSync(filename, 'utf8');
150
+ const schema = isTypeScript
151
+ ? TypeScriptParser.parseString(contents, filename)
152
+ : FlowParser.parseString(contents, filename);
153
+ // there will be at most one turbo module per file
154
+ const moduleName = Object.keys(schema.modules)[0];
155
+ if (moduleName) {
156
+ const spec = schema.modules[moduleName];
157
+ if (spec.type === 'NativeModule') {
158
+ const contents = fs.readFileSync(filename, 'utf8');
159
+ if (contents) {
160
+ // This is a temporary implementation until such information is added to the schema in facebook/react-native
161
+ if (contents.includes('TurboModuleRegistry.get<')) {
162
+ setOptionalTurboModule(spec, true);
163
+ } else if (contents.includes('TurboModuleRegistry.getEnforcing<')) {
164
+ setOptionalTurboModule(spec, false);
165
+ }
166
+ }
167
+ }
168
+ }
169
+ return schema;
170
+ } catch (e) {
171
+ if (e instanceof Error) {
172
+ e.message = `(${filename}): ${e.message}`;
173
+ }
174
+ throw e;
175
+ }
176
+ }
177
+
178
+ export function combineSchemas(files: string[]): SchemaType {
179
+ return files.reduce(
180
+ (merged, filename) => {
181
+ const contents = fs.readFileSync(filename, 'utf8');
182
+ if (
183
+ contents &&
184
+ (/export\s+default\s+\(?codegenNativeComponent</.test(contents) ||
185
+ contents.includes('extends TurboModule'))
186
+ ) {
187
+ const schema = parseFile(filename);
188
+ merged.modules = {...merged.modules, ...schema.modules};
189
+ }
190
+ return merged;
191
+ },
192
+ {modules: {}},
193
+ );
194
+ }
195
+
196
+ export function generate(
197
+ {
198
+ libraryName,
199
+ methodOnly,
200
+ modulesCxx,
201
+ moduleSpecName,
202
+ modulesTypeScriptTypes,
203
+ modulesWindows,
204
+ namespace,
205
+ outputDirectory,
206
+ schema,
207
+ }: Options,
208
+ {/*generators,*/ test}: Config,
209
+ ): boolean {
210
+ schemaValidator.validate(schema);
211
+
212
+ const componentOutputdir = path.join(
213
+ outputDirectory,
214
+ 'react/components',
215
+ libraryName,
216
+ );
217
+
218
+ const generatedFiles = new Map<string, string>();
219
+
220
+ generatedFiles.set(
221
+ path.join(outputDirectory, '.clang-format'),
222
+ 'DisableFormat: true\nSortIncludes: false',
223
+ );
224
+
225
+ const generateNM2 = createNM2Generator({
226
+ methodOnly,
227
+ namespace,
228
+ });
229
+
230
+ const generateJsiModuleH = require(path.resolve(
231
+ rncodegenPath,
232
+ 'lib/generators/modules/GenerateModuleH',
233
+ )).generate;
234
+ const generateJsiModuleCpp = require(path.resolve(
235
+ rncodegenPath,
236
+ 'lib/generators/modules/GenerateModuleCpp',
237
+ )).generate;
238
+ const generatorPropsH = require(path.resolve(
239
+ rncodegenPath,
240
+ 'lib/generators/components/GeneratePropsH',
241
+ )).generate;
242
+ const generatorPropsCPP = require(path.resolve(
243
+ rncodegenPath,
244
+ 'lib/generators/components/GeneratePropsCPP',
245
+ )).generate;
246
+ const generatorShadowNodeH = require(path.resolve(
247
+ rncodegenPath,
248
+ 'lib/generators/components/GenerateShadowNodeH',
249
+ )).generate;
250
+ const generatorShadowNodeCPP = require(path.resolve(
251
+ rncodegenPath,
252
+ 'lib/generators/components/GenerateShadowNodeCPP',
253
+ )).generate;
254
+ const generatorComponentDescriptorH = require(path.resolve(
255
+ rncodegenPath,
256
+ 'lib/generators/components/GenerateComponentDescriptorH',
257
+ )).generate;
258
+ const generatorEventEmitterH = require(path.resolve(
259
+ rncodegenPath,
260
+ 'lib/generators/components/GenerateEventEmitterH',
261
+ )).generate;
262
+ const generatorEventEmitterCPP = require(path.resolve(
263
+ rncodegenPath,
264
+ 'lib/generators/components/GenerateEventEmitterCpp',
265
+ )).generate;
266
+ const generatorStateCPP = require(path.resolve(
267
+ rncodegenPath,
268
+ 'lib/generators/components/GenerateStateCpp',
269
+ )).generate;
270
+ const generatorStateH = require(path.resolve(
271
+ rncodegenPath,
272
+ 'lib/generators/components/GenerateStateH',
273
+ )).generate;
274
+
275
+ const moduleGenerators = [];
276
+
277
+ if (modulesWindows) {
278
+ moduleGenerators.push(generateNM2);
279
+ }
280
+
281
+ if (modulesCxx) {
282
+ moduleGenerators.push(generateJsiModuleH);
283
+ moduleGenerators.push(generateJsiModuleCpp);
284
+ }
285
+
286
+ if (modulesTypeScriptTypes) {
287
+ moduleGenerators.push(generateTypeScript);
288
+ }
289
+
290
+ moduleGenerators.forEach(generator => {
291
+ const generated: Map<string, string> = generator(
292
+ libraryName,
293
+ schema,
294
+ moduleSpecName,
295
+ );
296
+ normalizeFileMap(generated, outputDirectory, generatedFiles);
297
+ });
298
+
299
+ if (
300
+ Object.keys(schema.modules).some(
301
+ moduleName => schema.modules[moduleName].type === 'Component',
302
+ )
303
+ ) {
304
+ const componentGenerators = [
305
+ generatorComponentDescriptorH,
306
+ generatorEventEmitterCPP,
307
+ generatorEventEmitterH,
308
+ generatorPropsCPP,
309
+ generatorPropsH,
310
+ generatorShadowNodeCPP,
311
+ generatorShadowNodeH,
312
+ generatorStateCPP,
313
+ generatorStateH,
314
+ ];
315
+
316
+ componentGenerators.forEach(generator => {
317
+ const generated: Map<string, string> = generator(
318
+ libraryName,
319
+ schema,
320
+ moduleSpecName,
321
+ );
322
+ normalizeFileMap(generated, componentOutputdir, generatedFiles);
323
+ });
324
+ }
325
+
326
+ if (test === true) {
327
+ return checkFilesForChanges(generatedFiles, outputDirectory);
328
+ }
329
+
330
+ return writeMapToFiles(generatedFiles, outputDirectory);
331
+ }
332
+
333
+ export type CodeGenOptions = {
334
+ file?: string;
335
+ files?: string[];
336
+ libraryName: string;
337
+ methodOnly: boolean;
338
+ modulesCxx: boolean;
339
+ modulesTypeScriptTypes: boolean;
340
+ modulesWindows: boolean;
341
+ namespace: string;
342
+ outputDirectory: string;
343
+ test: boolean;
344
+ };
345
+
346
+ export function runCodeGen(options: CodeGenOptions): boolean {
347
+ if (!options.file && !options.files)
348
+ throw new Error('Must specify file or files option');
349
+
350
+ const schema = options.file
351
+ ? parseFile(options.file)
352
+ : combineSchemas(globby.sync(options.files!));
353
+
354
+ const libraryName = options.libraryName;
355
+ const moduleSpecName = 'moduleSpecName';
356
+ const {
357
+ methodOnly,
358
+ modulesCxx,
359
+ modulesTypeScriptTypes,
360
+ modulesWindows,
361
+ namespace,
362
+ outputDirectory,
363
+ } = options;
364
+ return generate(
365
+ {
366
+ libraryName,
367
+ methodOnly,
368
+ modulesCxx,
369
+ moduleSpecName,
370
+ modulesTypeScriptTypes,
371
+ modulesWindows,
372
+ namespace,
373
+ outputDirectory,
374
+ schema,
375
+ },
376
+ {generators: [], test: options.test},
377
+ );
378
+ }
package/.eslintrc.js DELETED
@@ -1,4 +0,0 @@
1
- module.exports = {
2
- extends: ['@rnw-scripts'],
3
- parserOptions: {tsconfigRootDir : __dirname},
4
- };
@@ -1,23 +0,0 @@
1
- {
2
- // Use IntelliSense to learn about possible attributes.
3
- // Hover to view descriptions of existing attributes.
4
- // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
- "version": "0.2.0",
6
- "configurations": [
7
- {
8
- "name": "vscode-jest-tests",
9
- "type": "node",
10
- "request": "launch",
11
- "runtimeArgs": [
12
- "--inspect-brk",
13
- "../../node_modules/jest/bin/jest.js",
14
- "--runInBand",
15
- "--config",
16
- "../@rnw-scripts/jest-debug-config/jest.debug.config.js",
17
- ],
18
- "console": "integratedTerminal",
19
- "internalConsoleOptions": "neverOpen",
20
- "port": 9229,
21
- },
22
- ]
23
- }