@snap/camera-kit 0.7.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 (554) hide show
  1. package/LICENSE.md +6247 -0
  2. package/README.md +166 -0
  3. package/docs/html/.nojekyll +1 -0
  4. package/docs/html/assets/highlight.css +106 -0
  5. package/docs/html/assets/main.js +54 -0
  6. package/docs/html/assets/search.js +1 -0
  7. package/docs/html/assets/style.css +1225 -0
  8. package/docs/html/assets/widgets.png +0 -0
  9. package/docs/html/assets/widgets@2x.png +0 -0
  10. package/docs/html/classes/CameraKit.html +121 -0
  11. package/docs/html/classes/CameraKitSession.html +347 -0
  12. package/docs/html/classes/CameraKitSource.html +152 -0
  13. package/docs/html/classes/LensPerformanceMeasurement.html +115 -0
  14. package/docs/html/classes/LensPerformanceMetrics.html +76 -0
  15. package/docs/html/classes/LensRepository.html +171 -0
  16. package/docs/html/classes/LensSources.html +82 -0
  17. package/docs/html/classes/Transform2D.html +99 -0
  18. package/docs/html/classes/TypedCustomEvent.html +109 -0
  19. package/docs/html/classes/TypedEventTarget.html +146 -0
  20. package/docs/html/functions/Injectable.html +193 -0
  21. package/docs/html/functions/bootstrapCameraKit.html +158 -0
  22. package/docs/html/functions/createExtension.html +127 -0
  23. package/docs/html/functions/createImageSource.html +123 -0
  24. package/docs/html/functions/createMediaStreamSource.html +123 -0
  25. package/docs/html/functions/createUserMediaSource.html +127 -0
  26. package/docs/html/functions/createVideoSource.html +124 -0
  27. package/docs/html/functions/estimateLensPerformance.html +116 -0
  28. package/docs/html/functions/getRequiredBootstrapURLs.html +124 -0
  29. package/docs/html/functions/lensSourcesFactory.html +116 -0
  30. package/docs/html/functions/uriHandlersFactory.html +118 -0
  31. package/docs/html/index.html +208 -0
  32. package/docs/html/interfaces/CameraKitBootstrapConfiguration.html +132 -0
  33. package/docs/html/interfaces/CameraKitSourceSubscriber.html +121 -0
  34. package/docs/html/interfaces/ComputedFrameMetrics.html +70 -0
  35. package/docs/html/interfaces/CreateSessionOptions.html +77 -0
  36. package/docs/html/interfaces/EstimatedLensPerformance.html +78 -0
  37. package/docs/html/interfaces/Lens.html +115 -0
  38. package/docs/html/interfaces/LensSource.html +113 -0
  39. package/docs/html/interfaces/MediaStreamSourceOptions.html +65 -0
  40. package/docs/html/interfaces/UriCancelRequest.html +65 -0
  41. package/docs/html/interfaces/UriHandler.html +128 -0
  42. package/docs/html/interfaces/UriRequest.html +80 -0
  43. package/docs/html/interfaces/UriResponse.html +80 -0
  44. package/docs/html/interfaces/VideoSourceOptions.html +60 -0
  45. package/docs/html/modules.html +198 -0
  46. package/docs/html/types/AssetLoader.html +126 -0
  47. package/docs/html/types/AssetTiming.html +116 -0
  48. package/docs/html/types/BenchmarkError.html +107 -0
  49. package/docs/html/types/BootstrapError.html +110 -0
  50. package/docs/html/types/CacheKeyNotFoundError.html +107 -0
  51. package/docs/html/types/CameraKitDeviceInfo.html +114 -0
  52. package/docs/html/types/CameraKitSessionEventListener.html +109 -0
  53. package/docs/html/types/CameraKitSessionEvents.html +118 -0
  54. package/docs/html/types/CameraKitSourceError.html +107 -0
  55. package/docs/html/types/CameraKitSourceInfo.html +107 -0
  56. package/docs/html/types/CameraKitSourceOptions.html +113 -0
  57. package/docs/html/types/ConfigurationError.html +109 -0
  58. package/docs/html/types/Keyboard.html +196 -0
  59. package/docs/html/types/KeyboardEvents.html +109 -0
  60. package/docs/html/types/LegalError.html +107 -0
  61. package/docs/html/types/LensAssetError.html +109 -0
  62. package/docs/html/types/LensContentValidationError.html +107 -0
  63. package/docs/html/types/LensError.html +107 -0
  64. package/docs/html/types/LensExecutionError.html +114 -0
  65. package/docs/html/types/LensImagePickerError.html +110 -0
  66. package/docs/html/types/LensLaunchParams.html +109 -0
  67. package/docs/html/types/LensMetricsEvents.html +110 -0
  68. package/docs/html/types/LensPerformanceCluster.html +107 -0
  69. package/docs/html/types/LensView.html +119 -0
  70. package/docs/html/types/LensWait.html +111 -0
  71. package/docs/html/types/PersistentStoreError.html +109 -0
  72. package/docs/html/types/PlatformNotSupportedError.html +110 -0
  73. package/docs/html/types/PublicContainer.html +110 -0
  74. package/docs/html/types/RenderTarget.html +111 -0
  75. package/docs/html/types/Uri.html +107 -0
  76. package/docs/html/types/UriHandlers.html +109 -0
  77. package/docs/html/types/WebGLError.html +107 -0
  78. package/docs/html/variables/extensionRequestContext.html +109 -0
  79. package/docs/md/.nojekyll +1 -0
  80. package/docs/md/README.md +168 -0
  81. package/docs/md/classes/CameraKit.md +94 -0
  82. package/docs/md/classes/CameraKitSession.md +359 -0
  83. package/docs/md/classes/CameraKitSource.md +110 -0
  84. package/docs/md/classes/LensPerformanceMeasurement.md +77 -0
  85. package/docs/md/classes/LensPerformanceMetrics.md +37 -0
  86. package/docs/md/classes/LensRepository.md +145 -0
  87. package/docs/md/classes/LensSources.md +29 -0
  88. package/docs/md/classes/Transform2D.md +55 -0
  89. package/docs/md/classes/TypedCustomEvent.md +65 -0
  90. package/docs/md/classes/TypedEventTarget.md +103 -0
  91. package/docs/md/interfaces/CameraKitBootstrapConfiguration.md +106 -0
  92. package/docs/md/interfaces/CameraKitSourceSubscriber.md +55 -0
  93. package/docs/md/interfaces/ComputedFrameMetrics.md +29 -0
  94. package/docs/md/interfaces/CreateSessionOptions.md +35 -0
  95. package/docs/md/interfaces/EstimatedLensPerformance.md +38 -0
  96. package/docs/md/interfaces/Lens.md +84 -0
  97. package/docs/md/interfaces/LensSource.md +68 -0
  98. package/docs/md/interfaces/MediaStreamSourceOptions.md +22 -0
  99. package/docs/md/interfaces/UriCancelRequest.md +22 -0
  100. package/docs/md/interfaces/UriHandler.md +63 -0
  101. package/docs/md/interfaces/UriRequest.md +43 -0
  102. package/docs/md/interfaces/UriResponse.md +43 -0
  103. package/docs/md/interfaces/VideoSourceOptions.md +15 -0
  104. package/docs/md/modules.md +827 -0
  105. package/lib/CameraKit.d.ts +170 -0
  106. package/lib/CameraKit.js +145 -0
  107. package/lib/CameraKit.js.map +1 -0
  108. package/lib/__tests__/data.d.ts +9 -0
  109. package/lib/__tests__/data.js +50 -0
  110. package/lib/__tests__/data.js.map +1 -0
  111. package/lib/__tests__/deferred.d.ts +16 -0
  112. package/lib/__tests__/deferred.js +29 -0
  113. package/lib/__tests__/deferred.js.map +1 -0
  114. package/lib/__tests__/jest.matchers.d.ts +17 -0
  115. package/lib/__tests__/jest.matchers.js +67 -0
  116. package/lib/__tests__/jest.matchers.js.map +1 -0
  117. package/lib/assertPlatformSupported.d.ts +4 -0
  118. package/lib/assertPlatformSupported.js +10 -0
  119. package/lib/assertPlatformSupported.js.map +1 -0
  120. package/lib/benchmark/benchmarkGflops.d.ts +16 -0
  121. package/lib/benchmark/benchmarkGflops.js +129 -0
  122. package/lib/benchmark/benchmarkGflops.js.map +1 -0
  123. package/lib/benchmark/estimateLensPerformanceCluster.d.ts +33 -0
  124. package/lib/benchmark/estimateLensPerformanceCluster.js +48 -0
  125. package/lib/benchmark/estimateLensPerformanceCluster.js.map +1 -0
  126. package/lib/benchmark/webglUtils.d.ts +7 -0
  127. package/lib/benchmark/webglUtils.js +87 -0
  128. package/lib/benchmark/webglUtils.js.map +1 -0
  129. package/lib/bootstrapCameraKit.d.ts +96 -0
  130. package/lib/bootstrapCameraKit.js +204 -0
  131. package/lib/bootstrapCameraKit.js.map +1 -0
  132. package/lib/common/__mocks__/loadScript.d.ts +1 -0
  133. package/lib/common/__mocks__/loadScript.js +10 -0
  134. package/lib/common/__mocks__/loadScript.js.map +1 -0
  135. package/lib/common/assertions.d.ts +27 -0
  136. package/lib/common/assertions.js +39 -0
  137. package/lib/common/assertions.js.map +1 -0
  138. package/lib/common/cameraKitUserAgent.d.ts +34 -0
  139. package/lib/common/cameraKitUserAgent.js +216 -0
  140. package/lib/common/cameraKitUserAgent.js.map +1 -0
  141. package/lib/common/copyDefinedProperties.d.ts +13 -0
  142. package/lib/common/copyDefinedProperties.js +16 -0
  143. package/lib/common/copyDefinedProperties.js.map +1 -0
  144. package/lib/common/entries.d.ts +3 -0
  145. package/lib/common/entries.js +3 -0
  146. package/lib/common/entries.js.map +1 -0
  147. package/lib/common/errorHelpers.d.ts +10 -0
  148. package/lib/common/errorHelpers.js +24 -0
  149. package/lib/common/errorHelpers.js.map +1 -0
  150. package/lib/common/getFilename.d.ts +1 -0
  151. package/lib/common/getFilename.js +4 -0
  152. package/lib/common/getFilename.js.map +1 -0
  153. package/lib/common/index.d.ts +2 -0
  154. package/lib/common/index.js +3 -0
  155. package/lib/common/index.js.map +1 -0
  156. package/lib/common/loadScript.d.ts +1 -0
  157. package/lib/common/loadScript.js +11 -0
  158. package/lib/common/loadScript.js.map +1 -0
  159. package/lib/common/locale.d.ts +2 -0
  160. package/lib/common/locale.js +11 -0
  161. package/lib/common/locale.js.map +1 -0
  162. package/lib/common/localization.d.ts +43 -0
  163. package/lib/common/localization.js +43 -0
  164. package/lib/common/localization.js.map +1 -0
  165. package/lib/common/memoize.d.ts +8 -0
  166. package/lib/common/memoize.js +15 -0
  167. package/lib/common/memoize.js.map +1 -0
  168. package/lib/common/pageVisibility.d.ts +20 -0
  169. package/lib/common/pageVisibility.js +62 -0
  170. package/lib/common/pageVisibility.js.map +1 -0
  171. package/lib/common/time.d.ts +1 -0
  172. package/lib/common/time.js +2 -0
  173. package/lib/common/time.js.map +1 -0
  174. package/lib/common/typeguards.d.ts +53 -0
  175. package/lib/common/typeguards.js +92 -0
  176. package/lib/common/typeguards.js.map +1 -0
  177. package/lib/common/types.d.ts +10 -0
  178. package/lib/common/types.js +2 -0
  179. package/lib/common/types.js.map +1 -0
  180. package/lib/common/validate.d.ts +14 -0
  181. package/lib/common/validate.js +104 -0
  182. package/lib/common/validate.js.map +1 -0
  183. package/lib/configuration.d.ts +92 -0
  184. package/lib/configuration.js +36 -0
  185. package/lib/configuration.js.map +1 -0
  186. package/lib/configurationOverrides.d.ts +12 -0
  187. package/lib/configurationOverrides.js +41 -0
  188. package/lib/configurationOverrides.js.map +1 -0
  189. package/lib/dependency-injection/Container.d.ts +177 -0
  190. package/lib/dependency-injection/Container.js +160 -0
  191. package/lib/dependency-injection/Container.js.map +1 -0
  192. package/lib/dependency-injection/Injectable.d.ts +39 -0
  193. package/lib/dependency-injection/Injectable.js +18 -0
  194. package/lib/dependency-injection/Injectable.js.map +1 -0
  195. package/lib/dependency-injection/PartialContainer.d.ts +81 -0
  196. package/lib/dependency-injection/PartialContainer.js +85 -0
  197. package/lib/dependency-injection/PartialContainer.js.map +1 -0
  198. package/lib/dependency-injection/RootServices.d.ts +62 -0
  199. package/lib/dependency-injection/RootServices.js +2 -0
  200. package/lib/dependency-injection/RootServices.js.map +1 -0
  201. package/lib/dependency-injection/types.d.ts +56 -0
  202. package/lib/dependency-injection/types.js +2 -0
  203. package/lib/dependency-injection/types.js.map +1 -0
  204. package/lib/environment.json +1 -0
  205. package/lib/events/TypedCustomEvent.d.ts +10 -0
  206. package/lib/events/TypedCustomEvent.js +11 -0
  207. package/lib/events/TypedCustomEvent.js.map +1 -0
  208. package/lib/events/TypedEventTarget.d.ts +25 -0
  209. package/lib/events/TypedEventTarget.js +57 -0
  210. package/lib/events/TypedEventTarget.js.map +1 -0
  211. package/lib/events/scan.d.ts +15 -0
  212. package/lib/events/scan.js +46 -0
  213. package/lib/events/scan.js.map +1 -0
  214. package/lib/extensions/LensSources.d.ts +58 -0
  215. package/lib/extensions/LensSources.js +50 -0
  216. package/lib/extensions/LensSources.js.map +1 -0
  217. package/lib/extensions/UriHandlers.d.ts +54 -0
  218. package/lib/extensions/UriHandlers.js +93 -0
  219. package/lib/extensions/UriHandlers.js.map +1 -0
  220. package/lib/extensions/extensionRequestContext.d.ts +4 -0
  221. package/lib/extensions/extensionRequestContext.js +14 -0
  222. package/lib/extensions/extensionRequestContext.js.map +1 -0
  223. package/lib/generated-proto/blizzard/cameraKitEvents.d.ts +5603 -0
  224. package/lib/generated-proto/blizzard/cameraKitEvents.js +522 -0
  225. package/lib/generated-proto/blizzard/cameraKitEvents.js.map +1 -0
  226. package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.d.ts +98 -0
  227. package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.js +260 -0
  228. package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.js.map +1 -0
  229. package/lib/generated-proto/pb_schema/camera_kit/v3/export.d.ts +543 -0
  230. package/lib/generated-proto/pb_schema/camera_kit/v3/export.js +429 -0
  231. package/lib/generated-proto/pb_schema/camera_kit/v3/export.js.map +1 -0
  232. package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.d.ts +100 -0
  233. package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.js +164 -0
  234. package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.js.map +1 -0
  235. package/lib/generated-proto/pb_schema/camera_kit/v3/lens.d.ts +395 -0
  236. package/lib/generated-proto/pb_schema/camera_kit/v3/lens.js +644 -0
  237. package/lib/generated-proto/pb_schema/camera_kit/v3/lens.js.map +1 -0
  238. package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.d.ts +185 -0
  239. package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.js +172 -0
  240. package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.js.map +1 -0
  241. package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.d.ts +86 -0
  242. package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.js +234 -0
  243. package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.js.map +1 -0
  244. package/lib/generated-proto/pb_schema/camera_kit/v3/service.d.ts +854 -0
  245. package/lib/generated-proto/pb_schema/camera_kit/v3/service.js +629 -0
  246. package/lib/generated-proto/pb_schema/camera_kit/v3/service.js.map +1 -0
  247. package/lib/generated-proto/pb_schema/cdp/cof/benchmark.d.ts +86 -0
  248. package/lib/generated-proto/pb_schema/cdp/cof/benchmark.js +185 -0
  249. package/lib/generated-proto/pb_schema/cdp/cof/benchmark.js.map +1 -0
  250. package/lib/generated-proto/pb_schema/cdp/cof/benchmark_name.d.ts +95 -0
  251. package/lib/generated-proto/pb_schema/cdp/cof/benchmark_name.js +104 -0
  252. package/lib/generated-proto/pb_schema/cdp/cof/benchmark_name.js.map +1 -0
  253. package/lib/generated-proto/pb_schema/cdp/cof/circumstance_service.d.ts +10212 -0
  254. package/lib/generated-proto/pb_schema/cdp/cof/circumstance_service.js +1300 -0
  255. package/lib/generated-proto/pb_schema/cdp/cof/circumstance_service.js.map +1 -0
  256. package/lib/generated-proto/pb_schema/cdp/cof/config_request.d.ts +401 -0
  257. package/lib/generated-proto/pb_schema/cdp/cof/config_request.js +525 -0
  258. package/lib/generated-proto/pb_schema/cdp/cof/config_request.js.map +1 -0
  259. package/lib/generated-proto/pb_schema/cdp/cof/config_response.d.ts +1287 -0
  260. package/lib/generated-proto/pb_schema/cdp/cof/config_response.js +135 -0
  261. package/lib/generated-proto/pb_schema/cdp/cof/config_response.js.map +1 -0
  262. package/lib/generated-proto/pb_schema/cdp/cof/config_result.d.ts +4208 -0
  263. package/lib/generated-proto/pb_schema/cdp/cof/config_result.js +1053 -0
  264. package/lib/generated-proto/pb_schema/cdp/cof/config_result.js.map +1 -0
  265. package/lib/generated-proto/pb_schema/cdp/cof/debug_info.d.ts +102 -0
  266. package/lib/generated-proto/pb_schema/cdp/cof/debug_info.js +165 -0
  267. package/lib/generated-proto/pb_schema/cdp/cof/debug_info.js.map +1 -0
  268. package/lib/generated-proto/pb_schema/cdp/cof/namespace.d.ts +8 -0
  269. package/lib/generated-proto/pb_schema/cdp/cof/namespace.js +17 -0
  270. package/lib/generated-proto/pb_schema/cdp/cof/namespace.js.map +1 -0
  271. package/lib/generated-proto/pb_schema/common/ruid.d.ts +75 -0
  272. package/lib/generated-proto/pb_schema/common/ruid.js +96 -0
  273. package/lib/generated-proto/pb_schema/common/ruid.js.map +1 -0
  274. package/lib/generated-proto/pb_schema/common/value.d.ts +131 -0
  275. package/lib/generated-proto/pb_schema/common/value.js +204 -0
  276. package/lib/generated-proto/pb_schema/common/value.js.map +1 -0
  277. package/lib/generated-proto/pb_schema/google/api/annotations.d.ts +1 -0
  278. package/lib/generated-proto/pb_schema/google/api/annotations.js +9 -0
  279. package/lib/generated-proto/pb_schema/google/api/annotations.js.map +1 -0
  280. package/lib/generated-proto/pb_schema/google/api/http.d.ts +3636 -0
  281. package/lib/generated-proto/pb_schema/google/api/http.js +271 -0
  282. package/lib/generated-proto/pb_schema/google/api/http.js.map +1 -0
  283. package/lib/generated-proto/pb_schema/google/protobuf/any.d.ts +139 -0
  284. package/lib/generated-proto/pb_schema/google/protobuf/any.js +94 -0
  285. package/lib/generated-proto/pb_schema/google/protobuf/any.js.map +1 -0
  286. package/lib/generated-proto/pb_schema/google/protobuf/descriptor.d.ts +50968 -0
  287. package/lib/generated-proto/pb_schema/google/protobuf/descriptor.js +2962 -0
  288. package/lib/generated-proto/pb_schema/google/protobuf/descriptor.js.map +1 -0
  289. package/lib/generated-proto/pb_schema/google/protobuf/timestamp.d.ts +98 -0
  290. package/lib/generated-proto/pb_schema/google/protobuf/timestamp.js +82 -0
  291. package/lib/generated-proto/pb_schema/google/protobuf/timestamp.js.map +1 -0
  292. package/lib/generated-proto/pb_schema/google/protobuf/wrappers.d.ts +173 -0
  293. package/lib/generated-proto/pb_schema/google/protobuf/wrappers.js +332 -0
  294. package/lib/generated-proto/pb_schema/google/protobuf/wrappers.js.map +1 -0
  295. package/lib/generated-proto/pb_schema/lenses/geocircle.d.ts +42 -0
  296. package/lib/generated-proto/pb_schema/lenses/geocircle.js +52 -0
  297. package/lib/generated-proto/pb_schema/lenses/geocircle.js.map +1 -0
  298. package/lib/generated-proto/pb_schema/lenses/geopoint.d.ts +32 -0
  299. package/lib/generated-proto/pb_schema/lenses/geopoint.js +50 -0
  300. package/lib/generated-proto/pb_schema/lenses/geopoint.js.map +1 -0
  301. package/lib/generated-proto/pb_schema/lenses/launch_params.d.ts +29 -0
  302. package/lib/generated-proto/pb_schema/lenses/launch_params.js +43 -0
  303. package/lib/generated-proto/pb_schema/lenses/launch_params.js.map +1 -0
  304. package/lib/generated-proto/pb_schema/lenses/launchdata.d.ts +365 -0
  305. package/lib/generated-proto/pb_schema/lenses/launchdata.js +216 -0
  306. package/lib/generated-proto/pb_schema/lenses/launchdata.js.map +1 -0
  307. package/lib/generated-proto/pb_schema/lenses/lures.d.ts +113 -0
  308. package/lib/generated-proto/pb_schema/lenses/lures.js +64 -0
  309. package/lib/generated-proto/pb_schema/lenses/lures.js.map +1 -0
  310. package/lib/generated-proto/pb_schema/lenses/persistent_store.d.ts +29 -0
  311. package/lib/generated-proto/pb_schema/lenses/persistent_store.js +43 -0
  312. package/lib/generated-proto/pb_schema/lenses/persistent_store.js.map +1 -0
  313. package/lib/generated-proto/pb_schema/lenses/snappable.d.ts +921 -0
  314. package/lib/generated-proto/pb_schema/lenses/snappable.js +954 -0
  315. package/lib/generated-proto/pb_schema/lenses/snappable.js.map +1 -0
  316. package/lib/generated-proto/pb_schema/lenses/user_data.d.ts +247 -0
  317. package/lib/generated-proto/pb_schema/lenses/user_data.js +362 -0
  318. package/lib/generated-proto/pb_schema/lenses/user_data.js.map +1 -0
  319. package/lib/handlers/HandlerChainBuilder.d.ts +95 -0
  320. package/lib/handlers/HandlerChainBuilder.js +187 -0
  321. package/lib/handlers/HandlerChainBuilder.js.map +1 -0
  322. package/lib/handlers/arrayBufferParsingHandler.d.ts +10 -0
  323. package/lib/handlers/arrayBufferParsingHandler.js +18 -0
  324. package/lib/handlers/arrayBufferParsingHandler.js.map +1 -0
  325. package/lib/handlers/batchingHandler.d.ts +25 -0
  326. package/lib/handlers/batchingHandler.js +79 -0
  327. package/lib/handlers/batchingHandler.js.map +1 -0
  328. package/lib/handlers/cameraKitServiceFetchHandlerFactory.d.ts +12 -0
  329. package/lib/handlers/cameraKitServiceFetchHandlerFactory.js +19 -0
  330. package/lib/handlers/cameraKitServiceFetchHandlerFactory.js.map +1 -0
  331. package/lib/handlers/debugHandler.d.ts +8 -0
  332. package/lib/handlers/debugHandler.js +27 -0
  333. package/lib/handlers/debugHandler.js.map +1 -0
  334. package/lib/handlers/defaultFetchHandler.d.ts +15 -0
  335. package/lib/handlers/defaultFetchHandler.js +29 -0
  336. package/lib/handlers/defaultFetchHandler.js.map +1 -0
  337. package/lib/handlers/headersModifyingFetchHandler.d.ts +8 -0
  338. package/lib/handlers/headersModifyingFetchHandler.js +13 -0
  339. package/lib/handlers/headersModifyingFetchHandler.js.map +1 -0
  340. package/lib/handlers/index.d.ts +2 -0
  341. package/lib/handlers/index.js +3 -0
  342. package/lib/handlers/index.js.map +1 -0
  343. package/lib/handlers/mappingHandler.d.ts +15 -0
  344. package/lib/handlers/mappingHandler.js +65 -0
  345. package/lib/handlers/mappingHandler.js.map +1 -0
  346. package/lib/handlers/noCorsRetryingFetchHandler.d.ts +48 -0
  347. package/lib/handlers/noCorsRetryingFetchHandler.js +94 -0
  348. package/lib/handlers/noCorsRetryingFetchHandler.js.map +1 -0
  349. package/lib/handlers/persistingHandler.d.ts +14 -0
  350. package/lib/handlers/persistingHandler.js +71 -0
  351. package/lib/handlers/persistingHandler.js.map +1 -0
  352. package/lib/handlers/rateLimitingHandler.d.ts +20 -0
  353. package/lib/handlers/rateLimitingHandler.js +43 -0
  354. package/lib/handlers/rateLimitingHandler.js.map +1 -0
  355. package/lib/handlers/requestStateEmittingHandler.d.ts +29 -0
  356. package/lib/handlers/requestStateEmittingHandler.js +43 -0
  357. package/lib/handlers/requestStateEmittingHandler.js.map +1 -0
  358. package/lib/handlers/responseCachingHandler.d.ts +27 -0
  359. package/lib/handlers/responseCachingHandler.js +94 -0
  360. package/lib/handlers/responseCachingHandler.js.map +1 -0
  361. package/lib/handlers/retryingHandler.d.ts +37 -0
  362. package/lib/handlers/retryingHandler.js +73 -0
  363. package/lib/handlers/retryingHandler.js.map +1 -0
  364. package/lib/handlers/timeoutHandler.d.ts +18 -0
  365. package/lib/handlers/timeoutHandler.js +30 -0
  366. package/lib/handlers/timeoutHandler.js.map +1 -0
  367. package/lib/index.d.ts +33 -0
  368. package/lib/index.js +32 -0
  369. package/lib/index.js.map +1 -0
  370. package/lib/legal/legalPrompt.d.ts +17 -0
  371. package/lib/legal/legalPrompt.js +144 -0
  372. package/lib/legal/legalPrompt.js.map +1 -0
  373. package/lib/legal/legalState.d.ts +50 -0
  374. package/lib/legal/legalState.js +149 -0
  375. package/lib/legal/legalState.js.map +1 -0
  376. package/lib/lens/Lens.d.ts +71 -0
  377. package/lib/lens/Lens.js +63 -0
  378. package/lib/lens/Lens.js.map +1 -0
  379. package/lib/lens/LensLaunchParams.d.ts +19 -0
  380. package/lib/lens/LensLaunchParams.js +38 -0
  381. package/lib/lens/LensLaunchParams.js.map +1 -0
  382. package/lib/lens/LensPersistenceStore.d.ts +7 -0
  383. package/lib/lens/LensPersistenceStore.js +20 -0
  384. package/lib/lens/LensPersistenceStore.js.map +1 -0
  385. package/lib/lens/LensRepository.d.ts +134 -0
  386. package/lib/lens/LensRepository.js +239 -0
  387. package/lib/lens/LensRepository.js.map +1 -0
  388. package/lib/lens/assets/LensAssetRepository.d.ts +66 -0
  389. package/lib/lens/assets/LensAssetRepository.js +179 -0
  390. package/lib/lens/assets/LensAssetRepository.js.map +1 -0
  391. package/lib/lens/assets/LensAssetsProvider.d.ts +21 -0
  392. package/lib/lens/assets/LensAssetsProvider.js +41 -0
  393. package/lib/lens/assets/LensAssetsProvider.js.map +1 -0
  394. package/lib/lens/assets/deviceDependentAssetLoader.d.ts +11 -0
  395. package/lib/lens/assets/deviceDependentAssetLoader.js +58 -0
  396. package/lib/lens/assets/deviceDependentAssetLoader.js.map +1 -0
  397. package/lib/lens/assets/remoteMediaAssetLoaderFactory.d.ts +10 -0
  398. package/lib/lens/assets/remoteMediaAssetLoaderFactory.js +26 -0
  399. package/lib/lens/assets/remoteMediaAssetLoaderFactory.js.map +1 -0
  400. package/lib/lens/assets/staticAssetLoader.d.ts +10 -0
  401. package/lib/lens/assets/staticAssetLoader.js +24 -0
  402. package/lib/lens/assets/staticAssetLoader.js.map +1 -0
  403. package/lib/lens/index.d.ts +7 -0
  404. package/lib/lens/index.js +7 -0
  405. package/lib/lens/index.js.map +1 -0
  406. package/lib/lens/lensEnvelopeUtil.d.ts +5 -0
  407. package/lib/lens/lensEnvelopeUtil.js +19 -0
  408. package/lib/lens/lensEnvelopeUtil.js.map +1 -0
  409. package/lib/lens/lensHttpUtil.d.ts +4 -0
  410. package/lib/lens/lensHttpUtil.js +30 -0
  411. package/lib/lens/lensHttpUtil.js.map +1 -0
  412. package/lib/lens-client-interface/exif.d.ts +20 -0
  413. package/lib/lens-client-interface/exif.js +61 -0
  414. package/lib/lens-client-interface/exif.js.map +1 -0
  415. package/lib/lens-client-interface/imagePicker.d.ts +7 -0
  416. package/lib/lens-client-interface/imagePicker.js +128 -0
  417. package/lib/lens-client-interface/imagePicker.js.map +1 -0
  418. package/lib/lens-client-interface/lensClientInterface.d.ts +13 -0
  419. package/lib/lens-client-interface/lensClientInterface.js +30 -0
  420. package/lib/lens-client-interface/lensClientInterface.js.map +1 -0
  421. package/lib/lens-core-module/generated-types.d.ts +426 -0
  422. package/lib/lens-core-module/generated-types.js +2 -0
  423. package/lib/lens-core-module/generated-types.js.map +1 -0
  424. package/lib/lens-core-module/index.d.ts +2 -0
  425. package/lib/lens-core-module/index.js +3 -0
  426. package/lib/lens-core-module/index.js.map +1 -0
  427. package/lib/lens-core-module/loader/index.d.ts +1 -0
  428. package/lib/lens-core-module/loader/index.js +2 -0
  429. package/lib/lens-core-module/loader/index.js.map +1 -0
  430. package/lib/lens-core-module/loader/lensCoreFactory.d.ts +30 -0
  431. package/lib/lens-core-module/loader/lensCoreFactory.js +121 -0
  432. package/lib/lens-core-module/loader/lensCoreFactory.js.map +1 -0
  433. package/lib/lensCoreWasmVersions.json +5 -0
  434. package/lib/logger/errorLoggingDecorator.d.ts +9 -0
  435. package/lib/logger/errorLoggingDecorator.js +32 -0
  436. package/lib/logger/errorLoggingDecorator.js.map +1 -0
  437. package/lib/logger/logEntries.d.ts +15 -0
  438. package/lib/logger/logEntries.js +14 -0
  439. package/lib/logger/logEntries.js.map +1 -0
  440. package/lib/logger/logger.d.ts +35 -0
  441. package/lib/logger/logger.js +48 -0
  442. package/lib/logger/logger.js.map +1 -0
  443. package/lib/logger/registerLogEntriesSubscriber.d.ts +14 -0
  444. package/lib/logger/registerLogEntriesSubscriber.js +23 -0
  445. package/lib/logger/registerLogEntriesSubscriber.js.map +1 -0
  446. package/lib/media-sources/CameraKitSource.d.ts +88 -0
  447. package/lib/media-sources/CameraKitSource.js +140 -0
  448. package/lib/media-sources/CameraKitSource.js.map +1 -0
  449. package/lib/media-sources/FunctionSource.d.ts +30 -0
  450. package/lib/media-sources/FunctionSource.js +132 -0
  451. package/lib/media-sources/FunctionSource.js.map +1 -0
  452. package/lib/media-sources/ImageSource.d.ts +13 -0
  453. package/lib/media-sources/ImageSource.js +28 -0
  454. package/lib/media-sources/ImageSource.js.map +1 -0
  455. package/lib/media-sources/MediaStreamSource.d.ts +41 -0
  456. package/lib/media-sources/MediaStreamSource.js +146 -0
  457. package/lib/media-sources/MediaStreamSource.js.map +1 -0
  458. package/lib/media-sources/VideoSource.d.ts +21 -0
  459. package/lib/media-sources/VideoSource.js +38 -0
  460. package/lib/media-sources/VideoSource.js.map +1 -0
  461. package/lib/metrics/businessEventsReporter.d.ts +37 -0
  462. package/lib/metrics/businessEventsReporter.js +160 -0
  463. package/lib/metrics/businessEventsReporter.js.map +1 -0
  464. package/lib/metrics/metricsEventTarget.d.ts +41 -0
  465. package/lib/metrics/metricsEventTarget.js +11 -0
  466. package/lib/metrics/metricsEventTarget.js.map +1 -0
  467. package/lib/metrics/metricsHandler.d.ts +9 -0
  468. package/lib/metrics/metricsHandler.js +13 -0
  469. package/lib/metrics/metricsHandler.js.map +1 -0
  470. package/lib/metrics/operationalMetricsReporter.d.ts +52 -0
  471. package/lib/metrics/operationalMetricsReporter.js +108 -0
  472. package/lib/metrics/operationalMetricsReporter.js.map +1 -0
  473. package/lib/metrics/reporters/reportBenchmarks.d.ts +10 -0
  474. package/lib/metrics/reporters/reportBenchmarks.js +29 -0
  475. package/lib/metrics/reporters/reportBenchmarks.js.map +1 -0
  476. package/lib/metrics/reporters/reportGlobalException.d.ts +19 -0
  477. package/lib/metrics/reporters/reportGlobalException.js +68 -0
  478. package/lib/metrics/reporters/reportGlobalException.js.map +1 -0
  479. package/lib/metrics/reporters/reportHttpMetrics.d.ts +17 -0
  480. package/lib/metrics/reporters/reportHttpMetrics.js +92 -0
  481. package/lib/metrics/reporters/reportHttpMetrics.js.map +1 -0
  482. package/lib/metrics/reporters/reportLegalState.d.ts +15 -0
  483. package/lib/metrics/reporters/reportLegalState.js +34 -0
  484. package/lib/metrics/reporters/reportLegalState.js.map +1 -0
  485. package/lib/metrics/reporters/reportLensAndAssetDownload.d.ts +38 -0
  486. package/lib/metrics/reporters/reportLensAndAssetDownload.js +88 -0
  487. package/lib/metrics/reporters/reportLensAndAssetDownload.js.map +1 -0
  488. package/lib/metrics/reporters/reportLensValidationFailed.d.ts +20 -0
  489. package/lib/metrics/reporters/reportLensValidationFailed.js +24 -0
  490. package/lib/metrics/reporters/reportLensValidationFailed.js.map +1 -0
  491. package/lib/metrics/reporters/reportLensView.d.ts +36 -0
  492. package/lib/metrics/reporters/reportLensView.js +101 -0
  493. package/lib/metrics/reporters/reportLensView.js.map +1 -0
  494. package/lib/metrics/reporters/reportLensWait.d.ts +33 -0
  495. package/lib/metrics/reporters/reportLensWait.js +56 -0
  496. package/lib/metrics/reporters/reportLensWait.js.map +1 -0
  497. package/lib/metrics/reporters/reportSessionException.d.ts +17 -0
  498. package/lib/metrics/reporters/reportSessionException.js +12 -0
  499. package/lib/metrics/reporters/reportSessionException.js.map +1 -0
  500. package/lib/metrics/reporters/reportUserSession.d.ts +14 -0
  501. package/lib/metrics/reporters/reportUserSession.js +67 -0
  502. package/lib/metrics/reporters/reportUserSession.js.map +1 -0
  503. package/lib/metrics/reporters/reporters.d.ts +44 -0
  504. package/lib/metrics/reporters/reporters.js +33 -0
  505. package/lib/metrics/reporters/reporters.js.map +1 -0
  506. package/lib/namedErrors.d.ts +107 -0
  507. package/lib/namedErrors.js +56 -0
  508. package/lib/namedErrors.js.map +1 -0
  509. package/lib/persistence/ExpiringPersistence.d.ts +20 -0
  510. package/lib/persistence/ExpiringPersistence.js +58 -0
  511. package/lib/persistence/ExpiringPersistence.js.map +1 -0
  512. package/lib/persistence/IndexedDBPersistence.d.ts +47 -0
  513. package/lib/persistence/IndexedDBPersistence.js +180 -0
  514. package/lib/persistence/IndexedDBPersistence.js.map +1 -0
  515. package/lib/persistence/Persistence.d.ts +25 -0
  516. package/lib/persistence/Persistence.js +10 -0
  517. package/lib/persistence/Persistence.js.map +1 -0
  518. package/lib/remote-configuration/cofHandler.d.ts +21 -0
  519. package/lib/remote-configuration/cofHandler.js +75 -0
  520. package/lib/remote-configuration/cofHandler.js.map +1 -0
  521. package/lib/remote-configuration/remoteConfiguration.d.ts +13 -0
  522. package/lib/remote-configuration/remoteConfiguration.js +43 -0
  523. package/lib/remote-configuration/remoteConfiguration.js.map +1 -0
  524. package/lib/session/CameraKitSession.d.ts +252 -0
  525. package/lib/session/CameraKitSession.js +439 -0
  526. package/lib/session/CameraKitSession.js.map +1 -0
  527. package/lib/session/CameraKitSessionEvents.d.ts +33 -0
  528. package/lib/session/CameraKitSessionEvents.js +21 -0
  529. package/lib/session/CameraKitSessionEvents.js.map +1 -0
  530. package/lib/session/LensKeyboard.d.ts +89 -0
  531. package/lib/session/LensKeyboard.js +95 -0
  532. package/lib/session/LensKeyboard.js.map +1 -0
  533. package/lib/session/LensPerformanceMeasurement.d.ts +55 -0
  534. package/lib/session/LensPerformanceMeasurement.js +91 -0
  535. package/lib/session/LensPerformanceMeasurement.js.map +1 -0
  536. package/lib/session/LensPerformanceMetrics.d.ts +31 -0
  537. package/lib/session/LensPerformanceMetrics.js +58 -0
  538. package/lib/session/LensPerformanceMetrics.js.map +1 -0
  539. package/lib/session/index.d.ts +1 -0
  540. package/lib/session/index.js +2 -0
  541. package/lib/session/index.js.map +1 -0
  542. package/lib/session/lensState.d.ts +29 -0
  543. package/lib/session/lensState.js +160 -0
  544. package/lib/session/lensState.js.map +1 -0
  545. package/lib/session/sessionState.d.ts +10 -0
  546. package/lib/session/sessionState.js +12 -0
  547. package/lib/session/sessionState.js.map +1 -0
  548. package/lib/transforms/Transform2D.d.ts +17 -0
  549. package/lib/transforms/Transform2D.js +18 -0
  550. package/lib/transforms/Transform2D.js.map +1 -0
  551. package/lib/transforms/index.d.ts +1 -0
  552. package/lib/transforms/index.js +2 -0
  553. package/lib/transforms/index.js.map +1 -0
  554. package/package.json +62 -0
@@ -0,0 +1,239 @@
1
+ import { __awaiter, __decorate, __metadata, __param } from "tslib";
2
+ import { guard, validate } from "../common/validate";
3
+ import { isArrayOfType, isSafeString, isSafeStringArray, isString, isUndefined } from "../common/typeguards";
4
+ import { Injectable } from "../dependency-injection/Injectable";
5
+ import { cameraKitServiceFetchHandlerFactory } from "../handlers/cameraKitServiceFetchHandlerFactory";
6
+ import { defaultFetchHandlerFactory } from "../handlers/defaultFetchHandler";
7
+ import { lensSourcesFactory } from "../extensions/LensSources";
8
+ import { createRequestStateEmittingHandler } from "../handlers/requestStateEmittingHandler";
9
+ import { HandlerChainBuilder } from "../handlers/HandlerChainBuilder";
10
+ import { createArrayBufferParsingHandler } from "../handlers/arrayBufferParsingHandler";
11
+ import { LensAssetManifestItem_RequestTiming } from "../generated-proto/pb_schema/camera_kit/v3/lens";
12
+ import { getLogger } from "../logger/logger";
13
+ import { errorLoggingDecorator } from "../logger/errorLoggingDecorator";
14
+ import { isLensArray, toPublicLens } from "./Lens";
15
+ import { retrieveCameraKitLens, retrieveCameraKitLensGroup } from "./lensHttpUtil";
16
+ import { decodeEnvelopes } from "./lensEnvelopeUtil";
17
+ import { lensAssetRepositoryFactory } from "./assets/LensAssetRepository";
18
+ const logger = getLogger("LensRepository");
19
+ const log = errorLoggingDecorator(logger);
20
+ const assetTimingMap = {
21
+ required: LensAssetManifestItem_RequestTiming.REQUIRED,
22
+ onDemand: LensAssetManifestItem_RequestTiming.ON_DEMAND,
23
+ };
24
+ function isAssetTiming(value) {
25
+ return isString(value) && assetTimingMap.hasOwnProperty(value);
26
+ }
27
+ function isOptionalAssetTimingArray(value) {
28
+ return isUndefined(value) || isArrayOfType(isAssetTiming, value);
29
+ }
30
+ /**
31
+ * The LensRepository is used to query for lenses from specific lens groups, or for a lens with a specific ID.
32
+ *
33
+ * Lens groups are configured in the CameraKit Portal -- that's where you'll find lens group IDs and lens IDs.
34
+ *
35
+ * Lenses must be loaded by the LensRepository before they can be applied to a {@link CameraKitSession}.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * const cameraKit = await bootstrapCameraKit(options)
40
+ * const session = await cameraKit.createSession()
41
+ * const lens = await cameraKit.lensRepository.loadLens(lensId, groupId)
42
+ * session.applyLens(lens)
43
+ * ```
44
+ *
45
+ * @category Lenses
46
+ */
47
+ export class LensRepository {
48
+ /** @internal */
49
+ constructor(lensMetadataFetchHandler, lensFetchHandler, lensSources, lensAssetRepository) {
50
+ this.lensMetadataFetchHandler = lensMetadataFetchHandler;
51
+ this.lensFetchHandler = lensFetchHandler;
52
+ this.lensSources = lensSources;
53
+ this.lensAssetRepository = lensAssetRepository;
54
+ this.metadataCache = new Map();
55
+ this.binariesCache = new Map();
56
+ }
57
+ /**
58
+ * Retrieve a single Lens.
59
+ *
60
+ * @param lensId Desired Lens's unique ID. Can be found in the CameraKit Portal.
61
+ * @param groupId The ID of a group containing the desired Lens. Can be found in the CameraKit Portal.
62
+ * @returns Resolves with the desired Lens, or rejects if an error occurred (including a missing Lens).
63
+ */
64
+ loadLens(lensId, groupId) {
65
+ return __awaiter(this, void 0, void 0, function* () {
66
+ const envelopes = yield this.lensSources.retrieveLenses({ lensId, groupId });
67
+ let lens;
68
+ if (envelopes) {
69
+ lens = decodeEnvelopes(envelopes)[0];
70
+ if (!lens) {
71
+ throw new Error("Expected non-empty envelope");
72
+ }
73
+ }
74
+ else {
75
+ lens = yield retrieveCameraKitLens(this.lensMetadataFetchHandler, lensId, groupId);
76
+ }
77
+ this.metadataCache.set(lens.id, lens);
78
+ return toPublicLens(lens);
79
+ });
80
+ }
81
+ /**
82
+ * Retrieve the Lenses contained in a list of Lens Groups.
83
+ *
84
+ * This may result in multiple requests to retrieve Lens data (e.g. one per desired group). If any constituent
85
+ * requests fail, those errors will be reported in the response – but the returned Promise will not be rejected. Any
86
+ * Lenses which could be successfully retrieved will be available in the response.
87
+ *
88
+ * @param groupIds A list of Lens Group IDs. Can be found in the CameraKit Portal.
89
+ * @returns Resolves with a flattened list of all lenses in the desired groups. If any errors occurred during the
90
+ * query operation, these will be included in a separate list. If errors are present, the list of Lenses may not
91
+ * contain all the Lenses from the desired groups.
92
+ */
93
+ loadLensGroups(groupIds) {
94
+ return __awaiter(this, void 0, void 0, function* () {
95
+ const responses = yield Promise.all(groupIds.map((groupId) => __awaiter(this, void 0, void 0, function* () {
96
+ try {
97
+ const envelopes = yield this.lensSources.retrieveLenses({ groupId });
98
+ const lenses = envelopes
99
+ ? decodeEnvelopes(envelopes)
100
+ : yield retrieveCameraKitLensGroup(this.lensMetadataFetchHandler, groupId);
101
+ lenses.forEach((lens) => this.metadataCache.set(lens.id, lens));
102
+ return lenses.map(toPublicLens);
103
+ }
104
+ catch (error) {
105
+ logger.error(new Error(`Failed to load lens group ${groupId}`, { cause: error }));
106
+ return error;
107
+ }
108
+ })));
109
+ const errors = [];
110
+ const lenses = [];
111
+ responses.forEach((response) => (Array.isArray(response) ? lenses.push(...response) : errors.push(response)));
112
+ return { errors, lenses };
113
+ });
114
+ }
115
+ /**
116
+ * Loads and caches lens content and dependencies to reduce latency when {@link CameraKitSession.applyLens} is later
117
+ * called to apply the lens. This is an in-memory cache, it will not be persisted across page loads.
118
+ *
119
+ * This may useful if the application A) knows which lenses will be applied and B) has some opportunity to call
120
+ * this method before a lens is applied. For example, if the user must perform some other actions before lenses
121
+ * become active, this might be a good opportunity to cache lenses to improve applyLens latency.
122
+ *
123
+ * @example
124
+ * ```ts
125
+ * const lens = await cameraKit.lensRepository.loadLens(lensId, groupId)
126
+ * await cameraKit.lensRepository.cacheLensContent([lens])
127
+ *
128
+ * // sometime later -- this call will use the cached lens content, making lens application faster.
129
+ * await cameraKitSession.applyLens(lens)
130
+ * ```
131
+ *
132
+ * @param lenses Array of lenses to cache in memory.
133
+ * @param assetTimingsToCache Lenses specify certain required assets that are necessary for the lens to render, and
134
+ * other assets which may be needed by the lens. By default this method will cache all of those assets, but this
135
+ * behavior can be modified to only load the required assets, only the "onDemand" assets, or neither (by passing
136
+ * an empty array).
137
+ */
138
+ cacheLensContent(lenses, assetTimingsToCache = ["required", "onDemand"]) {
139
+ return __awaiter(this, void 0, void 0, function* () {
140
+ const assetTimingsToLoad = assetTimingsToCache.map((timing) => assetTimingMap[timing]);
141
+ yield Promise.all(lenses.map((lens) => __awaiter(this, void 0, void 0, function* () {
142
+ try {
143
+ const { lensBuffer } = yield this.getLensContent(lens);
144
+ // Safety: getLensContent() call above ensures metadata to exist
145
+ const { content } = this.metadataCache.get(lens.id);
146
+ this.binariesCache.set(lens.id, lensBuffer);
147
+ yield this.lensAssetRepository.cacheAssets(content.assetManifest, lens, assetTimingsToLoad);
148
+ }
149
+ catch (e) {
150
+ logger.warn(new Error(`Failed to cache lens ${lens.id}.`, { cause: e }));
151
+ }
152
+ })));
153
+ });
154
+ }
155
+ /**
156
+ * Returns loaded Lens metadata if available.
157
+ */
158
+ getLensMetadata(lensId) {
159
+ return this.metadataCache.get(lensId);
160
+ }
161
+ /**
162
+ * Removes Lens content from the in-memory cache.
163
+ */
164
+ removeCachedLenses(lenses) {
165
+ lenses.forEach((lens) => this.binariesCache.delete(lens.id));
166
+ }
167
+ /**
168
+ * Fetches lens content and assets. This may come from the cache, otherwise network requests will be made.
169
+ *
170
+ * @internal
171
+ */
172
+ getLensContent(lens) {
173
+ var _a;
174
+ return __awaiter(this, void 0, void 0, function* () {
175
+ const { content } = (_a = this.metadataCache.get(lens.id)) !== null && _a !== void 0 ? _a : {};
176
+ if (!content) {
177
+ throw new Error(`Cannot find metadata for lens ${lens.id}.`);
178
+ }
179
+ const cachedLensBuffer = this.binariesCache.get(lens.id);
180
+ if (cachedLensBuffer) {
181
+ return {
182
+ lensBuffer: cachedLensBuffer,
183
+ lensChecksum: content.lnsSha256,
184
+ };
185
+ }
186
+ // Load required lens assets and the lens itself in parallel. We count both toward lens download time.
187
+ const [lensBuffer] = yield this.lensFetchHandler([
188
+ // TODO: remove force-cache once https://jira.sc-corp.net/browse/CAMKIT-3671 is addressed
189
+ new Request(content.lnsUrlBolt, { cache: "force-cache" }),
190
+ {
191
+ requestType: "lens_content",
192
+ lensId: lens.id,
193
+ },
194
+ ]);
195
+ return { lensBuffer, lensChecksum: content.lnsSha256 };
196
+ });
197
+ }
198
+ }
199
+ __decorate([
200
+ validate,
201
+ log,
202
+ __param(0, guard(isSafeString)),
203
+ __param(1, guard(isSafeString)),
204
+ __metadata("design:type", Function),
205
+ __metadata("design:paramtypes", [String, String]),
206
+ __metadata("design:returntype", Promise)
207
+ ], LensRepository.prototype, "loadLens", null);
208
+ __decorate([
209
+ validate,
210
+ log,
211
+ __param(0, guard(isSafeStringArray)),
212
+ __metadata("design:type", Function),
213
+ __metadata("design:paramtypes", [Array]),
214
+ __metadata("design:returntype", Promise)
215
+ ], LensRepository.prototype, "loadLensGroups", null);
216
+ __decorate([
217
+ validate,
218
+ log,
219
+ __param(0, guard(isLensArray)),
220
+ __param(1, guard(isOptionalAssetTimingArray)),
221
+ __metadata("design:type", Function),
222
+ __metadata("design:paramtypes", [Array, Array]),
223
+ __metadata("design:returntype", Promise)
224
+ ], LensRepository.prototype, "cacheLensContent", null);
225
+ /**
226
+ * @internal
227
+ */
228
+ export const lensRepositoryFactory = Injectable("LensRepository", [
229
+ cameraKitServiceFetchHandlerFactory.token,
230
+ defaultFetchHandlerFactory.token,
231
+ lensSourcesFactory.token,
232
+ lensAssetRepositoryFactory.token,
233
+ ], (lensMetadataFetchHandler, defaultFetchHandler, lensSources, lensAssetRepository) => {
234
+ const lensFetchHandler = new HandlerChainBuilder(defaultFetchHandler)
235
+ .map(createRequestStateEmittingHandler())
236
+ .map(createArrayBufferParsingHandler()).handler;
237
+ return new LensRepository(lensMetadataFetchHandler, lensFetchHandler, lensSources, lensAssetRepository);
238
+ });
239
+ //# sourceMappingURL=LensRepository.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LensRepository.js","sourceRoot":"","sources":["../../src/lens/LensRepository.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,iBAAiB,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC7G,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAChE,OAAO,EAAE,mCAAmC,EAAE,MAAM,iDAAiD,CAAC;AACtG,OAAO,EAAE,0BAA0B,EAAgB,MAAM,iCAAiC,CAAC;AAC3F,OAAO,EAAe,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC5E,OAAO,EAAE,iCAAiC,EAAE,MAAM,yCAAyC,CAAC;AAE5F,OAAO,EAAW,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AAC/E,OAAO,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAC;AACxF,OAAO,EAAE,mCAAmC,EAAE,MAAM,iDAAiD,CAAC;AACtG,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AACxE,OAAO,EAAE,WAAW,EAAmB,YAAY,EAAE,MAAM,QAAQ,CAAC;AACpE,OAAO,EAAE,qBAAqB,EAAE,0BAA0B,EAAE,MAAM,gBAAgB,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CA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G;IACY,WAAA,KAAK,CAAC,YAAY,CAAC,CAAA;IAAkB,WAAA,KAAK,CAAC,YAAY,CAAC,CAAA;;;;8CAavE;AAgBK;IAFL,QAAQ;IACR,GAAG;IACkB,WAAA,KAAK,CAAC,iBAAiB,CAAC,CAAA;;;;oDAqB7C;AA2BK;IAFL,QAAQ;IACR,GAAG;IAEC,WAAA,KAAK,CAAC,WAAW,CAAC,CAAA;IAClB,WAAA,KAAK,CAAC,0BAA0B,CAAC,CAAA;;;;sDAgBrC;AAgDL;;GAEG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,UAAU,CAC3C,gBAAgB,EAChB;IACI,mCAAmC,CAAC,KAAK;IACzC,0BAA0B,CAAC,KAAK;IAChC,kBAAkB,CAAC,KAAK;IACxB,0BAA0B,CAAC,KAAK;CAC1B,EACV,CACI,wBAAsC,EACtC,mBAAiC,EACjC,WAAwB,EACxB,mBAAwC,EAC1C,EAAE;IACA,MAAM,gBAAgB,GAAG,IAAI,mBAAmB,CAAC,mBAAmB,CAAC;SAChE,GAAG,CAAC,iCAAiC,EAA0B,CAAC;SAChE,GAAG,CAAC,+BAA+B,EAAE,CAAC,CAAC,OAAO,CAAC;IACpD,OAAO,IAAI,cAAc,CAAC,wBAAwB,EAAE,gBAAgB,EAAE,WAAW,EAAE,mBAAmB,CAAC,CAAC;AAC5G,CAAC,CACJ,CAAC","sourcesContent":["import { guard, validate } from \"../common/validate\";\nimport { isArrayOfType, isSafeString, isSafeStringArray, isString, isUndefined } from \"../common/typeguards\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\nimport { cameraKitServiceFetchHandlerFactory } from \"../handlers/cameraKitServiceFetchHandlerFactory\";\nimport { defaultFetchHandlerFactory, FetchHandler } from \"../handlers/defaultFetchHandler\";\nimport { LensSources, lensSourcesFactory } from \"../extensions/LensSources\";\nimport { createRequestStateEmittingHandler } from \"../handlers/requestStateEmittingHandler\";\nimport { LensDownloadDimensions } from \"../metrics/reporters/reportLensAndAssetDownload\";\nimport { Handler, HandlerChainBuilder } from \"../handlers/HandlerChainBuilder\";\nimport { createArrayBufferParsingHandler } from \"../handlers/arrayBufferParsingHandler\";\nimport { LensAssetManifestItem_RequestTiming } from \"../generated-proto/pb_schema/camera_kit/v3/lens\";\nimport { getLogger } from \"../logger/logger\";\nimport { errorLoggingDecorator } from \"../logger/errorLoggingDecorator\";\nimport { isLensArray, Lens, LensProto, toPublicLens } from \"./Lens\";\nimport { retrieveCameraKitLens, retrieveCameraKitLensGroup } from \"./lensHttpUtil\";\nimport { decodeEnvelopes } from \"./lensEnvelopeUtil\";\nimport { LensAssetRepository, lensAssetRepositoryFactory } from \"./assets/LensAssetRepository\";\n\nconst logger = getLogger(\"LensRepository\");\nconst log = errorLoggingDecorator(logger);\n\ntype LensFetchHandler = Handler<\n [RequestInfo, LensDownloadDimensions],\n [ArrayBuffer, Response],\n RequestInit | undefined\n>;\n\nconst assetTimingMap = {\n required: LensAssetManifestItem_RequestTiming.REQUIRED,\n onDemand: LensAssetManifestItem_RequestTiming.ON_DEMAND,\n};\n\nfunction isAssetTiming(value: unknown): value is AssetTiming {\n return isString(value) && assetTimingMap.hasOwnProperty(value);\n}\n\nfunction isOptionalAssetTimingArray(value: unknown): value is undefined | AssetTiming[] {\n return isUndefined(value) || isArrayOfType(isAssetTiming, value);\n}\n\n/**\n * Lens assets are included in a manifest, and each will indicate when that asset will be used by the lens.\n *\n * Assets can have the following timing values:\n * - `required`: the lens will definitely request this asset immediately when the lens is applied.\n * - `onDemand`: the lens may request this asset at some time while the lens is applied.\n *\n * Depending on the use-case, an application may want to cache both required and onDemand assets for\n * a particular lens, or may decide to only cache required assets (or cache no assets).\n *\n * @category Lenses\n */\nexport type AssetTiming = keyof typeof assetTimingMap;\n\nexport interface LensGroupsQueryResponse {\n errors: Error[];\n lenses: Lens[];\n}\n\nexport interface LensBinary {\n lensBuffer: ArrayBuffer;\n lensChecksum: string;\n}\n\n/**\n * The LensRepository is used to query for lenses from specific lens groups, or for a lens with a specific ID.\n *\n * Lens groups are configured in the CameraKit Portal -- that's where you'll find lens group IDs and lens IDs.\n *\n * Lenses must be loaded by the LensRepository before they can be applied to a {@link CameraKitSession}.\n *\n * @example\n * ```ts\n * const cameraKit = await bootstrapCameraKit(options)\n * const session = await cameraKit.createSession()\n * const lens = await cameraKit.lensRepository.loadLens(lensId, groupId)\n * session.applyLens(lens)\n * ```\n *\n * @category Lenses\n */\nexport class LensRepository {\n private readonly metadataCache = new Map<string, LensProto>();\n private readonly binariesCache = new Map<string, ArrayBuffer>();\n\n /** @internal */\n constructor(\n private readonly lensMetadataFetchHandler: FetchHandler,\n private readonly lensFetchHandler: LensFetchHandler,\n private readonly lensSources: LensSources,\n private readonly lensAssetRepository: LensAssetRepository\n ) {}\n\n /**\n * Retrieve a single Lens.\n *\n * @param lensId Desired Lens's unique ID. Can be found in the CameraKit Portal.\n * @param groupId The ID of a group containing the desired Lens. Can be found in the CameraKit Portal.\n * @returns Resolves with the desired Lens, or rejects if an error occurred (including a missing Lens).\n */\n @validate\n @log\n async loadLens(@guard(isSafeString) lensId: string, @guard(isSafeString) groupId: string): Promise<Lens> {\n const envelopes = await this.lensSources.retrieveLenses({ lensId, groupId });\n let lens: LensProto;\n if (envelopes) {\n lens = decodeEnvelopes(envelopes)[0];\n if (!lens) {\n throw new Error(\"Expected non-empty envelope\");\n }\n } else {\n lens = await retrieveCameraKitLens(this.lensMetadataFetchHandler, lensId, groupId);\n }\n this.metadataCache.set(lens.id, lens);\n return toPublicLens(lens);\n }\n\n /**\n * Retrieve the Lenses contained in a list of Lens Groups.\n *\n * This may result in multiple requests to retrieve Lens data (e.g. one per desired group). If any constituent\n * requests fail, those errors will be reported in the response – but the returned Promise will not be rejected. Any\n * Lenses which could be successfully retrieved will be available in the response.\n *\n * @param groupIds A list of Lens Group IDs. Can be found in the CameraKit Portal.\n * @returns Resolves with a flattened list of all lenses in the desired groups. If any errors occurred during the\n * query operation, these will be included in a separate list. If errors are present, the list of Lenses may not\n * contain all the Lenses from the desired groups.\n */\n @validate\n @log\n async loadLensGroups(@guard(isSafeStringArray) groupIds: string[]): Promise<LensGroupsQueryResponse> {\n const responses = await Promise.all(\n groupIds.map(async (groupId) => {\n try {\n const envelopes = await this.lensSources.retrieveLenses({ groupId });\n const lenses = envelopes\n ? decodeEnvelopes(envelopes)\n : await retrieveCameraKitLensGroup(this.lensMetadataFetchHandler, groupId);\n lenses.forEach((lens) => this.metadataCache.set(lens.id, lens));\n return lenses.map(toPublicLens);\n } catch (error) {\n logger.error(new Error(`Failed to load lens group ${groupId}`, { cause: error }));\n return error as Error;\n }\n })\n );\n\n const errors: Error[] = [];\n const lenses: Lens[] = [];\n responses.forEach((response) => (Array.isArray(response) ? lenses.push(...response) : errors.push(response)));\n return { errors, lenses };\n }\n\n /**\n * Loads and caches lens content and dependencies to reduce latency when {@link CameraKitSession.applyLens} is later\n * called to apply the lens. This is an in-memory cache, it will not be persisted across page loads.\n *\n * This may useful if the application A) knows which lenses will be applied and B) has some opportunity to call\n * this method before a lens is applied. For example, if the user must perform some other actions before lenses\n * become active, this might be a good opportunity to cache lenses to improve applyLens latency.\n *\n * @example\n * ```ts\n * const lens = await cameraKit.lensRepository.loadLens(lensId, groupId)\n * await cameraKit.lensRepository.cacheLensContent([lens])\n *\n * // sometime later -- this call will use the cached lens content, making lens application faster.\n * await cameraKitSession.applyLens(lens)\n * ```\n *\n * @param lenses Array of lenses to cache in memory.\n * @param assetTimingsToCache Lenses specify certain required assets that are necessary for the lens to render, and\n * other assets which may be needed by the lens. By default this method will cache all of those assets, but this\n * behavior can be modified to only load the required assets, only the \"onDemand\" assets, or neither (by passing\n * an empty array).\n */\n @validate\n @log\n async cacheLensContent(\n @guard(isLensArray) lenses: Lens[],\n @guard(isOptionalAssetTimingArray) assetTimingsToCache: AssetTiming[] = [\"required\", \"onDemand\"]\n ) {\n const assetTimingsToLoad = assetTimingsToCache.map((timing) => assetTimingMap[timing]);\n await Promise.all(\n lenses.map(async (lens) => {\n try {\n const { lensBuffer } = await this.getLensContent(lens);\n // Safety: getLensContent() call above ensures metadata to exist\n const { content } = this.metadataCache.get(lens.id)!;\n this.binariesCache.set(lens.id, lensBuffer);\n await this.lensAssetRepository.cacheAssets(content!.assetManifest, lens, assetTimingsToLoad);\n } catch (e) {\n logger.warn(new Error(`Failed to cache lens ${lens.id}.`, { cause: e }));\n }\n })\n );\n }\n\n /**\n * Returns loaded Lens metadata if available.\n */\n getLensMetadata(lensId: string): LensProto | undefined {\n return this.metadataCache.get(lensId);\n }\n\n /**\n * Removes Lens content from the in-memory cache.\n */\n removeCachedLenses(lenses: Lens[]) {\n lenses.forEach((lens) => this.binariesCache.delete(lens.id));\n }\n\n /**\n * Fetches lens content and assets. This may come from the cache, otherwise network requests will be made.\n *\n * @internal\n */\n async getLensContent(lens: Lens): Promise<LensBinary> {\n const { content } = this.metadataCache.get(lens.id) ?? {};\n if (!content) {\n throw new Error(`Cannot find metadata for lens ${lens.id}.`);\n }\n\n const cachedLensBuffer = this.binariesCache.get(lens.id);\n if (cachedLensBuffer) {\n return {\n lensBuffer: cachedLensBuffer,\n lensChecksum: content.lnsSha256,\n };\n }\n\n // Load required lens assets and the lens itself in parallel. We count both toward lens download time.\n const [lensBuffer] = await this.lensFetchHandler([\n // TODO: remove force-cache once https://jira.sc-corp.net/browse/CAMKIT-3671 is addressed\n new Request(content.lnsUrlBolt, { cache: \"force-cache\" }),\n {\n requestType: \"lens_content\",\n lensId: lens.id,\n },\n ]);\n return { lensBuffer, lensChecksum: content.lnsSha256 };\n }\n}\n\n/**\n * @internal\n */\nexport const lensRepositoryFactory = Injectable(\n \"LensRepository\",\n [\n cameraKitServiceFetchHandlerFactory.token,\n defaultFetchHandlerFactory.token,\n lensSourcesFactory.token,\n lensAssetRepositoryFactory.token,\n ] as const,\n (\n lensMetadataFetchHandler: FetchHandler,\n defaultFetchHandler: FetchHandler,\n lensSources: LensSources,\n lensAssetRepository: LensAssetRepository\n ) => {\n const lensFetchHandler = new HandlerChainBuilder(defaultFetchHandler)\n .map(createRequestStateEmittingHandler<LensDownloadDimensions>())\n .map(createArrayBufferParsingHandler()).handler;\n return new LensRepository(lensMetadataFetchHandler, lensFetchHandler, lensSources, lensAssetRepository);\n }\n);\n"]}
@@ -0,0 +1,66 @@
1
+ import { Lens } from "../Lens";
2
+ import { LensAssetManifestItem, LensAssetManifestItem_RequestTiming, LensAssetManifestItem_Type } from "../../generated-proto/pb_schema/camera_kit/v3/lens";
3
+ import { AssetDescriptor, AssetType, LensCoreModule } from "../../lens-core-module";
4
+ import { MetricsEventTarget } from "../../metrics/metricsEventTarget";
5
+ export declare function mapManfiestItemToAssetType(lensCore: LensCoreModule, type: LensAssetManifestItem_Type): AssetType;
6
+ export interface Asset {
7
+ assetId: string;
8
+ assetBuffer: ArrayBuffer;
9
+ assetType: AssetType;
10
+ assetChecksum: string | undefined;
11
+ }
12
+ export declare type AssetResponse = ArrayBuffer | {
13
+ data: ArrayBuffer;
14
+ checksum?: string;
15
+ };
16
+ /**
17
+ * An AssetLoader is used to retrieve assets. A separate loader may be defined to retrieve different asset types.
18
+ *
19
+ * @category Lenses
20
+ */
21
+ export declare type AssetLoader = (asset: AssetDescriptor, lens?: Lens, assetManifest?: LensAssetManifestItem[]) => Promise<AssetResponse> | AssetResponse;
22
+ /**
23
+ * Registers a remote asset provider function with a given instance of LensCore, and uses a provided mapping of asset
24
+ * types to loading functions to acquire remote asset data and pass it to LensCore.
25
+ *
26
+ * *Note:* LensCoreModule.initialize must be called on the desired LensCoreModule instance **prior** to passing it
27
+ * to the LensAssetProvider constructor. If this class is instantiated with a LensCoreModule that has not been
28
+ * initialized, the registry of the asset provider function will fail silently and no remote assets will be loaded.
29
+ */
30
+ export declare class LensAssetRepository {
31
+ private readonly lensCore;
32
+ private readonly assetLoaders;
33
+ private readonly metrics;
34
+ private readonly cachedAssetKeys;
35
+ constructor(lensCore: LensCoreModule, assetLoaders: Map<AssetType, [keyof LensCoreModule["AssetType"], AssetLoader]>, metrics: MetricsEventTarget);
36
+ /**
37
+ * Caches lens assets defined in asset manifest.
38
+ *
39
+ * @param assetManifest Lens asset manifest.
40
+ * @param lens Lens to cache assets of.
41
+ * @param assetTimings Optionally specifies what assets to cache. By default, on-demand assets are not cached.
42
+ * @returns Promise rejects if any required assets could not be loaded – if this occurs, it's very likely the Lens
43
+ * with this manifest will not function.
44
+ */
45
+ cacheAssets(assetManifest: LensAssetManifestItem[], lens: Lens, assetTimings?: LensAssetManifestItem_RequestTiming[]): Promise<void>;
46
+ /**
47
+ * Calls the correct asset loader to fetch the asset's data,
48
+ * depending on the requested asset's type and provides that to LensCore.
49
+ */
50
+ loadAsset(assetDescriptor: AssetDescriptor, lens: Lens | undefined, assetManifest: LensAssetManifestItem[] | undefined): Promise<void>;
51
+ /**
52
+ * Downloads and caches assets if applicable. Does nothing for assets that are already in cache.
53
+ * @param assetDescriptors Asset ID and type pairs.
54
+ * @param lens Lens to load assets for.
55
+ * @param assetManifest Lens asset manifest.
56
+ */
57
+ private cacheAssetsByDescriptor;
58
+ }
59
+ /**
60
+ * @internal
61
+ */
62
+ export declare const lensAssetRepositoryFactory: {
63
+ (args_0: LensCoreModule, args_1: AssetLoader, args_2: AssetLoader, args_3: AssetLoader, args_4: MetricsEventTarget): LensAssetRepository;
64
+ token: "lensAssetRepository";
65
+ dependencies: readonly ["lensCore", "deviceDependentAssetLoader", "remoteMediaAssetLoader", "staticAssetLoader", "metricsEventTarget"];
66
+ };
@@ -0,0 +1,179 @@
1
+ import { __awaiter } from "tslib";
2
+ import { ensureError } from "../../common/errorHelpers";
3
+ import { Injectable } from "../../dependency-injection/Injectable";
4
+ import { dispatchRequestCompleted, dispatchRequestErrored, dispatchRequestStarted, } from "../../handlers/requestStateEmittingHandler";
5
+ import { LensAssetManifestItem_RequestTiming, LensAssetManifestItem_Type, } from "../../generated-proto/pb_schema/camera_kit/v3/lens";
6
+ import { lensCoreFactory } from "../../lens-core-module";
7
+ import { assertUnreachable } from "../../common/assertions";
8
+ import { getLogger } from "../../logger/logger";
9
+ import { metricsEventTargetFactory } from "../../metrics/metricsEventTarget";
10
+ import { TypedCustomEvent } from "../../events/TypedCustomEvent";
11
+ import { deviceDependentAssetLoaderFactory } from "./deviceDependentAssetLoader";
12
+ import { remoteMediaAssetLoaderFactory } from "./remoteMediaAssetLoaderFactory";
13
+ import { staticAssetLoaderFactory } from "./staticAssetLoader";
14
+ const logger = getLogger("LensAssetRepository");
15
+ /**
16
+ * Computes cache key for asset ID and loader type pair.
17
+ * @param asset Asset ID and loader type pair.
18
+ * @returns Cache key.
19
+ */
20
+ function getCacheKey(asset) {
21
+ return `${asset.assetId}_${asset.assetType.value}`;
22
+ }
23
+ export function mapManfiestItemToAssetType(lensCore, type) {
24
+ switch (type) {
25
+ case LensAssetManifestItem_Type.ASSET:
26
+ return lensCore.AssetType.Static;
27
+ case LensAssetManifestItem_Type.DEVICE_DEPENDENT_ASSET_UNSET:
28
+ case LensAssetManifestItem_Type.UNRECOGNIZED:
29
+ return lensCore.AssetType.DeviceDependent;
30
+ default:
31
+ return assertUnreachable(type);
32
+ }
33
+ }
34
+ /**
35
+ * Registers a remote asset provider function with a given instance of LensCore, and uses a provided mapping of asset
36
+ * types to loading functions to acquire remote asset data and pass it to LensCore.
37
+ *
38
+ * *Note:* LensCoreModule.initialize must be called on the desired LensCoreModule instance **prior** to passing it
39
+ * to the LensAssetProvider constructor. If this class is instantiated with a LensCoreModule that has not been
40
+ * initialized, the registry of the asset provider function will fail silently and no remote assets will be loaded.
41
+ */
42
+ export class LensAssetRepository {
43
+ constructor(lensCore, assetLoaders, metrics) {
44
+ this.lensCore = lensCore;
45
+ this.assetLoaders = assetLoaders;
46
+ this.metrics = metrics;
47
+ this.cachedAssetKeys = new Set();
48
+ }
49
+ /**
50
+ * Caches lens assets defined in asset manifest.
51
+ *
52
+ * @param assetManifest Lens asset manifest.
53
+ * @param lens Lens to cache assets of.
54
+ * @param assetTimings Optionally specifies what assets to cache. By default, on-demand assets are not cached.
55
+ * @returns Promise rejects if any required assets could not be loaded – if this occurs, it's very likely the Lens
56
+ * with this manifest will not function.
57
+ */
58
+ cacheAssets(assetManifest, lens, assetTimings = [LensAssetManifestItem_RequestTiming.REQUIRED]) {
59
+ return __awaiter(this, void 0, void 0, function* () {
60
+ const assetTimingsToPreload = new Set([
61
+ // That is a bad naming, but PRELOAD_UNSET actually means
62
+ // that an asset has to be preloaded
63
+ LensAssetManifestItem_RequestTiming.PRELOAD_UNSET,
64
+ ...assetTimings,
65
+ ]);
66
+ const assetDescriptors = assetManifest
67
+ .filter((asset) => {
68
+ return assetTimingsToPreload.has(asset.requestTiming);
69
+ })
70
+ .map(({ id, type }) => ({
71
+ assetId: id,
72
+ assetType: mapManfiestItemToAssetType(this.lensCore, type),
73
+ }));
74
+ if (assetDescriptors.length) {
75
+ // When preloading, we *do* want load failures to reject Promise.all (assets listed in the manifest
76
+ // are known to be hard requirements of the lens).
77
+ return this.cacheAssetsByDescriptor(assetDescriptors, lens, assetManifest);
78
+ }
79
+ });
80
+ }
81
+ /**
82
+ * Calls the correct asset loader to fetch the asset's data,
83
+ * depending on the requested asset's type and provides that to LensCore.
84
+ */
85
+ loadAsset(assetDescriptor, lens, assetManifest) {
86
+ var _a, _b;
87
+ return __awaiter(this, void 0, void 0, function* () {
88
+ const { assetId, assetType } = assetDescriptor;
89
+ const [assetTypeName, assetLoader] = (_a = this.assetLoaders.get(assetType)) !== null && _a !== void 0 ? _a : [];
90
+ const safeAssetTypeName = assetTypeName !== null && assetTypeName !== void 0 ? assetTypeName : "unknown";
91
+ const dimensions = {
92
+ requestType: "asset",
93
+ assetId: assetId,
94
+ assetType: safeAssetTypeName,
95
+ lensId: (_b = lens === null || lens === void 0 ? void 0 : lens.id) !== null && _b !== void 0 ? _b : "unknown",
96
+ };
97
+ const { requestId } = dispatchRequestStarted({ dimensions });
98
+ try {
99
+ if (!assetLoader) {
100
+ throw new Error(`Cannot get asset "${assetId}". Asset type "${safeAssetTypeName}" is not supported.`);
101
+ }
102
+ const assetResponse = yield assetLoader(assetDescriptor, lens, assetManifest);
103
+ const assetBuffer = "data" in assetResponse ? assetResponse.data : assetResponse;
104
+ const assetChecksum = "checksum" in assetResponse ? assetResponse.checksum : undefined;
105
+ if (assetBuffer.byteLength === 0) {
106
+ throw new Error(`Got empty response for asset "${assetId}" from "${safeAssetTypeName}" loader.`);
107
+ }
108
+ dispatchRequestCompleted({ requestId, dimensions, status: 200, sizeByte: assetBuffer.byteLength });
109
+ this.lensCore.provideRemoteAssetsResponse({
110
+ assetId,
111
+ assetBuffer,
112
+ assetType,
113
+ assetChecksum,
114
+ onFailure: (reason) => {
115
+ const lensCoreError = ensureError(reason);
116
+ if (/validation failed/.test(lensCoreError.message)) {
117
+ this.metrics.dispatchEvent(new TypedCustomEvent("assetValidationFailed", {
118
+ name: "assetValidationFailed",
119
+ assetId,
120
+ }));
121
+ }
122
+ logger.warn(new Error(`Failed to provide lens asset "${assetId}".`, { cause: lensCoreError }));
123
+ },
124
+ });
125
+ }
126
+ catch (error) {
127
+ const wrappedError = new Error(`Failed to load lens asset "${assetId}".`, { cause: error });
128
+ dispatchRequestErrored({ requestId, dimensions, error: wrappedError });
129
+ throw wrappedError;
130
+ }
131
+ });
132
+ }
133
+ /**
134
+ * Downloads and caches assets if applicable. Does nothing for assets that are already in cache.
135
+ * @param assetDescriptors Asset ID and type pairs.
136
+ * @param lens Lens to load assets for.
137
+ * @param assetManifest Lens asset manifest.
138
+ */
139
+ cacheAssetsByDescriptor(assetDescriptors, lens, assetManifest) {
140
+ return __awaiter(this, void 0, void 0, function* () {
141
+ yield Promise.all(assetDescriptors
142
+ .filter((assetDescriptors) => !this.cachedAssetKeys.has(getCacheKey(assetDescriptors)))
143
+ .map((assetDescriptor) => __awaiter(this, void 0, void 0, function* () {
144
+ var _a;
145
+ try {
146
+ // NOTE: we allow concurrent cache request to download the same asset more than once,
147
+ // because that is better than skipping second request when the firs one fails.
148
+ // In future we could improve concurretn logic with observables as part of
149
+ // https://jira.sc-corp.net/browse/CAMKIT-3931
150
+ yield this.loadAsset(assetDescriptor, lens, assetManifest);
151
+ this.cachedAssetKeys.add(getCacheKey(assetDescriptor));
152
+ }
153
+ catch (error) {
154
+ const { assetId, assetType } = assetDescriptor;
155
+ const [assetTypeName] = (_a = this.assetLoaders.get(assetType)) !== null && _a !== void 0 ? _a : [];
156
+ logger.warn(new Error(`Failed to cache asset "${assetId}" of type "${assetTypeName !== null && assetTypeName !== void 0 ? assetTypeName : assetType.value}".`, { cause: error }));
157
+ }
158
+ })));
159
+ });
160
+ }
161
+ }
162
+ /**
163
+ * @internal
164
+ */
165
+ export const lensAssetRepositoryFactory = Injectable("lensAssetRepository", [
166
+ lensCoreFactory.token,
167
+ deviceDependentAssetLoaderFactory.token,
168
+ remoteMediaAssetLoaderFactory.token,
169
+ staticAssetLoaderFactory.token,
170
+ metricsEventTargetFactory.token,
171
+ ], (lensCore, deviceDependentAssetLoader, remoteMediaAssetLoader, staticAssetLoader, metrics) => new LensAssetRepository(lensCore, new Map([
172
+ [lensCore.AssetType.DeviceDependent, ["DeviceDependent", deviceDependentAssetLoader]],
173
+ [lensCore.AssetType.RemoteMediaByUrl, ["RemoteMediaByUrl", remoteMediaAssetLoader]],
174
+ // URL type is deprecated and was introduced before RemoteMediaByURL
175
+ // however, there are some lenses still using it so we need to support it
176
+ [lensCore.AssetType.URL, ["URL", remoteMediaAssetLoader]],
177
+ [lensCore.AssetType.Static, ["Static", staticAssetLoader]],
178
+ ]), metrics));
179
+ //# sourceMappingURL=LensAssetRepository.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LensAssetRepository.js","sourceRoot":"","sources":["../../../src/lens/assets/LensAssetRepository.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,uCAAuC,CAAC;AAEnE,OAAO,EACH,wBAAwB,EACxB,sBAAsB,EACtB,sBAAsB,GACzB,MA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,CAAC,GAAG,CAAC,SAAS,CAAC,mCAAI,EAAE,CAAC;oBAC/D,MAAM,CAAC,IAAI,CACP,IAAI,KAAK,CACL,0BAA0B,OAAO,cAAc,aAAa,aAAb,aAAa,cAAb,aAAa,GAAI,SAAS,CAAC,KAAK,IAAI,EACnF,EAAE,KAAK,EAAE,KAAK,EAAE,CACnB,CACJ,CAAC;iBACL;YACL,CAAC,CAAA,CAAC,CACT,CAAC;QACN,CAAC;KAAA;CACJ;AAED;;GAEG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,UAAU,CAChD,qBAAqB,EACrB;IACI,eAAe,CAAC,KAAK;IACrB,iCAAiC,CAAC,KAAK;IACvC,6BAA6B,CAAC,KAAK;IACnC,wBAAwB,CAAC,KAAK;IAC9B,yBAAyB,CAAC,KAAK;CACzB,EACV,CACI,QAAwB,EACxB,0BAAuC,EACvC,sBAAmC,EACnC,iBAA8B,EAC9B,OAA2B,EAC7B,EAAE,CACA,IAAI,mBAAmB,CACnB,QAAQ,EACR,IAAI,GAAG,CAAC;IACJ,CAAC,QAAQ,CAAC,SAAS,CAAC,eAAe,EAAE,CAAC,iBAAiB,EAAE,0BAA0B,CAAC,CAAC;IACrF,CAAC,QAAQ,CAAC,SAAS,CAAC,gBAAgB,EAAE,CAAC,kBAAkB,EAAE,sBAAsB,CAAC,CAAC;IACnF,oEAAoE;IACpE,yEAAyE;IACzE,CAAC,QAAQ,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC,KAAK,EAAE,sBAAsB,CAAC,CAAC;IACzD,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,iBAAiB,CAAC,CAAC;CAC7D,CAAC,EACF,OAAO,CACV,CACR,CAAC","sourcesContent":["import { ensureError } from \"../../common/errorHelpers\";\nimport { Injectable } from \"../../dependency-injection/Injectable\";\nimport { Lens } from \"../Lens\";\nimport {\n dispatchRequestCompleted,\n dispatchRequestErrored,\n dispatchRequestStarted,\n} from \"../../handlers/requestStateEmittingHandler\";\nimport { AssetDownloadDimensions } from \"../../metrics/reporters/reportLensAndAssetDownload\";\nimport {\n LensAssetManifestItem,\n LensAssetManifestItem_RequestTiming,\n LensAssetManifestItem_Type,\n} from \"../../generated-proto/pb_schema/camera_kit/v3/lens\";\nimport { AssetDescriptor, AssetType, lensCoreFactory, LensCoreModule } from \"../../lens-core-module\";\nimport { assertUnreachable } from \"../../common/assertions\";\nimport { getLogger } from \"../../logger/logger\";\nimport { MetricsEventTarget, metricsEventTargetFactory } from \"../../metrics/metricsEventTarget\";\nimport { TypedCustomEvent } from \"../../events/TypedCustomEvent\";\nimport { deviceDependentAssetLoaderFactory } from \"./deviceDependentAssetLoader\";\nimport { remoteMediaAssetLoaderFactory } from \"./remoteMediaAssetLoaderFactory\";\nimport { staticAssetLoaderFactory } from \"./staticAssetLoader\";\n\nconst logger = getLogger(\"LensAssetRepository\");\n\n/**\n * Computes cache key for asset ID and loader type pair.\n * @param asset Asset ID and loader type pair.\n * @returns Cache key.\n */\nfunction getCacheKey(asset: AssetDescriptor) {\n return `${asset.assetId}_${asset.assetType.value}`;\n}\n\nexport function mapManfiestItemToAssetType(lensCore: LensCoreModule, type: LensAssetManifestItem_Type): AssetType {\n switch (type) {\n case LensAssetManifestItem_Type.ASSET:\n return lensCore.AssetType.Static;\n case LensAssetManifestItem_Type.DEVICE_DEPENDENT_ASSET_UNSET:\n case LensAssetManifestItem_Type.UNRECOGNIZED:\n return lensCore.AssetType.DeviceDependent;\n default:\n return assertUnreachable(type);\n }\n}\n\nexport interface Asset {\n assetId: string;\n assetBuffer: ArrayBuffer;\n assetType: AssetType;\n assetChecksum: string | undefined;\n}\n\nexport type AssetResponse =\n | ArrayBuffer\n | {\n data: ArrayBuffer;\n checksum?: string;\n };\n\n/**\n * An AssetLoader is used to retrieve assets. A separate loader may be defined to retrieve different asset types.\n *\n * @category Lenses\n */\nexport type AssetLoader = (\n asset: AssetDescriptor,\n lens?: Lens,\n assetManifest?: LensAssetManifestItem[]\n) => Promise<AssetResponse> | AssetResponse;\n\n/**\n * Registers a remote asset provider function with a given instance of LensCore, and uses a provided mapping of asset\n * types to loading functions to acquire remote asset data and pass it to LensCore.\n *\n * *Note:* LensCoreModule.initialize must be called on the desired LensCoreModule instance **prior** to passing it\n * to the LensAssetProvider constructor. If this class is instantiated with a LensCoreModule that has not been\n * initialized, the registry of the asset provider function will fail silently and no remote assets will be loaded.\n */\nexport class LensAssetRepository {\n private readonly cachedAssetKeys = new Set<string>();\n\n constructor(\n private readonly lensCore: LensCoreModule,\n private readonly assetLoaders: Map<AssetType, [keyof LensCoreModule[\"AssetType\"], AssetLoader]>,\n private readonly metrics: MetricsEventTarget\n ) {}\n\n /**\n * Caches lens assets defined in asset manifest.\n *\n * @param assetManifest Lens asset manifest.\n * @param lens Lens to cache assets of.\n * @param assetTimings Optionally specifies what assets to cache. By default, on-demand assets are not cached.\n * @returns Promise rejects if any required assets could not be loaded – if this occurs, it's very likely the Lens\n * with this manifest will not function.\n */\n public async cacheAssets(\n assetManifest: LensAssetManifestItem[],\n lens: Lens,\n assetTimings: LensAssetManifestItem_RequestTiming[] = [LensAssetManifestItem_RequestTiming.REQUIRED]\n ): Promise<void> {\n const assetTimingsToPreload = new Set([\n // That is a bad naming, but PRELOAD_UNSET actually means\n // that an asset has to be preloaded\n LensAssetManifestItem_RequestTiming.PRELOAD_UNSET,\n ...assetTimings,\n ]);\n const assetDescriptors = assetManifest\n .filter((asset) => {\n return assetTimingsToPreload.has(asset.requestTiming);\n })\n .map(({ id, type }) => ({\n assetId: id,\n assetType: mapManfiestItemToAssetType(this.lensCore, type),\n }));\n\n if (assetDescriptors.length) {\n // When preloading, we *do* want load failures to reject Promise.all (assets listed in the manifest\n // are known to be hard requirements of the lens).\n return this.cacheAssetsByDescriptor(assetDescriptors, lens, assetManifest);\n }\n }\n\n /**\n * Calls the correct asset loader to fetch the asset's data,\n * depending on the requested asset's type and provides that to LensCore.\n */\n public async loadAsset(\n assetDescriptor: AssetDescriptor,\n lens: Lens | undefined,\n assetManifest: LensAssetManifestItem[] | undefined\n ): Promise<void> {\n const { assetId, assetType } = assetDescriptor;\n const [assetTypeName, assetLoader] = this.assetLoaders.get(assetType) ?? [];\n const safeAssetTypeName = assetTypeName ?? \"unknown\";\n const dimensions: AssetDownloadDimensions = {\n requestType: \"asset\",\n assetId: assetId,\n assetType: safeAssetTypeName,\n lensId: lens?.id ?? \"unknown\",\n };\n\n const { requestId } = dispatchRequestStarted({ dimensions });\n\n try {\n if (!assetLoader) {\n throw new Error(`Cannot get asset \"${assetId}\". Asset type \"${safeAssetTypeName}\" is not supported.`);\n }\n\n const assetResponse = await assetLoader(assetDescriptor, lens, assetManifest);\n const assetBuffer = \"data\" in assetResponse ? assetResponse.data : assetResponse;\n const assetChecksum = \"checksum\" in assetResponse ? assetResponse.checksum : undefined;\n\n if (assetBuffer.byteLength === 0) {\n throw new Error(`Got empty response for asset \"${assetId}\" from \"${safeAssetTypeName}\" loader.`);\n }\n\n dispatchRequestCompleted({ requestId, dimensions, status: 200, sizeByte: assetBuffer.byteLength });\n\n this.lensCore.provideRemoteAssetsResponse({\n assetId,\n assetBuffer,\n assetType,\n assetChecksum,\n onFailure: (reason) => {\n const lensCoreError = ensureError(reason);\n if (/validation failed/.test(lensCoreError.message)) {\n this.metrics.dispatchEvent(\n new TypedCustomEvent(\"assetValidationFailed\", {\n name: \"assetValidationFailed\",\n assetId,\n })\n );\n }\n logger.warn(new Error(`Failed to provide lens asset \"${assetId}\".`, { cause: lensCoreError }));\n },\n });\n } catch (error) {\n const wrappedError = new Error(`Failed to load lens asset \"${assetId}\".`, { cause: error });\n dispatchRequestErrored({ requestId, dimensions, error: wrappedError });\n throw wrappedError;\n }\n }\n\n /**\n * Downloads and caches assets if applicable. Does nothing for assets that are already in cache.\n * @param assetDescriptors Asset ID and type pairs.\n * @param lens Lens to load assets for.\n * @param assetManifest Lens asset manifest.\n */\n private async cacheAssetsByDescriptor(\n assetDescriptors: AssetDescriptor[],\n lens: Lens,\n assetManifest: LensAssetManifestItem[] | undefined\n ): Promise<void> {\n await Promise.all(\n assetDescriptors\n .filter((assetDescriptors) => !this.cachedAssetKeys.has(getCacheKey(assetDescriptors)))\n .map(async (assetDescriptor) => {\n try {\n // NOTE: we allow concurrent cache request to download the same asset more than once,\n // because that is better than skipping second request when the firs one fails.\n // In future we could improve concurretn logic with observables as part of\n // https://jira.sc-corp.net/browse/CAMKIT-3931\n await this.loadAsset(assetDescriptor, lens, assetManifest);\n this.cachedAssetKeys.add(getCacheKey(assetDescriptor));\n } catch (error) {\n const { assetId, assetType } = assetDescriptor;\n const [assetTypeName] = this.assetLoaders.get(assetType) ?? [];\n logger.warn(\n new Error(\n `Failed to cache asset \"${assetId}\" of type \"${assetTypeName ?? assetType.value}\".`,\n { cause: error }\n )\n );\n }\n })\n );\n }\n}\n\n/**\n * @internal\n */\nexport const lensAssetRepositoryFactory = Injectable(\n \"lensAssetRepository\",\n [\n lensCoreFactory.token,\n deviceDependentAssetLoaderFactory.token,\n remoteMediaAssetLoaderFactory.token,\n staticAssetLoaderFactory.token,\n metricsEventTargetFactory.token,\n ] as const,\n (\n lensCore: LensCoreModule,\n deviceDependentAssetLoader: AssetLoader,\n remoteMediaAssetLoader: AssetLoader,\n staticAssetLoader: AssetLoader,\n metrics: MetricsEventTarget\n ) =>\n new LensAssetRepository(\n lensCore,\n new Map([\n [lensCore.AssetType.DeviceDependent, [\"DeviceDependent\", deviceDependentAssetLoader]],\n [lensCore.AssetType.RemoteMediaByUrl, [\"RemoteMediaByUrl\", remoteMediaAssetLoader]],\n // URL type is deprecated and was introduced before RemoteMediaByURL\n // however, there are some lenses still using it so we need to support it\n [lensCore.AssetType.URL, [\"URL\", remoteMediaAssetLoader]],\n [lensCore.AssetType.Static, [\"Static\", staticAssetLoader]],\n ]),\n metrics\n )\n);\n"]}
@@ -0,0 +1,21 @@
1
+ import { LensCoreModule } from "../../lens-core-module";
2
+ import { MakeTaggedBusinessEvent } from "../../metrics/businessEventsReporter";
3
+ import { LensRepository } from "../LensRepository";
4
+ import { LensAssetRepository } from "./LensAssetRepository";
5
+ /**
6
+ * The AssetValidationFailed metric reports every time we handle an asset checksum validation failure.
7
+ */
8
+ export declare type AssetValidationFailed = MakeTaggedBusinessEvent<"assetValidationFailed">;
9
+ /**
10
+ * Registers a remote asset provider function with a given instance of LensCore.
11
+ *
12
+ * *Note:* LensCoreModule.initialize must be called on the desired LensCoreModule instance **prior** to passing it
13
+ * to the LensAssetsProvider constructor. If this class is instantiated with a LensCoreModule that has not been
14
+ * initialized, the registry of the asset provider function will fail silently and no remote assets will be loaded.
15
+ * @internal
16
+ */
17
+ export declare const registerLensAssetsProvider: {
18
+ (args_0: LensCoreModule, args_1: LensRepository, args_2: LensAssetRepository): void;
19
+ token: "registerLensAssetsProvider";
20
+ dependencies: readonly ["lensCore", "LensRepository", "lensAssetRepository"];
21
+ };
@@ -0,0 +1,41 @@
1
+ import { __awaiter } from "tslib";
2
+ import { Injectable } from "../../dependency-injection/Injectable";
3
+ import { lensAssetError } from "../../namedErrors";
4
+ import { lensCoreFactory } from "../../lens-core-module";
5
+ import { getLogger } from "../../logger/logger";
6
+ import { toPublicLens } from "../Lens";
7
+ import { lensRepositoryFactory } from "../LensRepository";
8
+ import { lensAssetRepositoryFactory } from "./LensAssetRepository";
9
+ const logger = getLogger("LensAssetProvider");
10
+ /**
11
+ * Registers a remote asset provider function with a given instance of LensCore.
12
+ *
13
+ * *Note:* LensCoreModule.initialize must be called on the desired LensCoreModule instance **prior** to passing it
14
+ * to the LensAssetsProvider constructor. If this class is instantiated with a LensCoreModule that has not been
15
+ * initialized, the registry of the asset provider function will fail silently and no remote assets will be loaded.
16
+ * @internal
17
+ */
18
+ export const registerLensAssetsProvider = Injectable("registerLensAssetsProvider", [lensCoreFactory.token, lensRepositoryFactory.token, lensAssetRepositoryFactory.token], (lensCore, lensRepository, lensAssetRepository) => {
19
+ lensCore.setRemoteAssetsProvider((assetDescriptor) => __awaiter(void 0, void 0, void 0, function* () {
20
+ var _a;
21
+ // Fetch an asset and provide it to LensCore. If fetching the asset fails we give LensCore
22
+ // an empty response (which it may handle in a variety of ways, e.g. retry, gracefully
23
+ // degrade lens behavior, throw error) and then reject.
24
+ const { assetId, assetType, effectId } = assetDescriptor;
25
+ try {
26
+ const lens = effectId ? lensRepository.getLensMetadata(effectId) : undefined;
27
+ yield lensAssetRepository.loadAsset(assetDescriptor, lens && toPublicLens(lens), (_a = lens === null || lens === void 0 ? void 0 : lens.content) === null || _a === void 0 ? void 0 : _a.assetManifest);
28
+ }
29
+ catch (error) {
30
+ // if an error occurs, LensCore handles things in different ways
31
+ // depending on the active lens. It might: 1) retry, 2) gracefully degrade lens behavior,
32
+ // 3) lens JS might throw, which will be passed to the exceptionHandler we register with LensCore.
33
+ lensCore.provideRemoteAssetsResponse({
34
+ assetId,
35
+ assetType,
36
+ });
37
+ logger.error(lensAssetError(`Unable to handle lens asset "${assetId}" request.`, error));
38
+ }
39
+ }));
40
+ });
41
+ //# sourceMappingURL=LensAssetsProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LensAssetsProvider.js","sourceRoot":"","sources":["../../../src/lens/assets/LensAssetsProvider.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,uCAAuC,CAAC;AACnE,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAkB,MAAM,wBAAwB,CAAC;AACzE,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAEhD,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAkB,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1E,OAAO,EAAuB,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAExF,MAAM,MAAM,GAAG,SAAS,CAAC,mBAAmB,CAAC,CAAC;AAO9C;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,UAAU,CAChD,4BAA4B,EAC5B,CAAC,eAAe,CAAC,KAAK,EAAE,qBAAqB,CAAC,KAAK,EAAE,0BAA0B,CAAC,KAAK,CAAU,EAC/F,CAAC,QAAwB,EAAE,cAA8B,EAAE,mBAAwC,EAAE,EAAE;IACnG,QAAQ,CAAC,uBAAuB,CAAC,CAAO,eAAe,EAAE,EAAE;;QACvD,0FAA0F;QAC1F,sFAAsF;QACtF,uDAAuD;QACvD,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,GAAG,eAAe,CAAC;QACzD,IAAI;YACA,MAAM,IAAI,GAAG,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;YAC7E,MAAM,mBAAmB,CAAC,SAAS,CAC/B,eAAe,EACf,IAAI,IAAI,YAAY,CAAC,IAAI,CAAC,EAC1B,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,0CAAE,aAAa,CAC/B,CAAC;SACL;QAAC,OAAO,KAAK,EAAE;YACZ,gEAAgE;YAChE,yFAAyF;YACzF,kGAAkG;YAClG,QAAQ,CAAC,2BAA2B,CAAC;gBACjC,OAAO;gBACP,SAAS;aACZ,CAAC,CAAC;YACH,MAAM,CAAC,KAAK,CAAC,cAAc,CAAC,gCAAgC,OAAO,YAAY,EAAE,KAAK,CAAC,CAAC,CAAC;SAC5F;IACL,CAAC,CAAA,CAAC,CAAC;AACP,CAAC,CACJ,CAAC","sourcesContent":["import { Injectable } from \"../../dependency-injection/Injectable\";\nimport { lensAssetError } from \"../../namedErrors\";\nimport { lensCoreFactory, LensCoreModule } from \"../../lens-core-module\";\nimport { getLogger } from \"../../logger/logger\";\nimport { MakeTaggedBusinessEvent } from \"../../metrics/businessEventsReporter\";\nimport { toPublicLens } from \"../Lens\";\nimport { LensRepository, lensRepositoryFactory } from \"../LensRepository\";\nimport { LensAssetRepository, lensAssetRepositoryFactory } from \"./LensAssetRepository\";\n\nconst logger = getLogger(\"LensAssetProvider\");\n\n/**\n * The AssetValidationFailed metric reports every time we handle an asset checksum validation failure.\n */\nexport type AssetValidationFailed = MakeTaggedBusinessEvent<\"assetValidationFailed\">;\n\n/**\n * Registers a remote asset provider function with a given instance of LensCore.\n *\n * *Note:* LensCoreModule.initialize must be called on the desired LensCoreModule instance **prior** to passing it\n * to the LensAssetsProvider constructor. If this class is instantiated with a LensCoreModule that has not been\n * initialized, the registry of the asset provider function will fail silently and no remote assets will be loaded.\n * @internal\n */\nexport const registerLensAssetsProvider = Injectable(\n \"registerLensAssetsProvider\",\n [lensCoreFactory.token, lensRepositoryFactory.token, lensAssetRepositoryFactory.token] as const,\n (lensCore: LensCoreModule, lensRepository: LensRepository, lensAssetRepository: LensAssetRepository) => {\n lensCore.setRemoteAssetsProvider(async (assetDescriptor) => {\n // Fetch an asset and provide it to LensCore. If fetching the asset fails we give LensCore\n // an empty response (which it may handle in a variety of ways, e.g. retry, gracefully\n // degrade lens behavior, throw error) and then reject.\n const { assetId, assetType, effectId } = assetDescriptor;\n try {\n const lens = effectId ? lensRepository.getLensMetadata(effectId) : undefined;\n await lensAssetRepository.loadAsset(\n assetDescriptor,\n lens && toPublicLens(lens),\n lens?.content?.assetManifest\n );\n } catch (error) {\n // if an error occurs, LensCore handles things in different ways\n // depending on the active lens. It might: 1) retry, 2) gracefully degrade lens behavior,\n // 3) lens JS might throw, which will be passed to the exceptionHandler we register with LensCore.\n lensCore.provideRemoteAssetsResponse({\n assetId,\n assetType,\n });\n logger.error(lensAssetError(`Unable to handle lens asset \"${assetId}\" request.`, error));\n }\n });\n }\n);\n"]}