@react-native-oh/react-native-harmony-cli 0.0.15 → 0.0.23

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 (85) hide show
  1. package/.prettierrc +6 -6
  2. package/dist/assetResolver.js +23 -5
  3. package/dist/codegen/core/Codegen.js +35 -0
  4. package/dist/codegen/core/CodegenError.js +7 -0
  5. package/dist/codegen/core/EventUtils.js +19 -0
  6. package/dist/codegen/core/TypeAnnotationToTS.js +132 -0
  7. package/dist/codegen/core/UberSchema.js +74 -0
  8. package/dist/codegen/core/index.js +21 -0
  9. package/dist/codegen/generators/ComponentCodeGenerator.js +66 -0
  10. package/dist/codegen/generators/NativeModuleCodeGenerator.js +64 -0
  11. package/dist/codegen/generators/PackageCodeGenerator.js +52 -0
  12. package/dist/codegen/generators/index.js +19 -0
  13. package/dist/codegen/index.js +18 -0
  14. package/dist/codegen/templates/ComponentDescriptorHTemplate.js +55 -0
  15. package/dist/codegen/templates/ComponentJSIBinderHTemplate.js +78 -0
  16. package/dist/codegen/templates/ComponentUtilsTSTemplate.js +181 -0
  17. package/dist/codegen/templates/IndexTSTemplate.js +31 -0
  18. package/dist/codegen/templates/RNOHGeneratedPackageHTemplate.js +117 -0
  19. package/dist/codegen/templates/TurboModuleCppTemplate.js +45 -0
  20. package/dist/codegen/templates/TurboModuleHTemplate.js +32 -0
  21. package/dist/codegen/templates/TurboModuleSpecTSTemplate.js +64 -0
  22. package/dist/codegen/templates/index.js +24 -0
  23. package/dist/commands/codegen-harmony.js +110 -0
  24. package/dist/commands/create-metro-host-constants.js +61 -0
  25. package/dist/commands/index.js +2 -0
  26. package/dist/commands/pack-harmony.js +4 -1
  27. package/dist/commands/unpack-harmony.js +86 -43
  28. package/dist/core/AbsolutePath.js +41 -0
  29. package/dist/core/CodegenConfig.js +53 -0
  30. package/dist/core/DescriptiveError.js +49 -0
  31. package/dist/core/PackageJSON.js +53 -0
  32. package/dist/core/ProjectDependenciesManager.js +70 -0
  33. package/dist/core/ValueObject.js +2 -0
  34. package/dist/core/fs.js +36 -0
  35. package/dist/core/index.js +7 -0
  36. package/dist/index.js +7 -1
  37. package/dist/io/Logger.js +71 -0
  38. package/dist/io/fsUtils.js +23 -0
  39. package/dist/io/index.js +18 -0
  40. package/jest.config.js +5 -5
  41. package/package.json +52 -47
  42. package/react-native.config.js +10 -10
  43. package/src/assetResolver.ts +44 -25
  44. package/src/codegen/core/Codegen.ts +44 -0
  45. package/src/codegen/core/CodegenError.ts +3 -0
  46. package/src/codegen/core/EventUtils.ts +18 -0
  47. package/src/codegen/core/TypeAnnotationToTS.test.ts +75 -0
  48. package/src/codegen/core/TypeAnnotationToTS.ts +188 -0
  49. package/src/codegen/core/UberSchema.ts +99 -0
  50. package/src/codegen/core/index.ts +5 -0
  51. package/src/codegen/generators/ComponentCodeGenerator.ts +98 -0
  52. package/src/codegen/generators/NativeModuleCodeGenerator.ts +95 -0
  53. package/src/codegen/generators/PackageCodeGenerator.ts +73 -0
  54. package/src/codegen/generators/index.ts +3 -0
  55. package/src/codegen/index.ts +2 -0
  56. package/src/codegen/templates/ComponentDescriptorHTemplate.ts +49 -0
  57. package/src/codegen/templates/ComponentJSIBinderHTemplate.ts +85 -0
  58. package/src/codegen/templates/ComponentUtilsTSTemplate.ts +202 -0
  59. package/src/codegen/templates/IndexTSTemplate.ts +33 -0
  60. package/src/codegen/templates/RNOHGeneratedPackageHTemplate.ts +124 -0
  61. package/src/codegen/templates/TurboModuleCppTemplate.ts +47 -0
  62. package/src/codegen/templates/TurboModuleHTemplate.ts +26 -0
  63. package/src/codegen/templates/TurboModuleSpecTSTemplate.ts +81 -0
  64. package/src/codegen/templates/index.ts +8 -0
  65. package/src/commands/bundle-harmony.ts +202 -202
  66. package/src/commands/codegen-harmony.ts +143 -0
  67. package/src/commands/create-metro-host-constants.ts +48 -0
  68. package/src/commands/index.ts +5 -3
  69. package/src/commands/pack-harmony.ts +121 -118
  70. package/src/commands/unpack-harmony.ts +231 -156
  71. package/src/core/AbsolutePath.ts +43 -0
  72. package/src/core/CodegenConfig.ts +54 -0
  73. package/src/core/DescriptiveError.ts +61 -0
  74. package/src/core/PackageJSON.ts +63 -0
  75. package/src/core/ProjectDependenciesManager.ts +77 -0
  76. package/src/core/ValidationError.ts +1 -1
  77. package/src/core/ValueObject.ts +2 -0
  78. package/src/core/fs.ts +31 -0
  79. package/src/core/index.ts +8 -1
  80. package/src/index.ts +18 -10
  81. package/src/io/Logger.ts +68 -0
  82. package/src/io/fsUtils.ts +24 -0
  83. package/src/io/index.ts +2 -0
  84. package/tsconfig.build.json +6 -5
  85. package/tsconfig.json +2 -2
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Logger = void 0;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ class Logger {
9
+ info(prepareMsg, options) {
10
+ const prefix = (options === null || options === void 0 ? void 0 : options.prefix) ? `[${chalk_1.default.bold(chalk_1.default.cyan('INFO'))}]` : '';
11
+ if (prefix) {
12
+ console.info(prefix, prepareMsg(chalk_1.default));
13
+ }
14
+ else {
15
+ console.info(prepareMsg(chalk_1.default));
16
+ }
17
+ }
18
+ debug(prepareMsg) {
19
+ console.debug(prepareMsg(chalk_1.default));
20
+ }
21
+ descriptiveError(error) {
22
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
23
+ const lines = [];
24
+ if (error.isUnexpected() && error.stack) {
25
+ lines.push('');
26
+ lines.push(chalk_1.default.bold('Stack'));
27
+ error.stack.split('\n').forEach((line) => lines.push(chalk_1.default.gray(line)));
28
+ }
29
+ const details = error.getDetails();
30
+ if (details) {
31
+ lines.push('');
32
+ lines.push(chalk_1.default.bold('Details'));
33
+ details.split('\n').forEach((line) => lines.push(line));
34
+ }
35
+ lines.push('');
36
+ let prefix = '';
37
+ if (error.isUnexpected()) {
38
+ prefix = '[' + chalk_1.default.red(chalk_1.default.bold('UNEXPECTED_ERROR')) + ']';
39
+ }
40
+ else {
41
+ prefix = '[' + chalk_1.default.red(chalk_1.default.bold('ERROR')) + ']';
42
+ }
43
+ lines.push(`${prefix} ${error.getMessage()}`);
44
+ const suggestionsByRole = error.getSuggestionsByRole();
45
+ if (suggestionsByRole) {
46
+ if (((_b = (_a = suggestionsByRole.default) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0) {
47
+ lines.push('');
48
+ lines.push(chalk_1.default.bold(`Suggestions`));
49
+ (_c = suggestionsByRole.default) === null || _c === void 0 ? void 0 : _c.forEach((suggestion) => {
50
+ lines.push(suggestion);
51
+ });
52
+ }
53
+ if (((_e = (_d = suggestionsByRole.rnAppDeveloper) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0) > 0) {
54
+ lines.push('');
55
+ lines.push(chalk_1.default.bold(`Suggestions for RN App developers`));
56
+ (_f = suggestionsByRole.rnAppDeveloper) === null || _f === void 0 ? void 0 : _f.forEach((suggestion) => {
57
+ lines.push(suggestion);
58
+ });
59
+ }
60
+ if ((_h = (_g = suggestionsByRole.rnPackageDeveloper) === null || _g === void 0 ? void 0 : _g.length) !== null && _h !== void 0 ? _h : 0) {
61
+ lines.push('');
62
+ lines.push(chalk_1.default.bold(`Suggestions for RN package developers`));
63
+ (_j = suggestionsByRole.rnPackageDeveloper) === null || _j === void 0 ? void 0 : _j.forEach((suggestion) => {
64
+ lines.push(suggestion);
65
+ });
66
+ }
67
+ }
68
+ console.error(lines.join('\n'));
69
+ }
70
+ }
71
+ exports.Logger = Logger;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.findFilePathsWithExtensions = void 0;
7
+ const node_path_1 = __importDefault(require("node:path"));
8
+ const node_fs_1 = __importDefault(require("node:fs"));
9
+ function findFilePathsWithExtensions(dirPath, fileExtensions) {
10
+ let results = [];
11
+ const files = node_fs_1.default.readdirSync(dirPath.getValue(), { withFileTypes: true });
12
+ for (const file of files) {
13
+ const path = dirPath.copyWithNewSegment(file.name);
14
+ if (file.isDirectory()) {
15
+ results = results.concat(findFilePathsWithExtensions(path, fileExtensions));
16
+ }
17
+ else if (fileExtensions.includes(node_path_1.default.extname(file.name).substring(1))) {
18
+ results.push(path);
19
+ }
20
+ }
21
+ return results;
22
+ }
23
+ exports.findFilePathsWithExtensions = findFilePathsWithExtensions;
@@ -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/jest.config.js CHANGED
@@ -1,5 +1,5 @@
1
- /** @type {import('ts-jest').JestConfigWithTsJest} */
2
- module.exports = {
3
- preset: 'ts-jest',
4
- testEnvironment: 'node',
5
- };
1
+ /** @type {import('ts-jest').JestConfigWithTsJest} */
2
+ module.exports = {
3
+ preset: 'ts-jest',
4
+ testEnvironment: 'node',
5
+ };
package/package.json CHANGED
@@ -1,47 +1,52 @@
1
- {
2
- "name": "@react-native-oh/react-native-harmony-cli",
3
- "version": "0.0.15",
4
- "description": "",
5
- "publishConfig": {
6
- "registry": "https://registry.npmjs.org/",
7
- "access": "public"
8
- },
9
- "scripts": {
10
- "build": "tsc --outDir dist -p tsconfig.build.json",
11
- "prepack": "npm run build",
12
- "verify": "tsc --noEmit && npm run test",
13
- "test": "npm run build && jest",
14
- "rn": "npm run build && react-native",
15
- "prepublishOnly": "npm run verify"
16
- },
17
- "keywords": [],
18
- "author": "",
19
- "license": "ISC",
20
- "peerDependencies": {
21
- "metro": "*"
22
- },
23
- "main": "dist/index.js",
24
- "devDependencies": {
25
- "@react-native-community/cli-types": "^11.3.0",
26
- "@types/fs-extra": "^11.0.1",
27
- "@types/jest": "^29.5.1",
28
- "@types/tar": "^6.1.5",
29
- "@types/tmp": "^0.2.3",
30
- "directory-tree": "^3.5.1",
31
- "execa": "npm:@esm2cjs/execa@^6.1.1-cjs.1",
32
- "jest": "^29.5.0",
33
- "react-native": "^0.72.0",
34
- "tmp": "^0.2.1",
35
- "ts-jest": "^29.1.0",
36
- "ts-node": "^10.9.1",
37
- "typescript": "^5.0.4"
38
- },
39
- "dependencies": {
40
- "@tsconfig/recommended": "^1.0.2",
41
- "fs-extra": "^11.1.1",
42
- "glob": "^10.2.6",
43
- "ignore": "^5.2.4",
44
- "json5": "^2.2.3",
45
- "tar": "^6.1.15"
46
- }
47
- }
1
+ {
2
+ "name": "@react-native-oh/react-native-harmony-cli",
3
+ "version": "0.0.23",
4
+ "description": "",
5
+ "publishConfig": {
6
+ "registry": "https://registry.npmjs.org/",
7
+ "access": "public"
8
+ },
9
+ "scripts": {
10
+ "build": "tsc --outDir dist -p tsconfig.build.json",
11
+ "prepack": "npm run build",
12
+ "verify": "tsc --noEmit && npm run test",
13
+ "test": "npm run build && jest",
14
+ "test:codegen": "jest ./src/codegen/.* && npm run build && jest tests/codegen.*",
15
+ "rn": "npm run build && react-native",
16
+ "prepublishOnly": "npm run verify"
17
+ },
18
+ "keywords": [],
19
+ "author": "",
20
+ "license": "ISC",
21
+ "peerDependencies": {
22
+ "metro": "*"
23
+ },
24
+ "main": "dist/index.js",
25
+ "devDependencies": {
26
+ "@react-native-community/cli-types": "^11.3.0",
27
+ "@types/fs-extra": "^11.0.1",
28
+ "@types/jest": "^29.5.1",
29
+ "@types/mustache": "^4.2.5",
30
+ "@types/tar": "^6.1.5",
31
+ "@types/tmp": "^0.2.3",
32
+ "directory-tree": "^3.5.1",
33
+ "execa": "npm:@esm2cjs/execa@^6.1.1-cjs.1",
34
+ "jest": "^29.5.0",
35
+ "react-native": "^0.72.0",
36
+ "tmp": "^0.2.1",
37
+ "ts-jest": "^29.1.0",
38
+ "ts-node": "^10.9.1",
39
+ "typescript": "^5.0.4"
40
+ },
41
+ "dependencies": {
42
+ "@react-native/codegen": "0.74.0",
43
+ "@tsconfig/recommended": "^1.0.2",
44
+ "chalk": "^4",
45
+ "fs-extra": "^11.1.1",
46
+ "glob": "^10.2.6",
47
+ "ignore": "^5.2.4",
48
+ "json5": "^2.2.3",
49
+ "mustache": "^4.2.0",
50
+ "tar": "^6.1.15"
51
+ }
52
+ }
@@ -1,10 +1,10 @@
1
- const { config: harmonyConfig } = require('./dist');
2
-
3
- /**
4
- * @type {import("@react-native-community/cli-types").Config}
5
- */
6
- const config = {
7
- commands: harmonyConfig.commands,
8
- };
9
-
10
- module.exports = config;
1
+ const { config: harmonyConfig } = require('./dist');
2
+
3
+ /**
4
+ * @type {import("@react-native-community/cli-types").Config}
5
+ */
6
+ const config = {
7
+ commands: harmonyConfig.commands,
8
+ };
9
+
10
+ module.exports = config;
@@ -1,25 +1,44 @@
1
- import type { AssetData } from 'metro';
2
-
3
- export type Asset = AssetData;
4
-
5
- export function getAssetDestRelativePath(asset: Asset): string {
6
- const fileName = getResourceIdentifier(asset);
7
- return `${fileName}.${asset.type}`;
8
- }
9
-
10
- function getResourceIdentifier(asset: Asset): string {
11
- const folderPath = getBasePath(asset);
12
- return `${folderPath}/${asset.name}`
13
- .toLowerCase()
14
- .replace(/\//g, '_') // Encode folder structure in file name
15
- .replace(/([^a-z0-9_])/g, '') // Remove illegal chars
16
- .replace(/^assets_/, ''); // Remove "assets_" prefix
17
- }
18
-
19
- function getBasePath(asset: Asset): string {
20
- let basePath = asset.httpServerLocation;
21
- if (basePath[0] === '/') {
22
- basePath = basePath.substr(1);
23
- }
24
- return basePath;
25
- }
1
+ import type { AssetData } from 'metro';
2
+
3
+ export type Asset = AssetData;
4
+
5
+ /*
6
+ cyrb53 (c) 2018 bryc (github.com/bryc)
7
+ License: Public domain. Attribution appreciated.
8
+ A fast and simple 53-bit string hash function with decent collision resistance.
9
+ Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
10
+ */
11
+ function cyrb53(str: string, seed = 0) {
12
+ let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
13
+ for(let i = 0, ch; i < str.length; i++) {
14
+ ch = str.charCodeAt(i);
15
+ h1 = Math.imul(h1 ^ ch, 2654435761);
16
+ h2 = Math.imul(h2 ^ ch, 1597334677);
17
+ }
18
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
19
+ h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
20
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
21
+ h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
22
+ return 4294967296 * (2097151 & h2) + (h1 >>> 0);
23
+ };
24
+
25
+
26
+ export function getAssetDestRelativePath(asset: Asset): string {
27
+ const fileName = getResourceIdentifier(asset);
28
+ return `${fileName}.${asset.type}`;
29
+ }
30
+
31
+ function getResourceIdentifier(asset: Asset): string {
32
+ const folderPath = getBasePath(asset);
33
+ const fullAssetPath = `${folderPath}/${asset.name}.${asset.type}`.toLowerCase();
34
+ const assetPathHash = cyrb53(fullAssetPath);
35
+ return assetPathHash.toString(16);
36
+ }
37
+
38
+ function getBasePath(asset: Asset): string {
39
+ let basePath = asset.httpServerLocation;
40
+ if (basePath[0] === '/') {
41
+ basePath = basePath.substr(1);
42
+ }
43
+ return basePath;
44
+ }
@@ -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
+ }