nitrogen 0.2.24 → 0.29.5

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 (241) hide show
  1. package/README.md +18 -108
  2. package/lib/Logger.js +56 -0
  3. package/lib/autolinking/Autolinking.js +1 -0
  4. package/lib/autolinking/android/createCMakeExtension.js +109 -0
  5. package/lib/autolinking/android/createGradleExtension.js +36 -0
  6. package/lib/autolinking/android/createHybridObjectInitializer.js +159 -0
  7. package/lib/autolinking/createAndroidAutolinking.js +13 -0
  8. package/lib/autolinking/createIOSAutolinking.js +19 -0
  9. package/lib/autolinking/ios/createHybridObjectInitializer.js +97 -0
  10. package/lib/autolinking/ios/createPodspecRubyExtension.js +69 -0
  11. package/lib/autolinking/ios/createSwiftCxxBridge.js +117 -0
  12. package/lib/autolinking/ios/createSwiftUmbrellaHeader.js +74 -0
  13. package/lib/config/NitroConfig.js +112 -0
  14. package/lib/config/NitroUserConfig.js +88 -0
  15. package/lib/config/getConfig.js +84 -0
  16. package/lib/createGitAttributes.js +11 -0
  17. package/lib/createPlatformSpec.js +127 -0
  18. package/lib/getFiles.js +28 -0
  19. package/lib/getPlatformSpecs.js +153 -0
  20. package/lib/index.js +113 -10
  21. package/lib/init.js +123 -0
  22. package/lib/nitrogen.js +165 -0
  23. package/lib/prettifyDirectory.js +27 -0
  24. package/lib/syntax/BridgedType.js +1 -0
  25. package/lib/syntax/CodeNode.js +1 -0
  26. package/lib/syntax/HybridObjectSpec.js +1 -0
  27. package/lib/syntax/Method.js +108 -0
  28. package/lib/syntax/Parameter.js +65 -0
  29. package/lib/syntax/Property.js +147 -0
  30. package/lib/syntax/SourceFile.js +7 -0
  31. package/lib/syntax/c++/CppEnum.js +110 -0
  32. package/lib/syntax/c++/CppHybridObject.js +146 -0
  33. package/lib/syntax/c++/CppHybridObjectRegistration.js +18 -0
  34. package/lib/syntax/c++/CppStruct.js +108 -0
  35. package/lib/syntax/c++/CppUnion.js +88 -0
  36. package/lib/syntax/c++/getForwardDeclaration.js +14 -0
  37. package/lib/syntax/c++/includeNitroHeader.js +34 -0
  38. package/lib/syntax/createType.js +303 -0
  39. package/lib/syntax/getAllTypes.js +11 -0
  40. package/lib/syntax/getCustomTypeConfig.js +53 -0
  41. package/lib/syntax/getHybridObjectName.d.ts +36 -0
  42. package/lib/syntax/getHybridObjectName.js +10 -0
  43. package/lib/syntax/getInterfaceProperties.js +9 -0
  44. package/lib/syntax/getReferencedTypes.js +47 -0
  45. package/lib/syntax/helpers.js +53 -0
  46. package/lib/syntax/isCoreType.js +47 -0
  47. package/lib/syntax/kotlin/FbjniHybridObject.js +261 -0
  48. package/lib/syntax/kotlin/JNINativeRegistrations.js +7 -0
  49. package/lib/syntax/kotlin/KotlinBoxedPrimitive.js +17 -0
  50. package/lib/syntax/kotlin/KotlinCxxBridgedType.js +893 -0
  51. package/lib/syntax/kotlin/KotlinEnum.js +113 -0
  52. package/lib/syntax/kotlin/KotlinFunction.js +256 -0
  53. package/lib/syntax/kotlin/KotlinHybridObject.js +177 -0
  54. package/lib/syntax/kotlin/KotlinHybridObjectRegistration.js +26 -0
  55. package/lib/syntax/kotlin/KotlinStruct.js +172 -0
  56. package/lib/syntax/kotlin/KotlinVariant.js +191 -0
  57. package/lib/syntax/swift/SwiftCxxBridgedType.js +819 -0
  58. package/lib/syntax/swift/SwiftCxxTypeHelper.js +613 -0
  59. package/lib/syntax/swift/SwiftEnum.js +52 -0
  60. package/lib/syntax/swift/SwiftFunction.js +83 -0
  61. package/lib/syntax/swift/SwiftHybridObject.js +103 -0
  62. package/lib/syntax/swift/SwiftHybridObjectBridge.js +451 -0
  63. package/lib/syntax/swift/SwiftHybridObjectRegistration.js +42 -0
  64. package/lib/syntax/swift/SwiftStruct.js +75 -0
  65. package/lib/syntax/swift/SwiftVariant.js +58 -0
  66. package/lib/syntax/types/ArrayBufferType.js +37 -0
  67. package/lib/syntax/types/ArrayType.d.ts +12 -0
  68. package/lib/syntax/types/ArrayType.js +52 -0
  69. package/lib/syntax/types/BigIntType.js +27 -0
  70. package/lib/syntax/types/BooleanType.js +27 -0
  71. package/lib/syntax/types/CustomType.d.ts +14 -0
  72. package/lib/syntax/types/CustomType.js +36 -0
  73. package/lib/syntax/types/DateType.js +35 -0
  74. package/lib/syntax/types/EnumType.js +101 -0
  75. package/lib/syntax/types/ErrorType.js +37 -0
  76. package/lib/syntax/types/FunctionType.js +147 -0
  77. package/lib/syntax/types/HybridObjectBaseType.js +38 -0
  78. package/lib/syntax/types/HybridObjectType.js +131 -0
  79. package/lib/syntax/types/MapType.js +37 -0
  80. package/lib/syntax/types/NamedWrappingType.js +27 -0
  81. package/lib/syntax/types/NullType.js +23 -0
  82. package/lib/syntax/types/NumberType.js +27 -0
  83. package/lib/syntax/types/OptionalType.js +59 -0
  84. package/lib/syntax/types/PromiseType.js +62 -0
  85. package/lib/syntax/types/RecordType.js +47 -0
  86. package/lib/syntax/types/ResultWrappingType.js +44 -0
  87. package/lib/syntax/types/StringType.js +35 -0
  88. package/lib/syntax/types/StructType.js +61 -0
  89. package/lib/syntax/types/TupleType.js +39 -0
  90. package/lib/syntax/types/Type.js +1 -0
  91. package/lib/syntax/types/VariantType.js +75 -0
  92. package/lib/syntax/types/VoidType.js +27 -0
  93. package/lib/syntax/types/getTypeAs.js +12 -0
  94. package/lib/utils.js +126 -0
  95. package/lib/views/CppHybridViewComponent.js +256 -0
  96. package/lib/views/createHostComponentJs.js +27 -0
  97. package/lib/views/kotlin/KotlinHybridViewManager.js +229 -0
  98. package/lib/views/swift/SwiftHybridViewManager.js +131 -0
  99. package/lib/writeFile.js +19 -0
  100. package/package.json +58 -29
  101. package/src/Logger.ts +63 -0
  102. package/src/autolinking/Autolinking.ts +9 -0
  103. package/src/autolinking/android/createCMakeExtension.ts +126 -0
  104. package/src/autolinking/android/createGradleExtension.ts +43 -0
  105. package/src/autolinking/android/createHybridObjectInitializer.ts +174 -0
  106. package/src/autolinking/createAndroidAutolinking.ts +28 -0
  107. package/src/autolinking/createIOSAutolinking.ts +24 -0
  108. package/src/autolinking/ios/createHybridObjectInitializer.ts +112 -0
  109. package/src/autolinking/ios/createPodspecRubyExtension.ts +76 -0
  110. package/src/autolinking/ios/createSwiftCxxBridge.ts +137 -0
  111. package/src/autolinking/ios/createSwiftUmbrellaHeader.ts +90 -0
  112. package/src/config/NitroConfig.ts +139 -0
  113. package/src/config/NitroUserConfig.ts +105 -0
  114. package/src/config/getConfig.ts +91 -0
  115. package/src/createGitAttributes.ts +15 -0
  116. package/src/createPlatformSpec.ts +176 -0
  117. package/src/getFiles.ts +31 -0
  118. package/src/getPlatformSpecs.ts +202 -0
  119. package/src/index.ts +146 -0
  120. package/src/init.ts +186 -0
  121. package/src/nitrogen.ts +246 -0
  122. package/src/prettifyDirectory.ts +32 -0
  123. package/src/syntax/BridgedType.ts +59 -0
  124. package/src/syntax/CodeNode.ts +24 -0
  125. package/src/syntax/HybridObjectSpec.ts +14 -0
  126. package/src/syntax/Method.ts +154 -0
  127. package/src/syntax/Parameter.ts +81 -0
  128. package/src/syntax/Property.ts +203 -0
  129. package/src/syntax/SourceFile.ts +80 -0
  130. package/src/syntax/c++/CppEnum.ts +128 -0
  131. package/src/syntax/c++/CppHybridObject.ts +165 -0
  132. package/src/syntax/c++/CppHybridObjectRegistration.ts +39 -0
  133. package/src/syntax/c++/CppStruct.ts +129 -0
  134. package/src/syntax/c++/CppUnion.ts +105 -0
  135. package/src/syntax/c++/getForwardDeclaration.ts +19 -0
  136. package/src/syntax/c++/includeNitroHeader.ts +40 -0
  137. package/src/syntax/createType.ts +365 -0
  138. package/src/syntax/getAllTypes.ts +18 -0
  139. package/src/syntax/getCustomTypeConfig.ts +71 -0
  140. package/src/syntax/getHybridObjectName.ts +48 -0
  141. package/src/syntax/getInterfaceProperties.ts +21 -0
  142. package/src/syntax/getReferencedTypes.ts +57 -0
  143. package/src/syntax/helpers.ts +79 -0
  144. package/src/syntax/isCoreType.ts +60 -0
  145. package/src/syntax/kotlin/FbjniHybridObject.ts +313 -0
  146. package/src/syntax/kotlin/JNINativeRegistrations.ts +19 -0
  147. package/src/syntax/kotlin/KotlinBoxedPrimitive.ts +19 -0
  148. package/src/syntax/kotlin/KotlinCxxBridgedType.ts +942 -0
  149. package/src/syntax/kotlin/KotlinEnum.ts +130 -0
  150. package/src/syntax/kotlin/KotlinFunction.ts +277 -0
  151. package/src/syntax/kotlin/KotlinHybridObject.ts +205 -0
  152. package/src/syntax/kotlin/KotlinHybridObjectRegistration.ts +51 -0
  153. package/src/syntax/kotlin/KotlinStruct.ts +198 -0
  154. package/src/syntax/kotlin/KotlinVariant.ts +212 -0
  155. package/src/syntax/swift/SwiftCxxBridgedType.ts +874 -0
  156. package/src/syntax/swift/SwiftCxxTypeHelper.ts +674 -0
  157. package/src/syntax/swift/SwiftEnum.ts +65 -0
  158. package/src/syntax/swift/SwiftFunction.ts +91 -0
  159. package/src/syntax/swift/SwiftHybridObject.ts +121 -0
  160. package/src/syntax/swift/SwiftHybridObjectBridge.ts +522 -0
  161. package/src/syntax/swift/SwiftHybridObjectRegistration.ts +75 -0
  162. package/src/syntax/swift/SwiftStruct.ts +85 -0
  163. package/src/syntax/swift/SwiftVariant.ts +67 -0
  164. package/src/syntax/types/ArrayBufferType.ts +49 -0
  165. package/src/syntax/types/ArrayType.ts +62 -0
  166. package/src/syntax/types/BigIntType.ts +35 -0
  167. package/src/syntax/types/BooleanType.ts +35 -0
  168. package/src/syntax/types/CustomType.ts +47 -0
  169. package/src/syntax/types/DateType.ts +43 -0
  170. package/src/syntax/types/EnumType.ts +130 -0
  171. package/src/syntax/types/ErrorType.ts +44 -0
  172. package/src/syntax/types/FunctionType.ts +167 -0
  173. package/src/syntax/types/HybridObjectBaseType.ts +54 -0
  174. package/src/syntax/types/HybridObjectType.ts +198 -0
  175. package/src/syntax/types/MapType.ts +49 -0
  176. package/src/syntax/types/NamedWrappingType.ts +33 -0
  177. package/src/syntax/types/NullType.ts +30 -0
  178. package/src/syntax/types/NumberType.ts +34 -0
  179. package/src/syntax/types/OptionalType.ts +66 -0
  180. package/src/syntax/types/PromiseType.ts +72 -0
  181. package/src/syntax/types/RecordType.ts +56 -0
  182. package/src/syntax/types/ResultWrappingType.ts +53 -0
  183. package/src/syntax/types/StringType.ts +44 -0
  184. package/src/syntax/types/StructType.ts +83 -0
  185. package/src/syntax/types/TupleType.ts +53 -0
  186. package/src/syntax/types/Type.ts +82 -0
  187. package/src/syntax/types/VariantType.ts +92 -0
  188. package/src/syntax/types/VoidType.ts +34 -0
  189. package/src/syntax/types/getTypeAs.ts +15 -0
  190. package/src/utils.ts +162 -0
  191. package/src/views/CppHybridViewComponent.ts +304 -0
  192. package/src/views/createHostComponentJs.ts +34 -0
  193. package/src/views/kotlin/KotlinHybridViewManager.ts +258 -0
  194. package/src/views/swift/SwiftHybridViewManager.ts +153 -0
  195. package/src/writeFile.ts +27 -0
  196. package/.jshintignore +0 -6
  197. package/.jshintrc +0 -3
  198. package/.npmignore +0 -3
  199. package/.travis.yml +0 -13
  200. package/LICENSE +0 -13
  201. package/browser/nitrogen-min.js +0 -3
  202. package/browser/nitrogen.js +0 -6369
  203. package/lib/apiKey.js +0 -67
  204. package/lib/blob.js +0 -57
  205. package/lib/commandManager.js +0 -350
  206. package/lib/device.js +0 -19
  207. package/lib/memoryStore.js +0 -24
  208. package/lib/message.js +0 -298
  209. package/lib/permission.js +0 -121
  210. package/lib/principal.js +0 -330
  211. package/lib/service.js +0 -347
  212. package/lib/session.js +0 -494
  213. package/lib/user.js +0 -20
  214. package/publish +0 -2
  215. package/scripts/build-documentation +0 -4
  216. package/scripts/build-module +0 -27
  217. package/scripts/module.js +0 -12
  218. package/scripts/postamble.js +0 -1
  219. package/scripts/preamble.js +0 -2
  220. package/scripts/run-test-server +0 -9
  221. package/test/config.js +0 -12
  222. package/test/fixtures/images/image.jpg +0 -0
  223. package/test/fixtures/images/motion0.jpg +0 -0
  224. package/test/fixtures/images/motion1.jpg +0 -0
  225. package/test/fixtures/images/motion2.jpg +0 -0
  226. package/test/fixtures/index.js +0 -76
  227. package/test/main.js +0 -5
  228. package/test/memoryStore.js +0 -22
  229. package/test/mocha.opts +0 -3
  230. package/test/units/apiKey.js +0 -46
  231. package/test/units/blob.js +0 -35
  232. package/test/units/commandManager.js +0 -67
  233. package/test/units/device.js +0 -26
  234. package/test/units/heartbeat.js +0 -28
  235. package/test/units/message.js +0 -79
  236. package/test/units/permissions.js +0 -43
  237. package/test/units/principal.js +0 -116
  238. package/test/units/service.js +0 -92
  239. package/test/units/session.js +0 -97
  240. package/test/units/user.js +0 -48
  241. package/yuidoc.json +0 -8
@@ -0,0 +1,28 @@
1
+ import { Dirent, promises as fs } from 'fs';
2
+ import path from 'path';
3
+ function getFilePath(file, rootDir) {
4
+ const dir = file.parentPath ?? file.path ?? rootDir;
5
+ return path.join(dir, file.name);
6
+ }
7
+ export async function getFiles(directory) {
8
+ try {
9
+ const files = await fs.readdir(directory, {
10
+ recursive: true,
11
+ withFileTypes: true,
12
+ });
13
+ return files.filter((f) => f.isFile()).map((f) => getFilePath(f, directory));
14
+ }
15
+ catch (error) {
16
+ if (typeof error === 'object' &&
17
+ error != null &&
18
+ 'code' in error &&
19
+ error.code === 'ENOENT') {
20
+ // directory does not exist
21
+ return [];
22
+ }
23
+ else {
24
+ // different error
25
+ throw error;
26
+ }
27
+ }
28
+ }
@@ -0,0 +1,153 @@
1
+ import { Node, Symbol } from 'ts-morph';
2
+ import { getBaseTypes } from './utils.js';
3
+ const platformLanguages = {
4
+ ios: ['swift', 'c++'],
5
+ android: ['kotlin', 'c++'],
6
+ };
7
+ const allPlatforms = Object.keys(platformLanguages);
8
+ const allLanguages = Object.values(platformLanguages).flatMap((l) => l);
9
+ function isValidLanguage(language) {
10
+ if (language == null) {
11
+ return false;
12
+ }
13
+ return allLanguages.includes(language);
14
+ }
15
+ function isValidPlatform(platform) {
16
+ return allPlatforms.includes(platform);
17
+ }
18
+ function getLiteralValue(symbol) {
19
+ const value = symbol.getValueDeclaration();
20
+ if (value == null) {
21
+ return undefined;
22
+ }
23
+ const type = value.getType();
24
+ const literal = type.getLiteralValue();
25
+ if (typeof literal === 'string') {
26
+ return literal;
27
+ }
28
+ return undefined;
29
+ }
30
+ // TODO: The type casting result here doesn't really work in TS.
31
+ function isValidLanguageForPlatform(language, platform) {
32
+ return platformLanguages[platform].includes(language);
33
+ }
34
+ function getPlatformSpec(typeName, platformSpecs) {
35
+ const result = {};
36
+ // Properties (ios, android)
37
+ const properties = platformSpecs.getProperties();
38
+ for (const property of properties) {
39
+ // Property name (ios, android)
40
+ const platform = property.getName();
41
+ if (!isValidPlatform(platform)) {
42
+ console.warn(` ⚠️ ${typeName} does not properly extend HybridObject<T> - "${platform}" is not a valid Platform! ` +
43
+ `Valid platforms are: [${allPlatforms.join(', ')}]`);
44
+ continue;
45
+ }
46
+ // Value (swift, kotlin, c++)
47
+ const language = getLiteralValue(property);
48
+ if (!isValidLanguage(language)) {
49
+ console.warn(` ⚠️ ${typeName}: Language ${language} is not a valid language for ${platform}! ` +
50
+ `Valid languages are: [${platformLanguages[platform].join(', ')}]`);
51
+ continue;
52
+ }
53
+ // Double-check that language works on this platform (android: kotlin/c++, ios: swift/c++)
54
+ if (!isValidLanguageForPlatform(language, platform)) {
55
+ console.warn(` ⚠️ ${typeName}: Language ${language} is not a valid language for ${platform}! ` +
56
+ `Valid languages are: [${platformLanguages[platform].join(', ')}]`);
57
+ continue;
58
+ }
59
+ // @ts-expect-error because TypeScript isn't smart enough yet to correctly cast after the `isValidLanguageForPlatform` check.
60
+ result[platform] = language;
61
+ }
62
+ return result;
63
+ }
64
+ function isDirectlyType(type, name) {
65
+ const symbol = type.getSymbol() ?? type.getAliasSymbol();
66
+ if (symbol?.getName() === name) {
67
+ return true;
68
+ }
69
+ return false;
70
+ }
71
+ function extendsType(type, name, recursive) {
72
+ for (const base of getBaseTypes(type)) {
73
+ const isHybrid = isDirectlyType(base, name);
74
+ if (isHybrid) {
75
+ return true;
76
+ }
77
+ if (recursive) {
78
+ const baseExtends = extendsType(base, name, recursive);
79
+ if (baseExtends) {
80
+ return true;
81
+ }
82
+ }
83
+ }
84
+ return false;
85
+ }
86
+ export function isDirectlyHybridObject(type) {
87
+ return isDirectlyType(type, 'HybridObject');
88
+ }
89
+ export function extendsHybridObject(type, recursive) {
90
+ return extendsType(type, 'HybridObject', recursive);
91
+ }
92
+ export function isHybridViewProps(type) {
93
+ return extendsType(type, 'HybridViewProps', true);
94
+ }
95
+ export function isHybridViewMethods(type) {
96
+ return extendsType(type, 'HybridViewMethods', true);
97
+ }
98
+ export function isHybridView(type) {
99
+ // HybridViews are type aliases for `HybridView`, and `Props & Methods` are just intersected together.
100
+ const unionTypes = type.getIntersectionTypes();
101
+ for (const union of unionTypes) {
102
+ const symbol = union.getSymbol();
103
+ if (symbol == null)
104
+ return false;
105
+ return symbol.getName() === 'HybridViewTag';
106
+ }
107
+ return false;
108
+ }
109
+ export function isAnyHybridSubclass(type) {
110
+ if (isDirectlyHybridObject(type))
111
+ return false;
112
+ if (isHybridView(type))
113
+ return true;
114
+ if (extendsHybridObject(type, true))
115
+ return true;
116
+ return false;
117
+ }
118
+ /**
119
+ * If the given interface ({@linkcode declaration}) extends `HybridObject`,
120
+ * this method returns the platforms it exists on.
121
+ * If it doesn't extend `HybridObject`, this returns `undefined`.
122
+ */
123
+ export function getHybridObjectPlatforms(declaration) {
124
+ const base = getBaseTypes(declaration.getType()).find((t) => isDirectlyHybridObject(t));
125
+ if (base == null) {
126
+ // this type does not extend `HybridObject`.
127
+ throw new Error(`Couldn't find HybridObject<..> base for ${declaration.getName()}! (${declaration.getText()})`);
128
+ }
129
+ const genericArguments = base.getTypeArguments();
130
+ const platformSpecsArgument = genericArguments[0];
131
+ if (platformSpecsArgument == null) {
132
+ // it uses `HybridObject` without generic arguments. This defaults to C++
133
+ return { android: 'c++', ios: 'c++' };
134
+ }
135
+ return getPlatformSpec(declaration.getName(), platformSpecsArgument);
136
+ }
137
+ export function getHybridViewPlatforms(view) {
138
+ if (Node.isTypeAliasDeclaration(view)) {
139
+ const hybridViewTypeNode = view.getTypeNode();
140
+ const isHybridViewType = Node.isTypeReference(hybridViewTypeNode) &&
141
+ hybridViewTypeNode.getTypeName().getText() === 'HybridView';
142
+ if (!isHybridViewType) {
143
+ return;
144
+ }
145
+ const genericArguments = hybridViewTypeNode.getTypeArguments();
146
+ const platformSpecArg = genericArguments[2];
147
+ if (platformSpecArg != null) {
148
+ return getPlatformSpec(view.getName(), platformSpecArg.getType());
149
+ }
150
+ }
151
+ // it uses `HybridObject` without generic arguments. This defaults to platform native languages
152
+ return { ios: 'swift', android: 'kotlin' };
153
+ }
package/lib/index.js CHANGED
@@ -1,10 +1,113 @@
1
- exports.ApiKey = require('./apiKey');
2
- exports.Blob = require('./blob');
3
- exports.CommandManager = require('./commandManager');
4
- exports.Device = require('./device');
5
- exports.Message = require('./message');
6
- exports.Permission = require('./permission');
7
- exports.Principal = require('./principal');
8
- exports.Service = require('./service');
9
- exports.Session = require('./session');
10
- exports.User = require('./user');
1
+ #!/usr/bin/env node
2
+ import yargs from 'yargs/yargs';
3
+ import { hideBin } from 'yargs/helpers';
4
+ import chalk from 'chalk';
5
+ import { prettifyDirectory } from './prettifyDirectory.js';
6
+ import { getFiles } from './getFiles.js';
7
+ import { runNitrogen } from './nitrogen.js';
8
+ import { promises as fs } from 'fs';
9
+ import { isValidLogLevel, setLogLevel } from './Logger.js';
10
+ import { initNewNitroModule } from './init.js';
11
+ import { NITROGEN_VERSION } from './utils.js';
12
+ const commandName = 'nitrogen';
13
+ // Maximum of 100 col width
14
+ const cliWidth = Math.min(process.stdout.columns * 0.9, 100);
15
+ // Set up yargs CLI app
16
+ await yargs(hideBin(process.argv))
17
+ .option('log-level', {
18
+ type: 'string',
19
+ description: 'Configures the log-level of nitrogen.',
20
+ default: 'info',
21
+ choices: ['debug', 'info', 'warning', 'error'],
22
+ })
23
+ .middleware((args) => {
24
+ if (!isValidLogLevel(args.logLevel)) {
25
+ throw new Error(`Invalid log-level ("${args.logLevel}")!`);
26
+ }
27
+ setLogLevel(args.logLevel);
28
+ })
29
+ // 🔥 nitrogen [path]
30
+ .command('$0 [basePath]', `Usage: ${chalk.bold(`${commandName} <basePath> [options]`)}\n` +
31
+ `Run the nitro code-generator on all ${chalk.underline('**/*.nitro.ts')} files found ` +
32
+ `in the current directory and generate C++, Swift or Kotlin outputs in ${chalk.underline('./nitrogen/generated')}.`, (y) => y
33
+ .positional('basePath', {
34
+ type: 'string',
35
+ description: `The base path of where Nitrogen will start looking for ${chalk.underline('**/*.nitro.ts')} specs.`,
36
+ default: process.cwd(),
37
+ })
38
+ .option('out', {
39
+ type: 'string',
40
+ description: 'Configures the output path of the generated C++, Swift or Kotlin files.',
41
+ default: './nitrogen/generated',
42
+ })
43
+ .option('config', {
44
+ type: 'string',
45
+ description: `A custom path to a ${chalk.underline('nitro.json')} config file.`,
46
+ default: './nitro.json',
47
+ }), async (argv) => {
48
+ const basePath = argv.basePath;
49
+ const outputDirectory = argv.out;
50
+ await runNitrogenCommand(basePath, outputDirectory);
51
+ })
52
+ // 🔥 nitrogen init <moduleName>
53
+ .command('init <moduleName>', `Usage: ${chalk.bold(`${commandName} init <moduleName> [options]`)}\n` +
54
+ `Create a new Nitro Module.`, (y) => y
55
+ .positional('moduleName', {
56
+ type: 'string',
57
+ description: 'The name of the Nitro Module that will be created.',
58
+ demandOption: true,
59
+ })
60
+ .option('path', {
61
+ type: 'string',
62
+ description: `A custom path to create the new Nitro Module in - instead of the current working directory.`,
63
+ default: process.cwd(),
64
+ }), async (argv) => {
65
+ await initNewNitroModule(argv.path, argv.moduleName);
66
+ })
67
+ .usage(`Usage: ${chalk.bold('$0 [options]')}\n` +
68
+ `$0 is a code-generater for Nitro Modules (${chalk.underline('https://github.com/mrousavy/nitro')})\n` +
69
+ `It converts all TypeScript specs found in ${chalk.underline('**/*.nitro.ts')} to C++, Swift or Kotlin specs.\n` +
70
+ `Each library/module must have a ${chalk.underline('nitro.json')} configuration file in it's root directory.\n` +
71
+ `$Nitrogen Version: ${chalk.bold(NITROGEN_VERSION)}`)
72
+ .help()
73
+ .strict()
74
+ .wrap(cliWidth).argv;
75
+ async function runNitrogenCommand(baseDirectory, outputDirectory) {
76
+ // 1. Prepare output folders
77
+ const filesBefore = await getFiles(outputDirectory);
78
+ const start = performance.now();
79
+ // 2. Run Nitrogen
80
+ const { generatedFiles, generatedSpecsCount, targetSpecsCount } = await runNitrogen({
81
+ baseDirectory: baseDirectory,
82
+ outputDirectory: outputDirectory,
83
+ });
84
+ const end = performance.now();
85
+ const timeS = ((end - start) / 1000).toFixed(1);
86
+ console.log(`🎉 Generated ${generatedSpecsCount}/${targetSpecsCount} HybridObject${generatedSpecsCount === 1 ? '' : 's'} in ${timeS}s!`);
87
+ console.log(`💡 Your code is in ${chalk.underline(prettifyDirectory(outputDirectory))}`);
88
+ // 3. Delete all old dangling files
89
+ const addedFiles = generatedFiles.filter((f) => !filesBefore.includes(f));
90
+ const removedFiles = filesBefore.filter((f) => !generatedFiles.includes(f));
91
+ if (addedFiles.length > 0 || removedFiles.length > 0) {
92
+ let text = '';
93
+ const as = addedFiles.length > 1 ? 's' : '';
94
+ const rs = removedFiles.length > 1 ? 's' : '';
95
+ if (addedFiles.length > 0 && removedFiles.length === 0) {
96
+ text = `Added ${addedFiles.length} file${as}`;
97
+ }
98
+ else if (addedFiles.length === 0 && removedFiles.length > 0) {
99
+ text = `Removed ${removedFiles.length} file${rs}`;
100
+ }
101
+ else {
102
+ text = `Added ${addedFiles.length} file${as} and removed ${removedFiles.length} file${rs}`;
103
+ }
104
+ console.log(`‼️ ${text} - ${chalk.bold('you need to run `pod install`/sync gradle to update files!')}`);
105
+ }
106
+ const promises = removedFiles.map(async (file) => {
107
+ const stat = await fs.stat(file);
108
+ if (stat.isFile()) {
109
+ await fs.rm(file);
110
+ }
111
+ });
112
+ await Promise.all(promises);
113
+ }
package/lib/init.js ADDED
@@ -0,0 +1,123 @@
1
+ import path from 'path';
2
+ import { prettifyDirectory } from './prettifyDirectory.js';
3
+ import fs from 'fs/promises';
4
+ import { existsSync } from 'fs';
5
+ import { Logger } from './Logger.js';
6
+ import chalk from 'chalk';
7
+ import { execSync } from 'child_process';
8
+ import { randomUUID } from 'crypto';
9
+ export async function initNewNitroModule(baseDirectory, moduleName, ref = 'main') {
10
+ Logger.info(`⚙️ Creating new Nitro Module "${chalk.bold(moduleName)}" in ${chalk.underline(prettifyDirectory(baseDirectory))}...`);
11
+ const directory = path.join(baseDirectory, moduleName);
12
+ if (existsSync(directory)) {
13
+ Logger.error(`❌ A folder named "${chalk.underline(moduleName)}" already exists in the directory ${chalk.underline(prettifyDirectory(baseDirectory))}!`);
14
+ process.exit(1);
15
+ }
16
+ await fs.mkdir(directory);
17
+ const modulePath = await downloadGitHubFolder('mrousavy', 'nitro', ref, 'packages/template', directory);
18
+ Logger.info(`🏗️ Constructing template...`);
19
+ const cleanLibraryName = moduleName.replace('react-native-', '');
20
+ const cxxNamespace = cleanLibraryName.replaceAll('-', '');
21
+ let camelCaseName = cleanLibraryName
22
+ .split('-')
23
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
24
+ .join('');
25
+ if (!camelCaseName.startsWith('Nitro')) {
26
+ camelCaseName = 'Nitro' + camelCaseName;
27
+ }
28
+ await replaceTemplate(modulePath, `cxxNamespace`, cxxNamespace);
29
+ await replaceTemplate(modulePath, `androidNamespace`, cxxNamespace);
30
+ await replaceTemplate(modulePath, `androidCxxLibName`, camelCaseName);
31
+ await replaceTemplate(modulePath, `iosModuleName`, camelCaseName);
32
+ await replaceTemplate(modulePath, `packageName`, moduleName);
33
+ await replaceTemplate(modulePath, `packageDescription`, moduleName);
34
+ Logger.info(`🎉 Created Nitro Module "${chalk.bold(moduleName)}" in ${chalk.underline(prettifyDirectory(directory))}!`);
35
+ Logger.info(`👉 To install dependencies, use your package manager of choice (e.g. ${chalk.bold('npm install')})`);
36
+ Logger.info(`👉 To create your first Hybrid Object, add a ${chalk.underline(`*.nitro.ts`)} file, declare a TypeScript interface that extends ${chalk.bold('HybridObject<...>')}, and run ${chalk.bold('npx nitrogen')}.`);
37
+ Logger.info(`👉 To test your module in an app, create a new React Native app somewhere (e.g. in ${chalk.underline(`./${moduleName}/example`)}) and add ${chalk.bold(moduleName)} as a local dependency.`);
38
+ }
39
+ async function isGitInstalled() {
40
+ try {
41
+ execSync('git --version');
42
+ return true;
43
+ }
44
+ catch (error) {
45
+ return false;
46
+ }
47
+ }
48
+ async function downloadGitHubFolder(owner, repo, branch, folder, outputPath) {
49
+ if (!isGitInstalled()) {
50
+ console.error(`❌ ${chalk.bold('git')} is not installed or available in the current path! Make sure to install ${chalk.bold('git')} and try again.`);
51
+ process.exit(1);
52
+ }
53
+ const repoUrl = `https://github.com/${owner}/${repo}`;
54
+ Logger.info(`⏳ Cloning ${chalk.underline(repoUrl)}...`);
55
+ const tempPath = randomUUID();
56
+ const tempDir = path.join(outputPath, tempPath);
57
+ execSync(`git clone --depth 1 --filter=blob:none -b ${branch} --quiet --sparse ${repoUrl} ${tempDir}`);
58
+ const prettyOutputPath = prettifyDirectory(outputPath);
59
+ const initialDir = process.cwd();
60
+ try {
61
+ process.chdir(tempDir);
62
+ Logger.debug(`⏳ Checking out ${chalk.underline(folder)}...`);
63
+ execSync(`git sparse-checkout set ${folder}`);
64
+ Logger.debug(`📁 Copying files from ${chalk.underline(`${prettyOutputPath}/${tempPath}`)} to ${chalk.underline(prettyOutputPath)}...`);
65
+ const sourcePath = path.join(tempDir, folder);
66
+ await fs.mkdir(outputPath, { recursive: true });
67
+ await copyFolder(sourcePath, outputPath);
68
+ return outputPath;
69
+ }
70
+ finally {
71
+ // change dir back to original
72
+ process.chdir(initialDir);
73
+ Logger.debug(`🗑️ Removing temporary folder ${chalk.underline(prettifyDirectory(tempDir))}...`);
74
+ await fs.rm(tempDir, { recursive: true, force: true });
75
+ }
76
+ }
77
+ async function copyFolder(src, dest) {
78
+ const entries = await fs.readdir(src, { withFileTypes: true });
79
+ for (const entry of entries) {
80
+ const srcPath = path.join(src, entry.name);
81
+ const destPath = path.join(dest, entry.name);
82
+ if (entry.isDirectory()) {
83
+ await fs.mkdir(destPath, { recursive: true });
84
+ await copyFolder(srcPath, destPath);
85
+ }
86
+ else {
87
+ await fs.copyFile(srcPath, destPath);
88
+ }
89
+ }
90
+ }
91
+ async function replaceTemplate(dir, templateName, replacementValue) {
92
+ const replaceInFile = async (filePath) => {
93
+ const content = await fs.readFile(filePath, 'utf8');
94
+ const updatedContent = content.replaceAll(`$$${templateName}$$`, replacementValue);
95
+ if (content !== updatedContent) {
96
+ await fs.writeFile(filePath, updatedContent, 'utf8');
97
+ }
98
+ };
99
+ const replaceInName = (name) => {
100
+ return name.replaceAll(`$$${templateName}$$`, replacementValue);
101
+ };
102
+ const processDirectory = async (currentDir) => {
103
+ const entries = await fs.readdir(currentDir, { withFileTypes: true });
104
+ for (const entry of entries) {
105
+ const oldPath = path.join(currentDir, entry.name);
106
+ const updatedName = replaceInName(entry.name);
107
+ const newPath = path.join(currentDir, updatedName);
108
+ if (oldPath !== newPath) {
109
+ await fs.rename(oldPath, newPath);
110
+ }
111
+ if (entry.isDirectory()) {
112
+ await processDirectory(newPath);
113
+ }
114
+ else if (entry.isFile()) {
115
+ await replaceInFile(newPath);
116
+ }
117
+ }
118
+ };
119
+ if (!existsSync(dir)) {
120
+ throw new Error(`The directory "${dir}" does not exist.`);
121
+ }
122
+ await processDirectory(dir);
123
+ }
@@ -0,0 +1,165 @@
1
+ import { Project } from 'ts-morph';
2
+ import { extendsHybridObject, isHybridView, getHybridObjectPlatforms, getHybridViewPlatforms, } from './getPlatformSpecs.js';
3
+ import { generatePlatformFiles } from './createPlatformSpec.js';
4
+ import path from 'path';
5
+ import { prettifyDirectory } from './prettifyDirectory.js';
6
+ import { capitalizeName, deduplicateFiles, errorToString, indent, NITROGEN_VERSION, } from './utils.js';
7
+ import { writeFile } from './writeFile.js';
8
+ import chalk from 'chalk';
9
+ import { groupByPlatform } from './syntax/SourceFile.js';
10
+ import { Logger } from './Logger.js';
11
+ import { NitroConfig } from './config/NitroConfig.js';
12
+ import { createIOSAutolinking } from './autolinking/createIOSAutolinking.js';
13
+ import { createAndroidAutolinking } from './autolinking/createAndroidAutolinking.js';
14
+ import { createGitAttributes } from './createGitAttributes.js';
15
+ export async function runNitrogen({ baseDirectory, outputDirectory, }) {
16
+ let targetSpecs = 0;
17
+ let generatedSpecs = 0;
18
+ // Create the TS project
19
+ const project = new Project({
20
+ compilerOptions: {
21
+ strict: true,
22
+ strictNullChecks: true,
23
+ noUncheckedIndexedAccess: true,
24
+ },
25
+ });
26
+ const ignorePaths = NitroConfig.current.getIgnorePaths();
27
+ const globPattern = [path.join(baseDirectory, '**', '*.nitro.ts')];
28
+ ignorePaths.forEach((ignorePath) => {
29
+ globPattern.push('!' + path.join(baseDirectory, ignorePath));
30
+ });
31
+ project.addSourceFilesAtPaths(globPattern);
32
+ // Loop through all source files to log them
33
+ Logger.info(chalk.reset(`🚀 Nitrogen ${chalk.bold(NITROGEN_VERSION)} runs at ${chalk.underline(prettifyDirectory(baseDirectory))}`));
34
+ for (const dir of project.getDirectories()) {
35
+ const specs = dir.getSourceFiles().length;
36
+ const relativePath = prettifyDirectory(dir.getPath());
37
+ Logger.info(` 🔍 Nitrogen found ${specs} spec${specs === 1 ? '' : 's'} in ${chalk.underline(relativePath)}`);
38
+ }
39
+ // If no source files are found, we can exit
40
+ if (project.getSourceFiles().length === 0) {
41
+ const searchDir = prettifyDirectory(path.join(path.resolve(baseDirectory), '**', '*.nitro.ts'));
42
+ Logger.error(`❌ Nitrogen didn't find any spec files in ${chalk.underline(searchDir)}! ` +
43
+ `To create a Nitro Module, create a TypeScript file with the "${chalk.underline('.nitro.ts')}" suffix ` +
44
+ 'and export an interface that extends HybridObject<T>.');
45
+ process.exit();
46
+ }
47
+ const usedPlatforms = [];
48
+ const filesAfter = [];
49
+ const writtenFiles = [];
50
+ for (const sourceFile of project.getSourceFiles()) {
51
+ Logger.info(`⏳ Parsing ${sourceFile.getBaseName()}...`);
52
+ const startedWithSpecs = generatedSpecs;
53
+ // Find all interfaceDeclarations in the given file
54
+ const declarations = [
55
+ ...sourceFile.getInterfaces(),
56
+ ...sourceFile.getTypeAliases(),
57
+ ];
58
+ for (const declaration of declarations) {
59
+ let typeName = declaration.getName();
60
+ try {
61
+ let platformSpec;
62
+ if (isHybridView(declaration.getType())) {
63
+ // Hybrid View Props
64
+ const targetPlatforms = getHybridViewPlatforms(declaration);
65
+ if (targetPlatforms == null) {
66
+ // It does not extend HybridView, continue..
67
+ continue;
68
+ }
69
+ platformSpec = targetPlatforms;
70
+ }
71
+ else if (extendsHybridObject(declaration.getType(), true)) {
72
+ // Hybrid View
73
+ const targetPlatforms = getHybridObjectPlatforms(declaration);
74
+ if (targetPlatforms == null) {
75
+ // It does not extend HybridObject, continue..
76
+ continue;
77
+ }
78
+ platformSpec = targetPlatforms;
79
+ }
80
+ else {
81
+ continue;
82
+ }
83
+ const platforms = Object.keys(platformSpec);
84
+ if (platforms.length === 0) {
85
+ Logger.warn(`⚠️ ${typeName} does not declare any platforms in HybridObject<T> - nothing can be generated.`);
86
+ continue;
87
+ }
88
+ targetSpecs++;
89
+ Logger.info(` ⚙️ Generating specs for HybridObject "${chalk.bold(typeName)}"...`);
90
+ // Create all files and throw it into a big list
91
+ let allFiles = platforms.flatMap((p) => {
92
+ usedPlatforms.push(p);
93
+ const language = platformSpec[p];
94
+ const r = generatePlatformFiles(declaration.getType(), language);
95
+ return r;
96
+ });
97
+ allFiles = deduplicateFiles(allFiles);
98
+ // Group the files by platform ({ ios: [], android: [], shared: [] })
99
+ const filesPerPlatform = groupByPlatform(allFiles);
100
+ // Loop through each platform one by one so that it has some kind of order (per-platform)
101
+ for (const [p, files] of Object.entries(filesPerPlatform)) {
102
+ const platform = p;
103
+ const language = platform === 'shared' ? 'c++' : platformSpec[platform];
104
+ if (language == null) {
105
+ // if the language was never specified in the spec, skip it
106
+ continue;
107
+ }
108
+ if (files.length === 0) {
109
+ // if no files exist on this platform, skip it
110
+ continue;
111
+ }
112
+ Logger.info(` ${chalk.dim(platform)}: Generating ${capitalizeName(language)} code...`);
113
+ // Write the actual files for this specific platform.
114
+ for (const file of files) {
115
+ const basePath = path.join(outputDirectory, file.platform, file.language);
116
+ const actualPath = await writeFile(basePath, file);
117
+ filesAfter.push(actualPath);
118
+ writtenFiles.push(file);
119
+ }
120
+ }
121
+ // Done!
122
+ generatedSpecs++;
123
+ }
124
+ catch (error) {
125
+ const message = indent(errorToString(error), ' ');
126
+ Logger.error(chalk.redBright(` ❌ Failed to generate spec for ${typeName}! ${message}`));
127
+ process.exitCode = 1;
128
+ }
129
+ }
130
+ if (generatedSpecs === startedWithSpecs) {
131
+ Logger.error(chalk.redBright(` ❌ No specs found in ${sourceFile.getBaseName()}!`));
132
+ }
133
+ }
134
+ // Autolinking
135
+ Logger.info(`⛓️ Setting up build configs for autolinking...`);
136
+ const autolinkingFiles = [];
137
+ if (usedPlatforms.includes('ios')) {
138
+ autolinkingFiles.push(createIOSAutolinking());
139
+ }
140
+ if (usedPlatforms.includes('android')) {
141
+ autolinkingFiles.push(createAndroidAutolinking(writtenFiles));
142
+ }
143
+ for (const autolinking of autolinkingFiles) {
144
+ Logger.info(` Creating autolinking build setup for ${chalk.dim(autolinking.platform)}...`);
145
+ for (const file of autolinking.sourceFiles) {
146
+ const basePath = path.join(outputDirectory, file.platform);
147
+ const actualPath = await writeFile(basePath, file);
148
+ filesAfter.push(actualPath);
149
+ }
150
+ }
151
+ try {
152
+ // write a .gitattributes file
153
+ const markAsGenerated = NitroConfig.current.getGitAttributesGeneratedFlag();
154
+ const file = await createGitAttributes(markAsGenerated, outputDirectory);
155
+ filesAfter.push(file);
156
+ }
157
+ catch {
158
+ Logger.error(`❌ Failed to write ${chalk.dim(`.gitattributes`)}!`);
159
+ }
160
+ return {
161
+ generatedFiles: filesAfter,
162
+ targetSpecsCount: targetSpecs,
163
+ generatedSpecsCount: generatedSpecs,
164
+ };
165
+ }
@@ -0,0 +1,27 @@
1
+ import os from 'os';
2
+ import path from 'path';
3
+ export function prettifyDirectory(directory) {
4
+ let relativePath = path.relative(process.cwd(), path.resolve(directory));
5
+ if (!relativePath.startsWith('.') && relativePath.length > 0) {
6
+ // Make sure all relative paths start with "./something", not just "something"
7
+ relativePath = `./${relativePath}`;
8
+ }
9
+ const home = os.homedir();
10
+ const homeShorthand = os.platform() === 'win32' ? '$HOME' : '~';
11
+ const prettifiedHomeShorthand = directory.startsWith(home)
12
+ ? `${homeShorthand}${directory.slice(home.length)}`
13
+ : directory;
14
+ if (relativePath.length < 1) {
15
+ // If relativePath is ".", we don't want to return it
16
+ return prettifiedHomeShorthand;
17
+ }
18
+ if (relativePath.length > 0 &&
19
+ relativePath.length < prettifiedHomeShorthand.length) {
20
+ // If relativePath is shroter than the ~/... home path, we use the relative one.
21
+ return relativePath;
22
+ }
23
+ else {
24
+ // ..otherwise just use the ~/... home relative path.
25
+ return prettifiedHomeShorthand;
26
+ }
27
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};