nitrogen 0.2.23 → 0.29.4

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 (333) hide show
  1. package/README.md +15 -109
  2. package/lib/Logger.d.ts +10 -0
  3. package/lib/Logger.js +56 -0
  4. package/lib/autolinking/Autolinking.d.ts +8 -0
  5. package/lib/autolinking/Autolinking.js +1 -0
  6. package/lib/autolinking/android/createCMakeExtension.d.ts +6 -0
  7. package/lib/autolinking/android/createCMakeExtension.js +106 -0
  8. package/lib/autolinking/android/createGradleExtension.d.ts +5 -0
  9. package/lib/autolinking/android/createGradleExtension.js +36 -0
  10. package/lib/autolinking/android/createHybridObjectInitializer.d.ts +2 -0
  11. package/lib/autolinking/android/createHybridObjectInitializer.js +159 -0
  12. package/lib/autolinking/createAndroidAutolinking.d.ts +11 -0
  13. package/lib/autolinking/createAndroidAutolinking.js +13 -0
  14. package/lib/autolinking/createIOSAutolinking.d.ts +5 -0
  15. package/lib/autolinking/createIOSAutolinking.js +19 -0
  16. package/lib/autolinking/ios/createHybridObjectInitializer.d.ts +9 -0
  17. package/lib/autolinking/ios/createHybridObjectInitializer.js +97 -0
  18. package/lib/autolinking/ios/createPodspecRubyExtension.d.ts +5 -0
  19. package/lib/autolinking/ios/createPodspecRubyExtension.js +69 -0
  20. package/lib/autolinking/ios/createSwiftCxxBridge.d.ts +2 -0
  21. package/lib/autolinking/ios/createSwiftCxxBridge.js +117 -0
  22. package/lib/autolinking/ios/createSwiftUmbrellaHeader.d.ts +3 -0
  23. package/lib/autolinking/ios/createSwiftUmbrellaHeader.js +74 -0
  24. package/lib/config/NitroConfig.d.ts +52 -0
  25. package/lib/config/NitroConfig.js +112 -0
  26. package/lib/config/NitroUserConfig.d.ts +22 -0
  27. package/lib/config/NitroUserConfig.js +88 -0
  28. package/lib/config/getConfig.d.ts +2 -0
  29. package/lib/config/getConfig.js +84 -0
  30. package/lib/createGitAttributes.d.ts +1 -0
  31. package/lib/createGitAttributes.js +11 -0
  32. package/lib/createPlatformSpec.d.ts +4 -0
  33. package/lib/createPlatformSpec.js +127 -0
  34. package/lib/getFiles.d.ts +1 -0
  35. package/lib/getFiles.js +28 -0
  36. package/lib/getPlatformSpecs.d.ts +17 -0
  37. package/lib/getPlatformSpecs.js +153 -0
  38. package/lib/index.d.ts +2 -0
  39. package/lib/index.js +113 -10
  40. package/lib/init.d.ts +1 -0
  41. package/lib/init.js +123 -0
  42. package/lib/nitrogen.d.ts +11 -0
  43. package/lib/nitrogen.js +165 -0
  44. package/lib/prettifyDirectory.d.ts +1 -0
  45. package/lib/prettifyDirectory.js +27 -0
  46. package/lib/syntax/BridgedType.d.ts +41 -0
  47. package/lib/syntax/BridgedType.js +1 -0
  48. package/lib/syntax/CodeNode.d.ts +23 -0
  49. package/lib/syntax/CodeNode.js +1 -0
  50. package/lib/syntax/HybridObjectSpec.d.ts +13 -0
  51. package/lib/syntax/HybridObjectSpec.js +1 -0
  52. package/lib/syntax/Method.d.ts +41 -0
  53. package/lib/syntax/Method.js +108 -0
  54. package/lib/syntax/Parameter.d.ts +15 -0
  55. package/lib/syntax/Parameter.js +65 -0
  56. package/lib/syntax/Property.d.ts +50 -0
  57. package/lib/syntax/Property.js +147 -0
  58. package/lib/syntax/SourceFile.d.ts +70 -0
  59. package/lib/syntax/SourceFile.js +7 -0
  60. package/lib/syntax/c++/CppEnum.d.ts +6 -0
  61. package/lib/syntax/c++/CppEnum.js +110 -0
  62. package/lib/syntax/c++/CppHybridObject.d.ts +3 -0
  63. package/lib/syntax/c++/CppHybridObject.js +146 -0
  64. package/lib/syntax/c++/CppHybridObjectRegistration.d.ts +17 -0
  65. package/lib/syntax/c++/CppHybridObjectRegistration.js +18 -0
  66. package/lib/syntax/c++/CppStruct.d.ts +3 -0
  67. package/lib/syntax/c++/CppStruct.js +108 -0
  68. package/lib/syntax/c++/CppUnion.d.ts +6 -0
  69. package/lib/syntax/c++/CppUnion.js +88 -0
  70. package/lib/syntax/c++/getForwardDeclaration.d.ts +3 -0
  71. package/lib/syntax/c++/getForwardDeclaration.js +14 -0
  72. package/lib/syntax/c++/includeNitroHeader.d.ts +7 -0
  73. package/lib/syntax/c++/includeNitroHeader.js +34 -0
  74. package/lib/syntax/createType.d.ts +15 -0
  75. package/lib/syntax/createType.js +303 -0
  76. package/lib/syntax/getAllTypes.d.ts +3 -0
  77. package/lib/syntax/getAllTypes.js +11 -0
  78. package/lib/syntax/getCustomTypeConfig.d.ts +8 -0
  79. package/lib/syntax/getCustomTypeConfig.js +53 -0
  80. package/lib/syntax/getHybridObjectName.d.ts +36 -0
  81. package/lib/syntax/getHybridObjectName.js +10 -0
  82. package/lib/syntax/getInterfaceProperties.d.ts +4 -0
  83. package/lib/syntax/getInterfaceProperties.js +9 -0
  84. package/lib/syntax/getReferencedTypes.d.ts +2 -0
  85. package/lib/syntax/getReferencedTypes.js +47 -0
  86. package/lib/syntax/helpers.d.ts +13 -0
  87. package/lib/syntax/helpers.js +53 -0
  88. package/lib/syntax/isCoreType.d.ts +9 -0
  89. package/lib/syntax/isCoreType.js +47 -0
  90. package/lib/syntax/kotlin/FbjniHybridObject.d.ts +3 -0
  91. package/lib/syntax/kotlin/FbjniHybridObject.js +261 -0
  92. package/lib/syntax/kotlin/JNINativeRegistrations.d.ts +8 -0
  93. package/lib/syntax/kotlin/JNINativeRegistrations.js +7 -0
  94. package/lib/syntax/kotlin/KotlinBoxedPrimitive.d.ts +7 -0
  95. package/lib/syntax/kotlin/KotlinBoxedPrimitive.js +17 -0
  96. package/lib/syntax/kotlin/KotlinCxxBridgedType.d.ts +19 -0
  97. package/lib/syntax/kotlin/KotlinCxxBridgedType.js +893 -0
  98. package/lib/syntax/kotlin/KotlinEnum.d.ts +3 -0
  99. package/lib/syntax/kotlin/KotlinEnum.js +113 -0
  100. package/lib/syntax/kotlin/KotlinFunction.d.ts +3 -0
  101. package/lib/syntax/kotlin/KotlinFunction.js +256 -0
  102. package/lib/syntax/kotlin/KotlinHybridObject.d.ts +3 -0
  103. package/lib/syntax/kotlin/KotlinHybridObject.js +177 -0
  104. package/lib/syntax/kotlin/KotlinHybridObjectRegistration.d.ts +17 -0
  105. package/lib/syntax/kotlin/KotlinHybridObjectRegistration.js +26 -0
  106. package/lib/syntax/kotlin/KotlinStruct.d.ts +3 -0
  107. package/lib/syntax/kotlin/KotlinStruct.js +172 -0
  108. package/lib/syntax/kotlin/KotlinVariant.d.ts +3 -0
  109. package/lib/syntax/kotlin/KotlinVariant.js +191 -0
  110. package/lib/syntax/swift/SwiftCxxBridgedType.d.ts +21 -0
  111. package/lib/syntax/swift/SwiftCxxBridgedType.js +819 -0
  112. package/lib/syntax/swift/SwiftCxxTypeHelper.d.ts +17 -0
  113. package/lib/syntax/swift/SwiftCxxTypeHelper.js +613 -0
  114. package/lib/syntax/swift/SwiftEnum.d.ts +3 -0
  115. package/lib/syntax/swift/SwiftEnum.js +52 -0
  116. package/lib/syntax/swift/SwiftFunction.d.ts +3 -0
  117. package/lib/syntax/swift/SwiftFunction.js +83 -0
  118. package/lib/syntax/swift/SwiftHybridObject.d.ts +3 -0
  119. package/lib/syntax/swift/SwiftHybridObject.js +103 -0
  120. package/lib/syntax/swift/SwiftHybridObjectBridge.d.ts +11 -0
  121. package/lib/syntax/swift/SwiftHybridObjectBridge.js +451 -0
  122. package/lib/syntax/swift/SwiftHybridObjectRegistration.d.ts +19 -0
  123. package/lib/syntax/swift/SwiftHybridObjectRegistration.js +42 -0
  124. package/lib/syntax/swift/SwiftStruct.d.ts +3 -0
  125. package/lib/syntax/swift/SwiftStruct.js +75 -0
  126. package/lib/syntax/swift/SwiftVariant.d.ts +3 -0
  127. package/lib/syntax/swift/SwiftVariant.js +58 -0
  128. package/lib/syntax/types/ArrayBufferType.d.ts +10 -0
  129. package/lib/syntax/types/ArrayBufferType.js +37 -0
  130. package/lib/syntax/types/ArrayType.d.ts +12 -0
  131. package/lib/syntax/types/ArrayType.js +52 -0
  132. package/lib/syntax/types/BigIntType.d.ts +10 -0
  133. package/lib/syntax/types/BigIntType.js +27 -0
  134. package/lib/syntax/types/BooleanType.d.ts +10 -0
  135. package/lib/syntax/types/BooleanType.js +27 -0
  136. package/lib/syntax/types/CustomType.d.ts +14 -0
  137. package/lib/syntax/types/CustomType.js +36 -0
  138. package/lib/syntax/types/DateType.d.ts +10 -0
  139. package/lib/syntax/types/DateType.js +35 -0
  140. package/lib/syntax/types/EnumType.d.ts +23 -0
  141. package/lib/syntax/types/EnumType.js +101 -0
  142. package/lib/syntax/types/ErrorType.d.ts +11 -0
  143. package/lib/syntax/types/ErrorType.js +37 -0
  144. package/lib/syntax/types/FunctionType.d.ts +29 -0
  145. package/lib/syntax/types/FunctionType.js +147 -0
  146. package/lib/syntax/types/HybridObjectBaseType.d.ts +11 -0
  147. package/lib/syntax/types/HybridObjectBaseType.js +38 -0
  148. package/lib/syntax/types/HybridObjectType.d.ts +23 -0
  149. package/lib/syntax/types/HybridObjectType.js +131 -0
  150. package/lib/syntax/types/MapType.d.ts +10 -0
  151. package/lib/syntax/types/MapType.js +37 -0
  152. package/lib/syntax/types/NamedWrappingType.d.ts +14 -0
  153. package/lib/syntax/types/NamedWrappingType.js +27 -0
  154. package/lib/syntax/types/NullType.d.ts +10 -0
  155. package/lib/syntax/types/NullType.js +23 -0
  156. package/lib/syntax/types/NumberType.d.ts +10 -0
  157. package/lib/syntax/types/NumberType.js +27 -0
  158. package/lib/syntax/types/OptionalType.d.ts +13 -0
  159. package/lib/syntax/types/OptionalType.js +59 -0
  160. package/lib/syntax/types/PromiseType.d.ts +16 -0
  161. package/lib/syntax/types/PromiseType.js +62 -0
  162. package/lib/syntax/types/RecordType.d.ts +13 -0
  163. package/lib/syntax/types/RecordType.js +47 -0
  164. package/lib/syntax/types/ResultWrappingType.d.ts +13 -0
  165. package/lib/syntax/types/ResultWrappingType.js +44 -0
  166. package/lib/syntax/types/StringType.d.ts +10 -0
  167. package/lib/syntax/types/StringType.js +35 -0
  168. package/lib/syntax/types/StructType.d.ts +14 -0
  169. package/lib/syntax/types/StructType.js +61 -0
  170. package/lib/syntax/types/TupleType.d.ts +12 -0
  171. package/lib/syntax/types/TupleType.js +39 -0
  172. package/lib/syntax/types/Type.d.ts +55 -0
  173. package/lib/syntax/types/Type.js +1 -0
  174. package/lib/syntax/types/VariantType.d.ts +19 -0
  175. package/lib/syntax/types/VariantType.js +75 -0
  176. package/lib/syntax/types/VoidType.d.ts +10 -0
  177. package/lib/syntax/types/VoidType.js +27 -0
  178. package/lib/syntax/types/getTypeAs.d.ts +2 -0
  179. package/lib/syntax/types/getTypeAs.js +12 -0
  180. package/lib/utils.d.ts +22 -0
  181. package/lib/utils.js +126 -0
  182. package/lib/views/CppHybridViewComponent.d.ts +14 -0
  183. package/lib/views/CppHybridViewComponent.js +254 -0
  184. package/lib/views/createHostComponentJs.d.ts +3 -0
  185. package/lib/views/createHostComponentJs.js +27 -0
  186. package/lib/views/kotlin/KotlinHybridViewManager.d.ts +3 -0
  187. package/lib/views/kotlin/KotlinHybridViewManager.js +229 -0
  188. package/lib/views/swift/SwiftHybridViewManager.d.ts +3 -0
  189. package/lib/views/swift/SwiftHybridViewManager.js +131 -0
  190. package/lib/writeFile.d.ts +5 -0
  191. package/lib/writeFile.js +19 -0
  192. package/package.json +58 -29
  193. package/src/Logger.ts +63 -0
  194. package/src/autolinking/Autolinking.ts +9 -0
  195. package/src/autolinking/android/createCMakeExtension.ts +123 -0
  196. package/src/autolinking/android/createGradleExtension.ts +43 -0
  197. package/src/autolinking/android/createHybridObjectInitializer.ts +174 -0
  198. package/src/autolinking/createAndroidAutolinking.ts +28 -0
  199. package/src/autolinking/createIOSAutolinking.ts +24 -0
  200. package/src/autolinking/ios/createHybridObjectInitializer.ts +112 -0
  201. package/src/autolinking/ios/createPodspecRubyExtension.ts +76 -0
  202. package/src/autolinking/ios/createSwiftCxxBridge.ts +137 -0
  203. package/src/autolinking/ios/createSwiftUmbrellaHeader.ts +90 -0
  204. package/src/config/NitroConfig.ts +139 -0
  205. package/src/config/NitroUserConfig.ts +105 -0
  206. package/src/config/getConfig.ts +91 -0
  207. package/src/createGitAttributes.ts +15 -0
  208. package/src/createPlatformSpec.ts +176 -0
  209. package/src/getFiles.ts +31 -0
  210. package/src/getPlatformSpecs.ts +202 -0
  211. package/src/index.ts +146 -0
  212. package/src/init.ts +186 -0
  213. package/src/nitrogen.ts +246 -0
  214. package/src/prettifyDirectory.ts +32 -0
  215. package/src/syntax/BridgedType.ts +59 -0
  216. package/src/syntax/CodeNode.ts +24 -0
  217. package/src/syntax/HybridObjectSpec.ts +14 -0
  218. package/src/syntax/Method.ts +154 -0
  219. package/src/syntax/Parameter.ts +81 -0
  220. package/src/syntax/Property.ts +203 -0
  221. package/src/syntax/SourceFile.ts +80 -0
  222. package/src/syntax/c++/CppEnum.ts +128 -0
  223. package/src/syntax/c++/CppHybridObject.ts +165 -0
  224. package/src/syntax/c++/CppHybridObjectRegistration.ts +39 -0
  225. package/src/syntax/c++/CppStruct.ts +129 -0
  226. package/src/syntax/c++/CppUnion.ts +105 -0
  227. package/src/syntax/c++/getForwardDeclaration.ts +19 -0
  228. package/src/syntax/c++/includeNitroHeader.ts +40 -0
  229. package/src/syntax/createType.ts +365 -0
  230. package/src/syntax/getAllTypes.ts +18 -0
  231. package/src/syntax/getCustomTypeConfig.ts +71 -0
  232. package/src/syntax/getHybridObjectName.ts +48 -0
  233. package/src/syntax/getInterfaceProperties.ts +21 -0
  234. package/src/syntax/getReferencedTypes.ts +57 -0
  235. package/src/syntax/helpers.ts +79 -0
  236. package/src/syntax/isCoreType.ts +60 -0
  237. package/src/syntax/kotlin/FbjniHybridObject.ts +313 -0
  238. package/src/syntax/kotlin/JNINativeRegistrations.ts +19 -0
  239. package/src/syntax/kotlin/KotlinBoxedPrimitive.ts +19 -0
  240. package/src/syntax/kotlin/KotlinCxxBridgedType.ts +942 -0
  241. package/src/syntax/kotlin/KotlinEnum.ts +130 -0
  242. package/src/syntax/kotlin/KotlinFunction.ts +277 -0
  243. package/src/syntax/kotlin/KotlinHybridObject.ts +205 -0
  244. package/src/syntax/kotlin/KotlinHybridObjectRegistration.ts +51 -0
  245. package/src/syntax/kotlin/KotlinStruct.ts +198 -0
  246. package/src/syntax/kotlin/KotlinVariant.ts +212 -0
  247. package/src/syntax/swift/SwiftCxxBridgedType.ts +874 -0
  248. package/src/syntax/swift/SwiftCxxTypeHelper.ts +674 -0
  249. package/src/syntax/swift/SwiftEnum.ts +65 -0
  250. package/src/syntax/swift/SwiftFunction.ts +91 -0
  251. package/src/syntax/swift/SwiftHybridObject.ts +121 -0
  252. package/src/syntax/swift/SwiftHybridObjectBridge.ts +522 -0
  253. package/src/syntax/swift/SwiftHybridObjectRegistration.ts +75 -0
  254. package/src/syntax/swift/SwiftStruct.ts +85 -0
  255. package/src/syntax/swift/SwiftVariant.ts +67 -0
  256. package/src/syntax/types/ArrayBufferType.ts +49 -0
  257. package/src/syntax/types/ArrayType.ts +62 -0
  258. package/src/syntax/types/BigIntType.ts +35 -0
  259. package/src/syntax/types/BooleanType.ts +35 -0
  260. package/src/syntax/types/CustomType.ts +47 -0
  261. package/src/syntax/types/DateType.ts +43 -0
  262. package/src/syntax/types/EnumType.ts +130 -0
  263. package/src/syntax/types/ErrorType.ts +44 -0
  264. package/src/syntax/types/FunctionType.ts +167 -0
  265. package/src/syntax/types/HybridObjectBaseType.ts +54 -0
  266. package/src/syntax/types/HybridObjectType.ts +198 -0
  267. package/src/syntax/types/MapType.ts +49 -0
  268. package/src/syntax/types/NamedWrappingType.ts +33 -0
  269. package/src/syntax/types/NullType.ts +30 -0
  270. package/src/syntax/types/NumberType.ts +34 -0
  271. package/src/syntax/types/OptionalType.ts +66 -0
  272. package/src/syntax/types/PromiseType.ts +72 -0
  273. package/src/syntax/types/RecordType.ts +56 -0
  274. package/src/syntax/types/ResultWrappingType.ts +53 -0
  275. package/src/syntax/types/StringType.ts +44 -0
  276. package/src/syntax/types/StructType.ts +83 -0
  277. package/src/syntax/types/TupleType.ts +53 -0
  278. package/src/syntax/types/Type.ts +82 -0
  279. package/src/syntax/types/VariantType.ts +92 -0
  280. package/src/syntax/types/VoidType.ts +34 -0
  281. package/src/syntax/types/getTypeAs.ts +15 -0
  282. package/src/utils.ts +162 -0
  283. package/src/views/CppHybridViewComponent.ts +301 -0
  284. package/src/views/createHostComponentJs.ts +34 -0
  285. package/src/views/kotlin/KotlinHybridViewManager.ts +258 -0
  286. package/src/views/swift/SwiftHybridViewManager.ts +153 -0
  287. package/src/writeFile.ts +27 -0
  288. package/.jshintignore +0 -6
  289. package/.jshintrc +0 -3
  290. package/.npmignore +0 -3
  291. package/.travis.yml +0 -13
  292. package/LICENSE +0 -13
  293. package/browser/nitrogen-min.js +0 -3
  294. package/browser/nitrogen.js +0 -6369
  295. package/lib/apiKey.js +0 -67
  296. package/lib/blob.js +0 -57
  297. package/lib/commandManager.js +0 -350
  298. package/lib/device.js +0 -19
  299. package/lib/memoryStore.js +0 -24
  300. package/lib/message.js +0 -298
  301. package/lib/permission.js +0 -121
  302. package/lib/principal.js +0 -330
  303. package/lib/service.js +0 -349
  304. package/lib/session.js +0 -494
  305. package/lib/user.js +0 -20
  306. package/publish +0 -2
  307. package/scripts/build-documentation +0 -4
  308. package/scripts/build-module +0 -27
  309. package/scripts/module.js +0 -12
  310. package/scripts/postamble.js +0 -1
  311. package/scripts/preamble.js +0 -2
  312. package/scripts/run-test-server +0 -9
  313. package/test/config.js +0 -12
  314. package/test/fixtures/images/image.jpg +0 -0
  315. package/test/fixtures/images/motion0.jpg +0 -0
  316. package/test/fixtures/images/motion1.jpg +0 -0
  317. package/test/fixtures/images/motion2.jpg +0 -0
  318. package/test/fixtures/index.js +0 -76
  319. package/test/main.js +0 -5
  320. package/test/memoryStore.js +0 -22
  321. package/test/mocha.opts +0 -3
  322. package/test/units/apiKey.js +0 -46
  323. package/test/units/blob.js +0 -35
  324. package/test/units/commandManager.js +0 -67
  325. package/test/units/device.js +0 -26
  326. package/test/units/heartbeat.js +0 -28
  327. package/test/units/message.js +0 -79
  328. package/test/units/permissions.js +0 -43
  329. package/test/units/principal.js +0 -116
  330. package/test/units/service.js +0 -92
  331. package/test/units/session.js +0 -97
  332. package/test/units/user.js +0 -48
  333. package/yuidoc.json +0 -8
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,11 @@
1
+ interface NitrogenOptions {
2
+ baseDirectory: string;
3
+ outputDirectory: string;
4
+ }
5
+ interface NitrogenResult {
6
+ generatedFiles: string[];
7
+ targetSpecsCount: number;
8
+ generatedSpecsCount: number;
9
+ }
10
+ export declare function runNitrogen({ baseDirectory, outputDirectory, }: NitrogenOptions): Promise<NitrogenResult>;
11
+ export {};
@@ -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 @@
1
+ export declare function prettifyDirectory(directory: string): string;
@@ -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,41 @@
1
+ import type { Language } from '../getPlatformSpecs.js';
2
+ import type { SourceFile, SourceImport } from './SourceFile.js';
3
+ import type { Type } from './types/Type.js';
4
+ export interface BridgedType<FromLanguage extends Language, ToLanguage extends Language> {
5
+ /**
6
+ * The underlying type that is being bridged between {@linkcode FromLanguage} and {@linkcode ToLanguage}
7
+ */
8
+ readonly type: Type;
9
+ /**
10
+ * Whether the underlying type has a valid type (is not void or null)
11
+ */
12
+ readonly hasType: boolean;
13
+ /**
14
+ * Whether this type can be passed by reference
15
+ */
16
+ readonly canBePassedByReference: boolean;
17
+ /**
18
+ * Whether this bridged type needs special handling, or can just be used as-is
19
+ */
20
+ readonly needsSpecialHandling: boolean;
21
+ /**
22
+ * Get all imports required for this bridge to work
23
+ */
24
+ getRequiredImports(language: Language): SourceImport[];
25
+ /**
26
+ * Get all extra files that need to be created for this type, as well as the bridge.
27
+ */
28
+ getExtraFiles(): SourceFile[];
29
+ /**
30
+ * Get the code for the type itself in the given language
31
+ */
32
+ getTypeCode(language: FromLanguage | ToLanguage): string;
33
+ /**
34
+ * Parse the given parameter from the source language to the given target language, in the given language.
35
+ * For example, to convert an ArrayBuffer from Swift ({@linkcode from}) to C++ ({@linkcode to}) we
36
+ * have to wrap it in an ArrayBufferHolder in Swift ({@linkcode inLanguage}), and unwrap
37
+ * it from the ArrayBufferHolder again in C++ ({@linkcode inLanguage})
38
+ */
39
+ parse(parameterName: string, from: FromLanguage, to: ToLanguage, inLanguage: FromLanguage | ToLanguage): string;
40
+ parse(parameterName: string, from: ToLanguage, to: FromLanguage, inLanguage: FromLanguage | ToLanguage): string;
41
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,23 @@
1
+ import type { Language } from '../getPlatformSpecs.js';
2
+ import type { SourceFile, SourceImport } from './SourceFile.js';
3
+ export interface CodeNode {
4
+ /**
5
+ * Get the code of this code node (e.g. property, method) in the given language.
6
+ */
7
+ getCode(language: Language): string;
8
+ /**
9
+ * Get all extra definition files this code node needs (e.g. extra type/struct declarations
10
+ * for complex types), or `[]` if none are required (e.g. if this uses primitive types only)
11
+ *
12
+ * All files returned here must be created in the project.
13
+ * To include them, see {@linkcode getRequiredImports | getRequiredImports()}
14
+ */
15
+ getExtraFiles(): SourceFile[];
16
+ /**
17
+ * Get all required imports this code node needs (e.g. extra type/struct declarations for complex types),
18
+ * or `[]` if no imports are required (e.g. if this uses primitive types only).
19
+ *
20
+ * All imports returned here must be included in the current file (e.g. `#include "..."` or `import ...`)
21
+ */
22
+ getRequiredImports(language: Language): SourceImport[];
23
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ import type { NitroConfig } from '../config/NitroConfig.js';
2
+ import type { Language } from '../getPlatformSpecs.js';
3
+ import type { Method } from './Method.js';
4
+ import type { Property } from './Property.js';
5
+ export interface HybridObjectSpec {
6
+ name: string;
7
+ language: Language;
8
+ properties: Property[];
9
+ methods: Method[];
10
+ baseTypes: HybridObjectSpec[];
11
+ isHybridView: boolean;
12
+ config: NitroConfig;
13
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,41 @@
1
+ import type { CodeNode } from './CodeNode.js';
2
+ import type { Language } from '../getPlatformSpecs.js';
3
+ import { type SourceFile, type SourceImport } from './SourceFile.js';
4
+ import { Parameter } from './Parameter.js';
5
+ import type { Type } from './types/Type.js';
6
+ export type MethodBody = string;
7
+ export interface MethodModifiers {
8
+ /**
9
+ * The name of the class that defines this C++ method.
10
+ * Example: `Person` -> `void Person::sayHi()`
11
+ */
12
+ classDefinitionName?: string;
13
+ /**
14
+ * Whether the function should be marked as inlineable.
15
+ */
16
+ inline?: boolean;
17
+ virtual?: boolean;
18
+ /**
19
+ * Whether the function is marked as `noexcept` (doesn't throw) or not.
20
+ */
21
+ noexcept?: boolean;
22
+ /**
23
+ * Whether this function overrides a base/super function.
24
+ */
25
+ override?: boolean;
26
+ /**
27
+ * Whether this method has a `@DoNotStrip` and `@Keep` attribute to avoid
28
+ * it from being stripped from the binary by the Java compiler or ProGuard.
29
+ */
30
+ doNotStrip?: boolean;
31
+ }
32
+ export declare class Method implements CodeNode {
33
+ readonly name: string;
34
+ readonly returnType: Type;
35
+ readonly parameters: Parameter[];
36
+ constructor(name: string, returnType: Type, parameters: Parameter[]);
37
+ get jsSignature(): string;
38
+ getCode(language: Language, modifiers?: MethodModifiers, body?: MethodBody): string;
39
+ getExtraFiles(): SourceFile[];
40
+ getRequiredImports(language: Language): SourceImport[];
41
+ }
@@ -0,0 +1,108 @@
1
+ import {} from './SourceFile.js';
2
+ import { Parameter } from './Parameter.js';
3
+ import { indent } from '../utils.js';
4
+ export class Method {
5
+ name;
6
+ returnType;
7
+ parameters;
8
+ constructor(name, returnType, parameters) {
9
+ this.name = name;
10
+ this.returnType = returnType;
11
+ this.parameters = parameters;
12
+ if (this.name.startsWith('__')) {
13
+ throw new Error(`Method names are not allowed to start with two underscores (__)! (In ${this.jsSignature})`);
14
+ }
15
+ }
16
+ get jsSignature() {
17
+ const returnType = this.returnType.kind;
18
+ const params = this.parameters.map((p) => `${p.name}: ${p.type.kind}`);
19
+ return `${this.name}(${params.join(', ')}): ${returnType}`;
20
+ }
21
+ getCode(language, modifiers, body) {
22
+ body = body?.trim();
23
+ switch (language) {
24
+ case 'c++': {
25
+ const returnType = this.returnType.getCode('c++');
26
+ const params = this.parameters.map((p) => p.getCode('c++'));
27
+ // C++ modifiers start in the beginning
28
+ const name = modifiers?.classDefinitionName
29
+ ? `${modifiers.classDefinitionName}::${this.name}`
30
+ : this.name;
31
+ let signature = `${returnType} ${name}(${params.join(', ')})`;
32
+ if (modifiers?.inline)
33
+ signature = `inline ${signature}`;
34
+ if (modifiers?.virtual)
35
+ signature = `virtual ${signature}`;
36
+ if (modifiers?.noexcept)
37
+ signature = `${signature} noexcept`;
38
+ if (modifiers?.override)
39
+ signature = `${signature} override`;
40
+ if (body == null) {
41
+ // It's a function declaration (no body)
42
+ if (modifiers?.virtual) {
43
+ // if it is a virtual function, we have no implementation (= 0)
44
+ signature = `${signature} = 0`;
45
+ }
46
+ return `${signature};`;
47
+ }
48
+ else {
49
+ return `
50
+ ${signature} {
51
+ ${indent(body, ' ')}
52
+ }`.trim();
53
+ }
54
+ }
55
+ case 'swift': {
56
+ const params = this.parameters.map((p) => p.getCode('swift'));
57
+ const returnType = this.returnType.getCode('swift');
58
+ let signature = `func ${this.name}(${params.join(', ')}) throws -> ${returnType}`;
59
+ if (modifiers?.inline)
60
+ signature = `@inline(__always)\n${signature}`;
61
+ if (body == null) {
62
+ return signature;
63
+ }
64
+ else {
65
+ return `
66
+ ${signature} {
67
+ ${indent(body, ' ')}
68
+ }`.trim();
69
+ }
70
+ }
71
+ case 'kotlin': {
72
+ const params = this.parameters.map((p) => p.getCode('kotlin'));
73
+ const returnType = this.returnType.getCode('kotlin');
74
+ let signature = `fun ${this.name}(${params.join(', ')}): ${returnType}`;
75
+ if (modifiers?.inline)
76
+ signature = `inline ${signature}`;
77
+ if (modifiers?.override)
78
+ signature = `override ${signature}`;
79
+ if (modifiers?.virtual)
80
+ signature = `abstract ${signature}`;
81
+ if (modifiers?.doNotStrip)
82
+ signature = `@DoNotStrip\n@Keep\n${signature}`;
83
+ if (body == null) {
84
+ return signature;
85
+ }
86
+ else {
87
+ return `
88
+ ${signature} {
89
+ ${indent(body, ' ')}
90
+ }
91
+ `.trim();
92
+ }
93
+ }
94
+ default:
95
+ throw new Error(`Language ${language} is not yet supported for property getters!`);
96
+ }
97
+ }
98
+ getExtraFiles() {
99
+ const returnTypeExtraFiles = this.returnType.getExtraFiles();
100
+ const paramsExtraFiles = this.parameters.flatMap((p) => p.getExtraFiles());
101
+ return [...returnTypeExtraFiles, ...paramsExtraFiles];
102
+ }
103
+ getRequiredImports(language) {
104
+ const returnTypeFiles = this.returnType.getRequiredImports(language);
105
+ const paramsImports = this.parameters.flatMap((p) => p.getRequiredImports(language));
106
+ return [...returnTypeFiles, ...paramsImports];
107
+ }
108
+ }
@@ -0,0 +1,15 @@
1
+ import type { ParameterDeclaration } from 'ts-morph';
2
+ import type { CodeNode } from './CodeNode.js';
3
+ import type { Language } from '../getPlatformSpecs.js';
4
+ import { type SourceFile, type SourceImport } from './SourceFile.js';
5
+ import type { NamedType, Type } from './types/Type.js';
6
+ export declare class Parameter implements CodeNode {
7
+ readonly type: NamedType;
8
+ constructor(name: string, type: Type);
9
+ constructor(parameter: ParameterDeclaration, language: Language);
10
+ get jsSignature(): string;
11
+ get name(): string;
12
+ getCode(language: Language): string;
13
+ getExtraFiles(): SourceFile[];
14
+ getRequiredImports(language: Language): SourceImport[];
15
+ }
@@ -0,0 +1,65 @@
1
+ import { escapeCppName, toReferenceType } from './helpers.js';
2
+ import {} from './SourceFile.js';
3
+ import { NamedWrappingType } from './types/NamedWrappingType.js';
4
+ import { createNamedType } from './createType.js';
5
+ export class Parameter {
6
+ type;
7
+ constructor(...args) {
8
+ if (typeof args[0] === 'string' && typeof args[1] === 'object') {
9
+ // constructor(...) #1
10
+ if (args.length !== 2)
11
+ throw new Error(`Missing arguments for new Parameter(...) overload #1!`);
12
+ const [name, type] = args;
13
+ this.type = new NamedWrappingType(name, type);
14
+ }
15
+ else if (typeof args[0] === 'object' && typeof args[1] === 'string') {
16
+ // constructor(...) #2
17
+ const [param, language] = args;
18
+ const name = param.getSymbolOrThrow().getEscapedName();
19
+ const type = param.getType();
20
+ const isOptional = param.hasQuestionToken() || param.isOptional() || type.isNullable();
21
+ this.type = createNamedType(language, name, type, isOptional);
22
+ }
23
+ else {
24
+ // constructor(...)???
25
+ throw new Error(`Invalid constructor! Arguments: ${args}`);
26
+ }
27
+ if (this.type.name.startsWith('__')) {
28
+ throw new Error(`Parameter names are not allowed to start with two underscores (__)! (In ${this.jsSignature})`);
29
+ }
30
+ }
31
+ get jsSignature() {
32
+ return `${this.type.name}: ${this.type.kind}`;
33
+ }
34
+ get name() {
35
+ return this.type.name;
36
+ }
37
+ getCode(language) {
38
+ const name = escapeCppName(this.name);
39
+ switch (language) {
40
+ case 'c++':
41
+ let cppType = this.type.getCode('c++');
42
+ if (this.type.canBePassedByReference) {
43
+ // T -> const T&
44
+ cppType = toReferenceType(cppType);
45
+ }
46
+ return `${cppType} ${name}`;
47
+ case 'swift':
48
+ let flags = '';
49
+ if (this.type.kind === 'function') {
50
+ flags = '@escaping ';
51
+ }
52
+ return `${name}: ${flags + this.type.getCode('swift')}`;
53
+ case 'kotlin':
54
+ return `${name}: ${this.type.getCode('kotlin')}`;
55
+ default:
56
+ throw new Error(`Language ${language} is not yet supported for parameters!`);
57
+ }
58
+ }
59
+ getExtraFiles() {
60
+ return this.type.getExtraFiles();
61
+ }
62
+ getRequiredImports(language) {
63
+ return this.type.getRequiredImports(language);
64
+ }
65
+ }