@react-native-oh/react-native-harmony-cli 0.0.16 → 0.0.24

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 (77) hide show
  1. package/dist/codegen/core/Codegen.js +35 -0
  2. package/dist/codegen/core/CodegenError.js +7 -0
  3. package/dist/codegen/core/EventUtils.js +19 -0
  4. package/dist/codegen/core/TypeAnnotationToTS.js +132 -0
  5. package/dist/codegen/core/UberSchema.js +74 -0
  6. package/dist/codegen/core/index.js +21 -0
  7. package/dist/codegen/generators/ComponentCodeGenerator.js +66 -0
  8. package/dist/codegen/generators/NativeModuleCodeGenerator.js +64 -0
  9. package/dist/codegen/generators/PackageCodeGenerator.js +52 -0
  10. package/dist/codegen/generators/index.js +19 -0
  11. package/dist/codegen/index.js +18 -0
  12. package/dist/codegen/templates/ComponentDescriptorHTemplate.js +55 -0
  13. package/dist/codegen/templates/ComponentJSIBinderHTemplate.js +78 -0
  14. package/dist/codegen/templates/ComponentUtilsTSTemplate.js +181 -0
  15. package/dist/codegen/templates/IndexTSTemplate.js +31 -0
  16. package/dist/codegen/templates/RNOHGeneratedPackageHTemplate.js +117 -0
  17. package/dist/codegen/templates/TurboModuleCppTemplate.js +45 -0
  18. package/dist/codegen/templates/TurboModuleHTemplate.js +32 -0
  19. package/dist/codegen/templates/TurboModuleSpecTSTemplate.js +64 -0
  20. package/dist/codegen/templates/index.js +24 -0
  21. package/dist/commands/codegen-harmony.js +110 -0
  22. package/dist/commands/create-metro-host-constants.js +61 -0
  23. package/dist/commands/index.js +2 -0
  24. package/dist/commands/pack-harmony.js +4 -1
  25. package/dist/commands/unpack-harmony.js +86 -43
  26. package/dist/core/AbsolutePath.js +41 -0
  27. package/dist/core/CodegenConfig.js +53 -0
  28. package/dist/core/DescriptiveError.js +49 -0
  29. package/dist/core/PackageJSON.js +53 -0
  30. package/dist/core/ProjectDependenciesManager.js +70 -0
  31. package/dist/core/ValueObject.js +2 -0
  32. package/dist/core/fs.js +36 -0
  33. package/dist/core/index.js +7 -0
  34. package/dist/index.js +7 -1
  35. package/dist/io/Logger.js +71 -0
  36. package/dist/io/fsUtils.js +23 -0
  37. package/dist/io/index.js +18 -0
  38. package/package.json +6 -1
  39. package/src/codegen/core/Codegen.ts +44 -0
  40. package/src/codegen/core/CodegenError.ts +3 -0
  41. package/src/codegen/core/EventUtils.ts +18 -0
  42. package/src/codegen/core/TypeAnnotationToTS.test.ts +75 -0
  43. package/src/codegen/core/TypeAnnotationToTS.ts +188 -0
  44. package/src/codegen/core/UberSchema.ts +99 -0
  45. package/src/codegen/core/index.ts +5 -0
  46. package/src/codegen/generators/ComponentCodeGenerator.ts +98 -0
  47. package/src/codegen/generators/NativeModuleCodeGenerator.ts +95 -0
  48. package/src/codegen/generators/PackageCodeGenerator.ts +73 -0
  49. package/src/codegen/generators/index.ts +3 -0
  50. package/src/codegen/index.ts +2 -0
  51. package/src/codegen/templates/ComponentDescriptorHTemplate.ts +49 -0
  52. package/src/codegen/templates/ComponentJSIBinderHTemplate.ts +85 -0
  53. package/src/codegen/templates/ComponentUtilsTSTemplate.ts +202 -0
  54. package/src/codegen/templates/IndexTSTemplate.ts +33 -0
  55. package/src/codegen/templates/RNOHGeneratedPackageHTemplate.ts +124 -0
  56. package/src/codegen/templates/TurboModuleCppTemplate.ts +47 -0
  57. package/src/codegen/templates/TurboModuleHTemplate.ts +26 -0
  58. package/src/codegen/templates/TurboModuleSpecTSTemplate.ts +81 -0
  59. package/src/codegen/templates/index.ts +8 -0
  60. package/src/commands/codegen-harmony.ts +143 -0
  61. package/src/commands/create-metro-host-constants.ts +48 -0
  62. package/src/commands/index.ts +2 -0
  63. package/src/commands/pack-harmony.ts +4 -1
  64. package/src/commands/unpack-harmony.ts +133 -58
  65. package/src/core/AbsolutePath.ts +43 -0
  66. package/src/core/CodegenConfig.ts +54 -0
  67. package/src/core/DescriptiveError.ts +61 -0
  68. package/src/core/PackageJSON.ts +63 -0
  69. package/src/core/ProjectDependenciesManager.ts +77 -0
  70. package/src/core/ValueObject.ts +2 -0
  71. package/src/core/fs.ts +31 -0
  72. package/src/core/index.ts +7 -0
  73. package/src/index.ts +9 -1
  74. package/src/io/Logger.ts +68 -0
  75. package/src/io/fsUtils.ts +24 -0
  76. package/src/io/index.ts +2 -0
  77. package/tsconfig.build.json +2 -1
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./Logger"), exports);
18
+ __exportStar(require("./fsUtils"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@react-native-oh/react-native-harmony-cli",
3
- "version": "0.0.16",
3
+ "version": "0.0.24",
4
4
  "description": "",
5
5
  "publishConfig": {
6
6
  "registry": "https://registry.npmjs.org/",
@@ -11,6 +11,7 @@
11
11
  "prepack": "npm run build",
12
12
  "verify": "tsc --noEmit && npm run test",
13
13
  "test": "npm run build && jest",
14
+ "test:codegen": "jest ./src/codegen/.* && npm run build && jest tests/codegen.*",
14
15
  "rn": "npm run build && react-native",
15
16
  "prepublishOnly": "npm run verify"
16
17
  },
@@ -25,6 +26,7 @@
25
26
  "@react-native-community/cli-types": "^11.3.0",
26
27
  "@types/fs-extra": "^11.0.1",
27
28
  "@types/jest": "^29.5.1",
29
+ "@types/mustache": "^4.2.5",
28
30
  "@types/tar": "^6.1.5",
29
31
  "@types/tmp": "^0.2.3",
30
32
  "directory-tree": "^3.5.1",
@@ -37,11 +39,14 @@
37
39
  "typescript": "^5.0.4"
38
40
  },
39
41
  "dependencies": {
42
+ "@react-native/codegen": "0.74.0",
40
43
  "@tsconfig/recommended": "^1.0.2",
44
+ "chalk": "^4",
41
45
  "fs-extra": "^11.1.1",
42
46
  "glob": "^10.2.6",
43
47
  "ignore": "^5.2.4",
44
48
  "json5": "^2.2.3",
49
+ "mustache": "^4.2.0",
45
50
  "tar": "^6.1.15"
46
51
  }
47
52
  }
@@ -0,0 +1,44 @@
1
+ import { AbsolutePath } from '../../core';
2
+ import { CodegenError } from './CodegenError';
3
+ import { SpecSchema, SpecSchemaType, UberSchema } from './UberSchema';
4
+
5
+ export interface CodeGenerator<T> {
6
+ generate(data: T): Map<AbsolutePath, string>;
7
+ }
8
+
9
+ export interface SpecCodeGenerator extends CodeGenerator<SpecSchema> {}
10
+
11
+ export class Codegen {
12
+ constructor(
13
+ private packageCodeGenerator: CodeGenerator<UberSchema>,
14
+ private codeGeneratorBySpecSchemaType: Record<
15
+ SpecSchemaType,
16
+ SpecCodeGenerator
17
+ >
18
+ ) {}
19
+
20
+ generate(uberSchema: UberSchema): Map<AbsolutePath, string> {
21
+ const result = new Map<AbsolutePath, string>();
22
+ for (const [_fileName, specSchema] of uberSchema
23
+ .getSpecSchemaByFilenameMap()
24
+ .entries()) {
25
+ if (!(specSchema.type in this.codeGeneratorBySpecSchemaType)) {
26
+ throw new CodegenError({
27
+ whatHappened: `Could not find a code generator for a specification of type '${specSchema.type}'`,
28
+ unexpected: true,
29
+ });
30
+ }
31
+ this.codeGeneratorBySpecSchemaType[specSchema.type]
32
+ .generate(specSchema)
33
+ .forEach((fileContent, filePath) => {
34
+ result.set(filePath, fileContent);
35
+ });
36
+ }
37
+ this.packageCodeGenerator
38
+ .generate(uberSchema)
39
+ .forEach((fileContent, filePath) => {
40
+ result.set(filePath, fileContent);
41
+ });
42
+ return result;
43
+ }
44
+ }
@@ -0,0 +1,3 @@
1
+ import { DescriptiveError } from '../../core';
2
+
3
+ export class CodegenError extends DescriptiveError {}
@@ -0,0 +1,18 @@
1
+ import { CodegenError } from './CodegenError';
2
+
3
+ export function createEventNameFromEventHandlerName(
4
+ eventHandlerName: string
5
+ ): string {
6
+ const eventName = eventHandlerName.replace('on', '');
7
+ if (eventName.length === 0) {
8
+ throw new CodegenError({
9
+ whatHappened: `Received invalid event handler name: ${eventHandlerName}`,
10
+ whatCanUserDo: {
11
+ default: [
12
+ 'Change your event listener name to match naming convention "onEventName" e.g. "onPress"',
13
+ ],
14
+ },
15
+ });
16
+ }
17
+ return eventName.charAt(0).toLowerCase() + eventName.slice(1);
18
+ }
@@ -0,0 +1,75 @@
1
+ import { TypeAnnotationToTS, TypeAnnotation } from './TypeAnnotationToTS';
2
+
3
+ function convert(typeAnnotation: TypeAnnotation) {
4
+ return new TypeAnnotationToTS().convert(typeAnnotation);
5
+ }
6
+
7
+ it('should convert boolean prop correctly', () => {
8
+ const result = convert({
9
+ type: 'BooleanTypeAnnotation',
10
+ });
11
+
12
+ expect(result).toBe('boolean');
13
+ });
14
+
15
+ it('should convert string prop correctly', () => {
16
+ const result = convert({
17
+ type: 'StringTypeAnnotation',
18
+ });
19
+
20
+ expect(result).toBe('string');
21
+ });
22
+
23
+ it('should convert double prop correctly', () => {
24
+ const result = convert({
25
+ type: 'DoubleTypeAnnotation',
26
+ });
27
+
28
+ expect(result).toBe('number');
29
+ });
30
+
31
+ it('should convert float prop correctly', () => {
32
+ const result = convert({
33
+ type: 'FloatTypeAnnotation',
34
+ });
35
+
36
+ expect(result).toBe('number');
37
+ });
38
+
39
+ it('should convert object prop correctly', () => {
40
+ const result = convert({
41
+ type: 'ObjectTypeAnnotation',
42
+ properties: [
43
+ {
44
+ typeAnnotation: { type: 'BooleanTypeAnnotation' },
45
+ name: 'booleanTest',
46
+ optional: false,
47
+ },
48
+ {
49
+ typeAnnotation: { type: 'ObjectTypeAnnotation', properties: [] },
50
+ name: 'objectTest',
51
+ optional: true,
52
+ },
53
+ ],
54
+ });
55
+
56
+ expect(result).toBe('{booleanTest: boolean, objectTest?: {}}');
57
+ });
58
+
59
+ it('should convert array correctly', () => {
60
+ const result = convert({
61
+ type: 'ObjectTypeAnnotation',
62
+ properties: [
63
+ {
64
+ typeAnnotation: {
65
+ type: 'ArrayTypeAnnotation',
66
+ elementType: { type: 'StringTypeAnnotation' },
67
+ },
68
+ name: 'arrayTest',
69
+ optional: false,
70
+ },
71
+ ],
72
+ });
73
+
74
+ expect(result).toBe('{arrayTest: string[]}');
75
+ });
@@ -0,0 +1,188 @@
1
+ import {
2
+ BooleanTypeAnnotation,
3
+ DoubleTypeAnnotation,
4
+ FloatTypeAnnotation,
5
+ Int32TypeAnnotation,
6
+ MixedTypeAnnotation,
7
+ ObjectTypeAnnotation,
8
+ PropTypeAnnotation,
9
+ ReservedPropTypeAnnotation,
10
+ ReservedTypeAnnotation,
11
+ StringTypeAnnotation,
12
+ Nullable,
13
+ NativeModuleTypeAnnotation,
14
+ UnionTypeAnnotationMemberType,
15
+ } from '@react-native/codegen/lib/CodegenSchema';
16
+
17
+ type StringEnumTypeAnnotation = {
18
+ readonly type: 'StringEnumTypeAnnotation';
19
+ readonly options: readonly string[];
20
+ };
21
+
22
+ type Int32EnumTypeAnnotation = {
23
+ readonly type: 'Int32EnumTypeAnnotation';
24
+ readonly options: readonly number[];
25
+ };
26
+
27
+ type ArrayTypeAnnotation = {
28
+ readonly type: 'ArrayTypeAnnotation';
29
+ readonly elementType: TypeAnnotation;
30
+ };
31
+
32
+ export type TypeAnnotation =
33
+ | BooleanTypeAnnotation
34
+ | StringTypeAnnotation
35
+ | DoubleTypeAnnotation
36
+ | FloatTypeAnnotation
37
+ | Int32TypeAnnotation
38
+ | ReservedPropTypeAnnotation
39
+ | ReservedTypeAnnotation
40
+ | StringEnumTypeAnnotation
41
+ | Int32EnumTypeAnnotation
42
+ | MixedTypeAnnotation
43
+ | ArrayTypeAnnotation
44
+ | NativeModuleTypeAnnotation
45
+ | Nullable<NativeModuleTypeAnnotation>
46
+ | ObjectTypeAnnotation<TypeAnnotation>;
47
+
48
+ export class TypeAnnotationToTS {
49
+ constructor(private aliasPrefix: string = '') {}
50
+
51
+ convert(typeAnnotation: TypeAnnotation | undefined): string {
52
+ if (!typeAnnotation) {
53
+ return 'unknown';
54
+ }
55
+ switch (typeAnnotation.type) {
56
+ case 'BooleanTypeAnnotation':
57
+ return 'boolean';
58
+ case 'DoubleTypeAnnotation':
59
+ return 'number';
60
+ case 'FloatTypeAnnotation':
61
+ return 'number';
62
+ case 'Int32EnumTypeAnnotation':
63
+ return typeAnnotation.options.join(' | ');
64
+ case 'Int32TypeAnnotation':
65
+ return 'number';
66
+ case 'MixedTypeAnnotation':
67
+ return 'unknown';
68
+ case 'ReservedTypeAnnotation':
69
+ switch (typeAnnotation.name) {
70
+ case 'RootTag':
71
+ return 'Tag';
72
+ default:
73
+ return 'unknown';
74
+ }
75
+ case 'ReservedPropTypeAnnotation':
76
+ switch (typeAnnotation.name) {
77
+ case 'ColorPrimitive':
78
+ return 'ColorValue';
79
+ case 'DimensionPrimitive':
80
+ return 'unknown';
81
+ case 'EdgeInsetsPrimitive':
82
+ return 'unknown';
83
+ case 'ImageRequestPrimitive':
84
+ return 'unknown';
85
+ case 'ImageSourcePrimitive':
86
+ return 'unknown';
87
+ case 'PointPrimitive':
88
+ return 'unknown';
89
+ default:
90
+ return 'unknown';
91
+ }
92
+ case 'StringEnumTypeAnnotation':
93
+ return typeAnnotation.options
94
+ .map((option) => {
95
+ if (typeof option !== 'string') {
96
+ return option;
97
+ }
98
+ return wrapWithQuotes(option);
99
+ })
100
+ .join(' | ');
101
+ case 'StringTypeAnnotation':
102
+ return 'string';
103
+ case 'FunctionTypeAnnotation':
104
+ const { params, returnTypeAnnotation } = typeAnnotation;
105
+ const stringifiedArgs = params
106
+ .map(
107
+ (param) => `${param.name}: ${this.convert(param.typeAnnotation)}`
108
+ )
109
+ .join(', ');
110
+ return `(${stringifiedArgs}) => ${this.convert(returnTypeAnnotation)}`;
111
+
112
+ case 'EnumDeclaration':
113
+ return typeAnnotation.name;
114
+ case 'GenericObjectTypeAnnotation':
115
+ return 'Object';
116
+ case 'TypeAliasTypeAnnotation':
117
+ return this.aliasPrefix + typeAnnotation.name;
118
+ case 'UnionTypeAnnotation':
119
+ return this.convertUnionMemberAnnotation(typeAnnotation.memberType);
120
+ case 'NumberTypeAnnotation':
121
+ return 'number';
122
+ case 'NullableTypeAnnotation':
123
+ return `null | ${this.convert(typeAnnotation.typeAnnotation)}`;
124
+ case 'ObjectTypeAnnotation':
125
+ return this.convertObjectTypeAnnotation(typeAnnotation);
126
+ case 'PromiseTypeAnnotation':
127
+ return `Promise<${this.convert(typeAnnotation.elementType)}>`;
128
+ case 'VoidTypeAnnotation':
129
+ return 'void';
130
+ case 'ArrayTypeAnnotation':
131
+ return `${this.convert(typeAnnotation.elementType)}[]`;
132
+ default:
133
+ return 'unknown';
134
+ }
135
+ }
136
+
137
+ private convertUnionMemberAnnotation(
138
+ memberAnnotation: UnionTypeAnnotationMemberType
139
+ ) {
140
+ switch (memberAnnotation) {
141
+ case 'NumberTypeAnnotation':
142
+ return 'number';
143
+ case 'ObjectTypeAnnotation':
144
+ return 'Object';
145
+ case 'StringTypeAnnotation':
146
+ return 'string';
147
+ }
148
+ }
149
+
150
+ private convertObjectTypeAnnotation(
151
+ objectTypeAnnotation: ObjectTypeAnnotation<
152
+ TypeAnnotation | Nullable<NativeModuleTypeAnnotation>
153
+ >
154
+ ): string {
155
+ const props = objectTypeAnnotation.properties
156
+ .map((prop) => {
157
+ const maybeOptionalSymbol = prop.optional ? '?' : '';
158
+ return `${prop.name}${maybeOptionalSymbol}: ${this.convert(
159
+ prop.typeAnnotation
160
+ )}`;
161
+ })
162
+ .join(', ');
163
+ if (props.length === 0) {
164
+ return '{}';
165
+ }
166
+ return `{${props}}`;
167
+ }
168
+ }
169
+
170
+ export function getStringifiedTSDefaultValueFromPropTypeAnnotation(
171
+ propTypeAnnotation: PropTypeAnnotation
172
+ ): string | null {
173
+ if ('default' in propTypeAnnotation && propTypeAnnotation.default !== null) {
174
+ if (typeof propTypeAnnotation.default === 'string') {
175
+ return wrapWithQuotes(propTypeAnnotation.default);
176
+ }
177
+ return String(propTypeAnnotation.default);
178
+ }
179
+ return null;
180
+ }
181
+
182
+ export function wrapWithQuotes(str: string): string {
183
+ if (str.includes("'")) {
184
+ return `"${str}"`;
185
+ } else {
186
+ return `'${str}'`;
187
+ }
188
+ }
@@ -0,0 +1,99 @@
1
+ import {
2
+ ComponentSchema,
3
+ NativeModuleSchema,
4
+ SchemaType as RawUberSchema,
5
+ } from '@react-native/codegen/lib/CodegenSchema';
6
+ import {
7
+ AbsolutePath,
8
+ ValueObject,
9
+ PackageJSON,
10
+ ProjectDependenciesManager,
11
+ CodegenConfig,
12
+ } from '../../core';
13
+ // @ts-expect-error
14
+ import extractUberSchemaFromSpecFilePaths_ from '@react-native/codegen/lib/cli/combine/combine-js-to-schema.js';
15
+ import { CodegenError } from './CodegenError';
16
+
17
+ function createRawUberSchemaFromSpecFilePaths(
18
+ projectSourceFilePaths: AbsolutePath[]
19
+ ): RawUberSchema {
20
+ return extractUberSchemaFromSpecFilePaths_(
21
+ projectSourceFilePaths.map((p) => p.getValue())
22
+ );
23
+ }
24
+
25
+ export type SpecSchema = ComponentSchema | NativeModuleSchema;
26
+ export type SpecSchemaType = SpecSchema['type'];
27
+ type FindSpecSchemaByType<
28
+ TType extends SpecSchemaType,
29
+ TSpecSchema = SpecSchema
30
+ > = TSpecSchema extends { type: TType } ? TSpecSchema : never;
31
+
32
+ export class UberSchema implements ValueObject {
33
+ static async fromProjectRootPath(
34
+ projectRootPath: AbsolutePath
35
+ ): Promise<UberSchema> {
36
+ const packageJSON = PackageJSON.fromProjectRootPath(
37
+ projectRootPath,
38
+ projectRootPath
39
+ );
40
+ const codegenConfigs: CodegenConfig[] = [];
41
+ const appCodegenConfig = packageJSON.maybeCreateCodegenConfig();
42
+ if (appCodegenConfig) {
43
+ codegenConfigs.push(appCodegenConfig);
44
+ }
45
+ await new ProjectDependenciesManager(projectRootPath).forEachAsync(
46
+ (dependency) => {
47
+ const codegenConfig = dependency.maybeCreateCodegenConfig();
48
+ if (codegenConfig) {
49
+ codegenConfigs.push(codegenConfig);
50
+ }
51
+ }
52
+ );
53
+ try {
54
+ return new UberSchema(
55
+ createRawUberSchemaFromSpecFilePaths(
56
+ codegenConfigs.flatMap((codegenConfig) =>
57
+ codegenConfig.getSpecFilePaths()
58
+ )
59
+ )
60
+ );
61
+ } catch (err) {
62
+ if (err instanceof Error) {
63
+ throw new CodegenError({
64
+ whatHappened: "Couldn't create the schema",
65
+ whatCanUserDo: {
66
+ default: [
67
+ `There's probably at least one spec file defined in your project or in a third-party package that breaks some code generation restrictions. Please check the message below. If it's ambiguous, debug the problem with divide and conquer strategy.\n\n${err.message}`,
68
+ ],
69
+ },
70
+ });
71
+ }
72
+ throw err;
73
+ }
74
+ }
75
+
76
+ private constructor(private schemaValue: RawUberSchema) {}
77
+
78
+ getValue(): RawUberSchema {
79
+ return this.schemaValue;
80
+ }
81
+
82
+ findAllSpecSchemasByType<TSpecSchemaType extends SpecSchemaType>(
83
+ schemaType: TSpecSchemaType
84
+ ): FindSpecSchemaByType<TSpecSchemaType>[] {
85
+ return Object.values(this.schemaValue.modules)
86
+ .filter((module) => module.type === schemaType)
87
+ .map((module) => module as FindSpecSchemaByType<TSpecSchemaType>);
88
+ }
89
+
90
+ getSpecSchemaByFilenameMap(): ReadonlyMap<string, SpecSchema> {
91
+ return Object.entries(this.schemaValue.modules).reduce(
92
+ (acc, [moduleName, moduleSchema]) => {
93
+ acc.set(moduleName, moduleSchema);
94
+ return acc;
95
+ },
96
+ new Map<string, SpecSchema>()
97
+ );
98
+ }
99
+ }
@@ -0,0 +1,5 @@
1
+ export * from './Codegen';
2
+ export * from './UberSchema';
3
+ export * from './CodegenError';
4
+ export * from './EventUtils';
5
+ export * from './TypeAnnotationToTS';
@@ -0,0 +1,98 @@
1
+ import { AbsolutePath } from '../../core';
2
+ import {
3
+ CodegenError,
4
+ TypeAnnotationToTS,
5
+ createEventNameFromEventHandlerName,
6
+ getStringifiedTSDefaultValueFromPropTypeAnnotation,
7
+ } from '../core';
8
+ import type { SpecCodeGenerator } from '../core';
9
+ import { SpecSchema } from '../core';
10
+ import {
11
+ ComponentDescriptorHTemplate,
12
+ ComponentJSIBinderHTemplate,
13
+ ComponentUtilsTSTemplate,
14
+ } from '../templates';
15
+
16
+ export class ComponentCodeGenerator implements SpecCodeGenerator {
17
+ constructor(
18
+ private cppOutputPath: AbsolutePath,
19
+ private tsOutputPath: AbsolutePath
20
+ ) {}
21
+
22
+ generate(schema: SpecSchema): Map<AbsolutePath, string> {
23
+ if (schema.type !== 'Component') {
24
+ throw new CodegenError({
25
+ whatHappened: `ComponentCodeGenerator can't generate code for a module type: ${schema.type}`,
26
+ unexpected: true,
27
+ });
28
+ }
29
+ const typeAnnotationToTS = new TypeAnnotationToTS();
30
+ const result = new Map<AbsolutePath, string>();
31
+ Object.entries(schema.components).map(([name, shape]) => {
32
+ const componentDescriptorHTemplate = new ComponentDescriptorHTemplate(
33
+ name
34
+ );
35
+ const componentJSIBinderHTemplate = new ComponentJSIBinderHTemplate(name);
36
+ const componentUtilsTSTemplate = new ComponentUtilsTSTemplate(name);
37
+
38
+ shape.props.forEach((prop) => {
39
+ componentJSIBinderHTemplate.addProp({
40
+ name: prop.name,
41
+ isObject: prop.typeAnnotation.type === 'ObjectTypeAnnotation',
42
+ });
43
+
44
+ componentUtilsTSTemplate.addProp({
45
+ name: prop.name,
46
+ tsType: typeAnnotationToTS.convert(prop.typeAnnotation),
47
+ defaultValue: getStringifiedTSDefaultValueFromPropTypeAnnotation(
48
+ prop.typeAnnotation
49
+ ),
50
+ isOptional: prop.optional,
51
+ });
52
+ });
53
+
54
+ shape.commands.forEach((command) => {
55
+ componentUtilsTSTemplate.addCommand({
56
+ name: command.name,
57
+ argsTSType:
58
+ '[' +
59
+ command.typeAnnotation.params
60
+ .map(
61
+ (param) =>
62
+ typeAnnotationToTS.convert(param.typeAnnotation) +
63
+ (param.optional ? '?' : '')
64
+ )
65
+ .join(', ') +
66
+ ']',
67
+ });
68
+ });
69
+
70
+ shape.events.forEach((event) => {
71
+ componentUtilsTSTemplate.addEvent({
72
+ name: createEventNameFromEventHandlerName(event.name),
73
+ payloadTSType: event.typeAnnotation.argument
74
+ ? typeAnnotationToTS.convert(event.typeAnnotation.argument)
75
+ : 'undefined',
76
+ });
77
+ componentJSIBinderHTemplate.addEvent({
78
+ type: event.bubblingType,
79
+ eventHandlerName: event.name,
80
+ });
81
+ });
82
+
83
+ result.set(
84
+ this.cppOutputPath.copyWithNewSegment(`${name}ComponentDescriptor.h`),
85
+ componentDescriptorHTemplate.build()
86
+ );
87
+ result.set(
88
+ this.cppOutputPath.copyWithNewSegment(`${name}JSIBinder.h`),
89
+ componentJSIBinderHTemplate.build()
90
+ );
91
+ result.set(
92
+ this.tsOutputPath.copyWithNewSegment(`${name}.ts`),
93
+ componentUtilsTSTemplate.build()
94
+ );
95
+ });
96
+ return result;
97
+ }
98
+ }
@@ -0,0 +1,95 @@
1
+ import { AbsolutePath } from '../../core';
2
+ import type { SpecCodeGenerator } from '../core/Codegen';
3
+ import { CodegenError } from '../core/CodegenError';
4
+ import {
5
+ TurboModuleCppTemplate,
6
+ TurboModuleHTemplate,
7
+ TurboModuleInterfaceTS,
8
+ } from '../templates';
9
+ import { SpecSchema } from '../core/UberSchema';
10
+ import { TypeAnnotationToTS, wrapWithQuotes } from '../core';
11
+
12
+ export class NativeModuleCodeGenerator implements SpecCodeGenerator {
13
+ constructor(
14
+ private cppOutputPath: AbsolutePath,
15
+ private etsOutputPath: AbsolutePath
16
+ ) {}
17
+
18
+ generate(schema: SpecSchema): Map<AbsolutePath, string> {
19
+ const result = new Map<AbsolutePath, string>();
20
+ if (schema.type !== 'NativeModule') {
21
+ throw new CodegenError({
22
+ whatHappened: `NativeModuleCodeGenerator can't generate code for module type: ${schema.type}`,
23
+ unexpected: true,
24
+ });
25
+ }
26
+ const typeAnnotationToTS = new TypeAnnotationToTS();
27
+ const turboModuleInterfaceTS = new TurboModuleInterfaceTS(
28
+ schema.moduleName
29
+ );
30
+ const turboModuleH = new TurboModuleHTemplate(schema.moduleName).build();
31
+ result.set(
32
+ this.cppOutputPath.copyWithNewSegment(`${schema.moduleName}.h`),
33
+ turboModuleH
34
+ );
35
+
36
+ const turboModuleCpp = new TurboModuleCppTemplate(schema.moduleName);
37
+
38
+ Object.entries(schema.aliasMap).map(([name, typeAnnotation]) => {
39
+ turboModuleInterfaceTS.addAlias({
40
+ name: name,
41
+ type: typeAnnotationToTS.convert(typeAnnotation),
42
+ });
43
+ });
44
+
45
+ Object.entries(schema.enumMap).map(([name, enumSpec]) => {
46
+ turboModuleInterfaceTS.addEnum({
47
+ name,
48
+ members: enumSpec.members.map((member) => ({
49
+ name: member.name,
50
+ value:
51
+ typeof member.value === 'string'
52
+ ? wrapWithQuotes(member.value)
53
+ : member.value.toString(),
54
+ })),
55
+ });
56
+ });
57
+
58
+ schema.spec.properties.map((prop) => {
59
+ if (prop.typeAnnotation.type === 'FunctionTypeAnnotation') {
60
+ turboModuleCpp.addMethod({
61
+ name: prop.name,
62
+ argsCount: prop.typeAnnotation.params.length,
63
+ isAsync:
64
+ prop.typeAnnotation.returnTypeAnnotation.type ===
65
+ 'PromiseTypeAnnotation',
66
+ });
67
+
68
+ turboModuleInterfaceTS.addMethod({
69
+ name: prop.name,
70
+ returnType: typeAnnotationToTS.convert(
71
+ prop.typeAnnotation.returnTypeAnnotation
72
+ ),
73
+ stringifiedArgs: prop.typeAnnotation.params
74
+ .map(
75
+ (param) =>
76
+ `${param.name}: ${typeAnnotationToTS.convert(
77
+ param.typeAnnotation
78
+ )}`
79
+ )
80
+ .join(', '),
81
+ });
82
+ }
83
+ });
84
+ result.set(
85
+ this.cppOutputPath.copyWithNewSegment(`${schema.moduleName}.cpp`),
86
+ turboModuleCpp.build()
87
+ );
88
+ result.set(
89
+ this.etsOutputPath.copyWithNewSegment(`${schema.moduleName}.ts`),
90
+ turboModuleInterfaceTS.build()
91
+ );
92
+
93
+ return result;
94
+ }
95
+ }