@snap/camera-kit 0.7.0 → 0.9.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 (245) hide show
  1. package/docs/html/assets/main.js +57 -53
  2. package/docs/html/assets/search.js +1 -1
  3. package/docs/html/assets/style.css +504 -362
  4. package/docs/html/classes/CameraKit.html +113 -47
  5. package/docs/html/classes/CameraKitSession.html +202 -142
  6. package/docs/html/classes/CameraKitSource.html +124 -60
  7. package/docs/html/classes/LensPerformanceMeasurement.html +112 -46
  8. package/docs/html/classes/LensPerformanceMetrics.html +97 -32
  9. package/docs/html/classes/LensRepository.html +130 -66
  10. package/docs/html/classes/LensSources.html +98 -32
  11. package/docs/html/classes/Transform2D.html +111 -43
  12. package/docs/html/classes/TypedCustomEvent.html +109 -47
  13. package/docs/html/classes/TypedEventTarget.html +125 -65
  14. package/docs/html/functions/Injectable.html +113 -120
  15. package/docs/html/functions/bootstrapCameraKit.html +100 -104
  16. package/docs/html/functions/createExtension.html +90 -94
  17. package/docs/html/functions/createImageSource.html +90 -93
  18. package/docs/html/functions/createMediaStreamSource.html +90 -93
  19. package/docs/html/functions/createUserMediaSource.html +92 -96
  20. package/docs/html/functions/createVideoSource.html +90 -93
  21. package/docs/html/functions/estimateLensPerformance.html +88 -92
  22. package/docs/html/functions/getRequiredBootstrapURLs.html +90 -94
  23. package/docs/html/functions/lensSourcesFactory.html +88 -91
  24. package/docs/html/functions/uriHandlersFactory.html +88 -91
  25. package/docs/html/index.html +134 -170
  26. package/docs/html/interfaces/CameraKitBootstrapConfiguration.html +115 -49
  27. package/docs/html/interfaces/CameraKitSourceSubscriber.html +111 -45
  28. package/docs/html/interfaces/ComputedFrameMetrics.html +98 -32
  29. package/docs/html/interfaces/CreateSessionOptions.html +95 -29
  30. package/docs/html/interfaces/EstimatedLensPerformance.html +98 -32
  31. package/docs/html/interfaces/Lens.html +115 -49
  32. package/docs/html/interfaces/LensSource.html +107 -41
  33. package/docs/html/interfaces/MediaStreamSourceOptions.html +94 -28
  34. package/docs/html/interfaces/UriCancelRequest.html +94 -28
  35. package/docs/html/interfaces/UriHandler.html +108 -42
  36. package/docs/html/interfaces/UriRequest.html +106 -40
  37. package/docs/html/interfaces/UriResponse.html +106 -40
  38. package/docs/html/interfaces/VideoSourceOptions.html +90 -24
  39. package/docs/html/modules.html +161 -164
  40. package/docs/html/types/AssetLoader.html +91 -94
  41. package/docs/html/types/AssetTiming.html +85 -88
  42. package/docs/html/types/BenchmarkError.html +85 -88
  43. package/docs/html/types/BootstrapError.html +86 -89
  44. package/docs/html/types/CacheKeyNotFoundError.html +85 -88
  45. package/docs/html/types/CameraKitDeviceInfo.html +87 -90
  46. package/docs/html/types/CameraKitSessionEventListener.html +86 -89
  47. package/docs/html/types/CameraKitSessionEvents.html +88 -91
  48. package/docs/html/types/CameraKitSourceError.html +85 -88
  49. package/docs/html/types/CameraKitSourceInfo.html +85 -88
  50. package/docs/html/types/CameraKitSourceOptions.html +88 -92
  51. package/docs/html/types/ConfigurationError.html +86 -89
  52. package/docs/html/types/Keyboard.html +108 -111
  53. package/docs/html/types/KeyboardEvents.html +86 -89
  54. package/docs/html/types/LegalError.html +85 -88
  55. package/docs/html/types/LensAssetError.html +85 -88
  56. package/docs/html/types/LensContentValidationError.html +85 -88
  57. package/docs/html/types/LensError.html +85 -88
  58. package/docs/html/types/LensExecutionError.html +86 -89
  59. package/docs/html/types/LensImagePickerError.html +85 -88
  60. package/docs/html/types/LensLaunchParams.html +85 -88
  61. package/docs/html/types/LensMetricsEvents.html +86 -89
  62. package/docs/html/types/LensPerformanceCluster.html +85 -88
  63. package/docs/html/types/LensView.html +85 -88
  64. package/docs/html/types/LensWait.html +85 -88
  65. package/docs/html/types/PersistentStoreError.html +85 -88
  66. package/docs/html/types/PlatformNotSupportedError.html +86 -89
  67. package/docs/html/types/PublicContainer.html +85 -88
  68. package/docs/html/types/RenderTarget.html +85 -88
  69. package/docs/html/types/Uri.html +85 -88
  70. package/docs/html/types/UriHandlers.html +86 -89
  71. package/docs/html/types/WebGLError.html +85 -88
  72. package/docs/html/variables/extensionRequestContext.html +85 -88
  73. package/docs/md/README.md +1 -1
  74. package/docs/md/classes/CameraKit.md +1 -1
  75. package/docs/md/classes/CameraKitSession.md +1 -1
  76. package/docs/md/classes/CameraKitSource.md +1 -1
  77. package/docs/md/classes/LensPerformanceMeasurement.md +1 -1
  78. package/docs/md/classes/LensPerformanceMetrics.md +1 -1
  79. package/docs/md/classes/LensRepository.md +3 -3
  80. package/docs/md/classes/LensSources.md +1 -1
  81. package/docs/md/classes/Transform2D.md +3 -1
  82. package/docs/md/classes/TypedCustomEvent.md +1 -1
  83. package/docs/md/classes/TypedEventTarget.md +3 -3
  84. package/docs/md/interfaces/CameraKitBootstrapConfiguration.md +1 -1
  85. package/docs/md/interfaces/CameraKitSourceSubscriber.md +1 -1
  86. package/docs/md/interfaces/ComputedFrameMetrics.md +1 -1
  87. package/docs/md/interfaces/CreateSessionOptions.md +1 -1
  88. package/docs/md/interfaces/EstimatedLensPerformance.md +1 -1
  89. package/docs/md/interfaces/Lens.md +1 -1
  90. package/docs/md/interfaces/LensSource.md +1 -1
  91. package/docs/md/interfaces/MediaStreamSourceOptions.md +1 -1
  92. package/docs/md/interfaces/UriCancelRequest.md +1 -1
  93. package/docs/md/interfaces/UriHandler.md +1 -1
  94. package/docs/md/interfaces/UriRequest.md +1 -1
  95. package/docs/md/interfaces/UriResponse.md +1 -1
  96. package/docs/md/interfaces/VideoSourceOptions.md +1 -1
  97. package/docs/md/modules.md +3 -3
  98. package/lib/CameraKit.d.ts +7 -7
  99. package/lib/__tests__/data.d.ts +1 -1
  100. package/lib/__tests__/deferred.d.ts +1 -1
  101. package/lib/__tests__/jest.matchers.d.ts +1 -1
  102. package/lib/benchmark/estimateLensPerformanceCluster.d.ts +2 -2
  103. package/lib/bootstrapCameraKit.d.ts +1 -1
  104. package/lib/common/cameraKitUserAgent.d.ts +1 -1
  105. package/lib/common/cameraKitUserAgent.js +5 -3
  106. package/lib/common/cameraKitUserAgent.js.map +1 -1
  107. package/lib/common/localization.d.ts +8 -4
  108. package/lib/common/localization.js.map +1 -1
  109. package/lib/common/memoize.d.ts +2 -2
  110. package/lib/common/pageVisibility.js +1 -1
  111. package/lib/common/pageVisibility.js.map +1 -1
  112. package/lib/common/typeguards.d.ts +2 -2
  113. package/lib/common/types.d.ts +2 -2
  114. package/lib/common/validate.js +20 -12
  115. package/lib/common/validate.js.map +1 -1
  116. package/lib/configuration.d.ts +1 -1
  117. package/lib/configuration.js.map +1 -1
  118. package/lib/configurationOverrides.d.ts +1 -1
  119. package/lib/dependency-injection/Container.d.ts +5 -6
  120. package/lib/dependency-injection/Container.js +1 -1
  121. package/lib/dependency-injection/Container.js.map +1 -1
  122. package/lib/dependency-injection/PartialContainer.d.ts +10 -6
  123. package/lib/dependency-injection/PartialContainer.js.map +1 -1
  124. package/lib/dependency-injection/RootServices.d.ts +2 -2
  125. package/lib/dependency-injection/types.d.ts +9 -9
  126. package/lib/dependency-injection/types.js.map +1 -1
  127. package/lib/environment.json +1 -1
  128. package/lib/events/TypedCustomEvent.d.ts +1 -1
  129. package/lib/events/TypedEventTarget.d.ts +2 -2
  130. package/lib/events/scan.d.ts +1 -1
  131. package/lib/events/scan.js +3 -3
  132. package/lib/events/scan.js.map +1 -1
  133. package/lib/extensions/UriHandlers.d.ts +1 -1
  134. package/lib/generated-proto/blizzard/cameraKitEvents.d.ts +4 -4
  135. package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.d.ts +4 -4
  136. package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.js +3 -3
  137. package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.js.map +1 -1
  138. package/lib/generated-proto/pb_schema/camera_kit/v3/export.d.ts +4 -4
  139. package/lib/generated-proto/pb_schema/camera_kit/v3/export.js +9 -9
  140. package/lib/generated-proto/pb_schema/camera_kit/v3/export.js.map +1 -1
  141. package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.d.ts +4 -4
  142. package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.js +2 -2
  143. package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.js.map +1 -1
  144. package/lib/generated-proto/pb_schema/camera_kit/v3/lens.d.ts +4 -4
  145. package/lib/generated-proto/pb_schema/camera_kit/v3/lens.js +17 -17
  146. package/lib/generated-proto/pb_schema/camera_kit/v3/lens.js.map +1 -1
  147. package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.d.ts +4 -4
  148. package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.js +4 -4
  149. package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.js.map +1 -1
  150. package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.d.ts +4 -4
  151. package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.js +3 -3
  152. package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.js.map +1 -1
  153. package/lib/generated-proto/pb_schema/camera_kit/v3/service.d.ts +4 -4
  154. package/lib/generated-proto/pb_schema/camera_kit/v3/service.js +25 -25
  155. package/lib/generated-proto/pb_schema/camera_kit/v3/service.js.map +1 -1
  156. package/lib/generated-proto/pb_schema/cdp/cof/benchmark.d.ts +4 -4
  157. package/lib/generated-proto/pb_schema/cdp/cof/circumstance_service.d.ts +4533 -333
  158. package/lib/generated-proto/pb_schema/cdp/cof/config_request.d.ts +4 -4
  159. package/lib/generated-proto/pb_schema/cdp/cof/config_response.d.ts +572 -32
  160. package/lib/generated-proto/pb_schema/cdp/cof/config_result.d.ts +4 -4
  161. package/lib/generated-proto/pb_schema/cdp/cof/debug_info.d.ts +4 -4
  162. package/lib/generated-proto/pb_schema/common/ruid.d.ts +4 -4
  163. package/lib/generated-proto/pb_schema/common/value.d.ts +4 -4
  164. package/lib/generated-proto/pb_schema/google/api/http.d.ts +4 -4
  165. package/lib/generated-proto/pb_schema/google/protobuf/any.d.ts +4 -4
  166. package/lib/generated-proto/pb_schema/google/protobuf/descriptor.d.ts +4 -4
  167. package/lib/generated-proto/pb_schema/google/protobuf/timestamp.d.ts +4 -4
  168. package/lib/generated-proto/pb_schema/google/protobuf/wrappers.d.ts +4 -4
  169. package/lib/generated-proto/pb_schema/lenses/geocircle.d.ts +4 -4
  170. package/lib/generated-proto/pb_schema/lenses/geopoint.d.ts +4 -4
  171. package/lib/generated-proto/pb_schema/lenses/launch_params.d.ts +4 -4
  172. package/lib/generated-proto/pb_schema/lenses/launchdata.d.ts +4 -4
  173. package/lib/generated-proto/pb_schema/lenses/lures.d.ts +4 -4
  174. package/lib/generated-proto/pb_schema/lenses/persistent_store.d.ts +4 -4
  175. package/lib/generated-proto/pb_schema/lenses/snappable.d.ts +4 -4
  176. package/lib/generated-proto/pb_schema/lenses/user_data.d.ts +4 -4
  177. package/lib/handlers/HandlerChainBuilder.d.ts +3 -3
  178. package/lib/handlers/arrayBufferParsingHandler.d.ts +2 -2
  179. package/lib/handlers/arrayBufferParsingHandler.js.map +1 -1
  180. package/lib/handlers/cameraKitServiceFetchHandlerFactory.d.ts +1 -1
  181. package/lib/handlers/defaultFetchHandler.d.ts +1 -1
  182. package/lib/handlers/headersModifyingFetchHandler.js +5 -1
  183. package/lib/handlers/headersModifyingFetchHandler.js.map +1 -1
  184. package/lib/handlers/noCorsRetryingFetchHandler.js +4 -3
  185. package/lib/handlers/noCorsRetryingFetchHandler.js.map +1 -1
  186. package/lib/handlers/requestStateEmittingHandler.d.ts +2 -2
  187. package/lib/handlers/requestStateEmittingHandler.js.map +1 -1
  188. package/lib/handlers/responseCachingHandler.d.ts +1 -1
  189. package/lib/handlers/responseCachingHandler.js.map +1 -1
  190. package/lib/handlers/retryingHandler.d.ts +7 -0
  191. package/lib/handlers/retryingHandler.js +14 -5
  192. package/lib/handlers/retryingHandler.js.map +1 -1
  193. package/lib/legal/legalPrompt.d.ts +1 -1
  194. package/lib/legal/legalPrompt.js.map +1 -1
  195. package/lib/legal/legalState.d.ts +1 -1
  196. package/lib/legal/legalState.js.map +1 -1
  197. package/lib/lens/Lens.d.ts +1 -1
  198. package/lib/lens/LensLaunchParams.d.ts +2 -2
  199. package/lib/lens/LensRepository.d.ts +7 -8
  200. package/lib/lens/LensRepository.js.map +1 -1
  201. package/lib/lens/assets/LensAssetRepository.d.ts +2 -2
  202. package/lib/lens/assets/LensAssetsProvider.d.ts +1 -1
  203. package/lib/lens/assets/deviceDependentAssetLoader.d.ts +1 -1
  204. package/lib/lens/assets/remoteMediaAssetLoaderFactory.d.ts +1 -1
  205. package/lib/lens/assets/staticAssetLoader.d.ts +1 -1
  206. package/lib/lens-core-module/generated-types.d.ts +29 -29
  207. package/lib/lens-core-module/generated-types.js.map +1 -1
  208. package/lib/lens-core-module/loader/lensCoreFactory.d.ts +1 -1
  209. package/lib/lensCoreWasmVersions.json +3 -3
  210. package/lib/logger/logger.d.ts +2 -2
  211. package/lib/media-sources/CameraKitSource.d.ts +3 -3
  212. package/lib/media-sources/CameraKitSource.js.map +1 -1
  213. package/lib/media-sources/FunctionSource.d.ts +1 -1
  214. package/lib/metrics/businessEventsReporter.d.ts +4 -4
  215. package/lib/metrics/businessEventsReporter.js.map +1 -1
  216. package/lib/metrics/metricsEventTarget.d.ts +5 -5
  217. package/lib/metrics/metricsHandler.d.ts +1 -1
  218. package/lib/metrics/operationalMetricsReporter.d.ts +2 -2
  219. package/lib/metrics/reporters/reportBenchmarks.d.ts +1 -1
  220. package/lib/metrics/reporters/reportLegalState.d.ts +1 -1
  221. package/lib/metrics/reporters/reportLensAndAssetDownload.d.ts +4 -4
  222. package/lib/metrics/reporters/reportLensValidationFailed.d.ts +1 -1
  223. package/lib/metrics/reporters/reportLensView.d.ts +1 -1
  224. package/lib/metrics/reporters/reportLensView.js +1 -1
  225. package/lib/metrics/reporters/reportLensView.js.map +1 -1
  226. package/lib/metrics/reporters/reportLensWait.d.ts +1 -1
  227. package/lib/metrics/reporters/reportUserSession.d.ts +1 -1
  228. package/lib/namedErrors.d.ts +17 -17
  229. package/lib/persistence/Persistence.d.ts +1 -1
  230. package/lib/remote-configuration/cofHandler.d.ts +1 -1
  231. package/lib/remote-configuration/cofHandler.js +18 -5
  232. package/lib/remote-configuration/cofHandler.js.map +1 -1
  233. package/lib/session/CameraKitSession.d.ts +1 -1
  234. package/lib/session/CameraKitSession.js.map +1 -1
  235. package/lib/session/CameraKitSessionEvents.d.ts +3 -3
  236. package/lib/session/LensKeyboard.d.ts +2 -2
  237. package/lib/session/LensPerformanceMetrics.js.map +1 -1
  238. package/lib/session/lensState.d.ts +2 -2
  239. package/lib/session/lensState.js.map +1 -1
  240. package/lib/session/sessionState.d.ts +1 -1
  241. package/lib/transforms/Transform2D.js +2 -1
  242. package/lib/transforms/Transform2D.js.map +1 -1
  243. package/package.json +14 -14
  244. package/docs/html/assets/widgets.png +0 -0
  245. package/docs/html/assets/widgets@2x.png +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"reportLensView.js","sourceRoot":"","sources":["../../../src/metrics/reporters/reportLensView.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACjH,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,uCAAuC,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,EAAsB,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AACtF,OAAO,EAAoB,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAE3F,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,gCAAgC,EAA8B,MAAM,+BAA+B,CAAC;AAC7G,OAAO,EAA0B,kBAAkB,EAAE,M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AAe,CAAC,mCAAI;gBACzC,OAAO,EAAE,CAAC;gBACV,iBAAiB,EAAE,SAAS;aAC/B,CAAC;YACF,MAAM,QAAQ,GAAa;gBACvB,IAAI,EAAE,UAAU;gBAChB,aAAa;gBACb,MAAM;gBACN,MAAM;gBACN,4BAA4B;gBAC5B,4BAA4B;gBAC5B,wFAAwF;gBACxF,gBAAgB,EAAE,CAAC;gBACnB,WAAW;gBACX,6FAA6F;gBAC7F,qCAAqC;gBACrC,8CAA8C;gBAC9C,oBAAoB,EAAE,KAAK;gBAC3B,sBAAsB,EAAE,KAAK;gBAC7B,kBAAkB;gBAClB,iBAAiB;aACpB,CAAC;YAEF,kBAAkB,CAAC,aAAa,CAAC,IAAI,gBAAgB,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC,CAAC;YAE7E,gDAAgD;YAChD,kFAAkF;YAClF,EAAE;YACF,gGAAgG;YAChG,4EAA4E;YAC5E,IAAI,aAAa,GAAG,CAAC;gBACjB,0BAA0B,CAAC,KAAK,CAAC,2BAA2B,EAAE,aAAa,GAAG,IAAI,CAAC,CAAC;YACxF,0BAA0B,CAAC,KAAK,CAC5B,sBAAsB,EACtB,4BAA4B,EAC5B,IAAI,GAAG,CAAC,CAAC,CAAC,qBAAqB,EAAE,kBAAkB,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CACpE,CAAC;QACN,CAAC,CAAA;KACJ,CAAC,CAAC;AACX,CAAC,CACJ,CAAC","sourcesContent":["import { combineLatestWith, filter, map, merge, mergeMap, of, raceWith, switchMap, take, takeUntil } from \"rxjs\";\nimport { forActions, inStates, isState } from \"@snap/state-management\";\nimport { Injectable } from \"../../dependency-injection/Injectable\";\nimport { TypedCustomEvent } from \"../../events/TypedCustomEvent\";\nimport { MetricsEventTarget, metricsEventTargetFactory } from \"../metricsEventTarget\";\nimport { CameraKitSession, cameraKitSessionFactory } from \"../../session/CameraKitSession\";\nimport { MakeTaggedBusinessEvent } from \"../businessEventsReporter\";\nimport { getTimeMs } from \"../../common/time\";\nimport { operationalMetricReporterFactory, OperationalMetricsReporter } from \"../operationalMetricsReporter\";\nimport { CameraKitConfiguration, configurationToken } from \"../../configuration\";\nimport { lensStateFactory, LensState } from \"../../session/lensState\";\nimport { SessionState, sessionStateFactory } from \"../../session/sessionState\";\n\n// We ignore short-duration lens views.\n//\n// The value is documented here:\n// https://docs.google.com/document/d/1-kSzFWCWw9Qo3D08FR1_cqeHTsUtk9p3p3uOptzWDTY/edit#heading=h.q5liip76r9lt\nconst viewTimeThresholdSec = 0.1;\n\n/**\n * The LensView metric is emitted after a lens has been viewed (for longer than 100ms), when the lens is turned off.\n *\n * It contains information about rendering performance.\n *\n * Notes:\n * - If the page is hidden (e.g. user switches to a different tab, or application, or closes the tab, or closes the\n * browser, navigates to a new page, refreshes, etc.) this metric will be emitted at that time. This is to ensure\n * we don't lose the metric if the page is closed.\n * - If the page is hidden and then made visible again later (e.g. user switches to a different tab, then back), we\n * will begin measuring a new LensView. That is, we will not capture the time when the page is hidden even if the\n * lens is still rendering in the background.\n *\n * @category Lenses\n * @category Metrics\n */\n// This type corresponds to the internal CameraKitLensSwipe event, described here:\n// https://docs.google.com/document/d/1-kSzFWCWw9Qo3D08FR1_cqeHTsUtk9p3p3uOptzWDTY#heading=h.q5liip76r9lt\nexport type LensView = MakeTaggedBusinessEvent<\"lensView\">;\n\n/**\n * @internal\n */\nexport const reportLensView = Injectable(\n \"reportLensView\",\n [\n cameraKitSessionFactory.token,\n lensStateFactory.token,\n sessionStateFactory.token,\n metricsEventTargetFactory.token,\n operationalMetricReporterFactory.token,\n configurationToken,\n ] as const,\n (\n session: CameraKitSession,\n lensState: LensState,\n sessionState: SessionState,\n metricsEventTarget: MetricsEventTarget,\n operationalMetricsReporter: OperationalMetricsReporter,\n configuration: CameraKitConfiguration\n ): void => {\n merge(\n // Begin measuring LensCore apply time once the lens has finished downloading and we actually add the lens\n // to LensCore (LensWait measures the full download + LensCore apply time i.e. perceived UX latency).\n lensState.events.pipe(\n forActions(\"downloadComplete\"),\n map(([a]) => a.data)\n ),\n\n // If the session is resumed (e.g. user returns to this tab while a lens is on), we count this as a new\n // LensView (and applyDelaySec will be 0).\n lensState.events.pipe(\n inStates(\"lensApplied\"),\n switchMap(([, s]) =>\n sessionState.events.pipe(\n forActions(\"resume\"),\n takeUntil(lensState.events.pipe(forActions(\"removeLens\"))),\n map(() => s.data)\n )\n )\n )\n )\n .pipe(\n map((lens): [number, string] => [getTimeMs(), lens.id]),\n mergeMap(([applyLensStartTime, lensId]) => {\n const alreadyOn = isState(lensState.getState(), \"lensApplied\");\n\n const applyDelay = alreadyOn\n ? of(0)\n : lensState.events.pipe(\n forActions(\"resourcesLoaded\"),\n filter(([a]) => a.data.id === lensId),\n // Applying a new lens may happen before removing the old one, so if we kept taking events\n // we would get the lensResourcesLoaded for the next lens, too.\n take(1),\n map(() => (getTimeMs() - applyLensStartTime) / 1000)\n );\n\n const viewMetrics = (alreadyOn\n ? of([getTimeMs(), session.metrics.beginMeasurement()] as const)\n : lensState.events.pipe(\n forActions(\"turnedOn\"),\n filter(([a]) => a.data.id === lensId),\n map(() => [getTimeMs(), session.metrics.beginMeasurement()] as const)\n )\n ).pipe(\n take(1),\n mergeMap(([lensTurnedOnTime, metricsMeasurement]) =>\n lensState.events.pipe(\n forActions(\"turnedOff\"),\n // Applying a new lens may happen before removing the old one, so we'll get a\n // lensTurnedOff for the prior lens (if one was applied), which we must filter out.\n filter(([a]) => a.data.id === lensId),\n // If the session is suspended, we'll count that as the lens turning off.\n raceWith(sessionState.events.pipe(forActions(\"suspend\"))),\n map(() => {\n metricsMeasurement.end();\n return {\n viewTimeSec: (getTimeMs() - lensTurnedOnTime) / 1000,\n ...metricsMeasurement.measure(),\n };\n })\n )\n )\n );\n\n return applyDelay.pipe(\n combineLatestWith(viewMetrics),\n // This lens should always receive the lensTurnedOff action *before* the next lens is turned on.\n // But just in case that assumption is violated, we'll clean up (and not report) if another lens\n // turns on before our lens is turned off.\n takeUntil(\n lensState.events.pipe(\n forActions(\"turnedOn\"),\n filter(([a]) => a.data.id !== lensId)\n )\n ),\n take(1),\n map(([applyDelaySec, viewMetrics]) => ({\n applyDelaySec,\n lensId,\n ...viewMetrics,\n }))\n );\n })\n )\n .subscribe({\n next: async ({\n applyDelaySec,\n lensId,\n viewTimeSec,\n avgFps,\n lensFrameProcessingTimeMsAvg,\n lensFrameProcessingTimeMsStd,\n }) => {\n if (viewTimeSec < viewTimeThresholdSec) return;\n const {\n cluster: performanceCluster,\n webglRendererInfo,\n } = (await configuration.lensPerformance) ?? {\n cluster: 0,\n webglRendererInfo: \"unknown\",\n };\n const lensView: LensView = {\n name: \"lensView\",\n applyDelaySec,\n avgFps,\n lensId,\n lensFrameProcessingTimeMsAvg,\n lensFrameProcessingTimeMsStd,\n // We don't support recording video, but applications may do this without our knowledge.\n recordingTimeSec: 0,\n viewTimeSec,\n // TODO: if we want to support these fields, we'll need some persistence to keep track of the\n // date of last application per lens.\n // https://jira.sc-corp.net/browse/CAMKIT-3050\n isLensFirstWithinDay: false,\n isLensFirstWithinMonth: false,\n performanceCluster,\n webglRendererInfo,\n };\n\n metricsEventTarget.dispatchEvent(new TypedCustomEvent(\"lensView\", lensView));\n\n // Reporting operational metrics described here:\n // https://docs.google.com/document/d/1g4PncAmKdyrLEFVp8ODp58oer2UJu9PIetRW035nnTo\n //\n // We ignore if applyDelaySec is 0, which will be the case if the session was suspended and then\n // resumed - we only care about this metric when a new lens has been loaded.\n if (applyDelaySec > 0)\n operationalMetricsReporter.timer(\"lens.core_loading_latency\", applyDelaySec * 1000);\n operationalMetricsReporter.timer(\n \"lens.processing_time\",\n lensFrameProcessingTimeMsAvg,\n new Map([[\"performance_cluster\", performanceCluster.toString()]])\n );\n },\n });\n }\n);\n"]}
1
+ {"version":3,"file":"reportLensView.js","sourceRoot":"","sources":["../../../src/metrics/reporters/reportLensView.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,GAAG,EA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C,KAAK,CAC5B,sBAAsB,EACtB,4BAA4B,EAC5B,IAAI,GAAG,CAAC,CAAC,CAAC,qBAAqB,EAAE,kBAAkB,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CACpE,CAAC;QACN,CAAC,CAAA;KACJ,CAAC,CAAC;AACX,CAAC,CACJ,CAAC","sourcesContent":["import { combineLatestWith, filter, map, merge, mergeMap, of, raceWith, switchMap, take, takeUntil } from \"rxjs\";\nimport { forActions, inStates, isState } from \"@snap/state-management\";\nimport { Injectable } from \"../../dependency-injection/Injectable\";\nimport { TypedCustomEvent } from \"../../events/TypedCustomEvent\";\nimport { MetricsEventTarget, metricsEventTargetFactory } from \"../metricsEventTarget\";\nimport { CameraKitSession, cameraKitSessionFactory } from \"../../session/CameraKitSession\";\nimport { MakeTaggedBusinessEvent } from \"../businessEventsReporter\";\nimport { getTimeMs } from \"../../common/time\";\nimport { operationalMetricReporterFactory, OperationalMetricsReporter } from \"../operationalMetricsReporter\";\nimport { CameraKitConfiguration, configurationToken } from \"../../configuration\";\nimport { lensStateFactory, LensState } from \"../../session/lensState\";\nimport { SessionState, sessionStateFactory } from \"../../session/sessionState\";\n\n// We ignore short-duration lens views.\n//\n// The value is documented here:\n// https://docs.google.com/document/d/1-kSzFWCWw9Qo3D08FR1_cqeHTsUtk9p3p3uOptzWDTY/edit#heading=h.q5liip76r9lt\nconst viewTimeThresholdSec = 0.1;\n\n/**\n * The LensView metric is emitted after a lens has been viewed (for longer than 100ms), when the lens is turned off.\n *\n * It contains information about rendering performance.\n *\n * Notes:\n * - If the page is hidden (e.g. user switches to a different tab, or application, or closes the tab, or closes the\n * browser, navigates to a new page, refreshes, etc.) this metric will be emitted at that time. This is to ensure\n * we don't lose the metric if the page is closed.\n * - If the page is hidden and then made visible again later (e.g. user switches to a different tab, then back), we\n * will begin measuring a new LensView. That is, we will not capture the time when the page is hidden even if the\n * lens is still rendering in the background.\n *\n * @category Lenses\n * @category Metrics\n */\n// This type corresponds to the internal CameraKitLensSwipe event, described here:\n// https://docs.google.com/document/d/1-kSzFWCWw9Qo3D08FR1_cqeHTsUtk9p3p3uOptzWDTY#heading=h.q5liip76r9lt\nexport type LensView = MakeTaggedBusinessEvent<\"lensView\">;\n\n/**\n * @internal\n */\nexport const reportLensView = Injectable(\n \"reportLensView\",\n [\n cameraKitSessionFactory.token,\n lensStateFactory.token,\n sessionStateFactory.token,\n metricsEventTargetFactory.token,\n operationalMetricReporterFactory.token,\n configurationToken,\n ] as const,\n (\n session: CameraKitSession,\n lensState: LensState,\n sessionState: SessionState,\n metricsEventTarget: MetricsEventTarget,\n operationalMetricsReporter: OperationalMetricsReporter,\n configuration: CameraKitConfiguration\n ): void => {\n merge(\n // Begin measuring LensCore apply time once the lens has finished downloading and we actually add the lens\n // to LensCore (LensWait measures the full download + LensCore apply time i.e. perceived UX latency).\n lensState.events.pipe(\n forActions(\"downloadComplete\"),\n map(([a]) => a.data)\n ),\n\n // If the session is resumed (e.g. user returns to this tab while a lens is on), we count this as a new\n // LensView (and applyDelaySec will be 0).\n lensState.events.pipe(\n inStates(\"lensApplied\"),\n switchMap(([, s]) =>\n sessionState.events.pipe(\n forActions(\"resume\"),\n takeUntil(lensState.events.pipe(forActions(\"removeLens\"))),\n map(() => s.data)\n )\n )\n )\n )\n .pipe(\n map((lens): [number, string] => [getTimeMs(), lens.id]),\n mergeMap(([applyLensStartTime, lensId]) => {\n const alreadyOn = isState(lensState.getState(), \"lensApplied\");\n\n const applyDelay = alreadyOn\n ? of(0)\n : lensState.events.pipe(\n forActions(\"resourcesLoaded\"),\n filter(([a]) => a.data.id === lensId),\n // Applying a new lens may happen before removing the old one, so if we kept taking events\n // we would get the lensResourcesLoaded for the next lens, too.\n take(1),\n map(() => (getTimeMs() - applyLensStartTime) / 1000)\n );\n\n const viewMetrics = (\n alreadyOn\n ? of([getTimeMs(), session.metrics.beginMeasurement()] as const)\n : lensState.events.pipe(\n forActions(\"turnedOn\"),\n filter(([a]) => a.data.id === lensId),\n map(() => [getTimeMs(), session.metrics.beginMeasurement()] as const)\n )\n ).pipe(\n take(1),\n mergeMap(([lensTurnedOnTime, metricsMeasurement]) =>\n lensState.events.pipe(\n forActions(\"turnedOff\"),\n // Applying a new lens may happen before removing the old one, so we'll get a\n // lensTurnedOff for the prior lens (if one was applied), which we must filter out.\n filter(([a]) => a.data.id === lensId),\n // If the session is suspended, we'll count that as the lens turning off.\n raceWith(sessionState.events.pipe(forActions(\"suspend\"))),\n map(() => {\n metricsMeasurement.end();\n return {\n viewTimeSec: (getTimeMs() - lensTurnedOnTime) / 1000,\n ...metricsMeasurement.measure(),\n };\n })\n )\n )\n );\n\n return applyDelay.pipe(\n combineLatestWith(viewMetrics),\n // This lens should always receive the lensTurnedOff action *before* the next lens is turned on.\n // But just in case that assumption is violated, we'll clean up (and not report) if another lens\n // turns on before our lens is turned off.\n takeUntil(\n lensState.events.pipe(\n forActions(\"turnedOn\"),\n filter(([a]) => a.data.id !== lensId)\n )\n ),\n take(1),\n map(([applyDelaySec, viewMetrics]) => ({\n applyDelaySec,\n lensId,\n ...viewMetrics,\n }))\n );\n })\n )\n .subscribe({\n next: async ({\n applyDelaySec,\n lensId,\n viewTimeSec,\n avgFps,\n lensFrameProcessingTimeMsAvg,\n lensFrameProcessingTimeMsStd,\n }) => {\n if (viewTimeSec < viewTimeThresholdSec) return;\n const { cluster: performanceCluster, webglRendererInfo } =\n (await configuration.lensPerformance) ?? {\n cluster: 0,\n webglRendererInfo: \"unknown\",\n };\n const lensView: LensView = {\n name: \"lensView\",\n applyDelaySec,\n avgFps,\n lensId,\n lensFrameProcessingTimeMsAvg,\n lensFrameProcessingTimeMsStd,\n // We don't support recording video, but applications may do this without our knowledge.\n recordingTimeSec: 0,\n viewTimeSec,\n // TODO: if we want to support these fields, we'll need some persistence to keep track of the\n // date of last application per lens.\n // https://jira.sc-corp.net/browse/CAMKIT-3050\n isLensFirstWithinDay: false,\n isLensFirstWithinMonth: false,\n performanceCluster,\n webglRendererInfo,\n };\n\n metricsEventTarget.dispatchEvent(new TypedCustomEvent(\"lensView\", lensView));\n\n // Reporting operational metrics described here:\n // https://docs.google.com/document/d/1g4PncAmKdyrLEFVp8ODp58oer2UJu9PIetRW035nnTo\n //\n // We ignore if applyDelaySec is 0, which will be the case if the session was suspended and then\n // resumed - we only care about this metric when a new lens has been loaded.\n if (applyDelaySec > 0)\n operationalMetricsReporter.timer(\"lens.core_loading_latency\", applyDelaySec * 1000);\n operationalMetricsReporter.timer(\n \"lens.processing_time\",\n lensFrameProcessingTimeMsAvg,\n new Map([[\"performance_cluster\", performanceCluster.toString()]])\n );\n },\n });\n }\n);\n"]}
@@ -9,7 +9,7 @@ import { OperationalMetricsReporter } from "../operationalMetricsReporter";
9
9
  * @category Lenses
10
10
  * @category Metrics
11
11
  */
12
- export declare type LensWait = MakeTaggedBusinessEvent<"lensWait">;
12
+ export type LensWait = MakeTaggedBusinessEvent<"lensWait">;
13
13
  /**
14
14
  * Each time a lens is applied, we measure the duration until the lens is fully loaded by LensCore. This
15
15
  * includes any time spent downloading the lens content and required assets from the lens manifest.
@@ -3,7 +3,7 @@ import { MetricsEventTarget } from "../metricsEventTarget";
3
3
  /**
4
4
  * The Session metric reports each user session.
5
5
  */
6
- export declare type Session = MakeTaggedBusinessEvent<"session">;
6
+ export type Session = MakeTaggedBusinessEvent<"session">;
7
7
  /**
8
8
  * @internal
9
9
  */
@@ -1,12 +1,12 @@
1
1
  /**
2
2
  * Helper type to extract type generic parameter.
3
3
  */
4
- declare type ExtractName<P> = P extends NamedError<infer T> ? T : never;
4
+ type ExtractName<P> = P extends NamedError<infer T> ? T : never;
5
5
  /**
6
6
  * All errors are expected to have "Error" suffix.
7
7
  */
8
- declare type ErrorName = `${string}Error`;
9
- declare type NamedError<Name extends ErrorName> = Error & {
8
+ type ErrorName = `${string}Error`;
9
+ type NamedError<Name extends ErrorName> = Error & {
10
10
  name: Name;
11
11
  };
12
12
  /**
@@ -19,26 +19,26 @@ declare type NamedError<Name extends ErrorName> = Error & {
19
19
  * @internal
20
20
  */
21
21
  export declare function namedError<TError extends NamedError<TName> = never, TName extends ErrorName = ExtractName<TError>>(name: TName): (message: string, cause?: unknown) => TError;
22
- export declare type LegalError = NamedError<"LegalError">;
22
+ export type LegalError = NamedError<"LegalError">;
23
23
  /** @internal */
24
24
  export declare const legalError: (message: string, cause?: unknown) => LegalError;
25
- export declare type LensContentValidationError = NamedError<"LensContentValidationError">;
25
+ export type LensContentValidationError = NamedError<"LensContentValidationError">;
26
26
  /** @internal */
27
27
  export declare const lensContentValidationError: (message: string, cause?: unknown) => LensContentValidationError;
28
- export declare type LensError = NamedError<"LensError">;
28
+ export type LensError = NamedError<"LensError">;
29
29
  /** @internal */
30
30
  export declare const lensError: (message: string, cause?: unknown) => LensError;
31
- export declare type CameraKitSourceError = NamedError<"CameraKitSourceError">;
31
+ export type CameraKitSourceError = NamedError<"CameraKitSourceError">;
32
32
  /** @internal */
33
33
  export declare const cameraKitSourceError: (message: string, cause?: unknown) => CameraKitSourceError;
34
34
  /**
35
35
  * The error triggered when a lens prompts the user to select an image, but the image fails to be successfully delivered
36
36
  * to the lens.
37
37
  */
38
- export declare type LensImagePickerError = NamedError<"LensImagePickerError">;
38
+ export type LensImagePickerError = NamedError<"LensImagePickerError">;
39
39
  /** @internal */
40
40
  export declare const lensImagePickerError: (message: string, cause?: unknown) => LensImagePickerError;
41
- export declare type CacheKeyNotFoundError = NamedError<"CacheKeyNotFoundError">;
41
+ export type CacheKeyNotFoundError = NamedError<"CacheKeyNotFoundError">;
42
42
  /** @internal */
43
43
  export declare const cacheKeyNotFoundError: (message: string, cause?: unknown) => CacheKeyNotFoundError;
44
44
  /**
@@ -46,13 +46,13 @@ export declare const cacheKeyNotFoundError: (message: string, cause?: unknown) =
46
46
  *
47
47
  * @category Bootstrapping and Configuration
48
48
  */
49
- export declare type ConfigurationError = NamedError<"ConfigurationError">;
49
+ export type ConfigurationError = NamedError<"ConfigurationError">;
50
50
  /** @internal */
51
51
  export declare const configurationError: (message: string, cause?: unknown) => ConfigurationError;
52
- export declare type WebGLError = NamedError<"WebGLError">;
52
+ export type WebGLError = NamedError<"WebGLError">;
53
53
  /** @internal */
54
54
  export declare const webGLError: (message: string, cause?: unknown) => WebGLError;
55
- export declare type BenchmarkError = NamedError<"BenchmarkError">;
55
+ export type BenchmarkError = NamedError<"BenchmarkError">;
56
56
  /** @internal */
57
57
  export declare const benchmarkError: (message: string, cause?: unknown) => BenchmarkError;
58
58
  /**
@@ -62,7 +62,7 @@ export declare const benchmarkError: (message: string, cause?: unknown) => Bench
62
62
  *
63
63
  * @category Bootstrapping and Configuration
64
64
  */
65
- export declare type PlatformNotSupportedError = NamedError<"PlatformNotSupportedError">;
65
+ export type PlatformNotSupportedError = NamedError<"PlatformNotSupportedError">;
66
66
  /** @internal */
67
67
  export declare const platformNotSupportedError: (message: string, cause?: unknown) => PlatformNotSupportedError;
68
68
  /**
@@ -80,19 +80,19 @@ export declare const platformNotSupportedError: (message: string, cause?: unknow
80
80
  * })
81
81
  * ```
82
82
  */
83
- export declare type LensExecutionError = NamedError<"LensExecutionError">;
83
+ export type LensExecutionError = NamedError<"LensExecutionError">;
84
84
  /** @internal */
85
85
  export declare const lensExecutionError: (message: string, cause?: unknown) => LensExecutionError;
86
86
  /**
87
87
  * Error thrown when LensCore asked to store lens data, but CameraKit failed storing that.
88
88
  */
89
- export declare type PersistentStoreError = NamedError<"PersistentStoreError">;
89
+ export type PersistentStoreError = NamedError<"PersistentStoreError">;
90
90
  /** @internal */
91
91
  export declare const persistentStoreError: (message: string, cause?: unknown) => PersistentStoreError;
92
92
  /**
93
93
  * Error thrown when LensCore asked to provide an asset, but CameraKit failed providing that.
94
94
  */
95
- export declare type LensAssetError = NamedError<"LensAssetError">;
95
+ export type LensAssetError = NamedError<"LensAssetError">;
96
96
  /** @internal */
97
97
  export declare const lensAssetError: (message: string, cause?: unknown) => LensAssetError;
98
98
  /**
@@ -101,7 +101,7 @@ export declare const lensAssetError: (message: string, cause?: unknown) => LensA
101
101
  *
102
102
  * @category Bootstrapping and Configuration
103
103
  */
104
- export declare type BootstrapError = NamedError<"BootstrapError">;
104
+ export type BootstrapError = NamedError<"BootstrapError">;
105
105
  /** @internal */
106
106
  export declare const bootstrapError: (message: string, cause?: unknown) => BootstrapError;
107
107
  export {};
@@ -2,7 +2,7 @@
2
2
  * Different persistence mechanisms (e.g. localStorage, IndexedDB) may support different key types. This type should be
3
3
  * a valid key across all concrete Persistence implementations.
4
4
  */
5
- export declare type ValidKey = string | number;
5
+ export type ValidKey = string | number;
6
6
  export declare const isValidKey: (key: unknown) => key is ValidKey;
7
7
  /**
8
8
  * The abstract Persistence class defines an async interface for interacting with persistent client-side storage. This
@@ -4,7 +4,7 @@ interface Metadata {
4
4
  [key: string]: string;
5
5
  }
6
6
  export declare const COF_REQUEST_TYPE = "cof";
7
- export declare type CofDimensions = {
7
+ export type CofDimensions = {
8
8
  requestType: typeof COF_REQUEST_TYPE;
9
9
  };
10
10
  /**
@@ -18,11 +18,24 @@ const createTargetingQueryHandler = (apiToken) => (request, _a) => __awaiter(voi
18
18
  var { signal } = _a, metadata = __rest(_a, ["signal"]);
19
19
  const rpc = new GrpcWebImpl("https://api-kit.snapchat.com", {});
20
20
  const client = new CircumstancesServiceClientImpl(rpc);
21
- const response = yield client.targetingQuery(request, new BrowserHeaders(Object.assign({ authorization: `Bearer ${apiToken}`, "x-snap-client-user-agent": cameraKitUserAgent.userAgent }, metadata)));
22
- // NOTE: in order for cache persistance to work, we need to make the object cloneable,
23
- // i.e. with no methods (it appears targetingQuery() attaches toObject() to response object).
24
- delete response["toObject"];
25
- return response;
21
+ return new Promise((resolve, reject) => {
22
+ if (signal) {
23
+ signal.addEventListener("abort", () => reject(new Error("COF request aborted by handler chain.")));
24
+ }
25
+ client
26
+ .targetingQuery(request, new BrowserHeaders(Object.assign({ authorization: `Bearer ${apiToken}`, "x-snap-client-user-agent": cameraKitUserAgent.userAgent }, metadata)))
27
+ .then((response) => {
28
+ // NOTE: in order for cache persistance to work, we need to make the object cloneable,
29
+ // i.e. with no methods (it appears targetingQuery() attaches toObject() to response object).
30
+ // Safety: We have to cast response object to a type that has toObject defined, because that is
31
+ // indeed what generated code has:
32
+ // eslint-disable-next-line max-len
33
+ // https://github.sc-corp.net/Snapchat/camera-kit-web-sdk/blob/8d6b4e8bfa3717b376ab197a49972a1e410851f7/packages/web-sdk/src/generated-proto/pb_schema/cdp/cof/circumstance_service.ts#L1459
34
+ delete response.toObject;
35
+ resolve(response);
36
+ })
37
+ .catch(reject);
38
+ });
26
39
  });
27
40
  export const COF_REQUEST_TYPE = "cof";
28
41
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"cofHandler.js","sourceRoot":"","sources":["../../src/remote-configuration/cofHandler.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,8BAA8B,EAAE,WAAW,EAAE,MAAM,2DAA2D,CAAC;AAGxH,OAAO,EAAoB,mBAAmB,EAAmB,MAAM,iCAAiC,CAAC;AACzG,OAAO,EACH,wBAAwB,EACxB,sBAAsB,EACtB,sBAAsB,GACzB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,4BAA4B,EAAE,4BAA4B,EAAE,MAAM,oCAAoC,CAAC;AAChH,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAC;AAM3E,MAAM,EAAE,GAAG,CAAyC,CAA6C,EAAE,EAAE,CAAC,CAAC,CAAC;AAExG,uHAAuH;AACvH,kHAAkH;AAClH,2C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AAI,QAAQ,GAAG,CAAC,CAAC;QACjB,IAAI;YACA,QAAQ,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC;SAC5E;gBAAS;YACN,wBAAwB,CAAC,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;YACtE,OAAO,QAAQ,CAAC;SACnB;KACJ;IAAC,OAAO,KAAK,EAAE;QACZ,sBAAsB,CAAC,EAAE,SAAS,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAC7E,MAAM,KAAK,CAAC;KACf;AACL,CAAC,CAAA,CAAC,CACL;IACD,sGAAsG;IACtG,0GAA0G;IAC1G,oDAAoD;KACnD,GAAG,CAAC,qBAAqB,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,YAAY,KAAK,EAAE,CAAC,CAAC;IAC1E,+DAA+D;KAC9D,GAAG,CAAC,oBAAoB,CAAC,EAAE,OAAO,EAAE,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;KACjD,GAAG,CACA,4BAA4B;AACxB,oGAAoG;AACpG,sGAAsG;AACtG,0DAA0D;AAC1D,IAAI,mBAAmB,CACnB,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,EACtB,IAAI,oBAAoB,CAAC,EAAE,YAAY,EAAE,UAAU,EAAE,CAAC,CACzD,EACD,CAAC,CAAkC,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;AAEzD,mGAAmG;AACnG,2BAA2B;AAC3B,4BAA4B,EAAE,CACjC,CACJ,CAAC,OAAO,CAAC","sourcesContent":["import { BrowserHeaders } from \"browser-headers\";\nimport { cameraKitUserAgent } from \"../common/cameraKitUserAgent\";\nimport { ensureError } from \"../common/errorHelpers\";\nimport { CircumstancesServiceClientImpl, GrpcWebImpl } from \"../generated-proto/pb_schema/cdp/cof/circumstance_service\";\nimport { ConfigTargetingRequest } from \"../generated-proto/pb_schema/cdp/cof/config_request\";\nimport { ConfigTargetingResponse } from \"../generated-proto/pb_schema/cdp/cof/config_response\";\nimport { ChainableHandler, HandlerChainBuilder, RequestMetadata } from \"../handlers/HandlerChainBuilder\";\nimport {\n dispatchRequestCompleted,\n dispatchRequestErrored,\n dispatchRequestStarted,\n} from \"../handlers/requestStateEmittingHandler\";\nimport { createResponseCachingHandler, staleWhileRevalidateStrategy } from \"../handlers/responseCachingHandler\";\nimport { createRetryingHandler } from \"../handlers/retryingHandler\";\nimport { createTimeoutHandler } from \"../handlers/timeoutHandler\";\nimport { ExpiringPersistence } from \"../persistence/ExpiringPersistence\";\nimport { IndexedDBPersistence } from \"../persistence/IndexedDBPersistence\";\n\ninterface Metadata {\n [key: string]: string;\n}\n\nconst id = <Req, Res, Meta extends RequestMetadata>(h: ChainableHandler<Req, Res, Req, Res, Meta>) => h;\n\n// We need to wrap `targetingQuery` to create a usable Handler – the main issue is that HandlerChainBuilder always adds\n// a `signal` property to the metadata argument (second argument of the Handler), but `targetingQuery` expects the\n// second argument to only contain headers.\nconst createTargetingQueryHandler = (apiToken: string) => async (\n request: Partial<ConfigTargetingRequest>,\n { signal, ...metadata }: Metadata & RequestMetadata\n) => {\n const rpc = new GrpcWebImpl(\"https://api-kit.snapchat.com\", {});\n const client = new CircumstancesServiceClientImpl(rpc);\n const response = await client.targetingQuery(\n request,\n new BrowserHeaders({\n authorization: `Bearer ${apiToken}`,\n \"x-snap-client-user-agent\": cameraKitUserAgent.userAgent,\n ...metadata,\n })\n );\n\n // NOTE: in order for cache persistance to work, we need to make the object cloneable,\n // i.e. with no methods (it appears targetingQuery() attaches toObject() to response object).\n delete response[\"toObject\"];\n return response;\n};\n\nexport const COF_REQUEST_TYPE = \"cof\";\n\nexport type CofDimensions = { requestType: typeof COF_REQUEST_TYPE };\n\n/**\n * Handler chain used to make COF requests. Uses the COF client to perform the\n * requests, with retries, timeout, and caching.\n *\n * The handler will first attempt to retrieve the COF response from cache. If it is found, the result is returned\n * immediately and the cache is updated in the background. If no response is found, a COF request is made. This request\n * will retry (with exponential backoff + jitter) for 5 seconds before returning an error to the caller.\n */\nexport const cofHandlerFactory = (apiToken: string) =>\n new HandlerChainBuilder(createTargetingQueryHandler(apiToken))\n .map(\n id((next) => async (request, metadata) => {\n const dimensions: CofDimensions = { requestType: COF_REQUEST_TYPE };\n const { requestId } = dispatchRequestStarted({ dimensions });\n try {\n const response = await next(request, metadata);\n // TODO: We hardcode status code and sizeByte values because we do not have access to underlying\n // transport of configs-web.\n // When this ticket is done https://jira.sc-corp.net/browse/CAMKIT-2840,\n // we will remove this handler and benefit from existing ones.\n const status = 200;\n let sizeByte = 0;\n try {\n sizeByte = new TextEncoder().encode(JSON.stringify(response)).byteLength;\n } finally {\n dispatchRequestCompleted({ requestId, dimensions, status, sizeByte });\n return response;\n }\n } catch (error) {\n dispatchRequestErrored({ requestId, dimensions, error: ensureError(error) });\n throw error;\n }\n })\n )\n // targetingQuery() always converts failed responses into errors (unlike fetch()), so we need a custom\n // retryPredicate that retries all errors. We'll keep retrying (with backoff) for 20 seconds total elapsed\n // time before we return an error back up the chain.\n .map(createRetryingHandler({ retryPredicate: (r) => r instanceof Error }))\n // API gateway has 15 seconds timeout, so we rely on that first\n .map(createTimeoutHandler({ timeout: 20 * 1000 }))\n .map(\n createResponseCachingHandler(\n // COF responses will be removed from cache after 1 week. Keep in mind that the staleWhileRevalidate\n // strategy will update the cache each time COF is requested – this expiration comes into play only if\n // e.g. a user doesn't load the page for more than a week.\n new ExpiringPersistence<ConfigTargetingResponse>(\n () => 7 * 24 * 60 * 60,\n new IndexedDBPersistence({ databaseName: \"COFCache\" })\n ),\n (r: Partial<ConfigTargetingRequest>) => JSON.stringify(r),\n\n // If we have a matching response already in cache, we'll return it immediately and then update the\n // cache in the background.\n staleWhileRevalidateStrategy()\n )\n ).handler;\n"]}
1
+ {"version":3,"file":"cofHandler.js","sourceRoot":"","sources":["../../src/remote-configuration/cofHandler.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,8BAA8B,EAAE,WAAW,EAAE,MAAM,2DAA2D,CAAC;AAGxH,OAAO,EAAoB,mBAAmB,EAAmB,MAAM,iCAAiC,CAAC;AACzG,OAAO,EACH,wBAAwB,EACxB,sBAAsB,EACtB,sBAAsB,GACzB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,4BAA4B,EAAE,4BAA4B,EAAE,MAAM,oCAAoC,CAAC;AAChH,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAC;AAM3E,MAAM,EAAE,GAAG,CAAyC,CAA6C,EAAE,EAAE,CAAC,CAAC,CAAC;AAExG,uHAAuH;AACvH,kHAAkH;AAClH,2CAA2C;AAC3C,MAAM,2BAA2B,GAC7B,CAAC,QAAgB,EAAE,EAAE,CACrB,CAAO,OAAwC,EAAE,EAAmD,EAAE,EAAE;QAAvD,EAAE,MAAM,OAA2C,EAAtC,QAAQ,cAArB,UAAuB,CAAF;IAClE,MAAM,GAAG,GAAG,IAAI,WAAW,CAAC,8BAA8B,EAAE,EAAE,CAAC,CAAC;IAChE,MAAM,MAAM,GAAG,IAAI,8BAA8B,CAAC,GAAG,CAAC,CAAC;IACvD,OAAO,IAAI,OAAO,CAA0B,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QAC5D,IAAI,MAA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,GAAG,CAAC,CAAC;QACjB,IAAI;YACA,QAAQ,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC;SAC5E;gBAAS;YACN,wBAAwB,CAAC,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;YACtE,OAAO,QAAQ,CAAC;SACnB;KACJ;IAAC,OAAO,KAAK,EAAE;QACZ,sBAAsB,CAAC,EAAE,SAAS,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAC7E,MAAM,KAAK,CAAC;KACf;AACL,CAAC,CAAA,CAAC,CACL;IACD,sGAAsG;IACtG,0GAA0G;IAC1G,oDAAoD;KACnD,GAAG,CAAC,qBAAqB,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,YAAY,KAAK,EAAE,CAAC,CAAC;IAC1E,+DAA+D;KAC9D,GAAG,CAAC,oBAAoB,CAAC,EAAE,OAAO,EAAE,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;KACjD,GAAG,CACA,4BAA4B;AACxB,oGAAoG;AACpG,sGAAsG;AACtG,0DAA0D;AAC1D,IAAI,mBAAmB,CACnB,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,EACtB,IAAI,oBAAoB,CAAC,EAAE,YAAY,EAAE,UAAU,EAAE,CAAC,CACzD,EACD,CAAC,CAAkC,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;AAEzD,mGAAmG;AACnG,2BAA2B;AAC3B,4BAA4B,EAAE,CACjC,CACJ,CAAC,OAAO,CAAC","sourcesContent":["import { BrowserHeaders } from \"browser-headers\";\nimport { cameraKitUserAgent } from \"../common/cameraKitUserAgent\";\nimport { ensureError } from \"../common/errorHelpers\";\nimport { CircumstancesServiceClientImpl, GrpcWebImpl } from \"../generated-proto/pb_schema/cdp/cof/circumstance_service\";\nimport { ConfigTargetingRequest } from \"../generated-proto/pb_schema/cdp/cof/config_request\";\nimport { ConfigTargetingResponse } from \"../generated-proto/pb_schema/cdp/cof/config_response\";\nimport { ChainableHandler, HandlerChainBuilder, RequestMetadata } from \"../handlers/HandlerChainBuilder\";\nimport {\n dispatchRequestCompleted,\n dispatchRequestErrored,\n dispatchRequestStarted,\n} from \"../handlers/requestStateEmittingHandler\";\nimport { createResponseCachingHandler, staleWhileRevalidateStrategy } from \"../handlers/responseCachingHandler\";\nimport { createRetryingHandler } from \"../handlers/retryingHandler\";\nimport { createTimeoutHandler } from \"../handlers/timeoutHandler\";\nimport { ExpiringPersistence } from \"../persistence/ExpiringPersistence\";\nimport { IndexedDBPersistence } from \"../persistence/IndexedDBPersistence\";\n\ninterface Metadata {\n [key: string]: string;\n}\n\nconst id = <Req, Res, Meta extends RequestMetadata>(h: ChainableHandler<Req, Res, Req, Res, Meta>) => h;\n\n// We need to wrap `targetingQuery` to create a usable Handler – the main issue is that HandlerChainBuilder always adds\n// a `signal` property to the metadata argument (second argument of the Handler), but `targetingQuery` expects the\n// second argument to only contain headers.\nconst createTargetingQueryHandler =\n (apiToken: string) =>\n async (request: Partial<ConfigTargetingRequest>, { signal, ...metadata }: Metadata & RequestMetadata) => {\n const rpc = new GrpcWebImpl(\"https://api-kit.snapchat.com\", {});\n const client = new CircumstancesServiceClientImpl(rpc);\n return new Promise<ConfigTargetingResponse>((resolve, reject) => {\n if (signal) {\n signal.addEventListener(\"abort\", () => reject(new Error(\"COF request aborted by handler chain.\")));\n }\n client\n .targetingQuery(\n request,\n new BrowserHeaders({\n authorization: `Bearer ${apiToken}`,\n \"x-snap-client-user-agent\": cameraKitUserAgent.userAgent,\n ...metadata,\n })\n )\n .then((response) => {\n // NOTE: in order for cache persistance to work, we need to make the object cloneable,\n // i.e. with no methods (it appears targetingQuery() attaches toObject() to response object).\n // Safety: We have to cast response object to a type that has toObject defined, because that is\n // indeed what generated code has:\n // eslint-disable-next-line max-len\n // https://github.sc-corp.net/Snapchat/camera-kit-web-sdk/blob/8d6b4e8bfa3717b376ab197a49972a1e410851f7/packages/web-sdk/src/generated-proto/pb_schema/cdp/cof/circumstance_service.ts#L1459\n delete (response as any).toObject;\n resolve(response);\n })\n .catch(reject);\n });\n };\n\nexport const COF_REQUEST_TYPE = \"cof\";\n\nexport type CofDimensions = { requestType: typeof COF_REQUEST_TYPE };\n\n/**\n * Handler chain used to make COF requests. Uses the COF client to perform the\n * requests, with retries, timeout, and caching.\n *\n * The handler will first attempt to retrieve the COF response from cache. If it is found, the result is returned\n * immediately and the cache is updated in the background. If no response is found, a COF request is made. This request\n * will retry (with exponential backoff + jitter) for 5 seconds before returning an error to the caller.\n */\nexport const cofHandlerFactory = (apiToken: string) =>\n new HandlerChainBuilder(createTargetingQueryHandler(apiToken))\n .map(\n id((next) => async (request, metadata) => {\n const dimensions: CofDimensions = { requestType: COF_REQUEST_TYPE };\n const { requestId } = dispatchRequestStarted({ dimensions });\n try {\n const response = await next(request, metadata);\n // TODO: We hardcode status code and sizeByte values because we do not have access to underlying\n // transport of configs-web.\n // When this ticket is done https://jira.sc-corp.net/browse/CAMKIT-2840,\n // we will remove this handler and benefit from existing ones.\n const status = 200;\n let sizeByte = 0;\n try {\n sizeByte = new TextEncoder().encode(JSON.stringify(response)).byteLength;\n } finally {\n dispatchRequestCompleted({ requestId, dimensions, status, sizeByte });\n return response;\n }\n } catch (error) {\n dispatchRequestErrored({ requestId, dimensions, error: ensureError(error) });\n throw error;\n }\n })\n )\n // targetingQuery() always converts failed responses into errors (unlike fetch()), so we need a custom\n // retryPredicate that retries all errors. We'll keep retrying (with backoff) for 20 seconds total elapsed\n // time before we return an error back up the chain.\n .map(createRetryingHandler({ retryPredicate: (r) => r instanceof Error }))\n // API gateway has 15 seconds timeout, so we rely on that first\n .map(createTimeoutHandler({ timeout: 20 * 1000 }))\n .map(\n createResponseCachingHandler(\n // COF responses will be removed from cache after 1 week. Keep in mind that the staleWhileRevalidate\n // strategy will update the cache each time COF is requested – this expiration comes into play only if\n // e.g. a user doesn't load the page for more than a week.\n new ExpiringPersistence<ConfigTargetingResponse>(\n () => 7 * 24 * 60 * 60,\n new IndexedDBPersistence({ databaseName: \"COFCache\" })\n ),\n (r: Partial<ConfigTargetingRequest>) => JSON.stringify(r),\n\n // If we have a matching response already in cache, we'll return it immediately and then update the\n // cache in the background.\n staleWhileRevalidateStrategy()\n )\n ).handler;\n"]}
@@ -19,7 +19,7 @@ import { CameraKitSessionEvents } from "./CameraKitSessionEvents";
19
19
  * @category Rendering
20
20
  * @category Lenses
21
21
  */
22
- export declare type RenderTarget = "live" | "capture";
22
+ export type RenderTarget = "live" | "capture";
23
23
  /**
24
24
  * A CameraKitSession represents a single rendering pipeline connecting an input media source to output `<canvas>`
25
25
  * elements. When a Lens is applied to the session, CameraKit uses the Lens to transform the input media into rendered
@@ -1 +1 @@
1
- {"version":3,"file":"CameraKitSession.js","sourceRoot":"","sources":["../../src/session/CameraKitSession.ts"],"names":[],"mappings":";AAAA,uDAAuD;AACvD,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,GAAG,EAAc,EAAE,EAAgB,SAAS,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AACjG,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAC3F,OAAO,EAAQ,MAAM,EAAE,MAAM,SAAS,CAAC;AAEvC,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAChE,OAAO,EAAE,eAAe,EAAE,MAAM,4CAA4C,CAAC;AAE7E,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,gBAAgB,EAAE,MAAM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AAC,CAAC,CAAC;oBAC1F,CAAC,CAAC,CAAC;oBACH,wGAAwG;oBACxG,6EAA6E;iBAChF;gBAAC,OAAO,KAAK,EAAE;oBACZ,MAAM,CAAC,KAAK,CACR,oBAAoB,CAAC,kCAAkC,OAAO,IAAI,CAAC,MAAM,UAAU,EAAE,KAAK,CAAC,CAC9F,CAAC;iBACL;aACJ;QACL,CAAC;KAAA;CACJ;AAtRS;IAFL,QAAQ;IACR,GAAG;IACa,WAAA,KAAK,CAAC,MAAM,CAAC,CAAA;;;;iDA4B7B;AAgBK;IADL,GAAG;;;;kDAqBH;AAwBK;IAFL,QAAQ;IACR,GAAG;IACQ,WAAA,KAAK,CAAC,sBAAsB,CAAC,CAAA;;;;4CAexC;AAWK;IAFL,QAAQ;IACR,GAAG;IACS,WAAA,KAAK,CAAC,sBAAsB,CAAC,CAAA;;;;6CAgBzC;AAOD;IAAC,GAAG;;;;4CAMH;AAOD;IAAC,GAAG;;;;8CAMH;AA8BK;IAFL,QAAQ;IACR,GAAG;;;;iDAkCH;AAgBK;IADL,GAAG;;;;mDAOH;AAQK;IADL,GAAG;;;;+CASH;AAuBL;;GAEG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,UAAU,CAC7C,kBAAkB,EAClB;IACI,eAAe,CAAC,KAAK;IACrB,iBAAiB,CAAC,KAAK;IACvB,mBAAmB,CAAC,KAAK;IACzB,mBAAmB,CAAC,KAAK;IACzB,gBAAgB,CAAC,KAAK;CAChB,EACV,CACI,QAAwB,EACxB,UAAgC,EAChC,QAAsB,EACtB,YAA0B,EAC1B,SAAoB,EACtB,EAAE,CAAC,IAAI,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,YAAY,EAAE,SAAS,EAAE,UAAU,CAAC,CACrF,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/member-ordering */\nimport { filter, firstValueFrom, map, Observable, of, Subscription, takeUntil, tap } from \"rxjs\";\nimport { dispatch, forActions, inStates, isAction, isState } from \"@snap/state-management\";\nimport { Lens, isLens } from \"../lens\";\nimport { CanvasType, LensCoreModule } from \"../lens-core-module\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\nimport { lensCoreFactory } from \"../lens-core-module/loader/lensCoreFactory\";\nimport { LensLaunchParams } from \"../lens/LensLaunchParams\";\nimport { onPageHidden, onPageVisible } from \"../common/pageVisibility\";\nimport { guard, validate } from \"../common/validate\";\nimport { TypedEventTarget } from \"../events/TypedEventTarget\";\nimport { TypedCustomEvent } from \"../events/TypedCustomEvent\";\nimport { CameraKitDeviceInfo, CameraKitSource } from \"../media-sources/CameraKitSource\";\nimport { cameraKitSourceError } from \"../namedErrors\";\nimport { createMediaStreamSource } from \"../media-sources/MediaStreamSource\";\nimport { createVideoSource } from \"../media-sources/VideoSource\";\nimport { getLogger, LogEntry } from \"../logger/logger\";\nimport { errorLoggingDecorator } from \"../logger/errorLoggingDecorator\";\nimport { logEntriesFactory } from \"../logger/logEntries\";\nimport { LensPerformanceMetrics } from \"./LensPerformanceMetrics\";\nimport { lensStateFactory, LensState } from \"./lensState\";\nimport { SessionState, sessionStateFactory } from \"./sessionState\";\nimport { Keyboard, lensKeyboardFactory, LensKeyboard } from \"./LensKeyboard\";\nimport { CameraKitSessionEvents, isSessionError } from \"./CameraKitSessionEvents\";\n\nconst logger = getLogger(\"CameraKitSession\");\nconst log = errorLoggingDecorator(logger);\n\nfunction isOptionalRenderTarget(value: unknown): value is RenderTarget | undefined {\n return value === \"live\" || value === \"capture\" || value === undefined;\n}\n\n/**\n * Enumerates the supported render targets.\n *\n * Lenses may render to different render targets, as designed by the lens creator. In CameraKit, it's possible to choose\n * which render target to render, and the result for each target is available as a separate `<canvas>` element.\n *\n * @category Rendering\n * @category Lenses\n */\nexport type RenderTarget = \"live\" | \"capture\";\n\n/**\n * A CameraKitSession represents a single rendering pipeline connecting an input media source to output `<canvas>`\n * elements. When a Lens is applied to the session, CameraKit uses the Lens to transform the input media into rendered\n * output.\n *\n * CameraKitSession is the primary object that applications interact with when integrating the CameraKit SDK.\n *\n * A CameraKitSession instance is obtained by calling {@link CameraKit.createSession}.\n *\n * @example\n * ```ts\n * const cameraKit = await bootstrapCameraKit(config)\n * const session = await cameraKit.createSession()\n * ```\n *\n * @category Rendering\n * @category Lenses\n */\nexport class CameraKitSession {\n /**\n * CameraKitSession renders video output to a `<canvas>` element. In fact, each session contains two canvas outputs\n * corresponding to the RenderTargets used by Lens creators, when using LensStudio to create a Lens.\n *\n * The `live` output renders content suitable for the Lens user (e.g. it may contain additional UI elements\n * applicable only to the person applying the lens). The `capture` output renders content suitable for sharing with\n * other users (e.g. sent to the other members of a video call, or saved to disk for sharing later).\n *\n * For many lenses, these outputs are identical – but each lens is free to render differently, based on its own\n * use-case.\n */\n readonly output: {\n live: HTMLCanvasElement;\n capture: HTMLCanvasElement;\n };\n\n /**\n * Indicates whether or not the session is currently rendering. If `false`, rendering is stopped. Otherwise the\n * value indicates which output is being rendered.\n */\n playing: false | RenderTarget;\n\n /**\n * Add event listeners here to handle events which occur during the CameraKitSession.\n *\n * **Note:** Applications may want to handle the `error` event, and check the contained error type -- if the type\n * is {@link LensExecutionError}, this means the current lens was unable to render and CameraKit will automatically\n * remove the lens.\n *\n * @example\n * ```ts\n * cameraKitSession.events.addEventListener('error', ({ detail }) => {\n * if (detail.error.name === 'LensExecutionError') {\n * console.log(`Lens ${detail.lens.name} encountered an error and was removed. Please pick a different lens.`)\n * }\n * })\n * ```\n */\n readonly events = new TypedEventTarget<CameraKitSessionEvents>();\n\n /**\n * Use this to measure current lens performance.\n */\n readonly metrics: LensPerformanceMetrics;\n\n private readonly removePageVisibilityHandlers: () => void;\n private source?: CameraKitSource;\n private subscriptions: Subscription[];\n\n /**\n * @internal\n */\n constructor(\n /**\n * Use this to interact with lenses which require text input.\n */\n public readonly keyboard: Keyboard,\n\n private readonly lensCore: LensCoreModule,\n private readonly sessionState: SessionState,\n private readonly lensState: LensState,\n logEntries: Observable<LogEntry>\n ) {\n const outputs = this.lensCore.getOutputCanvases();\n this.output = {\n live: outputs[this.lensCore.CanvasType.Preview.value],\n capture: outputs[this.lensCore.CanvasType.Capture.value],\n };\n this.playing = false;\n\n this.metrics = new LensPerformanceMetrics(this.lensCore);\n\n const removeOnHidden = onPageHidden(() => this.sessionState.dispatch(\"suspend\", this));\n const removeOnVisible = onPageVisible(() => this.sessionState.dispatch(\"resume\", this));\n this.removePageVisibilityHandlers = () => {\n removeOnHidden();\n removeOnVisible();\n };\n\n const sessionErrors = logEntries.pipe(\n filter((entry) => entry.level === \"error\"),\n map((entry) => entry.messages.find((e) => e instanceof Error)),\n filter(isSessionError)\n );\n\n this.subscriptions = [\n // In case of LensCore lens execution error, we must remove the lens from rendering\n // NOTE: LensCore doesn't differentiate recoverable vs non-recoverable errors and\n // it is recommened to always remove the lens.\n sessionErrors\n .pipe(filter((error) => error.name === \"LensExecutionError\"))\n .subscribe(() => this.removeLens()),\n\n // Report LensExecutionError and LensImagePickerError errors to apps\n sessionErrors.subscribe((error) => {\n if (error.name !== \"LensExecutionError\" && error.name !== \"LensImagePickerError\") return;\n\n const state = lensState.getState();\n if (!isState(state, \"noLensApplied\")) {\n this.events.dispatchEvent(new TypedCustomEvent(\"error\", { error, lens: state.data }));\n } else {\n // NOTE: at this point the error is already reported, so we can just log a warning\n logger.warn(\n new Error(\"Lens error occurred even though there is no active lens.\", {\n cause: error,\n })\n );\n }\n }),\n ];\n }\n\n /**\n * Apply a Lens to this session.\n *\n * This method will download (and cache) the Lens executable, and then use that Lens for rendering. If the session\n * is currently playing, this will immediately update the rendered output. Otherwise, the new Lens will be used\n * when session playback in resumed.\n *\n * Calling `applyLens` replaces any prior Lens – only one Lens is allowed at a time (per session).\n *\n * **NOTE**: Errors may occur after the Lens is applied. If the Lens encounters errors while rendering,\n * Camera Kit will automatically remove the Lens from the session and emit a {@link LensExecutionError} event.\n * Applications may want to listen for this error and, for example,\n * prevent the Lens from being selected again by the user.\n *\n * ```ts\n * session.events.addEventListener(\"error\", ({ detail }) => {\n * if (detail.error.name === \"LensExecutionError\") {\n * preventFutureLensSelection(detail.lens);\n * showMessage(\"We're sorry, but the Lens you selected encountered an error. Please choose a different Lens.\");\n * }\n * });\n * ```\n *\n * @param lens The Lens to apply to this session.\n * @param launchParams: This can optionally be provided to pass some initial data to the lens – only certain lenses\n * expect launch data.\n * @returns A promise which can have the following results:\n * 1. Resolved with `true`: the lens has been applied.\n * 2. Resolved with `false`: the lens has not been applied, but no error occurred – this can happen if a\n * subsequent call to `applyLens` interrupted the lens application.\n * 3. Rejected: the lens has not been applied because an error occurred. This can happen if:\n * - The lens ID cannot be found in the LensRepository (use LensRepository to load the lens before calling this\n * method)\n * - Lens content download fails, or the download of any required lens assets fails.\n * - An internal failure occurs in the Lens rendering engine when attempting to apply the lens.\n */\n @validate\n @log\n async applyLens(@guard(isLens) lens: Lens, launchParams?: LensLaunchParams): Promise<boolean> {\n const action = this.lensState.actions.applyLens({ lens, launchParams });\n return firstValueFrom(\n of(action).pipe(\n dispatch(this.lensState),\n\n // If another applyLens occurs while we're waiting, resolve this applyLens promise early – we're no\n // longer waiting for the requested lens to be applied.\n takeUntil(\n this.lensState.events.pipe(\n forActions(\"applyLens\"),\n filter(([a]) => a !== action)\n )\n ),\n\n // If lens application failed, convert this into a rejected promise by throwing the error.\n tap(([a]) => {\n if (isAction(a, \"applyLensFailed\") && a.data.lens.id === lens.id) throw a.data.error;\n }),\n\n inStates(\"lensApplied\"),\n\n map(() => true)\n ),\n // The default value is used if `takeUntil` completes the Observable early – i.e. the lens was not\n // applied (application was interrupted by a new call to `applyLens`), so we'll resolve with `false`.\n { defaultValue: false }\n );\n }\n\n /**\n * Remove a Lens from this session.\n *\n * When a Lens is removed, rendering continues if the session is playing. It will just render the session input\n * directly to the outputs without any image processing.\n *\n * @returns A promise which can have the following results:\n * 1. Resolved with `true`: the session's rendered output has no lens applied.\n * 2. Resolved with `false`: the current lens has been removed, but a subsequent call to `applyLens` means that the\n * session's rendered output will still have a (new) lens applied.\n * 3. Rejected: the lens has failed to be removed. This can happen if an internal failure occurs in the Lens\n * rendering engine when attempting to remove the lens.\n */\n @log\n async removeLens(): Promise<boolean> {\n if (isState(this.lensState.getState(), \"noLensApplied\")) return true;\n return firstValueFrom(\n of(this.lensState.actions.removeLens()).pipe(\n dispatch(this.lensState),\n // If lens removal failed, convert this into a rejected promise by throwing the error.\n tap(([a]) => {\n if (isAction(a, \"removeLensFailed\")) throw a.data;\n }),\n inStates(\"noLensApplied\"),\n\n // If applyLens is called while we're waiting for removal, complete immediately – applying the next lens\n // will replace the current one.\n takeUntil(this.lensState.events.pipe(forActions(\"applyLens\"))),\n map(() => true)\n ),\n // The default value is used if `takeUntil` completes the Observable early (otherwise firstValueFrom will\n // return a rejected Promise).\n { defaultValue: false }\n );\n }\n\n /**\n * Start/resume session playback – LensCore will begin rendering frames to the output.\n *\n * If no source has been set for the session, calling `play()` will update the playing state, but no actual image\n * processing will occur until `setSource()` is called.\n *\n * @example\n * ```ts\n * const cameraKitSession = await cameraKit.createSession()\n * await cameraKitSession.setSource(mySource)\n * await cameraKitSession.play()\n *\n * // If you call `play` before `setSource`, the call to `play` will resolve but playback will only begin once a\n * // media source has been set.\n * ```\n *\n * @param target Specify the {@link RenderTarget} to render. Defaults to the `live` RenderTarget.\n * @returns Promise resolves when playback state has been updated. If no source has been set, this means `play` will\n * resolve before any frames are processed -- but once a source is set, frames will immediately begin processing.\n */\n @validate\n @log\n async play(@guard(isOptionalRenderTarget) target: RenderTarget = \"live\"): Promise<void> {\n if (this.playing) return;\n this.playing = target;\n\n const type = this.renderTargetToCanvasType(target);\n return new Promise((resolve, reject) => {\n this.lensCore.playCanvas({\n type,\n onSuccess: resolve,\n onFailure: (error: Error) => {\n this.playing = false;\n reject(error);\n },\n });\n });\n }\n\n /**\n * Pause session playback – LensCore will stop rendering frames to the output.\n *\n * @param target Specify the RenderTarget to pause playback. May be either `'live'` or `'capture'`.\n * Default is `'live'`.\n * @returns Promise resolves when playback has stopped.\n */\n @validate\n @log\n async pause(@guard(isOptionalRenderTarget) target: RenderTarget = \"live\"): Promise<void> {\n if (!this.playing) return;\n const priorPlayingState = this.playing;\n this.playing = false;\n\n const type = this.renderTargetToCanvasType(target);\n return new Promise((resolve, reject) => {\n this.lensCore.pauseCanvas({\n type,\n onSuccess: resolve,\n onFailure: (error: Error) => {\n this.playing = priorPlayingState;\n reject(error);\n },\n });\n });\n }\n\n /**\n * Mute all sounds (default SDK state is unmuted).\n *\n * @param fade Do we want audio to fade out?\n */\n @log\n mute(fade: boolean = false): void {\n this.lensCore.setAllSoundsMuted({\n muted: true,\n fade,\n });\n }\n\n /**\n * Unmute all sounds.\n *\n * @param fade Do we want audio to fade in?\n */\n @log\n unmute(fade: boolean = false): void {\n this.lensCore.setAllSoundsMuted({\n muted: false,\n fade,\n });\n }\n\n /**\n * Set the media source for this session.\n *\n * Sessions may only have one source at a time - if `setSource` is called multiple times, subsequent calls replace\n * the prior source. Setting the source does not trigger rendering (that’s done by `session.play()`). If the session\n * is already playing, setting the source will immediately begin rendering the new source.\n *\n * The CameraKit SDK provides implementations for various common sources, which applications can create using the\n * following functions:\n * - {@link createUserMediaSource}\n * - {@link createMediaStreamSource}\n * - {@link createVideoSource}\n * - {@link createImageSource}\n *\n * @param source A CameraKitSource object representing input media (e.g. a webcam stream, video, or some other\n * source of image data), which CameraKit will supply to Lenses in order for them to render effects on top of that\n * source.\n * @returns Promise is resolved when the source has successfully be set. If the session was already in the playing\n * state, the Promise resolves when the first frame from the new source has been rendered. The resolved value is\n * the {@link CameraKitSource} object attached to the session.\n */\n async setSource(source: CameraKitSource): Promise<CameraKitSource>;\n async setSource(\n source: MediaStream | HTMLVideoElement,\n options?: Partial<CameraKitDeviceInfo>\n ): Promise<CameraKitSource>;\n @validate\n @log\n async setSource(\n source: CameraKitSource | MediaStream | HTMLVideoElement,\n options: Partial<CameraKitDeviceInfo> = {}\n ): Promise<CameraKitSource> {\n await this.safelyDetachSource();\n\n // For convenience, we allow callers to pass in native objects (e.g. MediaStream) as well as CameraKitSource.\n // Native objects are wrapped in corresponding CameraKitSource classes with default options.\n const cameraKitSource =\n source instanceof MediaStream\n ? createMediaStreamSource(source, options)\n : source instanceof HTMLVideoElement\n ? createVideoSource(source, options)\n : source;\n\n const priorPlayingState = this.playing;\n this.playing = false;\n\n // The source will provide its data to LensCore, and use other LensCore APIs (e.g. setRenderSize,\n // setInputTransform) to render the source correctly.\n await cameraKitSource.attach(this.lensCore, (error) => {\n logger.error(cameraKitSourceError(\"Error happened during source attachment.\", error));\n });\n\n // If attachment is successful, we'll update our source so that we can detach it later.\n this.source = cameraKitSource;\n\n // Finally we'll resume playback, if appropriate.\n if (priorPlayingState) {\n await this.play(priorPlayingState);\n }\n\n return cameraKitSource;\n }\n\n /**\n * Set an FPS limit.\n *\n * This may be useful to reduce CPU/GPU resource usage by CameraKit if, for example, the input\n * media source has a low FPS – CameraKit would then not try to render more frequently than the source produces\n * new frames.\n *\n * This may also be useful to gracefully degrade performance in situations where lowering FPS is preferable over\n * alternatives.\n *\n * @param fpsLimit A maximum FPS, rendering will not exceed this limit\n * @returns Promise is resolved when the limit is successfully set.\n */\n @log\n async setFPSLimit(fpsLimit: number): Promise<void> {\n // LensCore uses 0 to remove the limit.\n const fps = fpsLimit < Number.POSITIVE_INFINITY ? fpsLimit : 0;\n return new Promise((onSuccess, onFailure) => {\n this.lensCore.setFPSLimit({ fps, onSuccess, onFailure });\n });\n }\n\n /**\n * Destroy the session.\n *\n * The session will become inoperable. Frame processing stops, and any session-scoped graphical resources are freed.\n */\n @log\n async destroy(): Promise<void> {\n this.subscriptions.forEach((sub) => sub.unsubscribe());\n await this.removeLens();\n await this.safelyDetachSource();\n await new Promise<void>((resolve, reject) => {\n this.lensCore.teardown({ onSuccess: resolve, onFailure: reject });\n });\n this.removePageVisibilityHandlers();\n }\n\n private renderTargetToCanvasType(target: RenderTarget): CanvasType {\n return target === \"capture\" ? this.lensCore.CanvasType.Capture : this.lensCore.CanvasType.Preview;\n }\n\n private async safelyDetachSource(): Promise<void> {\n if (this.source) {\n try {\n await this.source.detach((error) => {\n logger.error(cameraKitSourceError(\"Error happened during source detachment.\", error));\n });\n // If there's a failure to detach, we will report the error and proceed. Failure to detach may lead to a\n // memory leak, but it shouldn't prevent us from switching to the new source.\n } catch (error) {\n logger.error(\n cameraKitSourceError(`Detaching prior source of type ${typeof this.source} failed.`, error)\n );\n }\n }\n }\n}\n\n/**\n * @internal\n */\nexport const cameraKitSessionFactory = Injectable(\n \"CameraKitSession\",\n [\n lensCoreFactory.token,\n logEntriesFactory.token,\n lensKeyboardFactory.token,\n sessionStateFactory.token,\n lensStateFactory.token,\n ] as const,\n (\n lensCore: LensCoreModule,\n logEntries: Observable<LogEntry>,\n keyboard: LensKeyboard,\n sessionState: SessionState,\n lensState: LensState\n ) => new CameraKitSession(keyboard, lensCore, sessionState, lensState, logEntries)\n);\n"]}
1
+ {"version":3,"file":"CameraKitSession.js","sourceRoot":"","sources":["../../src/session/CameraKitSession.ts"],"names":[],"mappings":";AAAA,uDAAuD;AACvD,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,GAAG,EAAc,EAAE,EAAgB,SAAS,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AACjG,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAC3F,OAAO,EAAQ,MAAM,EAAE,MAAM,SAAS,CAAC;AAEvC,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAChE,OAAO,EAAE,eAAe,EAAE,MAAM,4CAA4C,CAAC;AAE7E,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA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ACxG,6EAA6E;iBAChF;gBAAC,OAAO,KAAK,EAAE;oBACZ,MAAM,CAAC,KAAK,CACR,oBAAoB,CAAC,kCAAkC,OAAO,IAAI,CAAC,MAAM,UAAU,EAAE,KAAK,CAAC,CAC9F,CAAC;iBACL;aACJ;QACL,CAAC;KAAA;CACJ;AAtRS;IAFL,QAAQ;IACR,GAAG;IACa,WAAA,KAAK,CAAC,MAAM,CAAC,CAAA;;;;iDA4B7B;AAgBK;IADL,GAAG;;;;kDAqBH;AAwBK;IAFL,QAAQ;IACR,GAAG;IACQ,WAAA,KAAK,CAAC,sBAAsB,CAAC,CAAA;;;;4CAexC;AAWK;IAFL,QAAQ;IACR,GAAG;IACS,WAAA,KAAK,CAAC,sBAAsB,CAAC,CAAA;;;;6CAgBzC;AAQD;IADC,GAAG;;;;4CAMH;AAQD;IADC,GAAG;;;;8CAMH;AA8BK;IAFL,QAAQ;IACR,GAAG;;;;iDAkCH;AAgBK;IADL,GAAG;;;;mDAOH;AAQK;IADL,GAAG;;;;+CASH;AAuBL;;GAEG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,UAAU,CAC7C,kBAAkB,EAClB;IACI,eAAe,CAAC,KAAK;IACrB,iBAAiB,CAAC,KAAK;IACvB,mBAAmB,CAAC,KAAK;IACzB,mBAAmB,CAAC,KAAK;IACzB,gBAAgB,CAAC,KAAK;CAChB,EACV,CACI,QAAwB,EACxB,UAAgC,EAChC,QAAsB,EACtB,YAA0B,EAC1B,SAAoB,EACtB,EAAE,CAAC,IAAI,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,YAAY,EAAE,SAAS,EAAE,UAAU,CAAC,CACrF,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/member-ordering */\nimport { filter, firstValueFrom, map, Observable, of, Subscription, takeUntil, tap } from \"rxjs\";\nimport { dispatch, forActions, inStates, isAction, isState } from \"@snap/state-management\";\nimport { Lens, isLens } from \"../lens\";\nimport { CanvasType, LensCoreModule } from \"../lens-core-module\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\nimport { lensCoreFactory } from \"../lens-core-module/loader/lensCoreFactory\";\nimport { LensLaunchParams } from \"../lens/LensLaunchParams\";\nimport { onPageHidden, onPageVisible } from \"../common/pageVisibility\";\nimport { guard, validate } from \"../common/validate\";\nimport { TypedEventTarget } from \"../events/TypedEventTarget\";\nimport { TypedCustomEvent } from \"../events/TypedCustomEvent\";\nimport { CameraKitDeviceInfo, CameraKitSource } from \"../media-sources/CameraKitSource\";\nimport { cameraKitSourceError } from \"../namedErrors\";\nimport { createMediaStreamSource } from \"../media-sources/MediaStreamSource\";\nimport { createVideoSource } from \"../media-sources/VideoSource\";\nimport { getLogger, LogEntry } from \"../logger/logger\";\nimport { errorLoggingDecorator } from \"../logger/errorLoggingDecorator\";\nimport { logEntriesFactory } from \"../logger/logEntries\";\nimport { LensPerformanceMetrics } from \"./LensPerformanceMetrics\";\nimport { lensStateFactory, LensState } from \"./lensState\";\nimport { SessionState, sessionStateFactory } from \"./sessionState\";\nimport { Keyboard, lensKeyboardFactory, LensKeyboard } from \"./LensKeyboard\";\nimport { CameraKitSessionEvents, isSessionError } from \"./CameraKitSessionEvents\";\n\nconst logger = getLogger(\"CameraKitSession\");\nconst log = errorLoggingDecorator(logger);\n\nfunction isOptionalRenderTarget(value: unknown): value is RenderTarget | undefined {\n return value === \"live\" || value === \"capture\" || value === undefined;\n}\n\n/**\n * Enumerates the supported render targets.\n *\n * Lenses may render to different render targets, as designed by the lens creator. In CameraKit, it's possible to choose\n * which render target to render, and the result for each target is available as a separate `<canvas>` element.\n *\n * @category Rendering\n * @category Lenses\n */\nexport type RenderTarget = \"live\" | \"capture\";\n\n/**\n * A CameraKitSession represents a single rendering pipeline connecting an input media source to output `<canvas>`\n * elements. When a Lens is applied to the session, CameraKit uses the Lens to transform the input media into rendered\n * output.\n *\n * CameraKitSession is the primary object that applications interact with when integrating the CameraKit SDK.\n *\n * A CameraKitSession instance is obtained by calling {@link CameraKit.createSession}.\n *\n * @example\n * ```ts\n * const cameraKit = await bootstrapCameraKit(config)\n * const session = await cameraKit.createSession()\n * ```\n *\n * @category Rendering\n * @category Lenses\n */\nexport class CameraKitSession {\n /**\n * CameraKitSession renders video output to a `<canvas>` element. In fact, each session contains two canvas outputs\n * corresponding to the RenderTargets used by Lens creators, when using LensStudio to create a Lens.\n *\n * The `live` output renders content suitable for the Lens user (e.g. it may contain additional UI elements\n * applicable only to the person applying the lens). The `capture` output renders content suitable for sharing with\n * other users (e.g. sent to the other members of a video call, or saved to disk for sharing later).\n *\n * For many lenses, these outputs are identical – but each lens is free to render differently, based on its own\n * use-case.\n */\n readonly output: {\n live: HTMLCanvasElement;\n capture: HTMLCanvasElement;\n };\n\n /**\n * Indicates whether or not the session is currently rendering. If `false`, rendering is stopped. Otherwise the\n * value indicates which output is being rendered.\n */\n playing: false | RenderTarget;\n\n /**\n * Add event listeners here to handle events which occur during the CameraKitSession.\n *\n * **Note:** Applications may want to handle the `error` event, and check the contained error type -- if the type\n * is {@link LensExecutionError}, this means the current lens was unable to render and CameraKit will automatically\n * remove the lens.\n *\n * @example\n * ```ts\n * cameraKitSession.events.addEventListener('error', ({ detail }) => {\n * if (detail.error.name === 'LensExecutionError') {\n * console.log(`Lens ${detail.lens.name} encountered an error and was removed. Please pick a different lens.`)\n * }\n * })\n * ```\n */\n readonly events = new TypedEventTarget<CameraKitSessionEvents>();\n\n /**\n * Use this to measure current lens performance.\n */\n readonly metrics: LensPerformanceMetrics;\n\n private readonly removePageVisibilityHandlers: () => void;\n private source?: CameraKitSource;\n private subscriptions: Subscription[];\n\n /**\n * @internal\n */\n constructor(\n /**\n * Use this to interact with lenses which require text input.\n */\n public readonly keyboard: Keyboard,\n\n private readonly lensCore: LensCoreModule,\n private readonly sessionState: SessionState,\n private readonly lensState: LensState,\n logEntries: Observable<LogEntry>\n ) {\n const outputs = this.lensCore.getOutputCanvases();\n this.output = {\n live: outputs[this.lensCore.CanvasType.Preview.value],\n capture: outputs[this.lensCore.CanvasType.Capture.value],\n };\n this.playing = false;\n\n this.metrics = new LensPerformanceMetrics(this.lensCore);\n\n const removeOnHidden = onPageHidden(() => this.sessionState.dispatch(\"suspend\", this));\n const removeOnVisible = onPageVisible(() => this.sessionState.dispatch(\"resume\", this));\n this.removePageVisibilityHandlers = () => {\n removeOnHidden();\n removeOnVisible();\n };\n\n const sessionErrors = logEntries.pipe(\n filter((entry) => entry.level === \"error\"),\n map((entry) => entry.messages.find((e) => e instanceof Error)),\n filter(isSessionError)\n );\n\n this.subscriptions = [\n // In case of LensCore lens execution error, we must remove the lens from rendering\n // NOTE: LensCore doesn't differentiate recoverable vs non-recoverable errors and\n // it is recommened to always remove the lens.\n sessionErrors\n .pipe(filter((error) => error.name === \"LensExecutionError\"))\n .subscribe(() => this.removeLens()),\n\n // Report LensExecutionError and LensImagePickerError errors to apps\n sessionErrors.subscribe((error) => {\n if (error.name !== \"LensExecutionError\" && error.name !== \"LensImagePickerError\") return;\n\n const state = lensState.getState();\n if (!isState(state, \"noLensApplied\")) {\n this.events.dispatchEvent(new TypedCustomEvent(\"error\", { error, lens: state.data }));\n } else {\n // NOTE: at this point the error is already reported, so we can just log a warning\n logger.warn(\n new Error(\"Lens error occurred even though there is no active lens.\", {\n cause: error,\n })\n );\n }\n }),\n ];\n }\n\n /**\n * Apply a Lens to this session.\n *\n * This method will download (and cache) the Lens executable, and then use that Lens for rendering. If the session\n * is currently playing, this will immediately update the rendered output. Otherwise, the new Lens will be used\n * when session playback in resumed.\n *\n * Calling `applyLens` replaces any prior Lens – only one Lens is allowed at a time (per session).\n *\n * **NOTE**: Errors may occur after the Lens is applied. If the Lens encounters errors while rendering,\n * Camera Kit will automatically remove the Lens from the session and emit a {@link LensExecutionError} event.\n * Applications may want to listen for this error and, for example,\n * prevent the Lens from being selected again by the user.\n *\n * ```ts\n * session.events.addEventListener(\"error\", ({ detail }) => {\n * if (detail.error.name === \"LensExecutionError\") {\n * preventFutureLensSelection(detail.lens);\n * showMessage(\"We're sorry, but the Lens you selected encountered an error. Please choose a different Lens.\");\n * }\n * });\n * ```\n *\n * @param lens The Lens to apply to this session.\n * @param launchParams: This can optionally be provided to pass some initial data to the lens – only certain lenses\n * expect launch data.\n * @returns A promise which can have the following results:\n * 1. Resolved with `true`: the lens has been applied.\n * 2. Resolved with `false`: the lens has not been applied, but no error occurred – this can happen if a\n * subsequent call to `applyLens` interrupted the lens application.\n * 3. Rejected: the lens has not been applied because an error occurred. This can happen if:\n * - The lens ID cannot be found in the LensRepository (use LensRepository to load the lens before calling this\n * method)\n * - Lens content download fails, or the download of any required lens assets fails.\n * - An internal failure occurs in the Lens rendering engine when attempting to apply the lens.\n */\n @validate\n @log\n async applyLens(@guard(isLens) lens: Lens, launchParams?: LensLaunchParams): Promise<boolean> {\n const action = this.lensState.actions.applyLens({ lens, launchParams });\n return firstValueFrom(\n of(action).pipe(\n dispatch(this.lensState),\n\n // If another applyLens occurs while we're waiting, resolve this applyLens promise early – we're no\n // longer waiting for the requested lens to be applied.\n takeUntil(\n this.lensState.events.pipe(\n forActions(\"applyLens\"),\n filter(([a]) => a !== action)\n )\n ),\n\n // If lens application failed, convert this into a rejected promise by throwing the error.\n tap(([a]) => {\n if (isAction(a, \"applyLensFailed\") && a.data.lens.id === lens.id) throw a.data.error;\n }),\n\n inStates(\"lensApplied\"),\n\n map(() => true)\n ),\n // The default value is used if `takeUntil` completes the Observable early – i.e. the lens was not\n // applied (application was interrupted by a new call to `applyLens`), so we'll resolve with `false`.\n { defaultValue: false }\n );\n }\n\n /**\n * Remove a Lens from this session.\n *\n * When a Lens is removed, rendering continues if the session is playing. It will just render the session input\n * directly to the outputs without any image processing.\n *\n * @returns A promise which can have the following results:\n * 1. Resolved with `true`: the session's rendered output has no lens applied.\n * 2. Resolved with `false`: the current lens has been removed, but a subsequent call to `applyLens` means that the\n * session's rendered output will still have a (new) lens applied.\n * 3. Rejected: the lens has failed to be removed. This can happen if an internal failure occurs in the Lens\n * rendering engine when attempting to remove the lens.\n */\n @log\n async removeLens(): Promise<boolean> {\n if (isState(this.lensState.getState(), \"noLensApplied\")) return true;\n return firstValueFrom(\n of(this.lensState.actions.removeLens()).pipe(\n dispatch(this.lensState),\n // If lens removal failed, convert this into a rejected promise by throwing the error.\n tap(([a]) => {\n if (isAction(a, \"removeLensFailed\")) throw a.data;\n }),\n inStates(\"noLensApplied\"),\n\n // If applyLens is called while we're waiting for removal, complete immediately – applying the next lens\n // will replace the current one.\n takeUntil(this.lensState.events.pipe(forActions(\"applyLens\"))),\n map(() => true)\n ),\n // The default value is used if `takeUntil` completes the Observable early (otherwise firstValueFrom will\n // return a rejected Promise).\n { defaultValue: false }\n );\n }\n\n /**\n * Start/resume session playback – LensCore will begin rendering frames to the output.\n *\n * If no source has been set for the session, calling `play()` will update the playing state, but no actual image\n * processing will occur until `setSource()` is called.\n *\n * @example\n * ```ts\n * const cameraKitSession = await cameraKit.createSession()\n * await cameraKitSession.setSource(mySource)\n * await cameraKitSession.play()\n *\n * // If you call `play` before `setSource`, the call to `play` will resolve but playback will only begin once a\n * // media source has been set.\n * ```\n *\n * @param target Specify the {@link RenderTarget} to render. Defaults to the `live` RenderTarget.\n * @returns Promise resolves when playback state has been updated. If no source has been set, this means `play` will\n * resolve before any frames are processed -- but once a source is set, frames will immediately begin processing.\n */\n @validate\n @log\n async play(@guard(isOptionalRenderTarget) target: RenderTarget = \"live\"): Promise<void> {\n if (this.playing) return;\n this.playing = target;\n\n const type = this.renderTargetToCanvasType(target);\n return new Promise((resolve, reject) => {\n this.lensCore.playCanvas({\n type,\n onSuccess: resolve,\n onFailure: (error: Error) => {\n this.playing = false;\n reject(error);\n },\n });\n });\n }\n\n /**\n * Pause session playback – LensCore will stop rendering frames to the output.\n *\n * @param target Specify the RenderTarget to pause playback. May be either `'live'` or `'capture'`.\n * Default is `'live'`.\n * @returns Promise resolves when playback has stopped.\n */\n @validate\n @log\n async pause(@guard(isOptionalRenderTarget) target: RenderTarget = \"live\"): Promise<void> {\n if (!this.playing) return;\n const priorPlayingState = this.playing;\n this.playing = false;\n\n const type = this.renderTargetToCanvasType(target);\n return new Promise((resolve, reject) => {\n this.lensCore.pauseCanvas({\n type,\n onSuccess: resolve,\n onFailure: (error: Error) => {\n this.playing = priorPlayingState;\n reject(error);\n },\n });\n });\n }\n\n /**\n * Mute all sounds (default SDK state is unmuted).\n *\n * @param fade Do we want audio to fade out?\n */\n @log\n mute(fade: boolean = false): void {\n this.lensCore.setAllSoundsMuted({\n muted: true,\n fade,\n });\n }\n\n /**\n * Unmute all sounds.\n *\n * @param fade Do we want audio to fade in?\n */\n @log\n unmute(fade: boolean = false): void {\n this.lensCore.setAllSoundsMuted({\n muted: false,\n fade,\n });\n }\n\n /**\n * Set the media source for this session.\n *\n * Sessions may only have one source at a time - if `setSource` is called multiple times, subsequent calls replace\n * the prior source. Setting the source does not trigger rendering (that’s done by `session.play()`). If the session\n * is already playing, setting the source will immediately begin rendering the new source.\n *\n * The CameraKit SDK provides implementations for various common sources, which applications can create using the\n * following functions:\n * - {@link createUserMediaSource}\n * - {@link createMediaStreamSource}\n * - {@link createVideoSource}\n * - {@link createImageSource}\n *\n * @param source A CameraKitSource object representing input media (e.g. a webcam stream, video, or some other\n * source of image data), which CameraKit will supply to Lenses in order for them to render effects on top of that\n * source.\n * @returns Promise is resolved when the source has successfully be set. If the session was already in the playing\n * state, the Promise resolves when the first frame from the new source has been rendered. The resolved value is\n * the {@link CameraKitSource} object attached to the session.\n */\n async setSource(source: CameraKitSource): Promise<CameraKitSource>;\n async setSource(\n source: MediaStream | HTMLVideoElement,\n options?: Partial<CameraKitDeviceInfo>\n ): Promise<CameraKitSource>;\n @validate\n @log\n async setSource(\n source: CameraKitSource | MediaStream | HTMLVideoElement,\n options: Partial<CameraKitDeviceInfo> = {}\n ): Promise<CameraKitSource> {\n await this.safelyDetachSource();\n\n // For convenience, we allow callers to pass in native objects (e.g. MediaStream) as well as CameraKitSource.\n // Native objects are wrapped in corresponding CameraKitSource classes with default options.\n const cameraKitSource =\n source instanceof MediaStream\n ? createMediaStreamSource(source, options)\n : source instanceof HTMLVideoElement\n ? createVideoSource(source, options)\n : source;\n\n const priorPlayingState = this.playing;\n this.playing = false;\n\n // The source will provide its data to LensCore, and use other LensCore APIs (e.g. setRenderSize,\n // setInputTransform) to render the source correctly.\n await cameraKitSource.attach(this.lensCore, (error) => {\n logger.error(cameraKitSourceError(\"Error happened during source attachment.\", error));\n });\n\n // If attachment is successful, we'll update our source so that we can detach it later.\n this.source = cameraKitSource;\n\n // Finally we'll resume playback, if appropriate.\n if (priorPlayingState) {\n await this.play(priorPlayingState);\n }\n\n return cameraKitSource;\n }\n\n /**\n * Set an FPS limit.\n *\n * This may be useful to reduce CPU/GPU resource usage by CameraKit if, for example, the input\n * media source has a low FPS – CameraKit would then not try to render more frequently than the source produces\n * new frames.\n *\n * This may also be useful to gracefully degrade performance in situations where lowering FPS is preferable over\n * alternatives.\n *\n * @param fpsLimit A maximum FPS, rendering will not exceed this limit\n * @returns Promise is resolved when the limit is successfully set.\n */\n @log\n async setFPSLimit(fpsLimit: number): Promise<void> {\n // LensCore uses 0 to remove the limit.\n const fps = fpsLimit < Number.POSITIVE_INFINITY ? fpsLimit : 0;\n return new Promise((onSuccess, onFailure) => {\n this.lensCore.setFPSLimit({ fps, onSuccess, onFailure });\n });\n }\n\n /**\n * Destroy the session.\n *\n * The session will become inoperable. Frame processing stops, and any session-scoped graphical resources are freed.\n */\n @log\n async destroy(): Promise<void> {\n this.subscriptions.forEach((sub) => sub.unsubscribe());\n await this.removeLens();\n await this.safelyDetachSource();\n await new Promise<void>((resolve, reject) => {\n this.lensCore.teardown({ onSuccess: resolve, onFailure: reject });\n });\n this.removePageVisibilityHandlers();\n }\n\n private renderTargetToCanvasType(target: RenderTarget): CanvasType {\n return target === \"capture\" ? this.lensCore.CanvasType.Capture : this.lensCore.CanvasType.Preview;\n }\n\n private async safelyDetachSource(): Promise<void> {\n if (this.source) {\n try {\n await this.source.detach((error) => {\n logger.error(cameraKitSourceError(\"Error happened during source detachment.\", error));\n });\n // If there's a failure to detach, we will report the error and proceed. Failure to detach may lead to a\n // memory leak, but it shouldn't prevent us from switching to the new source.\n } catch (error) {\n logger.error(\n cameraKitSourceError(`Detaching prior source of type ${typeof this.source} failed.`, error)\n );\n }\n }\n }\n}\n\n/**\n * @internal\n */\nexport const cameraKitSessionFactory = Injectable(\n \"CameraKitSession\",\n [\n lensCoreFactory.token,\n logEntriesFactory.token,\n lensKeyboardFactory.token,\n sessionStateFactory.token,\n lensStateFactory.token,\n ] as const,\n (\n lensCore: LensCoreModule,\n logEntries: Observable<LogEntry>,\n keyboard: LensKeyboard,\n sessionState: SessionState,\n lensState: LensState\n ) => new CameraKitSession(keyboard, lensCore, sessionState, lensState, logEntries)\n);\n"]}
@@ -10,7 +10,7 @@ export declare function isSessionError(value: unknown): value is SessionErrors;
10
10
  * Misc errors that occur during CameraKit session.
11
11
  * @internal
12
12
  */
13
- export declare type SessionErrors = LensExecutionError | LensImagePickerError | CameraKitSourceError;
13
+ export type SessionErrors = LensExecutionError | LensImagePickerError | CameraKitSourceError;
14
14
  /**
15
15
  * Events emitted by {@link CameraKitSession.events | CameraKitSession.events}.
16
16
  *
@@ -23,11 +23,11 @@ export declare type SessionErrors = LensExecutionError | LensImagePickerError |
23
23
  * @category Rendering
24
24
  * @category Lenses
25
25
  */
26
- export declare type CameraKitSessionEvents = TypedCustomEvent<"error", {
26
+ export type CameraKitSessionEvents = TypedCustomEvent<"error", {
27
27
  error: LensExecutionError | LensImagePickerError;
28
28
  lens: Lens;
29
29
  }>;
30
30
  /**
31
31
  * Listener of {@link CameraKitSessionEvents} events.
32
32
  */
33
- export declare type CameraKitSessionEventListener = TypedEventListener<CameraKitSessionEvents>;
33
+ export type CameraKitSessionEventListener = TypedEventListener<CameraKitSessionEvents>;
@@ -6,7 +6,7 @@ import { LensState } from "./lensState";
6
6
  /**
7
7
  * Events emitted by {@link Keyboard}.
8
8
  */
9
- export declare type KeyboardEvents = TypedCustomEvent<"active", {
9
+ export type KeyboardEvents = TypedCustomEvent<"active", {
10
10
  element: HTMLTextAreaElement;
11
11
  active: boolean;
12
12
  lens?: Lens;
@@ -36,7 +36,7 @@ export declare type KeyboardEvents = TypedCustomEvent<"active", {
36
36
  *
37
37
  * @category Lenses
38
38
  */
39
- export declare type Keyboard = {
39
+ export type Keyboard = {
40
40
  addEventListener: (type: "active", callback: TypedEventListener<KeyboardEvents>, options?: TypedEventListenerOptions) => void;
41
41
  removeEventListener: (type: "active", callback: TypedEventListener<KeyboardEvents>) => void;
42
42
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"LensPerformanceMetrics.js","sourceRoot":"","sources":["../../src/session/LensPerformanceMetrics.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAE1E,MAAM,MAAM,GAAG,SAAS,CAAC,kBAAkB,CAAC,CAAC;AAC7C,MAAM,GAAG,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;AAE1C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,sBAAsB;IAG/B,gBAAgB;IAChB,YAAoB,QAAwB;QAAxB,aAAQ,GAAR,QAAQ,CAAgB;QACxC,IAAI,CAAC,oBAAoB,GAAG,IAAI,GAAG,EAAE,CAAC;QACtC,IAAI,CAAC,QAAQ,CAAC,2BAA2B,CAAC;YACtC,gBAAgB,EAAE,CAAC,EAAE,gBAAgB,EAAE,EAAE,EAAE;gBACvC,IAAI;oBACA,KAAK,MAAM,WAAW,IAAI,IAAI,CAAC,oBAAoB,CAAC,MAAM,EAAE,EAAE;wBAC1D,WAAW,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;qBACxC;iBACJ;gBAAC,OAAO,KAAK,EAAE;oBACZ,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;iBACvB;YACL,CAAC;YACD,SAAS,EAAE,CAAC,KAAK,EAAE,EAAE,CACjB,MAAM,CAAC,KAAK,CAAC,8DAA8D,KAAK,CAAC,OAAO,EAAE,CAAC;SAClG,CAAC,CAAC;IACP,CAAC;IAED;;;;;OAKG;IAEH,gBAAgB;QACZ,OAAO,IAAI,0BAA0B,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;IACrE,CAAC;CACJ;AAJG;IAAC,GAAG;;;oCACgB,0BAA0B;8DAE7C","sourcesContent":["import { errorLoggingDecorator } from \"../logger/errorLoggingDecorator\";\nimport { LensCoreModule } from \"../lens-core-module\";\nimport { getLogger } from \"../logger/logger\";\nimport { LensPerformanceMeasurement } from \"./LensPerformanceMeasurement\";\n\nconst logger = getLogger(\"RenderingMetrics\");\nconst log = errorLoggingDecorator(logger);\n\n/**\n * Use to measure lens rendering performance.\n *\n * The {@link LensPerformanceMetrics.beginMeasurement} method is used to start measuring rendering performance. After\n * a measurement has begun, performance metrics can be read using {@link LensPerformanceMeasurement}.\n *\n * @example\n * ```ts\n * const measurement = cameraKitSession.metrics.beginMeasurement()\n * // some time later\n * console.log(measurement.measure())\n * ```\n *\n * @category Rendering\n * @category Metrics\n */\nexport class LensPerformanceMetrics {\n private readonly measurementInstances: Set<LensPerformanceMeasurement>;\n\n /** @internal */\n constructor(private lensCore: LensCoreModule) {\n this.measurementInstances = new Set();\n this.lensCore.setOnFrameProcessedCallback({\n onFrameProcessed: ({ processingTimeMs }) => {\n try {\n for (const measurement of this.measurementInstances.values()) {\n measurement.update(processingTimeMs);\n }\n } catch (error) {\n logger.error(error);\n }\n },\n onFailure: (error) =>\n logger.error(`Failed registering setOnFrameProcessedCallback with error: ${error.message}`),\n });\n }\n\n /**\n * Begin a measurement window, during which time rendering metrics will be gathered.\n *\n * @returns A {@link LensPerformanceMeasurement} representing an ongoing measurement of aggregated rendering\n * metrics, from which specific metrics can be obtained.\n */\n @log\n beginMeasurement(): LensPerformanceMeasurement {\n return new LensPerformanceMeasurement(this.measurementInstances);\n }\n}\n"]}
1
+ {"version":3,"file":"LensPerformanceMetrics.js","sourceRoot":"","sources":["../../src/session/LensPerformanceMetrics.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAE1E,MAAM,MAAM,GAAG,SAAS,CAAC,kBAAkB,CAAC,CAAC;AAC7C,MAAM,GAAG,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;AAE1C;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,sBAAsB;IAG/B,gBAAgB;IAChB,YAAoB,QAAwB;QAAxB,aAAQ,GAAR,QAAQ,CAAgB;QACxC,IAAI,CAAC,oBAAoB,GAAG,IAAI,GAAG,EAAE,CAAC;QACtC,IAAI,CAAC,QAAQ,CAAC,2BAA2B,CAAC;YACtC,gBAAgB,EAAE,CAAC,EAAE,gBAAgB,EAAE,EAAE,EAAE;gBACvC,IAAI;oBACA,KAAK,MAAM,WAAW,IAAI,IAAI,CAAC,oBAAoB,CAAC,MAAM,EAAE,EAAE;wBAC1D,WAAW,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;qBACxC;iBACJ;gBAAC,OAAO,KAAK,EAAE;oBACZ,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;iBACvB;YACL,CAAC;YACD,SAAS,EAAE,CAAC,KAAK,EAAE,EAAE,CACjB,MAAM,CAAC,KAAK,CAAC,8DAA8D,KAAK,CAAC,OAAO,EAAE,CAAC;SAClG,CAAC,CAAC;IACP,CAAC;IAED;;;;;OAKG;IAEH,gBAAgB;QACZ,OAAO,IAAI,0BAA0B,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;IACrE,CAAC;CACJ;AAHG;IADC,GAAG;;;oCACgB,0BAA0B;8DAE7C","sourcesContent":["import { errorLoggingDecorator } from \"../logger/errorLoggingDecorator\";\nimport { LensCoreModule } from \"../lens-core-module\";\nimport { getLogger } from \"../logger/logger\";\nimport { LensPerformanceMeasurement } from \"./LensPerformanceMeasurement\";\n\nconst logger = getLogger(\"RenderingMetrics\");\nconst log = errorLoggingDecorator(logger);\n\n/**\n * Use to measure lens rendering performance.\n *\n * The {@link LensPerformanceMetrics.beginMeasurement} method is used to start measuring rendering performance. After\n * a measurement has begun, performance metrics can be read using {@link LensPerformanceMeasurement}.\n *\n * @example\n * ```ts\n * const measurement = cameraKitSession.metrics.beginMeasurement()\n * // some time later\n * console.log(measurement.measure())\n * ```\n *\n * @category Rendering\n * @category Metrics\n */\nexport class LensPerformanceMetrics {\n private readonly measurementInstances: Set<LensPerformanceMeasurement>;\n\n /** @internal */\n constructor(private lensCore: LensCoreModule) {\n this.measurementInstances = new Set();\n this.lensCore.setOnFrameProcessedCallback({\n onFrameProcessed: ({ processingTimeMs }) => {\n try {\n for (const measurement of this.measurementInstances.values()) {\n measurement.update(processingTimeMs);\n }\n } catch (error) {\n logger.error(error);\n }\n },\n onFailure: (error) =>\n logger.error(`Failed registering setOnFrameProcessedCallback with error: ${error.message}`),\n });\n }\n\n /**\n * Begin a measurement window, during which time rendering metrics will be gathered.\n *\n * @returns A {@link LensPerformanceMeasurement} representing an ongoing measurement of aggregated rendering\n * metrics, from which specific metrics can be obtained.\n */\n @log\n beginMeasurement(): LensPerformanceMeasurement {\n return new LensPerformanceMeasurement(this.measurementInstances);\n }\n}\n"]}
@@ -13,8 +13,8 @@ declare const createLensState: () => StateMachine<import("@snap/state-management
13
13
  error: LensErrors;
14
14
  lens: Lens;
15
15
  }> | import("@snap/state-management").Action<"removeLens", undefined> | import("@snap/state-management").Action<"turnedOff", Lens> | import("@snap/state-management").Action<"removeLensComplete", undefined> | import("@snap/state-management").Action<"removeLensFailed", Error>, import("@snap/state-management").State<"noLensApplied", undefined> | import("@snap/state-management").State<"applyingLens", Lens> | import("@snap/state-management").State<"lensApplied", Lens>>;
16
- export declare type LensErrors = LegalError | LensContentValidationError | LensError;
17
- export declare type LensState = ReturnType<typeof createLensState>;
16
+ export type LensErrors = LegalError | LensContentValidationError | LensError;
17
+ export type LensState = ReturnType<typeof createLensState>;
18
18
  export declare const lensStateFactory: {
19
19
  (args_0: LensCoreModule, args_1: LensRepository, args_2: LensAssetRepository, args_3: IndexedDBPersistence<ArrayBuffer>, args_4: StateMachine<import("@snap/state-management").Action<"requestLegalPrompt", undefined> | import("@snap/state-management").Action<"accept", string> | import("@snap/state-management").Action<"reject", string>, import("@snap/state-management").State<"unknown", undefined> | import("@snap/state-management").State<"accepted", undefined> | import("@snap/state-management").State<"rejected", undefined>>): StateMachine<import("@snap/state-management").Action<"applyLens", {
20
20
  lens: Lens;