@snap/camera-kit 0.11.0 → 0.13.0

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 (319) hide show
  1. package/README.md +264 -67
  2. package/docs/html/assets/search.js +1 -1
  3. package/docs/html/classes/CameraKit.html +12 -7
  4. package/docs/html/classes/CameraKitSession.html +27 -7
  5. package/docs/html/classes/CameraKitSource.html +26 -17
  6. package/docs/html/classes/LensPerformanceMeasurement.html +12 -7
  7. package/docs/html/classes/LensPerformanceMetrics.html +12 -7
  8. package/docs/html/classes/LensRepository.html +12 -7
  9. package/docs/html/classes/LensSources.html +12 -7
  10. package/docs/html/classes/Transform2D.html +12 -7
  11. package/docs/html/classes/TypedCustomEvent.html +12 -7
  12. package/docs/html/classes/TypedEventTarget.html +12 -7
  13. package/docs/html/functions/Injectable.html +12 -7
  14. package/docs/html/functions/bootstrapCameraKit.html +12 -7
  15. package/docs/html/functions/createExtension.html +12 -7
  16. package/docs/html/functions/createImageSource.html +12 -7
  17. package/docs/html/functions/createMediaStreamSource.html +12 -7
  18. package/docs/html/functions/createUserMediaSource.html +12 -7
  19. package/docs/html/functions/createVideoSource.html +12 -7
  20. package/docs/html/functions/estimateLensPerformance.html +12 -7
  21. package/docs/html/functions/getRequiredBootstrapURLs.html +12 -7
  22. package/docs/html/functions/lensSourcesFactory.html +12 -7
  23. package/docs/html/functions/{uriHandlersFactory.html → remoteApiServicesFactory.html} +16 -14
  24. package/docs/html/index.html +194 -50
  25. package/docs/html/interfaces/CameraKitBootstrapConfiguration.html +12 -7
  26. package/docs/html/interfaces/CameraKitSourceSubscriber.html +12 -7
  27. package/docs/html/interfaces/ComputedFrameMetrics.html +12 -7
  28. package/docs/html/interfaces/CreateSessionOptions.html +12 -7
  29. package/docs/html/interfaces/EstimatedLensPerformance.html +12 -7
  30. package/docs/html/interfaces/Lens.html +12 -7
  31. package/docs/html/interfaces/LensSource.html +16 -11
  32. package/docs/html/interfaces/MediaStreamSourceOptions.html +12 -7
  33. package/docs/html/interfaces/Preview.html +12 -7
  34. package/docs/html/interfaces/RemoteApiRequest.html +164 -0
  35. package/docs/html/interfaces/RemoteApiResponse.html +156 -0
  36. package/docs/html/interfaces/{UriHandler.html → RemoteApiService.html} +34 -68
  37. package/docs/html/interfaces/Snapcode.html +12 -7
  38. package/docs/html/interfaces/UriCancelRequest.html +12 -7
  39. package/docs/html/interfaces/UriRequest.html +20 -10
  40. package/docs/html/interfaces/UriResponse.html +12 -7
  41. package/docs/html/interfaces/VideoSourceOptions.html +12 -7
  42. package/docs/html/modules.html +22 -12
  43. package/docs/html/types/AssetLoader.html +12 -7
  44. package/docs/html/types/AssetTiming.html +12 -7
  45. package/docs/html/types/BenchmarkError.html +12 -7
  46. package/docs/html/types/BootstrapError.html +12 -7
  47. package/docs/html/types/CacheKeyNotFoundError.html +12 -7
  48. package/docs/html/types/CameraKitDeviceInfo.html +19 -9
  49. package/docs/html/types/CameraKitDeviceOptions.html +119 -0
  50. package/docs/html/types/CameraKitSessionEventListener.html +12 -7
  51. package/docs/html/types/CameraKitSessionEvents.html +12 -7
  52. package/docs/html/types/CameraKitSourceError.html +12 -7
  53. package/docs/html/types/CameraKitSourceInfo.html +12 -7
  54. package/docs/html/types/CameraKitSourceOptions.html +13 -8
  55. package/docs/html/types/ConfigurationError.html +12 -7
  56. package/docs/html/types/Keyboard.html +12 -7
  57. package/docs/html/types/KeyboardEvents.html +12 -7
  58. package/docs/html/types/LegalError.html +12 -7
  59. package/docs/html/types/LensAssetError.html +12 -7
  60. package/docs/html/types/LensContentValidationError.html +12 -7
  61. package/docs/html/types/LensError.html +12 -7
  62. package/docs/html/types/LensExecutionError.html +12 -7
  63. package/docs/html/types/LensImagePickerError.html +12 -7
  64. package/docs/html/types/LensLaunchParams.html +12 -7
  65. package/docs/html/types/LensMetricsEvents.html +12 -7
  66. package/docs/html/types/LensPerformanceCluster.html +12 -7
  67. package/docs/html/types/LensView.html +12 -7
  68. package/docs/html/types/LensWait.html +12 -7
  69. package/docs/html/types/PersistentStoreError.html +12 -7
  70. package/docs/html/types/PlatformNotSupportedError.html +12 -7
  71. package/docs/html/types/PublicContainer.html +12 -7
  72. package/docs/html/types/RemoteApiRequestHandler.html +141 -0
  73. package/docs/html/types/{UriHandlers.html → RemoteApiServices.html} +15 -13
  74. package/docs/html/types/RemoteApiStatus.html +114 -0
  75. package/docs/html/types/RenderTarget.html +12 -7
  76. package/docs/html/types/Uri.html +12 -7
  77. package/docs/html/types/WebGLError.html +12 -7
  78. package/docs/html/variables/extensionRequestContext.html +12 -7
  79. package/docs/md/README.md +264 -67
  80. package/docs/md/classes/CameraKit.md +1 -1
  81. package/docs/md/classes/CameraKitSession.md +19 -1
  82. package/docs/md/classes/CameraKitSource.md +19 -7
  83. package/docs/md/classes/LensPerformanceMeasurement.md +1 -1
  84. package/docs/md/classes/LensPerformanceMetrics.md +1 -1
  85. package/docs/md/classes/LensRepository.md +1 -1
  86. package/docs/md/classes/LensSources.md +1 -1
  87. package/docs/md/classes/Transform2D.md +1 -1
  88. package/docs/md/classes/TypedCustomEvent.md +1 -1
  89. package/docs/md/classes/TypedEventTarget.md +1 -1
  90. package/docs/md/interfaces/CameraKitBootstrapConfiguration.md +1 -1
  91. package/docs/md/interfaces/CameraKitSourceSubscriber.md +1 -1
  92. package/docs/md/interfaces/ComputedFrameMetrics.md +1 -1
  93. package/docs/md/interfaces/CreateSessionOptions.md +1 -1
  94. package/docs/md/interfaces/EstimatedLensPerformance.md +1 -1
  95. package/docs/md/interfaces/Lens.md +1 -1
  96. package/docs/md/interfaces/LensSource.md +3 -3
  97. package/docs/md/interfaces/MediaStreamSourceOptions.md +1 -1
  98. package/docs/md/interfaces/Preview.md +1 -1
  99. package/docs/md/interfaces/RemoteApiRequest.md +46 -0
  100. package/docs/md/interfaces/RemoteApiResponse.md +37 -0
  101. package/docs/md/interfaces/RemoteApiService.md +45 -0
  102. package/docs/md/interfaces/Snapcode.md +1 -1
  103. package/docs/md/interfaces/UriCancelRequest.md +1 -1
  104. package/docs/md/interfaces/UriRequest.md +9 -2
  105. package/docs/md/interfaces/UriResponse.md +1 -1
  106. package/docs/md/interfaces/VideoSourceOptions.md +1 -1
  107. package/docs/md/modules.md +66 -15
  108. package/lib/CameraKit.d.ts +16 -6
  109. package/lib/CameraKit.js +3 -1
  110. package/lib/CameraKit.js.map +1 -1
  111. package/lib/__tests__/data.d.ts +1 -1
  112. package/lib/__tests__/data.js +1 -0
  113. package/lib/__tests__/data.js.map +1 -1
  114. package/lib/assertPlatformSupported.d.ts +3 -1
  115. package/lib/assertPlatformSupported.js +13 -2
  116. package/lib/assertPlatformSupported.js.map +1 -1
  117. package/lib/bootstrapCameraKit.js +13 -9
  118. package/lib/bootstrapCameraKit.js.map +1 -1
  119. package/lib/common/any.d.ts +17 -0
  120. package/lib/common/any.js +36 -0
  121. package/lib/common/any.js.map +1 -0
  122. package/lib/common/cameraKitUserAgent.d.ts +5 -0
  123. package/lib/common/cameraKitUserAgent.js +18 -2
  124. package/lib/common/cameraKitUserAgent.js.map +1 -1
  125. package/lib/common/date.d.ts +3 -0
  126. package/lib/common/date.js +13 -0
  127. package/lib/common/date.js.map +1 -0
  128. package/lib/common/dialog.d.ts +43 -0
  129. package/lib/common/dialog.js +26 -12
  130. package/lib/common/dialog.js.map +1 -1
  131. package/lib/common/errorHelpers.js +1 -1
  132. package/lib/common/errorHelpers.js.map +1 -1
  133. package/lib/common/time.d.ts +1 -0
  134. package/lib/common/time.js +1 -0
  135. package/lib/common/time.js.map +1 -1
  136. package/lib/common/types.d.ts +8 -0
  137. package/lib/common/types.js.map +1 -1
  138. package/lib/configuration.d.ts +2 -0
  139. package/lib/configuration.js +1 -0
  140. package/lib/configuration.js.map +1 -1
  141. package/lib/dependency-injection/RootServices.d.ts +4 -0
  142. package/lib/dependency-injection/RootServices.js.map +1 -1
  143. package/lib/environment.json +1 -1
  144. package/lib/extensions/LensSources.d.ts +2 -2
  145. package/lib/extensions/LensSources.js +7 -3
  146. package/lib/extensions/LensSources.js.map +1 -1
  147. package/lib/extensions/RemoteApiServices.d.ts +101 -0
  148. package/lib/extensions/RemoteApiServices.js +198 -0
  149. package/lib/extensions/RemoteApiServices.js.map +1 -0
  150. package/lib/extensions/UriHandlers.d.ts +10 -17
  151. package/lib/extensions/UriHandlers.js +5 -60
  152. package/lib/extensions/UriHandlers.js.map +1 -1
  153. package/lib/extensions/uriHandlersRegister.d.ts +21 -0
  154. package/lib/extensions/uriHandlersRegister.js +72 -0
  155. package/lib/extensions/uriHandlersRegister.js.map +1 -0
  156. package/lib/generated-proto/blizzard/cameraKitEvents.js.map +1 -1
  157. package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.d.ts +0 -26
  158. package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.js +0 -15
  159. package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.js.map +1 -1
  160. package/lib/generated-proto/pb_schema/camera_kit/v3/export.d.ts +0 -59
  161. package/lib/generated-proto/pb_schema/camera_kit/v3/export.js +0 -10
  162. package/lib/generated-proto/pb_schema/camera_kit/v3/export.js.map +1 -1
  163. package/lib/generated-proto/pb_schema/camera_kit/v3/features/remote_api_info.d.ts +31 -0
  164. package/lib/generated-proto/pb_schema/camera_kit/v3/features/remote_api_info.js +43 -0
  165. package/lib/generated-proto/pb_schema/camera_kit/v3/features/remote_api_info.js.map +1 -0
  166. package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.d.ts +0 -13
  167. package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.js +0 -7
  168. package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.js.map +1 -1
  169. package/lib/generated-proto/pb_schema/camera_kit/v3/lens.d.ts +0 -55
  170. package/lib/generated-proto/pb_schema/camera_kit/v3/lens.js +0 -12
  171. package/lib/generated-proto/pb_schema/camera_kit/v3/lens.js.map +1 -1
  172. package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.d.ts +0 -5
  173. package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.js +0 -7
  174. package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.js.map +1 -1
  175. package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.d.ts +0 -23
  176. package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.js +0 -15
  177. package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.js.map +1 -1
  178. package/lib/generated-proto/pb_schema/camera_kit/v3/service.d.ts +0 -62
  179. package/lib/generated-proto/pb_schema/camera_kit/v3/service.js +0 -1
  180. package/lib/generated-proto/pb_schema/camera_kit/v3/service.js.map +1 -1
  181. package/lib/generated-proto/pb_schema/cdp/cof/benchmark.d.ts +0 -8
  182. package/lib/generated-proto/pb_schema/cdp/cof/benchmark.js +0 -1
  183. package/lib/generated-proto/pb_schema/cdp/cof/benchmark.js.map +1 -1
  184. package/lib/generated-proto/pb_schema/cdp/cof/benchmark_name.d.ts +0 -45
  185. package/lib/generated-proto/pb_schema/cdp/cof/benchmark_name.js +0 -46
  186. package/lib/generated-proto/pb_schema/cdp/cof/benchmark_name.js.map +1 -1
  187. package/lib/generated-proto/pb_schema/cdp/cof/circumstance_service.d.ts +0 -104
  188. package/lib/generated-proto/pb_schema/cdp/cof/circumstance_service.js +0 -1
  189. package/lib/generated-proto/pb_schema/cdp/cof/circumstance_service.js.map +1 -1
  190. package/lib/generated-proto/pb_schema/cdp/cof/config_request.d.ts +0 -129
  191. package/lib/generated-proto/pb_schema/cdp/cof/config_request.js +0 -24
  192. package/lib/generated-proto/pb_schema/cdp/cof/config_request.js.map +1 -1
  193. package/lib/generated-proto/pb_schema/cdp/cof/config_response.d.ts +0 -22
  194. package/lib/generated-proto/pb_schema/cdp/cof/config_response.js +0 -1
  195. package/lib/generated-proto/pb_schema/cdp/cof/config_response.js.map +1 -1
  196. package/lib/generated-proto/pb_schema/cdp/cof/config_result.d.ts +0 -510
  197. package/lib/generated-proto/pb_schema/cdp/cof/config_result.js +0 -415
  198. package/lib/generated-proto/pb_schema/cdp/cof/config_result.js.map +1 -1
  199. package/lib/generated-proto/pb_schema/cdp/cof/debug_info.d.ts +0 -9
  200. package/lib/generated-proto/pb_schema/cdp/cof/debug_info.js +0 -3
  201. package/lib/generated-proto/pb_schema/cdp/cof/debug_info.js.map +1 -1
  202. package/lib/generated-proto/pb_schema/cdp/cof/namespace.d.ts +1 -1
  203. package/lib/generated-proto/pb_schema/cdp/cof/namespace.js +1 -2
  204. package/lib/generated-proto/pb_schema/cdp/cof/namespace.js.map +1 -1
  205. package/lib/generated-proto/pb_schema/common/ruid.d.ts +0 -27
  206. package/lib/generated-proto/pb_schema/common/ruid.js +0 -20
  207. package/lib/generated-proto/pb_schema/common/ruid.js.map +1 -1
  208. package/lib/generated-proto/pb_schema/common/value.d.ts +0 -9
  209. package/lib/generated-proto/pb_schema/common/value.js +0 -1
  210. package/lib/generated-proto/pb_schema/common/value.js.map +1 -1
  211. package/lib/generated-proto/pb_schema/google/protobuf/any.d.ts +0 -105
  212. package/lib/generated-proto/pb_schema/google/protobuf/any.js +0 -1
  213. package/lib/generated-proto/pb_schema/google/protobuf/any.js.map +1 -1
  214. package/lib/generated-proto/pb_schema/google/protobuf/timestamp.d.ts +0 -64
  215. package/lib/generated-proto/pb_schema/google/protobuf/timestamp.js +0 -1
  216. package/lib/generated-proto/pb_schema/google/protobuf/timestamp.js.map +1 -1
  217. package/lib/generated-proto/pb_schema/google/protobuf/wrappers.d.ts +0 -54
  218. package/lib/generated-proto/pb_schema/google/protobuf/wrappers.js +0 -1
  219. package/lib/generated-proto/pb_schema/google/protobuf/wrappers.js.map +1 -1
  220. package/lib/generated-proto/pb_schema/lenses/geocircle.js +0 -1
  221. package/lib/generated-proto/pb_schema/lenses/geocircle.js.map +1 -1
  222. package/lib/generated-proto/pb_schema/lenses/geopoint.js +0 -1
  223. package/lib/generated-proto/pb_schema/lenses/geopoint.js.map +1 -1
  224. package/lib/generated-proto/pb_schema/lenses/launch_params.js +0 -1
  225. package/lib/generated-proto/pb_schema/lenses/launch_params.js.map +1 -1
  226. package/lib/generated-proto/pb_schema/lenses/launchdata.d.ts +0 -2
  227. package/lib/generated-proto/pb_schema/lenses/launchdata.js +0 -3
  228. package/lib/generated-proto/pb_schema/lenses/launchdata.js.map +1 -1
  229. package/lib/generated-proto/pb_schema/lenses/lures.d.ts +0 -2
  230. package/lib/generated-proto/pb_schema/lenses/lures.js +0 -1
  231. package/lib/generated-proto/pb_schema/lenses/lures.js.map +1 -1
  232. package/lib/generated-proto/pb_schema/lenses/persistent_store.js +0 -1
  233. package/lib/generated-proto/pb_schema/lenses/persistent_store.js.map +1 -1
  234. package/lib/generated-proto/pb_schema/lenses/remote_api/remote_api_service.d.ts +569 -0
  235. package/lib/generated-proto/pb_schema/lenses/remote_api/remote_api_service.js +1175 -0
  236. package/lib/generated-proto/pb_schema/lenses/remote_api/remote_api_service.js.map +1 -0
  237. package/lib/generated-proto/pb_schema/lenses/snappable.d.ts +0 -19
  238. package/lib/generated-proto/pb_schema/lenses/snappable.js +0 -2
  239. package/lib/generated-proto/pb_schema/lenses/snappable.js.map +1 -1
  240. package/lib/generated-proto/pb_schema/lenses/user_data.d.ts +0 -18
  241. package/lib/generated-proto/pb_schema/lenses/user_data.js +0 -1
  242. package/lib/generated-proto/pb_schema/lenses/user_data.js.map +1 -1
  243. package/lib/handlers/defaultFetchHandler.js +17 -4
  244. package/lib/handlers/defaultFetchHandler.js.map +1 -1
  245. package/lib/index.d.ts +1 -0
  246. package/lib/index.js +1 -0
  247. package/lib/index.js.map +1 -1
  248. package/lib/legal/legalPrompt.js +29 -27
  249. package/lib/legal/legalPrompt.js.map +1 -1
  250. package/lib/legal/legalState.js +1 -1
  251. package/lib/legal/legalState.js.map +1 -1
  252. package/lib/lens/LensRepository.d.ts +5 -3
  253. package/lib/lens/LensRepository.js +8 -5
  254. package/lib/lens/LensRepository.js.map +1 -1
  255. package/lib/lens/assets/LensAssetsProvider.js +18 -3
  256. package/lib/lens/assets/LensAssetsProvider.js.map +1 -1
  257. package/lib/lens/lensHttpUtil.d.ts +3 -2
  258. package/lib/lens/lensHttpUtil.js +31 -9
  259. package/lib/lens/lensHttpUtil.js.map +1 -1
  260. package/lib/lens-core-module/generated-types.d.ts +42 -1
  261. package/lib/lens-core-module/generated-types.js.map +1 -1
  262. package/lib/lensCoreWasmVersions.json +3 -3
  263. package/lib/logger/registerLogEntriesSubscriber.js +13 -1
  264. package/lib/logger/registerLogEntriesSubscriber.js.map +1 -1
  265. package/lib/media-sources/CameraKitSource.d.ts +13 -3
  266. package/lib/media-sources/CameraKitSource.js +2 -8
  267. package/lib/media-sources/CameraKitSource.js.map +1 -1
  268. package/lib/media-sources/FunctionSource.d.ts +1 -1
  269. package/lib/media-sources/FunctionSource.js +1 -1
  270. package/lib/media-sources/FunctionSource.js.map +1 -1
  271. package/lib/media-sources/ImageSource.d.ts +1 -1
  272. package/lib/media-sources/ImageSource.js +1 -1
  273. package/lib/media-sources/ImageSource.js.map +1 -1
  274. package/lib/media-sources/MediaStreamSource.d.ts +1 -1
  275. package/lib/media-sources/MediaStreamSource.js +6 -1
  276. package/lib/media-sources/MediaStreamSource.js.map +1 -1
  277. package/lib/media-sources/VideoSource.d.ts +1 -1
  278. package/lib/media-sources/VideoSource.js +1 -1
  279. package/lib/media-sources/VideoSource.js.map +1 -1
  280. package/lib/metrics/businessEventsReporter.d.ts +4 -2
  281. package/lib/metrics/businessEventsReporter.js +134 -68
  282. package/lib/metrics/businessEventsReporter.js.map +1 -1
  283. package/lib/metrics/operational/operationalMetricsReporter.d.ts +3 -2
  284. package/lib/metrics/operational/operationalMetricsReporter.js +31 -11
  285. package/lib/metrics/operational/operationalMetricsReporter.js.map +1 -1
  286. package/lib/metrics/reporters/reportHttpMetrics.d.ts +0 -7
  287. package/lib/metrics/reporters/reportHttpMetrics.js +3 -2
  288. package/lib/metrics/reporters/reportHttpMetrics.js.map +1 -1
  289. package/lib/metrics/reporters/reportLensView.d.ts +1 -1
  290. package/lib/metrics/reporters/reportLensView.js +41 -13
  291. package/lib/metrics/reporters/reportLensView.js.map +1 -1
  292. package/lib/metrics/reporters/reportUserSession.js +15 -16
  293. package/lib/metrics/reporters/reportUserSession.js.map +1 -1
  294. package/lib/metrics/reporters/reporters.d.ts +1 -1
  295. package/lib/persistence/ExpiringPersistence.d.ts +2 -1
  296. package/lib/persistence/ExpiringPersistence.js +15 -1
  297. package/lib/persistence/ExpiringPersistence.js.map +1 -1
  298. package/lib/persistence/IndexedDBPersistence.d.ts +1 -1
  299. package/lib/persistence/IndexedDBPersistence.js +11 -1
  300. package/lib/persistence/IndexedDBPersistence.js.map +1 -1
  301. package/lib/persistence/Persistence.d.ts +1 -1
  302. package/lib/persistence/Persistence.js.map +1 -1
  303. package/lib/remote-configuration/cofHandler.d.ts +10 -6
  304. package/lib/remote-configuration/cofHandler.js +77 -67
  305. package/lib/remote-configuration/cofHandler.js.map +1 -1
  306. package/lib/remote-configuration/preloadConfiguration.d.ts +7 -0
  307. package/lib/remote-configuration/preloadConfiguration.js +15 -0
  308. package/lib/remote-configuration/preloadConfiguration.js.map +1 -0
  309. package/lib/remote-configuration/remoteConfiguration.d.ts +14 -7
  310. package/lib/remote-configuration/remoteConfiguration.js +15 -15
  311. package/lib/remote-configuration/remoteConfiguration.js.map +1 -1
  312. package/lib/session/CameraKitSession.d.ts +7 -2
  313. package/lib/session/CameraKitSession.js +1 -0
  314. package/lib/session/CameraKitSession.js.map +1 -1
  315. package/lib/session/sessionState.d.ts +2 -2
  316. package/lib/session/sessionState.js +3 -3
  317. package/lib/session/sessionState.js.map +1 -1
  318. package/package.json +2 -1
  319. package/docs/md/interfaces/UriHandler.md +0 -63
@@ -1 +1 @@
1
- {"version":3,"file":"time.js","sourceRoot":"","sources":["../../src/common/time.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,SAAS,GAAG,GAAG,EAAE,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC","sourcesContent":["export const getTimeMs = () => performance.now();\n"]}
1
+ {"version":3,"file":"time.js","sourceRoot":"","sources":["../../src/common/time.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,SAAS,GAAG,GAAG,EAAE,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC;AAEjD,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC","sourcesContent":["export const getTimeMs = () => performance.now();\n\nexport const convertDaysToSeconds = (days: number) => days * 24 * 60 * 60;\n"]}
@@ -7,4 +7,12 @@
7
7
  */
8
8
  type _TupleOf<T, N extends number, R extends unknown[]> = R["length"] extends N ? R : _TupleOf<T, N, [T, ...R]>;
9
9
  export type TupleOf<T, N extends number> = N extends N ? (number extends N ? T[] : _TupleOf<T, N, []>) : never;
10
+ /**
11
+ * Converts snake_case string literal types to camelCase.
12
+ */
13
+ export type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U}` ? `${T}${Capitalize<SnakeToCamelCase<U>>}` : S;
14
+ /**
15
+ * Converts camelCase string literal types to snake_case.
16
+ */
17
+ export type CamelToSnakeCase<S extends string> = S extends `${infer T}${infer U}` ? `${T extends Capitalize<T> ? "_" : ""}${Lowercase<T>}${CamelToSnakeCase<U>}` : S;
10
18
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/common/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * For instances where we'd like to define a Tuple to be of certain type and length.\n * Example: TupleOf<number, 3> // [number, number, number]\n *\n * For more example and use cases regarding Recursive conditional types\n * see: https://github.com/microsoft/TypeScript/pull/40002\n */\ntype _TupleOf<T, N extends number, R extends unknown[]> = R[\"length\"] extends N ? R : _TupleOf<T, N, [T, ...R]>;\nexport type TupleOf<T, N extends number> = N extends N ? (number extends N ? T[] : _TupleOf<T, N, []>) : never;\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/common/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * For instances where we'd like to define a Tuple to be of certain type and length.\n * Example: TupleOf<number, 3> // [number, number, number]\n *\n * For more example and use cases regarding Recursive conditional types\n * see: https://github.com/microsoft/TypeScript/pull/40002\n */\ntype _TupleOf<T, N extends number, R extends unknown[]> = R[\"length\"] extends N ? R : _TupleOf<T, N, [T, ...R]>;\nexport type TupleOf<T, N extends number> = N extends N ? (number extends N ? T[] : _TupleOf<T, N, []>) : never;\n\n/**\n * Converts snake_case string literal types to camelCase.\n */\nexport type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U}`\n ? `${T}${Capitalize<SnakeToCamelCase<U>>}`\n : S;\n\n/**\n * Converts camelCase string literal types to snake_case.\n */\nexport type CamelToSnakeCase<S extends string> = S extends `${infer T}${infer U}`\n ? `${T extends Capitalize<T> ? \"_\" : \"\"}${Lowercase<T>}${CamelToSnakeCase<U>}`\n : S;\n"]}
@@ -5,7 +5,9 @@ interface CameraKitRuntimeConfiguration {
5
5
  logger: "noop" | "console";
6
6
  logLevel: LogLevelName;
7
7
  shouldUseWorker: boolean;
8
+ apiHostname: CameraKitApiHostname;
8
9
  }
10
+ export type CameraKitApiHostname = "camera-kit-api.snapar.com" | "api-kit.snapchat.com";
9
11
  /**
10
12
  * Configuration which must be provided when calling {@link bootstrapCameraKit}. These values are used to create various
11
13
  * CameraKit components.
@@ -13,6 +13,7 @@ const defaultConfiguration = {
13
13
  logger: "noop",
14
14
  logLevel: "info",
15
15
  shouldUseWorker: true,
16
+ apiHostname: "camera-kit-api.snapar.com",
16
17
  };
17
18
  /** @internal */
18
19
  export const configurationToken = "configuration";
@@ -1 +1 @@
1
- {"version":3,"file":"configuration.js","sourceRoot":"","sources":["../src/configuration.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACvE,OAAO,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAC;AAU/D;;;GAGG;AACH,MAAM,oBAAoB,GAAmF;IACzG,mHAAmH;IACnH,6GAA6G;IAC7G,qFAAqF;IACrF,eAAe,EAAE,EAAE,OAAO,EAAE,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,iBAAiB,EAAE,SAAS,EAAE;IAC7E,MAAM,EAAE,MAAM;IACd,QAAQ,EAAE,MAAM;IAChB,eAAe,EAAE,IAAI;CACxB,CAAC;AAwFF,gBAAgB;AAChB,MAAM,CAAC,MAAM,kBAAkB,GAAG,eAAe,CAAC;AAElD,gBAAgB;AAChB,MAAM,CAAC,MAAM,mCAAmC,GAAG,CAAC,aAA8C,EAAE,EAAE;IAClG,6DAA6D;IAC7D,MAAM,SAAS,GAAG,yBAAyB,EAAE,CAAC;IAC9C,IAAI,SAAS,EAAE;QACX,OAAO,CAAC,IAAI,CAAC,iCAAiC,EAAE,SAAS,CAAC,CAAC;KAC9D;IACD,OAAO,UAAU,CAAC,kBAAkB,EAAE,GAA2B,EAAE;QAC/D,uGAAuG;QACvG,kFAAkF;QAClF,MAAM,UAAU,mCACT,aAAa,KAChB,eAAe,EACX,aAAa,CAAC,eAAe,YAAY,OAAO;gBAC5C,CAAC,CAAC,kFAAkF;oBAClF,aAAa,CAAC,eAAe,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,oBAAoB,CAAC,eAAgB,CAAC;gBAClF,CAAC,CAAC,aAAa,CAAC,eAAe,GAC1C,CAAC;QACF,qDACO,oBAAoB,GACpB,qBAAqB,CAAC,UAAU,CAAC,GACjC,qBAAqB,CAAC,SAAS,aAAT,SAAS,cAAT,SAAS,GAAI,EAAE,CAAC,EAC3C;IACN,CAAC,CAAC,CAAC;AACP,CAAC,CAAC","sourcesContent":["import { EstimatedLensPerformance } from \"./benchmark/estimateLensPerformanceCluster\";\nimport { copyDefinedProperties } from \"./common/copyDefinedProperties\";\nimport { getConfigurationOverrides } from \"./configurationOverrides\";\nimport { Injectable } from \"./dependency-injection/Injectable\";\nimport { LogLevelName } from \"./logger/logger\";\n\n/**\n * From T, pick the set of properties whose values are optional. Create a new type containing only those properties.\n */\ntype PickOptionals<T> = {\n [K in keyof T as T[K] extends Exclude<T[K], undefined> ? never : K]: T[K];\n};\n\n/**\n * Defaults are provided for runtime configuration and any optional bootstrap configuration properties which require\n * defaults.\n */\nconst defaultConfiguration: CameraKitRuntimeConfiguration & PickOptionals<CameraKitBootstrapConfiguration> = {\n // If the applications doesn't provide performance data (e.g. via estimateLensPerformance), we'll use 0 to indicate\n // no performance estimation occurred. This is indicative of typical performance-targeting logic, which often\n // defaults to the lowest-tier experience in the absense of performance cluster data.\n lensPerformance: { cluster: 0, benchmarks: [], webglRendererInfo: \"unknown\" },\n logger: \"noop\",\n logLevel: \"info\",\n shouldUseWorker: true,\n};\n\ninterface CameraKitRuntimeConfiguration {\n lensPerformance: EstimatedLensPerformance | Promise<EstimatedLensPerformance>;\n logger: \"noop\" | \"console\";\n logLevel: LogLevelName;\n shouldUseWorker: boolean;\n}\n\n/**\n * Configuration which must be provided when calling {@link bootstrapCameraKit}. These values are used to create various\n * CameraKit components.\n *\n * @category Bootstrapping and Configuration\n */\nexport interface CameraKitBootstrapConfiguration {\n /**\n * Long-lived token granting your application access to CameraKit APIs. This is found in the SnapKit Dev Portal,\n * where it's called the API Token.\n */\n apiToken: string;\n\n /**\n * Determine where to print CameraKit log messages. By default no logs will be printed.\n *\n * CameraKit emits log messages to help diagnose and root cause issues that may occur during the development of a\n * host application. The printing of these can be controlled via the following\n * options:\n * - `noop`: log messages are ignored.\n * - `console`: log messages are printed to console.\n */\n logger?: \"noop\" | \"console\";\n\n /**\n * Log only if a logged entry level is greater than or equal to this level. Here is the order of levels:\n * error > warn > log = info > debug. Default value is \"info\".\n */\n logLevel?: LogLevelName;\n\n /**\n * Some lenses may decide to modify their behavior based on the performance of the current environment. If you are\n * using such lenses, providing an estimation of lens performance may lead to better user experience (especially on\n * low-performance devices).\n *\n * Running the {@link estimateLensPerformance} function will run benchmarks and estimate an appropriate lens\n * performance cluster (i.e. a performance rating) based on the current environment.\n *\n * Lower cluster = worse expected performance capability.\n *\n * @example\n * ```ts\n * import { bootstrapCameraKit, estimateLensPerformance } from '@snap/camera-kit`\n *\n * const cameraKit = await bootstrapCameraKit({\n * apiToken: '...',\n * lensPerformance: estimateLensPerformance(),\n * })\n * ```\n */\n lensPerformance?: EstimatedLensPerformance | Promise<EstimatedLensPerformance>;\n\n /**\n * In recommended production deployments, the WebAssembly assets required by CameraKit will be downloaded from an\n * optimized CDN. But sometimes (e.g. during development or within a CI pipeline), it may be necessary to download\n * these assets from somewhere else.\n *\n * This configuration option allows the application to specify URLs to be used for both the WebAssembly and JS glue\n * file that are used to run and interact with CameraKit's rendering engine.\n */\n lensCoreOverrideUrls?: { wasm: string; js: string };\n\n /**\n * In recommended production deployments, the WebAssembly assets required by CameraKit will be downloaded from an\n * optimized CDN. But sometimes during development or within a CI pipeline, it may be necessary to download these\n * assets from somewhere else. With a provided `wasmEndpointOverride`, asset URLs will be automatically generated\n * based on this root endpoint.\n */\n wasmEndpointOverride?: string;\n}\n\n/**\n * This type represents the result of merging user-supplied config with default config -- as such, it has no nullable\n * fields, making it a more convenient type for other components to use.\n *\n * @internal\n */\nexport type CameraKitConfiguration = CameraKitRuntimeConfiguration & CameraKitBootstrapConfiguration;\n\n/** @internal */\nexport const configurationToken = \"configuration\";\n\n/** @internal */\nexport const createCameraKitConfigurationFactory = (configuration: CameraKitBootstrapConfiguration) => {\n // always leave debug mode warning about overrides in console\n const overrides = getConfigurationOverrides();\n if (overrides) {\n console.warn(\"Configuration overrides applied\", overrides);\n }\n return Injectable(configurationToken, (): CameraKitConfiguration => {\n // We'll ensure that we handle errors on any Promises passed as config values, otherwise we either must\n // handle them separately wherever they're used, or rejections would go unhandled.\n const safeConfig: CameraKitBootstrapConfiguration = {\n ...configuration,\n lensPerformance:\n configuration.lensPerformance instanceof Promise\n ? // Safety: defaultConfiguration.lensPerformance is defined (it's hardcoded above).\n configuration.lensPerformance.catch(() => defaultConfiguration.lensPerformance!)\n : configuration.lensPerformance,\n };\n return {\n ...defaultConfiguration,\n ...copyDefinedProperties(safeConfig),\n ...copyDefinedProperties(overrides ?? {}),\n };\n });\n};\n"]}
1
+ {"version":3,"file":"configuration.js","sourceRoot":"","sources":["../src/configuration.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACvE,OAAO,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAC;AAU/D;;;GAGG;AACH,MAAM,oBAAoB,GAAmF;IACzG,mHAAmH;IACnH,6GAA6G;IAC7G,qFAAqF;IACrF,eAAe,EAAE,EAAE,OAAO,EAAE,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,iBAAiB,EAAE,SAAS,EAAE;IAC7E,MAAM,EAAE,MAAM;IACd,QAAQ,EAAE,MAAM;IAChB,eAAe,EAAE,IAAI;IACrB,WAAW,EAAE,2BAA2B;CAC3C,CAAC;AA2FF,gBAAgB;AAChB,MAAM,CAAC,MAAM,kBAAkB,GAAG,eAAe,CAAC;AAElD,gBAAgB;AAChB,MAAM,CAAC,MAAM,mCAAmC,GAAG,CAAC,aAA8C,EAAE,EAAE;IAClG,6DAA6D;IAC7D,MAAM,SAAS,GAAG,yBAAyB,EAAE,CAAC;IAC9C,IAAI,SAAS,EAAE;QACX,OAAO,CAAC,IAAI,CAAC,iCAAiC,EAAE,SAAS,CAAC,CAAC;KAC9D;IACD,OAAO,UAAU,CAAC,kBAAkB,EAAE,GAA2B,EAAE;QAC/D,uGAAuG;QACvG,kFAAkF;QAClF,MAAM,UAAU,mCACT,aAAa,KAChB,eAAe,EACX,aAAa,CAAC,eAAe,YAAY,OAAO;gBAC5C,CAAC,CAAC,kFAAkF;oBAClF,aAAa,CAAC,eAAe,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,oBAAoB,CAAC,eAAgB,CAAC;gBAClF,CAAC,CAAC,aAAa,CAAC,eAAe,GAC1C,CAAC;QACF,qDACO,oBAAoB,GACpB,qBAAqB,CAAC,UAAU,CAAC,GACjC,qBAAqB,CAAC,SAAS,aAAT,SAAS,cAAT,SAAS,GAAI,EAAE,CAAC,EAC3C;IACN,CAAC,CAAC,CAAC;AACP,CAAC,CAAC","sourcesContent":["import { EstimatedLensPerformance } from \"./benchmark/estimateLensPerformanceCluster\";\nimport { copyDefinedProperties } from \"./common/copyDefinedProperties\";\nimport { getConfigurationOverrides } from \"./configurationOverrides\";\nimport { Injectable } from \"./dependency-injection/Injectable\";\nimport { LogLevelName } from \"./logger/logger\";\n\n/**\n * From T, pick the set of properties whose values are optional. Create a new type containing only those properties.\n */\ntype PickOptionals<T> = {\n [K in keyof T as T[K] extends Exclude<T[K], undefined> ? never : K]: T[K];\n};\n\n/**\n * Defaults are provided for runtime configuration and any optional bootstrap configuration properties which require\n * defaults.\n */\nconst defaultConfiguration: CameraKitRuntimeConfiguration & PickOptionals<CameraKitBootstrapConfiguration> = {\n // If the applications doesn't provide performance data (e.g. via estimateLensPerformance), we'll use 0 to indicate\n // no performance estimation occurred. This is indicative of typical performance-targeting logic, which often\n // defaults to the lowest-tier experience in the absense of performance cluster data.\n lensPerformance: { cluster: 0, benchmarks: [], webglRendererInfo: \"unknown\" },\n logger: \"noop\",\n logLevel: \"info\",\n shouldUseWorker: true,\n apiHostname: \"camera-kit-api.snapar.com\",\n};\n\ninterface CameraKitRuntimeConfiguration {\n lensPerformance: EstimatedLensPerformance | Promise<EstimatedLensPerformance>;\n logger: \"noop\" | \"console\";\n logLevel: LogLevelName;\n shouldUseWorker: boolean;\n apiHostname: CameraKitApiHostname;\n}\n\nexport type CameraKitApiHostname = \"camera-kit-api.snapar.com\" | \"api-kit.snapchat.com\";\n\n/**\n * Configuration which must be provided when calling {@link bootstrapCameraKit}. These values are used to create various\n * CameraKit components.\n *\n * @category Bootstrapping and Configuration\n */\nexport interface CameraKitBootstrapConfiguration {\n /**\n * Long-lived token granting your application access to CameraKit APIs. This is found in the SnapKit Dev Portal,\n * where it's called the API Token.\n */\n apiToken: string;\n\n /**\n * Determine where to print CameraKit log messages. By default no logs will be printed.\n *\n * CameraKit emits log messages to help diagnose and root cause issues that may occur during the development of a\n * host application. The printing of these can be controlled via the following\n * options:\n * - `noop`: log messages are ignored.\n * - `console`: log messages are printed to console.\n */\n logger?: \"noop\" | \"console\";\n\n /**\n * Log only if a logged entry level is greater than or equal to this level. Here is the order of levels:\n * error > warn > log = info > debug. Default value is \"info\".\n */\n logLevel?: LogLevelName;\n\n /**\n * Some lenses may decide to modify their behavior based on the performance of the current environment. If you are\n * using such lenses, providing an estimation of lens performance may lead to better user experience (especially on\n * low-performance devices).\n *\n * Running the {@link estimateLensPerformance} function will run benchmarks and estimate an appropriate lens\n * performance cluster (i.e. a performance rating) based on the current environment.\n *\n * Lower cluster = worse expected performance capability.\n *\n * @example\n * ```ts\n * import { bootstrapCameraKit, estimateLensPerformance } from '@snap/camera-kit`\n *\n * const cameraKit = await bootstrapCameraKit({\n * apiToken: '...',\n * lensPerformance: estimateLensPerformance(),\n * })\n * ```\n */\n lensPerformance?: EstimatedLensPerformance | Promise<EstimatedLensPerformance>;\n\n /**\n * In recommended production deployments, the WebAssembly assets required by CameraKit will be downloaded from an\n * optimized CDN. But sometimes (e.g. during development or within a CI pipeline), it may be necessary to download\n * these assets from somewhere else.\n *\n * This configuration option allows the application to specify URLs to be used for both the WebAssembly and JS glue\n * file that are used to run and interact with CameraKit's rendering engine.\n */\n lensCoreOverrideUrls?: { wasm: string; js: string };\n\n /**\n * In recommended production deployments, the WebAssembly assets required by CameraKit will be downloaded from an\n * optimized CDN. But sometimes during development or within a CI pipeline, it may be necessary to download these\n * assets from somewhere else. With a provided `wasmEndpointOverride`, asset URLs will be automatically generated\n * based on this root endpoint.\n */\n wasmEndpointOverride?: string;\n}\n\n/**\n * This type represents the result of merging user-supplied config with default config -- as such, it has no nullable\n * fields, making it a more convenient type for other components to use.\n *\n * @internal\n */\nexport type CameraKitConfiguration = CameraKitRuntimeConfiguration & CameraKitBootstrapConfiguration;\n\n/** @internal */\nexport const configurationToken = \"configuration\";\n\n/** @internal */\nexport const createCameraKitConfigurationFactory = (configuration: CameraKitBootstrapConfiguration) => {\n // always leave debug mode warning about overrides in console\n const overrides = getConfigurationOverrides();\n if (overrides) {\n console.warn(\"Configuration overrides applied\", overrides);\n }\n return Injectable(configurationToken, (): CameraKitConfiguration => {\n // We'll ensure that we handle errors on any Promises passed as config values, otherwise we either must\n // handle them separately wherever they're used, or rejections would go unhandled.\n const safeConfig: CameraKitBootstrapConfiguration = {\n ...configuration,\n lensPerformance:\n configuration.lensPerformance instanceof Promise\n ? // Safety: defaultConfiguration.lensPerformance is defined (it's hardcoded above).\n configuration.lensPerformance.catch(() => defaultConfiguration.lensPerformance!)\n : configuration.lensPerformance,\n };\n return {\n ...defaultConfiguration,\n ...copyDefinedProperties(safeConfig),\n ...copyDefinedProperties(overrides ?? {}),\n };\n });\n};\n"]}
@@ -13,6 +13,7 @@ import { operationalMetricReporterFactory } from "../metrics/operational/operati
13
13
  import { lensSourcesFactory } from "../extensions/LensSources";
14
14
  import { uriHandlersFactory } from "../extensions/UriHandlers";
15
15
  import { lensPersistenceStoreFactory } from "../lens/LensPersistenceStore";
16
+ import { cofHandlerFactory } from "../remote-configuration/cofHandler";
16
17
  import { remoteConfigurationFactory } from "../remote-configuration/remoteConfiguration";
17
18
  import { lensAssetRepositoryFactory } from "../lens/assets/LensAssetRepository";
18
19
  import { legalStateFactory } from "../legal/legalState";
@@ -21,6 +22,7 @@ import { logEntriesFactory } from "../logger/logEntries";
21
22
  import { reportGlobalException } from "../metrics/reporters/reportGlobalException";
22
23
  import { requestStateEventTargetFactory } from "../handlers/requestStateEmittingHandler";
23
24
  import { pageVisibilityFactory } from "../common/pageVisibility";
25
+ import { remoteApiServicesFactory } from "../extensions/RemoteApiServices";
24
26
  import { ServicesFromInjectables } from "./types";
25
27
  /**
26
28
  * All services available to be customized by client app.
@@ -31,6 +33,7 @@ export type PublicServices = ServicesFromInjectables<[
31
33
  typeof defaultFetchHandlerFactory,
32
34
  typeof remoteMediaAssetLoaderFactory,
33
35
  typeof lensSourcesFactory,
36
+ typeof remoteApiServicesFactory,
34
37
  typeof uriHandlersFactory
35
38
  ]>;
36
39
  /**
@@ -51,6 +54,7 @@ export type RootServices = {
51
54
  typeof metricsEventTargetFactory,
52
55
  typeof requestStateEventTargetFactory,
53
56
  typeof cameraKitServiceFetchHandlerFactory,
57
+ typeof cofHandlerFactory,
54
58
  typeof remoteConfigurationFactory,
55
59
  typeof lensRepositoryFactory,
56
60
  typeof lensPersistenceStoreFactory,
@@ -1 +1 @@
1
- {"version":3,"file":"RootServices.js","sourceRoot":"","sources":["../../src/dependency-injection/RootServices.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,4CAA4C,CAAC","sourcesContent":["import { lensRepositoryFactory } from \"../lens/LensRepository\";\nimport { lensCoreFactory } from \"../lens-core-module/loader/lensCoreFactory\";\nimport { remoteMediaAssetLoaderFactory } from \"../lens/assets/remoteMediaAssetLoaderFactory\";\nimport { deviceDependentAssetLoaderFactory } from \"../lens/assets/deviceDependentAssetLoader\";\nimport { staticAssetLoaderFactory } from \"../lens/assets/staticAssetLoader\";\nimport { defaultFetchHandlerFactory } from \"../handlers/defaultFetchHandler\";\nimport { cameraKitServiceFetchHandlerFactory } from \"../handlers/cameraKitServiceFetchHandlerFactory\";\nimport { createCameraKitConfigurationFactory } from \"../configuration\";\nimport { LensCoreModule } from \"../lens-core-module/generated-types\";\nimport { metricsEventTargetFactory } from \"../metrics/metricsEventTarget\";\nimport { metricsHandlerFactory } from \"../metrics/metricsHandler\";\nimport { operationalMetricReporterFactory } from \"../metrics/operational/operationalMetricsReporter\";\nimport { lensSourcesFactory } from \"../extensions/LensSources\";\nimport { uriHandlersFactory } from \"../extensions/UriHandlers\";\nimport { lensPersistenceStoreFactory } from \"../lens/LensPersistenceStore\";\nimport { remoteConfigurationFactory } from \"../remote-configuration/remoteConfiguration\";\nimport { lensAssetRepositoryFactory } from \"../lens/assets/LensAssetRepository\";\nimport { legalStateFactory } from \"../legal/legalState\";\nimport { legalPromptFactory } from \"../legal/legalPrompt\";\nimport { logEntriesFactory } from \"../logger/logEntries\";\nimport { reportGlobalException } from \"../metrics/reporters/reportGlobalException\";\nimport { requestStateEventTargetFactory } from \"../handlers/requestStateEmittingHandler\";\nimport { pageVisibilityFactory } from \"../common/pageVisibility\";\nimport { ServicesFromInjectables } from \"./types\";\n\n/**\n * All services available to be customized by client app.\n */\nexport type PublicServices = ServicesFromInjectables<\n [\n ReturnType<typeof createCameraKitConfigurationFactory>,\n typeof pageVisibilityFactory,\n typeof defaultFetchHandlerFactory,\n typeof remoteMediaAssetLoaderFactory,\n typeof lensSourcesFactory,\n typeof uriHandlersFactory\n ]\n>;\n\n/**\n * Define all the Services contained in CameraKit's root dependency injection container.\n *\n * Note: we do end up defining this list of Services twice (once here to create the type, once when we actually\n * create the Container inside the `bootstrapCameraKit` function). We could avoid doing this and just infer the\n * RootContainer type from the constructed container – but since we can only do that *inside* `bootstrapCameraKit`, it\n * makes it more awkward to provide a type for the `provide` user-supplied function (or use the type elsewhere, like in\n * CameraKitSession).\n *\n * There may be a way to eliminate this extra boilerplate, but for now it's required in order to present a cleaner\n * `bootstrapCameraKit` API to applications.\n */\nexport type RootServices = {\n // bootstrapCameraKit replaces the lensCoreFactory token's value with the resolved LensCoreModule (rather than the\n // Promise of the LensCoreModule), so we need to do the same re-mapping here.\n [lensCoreFactory.token]: LensCoreModule;\n} & PublicServices &\n ServicesFromInjectables<\n [\n typeof metricsEventTargetFactory,\n typeof requestStateEventTargetFactory,\n typeof cameraKitServiceFetchHandlerFactory,\n typeof remoteConfigurationFactory,\n typeof lensRepositoryFactory,\n typeof lensPersistenceStoreFactory,\n typeof metricsHandlerFactory,\n typeof operationalMetricReporterFactory,\n typeof lensAssetRepositoryFactory,\n typeof deviceDependentAssetLoaderFactory,\n typeof staticAssetLoaderFactory,\n typeof legalStateFactory,\n typeof legalPromptFactory,\n typeof logEntriesFactory,\n typeof reportGlobalException\n ]\n >;\n"]}
1
+ {"version":3,"file":"RootServices.js","sourceRoot":"","sources":["../../src/dependency-injection/RootServices.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,4CAA4C,CAAC","sourcesContent":["import { lensRepositoryFactory } from \"../lens/LensRepository\";\nimport { lensCoreFactory } from \"../lens-core-module/loader/lensCoreFactory\";\nimport { remoteMediaAssetLoaderFactory } from \"../lens/assets/remoteMediaAssetLoaderFactory\";\nimport { deviceDependentAssetLoaderFactory } from \"../lens/assets/deviceDependentAssetLoader\";\nimport { staticAssetLoaderFactory } from \"../lens/assets/staticAssetLoader\";\nimport { defaultFetchHandlerFactory } from \"../handlers/defaultFetchHandler\";\nimport { cameraKitServiceFetchHandlerFactory } from \"../handlers/cameraKitServiceFetchHandlerFactory\";\nimport { createCameraKitConfigurationFactory } from \"../configuration\";\nimport { LensCoreModule } from \"../lens-core-module/generated-types\";\nimport { metricsEventTargetFactory } from \"../metrics/metricsEventTarget\";\nimport { metricsHandlerFactory } from \"../metrics/metricsHandler\";\nimport { operationalMetricReporterFactory } from \"../metrics/operational/operationalMetricsReporter\";\nimport { lensSourcesFactory } from \"../extensions/LensSources\";\nimport { uriHandlersFactory } from \"../extensions/UriHandlers\";\nimport { lensPersistenceStoreFactory } from \"../lens/LensPersistenceStore\";\nimport { cofHandlerFactory } from \"../remote-configuration/cofHandler\";\nimport { remoteConfigurationFactory } from \"../remote-configuration/remoteConfiguration\";\nimport { lensAssetRepositoryFactory } from \"../lens/assets/LensAssetRepository\";\nimport { legalStateFactory } from \"../legal/legalState\";\nimport { legalPromptFactory } from \"../legal/legalPrompt\";\nimport { logEntriesFactory } from \"../logger/logEntries\";\nimport { reportGlobalException } from \"../metrics/reporters/reportGlobalException\";\nimport { requestStateEventTargetFactory } from \"../handlers/requestStateEmittingHandler\";\nimport { pageVisibilityFactory } from \"../common/pageVisibility\";\nimport { remoteApiServicesFactory } from \"../extensions/RemoteApiServices\";\nimport { ServicesFromInjectables } from \"./types\";\n\n/**\n * All services available to be customized by client app.\n */\nexport type PublicServices = ServicesFromInjectables<\n [\n ReturnType<typeof createCameraKitConfigurationFactory>,\n typeof pageVisibilityFactory,\n typeof defaultFetchHandlerFactory,\n typeof remoteMediaAssetLoaderFactory,\n typeof lensSourcesFactory,\n typeof remoteApiServicesFactory,\n typeof uriHandlersFactory\n ]\n>;\n\n/**\n * Define all the Services contained in CameraKit's root dependency injection container.\n *\n * Note: we do end up defining this list of Services twice (once here to create the type, once when we actually\n * create the Container inside the `bootstrapCameraKit` function). We could avoid doing this and just infer the\n * RootContainer type from the constructed container – but since we can only do that *inside* `bootstrapCameraKit`, it\n * makes it more awkward to provide a type for the `provide` user-supplied function (or use the type elsewhere, like in\n * CameraKitSession).\n *\n * There may be a way to eliminate this extra boilerplate, but for now it's required in order to present a cleaner\n * `bootstrapCameraKit` API to applications.\n */\nexport type RootServices = {\n // bootstrapCameraKit replaces the lensCoreFactory token's value with the resolved LensCoreModule (rather than the\n // Promise of the LensCoreModule), so we need to do the same re-mapping here.\n [lensCoreFactory.token]: LensCoreModule;\n} & PublicServices &\n ServicesFromInjectables<\n [\n typeof metricsEventTargetFactory,\n typeof requestStateEventTargetFactory,\n typeof cameraKitServiceFetchHandlerFactory,\n typeof cofHandlerFactory,\n typeof remoteConfigurationFactory,\n typeof lensRepositoryFactory,\n typeof lensPersistenceStoreFactory,\n typeof metricsHandlerFactory,\n typeof operationalMetricReporterFactory,\n typeof lensAssetRepositoryFactory,\n typeof deviceDependentAssetLoaderFactory,\n typeof staticAssetLoaderFactory,\n typeof legalStateFactory,\n typeof legalPromptFactory,\n typeof logEntriesFactory,\n typeof reportGlobalException\n ]\n >;\n"]}
@@ -1 +1 @@
1
- { "PACKAGE_VERSION": "0.11.0-alpha.1" }
1
+ { "PACKAGE_VERSION": "0.13.0-alpha.1" }
@@ -12,12 +12,12 @@ export interface LensSource {
12
12
  * @param lensId Lens ID to get.
13
13
  * @param groupId Group ID the lens belongs to.
14
14
  */
15
- getLens(lensId: string, groupId: string): Promise<ArrayBuffer>;
15
+ getLens?(lensId: string, groupId: string): Promise<ArrayBuffer>;
16
16
  /**
17
17
  * Returns encoded lens objects.
18
18
  * @param groupId Group ID to get lenses of.
19
19
  */
20
- getLensGroup(groupId: string): Promise<ArrayBuffer[]>;
20
+ getLensGroup?(groupId: string): Promise<ArrayBuffer[]>;
21
21
  }
22
22
  /**
23
23
  * A chain of {@link LensSource} objects to be registered in Camera Kit on bootstrap. Camera Kit evaluates all
@@ -38,9 +38,13 @@ export class LensSources {
38
38
  var _a, _b;
39
39
  return __awaiter(this, void 0, void 0, function* () {
40
40
  if ((_a = this.source) === null || _a === void 0 ? void 0 : _a.isGroupOwner(groupId)) {
41
- return isUndefined(lensId)
42
- ? this.source.getLensGroup(groupId)
43
- : this.source.getLens(lensId, groupId).then((envelope) => [envelope]);
41
+ if (isUndefined(lensId)) {
42
+ if (this.source.getLensGroup)
43
+ return this.source.getLensGroup(groupId);
44
+ }
45
+ else if (this.source.getLens) {
46
+ return this.source.getLens(lensId, groupId).then((envelope) => [envelope]);
47
+ }
44
48
  }
45
49
  return (_b = this.fallbackSources) === null || _b === void 0 ? void 0 : _b.retrieveLenses({ groupId, lensId });
46
50
  });
@@ -1 +1 @@
1
- {"version":3,"file":"LensSources.js","sourceRoot":"","sources":["../../src/extensions/LensSources.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AA0BhE;;;;;GAKG;AACH,MAAM,OAAO,WAAW;IACpB;;;OAGG;IACH,MAAM,CAAC,KAAK;QACR,qEAAqE;QACrE,sDAAsD;QACtD,mBAAmB;QACnB,OAAO,IAAI,WAAW,EAAE,CAAC;IAC7B,CAAC;IAKD;;;;OAIG;IACH,YAAY,eAA4B,EAAE,MAAkB;QACxD,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;IAED;;;;;;OAMG;IACG,cAAc,CAAC,EAAE,OAAO,EAAE,MAAM,EAAwC;;;YAC1E,IAAI,MAAA,IAAI,CAAC,MAAM,0CAAE,YAAY,CAAC,OAAO,CAAC,EAAE;gBACpC,OAAO,WAAW,CAAC,MAAM,CAAC;oBACtB,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC;oBACnC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;aAC7E;YACD,OAAO,MAAA,IAAI,CAAC,eAAe,0CAAE,cAAc,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;;KACpE;CACJ;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAG,UAAU,CAAC,aAAa,EAAE,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC","sourcesContent":["import { isUndefined } from \"../common/typeguards\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\n\n/**\n * A source of a lens group.\n */\nexport interface LensSource {\n /**\n * Whether the given source is able to load lenses of the supplied group.\n * @param groupId Group ID to check.\n */\n isGroupOwner(groupId: string): boolean;\n\n /**\n * Returns an encoded lens object.\n * @param lensId Lens ID to get.\n * @param groupId Group ID the lens belongs to.\n */\n getLens(lensId: string, groupId: string): Promise<ArrayBuffer>;\n\n /**\n * Returns encoded lens objects.\n * @param groupId Group ID to get lenses of.\n */\n getLensGroup(groupId: string): Promise<ArrayBuffer[]>;\n}\n\n/**\n * A chain of {@link LensSource} objects to be registered in Camera Kit on bootstrap. Camera Kit evaluates all\n * registered {@link LensSource} objects for a group ownership during Lens retrieval ({@link CameraKit.lenses}).\n * And if a source claims the ownership, its {@link LensSource.getLens} or {@link LensSource.getLensGroup}\n * methods are called.\n */\nexport class LensSources {\n /**\n * Returns empty LensSources instance.\n * @internal\n */\n static empty() {\n // NOTE: we want to keep LensSources constructor to require arguments\n // but internally we don't need them for the base case\n // @ts-expect-error\n return new LensSources();\n }\n\n private readonly fallbackSources: LensSources | undefined;\n private readonly source: LensSource | undefined;\n\n /**\n * Creates an instance of Lens sources.\n * @param fallbackSources A fallback sources if given {@link LensSource} doesn't claim a group ownership.\n * @param source Lens source.\n */\n constructor(fallbackSources: LensSources, source: LensSource) {\n this.fallbackSources = fallbackSources;\n this.source = source;\n }\n\n /**\n * Returns envelopes of lens/groups taking into account group ownership.\n * @internal\n * @param groupId A group to test ownership and get lens envelopes of.\n * @param lensId An optional lens ID to narrow envelopes down to a single lens.\n * @returns Envelopes or undefined if not applicable.\n */\n async retrieveLenses({ groupId, lensId }: { groupId: string; lensId?: string }): Promise<ArrayBuffer[] | void> {\n if (this.source?.isGroupOwner(groupId)) {\n return isUndefined(lensId)\n ? this.source.getLensGroup(groupId)\n : this.source.getLens(lensId, groupId).then((envelope) => [envelope]);\n }\n return this.fallbackSources?.retrieveLenses({ groupId, lensId });\n }\n}\n\nexport const lensSourcesFactory = Injectable(\"lensSources\", () => LensSources.empty());\n"]}
1
+ {"version":3,"file":"LensSources.js","sourceRoot":"","sources":["../../src/extensions/LensSources.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AA0BhE;;;;;GAKG;AACH,MAAM,OAAO,WAAW;IACpB;;;OAGG;IACH,MAAM,CAAC,KAAK;QACR,qEAAqE;QACrE,sDAAsD;QACtD,mBAAmB;QACnB,OAAO,IAAI,WAAW,EAAE,CAAC;IAC7B,CAAC;IAKD;;;;OAIG;IACH,YAAY,eAA4B,EAAE,MAAkB;QACxD,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;IAED;;;;;;OAMG;IACG,cAAc,CAAC,EAAE,OAAO,EAAE,MAAM,EAAwC;;;YAC1E,IAAI,MAAA,IAAI,CAAC,MAAM,0CAAE,YAAY,CAAC,OAAO,CAAC,EAAE;gBACpC,IAAI,WAAW,CAAC,MAAM,CAAC,EAAE;oBACrB,IAAI,IAAI,CAAC,MAAM,CAAC,YAAY;wBAAE,OAAO,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;iBAC1E;qBAAM,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE;oBAC5B,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;iBAC9E;aACJ;YACD,OAAO,MAAA,IAAI,CAAC,eAAe,0CAAE,cAAc,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;;KACpE;CACJ;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAG,UAAU,CAAC,aAAa,EAAE,GAAG,EAAE,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC,CAAC","sourcesContent":["import { isUndefined } from \"../common/typeguards\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\n\n/**\n * A source of a lens group.\n */\nexport interface LensSource {\n /**\n * Whether the given source is able to load lenses of the supplied group.\n * @param groupId Group ID to check.\n */\n isGroupOwner(groupId: string): boolean;\n\n /**\n * Returns an encoded lens object.\n * @param lensId Lens ID to get.\n * @param groupId Group ID the lens belongs to.\n */\n getLens?(lensId: string, groupId: string): Promise<ArrayBuffer>;\n\n /**\n * Returns encoded lens objects.\n * @param groupId Group ID to get lenses of.\n */\n getLensGroup?(groupId: string): Promise<ArrayBuffer[]>;\n}\n\n/**\n * A chain of {@link LensSource} objects to be registered in Camera Kit on bootstrap. Camera Kit evaluates all\n * registered {@link LensSource} objects for a group ownership during Lens retrieval ({@link CameraKit.lenses}).\n * And if a source claims the ownership, its {@link LensSource.getLens} or {@link LensSource.getLensGroup}\n * methods are called.\n */\nexport class LensSources {\n /**\n * Returns empty LensSources instance.\n * @internal\n */\n static empty() {\n // NOTE: we want to keep LensSources constructor to require arguments\n // but internally we don't need them for the base case\n // @ts-expect-error\n return new LensSources();\n }\n\n private readonly fallbackSources: LensSources | undefined;\n private readonly source: LensSource | undefined;\n\n /**\n * Creates an instance of Lens sources.\n * @param fallbackSources A fallback sources if given {@link LensSource} doesn't claim a group ownership.\n * @param source Lens source.\n */\n constructor(fallbackSources: LensSources, source: LensSource) {\n this.fallbackSources = fallbackSources;\n this.source = source;\n }\n\n /**\n * Returns envelopes of lens/groups taking into account group ownership.\n * @internal\n * @param groupId A group to test ownership and get lens envelopes of.\n * @param lensId An optional lens ID to narrow envelopes down to a single lens.\n * @returns Envelopes or undefined if not applicable.\n */\n async retrieveLenses({ groupId, lensId }: { groupId: string; lensId?: string }): Promise<ArrayBuffer[] | void> {\n if (this.source?.isGroupOwner(groupId)) {\n if (isUndefined(lensId)) {\n if (this.source.getLensGroup) return this.source.getLensGroup(groupId);\n } else if (this.source.getLens) {\n return this.source.getLens(lensId, groupId).then((envelope) => [envelope]);\n }\n }\n return this.fallbackSources?.retrieveLenses({ groupId, lensId });\n }\n}\n\nexport const lensSourcesFactory = Injectable(\"lensSources\", () => LensSources.empty());\n"]}
@@ -0,0 +1,101 @@
1
+ import { ResponseCode } from "../generated-proto/pb_schema/lenses/remote_api/remote_api_service";
2
+ import { LensRepository } from "../lens";
3
+ import { Lens } from "../lens/Lens";
4
+ import { LensState } from "../session/lensState";
5
+ import { SessionState } from "../session/sessionState";
6
+ import { OperationalMetricsReporter } from "../metrics/operational/operationalMetricsReporter";
7
+ import { UriHandler } from "./UriHandlers";
8
+ declare const statusToResponseCodeMap: {
9
+ success: ResponseCode.SUCCESS;
10
+ redirected: ResponseCode.REDIRECTED;
11
+ badRequest: ResponseCode.BAD_REQUEST;
12
+ accessDenied: ResponseCode.ACCESS_DENIED;
13
+ notFound: ResponseCode.NOT_FOUND;
14
+ timeout: ResponseCode.TIMEOUT;
15
+ requestTooLarge: ResponseCode.REQUEST_TOO_LARGE;
16
+ serverError: ResponseCode.SERVER_ERROR;
17
+ cancelled: ResponseCode.CANCELLED;
18
+ proxyError: ResponseCode.PROXY_ERROR;
19
+ };
20
+ /**
21
+ * Status of a Remote API response.
22
+ */
23
+ export type RemoteApiStatus = keyof typeof statusToResponseCodeMap;
24
+ /**
25
+ * Remote API request sent by a lens.
26
+ */
27
+ export interface RemoteApiRequest {
28
+ /**
29
+ * Unique id of the remote API service specification.
30
+ */
31
+ apiSpecId: string;
32
+ /**
33
+ * Unique id of the remote API service endpoint requested by this request.
34
+ */
35
+ endpointId: string;
36
+ /**
37
+ * A map of named parameters associated with the request.
38
+ */
39
+ parameters: Record<string, string>;
40
+ /**
41
+ * Additional binary request payload.
42
+ */
43
+ body: ArrayBuffer;
44
+ }
45
+ /**
46
+ * Remote API response to a request sent by a lens.
47
+ */
48
+ export interface RemoteApiResponse {
49
+ /**
50
+ * Status of the response
51
+ */
52
+ status: RemoteApiStatus;
53
+ /**
54
+ * A map of named metadata associated with the response.
55
+ */
56
+ metadata: Record<string, string>;
57
+ /**
58
+ * Additional binary request payload.
59
+ */
60
+ body: ArrayBuffer;
61
+ }
62
+ /**
63
+ * Represents a Remote API request cancellation handler function.
64
+ */
65
+ export type RemoteApiCancelRequestHandler = () => void;
66
+ /**
67
+ * Represents a Remote API request handler function.
68
+ * It is provided with a reply callback that must be invoked to send a response back to the lens.
69
+ * The reply callback can be invoked multiple times if needed.
70
+ * Additionally, the handler can return a cancellation callback, which is triggered when the lens cancels the request.
71
+ */
72
+ export type RemoteApiRequestHandler = (reply: (response: RemoteApiResponse) => void) => RemoteApiCancelRequestHandler | void;
73
+ /**
74
+ * Service to handle a lens Remote API request.
75
+ */
76
+ export interface RemoteApiService {
77
+ /**
78
+ * Remote API spec ID(s).
79
+ */
80
+ apiSpecId: string;
81
+ /**
82
+ * This method is called by Camera Kit when a lens triggers a Remote API request with a corresponding spec ID.
83
+ * If the service can handle the request, the method returns a request handler; otherwise, it returns nothing.
84
+ * @param request Remote API request object.
85
+ * @param lens Lens that trigges the request.
86
+ * @returns A request handler if applicable.
87
+ */
88
+ getRequestHandler(request: RemoteApiRequest, lens: Lens): RemoteApiRequestHandler | undefined;
89
+ }
90
+ export type RemoteApiServices = RemoteApiService[];
91
+ export declare const remoteApiServicesFactory: {
92
+ (): RemoteApiServices;
93
+ token: "remoteApiServices";
94
+ dependencies: [];
95
+ };
96
+ /**
97
+ * Provides a URI handler that searches for a match within the provided services to handle Remote API requests,
98
+ * i.e., those whose URI starts with 'app://remote-api/performApiRequest'.
99
+ */
100
+ export declare function getRemoteApiUriHandler(registeredServices: RemoteApiService[], sessionState: SessionState, lensState: LensState, lensRepository: LensRepository, reporter: OperationalMetricsReporter): UriHandler;
101
+ export {};
@@ -0,0 +1,198 @@
1
+ import { Subject, catchError, filter, map, merge, retry, takeUntil, tap } from "rxjs";
2
+ import { forActions } from "@snap/state-management";
3
+ import { Injectable } from "../dependency-injection/Injectable";
4
+ import { RemoteApiInfo } from "../generated-proto/pb_schema/camera_kit/v3/features/remote_api_info";
5
+ import { ResponseCode, responseCodeToNumber } from "../generated-proto/pb_schema/lenses/remote_api/remote_api_service";
6
+ import { getLogger } from "../logger/logger";
7
+ import { knownAnyTypes } from "../common/any";
8
+ import { extractSchemeAndRoute } from "./UriHandlers";
9
+ // NOTE: There's potential for overloads when reporting metrics if reporting is triggered on each frame,
10
+ // (i.e., when the lens sends Remote API requests every frame).
11
+ // As of now, this isn't a concern because src/metrics/operational/operationalMetricsReporter.ts aggregates
12
+ // "count" metrics into a single metric within a batch, and the Remote API service currently
13
+ // reports only "count" metrics. For instance, if 30 metrics with the same name are generated per second,
14
+ // given the current bundle size of 100 operational metrics, there will be one metrics report approximately
15
+ // every 3.3 seconds.
16
+ // In the future, if we opt to report "histogram" or other metric types, they must be approached with caution:
17
+ // either the operationalMetricsReporter should be enhanced to aggregate such metrics,
18
+ // or the Remote API service should manage it directly.
19
+ // Mobiles ticket: https://jira.sc-corp.net/browse/CAMKIT-3092
20
+ const logger = getLogger("RemoteApiServices");
21
+ const uriResponseOkCode = 200;
22
+ const apiResponseStatusHeader = ":sc_lens_api_status";
23
+ const apiBinaryContentType = "application/octet-stream";
24
+ const statusToResponseCodeMap = {
25
+ success: ResponseCode.SUCCESS,
26
+ redirected: ResponseCode.REDIRECTED,
27
+ badRequest: ResponseCode.BAD_REQUEST,
28
+ accessDenied: ResponseCode.ACCESS_DENIED,
29
+ notFound: ResponseCode.NOT_FOUND,
30
+ timeout: ResponseCode.TIMEOUT,
31
+ requestTooLarge: ResponseCode.REQUEST_TOO_LARGE,
32
+ serverError: ResponseCode.SERVER_ERROR,
33
+ cancelled: ResponseCode.CANCELLED,
34
+ proxyError: ResponseCode.PROXY_ERROR,
35
+ };
36
+ /**
37
+ * Invokes the cancellation handler associated with the provided key and removes it from the collection of handlers.
38
+ */
39
+ function callCancellationHandler(cancellationHandlers, ...keys) {
40
+ var _a;
41
+ for (const key of keys) {
42
+ (_a = cancellationHandlers.get(key)) === null || _a === void 0 ? void 0 : _a();
43
+ cancellationHandlers.delete(key);
44
+ }
45
+ }
46
+ /**
47
+ * Removes the specified lenses' metadata from the cache and invokes their cancellation callbacks.
48
+ *
49
+ * @param lensRequestState The state representing the lens cache.
50
+ * @param lensIds An array of lens IDs to be removed from the cache
51
+ * and for which the cancellation callbacks will be invoked.
52
+ */
53
+ function handleLensApplicationEnd(lensRequestState, ...lensIds) {
54
+ for (const lensId of lensIds) {
55
+ const state = lensRequestState.get(lensId);
56
+ if (state) {
57
+ callCancellationHandler(state.cancellationHandlers, ...state.cancellationHandlers.keys());
58
+ lensRequestState.delete(lensId);
59
+ }
60
+ }
61
+ }
62
+ export const remoteApiServicesFactory = Injectable("remoteApiServices", () => {
63
+ const remoteApiServices = [];
64
+ return remoteApiServices;
65
+ });
66
+ /**
67
+ * Provides a URI handler that searches for a match within the provided services to handle Remote API requests,
68
+ * i.e., those whose URI starts with 'app://remote-api/performApiRequest'.
69
+ */
70
+ export function getRemoteApiUriHandler(registeredServices, sessionState, lensState, lensRepository, reporter) {
71
+ // Groups services by spec ID for faster lookups.
72
+ const registeredServiceMap = new Map();
73
+ for (const service of registeredServices) {
74
+ const existingServices = registeredServiceMap.get(service.apiSpecId) || [];
75
+ registeredServiceMap.set(service.apiSpecId, [...existingServices, service]);
76
+ }
77
+ const uriRequests = new Subject();
78
+ const uriCancelRequests = new Subject();
79
+ const lensRequestState = new Map();
80
+ const lensTurnOffEvents = lensState.events.pipe(forActions("turnedOff"), tap(([action]) => handleLensApplicationEnd(lensRequestState, action.data.id)));
81
+ const uriRequestEvents = uriRequests.pipe(map((uriRequest) => {
82
+ var _a, _b;
83
+ const lensId = uriRequest.lens.id;
84
+ if (!lensRequestState.has(lensId)) {
85
+ lensRequestState.set(lensId, {
86
+ // Prepares a collection to store cancellation handlers.
87
+ // A specific handler will be invoked when a cancellation request is issued by the lens.
88
+ // All handlers will be invoked when the lens is replaced with another one or the session
89
+ // is destroyed.
90
+ cancellationHandlers: new Map(),
91
+ // Parse lens metadata to obtain supported Remote API specs.
92
+ supportedSpecIds: new Set(((_b = (_a = lensRepository.getLensMetadata(lensId)) === null || _a === void 0 ? void 0 : _a.featureMetadata) !== null && _b !== void 0 ? _b : [])
93
+ .filter((feature) => feature.typeUrl === knownAnyTypes.remoteApiInfo)
94
+ .flatMap((any) => RemoteApiInfo.decode(any.value).apiSpecIds)),
95
+ });
96
+ }
97
+ const requestState = lensRequestState.get(lensId);
98
+ // Extracts the spec ID and endpoint ID from the provided Remote API request URI.
99
+ // The given URI is expected to conform to the following specification:
100
+ // eslint-disable-next-line max-len
101
+ // https://docs.google.com/document/d/18fbGYDhD2N_aMTe4ZLY4QKeCSoMeJuklG28TutDzLZc/edit#bookmark=id.p2y39gwgbm4g
102
+ const { route } = extractSchemeAndRoute(uriRequest.request.uri);
103
+ const [specId, endpointIdWithQuery] = route.split("/").slice(2);
104
+ const [endpointId] = endpointIdWithQuery.split("?");
105
+ return { uriRequest, specId, endpointId, requestState };
106
+ }),
107
+ // only handle requests for API spec ID that current lens supports
108
+ filter(({ specId, requestState }) => requestState.supportedSpecIds.has(specId)),
109
+ // only handle requests if we have a registered service for it
110
+ filter(({ specId }) => registeredServiceMap.has(specId)), map(({ uriRequest, specId, endpointId, requestState }) => {
111
+ var _a;
112
+ const dimensions = new Map([["specId", specId]]);
113
+ reporter.count("lens_remote-api_requests", 1, dimensions);
114
+ const remoteApiRequest = {
115
+ apiSpecId: specId,
116
+ body: uriRequest.request.data,
117
+ endpointId,
118
+ parameters: uriRequest.request.metadata,
119
+ };
120
+ // Looks for the first Remote API request handler.
121
+ for (const service of (_a = registeredServiceMap.get(specId)) !== null && _a !== void 0 ? _a : []) {
122
+ let requestHandler = undefined;
123
+ try {
124
+ requestHandler = service.getRequestHandler(remoteApiRequest, uriRequest.lens);
125
+ }
126
+ catch (_b) {
127
+ logger.warn("Client's Remote API request handler factory threw an error.");
128
+ }
129
+ if (requestHandler) {
130
+ reporter.count("lens_remote-api_handled-requests", 1, dimensions);
131
+ let cancellationHandler = undefined;
132
+ try {
133
+ // Calls client's Remote API handler to process the request.
134
+ cancellationHandler = requestHandler((response) => {
135
+ var _a;
136
+ reporter.count("lens_remote-api_responses", 1, dimensions);
137
+ const responseCode = (_a = statusToResponseCodeMap[response.status]) !== null && _a !== void 0 ? _a : ResponseCode.UNRECOGNIZED;
138
+ const uriResponse = {
139
+ code: uriResponseOkCode,
140
+ description: "",
141
+ contentType: apiBinaryContentType,
142
+ data: response.body,
143
+ metadata: Object.assign(Object.assign({}, response.metadata), { [apiResponseStatusHeader]: responseCodeToNumber(responseCode).toString() }),
144
+ };
145
+ uriRequest.reply(uriResponse);
146
+ });
147
+ }
148
+ catch (error) {
149
+ logger.warn("Client's Remote API request handler threw an error.");
150
+ }
151
+ if (typeof cancellationHandler === "function") {
152
+ requestState.cancellationHandlers.set(uriRequest.request.identifier, () => {
153
+ try {
154
+ cancellationHandler();
155
+ }
156
+ catch (_a) {
157
+ logger.warn("Client's Remote API request cancellation handler threw an error.");
158
+ }
159
+ });
160
+ }
161
+ break;
162
+ }
163
+ }
164
+ }));
165
+ const uriCancelRequestEvents = uriCancelRequests.pipe(tap((uriRequest) => {
166
+ var _a;
167
+ const cancellationHandlers = (_a = lensRequestState.get(uriRequest.lens.id)) === null || _a === void 0 ? void 0 : _a.cancellationHandlers;
168
+ if (cancellationHandlers) {
169
+ callCancellationHandler(cancellationHandlers, uriRequest.request.requestId);
170
+ }
171
+ }));
172
+ merge(lensTurnOffEvents, uriRequestEvents, uriCancelRequestEvents)
173
+ .pipe(catchError((error, sourcePipe) => {
174
+ // The expectation is that if an error occurs, it happens in our own implementation,
175
+ // because app callbacks are wrapped with try..catch blocks.
176
+ // Therefore, we would like to report this error.
177
+ logger.error(error);
178
+ reporter.count("lens_remote-api_errors", 1);
179
+ // Return the source pipe so that we can retry the pipe instead of just completing it.
180
+ return sourcePipe;
181
+ }),
182
+ // When the pipe completes due to an error,
183
+ // we want to resubscribe to the original pipe to keep it alive.
184
+ retry(), takeUntil(sessionState.events.pipe(forActions("destroy"))))
185
+ .subscribe({
186
+ complete: () => handleLensApplicationEnd(lensRequestState, ...lensRequestState.keys()),
187
+ });
188
+ return {
189
+ uri: "app://remote-api/performApiRequest",
190
+ handleRequest(request, reply, lens) {
191
+ uriRequests.next({ request, reply, lens });
192
+ },
193
+ cancelRequest(request, lens) {
194
+ uriCancelRequests.next({ request, lens });
195
+ },
196
+ };
197
+ }
198
+ //# sourceMappingURL=RemoteApiServices.js.map
@@ -0,0 +1 @@
1
+ {"version":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;KACzF,CAAC,CAAC;IAEP,OAAO;QACH,GAAG,EAAE,oCAAoC;QAEzC,aAAa,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI;YAC9B,WAAW,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAC/C,CAAC;QAED,aAAa,CAAC,OAAO,EAAE,IAAI;YACvB,iBAAiB,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;QAC9C,CAAC;KACJ,CAAC;AACN,CAAC","sourcesContent":["import { Subject, catchError, filter, map, merge, retry, takeUntil, tap } from \"rxjs\";\nimport { forActions } from \"@snap/state-management\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\nimport { RemoteApiInfo } from \"../generated-proto/pb_schema/camera_kit/v3/features/remote_api_info\";\nimport { ResponseCode, responseCodeToNumber } from \"../generated-proto/pb_schema/lenses/remote_api/remote_api_service\";\nimport { LensRepository } from \"../lens\";\nimport { Lens } from \"../lens/Lens\";\nimport { LensState } from \"../session/lensState\";\nimport { SessionState } from \"../session/sessionState\";\nimport { getLogger } from \"../logger/logger\";\nimport { knownAnyTypes } from \"../common/any\";\nimport { CamelToSnakeCase, SnakeToCamelCase } from \"../common/types\";\nimport { OperationalMetricsReporter } from \"../metrics/operational/operationalMetricsReporter\";\nimport { UriCancelRequest, UriHandler, UriRequest, UriResponse, extractSchemeAndRoute } from \"./UriHandlers\";\n\n// NOTE: There's potential for overloads when reporting metrics if reporting is triggered on each frame,\n// (i.e., when the lens sends Remote API requests every frame).\n// As of now, this isn't a concern because src/metrics/operational/operationalMetricsReporter.ts aggregates\n// \"count\" metrics into a single metric within a batch, and the Remote API service currently\n// reports only \"count\" metrics. For instance, if 30 metrics with the same name are generated per second,\n// given the current bundle size of 100 operational metrics, there will be one metrics report approximately\n// every 3.3 seconds.\n// In the future, if we opt to report \"histogram\" or other metric types, they must be approached with caution:\n// either the operationalMetricsReporter should be enhanced to aggregate such metrics,\n// or the Remote API service should manage it directly.\n// Mobiles ticket: https://jira.sc-corp.net/browse/CAMKIT-3092\n\nconst logger = getLogger(\"RemoteApiServices\");\n\nconst uriResponseOkCode = 200;\nconst apiResponseStatusHeader = \":sc_lens_api_status\";\nconst apiBinaryContentType = \"application/octet-stream\";\n\nconst statusToResponseCodeMap = {\n success: ResponseCode.SUCCESS,\n redirected: ResponseCode.REDIRECTED,\n badRequest: ResponseCode.BAD_REQUEST,\n accessDenied: ResponseCode.ACCESS_DENIED,\n notFound: ResponseCode.NOT_FOUND,\n timeout: ResponseCode.TIMEOUT,\n requestTooLarge: ResponseCode.REQUEST_TOO_LARGE,\n serverError: ResponseCode.SERVER_ERROR,\n cancelled: ResponseCode.CANCELLED,\n proxyError: ResponseCode.PROXY_ERROR,\n} satisfies { [Status in RemoteApiStatusInternal]: Uppercase<CamelToSnakeCase<Status>> };\n\ntype RemoteApiStatusInternal = SnakeToCamelCase<\n Lowercase<Exclude<keyof typeof ResponseCode, \"RESPONSE_CODE_UNSET\" | \"UNRECOGNIZED\">>\n>;\n\ntype LensId = string;\ntype RequestId = string;\n\ntype UriRequestEvent = {\n request: UriRequest;\n reply: (response: UriResponse) => void;\n lens: Lens;\n};\n\ntype UriCancelRequestEvent = {\n request: UriCancelRequest;\n lens: Lens;\n};\n\ninterface LensRequestState {\n cancellationHandlers: Map<RequestId, RemoteApiCancelRequestHandler>;\n supportedSpecIds: Set<string>;\n}\n\n/**\n * Invokes the cancellation handler associated with the provided key and removes it from the collection of handlers.\n */\nfunction callCancellationHandler(\n cancellationHandlers: Map<RequestId, RemoteApiCancelRequestHandler>,\n ...keys: RequestId[]\n) {\n for (const key of keys) {\n cancellationHandlers.get(key)?.();\n cancellationHandlers.delete(key);\n }\n}\n\n/**\n * Removes the specified lenses' metadata from the cache and invokes their cancellation callbacks.\n *\n * @param lensRequestState The state representing the lens cache.\n * @param lensIds An array of lens IDs to be removed from the cache\n * and for which the cancellation callbacks will be invoked.\n */\nfunction handleLensApplicationEnd(lensRequestState: Map<LensId, LensRequestState>, ...lensIds: LensId[]) {\n for (const lensId of lensIds) {\n const state = lensRequestState.get(lensId);\n if (state) {\n callCancellationHandler(state.cancellationHandlers, ...state.cancellationHandlers.keys());\n lensRequestState.delete(lensId);\n }\n }\n}\n\n/**\n * Status of a Remote API response.\n */\nexport type RemoteApiStatus = keyof typeof statusToResponseCodeMap;\n\n/**\n * Remote API request sent by a lens.\n */\nexport interface RemoteApiRequest {\n /**\n * Unique id of the remote API service specification.\n */\n apiSpecId: string;\n /**\n * Unique id of the remote API service endpoint requested by this request.\n */\n endpointId: string;\n /**\n * A map of named parameters associated with the request.\n */\n parameters: Record<string, string>;\n /**\n * Additional binary request payload.\n */\n body: ArrayBuffer;\n}\n\n/**\n * Remote API response to a request sent by a lens.\n */\nexport interface RemoteApiResponse {\n /**\n * Status of the response\n */\n status: RemoteApiStatus;\n /**\n * A map of named metadata associated with the response.\n */\n metadata: Record<string, string>;\n /**\n * Additional binary request payload.\n */\n body: ArrayBuffer;\n}\n\n/**\n * Represents a Remote API request cancellation handler function.\n */\nexport type RemoteApiCancelRequestHandler = () => void;\n\n/**\n * Represents a Remote API request handler function.\n * It is provided with a reply callback that must be invoked to send a response back to the lens.\n * The reply callback can be invoked multiple times if needed.\n * Additionally, the handler can return a cancellation callback, which is triggered when the lens cancels the request.\n */\nexport type RemoteApiRequestHandler = (\n reply: (response: RemoteApiResponse) => void\n) => RemoteApiCancelRequestHandler | void;\n\n/**\n * Service to handle a lens Remote API request.\n */\nexport interface RemoteApiService {\n /**\n * Remote API spec ID(s).\n */\n apiSpecId: string;\n\n /**\n * This method is called by Camera Kit when a lens triggers a Remote API request with a corresponding spec ID.\n * If the service can handle the request, the method returns a request handler; otherwise, it returns nothing.\n * @param request Remote API request object.\n * @param lens Lens that trigges the request.\n * @returns A request handler if applicable.\n */\n getRequestHandler(request: RemoteApiRequest, lens: Lens): RemoteApiRequestHandler | undefined;\n}\n\nexport type RemoteApiServices = RemoteApiService[];\n\nexport const remoteApiServicesFactory = Injectable(\"remoteApiServices\", () => {\n const remoteApiServices: RemoteApiServices = [];\n return remoteApiServices;\n});\n\n/**\n * Provides a URI handler that searches for a match within the provided services to handle Remote API requests,\n * i.e., those whose URI starts with 'app://remote-api/performApiRequest'.\n */\nexport function getRemoteApiUriHandler(\n registeredServices: RemoteApiService[],\n sessionState: SessionState,\n lensState: LensState,\n lensRepository: LensRepository,\n reporter: OperationalMetricsReporter\n): UriHandler {\n // Groups services by spec ID for faster lookups.\n const registeredServiceMap = new Map<string, RemoteApiService[]>();\n for (const service of registeredServices) {\n const existingServices = registeredServiceMap.get(service.apiSpecId) || [];\n registeredServiceMap.set(service.apiSpecId, [...existingServices, service]);\n }\n\n const uriRequests = new Subject<UriRequestEvent>();\n const uriCancelRequests = new Subject<UriCancelRequestEvent>();\n const lensRequestState = new Map<LensId, LensRequestState>();\n\n const lensTurnOffEvents = lensState.events.pipe(\n forActions(\"turnedOff\"),\n\n tap(([action]) => handleLensApplicationEnd(lensRequestState, action.data.id))\n );\n\n const uriRequestEvents = uriRequests.pipe(\n map((uriRequest) => {\n const lensId = uriRequest.lens.id;\n\n if (!lensRequestState.has(lensId)) {\n lensRequestState.set(lensId, {\n // Prepares a collection to store cancellation handlers.\n // A specific handler will be invoked when a cancellation request is issued by the lens.\n // All handlers will be invoked when the lens is replaced with another one or the session\n // is destroyed.\n cancellationHandlers: new Map(),\n // Parse lens metadata to obtain supported Remote API specs.\n supportedSpecIds: new Set(\n (lensRepository.getLensMetadata(lensId)?.featureMetadata ?? [])\n .filter((feature) => feature.typeUrl === knownAnyTypes.remoteApiInfo)\n .flatMap((any) => RemoteApiInfo.decode(any.value).apiSpecIds)\n ),\n });\n }\n const requestState = lensRequestState.get(lensId)!;\n\n // Extracts the spec ID and endpoint ID from the provided Remote API request URI.\n // The given URI is expected to conform to the following specification:\n // eslint-disable-next-line max-len\n // https://docs.google.com/document/d/18fbGYDhD2N_aMTe4ZLY4QKeCSoMeJuklG28TutDzLZc/edit#bookmark=id.p2y39gwgbm4g\n const { route } = extractSchemeAndRoute(uriRequest.request.uri);\n const [specId, endpointIdWithQuery] = route.split(\"/\").slice(2);\n const [endpointId] = endpointIdWithQuery.split(\"?\");\n\n return { uriRequest, specId, endpointId, requestState };\n }),\n\n // only handle requests for API spec ID that current lens supports\n filter(({ specId, requestState }) => requestState.supportedSpecIds.has(specId)),\n\n // only handle requests if we have a registered service for it\n filter(({ specId }) => registeredServiceMap.has(specId)),\n\n map(({ uriRequest, specId, endpointId, requestState }) => {\n const dimensions = new Map([[\"specId\", specId]]);\n reporter.count(\"lens_remote-api_requests\", 1, dimensions);\n\n const remoteApiRequest: RemoteApiRequest = {\n apiSpecId: specId,\n body: uriRequest.request.data,\n endpointId,\n parameters: uriRequest.request.metadata,\n };\n\n // Looks for the first Remote API request handler.\n for (const service of registeredServiceMap.get(specId) ?? []) {\n let requestHandler: RemoteApiRequestHandler | undefined = undefined;\n try {\n requestHandler = service.getRequestHandler(remoteApiRequest, uriRequest.lens);\n } catch {\n logger.warn(\"Client's Remote API request handler factory threw an error.\");\n }\n\n if (requestHandler) {\n reporter.count(\"lens_remote-api_handled-requests\", 1, dimensions);\n\n let cancellationHandler: RemoteApiCancelRequestHandler | void = undefined;\n try {\n // Calls client's Remote API handler to process the request.\n cancellationHandler = requestHandler((response) => {\n reporter.count(\"lens_remote-api_responses\", 1, dimensions);\n\n const responseCode = statusToResponseCodeMap[response.status] ?? ResponseCode.UNRECOGNIZED;\n const uriResponse: UriResponse = {\n code: uriResponseOkCode,\n description: \"\",\n contentType: apiBinaryContentType,\n data: response.body,\n metadata: {\n ...response.metadata,\n [apiResponseStatusHeader]: responseCodeToNumber(responseCode).toString(),\n },\n };\n uriRequest.reply(uriResponse);\n });\n } catch (error) {\n logger.warn(\"Client's Remote API request handler threw an error.\");\n }\n\n if (typeof cancellationHandler === \"function\") {\n requestState.cancellationHandlers.set(uriRequest.request.identifier, () => {\n try {\n cancellationHandler!();\n } catch {\n logger.warn(\"Client's Remote API request cancellation handler threw an error.\");\n }\n });\n }\n\n break;\n }\n }\n })\n );\n\n const uriCancelRequestEvents = uriCancelRequests.pipe(\n tap((uriRequest) => {\n const cancellationHandlers = lensRequestState.get(uriRequest.lens.id)?.cancellationHandlers;\n if (cancellationHandlers) {\n callCancellationHandler(cancellationHandlers, uriRequest.request.requestId);\n }\n })\n );\n\n merge(lensTurnOffEvents, uriRequestEvents, uriCancelRequestEvents)\n .pipe(\n catchError((error, sourcePipe) => {\n // The expectation is that if an error occurs, it happens in our own implementation,\n // because app callbacks are wrapped with try..catch blocks.\n // Therefore, we would like to report this error.\n logger.error(error);\n reporter.count(\"lens_remote-api_errors\", 1);\n // Return the source pipe so that we can retry the pipe instead of just completing it.\n return sourcePipe;\n }),\n // When the pipe completes due to an error,\n // we want to resubscribe to the original pipe to keep it alive.\n retry(),\n takeUntil(sessionState.events.pipe(forActions(\"destroy\")))\n )\n .subscribe({\n complete: () => handleLensApplicationEnd(lensRequestState, ...lensRequestState.keys()),\n });\n\n return {\n uri: \"app://remote-api/performApiRequest\",\n\n handleRequest(request, reply, lens) {\n uriRequests.next({ request, reply, lens });\n },\n\n cancelRequest(request, lens) {\n uriCancelRequests.next({ request, lens });\n },\n };\n}\n"]}
@@ -1,8 +1,14 @@
1
- import { LensCoreModule, Uri, UriCancelRequest, UriRequest, UriResponse } from "../lens-core-module/generated-types";
1
+ import { Uri, UriCancelRequest, UriRequest, UriResponse } from "../lens-core-module/generated-types";
2
2
  import { Lens } from "../lens/Lens";
3
- import { LensKeyboard } from "../session/LensKeyboard";
3
+ export declare function extractSchemeAndRoute(uri: Uri): {
4
+ scheme: string;
5
+ route: string;
6
+ };
7
+ export declare function isUriHandlers(value: unknown): value is UriHandlers;
8
+ export declare function isUriResponse(value: unknown): value is UriResponse;
4
9
  /**
5
10
  * Provides a way for a lens to call into external services that work under HTTP-like protocol.
11
+ * @internal
6
12
  */
7
13
  export interface UriHandler {
8
14
  /**
@@ -26,29 +32,16 @@ export interface UriHandler {
26
32
  }
27
33
  /**
28
34
  * Array of {@link UriHandler} objects.
35
+ * @internal
29
36
  */
30
37
  export type UriHandlers = UriHandler[];
31
38
  /**
32
39
  * An extension point for client URI handlers.
40
+ * @internal
33
41
  */
34
42
  export declare const uriHandlersFactory: {
35
43
  (): UriHandlers;
36
44
  token: "UriHandlers";
37
45
  dependencies: [];
38
46
  };
39
- /**
40
- * Registers URI handlers within LensCore.
41
- * @internal
42
- */
43
- export declare const registerUriHandlers: {
44
- (args_0: LensCoreModule, args_1: import("@snap/state-management").StateMachine<import("@snap/state-management").Action<"applyLens", {
45
- lens: Lens;
46
- launchParams?: import("..").LensLaunchParams | undefined;
47
- }> | import("@snap/state-management").Action<"downloadComplete", Lens> | import("@snap/state-management").Action<"turnedOn", Lens> | import("@snap/state-management").Action<"resourcesLoaded", Lens> | import("@snap/state-management").Action<"firstFrameProcessed", Lens> | import("@snap/state-management").Action<"applyLensComplete", Lens> | import("@snap/state-management").Action<"applyLensFailed", {
48
- error: import("../session/lensState").LensErrors;
49
- lens: Lens;
50
- }> | import("@snap/state-management").Action<"applyLensAborted", Lens> | import("@snap/state-management").Action<"removeLens", undefined> | import("@snap/state-management").Action<"turnedOff", Lens> | import("@snap/state-management").Action<"removeLensComplete", undefined> | import("@snap/state-management").Action<"removeLensFailed", Error>, import("@snap/state-management").State<"noLensApplied", undefined> | import("@snap/state-management").State<"applyingLens", Lens> | import("@snap/state-management").State<"lensApplied", Lens>>, args_2: UriHandlers, args_3: LensKeyboard): void;
51
- token: "registerUriHandlers";
52
- dependencies: readonly ["lensCore", "lensState", "UriHandlers", "lensKeyboard"];
53
- };
54
47
  export { Uri, UriCancelRequest, UriRequest, UriResponse } from "../lens-core-module/generated-types";