Scanly SDK API reference
This reference describes the supported exports of @scanly/sdk. Import
lead-form domain contracts such as LeadFormDefinition, LeadFormValues, and
LeadFormSubmissionReceipt from @scanly/public; the SDK does not
re-export them.
Public contracts and functions
@scanly/public is the SDK-safe package for both public types and
platform-neutral functions. Its exports are organized as follows:
| Import path | Contents |
|---|---|
@scanly/public | Root barrel for public types and functions. |
@scanly/public/types | Public CMS and SDK contracts only. |
@scanly/public/functions | All public platform-neutral functions. |
@scanly/public/functions/lead-forms | Canonical lead-form compilation and behavior. |
Client and shared runtime
Import from @scanly/sdk.
Functions and classes
| Export | Construction / input | Returns | Use |
|---|---|---|---|
createScanlyClient(options) | ScanlyClientOptions with apiBaseUrl and an sdk_pub_… public key. Optional fetch, random-byte, storage, session, attestation, and error adapters may be supplied. | ScanlyClient | Creates one isolated client for one SDK target. Repositories create or restore a session lazily when required. |
new ScanlyError(code, message, options?) | A Scanly error code, readable message, and optional HTTP/retry/request details. | ScanlyError | Represents normalized configuration, transport, session, push, theme, and form failures. ScanlyError.fromUnknown(error, fallback?) converts unknown failures. |
new MemoryStorage() | No arguments. | MemoryStorage implementing ScanlyStorage | Keeps session state in memory. This is the default and does not survive reloads. |
createBrowserStorage(storage) | A synchronous getItem, setItem, and removeItem implementation, such as localStorage. | ScanlyStorage | Adapts browser storage to the SDK’s asynchronous storage interface. Persistent browser storage increases the impact of XSS. |
createSecureStorage(storage) | An asynchronous getItem, setItem, and removeItem implementation. | ScanlyStorage | Adapts platform secure storage, for example an encrypted native key-value store. |
ScanlyClient
The client has no public constructor; create it with createScanlyClient.
| Member | Input | Returns | Use |
|---|---|---|---|
initialize() | None. | Promise<SessionState> | Restores local state and creates an installation ID without forcing a session network request. |
destroy(options?) | { revokeRemoteSession?: boolean } | Promise<void> | Clears listeners, caches, and local session data. Optionally revokes the remote session first. |
session | — | Session manager | Reads or controls the current session through getState, getAccessToken, ensure, refresh, clearSession, subscribe, and getInstallationId. Most applications only need client.initialize() and repository methods. |
identity | — | IdentityRepo | Reads the current principal, subscribes to identity changes, or signs out. |
push | — | PushRepo | Registers, inspects, revokes, and observes push notifications. |
leadForms | — | LeadFormsRepository | Loads definitions and prepares or submits public lead forms. |
themes | — | ThemesRepository | Fetches CMS themes by ID. |
Client types
| Type | Purpose |
|---|---|
ScanlyClientOptions | Client construction options. apiBaseUrl and publicKey are required. |
ScanlyClient | Complete client facade returned by createScanlyClient. |
SessionOptions | Access-token refresh skew plus platform and application identity. |
SessionState | Current status, installation/session IDs, principal, scopes, and token expiry timestamps. |
IdentityRepo | getPrincipal(), signOut(), and onChange() contract. |
PushRepo | Client-bound push registration and foreground-message contract. |
ThemesRepository | getById(themeId): Promise<CMS.Theme> contract. |
ScanlyStorage | Asynchronous string key-value storage contract. |
Push types
| Type | Purpose |
|---|---|
PushAdapter | Platform bridge for permission, provider-token, token-refresh, foreground-message, and deletion operations. |
PushConsent | Consent evidence sent when registering push notifications. |
PushMessage | Normalized provider message with optional ID, title, body, and string data. |
PushPermission | 'granted', 'denied', 'provisional', 'unsupported', or 'unknown'. |
PushRegisterOptions | Adapter, consent, and optional device/app labels passed to client.push.register. |
PushRegistrationMaterial | Sensitive provider token, platform, and optional provider installation ID. |
PushRevokeOptions | Controls whether revocation also deletes the provider token. |
Transport types
| Type | Purpose |
|---|---|
AbortSignalLike | Portable subset of AbortSignal. |
FetchHeaders | Normalized Record<string, string> request headers. |
FetchInit | Portable request method, headers, body, abort signal, and omitted credentials. |
FetchResponse | Minimal response contract required by the SDK. |
FetchLike | Fetch-compatible function accepted by ScanlyClientOptions. |
Themes for React
Import from @scanly/sdk/theme/react. React is an optional peer dependency.
| Export | Construction / input | Returns | Use |
|---|---|---|---|
ThemeWrapper | React component receiving ThemeWrapperProps. | ReactElement | Wraps descendant content in CMS-derived CSS variables and inherited base styles. The theme takes precedence over caller-provided wrapper styles. |
ThemeWrapperProps | A CMS.Theme, children, optional styles, and normal div attributes. | Props type | Configures ThemeWrapper. |
The wrapper only affects descendants:
import { ThemeWrapper } from '@scanly/sdk/theme/react';
const theme = await client.themes.getById(themeId);
<ThemeWrapper theme={theme}>
<YourContent />
</ThemeWrapper>;Framework-independent lead forms
Import from @scanly/sdk/lead-forms.
Controller
| Export | Construction / input | Returns | Use |
|---|---|---|---|
createLeadFormController(options) | LeadFormControllerOptions with a definition, optional initial state, clock, and optional leadForms transport. | LeadFormController | Manages values, list targets, consent, validation, subscriptions, and retry-safe submission without React. |
LeadFormControllerOptions | Definition plus optional initial values, list-target IDs, granted consent IDs, clock/date, and transport. | Options type | Constructs the controller. |
LeadFormControllerState | Definition, canonical form state, validation, runtime, receipt/error, and submission lifecycle. | State type | Returned by getState() and subscriptions. |
LeadFormController | Controller method contract. | Controller type | getState, subscribe, value/list-target/consent setters, validate, prepareSubmission, submit, retry, reset, and destroy. |
For host-owned transport, controller.prepare({ idempotencyKey }) accepts a
PrepareLeadFormAttemptInput. The same parameter object is used by
useLeadForm(...).prepare(...).
Repository contracts
| Type | Purpose |
|---|---|
LeadFormsRepository | Contract exposed as client.leadForms. |
LeadFormDefinitionOptions | Locale, abort signal, and cache-bypass options for getDefinition. |
LeadFormSubmitOptions | Abort signal accepted by submit. |
PrepareLeadFormInput | Named definition, values, selected list-target IDs, consent, and validation-date input accepted by prepare. |
SerializedLeadFormAttempt | JSON-safe retry attempt returned by serializeAttempt. Restore it through restoreAttempt before submitting. |
LeadFormMessageCatalog | Client-owned renderer and validation text, keyed by stable SDK message names. |
LeadFormUiTextKey | Supported renderer-owned message keys. |
LEAD_FORM_UI_MESSAGE_KEYS | Stable host-i18n keys for renderer-owned interface text. |
LEAD_FORM_ISSUE_MESSAGE_KEYS | Stable host-i18n keys keyed by public validation issue code. |
PrepareLeadFormAttemptInput | Named idempotency-key input accepted by controller and useLeadForm preparation. |
LeadFormsRepository methods:
| Method | Input | Returns | Use |
|---|---|---|---|
getDefinition(formId, options?) | Public form_1_… ID and optional locale/cache options. | Promise<LeadFormDefinition> | Fetches, validates, and briefly caches a target-bound definition. |
createPlacesAutocompleteProvider(options?) | Optional { language } parameter object. | LeadFormAutocompleteProvider | Creates the first-party, target-authorized Places provider used by authored address fields. |
prepare(input) | PrepareLeadFormInput parameter object. | LeadFormPreparedSubmission | Validates state and creates a branded immutable attempt with a fresh idempotency key. |
submit(attempt, options?) | An attempt created or restored by this repository. | Promise<LeadFormSubmissionReceipt> | Sends the immutable attempt. Reuse it when retrying. |
serializeAttempt(attempt) | SDK-prepared attempt. | SerializedLeadFormAttempt | Persists a retryable attempt without exposing repository internals. |
restoreAttempt(value) | Previously serialized unknown value. | LeadFormPreparedSubmission | Validates and rebrands a stored attempt. |
clearCache() | None. | void | Clears process-local form definitions. The client calls this during destruction. |
Lead-form core
Import pure functions from @scanly/sdk/lead-forms/core. These functions do
not render UI or perform network requests.
| Export | Input | Returns | Use |
|---|---|---|---|
parseLeadFormDefinition(value) | Unknown API or stored value. | LeadFormDefinition | Validates a public definition and throws for an invalid contract or version. |
parseLocalLeadFormDefinition(value) | Unknown locally authored value. | LocalLeadFormDefinition | Validates a local definition and identity. |
isLeadFormDefinition(value) | Unknown value. | Type predicate | Non-throwing public-definition check. |
computeLeadFormDefinitionVersion(definition) | Definition with or without its current version. | ldf_1_${string} | Produces the deterministic canonical version. |
computeLeadFormContentHash(label, content) | Consent label and portable content blocks. | string | Produces consent-content integrity metadata. |
parseLeadFormPortableContent(value) | Supported authored markup or portable content. | Array<LeadFormContentBlock> | Produces sanitized cross-platform content. |
createLeadFormLocalReferenceId(kind, internalId) | Entity kind and host-owned internal ID. | string | Creates a stable local reference ID. |
createLocalLeadFormDefinition(definition, localId) | Definition without identity fields and an opaque base64url ID. | LocalLeadFormDefinition | Adds a local form ID and deterministic local definition version. |
createLocalLeadFormDefinitionFromAuthoring(input) | CreateLocalLeadFormDefinitionFromAuthoringInput parameter object. | LocalLeadFormAuthoringResult | Compiles neutral host authoring data into the canonical local definition used by SDK renderers and validation. |
createLeadFormRuntime(definition, values?, selectedListTargetIds?) | Definition and current state. | LeadFormRuntime | Derives visible/enabled/required fields, active consents, and list-target state. |
createLeadFormInitialState(definition, options?) | Definition and optional initial values, list targets, and consents. | LeadFormState | Creates normalized initial state. |
reconcileLeadFormState(previous, next, state) | Previous/new definitions and current state. | LeadFormReconciliation | Migrates compatible state when a definition changes. |
validateLeadForm(input) | ValidateLeadFormInput parameter object. | LeadFormValidationResult | Validates active inputs and returns normalized values plus issues. |
prepareLeadFormSubmission(input) | PrepareLeadFormSubmissionInput parameter object. | LeadFormPreparedSubmission | Creates a transport-ready public attempt. Prefer client.leadForms.prepare when using the SDK transport. |
prepareLocalLeadFormSubmission(input) | PrepareLocalLeadFormSubmissionInput parameter object. | LocalLeadFormSubmissionBody | Prepares data for a host-owned create flow. |
prepareLeadFormUpdatePatch(input) | PrepareLeadFormUpdatePatchInput parameter object. | LeadFormUpdatePatch | Produces the minimal update patch for an existing lead. |
The core entry point also exports the parameter-object types named in the table above. Their property names match the corresponding function calls, so TypeScript autocomplete documents each argument at the call site.
LeadFormAuthoringDefinition, LeadFormAuthoringField,
LeadFormAuthoringConsent, and LeadFormAuthoringListTarget are imported
from @scanly/public. They describe platform-neutral authoring data, not
Scanly’s private database/editor records. The compiler normalizes raw options,
defaults, constraints, conditions, consent content, and list-target links;
generates opaque local IDs and hashes; and validates the final contract. Its
result also contains source-to-opaque list-target and consent maps for hosts
that need to translate their own IDs.
LeadFormListTarget represents an audience list that may receive the submitted
lead. listTargets contains the mandatory root list and any coupled lists.
Optional targets are rendered as selectors; selecting one activates fields and
consents whose appliesToListTargetIds contain its ID. The submitted
selectedListTargetIds tell Scanly which audience-list memberships to create.
React Hook Form integration
Import from @scanly/sdk/lead-forms/react-hook-form. React,
react-hook-form, and their runtime peers are optional dependencies required
only by this entry point.
Hooks and helpers
| Export | Input | Returns | Use |
|---|---|---|---|
useLeadForm(options) | UseLeadFormOptions with an already resolved public or local definition. | UseLeadFormResult | Manages form state, runtime derivation, validation, reconciliation, consent, and list targets. It performs no network request. |
useSdkLeadForm(options) | UseSdkLeadFormOptions with a client and public form ID. | UseSdkLeadFormResult | Loads a definition and manages retry-safe SDK submission. |
createLeadFormRHFBindings(definition) | Renderable definition. | LeadFormRHFBindings | Creates stable encoded RHF paths for fields, list targets, and consents. |
useLeadFormAutocomplete(options) | Field, provider, minimum query length, and apply callback. | UseLeadFormAutocompleteResult | Debounces search, cancels stale work, resolves selections, and applies mapped values. |
mapLeadFormAutocompleteValues(field, values) | Authored autocomplete field and provider-keyed values. | LeadFormAutocompleteMappedValues | Maps authored provider keys to target fields. Extra provider values are ignored; value fills the active field when no targets are configured. |
Types
| Type | Purpose |
|---|---|
UseLeadFormOptions | Definition, initial values, selected list targets, consents, validation date, clock, and selected RHF options. |
UseLeadFormResult | RHF form, bindings, runtime, issues, reconciliation, domain-value accessors, setters, reset, validation, and preparation. |
UseSdkLeadFormOptions | Client, form ID, optional preloaded definition/locale/initial state, and optional custom submitter. |
UseSdkLeadFormResult | Load and submit lifecycles, managed form, errors, receipt, submit, retry, and reset. |
LeadFormSubmitter | Custom (attempt, options?) => Promise<receipt> transport. |
LeadFormRHFValues | Encoded RHF fields, list targets, and consents. |
LeadFormRHFBindings | Mapping from public IDs to encoded RHF paths. |
LeadFormAutocompleteSuggestion | Provider-owned suggestion ID and display label. |
LeadFormAutocompleteProvider | Asynchronous search and resolve contract. |
LeadFormAutocompleteProviders | Optional provider map accepted by managed renderers. Set a provider to false to disable it. |
LeadFormAutocompleteMappedValues | Domain values after provider-target mapping. |
PlacesAutocompleteProviderOptions | Optional BCP 47 language configuration for Scanly’s first-party Places provider. |
UseLeadFormAutocompleteOptions | Autocomplete hook configuration. |
UseLeadFormAutocompleteResult | Query, suggestions, loading/error state, setQuery, select, and clear. |
Managed web lead forms
Import from @scanly/sdk/lead-forms/web. React, React DOM, and React Hook Form
are optional peers required by managed web forms.
| Export | Construction / input | Returns | Use |
|---|---|---|---|
SdkLeadForm | SdkLeadFormProps with a client and public form ID. | ReactElement | Loads, renders, validates, submits, retries, and displays success/error state. |
WebLeadForm | WebLeadFormProps with an already resolved definition. | ReactElement | Transport-free managed form for host-owned data flows. |
LeadFormView | LeadFormRenderProps with state from useLeadForm. | ReactElement | Renders already managed state using semantic HTML. |
parseLeadFormWebViewMessage(value) | Unknown host message. | LeadFormWebViewMessage | null | Validates a privacy-safe WebView lifecycle envelope. |
postLeadFormWebViewMessage(message, targetOrigin) | Valid message and exact HTTPS parent origin. | void | Posts allowlisted lifecycle metadata to WKWebView or a parent window. |
Web renderer types
| Type | Purpose |
|---|---|
SdkLeadFormProps | SDK-backed form loading, rendering, callbacks, styles, and WebView origin. |
WebLeadFormProps | Transport-free definition plus renderer options. |
LeadFormRenderProps | Managed state, component overrides, submission callbacks, mode, messages, classes, and styles. |
LeadFormRendererComponents | Optional field, consent, list-target, submit, form-error, and success component overrides. |
LeadFormListTargetComponentProps | Props passed to a custom list-target selector. |
LeadFormFieldComponentProps | Props passed to a custom field renderer. |
LeadFormMode | 'create', 'edit', or 'preview'. |
LeadFormSlot | Stable renderer slot names. |
LeadFormClassNames | Optional CSS classes keyed by slot. |
LeadFormWebStyleTokens | Colors, spacing, radius, control height, and font tokens. |
LeadFormMessageCatalog | Client-owned UI and validation text. Missing entries render stable SDK i18n keys. |
LeadFormWebViewMessage | PII-free ready, submitted, or error lifecycle envelope. |
Import @scanly/sdk/lead-forms/styles.css once for the default stylesheet.
Set unstyled when the host owns all classes and styles.
className applies to the renderer root; use classNames.form for the nested
form element and the remaining LeadFormSlot keys for individual slots.
Submit controls are disabled while the form is pristine by default. Set
allowPristineSubmit to true when initial or default values may be submitted
without a user change. Validation still runs before submission.
styleTokens.spacing and styleTokens.borderRadius accept bounded numbers
(CSS pixels) or 0, px, rem, and em values.
SdkLeadForm automatically creates the first-party Places provider for fields
authored with autocomplete.provider: 'places'. The SDK target must include
the places:read capability. WebLeadForm and custom renderers can receive
the same provider explicitly:
const places = client.leadForms.createPlacesAutocompleteProvider({
language: 'de',
});
<WebLeadForm definition={definition} autocompleteProviders={{ places }} />;Resolving a suggestion returns provider-keyed values for value,
formattedAddress, street, houseNumber, postalCode, city, state,
country, and countryCode when supplied by Google. Authored targets
determine which definition fields receive those values.
Framework-free web embed
Import or bundle from @scanly/sdk/lead-forms/web-embed.
| Export | Input | Returns | Use |
|---|---|---|---|
mountScanlyLeadForm(element, options) | Target HTMLElement and SafeLeadFormEmbedOptions. | { unmount, update } | Mounts one independently managed form. |
mountScanlyLeadForm({ element, ...options }) | MountScanlyLeadFormOptions. | { unmount, update } | Object-form overload of the same mount operation. |
update(options) accepts SafeLeadFormEmbedUpdate: locale and presentation
changes that are safe after mounting. unmount() releases the React root.
Exported embed types are SafeLeadFormEmbedOptions,
MountScanlyLeadFormOptions, SafeLeadFormEmbedUpdate,
LeadFormClassNames, LeadFormRendererComponents,
LeadFormWebStyleTokens, and LeadFormMessageCatalog.
The browser IIFE exposes window.ScanlyLeadForms.mountScanlyLeadForm and does
not mount automatically. Non-bundler hosts must also load the version-matched
lead-forms/styles.css asset once, or set unstyled and supply all presentation
styles themselves.
React Native lead forms
Import from @scanly/sdk/lead-forms/react-native. React, React Native, and
React Hook Form are optional peers required by this entry point.
| Export | Input | Returns | Use |
|---|---|---|---|
SdkReactNativeLeadForm | SdkReactNativeLeadFormProps with a client and public form ID. | ReactElement | Loads, renders, submits, retries, and reports a managed public form. |
ReactNativeLeadForm | ReactNativeLeadFormProps with an already resolved definition. | ReactElement | Creates transport-free form state and renders native controls. |
ReactNativeLeadFormView | ReactNativeLeadFormViewProps with state from useLeadForm. | ReactElement | Renders already managed state with accessible native primitives. |
Exported native types are SdkReactNativeLeadFormProps,
ReactNativeLeadFormProps, ReactNativeLeadFormViewProps, and
ReactNativeLeadFormRendererComponents, plus the native field, consent,
list-target, and form-error component prop types.
Firebase push adapters
Firebase packages are optional peers. Configure only the platform used by the host application.
Browser
Import from @scanly/sdk/firebase/web.
| Export | Input | Returns | Use |
|---|---|---|---|
createFirebaseWebAdapter(options) | FirebaseWebAdapterOptions: Firebase app, VAPID key, service-worker registration, and optional installation-ID resolver. | PushAdapter | Bridges browser notification permission, FCM tokens, foreground messages, and token deletion to client.push. |
FirebaseWebAdapterOptions | Browser Firebase and service-worker dependencies. | Options type | Constructs the web adapter. |
Import registerScanlyBackgroundHandler from
@scanly/sdk/firebase/web/service-worker. It accepts Firebase Messaging and
a PushMessage listener, then returns a cleanup function that prevents future
listener delivery.
React Native
Import from @scanly/sdk/firebase/react-native.
| Export | Input | Returns | Use |
|---|---|---|---|
createFirebaseReactNativeAdapter(options?) | FirebaseReactNativeAdapterOptions; defaults to lazily loading React Native Firebase Messaging for Android. | PushAdapter | Bridges native permission, FCM registration, refresh, foreground messages, and token deletion. |
registerFirebaseReactNativeBackgroundHandler(handler, messaging?) | Async/sync normalized message handler and a messaging module exposing setBackgroundMessageHandler. | void | Registers native background delivery when the supplied module supports it. |
FirebaseReactNativeAdapterOptions | Optional messaging implementation, platform, Android permission callback, and installation-ID resolver. | Options type | Constructs the native adapter. |
ReactNativeMessagingModule | Minimal messaging-module contract used by the adapter. | Adapter dependency type | Supports dependency injection and testing without importing the full Firebase module eagerly. |
Testing helpers
Import from @scanly/sdk/testing. These helpers are intended for unit tests,
not production code.
| Export | Input | Returns | Use |
|---|---|---|---|
jsonResponse(body, status?, headers?) | JSON body, HTTP status, and header record. | FetchResponse | Creates a minimal SDK-compatible response. |
createFakeFetch(responses?) | Ordered Array<FetchResponse>. | FetchLike | Returns responses sequentially, repeating the final response when exhausted. |
createFakePushAdapter(options?) | Optional platform, permission, and registration. | PushAdapter | Creates an in-memory push adapter for registration and permission tests. |
MemoryStorage | No constructor arguments. | MemoryStorage | Re-export of the root in-memory session storage. |