@snap/camera-kit
Version:
Camera Kit Web
1,066 lines (683 loc) • 36.4 kB
Markdown
[CameraKit Web SDK - v0.22.0](README.md) / Exports
# CameraKit Web SDK - v0.22.0
## Table of contents
### Enumerations
- [Lens\_CameraFacing](enums/Lens_CameraFacing.md)
### Classes
- [CameraKit](classes/CameraKit.md)
- [TypedCustomEvent](classes/TypedCustomEvent.md)
- [TypedEventTarget](classes/TypedEventTarget.md)
- [LensRepository](classes/LensRepository.md)
- [CameraKitSource](classes/CameraKitSource.md)
- [CameraKitSession](classes/CameraKitSession.md)
- [LensPerformanceMeasurement](classes/LensPerformanceMeasurement.md)
- [LensPerformanceMetrics](classes/LensPerformanceMetrics.md)
- [Transform2D](classes/Transform2D.md)
### Interfaces
- [CreateSessionOptions](interfaces/CreateSessionOptions.md)
- [EstimatedLensPerformance](interfaces/EstimatedLensPerformance.md)
- [CameraKitBootstrapConfiguration](interfaces/CameraKitBootstrapConfiguration.md)
- [RemoteApiRequest](interfaces/RemoteApiRequest.md)
- [RemoteApiResponse](interfaces/RemoteApiResponse.md)
- [RemoteApiService](interfaces/RemoteApiService.md)
- [UriRequest](interfaces/UriRequest.md)
- [UriResponse](interfaces/UriResponse.md)
- [UriCancelRequest](interfaces/UriCancelRequest.md)
- [LensCreator](interfaces/LensCreator.md)
- [Lens](interfaces/Lens.md)
- [Preview](interfaces/Preview.md)
- [Snapcode](interfaces/Snapcode.md)
- [LensLaunchData](interfaces/LensLaunchData.md)
- [LensUserData](interfaces/LensUserData.md)
- [BitmojiUserInfo](interfaces/BitmojiUserInfo.md)
- [FriendUserInfo](interfaces/FriendUserInfo.md)
- [LensSource](interfaces/LensSource.md)
- [LoadAssetRequest](interfaces/LoadAssetRequest.md)
- [CameraKitSourceSubscriber](interfaces/CameraKitSourceSubscriber.md)
- [CameraKitDeviceOptions](interfaces/CameraKitDeviceOptions.md)
- [CameraKitSourceInfo](interfaces/CameraKitSourceInfo.md)
- [FunctionSourceOptions](interfaces/FunctionSourceOptions.md)
- [MediaStreamSourceOptions](interfaces/MediaStreamSourceOptions.md)
- [VideoSourceOptions](interfaces/VideoSourceOptions.md)
- [ComputedFrameMetrics](interfaces/ComputedFrameMetrics.md)
### Type Aliases
- [LensMetricsEvents](modules.md#lensmetricsevents)
- [LensPerformanceCluster](modules.md#lensperformancecluster)
- [PublicContainer](modules.md#publiccontainer)
- [PublicServices](modules.md#publicservices)
- [RemoteApiStatus](modules.md#remoteapistatus)
- [RemoteApiCancelRequestHandler](modules.md#remoteapicancelrequesthandler)
- [RemoteApiRequestHandler](modules.md#remoteapirequesthandler)
- [RemoteApiServices](modules.md#remoteapiservices)
- [FetchHandler](modules.md#fetchhandler)
- [FilePickerOptions](modules.md#filepickeroptions)
- [FilePickerResult](modules.md#filepickerresult)
- [FilePicker](modules.md#filepicker)
- [Uri](modules.md#uri)
- [LensLaunchParams](modules.md#lenslaunchparams)
- [Zodiac](modules.md#zodiac)
- [AssetTiming](modules.md#assettiming)
- [AssetResponse](modules.md#assetresponse)
- [AssetLoader](modules.md#assetloader)
- [LensView](modules.md#lensview)
- [LensWait](modules.md#lenswait)
- [LegalError](modules.md#legalerror)
- [LensContentValidationError](modules.md#lenscontentvalidationerror)
- [LensError](modules.md#lenserror)
- [CameraKitSourceError](modules.md#camerakitsourceerror)
- [LensImagePickerError](modules.md#lensimagepickererror)
- [CacheKeyNotFoundError](modules.md#cachekeynotfounderror)
- [ConfigurationError](modules.md#configurationerror)
- [WebGLError](modules.md#webglerror)
- [BenchmarkError](modules.md#benchmarkerror)
- [PlatformNotSupportedError](modules.md#platformnotsupportederror)
- [LensExecutionError](modules.md#lensexecutionerror)
- [LensAbortError](modules.md#lensaborterror)
- [PersistentStoreError](modules.md#persistentstoreerror)
- [LensAssetError](modules.md#lensasseterror)
- [BootstrapError](modules.md#bootstraperror)
- [ArgumentValidationError](modules.md#argumentvalidationerror)
- [RenderTarget](modules.md#rendertarget)
- [CameraKitSessionEvents](modules.md#camerakitsessionevents)
- [CameraKitSessionEventListener](modules.md#camerakitsessioneventlistener)
- [KeyboardEvents](modules.md#keyboardevents)
- [Keyboard](modules.md#keyboard)
- [Matrix](modules.md#matrix)
### Variables
- [extensionRequestContext](modules.md#extensionrequestcontext)
### Functions
- [estimateLensPerformance](modules.md#estimatelensperformance)
- [bootstrapCameraKit](modules.md#bootstrapcamerakit)
- [createExtension](modules.md#createextension)
- [Injectable](modules.md#injectable)
- [ConcatInjectable](modules.md#concatinjectable)
- [remoteApiServicesFactory](modules.md#remoteapiservicesfactory)
- [filePickerFactory](modules.md#filepickerfactory)
- [lensSourcesFactory](modules.md#lenssourcesfactory)
- [createImageSource](modules.md#createimagesource)
- [createMediaStreamSource](modules.md#createmediastreamsource)
- [createVideoSource](modules.md#createvideosource)
## Bootstrapping and Configuration
### LensPerformanceCluster
Ƭ **LensPerformanceCluster**: ``0`` \| ``1`` \| ``2`` \| ``3`` \| ``4`` \| ``5`` \| ``6``
___
### PublicContainer
Ƭ **PublicContainer**: `Container`\<[`PublicServices`](modules.md#publicservices)\>
For more advanced use-cases, this DI Container holds services for which a custom implementation may be provided by
the application.
___
### ConfigurationError
Ƭ **ConfigurationError**: `NamedError`\<``"ConfigurationError"``\>
Thrown by [bootstrapCameraKit](modules.md#bootstrapcamerakit) if provided configuration is invalid.
___
### PlatformNotSupportedError
Ƭ **PlatformNotSupportedError**: `NamedError`\<``"PlatformNotSupportedError"``\>
Thrown by [bootstrapCameraKit](modules.md#bootstrapcamerakit) when the current platform is not supported by CameraKit.
This can happen if the browser doesn't support a required feature (e.g. WebGL).
___
### BootstrapError
Ƭ **BootstrapError**: `NamedError`\<``"BootstrapError"``\>
Thrown by [bootstrapCameraKit](modules.md#bootstrapcamerakit) if an error occurs during SDK initialization or while downloading the render
engine WebAssembly.
___
### estimateLensPerformance
▸ **estimateLensPerformance**(): `Promise`\<[`EstimatedLensPerformance`](interfaces/EstimatedLensPerformance.md)\>
Run benchmarks which attempt to predict expected lens performance, and assign a cluster (i.e. a performance rating)
which the CameraKit SDK can use to optimize certain lenses.
#### Returns
`Promise`\<[`EstimatedLensPerformance`](interfaces/EstimatedLensPerformance.md)\>
A rating from 1-6, indicating expected Lens performance.
___
### bootstrapCameraKit
▸ **bootstrapCameraKit**(`configuration`, `provide?`): `Promise`\<[`CameraKit`](classes/CameraKit.md)\>
Bootstrap CameraKit. This will download the WebAssembly code which powers CameraKit's rendering engine, and return
an instance of [CameraKit](classes/CameraKit.md).
CameraKit must be provided with some configuration (the application's API token), and there are some additional
configurations which are optional.
Descriptions of the available configurations can be found in the documentation for
[CameraKitBootstrapConfiguration](interfaces/CameraKitBootstrapConfiguration.md)
---
There is also a second, more advanced way to modify CameraKit to provide greater flexibility to support less common
use cases.
This requires some knowledge of CameraKit's dependency injection system, and allows applications to provide their
own custom implementations of certain CameraKit components. This functionality will only be needed by applications
with very specific, more advanced requirements.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `configuration` | [`CameraKitBootstrapConfiguration`](interfaces/CameraKitBootstrapConfiguration.md) | Configure CameraKit with e.g. credentials, global resource endpoints, etc. |
| `provide?` | (`c`: [`PublicContainer`](modules.md#publiccontainer)) => [`PublicContainer`](modules.md#publiccontainer) | Optional function that can make modifications to CameraKit's root DI container. |
#### Returns
`Promise`\<[`CameraKit`](classes/CameraKit.md)\>
A [CameraKit](classes/CameraKit.md) instance, which is the entry point to CameraKit's API.
**`Example`**
```ts
// The most common way to bootstrap:
const cameraKit = await bootstrapCameraKit({ apiToken: myApiToken })
// For special advanced use-cases, it is possible to provide custom implementations for certain CameraKit components.
const cameraKit = await bootstrapCameraKit(config, (container) => {
return container.provides(myCustomRemoteMediaAssetLoaderFactory)
})
```
**`Throws`**
- [ConfigurationError](modules.md#configurationerror) when provided configuration object is invalid
- [PlatformNotSupportedError](modules.md#platformnotsupportederror) when current platform is not supported by CameraKit
- [BootstrapError](modules.md#bootstraperror) when a failure occurs while initializing CameraKit and downloading the render engine
WebAssembly binary.
___
### createExtension
▸ **createExtension**(): `PartialContainer`
Extensions offer a way to provide custom implementations of certain parts of the CameraKit SDK.
This enables more advanced use-cases, in which the default behavior of the SDK is substantially altered. For example,
replacing the default implementation that loads remote lens assets with a custom implementation that returns
different assets based on some business logic within the application.
An extension is implemented as a PartialContainer – a collection of factory functions, each with its own
dependencies, which each provide some "Service". A Service can be of any type, and the CameraKit SDK defines its
own Services, some of which can be overridden by providing a custom implementation of the type via an extension.
Here's an example of how extensions might be used:
```ts
import { bootstrapCameraKit, createExtension, remoteMediaAssetLoaderFactory } from '@snap/camera-kit'
const myCustomRemoteAssetLoader = Injectable(
remoteMediaAssetLoaderFactory.token,
[remoteMediaAssetLoaderFactory.token] as const,
(defaultLoader: AssetLoader): AssetLoader => {
return async (asset, lens) => {
if (lens?.id === MY_SPECIAL_LENS) {
return (await fetch('my/asset.glb')).arrayBuffer()
}
return defaultLoader(asset, lens)
}
},
)
const myExtension = createExtension().provides(myCustomRemoteAssetLoader);
const cameraKit = bootstrapCameraKit(config, container => container.provides(myExtension));
```
This also enables greater modularity – the person/team creating the extension can do so in their own package, which
could be shared by many applications that all require the same functionality.
#### Returns
`PartialContainer`
A PartialContainer which can be used to create a collection of Services, and can later be provided
to CameraKit's DI container during [bootstrapCameraKit](modules.md#bootstrapcamerakit).
## Lenses
### LensMetricsEvents
Ƭ **LensMetricsEvents**: [`TypedCustomEvent`](classes/TypedCustomEvent.md)\<[`LensView`](modules.md#lensview)[``"name"``], [`LensView`](modules.md#lensview)\> \| [`TypedCustomEvent`](classes/TypedCustomEvent.md)\<[`LensWait`](modules.md#lenswait)[``"name"``], [`LensWait`](modules.md#lenswait)\>
Lens metrics events.
These events are emitted by [CameraKit](classes/CameraKit.md) to report lens usage, performance, apply latency, etc.
___
### AssetTiming
Ƭ **AssetTiming**: ``"required"`` \| ``"onDemand"``
Lens assets are included in a manifest, and each will indicate when that asset will be used by the lens.
Assets can have the following timing values:
- `required`: the lens will definitely request this asset immediately when the lens is applied.
- `onDemand`: the lens may request this asset at some time while the lens is applied.
Depending on the use-case, an application may want to cache both required and onDemand assets for
a particular lens, or may decide to only cache required assets (or cache no assets).
___
### AssetLoader
Ƭ **AssetLoader**: (`request`: [`LoadAssetRequest`](interfaces/LoadAssetRequest.md)) => `Promise`\<[`AssetResponse`](modules.md#assetresponse)\> \| [`AssetResponse`](modules.md#assetresponse)
An AssetLoader is used to retrieve assets. A separate loader may be defined to retrieve different asset types.
#### Type declaration
▸ (`request`): `Promise`\<[`AssetResponse`](modules.md#assetresponse)\> \| [`AssetResponse`](modules.md#assetresponse)
##### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `request` | [`LoadAssetRequest`](interfaces/LoadAssetRequest.md) | The [LoadAssetRequest](interfaces/LoadAssetRequest.md) detailing the asset to be loaded, its context, and loading priority. |
##### Returns
`Promise`\<[`AssetResponse`](modules.md#assetresponse)\> \| [`AssetResponse`](modules.md#assetresponse)
___
### LensView
Ƭ **LensView**: `MakeTaggedBusinessEvent`\<``"lensView"``\>
The LensView metric is emitted after a lens has been viewed (for longer than 100ms), when the lens is turned off.
It contains information about rendering performance.
Notes:
- If the page is hidden (e.g. user switches to a different tab, or application, or closes the tab, or closes the
browser, navigates to a new page, refreshes, etc.) this metric will be emitted at that time. This is to ensure
we don't lose the metric if the page is closed.
- If the page is hidden and then made visible again later (e.g. user switches to a different tab, then back), we
will begin measuring a new LensView. That is, we will not capture the time when the page is hidden even if the
lens is still rendering in the background.
___
### LensWait
Ƭ **LensWait**: `MakeTaggedBusinessEvent`\<``"lensWait"``\>
The LensWait metric measures the time spent downloading the lens content and required assets. It gives an indication
of the real UX impact of download latency. If lens content and assets are pre-loaded, the latency measured here
should decrease – we measure between the request to apply a lens and when the lens is ready to render.
___
### RenderTarget
Ƭ **RenderTarget**: ``"live"`` \| ``"capture"``
Enumerates the supported render targets.
Lenses may render to different render targets, as designed by the lens creator. In CameraKit, it's possible to choose
which render target to render, and the result for each target is available as a separate `<canvas>` element.
___
### CameraKitSessionEvents
Ƭ **CameraKitSessionEvents**: [`TypedCustomEvent`](classes/TypedCustomEvent.md)\<``"error"``, \{ `error`: [`LensExecutionError`](modules.md#lensexecutionerror) \| [`LensAbortError`](modules.md#lensaborterror) \| [`LensImagePickerError`](modules.md#lensimagepickererror) ; `lens`: [`Lens`](interfaces/Lens.md) }\>
Events emitted by [CameraKitSession.events](classes/CameraKitSession.md#events).
The following events are emitted:
- `error`: An error has been encountered during lens rendering. May contain an error of type:
- [LensExecutionError](modules.md#lensexecutionerror) If an error of this type occurs, the rendering lens will be automatically removed
from the associated CameraKitSession.
- [LensImagePickerError](modules.md#lensimagepickererror)
___
### Keyboard
Ƭ **Keyboard**: `Object`
Keyboard is an API enabling lenses to consume and render user-generated text.
Applications that wish to use lenses that expect user-generated text will need to use this API to integrate text
input into their user experience.
There are two ways to do this:
1. Add the provided DOM element (an HTMLTextAreaElement) to the page. When the user updates this element with text,
that text will be sent to the currently active lens.
2. Use the [Keyboard.sendInputToLens](modules.md#sendinputtolens) method to send text strings to the currently active lens directly.
Lenses will also signal to the application when text input is expected -- applications should add an event listener
and ensure the user is able to input text when the `active` event is received.
**`Example`**
```ts
cameraKitSession.keyboard.addEventListener('active', ({ detail }) => {
const { element, active } = detail
if (active) document.body.appendChild(element)
else element.remove()
})
```
#### Type declaration
| Name | Type | Description |
| :------ | :------ | :------ |
| `addEventListener` | (`type`: ``"active"``, `callback`: `TypedEventListener`\<[`KeyboardEvents`](modules.md#keyboardevents)\>, `options?`: `TypedEventListenerOptions`) => `void` | - |
| `removeEventListener` | (`type`: ``"active"``, `callback`: `TypedEventListener`\<[`KeyboardEvents`](modules.md#keyboardevents)\>) => `void` | - |
| `getElement` | () => `HTMLTextAreaElement` | Get an HTMLTextAreaElement that communicates text to the active Lens. |
| `sendInputToLens` | (`text`: `string`) => `void` | Send text to the active Lens. Also updates the provided HTMLTextAreaElement. |
| `dismiss` | () => `void` | Clears the provided HTMLTextAreaElement, and emits the "active" event with `active == false`, allowing the application to e.g. remove relevant text input elements from the DOM. |
## Metrics
### LensMetricsEvents
Ƭ **LensMetricsEvents**: [`TypedCustomEvent`](classes/TypedCustomEvent.md)\<[`LensView`](modules.md#lensview)[``"name"``], [`LensView`](modules.md#lensview)\> \| [`TypedCustomEvent`](classes/TypedCustomEvent.md)\<[`LensWait`](modules.md#lenswait)[``"name"``], [`LensWait`](modules.md#lenswait)\>
Lens metrics events.
These events are emitted by [CameraKit](classes/CameraKit.md) to report lens usage, performance, apply latency, etc.
___
### LensView
Ƭ **LensView**: `MakeTaggedBusinessEvent`\<``"lensView"``\>
The LensView metric is emitted after a lens has been viewed (for longer than 100ms), when the lens is turned off.
It contains information about rendering performance.
Notes:
- If the page is hidden (e.g. user switches to a different tab, or application, or closes the tab, or closes the
browser, navigates to a new page, refreshes, etc.) this metric will be emitted at that time. This is to ensure
we don't lose the metric if the page is closed.
- If the page is hidden and then made visible again later (e.g. user switches to a different tab, then back), we
will begin measuring a new LensView. That is, we will not capture the time when the page is hidden even if the
lens is still rendering in the background.
___
### LensWait
Ƭ **LensWait**: `MakeTaggedBusinessEvent`\<``"lensWait"``\>
The LensWait metric measures the time spent downloading the lens content and required assets. It gives an indication
of the real UX impact of download latency. If lens content and assets are pre-loaded, the latency measured here
should decrease – we measure between the request to apply a lens and when the lens is ready to render.
## Other
### PublicServices
Ƭ **PublicServices**: `ServicesFromInjectables`\<[`ReturnType`\<typeof `createCameraKitConfigurationFactory`\>, typeof [`filePickerFactory`](modules.md#filepickerfactory), typeof `defaultFetchHandlerFactory`, typeof `remoteMediaAssetLoaderFactory`, typeof [`lensSourcesFactory`](modules.md#lenssourcesfactory), typeof [`remoteApiServicesFactory`](modules.md#remoteapiservicesfactory), typeof `uriHandlersFactory`, typeof `externalMetricsSubjectFactory`]\>
All services available to be customized by client app.
___
### RemoteApiStatus
Ƭ **RemoteApiStatus**: ``"success"`` \| ``"redirected"`` \| ``"badRequest"`` \| ``"accessDenied"`` \| ``"notFound"`` \| ``"timeout"`` \| ``"requestTooLarge"`` \| ``"serverError"`` \| ``"cancelled"`` \| ``"proxyError"``
Status of a Remote API response.
___
### RemoteApiCancelRequestHandler
Ƭ **RemoteApiCancelRequestHandler**: () => `void`
Represents a Remote API request cancellation handler function.
#### Type declaration
▸ (): `void`
##### Returns
`void`
___
### RemoteApiRequestHandler
Ƭ **RemoteApiRequestHandler**: (`reply`: (`response`: [`RemoteApiResponse`](interfaces/RemoteApiResponse.md)) => `void`) => [`RemoteApiCancelRequestHandler`](modules.md#remoteapicancelrequesthandler) \| `void`
Represents a Remote API request handler function.
It is provided with a reply callback that must be invoked to send a response back to the lens.
The reply callback can be invoked multiple times if needed.
Additionally, the handler can return a cancellation callback, which is triggered when the lens cancels the request.
#### Type declaration
▸ (`reply`): [`RemoteApiCancelRequestHandler`](modules.md#remoteapicancelrequesthandler) \| `void`
##### Parameters
| Name | Type |
| :------ | :------ |
| `reply` | (`response`: [`RemoteApiResponse`](interfaces/RemoteApiResponse.md)) => `void` |
##### Returns
[`RemoteApiCancelRequestHandler`](modules.md#remoteapicancelrequesthandler) \| `void`
___
### RemoteApiServices
Ƭ **RemoteApiServices**: [`RemoteApiService`](interfaces/RemoteApiService.md)[]
___
### FetchHandler
Ƭ **FetchHandler**\<`R`\>: (`input`: `RequestInfo`, `init?`: `RequestInit`) => `Promise`\<`R`\>
#### Type parameters
| Name | Type |
| :------ | :------ |
| `R` | `Response` |
#### Type declaration
▸ (`input`, `init?`): `Promise`\<`R`\>
##### Parameters
| Name | Type |
| :------ | :------ |
| `input` | `RequestInfo` |
| `init?` | `RequestInit` |
##### Returns
`Promise`\<`R`\>
___
### FilePickerOptions
Ƭ **FilePickerOptions**: `Parameters`\<`OpenDefaultFilePicker`\>[``0``]
File picker options. For example, it indicates which MIME types of files are expected to be picked.
___
### FilePickerResult
Ƭ **FilePickerResult**: `Promise`\<`FileWithHandle` \| `FileWithHandle`[]\>
File picker dialog result object, which is a Promise that resolves to a file or an array of files with handles.
___
### FilePicker
Ƭ **FilePicker**: (`options`: [`FilePickerOptions`](modules.md#filepickeroptions), `openDefaultPicker`: `OpenDefaultFilePicker`) => [`FilePickerResult`](modules.md#filepickerresult)
A callback to show a file picker dialog.
#### Type declaration
▸ (`options`, `openDefaultPicker`): [`FilePickerResult`](modules.md#filepickerresult)
##### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `options` | [`FilePickerOptions`](modules.md#filepickeroptions) | Options for the file picker dialog. |
| `openDefaultPicker` | `OpenDefaultFilePicker` | The default file picker function. The client app may choose to use the default file picker. |
##### Returns
[`FilePickerResult`](modules.md#filepickerresult)
___
### Uri
Ƭ **Uri**: \`$\{string}://$\{string}\`
___
### LensLaunchParams
Ƭ **LensLaunchParams**: `Record`\<`string`, `string` \| `number` \| `string`[] \| `number`[]\>
Lens launch params.
___
### Zodiac
Ƭ **Zodiac**: ``"aquarius"`` \| ``"aries"`` \| ``"cancer"`` \| ``"capricorn"`` \| ``"gemini"`` \| ``"leo"`` \| ``"libra"`` \| ``"pisces"`` \| ``"sagittarius"`` \| ``"scorpio"`` \| ``"taurus"`` \| ``"virgo"``
___
### AssetResponse
Ƭ **AssetResponse**: `ArrayBuffer` \| \{ `data`: `ArrayBuffer` ; `checksum?`: `string` }
___
### LegalError
Ƭ **LegalError**: `NamedError`\<``"LegalError"``\>
___
### LensContentValidationError
Ƭ **LensContentValidationError**: `NamedError`\<``"LensContentValidationError"``\>
___
### LensError
Ƭ **LensError**: `NamedError`\<``"LensError"``\>
___
### CameraKitSourceError
Ƭ **CameraKitSourceError**: `NamedError`\<``"CameraKitSourceError"``\>
___
### LensImagePickerError
Ƭ **LensImagePickerError**: `NamedError`\<``"LensImagePickerError"``\>
The error triggered when a lens prompts the user to select an image, but the image fails to be successfully delivered
to the lens.
___
### CacheKeyNotFoundError
Ƭ **CacheKeyNotFoundError**: `NamedError`\<``"CacheKeyNotFoundError"``\>
___
### WebGLError
Ƭ **WebGLError**: `NamedError`\<``"WebGLError"``\>
___
### BenchmarkError
Ƭ **BenchmarkError**: `NamedError`\<``"BenchmarkError"``\>
___
### LensExecutionError
Ƭ **LensExecutionError**: `NamedError`\<``"LensExecutionError"``\>
This error occurs if a Lens is unable to continue rendering.
If this error occurs, Camera Kit automatically removes the Lens from the session.
It's always a good idea to handle this error and update the user experience accordingly.
For example, you could remove the faulty Lens from your Lens selection UI.
```ts
cameraKitSession.events.addEventListener('error', ({ detail }) => {
if (detail.error.name === 'LensExecutionError') {
console.log(`Lens ${detail.lens.name} encountered an error and was removed. Please pick a different lens.`)
}
})
```
___
### LensAbortError
Ƭ **LensAbortError**: `NamedError`\<``"LensAbortError"``\>
This error occurs when a session becomes inoperable.
It's always a good idea to handle this error and update the user experience accordingly.
For example, you could show a message to a user.
```ts
cameraKitSession.events.addEventListener('error', ({ detail }) => {
if (detail.error.name === 'LensAbortError') {
console.log(`Camera Kit encountered an unrecoverable error and became inoperable. Please refresh the page.`)
}
})
```
___
### PersistentStoreError
Ƭ **PersistentStoreError**: `NamedError`\<``"PersistentStoreError"``\>
Error thrown when LensCore asked to store lens data, but CameraKit failed storing that.
___
### LensAssetError
Ƭ **LensAssetError**: `NamedError`\<``"LensAssetError"``\>
Error thrown when LensCore asked to provide an asset, but CameraKit failed providing that.
___
### ArgumentValidationError
Ƭ **ArgumentValidationError**: `NamedError`\<``"ArgumentValidationError"``\>
Thrown when a method receives an argument with an unexpected value.
___
### CameraKitSessionEventListener
Ƭ **CameraKitSessionEventListener**: `TypedEventListener`\<[`CameraKitSessionEvents`](modules.md#camerakitsessionevents)\>
Listener of [CameraKitSessionEvents](modules.md#camerakitsessionevents) events.
___
### KeyboardEvents
Ƭ **KeyboardEvents**: [`TypedCustomEvent`](classes/TypedCustomEvent.md)\<``"active"``, \{ `element`: `HTMLTextAreaElement` ; `active`: `boolean` ; `lens?`: [`Lens`](interfaces/Lens.md) }\>
Events emitted by [Keyboard](modules.md#keyboard).
___
### Matrix
Ƭ **Matrix**: `TupleOf`\<`number`, ``9``\>
Matrix as a 9-value array in column-major order,
where elements are stored sequentially by columns.
___
### extensionRequestContext
• `Const` **extensionRequestContext**: `ArrayBuffer`
Extension request context.
___
### Injectable
▸ **Injectable**\<`Token`, `Service`\>(`token`, `fn`): `InjectableFunction`\<`any`, [], `Token`, `Service`\>
Create an Injectable factory function with no dependencies (i.e. the factory function has no arguments).
Ex:
```ts
const createMyService = Injectable(
'MyService',
() => { return ... },
)
```
#### Type parameters
| Name | Type |
| :------ | :------ |
| `Token` | extends `string` |
| `Service` | `Service` |
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `token` | `Token` | A unique string Token which will correspond to the created Service. |
| `fn` | () => `Service` | A function with no arguments which returns the Service. |
#### Returns
`InjectableFunction`\<`any`, [], `Token`, `Service`\>
▸ **Injectable**\<`Token`, `Tokens`, `Params`, `Service`\>(`token`, `dependencies`, `fn`): `Tokens`[``"length"``] extends `Params`[``"length"``] ? `InjectableFunction`\<`ServicesFromTokenizedParams`\<`Tokens`, `Params`\>, `Tokens`, `Token`, `Service`\> : `never`
Create an Injectable factory function with dependencies (i.e. the factory function has arguments).
**Note:** the list of dependencies must contain only string literals or string consts.
Ex:
```ts
const DependencyB = 'DependencyB'
const createMyService = Injectable(
'MyService',
['DependencyA', DependencyB] as const,
(a: A, b: B) => { return ... },
)
```
#### Type parameters
| Name | Type |
| :------ | :------ |
| `Token` | extends `string` |
| `Tokens` | extends readonly `string`[] |
| `Params` | extends readonly `any`[] |
| `Service` | `Service` |
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `token` | `Token` | A unique string Token which will correspond to the created Service. |
| `dependencies` | `Tokens` | A *readonly* list of Tokens corresponding to dependencies (i.e. arguments to the Factory), which will be resolved by the Container to which this Injectable is provided. |
| `fn` | (...`args`: `Tokens`[``"length"``] extends `Params`[``"length"``] ? `Params` : `void`[]) => `Service` | A function with arguments matching in type and length to the given list of dependencies. When called, it must return the Service. |
#### Returns
`Tokens`[``"length"``] extends `Params`[``"length"``] ? `InjectableFunction`\<`ServicesFromTokenizedParams`\<`Tokens`, `Params`\>, `Tokens`, `Token`, `Service`\> : `never`
___
### ConcatInjectable
▸ **ConcatInjectable**\<`Token`, `Service`\>(`token`, `fn`): `InjectableFunction`\<\{ [T in keyof Token]: Service[] }, [], `Token`, `Service`[]\>
Create an Injectable factory function without dependencies (i.e. the factory function has no arguments) that appends
a Service onto an existing array of Services of the same type.
Ex:
```ts
import { myServiceFactory, MyService } from './my-service'
const createMyService = ConcatInjectable(
myServiceFactory.token,
(): MyService => { return ... },
)
// Consumers then do:
const myConsumingServiceFactory = Injectable(
'myConsumingService',
[myServiceFactory.token] as const,
(myServices: MyService[]) => { return ... }
)
```
#### Type parameters
| Name | Type |
| :------ | :------ |
| `Token` | extends `string` |
| `Service` | `Service` |
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `token` | `Token` | A string Token identifying an existing Service that has an Array type, to which will be appended the Service created by this factory function. |
| `fn` | () => `Service` | A function with no arguments which returns the Service. |
#### Returns
`InjectableFunction`\<\{ [T in keyof Token]: Service[] }, [], `Token`, `Service`[]\>
▸ **ConcatInjectable**\<`Token`, `Tokens`, `Params`, `Service`\>(`token`, `dependencies`, `fn`): `InjectableFunction`\<`ServicesFromTokenizedParams`\<`Tokens`, `Params`\>, `Tokens`, `Token`, `Service`[]\>
Create an Injectable factory function with dependencies (i.e. the factory function has arguments) that appends
a Service onto an existing array of Services of the same type.
Ex:
```ts
import { myServiceFactory, MyService } from './my-service'
const createMyService = ConcatInjectable(
myServiceFactory.token,
['DependencyA', 'DependencyB'] as const,
(a: A, b: B): MyService => { return ... },
)
// Consumers then do:
const myConsumingServiceFactory = Injectable(
'myConsumingService',
[myServiceFactory.token] as const,
(myServices: MyService[]) => { return ... }
)
```
#### Type parameters
| Name | Type |
| :------ | :------ |
| `Token` | extends `string` |
| `Tokens` | extends readonly `string`[] |
| `Params` | extends readonly `any`[] |
| `Service` | `Service` |
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `token` | `Token` | A string Token identifying an existing Service that has an Array type, to which will be appended the Service created by this factory function. |
| `dependencies` | `Tokens` | A *readonly* list of Tokens corresponding to dependencies (i.e. arguments to the Factory), which will be resolved by the Container to which this Injectable is provided. |
| `fn` | (...`args`: `Tokens`[``"length"``] extends `Params`[``"length"``] ? `Params` : `void`[]) => `Service` | A function with no arguments which returns the Service. |
#### Returns
`InjectableFunction`\<`ServicesFromTokenizedParams`\<`Tokens`, `Params`\>, `Tokens`, `Token`, `Service`[]\>
___
### remoteApiServicesFactory
▸ **remoteApiServicesFactory**(`...args`): [`RemoteApiServices`](modules.md#remoteapiservices)
#### Parameters
| Name | Type |
| :------ | :------ |
| `...args` | [] |
#### Returns
[`RemoteApiServices`](modules.md#remoteapiservices)
___
### filePickerFactory
▸ **filePickerFactory**(`...args`): [`FilePicker`](modules.md#filepicker)
Default file picker factory function. The file picker is triggered when a lens issues a file request.
Client applications can override this factory function to provide their custom file picker.
#### Parameters
| Name | Type |
| :------ | :------ |
| `...args` | [] |
#### Returns
[`FilePicker`](modules.md#filepicker)
___
### lensSourcesFactory
▸ **lensSourcesFactory**(`...args`): [`LensSource`](interfaces/LensSource.md)[]
By default, no custom [LensSource](interfaces/LensSource.md) is provided to CameraKit. But to enable certain advanced use-cases,
applications may provide their own [LensSource](interfaces/LensSource.md).
Perhaps the most convenient way to do this is with [ConcatInjectable](modules.md#concatinjectable), as shown here:
#### Parameters
| Name | Type |
| :------ | :------ |
| `...args` | [] |
#### Returns
[`LensSource`](interfaces/LensSource.md)[]
**`Example`**
```ts
import { bootstrapCameraKit, lensSourcesFactory, LensSource } from '@snap/camera-kit'
const cameraKit = bootstrapCameraKit(config, (container) => {
return container.provides(ConcatInjectable(
lensSourcesFactory.token,
(): LensSource => { return ... }
))
})
```
## Rendering
### RenderTarget
Ƭ **RenderTarget**: ``"live"`` \| ``"capture"``
Enumerates the supported render targets.
Lenses may render to different render targets, as designed by the lens creator. In CameraKit, it's possible to choose
which render target to render, and the result for each target is available as a separate `<canvas>` element.
___
### CameraKitSessionEvents
Ƭ **CameraKitSessionEvents**: [`TypedCustomEvent`](classes/TypedCustomEvent.md)\<``"error"``, \{ `error`: [`LensExecutionError`](modules.md#lensexecutionerror) \| [`LensAbortError`](modules.md#lensaborterror) \| [`LensImagePickerError`](modules.md#lensimagepickererror) ; `lens`: [`Lens`](interfaces/Lens.md) }\>
Events emitted by [CameraKitSession.events](classes/CameraKitSession.md#events).
The following events are emitted:
- `error`: An error has been encountered during lens rendering. May contain an error of type:
- [LensExecutionError](modules.md#lensexecutionerror) If an error of this type occurs, the rendering lens will be automatically removed
from the associated CameraKitSession.
- [LensImagePickerError](modules.md#lensimagepickererror)
___
### createImageSource
▸ **createImageSource**(`image`, `options?`): [`CameraKitSource`](classes/CameraKitSource.md)
Create a [CameraKitSource](classes/CameraKitSource.md) from an
[HTMLImageElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement).
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `image` | `HTMLImageElement` | Image element. |
| `options` | `Partial`\<[`CameraKitDeviceOptions`](interfaces/CameraKitDeviceOptions.md)\> | Options. |
#### Returns
[`CameraKitSource`](classes/CameraKitSource.md)
___
### createMediaStreamSource
▸ **createMediaStreamSource**(`stream`, `options?`): [`CameraKitSource`](classes/CameraKitSource.md)
Create a [CameraKitSource](classes/CameraKitSource.md) from any
[MediaStream](https://developer.mozilla.org/en-US/docs/Web/API/MediaStream).
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `stream` | `MediaStream` | Any MediaStream, such as obtained via `canvas.captureStream()` or `mediaDevices.getUserMedia()`. |
| `options` | `Partial`\<[`MediaStreamSourceOptions`](interfaces/MediaStreamSourceOptions.md)\> | Options. |
#### Returns
[`CameraKitSource`](classes/CameraKitSource.md)
___
### createVideoSource
▸ **createVideoSource**(`video`, `options?`): [`CameraKitSource`](classes/CameraKitSource.md)
Create a [CameraKitSource](classes/CameraKitSource.md) from an
[HTMLVideoElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement).
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `video` | `HTMLVideoElement` | CameraKit performs best when the source video is 720p – arbitrary resolutions are supported, but very high resolutions may not perform well. |
| `options` | `Partial`\<[`VideoSourceOptions`](interfaces/VideoSourceOptions.md)\> | Options. |
#### Returns
[`CameraKitSource`](classes/CameraKitSource.md)