@snap/camera-kit 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +242 -67
- package/docs/html/assets/search.js +1 -1
- package/docs/html/classes/CameraKit.html +116 -100
- package/docs/html/classes/CameraKitSession.html +175 -153
- package/docs/html/classes/CameraKitSource.html +109 -101
- package/docs/html/classes/LensPerformanceMeasurement.html +98 -94
- package/docs/html/classes/LensPerformanceMetrics.html +83 -81
- package/docs/html/classes/LensRepository.html +120 -109
- package/docs/html/classes/LensSources.html +86 -82
- package/docs/html/classes/Transform2D.html +98 -94
- package/docs/html/classes/TypedCustomEvent.html +83 -82
- package/docs/html/classes/TypedEventTarget.html +92 -91
- package/docs/html/functions/Injectable.html +87 -80
- package/docs/html/functions/bootstrapCameraKit.html +89 -86
- package/docs/html/functions/createExtension.html +76 -75
- package/docs/html/functions/createImageSource.html +80 -77
- package/docs/html/functions/createMediaStreamSource.html +80 -77
- package/docs/html/functions/createUserMediaSource.html +84 -81
- package/docs/html/functions/createVideoSource.html +80 -77
- package/docs/html/functions/estimateLensPerformance.html +76 -75
- package/docs/html/functions/getRequiredBootstrapURLs.html +78 -76
- package/docs/html/functions/lensSourcesFactory.html +74 -74
- package/docs/html/functions/uriHandlersFactory.html +76 -75
- package/docs/html/index.html +233 -117
- package/docs/html/interfaces/CameraKitBootstrapConfiguration.html +107 -100
- package/docs/html/interfaces/CameraKitSourceSubscriber.html +82 -81
- package/docs/html/interfaces/ComputedFrameMetrics.html +94 -84
- package/docs/html/interfaces/CreateSessionOptions.html +86 -83
- package/docs/html/interfaces/EstimatedLensPerformance.html +85 -84
- package/docs/html/interfaces/Lens.html +114 -106
- package/docs/html/interfaces/LensSource.html +102 -94
- package/docs/html/interfaces/MediaStreamSourceOptions.html +80 -80
- package/docs/html/interfaces/Preview.html +81 -79
- package/docs/html/interfaces/Snapcode.html +86 -83
- package/docs/html/interfaces/UriCancelRequest.html +80 -80
- package/docs/html/interfaces/UriHandler.html +102 -93
- package/docs/html/interfaces/UriRequest.html +95 -90
- package/docs/html/interfaces/UriResponse.html +89 -89
- package/docs/html/interfaces/VideoSourceOptions.html +77 -77
- package/docs/html/modules.html +153 -153
- package/docs/html/types/AssetLoader.html +75 -74
- package/docs/html/types/AssetTiming.html +75 -74
- package/docs/html/types/BenchmarkError.html +73 -73
- package/docs/html/types/BootstrapError.html +75 -74
- package/docs/html/types/CacheKeyNotFoundError.html +73 -73
- package/docs/html/types/CameraKitDeviceInfo.html +75 -74
- package/docs/html/types/CameraKitSessionEventListener.html +75 -74
- package/docs/html/types/CameraKitSessionEvents.html +82 -74
- package/docs/html/types/CameraKitSourceError.html +73 -73
- package/docs/html/types/CameraKitSourceInfo.html +73 -73
- package/docs/html/types/CameraKitSourceOptions.html +75 -74
- package/docs/html/types/ConfigurationError.html +75 -74
- package/docs/html/types/Keyboard.html +85 -80
- package/docs/html/types/KeyboardEvents.html +84 -74
- package/docs/html/types/LegalError.html +73 -73
- package/docs/html/types/LensAssetError.html +75 -74
- package/docs/html/types/LensContentValidationError.html +73 -73
- package/docs/html/types/LensError.html +73 -73
- package/docs/html/types/LensExecutionError.html +75 -74
- package/docs/html/types/LensImagePickerError.html +75 -74
- package/docs/html/types/LensLaunchParams.html +75 -74
- package/docs/html/types/LensMetricsEvents.html +75 -74
- package/docs/html/types/LensPerformanceCluster.html +75 -74
- package/docs/html/types/LensView.html +75 -74
- package/docs/html/types/LensWait.html +75 -74
- package/docs/html/types/PersistentStoreError.html +75 -74
- package/docs/html/types/PlatformNotSupportedError.html +75 -74
- package/docs/html/types/PublicContainer.html +75 -74
- package/docs/html/types/RenderTarget.html +75 -74
- package/docs/html/types/Uri.html +73 -73
- package/docs/html/types/UriHandlers.html +75 -74
- package/docs/html/types/WebGLError.html +73 -73
- package/docs/html/variables/extensionRequestContext.html +75 -74
- package/docs/md/README.md +242 -67
- package/docs/md/classes/CameraKit.md +14 -1
- package/docs/md/classes/CameraKitSession.md +1 -1
- package/docs/md/classes/CameraKitSource.md +1 -1
- package/docs/md/classes/LensPerformanceMeasurement.md +1 -1
- package/docs/md/classes/LensPerformanceMetrics.md +1 -1
- package/docs/md/classes/LensRepository.md +1 -1
- package/docs/md/classes/LensSources.md +1 -1
- package/docs/md/classes/Transform2D.md +1 -1
- package/docs/md/classes/TypedCustomEvent.md +1 -1
- package/docs/md/classes/TypedEventTarget.md +1 -1
- package/docs/md/interfaces/CameraKitBootstrapConfiguration.md +1 -1
- package/docs/md/interfaces/CameraKitSourceSubscriber.md +1 -1
- package/docs/md/interfaces/ComputedFrameMetrics.md +15 -1
- package/docs/md/interfaces/CreateSessionOptions.md +1 -1
- package/docs/md/interfaces/EstimatedLensPerformance.md +1 -1
- package/docs/md/interfaces/Lens.md +1 -1
- package/docs/md/interfaces/LensSource.md +1 -1
- package/docs/md/interfaces/MediaStreamSourceOptions.md +1 -1
- package/docs/md/interfaces/Preview.md +1 -1
- package/docs/md/interfaces/Snapcode.md +1 -1
- package/docs/md/interfaces/UriCancelRequest.md +1 -1
- package/docs/md/interfaces/UriHandler.md +1 -1
- package/docs/md/interfaces/UriRequest.md +8 -1
- package/docs/md/interfaces/UriResponse.md +1 -1
- package/docs/md/interfaces/VideoSourceOptions.md +1 -1
- package/docs/md/modules.md +2 -2
- package/lib/CameraKit.d.ts +33 -14
- package/lib/CameraKit.js +32 -4
- package/lib/CameraKit.js.map +1 -1
- package/lib/assertPlatformSupported.d.ts +3 -1
- package/lib/assertPlatformSupported.js +13 -2
- package/lib/assertPlatformSupported.js.map +1 -1
- package/lib/bootstrapCameraKit.js +7 -3
- package/lib/bootstrapCameraKit.js.map +1 -1
- package/lib/common/__mocks__/loadScript.d.ts +1 -1
- package/lib/common/__mocks__/loadScript.js +1 -1
- package/lib/common/__mocks__/loadScript.js.map +1 -1
- package/lib/common/cameraKitUserAgent.js +17 -2
- package/lib/common/cameraKitUserAgent.js.map +1 -1
- package/lib/common/dialog.d.ts +59 -0
- package/lib/common/dialog.js +160 -0
- package/lib/common/dialog.js.map +1 -0
- package/lib/common/hash.d.ts +5 -0
- package/lib/common/hash.js +17 -0
- package/lib/common/hash.js.map +1 -0
- package/lib/common/loadScript.d.ts +6 -1
- package/lib/common/loadScript.js +9 -2
- package/lib/common/loadScript.js.map +1 -1
- package/lib/common/localization.d.ts +17 -10
- package/lib/common/localization.js +653 -18
- package/lib/common/localization.js.map +1 -1
- package/lib/common/pageVisibility.d.ts +34 -20
- package/lib/common/pageVisibility.js +57 -48
- package/lib/common/pageVisibility.js.map +1 -1
- package/lib/configuration.d.ts +2 -0
- package/lib/configuration.js +1 -0
- package/lib/configuration.js.map +1 -1
- package/lib/dependency-injection/Container.d.ts +2 -2
- package/lib/dependency-injection/Container.js +10 -10
- package/lib/dependency-injection/Container.js.map +1 -1
- package/lib/dependency-injection/RootServices.d.ts +5 -1
- package/lib/dependency-injection/RootServices.js.map +1 -1
- package/lib/environment.json +1 -1
- package/lib/extensions/LensSources.d.ts +5 -5
- package/lib/extensions/LensSources.js +9 -9
- package/lib/extensions/LensSources.js.map +1 -1
- package/lib/extensions/UriHandlers.d.ts +1 -1
- package/lib/generated-proto/blizzard/cameraKitEvents.js.map +1 -1
- package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.d.ts +0 -26
- package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.js +0 -15
- package/lib/generated-proto/pb_schema/camera_kit/v3/business_events.js.map +1 -1
- package/lib/generated-proto/pb_schema/camera_kit/v3/export.d.ts +0 -59
- package/lib/generated-proto/pb_schema/camera_kit/v3/export.js +0 -10
- package/lib/generated-proto/pb_schema/camera_kit/v3/export.js.map +1 -1
- package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.d.ts +5 -13
- package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.js +61 -7
- package/lib/generated-proto/pb_schema/camera_kit/v3/legal_prompt.js.map +1 -1
- package/lib/generated-proto/pb_schema/camera_kit/v3/lens.d.ts +0 -55
- package/lib/generated-proto/pb_schema/camera_kit/v3/lens.js +0 -12
- package/lib/generated-proto/pb_schema/camera_kit/v3/lens.js.map +1 -1
- package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.d.ts +0 -5
- package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.js +0 -7
- package/lib/generated-proto/pb_schema/camera_kit/v3/operational_metrics.js.map +1 -1
- package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.d.ts +0 -23
- package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.js +0 -15
- package/lib/generated-proto/pb_schema/camera_kit/v3/ranking.js.map +1 -1
- package/lib/generated-proto/pb_schema/camera_kit/v3/service.d.ts +43 -56
- package/lib/generated-proto/pb_schema/camera_kit/v3/service.js +17 -2
- package/lib/generated-proto/pb_schema/camera_kit/v3/service.js.map +1 -1
- package/lib/generated-proto/pb_schema/cdp/cof/benchmark.d.ts +0 -8
- package/lib/generated-proto/pb_schema/cdp/cof/benchmark.js +0 -1
- package/lib/generated-proto/pb_schema/cdp/cof/benchmark.js.map +1 -1
- package/lib/generated-proto/pb_schema/cdp/cof/benchmark_name.d.ts +0 -45
- package/lib/generated-proto/pb_schema/cdp/cof/benchmark_name.js +0 -46
- package/lib/generated-proto/pb_schema/cdp/cof/benchmark_name.js.map +1 -1
- package/lib/generated-proto/pb_schema/cdp/cof/circumstance_service.d.ts +578 -104
- package/lib/generated-proto/pb_schema/cdp/cof/circumstance_service.js +0 -1
- package/lib/generated-proto/pb_schema/cdp/cof/circumstance_service.js.map +1 -1
- package/lib/generated-proto/pb_schema/cdp/cof/config_request.d.ts +0 -129
- package/lib/generated-proto/pb_schema/cdp/cof/config_request.js +0 -24
- package/lib/generated-proto/pb_schema/cdp/cof/config_request.js.map +1 -1
- package/lib/generated-proto/pb_schema/cdp/cof/config_response.d.ts +84 -22
- package/lib/generated-proto/pb_schema/cdp/cof/config_response.js +0 -1
- package/lib/generated-proto/pb_schema/cdp/cof/config_response.js.map +1 -1
- package/lib/generated-proto/pb_schema/cdp/cof/config_result.d.ts +177 -466
- package/lib/generated-proto/pb_schema/cdp/cof/config_result.js +80 -399
- package/lib/generated-proto/pb_schema/cdp/cof/config_result.js.map +1 -1
- package/lib/generated-proto/pb_schema/cdp/cof/debug_info.d.ts +0 -9
- package/lib/generated-proto/pb_schema/cdp/cof/debug_info.js +0 -3
- package/lib/generated-proto/pb_schema/cdp/cof/debug_info.js.map +1 -1
- package/lib/generated-proto/pb_schema/cdp/cof/namespace.d.ts +0 -1
- package/lib/generated-proto/pb_schema/cdp/cof/namespace.js +0 -2
- package/lib/generated-proto/pb_schema/cdp/cof/namespace.js.map +1 -1
- package/lib/generated-proto/pb_schema/common/ruid.d.ts +0 -27
- package/lib/generated-proto/pb_schema/common/ruid.js +0 -20
- package/lib/generated-proto/pb_schema/common/ruid.js.map +1 -1
- package/lib/generated-proto/pb_schema/common/value.d.ts +0 -9
- package/lib/generated-proto/pb_schema/common/value.js +0 -1
- package/lib/generated-proto/pb_schema/common/value.js.map +1 -1
- package/lib/generated-proto/pb_schema/google/protobuf/any.d.ts +0 -105
- package/lib/generated-proto/pb_schema/google/protobuf/any.js +0 -1
- package/lib/generated-proto/pb_schema/google/protobuf/any.js.map +1 -1
- package/lib/generated-proto/pb_schema/google/protobuf/timestamp.d.ts +0 -64
- package/lib/generated-proto/pb_schema/google/protobuf/timestamp.js +0 -1
- package/lib/generated-proto/pb_schema/google/protobuf/timestamp.js.map +1 -1
- package/lib/generated-proto/pb_schema/google/protobuf/wrappers.d.ts +0 -54
- package/lib/generated-proto/pb_schema/google/protobuf/wrappers.js +0 -1
- package/lib/generated-proto/pb_schema/google/protobuf/wrappers.js.map +1 -1
- package/lib/generated-proto/pb_schema/lenses/geocircle.js +0 -1
- package/lib/generated-proto/pb_schema/lenses/geocircle.js.map +1 -1
- package/lib/generated-proto/pb_schema/lenses/geopoint.js +0 -1
- package/lib/generated-proto/pb_schema/lenses/geopoint.js.map +1 -1
- package/lib/generated-proto/pb_schema/lenses/launch_params.js +0 -1
- package/lib/generated-proto/pb_schema/lenses/launch_params.js.map +1 -1
- package/lib/generated-proto/pb_schema/lenses/launchdata.d.ts +0 -2
- package/lib/generated-proto/pb_schema/lenses/launchdata.js +0 -3
- package/lib/generated-proto/pb_schema/lenses/launchdata.js.map +1 -1
- package/lib/generated-proto/pb_schema/lenses/lures.d.ts +0 -2
- package/lib/generated-proto/pb_schema/lenses/lures.js +0 -1
- package/lib/generated-proto/pb_schema/lenses/lures.js.map +1 -1
- package/lib/generated-proto/pb_schema/lenses/persistent_store.js +0 -1
- package/lib/generated-proto/pb_schema/lenses/persistent_store.js.map +1 -1
- package/lib/generated-proto/pb_schema/lenses/snappable.d.ts +0 -19
- package/lib/generated-proto/pb_schema/lenses/snappable.js +0 -2
- package/lib/generated-proto/pb_schema/lenses/snappable.js.map +1 -1
- package/lib/generated-proto/pb_schema/lenses/user_data.d.ts +0 -18
- package/lib/generated-proto/pb_schema/lenses/user_data.js +0 -1
- package/lib/generated-proto/pb_schema/lenses/user_data.js.map +1 -1
- package/lib/handlers/HandlerChainBuilder.js +7 -2
- package/lib/handlers/HandlerChainBuilder.js.map +1 -1
- package/lib/handlers/batchingHandler.d.ts +8 -2
- package/lib/handlers/batchingHandler.js +5 -8
- package/lib/handlers/batchingHandler.js.map +1 -1
- package/lib/handlers/mappingHandler.d.ts +5 -1
- package/lib/handlers/mappingHandler.js +6 -4
- package/lib/handlers/mappingHandler.js.map +1 -1
- package/lib/handlers/rateLimitingHandler.d.ts +5 -1
- package/lib/handlers/rateLimitingHandler.js +6 -4
- package/lib/handlers/rateLimitingHandler.js.map +1 -1
- package/lib/handlers/responseCachingHandler.d.ts +1 -1
- package/lib/handlers/responseCachingHandler.js.map +1 -1
- package/lib/handlers/retryingHandler.d.ts +5 -1
- package/lib/handlers/retryingHandler.js +13 -9
- package/lib/handlers/retryingHandler.js.map +1 -1
- package/lib/legal/legalPrompt.d.ts +7 -4
- package/lib/legal/legalPrompt.js +126 -135
- package/lib/legal/legalPrompt.js.map +1 -1
- package/lib/legal/legalState.d.ts +2 -2
- package/lib/legal/legalState.js +52 -38
- package/lib/legal/legalState.js.map +1 -1
- package/lib/lens/LensRepository.d.ts +5 -3
- package/lib/lens/LensRepository.js +8 -5
- package/lib/lens/LensRepository.js.map +1 -1
- package/lib/lens/assets/LensAssetsProvider.js +18 -3
- package/lib/lens/assets/LensAssetsProvider.js.map +1 -1
- package/lib/lens/lensHttpUtil.d.ts +3 -2
- package/lib/lens/lensHttpUtil.js +5 -5
- package/lib/lens/lensHttpUtil.js.map +1 -1
- package/lib/lens-core-module/generated-types.d.ts +21 -0
- package/lib/lens-core-module/generated-types.js.map +1 -1
- package/lib/lens-core-module/loader/lensCoreFactory.js +3 -1
- package/lib/lens-core-module/loader/lensCoreFactory.js.map +1 -1
- package/lib/lensCoreWasmVersions.json +3 -3
- package/lib/logger/logEntries.d.ts +1 -1
- package/lib/logger/logEntries.js +3 -3
- package/lib/logger/logEntries.js.map +1 -1
- package/lib/logger/logger.d.ts +7 -2
- package/lib/logger/logger.js +9 -4
- package/lib/logger/logger.js.map +1 -1
- package/lib/media-sources/MediaStreamSource.js +13 -4
- package/lib/media-sources/MediaStreamSource.js.map +1 -1
- package/lib/metrics/businessEventsReporter.d.ts +4 -2
- package/lib/metrics/businessEventsReporter.js +27 -14
- package/lib/metrics/businessEventsReporter.js.map +1 -1
- package/lib/metrics/metricsHandler.d.ts +3 -2
- package/lib/metrics/metricsHandler.js +3 -3
- package/lib/metrics/metricsHandler.js.map +1 -1
- package/lib/metrics/operational/Count.d.ts +17 -0
- package/lib/metrics/operational/Count.js +28 -0
- package/lib/metrics/operational/Count.js.map +1 -0
- package/lib/metrics/operational/Histogram.d.ts +17 -0
- package/lib/metrics/operational/Histogram.js +23 -0
- package/lib/metrics/operational/Histogram.js.map +1 -0
- package/lib/metrics/operational/Metric.d.ts +20 -0
- package/lib/metrics/operational/Metric.js +26 -0
- package/lib/metrics/operational/Metric.js.map +1 -0
- package/lib/metrics/operational/Timer.d.ts +91 -0
- package/lib/metrics/operational/Timer.js +122 -0
- package/lib/metrics/operational/Timer.js.map +1 -0
- package/lib/metrics/{operationalMetricsReporter.d.ts → operational/operationalMetricsReporter.d.ts} +16 -4
- package/lib/metrics/{operationalMetricsReporter.js → operational/operationalMetricsReporter.js} +31 -13
- package/lib/metrics/operational/operationalMetricsReporter.js.map +1 -0
- package/lib/metrics/reporters/reportBenchmarks.d.ts +1 -1
- package/lib/metrics/reporters/reportBenchmarks.js +1 -1
- package/lib/metrics/reporters/reportBenchmarks.js.map +1 -1
- package/lib/metrics/reporters/reportGlobalException.d.ts +1 -1
- package/lib/metrics/reporters/reportGlobalException.js +1 -1
- package/lib/metrics/reporters/reportGlobalException.js.map +1 -1
- package/lib/metrics/reporters/reportHttpMetrics.d.ts +1 -1
- package/lib/metrics/reporters/reportHttpMetrics.js +1 -1
- package/lib/metrics/reporters/reportHttpMetrics.js.map +1 -1
- package/lib/metrics/reporters/reportLegalState.d.ts +1 -1
- package/lib/metrics/reporters/reportLegalState.js +1 -1
- package/lib/metrics/reporters/reportLegalState.js.map +1 -1
- package/lib/metrics/reporters/reportLensAndAssetDownload.d.ts +1 -1
- package/lib/metrics/reporters/reportLensAndAssetDownload.js +1 -1
- package/lib/metrics/reporters/reportLensAndAssetDownload.js.map +1 -1
- package/lib/metrics/reporters/reportLensValidationFailed.d.ts +1 -1
- package/lib/metrics/reporters/reportLensView.d.ts +2 -2
- package/lib/metrics/reporters/reportLensView.js +23 -17
- package/lib/metrics/reporters/reportLensView.js.map +1 -1
- package/lib/metrics/reporters/reportLensWait.d.ts +2 -2
- package/lib/metrics/reporters/reportLensWait.js +1 -1
- package/lib/metrics/reporters/reportLensWait.js.map +1 -1
- package/lib/metrics/reporters/reportSessionException.d.ts +1 -1
- package/lib/metrics/reporters/reporters.d.ts +6 -6
- package/lib/metrics/reporters/reporters.js +3 -3
- package/lib/metrics/reporters/reporters.js.map +1 -1
- package/lib/observable-operators/unsubscribed.d.ts +12 -0
- package/lib/observable-operators/unsubscribed.js +27 -0
- package/lib/observable-operators/unsubscribed.js.map +1 -0
- package/lib/remote-configuration/cofHandler.d.ts +11 -7
- package/lib/remote-configuration/cofHandler.js +77 -67
- package/lib/remote-configuration/cofHandler.js.map +1 -1
- package/lib/remote-configuration/remoteConfiguration.d.ts +20 -6
- package/lib/remote-configuration/remoteConfiguration.js +24 -7
- package/lib/remote-configuration/remoteConfiguration.js.map +1 -1
- package/lib/session/CameraKitSession.d.ts +4 -3
- package/lib/session/CameraKitSession.js +6 -5
- package/lib/session/CameraKitSession.js.map +1 -1
- package/lib/session/LensKeyboard.d.ts +1 -1
- package/lib/session/LensPerformanceMeasurement.d.ts +2 -0
- package/lib/session/LensPerformanceMeasurement.js +27 -4
- package/lib/session/LensPerformanceMeasurement.js.map +1 -1
- package/lib/session/lensState.d.ts +5 -4
- package/lib/session/lensState.js +94 -39
- package/lib/session/lensState.js.map +1 -1
- package/package.json +12 -12
- package/lib/metrics/operationalMetricsReporter.js.map +0 -1
|
@@ -4,39 +4,16 @@ import { cameraKitUserAgent } from "../common/cameraKitUserAgent";
|
|
|
4
4
|
import { ensureError } from "../common/errorHelpers";
|
|
5
5
|
import { CircumstancesServiceClientImpl, GrpcWebImpl } from "../generated-proto/pb_schema/cdp/cof/circumstance_service";
|
|
6
6
|
import { HandlerChainBuilder } from "../handlers/HandlerChainBuilder";
|
|
7
|
-
import { dispatchRequestCompleted, dispatchRequestErrored, dispatchRequestStarted, } from "../handlers/requestStateEmittingHandler";
|
|
7
|
+
import { dispatchRequestCompleted, dispatchRequestErrored, dispatchRequestStarted, requestStateEventTargetFactory, } from "../handlers/requestStateEmittingHandler";
|
|
8
8
|
import { createResponseCachingHandler, staleWhileRevalidateStrategy } from "../handlers/responseCachingHandler";
|
|
9
9
|
import { createRetryingHandler } from "../handlers/retryingHandler";
|
|
10
10
|
import { createTimeoutHandler } from "../handlers/timeoutHandler";
|
|
11
11
|
import { ExpiringPersistence } from "../persistence/ExpiringPersistence";
|
|
12
12
|
import { IndexedDBPersistence } from "../persistence/IndexedDBPersistence";
|
|
13
|
+
import { operationalMetricReporterFactory, } from "../metrics/operational/operationalMetricsReporter";
|
|
14
|
+
import { configurationToken } from "../configuration";
|
|
15
|
+
import { Injectable } from "../dependency-injection/Injectable";
|
|
13
16
|
const id = (h) => h;
|
|
14
|
-
// We need to wrap `targetingQuery` to create a usable Handler – the main issue is that HandlerChainBuilder always adds
|
|
15
|
-
// a `signal` property to the metadata argument (second argument of the Handler), but `targetingQuery` expects the
|
|
16
|
-
// second argument to only contain headers.
|
|
17
|
-
const createTargetingQueryHandler = (apiToken) => (request, _a) => __awaiter(void 0, void 0, void 0, function* () {
|
|
18
|
-
var { signal, isSideEffect: _ } = _a, metadata = __rest(_a, ["signal", "isSideEffect"]);
|
|
19
|
-
const rpc = new GrpcWebImpl("https://api-kit.snapchat.com", {});
|
|
20
|
-
const client = new CircumstancesServiceClientImpl(rpc);
|
|
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
|
-
});
|
|
39
|
-
});
|
|
40
17
|
export const COF_REQUEST_TYPE = "cof";
|
|
41
18
|
/**
|
|
42
19
|
* Handler chain used to make COF requests. Uses the COF client to perform the
|
|
@@ -46,47 +23,80 @@ export const COF_REQUEST_TYPE = "cof";
|
|
|
46
23
|
* immediately and the cache is updated in the background. If no response is found, a COF request is made. This request
|
|
47
24
|
* will retry (with exponential backoff + jitter) for 5 seconds before returning an error to the caller.
|
|
48
25
|
*/
|
|
49
|
-
export const cofHandlerFactory = (
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
26
|
+
export const cofHandlerFactory = Injectable("cofHandler", [configurationToken, requestStateEventTargetFactory.token, operationalMetricReporterFactory.token], (config, requestStateEventTarget, reporter) => {
|
|
27
|
+
// We need to wrap `targetingQuery` to create a usable Handler – the main issue is that HandlerChainBuilder
|
|
28
|
+
// always adds a `signal` property to the metadata argument (second argument of the Handler), but
|
|
29
|
+
// `targetingQuery` expects the second argument to only contain headers.
|
|
30
|
+
return (new HandlerChainBuilder((request, _a) => __awaiter(void 0, void 0, void 0, function* () {
|
|
31
|
+
var { signal, isSideEffect: _ } = _a, metadata = __rest(_a, ["signal", "isSideEffect"]);
|
|
32
|
+
const rpc = new GrpcWebImpl(`https://${config.apiHostname}`, {});
|
|
33
|
+
const client = new CircumstancesServiceClientImpl(rpc);
|
|
34
|
+
return new Promise((resolve, reject) => {
|
|
35
|
+
if (signal) {
|
|
36
|
+
signal.addEventListener("abort", () => reject(new Error("COF request aborted by handler chain.")));
|
|
37
|
+
}
|
|
38
|
+
client
|
|
39
|
+
.targetingQuery(request, new BrowserHeaders(Object.assign({ authorization: `Bearer ${config.apiToken}`, "x-snap-client-user-agent": cameraKitUserAgent.userAgent }, metadata)))
|
|
40
|
+
.then((response) => {
|
|
41
|
+
// NOTE: in order for cache persistance to work, we need to make the object cloneable,
|
|
42
|
+
// i.e. with no methods (it appears targetingQuery() attaches toObject() to response
|
|
43
|
+
// object). Safety: We have to cast response object to a type that has toObject
|
|
44
|
+
// defined, because that is indeed what generated code has:
|
|
45
|
+
// eslint-disable-next-line max-len
|
|
46
|
+
// 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
|
|
47
|
+
delete response.toObject;
|
|
48
|
+
resolve(response);
|
|
49
|
+
})
|
|
50
|
+
.catch(reject);
|
|
51
|
+
});
|
|
52
|
+
}))
|
|
53
|
+
.map(id((next) => (request, metadata) => __awaiter(void 0, void 0, void 0, function* () {
|
|
54
|
+
const dimensions = { requestType: COF_REQUEST_TYPE };
|
|
55
|
+
const { requestId } = dispatchRequestStarted(requestStateEventTarget, { dimensions });
|
|
61
56
|
try {
|
|
62
|
-
|
|
57
|
+
const response = yield next(request, metadata);
|
|
58
|
+
// TODO: We hardcode status code and sizeByte values because we do not have access to
|
|
59
|
+
// underlying transport of configs-web.
|
|
60
|
+
// When this ticket is done https://jira.sc-corp.net/browse/CAMKIT-2840,
|
|
61
|
+
// we will remove this handler and benefit from existing ones.
|
|
62
|
+
const status = 200;
|
|
63
|
+
let sizeByte = 0;
|
|
64
|
+
try {
|
|
65
|
+
sizeByte = new TextEncoder().encode(JSON.stringify(response)).byteLength;
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
dispatchRequestCompleted(requestStateEventTarget, {
|
|
69
|
+
requestId,
|
|
70
|
+
dimensions,
|
|
71
|
+
status,
|
|
72
|
+
sizeByte,
|
|
73
|
+
});
|
|
74
|
+
return response;
|
|
75
|
+
}
|
|
63
76
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
77
|
+
catch (error) {
|
|
78
|
+
dispatchRequestErrored(requestStateEventTarget, {
|
|
79
|
+
requestId,
|
|
80
|
+
dimensions,
|
|
81
|
+
error: ensureError(error),
|
|
82
|
+
});
|
|
83
|
+
throw error;
|
|
67
84
|
}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
})
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
//
|
|
79
|
-
//
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
//
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
// COF responses will be removed from cache after 1 week. Keep in mind that the staleWhileRevalidate
|
|
86
|
-
// strategy will update the cache each time COF is requested – this expiration comes into play only if
|
|
87
|
-
// e.g. a user doesn't load the page for more than a week.
|
|
88
|
-
new ExpiringPersistence(() => 7 * 24 * 60 * 60, new IndexedDBPersistence({ databaseName: "COFCache" })), (r) => JSON.stringify(r),
|
|
89
|
-
// If we have a matching response already in cache, we'll return it immediately and then update the
|
|
90
|
-
// cache in the background.
|
|
91
|
-
staleWhileRevalidateStrategy({ requestType: "cof", reporter }))).handler;
|
|
85
|
+
})))
|
|
86
|
+
// targetingQuery() always converts failed responses into errors (unlike fetch()), so we need a custom
|
|
87
|
+
// retryPredicate that retries all errors. We'll keep retrying (with backoff) for 20 seconds total
|
|
88
|
+
// elapsed time before we return an error back up the chain.
|
|
89
|
+
.map(createRetryingHandler({ retryPredicate: (r) => r instanceof Error }))
|
|
90
|
+
// API gateway has 15 seconds timeout, so we rely on that first
|
|
91
|
+
.map(createTimeoutHandler({ timeout: 20 * 1000 }))
|
|
92
|
+
.map(createResponseCachingHandler(
|
|
93
|
+
// COF responses will be removed from cache after 1 week. Keep in mind that the
|
|
94
|
+
// staleWhileRevalidate strategy will update the cache each time COF is requested
|
|
95
|
+
// – this expiration comes into play only if e.g. a user doesn't load the page
|
|
96
|
+
// for more than a week.
|
|
97
|
+
new ExpiringPersistence(() => 7 * 24 * 60 * 60, new IndexedDBPersistence({ databaseName: "COFCache" })), (r) => JSON.stringify(r),
|
|
98
|
+
// If we have a matching response already in cache,
|
|
99
|
+
// we'll return it immediately and then update the cache in the background.
|
|
100
|
+
staleWhileRevalidateStrategy({ requestType: "cof", reporter }))).handler);
|
|
101
|
+
});
|
|
92
102
|
//# sourceMappingURL=cofHandler.js.map
|
|
@@ -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,EAEH,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;AAO3E,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,CACI,OAAwC,EACxC,EAAoE,EACtE,EAAE;QADA,EAAE,MAAM,EAAE,YAAY,EAAE,CAAC,OAA2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,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,CAAC,EAAE,WAAW,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CACjE,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 RequestStateEventTarget,\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\";\nimport { OperationalMetricsReporter } from \"../metrics/operationalMetricsReporter\";\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 (\n request: Partial<ConfigTargetingRequest>,\n { signal, isSideEffect: _, ...metadata }: Metadata & RequestMetadata\n ) => {\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 = (\n requestStateEventTarget: RequestStateEventTarget,\n apiToken: string,\n reporter: OperationalMetricsReporter\n) =>\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(requestStateEventTarget, { 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(requestStateEventTarget, { requestId, dimensions, status, sizeByte });\n return response;\n }\n } catch (error) {\n dispatchRequestErrored(requestStateEventTarget, {\n requestId,\n dimensions,\n error: ensureError(error),\n });\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({ requestType: \"cof\", reporter })\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,E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serHeaders } 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 RequestStateEventTarget,\n dispatchRequestCompleted,\n dispatchRequestErrored,\n dispatchRequestStarted,\n requestStateEventTargetFactory,\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\";\nimport {\n OperationalMetricsReporter,\n operationalMetricReporterFactory,\n} from \"../metrics/operational/operationalMetricsReporter\";\nimport { CameraKitConfiguration, configurationToken } from \"../configuration\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\n\nexport interface Metadata {\n [key: string]: string;\n}\n\nconst id = <Req, Res, Meta extends RequestMetadata>(h: ChainableHandler<Req, Res, Req, Res, Meta>) => h;\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 = Injectable(\n \"cofHandler\",\n [configurationToken, requestStateEventTargetFactory.token, operationalMetricReporterFactory.token] as const,\n (\n config: CameraKitConfiguration,\n requestStateEventTarget: RequestStateEventTarget,\n reporter: OperationalMetricsReporter\n ) => {\n // We need to wrap `targetingQuery` to create a usable Handler – the main issue is that HandlerChainBuilder\n // always adds a `signal` property to the metadata argument (second argument of the Handler), but\n // `targetingQuery` expects the second argument to only contain headers.\n return (\n new HandlerChainBuilder(\n async (\n request: Partial<ConfigTargetingRequest>,\n { signal, isSideEffect: _, ...metadata }: Metadata & RequestMetadata\n ) => {\n const rpc = new GrpcWebImpl(`https://${config.apiHostname}`, {});\n const client = new CircumstancesServiceClientImpl(rpc);\n return new Promise<ConfigTargetingResponse>((resolve, reject) => {\n if (signal) {\n signal.addEventListener(\"abort\", () =>\n reject(new Error(\"COF request aborted by handler chain.\"))\n );\n }\n client\n .targetingQuery(\n request,\n new BrowserHeaders({\n authorization: `Bearer ${config.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\n // object). Safety: We have to cast response object to a type that has toObject\n // defined, because that is 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 )\n .map(\n id((next) => async (request, metadata) => {\n const dimensions: CofDimensions = { requestType: COF_REQUEST_TYPE };\n const { requestId } = dispatchRequestStarted(requestStateEventTarget, { 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\n // underlying 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(requestStateEventTarget, {\n requestId,\n dimensions,\n status,\n sizeByte,\n });\n return response;\n }\n } catch (error) {\n dispatchRequestErrored(requestStateEventTarget, {\n requestId,\n dimensions,\n error: ensureError(error),\n });\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\n // elapsed 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\n // staleWhileRevalidate strategy will update the cache each time COF is requested\n // – this expiration comes into play only if e.g. a user doesn't load the page\n // 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,\n // we'll return it immediately and then update the cache in the background.\n staleWhileRevalidateStrategy({ requestType: \"cof\", reporter })\n )\n ).handler\n );\n }\n);\n"]}
|
|
@@ -1,15 +1,29 @@
|
|
|
1
1
|
import { Observable } from "rxjs";
|
|
2
|
-
import { CameraKitConfiguration } from "../configuration";
|
|
2
|
+
import { CameraKitApiHostname, CameraKitConfiguration } from "../configuration";
|
|
3
|
+
import { ConfigTargetingRequest } from "../generated-proto/pb_schema/cdp/cof/config_request";
|
|
3
4
|
import { ConfigResult } from "../generated-proto/pb_schema/cdp/cof/config_result";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
5
|
+
import { GetInitializationConfigResponse } from "../generated-proto/pb_schema/camera_kit/v3/service";
|
|
6
|
+
import { FetchHandler } from "../handlers";
|
|
7
|
+
import { cofHandlerFactory } from "./cofHandler";
|
|
8
|
+
export type InitializationConfig = GetInitializationConfigResponse;
|
|
6
9
|
export declare class RemoteConfiguration {
|
|
7
10
|
private readonly configById;
|
|
8
|
-
|
|
11
|
+
private readonly initializationConfig;
|
|
12
|
+
constructor(lensPerformance: CameraKitConfiguration["lensPerformance"], apiHostname: CameraKitApiHostname, cofHandler: ReturnType<typeof cofHandlerFactory>, fetchHandler: FetchHandler);
|
|
13
|
+
/**
|
|
14
|
+
* COF configuration.
|
|
15
|
+
*/
|
|
9
16
|
get(configId: string): Observable<ConfigResult[]>;
|
|
17
|
+
/**
|
|
18
|
+
* Configuration that is provided by Camera Kit backend.
|
|
19
|
+
*/
|
|
20
|
+
getIntializationConfig(): Observable<InitializationConfig>;
|
|
10
21
|
}
|
|
11
22
|
export declare const remoteConfigurationFactory: {
|
|
12
|
-
(args_0: CameraKitConfiguration, args_1:
|
|
23
|
+
(args_0: CameraKitConfiguration, args_1: import("../handlers/HandlerChainBuilder").Handler<Partial<ConfigTargetingRequest>, import("../generated-proto/pb_schema/cdp/cof/config_response").ConfigTargetingResponse, import("./cofHandler").Metadata & {
|
|
24
|
+
signal?: AbortSignal | null | undefined;
|
|
25
|
+
isSideEffect?: boolean | undefined;
|
|
26
|
+
}>, args_2: FetchHandler): RemoteConfiguration;
|
|
13
27
|
token: "remoteConfiguration";
|
|
14
|
-
dependencies: readonly ["configuration", "
|
|
28
|
+
dependencies: readonly ["configuration", "cofHandler", "cameraKitServiceFetchHandler"];
|
|
15
29
|
};
|
|
@@ -1,20 +1,19 @@
|
|
|
1
|
-
import { from, map, mergeMap, shareReplay, take } from "rxjs";
|
|
1
|
+
import { from, map, mergeMap, Observable, shareReplay, take } from "rxjs";
|
|
2
2
|
import { configurationToken } from "../configuration";
|
|
3
3
|
import { Injectable } from "../dependency-injection/Injectable";
|
|
4
4
|
import { Namespace } from "../generated-proto/pb_schema/cdp/cof/namespace";
|
|
5
|
-
import {
|
|
6
|
-
import { requestStateEventTargetFactory } from "../handlers/requestStateEmittingHandler";
|
|
5
|
+
import { cameraKitServiceFetchHandlerFactory } from "../handlers";
|
|
7
6
|
import { cofHandlerFactory } from "./cofHandler";
|
|
8
7
|
const defaultTargetingRequest = {
|
|
9
8
|
namespaces: [Namespace.LENS_CORE, Namespace.CAMERA_KIT_CORE],
|
|
10
9
|
};
|
|
10
|
+
const initializeConfigRelativePath = "/com.snap.camerakit.v3.Metrics/metrics/initialization_config";
|
|
11
11
|
export class RemoteConfiguration {
|
|
12
|
-
constructor(
|
|
12
|
+
constructor(lensPerformance, apiHostname, cofHandler, fetchHandler) {
|
|
13
13
|
const lensCluster = Promise.resolve(lensPerformance).then((lensPerformance) => {
|
|
14
14
|
// `0` means no cluster could be determined. For COF, we'll omit a value in that case.
|
|
15
15
|
return (lensPerformance === null || lensPerformance === void 0 ? void 0 : lensPerformance.cluster) === 0 ? undefined : lensPerformance === null || lensPerformance === void 0 ? void 0 : lensPerformance.cluster;
|
|
16
16
|
});
|
|
17
|
-
const cofHandler = cofHandlerFactory(requestStateEventTarget, apiToken, reporter);
|
|
18
17
|
this.configById = from(lensCluster).pipe(
|
|
19
18
|
// Note: we don't catch errors here, purposefully letting them propagate to subscribers outside this class.
|
|
20
19
|
// Subscribers, having more context about the config use-case, will know better how to handle an error than
|
|
@@ -30,13 +29,31 @@ export class RemoteConfiguration {
|
|
|
30
29
|
});
|
|
31
30
|
return configById;
|
|
32
31
|
}), shareReplay(1));
|
|
32
|
+
this.initializationConfig = new Observable((observer) => {
|
|
33
|
+
fetchHandler(`https://${apiHostname}${initializeConfigRelativePath}`)
|
|
34
|
+
.then((response) => response.json())
|
|
35
|
+
.then((data) => {
|
|
36
|
+
observer.next(data);
|
|
37
|
+
observer.complete();
|
|
38
|
+
})
|
|
39
|
+
.catch((err) => observer.error(err));
|
|
40
|
+
}).pipe(shareReplay(1));
|
|
33
41
|
}
|
|
42
|
+
/**
|
|
43
|
+
* COF configuration.
|
|
44
|
+
*/
|
|
34
45
|
get(configId) {
|
|
35
46
|
return this.configById.pipe(map((config) => { var _a; return (_a = config.get(configId)) !== null && _a !== void 0 ? _a : []; }));
|
|
36
47
|
}
|
|
48
|
+
/**
|
|
49
|
+
* Configuration that is provided by Camera Kit backend.
|
|
50
|
+
*/
|
|
51
|
+
getIntializationConfig() {
|
|
52
|
+
return this.initializationConfig;
|
|
53
|
+
}
|
|
37
54
|
}
|
|
38
|
-
export const remoteConfigurationFactory = Injectable("remoteConfiguration", [configurationToken,
|
|
39
|
-
const remoteConfig = new RemoteConfiguration(
|
|
55
|
+
export const remoteConfigurationFactory = Injectable("remoteConfiguration", [configurationToken, cofHandlerFactory.token, cameraKitServiceFetchHandlerFactory.token], (config, cofHandler, fetchHandler) => {
|
|
56
|
+
const remoteConfig = new RemoteConfiguration(config.lensPerformance, config.apiHostname, cofHandler, fetchHandler);
|
|
40
57
|
// We'll kick off remote configuration loading by subscribing (and then unsubscribing) to a dummy config value.
|
|
41
58
|
// Subsequent requests for config will use the shared Observable, benefitting from this eager loading.
|
|
42
59
|
remoteConfig.get("").pipe(take(1)).subscribe();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remoteConfiguration.js","sourceRoot":"","sources":["../../src/remote-configuration/remoteConfiguration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,QAAQ,
|
|
1
|
+
{"version":3,"file":"remoteConfiguration.js","sourceRoot":"","sources":["../../src/remote-configuration/remoteConfiguration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,QAAQ,EAAE,UAAU,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1E,OAAO,EAAgD,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACpG,OAAO,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAC;AAGhE,OAAO,EAAE,SAAS,EAAE,MAAM,gDAAgD,CAAC;AAE3E,OAAO,EAAE,mCAAmC,EAAgB,MAA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eAAe,EACtB,MAAM,CAAC,WAAW,EAClB,UAAU,EACV,YAAY,CACf,CAAC;IAEF,+GAA+G;IAC/G,sGAAsG;IACtG,YAAY,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC;IAE/C,OAAO,YAAY,CAAC;AACxB,CAAC,CACJ,CAAC","sourcesContent":["import { from, map, mergeMap, Observable, shareReplay, take } from \"rxjs\";\nimport { CameraKitApiHostname, CameraKitConfiguration, configurationToken } from \"../configuration\";\nimport { Injectable } from \"../dependency-injection/Injectable\";\nimport { ConfigTargetingRequest } from \"../generated-proto/pb_schema/cdp/cof/config_request\";\nimport { ConfigResult } from \"../generated-proto/pb_schema/cdp/cof/config_result\";\nimport { Namespace } from \"../generated-proto/pb_schema/cdp/cof/namespace\";\nimport { GetInitializationConfigResponse } from \"../generated-proto/pb_schema/camera_kit/v3/service\";\nimport { cameraKitServiceFetchHandlerFactory, FetchHandler } from \"../handlers\";\nimport { cofHandlerFactory } from \"./cofHandler\";\n\nconst defaultTargetingRequest: Partial<ConfigTargetingRequest> = {\n namespaces: [Namespace.LENS_CORE, Namespace.CAMERA_KIT_CORE],\n};\n\nconst initializeConfigRelativePath = \"/com.snap.camerakit.v3.Metrics/metrics/initialization_config\";\n\nexport type InitializationConfig = GetInitializationConfigResponse;\n\nexport class RemoteConfiguration {\n private readonly configById: Observable<Map<string, ConfigResult[]>>;\n private readonly initializationConfig: Observable<InitializationConfig>;\n\n constructor(\n lensPerformance: CameraKitConfiguration[\"lensPerformance\"],\n apiHostname: CameraKitApiHostname,\n cofHandler: ReturnType<typeof cofHandlerFactory>,\n fetchHandler: FetchHandler\n ) {\n const lensCluster = Promise.resolve(lensPerformance).then((lensPerformance) => {\n // `0` means no cluster could be determined. For COF, we'll omit a value in that case.\n return lensPerformance?.cluster === 0 ? undefined : lensPerformance?.cluster;\n });\n\n this.configById = from(lensCluster).pipe(\n // Note: we don't catch errors here, purposefully letting them propagate to subscribers outside this class.\n // Subscribers, having more context about the config use-case, will know better how to handle an error than\n // we do here (e.g. their logging / reporting will have more context, and they can use the error they get\n // from this Observable as a cause).\n mergeMap((lensClusterOrig4) =>\n from(\n cofHandler({\n ...defaultTargetingRequest,\n lensClusterOrig4,\n })\n )\n ),\n map((result) => {\n const configById = new Map<string, ConfigResult[]>();\n result.configResults.forEach((config) => {\n const configsWithId = configById.get(config.configId) ?? [];\n configsWithId.push(config);\n configById.set(config.configId, configsWithId);\n });\n return configById;\n }),\n shareReplay(1)\n );\n\n this.initializationConfig = new Observable<InitializationConfig>((observer) => {\n fetchHandler(`https://${apiHostname}${initializeConfigRelativePath}`)\n .then((response) => response.json())\n .then((data) => {\n observer.next(data);\n observer.complete();\n })\n .catch((err) => observer.error(err));\n }).pipe(shareReplay(1));\n }\n\n /**\n * COF configuration.\n */\n get(configId: string): Observable<ConfigResult[]> {\n return this.configById.pipe(map((config) => config.get(configId) ?? []));\n }\n\n /**\n * Configuration that is provided by Camera Kit backend.\n */\n getIntializationConfig(): Observable<InitializationConfig> {\n return this.initializationConfig;\n }\n}\n\nexport const remoteConfigurationFactory = Injectable(\n \"remoteConfiguration\",\n [configurationToken, cofHandlerFactory.token, cameraKitServiceFetchHandlerFactory.token] as const,\n (\n config: CameraKitConfiguration,\n cofHandler: ReturnType<typeof cofHandlerFactory>,\n fetchHandler: FetchHandler\n ): RemoteConfiguration => {\n const remoteConfig = new RemoteConfiguration(\n config.lensPerformance,\n config.apiHostname,\n cofHandler,\n fetchHandler\n );\n\n // We'll kick off remote configuration loading by subscribing (and then unsubscribing) to a dummy config value.\n // Subsequent requests for config will use the shared Observable, benefitting from this eager loading.\n remoteConfig.get(\"\").pipe(take(1)).subscribe();\n\n return remoteConfig;\n }\n);\n"]}
|
|
@@ -5,6 +5,7 @@ import { LensLaunchParams } from "../lens/LensLaunchParams";
|
|
|
5
5
|
import { TypedEventTarget } from "../events/TypedEventTarget";
|
|
6
6
|
import { CameraKitDeviceInfo, CameraKitSource } from "../media-sources/CameraKitSource";
|
|
7
7
|
import { LogEntry } from "../logger/logger";
|
|
8
|
+
import { PageVisibility } from "../common/pageVisibility";
|
|
8
9
|
import { LensPerformanceMetrics } from "./LensPerformanceMetrics";
|
|
9
10
|
import { LensState } from "./lensState";
|
|
10
11
|
import { SessionState } from "./sessionState";
|
|
@@ -97,7 +98,7 @@ export declare class CameraKitSession {
|
|
|
97
98
|
/**
|
|
98
99
|
* Use this to interact with lenses which require text input.
|
|
99
100
|
*/
|
|
100
|
-
keyboard: Keyboard, lensCore: LensCoreModule, sessionState: SessionState, lensState: LensState, logEntries: Observable<LogEntry
|
|
101
|
+
keyboard: Keyboard, lensCore: LensCoreModule, sessionState: SessionState, lensState: LensState, logEntries: Observable<LogEntry>, pageVisibility: PageVisibility);
|
|
101
102
|
/**
|
|
102
103
|
* Apply a Lens to this session.
|
|
103
104
|
*
|
|
@@ -245,7 +246,7 @@ export declare const cameraKitSessionFactory: {
|
|
|
245
246
|
}> | import("@snap/state-management").Action<"downloadComplete", Lens> | import("@snap/state-management").Action<"turnedOn", Lens> | import("@snap/state-management").Action<"resourcesLoaded", Lens> | import("@snap/state-management").Action<"firstFrameProcessed", Lens> | import("@snap/state-management").Action<"applyLensComplete", Lens> | import("@snap/state-management").Action<"applyLensFailed", {
|
|
246
247
|
error: import("./lensState").LensErrors;
|
|
247
248
|
lens: Lens;
|
|
248
|
-
}> | 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
|
|
249
|
+
}> | import("@snap/state-management").Action<"applyLensAborted", Lens> | import("@snap/state-management").Action<"removeLens", undefined> | import("@snap/state-management").Action<"turnedOff", Lens> | import("@snap/state-management").Action<"removeLensComplete", undefined> | import("@snap/state-management").Action<"removeLensFailed", Error>, import("@snap/state-management").State<"noLensApplied", undefined> | import("@snap/state-management").State<"applyingLens", Lens> | import("@snap/state-management").State<"lensApplied", Lens>>, args_5: PageVisibility): CameraKitSession;
|
|
249
250
|
token: "CameraKitSession";
|
|
250
|
-
dependencies: readonly ["lensCore", "logEntries", "lensKeyboard", "sessionState", "lensState"];
|
|
251
|
+
dependencies: readonly ["lensCore", "logEntries", "lensKeyboard", "sessionState", "lensState", "pageVisibility"];
|
|
251
252
|
};
|
|
@@ -5,7 +5,6 @@ import { dispatch, forActions, inStates, isAction, isState } from "@snap/state-m
|
|
|
5
5
|
import { isLens } from "../lens";
|
|
6
6
|
import { Injectable } from "../dependency-injection/Injectable";
|
|
7
7
|
import { lensCoreFactory } from "../lens-core-module/loader/lensCoreFactory";
|
|
8
|
-
import { onPageHidden, onPageVisible } from "../common/pageVisibility";
|
|
9
8
|
import { getTypeName, guard, validate } from "../common/validate";
|
|
10
9
|
import { TypedEventTarget } from "../events/TypedEventTarget";
|
|
11
10
|
import { TypedCustomEvent } from "../events/TypedCustomEvent";
|
|
@@ -15,6 +14,7 @@ import { createVideoSource } from "../media-sources/VideoSource";
|
|
|
15
14
|
import { getLogger } from "../logger/logger";
|
|
16
15
|
import { errorLoggingDecorator } from "../logger/errorLoggingDecorator";
|
|
17
16
|
import { logEntriesFactory } from "../logger/logEntries";
|
|
17
|
+
import { pageVisibilityFactory } from "../common/pageVisibility";
|
|
18
18
|
import { LensPerformanceMetrics } from "./LensPerformanceMetrics";
|
|
19
19
|
import { lensStateFactory } from "./lensState";
|
|
20
20
|
import { sessionStateFactory } from "./sessionState";
|
|
@@ -51,7 +51,7 @@ export class CameraKitSession {
|
|
|
51
51
|
/**
|
|
52
52
|
* Use this to interact with lenses which require text input.
|
|
53
53
|
*/
|
|
54
|
-
keyboard, lensCore, sessionState, lensState, logEntries) {
|
|
54
|
+
keyboard, lensCore, sessionState, lensState, logEntries, pageVisibility) {
|
|
55
55
|
this.keyboard = keyboard;
|
|
56
56
|
this.lensCore = lensCore;
|
|
57
57
|
this.sessionState = sessionState;
|
|
@@ -80,8 +80,8 @@ export class CameraKitSession {
|
|
|
80
80
|
};
|
|
81
81
|
this.playing = false;
|
|
82
82
|
this.metrics = new LensPerformanceMetrics(this.lensCore);
|
|
83
|
-
const removeOnHidden = onPageHidden(() => this.sessionState.dispatch("suspend", this));
|
|
84
|
-
const removeOnVisible = onPageVisible(() => this.sessionState.dispatch("resume", this));
|
|
83
|
+
const removeOnHidden = pageVisibility.onPageHidden(() => this.sessionState.dispatch("suspend", this));
|
|
84
|
+
const removeOnVisible = pageVisibility.onPageVisible(() => this.sessionState.dispatch("resume", this));
|
|
85
85
|
this.removePageVisibilityHandlers = () => {
|
|
86
86
|
removeOnHidden();
|
|
87
87
|
removeOnVisible();
|
|
@@ -435,5 +435,6 @@ export const cameraKitSessionFactory = Injectable("CameraKitSession", [
|
|
|
435
435
|
lensKeyboardFactory.token,
|
|
436
436
|
sessionStateFactory.token,
|
|
437
437
|
lensStateFactory.token,
|
|
438
|
-
|
|
438
|
+
pageVisibilityFactory.token,
|
|
439
|
+
], (lensCore, logEntries, keyboard, sessionState, lensState, pageVisibility) => new CameraKitSession(keyboard, lensCore, sessionState, lensState, logEntries, pageVisibility));
|
|
439
440
|
//# sourceMappingURL=CameraKitSession.js.map
|
|
@@ -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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AAgC,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 { getTypeName, 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 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 occurred 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 occurred 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 ${getTypeName(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,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,QAAwB,EACxB,UAAgC,EAChC,QAAsB,EACtB,YAA0B,EAC1B,SAAoB,EACpB,cAA8B,EAChC,EAAE,CAAC,IAAI,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,YAAY,EAAE,SAAS,EAAE,UAAU,EAAE,cAAc,CAAC,CACrG,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 { getTypeName, 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 { PageVisibility, pageVisibilityFactory } from \"../common/pageVisibility\";\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 pageVisibility: PageVisibility\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 = pageVisibility.onPageHidden(() => this.sessionState.dispatch(\"suspend\", this));\n const removeOnVisible = pageVisibility.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 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 occurred 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 occurred 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 ${getTypeName(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 pageVisibilityFactory.token,\n ] as const,\n (\n lensCore: LensCoreModule,\n logEntries: Observable<LogEntry>,\n keyboard: LensKeyboard,\n sessionState: SessionState,\n lensState: LensState,\n pageVisibility: PageVisibility\n ) => new CameraKitSession(keyboard, lensCore, sessionState, lensState, logEntries, pageVisibility)\n);\n"]}
|
|
@@ -83,7 +83,7 @@ export declare const lensKeyboardFactory: {
|
|
|
83
83
|
}> | import("@snap/state-management").Action<"downloadComplete", Lens> | import("@snap/state-management").Action<"turnedOn", Lens> | import("@snap/state-management").Action<"resourcesLoaded", Lens> | import("@snap/state-management").Action<"firstFrameProcessed", Lens> | import("@snap/state-management").Action<"applyLensComplete", Lens> | import("@snap/state-management").Action<"applyLensFailed", {
|
|
84
84
|
error: import("./lensState").LensErrors;
|
|
85
85
|
lens: Lens;
|
|
86
|
-
}> | 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>>): LensKeyboard;
|
|
86
|
+
}> | import("@snap/state-management").Action<"applyLensAborted", Lens> | import("@snap/state-management").Action<"removeLens", undefined> | import("@snap/state-management").Action<"turnedOff", Lens> | import("@snap/state-management").Action<"removeLensComplete", undefined> | import("@snap/state-management").Action<"removeLensFailed", Error>, import("@snap/state-management").State<"noLensApplied", undefined> | import("@snap/state-management").State<"applyingLens", Lens> | import("@snap/state-management").State<"lensApplied", Lens>>): LensKeyboard;
|
|
87
87
|
token: "lensKeyboard";
|
|
88
88
|
dependencies: readonly ["lensState"];
|
|
89
89
|
};
|