@snap/camera-kit 0.10.0 → 0.12.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 (333) hide show
  1. package/README.md +242 -67
  2. package/docs/html/assets/search.js +1 -1
  3. package/docs/html/classes/CameraKit.html +116 -100
  4. package/docs/html/classes/CameraKitSession.html +175 -153
  5. package/docs/html/classes/CameraKitSource.html +109 -101
  6. package/docs/html/classes/LensPerformanceMeasurement.html +98 -94
  7. package/docs/html/classes/LensPerformanceMetrics.html +83 -81
  8. package/docs/html/classes/LensRepository.html +120 -109
  9. package/docs/html/classes/LensSources.html +86 -82
  10. package/docs/html/classes/Transform2D.html +98 -94
  11. package/docs/html/classes/TypedCustomEvent.html +83 -82
  12. package/docs/html/classes/TypedEventTarget.html +92 -91
  13. package/docs/html/functions/Injectable.html +87 -80
  14. package/docs/html/functions/bootstrapCameraKit.html +89 -86
  15. package/docs/html/functions/createExtension.html +76 -75
  16. package/docs/html/functions/createImageSource.html +80 -77
  17. package/docs/html/functions/createMediaStreamSource.html +80 -77
  18. package/docs/html/functions/createUserMediaSource.html +84 -81
  19. package/docs/html/functions/createVideoSource.html +80 -77
  20. package/docs/html/functions/estimateLensPerformance.html +76 -75
  21. package/docs/html/functions/getRequiredBootstrapURLs.html +78 -76
  22. package/docs/html/functions/lensSourcesFactory.html +74 -74
  23. package/docs/html/functions/uriHandlersFactory.html +76 -75
  24. package/docs/html/index.html +233 -117
  25. package/docs/html/interfaces/CameraKitBootstrapConfiguration.html +107 -100
  26. package/docs/html/interfaces/CameraKitSourceSubscriber.html +82 -81
  27. package/docs/html/interfaces/ComputedFrameMetrics.html +94 -84
  28. package/docs/html/interfaces/CreateSessionOptions.html +86 -83
  29. package/docs/html/interfaces/EstimatedLensPerformance.html +85 -84
  30. package/docs/html/interfaces/Lens.html +114 -106
  31. package/docs/html/interfaces/LensSource.html +102 -94
  32. package/docs/html/interfaces/MediaStreamSourceOptions.html +80 -80
  33. package/docs/html/interfaces/Preview.html +81 -79
  34. package/docs/html/interfaces/Snapcode.html +86 -83
  35. package/docs/html/interfaces/UriCancelRequest.html +80 -80
  36. package/docs/html/interfaces/UriHandler.html +102 -93
  37. package/docs/html/interfaces/UriRequest.html +95 -90
  38. package/docs/html/interfaces/UriResponse.html +89 -89
  39. package/docs/html/interfaces/VideoSourceOptions.html +77 -77
  40. package/docs/html/modules.html +153 -153
  41. package/docs/html/types/AssetLoader.html +75 -74
  42. package/docs/html/types/AssetTiming.html +75 -74
  43. package/docs/html/types/BenchmarkError.html +73 -73
  44. package/docs/html/types/BootstrapError.html +75 -74
  45. package/docs/html/types/CacheKeyNotFoundError.html +73 -73
  46. package/docs/html/types/CameraKitDeviceInfo.html +75 -74
  47. package/docs/html/types/CameraKitSessionEventListener.html +75 -74
  48. package/docs/html/types/CameraKitSessionEvents.html +82 -74
  49. package/docs/html/types/CameraKitSourceError.html +73 -73
  50. package/docs/html/types/CameraKitSourceInfo.html +73 -73
  51. package/docs/html/types/CameraKitSourceOptions.html +75 -74
  52. package/docs/html/types/ConfigurationError.html +75 -74
  53. package/docs/html/types/Keyboard.html +85 -80
  54. package/docs/html/types/KeyboardEvents.html +84 -74
  55. package/docs/html/types/LegalError.html +73 -73
  56. package/docs/html/types/LensAssetError.html +75 -74
  57. package/docs/html/types/LensContentValidationError.html +73 -73
  58. package/docs/html/types/LensError.html +73 -73
  59. package/docs/html/types/LensExecutionError.html +75 -74
  60. package/docs/html/types/LensImagePickerError.html +75 -74
  61. package/docs/html/types/LensLaunchParams.html +75 -74
  62. package/docs/html/types/LensMetricsEvents.html +75 -74
  63. package/docs/html/types/LensPerformanceCluster.html +75 -74
  64. package/docs/html/types/LensView.html +75 -74
  65. package/docs/html/types/LensWait.html +75 -74
  66. package/docs/html/types/PersistentStoreError.html +75 -74
  67. package/docs/html/types/PlatformNotSupportedError.html +75 -74
  68. package/docs/html/types/PublicContainer.html +75 -74
  69. package/docs/html/types/RenderTarget.html +75 -74
  70. package/docs/html/types/Uri.html +73 -73
  71. package/docs/html/types/UriHandlers.html +75 -74
  72. package/docs/html/types/WebGLError.html +73 -73
  73. package/docs/html/variables/extensionRequestContext.html +75 -74
  74. package/docs/md/README.md +242 -67
  75. package/docs/md/classes/CameraKit.md +14 -1
  76. package/docs/md/classes/CameraKitSession.md +1 -1
  77. package/docs/md/classes/CameraKitSource.md +1 -1
  78. package/docs/md/classes/LensPerformanceMeasurement.md +1 -1
  79. package/docs/md/classes/LensPerformanceMetrics.md +1 -1
  80. package/docs/md/classes/LensRepository.md +1 -1
  81. package/docs/md/classes/LensSources.md +1 -1
  82. package/docs/md/classes/Transform2D.md +1 -1
  83. package/docs/md/classes/TypedCustomEvent.md +1 -1
  84. package/docs/md/classes/TypedEventTarget.md +1 -1
  85. package/docs/md/interfaces/CameraKitBootstrapConfiguration.md +1 -1
  86. package/docs/md/interfaces/CameraKitSourceSubscriber.md +1 -1
  87. package/docs/md/interfaces/ComputedFrameMetrics.md +15 -1
  88. package/docs/md/interfaces/CreateSessionOptions.md +1 -1
  89. package/docs/md/interfaces/EstimatedLensPerformance.md +1 -1
  90. package/docs/md/interfaces/Lens.md +1 -1
  91. package/docs/md/interfaces/LensSource.md +1 -1
  92. package/docs/md/interfaces/MediaStreamSourceOptions.md +1 -1
  93. package/docs/md/interfaces/Preview.md +1 -1
  94. package/docs/md/interfaces/Snapcode.md +1 -1
  95. package/docs/md/interfaces/UriCancelRequest.md +1 -1
  96. package/docs/md/interfaces/UriHandler.md +1 -1
  97. package/docs/md/interfaces/UriRequest.md +8 -1
  98. package/docs/md/interfaces/UriResponse.md +1 -1
  99. package/docs/md/interfaces/VideoSourceOptions.md +1 -1
  100. package/docs/md/modules.md +2 -2
  101. package/lib/CameraKit.d.ts +33 -14
  102. package/lib/CameraKit.js +32 -4
  103. package/lib/CameraKit.js.map +1 -1
  104. package/lib/assertPlatformSupported.d.ts +3 -1
  105. package/lib/assertPlatformSupported.js +13 -2
  106. package/lib/assertPlatformSupported.js.map +1 -1
  107. package/lib/bootstrapCameraKit.js +7 -3
  108. package/lib/bootstrapCameraKit.js.map +1 -1
  109. package/lib/common/__mocks__/loadScript.d.ts +1 -1
  110. package/lib/common/__mocks__/loadScript.js +1 -1
  111. package/lib/common/__mocks__/loadScript.js.map +1 -1
  112. package/lib/common/cameraKitUserAgent.js +17 -2
  113. package/lib/common/cameraKitUserAgent.js.map +1 -1
  114. package/lib/common/dialog.d.ts +59 -0
  115. package/lib/common/dialog.js +160 -0
  116. package/lib/common/dialog.js.map +1 -0
  117. package/lib/common/hash.d.ts +5 -0
  118. package/lib/common/hash.js +17 -0
  119. package/lib/common/hash.js.map +1 -0
  120. package/lib/common/loadScript.d.ts +6 -1
  121. package/lib/common/loadScript.js +9 -2
  122. package/lib/common/loadScript.js.map +1 -1
  123. package/lib/common/localization.d.ts +17 -10
  124. package/lib/common/localization.js +653 -18
  125. package/lib/common/localization.js.map +1 -1
  126. package/lib/common/pageVisibility.d.ts +34 -20
  127. package/lib/common/pageVisibility.js +57 -48
  128. package/lib/common/pageVisibility.js.map +1 -1
  129. package/lib/configuration.d.ts +2 -0
  130. package/lib/configuration.js +1 -0
  131. package/lib/configuration.js.map +1 -1
  132. package/lib/dependency-injection/Container.d.ts +2 -2
  133. package/lib/dependency-injection/Container.js +10 -10
  134. package/lib/dependency-injection/Container.js.map +1 -1
  135. package/lib/dependency-injection/RootServices.d.ts +5 -1
  136. package/lib/dependency-injection/RootServices.js.map +1 -1
  137. package/lib/environment.json +1 -1
  138. package/lib/extensions/LensSources.d.ts +5 -5
  139. package/lib/extensions/LensSources.js +9 -9
  140. package/lib/extensions/LensSources.js.map +1 -1
  141. package/lib/extensions/UriHandlers.d.ts +1 -1
  142. package/lib/generated-proto/blizzard/cameraKitEvents.js.map +1 -1
  143. package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.d.ts +0 -26
  144. package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.js +0 -15
  145. package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.js.map +1 -1
  146. package/lib/generated-proto/pb_schema/camera_kit/v3/export.d.ts +0 -59
  147. package/lib/generated-proto/pb_schema/camera_kit/v3/export.js +0 -10
  148. package/lib/generated-proto/pb_schema/camera_kit/v3/export.js.map +1 -1
  149. package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.d.ts +5 -13
  150. package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.js +61 -7
  151. package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.js.map +1 -1
  152. package/lib/generated-proto/pb_schema/camera_kit/v3/lens.d.ts +0 -55
  153. package/lib/generated-proto/pb_schema/camera_kit/v3/lens.js +0 -12
  154. package/lib/generated-proto/pb_schema/camera_kit/v3/lens.js.map +1 -1
  155. package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.d.ts +0 -5
  156. package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.js +0 -7
  157. package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.js.map +1 -1
  158. package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.d.ts +0 -23
  159. package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.js +0 -15
  160. package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.js.map +1 -1
  161. package/lib/generated-proto/pb_schema/camera_kit/v3/service.d.ts +43 -56
  162. package/lib/generated-proto/pb_schema/camera_kit/v3/service.js +17 -2
  163. package/lib/generated-proto/pb_schema/camera_kit/v3/service.js.map +1 -1
  164. package/lib/generated-proto/pb_schema/cdp/cof/benchmark.d.ts +0 -8
  165. package/lib/generated-proto/pb_schema/cdp/cof/benchmark.js +0 -1
  166. package/lib/generated-proto/pb_schema/cdp/cof/benchmark.js.map +1 -1
  167. package/lib/generated-proto/pb_schema/cdp/cof/benchmark_name.d.ts +0 -45
  168. package/lib/generated-proto/pb_schema/cdp/cof/benchmark_name.js +0 -46
  169. package/lib/generated-proto/pb_schema/cdp/cof/benchmark_name.js.map +1 -1
  170. package/lib/generated-proto/pb_schema/cdp/cof/circumstance_service.d.ts +578 -104
  171. package/lib/generated-proto/pb_schema/cdp/cof/circumstance_service.js +0 -1
  172. package/lib/generated-proto/pb_schema/cdp/cof/circumstance_service.js.map +1 -1
  173. package/lib/generated-proto/pb_schema/cdp/cof/config_request.d.ts +0 -129
  174. package/lib/generated-proto/pb_schema/cdp/cof/config_request.js +0 -24
  175. package/lib/generated-proto/pb_schema/cdp/cof/config_request.js.map +1 -1
  176. package/lib/generated-proto/pb_schema/cdp/cof/config_response.d.ts +84 -22
  177. package/lib/generated-proto/pb_schema/cdp/cof/config_response.js +0 -1
  178. package/lib/generated-proto/pb_schema/cdp/cof/config_response.js.map +1 -1
  179. package/lib/generated-proto/pb_schema/cdp/cof/config_result.d.ts +177 -466
  180. package/lib/generated-proto/pb_schema/cdp/cof/config_result.js +80 -399
  181. package/lib/generated-proto/pb_schema/cdp/cof/config_result.js.map +1 -1
  182. package/lib/generated-proto/pb_schema/cdp/cof/debug_info.d.ts +0 -9
  183. package/lib/generated-proto/pb_schema/cdp/cof/debug_info.js +0 -3
  184. package/lib/generated-proto/pb_schema/cdp/cof/debug_info.js.map +1 -1
  185. package/lib/generated-proto/pb_schema/cdp/cof/namespace.d.ts +0 -1
  186. package/lib/generated-proto/pb_schema/cdp/cof/namespace.js +0 -2
  187. package/lib/generated-proto/pb_schema/cdp/cof/namespace.js.map +1 -1
  188. package/lib/generated-proto/pb_schema/common/ruid.d.ts +0 -27
  189. package/lib/generated-proto/pb_schema/common/ruid.js +0 -20
  190. package/lib/generated-proto/pb_schema/common/ruid.js.map +1 -1
  191. package/lib/generated-proto/pb_schema/common/value.d.ts +0 -9
  192. package/lib/generated-proto/pb_schema/common/value.js +0 -1
  193. package/lib/generated-proto/pb_schema/common/value.js.map +1 -1
  194. package/lib/generated-proto/pb_schema/google/protobuf/any.d.ts +0 -105
  195. package/lib/generated-proto/pb_schema/google/protobuf/any.js +0 -1
  196. package/lib/generated-proto/pb_schema/google/protobuf/any.js.map +1 -1
  197. package/lib/generated-proto/pb_schema/google/protobuf/timestamp.d.ts +0 -64
  198. package/lib/generated-proto/pb_schema/google/protobuf/timestamp.js +0 -1
  199. package/lib/generated-proto/pb_schema/google/protobuf/timestamp.js.map +1 -1
  200. package/lib/generated-proto/pb_schema/google/protobuf/wrappers.d.ts +0 -54
  201. package/lib/generated-proto/pb_schema/google/protobuf/wrappers.js +0 -1
  202. package/lib/generated-proto/pb_schema/google/protobuf/wrappers.js.map +1 -1
  203. package/lib/generated-proto/pb_schema/lenses/geocircle.js +0 -1
  204. package/lib/generated-proto/pb_schema/lenses/geocircle.js.map +1 -1
  205. package/lib/generated-proto/pb_schema/lenses/geopoint.js +0 -1
  206. package/lib/generated-proto/pb_schema/lenses/geopoint.js.map +1 -1
  207. package/lib/generated-proto/pb_schema/lenses/launch_params.js +0 -1
  208. package/lib/generated-proto/pb_schema/lenses/launch_params.js.map +1 -1
  209. package/lib/generated-proto/pb_schema/lenses/launchdata.d.ts +0 -2
  210. package/lib/generated-proto/pb_schema/lenses/launchdata.js +0 -3
  211. package/lib/generated-proto/pb_schema/lenses/launchdata.js.map +1 -1
  212. package/lib/generated-proto/pb_schema/lenses/lures.d.ts +0 -2
  213. package/lib/generated-proto/pb_schema/lenses/lures.js +0 -1
  214. package/lib/generated-proto/pb_schema/lenses/lures.js.map +1 -1
  215. package/lib/generated-proto/pb_schema/lenses/persistent_store.js +0 -1
  216. package/lib/generated-proto/pb_schema/lenses/persistent_store.js.map +1 -1
  217. package/lib/generated-proto/pb_schema/lenses/snappable.d.ts +0 -19
  218. package/lib/generated-proto/pb_schema/lenses/snappable.js +0 -2
  219. package/lib/generated-proto/pb_schema/lenses/snappable.js.map +1 -1
  220. package/lib/generated-proto/pb_schema/lenses/user_data.d.ts +0 -18
  221. package/lib/generated-proto/pb_schema/lenses/user_data.js +0 -1
  222. package/lib/generated-proto/pb_schema/lenses/user_data.js.map +1 -1
  223. package/lib/handlers/HandlerChainBuilder.js +7 -2
  224. package/lib/handlers/HandlerChainBuilder.js.map +1 -1
  225. package/lib/handlers/batchingHandler.d.ts +8 -2
  226. package/lib/handlers/batchingHandler.js +5 -8
  227. package/lib/handlers/batchingHandler.js.map +1 -1
  228. package/lib/handlers/mappingHandler.d.ts +5 -1
  229. package/lib/handlers/mappingHandler.js +6 -4
  230. package/lib/handlers/mappingHandler.js.map +1 -1
  231. package/lib/handlers/rateLimitingHandler.d.ts +5 -1
  232. package/lib/handlers/rateLimitingHandler.js +6 -4
  233. package/lib/handlers/rateLimitingHandler.js.map +1 -1
  234. package/lib/handlers/responseCachingHandler.d.ts +1 -1
  235. package/lib/handlers/responseCachingHandler.js.map +1 -1
  236. package/lib/handlers/retryingHandler.d.ts +5 -1
  237. package/lib/handlers/retryingHandler.js +13 -9
  238. package/lib/handlers/retryingHandler.js.map +1 -1
  239. package/lib/legal/legalPrompt.d.ts +7 -4
  240. package/lib/legal/legalPrompt.js +126 -135
  241. package/lib/legal/legalPrompt.js.map +1 -1
  242. package/lib/legal/legalState.d.ts +2 -2
  243. package/lib/legal/legalState.js +52 -38
  244. package/lib/legal/legalState.js.map +1 -1
  245. package/lib/lens/LensRepository.d.ts +5 -3
  246. package/lib/lens/LensRepository.js +8 -5
  247. package/lib/lens/LensRepository.js.map +1 -1
  248. package/lib/lens/assets/LensAssetsProvider.js +18 -3
  249. package/lib/lens/assets/LensAssetsProvider.js.map +1 -1
  250. package/lib/lens/lensHttpUtil.d.ts +3 -2
  251. package/lib/lens/lensHttpUtil.js +5 -5
  252. package/lib/lens/lensHttpUtil.js.map +1 -1
  253. package/lib/lens-core-module/generated-types.d.ts +21 -0
  254. package/lib/lens-core-module/generated-types.js.map +1 -1
  255. package/lib/lens-core-module/loader/lensCoreFactory.js +3 -1
  256. package/lib/lens-core-module/loader/lensCoreFactory.js.map +1 -1
  257. package/lib/lensCoreWasmVersions.json +3 -3
  258. package/lib/logger/logEntries.d.ts +1 -1
  259. package/lib/logger/logEntries.js +3 -3
  260. package/lib/logger/logEntries.js.map +1 -1
  261. package/lib/logger/logger.d.ts +7 -2
  262. package/lib/logger/logger.js +9 -4
  263. package/lib/logger/logger.js.map +1 -1
  264. package/lib/media-sources/MediaStreamSource.js +13 -4
  265. package/lib/media-sources/MediaStreamSource.js.map +1 -1
  266. package/lib/metrics/businessEventsReporter.d.ts +4 -2
  267. package/lib/metrics/businessEventsReporter.js +27 -14
  268. package/lib/metrics/businessEventsReporter.js.map +1 -1
  269. package/lib/metrics/metricsHandler.d.ts +3 -2
  270. package/lib/metrics/metricsHandler.js +3 -3
  271. package/lib/metrics/metricsHandler.js.map +1 -1
  272. package/lib/metrics/operational/Count.d.ts +17 -0
  273. package/lib/metrics/operational/Count.js +28 -0
  274. package/lib/metrics/operational/Count.js.map +1 -0
  275. package/lib/metrics/operational/Histogram.d.ts +17 -0
  276. package/lib/metrics/operational/Histogram.js +23 -0
  277. package/lib/metrics/operational/Histogram.js.map +1 -0
  278. package/lib/metrics/operational/Metric.d.ts +20 -0
  279. package/lib/metrics/operational/Metric.js +26 -0
  280. package/lib/metrics/operational/Metric.js.map +1 -0
  281. package/lib/metrics/operational/Timer.d.ts +91 -0
  282. package/lib/metrics/operational/Timer.js +122 -0
  283. package/lib/metrics/operational/Timer.js.map +1 -0
  284. package/lib/metrics/{operationalMetricsReporter.d.ts → operational/operationalMetricsReporter.d.ts} +16 -4
  285. package/lib/metrics/{operationalMetricsReporter.js → operational/operationalMetricsReporter.js} +31 -13
  286. package/lib/metrics/operational/operationalMetricsReporter.js.map +1 -0
  287. package/lib/metrics/reporters/reportBenchmarks.d.ts +1 -1
  288. package/lib/metrics/reporters/reportBenchmarks.js +1 -1
  289. package/lib/metrics/reporters/reportBenchmarks.js.map +1 -1
  290. package/lib/metrics/reporters/reportGlobalException.d.ts +1 -1
  291. package/lib/metrics/reporters/reportGlobalException.js +1 -1
  292. package/lib/metrics/reporters/reportGlobalException.js.map +1 -1
  293. package/lib/metrics/reporters/reportHttpMetrics.d.ts +1 -1
  294. package/lib/metrics/reporters/reportHttpMetrics.js +1 -1
  295. package/lib/metrics/reporters/reportHttpMetrics.js.map +1 -1
  296. package/lib/metrics/reporters/reportLegalState.d.ts +1 -1
  297. package/lib/metrics/reporters/reportLegalState.js +1 -1
  298. package/lib/metrics/reporters/reportLegalState.js.map +1 -1
  299. package/lib/metrics/reporters/reportLensAndAssetDownload.d.ts +1 -1
  300. package/lib/metrics/reporters/reportLensAndAssetDownload.js +1 -1
  301. package/lib/metrics/reporters/reportLensAndAssetDownload.js.map +1 -1
  302. package/lib/metrics/reporters/reportLensValidationFailed.d.ts +1 -1
  303. package/lib/metrics/reporters/reportLensView.d.ts +2 -2
  304. package/lib/metrics/reporters/reportLensView.js +23 -17
  305. package/lib/metrics/reporters/reportLensView.js.map +1 -1
  306. package/lib/metrics/reporters/reportLensWait.d.ts +2 -2
  307. package/lib/metrics/reporters/reportLensWait.js +1 -1
  308. package/lib/metrics/reporters/reportLensWait.js.map +1 -1
  309. package/lib/metrics/reporters/reportSessionException.d.ts +1 -1
  310. package/lib/metrics/reporters/reporters.d.ts +6 -6
  311. package/lib/metrics/reporters/reporters.js +3 -3
  312. package/lib/metrics/reporters/reporters.js.map +1 -1
  313. package/lib/observable-operators/unsubscribed.d.ts +12 -0
  314. package/lib/observable-operators/unsubscribed.js +27 -0
  315. package/lib/observable-operators/unsubscribed.js.map +1 -0
  316. package/lib/remote-configuration/cofHandler.d.ts +11 -7
  317. package/lib/remote-configuration/cofHandler.js +77 -67
  318. package/lib/remote-configuration/cofHandler.js.map +1 -1
  319. package/lib/remote-configuration/remoteConfiguration.d.ts +20 -6
  320. package/lib/remote-configuration/remoteConfiguration.js +24 -7
  321. package/lib/remote-configuration/remoteConfiguration.js.map +1 -1
  322. package/lib/session/CameraKitSession.d.ts +4 -3
  323. package/lib/session/CameraKitSession.js +6 -5
  324. package/lib/session/CameraKitSession.js.map +1 -1
  325. package/lib/session/LensKeyboard.d.ts +1 -1
  326. package/lib/session/LensPerformanceMeasurement.d.ts +2 -0
  327. package/lib/session/LensPerformanceMeasurement.js +27 -4
  328. package/lib/session/LensPerformanceMeasurement.js.map +1 -1
  329. package/lib/session/lensState.d.ts +5 -4
  330. package/lib/session/lensState.js +94 -39
  331. package/lib/session/lensState.js.map +1 -1
  332. package/package.json +12 -12
  333. package/lib/metrics/operationalMetricsReporter.js.map +0 -1
@@ -4,6 +4,7 @@ import { RequestStateEventTarget } from "../handlers/requestStateEmittingHandler
4
4
  import { LensDownloadDimensions } from "../metrics/reporters/reportLensAndAssetDownload";
5
5
  import { Handler } from "../handlers/HandlerChainBuilder";
6
6
  import { LensAssetManifestItem_RequestTiming } from "../generated-proto/pb_schema/camera_kit/v3/lens";
7
+ import { CameraKitApiHostname, CameraKitConfiguration } from "../configuration";
7
8
  import { Lens, LensProto } from "./Lens";
8
9
  import { LensAssetRepository } from "./assets/LensAssetRepository";
9
10
  type LensFetchHandler = Handler<[
@@ -56,10 +57,11 @@ export declare class LensRepository {
56
57
  private readonly lensFetchHandler;
57
58
  private readonly lensSources;
58
59
  private readonly lensAssetRepository;
60
+ private readonly apiHostname;
59
61
  private readonly metadataCache;
60
62
  private readonly binariesCache;
61
63
  /** @internal */
62
- constructor(lensMetadataFetchHandler: FetchHandler, lensFetchHandler: LensFetchHandler, lensSources: LensSources, lensAssetRepository: LensAssetRepository);
64
+ constructor(lensMetadataFetchHandler: FetchHandler, lensFetchHandler: LensFetchHandler, lensSources: LensSources, lensAssetRepository: LensAssetRepository, apiHostname: CameraKitApiHostname);
63
65
  /**
64
66
  * Retrieve a single Lens.
65
67
  *
@@ -127,8 +129,8 @@ export declare class LensRepository {
127
129
  * @internal
128
130
  */
129
131
  export declare const lensRepositoryFactory: {
130
- (args_0: RequestStateEventTarget, args_1: FetchHandler, args_2: FetchHandler, args_3: LensSources, args_4: LensAssetRepository): LensRepository;
132
+ (args_0: RequestStateEventTarget, args_1: FetchHandler, args_2: FetchHandler, args_3: LensSources, args_4: LensAssetRepository, args_5: CameraKitConfiguration): LensRepository;
131
133
  token: "LensRepository";
132
- dependencies: readonly ["requestStateEventTarget", "cameraKitServiceFetchHandler", "defaultFetchHandler", "lensSources", "lensAssetRepository"];
134
+ dependencies: readonly ["requestStateEventTarget", "cameraKitServiceFetchHandler", "defaultFetchHandler", "lensSources", "lensAssetRepository", "configuration"];
133
135
  };
134
136
  export {};
@@ -11,6 +11,7 @@ import { createArrayBufferParsingHandler } from "../handlers/arrayBufferParsingH
11
11
  import { LensAssetManifestItem_RequestTiming } from "../generated-proto/pb_schema/camera_kit/v3/lens";
12
12
  import { getLogger } from "../logger/logger";
13
13
  import { errorLoggingDecorator } from "../logger/errorLoggingDecorator";
14
+ import { configurationToken } from "../configuration";
14
15
  import { isLensArray, toPublicLens } from "./Lens";
15
16
  import { retrieveCameraKitLens, retrieveCameraKitLensGroup } from "./lensHttpUtil";
16
17
  import { decodeEnvelopes } from "./lensEnvelopeUtil";
@@ -46,11 +47,12 @@ function isOptionalAssetTimingArray(value) {
46
47
  */
47
48
  export class LensRepository {
48
49
  /** @internal */
49
- constructor(lensMetadataFetchHandler, lensFetchHandler, lensSources, lensAssetRepository) {
50
+ constructor(lensMetadataFetchHandler, lensFetchHandler, lensSources, lensAssetRepository, apiHostname) {
50
51
  this.lensMetadataFetchHandler = lensMetadataFetchHandler;
51
52
  this.lensFetchHandler = lensFetchHandler;
52
53
  this.lensSources = lensSources;
53
54
  this.lensAssetRepository = lensAssetRepository;
55
+ this.apiHostname = apiHostname;
54
56
  this.metadataCache = new Map();
55
57
  this.binariesCache = new Map();
56
58
  }
@@ -72,7 +74,7 @@ export class LensRepository {
72
74
  }
73
75
  }
74
76
  else {
75
- lens = yield retrieveCameraKitLens(this.lensMetadataFetchHandler, lensId, groupId);
77
+ lens = yield retrieveCameraKitLens(this.lensMetadataFetchHandler, lensId, groupId, this.apiHostname);
76
78
  }
77
79
  this.metadataCache.set(lens.id, lens);
78
80
  return toPublicLens(lens);
@@ -97,7 +99,7 @@ export class LensRepository {
97
99
  const envelopes = yield this.lensSources.retrieveLenses({ groupId });
98
100
  const lenses = envelopes
99
101
  ? decodeEnvelopes(envelopes)
100
- : yield retrieveCameraKitLensGroup(this.lensMetadataFetchHandler, groupId);
102
+ : yield retrieveCameraKitLensGroup(this.lensMetadataFetchHandler, groupId, this.apiHostname);
101
103
  lenses.forEach((lens) => this.metadataCache.set(lens.id, lens));
102
104
  return lenses.map(toPublicLens);
103
105
  }
@@ -231,10 +233,11 @@ export const lensRepositoryFactory = Injectable("LensRepository", [
231
233
  defaultFetchHandlerFactory.token,
232
234
  lensSourcesFactory.token,
233
235
  lensAssetRepositoryFactory.token,
234
- ], (requestStateEventTarget, lensMetadataFetchHandler, defaultFetchHandler, lensSources, lensAssetRepository) => {
236
+ configurationToken,
237
+ ], (requestStateEventTarget, lensMetadataFetchHandler, defaultFetchHandler, lensSources, lensAssetRepository, configuration) => {
235
238
  const lensFetchHandler = new HandlerChainBuilder(defaultFetchHandler)
236
239
  .map(createRequestStateEmittingHandler(requestStateEventTarget))
237
240
  .map(createArrayBufferParsingHandler()).handler;
238
- return new LensRepository(lensMetadataFetchHandler, lensFetchHandler, lensSources, lensAssetRepository);
241
+ return new LensRepository(lensMetadataFetchHandler, lensFetchHandler, lensSources, lensAssetRepository, configuration.apiHostname);
239
242
  });
240
243
  //# sourceMappingURL=LensRepository.js.map
@@ -1 +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,MA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IAAI,mBAAmB,CAAC,mBAAmB,CAAC;SAChE,GAAG,CAAC,iCAAiC,CAAyB,uBAAuB,CAAC,CAAC;SACvF,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 {\n RequestStateEventTarget,\n createRequestStateEmittingHandler,\n requestStateEventTargetFactory,\n} 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 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<{\n errors: Error[];\n lenses: Lens[];\n }> {\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 requestStateEventTargetFactory.token,\n cameraKitServiceFetchHandlerFactory.token,\n defaultFetchHandlerFactory.token,\n lensSourcesFactory.token,\n lensAssetRepositoryFactory.token,\n ] as const,\n (\n requestStateEventTarget: RequestStateEventTarget,\n lensMetadataFetchHandler: FetchHandler,\n defaultFetchHandler: FetchHandler,\n lensSources: LensSources,\n lensAssetRepository: LensAssetRepository\n ) => {\n const lensFetchHandler = new HandlerChainBuilder(defaultFetchHandler)\n .map(createRequestStateEmittingHandler<LensDownloadDimensions>(requestStateEventTarget))\n .map(createArrayBufferParsingHandler()).handler;\n return new LensRepository(lensMetadataFetchHandler, lensFetchHandler, lensSources, lensAssetRepository);\n }\n);\n"]}
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,EA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AAK;IACxB,0BAA0B,CAAC,KAAK;IAChC,kBAAkB;CACZ,EACV,CACI,uBAAgD,EAChD,wBAAsC,EACtC,mBAAiC,EACjC,WAAwB,EACxB,mBAAwC,EACxC,aAAqC,EACvC,EAAE;IACA,MAAM,gBAAgB,GAAG,IAAI,mBAAmB,CAAC,mBAAmB,CAAC;SAChE,GAAG,CAAC,iCAAiC,CAAyB,uBAAuB,CAAC,CAAC;SACvF,GAAG,CAAC,+BAA+B,EAAE,CAAC,CAAC,OAAO,CAAC;IACpD,OAAO,IAAI,cAAc,CACrB,wBAAwB,EACxB,gBAAgB,EAChB,WAAW,EACX,mBAAmB,EACnB,aAAa,CAAC,WAAW,CAC5B,CAAC;AACN,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 {\n RequestStateEventTarget,\n createRequestStateEmittingHandler,\n requestStateEventTargetFactory,\n} 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 { CameraKitApiHostname, CameraKitConfiguration, configurationToken } from \"../configuration\";\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 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 private readonly apiHostname: CameraKitApiHostname\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, this.apiHostname);\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<{\n errors: Error[];\n lenses: Lens[];\n }> {\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, this.apiHostname);\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 requestStateEventTargetFactory.token,\n cameraKitServiceFetchHandlerFactory.token,\n defaultFetchHandlerFactory.token,\n lensSourcesFactory.token,\n lensAssetRepositoryFactory.token,\n configurationToken,\n ] as const,\n (\n requestStateEventTarget: RequestStateEventTarget,\n lensMetadataFetchHandler: FetchHandler,\n defaultFetchHandler: FetchHandler,\n lensSources: LensSources,\n lensAssetRepository: LensAssetRepository,\n configuration: CameraKitConfiguration\n ) => {\n const lensFetchHandler = new HandlerChainBuilder(defaultFetchHandler)\n .map(createRequestStateEmittingHandler<LensDownloadDimensions>(requestStateEventTarget))\n .map(createArrayBufferParsingHandler()).handler;\n return new LensRepository(\n lensMetadataFetchHandler,\n lensFetchHandler,\n lensSources,\n lensAssetRepository,\n configuration.apiHostname\n );\n }\n);\n"]}
@@ -7,6 +7,7 @@ import { toPublicLens } from "../Lens";
7
7
  import { lensRepositoryFactory } from "../LensRepository";
8
8
  import { lensAssetRepositoryFactory } from "./LensAssetRepository";
9
9
  const logger = getLogger("LensAssetProvider");
10
+ const maxConsecutiveErrors = 3;
10
11
  /**
11
12
  * Registers a remote asset provider function with a given instance of LensCore.
12
13
  *
@@ -16,15 +17,20 @@ const logger = getLogger("LensAssetProvider");
16
17
  * @internal
17
18
  */
18
19
  export const registerLensAssetsProvider = Injectable("registerLensAssetsProvider", [lensCoreFactory.token, lensRepositoryFactory.token, lensAssetRepositoryFactory.token], (lensCore, lensRepository, lensAssetRepository) => {
20
+ const consecutiveErrorsPerAsset = new Map();
19
21
  lensCore.setRemoteAssetsProvider((assetDescriptor) => __awaiter(void 0, void 0, void 0, function* () {
20
- var _a;
22
+ var _a, _b, _c;
21
23
  // Fetch an asset and provide it to LensCore. If fetching the asset fails we give LensCore
22
24
  // an empty response (which it may handle in a variety of ways, e.g. retry, gracefully
23
25
  // degrade lens behavior, throw error) and then reject.
24
26
  const { assetId, assetType, effectId } = assetDescriptor;
25
27
  try {
28
+ if (((_a = consecutiveErrorsPerAsset.get(assetId)) !== null && _a !== void 0 ? _a : 0) > maxConsecutiveErrors) {
29
+ throw new Error(`Maximum consecutive asset load errors reached for asset ${assetId}`);
30
+ }
26
31
  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);
32
+ yield lensAssetRepository.loadAsset(assetDescriptor, lens && toPublicLens(lens), (_b = lens === null || lens === void 0 ? void 0 : lens.content) === null || _b === void 0 ? void 0 : _b.assetManifest);
33
+ consecutiveErrorsPerAsset.set(assetId, 0);
28
34
  }
29
35
  catch (error) {
30
36
  // if an error occurs, LensCore handles things in different ways
@@ -34,7 +40,16 @@ export const registerLensAssetsProvider = Injectable("registerLensAssetsProvider
34
40
  assetId,
35
41
  assetType,
36
42
  });
37
- logger.error(lensAssetError(`Error occurred while handling lens asset ${assetId} request.`, error));
43
+ const consecutiveErrors = ((_c = consecutiveErrorsPerAsset.get(assetId)) !== null && _c !== void 0 ? _c : 0) + 1;
44
+ consecutiveErrorsPerAsset.set(assetId, consecutiveErrors);
45
+ // We've already reported `maxConsecutiveErrors` number of errors for this asset, so we can skip
46
+ // logging additional errors.
47
+ if (consecutiveErrors <= maxConsecutiveErrors) {
48
+ logger.error(lensAssetError(`Error occurred while handling lens asset ${assetId} request.`, error));
49
+ }
50
+ else {
51
+ logger.warn(`Maximum consecutive asset load errors reached for asset ${assetId}`);
52
+ }
38
53
  }
39
54
  }));
40
55
  });
@@ -1 +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,4CAA4C,OAAO,WAAW,EAAE,KAAK,CAAC,CAAC,CAAC;SACvG;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(`Error occurred while handling lens asset ${assetId} request.`, error));\n }\n });\n }\n);\n"]}
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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;gBACjC,OAAO;gBACP,SAAS;aACZ,CAAC,CAAC;YAEH,MAAM,iBAAiB,GAAG,CAAC,MAAA,yBAAyB,CAAC,GAAG,CAAC,OAAO,CAAC,mCAAI,CAAC,CAAC,GAAG,CAAC,CAAC;YAC5E,yBAAyB,CAAC,GAAG,CAAC,OAAO,EAAE,iBAAiB,CAAC,CAAC;YAE1D,gGAAgG;YAChG,6BAA6B;YAC7B,IAAI,iBAAiB,IAAI,oBAAoB,EAAE;gBAC3C,MAAM,CAAC,KAAK,CAAC,cAAc,CAAC,4CAA4C,OAAO,WAAW,EAAE,KAAK,CAAC,CAAC,CAAC;aACvG;iBAAM;gBACH,MAAM,CAAC,IAAI,CAAC,2DAA2D,OAAO,EAAE,CAAC,CAAC;aACrF;SACJ;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\");\nconst maxConsecutiveErrors = 3;\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 const consecutiveErrorsPerAsset = new Map<string, number>();\n\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\n try {\n if ((consecutiveErrorsPerAsset.get(assetId) ?? 0) > maxConsecutiveErrors) {\n throw new Error(`Maximum consecutive asset load errors reached for asset ${assetId}`);\n }\n\n const lens = effectId ? lensRepository.getLensMetadata(effectId) : undefined;\n await lensAssetRepository.loadAsset(\n assetDescriptor,\n lens && toPublicLens(lens),\n lens?.content?.assetManifest\n );\n consecutiveErrorsPerAsset.set(assetId, 0);\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\n const consecutiveErrors = (consecutiveErrorsPerAsset.get(assetId) ?? 0) + 1;\n consecutiveErrorsPerAsset.set(assetId, consecutiveErrors);\n\n // We've already reported `maxConsecutiveErrors` number of errors for this asset, so we can skip\n // logging additional errors.\n if (consecutiveErrors <= maxConsecutiveErrors) {\n logger.error(lensAssetError(`Error occurred while handling lens asset ${assetId} request.`, error));\n } else {\n logger.warn(`Maximum consecutive asset load errors reached for asset ${assetId}`);\n }\n }\n });\n }\n);\n"]}
@@ -1,4 +1,5 @@
1
+ import { CameraKitApiHostname } from "../configuration";
1
2
  import { FetchHandler } from "../handlers/defaultFetchHandler";
2
3
  import { LensProto } from "./Lens";
3
- export declare function retrieveCameraKitLens(httpClient: FetchHandler, lensId: string, groupId: string): Promise<LensProto>;
4
- export declare function retrieveCameraKitLensGroup(httpClient: FetchHandler, groupId: string): Promise<LensProto[]>;
4
+ export declare function retrieveCameraKitLens(httpClient: FetchHandler, lensId: string, groupId: string, apiHostname: CameraKitApiHostname): Promise<LensProto>;
5
+ export declare function retrieveCameraKitLensGroup(httpClient: FetchHandler, groupId: string, apiHostname: CameraKitApiHostname): Promise<LensProto[]>;
@@ -1,12 +1,12 @@
1
1
  import { __awaiter } from "tslib";
2
2
  import { isGetGroupResponse, isLensProto } from "./Lens";
3
- const BASE_PATH = "https://api-kit.snapchat.com/com.snap.camerakit.v3.Lenses";
3
+ const relativePath = "/com.snap.camerakit.v3.Lenses";
4
4
  function getRequestId(res) {
5
5
  return res.headers.get("x-request-id");
6
6
  }
7
- export function retrieveCameraKitLens(httpClient, lensId, groupId) {
7
+ export function retrieveCameraKitLens(httpClient, lensId, groupId, apiHostname) {
8
8
  return __awaiter(this, void 0, void 0, function* () {
9
- const url = [BASE_PATH, "groups", groupId, "lenses", lensId].join("/");
9
+ const url = `https://${apiHostname}${relativePath}/groups/${groupId}/lenses/${lensId}`;
10
10
  const response = yield httpClient(url, { credentials: "include" });
11
11
  const body = yield response.json();
12
12
  const lens = body.lens;
@@ -16,9 +16,9 @@ export function retrieveCameraKitLens(httpClient, lensId, groupId) {
16
16
  return lens;
17
17
  });
18
18
  }
19
- export function retrieveCameraKitLensGroup(httpClient, groupId) {
19
+ export function retrieveCameraKitLensGroup(httpClient, groupId, apiHostname) {
20
20
  return __awaiter(this, void 0, void 0, function* () {
21
- const url = [BASE_PATH, "groups", groupId].join("/");
21
+ const url = `https://${apiHostname}${relativePath}/groups/${groupId}`;
22
22
  const response = yield httpClient(url, { credentials: "include" });
23
23
  const body = yield response.json();
24
24
  if (!isGetGroupResponse(body)) {
@@ -1 +1 @@
1
- {"version":3,"file":"lensHttpUtil.js","sourceRoot":"","sources":["../../src/lens/lensHttpUtil.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAa,MAAM,QA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ACvE,IAAI,CACP,wBAAwB,YAAY,CAAC,QAAQ,CAAC,GAAG,CACrD,CAAC;SACL;QACD,OAAO,IAAI,CAAC,MAAM,CAAC;IACvB,CAAC;CAAA","sourcesContent":["import { FetchHandler } from \"../handlers/defaultFetchHandler\";\nimport { isGetGroupResponse, isLensProto, LensProto } from \"./Lens\";\n\nconst BASE_PATH = \"https://api-kit.snapchat.com/com.snap.camerakit.v3.Lenses\";\n\nfunction getRequestId(res: Response) {\n return res.headers.get(\"x-request-id\");\n}\n\nexport async function retrieveCameraKitLens(\n httpClient: FetchHandler,\n lensId: string,\n groupId: string\n): Promise<LensProto> {\n const url = [BASE_PATH, \"groups\", groupId, \"lenses\", lensId].join(\"/\");\n const response = await httpClient(url, { credentials: \"include\" });\n const body = await response.json();\n const lens = body.lens;\n if (!isLensProto(lens)) {\n throw new Error(\n `Expected request to ${url} to return a Lens. Got:\\n\\n${JSON.stringify(\n body\n )} with request-id of \"${getRequestId(response)}\"`\n );\n }\n return lens;\n}\n\nexport async function retrieveCameraKitLensGroup(httpClient: FetchHandler, groupId: string): Promise<LensProto[]> {\n const url = [BASE_PATH, \"groups\", groupId].join(\"/\");\n const response = await httpClient(url, { credentials: \"include\" });\n const body = await response.json();\n if (!isGetGroupResponse(body)) {\n throw new Error(\n `Expected request to ${url} to return a LensGroup. Got:\\n\\n${JSON.stringify(\n body\n )} with request-id of \"${getRequestId(response)}\"`\n );\n }\n return body.lenses;\n}\n"]}
1
+ {"version":3,"file":"lensHttpUtil.js","sourceRoot":"","sources":["../../src/lens/lensHttpUtil.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAa,MAAM,QAAQ,CAAC;AAEpE,MAAM,YAAY,GAAG,+BAA+B,CAAC;AAErD,SAAS,YAAY,CAAC,GAAa;IAC/B,OAAO,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;AAC3C,CAAC;AAED,MAAM,UAAgB,qBAAqB,CACvC,UAAwB,EACxB,MAAc,EACd,OAAe,EACf,WAAiC;;QAEjC,MAAM,GAAG,GAAG,WAAW,WAAW,GAAG,YAAY,WAAW,OAAO,WAAW,MAAM,EAAE,CAAC;QACvF,MAAM,QAAQ,GAAG,MAAM,UAAU,CAAC,GAAG,EAAE,EAAE,WAAW,EAAE,SAAS,EAAE,CAAC,CAAC;QACnE,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACvB,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE;YACpB,MAAM,IAAI,KAAK,CACX,uBAAuB,GAAG,8BAA8B,IAAI,CAAC,SAAS,CAClE,IAAI,CACP,wBAAwB,YAAY,CAAC,QAAQ,CAAC,GAAG,CACrD,CAAC;SACL;QACD,OAAO,IAAI,CAAC;IAChB,CAAC;CAAA;AAED,MAAM,UAAgB,0BAA0B,CAC5C,UAAwB,EACxB,OAAe,EACf,WAAiC;;QAEjC,MAAM,GAAG,GAAG,WAAW,WAAW,GAAG,YAAY,WAAW,OAAO,EAAE,CAAC;QACtE,MAAM,QAAQ,GAAG,MAAM,UAAU,CAAC,GAAG,EAAE,EAAE,WAAW,EAAE,SAAS,EAAE,CAAC,CAAC;QACnE,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,EAAE;YAC3B,MAAM,IAAI,KAAK,CACX,uBAAuB,GAAG,mCAAmC,IAAI,CAAC,SAAS,CACvE,IAAI,CACP,wBAAwB,YAAY,CAAC,QAAQ,CAAC,GAAG,CACrD,CAAC;SACL;QACD,OAAO,IAAI,CAAC,MAAM,CAAC;IACvB,CAAC;CAAA","sourcesContent":["import { CameraKitApiHostname } from \"../configuration\";\nimport { FetchHandler } from \"../handlers/defaultFetchHandler\";\nimport { isGetGroupResponse, isLensProto, LensProto } from \"./Lens\";\n\nconst relativePath = \"/com.snap.camerakit.v3.Lenses\";\n\nfunction getRequestId(res: Response) {\n return res.headers.get(\"x-request-id\");\n}\n\nexport async function retrieveCameraKitLens(\n httpClient: FetchHandler,\n lensId: string,\n groupId: string,\n apiHostname: CameraKitApiHostname\n): Promise<LensProto> {\n const url = `https://${apiHostname}${relativePath}/groups/${groupId}/lenses/${lensId}`;\n const response = await httpClient(url, { credentials: \"include\" });\n const body = await response.json();\n const lens = body.lens;\n if (!isLensProto(lens)) {\n throw new Error(\n `Expected request to ${url} to return a Lens. Got:\\n\\n${JSON.stringify(\n body\n )} with request-id of \"${getRequestId(response)}\"`\n );\n }\n return lens;\n}\n\nexport async function retrieveCameraKitLensGroup(\n httpClient: FetchHandler,\n groupId: string,\n apiHostname: CameraKitApiHostname\n): Promise<LensProto[]> {\n const url = `https://${apiHostname}${relativePath}/groups/${groupId}`;\n const response = await httpClient(url, { credentials: \"include\" });\n const body = await response.json();\n if (!isGetGroupResponse(body)) {\n throw new Error(\n `Expected request to ${url} to return a LensGroup. Got:\\n\\n${JSON.stringify(\n body\n )} with request-id of \"${getRequestId(response)}\"`\n );\n }\n return body.lenses;\n}\n"]}
@@ -7,6 +7,7 @@ export type LensCoreEnumValue = {
7
7
  export type GetOutputCanvasesOutput = Record<number, HTMLCanvasElement>;
8
8
  export type SetRenderSizeInput = SetRenderSizeMatchInputResolutionInput | SetRenderSizeExplicitInput;
9
9
  export type SetRemoteAssetsProviderInput = (assetDescriptor: AssetDescriptor) => void;
10
+ export type SetRemoteAssetsUploadHandlerInput = (assetUploadDescriptor: AssetUploadDescriptor) => void;
10
11
  export type ContentType = "text/plain" | "text/html" | "application/json" | "application/octet-stream" | "application/x-protobuf" | "application/grpc";
11
12
  export type SavePersistentStoreCallback = (id: string, data: ArrayBuffer) => void;
12
13
  export type ShowHintCallback = (effectId: string, hintId: string) => void;
@@ -128,6 +129,7 @@ export interface UriRequest {
128
129
  method: "GET" | "POST";
129
130
  contentType: ContentType;
130
131
  data: ArrayBuffer;
132
+ metadata: Record<string, string>;
131
133
  }
132
134
  export interface UriResponse {
133
135
  code: number;
@@ -172,6 +174,17 @@ export interface AssetDescriptor {
172
174
  assetType: AssetType;
173
175
  avatarId?: string;
174
176
  effectId?: string;
177
+ encryptionKey?: string;
178
+ }
179
+ export interface AssetUploadDescriptor {
180
+ requestId: number;
181
+ assetId: string;
182
+ assetType: AssetType;
183
+ effectId: string;
184
+ assetBuffer: ArrayBuffer;
185
+ encryptionKey?: string;
186
+ encryptionIv?: string;
187
+ assetBatchId?: string;
175
188
  }
176
189
  export interface ProvideRemoteAssetsResponseInput {
177
190
  assetId: string;
@@ -180,6 +193,12 @@ export interface ProvideRemoteAssetsResponseInput {
180
193
  assetChecksum?: string;
181
194
  onFailure?: DefaultErrorHandler;
182
195
  }
196
+ export interface ProvideRemoteAssetsUploadResponseInput {
197
+ requestId: number;
198
+ success: boolean;
199
+ assetUrl?: string;
200
+ assetUploadMetadata?: ArrayBuffer;
201
+ }
183
202
  export interface ProcessFrameInput {
184
203
  inputFrame: ImageBitmap | HTMLCanvasElement | HTMLImageElement | VideoFrame;
185
204
  timestampMillis: number;
@@ -402,6 +421,8 @@ export interface LensCoreModule extends InitialEmscriptenModule {
402
421
  provideUriResponse: (requestId: string, response: UriResponse) => void;
403
422
  setRemoteAssetsProvider: (provider: SetRemoteAssetsProviderInput) => void;
404
423
  provideRemoteAssetsResponse: (assetResponse: ProvideRemoteAssetsResponseInput) => void;
424
+ setRemoteAssetsUploadHandler: (provider: SetRemoteAssetsUploadHandlerInput) => void;
425
+ provideRemoteAssetsUploadResponse: (assetResponse: ProvideRemoteAssetsUploadResponseInput) => void;
405
426
  registerShowHintCallback: (callback: ShowHintCallback) => void;
406
427
  registerHideHintCallback: (callback: HideHintCallback) => void;
407
428
  registerSavePersistentStoreCallback: (callback: SavePersistentStoreCallback) => void;
@@ -1 +1 @@
1
- {"version":3,"file":"generated-types.js","sourceRoot":"","sources":["../../src/lens-core-module/generated-types.ts"],"names":[],"mappings":"","sourcesContent":["export type DefaultEventHandler = (...data: any[]) => void;\n\nexport type DefaultErrorHandler = (err: LensCoreError) => void;\n\nexport type LensCoreEnumValue = { value: number };\n\nexport type GetOutputCanvasesOutput = Record<number, HTMLCanvasElement>;\n\nexport type SetRenderSizeInput = SetRenderSizeMatchInputResolutionInput | SetRenderSizeExplicitInput;\n\nexport type SetRemoteAssetsProviderInput = (assetDescriptor: AssetDescriptor) => void;\n\nexport type ContentType =\n | \"text/plain\"\n | \"text/html\"\n | \"application/json\"\n | \"application/octet-stream\"\n | \"application/x-protobuf\"\n | \"application/grpc\";\n\nexport type SavePersistentStoreCallback = (id: string, data: ArrayBuffer) => void;\n\nexport type ShowHintCallback = (effectId: string, hintId: string) => void;\n\nexport type HideHintCallback = (effectId: string) => void;\n\nexport type ReceiveInstanceCallback = (instance: WebAssembly.Instance, module: WebAssembly.Module) => void;\n\nexport type AssetType = LensCoreEnumValue;\n\nexport type CanvasType = LensCoreEnumValue;\n\nexport type RenderLoopMode = LensCoreEnumValue;\n\nexport type LensApiVisibility = LensCoreEnumValue;\n\nexport type DeviceClass = LensCoreEnumValue;\n\nexport type UserDataAccess = LensCoreEnumValue;\n\nexport type InterfaceControl = LensCoreEnumValue;\n\nexport type InterfaceAction = LensCoreEnumValue;\n\nexport type ExternalMediaOrientation = LensCoreEnumValue;\n\nexport type ErrorType = LensCoreEnumValue;\n\nexport type Uri = `${string}://${string}`;\n\nexport type Dimensions = { width: number; height: number };\n\nexport type Size2D = { width: number; height: number };\n\nexport type Vec2D = { x: number; y: number };\n\nexport type Rect = { origin: Vec2D; size: Size2D };\n\nexport interface ClearAllLensesInput {\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface OnFrameProcessedParam {\n processingTimeMs: number;\n}\n\nexport interface InitializeInput {\n canvas?: HTMLCanvasElement | string;\n outputResolution?: Dimensions;\n showFpsPanel?: boolean;\n shouldUseWorker?: boolean;\n onFrameProcessed?: (arg: OnFrameProcessedParam) => void;\n onFailure?: DefaultErrorHandler;\n onSuccess?: DefaultEventHandler;\n exceptionHandler?: (error: LensCoreError) => void;\n}\n\nexport interface PlayCanvasInput {\n type: CanvasType;\n onReady?: () => void;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface PauseCanvasInput {\n type: CanvasType;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetFpsLimitInput {\n fps: number;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetInputTransformInput {\n matrix: Float32Array | ArrayBuffer;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetOnFrameProcessedInput {\n onFrameProcessed: (arg: OnFrameProcessedParam) => void;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetRenderSizeMatchInputResolutionInput {\n mode: \"matchInputResolution\";\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetRenderSizeExplicitInput {\n mode: \"explicit\";\n target: Dimensions;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetRenderLoopInput {\n mode: RenderLoopMode;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface TeardownInput {\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultEventHandler;\n}\n\nexport interface ReplayTrackingDataInput {\n buffer: Uint8Array | ArrayBuffer;\n}\n\nexport interface UseMediaElementInput {\n media?: HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | MediaStream;\n requestWebcam?: boolean;\n startOnFrontCamera?: boolean;\n mirrorMedia?: boolean;\n pauseExistingMedia?: boolean;\n autoplayNewMedia?: boolean;\n autoplayPreviewCanvas?: boolean;\n useManualFrameProcessing?: boolean;\n replayTrackingData?: ReplayTrackingDataInput;\n onFailure?: DefaultErrorHandler;\n onSuccess?: DefaultEventHandler;\n}\n\nexport interface UriListener {\n handleRequest: (request: UriRequest) => void;\n cancelRequest?: (request: UriCancelRequest) => void;\n}\n\nexport interface UriRequest {\n uri: Uri;\n identifier: string;\n method: \"GET\" | \"POST\";\n contentType: ContentType;\n data: ArrayBuffer;\n}\n\nexport interface UriResponse {\n code: number;\n description: string;\n contentType: ContentType;\n data: ArrayBuffer;\n metadata?: Record<string, string>;\n}\n\nexport interface UriCancelRequest {\n uri: Uri;\n requestId: string;\n}\n\nexport interface LensDescriptor {\n lensId: string;\n lensChecksum: string;\n lensPath?: string;\n lensDataBuffer?: Uint8Array | ArrayBuffer;\n onTurnOn?: DefaultEventHandler;\n onTurnOff?: DefaultEventHandler;\n onFirstFrameProcessed?: DefaultEventHandler;\n onResourcesLoaded?: DefaultEventHandler;\n launchData?: Uint8Array | ArrayBuffer;\n apiVisibility?: LensApiVisibility;\n publicApiUserDataAccess?: UserDataAccess;\n}\n\nexport interface AddLensInput extends LensDescriptor {\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface ReplaceLensesInput {\n lenses: LensDescriptor | Array<LensDescriptor>;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface RemoveLensInput {\n lensId: string;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface AssetDescriptor {\n assetId: string;\n assetType: AssetType;\n avatarId?: string;\n effectId?: string;\n}\n\nexport interface ProvideRemoteAssetsResponseInput {\n assetId: string;\n assetType: AssetType;\n assetBuffer?: ArrayBuffer;\n assetChecksum?: string;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface ProcessFrameInput {\n inputFrame: ImageBitmap | HTMLCanvasElement | HTMLImageElement | VideoFrame;\n timestampMillis: number;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface LensCoreError extends Error {\n otherExceptions?: Array<Error>;\n cause: { type: ErrorType; metadata?: any };\n}\n\nexport interface ImageToYuvBufferInput {\n image: Uint8Array | ArrayBuffer | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap;\n width: number;\n height: number;\n outputBuffer?: Uint8Array | ArrayBuffer;\n onSuccess: (buffer: ArrayBuffer) => void;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface YuvBufferToBitmapInput {\n buffer: Uint8Array | ArrayBuffer;\n width: number;\n height: number;\n targetWidth?: number;\n targetHeight?: number;\n preserveCanvasState?: boolean;\n allowBufferTransfer?: boolean;\n onSuccess: (bitmap: ImageBitmap) => void;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetInterfaceControlVisibilityInput {\n effectId: string;\n interfaceControl: InterfaceControl;\n visibility: boolean;\n}\n\nexport interface HandleClientInterfaceActionInput {\n effectId: string;\n interfaceControl: InterfaceControl;\n interfaceAction: InterfaceAction;\n}\n\nexport interface ProvideExternalImageInput {\n data: Uint8Array | ArrayBuffer;\n orientation: ExternalMediaOrientation;\n faceRects?: Array<Rect>;\n}\n\nexport interface ProvideExternalVideoInput {\n data: Uint8Array | ArrayBuffer;\n orientation: ExternalMediaOrientation;\n relStartPosition?: number;\n relEndPosition?: number;\n volume?: number;\n}\n\nexport interface ScreenDimmingRequestInput {\n effectId: string;\n enabled: boolean;\n}\n\nexport type ScreenDimmingRequestHandler = (config: ScreenDimmingRequestInput) => void;\n\nexport interface ClientInterfaceData {\n HeaderId?: string;\n DescriptionId?: string;\n FaceFilteringEnabled?: \"0\" | \"1\";\n FaceFilteringMultipleFaces?: \"0\" | \"1\";\n ImageEnabled?: \"0\" | \"1\";\n VideoEnabled?: \"0\" | \"1\";\n}\n\nexport interface ClientInterfaceRequestInput {\n effectId: string;\n interfaceControl: InterfaceControl;\n interfaceAction: InterfaceAction;\n data: ClientInterfaceData;\n}\n\nexport type ClientInterfaceRequestHandler = (config: ClientInterfaceRequestInput) => void;\n\nexport interface LensCoreConfig {\n configId: string;\n value:\n | { stringValue: string }\n | { boolValue: boolean }\n | { intValue: number }\n | { longValue: number }\n | { floatValue: number }\n | {\n anyValue: {\n typeUrl: string;\n value: Uint8Array | ArrayBuffer;\n };\n };\n}\n\nexport type SetPreloadedConfigurationInput = Array<LensCoreConfig>;\n\nexport interface SetAllSoundsMutedInput {\n muted: boolean;\n fade: boolean;\n}\n\nexport interface SetDeviceClassInput {\n deviceClass: DeviceClass;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetAudioParametersInput {\n parameters: {\n numChannels?: number;\n sampleRate?: number;\n };\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SystemFont {\n name: string;\n data: Uint8Array | ArrayBuffer;\n}\n\nexport interface SetSystemFontsInput {\n fonts: SystemFont[]\n}\nexport interface ProcessAudioSampleBufferInput {\n input: Float32Array[] | ArrayBuffer[];\n output?: Float32Array[] | ArrayBuffer[];\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface InitialEmscriptenModule {\n mainScriptUrlOrBlob: string;\n compiledModule?: WebAssembly.Module;\n pthreadWorkerScriptUrl?: string;\n instantiateWasm?: (importObject: WebAssembly.Imports, receiveInstance: ReceiveInstanceCallback) => void;\n print?: (text: string) => void;\n printErr?: (text: string) => void;\n}\n\nexport interface LensCoreModule extends InitialEmscriptenModule {\n AssetType: {\n RemoteMediaByUrl: AssetType;\n DeviceDependent: AssetType;\n Static: AssetType;\n URL: AssetType;\n BitmojiDynamicAsset: AssetType;\n };\n\n CanvasType: {\n None: CanvasType;\n Preview: CanvasType;\n Capture: CanvasType;\n All: CanvasType;\n };\n\n LensApiVisibility: {\n Dev: LensApiVisibility;\n Private: LensApiVisibility;\n Public: LensApiVisibility;\n };\n\n DeviceClass: {\n Undefined: DeviceClass;\n BarelyWorking: DeviceClass;\n LowEnd: DeviceClass;\n MidEnd: DeviceClass;\n HighEnd: DeviceClass;\n };\n\n RenderLoopMode: {\n SetTimeout: RenderLoopMode;\n RequestAnimationFrame: RenderLoopMode;\n };\n\n UserDataAccess: {\n Restricted: UserDataAccess;\n Unrestricted: UserDataAccess;\n };\n\n InterfaceControl: {\n ToggleCameraButton: InterfaceControl;\n ImagePicker: InterfaceControl;\n Hint: InterfaceControl;\n Modal: InterfaceControl;\n LinkBitmojiCallToAction: InterfaceControl;\n SnapButton: InterfaceControl;\n PlayButton: InterfaceControl;\n All: InterfaceControl;\n ExitFullScreenButton: InterfaceControl;\n MemoriesButton: InterfaceControl;\n LensAttachmentButton: InterfaceControl;\n ReverseCamera: InterfaceControl;\n };\n\n InterfaceAction: {\n EnableHighlight: InterfaceAction;\n DisableHighlight: InterfaceAction;\n Trigger: InterfaceAction;\n Show: InterfaceAction;\n Hide: InterfaceAction;\n };\n\n ExternalMediaOrientation: {\n CW0: ExternalMediaOrientation;\n CW90: ExternalMediaOrientation;\n CW180: ExternalMediaOrientation;\n CW270: ExternalMediaOrientation;\n };\n\n ErrorType: {\n LensDeserialization: ErrorType;\n Validation: ErrorType;\n Uncategorized: ErrorType;\n LensExecution: ErrorType;\n Abort: ErrorType;\n };\n\n initialize: (config: InitializeInput) => void;\n processFrame: (config: ProcessFrameInput) => void;\n addLens: (config: AddLensInput) => void;\n replaceLenses: (config: ReplaceLensesInput) => void;\n removeLens: (config: RemoveLensInput) => void;\n clearAllLenses: (config: ClearAllLensesInput) => void;\n teardown: (config: TeardownInput) => void;\n useMediaElement: (config: UseMediaElementInput) => void;\n setFPSLimit: (config: SetFpsLimitInput) => void;\n setRenderLoopMode: (config: SetRenderLoopInput) => void;\n getCoreVersion: () => number;\n playCanvas: (input: PlayCanvasInput) => void;\n pauseCanvas: (input: PauseCanvasInput) => void;\n getOutputCanvases: () => GetOutputCanvasesOutput;\n setRenderSize: (input: SetRenderSizeInput) => void;\n startProfiling: () => void;\n endProfiling: () => void;\n setInputTransform: (config: SetInputTransformInput) => void;\n registerUriListener: (scheme: string, route: string, listener: UriListener) => void;\n provideUriResponse: (requestId: string, response: UriResponse) => void;\n setRemoteAssetsProvider: (provider: SetRemoteAssetsProviderInput) => void;\n provideRemoteAssetsResponse: (assetResponse: ProvideRemoteAssetsResponseInput) => void;\n registerShowHintCallback: (callback: ShowHintCallback) => void;\n registerHideHintCallback: (callback: HideHintCallback) => void;\n registerSavePersistentStoreCallback: (callback: SavePersistentStoreCallback) => void;\n imageToYuvBuffer: (config: ImageToYuvBufferInput) => void;\n yuvBufferToBitmap: (config: YuvBufferToBitmapInput) => void;\n setOnFrameProcessedCallback: (config: SetOnFrameProcessedInput) => void;\n setInterfaceControlVisibility: (config: SetInterfaceControlVisibilityInput) => void;\n handleClientInterfaceAction: (config: HandleClientInterfaceActionInput) => void;\n provideExternalImage: (config: ProvideExternalImageInput) => void;\n provideExternalVideo: (config: ProvideExternalVideoInput) => void;\n setScreenDimmingRequestHandler: (callback: ScreenDimmingRequestHandler) => void;\n setClientInterfaceRequestHandler: (callback: ClientInterfaceRequestHandler) => void;\n setPreloadedConfiguration: (config: SetPreloadedConfigurationInput) => void;\n setAllSoundsMuted: (config: SetAllSoundsMutedInput) => void;\n setDeviceClass: (config: SetDeviceClassInput) => void;\n setSystemFonts: (config: SetSystemFontsInput) => void;\n setAudioParameters: (config: SetAudioParametersInput) => void;\n processAudioSampleBuffer: (config: ProcessAudioSampleBufferInput) => void;\n}\n\ndeclare global {\n // This function is provided by the Emscripten glue file and responsible for initialization, will be fullfiled\n // when everything is loaded and it is safe to call compiled functions\n // eslint-disable-next-line max-len\n // https://emscripten.org/docs/getting_started/FAQ.html#how-can-i-tell-when-the-page-is-fully-loaded-and-it-is-safe-to-call-compiled-functions\n // Function is defined by the LensCore web assembly\n // eslint-disable-next-line max-len\n // https://github.sc-corp.net/Snapchat/LensCore/blob/6715da8c877d593e4fe133f4145eb3022204525d/Platforms/WebAssembly/LookserySDK/CMakeLists.txt#L65\n function createLensesModule(module: InitialEmscriptenModule): Promise<InitialEmscriptenModule & LensCoreModule>;\n}\n"]}
1
+ {"version":3,"file":"generated-types.js","sourceRoot":"","sources":["../../src/lens-core-module/generated-types.ts"],"names":[],"mappings":"","sourcesContent":["export type DefaultEventHandler = (...data: any[]) => void;\n\nexport type DefaultErrorHandler = (err: LensCoreError) => void;\n\nexport type LensCoreEnumValue = { value: number };\n\nexport type GetOutputCanvasesOutput = Record<number, HTMLCanvasElement>;\n\nexport type SetRenderSizeInput = SetRenderSizeMatchInputResolutionInput | SetRenderSizeExplicitInput;\n\nexport type SetRemoteAssetsProviderInput = (assetDescriptor: AssetDescriptor) => void;\n\nexport type SetRemoteAssetsUploadHandlerInput = (assetUploadDescriptor: AssetUploadDescriptor) => void;\n\nexport type ContentType =\n | \"text/plain\"\n | \"text/html\"\n | \"application/json\"\n | \"application/octet-stream\"\n | \"application/x-protobuf\"\n | \"application/grpc\";\n\nexport type SavePersistentStoreCallback = (id: string, data: ArrayBuffer) => void;\n\nexport type ShowHintCallback = (effectId: string, hintId: string) => void;\n\nexport type HideHintCallback = (effectId: string) => void;\n\nexport type ReceiveInstanceCallback = (instance: WebAssembly.Instance, module: WebAssembly.Module) => void;\n\nexport type AssetType = LensCoreEnumValue;\n\nexport type CanvasType = LensCoreEnumValue;\n\nexport type RenderLoopMode = LensCoreEnumValue;\n\nexport type LensApiVisibility = LensCoreEnumValue;\n\nexport type DeviceClass = LensCoreEnumValue;\n\nexport type UserDataAccess = LensCoreEnumValue;\n\nexport type InterfaceControl = LensCoreEnumValue;\n\nexport type InterfaceAction = LensCoreEnumValue;\n\nexport type ExternalMediaOrientation = LensCoreEnumValue;\n\nexport type ErrorType = LensCoreEnumValue;\n\nexport type Uri = `${string}://${string}`;\n\nexport type Dimensions = { width: number; height: number };\n\nexport type Size2D = { width: number; height: number };\n\nexport type Vec2D = { x: number; y: number };\n\nexport type Rect = { origin: Vec2D; size: Size2D };\n\nexport interface ClearAllLensesInput {\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface OnFrameProcessedParam {\n processingTimeMs: number;\n}\n\nexport interface InitializeInput {\n canvas?: HTMLCanvasElement | string;\n outputResolution?: Dimensions;\n showFpsPanel?: boolean;\n shouldUseWorker?: boolean;\n onFrameProcessed?: (arg: OnFrameProcessedParam) => void;\n onFailure?: DefaultErrorHandler;\n onSuccess?: DefaultEventHandler;\n exceptionHandler?: (error: LensCoreError) => void;\n}\n\nexport interface PlayCanvasInput {\n type: CanvasType;\n onReady?: () => void;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface PauseCanvasInput {\n type: CanvasType;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetFpsLimitInput {\n fps: number;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetInputTransformInput {\n matrix: Float32Array | ArrayBuffer;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetOnFrameProcessedInput {\n onFrameProcessed: (arg: OnFrameProcessedParam) => void;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetRenderSizeMatchInputResolutionInput {\n mode: \"matchInputResolution\";\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetRenderSizeExplicitInput {\n mode: \"explicit\";\n target: Dimensions;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetRenderLoopInput {\n mode: RenderLoopMode;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface TeardownInput {\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultEventHandler;\n}\n\nexport interface ReplayTrackingDataInput {\n buffer: Uint8Array | ArrayBuffer;\n}\n\nexport interface UseMediaElementInput {\n media?: HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | MediaStream;\n requestWebcam?: boolean;\n startOnFrontCamera?: boolean;\n mirrorMedia?: boolean;\n pauseExistingMedia?: boolean;\n autoplayNewMedia?: boolean;\n autoplayPreviewCanvas?: boolean;\n useManualFrameProcessing?: boolean;\n replayTrackingData?: ReplayTrackingDataInput;\n onFailure?: DefaultErrorHandler;\n onSuccess?: DefaultEventHandler;\n}\n\nexport interface UriListener {\n handleRequest: (request: UriRequest) => void;\n cancelRequest?: (request: UriCancelRequest) => void;\n}\n\nexport interface UriRequest {\n uri: Uri;\n identifier: string;\n method: \"GET\" | \"POST\";\n contentType: ContentType;\n data: ArrayBuffer;\n metadata: Record<string, string>;\n}\n\nexport interface UriResponse {\n code: number;\n description: string;\n contentType: ContentType;\n data: ArrayBuffer;\n metadata?: Record<string, string>;\n}\n\nexport interface UriCancelRequest {\n uri: Uri;\n requestId: string;\n}\n\nexport interface LensDescriptor {\n lensId: string;\n lensChecksum: string;\n lensPath?: string;\n lensDataBuffer?: Uint8Array | ArrayBuffer;\n onTurnOn?: DefaultEventHandler;\n onTurnOff?: DefaultEventHandler;\n onFirstFrameProcessed?: DefaultEventHandler;\n onResourcesLoaded?: DefaultEventHandler;\n launchData?: Uint8Array | ArrayBuffer;\n apiVisibility?: LensApiVisibility;\n publicApiUserDataAccess?: UserDataAccess;\n}\n\nexport interface AddLensInput extends LensDescriptor {\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface ReplaceLensesInput {\n lenses: LensDescriptor | Array<LensDescriptor>;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface RemoveLensInput {\n lensId: string;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface AssetDescriptor {\n assetId: string;\n assetType: AssetType;\n avatarId?: string;\n effectId?: string;\n encryptionKey?: string;\n}\n\nexport interface AssetUploadDescriptor {\n requestId: number;\n assetId: string;\n assetType: AssetType;\n effectId: string;\n assetBuffer: ArrayBuffer;\n encryptionKey?: string;\n encryptionIv?: string;\n assetBatchId?: string;\n}\n\nexport interface ProvideRemoteAssetsResponseInput {\n assetId: string;\n assetType: AssetType;\n assetBuffer?: ArrayBuffer;\n assetChecksum?: string;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface ProvideRemoteAssetsUploadResponseInput {\n requestId: number;\n success: boolean;\n assetUrl?: string;\n assetUploadMetadata?: ArrayBuffer;\n}\n\nexport interface ProcessFrameInput {\n inputFrame: ImageBitmap | HTMLCanvasElement | HTMLImageElement | VideoFrame;\n timestampMillis: number;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface LensCoreError extends Error {\n otherExceptions?: Array<Error>;\n cause: { type: ErrorType; metadata?: any };\n}\n\nexport interface ImageToYuvBufferInput {\n image: Uint8Array | ArrayBuffer | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap;\n width: number;\n height: number;\n outputBuffer?: Uint8Array | ArrayBuffer;\n onSuccess: (buffer: ArrayBuffer) => void;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface YuvBufferToBitmapInput {\n buffer: Uint8Array | ArrayBuffer;\n width: number;\n height: number;\n targetWidth?: number;\n targetHeight?: number;\n preserveCanvasState?: boolean;\n allowBufferTransfer?: boolean;\n onSuccess: (bitmap: ImageBitmap) => void;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetInterfaceControlVisibilityInput {\n effectId: string;\n interfaceControl: InterfaceControl;\n visibility: boolean;\n}\n\nexport interface HandleClientInterfaceActionInput {\n effectId: string;\n interfaceControl: InterfaceControl;\n interfaceAction: InterfaceAction;\n}\n\nexport interface ProvideExternalImageInput {\n data: Uint8Array | ArrayBuffer;\n orientation: ExternalMediaOrientation;\n faceRects?: Array<Rect>;\n}\n\nexport interface ProvideExternalVideoInput {\n data: Uint8Array | ArrayBuffer;\n orientation: ExternalMediaOrientation;\n relStartPosition?: number;\n relEndPosition?: number;\n volume?: number;\n}\n\nexport interface ScreenDimmingRequestInput {\n effectId: string;\n enabled: boolean;\n}\n\nexport type ScreenDimmingRequestHandler = (config: ScreenDimmingRequestInput) => void;\n\nexport interface ClientInterfaceData {\n HeaderId?: string;\n DescriptionId?: string;\n FaceFilteringEnabled?: \"0\" | \"1\";\n FaceFilteringMultipleFaces?: \"0\" | \"1\";\n ImageEnabled?: \"0\" | \"1\";\n VideoEnabled?: \"0\" | \"1\";\n}\n\nexport interface ClientInterfaceRequestInput {\n effectId: string;\n interfaceControl: InterfaceControl;\n interfaceAction: InterfaceAction;\n data: ClientInterfaceData;\n}\n\nexport type ClientInterfaceRequestHandler = (config: ClientInterfaceRequestInput) => void;\n\nexport interface LensCoreConfig {\n configId: string;\n value:\n | { stringValue: string }\n | { boolValue: boolean }\n | { intValue: number }\n | { longValue: number }\n | { floatValue: number }\n | {\n anyValue: {\n typeUrl: string;\n value: Uint8Array | ArrayBuffer;\n };\n };\n}\n\nexport type SetPreloadedConfigurationInput = Array<LensCoreConfig>;\n\nexport interface SetAllSoundsMutedInput {\n muted: boolean;\n fade: boolean;\n}\n\nexport interface SetDeviceClassInput {\n deviceClass: DeviceClass;\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SetAudioParametersInput {\n parameters: {\n numChannels?: number;\n sampleRate?: number;\n };\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface SystemFont {\n name: string;\n data: Uint8Array | ArrayBuffer;\n}\n\nexport interface SetSystemFontsInput {\n fonts: SystemFont[]\n}\nexport interface ProcessAudioSampleBufferInput {\n input: Float32Array[] | ArrayBuffer[];\n output?: Float32Array[] | ArrayBuffer[];\n onSuccess?: DefaultEventHandler;\n onFailure?: DefaultErrorHandler;\n}\n\nexport interface InitialEmscriptenModule {\n mainScriptUrlOrBlob: string;\n compiledModule?: WebAssembly.Module;\n pthreadWorkerScriptUrl?: string;\n instantiateWasm?: (importObject: WebAssembly.Imports, receiveInstance: ReceiveInstanceCallback) => void;\n print?: (text: string) => void;\n printErr?: (text: string) => void;\n}\n\nexport interface LensCoreModule extends InitialEmscriptenModule {\n AssetType: {\n RemoteMediaByUrl: AssetType;\n DeviceDependent: AssetType;\n Static: AssetType;\n URL: AssetType;\n BitmojiDynamicAsset: AssetType;\n };\n\n CanvasType: {\n None: CanvasType;\n Preview: CanvasType;\n Capture: CanvasType;\n All: CanvasType;\n };\n\n LensApiVisibility: {\n Dev: LensApiVisibility;\n Private: LensApiVisibility;\n Public: LensApiVisibility;\n };\n\n DeviceClass: {\n Undefined: DeviceClass;\n BarelyWorking: DeviceClass;\n LowEnd: DeviceClass;\n MidEnd: DeviceClass;\n HighEnd: DeviceClass;\n };\n\n RenderLoopMode: {\n SetTimeout: RenderLoopMode;\n RequestAnimationFrame: RenderLoopMode;\n };\n\n UserDataAccess: {\n Restricted: UserDataAccess;\n Unrestricted: UserDataAccess;\n };\n\n InterfaceControl: {\n ToggleCameraButton: InterfaceControl;\n ImagePicker: InterfaceControl;\n Hint: InterfaceControl;\n Modal: InterfaceControl;\n LinkBitmojiCallToAction: InterfaceControl;\n SnapButton: InterfaceControl;\n PlayButton: InterfaceControl;\n All: InterfaceControl;\n ExitFullScreenButton: InterfaceControl;\n MemoriesButton: InterfaceControl;\n LensAttachmentButton: InterfaceControl;\n ReverseCamera: InterfaceControl;\n };\n\n InterfaceAction: {\n EnableHighlight: InterfaceAction;\n DisableHighlight: InterfaceAction;\n Trigger: InterfaceAction;\n Show: InterfaceAction;\n Hide: InterfaceAction;\n };\n\n ExternalMediaOrientation: {\n CW0: ExternalMediaOrientation;\n CW90: ExternalMediaOrientation;\n CW180: ExternalMediaOrientation;\n CW270: ExternalMediaOrientation;\n };\n\n ErrorType: {\n LensDeserialization: ErrorType;\n Validation: ErrorType;\n Uncategorized: ErrorType;\n LensExecution: ErrorType;\n Abort: ErrorType;\n };\n\n initialize: (config: InitializeInput) => void;\n processFrame: (config: ProcessFrameInput) => void;\n addLens: (config: AddLensInput) => void;\n replaceLenses: (config: ReplaceLensesInput) => void;\n removeLens: (config: RemoveLensInput) => void;\n clearAllLenses: (config: ClearAllLensesInput) => void;\n teardown: (config: TeardownInput) => void;\n useMediaElement: (config: UseMediaElementInput) => void;\n setFPSLimit: (config: SetFpsLimitInput) => void;\n setRenderLoopMode: (config: SetRenderLoopInput) => void;\n getCoreVersion: () => number;\n playCanvas: (input: PlayCanvasInput) => void;\n pauseCanvas: (input: PauseCanvasInput) => void;\n getOutputCanvases: () => GetOutputCanvasesOutput;\n setRenderSize: (input: SetRenderSizeInput) => void;\n startProfiling: () => void;\n endProfiling: () => void;\n setInputTransform: (config: SetInputTransformInput) => void;\n registerUriListener: (scheme: string, route: string, listener: UriListener) => void;\n provideUriResponse: (requestId: string, response: UriResponse) => void;\n setRemoteAssetsProvider: (provider: SetRemoteAssetsProviderInput) => void;\n provideRemoteAssetsResponse: (assetResponse: ProvideRemoteAssetsResponseInput) => void;\n setRemoteAssetsUploadHandler: (provider: SetRemoteAssetsUploadHandlerInput) => void;\n provideRemoteAssetsUploadResponse: (assetResponse: ProvideRemoteAssetsUploadResponseInput) => void;\n registerShowHintCallback: (callback: ShowHintCallback) => void;\n registerHideHintCallback: (callback: HideHintCallback) => void;\n registerSavePersistentStoreCallback: (callback: SavePersistentStoreCallback) => void;\n imageToYuvBuffer: (config: ImageToYuvBufferInput) => void;\n yuvBufferToBitmap: (config: YuvBufferToBitmapInput) => void;\n setOnFrameProcessedCallback: (config: SetOnFrameProcessedInput) => void;\n setInterfaceControlVisibility: (config: SetInterfaceControlVisibilityInput) => void;\n handleClientInterfaceAction: (config: HandleClientInterfaceActionInput) => void;\n provideExternalImage: (config: ProvideExternalImageInput) => void;\n provideExternalVideo: (config: ProvideExternalVideoInput) => void;\n setScreenDimmingRequestHandler: (callback: ScreenDimmingRequestHandler) => void;\n setClientInterfaceRequestHandler: (callback: ClientInterfaceRequestHandler) => void;\n setPreloadedConfiguration: (config: SetPreloadedConfigurationInput) => void;\n setAllSoundsMuted: (config: SetAllSoundsMutedInput) => void;\n setDeviceClass: (config: SetDeviceClassInput) => void;\n setSystemFonts: (config: SetSystemFontsInput) => void;\n setAudioParameters: (config: SetAudioParametersInput) => void;\n processAudioSampleBuffer: (config: ProcessAudioSampleBufferInput) => void;\n}\n\ndeclare global {\n // This function is provided by the Emscripten glue file and responsible for initialization, will be fullfiled\n // when everything is loaded and it is safe to call compiled functions\n // eslint-disable-next-line max-len\n // https://emscripten.org/docs/getting_started/FAQ.html#how-can-i-tell-when-the-page-is-fully-loaded-and-it-is-safe-to-call-compiled-functions\n // Function is defined by the LensCore web assembly\n // eslint-disable-next-line max-len\n // https://github.sc-corp.net/Snapchat/LensCore/blob/6715da8c877d593e4fe133f4145eb3022204525d/Platforms/WebAssembly/LookserySDK/CMakeLists.txt#L65\n function createLensesModule(module: InitialEmscriptenModule): Promise<InitialEmscriptenModule & LensCoreModule>;\n}\n"]}
@@ -88,7 +88,7 @@ export const lensCoreFactory = Injectable("lensCore", [defaultFetchHandlerFactor
88
88
  const glueScript = yield handler(lensCoreJS).then((r) => r.blob());
89
89
  lensCoreJS = URL.createObjectURL(glueScript);
90
90
  }
91
- yield loadScript(lensCoreJS);
91
+ const scriptElement = yield loadScript(lensCoreJS);
92
92
  const lensCore = yield new Promise((resolve, reject) => {
93
93
  let initialModule;
94
94
  // will trigger WASM initialization and data loading,
@@ -112,6 +112,8 @@ export const lensCoreFactory = Injectable("lensCore", [defaultFetchHandlerFactor
112
112
  },
113
113
  }));
114
114
  });
115
+ // now when we have LensCore WASM in memory we can release the script element
116
+ scriptElement.remove();
115
117
  // print warning if loaded version differs from hardcoded one
116
118
  if (lensCoreWasm.version != `${lensCore.getCoreVersion()}`) {
117
119
  logger.warn(`Loaded LensCore version (${lensCore.getCoreVersion()}) differs from expected one (${lensCoreWasm.version})`);
@@ -1 +1 @@
1
- {"version":3,"file":"lensCoreFactory.js","sourceRoot":"","sources":["../../../src/lens-core-module/loader/lensCoreFactory.ts"],"names":[],"mappings":";AAAA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xC,mCAAmC;QACnC,mKAAmK;QACnK,MAAM,UAAU,GAAG,UAAU,CAAC,kBAAkB,CAC5C,CAAC,aAAa,GAAG;YACb,kEAAkE;YAClE,mBAAmB,EAAE,UAAU;YAC/B,4DAA4D;YAC5D,eAAe,EAAE,CAAC,YAAY,EAAE,eAAe,EAAE,EAAE;gBAC/C,WAAW,CAAC,oBAAoB,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE,YAAY,CAAC;qBAChE,IAAI,CAAC,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE;oBAChC,eAAe,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;oBAClC,2CAA2C;oBAC3C,aAAa,CAAC,cAAc,GAAG,MAAM,CAAC;oBACtC,OAAO,CAAC,UAAU,CAAC,CAAC;gBACxB,CAAC,CAAC;qBACD,KAAK,CAAC,MAAM,CAAC,CAAC;YACvB,CAAC;SACJ,CAAC,CACL,CAAC;IACN,CAAC,CAAC,CAAC;IAEH,6DAA6D;IAC7D,IAAI,YAAY,CAAC,OAAO,IAAI,GAAG,QAAQ,CAAC,cAAc,EAAE,EAAE,EAAE;QACxD,MAAM,CAAC,IAAI,CACP,4BAA4B,QAAQ,CAAC,cAAc,EAAE,gCACjD,YAAY,CAAC,OACjB,GAAG,CACN,CAAC;KACL;IAED,OAAO,QAAQ,CAAC;AACpB,CAAC,CAAA,CACJ,CAAC","sourcesContent":["import { simd, exceptions } from \"wasm-feature-detect\";\nimport lensCoreWasm from \"../../lensCoreWasmVersions.json\";\nimport { loadScript } from \"../../common\";\nimport { CameraKitConfiguration, configurationToken } from \"../../configuration\";\nimport { Injectable } from \"../../dependency-injection/Injectable\";\nimport { defaultFetchHandlerFactory, FetchHandler } from \"../../handlers/defaultFetchHandler\";\nimport { InitialEmscriptenModule, LensCoreModule } from \"../generated-types\";\nimport { getLogger } from \"../../logger/logger\";\nimport { cameraKitUserAgent } from \"../../common/cameraKitUserAgent\";\n\nconst logger = getLogger(\"lensCoreFactory\");\n\nconst wasmAssets = [\"LensCoreWebAssembly.js\", \"LensCoreWebAssembly.wasm\"];\n\nconst findMatch = (regex: RegExp, strings: string[]) => strings.find((s) => regex.test(s));\n\nconst PlatformFeatures = {\n Default: 0,\n Simd: 0b01,\n Exceptions: 0b10,\n};\n\nconst platformFeaturesToFlavour = {\n [PlatformFeatures.Exceptions | PlatformFeatures.Simd]: \"rel-simd-neh\",\n [PlatformFeatures.Simd]: \"release-simd\",\n [PlatformFeatures.Exceptions]: \"rel-neh\",\n [PlatformFeatures.Default]: \"release\",\n};\n\n/**\n * Returns a list of URLs for resources which will be fetched during {@link bootstrapCameraKit}.\n *\n * When CameraKit is used on a website, these URLs much be reachable in order for CameraKit to be successfully\n * bootstrapped.\n *\n * @param endpointOverride Optional endpoint override to load the assets from.\n * @returns An array of asset URLs.\n *\n * @category Bootstrapping and Configuration\n */\nexport async function getRequiredBootstrapURLs(endpointOverride?: string): Promise<string[]> {\n // If we have an endpoint override, remove trailing `/` so we can construct a valid URL.\n const endpoint = endpointOverride?.replace(/[\\/]+$/, \"\");\n\n let [simdFeature, exceptionsFeature] = await Promise.all([\n simd().then((supported) => (supported ? PlatformFeatures.Simd : PlatformFeatures.Default)),\n exceptions().then((supported) => (supported ? PlatformFeatures.Exceptions : PlatformFeatures.Default)),\n ]);\n\n // Although Safari 16.4 reports SIMD support, LensCore encounters rendering bugs when using SIMD in Safari 16.4.\n // Therefore, we have made the decision to disable SIMD for now until Safari stabilizes the feature.\n const { brand } = cameraKitUserAgent.browser;\n if (brand === \"Safari\") simdFeature = PlatformFeatures.Default;\n\n const flavor = platformFeaturesToFlavour[simdFeature | exceptionsFeature];\n\n const version = lensCoreWasm.version;\n const buildNumber = lensCoreWasm.buildNumber;\n return wasmAssets.map((asset) => {\n if (endpoint) return `${endpoint}/${asset}`;\n const { origin, pathname, search } = new URL(lensCoreWasm.baseUrl);\n return `${origin}${pathname}/${version}/${buildNumber}/${flavor}/${asset}${search}`;\n });\n}\n\n/**\n * This component is responsible for:\n * 1) Loading LensCore WebAssembly (WASM) assets\n * 2) Using the WASM assets to initialize the LensCore WASM module\n *\n * By default, WASM assets will be loaded from the Bolt CDN – but if `endpoint` is provided, assets will be loaded\n * using it as a base URL.\n *\n * @internal\n */\nexport const lensCoreFactory = Injectable(\n \"lensCore\",\n [defaultFetchHandlerFactory.token, configurationToken] as const,\n async (handler: FetchHandler, { lensCoreOverrideUrls, wasmEndpointOverride }: CameraKitConfiguration) => {\n let lensCoreJS: string;\n let lensCoreWASM: string;\n\n if (lensCoreOverrideUrls) {\n lensCoreJS = lensCoreOverrideUrls.js;\n lensCoreWASM = lensCoreOverrideUrls.wasm;\n } else {\n const endpointOverride = wasmEndpointOverride ?? undefined;\n const assetURLs = await getRequiredBootstrapURLs(endpointOverride);\n\n lensCoreJS = findMatch(/\\.js/, assetURLs) ?? \"\";\n lensCoreWASM = findMatch(/\\.wasm/, assetURLs) ?? \"\";\n\n if (!lensCoreJS || !lensCoreWASM) {\n throw new Error(\n `Cannot fetch required LensCore assets. Either the JS or WASM filename is missing from ` +\n `this list: ${assetURLs}.`\n );\n }\n\n // Fetching here and creating an Object URL lets LensCore optimized loading itself in a WebWorker,\n // otherwise the glue script would need to be downloaded again.\n const glueScript = await handler(lensCoreJS).then((r) => r.blob());\n lensCoreJS = URL.createObjectURL(glueScript);\n }\n\n await loadScript(lensCoreJS);\n\n const lensCore = await new Promise<InitialEmscriptenModule & LensCoreModule>((resolve, reject) => {\n let initialModule: Partial<InitialEmscriptenModule>;\n // will trigger WASM initialization and data loading,\n // after completion it will be safe to call imported WASM functions\n // More about emscripten initialization:\n // eslint-disable-next-line max-len\n // https://emscripten.org/docs/getting_started/FAQ.html?highlight=modularize#how-can-i-tell-when-the-page-is-fully-loaded-and-it-is-safe-to-call-compiled-functions\n const moduleInit = globalThis.createLensesModule(\n (initialModule = {\n // url will be used for loading glue JS during Worker inialization\n mainScriptUrlOrBlob: lensCoreJS,\n // will be triggered by Emscripten during the initialization\n instantiateWasm: (importObject, receiveInstance) => {\n WebAssembly.instantiateStreaming(handler(lensCoreWASM), importObject)\n .then(function ({ instance, module }) {\n receiveInstance(instance, module);\n // compiled module will be reused in Worker\n initialModule.compiledModule = module;\n resolve(moduleInit);\n })\n .catch(reject);\n },\n })\n );\n });\n\n // print warning if loaded version differs from hardcoded one\n if (lensCoreWasm.version != `${lensCore.getCoreVersion()}`) {\n logger.warn(\n `Loaded LensCore version (${lensCore.getCoreVersion()}) differs from expected one (${\n lensCoreWasm.version\n })`\n );\n }\n\n return lensCore;\n }\n);\n"]}
1
+ {"version":3,"file":"lensCoreFactory.js","sourceRoot":"","sources":["../../../src/lens-core-module/loader/lensCoreFactory.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,YAAY,MAAM,iCAAiC,CAAC;AAC3D,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAA0B,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,MAAM,uCAAuC,CAAC;AACnE,OAAO,EAAE,0BAA0B,EAAgB,MAAM,oCAAoC,CAAC;AAE9F,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAErE,MAAM,MAAM,GAAG,SAAS,CAAC,iBAAiB,CAAC,CAAC;AAE5C,MAAM,UAAU,GAAG,CAAC,wBAAwB,EAAE,0BAA0B,CAAC,CAAC;AAE1E,MAAM,SAAS,GAAG,CAAC,KAAa,EAAE,OAAiB,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AAE3F,MAAM,gBAAgB,GAAG;IACrB,OAAO,EAAE,CAAC;IACV,IAAI,EAAE,IAAI;IACV,UAAU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AI,CACP,4BAA4B,QAAQ,CAAC,cAAc,EAAE,gCACjD,YAAY,CAAC,OACjB,GAAG,CACN,CAAC;KACL;IAED,OAAO,QAAQ,CAAC;AACpB,CAAC,CAAA,CACJ,CAAC","sourcesContent":["import { simd, exceptions } from \"wasm-feature-detect\";\nimport lensCoreWasm from \"../../lensCoreWasmVersions.json\";\nimport { loadScript } from \"../../common\";\nimport { CameraKitConfiguration, configurationToken } from \"../../configuration\";\nimport { Injectable } from \"../../dependency-injection/Injectable\";\nimport { defaultFetchHandlerFactory, FetchHandler } from \"../../handlers/defaultFetchHandler\";\nimport { InitialEmscriptenModule, LensCoreModule } from \"../generated-types\";\nimport { getLogger } from \"../../logger/logger\";\nimport { cameraKitUserAgent } from \"../../common/cameraKitUserAgent\";\n\nconst logger = getLogger(\"lensCoreFactory\");\n\nconst wasmAssets = [\"LensCoreWebAssembly.js\", \"LensCoreWebAssembly.wasm\"];\n\nconst findMatch = (regex: RegExp, strings: string[]) => strings.find((s) => regex.test(s));\n\nconst PlatformFeatures = {\n Default: 0,\n Simd: 0b01,\n Exceptions: 0b10,\n};\n\nconst platformFeaturesToFlavour = {\n [PlatformFeatures.Exceptions | PlatformFeatures.Simd]: \"rel-simd-neh\",\n [PlatformFeatures.Simd]: \"release-simd\",\n [PlatformFeatures.Exceptions]: \"rel-neh\",\n [PlatformFeatures.Default]: \"release\",\n};\n\n/**\n * Returns a list of URLs for resources which will be fetched during {@link bootstrapCameraKit}.\n *\n * When CameraKit is used on a website, these URLs much be reachable in order for CameraKit to be successfully\n * bootstrapped.\n *\n * @param endpointOverride Optional endpoint override to load the assets from.\n * @returns An array of asset URLs.\n *\n * @category Bootstrapping and Configuration\n */\nexport async function getRequiredBootstrapURLs(endpointOverride?: string): Promise<string[]> {\n // If we have an endpoint override, remove trailing `/` so we can construct a valid URL.\n const endpoint = endpointOverride?.replace(/[\\/]+$/, \"\");\n\n let [simdFeature, exceptionsFeature] = await Promise.all([\n simd().then((supported) => (supported ? PlatformFeatures.Simd : PlatformFeatures.Default)),\n exceptions().then((supported) => (supported ? PlatformFeatures.Exceptions : PlatformFeatures.Default)),\n ]);\n\n // Although Safari 16.4 reports SIMD support, LensCore encounters rendering bugs when using SIMD in Safari 16.4.\n // Therefore, we have made the decision to disable SIMD for now until Safari stabilizes the feature.\n const { brand } = cameraKitUserAgent.browser;\n if (brand === \"Safari\") simdFeature = PlatformFeatures.Default;\n\n const flavor = platformFeaturesToFlavour[simdFeature | exceptionsFeature];\n\n const version = lensCoreWasm.version;\n const buildNumber = lensCoreWasm.buildNumber;\n return wasmAssets.map((asset) => {\n if (endpoint) return `${endpoint}/${asset}`;\n const { origin, pathname, search } = new URL(lensCoreWasm.baseUrl);\n return `${origin}${pathname}/${version}/${buildNumber}/${flavor}/${asset}${search}`;\n });\n}\n\n/**\n * This component is responsible for:\n * 1) Loading LensCore WebAssembly (WASM) assets\n * 2) Using the WASM assets to initialize the LensCore WASM module\n *\n * By default, WASM assets will be loaded from the Bolt CDN – but if `endpoint` is provided, assets will be loaded\n * using it as a base URL.\n *\n * @internal\n */\nexport const lensCoreFactory = Injectable(\n \"lensCore\",\n [defaultFetchHandlerFactory.token, configurationToken] as const,\n async (handler: FetchHandler, { lensCoreOverrideUrls, wasmEndpointOverride }: CameraKitConfiguration) => {\n let lensCoreJS: string;\n let lensCoreWASM: string;\n\n if (lensCoreOverrideUrls) {\n lensCoreJS = lensCoreOverrideUrls.js;\n lensCoreWASM = lensCoreOverrideUrls.wasm;\n } else {\n const endpointOverride = wasmEndpointOverride ?? undefined;\n const assetURLs = await getRequiredBootstrapURLs(endpointOverride);\n\n lensCoreJS = findMatch(/\\.js/, assetURLs) ?? \"\";\n lensCoreWASM = findMatch(/\\.wasm/, assetURLs) ?? \"\";\n\n if (!lensCoreJS || !lensCoreWASM) {\n throw new Error(\n `Cannot fetch required LensCore assets. Either the JS or WASM filename is missing from ` +\n `this list: ${assetURLs}.`\n );\n }\n\n // Fetching here and creating an Object URL lets LensCore optimized loading itself in a WebWorker,\n // otherwise the glue script would need to be downloaded again.\n const glueScript = await handler(lensCoreJS).then((r) => r.blob());\n lensCoreJS = URL.createObjectURL(glueScript);\n }\n\n const scriptElement = await loadScript(lensCoreJS);\n\n const lensCore = await new Promise<InitialEmscriptenModule & LensCoreModule>((resolve, reject) => {\n let initialModule: Partial<InitialEmscriptenModule>;\n // will trigger WASM initialization and data loading,\n // after completion it will be safe to call imported WASM functions\n // More about emscripten initialization:\n // eslint-disable-next-line max-len\n // https://emscripten.org/docs/getting_started/FAQ.html?highlight=modularize#how-can-i-tell-when-the-page-is-fully-loaded-and-it-is-safe-to-call-compiled-functions\n const moduleInit = globalThis.createLensesModule(\n (initialModule = {\n // url will be used for loading glue JS during Worker inialization\n mainScriptUrlOrBlob: lensCoreJS,\n // will be triggered by Emscripten during the initialization\n instantiateWasm: (importObject, receiveInstance) => {\n WebAssembly.instantiateStreaming(handler(lensCoreWASM), importObject)\n .then(function ({ instance, module }) {\n receiveInstance(instance, module);\n // compiled module will be reused in Worker\n initialModule.compiledModule = module;\n resolve(moduleInit);\n })\n .catch(reject);\n },\n })\n );\n });\n\n // now when we have LensCore WASM in memory we can release the script element\n scriptElement.remove();\n\n // print warning if loaded version differs from hardcoded one\n if (lensCoreWasm.version != `${lensCore.getCoreVersion()}`) {\n logger.warn(\n `Loaded LensCore version (${lensCore.getCoreVersion()}) differs from expected one (${\n lensCoreWasm.version\n })`\n );\n }\n\n return lensCore;\n }\n);\n"]}
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "214",
3
- "buildNumber": "22",
4
- "baseUrl": "https://cf-st.sc-cdn.net/d/NhOZEMtsN1zJBWzj2dabN?go=IgsKCTIBBEgBUFxgAQ%3D%3D&uc=9"
2
+ "version": "225",
3
+ "buildNumber": "64",
4
+ "baseUrl": "https://cf-st.sc-cdn.net/d/JigrWXPgfeH1cbTxyo1FM?go=IgsKCTIBBEgBUFxgAQ%3D%3D&uc=92"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The factory creates new logEntries subject.
3
3
  *
4
- * NOTE: The factory calls `initLogger()`, which overrides the global `logEntrySubject`.
4
+ * NOTE: The factory calls `resetLogger()`, which overrides the global `logEntrySubject`.
5
5
  * This is currently necessary to avoid sharing the same subject between multiple `CameraKit` instances.
6
6
  * In the future, we may throw an error when bootstrapping more than a single `CameraKit`,
7
7
  * that will allow us to have a single log entry subject.
@@ -1,14 +1,14 @@
1
1
  import { Injectable } from "../dependency-injection/Injectable";
2
- import { initLogger } from "./logger";
2
+ import { resetLogger } from "./logger";
3
3
  /**
4
4
  * The factory creates new logEntries subject.
5
5
  *
6
- * NOTE: The factory calls `initLogger()`, which overrides the global `logEntrySubject`.
6
+ * NOTE: The factory calls `resetLogger()`, which overrides the global `logEntrySubject`.
7
7
  * This is currently necessary to avoid sharing the same subject between multiple `CameraKit` instances.
8
8
  * In the future, we may throw an error when bootstrapping more than a single `CameraKit`,
9
9
  * that will allow us to have a single log entry subject.
10
10
  *
11
11
  * @internal
12
12
  */
13
- export const logEntriesFactory = Injectable("logEntries", () => initLogger().asObservable());
13
+ export const logEntriesFactory = Injectable("logEntries", () => resetLogger().asObservable());
14
14
  //# sourceMappingURL=logEntries.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"logEntries.js","sourceRoot":"","sources":["../../src/logger/logEntries.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAChE,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAEtC;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,UAAU,CAAC,YAAY,EAAE,GAAG,EAAE,CAAC,UAAU,EAAE,CAAC,YAAY,EAAE,CAAC,CAAC","sourcesContent":["import { Injectable } from \"../dependency-injection/Injectable\";\nimport { initLogger } from \"./logger\";\n\n/**\n * The factory creates new logEntries subject.\n *\n * NOTE: The factory calls `initLogger()`, which overrides the global `logEntrySubject`.\n * This is currently necessary to avoid sharing the same subject between multiple `CameraKit` instances.\n * In the future, we may throw an error when bootstrapping more than a single `CameraKit`,\n * that will allow us to have a single log entry subject.\n *\n * @internal\n */\nexport const logEntriesFactory = Injectable(\"logEntries\", () => initLogger().asObservable());\n"]}
1
+ {"version":3,"file":"logEntries.js","sourceRoot":"","sources":["../../src/logger/logEntries.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAEvC;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,UAAU,CAAC,YAAY,EAAE,GAAG,EAAE,CAAC,WAAW,EAAE,CAAC,YAAY,EAAE,CAAC,CAAC","sourcesContent":["import { Injectable } from \"../dependency-injection/Injectable\";\nimport { resetLogger } from \"./logger\";\n\n/**\n * The factory creates new logEntries subject.\n *\n * NOTE: The factory calls `resetLogger()`, which overrides the global `logEntrySubject`.\n * This is currently necessary to avoid sharing the same subject between multiple `CameraKit` instances.\n * In the future, we may throw an error when bootstrapping more than a single `CameraKit`,\n * that will allow us to have a single log entry subject.\n *\n * @internal\n */\nexport const logEntriesFactory = Injectable(\"logEntries\", () => resetLogger().asObservable());\n"]}
@@ -12,10 +12,15 @@ export declare const logLevelMap: {
12
12
  debug: number;
13
13
  };
14
14
  /**
15
- * Initializes new logger subject.
15
+ * Initializes a new logger subject.
16
+ *
17
+ * Note: currently only one `CameraKit` instance is allowed to listen to log messages at a time, therefore that is
18
+ * necessary to avoid sharing the same subject between multiple `CameraKit` instances by calling`resetLogger()`.
19
+ * Also, `resetLogger()` should be called when there is no interest in logged messages.
20
+ * This allows the previous logEntriesSubject to be GCec.
16
21
  * @internal
17
22
  */
18
- export declare function initLogger(): Subject<LogEntry>;
23
+ export declare function resetLogger(): Subject<LogEntry>;
19
24
  export interface LogEntry {
20
25
  time: Date;
21
26
  module: string;