SDKAPI Reference

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 pathContents
@scanly/publicRoot barrel for public types and functions.
@scanly/public/typesPublic CMS and SDK contracts only.
@scanly/public/functionsAll public platform-neutral functions.
@scanly/public/functions/lead-formsCanonical lead-form compilation and behavior.

Client and shared runtime

Import from @scanly/sdk.

Functions and classes

ExportConstruction / inputReturnsUse
createScanlyClient(options)ScanlyClientOptions with apiBaseUrl and an sdk_pub_… public key. Optional fetch, random-byte, storage, session, attestation, and error adapters may be supplied.ScanlyClientCreates 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.ScanlyErrorRepresents normalized configuration, transport, session, push, theme, and form failures. ScanlyError.fromUnknown(error, fallback?) converts unknown failures.
new MemoryStorage()No arguments.MemoryStorage implementing ScanlyStorageKeeps 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.ScanlyStorageAdapts 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.ScanlyStorageAdapts platform secure storage, for example an encrypted native key-value store.

ScanlyClient

The client has no public constructor; create it with createScanlyClient.

MemberInputReturnsUse
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.
sessionSession managerReads or controls the current session through getState, getAccessToken, ensure, refresh, clearSession, subscribe, and getInstallationId. Most applications only need client.initialize() and repository methods.
identityIdentityRepoReads the current principal, subscribes to identity changes, or signs out.
pushPushRepoRegisters, inspects, revokes, and observes push notifications.
leadFormsLeadFormsRepositoryLoads definitions and prepares or submits public lead forms.
themesThemesRepositoryFetches CMS themes by ID.

Client types

TypePurpose
ScanlyClientOptionsClient construction options. apiBaseUrl and publicKey are required.
ScanlyClientComplete client facade returned by createScanlyClient.
SessionOptionsAccess-token refresh skew plus platform and application identity.
SessionStateCurrent status, installation/session IDs, principal, scopes, and token expiry timestamps.
IdentityRepogetPrincipal(), signOut(), and onChange() contract.
PushRepoClient-bound push registration and foreground-message contract.
ThemesRepositorygetById(themeId): Promise<CMS.Theme> contract.
ScanlyStorageAsynchronous string key-value storage contract.

Push types

TypePurpose
PushAdapterPlatform bridge for permission, provider-token, token-refresh, foreground-message, and deletion operations.
PushConsentConsent evidence sent when registering push notifications.
PushMessageNormalized provider message with optional ID, title, body, and string data.
PushPermission'granted', 'denied', 'provisional', 'unsupported', or 'unknown'.
PushRegisterOptionsAdapter, consent, and optional device/app labels passed to client.push.register.
PushRegistrationMaterialSensitive provider token, platform, and optional provider installation ID.
PushRevokeOptionsControls whether revocation also deletes the provider token.

Transport types

TypePurpose
AbortSignalLikePortable subset of AbortSignal.
FetchHeadersNormalized Record<string, string> request headers.
FetchInitPortable request method, headers, body, abort signal, and omitted credentials.
FetchResponseMinimal response contract required by the SDK.
FetchLikeFetch-compatible function accepted by ScanlyClientOptions.

Themes for React

Import from @scanly/sdk/theme/react. React is an optional peer dependency.

ExportConstruction / inputReturnsUse
ThemeWrapperReact component receiving ThemeWrapperProps.ReactElementWraps descendant content in CMS-derived CSS variables and inherited base styles. The theme takes precedence over caller-provided wrapper styles.
ThemeWrapperPropsA CMS.Theme, children, optional styles, and normal div attributes.Props typeConfigures 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

ExportConstruction / inputReturnsUse
createLeadFormController(options)LeadFormControllerOptions with a definition, optional initial state, clock, and optional leadForms transport.LeadFormControllerManages values, list targets, consent, validation, subscriptions, and retry-safe submission without React.
LeadFormControllerOptionsDefinition plus optional initial values, list-target IDs, granted consent IDs, clock/date, and transport.Options typeConstructs the controller.
LeadFormControllerStateDefinition, canonical form state, validation, runtime, receipt/error, and submission lifecycle.State typeReturned by getState() and subscriptions.
LeadFormControllerController method contract.Controller typegetState, 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

TypePurpose
LeadFormsRepositoryContract exposed as client.leadForms.
LeadFormDefinitionOptionsLocale, abort signal, and cache-bypass options for getDefinition.
LeadFormSubmitOptionsAbort signal accepted by submit.
PrepareLeadFormInputNamed definition, values, selected list-target IDs, consent, and validation-date input accepted by prepare.
SerializedLeadFormAttemptJSON-safe retry attempt returned by serializeAttempt. Restore it through restoreAttempt before submitting.
LeadFormMessageCatalogClient-owned renderer and validation text, keyed by stable SDK message names.
LeadFormUiTextKeySupported renderer-owned message keys.
LEAD_FORM_UI_MESSAGE_KEYSStable host-i18n keys for renderer-owned interface text.
LEAD_FORM_ISSUE_MESSAGE_KEYSStable host-i18n keys keyed by public validation issue code.
PrepareLeadFormAttemptInputNamed idempotency-key input accepted by controller and useLeadForm preparation.

LeadFormsRepository methods:

MethodInputReturnsUse
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.LeadFormAutocompleteProviderCreates the first-party, target-authorized Places provider used by authored address fields.
prepare(input)PrepareLeadFormInput parameter object.LeadFormPreparedSubmissionValidates 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.SerializedLeadFormAttemptPersists a retryable attempt without exposing repository internals.
restoreAttempt(value)Previously serialized unknown value.LeadFormPreparedSubmissionValidates and rebrands a stored attempt.
clearCache()None.voidClears 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.

ExportInputReturnsUse
parseLeadFormDefinition(value)Unknown API or stored value.LeadFormDefinitionValidates a public definition and throws for an invalid contract or version.
parseLocalLeadFormDefinition(value)Unknown locally authored value.LocalLeadFormDefinitionValidates a local definition and identity.
isLeadFormDefinition(value)Unknown value.Type predicateNon-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.stringProduces 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.stringCreates a stable local reference ID.
createLocalLeadFormDefinition(definition, localId)Definition without identity fields and an opaque base64url ID.LocalLeadFormDefinitionAdds a local form ID and deterministic local definition version.
createLocalLeadFormDefinitionFromAuthoring(input)CreateLocalLeadFormDefinitionFromAuthoringInput parameter object.LocalLeadFormAuthoringResultCompiles neutral host authoring data into the canonical local definition used by SDK renderers and validation.
createLeadFormRuntime(definition, values?, selectedListTargetIds?)Definition and current state.LeadFormRuntimeDerives visible/enabled/required fields, active consents, and list-target state.
createLeadFormInitialState(definition, options?)Definition and optional initial values, list targets, and consents.LeadFormStateCreates normalized initial state.
reconcileLeadFormState(previous, next, state)Previous/new definitions and current state.LeadFormReconciliationMigrates compatible state when a definition changes.
validateLeadForm(input)ValidateLeadFormInput parameter object.LeadFormValidationResultValidates active inputs and returns normalized values plus issues.
prepareLeadFormSubmission(input)PrepareLeadFormSubmissionInput parameter object.LeadFormPreparedSubmissionCreates a transport-ready public attempt. Prefer client.leadForms.prepare when using the SDK transport.
prepareLocalLeadFormSubmission(input)PrepareLocalLeadFormSubmissionInput parameter object.LocalLeadFormSubmissionBodyPrepares data for a host-owned create flow.
prepareLeadFormUpdatePatch(input)PrepareLeadFormUpdatePatchInput parameter object.LeadFormUpdatePatchProduces 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

ExportInputReturnsUse
useLeadForm(options)UseLeadFormOptions with an already resolved public or local definition.UseLeadFormResultManages 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.UseSdkLeadFormResultLoads a definition and manages retry-safe SDK submission.
createLeadFormRHFBindings(definition)Renderable definition.LeadFormRHFBindingsCreates stable encoded RHF paths for fields, list targets, and consents.
useLeadFormAutocomplete(options)Field, provider, minimum query length, and apply callback.UseLeadFormAutocompleteResultDebounces search, cancels stale work, resolves selections, and applies mapped values.
mapLeadFormAutocompleteValues(field, values)Authored autocomplete field and provider-keyed values.LeadFormAutocompleteMappedValuesMaps authored provider keys to target fields. Extra provider values are ignored; value fills the active field when no targets are configured.

Types

TypePurpose
UseLeadFormOptionsDefinition, initial values, selected list targets, consents, validation date, clock, and selected RHF options.
UseLeadFormResultRHF form, bindings, runtime, issues, reconciliation, domain-value accessors, setters, reset, validation, and preparation.
UseSdkLeadFormOptionsClient, form ID, optional preloaded definition/locale/initial state, and optional custom submitter.
UseSdkLeadFormResultLoad and submit lifecycles, managed form, errors, receipt, submit, retry, and reset.
LeadFormSubmitterCustom (attempt, options?) => Promise<receipt> transport.
LeadFormRHFValuesEncoded RHF fields, list targets, and consents.
LeadFormRHFBindingsMapping from public IDs to encoded RHF paths.
LeadFormAutocompleteSuggestionProvider-owned suggestion ID and display label.
LeadFormAutocompleteProviderAsynchronous search and resolve contract.
LeadFormAutocompleteProvidersOptional provider map accepted by managed renderers. Set a provider to false to disable it.
LeadFormAutocompleteMappedValuesDomain values after provider-target mapping.
PlacesAutocompleteProviderOptionsOptional BCP 47 language configuration for Scanly’s first-party Places provider.
UseLeadFormAutocompleteOptionsAutocomplete hook configuration.
UseLeadFormAutocompleteResultQuery, 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.

ExportConstruction / inputReturnsUse
SdkLeadFormSdkLeadFormProps with a client and public form ID.ReactElementLoads, renders, validates, submits, retries, and displays success/error state.
WebLeadFormWebLeadFormProps with an already resolved definition.ReactElementTransport-free managed form for host-owned data flows.
LeadFormViewLeadFormRenderProps with state from useLeadForm.ReactElementRenders already managed state using semantic HTML.
parseLeadFormWebViewMessage(value)Unknown host message.LeadFormWebViewMessage | nullValidates a privacy-safe WebView lifecycle envelope.
postLeadFormWebViewMessage(message, targetOrigin)Valid message and exact HTTPS parent origin.voidPosts allowlisted lifecycle metadata to WKWebView or a parent window.

Web renderer types

TypePurpose
SdkLeadFormPropsSDK-backed form loading, rendering, callbacks, styles, and WebView origin.
WebLeadFormPropsTransport-free definition plus renderer options.
LeadFormRenderPropsManaged state, component overrides, submission callbacks, mode, messages, classes, and styles.
LeadFormRendererComponentsOptional field, consent, list-target, submit, form-error, and success component overrides.
LeadFormListTargetComponentPropsProps passed to a custom list-target selector.
LeadFormFieldComponentPropsProps passed to a custom field renderer.
LeadFormMode'create', 'edit', or 'preview'.
LeadFormSlotStable renderer slot names.
LeadFormClassNamesOptional CSS classes keyed by slot.
LeadFormWebStyleTokensColors, spacing, radius, control height, and font tokens.
LeadFormMessageCatalogClient-owned UI and validation text. Missing entries render stable SDK i18n keys.
LeadFormWebViewMessagePII-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.

ExportInputReturnsUse
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.

ExportInputReturnsUse
SdkReactNativeLeadFormSdkReactNativeLeadFormProps with a client and public form ID.ReactElementLoads, renders, submits, retries, and reports a managed public form.
ReactNativeLeadFormReactNativeLeadFormProps with an already resolved definition.ReactElementCreates transport-free form state and renders native controls.
ReactNativeLeadFormViewReactNativeLeadFormViewProps with state from useLeadForm.ReactElementRenders 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.

ExportInputReturnsUse
createFirebaseWebAdapter(options)FirebaseWebAdapterOptions: Firebase app, VAPID key, service-worker registration, and optional installation-ID resolver.PushAdapterBridges browser notification permission, FCM tokens, foreground messages, and token deletion to client.push.
FirebaseWebAdapterOptionsBrowser Firebase and service-worker dependencies.Options typeConstructs 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.

ExportInputReturnsUse
createFirebaseReactNativeAdapter(options?)FirebaseReactNativeAdapterOptions; defaults to lazily loading React Native Firebase Messaging for Android.PushAdapterBridges native permission, FCM registration, refresh, foreground messages, and token deletion.
registerFirebaseReactNativeBackgroundHandler(handler, messaging?)Async/sync normalized message handler and a messaging module exposing setBackgroundMessageHandler.voidRegisters native background delivery when the supplied module supports it.
FirebaseReactNativeAdapterOptionsOptional messaging implementation, platform, Android permission callback, and installation-ID resolver.Options typeConstructs the native adapter.
ReactNativeMessagingModuleMinimal messaging-module contract used by the adapter.Adapter dependency typeSupports 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.

ExportInputReturnsUse
jsonResponse(body, status?, headers?)JSON body, HTTP status, and header record.FetchResponseCreates a minimal SDK-compatible response.
createFakeFetch(responses?)Ordered Array<FetchResponse>.FetchLikeReturns responses sequentially, repeating the final response when exhausted.
createFakePushAdapter(options?)Optional platform, permission, and registration.PushAdapterCreates an in-memory push adapter for registration and permission tests.
MemoryStorageNo constructor arguments.MemoryStorageRe-export of the root in-memory session storage.