diff --git a/.changeset/davinci-metadata-collector.md b/.changeset/davinci-metadata-collector.md
new file mode 100644
index 000000000..26dd20874
--- /dev/null
+++ b/.changeset/davinci-metadata-collector.md
@@ -0,0 +1,18 @@
+---
+'@ping-identity/rn-davinci': minor
+---
+
+feat(rn-davinci): add DaVinci METADATA collector pause/resume support (SDKS-5384)
+
+Exposes the SDK Integrator connector pause/resume flow: a `METADATA` field now
+surfaces as a typed `MetadataCollector` with the opaque connector payload on
+`metadata` and the new `metadata` execution mode/field kind. The flow pauses
+until the app sets a result as the collector's form value and resumes via
+`next()` — an object is POSTed as the success result (wrap it with the new
+`buildMetadataResult` helper, which keeps the form value type from accepting
+arbitrary objects for other collectors), and a `{ error: { code, message } }`
+envelope (build one with the new `buildMetadataError` helper) routes the
+connector's error branch. Submit
+planning blocks with `METADATA_RESULT_REQUIRED` while no result is set and
+with `METADATA_RESULT_MALFORMED` for non-object, array, or malformed-envelope
+values; `computeFormMeta` gains `hasMetadata`.
diff --git a/PingSampleApp/ui/davinci/components/molecules/DaVinciFieldRenderer.tsx b/PingSampleApp/ui/davinci/components/molecules/DaVinciFieldRenderer.tsx
index fefd423ab..8cbe8c87b 100644
--- a/PingSampleApp/ui/davinci/components/molecules/DaVinciFieldRenderer.tsx
+++ b/PingSampleApp/ui/davinci/components/molecules/DaVinciFieldRenderer.tsx
@@ -13,6 +13,7 @@ import DaVinciFidoField from './DaVinciFidoField';
import DaVinciIdpField from './DaVinciIdpField';
import DaVinciImageField from './DaVinciImageField';
import DaVinciLabelField from './DaVinciLabelField';
+import DaVinciMetadataField from './DaVinciMetadataField';
import DaVinciMultiSelectField from './DaVinciMultiSelectField';
import DaVinciPasswordField from './DaVinciPasswordField';
import DaVinciPhoneNumberField from './DaVinciPhoneNumberField';
@@ -86,6 +87,8 @@ function DaVinciFieldRenderer(
return ;
case 'IMAGE':
return ;
+ case 'METADATA':
+ return ;
default:
return ;
}
diff --git a/PingSampleApp/ui/davinci/components/molecules/DaVinciMetadataField.tsx b/PingSampleApp/ui/davinci/components/molecules/DaVinciMetadataField.tsx
new file mode 100644
index 000000000..46554c6bd
--- /dev/null
+++ b/PingSampleApp/ui/davinci/components/molecules/DaVinciMetadataField.tsx
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2026 Ping Identity Corporation. All rights reserved.
+ *
+ * This software may be modified and distributed under the terms
+ * of the MIT license. See the LICENSE file for details.
+ */
+
+import React from 'react';
+import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';
+import {
+ buildMetadataError,
+ buildMetadataResult,
+ type MetadataCollector,
+} from '@ping-identity/rn-davinci';
+import { colors } from '../../../../src/styles/colors';
+import { commonStyles } from '../../../../src/styles/common';
+import { davinciFieldStyles } from '../../../../src/styles/davinciStyles';
+import type { DaVinciCollectorRendererProps } from './types';
+
+/**
+ * Demo success result stored by the "Set result" control.
+ *
+ * @remarks
+ * A real integration replaces this with the object the connector expects —
+ * any non-empty JSON object is a valid success result.
+ */
+const DEMO_SUCCESS_RESULT = buildMetadataResult({
+ status: 'success',
+ source: 'sample-app',
+});
+
+/**
+ * Renders a {@link MetadataCollector} pause field: the connector payload as
+ * pretty JSON plus demo controls that store a success result, an error
+ * envelope, or clear the stored result.
+ *
+ * @remarks
+ * SDK Integrator connector pause/resume: the SDK surfaces the opaque
+ * `metadata` payload; the app performs the on-device work and stores a result
+ * as the collector's form value before the flow can resume via `next()`.
+ * This molecule is sample-app demo scaffolding — "Set result" stores
+ * {@link DEMO_SUCCESS_RESULT} and "Set error" stores a
+ * {@link buildMetadataError} envelope; a real integration would replace both
+ * with the actual SDK work. "Clear" stores `null`, which the submit helper
+ * treats as unset and blocks with `METADATA_RESULT_REQUIRED` until a result
+ * is present (gating is result-set-based, independent of the server
+ * `required` flag).
+ *
+ * @param props Renderer props.
+ * @returns Metadata field element.
+ */
+export default function DaVinciMetadataField(
+ props: DaVinciCollectorRendererProps,
+): React.ReactElement {
+ const { collector, value, onChange } = props;
+ const metadataCollector = collector as MetadataCollector;
+ const isSet = value !== undefined && value !== null;
+
+ return (
+
+
+ {metadataCollector.label || 'SDK metadata'}
+
+ Connector payload:
+
+ {JSON.stringify(metadataCollector.metadata, null, 2)}
+
+ Result:
+
+ {isSet ? JSON.stringify(value, null, 2) : 'Not set'}
+
+ {!isSet ? (
+
+ A result is required before the flow can resume.
+
+ ) : null}
+ onChange(DEMO_SUCCESS_RESULT)}
+ >
+ Set result
+
+
+ onChange(
+ buildMetadataError(
+ 'USER_CANCELLED',
+ 'User cancelled the operation',
+ ),
+ )
+ }
+ >
+ Set error
+
+ onChange(null)}
+ >
+ Clear
+
+
+ );
+}
+
+const styles = StyleSheet.create({
+ jsonText: {
+ fontFamily: 'Courier',
+ fontSize: 12,
+ color: colors.textDark,
+ backgroundColor: colors.background,
+ borderRadius: 8,
+ padding: 8,
+ marginTop: 4,
+ marginBottom: 4,
+ },
+});
diff --git a/PingSampleApp/ui/davinci/hooks/useDaVinciAutoForwarder.ts b/PingSampleApp/ui/davinci/hooks/useDaVinciAutoForwarder.ts
index a80fcf89f..2abab2a83 100644
--- a/PingSampleApp/ui/davinci/hooks/useDaVinciAutoForwarder.ts
+++ b/PingSampleApp/ui/davinci/hooks/useDaVinciAutoForwarder.ts
@@ -81,6 +81,12 @@ export function useDaVinciAutoForwarder(
if (lastNodeKeyRef.current === continueNodeKey) return;
const { meta, canSubmit, input } = form;
+ if (meta.hasMetadata) {
+ // A METADATA node needs an app-supplied result and an explicit Continue.
+ // Consume the one-shot flag here so a later node is not auto-forwarded.
+ onForwarded();
+ return;
+ }
if (meta.hasManual) return;
if (meta.hasIntegrationRequired) return;
if (meta.hasUnsupported) return;
diff --git a/PingTestRunner/__tests__/integration/davinci.test.ts b/PingTestRunner/__tests__/integration/davinci.test.ts
index aca736b21..58051f72f 100644
--- a/PingTestRunner/__tests__/integration/davinci.test.ts
+++ b/PingTestRunner/__tests__/integration/davinci.test.ts
@@ -1473,6 +1473,133 @@ describe('@ping-identity/rn-davinci — integration', () => {
});
});
+ // ─── METADATA — SDK Integrator pause/resume ───────────────────
+ //
+ // The native mapper (packages/davinci native tests) already proves a
+ // MetadataCollector serialises to { key, type: 'METADATA', label, required,
+ // metadata: }. These tests exercise the JS composition layer:
+ // classification, pause gating (unset/malformed block), and resume
+ // pass-through (success object / error envelope reach the next() payload
+ // intact).
+
+ describe('METADATA — SDK Integrator pause/resume', () => {
+ const metadataCollector = {
+ key: 'sdkMetadata',
+ type: 'METADATA',
+ label: '',
+ required: false,
+ metadata: { sdk: 'PROTECT', action: 'INITIALIZE' },
+ };
+
+ const metadataNode = {
+ type: 'ContinueNode',
+ collectors: [metadataCollector],
+ };
+
+ function loadWithMetadataNode(): Promise<{
+ mod: typeof import('@ping-identity/rn-davinci');
+ mock: NativeDaVinciMock;
+ }> {
+ const mock = makeMock({
+ start: jest.fn(async () => metadataNode),
+ });
+ return loadDaVinci(mock).then((mod) => ({ mod, mock }));
+ }
+
+ it('classifies METADATA as executionMode metadata + kind metadata (payload intact)', async () => {
+ const { mod } = await loadWithMetadataNode();
+ const client = mod.createDaVinciClient(VALID_CONFIG);
+ const node = asContinueNode(await client.start());
+ const collectors = mod.normalizeCollectors(node.collectors);
+ expect(collectors).toHaveLength(1);
+ expect(collectors[0]).toMatchObject({
+ key: 'sdkMetadata',
+ type: 'METADATA',
+ executionMode: 'metadata',
+ kind: 'metadata',
+ requiresUserInput: false,
+ metadata: { sdk: 'PROTECT', action: 'INITIALIZE' },
+ });
+ });
+
+ it('computeFormMeta reports hasMetadata for a metadata node', async () => {
+ const { mod } = await loadWithMetadataNode();
+ const client = mod.createDaVinciClient(VALID_CONFIG);
+ const node = asContinueNode(await client.start());
+ expect(
+ mod.computeFormMeta(mod.normalizeCollectors(node.collectors)),
+ ).toMatchObject({ hasMetadata: true });
+ });
+
+ it('unset value blocks with METADATA_RESULT_REQUIRED and sends nothing', async () => {
+ const { mod, mock } = await loadWithMetadataNode();
+ const client = mod.createDaVinciClient(VALID_CONFIG);
+ const node = asContinueNode(await client.start());
+ const plan = mod.buildNextInput(node, {});
+ expect(plan.canSubmit).toBe(false);
+ expect(plan.issues).toContainEqual(
+ expect.objectContaining({
+ code: 'METADATA_RESULT_REQUIRED',
+ key: 'sdkMetadata',
+ }),
+ );
+ await client.next(plan.input);
+ expect(mock.next).toHaveBeenCalledWith('davinci-id-mock', {
+ collectors: [],
+ });
+ });
+
+ it('success result passes through to the next() payload intact', async () => {
+ const { mod, mock } = await loadWithMetadataNode();
+ const client = mod.createDaVinciClient(VALID_CONFIG);
+ const node = asContinueNode(await client.start());
+ const plan = mod.buildNextInput(node, {
+ sdkMetadata: mod.buildMetadataResult({ status: 'success' }),
+ });
+ expect(plan.canSubmit).toBe(true);
+ expect(plan.issues).toEqual([]);
+ await client.next(plan.input);
+ expect(mock.next).toHaveBeenCalledTimes(1);
+ expect(mock.next).toHaveBeenCalledWith('davinci-id-mock', {
+ collectors: [{ key: 'sdkMetadata', value: { status: 'success' } }],
+ });
+ });
+
+ it('error envelope passes through to the next() payload intact', async () => {
+ const errorEnvelope = {
+ error: { code: 'USER_CANCELLED', message: 'User cancelled' },
+ };
+ const { mod, mock } = await loadWithMetadataNode();
+ const client = mod.createDaVinciClient(VALID_CONFIG);
+ const node = asContinueNode(await client.start());
+ const plan = mod.buildNextInput(node, { sdkMetadata: errorEnvelope });
+ expect(plan.canSubmit).toBe(true);
+ expect(plan.issues).toEqual([]);
+ await client.next(plan.input);
+ expect(mock.next).toHaveBeenCalledWith('davinci-id-mock', {
+ collectors: [{ key: 'sdkMetadata', value: errorEnvelope }],
+ });
+ });
+
+ it('malformed value (string) blocks with METADATA_RESULT_MALFORMED', async () => {
+ const { mod, mock } = await loadWithMetadataNode();
+ const client = mod.createDaVinciClient(VALID_CONFIG);
+ const node = asContinueNode(await client.start());
+ const plan = mod.buildNextInput(node, { sdkMetadata: 'not-an-object' });
+ expect(plan.canSubmit).toBe(false);
+ expect(plan.issues).toContainEqual(
+ expect.objectContaining({
+ code: 'METADATA_RESULT_MALFORMED',
+ key: 'sdkMetadata',
+ }),
+ );
+ await client.next(plan.input);
+ expect(mock.next).toHaveBeenCalledWith('davinci-id-mock', {
+ collectors: [],
+ });
+ });
+ });
+
// ─── terminal node shapes ──────────────────────────────────────────────────
//
// SuccessNode/ErrorNode/FailureNode pass through the bridge as-is. These
diff --git a/PingTestRunner/e2e/davinci-metadata.test.ts b/PingTestRunner/e2e/davinci-metadata.test.ts
new file mode 100644
index 000000000..8131124ac
--- /dev/null
+++ b/PingTestRunner/e2e/davinci-metadata.test.ts
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2026 Ping Identity Corporation. All rights reserved.
+ *
+ * This software may be modified and distributed under the terms
+ * of the MIT license. See the LICENSE file for details.
+ */
+
+/**
+ * E2E — DaVinci METADATA collector pause/resume
+ *
+ * A DaVinci SDK Integrator connector pauses the flow with a `METADATA`
+ * collector carrying an opaque payload; the app performs the on-device work
+ * and supplies a result before the flow resumes via `next()`.
+ *
+ * The live test is env-gated: driving a METADATA field requires a tenant flow
+ * whose connector actually pauses with `METADATA`. Unless
+ * DAVINCI_METADATA_FLOW is `true`, the live test is registered as skipped, so
+ * reports show it as skipped rather than passed. The deterministic scenario UI
+ * (payload display, Set result / Set error / Clear controls, unset-state
+ * indicator) is covered by the integration suite in
+ * `__tests__/integration/davinci.test.ts` without a live flow.
+ *
+ * To run the live test against a metadata-enabled tenant flow:
+ * 1. Set DAVINCI_METADATA_FLOW=true plus the standard DaVinci env vars
+ * (PINGONE_DISCOVERY_ENDPOINT, PINGONE_CLIENT_ID, PINGONE_REDIRECT_URI,
+ * PINGONE_ACR_VALUES — the same set the launchArgs below forward; note
+ * these launch the app's DaVinci scenario unauthenticated, matching
+ * davinci.test.ts — drive any login step through the flow itself).
+ * 2. Update DAVINCI_METADATA_KEY below to the connector's collector key.
+ *
+ * testIDs consumed (see scenarios/DaVinciScenario.tsx manifest):
+ * davinci-field-{key}-metadata-payload / -metadata-value / -metadata-unset
+ * davinci-field-{key}-metadata-set-result / -metadata-set-error / -metadata-clear
+ */
+
+/* eslint-disable @typescript-eslint/no-explicit-any */
+import { device, element, by, expect as detoxExpect, waitFor } from 'detox';
+import { expect as jestExpect } from '@jest/globals';
+import { assertAppReady, DAVINCI_ENV } from './setup';
+
+const NET_TIMEOUT = 30000;
+
+// Collector key the metadata-enabled connector uses on the pause node.
+const DAVINCI_METADATA_KEY =
+ process.env['PING_DAVINCI_METADATA_KEY'] ?? 'sdkMetadata';
+
+// Registered as skipped (not silently passed) unless a metadata-enabled tenant
+// flow is configured; the file header lists the env vars required to enable it.
+const itLive = process.env['DAVINCI_METADATA_FLOW'] === 'true' ? it : it.skip;
+
+const LAUNCH_ARGS = {
+ PING_TEST_SCENARIO: 'davinci',
+ ...(DAVINCI_ENV.discoveryEndpoint
+ ? { PINGONE_DISCOVERY_ENDPOINT: DAVINCI_ENV.discoveryEndpoint }
+ : {}),
+ ...(DAVINCI_ENV.clientId ? { PINGONE_CLIENT_ID: DAVINCI_ENV.clientId } : {}),
+ ...(DAVINCI_ENV.redirectUri
+ ? { PINGONE_REDIRECT_URI: DAVINCI_ENV.redirectUri }
+ : {}),
+ ...(DAVINCI_ENV.acrValues
+ ? { PINGONE_ACR_VALUES: DAVINCI_ENV.acrValues }
+ : {}),
+};
+
+describe('DaVinci — METADATA pause/resume', () => {
+ beforeAll(async () => {
+ await device.launchApp({ newInstance: true, launchArgs: LAUNCH_ARGS });
+ await device.disableSynchronization();
+ });
+
+ afterAll(async () => {
+ await device.terminateApp();
+ });
+
+ it('app launches and root is visible', async () => {
+ await assertAppReady();
+ });
+
+ itLive(
+ 'METADATA field surfaces payload, blocks while unset, then resumes with a result (live)',
+ async () => {
+ // The flow's first node is a form whose single SUBMIT_BUTTON ("Metadata")
+ // leads to the METADATA pause. The bridge surfaces exactly one submit
+ // button here, so it carries the generic davinci-submit-btn testID.
+ await element(by.id('davinci-start-btn')).tap();
+ await waitFor(element(by.id('davinci-submit-btn')))
+ .toBeVisible()
+ .withTimeout(NET_TIMEOUT);
+ await element(by.id('davinci-submit-btn')).tap();
+
+ await waitFor(element(by.id(`davinci-field-${DAVINCI_METADATA_KEY}`)))
+ .toBeVisible()
+ .withTimeout(NET_TIMEOUT);
+ // Re-asserted via detoxExpect: BrowserStack derives the test verdict from
+ // explicit expect calls, not waitFor polling.
+ await detoxExpect(
+ element(
+ by.id(`davinci-field-${DAVINCI_METADATA_KEY}-metadata-payload`),
+ ),
+ ).toBeVisible();
+
+ // Unset state: the blocking indicator is visible until a result is set.
+ await detoxExpect(
+ element(by.id(`davinci-field-${DAVINCI_METADATA_KEY}-metadata-unset`)),
+ ).toBeVisible();
+
+ // Store a demo success result and confirm the value indicator updated.
+ await element(
+ by.id(`davinci-field-${DAVINCI_METADATA_KEY}-metadata-set-result`),
+ ).tap();
+ await waitFor(
+ element(by.id(`davinci-field-${DAVINCI_METADATA_KEY}-metadata-value`)),
+ )
+ .toBeVisible()
+ .withTimeout(NET_TIMEOUT);
+ const attrs = await element(
+ by.id(`davinci-field-${DAVINCI_METADATA_KEY}-metadata-value`),
+ ).getAttributes();
+ const text = (attrs as any).text ?? (attrs as any).label ?? '';
+ jestExpect(text).toContain('status');
+
+ // Resume: with the result stored the flow must advance past the pause.
+ // The flow echoes the submitted result on a message node and then loops
+ // back to its start form, so the post-resume assertion is that a new
+ // form node arrived rather than a terminal success screen.
+ await element(by.id('davinci-submit-btn')).tap();
+ await waitFor(element(by.id('davinci-start-btn')))
+ .toBeVisible()
+ .withTimeout(NET_TIMEOUT);
+ // The next node renders a fresh form: the field container is gone
+ // (resumed past the pause) while the scenario stays interactive.
+ await detoxExpect(
+ element(by.id(`davinci-field-${DAVINCI_METADATA_KEY}-metadata-unset`)),
+ ).not.toExist();
+ },
+ );
+});
diff --git a/PingTestRunner/ios/Podfile.lock b/PingTestRunner/ios/Podfile.lock
index de8771a54..6299ba217 100644
--- a/PingTestRunner/ios/Podfile.lock
+++ b/PingTestRunner/ios/Podfile.lock
@@ -3731,86 +3731,86 @@ SPEC CHECKSUMS:
RCTTypeSafety: d877728097547d0a37786cc9130c43ad71739ac3
React: 4b0b9cb962e694611e5e8a697c1b0300a2510c21
React-callinvoker: 70f125c17c7132811a6b473946ac5e7ae93b5e57
- React-Core: 7cbc3118df2334b2ef597d9a515938b02c82109f
- React-CoreModules: 7d8c14ecb889e7786a04637583b55b7d8f246baf
- React-cxxreact: f32be07cba236c2f20f4e05ca200577ba5358e78
+ React-Core: bab40f5b1f46fe0c5896895a6f333e861a821a81
+ React-CoreModules: 05647d952e521113c128360633896ba7ba652e82
+ React-cxxreact: 2b4bac1ec6eecc6288ac8a6caea6afb42585740e
React-debug: deb3a146ef717fa3e8f4c23e0288369fe53199b7
- React-defaultsnativemodule: 2c13a4240c5f96c42d069d1ba2392de6b4145bbd
- React-domnativemodule: 91349b0b1cb20310cec1341b87cdd461aaa85e57
- React-Fabric: bdfc7ec2481f26d7a9b8f59461f29ba4d903c549
- React-FabricComponents: 47898469543d1bfb4528a9846419ec5568be89b1
- React-FabricImage: ac8fc85ef452e5e9ae935c41118814651bd9e7f3
- React-featureflags: 793b911e4c53e680db4a7d9965d0d6dc87b2fa88
- React-featureflagsnativemodule: 25c9516d0dd004493c9bbafeb97da20bf9bde7dc
- React-graphics: e07281690425dd9eeba3875d1faad28bc1f6da3b
- React-hermes: bc1440d0e0662cc813bbf1c5ffbf9e0db2993a0f
- React-idlecallbacksnativemodule: a2a3bb4a1793280b34d06d00169153b094be8c16
- React-ImageManager: c9fa7461f3cab08e7bc98cbf55455b499e71c8b3
- React-jserrorhandler: 15e591702040afed99cfcd088cf2337a8d09d807
- React-jsi: 512ab3a1a628bc8824c41de8bcbbb81b2ac6fa8d
- React-jsiexecutor: 653ccd2dee1e5ea558eecaf2f27b8bba0f09add8
- React-jsinspector: 9121ccd2676a3f7c079ac01c9f90183422e3190e
- React-jsinspectorcdp: 5c723ff2a09d73f2fdc496a545fb7003e7fdc079
- React-jsinspectornetwork: 9cb0173f69e8405cef33fc79030fad26bbc3c073
- React-jsinspectortracing: 65dc04125dc2392d85a82b6916f8cb088ea77566
- React-jsitooling: 21af93cc98f760dd88d65b06b9317e0d4849fbbc
- React-jsitracing: 4cc1b7de8087ae41c61a0eeee2593bc3362908b6
- React-logger: 2f0d40bc8e648fbb1ff3b6580ad54189a8753290
- React-Mapbuffer: 9a7c65078c6851397c1999068989e4fc239d0c80
- React-microtasksnativemodule: 4f1ef719ba6c7ebbd2d75346ffa2916f9b4771c9
- react-native-launch-arguments: c02ee750ca094c92d2f9a5830c2c085efd10ec56
- React-NativeModulesApple: f6f696e510b9d89c3c06b7764f56947dc13ae922
+ React-defaultsnativemodule: 11e2948787a15d3cf1b66d7f29f13770a177bff7
+ React-domnativemodule: 2f4b279acdb2963736fb5de2f585811dd90070b5
+ React-Fabric: 6f8d1a303c96f1d078c14d74c4005bf457e5b782
+ React-FabricComponents: b106410970e9a0c4e592da656c7a7e0947306c23
+ React-FabricImage: 1abaf230dfce9b58fdf53c4128f3f40c6e64af6a
+ React-featureflags: f7ef58d91079efde3ad223bcca6d197e845d5bcf
+ React-featureflagsnativemodule: ae5abc9849d1696f4f8f11ee3744bf5715e032cf
+ React-graphics: b306856c6ed9aac32f717a229550406a53b28a6d
+ React-hermes: b6edce8fa19388654b1aea30844497cbeade83bc
+ React-idlecallbacksnativemodule: cb386712842cb9e479c89311edb234d529b64db4
+ React-ImageManager: 8ce94417853eaa22faaad1f4cc1952dd3f8e2275
+ React-jserrorhandler: ab827d67dc270a9c8703eef524230baeafaf6876
+ React-jsi: 545342ec5c78ab1277af5f0dbe8d489e7e73db14
+ React-jsiexecutor: 20210891c7c77255c16dec6762faf68b373f9f74
+ React-jsinspector: 4e73460e488132d70d2b4894e5578cc856f2cb74
+ React-jsinspectorcdp: 8b2bcb5779289cb2b9ca517f2965ed23eb2fd3e0
+ React-jsinspectornetwork: b5e0cb9e488d294eed2d8209dc3dc0f9587210c1
+ React-jsinspectortracing: f3c4036e7b984405ac910f878576d325dd9f2834
+ React-jsitooling: 75bbfd221b6173a5e848ca5a6680506bac064a56
+ React-jsitracing: 11ed7d821864dd988c159d4943e0a1e0937c11b1
+ React-logger: 984ebd897afad067555d081deaf03f57c4315723
+ React-Mapbuffer: 0c045c844ce6d85cde53e85ab163294c6adad349
+ React-microtasksnativemodule: d9499269ad1f484ae71319bac1d9231447f2094e
+ react-native-launch-arguments: eab68037b01ea7c78a0b3b55da3a5e967e9aaf92
+ React-NativeModulesApple: 983f3483ef0a3446b56d490f09d579fba2442e17
React-oscompat: 114036cd8f064558c9c1a0c04fc9ae5e1453706a
- React-perflogger: 4b2f88ae059b600daf268528a4a83366338eef05
- React-performancetimeline: e15fd9798123436f99e46898422fe921fecf506b
+ React-perflogger: e7287fee27c16e3c8bd4d470f2361572b63be16b
+ React-performancetimeline: 8ebbaa31d2d0cea680b0a2a567500d3cab8954fc
React-RCTActionSheet: 68c68b0a7a5d2b0cfc255c64889b6e485974e988
- React-RCTAnimation: 6bf502c89c53076f92cd1a254f5ec8d63ee263de
- React-RCTAppDelegate: c90f5732784684c3dd226d812eccb578cd954ad7
- React-RCTBlob: d2905f01749b80efd6d3b86fb15e30ed26d5450b
- React-RCTFabric: 435b3ffaad113fb1f274c2f2a677c9fcc9b5cf55
- React-RCTFBReactNativeSpec: a3178b419f42af196e90ca4bf07710dce5d68301
- React-RCTImage: 8f5ffa03461339180a68820ea452af6e20ace2c7
- React-RCTLinking: 1151646834d31f97580d8a75d768a84b2533b7f9
- React-RCTNetwork: 52008724d0db90a540f4058ed0de0e41c4b7943c
- React-RCTRuntime: 10ce9a7cb27ba307544d29a2a04e6202dc7b3e9a
- React-RCTSettings: f724cacbd892ee18f985e1aebdd97386e49c76f5
- React-RCTText: 6e1b95d9126d808410dfa96e09bc4441ec6f36f7
- React-RCTVibration: 862a4e5b36d49e6299c8cbfb86486fc31f86f6fa
+ React-RCTAnimation: d6c5c728b888a967ce9aff1ff71a8ed71a68d069
+ React-RCTAppDelegate: 0fc048666bda159cd469a6fb9befb04b3fa62be4
+ React-RCTBlob: 12d8c699a1f906840113ee8d8bb575e69a05509f
+ React-RCTFabric: 01e815845ebc185f44205dcbf50eeb712fec23fe
+ React-RCTFBReactNativeSpec: f57927fb0af6ce2f25c19f8b894e2986138aa89f
+ React-RCTImage: a82518168f4ee407913b23ca749ca79ef51959f3
+ React-RCTLinking: 7f343b584c36f024f390fea563483568fe763ef6
+ React-RCTNetwork: 3165eb757ceb62a7cde4cdad043d63314122e8a3
+ React-RCTRuntime: feee590c459c4cb6aaa7a00f3abc8c04709b536f
+ React-RCTSettings: 6bad0ae45d8d872c873059f332f586f99875621f
+ React-RCTText: 657d60f35983062de8f0cea67c279aa7a3ea9858
+ React-RCTVibration: 78f4770515141efb7f55f9b27c49dda95319c3a8
React-rendererconsistency: f7baab26c6d0cd5b2eb7afcecfd2d8b957017b18
- React-renderercss: 62acb8f010a062309e3bd0e203aa14636162e3b3
- React-rendererdebug: 3a89ac44f15c7160735264d585a29525655238d2
+ React-renderercss: bdd2f83a4a054c3e4321fd61305c202b848e471b
+ React-rendererdebug: 9f8865ee038127a9d99d4b034c9da4935d204993
React-rncore: f7438473c4c71ee1963fb06a8635bb96013c9e1c
- React-RuntimeApple: 81f0a9ba81ce7eb203529b0471dc69bf18f5f637
- React-RuntimeCore: 6356e89b2518ba66a989c39a2adb18122a5e3b7b
+ React-RuntimeApple: 4d2ab9f72b9193da86eceded128a67254fc18aeb
+ React-RuntimeCore: 5fd73030438d094975ca0f549d162dd97746ae38
React-runtimeexecutor: 17c70842d5e611130cb66f91e247bc4a609c3508
- React-RuntimeHermes: 0a1d7ce2fe08cf182235de1a9330b51aa6b935cd
- React-runtimescheduler: 10ae98e1417eff159be5df8fdc8fcdaac557aba6
+ React-RuntimeHermes: 3c88e6e1ea7ea0899dcffc77c10d61ea46688cfd
+ React-runtimescheduler: 024500621c7c93d65371498abb4ee26d34f5d47d
React-timing: c3c923df2b86194e1682e01167717481232f1dc7
- React-utils: 7791a96e194eec85cb41dc98a2045b5f07839598
- ReactAppDependencyProvider: ba631a31783569c13056dd57ff39e19764abdd6f
- ReactCodegen: 1e9f3e8a3f56fa25fbf39ecd37b708a4838d9032
- ReactCommon: 96684b90b235d6ae340d126141edd4563b7a446a
+ React-utils: 9154a037543147e1c24098f1a48fc8472602c092
+ ReactAppDependencyProvider: afd905e84ee36e1678016ae04d7370c75ed539be
+ ReactCodegen: 62690fdeb185860673cb78e3d9b049c7e1d40531
+ ReactCommon: 17fd88849a174bf9ce45461912291aca711410fc
RecaptchaEnterprise: a28429a5366cc0f687ac5e93a44c5caa2c685aa9
RecaptchaEnterpriseSDK: 72239ea30c486d9093918c7b31eb85629eff1a50
RecaptchaInterop: 11e0b637842dfb48308d242afc3f448062325aba
- RNCAsyncStorage: 767abb068db6ad28b5f59a129fbc9fab18b377e2
- RNPingBinding: e4d2b04deac5fd415bc6c51183f8ab7f20a32cae
- RNPingBrowser: c8c9c7d39ae023f2dd3c5d59c7b5577e2afb5093
- RNPingCore: f4a461e75fbe3fccf3263e2b91938d9887324b32
- RNPingDavinci: 9b356e3b5bf6f0c3f956a20df788d2046d126bec
- RNPingDeviceClient: ffede82b969dd2119f02a79735a3e87bf2bd5290
- RNPingDeviceId: 24b703e3ae56c1e565fb3817916baa8874c51886
- RNPingDeviceProfile: 2ec43b7ac75897523af8222688b7e98a5a695eb9
- RNPingExternalIdp: 017fdda77ecf222960029213ad7a50bf54f9d067
- RNPingFido: faf7fbaeeef3c4e0513091eacfc46dd45579baa8
- RNPingJourney: 6cf81cf6036580d995ebf92e41843791251487bf
- RNPingLogger: 0ce33153b0caf1790dc8156986557924767a1b69
- RNPingOath: 58432fb0f7f72eaea13dc8c761a2fe45974da716
- RNPingOidc: bd7d8b6f5dc7da893c1f0d713058500a16606a95
- RNPingProtect: f80df46fd64be64c343ca1507315ec9093c53863
- RNPingPush: 1043c9fcb01b0172b99690d2fe7f12d61948f49d
- RNPingRecaptcha: 20ff6927ccac6cb4497e59c040eb9b778c323d48
- RNPingStorage: ce105d17812c024e043f8234ef62d1e5fdf80e25
+ RNCAsyncStorage: 1f04c8d56558e533277beda29187f571cf7eecb2
+ RNPingBinding: c2a36497bad23954aafa867594ff3da82ce4cd0a
+ RNPingBrowser: 798d176d117a73294d6b7863ecbc27fd54e6515d
+ RNPingCore: d97a80b517854e846c40b6f0155c4ffed6bd793a
+ RNPingDavinci: 5bd80921949104545f2744a7ec2d47da0a399554
+ RNPingDeviceClient: be4ccdf53ee94adb65bb6ccea1395a485426612e
+ RNPingDeviceId: b047b8e355f31104673e9ff3a65998329bfc999a
+ RNPingDeviceProfile: aaa66f2e792bbee60f4d40686668e867d7b1c73f
+ RNPingExternalIdp: 16a3b51f49df157dc11fe1568b4f89f251a45229
+ RNPingFido: b7025cc73c8bef937d43bcdcb693cb325ce86dbc
+ RNPingJourney: 8290ffc12aa49794e6b5aaac4d870f0488b12743
+ RNPingLogger: 5bd4be81a79cf6a7e1788bbac08d3c33156c0359
+ RNPingOath: aa9a3684200d9df715544106102857f314c09a32
+ RNPingOidc: c6c84a86496759050cdcb774ae5b5ce63b56ed9c
+ RNPingProtect: 04bbf636ae2b67a501d783495b73d59481f07329
+ RNPingPush: ef0ead1586fb6e98d0bfa0b44377f9c56d6f5e16
+ RNPingRecaptcha: f47c662cefe81eb994db5896a395d599de352b90
+ RNPingStorage: b25be825a2d9cfa85e1e640c1b3c52476e39f277
SocketRocket: d4aabe649be1e368d1318fdf28a022d714d65748
Yoga: daa1e4de4b971b977b23bc842aaa3e135324f1f3
diff --git a/PingTestRunner/scenarios/DaVinciScenario.tsx b/PingTestRunner/scenarios/DaVinciScenario.tsx
index 8b48b8b26..39f017a94 100644
--- a/PingTestRunner/scenarios/DaVinciScenario.tsx
+++ b/PingTestRunner/scenarios/DaVinciScenario.tsx
@@ -18,6 +18,12 @@
* davinci-field-{key} → per-collector input
* davinci-field-{key}-option-{value} → option button for single/multi-select
* davinci-field-{key}-image-url / -image-description / -image-hyperlink → IMAGE display-only field (url, alt text, optional hyperlink)
+ * davinci-field-{key}-metadata-payload → METADATA connector payload (pretty JSON)
+ * davinci-field-{key}-metadata-value → current result value, or "Not set"
+ * davinci-field-{key}-metadata-unset → visible only while unset (blocking)
+ * davinci-field-{key}-metadata-set-result → stores a demo success result
+ * davinci-field-{key}-metadata-set-error → stores a demo error envelope
+ * davinci-field-{key}-metadata-clear → clears the stored result
* davinci-flow-{key} → FLOW_BUTTON / FLOW_LINK / ACTION
* davinci-submit-btn → first SUBMIT_BUTTON (or fallback submit)
* davinci-submit-{label} → additional SUBMIT_BUTTON collectors, keyed by label
@@ -39,6 +45,7 @@ import React, { useCallback, useState } from 'react';
import { Button, Switch, Text, TextInput, View } from 'react-native';
import { LaunchArguments } from 'react-native-launch-arguments';
import {
+ buildMetadataResult,
createDaVinciClient,
normalizeCollectors,
} from '@ping-identity/rn-davinci';
@@ -584,6 +591,51 @@ function CollectorField({
return Polling…;
}
+ if (collector.type === 'METADATA') {
+ const metadataCollector = collector as Extract<
+ DaVinciNormalizedCollector,
+ { type: 'METADATA' }
+ >;
+ const isSet = value !== undefined && value !== null;
+ return (
+
+
+ {JSON.stringify(metadataCollector.metadata)}
+
+
+ {isSet ? JSON.stringify(value) : 'Not set'}
+
+ {!isSet ? (
+
+ Result required before resume
+
+ ) : null}
+
+ );
+ }
+
if (collector.type === 'DEVICE_AUTHENTICATION') {
return (
diff --git a/PingTestRunner/scenarios/UseDaVinciScenario.tsx b/PingTestRunner/scenarios/UseDaVinciScenario.tsx
index 8a65c72e9..627091a6e 100644
--- a/PingTestRunner/scenarios/UseDaVinciScenario.tsx
+++ b/PingTestRunner/scenarios/UseDaVinciScenario.tsx
@@ -18,6 +18,12 @@
* use-davinci-error → visible when actions.error !== null
* use-davinci-field-{key} → per-collector field input
* use-davinci-field-{key}-option-{v} → option button for single/multi-select
+ * use-davinci-field-{key}-metadata-payload → METADATA connector payload (JSON)
+ * use-davinci-field-{key}-metadata-value → current result value, or "Not set"
+ * use-davinci-field-{key}-metadata-unset → visible only while unset (blocking)
+ * use-davinci-field-{key}-metadata-set-result → stores a demo success result
+ * use-davinci-field-{key}-metadata-set-error → stores a demo error envelope
+ * use-davinci-field-{key}-metadata-clear → clears the stored result
* use-davinci-flow-{key} → FLOW_BUTTON / FLOW_LINK / ACTION
* use-davinci-submit-btn → calls actions.next(form.input)
* use-davinci-success → visible on SuccessNode
@@ -40,6 +46,7 @@ import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Button, Switch, Text, TextInput, View } from 'react-native';
import { LaunchArguments } from 'react-native-launch-arguments';
import {
+ buildMetadataResult,
createDaVinciClient,
useDaVinci,
useDaVinciForm,
@@ -589,5 +596,49 @@ function HookCollectorInput({
);
}
+ if (collector.kind === 'metadata') {
+ const metadataCollector = collector as {
+ metadata?: Record;
+ };
+ const isSet = value !== undefined && value !== null;
+ return (
+
+
+ {JSON.stringify(metadataCollector.metadata ?? {})}
+
+
+ {isSet ? JSON.stringify(value) : 'Not set'}
+
+ {!isSet ? (
+
+ Result required before resume
+
+ ) : null}
+
+ onValueChange(buildMetadataResult({ status: 'success' }))
+ }
+ />
+
+ onValueChange({
+ error: { code: 'USER_CANCELLED', message: 'User cancelled' },
+ })
+ }
+ />
+ onValueChange(null)}
+ />
+
+ );
+ }
+
return null;
}
diff --git a/packages/davinci/README.md b/packages/davinci/README.md
index 17130e77b..a24d131bc 100644
--- a/packages/davinci/README.md
+++ b/packages/davinci/README.md
@@ -310,13 +310,14 @@ if (errors.length > 0) {
Each normalized collector includes `executionMode` and `requiresUserInput`.
-| `executionMode` | Meaning | `requiresUserInput` default |
-| ---------------------- | ---------------------------------------------------------------------------------------- | --------------------------- |
-| `manual` | Collector value is submitted from form/planned input. | `true` |
-| `immediate` | Activating the collector immediately advances the flow without waiting for other fields. | `false` |
-| `output_only` | Display/label collector, no input value expected. | `false` |
-| `integration_required` | Collector is handled by an external integration package before submit. | `false` |
-| `unsupported` | Collector type is not currently handled by the bridge or any registered integration. | `false` |
+| `executionMode` | Meaning | `requiresUserInput` default |
+| ---------------------- | ------------------------------------------------------------------------------------------------------- | --------------------------- |
+| `manual` | Collector value is submitted from form/planned input. | `true` |
+| `immediate` | Activating the collector immediately advances the flow without waiting for other fields. | `false` |
+| `output_only` | Display/label collector, no input value expected. | `false` |
+| `integration_required` | Collector is handled by an external integration package before submit. | `false` |
+| `metadata` | SDK Integrator connector pause/resume ([METADATA](#davinci-sdk-connector-metadata-metadata-collector)). | `false` |
+| `unsupported` | Collector type is not currently handled by the bridge or any registered integration. | `false` |
#### Flow collector submission
@@ -333,31 +334,32 @@ await form.submitFlow('forgot-password');
The following collector types are supported on Android and iOS:
-| Collector Type | Description | Input Handling |
-| ----------------------- | -------------------------------------------------------------------------------------- | -------------- |
-| `TEXT` | Single-line text input. | Manual input |
-| `PASSWORD` | Masked password input. | Manual input |
-| `PASSWORD_VERIFY` | Password-confirmation variant of `PASSWORD`. | Manual input |
-| `SINGLE_SELECT` | Single-select input. | Manual input |
-| `DROPDOWN` | Single-select dropdown. | Manual input |
-| `RADIO` | Single-select radio group. | Manual input |
-| `MULTI_SELECT` | Multi-select input. | Manual input |
-| `COMBOBOX` | Multi-select combobox. | Manual input |
-| `CHECKBOX` | Multi-select checkbox group. | Manual input |
-| `PHONE_NUMBER` | Phone number input with country code. | Manual input |
-| `DEVICE_REGISTRATION` | Device picker for registration. | Manual input |
-| `DEVICE_AUTHENTICATION` | Device picker for authentication. | Manual input |
-| `SUBMIT_BUTTON` | Triggers form submission immediately. | Immediate |
-| `ACTION` | Action button that advances the flow immediately. | Immediate |
-| `FLOW_BUTTON` | Flow button that advances the flow immediately. | Immediate |
-| `FLOW_LINK` | Flow link that advances the flow immediately. | Immediate |
-| `SINGLE_CHECKBOX` | Single checkbox or toggle (boolean field). | Manual input |
-| `LABEL` | Read-only display content. | Output-only |
-| `READ_ONLY_TEXT` | Read-only text / agreement content. | Output-only |
-| `POLLING` | Async polling collector — see [Polling and QR code flows](#polling-and-qr-code-flows). | Output-only |
-| `QR_CODE` | Display-only QR code — see [Polling and QR code flows](#polling-and-qr-code-flows). | Output-only |
-| `IMAGE` | Display-only image with optional hyperlink. | Output-only |
-| `FIDO2` | FIDO passkey registration or authentication; narrow by `action`. | Integration |
+| Collector Type | Description | Input Handling |
+| ----------------------- | ------------------------------------------------------------------------------------------------------- | --------------- |
+| `TEXT` | Single-line text input. | Manual input |
+| `PASSWORD` | Masked password input. | Manual input |
+| `PASSWORD_VERIFY` | Password-confirmation variant of `PASSWORD`. | Manual input |
+| `SINGLE_SELECT` | Single-select input. | Manual input |
+| `DROPDOWN` | Single-select dropdown. | Manual input |
+| `RADIO` | Single-select radio group. | Manual input |
+| `MULTI_SELECT` | Multi-select input. | Manual input |
+| `COMBOBOX` | Multi-select combobox. | Manual input |
+| `CHECKBOX` | Multi-select checkbox group. | Manual input |
+| `PHONE_NUMBER` | Phone number input with country code. | Manual input |
+| `DEVICE_REGISTRATION` | Device picker for registration. | Manual input |
+| `DEVICE_AUTHENTICATION` | Device picker for authentication. | Manual input |
+| `SUBMIT_BUTTON` | Triggers form submission immediately. | Immediate |
+| `ACTION` | Action button that advances the flow immediately. | Immediate |
+| `FLOW_BUTTON` | Flow button that advances the flow immediately. | Immediate |
+| `FLOW_LINK` | Flow link that advances the flow immediately. | Immediate |
+| `SINGLE_CHECKBOX` | Single checkbox or toggle (boolean field). | Manual input |
+| `LABEL` | Read-only display content. | Output-only |
+| `READ_ONLY_TEXT` | Read-only text / agreement content. | Output-only |
+| `POLLING` | Async polling collector — see [Polling and QR code flows](#polling-and-qr-code-flows). | Output-only |
+| `QR_CODE` | Display-only QR code — see [Polling and QR code flows](#polling-and-qr-code-flows). | Output-only |
+| `IMAGE` | Display-only image with optional hyperlink. | Output-only |
+| `FIDO2` | FIDO passkey registration or authentication; narrow by `action`. | Integration |
+| `METADATA` | SDK Integrator connector pause/resume ([METADATA](#davinci-sdk-connector-metadata-metadata-collector)). | Metadata result |
Integration-dependent collectors are surfaced in node payloads with
`executionMode: 'integration_required'`. Their minimum generic shape is `key`,
@@ -412,6 +414,117 @@ The ceremony must be completed before calling `next`, and the FIDO collector key
must not be passed in `next` input. These DaVinci methods use native ceremony
defaults; no React Native ceremony customization options are exposed.
+### DaVinci SDK Connector metadata (METADATA collector)
+
+An SDK Integrator connector can pause a DaVinci flow by returning a form field
+of type `METADATA` carrying an opaque JSON payload. The bridge surfaces that
+field as a `MetadataCollector` (`type: 'METADATA'`) with the payload on
+`collector.metadata`. The SDK does not validate or introspect the payload —
+your app interprets it and performs the on-device work itself (third-party SDK
+call, risk evaluation, payment, and so on).
+
+Pause/resume contract:
+
+1. The flow pauses. The node arrives with a `MetadataCollector` in
+ `node.collectors` and `executionMode: 'metadata'`.
+2. The app reads `collector.metadata` and performs the on-device work.
+3. The app sets the result as the collector's form value —
+ `form.setValue(collector.key, result)` — and resumes with `next()` as usual.
+
+The value supplied as the form value is exactly what the native bridge applies
+to the collector and what lands in the resume payload (`formData.sdkMetadata`):
+
+- Any JSON object is a success result and is POSTed as-is. Wrap it with
+ `buildMetadataResult`. The form value type only accepts METADATA results
+ built this way, so a mis-shaped value for another collector (for example a
+ phone number missing `countryCode`) stays a compile-time error.
+- An object carrying a well-formed `{ error: { code, message } }` envelope
+ routes the connector's error branch. Build one with `buildMetadataError`:
+
+```ts
+import {
+ buildMetadataError,
+ buildMetadataResult,
+ useDaVinci,
+ useDaVinciForm,
+} from '@ping-identity/rn-davinci';
+
+const { node, next } = useDaVinci(client);
+const form = useDaVinciForm(node);
+
+for (const collector of node?.type === 'ContinueNode' ? node.collectors : []) {
+ if (collector.type === 'METADATA') {
+ // Perform the on-device work the connector payload describes, then
+ // either store a success result or route the connector's error branch.
+ const result = await performOnDeviceWork(collector.metadata);
+ form.setValue(
+ collector.key,
+ result.ok
+ ? buildMetadataResult({ status: 'success' })
+ : buildMetadataError('USER_CANCELLED', 'User dismissed the challenge.'),
+ );
+ }
+}
+
+if (form.canSubmit) {
+ await next(form.input);
+}
+```
+
+There are three distinct outcomes, and none of them fails silently:
+
+- **Success advance** — a result object is included in the `next()`
+ payload and the flow resumes into the connector's success path.
+- **Structured error** — a `buildMetadataError` envelope is POSTed as the
+ collector value; the server-side connector reads it and routes the flow to
+ its client-error branch. This intentionally differs from FIDO2, where
+ collector errors are promise rejections: for METADATA the error envelope IS
+ the collector value. The envelope carries exactly `code` and `message`.
+ Extra keys inside `error` pass validation but are not forwarded, because both
+ native bridges rebuild the envelope through `setError(code, message)`, so put
+ any additional context in `message`.
+- **Unset result** — submission is blocked with a
+ `METADATA_RESULT_REQUIRED` issue in `form.issues` and `canSubmit: false`
+ until a result is set. Gating is result-set-based: the native `validate()`
+ reports `REQUIRED` until a result is set and ignores the server `required`
+ flag.
+
+A value that is not an object (or is an array, or carries a malformed `error`
+envelope) is blocked with `METADATA_RESULT_MALFORMED` naming
+the offending value type, instead of being silently POSTed. A top-level `error`
+key is reserved for the error envelope, so a success result cannot use it for
+other data.
+
+Platform notes:
+
+- **Label/required**: Android's native collector exposes `label` and `required`
+ natively; iOS's does not, so the iOS bridge synthesizes them from the raw
+ form field JSON (defaults `''` and `false`). The serialized bridge shape is
+ identical across platforms.
+- **Empty result objects** are forwarded unchanged on both platforms, exactly as
+ the native SDKs accept them, but native 2.2.0 handles them differently. iOS
+ posts `formData.sdkMetadata: {}` and the server accepts it. Android omits an
+ empty result from the resume request, and the server replies with an
+ `INVALID_RESUME_PAYLOAD` message instead of resuming. On Android, return a
+ non-empty object until the native SDK is fixed.
+- **Malformed server payloads**: Android's native `MetadataCollector` init
+ throws on a non-object `payload`, which aborts node construction — the flow
+ surfaces a `FailureNode` carrying the `IllegalArgumentException` as its
+ cause (never an `unsupportedFields` entry) — while iOS defaults to an empty
+ `metadata` object. The JS shape is unaffected either way — narrow on
+ `type === 'METADATA'` and treat `metadata` as opaque.
+
+### Native SDK version requirement for METADATA
+
+The `MetadataCollector` native type ships with PingDavinci 2.2.0, and this
+package pins native 2.2.0 on both platforms. The bridge references
+`MetadataCollector` directly, so overriding the native dependency to an older
+version is not supported. A `METADATA` field that the native SDK does not
+instantiate as a `MetadataCollector` is not special-cased: it surfaces in
+`ContinueNode.unsupportedFields` and classifies as `executionMode:
+'unsupported'`, like any other unrecognized type (see
+[Unsupported fields](#unsupported-fields)). There is no JavaScript shim.
+
### Unsupported fields
When the native SDK cannot instantiate a collector from the server payload, the bridge surfaces it in `ContinueNode.unsupportedFields`:
diff --git a/packages/davinci/android/src/main/java/com/pingidentity/rndavinci/collector/DaVinciCollectorValueApplier.kt b/packages/davinci/android/src/main/java/com/pingidentity/rndavinci/collector/DaVinciCollectorValueApplier.kt
index eea5cffe0..aaf99e009 100644
--- a/packages/davinci/android/src/main/java/com/pingidentity/rndavinci/collector/DaVinciCollectorValueApplier.kt
+++ b/packages/davinci/android/src/main/java/com/pingidentity/rndavinci/collector/DaVinciCollectorValueApplier.kt
@@ -7,6 +7,7 @@
package com.pingidentity.rndavinci.collector
+import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.bridge.ReadableType
import com.pingidentity.davinci.collector.BooleanCollector
@@ -14,10 +15,17 @@ import com.pingidentity.davinci.collector.Device
import com.pingidentity.davinci.collector.DeviceAuthenticationCollector
import com.pingidentity.davinci.collector.DeviceRegistrationCollector
import com.pingidentity.davinci.collector.FlowCollector
+import com.pingidentity.davinci.collector.MetadataCollector
import com.pingidentity.davinci.collector.MultiSelectCollector
import com.pingidentity.davinci.collector.PhoneNumberCollector
import com.pingidentity.davinci.plugin.Collector
import com.pingidentity.orchestrate.ContinueNode
+import com.pingidentity.rncore.utils.JsonBridgeMapper
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
/**
* Applies collector value mutations from JS payloads to active DaVinci collectors.
@@ -133,6 +141,9 @@ internal object DaVinciCollectorValueApplier {
is BooleanCollector -> {
collector.value = asBoolean(value, key)
}
+ is MetadataCollector -> {
+ applyMetadataValue(collector, key, value)
+ }
else -> {
// All remaining collectors (TextCollector, PasswordCollector, SingleValueCollector,
// SubmitCollector, FlowCollector) extend SingleValueCollector which has setValue(String).
@@ -145,6 +156,136 @@ internal object DaVinciCollectorValueApplier {
}
}
+ /**
+ * Applies a JS-supplied result value to a [MetadataCollector].
+ *
+ * Semantics, mirroring the iOS applier:
+ * - `null` (JS null/undefined) → no-op: the collector's `validate()` keeps returning
+ * `Required`, so an unset result blocks the flow instead of silently clearing a
+ * previously set result.
+ * - Map containing an `error` key → strict envelope validation (a map with a non-empty
+ * string `code` and a string `message`) → [MetadataCollector.setError]. A malformed
+ * envelope throws rather than silently POSTing as a success result.
+ * - Any other map, including an empty one → [MetadataCollector.setResult] (the success
+ * path), forwarded unchanged.
+ * - Non-map values → throw: the resume body must be a JSON object.
+ *
+ * @remarks
+ * The error envelope is the collector's value, which the server-side connector routes
+ * on, so a well-formed envelope resolves the flow instead of rejecting the bridge call.
+ * Messages for rejected values name only the offending types, never the values, so
+ * result content does not reach logs or crash reports.
+ *
+ * @param collector Target metadata collector.
+ * @param key Collector key (for error messages).
+ * @param value Value from JS.
+ * @throws IllegalArgumentException when the value cannot be applied.
+ */
+ private fun applyMetadataValue(collector: MetadataCollector, key: String, value: Any?) {
+ when (value) {
+ null -> return
+ is Map<*, *> -> {
+ if (value.containsKey("error")) {
+ // ReadableNativeMap.toHashMap() converts nested maps recursively, but
+ // the JavaOnlyMap unit-test double copies shallowly, so the nested
+ // envelope can arrive as either a plain Map or a raw ReadableMap —
+ // accept both.
+ val rawEnvelope = value["error"]
+ val envelope: Map<*, *>? = when (rawEnvelope) {
+ is Map<*, *> -> rawEnvelope
+ is ReadableMap -> rawEnvelope.toHashMap()
+ else -> null
+ }
+ val code = envelope?.get("code")
+ val message = envelope?.get("message")
+ if (envelope == null || code !is String || code.isEmpty() || message !is String) {
+ throw IllegalArgumentException(
+ "MetadataCollector key='$key': malformed error envelope, expected " +
+ "{ error: { code: non-empty string, message: string } }, got " +
+ "error: ${typeName(rawEnvelope)}, code: ${typeName(code)}, " +
+ "message: ${typeName(message)}"
+ )
+ }
+ collector.setError(code, message)
+ return
+ }
+ // TODO-PARITY (SDKS-5545): in native 2.2.0 Collectors.asJson() omits an empty
+ // MetadataCollector result from the resume request, while iOS posts it as
+ // `{}`. The value is forwarded unchanged; the server answers an omitted
+ // result with INVALID_RESUME_PAYLOAD. Remove this note once native is fixed.
+ collector.setResult(toJsonObject(value))
+ }
+ else -> throw IllegalArgumentException(
+ "MetadataCollector key='$key' expects a JSON object result, got: " +
+ typeName(value)
+ )
+ }
+ }
+
+ /**
+ * Names the runtime type of a value for error messages, so rejected values are
+ * described without being echoed.
+ *
+ * @param value Any bridge value.
+ * @return The simple class name, or `"null"` when the value is null.
+ */
+ private fun typeName(value: Any?): String =
+ value?.let { it.javaClass.simpleName } ?: "null"
+
+ /**
+ * Recursively converts a bridge map into a [JsonObject] for
+ * [MetadataCollector.setResult].
+ *
+ * @param value Bridge map (as produced by `readDynamicValue` for object values).
+ * @return The equivalent JSON object.
+ * @throws IllegalArgumentException when the map contains a non-string key, matching the
+ * iOS applier rather than silently dropping the entry.
+ */
+ private fun toJsonObject(value: Map<*, *>): JsonObject = JsonObject(
+ value.entries.associate { (rawKey, rawValue) ->
+ val key = rawKey as? String
+ ?: throw IllegalArgumentException(
+ "MetadataCollector result has a non-string key of type ${typeName(rawKey)}"
+ )
+ key to toJsonElement(rawValue)
+ }
+ )
+
+ /**
+ * Recursively converts a bridge value tree into a [JsonElement].
+ *
+ * The top-level value from `readDynamicValue` is a plain `Map`
+ * (`ReadableMap.toHashMap()`). In production `ReadableNativeMap.toHashMap()`
+ * converts nested maps and arrays recursively, but the `JavaOnlyMap` unit-test
+ * double copies shallowly, so nested entries can still be raw bridge objects
+ * (`ReadableMap`/`ReadableArray`) there. Both shapes are handled: nested
+ * `ReadableMap`/`ReadableArray` instances delegate to rn-core's
+ * [JsonBridgeMapper.decodeReadableMap]/[JsonBridgeMapper.decodeReadableArray],
+ * which recurse fully.
+ *
+ * `null` entries become [JsonNull] — `JsonObject` supports explicit nulls, so a JS
+ * `{ "answer": null }` result round-trips to the server faithfully. Numbers are
+ * normalized with [normalizeBridgeNumber] (integer-valued doubles collapse to
+ * `Long`, so JS `87` serializes as `87`, not `87.0`) — the same iOS-parity rule
+ * `readDynamicValue` applies to top-level numbers. Non-JSON scalar types (which
+ * the RN bridge does not produce) fall back to their string form, mirroring
+ * `JsonBridgeMapper`'s scalar handling.
+ *
+ * @param value Bridge value (`Map`/`ReadableMap`/`List`/`ReadableArray`/primitive).
+ * @return The equivalent JSON element.
+ */
+ private fun toJsonElement(value: Any?): JsonElement = when (value) {
+ null -> JsonNull
+ is Map<*, *> -> toJsonObject(value)
+ is ReadableMap -> JsonBridgeMapper.decodeReadableMap(value)
+ is ReadableArray -> JsonBridgeMapper.decodeReadableArray(value)
+ is List<*> -> JsonArray(value.map { toJsonElement(it) })
+ is String -> JsonPrimitive(value)
+ is Boolean -> JsonPrimitive(value)
+ is Number -> JsonPrimitive(normalizeBridgeNumber(value.toDouble()))
+ else -> JsonPrimitive(value.toString())
+ }
+
/**
* Reads one dynamic value from a bridge map using runtime type inspection.
*/
diff --git a/packages/davinci/android/src/main/java/com/pingidentity/rndavinci/mapper/DaVinciNodeMapper.kt b/packages/davinci/android/src/main/java/com/pingidentity/rndavinci/mapper/DaVinciNodeMapper.kt
index 04748ad5d..8c19e1c19 100644
--- a/packages/davinci/android/src/main/java/com/pingidentity/rndavinci/mapper/DaVinciNodeMapper.kt
+++ b/packages/davinci/android/src/main/java/com/pingidentity/rndavinci/mapper/DaVinciNodeMapper.kt
@@ -20,6 +20,7 @@ import com.pingidentity.davinci.collector.ImageCollector
import com.pingidentity.davinci.collector.InvalidLength
import com.pingidentity.davinci.collector.LabelCollector
import com.pingidentity.davinci.collector.MaxRepeat
+import com.pingidentity.davinci.collector.MetadataCollector
import com.pingidentity.davinci.collector.MinCharacters
import com.pingidentity.davinci.collector.MultiSelectCollector
import com.pingidentity.davinci.collector.PasswordCollector
@@ -265,6 +266,7 @@ internal object DaVinciNodeMapper {
is ReadOnlyTextCollector -> mapReadOnlyTextCollector(collector)
is PollingCollector -> mapPollingCollector(collector, logger)
is ImageCollector -> mapImageCollector(collector, node, logger)
+ is MetadataCollector -> mapMetadataCollector(collector)
is QRCodeCollector -> mapQRCodeCollector(collector)
else -> {
// Try registered plugin serializers before generic server-type fallback.
@@ -575,6 +577,37 @@ internal object DaVinciNodeMapper {
return map
}
+ /**
+ * Serialize a [MetadataCollector] to a payload map.
+ *
+ * The collector is a resume-capable pause point: JS reads [MetadataCollector.metadata]
+ * (the server's opaque `payload`), performs on-device work, and POSTs a result back
+ * through `next()` (applied by [com.pingidentity.rndavinci.collector.DaVinciCollectorValueApplier]).
+ *
+ * @remarks
+ * Label/required parity delta: Android's native `MetadataCollector` extends
+ * `FieldCollector`, so `label`/`required` come from the native collector
+ * (parsed by `FieldCollector.init`). iOS's native collector is an `AnyFieldCollector`
+ * with no native `label`/`required` — the iOS bridge synthesizes both from the raw
+ * form field JSON (defaults `""`/`false`). The serialized bridge shape is identical
+ * across platforms; only the value source differs. Actual submission gating is
+ * result-set-based (native `validate()` returns `Required` until `setResult`/`setError`
+ * is called), independent of the server `required` flag.
+ *
+ * The server `payload` is serialized as `metadata` as-is — no transformation. A
+ * non-object `payload` never reaches this mapper: native `init` throws
+ * (`jsonObject` coercion) before the collector is constructed, so the node
+ * construction fails upstream.
+ *
+ * @param collector Native metadata collector.
+ * @return Serialized metadata collector map.
+ */
+ private fun mapMetadataCollector(collector: MetadataCollector): Map {
+ val map = baseCollectorMap(collector)
+ map["metadata"] = JsonBridgeMapper.encodeJsonElement(collector.metadata)
+ return map
+ }
+
private fun mapSingleSelectCollector(collector: SingleSelectCollector): Map {
val map = baseCollectorMap(collector)
map["value"] = collector.value ?: ""
diff --git a/packages/davinci/android/src/test/java/com/pingidentity/rndavinci/RNPingDavinciCommonTest.kt b/packages/davinci/android/src/test/java/com/pingidentity/rndavinci/RNPingDavinciCommonTest.kt
index d5dbb73ab..7b50afbbe 100644
--- a/packages/davinci/android/src/test/java/com/pingidentity/rndavinci/RNPingDavinciCommonTest.kt
+++ b/packages/davinci/android/src/test/java/com/pingidentity/rndavinci/RNPingDavinciCommonTest.kt
@@ -16,6 +16,7 @@ import com.facebook.react.bridge.WritableArray
import com.facebook.react.bridge.WritableMap
import com.facebook.react.modules.core.DeviceEventManagerModule
import com.pingidentity.davinci.collector.BooleanCollector
+import com.pingidentity.davinci.collector.MetadataCollector
import com.pingidentity.davinci.collector.PasswordCollector
import com.pingidentity.davinci.collector.PollingCollector
import com.pingidentity.davinci.collector.SubmitCollector
@@ -367,6 +368,95 @@ class RNPingDavinciCommonTest {
assertEquals(0, (captureResolve(promise) as ReadableArray).size())
}
+ // ---- validate — MetadataCollector ----
+
+ @Test
+ fun validate_metadataCollectorUnsetResultResolvesRequiredError() {
+ // Unset (null) application is a no-op, so the native validate() still
+ // reports Required — the flow blocks until the app sets a result.
+ val collector = MetadataCollector().apply {
+ init(buildJsonObject {
+ put("key", "sdkMetadata")
+ put("type", "METADATA")
+ put("payload", buildJsonObject { put("sdk", "PROTECT") })
+ })
+ }
+ val davinciId = registerDaVinciHandle(Workflow(WorkflowConfig()))
+ setContinueNode(davinciId, DummyContinueNode(actions = listOf(collector)))
+ val promise = TestPromise()
+
+ RNPingDavinciCommon.validate(
+ davinciId,
+ "sdkMetadata",
+ collectorInputMap("sdkMetadata") { putNull("value") },
+ promise
+ )
+
+ val errors = captureResolve(promise) as ReadableArray
+ assertEquals(1, errors.size())
+ assertEquals("REQUIRED", errors.getMap(0)?.getString("code"))
+ }
+
+ @Test
+ fun validate_metadataCollectorSetResultResolvesEmptyArray() {
+ val collector = MetadataCollector().apply {
+ init(buildJsonObject {
+ put("key", "sdkMetadata")
+ put("type", "METADATA")
+ put("payload", buildJsonObject { put("sdk", "PROTECT") })
+ })
+ }
+ val davinciId = registerDaVinciHandle(Workflow(WorkflowConfig()))
+ setContinueNode(davinciId, DummyContinueNode(actions = listOf(collector)))
+ val promise = TestPromise()
+
+ RNPingDavinciCommon.validate(
+ davinciId,
+ "sdkMetadata",
+ collectorInputMap("sdkMetadata") {
+ putMap("value", JavaOnlyMap().apply {
+ putString("status", "completed")
+ putInt("score", 87)
+ })
+ },
+ promise
+ )
+
+ assertEquals(0, (captureResolve(promise) as ReadableArray).size())
+ }
+
+ @Test
+ fun validate_metadataCollectorErrorEnvelopeResolvesEmptyArray() {
+ // The well-formed error envelope is the collector's value — it satisfies
+ // validate() exactly like a success result; the connector routes on it.
+ val collector = MetadataCollector().apply {
+ init(buildJsonObject {
+ put("key", "sdkMetadata")
+ put("type", "METADATA")
+ put("payload", buildJsonObject { put("sdk", "PROTECT") })
+ })
+ }
+ val davinciId = registerDaVinciHandle(Workflow(WorkflowConfig()))
+ setContinueNode(davinciId, DummyContinueNode(actions = listOf(collector)))
+ val promise = TestPromise()
+
+ RNPingDavinciCommon.validate(
+ davinciId,
+ "sdkMetadata",
+ collectorInputMap("sdkMetadata") {
+ putMap("value", JavaOnlyMap().apply {
+ putMap("error", JavaOnlyMap().apply {
+ putString("code", "USER_CANCELLED")
+ putString("message", "User abandoned the flow")
+ })
+ })
+ },
+ promise
+ )
+
+ assertEquals(0, (captureResolve(promise) as ReadableArray).size())
+ }
+
@Test
fun validate_rejectsStateErrorWhenNoContinueNode() {
val promise = TestPromise()
diff --git a/packages/davinci/android/src/test/java/com/pingidentity/rndavinci/collector/DaVinciCollectorValueApplierTest.kt b/packages/davinci/android/src/test/java/com/pingidentity/rndavinci/collector/DaVinciCollectorValueApplierTest.kt
index 4dad9bf13..e7606a2dd 100644
--- a/packages/davinci/android/src/test/java/com/pingidentity/rndavinci/collector/DaVinciCollectorValueApplierTest.kt
+++ b/packages/davinci/android/src/test/java/com/pingidentity/rndavinci/collector/DaVinciCollectorValueApplierTest.kt
@@ -14,6 +14,7 @@ import com.pingidentity.davinci.collector.DeviceAuthenticationCollector
import com.pingidentity.davinci.collector.DeviceRegistrationCollector
import com.pingidentity.davinci.collector.FlowCollector
import com.pingidentity.davinci.collector.ImageCollector
+import com.pingidentity.davinci.collector.MetadataCollector
import com.pingidentity.davinci.collector.MultiSelectCollector
import com.pingidentity.davinci.collector.PasswordCollector
import com.pingidentity.davinci.collector.PhoneNumberCollector
@@ -26,14 +27,21 @@ import com.pingidentity.orchestrate.FlowContext
import com.pingidentity.orchestrate.SharedContext
import com.pingidentity.orchestrate.Workflow
import com.pingidentity.orchestrate.WorkflowConfig
+import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonArray
+import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.int
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonArray
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -534,4 +542,308 @@ class DaVinciCollectorValueApplierTest {
assertTrue(error.message?.contains("is not supported by the bridge") == true)
}
}
+
+ // ---- MetadataCollector (success / error / unset) ----
+
+ private fun metadataCollector(): MetadataCollector = MetadataCollector().apply {
+ init(buildJsonObject {
+ put("key", "sdkMetadata")
+ put("type", "METADATA")
+ put("payload", buildJsonObject { put("sdk", "PROTECT") })
+ })
+ }
+
+ @Test
+ fun applyMetadataCollectorSetsResult() {
+ // Success object → native setResult; payload() is the JsonObject the resume
+ // envelope POSTs as formData.sdkMetadata.
+ val collector = metadataCollector()
+ val node = nodeWith(collector)
+
+ DaVinciCollectorValueApplier.apply(
+ node,
+ inputWithCollectors(
+ "sdkMetadata" to JavaOnlyMap().apply {
+ putString("status", "completed")
+ putInt("score", 87)
+ }
+ )
+ )
+
+ val payload = collector.payload()
+ assertNotNull(payload)
+ assertEquals("completed", payload?.get("status")?.jsonPrimitive?.content)
+ // putInt stores a Double in JavaOnlyMap; the applier's bridge-number
+ // normalization collapses integer-valued doubles back to Long (JSON "87").
+ assertEquals(87, payload?.get("score")?.jsonPrimitive?.int)
+ assertTrue(payload?.get("score")?.jsonPrimitive?.content == "87")
+ assertTrue(collector.validate().isEmpty())
+ }
+
+ @Test
+ fun applyMetadataCollectorErrorEnvelopeSetsStructuredError() {
+ // Well-formed { error: { code, message } } → native setError; the resulting
+ // payload() is the envelope the connector routes on.
+ val collector = metadataCollector()
+ val node = nodeWith(collector)
+
+ DaVinciCollectorValueApplier.apply(
+ node,
+ inputWithCollectors(
+ "sdkMetadata" to JavaOnlyMap().apply {
+ putMap("error", JavaOnlyMap().apply {
+ putString("code", "USER_CANCELLED")
+ putString("message", "User abandoned the flow")
+ })
+ }
+ )
+ )
+
+ val payload = collector.payload()
+ assertNotNull(payload)
+ val error = payload?.get("error")?.jsonObject
+ assertEquals("USER_CANCELLED", error?.get("code")?.jsonPrimitive?.content)
+ assertEquals("User abandoned the flow", error?.get("message")?.jsonPrimitive?.content)
+ assertTrue(collector.validate().isEmpty())
+ }
+
+ @Test
+ fun applyMetadataCollectorPlainMapErrorEnvelopeSetsStructuredError() {
+ // ReadableNativeMap.toHashMap() converts nested maps recursively, so in
+ // production the envelope arrives as a plain Map rather than a ReadableMap.
+ // JavaOnlyMap.of stores the raw value to reproduce that shape.
+ val collector = metadataCollector()
+ val node = nodeWith(collector)
+
+ DaVinciCollectorValueApplier.apply(
+ node,
+ inputWithCollectors(
+ "sdkMetadata" to JavaOnlyMap.of(
+ "error",
+ mapOf("code" to "USER_CANCELLED", "message" to "User abandoned the flow")
+ )
+ )
+ )
+
+ val error = collector.payload()?.get("error")?.jsonObject
+ assertEquals("USER_CANCELLED", error?.get("code")?.jsonPrimitive?.content)
+ assertEquals("User abandoned the flow", error?.get("message")?.jsonPrimitive?.content)
+ assertTrue(collector.validate().isEmpty())
+ }
+
+ @Test
+ fun applyMetadataCollectorRecursivelyConvertedResultRoundTrips() {
+ // Same production shape as above for success results: nested values are already
+ // plain Map/List/Boolean/Number instances by the time the converter runs.
+ val collector = metadataCollector()
+ val node = nodeWith(collector)
+
+ DaVinciCollectorValueApplier.apply(
+ node,
+ inputWithCollectors(
+ "sdkMetadata" to JavaOnlyMap.of(
+ "flag", true,
+ "score", 87.0,
+ "tags", listOf("device", 7.0, null),
+ "risk", mapOf("level" to "LOW"),
+ "unit", 'x'
+ )
+ )
+ )
+
+ val payload = collector.payload()
+ assertEquals(true, payload?.get("flag")?.jsonPrimitive?.boolean)
+ // Integer-valued doubles serialize as integers (87, not 87.0).
+ assertEquals("87", payload?.get("score")?.jsonPrimitive?.content)
+ val tags = payload?.get("tags")?.jsonArray
+ assertEquals("device", tags?.get(0)?.jsonPrimitive?.content)
+ assertEquals("7", tags?.get(1)?.jsonPrimitive?.content)
+ assertTrue(tags?.get(2) is JsonNull)
+ assertEquals("LOW", payload?.get("risk")?.jsonObject?.get("level")?.jsonPrimitive?.content)
+ // A non-JSON scalar the bridge does not produce falls back to its string form.
+ assertEquals("x", payload?.get("unit")?.jsonPrimitive?.content)
+ }
+
+ @Test
+ fun applyMetadataCollectorNonStringKeyMessageNamesTypeOnly() {
+ val collector = metadataCollector()
+ val node = nodeWith(collector)
+
+ try {
+ DaVinciCollectorValueApplier.apply(
+ node,
+ inputWithCollectors(
+ "sdkMetadata" to JavaOnlyMap.of("nested", mapOf(1 to "super-secret-token"))
+ )
+ )
+ throw AssertionError("expected IllegalArgumentException")
+ } catch (error: IllegalArgumentException) {
+ val message = error.message.orEmpty()
+ assertTrue(message.contains("non-string key of type Integer"))
+ assertFalse(message.contains("super-secret-token"))
+ }
+ assertNull(collector.payload())
+ }
+
+ @Test
+ fun applyMetadataCollectorNullValueIsNoOp() {
+ // null → no-op: an unset result stays unset (validate() keeps Required), and a
+ // previously set result is never cleared.
+ val collector = metadataCollector()
+ val node = nodeWith(collector)
+
+ DaVinciCollectorValueApplier.apply(node, inputWithCollectors("sdkMetadata" to null))
+
+ assertNull(collector.payload())
+ assertTrue(collector.validate().isNotEmpty())
+
+ // A second null application must not clear an already-set result either.
+ collector.setResult(buildJsonObject { put("status", "completed") })
+ DaVinciCollectorValueApplier.apply(node, inputWithCollectors("sdkMetadata" to null))
+ assertEquals("completed", collector.payload()?.get("status")?.jsonPrimitive?.content)
+ }
+
+ @Test
+ fun applyMetadataCollectorEmptyMapSetsEmptyResult() {
+ // An empty object is forwarded to native setResult unchanged: the collector is
+ // considered ready (validate() passes) and payload() is the empty object.
+ val collector = metadataCollector()
+ val node = nodeWith(collector)
+
+ DaVinciCollectorValueApplier.apply(
+ node,
+ inputWithCollectors("sdkMetadata" to JavaOnlyMap())
+ )
+
+ assertNotNull(collector.payload())
+ assertEquals(true, collector.payload()?.isEmpty())
+ assertTrue(collector.validate().isEmpty())
+ }
+
+ @Test
+ fun applyMetadataCollectorMalformedErrorEnvelopeThrows() {
+ // An 'error' key that isn't a well-formed {code, message} envelope must
+ // not silently POST as a success result.
+ val collector = metadataCollector()
+ val node = nodeWith(collector)
+
+ try {
+ DaVinciCollectorValueApplier.apply(
+ node,
+ inputWithCollectors(
+ "sdkMetadata" to JavaOnlyMap().apply {
+ putMap("error", JavaOnlyMap().apply { putInt("code", 42) })
+ }
+ )
+ )
+ throw AssertionError("expected IllegalArgumentException")
+ } catch (error: IllegalArgumentException) {
+ assertTrue(error.message?.contains("malformed error envelope") == true)
+ assertNull(collector.payload())
+ }
+ }
+
+ @Test
+ fun applyMetadataCollectorMalformedErrorEnvelopeMessageDoesNotEchoValues() {
+ // Rejected values are described by type only, so result content never reaches
+ // logs or crash reports through the bridge rejection message.
+ val collector = metadataCollector()
+ val node = nodeWith(collector)
+
+ val malformedEnvelopes = listOf(
+ // 'error' is not an object.
+ JavaOnlyMap().apply { putString("error", "super-secret-token") },
+ // 'code' is not a string.
+ JavaOnlyMap().apply {
+ putMap("error", JavaOnlyMap().apply {
+ putInt("code", 42)
+ putString("message", "super-secret-token")
+ })
+ },
+ // 'message' is not a string.
+ JavaOnlyMap().apply {
+ putMap("error", JavaOnlyMap().apply {
+ putString("code", "super-secret-token")
+ putBoolean("message", true)
+ })
+ },
+ // 'code' is an empty string.
+ JavaOnlyMap().apply {
+ putMap("error", JavaOnlyMap().apply {
+ putString("code", "")
+ putString("message", "super-secret-token")
+ })
+ },
+ // Neither 'code' nor 'message' is present.
+ JavaOnlyMap().apply { putMap("error", JavaOnlyMap()) }
+ )
+
+ for (malformed in malformedEnvelopes) {
+ try {
+ DaVinciCollectorValueApplier.apply(
+ node,
+ inputWithCollectors("sdkMetadata" to malformed)
+ )
+ throw AssertionError("expected IllegalArgumentException")
+ } catch (error: IllegalArgumentException) {
+ val message = error.message.orEmpty()
+ assertTrue(message.contains("malformed error envelope"))
+ assertFalse(message.contains("super-secret-token"))
+ }
+ }
+ assertNull(collector.payload())
+ }
+
+ @Test
+ fun applyMetadataCollectorNonMapValueThrows() {
+ val collector = metadataCollector()
+ val node = nodeWith(collector)
+
+ for (badValue in listOf("not-an-object", 7, true, listOf("a", "b"))) {
+ try {
+ DaVinciCollectorValueApplier.apply(
+ node,
+ inputWithCollectors("sdkMetadata" to badValue)
+ )
+ throw AssertionError("expected IllegalArgumentException for value: $badValue")
+ } catch (error: IllegalArgumentException) {
+ assertTrue(error.message?.contains("expects a JSON object result") == true)
+ }
+ assertNull(collector.payload())
+ }
+ }
+
+ @Test
+ fun applyMetadataCollectorNestedResultRoundTrips() {
+ // Nested objects/arrays and explicit nulls in a success result survive the
+ // bridge → collector path (JsonObject supports JsonNull entries).
+ val collector = metadataCollector()
+ val node = nodeWith(collector)
+
+ DaVinciCollectorValueApplier.apply(
+ node,
+ inputWithCollectors(
+ "sdkMetadata" to JavaOnlyMap().apply {
+ putMap("risk", JavaOnlyMap().apply {
+ putInt("score", 12)
+ putString("level", "LOW")
+ })
+ putArray("signals", JavaOnlyArray().apply {
+ pushString("device")
+ pushString("location")
+ })
+ putNull("answer")
+ }
+ )
+ )
+
+ val payload = collector.payload()
+ val risk = payload?.get("risk")?.jsonObject
+ assertEquals(12, risk?.get("score")?.jsonPrimitive?.int)
+ assertEquals("LOW", risk?.get("level")?.jsonPrimitive?.content)
+ val signals = payload?.get("signals")?.jsonArray
+ assertEquals(2, signals?.size)
+ assertEquals("device", signals?.get(0)?.jsonPrimitive?.content)
+ assertTrue(payload?.get("answer") is JsonNull)
+ }
}
diff --git a/packages/davinci/android/src/test/java/com/pingidentity/rndavinci/mapper/DaVinciNodeMapperTest.kt b/packages/davinci/android/src/test/java/com/pingidentity/rndavinci/mapper/DaVinciNodeMapperTest.kt
index 8bd1eb7b4..8c2b0e1e9 100644
--- a/packages/davinci/android/src/test/java/com/pingidentity/rndavinci/mapper/DaVinciNodeMapperTest.kt
+++ b/packages/davinci/android/src/test/java/com/pingidentity/rndavinci/mapper/DaVinciNodeMapperTest.kt
@@ -15,6 +15,7 @@ import com.pingidentity.davinci.collector.ImageCollector
import com.pingidentity.davinci.collector.InvalidLength
import com.pingidentity.davinci.collector.LabelCollector
import com.pingidentity.davinci.collector.MaxRepeat
+import com.pingidentity.davinci.collector.MetadataCollector
import com.pingidentity.davinci.collector.MinCharacters
import com.pingidentity.davinci.collector.MultiSelectCollector
import com.pingidentity.davinci.collector.PasswordCollector
@@ -43,9 +44,11 @@ import com.pingidentity.orchestrate.Workflow
import com.pingidentity.orchestrate.WorkflowConfig
import com.pingidentity.rncore.CoreRuntime
import java.util.UUID
+import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
+import kotlinx.serialization.json.putJsonArray
import kotlinx.serialization.json.JsonObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@@ -1527,4 +1530,161 @@ class DaVinciNodeMapperTest {
assertFalse(result.containsKey("unsupportedFields"))
}
+
+ // ---- MetadataCollector serialization ----
+
+ private fun metadataNodeInput() = buildJsonObject {
+ put("form", buildJsonObject {
+ put("components", buildJsonObject {
+ put("fields", buildJsonArray {
+ add(buildJsonObject {
+ put("key", "sdkMetadata")
+ put("type", "METADATA")
+ put("label", "SDK Metadata")
+ put("required", true)
+ put("payload", buildJsonObject {
+ put("sdk", "PROTECT")
+ put("action", "INITIALIZE")
+ })
+ })
+ })
+ })
+ })
+ }
+
+ @Test
+ fun mapMetadataCollectorEmitsAllFields() {
+ val collector = MetadataCollector().apply {
+ init(buildJsonObject {
+ put("key", "sdkMetadata")
+ put("type", "METADATA")
+ put("label", "SDK Metadata")
+ put("required", true)
+ put("payload", buildJsonObject {
+ put("sdk", "PROTECT")
+ put("action", "INITIALIZE")
+ })
+ })
+ }
+ val node = makeNode(collector)
+
+ val result = DaVinciNodeMapper.mapNodePayload(node)
+ val c = result.asList("collectors")!![0]
+
+ assertEquals("METADATA", c["type"])
+ assertEquals("sdkMetadata", c["key"])
+ assertEquals("SDK Metadata", c["label"])
+ assertEquals(true, c["required"])
+ val metadata = c["metadata"] as? Map<*, *>
+ assertEquals("PROTECT", metadata?.get("sdk"))
+ assertEquals("INITIALIZE", metadata?.get("action"))
+ }
+
+ @Test
+ fun mapMetadataCollectorExposesNativeLabelAndRequired() {
+ // Android's native MetadataCollector extends FieldCollector, so
+ // label/required come from the native collector. iOS synthesizes them from
+ // the raw form field JSON (AnyFieldCollector has no native accessors); the
+ // serialized bridge shape is identical across platforms.
+ val collector = MetadataCollector().apply {
+ init(buildJsonObject {
+ put("key", "sdkMetadata")
+ put("type", "METADATA")
+ put("label", "SDK Metadata")
+ put("required", true)
+ put("payload", buildJsonObject { put("sdk", "PROTECT") })
+ })
+ }
+ val node = makeNode(metadataNodeInput(), collector)
+
+ val result = DaVinciNodeMapper.mapNodePayload(node)
+ val c = result.asList("collectors")!![0]
+
+ assertEquals("SDK Metadata", c["label"])
+ assertEquals(true, c["required"])
+ assertNotNull(c["raw"])
+ assertFalse(result.containsKey("unsupportedFields"))
+ }
+
+ @Test
+ fun mapMetadataCollectorDefaultsLabelAndRequiredWhenAbsent() {
+ val collector = MetadataCollector().apply {
+ init(buildJsonObject {
+ put("key", "sdkMetadata")
+ put("type", "METADATA")
+ })
+ }
+ val node = makeNode(collector)
+
+ val result = DaVinciNodeMapper.mapNodePayload(node)
+ val c = result.asList("collectors")!![0]
+
+ assertEquals("", c["label"])
+ assertEquals(false, c["required"])
+ }
+
+ @Test
+ fun mapMetadataCollectorEmitsEmptyMetadataWhenPayloadAbsent() {
+ val collector = MetadataCollector().apply {
+ init(buildJsonObject {
+ put("key", "sdkMetadata")
+ put("type", "METADATA")
+ })
+ }
+ val node = makeNode(collector)
+
+ val result = DaVinciNodeMapper.mapNodePayload(node)
+ val c = result.asList("collectors")!![0]
+
+ val metadata = c["metadata"] as? Map<*, *>
+ assertNotNull(metadata)
+ assertTrue(metadata?.isEmpty() == true)
+ }
+
+ @Test
+ fun mapMetadataCollectorMetadataIncludesNestedStructures() {
+ val collector = MetadataCollector().apply {
+ init(buildJsonObject {
+ put("key", "sdkMetadata")
+ put("type", "METADATA")
+ put("payload", buildJsonObject {
+ put("sdk", "PROTECT")
+ put("nested", buildJsonObject { put("a", 1) })
+ putJsonArray("signals") {
+ add("device")
+ add("location")
+ }
+ })
+ })
+ }
+ val node = makeNode(collector)
+
+ val result = DaVinciNodeMapper.mapNodePayload(node)
+ val c = result.asList("collectors")!![0]
+ val metadata = c["metadata"] as? Map<*, *>
+
+ assertEquals("PROTECT", metadata?.get("sdk"))
+ val nested = metadata?.get("nested") as? Map<*, *>
+ // JsonBridgeMapper emits integral numbers as Long (house bridge convention).
+ assertEquals(1L, nested?.get("a"))
+ val signals = metadata?.get("signals") as? List<*>
+ assertEquals(listOf("device", "location"), signals)
+ }
+
+ @Test
+ fun mapMetadataCollectorInitThrowsOnNonObjectPayload() {
+ // Android-only guard: native init throws on a non-object payload, so the
+ // malformed-payload fallback path documented for iOS is unreachable here.
+ val collector = MetadataCollector()
+ try {
+ collector.init(buildJsonObject {
+ put("key", "sdkMetadata")
+ put("type", "METADATA")
+ put("payload", "not-an-object")
+ })
+ throw AssertionError("expected IllegalArgumentException")
+ } catch (error: IllegalArgumentException) {
+ // Native jsonObject coercion — the collector never reaches the mapper.
+ }
+ }
}
diff --git a/packages/davinci/ios/Collector/DaVinciCollectorValueApplier.swift b/packages/davinci/ios/Collector/DaVinciCollectorValueApplier.swift
index 3cbd42109..2d8f9636c 100644
--- a/packages/davinci/ios/Collector/DaVinciCollectorValueApplier.swift
+++ b/packages/davinci/ios/Collector/DaVinciCollectorValueApplier.swift
@@ -149,6 +149,13 @@ enum DaVinciCollectorValueApplier {
case let booleanCollector as BooleanCollector:
booleanCollector.value = try asBoolean(value, key: key)
+ case let metadataCollector as MetadataCollector:
+ // The error envelope is the collector's VALUE (the connector routes on
+ // formData.sdkMetadata). A structured error therefore reaches
+ // setError(code:message:) and the flow resumes via next() instead of
+ // rejecting the bridge call.
+ try applyMetadataValue(metadataCollector, key: key, value: value)
+
default:
// All remaining collectors (TextCollector, PasswordCollector, SingleSelectCollector,
// SubmitCollector, FlowCollector) extend SingleValueCollector which accepts a String
@@ -163,6 +170,88 @@ enum DaVinciCollectorValueApplier {
}
}
+ /// Applies a JS-supplied result value to a `MetadataCollector`.
+ ///
+ /// Semantics:
+ /// - `nil` (JS `null`/undefined) → no-op: the collector's `validate()` keeps returning
+ /// `.required`, so an unset result blocks the flow instead of silently clearing a
+ /// previously set result.
+ /// - Dictionary containing an `error` key → strict envelope validation (a dictionary with
+ /// a non-empty string `code` and a string `message`) → `setError(code:message:)`. A
+ /// malformed envelope throws rather than silently POSTing as a success result.
+ /// - Any other dictionary, including an empty one → `setResult(dict)` (the success path),
+ /// forwarded unchanged.
+ /// - Non-dictionary values → throw: the resume body must be a JSON object.
+ ///
+ /// - Note: The error envelope is the collector's value, which the server-side connector
+ /// routes on, so a well-formed envelope resolves the flow instead of rejecting the
+ /// bridge call. Messages for rejected values name only the offending types, never the
+ /// values, so result content does not reach logs or crash reports.
+ ///
+ /// - Note: An empty result is posted as `formData.sdkMetadata: {}`, which the server
+ /// accepts. In native 2.2.0 the Android SDK omits an empty result from the resume
+ /// request instead, and the server answers with `INVALID_RESUME_PAYLOAD`.
+ ///
+ /// - Parameters:
+ /// - collector: Target metadata collector.
+ /// - key: Collector key (used for error messages).
+ /// - value: Value from JS.
+ /// - Throws: `DaVinciBridgeError.collectorApply` when the value cannot be applied.
+ private static func applyMetadataValue(
+ _ collector: MetadataCollector,
+ key: String,
+ value: Any?
+ ) throws {
+ switch value {
+ case nil:
+ // Unset/null: keep the current state (validate() stays [.required] when unset).
+ // Never clear a previously set result — use node close/dispose for that.
+ return
+
+ case let dict as NSDictionary:
+ if let rawEnvelope = dict["error"] {
+ guard let envelope = rawEnvelope as? NSDictionary,
+ let code = envelope["code"] as? String,
+ !code.isEmpty,
+ let message = envelope["message"] as? String
+ else {
+ let envelope = rawEnvelope as? NSDictionary
+ throw DaVinciBridgeError.collectorApply(
+ "MetadataCollector key='\(key)': malformed error envelope, expected " +
+ "{ error: { code: non-empty string, message: string } }, got " +
+ "error: \(typeName(rawEnvelope)), code: \(typeName(envelope?["code"])), " +
+ "message: \(typeName(envelope?["message"]))"
+ )
+ }
+ collector.setError(code: code, message: message)
+ return
+ }
+ guard let result = dict as? [String: Any] else {
+ let keyTypes = Set(dict.allKeys.map { typeName($0) }).sorted().joined(separator: ", ")
+ throw DaVinciBridgeError.collectorApply(
+ "MetadataCollector key='\(key)': result dictionary has non-string keys (key types: \(keyTypes))"
+ )
+ }
+ collector.setResult(result)
+ return
+
+ default:
+ throw DaVinciBridgeError.collectorApply(
+ "MetadataCollector key='\(key)' expects a JSON object result, got \(type(of: value))"
+ )
+ }
+ }
+
+ /// Names the runtime type of a value for error messages, so rejected values are
+ /// described without being echoed.
+ ///
+ /// - Parameter value: Any bridge value.
+ /// - Returns: The type name, or `"nil"` when the value is absent.
+ private static func typeName(_ value: Any?) -> String {
+ guard let value else { return "nil" }
+ return String(describing: type(of: value))
+ }
+
// MARK: - Value coercion helpers
/// Read a dynamic value from a bridge entry.
diff --git a/packages/davinci/ios/Mapper/DaVinciNodeMapper.swift b/packages/davinci/ios/Mapper/DaVinciNodeMapper.swift
index ba227a03b..597ed6606 100644
--- a/packages/davinci/ios/Mapper/DaVinciNodeMapper.swift
+++ b/packages/davinci/ios/Mapper/DaVinciNodeMapper.swift
@@ -18,6 +18,7 @@ enum DaVinciNodeMapper {
private static let qrCode = "QR_CODE"
private static let socialLoginButton = "SOCIAL_LOGIN_BUTTON"
private static let image = "IMAGE"
+ private static let metadataType = "METADATA"
/// Converts a native DaVinci node to a bridge-friendly dictionary payload.
///
@@ -304,6 +305,8 @@ enum DaVinciNodeMapper {
return mapQRCodeCollector(qrCodeCollector, node: node, logger: logger)
case let imageCollector as ImageCollector:
map = mapImageCollector(imageCollector, node: node, logger: logger)
+ case let metadataCollector as MetadataCollector:
+ map = mapMetadataCollector(metadataCollector, node: node, logger: logger)
default:
// Try registered plugin serializers before generic server-type fallback.
if let serialized = CoreRuntime.serializeDaVinciCollector(collector) {
@@ -624,6 +627,69 @@ enum DaVinciNodeMapper {
return map
}
+ /// Serializes a `MetadataCollector` to a bridge map.
+ ///
+ /// The collector is a resume-capable pause point: JS reads `metadata`, performs
+ /// on-device work, and POSTs a result back through `next()` (applied by
+ /// `DaVinciCollectorValueApplier`).
+ ///
+ /// - Note: iOS's native `MetadataCollector` is an `AnyFieldCollector` — it does not
+ /// extend `FieldCollector` and therefore has no native `label`/`required` (unlike
+ /// Android's `FieldCollector` subtype, which exposes both natively).
+ /// The bridge synthesizes `label` (`""` default) and `required` (`false` default)
+ /// from the matching raw form field JSON so the serialized shape matches Android's.
+ /// Actual submission gating is result-set-based (native `validate()` returns
+ /// `.required` until `setResult`/`setError` is called), independent of the
+ /// server `required` flag.
+ /// TODO-PARITY (SDKS-5546): synthesize `label`/`required` here only until the iOS
+ /// `MetadataCollector` exposes them natively.
+ ///
+ /// - Note: The server's `payload` is the connector's contract with the app; it is
+ /// serialized as `metadata` as-is (no transformation, no filtering). A `payload`
+ /// present but not a dictionary is unreachable on Android — native `init` throws
+ /// before the bridge ever sees the collector — so the warning + `[:]` fallback
+ /// here is iOS-only behavior.
+ /// TODO-PARITY (SDKS-5546): iOS init silently defaults a non-object `payload` to
+ /// empty metadata while Android throws; drop the fallback once the SDKs align.
+ ///
+ /// - Parameters:
+ /// - collector: MetadataCollector instance.
+ /// - node: Active continue node providing form field context for the synthesized
+ /// `label`/`required` and the `raw` lookup.
+ /// - logger: Optional Ping logger for non-fatal mapping warnings.
+ /// - Returns: Serialized metadata collector map.
+ private static func mapMetadataCollector(
+ _ collector: MetadataCollector,
+ node: ContinueNode,
+ logger: Logger?
+ ) -> [String: Any] {
+ let field = findFieldJson(collector.key, node: node, logger: logger)
+ var metadata = collector.metadata
+ if let payload = field?["payload"], !(payload is [String: Any]) {
+ // No-silent-failure: native init coerces a non-dictionary payload to [:]
+ // (native 2.2 default). Surface the offending server value before emitting
+ // the documented default. Android never reaches this state: native init
+ // throws on a non-object payload, so the collector never exists to map.
+ logger?.w(
+ "[\(logTag)] METADATA collector key='\(collector.key)' has non-dictionary payload " +
+ "(server value: \(payload)); emitting empty metadata",
+ error: nil
+ )
+ metadata = [:]
+ }
+ var map: [String: Any] = [
+ "key": collector.key,
+ "type": metadataType,
+ "label": (field?["label"] as? String) ?? "",
+ "required": (field?["required"] as? Bool) ?? false,
+ "metadata": JsonBridgeMapper.encodeJsonObject(metadata)
+ ]
+ if let field {
+ map["raw"] = JsonBridgeMapper.encodeJsonObject(field)
+ }
+ return map
+ }
+
/// Serializes a `ReadOnlyTextCollector` to a bridge map.
///
/// The `type` field is normalized to `"READ_ONLY_TEXT"` (the stable inputType) rather
diff --git a/packages/davinci/ios/Tests/DaVinciCollectorValueApplierTests.swift b/packages/davinci/ios/Tests/DaVinciCollectorValueApplierTests.swift
index 044846a85..f72804093 100644
--- a/packages/davinci/ios/Tests/DaVinciCollectorValueApplierTests.swift
+++ b/packages/davinci/ios/Tests/DaVinciCollectorValueApplierTests.swift
@@ -374,6 +374,253 @@ final class DaVinciCollectorValueApplierTests: XCTestCase {
}
}
+ // MARK: - apply - MetadataCollector (success / error / unset)
+
+ private func makeMetadataCollector(key: String, payload: [String: Any]) -> MetadataCollector {
+ var json: [String: Any] = [
+ "key": key,
+ "type": "METADATA"
+ ]
+ if !payload.isEmpty {
+ json["payload"] = payload
+ }
+ return MetadataCollector(with: json)
+ }
+
+ func testApplyMetadataCollectorSetsResult() throws {
+ // Success object → native setResult; payload() returns the dictionary that
+ // the resume envelope POSTs as formData.sdkMetadata.
+ let collector = makeMetadataCollector(key: "sdkMetadata", payload: ["sdk": "PROTECT"])
+ let node = makeContinueNode(collectors: [collector])
+ let mutations = [
+ DaVinciCollectorValueApplier.CollectorMutation(
+ key: "sdkMetadata",
+ value: ["status": "completed", "score": 87] as NSDictionary
+ )
+ ]
+ _ = try DaVinciCollectorValueApplier.apply(node, mutations: mutations)
+
+ let payload = collector.payload()
+ XCTAssertNotNil(payload)
+ XCTAssertEqual(payload?["status"] as? String, "completed")
+ XCTAssertEqual(payload?["score"] as? Int, 87)
+ XCTAssertTrue(collector.validate().isEmpty)
+ }
+
+ func testApplyMetadataCollectorErrorEnvelopeSetsStructuredError() throws {
+ // Well-formed { error: { code, message } } → native setError; the resulting
+ // payload() is the envelope the connector routes on.
+ let collector = makeMetadataCollector(key: "sdkMetadata", payload: ["sdk": "PROTECT"])
+ let node = makeContinueNode(collectors: [collector])
+ let mutations = [
+ DaVinciCollectorValueApplier.CollectorMutation(
+ key: "sdkMetadata",
+ value: ["error": ["code": "USER_CANCELLED", "message": "User abandoned the flow"]] as NSDictionary
+ )
+ ]
+ _ = try DaVinciCollectorValueApplier.apply(node, mutations: mutations)
+
+ let payload = collector.payload()
+ XCTAssertNotNil(payload)
+ let error = payload?["error"] as? [String: Any]
+ XCTAssertEqual(error?["code"] as? String, "USER_CANCELLED")
+ XCTAssertEqual(error?["message"] as? String, "User abandoned the flow")
+ XCTAssertTrue(collector.validate().isEmpty)
+ }
+
+ func testApplyMetadataCollectorNilValueIsNoOp() throws {
+ // nil → no-op: a previously unset result stays unset, so validate() keeps
+ // returning [.required]. A previously set result is never cleared.
+ let collector = makeMetadataCollector(key: "sdkMetadata", payload: ["sdk": "PROTECT"])
+ let node = makeContinueNode(collectors: [collector])
+ let mutations = [
+ DaVinciCollectorValueApplier.CollectorMutation(key: "sdkMetadata", value: nil)
+ ]
+ _ = try DaVinciCollectorValueApplier.apply(node, mutations: mutations)
+
+ XCTAssertNil(collector.payload())
+ XCTAssertEqual(collector.validate(), [.required])
+
+ // A second nil application must not clear an already-set result either.
+ collector.setResult(["status": "completed"])
+ _ = try DaVinciCollectorValueApplier.apply(node, mutations: mutations)
+ XCTAssertEqual(collector.payload()?["status"] as? String, "completed")
+ }
+
+ func testApplyMetadataCollectorEmptyDictionarySetsEmptyResult() throws {
+ // An empty object is forwarded to native setResult unchanged: the collector is
+ // considered ready (validate() passes) and payload() is the empty dictionary.
+ let collector = makeMetadataCollector(key: "sdkMetadata", payload: ["sdk": "PROTECT"])
+ let node = makeContinueNode(collectors: [collector])
+ let mutations = [
+ DaVinciCollectorValueApplier.CollectorMutation(key: "sdkMetadata", value: NSDictionary())
+ ]
+ _ = try DaVinciCollectorValueApplier.apply(node, mutations: mutations)
+
+ XCTAssertNotNil(collector.payload())
+ XCTAssertEqual(collector.payload()?.count, 0)
+ XCTAssertTrue(collector.validate().isEmpty)
+ }
+
+ func testApplyMetadataCollectorMalformedErrorEnvelopeThrows() {
+ // An 'error' key that isn't a well-formed {code, message} envelope must
+ // not silently POST as a success result.
+ let collector = makeMetadataCollector(key: "sdkMetadata", payload: ["sdk": "PROTECT"])
+ let node = makeContinueNode(collectors: [collector])
+ let mutations = [
+ DaVinciCollectorValueApplier.CollectorMutation(
+ key: "sdkMetadata",
+ value: ["error": ["code": 42]] as NSDictionary
+ )
+ ]
+ XCTAssertThrowsError(try DaVinciCollectorValueApplier.apply(node, mutations: mutations)) { error in
+ guard case let DaVinciBridgeError.collectorApply(message) = error else {
+ return XCTFail("Expected collectorApply error, got \(error)")
+ }
+ XCTAssertTrue(message.contains("malformed error envelope"))
+ XCTAssertNil(collector.payload())
+ }
+ }
+
+ func testApplyMetadataCollectorMalformedEnvelopeMessageDoesNotEchoValues() {
+ // Rejected values are described by type only, so result content never reaches
+ // logs or crash reports through the bridge rejection message.
+ let collector = makeMetadataCollector(key: "sdkMetadata", payload: ["sdk": "PROTECT"])
+ let node = makeContinueNode(collectors: [collector])
+ let malformedEnvelopes: [NSDictionary] = [
+ // 'error' is not an object.
+ ["error": "super-secret-token"] as NSDictionary,
+ // 'code' is not a string.
+ ["error": ["code": 42, "message": "super-secret-token"]] as NSDictionary,
+ // 'message' is not a string.
+ ["error": ["code": "super-secret-token", "message": true]] as NSDictionary,
+ // 'code' is an empty string.
+ ["error": ["code": "", "message": "super-secret-token"]] as NSDictionary
+ ]
+
+ for malformed in malformedEnvelopes {
+ let mutations = [
+ DaVinciCollectorValueApplier.CollectorMutation(key: "sdkMetadata", value: malformed)
+ ]
+ XCTAssertThrowsError(try DaVinciCollectorValueApplier.apply(node, mutations: mutations)) { error in
+ guard case let DaVinciBridgeError.collectorApply(message) = error else {
+ return XCTFail("Expected collectorApply error, got \(error)")
+ }
+ XCTAssertTrue(message.contains("malformed error envelope"))
+ XCTAssertFalse(message.contains("super-secret-token"))
+ }
+ }
+ XCTAssertNil(collector.payload())
+ }
+
+ func testApplyMetadataCollectorNonStringKeysMessageNamesTypesOnly() {
+ let collector = makeMetadataCollector(key: "sdkMetadata", payload: ["sdk": "PROTECT"])
+ let node = makeContinueNode(collectors: [collector])
+ let nonStringKeys = NSDictionary(object: "super-secret-token", forKey: NSNumber(value: 1))
+ let mutations = [
+ DaVinciCollectorValueApplier.CollectorMutation(key: "sdkMetadata", value: nonStringKeys)
+ ]
+ XCTAssertThrowsError(try DaVinciCollectorValueApplier.apply(node, mutations: mutations)) { error in
+ guard case let DaVinciBridgeError.collectorApply(message) = error else {
+ return XCTFail("Expected collectorApply error, got \(error)")
+ }
+ XCTAssertTrue(message.contains("non-string keys"))
+ XCTAssertFalse(message.contains("super-secret-token"))
+ }
+ XCTAssertNil(collector.payload())
+ }
+
+ func testApplyMetadataCollectorNonDictionaryValueThrows() {
+ let collector = makeMetadataCollector(key: "sdkMetadata", payload: ["sdk": "PROTECT"])
+ let node = makeContinueNode(collectors: [collector])
+
+ for badValue in ["not-an-object", NSNumber(value: 7), true, ["a", "b"]] as [Any] {
+ let mutations = [
+ DaVinciCollectorValueApplier.CollectorMutation(key: "sdkMetadata", value: badValue)
+ ]
+ XCTAssertThrowsError(
+ try DaVinciCollectorValueApplier.apply(node, mutations: mutations)
+ ) { error in
+ guard case let DaVinciBridgeError.collectorApply(message) = error else {
+ return XCTFail("Expected collectorApply error, got \(error)")
+ }
+ XCTAssertTrue(message.contains("expects a JSON object result"))
+ }
+ XCTAssertNil(collector.payload())
+ }
+ }
+
+ func testApplyMetadataCollectorNestedResultRoundTrips() throws {
+ // Nested objects/arrays in a success result survive the bridge → collector path.
+ let collector = makeMetadataCollector(key: "sdkMetadata", payload: ["sdk": "PROTECT"])
+ let node = makeContinueNode(collectors: [collector])
+ let mutations = [
+ DaVinciCollectorValueApplier.CollectorMutation(
+ key: "sdkMetadata",
+ value: ["risk": ["score": 12, "level": "LOW"], "signals": ["device", "location"]] as NSDictionary
+ )
+ ]
+ _ = try DaVinciCollectorValueApplier.apply(node, mutations: mutations)
+
+ let payload = collector.payload()
+ let risk = payload?["risk"] as? [String: Any]
+ XCTAssertEqual(risk?["score"] as? Int, 12)
+ XCTAssertEqual(risk?["level"] as? String, "LOW")
+ XCTAssertEqual(payload?["signals"] as? [String], ["device", "location"])
+ }
+
+ // MARK: - MetadataCollector contract (real 2.2.0 native collector)
+
+ func testMetadataCollectorContractSetResultValidatesThenCloseResets() {
+ // Contract block against the real pods MetadataCollector: setResult →
+ // validate()==[] → close() → validate()==[.required].
+ let collector = MetadataCollector(with: [
+ "key": "sdkMetadata", "type": "METADATA", "payload": ["sdk": "PROTECT"]
+ ])
+
+ XCTAssertEqual(collector.validate(), [.required])
+ collector.setResult(["status": "completed"])
+ XCTAssertTrue(collector.validate().isEmpty)
+ XCTAssertEqual(collector.actionKey, "sdkMetadata")
+ collector.close()
+ XCTAssertEqual(collector.validate(), [.required])
+ XCTAssertNil(collector.payload())
+ }
+
+ func testMetadataCollectorContractSetErrorValidatesAndInitializeIsNoOp() {
+ // setError produces the { error: { code, message } } envelope; initialize(with:)
+ // is an intentional no-op (server-echo guard) and never satisfies validate().
+ let collector = MetadataCollector(with: [
+ "key": "sdkMetadata", "type": "METADATA", "payload": ["sdk": "PROTECT"]
+ ])
+
+ collector.setError(code: "USER_CANCELLED", message: "User abandoned the flow")
+ XCTAssertTrue(collector.validate().isEmpty)
+ let payload = collector.payload()
+ let error = payload?["error"] as? [String: Any]
+ XCTAssertEqual(error?["code"] as? String, "USER_CANCELLED")
+ XCTAssertEqual(error?["message"] as? String, "User abandoned the flow")
+
+ // initialize(with:) is an intentional no-op (server-echo guard): it must NOT
+ // overwrite the app-supplied result set via setError.
+ collector.initialize(with: "echoed-server-value")
+ let afterEcho = collector.payload()
+ let errorAfterEcho = afterEcho?["error"] as? [String: Any]
+ XCTAssertEqual(errorAfterEcho?["code"] as? String, "USER_CANCELLED")
+ }
+
+ func testMetadataCollectorContractInitializeIsNoOpKeepsRequiredState() {
+ let collector = MetadataCollector(with: [
+ "key": "sdkMetadata", "type": "METADATA", "payload": ["sdk": "PROTECT"]
+ ])
+
+ // Even when the server echoes a formData value, initialize() must not
+ // pre-satisfy validation — the result must come from setResult/setError.
+ collector.initialize(with: ["status": "completed"])
+ XCTAssertNil(collector.payload())
+ XCTAssertEqual(collector.validate(), [.required])
+ }
+
// MARK: - Helpers
private func makeContinueNode(collectors: [any Collector]) -> ContinueNode {
diff --git a/packages/davinci/ios/Tests/DaVinciNodeMapperTests.swift b/packages/davinci/ios/Tests/DaVinciNodeMapperTests.swift
index 3a1d44447..0b23fd6de 100644
--- a/packages/davinci/ios/Tests/DaVinciNodeMapperTests.swift
+++ b/packages/davinci/ios/Tests/DaVinciNodeMapperTests.swift
@@ -11,6 +11,7 @@
import XCTest
import PingDavinci
import PingDavinciPlugin
+import PingLogger
import PingOrchestrate
import RNPingCore
@testable import RNPingDavinci
@@ -1062,6 +1063,237 @@ final class DaVinciNodeMapperTests: XCTestCase {
XCTAssertNil(payload["unsupportedFields"])
}
+ // MARK: - MetadataCollector serialization
+
+ private func makeMetadataCollector(
+ key: String,
+ type: String = "METADATA",
+ payload: Any?
+ ) -> MetadataCollector {
+ var json: [String: Any] = [
+ "key": key,
+ "type": type
+ ]
+ if let payload {
+ json["payload"] = payload
+ }
+ return MetadataCollector(with: json)
+ }
+
+ private static func makeMetadataNodeInput() -> [String: Any] {
+ return [
+ "form": [
+ "components": [
+ "fields": [
+ [
+ "key": "sdkMetadata",
+ "type": "METADATA",
+ "label": "SDK Metadata",
+ "required": true,
+ "payload": ["sdk": "PROTECT", "action": "INITIALIZE"]
+ ]
+ ]
+ ]
+ ]
+ ]
+ }
+
+ func testMapMetadataCollectorEmitsAllFields() {
+ let node = makeContinueNode(
+ collectors: [
+ makeMetadataCollector(
+ key: "sdkMetadata",
+ payload: ["sdk": "PROTECT", "action": "INITIALIZE"]
+ )
+ ],
+ input: DaVinciNodeMapperTests.makeMetadataNodeInput()
+ )
+
+ let payload = DaVinciNodeMapper.mapNodePayload(node)
+ let first = (payload["collectors"] as? [[String: Any]])?.first
+
+ XCTAssertEqual(first?["type"] as? String, "METADATA")
+ XCTAssertEqual(first?["key"] as? String, "sdkMetadata")
+ let metadata = first?["metadata"] as? [String: Any]
+ XCTAssertEqual(metadata?["sdk"] as? String, "PROTECT")
+ XCTAssertEqual(metadata?["action"] as? String, "INITIALIZE")
+ }
+
+ func testMapMetadataCollectorSynthesizesLabelAndRequiredFromRawFieldJson() {
+ // iOS's native MetadataCollector is an AnyFieldCollector with no native
+ // label/required (unlike Android's FieldCollector subtype); the bridge
+ // synthesizes both from the raw form field JSON.
+ let node = makeContinueNode(
+ collectors: [
+ makeMetadataCollector(
+ key: "sdkMetadata",
+ payload: ["sdk": "PROTECT"]
+ )
+ ],
+ input: DaVinciNodeMapperTests.makeMetadataNodeInput()
+ )
+
+ let payload = DaVinciNodeMapper.mapNodePayload(node)
+ let first = (payload["collectors"] as? [[String: Any]])?.first
+
+ XCTAssertEqual(first?["label"] as? String, "SDK Metadata")
+ XCTAssertEqual(first?["required"] as? Bool, true)
+ }
+
+ func testMapMetadataCollectorDefaultsLabelAndRequiredWhenFieldAbsent() {
+ let node = makeContinueNode(
+ collectors: [
+ makeMetadataCollector(key: "sdkMetadata", payload: ["sdk": "PROTECT"])
+ ]
+ )
+
+ let payload = DaVinciNodeMapper.mapNodePayload(node)
+ let first = (payload["collectors"] as? [[String: Any]])?.first
+
+ XCTAssertEqual(first?["label"] as? String, "")
+ XCTAssertEqual(first?["required"] as? Bool, false)
+ }
+
+ func testMapMetadataCollectorDefaultsLabelAndRequiredWhenFieldValuesAbsent() {
+ // A matching field entry without label/required keys still yields the defaults.
+ let input: [String: Any] = [
+ "form": [
+ "components": [
+ "fields": [
+ ["key": "sdkMetadata", "type": "METADATA", "payload": ["sdk": "PROTECT"]]
+ ]
+ ]
+ ]
+ ]
+ let node = makeContinueNode(
+ collectors: [
+ makeMetadataCollector(key: "sdkMetadata", payload: ["sdk": "PROTECT"])
+ ],
+ input: input
+ )
+
+ let payload = DaVinciNodeMapper.mapNodePayload(node)
+ let first = (payload["collectors"] as? [[String: Any]])?.first
+
+ XCTAssertEqual(first?["label"] as? String, "")
+ XCTAssertEqual(first?["required"] as? Bool, false)
+ }
+
+ func testMapMetadataCollectorEmitsEmptyMetadataWhenPayloadAbsent() {
+ let collector = makeMetadataCollector(key: "sdkMetadata", payload: nil)
+ let node = makeContinueNode(collectors: [collector])
+
+ let payload = DaVinciNodeMapper.mapNodePayload(node)
+ let first = (payload["collectors"] as? [[String: Any]])?.first
+
+ let metadata = first?["metadata"] as? [String: Any]
+ XCTAssertNotNil(metadata)
+ XCTAssertTrue(metadata?.isEmpty ?? false)
+ }
+
+ func testMapMetadataCollectorWarnsAndEmitsEmptyMetadataForMalformedPayload() {
+ // iOS-only reachable: native init coerces a non-dictionary payload to [:]
+ // (Android's native init throws before the bridge sees the collector). The raw
+ // form field still carries the server value, which the mapper reports before
+ // falling back to empty metadata.
+ let collector = makeMetadataCollector(key: "sdkMetadata", payload: "not-a-dictionary")
+ let node = makeContinueNode(
+ collectors: [collector],
+ input: [
+ "form": [
+ "components": [
+ "fields": [
+ ["key": "sdkMetadata", "type": "METADATA", "payload": "not-a-dictionary"]
+ ]
+ ]
+ ]
+ ]
+ )
+ let logger = RecordingLogger()
+
+ let payload = DaVinciNodeMapper.mapNodePayload(node, logger: logger)
+ let first = (payload["collectors"] as? [[String: Any]])?.first
+
+ let metadata = first?["metadata"] as? [String: Any]
+ XCTAssertNotNil(metadata)
+ XCTAssertTrue(metadata?.isEmpty ?? false)
+ XCTAssertEqual(logger.warnings.count, 1)
+ XCTAssertTrue(logger.warnings.first?.contains("key='sdkMetadata'") ?? false)
+ XCTAssertTrue(logger.warnings.first?.contains("not-a-dictionary") ?? false)
+ }
+
+ func testMapMetadataCollectorDoesNotWarnForDictionaryPayload() {
+ let collector = makeMetadataCollector(key: "sdkMetadata", payload: ["sdk": "PROTECT"])
+ let node = makeContinueNode(collectors: [collector], input: Self.makeMetadataNodeInput())
+ let logger = RecordingLogger()
+
+ _ = DaVinciNodeMapper.mapNodePayload(node, logger: logger)
+
+ XCTAssertTrue(logger.warnings.isEmpty)
+ }
+
+ func testMapMetadataCollectorIncludesRawFieldWhenFormInputPresent() {
+ let node = makeContinueNode(
+ collectors: [
+ makeMetadataCollector(
+ key: "sdkMetadata",
+ payload: ["sdk": "PROTECT", "action": "INITIALIZE"]
+ )
+ ],
+ input: DaVinciNodeMapperTests.makeMetadataNodeInput()
+ )
+
+ let payload = DaVinciNodeMapper.mapNodePayload(node)
+ let first = (payload["collectors"] as? [[String: Any]])?.first
+
+ XCTAssertNotNil(first?["raw"])
+ }
+
+ func testMapMetadataCollectorNotReportedAsUnsupportedField() {
+ let node = makeContinueNode(
+ collectors: [
+ makeMetadataCollector(
+ key: "sdkMetadata",
+ payload: ["sdk": "PROTECT", "action": "INITIALIZE"]
+ )
+ ],
+ input: DaVinciNodeMapperTests.makeMetadataNodeInput()
+ )
+
+ let payload = DaVinciNodeMapper.mapNodePayload(node)
+
+ XCTAssertNil(payload["unsupportedFields"])
+ }
+
+ func testMapNodeRoundTripWithMetadataCollector() {
+ // Full mapNode round-trip: the NSDictionary payload emitted for the bridge
+ // carries the same typed fields as the intermediate payload map.
+ let node = makeContinueNode(
+ collectors: [
+ makeMetadataCollector(
+ key: "sdkMetadata",
+ payload: ["sdk": "PROTECT", "action": "INITIALIZE", "nested": ["a": 1]]
+ )
+ ],
+ input: DaVinciNodeMapperTests.makeMetadataNodeInput()
+ )
+
+ let payload = DaVinciNodeMapper.mapNode(node)
+ let collectors = payload["collectors"] as? [[String: Any]]
+ let first = collectors?.first
+
+ XCTAssertEqual(first?["type"] as? String, "METADATA")
+ XCTAssertEqual(first?["key"] as? String, "sdkMetadata")
+ XCTAssertEqual(first?["label"] as? String, "SDK Metadata")
+ XCTAssertEqual(first?["required"] as? Bool, true)
+ let metadata = first?["metadata"] as? [String: Any]
+ XCTAssertEqual(metadata?["sdk"] as? String, "PROTECT")
+ XCTAssertEqual(metadata?["action"] as? String, "INITIALIZE")
+ let nested = metadata?["nested"] as? [String: Any]
+ XCTAssertEqual(nested?["a"] as? Int, 1)
+ XCTAssertNotNil(first?["raw"])
+ }
+
// MARK: - ReadOnlyTextCollector serialization
func testMapReadOnlyTextCollectorIncludesAllFields() {
@@ -1266,6 +1498,28 @@ private final class TestContinueNode: ContinueNode {
}
}
+/// Records warning messages so tests can assert on what the mapper logs.
+private final class RecordingLogger: Logger, @unchecked Sendable {
+ private let lock = NSLock()
+ private var recordedWarnings: [String] = []
+
+ var warnings: [String] {
+ lock.lock()
+ defer { lock.unlock() }
+ return recordedWarnings
+ }
+
+ func d(_ message: String) {}
+ func i(_ message: String) {}
+ func e(_ message: String, error: Error?) {}
+
+ func w(_ message: String, error: Error?) {
+ lock.lock()
+ defer { lock.unlock() }
+ recordedWarnings.append(message)
+ }
+}
+
private struct StubSession: Session {
var value: String
}
diff --git a/packages/davinci/ios/Tests/RNPingDavinciCommonTests.swift b/packages/davinci/ios/Tests/RNPingDavinciCommonTests.swift
index 51daf2e02..ef19a373f 100644
--- a/packages/davinci/ios/Tests/RNPingDavinciCommonTests.swift
+++ b/packages/davinci/ios/Tests/RNPingDavinciCommonTests.swift
@@ -465,6 +465,73 @@ final class RNPingDavinciCommonTests: XCTestCase {
}
}
+ // MARK: - validate — MetadataCollector
+
+ func testValidateMetadataCollectorUnsetResultResolvesRequiredError() {
+ // Unset (null) application is a no-op, so the native validate() still
+ // reports .required — the flow blocks until the app sets a result.
+ let davinciId = "validate-metadata-unset"
+ RNPingDavinciCommon._setContinueNodeForTesting(
+ davinciId: davinciId,
+ node: makeContinueNode(collectors: [
+ MetadataCollector(with: [
+ "key": "sdkMetadata", "type": "METADATA", "payload": ["sdk": "PROTECT"]
+ ])
+ ])
+ )
+
+ assertValidateResolves(
+ davinciId: davinciId,
+ collectorKey: "sdkMetadata",
+ value: NSNull()
+ ) { errors in
+ XCTAssertEqual(errors.count, 1)
+ XCTAssertEqual(errors.first?["code"] as? String, "REQUIRED")
+ }
+ }
+
+ func testValidateMetadataCollectorSetResultResolvesEmptyArray() {
+ let davinciId = "validate-metadata-set"
+ RNPingDavinciCommon._setContinueNodeForTesting(
+ davinciId: davinciId,
+ node: makeContinueNode(collectors: [
+ MetadataCollector(with: [
+ "key": "sdkMetadata", "type": "METADATA", "payload": ["sdk": "PROTECT"]
+ ])
+ ])
+ )
+
+ assertValidateResolves(
+ davinciId: davinciId,
+ collectorKey: "sdkMetadata",
+ value: ["status": "completed", "score": 87]
+ ) { errors in
+ XCTAssertTrue(errors.isEmpty)
+ }
+ }
+
+ func testValidateMetadataCollectorErrorEnvelopeResolvesEmptyArray() {
+ // The well-formed error envelope is the collector's value — it satisfies
+ // validate() exactly like a success result; the connector routes on it.
+ let davinciId = "validate-metadata-error-envelope"
+ RNPingDavinciCommon._setContinueNodeForTesting(
+ davinciId: davinciId,
+ node: makeContinueNode(collectors: [
+ MetadataCollector(with: [
+ "key": "sdkMetadata", "type": "METADATA", "payload": ["sdk": "PROTECT"]
+ ])
+ ])
+ )
+
+ assertValidateResolves(
+ davinciId: davinciId,
+ collectorKey: "sdkMetadata",
+ value: ["error": ["code": "USER_CANCELLED", "message": "User abandoned the flow"]]
+ ) { errors in
+ XCTAssertTrue(errors.isEmpty)
+ }
+ }
+
// MARK: - getSession
func testGetSessionRejectsWhenDaVinciMissing() {
diff --git a/packages/davinci/src/__tests__/collectorHelpers.test.ts b/packages/davinci/src/__tests__/collectorHelpers.test.ts
index e052bc0a9..55bc79ac4 100644
--- a/packages/davinci/src/__tests__/collectorHelpers.test.ts
+++ b/packages/davinci/src/__tests__/collectorHelpers.test.ts
@@ -7,6 +7,8 @@
import { registerIntegrationCollectorType } from '@ping-identity/rn-types';
import {
+ buildMetadataError,
+ buildMetadataResult,
buildNextInput,
computeFormMeta,
normalizeCollectors,
@@ -16,6 +18,7 @@ import {
import type {
ContinueNode,
DaVinciCollector,
+ DaVinciFormValue,
DaVinciNormalizedCollector,
} from '../types';
@@ -87,6 +90,10 @@ describe('resolveExecutionMode', () => {
expect(resolveExecutionMode('IMAGE')).toBe('output_only');
});
+ it('returns metadata for METADATA', () => {
+ expect(resolveExecutionMode('METADATA')).toBe('metadata');
+ });
+
it('never returns integration_required for any base-registry type', () => {
const allKnownTypes = [...manualTypes, 'LABEL', ...immediateTypes];
allKnownTypes.forEach((type) => {
@@ -175,6 +182,10 @@ describe('resolveFieldKind', () => {
it('returns image for IMAGE', () => {
expect(resolveFieldKind('IMAGE')).toBe('image');
});
+
+ it('returns metadata for METADATA', () => {
+ expect(resolveFieldKind('METADATA')).toBe('metadata');
+ });
});
describe('normalizeCollectors', () => {
@@ -521,6 +532,315 @@ describe('normalizeCollectors — IMAGE', () => {
});
});
+describe('normalizeCollectors — METADATA', () => {
+ const metadataCollector: DaVinciCollector = {
+ key: 'sdkMetadata',
+ type: 'METADATA',
+ label: 'SDK Metadata',
+ required: false,
+ metadata: { sdk: 'PROTECT', action: 'INITIALIZE' },
+ raw: { type: 'METADATA', key: 'sdkMetadata', payload: { sdk: 'PROTECT' } },
+ } as DaVinciCollector;
+
+ it('classifies METADATA as metadata mode with kind metadata and no required input', () => {
+ const [normalized] = normalizeCollectors([metadataCollector]);
+ expect(normalized).toMatchObject({
+ key: 'sdkMetadata',
+ type: 'METADATA',
+ executionMode: 'metadata',
+ requiresUserInput: false,
+ kind: 'metadata',
+ });
+ });
+
+ it('passes the opaque metadata payload through untouched', () => {
+ const [normalized] = normalizeCollectors([metadataCollector]);
+ expect(normalized.metadata).toEqual({
+ sdk: 'PROTECT',
+ action: 'INITIALIZE',
+ });
+ });
+
+ it('has no server-seeded defaultValue', () => {
+ const [normalized] = normalizeCollectors([metadataCollector]);
+ expect(normalized.defaultValue).toBeUndefined();
+ });
+});
+
+describe('buildNextInput — metadata path', () => {
+ const makeMetadataNode = (): ContinueNode =>
+ makeNode([
+ {
+ key: 'sdkMetadata',
+ type: 'METADATA',
+ label: 'SDK Metadata',
+ required: false,
+ metadata: { sdk: 'PROTECT' },
+ } as DaVinciCollector,
+ ]);
+
+ it.each([
+ ['unset (key absent)', undefined],
+ ['null', null],
+ ])('blocks with METADATA_RESULT_REQUIRED for %s result', (_label, value) => {
+ const values = value === undefined ? {} : { sdkMetadata: value };
+ const result = buildNextInput(makeMetadataNode(), values);
+
+ expect(result.canSubmit).toBe(false);
+ expect(result.issues).toEqual([
+ expect.objectContaining({
+ code: 'METADATA_RESULT_REQUIRED',
+ key: 'sdkMetadata',
+ }),
+ ]);
+ expect(result.input.collectors).toEqual([]);
+ });
+
+ it.each([
+ ['string', 'not-an-object', 'string'],
+ ['number', 42, 'number'],
+ ['array', ['not', 'an', 'object'], 'array'],
+ ['boolean', true, 'boolean'],
+ ])(
+ 'blocks with METADATA_RESULT_MALFORMED for a %s result naming the offending type',
+ (_label, value, expectedType) => {
+ const result = buildNextInput(makeMetadataNode(), {
+ sdkMetadata: value as unknown as DaVinciFormValue,
+ });
+
+ expect(result.canSubmit).toBe(false);
+ expect(result.issues).toHaveLength(1);
+ expect(result.issues[0]).toMatchObject({
+ code: 'METADATA_RESULT_MALFORMED',
+ key: 'sdkMetadata',
+ });
+ expect(result.issues[0].message).toContain(expectedType);
+ expect(result.input.collectors).toEqual([]);
+ },
+ );
+
+ it('includes an empty object result in the payload unchanged', () => {
+ const result = buildNextInput(makeMetadataNode(), { sdkMetadata: {} });
+
+ expect(result.canSubmit).toBe(true);
+ expect(result.issues).toEqual([]);
+ expect(result.input.collectors).toEqual([
+ { key: 'sdkMetadata', value: {} },
+ ]);
+ });
+
+ it('blocks with METADATA_RESULT_MALFORMED when the error envelope is malformed', () => {
+ const result = buildNextInput(makeMetadataNode(), {
+ sdkMetadata: { error: { code: 'X' } },
+ });
+
+ expect(result.canSubmit).toBe(false);
+ expect(result.issues[0]).toMatchObject({
+ code: 'METADATA_RESULT_MALFORMED',
+ key: 'sdkMetadata',
+ });
+ expect(result.issues[0].message).toContain('envelope');
+ expect(result.input.collectors).toEqual([]);
+ });
+
+ it.each([
+ ['missing message', { error: { code: 'X' } }],
+ ['missing code', { error: { message: 'boom' } }],
+ ['empty code', { error: { code: '', message: 'boom' } }],
+ ['non-string message', { error: { code: 'X', message: 3 } }],
+ ['non-object envelope', { error: 'failed' }],
+ ['null envelope', { error: null }],
+ ['array envelope', { error: [] }],
+ ])(
+ 'blocks with METADATA_RESULT_MALFORMED for a malformed envelope: %s',
+ (_label, value) => {
+ const result = buildNextInput(makeMetadataNode(), {
+ sdkMetadata: value as unknown as DaVinciFormValue,
+ });
+
+ expect(result.canSubmit).toBe(false);
+ expect(result.issues).toEqual([
+ expect.objectContaining({
+ code: 'METADATA_RESULT_MALFORMED',
+ key: 'sdkMetadata',
+ }),
+ ]);
+ expect(result.input.collectors).toEqual([]);
+ },
+ );
+
+ it('includes a valid success object in the payload', () => {
+ const resultValue = buildMetadataResult({ status: 'success', score: 0.87 });
+ const result = buildNextInput(makeMetadataNode(), {
+ sdkMetadata: resultValue,
+ });
+
+ expect(result.canSubmit).toBe(true);
+ expect(result.issues).toEqual([]);
+ expect(result.input.collectors).toEqual([
+ { key: 'sdkMetadata', value: resultValue },
+ ]);
+ });
+
+ it('includes a well-formed error envelope in the payload untouched', () => {
+ const resultValue = { error: { code: 'USER_CANCELLED', message: 'Nope' } };
+ const result = buildNextInput(makeMetadataNode(), {
+ sdkMetadata: resultValue,
+ });
+
+ expect(result.canSubmit).toBe(true);
+ expect(result.issues).toEqual([]);
+ expect(result.input.collectors).toEqual([
+ { key: 'sdkMetadata', value: resultValue },
+ ]);
+ });
+
+ it('includes a buildMetadataError value in the payload with its exact shape', () => {
+ const result = buildNextInput(makeMetadataNode(), {
+ sdkMetadata: buildMetadataError('A', 'b'),
+ });
+
+ expect(result.canSubmit).toBe(true);
+ expect(result.issues).toEqual([]);
+ expect(result.input.collectors).toEqual([
+ { key: 'sdkMetadata', value: { error: { code: 'A', message: 'b' } } },
+ ]);
+ });
+
+ it('includes the metadata result alongside SUBMIT_BUTTON and TEXT on a mixed node', () => {
+ const node = makeNode([
+ baseField('username', 'TEXT', true),
+ baseField('submit', 'SUBMIT_BUTTON'),
+ {
+ key: 'sdkMetadata',
+ type: 'METADATA',
+ label: 'SDK Metadata',
+ required: false,
+ metadata: { sdk: 'PROTECT' },
+ } as DaVinciCollector,
+ ]);
+
+ const result = buildNextInput(node, {
+ username: 'alice',
+ sdkMetadata: buildMetadataResult({ status: 'success' }),
+ });
+
+ expect(result.canSubmit).toBe(true);
+ expect(result.issues).toEqual([]);
+ expect(result.input.collectors).toEqual([
+ { key: 'username', value: 'alice' },
+ { key: 'submit', value: 'submit' },
+ { key: 'sdkMetadata', value: { status: 'success' } },
+ ]);
+ });
+
+ it('blocks a mixed node on a malformed metadata result while other flows are unchanged', () => {
+ const node = makeNode([
+ baseField('username', 'TEXT', true),
+ baseField('submit', 'SUBMIT_BUTTON'),
+ {
+ key: 'sdkMetadata',
+ type: 'METADATA',
+ label: 'SDK Metadata',
+ required: false,
+ metadata: {},
+ } as DaVinciCollector,
+ ]);
+
+ const result = buildNextInput(node, {
+ username: 'alice',
+ sdkMetadata: 'bogus',
+ });
+
+ expect(result.canSubmit).toBe(false);
+ expect(result.issues).toEqual([
+ expect.objectContaining({
+ code: 'METADATA_RESULT_MALFORMED',
+ key: 'sdkMetadata',
+ }),
+ ]);
+ expect(result.input.collectors).toEqual([
+ { key: 'username', value: 'alice' },
+ { key: 'submit', value: 'submit' },
+ ]);
+ });
+
+ it('does not let buildMetadataResult bypass validation: a wrapped malformed envelope still blocks', () => {
+ const result = buildNextInput(makeMetadataNode(), {
+ sdkMetadata: buildMetadataResult({ error: 'failed' }),
+ });
+
+ expect(result.canSubmit).toBe(false);
+ expect(result.issues).toEqual([
+ expect.objectContaining({
+ code: 'METADATA_RESULT_MALFORMED',
+ key: 'sdkMetadata',
+ }),
+ ]);
+ });
+});
+
+describe('computeFormMeta — hasMetadata', () => {
+ it('flags hasMetadata when a METADATA collector is present', () => {
+ const collectors = normalizeCollectors([
+ {
+ key: 'sdkMetadata',
+ type: 'METADATA',
+ label: 'SDK Metadata',
+ required: false,
+ metadata: { sdk: 'PROTECT' },
+ } as DaVinciCollector,
+ ]);
+
+ expect(computeFormMeta(collectors).hasMetadata).toBe(true);
+ expect(computeFormMeta(collectors).hasManual).toBe(false);
+ });
+
+ it('hasMetadata stays false for forms without a METADATA collector', () => {
+ const collectors = normalizeCollectors([
+ baseField('username', 'TEXT'),
+ { key: 'l', type: 'LABEL', content: 'x' } as DaVinciCollector,
+ ]);
+
+ expect(computeFormMeta(collectors).hasMetadata).toBe(false);
+ });
+});
+
+describe('buildMetadataResult', () => {
+ it('returns the same object it was given (the brand is type-only)', () => {
+ const input = { status: 'success', score: 0.87 };
+
+ expect(buildMetadataResult(input)).toBe(input);
+ });
+});
+
+describe('buildMetadataError', () => {
+ it('returns the exact error envelope shape', () => {
+ expect(buildMetadataError('A', 'b')).toEqual({
+ error: { code: 'A', message: 'b' },
+ });
+ });
+
+ it('builds envelopes the metadata submit path accepts as valid', () => {
+ const node = makeNode([
+ {
+ key: 'sdkMetadata',
+ type: 'METADATA',
+ label: 'SDK Metadata',
+ required: false,
+ metadata: {},
+ } as DaVinciCollector,
+ ]);
+
+ const result = buildNextInput(node, {
+ sdkMetadata: buildMetadataError('USER_CANCELLED', 'dismissed'),
+ });
+
+ expect(result.canSubmit).toBe(true);
+ expect(result.issues).toEqual([]);
+ });
+});
+
describe('buildNextInput — no active node', () => {
it('returns NO_ACTIVE_CONTINUE_NODE when node is null', () => {
const result = buildNextInput(null, {});
@@ -982,6 +1302,7 @@ describe('computeFormMeta', () => {
hasOutputOnly: false,
hasAutoCapable: false,
hasIntegrationRequired: true,
+ hasMetadata: false,
hasUnsupported: false,
});
});
@@ -992,6 +1313,7 @@ describe('computeFormMeta', () => {
hasOutputOnly: false,
hasAutoCapable: false,
hasIntegrationRequired: false,
+ hasMetadata: false,
hasUnsupported: false,
});
});
diff --git a/packages/davinci/src/__tests__/index.test.tsx b/packages/davinci/src/__tests__/index.test.tsx
index fd1d4b8ce..a31776351 100644
--- a/packages/davinci/src/__tests__/index.test.tsx
+++ b/packages/davinci/src/__tests__/index.test.tsx
@@ -13,6 +13,8 @@ describe('@ping-identity/rn-davinci public export surface', () => {
});
it('exports collector helpers', () => {
+ expect(typeof DavinciIndex.buildMetadataError).toBe('function');
+ expect(typeof DavinciIndex.buildMetadataResult).toBe('function');
expect(typeof DavinciIndex.buildNextInput).toBe('function');
expect(typeof DavinciIndex.computeFormMeta).toBe('function');
expect(typeof DavinciIndex.normalizeCollectors).toBe('function');
diff --git a/packages/davinci/src/__tests__/useDavinciForm.test.tsx b/packages/davinci/src/__tests__/useDavinciForm.test.tsx
index 5337c88da..baff880c7 100644
--- a/packages/davinci/src/__tests__/useDavinciForm.test.tsx
+++ b/packages/davinci/src/__tests__/useDavinciForm.test.tsx
@@ -7,10 +7,11 @@
import React, { useEffect } from 'react';
import { registerIntegrationCollectorType } from '@ping-identity/rn-types';
-
-const integrationType = 'TEST_INTEGRATION_COLLECTOR';
import { render, act } from '@testing-library/react-native';
import { useDaVinciForm } from '../useDavinciForm';
+import { buildMetadataError, buildMetadataResult } from '../collectorHelpers';
+
+const integrationType = 'TEST_INTEGRATION_COLLECTOR';
type ContinueNode = import('../types').ContinueNode;
type DaVinciNode = import('../types').DaVinciNode;
@@ -717,6 +718,129 @@ describe('useDaVinciForm — unsupportedFields passthrough', () => {
});
});
+describe('useDaVinciForm — METADATA pause/resume', () => {
+ const metadataNode: ContinueNode = {
+ type: 'ContinueNode',
+ collectors: [
+ {
+ key: 'sdkMetadata',
+ type: 'METADATA',
+ label: 'SDK Metadata',
+ required: false,
+ metadata: { sdk: 'PROTECT', action: 'INITIALIZE' },
+ } as ContinueNode['collectors'][number],
+ ],
+ };
+
+ it('classifies the METADATA field as kind metadata with no required input', () => {
+ let latest: DaVinciFormResult | null = null;
+
+ render(
+ {
+ latest = r;
+ }}
+ />,
+ );
+
+ const field = requireLatest(latest).getField('sdkMetadata');
+ expect(field).toBeDefined();
+ expect(field?.kind).toBe('metadata');
+ expect(field?.executionMode).toBe('metadata');
+ expect(field?.requiresUserInput).toBe(false);
+ expect(requireLatest(latest).meta.hasMetadata).toBe(true);
+ });
+
+ it('blocks submit while the metadata result is unset', () => {
+ let latest: DaVinciFormResult | null = null;
+
+ render(
+ {
+ latest = r;
+ }}
+ />,
+ );
+
+ expect(requireLatest(latest).canSubmit).toBe(false);
+ expect(
+ requireLatest(latest).issues.some(
+ (i) => i.code === 'METADATA_RESULT_REQUIRED',
+ ),
+ ).toBe(true);
+ });
+
+ it('flows a success result set via setValue into values and buildInput()', async () => {
+ let latest: DaVinciFormResult | null = null;
+
+ render(
+ {
+ latest = r;
+ }}
+ />,
+ );
+
+ const resultValue = buildMetadataResult({ status: 'success', score: 0.87 });
+ await act(async () => {
+ requireLatest(latest).setValue('sdkMetadata', resultValue);
+ });
+
+ expect(requireLatest(latest).values['sdkMetadata']).toBe(resultValue);
+
+ const plan = requireLatest(latest).buildInput();
+ expect(plan.canSubmit).toBe(true);
+ expect(plan.issues).toEqual([]);
+ expect(plan.input.collectors).toEqual([
+ { key: 'sdkMetadata', value: resultValue },
+ ]);
+ });
+
+ it('flows a buildMetadataError envelope through setValue and buildInput()', async () => {
+ let latest: DaVinciFormResult | null = null;
+
+ render(
+ {
+ latest = r;
+ }}
+ />,
+ );
+
+ await act(async () => {
+ requireLatest(latest).setValue(
+ 'sdkMetadata',
+ buildMetadataError('USER_CANCELLED', 'User dismissed the challenge.'),
+ );
+ });
+
+ expect(requireLatest(latest).values['sdkMetadata']).toEqual({
+ error: {
+ code: 'USER_CANCELLED',
+ message: 'User dismissed the challenge.',
+ },
+ });
+
+ const plan = requireLatest(latest).buildInput();
+ expect(plan.canSubmit).toBe(true);
+ expect(plan.input.collectors).toEqual([
+ {
+ key: 'sdkMetadata',
+ value: {
+ error: {
+ code: 'USER_CANCELLED',
+ message: 'User dismissed the challenge.',
+ },
+ },
+ },
+ ]);
+ });
+});
+
describe('useDaVinciForm — submitFlow', () => {
const flowNode: ContinueNode = {
type: 'ContinueNode',
diff --git a/packages/davinci/src/collectorHelpers.ts b/packages/davinci/src/collectorHelpers.ts
index 67a0f0a1a..d17c6ce74 100644
--- a/packages/davinci/src/collectorHelpers.ts
+++ b/packages/davinci/src/collectorHelpers.ts
@@ -14,6 +14,8 @@ import type {
DaVinciFormMeta,
DaVinciFormValue,
DaVinciFormValues,
+ DaVinciMetadataErrorResult,
+ DaVinciMetadataResult,
DaVinciNextInput,
DaVinciNode,
DaVinciNormalizedCollector,
@@ -80,6 +82,16 @@ export const flowCollectorTypes = new Set([
'FLOW_LINK',
]);
+/**
+ * SDK Integrator connector pause/resume collector types.
+ *
+ * @remarks
+ * A `METADATA` collector pauses the flow and hands the app an opaque payload;
+ * the app performs the on-device work and sets a result value before the flow
+ * can resume via `next()`.
+ */
+const metadataCollectorTypes = new Set(['METADATA']);
+
/**
* Collector type strings handled entirely by an external integration package.
*
@@ -138,6 +150,7 @@ const flowFieldKindTypes = new Set([
* resolveExecutionMode('TEXT'); // 'manual'
* resolveExecutionMode('LABEL'); // 'output_only'
* resolveExecutionMode('SUBMIT_BUTTON'); // 'immediate'
+ * resolveExecutionMode('METADATA'); // 'metadata'
* resolveExecutionMode('UNKNOWN_TYPE'); // 'unsupported'
* ```
*
@@ -156,6 +169,9 @@ export function resolveExecutionMode(type: string): DaVinciExecutionMode {
if (immediateCollectorTypes.has(type)) {
return 'immediate';
}
+ if (metadataCollectorTypes.has(type)) {
+ return 'metadata';
+ }
return 'unsupported';
}
@@ -177,6 +193,7 @@ export function resolveExecutionMode(type: string): DaVinciExecutionMode {
* resolveFieldKind('SUBMIT_BUTTON'); // 'flow'
* resolveFieldKind('LABEL'); // 'output'
* resolveFieldKind('IMAGE'); // 'image'
+ * resolveFieldKind('METADATA'); // 'metadata'
* resolveFieldKind('UNKNOWN_TYPE'); // 'unknown'
* ```
*
@@ -219,6 +236,9 @@ export function resolveFieldKind(type: string): DaVinciFieldKind {
if (imageFieldKindTypes.has(type)) {
return 'image';
}
+ if (metadataCollectorTypes.has(type)) {
+ return 'metadata';
+ }
if (flowFieldKindTypes.has(type)) {
return 'flow';
}
@@ -394,6 +414,167 @@ export function normalizeCollectors(
});
}
+/**
+ * Wraps a success result for a {@link MetadataCollector} so it can be set as the
+ * collector's form value.
+ *
+ * @remarks
+ * `DaVinciFormValue` accepts only this branded type (and the error envelope from
+ * {@link buildMetadataError}) for METADATA, so a plain object literal does not
+ * compile. That keeps mis-shaped values for other collector kinds a compile-time
+ * error. The brand is type-only: the returned value is the same object that was
+ * passed in, and the runtime checks (plain non-array object, well-formed `error`
+ * envelope when an `error` key is present) are unchanged.
+ *
+ * @param result - The JSON object to POST as `formData.sdkMetadata`.
+ * @returns The same object, typed as a {@link DaVinciMetadataResult}.
+ *
+ * @example
+ * ```ts
+ * form.setValue('sdkMetadata', buildMetadataResult({ status: 'success' }));
+ * await next(form.input);
+ * ```
+ *
+ * @public
+ */
+export function buildMetadataResult(
+ result: Record,
+): DaVinciMetadataResult {
+ return result as DaVinciMetadataResult;
+}
+
+/**
+ * Builds the structured error envelope for a {@link MetadataCollector} result.
+ *
+ * @remarks
+ * The returned object routes the server-side connector to its client-error
+ * branch: set it as the collector's form value (via `setValue`) and resume with
+ * `next()` as usual. The error envelope is the collector's value, which the
+ * connector routes on, so a well-formed envelope resolves the flow instead of
+ * rejecting the bridge call.
+ *
+ * The envelope carries exactly `code` and `message`: extra keys inside the
+ * `error` object pass JS validation but are reconstructed (not forwarded) by
+ * the native `setError` call on both platforms, so additional context belongs
+ * in the message string, not in envelope extras.
+ *
+ * @param code - Short error code identifying the failure (e.g. `'USER_CANCELLED'`).
+ * @param message - Human-readable description of the failure.
+ * @returns The `{ error: { code, message } }` envelope to set as the
+ * {@link MetadataCollector} value.
+ *
+ * @example
+ * ```ts
+ * form.setValue(
+ * 'sdkMetadata',
+ * buildMetadataError('USER_CANCELLED', 'User dismissed the challenge.'),
+ * );
+ * await next(form.input);
+ * ```
+ *
+ * @public
+ */
+export function buildMetadataError(
+ code: string,
+ message: string,
+): DaVinciMetadataErrorResult {
+ return { error: { code, message } };
+}
+
+/**
+ * Returns a short runtime type description for an offending value.
+ *
+ * @remarks
+ * `typeof` alone reports `'object'` for both `null` and arrays, which would
+ * make malformed-value issues ambiguous — this distinguishes them.
+ *
+ * @param value - Offending value.
+ * @returns Human-readable type name (`'null'`, `'array'`, or the `typeof` result).
+ */
+function describeValueType(value: unknown): string {
+ if (value === null) {
+ return 'null';
+ }
+ if (Array.isArray(value)) {
+ return 'array';
+ }
+ return typeof value;
+}
+
+/**
+ * Validates a JS-supplied {@link MetadataCollector} result value.
+ *
+ * @remarks
+ * Mirrors the native appliers' contract (both platforms'
+ * `DaVinciCollectorValueApplier.applyMetadataValue`): `undefined`/`null` means
+ * the result is unset; a non-object, an array, or an object carrying a
+ * malformed `error` envelope is rejected; any other plain object, including an
+ * empty one, is a valid result and is forwarded unchanged, as native
+ * `setResult` does. A well-formed `{ error: { code, message } }` envelope is
+ * also valid — it routes the connector's error branch.
+ *
+ * Pure helpers in this package stay logger-free (house pattern): malformed
+ * app-supplied values surface as blocking issues carrying the offending type
+ * instead of log lines.
+ *
+ * @param key - Collector key (used in issue messages).
+ * @param value - Candidate form value.
+ * @returns A blocking issue when the value is unset or malformed; `null` when valid.
+ */
+function validateMetadataValue(
+ key: string,
+ value: DaVinciFormValue | undefined,
+): DaVinciSubmitIssue | null {
+ if (value === undefined || value === null) {
+ return {
+ code: 'METADATA_RESULT_REQUIRED',
+ message: `MetadataCollector "${key}" requires a result before the flow can resume.`,
+ key,
+ };
+ }
+
+ if (typeof value !== 'object' || Array.isArray(value)) {
+ return {
+ code: 'METADATA_RESULT_MALFORMED',
+ message: `MetadataCollector "${key}" expects a JSON object result, got ${describeValueType(value)}.`,
+ key,
+ };
+ }
+
+ const result = value as Record;
+ if ('error' in result) {
+ const envelope = result['error'];
+ if (
+ typeof envelope !== 'object' ||
+ envelope === null ||
+ Array.isArray(envelope)
+ ) {
+ return {
+ code: 'METADATA_RESULT_MALFORMED',
+ message: `MetadataCollector "${key}" error envelope must be { error: { code: string, message: string } }, got ${describeValueType(envelope)}.`,
+ key,
+ };
+ }
+ const { code, message } = envelope as Record;
+ if (typeof code !== 'string' || code.length === 0) {
+ return {
+ code: 'METADATA_RESULT_MALFORMED',
+ message: `MetadataCollector "${key}" error envelope "code" must be a non-empty string, got ${describeValueType(code)}.`,
+ key,
+ };
+ }
+ if (typeof message !== 'string') {
+ return {
+ code: 'METADATA_RESULT_MALFORMED',
+ message: `MetadataCollector "${key}" error envelope "message" must be a string, got ${describeValueType(message)}.`,
+ key,
+ };
+ }
+ }
+
+ return null;
+}
+
/**
* Builds a `next()` payload from a DaVinci node and form values.
*
@@ -423,6 +604,15 @@ export function normalizeCollectors(
* `handledCollectorTypes` are silently skipped; those not in the set emit a
* non-blocking `INTEGRATION_REQUIRED` issue and force `canSubmit: false`.
*
+ * METADATA collectors gate on the app-supplied result: an unset or `null`
+ * value blocks with `METADATA_RESULT_REQUIRED`; a non-object, array, or
+ * malformed `{ error: ... }` envelope blocks with
+ * `METADATA_RESULT_MALFORMED` (the message names the offending value type);
+ * a valid result object, including an empty one, is included in the payload
+ * as-is. This mirrors the
+ * native appliers' contract on both platforms — gating is result-set-based,
+ * independent of the collector's server `required` flag.
+ *
* @param node - Current DaVinci node. Returns a `NO_ACTIVE_CONTINUE_NODE` issue when absent.
* @param values - Form values keyed by collector key.
* @param handledCollectorTypes - Collector types the app has already
@@ -516,6 +706,21 @@ export function buildNextInput(
return;
}
+ if (collector.executionMode === 'metadata') {
+ const metadataIssue = validateMetadataValue(
+ collector.key,
+ values[collector.key],
+ );
+ if (metadataIssue) {
+ issues.push(metadataIssue);
+ return;
+ }
+ // The type guard in validateMetadataValue guarantees a plain object here
+ // (null/undefined returned a REQUIRED issue instead).
+ payload.push({ key: collector.key, value: values[collector.key] });
+ return;
+ }
+
const value = values[collector.key];
const required = readRequired(collector);
if (required && !hasManualValue(collector, value)) {
@@ -537,7 +742,9 @@ export function buildNextInput(
const blocking = issues.some(
(issue) =>
issue.code === 'REQUIRED_VALUE_MISSING' ||
- issue.code === 'INTEGRATION_REQUIRED',
+ issue.code === 'INTEGRATION_REQUIRED' ||
+ issue.code === 'METADATA_RESULT_REQUIRED' ||
+ issue.code === 'METADATA_RESULT_MALFORMED',
);
return {
@@ -557,8 +764,10 @@ export function buildNextInput(
* ```ts
* const fields = normalizeCollectors(node.collectors);
* const meta = computeFormMeta(fields);
- * if (!meta.hasManual && !meta.hasIntegrationRequired) {
+ * if (!meta.hasManual && !meta.hasIntegrationRequired && !meta.hasMetadata) {
* // All collectors are output-only or immediate — auto-submit is safe.
+ * // A METADATA collector needs an app-supplied result first, so it is
+ * // excluded here.
* }
* ```
*
@@ -577,6 +786,7 @@ export function computeFormMeta(
hasIntegrationRequired: collectors.some(
(c) => c.executionMode === 'integration_required',
),
+ hasMetadata: collectors.some((c) => c.executionMode === 'metadata'),
hasUnsupported: collectors.some((c) => c.executionMode === 'unsupported'),
};
}
diff --git a/packages/davinci/src/index.tsx b/packages/davinci/src/index.tsx
index d891cd34b..2dbf46f37 100644
--- a/packages/davinci/src/index.tsx
+++ b/packages/davinci/src/index.tsx
@@ -13,6 +13,8 @@ export { createDaVinciClient } from './davinci';
* Headless collector normalisation and submit-planning helpers.
*/
export {
+ buildMetadataError,
+ buildMetadataResult,
buildNextInput,
computeFormMeta,
normalizeCollectors,
diff --git a/packages/davinci/src/types/form.types.ts b/packages/davinci/src/types/form.types.ts
index d492dd246..fb8819d0e 100644
--- a/packages/davinci/src/types/form.types.ts
+++ b/packages/davinci/src/types/form.types.ts
@@ -15,6 +15,9 @@ import type {
ImageCollector,
IntegrationCollector,
LabelCollector,
+ DaVinciMetadataErrorResult,
+ DaVinciMetadataResult,
+ MetadataCollector,
MultiSelectCollector,
PasswordCollector,
PhoneNumberCollector,
@@ -46,6 +49,10 @@ import type {
* package performs its action and then calls `next()`.
* No base-registry collector maps to this mode in 2.2.0 —
* plugin collectors registered by future packages will.
+ * - `metadata` — SDK Integrator connector pause/resume (METADATA). The
+ * flow pauses with an opaque payload; the app performs
+ * the on-device work and sets a result value before
+ * calling `next()`.
* - `unsupported` — collector type not recognised by the bridge or any
* registered integration; skipped in the submit payload
*
@@ -59,6 +66,7 @@ export type DaVinciExecutionMode =
| 'output_only'
| 'immediate'
| 'integration_required'
+ | 'metadata'
| 'unsupported';
/**
@@ -77,6 +85,7 @@ export type DaVinciExecutionMode =
* - `polling` — async out-of-band polling status (POLLING), driven by `pollStatus`
* - `qrCode` — display-only QR code image (QR_CODE)
* - `image` — display-only image (IMAGE)
+ * - `metadata` — SDK Integrator connector pause/resume (METADATA)
* - `flow` — immediate-submit action (SUBMIT_BUTTON, ACTION, FLOW_BUTTON, FLOW_LINK)
* - `integration` — handled by an external integration package (future collectors)
* - `unknown` — unrecognised type
@@ -95,6 +104,7 @@ export type DaVinciFieldKind =
| 'polling'
| 'qrCode'
| 'image'
+ | 'metadata'
| 'flow'
| 'integration'
| 'unknown';
@@ -115,7 +125,9 @@ type DaVinciNormalizedMetadata = {
*
* @remarks
* `true` only when `executionMode === 'manual'`; `false` for `output_only`,
- * `immediate`, `integration_required`, and `unsupported`.
+ * `immediate`, `integration_required`, `metadata`, and `unsupported`.
+ * A `metadata` collector is not rendered as user input, but submission is
+ * still blocked until the app supplies a result.
* Integration-required collectors are handled by an external package, not by
* direct user input into the form.
*/
@@ -152,6 +164,7 @@ export type DaVinciNormalizedCollector =
| (PollingCollector & DaVinciNormalizedMetadata<'polling'>)
| (QRCodeCollector & DaVinciNormalizedMetadata<'qrCode'>)
| (ImageCollector & DaVinciNormalizedMetadata<'image'>)
+ | (MetadataCollector & DaVinciNormalizedMetadata<'metadata'>)
| (IntegrationCollector & DaVinciNormalizedMetadata<'integration'>)
| (IntegrationCollector & DaVinciNormalizedMetadata<'unknown'>);
@@ -166,6 +179,8 @@ export type DaVinciFormValue =
| boolean // SINGLE_CHECKBOX
| { countryCode: string; phoneNumber: string; extension?: string } // PHONE_NUMBER
| { type: string; id?: string; description?: string } // DEVICE_AUTHENTICATION
+ | DaVinciMetadataResult // METADATA success result (branded; see buildMetadataResult)
+ | DaVinciMetadataErrorResult // METADATA error envelope (see buildMetadataError)
| null;
/**
@@ -178,13 +193,27 @@ export type DaVinciFormValues = Record;
/**
* Stable issue code surfaced by the collector submit helper.
*
+ * @remarks
+ * Blocking codes (they force `canSubmit: false`):
+ * `REQUIRED_VALUE_MISSING` — a required manual collector has no value;
+ * `INTEGRATION_REQUIRED` — an unhandled `integration_required` collector is
+ * present; `METADATA_RESULT_REQUIRED` — a {@link MetadataCollector} has no
+ * result set; `METADATA_RESULT_MALFORMED` — the supplied METADATA value is a
+ * non-object, array, or a malformed `{ error: ... }` envelope
+ * (the message names the offending value type). `UNSUPPORTED_COLLECTOR` is
+ * non-blocking: an unknown-type collector is skipped in the payload.
+ * `NO_ACTIVE_CONTINUE_NODE` blocks via the absence of a submittable node
+ * rather than the blocking set.
+ *
* @public
*/
export type DaVinciSubmitIssueCode =
| 'NO_ACTIVE_CONTINUE_NODE'
| 'REQUIRED_VALUE_MISSING'
| 'UNSUPPORTED_COLLECTOR'
- | 'INTEGRATION_REQUIRED';
+ | 'INTEGRATION_REQUIRED'
+ | 'METADATA_RESULT_REQUIRED'
+ | 'METADATA_RESULT_MALFORMED';
/**
* Helper issue record for collector submit planning.
@@ -240,6 +269,11 @@ export type DaVinciFormMeta = {
* True when at least one collector requires an external package integration.
*/
hasIntegrationRequired: boolean;
+ /**
+ * True when at least one {@link MetadataCollector} (SDK Integrator connector
+ * pause/resume) is present.
+ */
+ hasMetadata: boolean;
/** True when at least one unsupported (unknown-type) collector is present. */
hasUnsupported: boolean;
};
diff --git a/packages/davinci/src/types/node.types.ts b/packages/davinci/src/types/node.types.ts
index e4dd8fe2a..e797029ea 100644
--- a/packages/davinci/src/types/node.types.ts
+++ b/packages/davinci/src/types/node.types.ts
@@ -586,6 +586,108 @@ export type ImageCollector = {
raw?: Record;
};
+/**
+ * SDK Integrator connector pause/resume collector — a DaVinci flow pauses and
+ * hands the app an opaque payload; the app performs the on-device work and
+ * supplies a result before the flow can resume.
+ *
+ * @remarks
+ * Field names and defaults mirror the native 2.2 `MetadataCollector` exactly
+ * (iOS `Davinci/Davinci/collector/MetadataCollector.swift`, Android
+ * `davinci/src/main/kotlin/com/pingidentity/davinci/collector/MetadataCollector.kt`):
+ * the server field is `{ type: "METADATA", key: "sdkMetadata", payload: