Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
5005a77
feat: run the bundled SDK Core in a hidden WebView inside <Formbricks…
pandeymangg Dec 4, 2026
5368054
Merge the React Native SDK Core shell [ENG-7737]
pandeymangg Dec 4, 2026
9ba10c3
feat: download SDK Core, check its hash and fall back to the bundled …
pandeymangg Dec 4, 2026
53c4397
Merge the React Native SDK Core Loader [ENG-7744]
pandeymangg Dec 4, 2026
b4f60a2
fix: log a failed command once, since SDK Core already logs it
pandeymangg Dec 4, 2026
68d08bb
fix: target the survey WebView in the golden journey, and strip trail…
pandeymangg Dec 4, 2026
130286e
fix: end stuck surveys and calls, and pass setAppearance to SDK Core
pandeymangg Dec 4, 2026
e65c6ef
fix: address review comments on the SDK Core shell
pandeymangg Dec 4, 2026
ca1c021
chore: re-record the bundled SDK Core 0.0.1 (0798def8)
pandeymangg Dec 4, 2026
3c663c4
chore: re-record the bundled SDK Core 0.0.1 (12e24a1d)
pandeymangg Dec 4, 2026
ab31224
fix: clear the local Embedded Data on a user change before SDK Core f…
pandeymangg Dec 4, 2026
cd45d61
fix: never reject a public method when sending a command throws
pandeymangg Dec 4, 2026
4b914bc
fix: refuse a bundled SDK Core download redirected to another origin,…
pandeymangg Dec 4, 2026
0368640
fix: keep the first app URL's origin while SDK Core runs, and take a …
pandeymangg Dec 4, 2026
7be20b5
chore: re-record the bundled SDK Core 0.0.1 (fca18124)
pandeymangg Dec 4, 2026
5a18671
fix: download SDK Core only from an https app URL, or http on the dev…
pandeymangg Dec 4, 2026
fe93da7
fix: record and check the formbricks commit the bundled SDK Core was …
pandeymangg Dec 4, 2026
ba86bfc
fix: send every link from the survey page through the shell's own han…
pandeymangg Dec 4, 2026
d70f77d
chore: re-record the bundled SDK Core 0.0.1 (ce90e9b9) with its sourc…
pandeymangg Dec 4, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,12 @@ jobs:
"$test"
done

# The SDK ships this file and runs it; it must be exactly what was published.
- name: Check the bundled SDK Core against its recorded sha256
run: |
scripts/sdk-core/update-bundled-sdk-core.sh --check
scripts/sdk-core/test/update-bundled-sdk-core.test.sh

- name: Upload coverage for Sonar
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
Expand Down
11 changes: 10 additions & 1 deletion .github/workflows/e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ name: E2E
# Cloudflare quick tunnel (e2e/tunnel) and the two jobs, side by side (neither needs the other), swap run
# artifacts: the tunnel URL one way, the journey result the other. A job's outputs only publish
# when it ends, which is why the hand-off uses artifacts.
# - Both platforms also run e2e/react-native/run-sdk-core.sh: SDK Core's conformance script in the
# SDK's real hidden WebView, against a test server the spec starts itself (no Formbricks server).
on:
workflow_call:
inputs:
Expand Down Expand Up @@ -136,7 +138,10 @@ jobs:
force-avd-creation: true
emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none -accel on -no-snapshot
disable-animations: true
script: e2e/react-native/run-journey.sh android test
# Then SDK Core's conformance script in the SDK's real hidden WebView.
script: |
e2e/react-native/run-journey.sh android test
e2e/react-native/run-sdk-core.sh android

- name: Assert the response through the V1 API
run: e2e/server/assert-response.sh
Expand Down Expand Up @@ -318,6 +323,10 @@ jobs:
- name: Build the playground and the Detox framework
run: e2e/react-native/run-journey.sh ios build

# Needs no server, so it runs while the server job boots.
- name: Run SDK Core's conformance script in the SDK's hidden WebView
run: e2e/react-native/run-sdk-core.sh ios

- name: Wait for the server's tunnel URL
id: server
env:
Expand Down
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
## Project Structure & Module Organization
This repository is a `pnpm` workspace with two main packages:

- `packages/react-native`: the published SDK (`@formbricks/react-native`). Source lives in `src/`, grouped by domain under `src/lib/`, with React components in `src/components/` and shared types in `src/types/`.
- `packages/react-native`: the published SDK (`@formbricks/react-native`). It is a shell around SDK Core (see `GLOSSARY.md`): the shell is `src/sdk-core/`, React components are in `src/components/`, the rest of `src/lib/` is local state (appearance, Embedded Data, logging), and the bundled SDK Core is `assets/sdk-core/`. Targeting rules belong in SDK Core, in the formbricks monorepo, not here.
- `apps/playground`: an Expo app for manual testing and integration checks. App code is in `src/`, with static assets in `assets/`.

GitHub Actions run every check from `.github/workflows/ci.yml`; its `PR Check Summary` job is the only required check. `release.yml` publishes.
Expand All @@ -24,6 +24,8 @@ Run commands from the repository root unless package-scoped work is needed.
- `pnpm api:update`: regenerate `packages/react-native/etc/react-native.api.md`. Commit it whenever the public API changes.
- `pnpm package-check`: after a build, run publint, attw, and install the `npm pack` tarball into a scratch consumer.
- `pnpm --filter playground ios` / `pnpm --filter playground android`: launch the Expo playground on a device target.
- `e2e/react-native/run-sdk-core.sh android|ios`: run SDK Core's conformance script in the SDK's real hidden WebView, on the playground `e2e/react-native/run-journey.sh <platform> build` built.
- `scripts/sdk-core/update-bundled-sdk-core.sh --commit <sha> [manifest-url]` / `--check`: update the bundled SDK Core from a server's manifest, checked against the formbricks/formbricks commit that records it; or check it against its recorded sha256 and commit.

## Coding Style & Naming Conventions
Use TypeScript with strict compiler settings. Biome is the formatter and linter; run `pnpm format` before large refactors. The repo uses spaces for indentation, double quotes, and semicolons.
Expand Down
24 changes: 16 additions & 8 deletions GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Terms the React Native SDK (`packages/react-native`) uses, grouped by area. Use

- **Workspace**: the Formbricks space the app's surveys, action classes and styling belong to, identified by `workspaceId` (`TWorkspace`, `src/lib/workspace/`). Replaces the older term _environment_: `environmentId` is a deprecated alias that still works, and stored configs that use it are migrated.
- **App URL**: the Formbricks instance the SDK talks to (`appUrl`), passed to `setup()` with the workspace ID.
- **Config**: the SDK's persisted state (`TConfig`, `RNConfig`): workspace ID, app URL, workspace state, user state and filtered surveys, stored in AsyncStorage.
- **Saved data**: the one JSON string SDK Core saves (workspace ID, app URL, workspace state, user state and filtered surveys), stored in AsyncStorage under `formbricks-react-native`. The shell only stores it. Formerly _config_.
- **Workspace state**: the workspace's surveys, action classes and settings as fetched from the server, cached with an expiry (30 minutes) and refetched when it lapses.

## Users
Expand All @@ -15,22 +15,30 @@ Terms the React Native SDK (`packages/react-native`) uses, grouped by area. Use
- **Attributes**: key/value facts about the user (`setAttribute()`, `setAttributes()`, `setLanguage()`), sent to the server and used for targeting.
- **User state**: what the server knows about the user (`TUserState`): user ID, segments, displays, responses, last display time and language.
- **Segment**: a server-defined group of users; the SDK only receives the IDs of the segments a user belongs to and never evaluates segment filters itself.
- **Interaction refresh**: refetching a user's segments after a survey display, response or finish, gated per survey by `interactionRefresh` (`src/lib/user/interaction-refresh.ts`).
- **Interaction refresh**: refetching a user's segments after a survey display, response or finish, gated per survey by `interactionRefresh` (done by SDK Core).

## Surveys

- **Action**: a named event the app reports with `track(name)`; it can trigger a survey.
- **Action class**: the workspace's definition of an action (`TActionClass`), either `code` (tracked from the app) or `noCode`.
- **Trigger**: an action class a survey listens for (`survey.triggers`).
- **Display option**: how often a survey may show to one user (`displayOnce`, `displayMultiple`, `displaySome`, `respondMultiple`).
- **Filtered surveys**: the surveys this user is eligible for after display options, recontact days and segments are applied (`filterSurveys`).
- **Filtered surveys**: the surveys this user is eligible for after display options, recontact days and segments are applied (by SDK Core).
- **Display**: one time a survey was shown to a user.
- **Response**: a user's answers to a survey.
- **Embedded Data**: app context attached to responses with `setEmbeddedData()` / `clearEmbeddedData()`. Held in memory, synchronous and never queued. A survey takes a snapshot of it when it opens, so later changes reach only surveys opened afterwards; values land only on fields the survey declares as ingested.
- **Survey web view**: the WebView that renders a survey with the Formbricks renderer (`src/components/survey-web-view.tsx`), mounted by the `<Formbricks />` component.
- **Survey web view**: the WebView that renders a survey SDK Core asked to show, with the Formbricks renderer (`src/components/survey-web-view.tsx`), mounted by the `<Formbricks />` component.
- **Appearance**: how surveys render, `light`, `dark` or `system` (`setAppearance()`); kept in memory only, never sent to the server.

## Internals

- **Command queue**: runs the public async methods (`track`, `setUserId`, `setAttributes`, `logout`, …) one at a time, in order (`CommandQueue`).
- **Update queue**: debounces user ID and attribute updates into one request to the server (`UpdateQueue`).
## SDK Core

- **SDK Core**: the one TypeScript package (in the formbricks monorepo) with all the targeting rules every Formbricks SDK shares: setup and sync, users and the update queue, which survey shows and when. This SDK runs its mobile build. _Avoid_: brain, mobile core.
- **Shell**: this SDK's own part (`src/sdk-core/`): it runs SDK Core and does only what SDK Core asks: store a string, make an HTTP call to the app URL's origin, show a survey, write a log line.
- **Engine**: where SDK Core runs: a hidden 0×0 WebView inside `<Formbricks />`, on a blank page with the CSP `default-src 'none'`. Each mount starts SDK Core afresh from the saved data.
- **Bridge contract**: the JSON messages SDK Core and the shell send each other (`start`, `command`, `http.request`, `survey.show`, …).
- **Bundled copy**: the SDK Core file shipped inside this SDK (`packages/react-native/assets/sdk-core/mobile.umd.cjs`), with the `{version, sha256}` it was published with and the formbricks/formbricks `commit` that records the same copy. `scripts/sdk-core/update-bundled-sdk-core.sh` updates it and CI checks it.
- **Manifest**: the server's list of SDK Core copies, with version and SHA-256 (`<appUrl>/js/sdk/mobile.json`). A server from before 6.3 has none.
- **Stored copy**: the last downloaded SDK Core file that passed the hash check, kept in AsyncStorage per app URL.
- **Loader**: the part of the shell that picks, downloads and checks SDK Core copies (`src/sdk-core/loader.ts`). Anything it can't use falls back to the bundled copy.
- **Protocol**: SDK Core's major version; the shell runs only copies of its own.
- **Conformance script**: a fake SDK Core every shell runs in its real engine to prove it follows the bridge contract (`assets/sdk-core/conformance.umd.cjs`; never published).
15 changes: 6 additions & 9 deletions apps/playground/e2e/golden-journey.e2e.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,9 @@ const TRACK_RETRY_INTERVAL_MS = 10_000;
const STEP_TIMEOUT_MS = 30_000;
const RESPONSE_TIMEOUT_MS = 60_000;

// The SDK's WebView is the only one in the app, so `web` needs no matcher.
const webElement = (matcher) => web.element(matcher);
// The survey's WebView, by its testID: SDK Core runs in a second, 0×0 WebView.
const SURVEY_WEBVIEW = by.id("formbricks-survey-webview");
const webElement = (matcher) => web(SURVEY_WEBVIEW).element(matcher);

const expectStatus = (text) =>
waitFor(element(by.id("status")))
Expand Down Expand Up @@ -93,14 +94,12 @@ const read = async (matcher, fn, args = []) => {
* - `typeInto` types into a survey text field. Android: Espresso-Web's key events. iOS: Detox's
* web typing left the field empty, so the value is set the way the browser does it and an input
* event follows, which is what the renderer listens to.
* - `webViewClass`: the native class of the survey's WebView.
*/
const PLATFORMS = {
android: {
afterFill: async () => {},
press: (matcher) => webElement(matcher).tap(),
typeInto: (matcher, text) => webElement(matcher).replaceText(text),
webViewClass: "android.webkit.WebView",
},
ios: {
afterFill: (testID) => element(by.id(testID)).tapReturnKey(),
Expand All @@ -116,7 +115,6 @@ const PLATFORMS = {
}`,
[text],
),
webViewClass: "WKWebView",
},
};

Expand All @@ -133,12 +131,11 @@ const press = (matcher) => platform().press(matcher);
const typeInto = (matcher, text) => platform().typeInto(matcher, text);

/**
* Passes only once no WebView is on screen (the survey's is the only one). A native query, so a
* Passes only once the survey's WebView is gone. A native query, so a
* failed web query is never mistaken for a closed survey, and errors such as the app being gone
* propagate.
*/
const surveyIsClosed = () =>
expect(element(by.type(platform().webViewClass))).not.toExist();
const surveyIsClosed = () => expect(element(SURVEY_WEBVIEW)).not.toExist();

const SETTLE_MS = 2_000;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
Expand All @@ -148,7 +145,7 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
* WebView is still being created can take the app down on a cold Android emulator.
*/
const surveyIsOpen = async () => {
await expect(element(by.type(platform().webViewClass))).toExist();
await expect(element(SURVEY_WEBVIEW)).toExist();
await sleep(SETTLE_MS);
await expect(webElement(by.web.xpath(NPS_9))).toExist();
};
Expand Down
2 changes: 1 addition & 1 deletion apps/playground/e2e/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Jest runs only the Detox journey; plain CommonJS, so no transform.
// Jest runs the Detox specs (the golden journey, SDK Core conformance); plain CommonJS, no transform.
/** @type {import('jest').Config} */
module.exports = {
rootDir: "..",
Expand Down
63 changes: 63 additions & 0 deletions apps/playground/e2e/sdk-core-conformance.e2e.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* SDK Core's conformance script in the SDK's real hidden WebView (the playground's conformance
* screen, src/sdk-core-conformance.tsx). This file is the script's test server: the app reaches it
* at http://127.0.0.1:3457 and, as the second origin the shell must refuse, http://localhost:3457.
* Android reaches the host through `adb reverse`. No Formbricks server is needed.
*/
const http = require("node:http");
const { by, device, element, waitFor } = require("detox");

const PORT = 3457;
const OTHER_ORIGIN = `http://localhost:${PORT}`;

/** What the script's README asks of the server. */
const answer = (request, body, response) => {
if (request.method === "GET" && request.url === "/conformance/config") {
response.writeHead(200, { "Content-Type": "application/json" });
response.end(JSON.stringify({ otherOrigin: OTHER_ORIGIN }));
} else if (request.method === "POST" && request.url === "/conformance/echo") {
response.writeHead(201, {
"X-Conformance": request.headers["x-conformance"] ?? "",
});
response.end(body);
} else {
response.writeHead(404);
response.end();
}
};

let server;

describe("SDK Core conformance", () => {
beforeAll(async () => {
server = http.createServer((request, response) => {
const chunks = [];
request.on("data", (chunk) => chunks.push(chunk));
request.on("end", () => answer(request, Buffer.concat(chunks), response));
});
await new Promise((resolve) => server.listen(PORT, resolve));
await device.launchApp({ newInstance: true, delete: true });
if (device.getPlatform() === "android") await device.reverseTcpPort(PORT);
// SDK Core keeps timers busy, so Detox would wait for "idle" forever.
await device.disableSynchronization();
});

afterAll(async () => {
await new Promise((resolve) => server.close(resolve));
});

it("passes every check in the SDK's hidden WebView", async () => {
await waitFor(element(by.id("sdk-core-conformance-button")))
.toBeVisible()
.whileElement(by.id("playground-scroll"))
.scroll(300, "down");
await element(by.id("sdk-core-conformance-button")).tap();

const result = element(by.id("sdk-core-conformance-result"));
await waitFor(result).not.toHaveText("running").withTimeout(180_000);
const { text } = await result.getAttributes();
const locale = await element(by.id("hermes-intl-locale")).getAttributes();
console.log(`${text}; ${locale.text}`);
if (text !== "passed") throw new Error(`SDK Core conformance ${text}`);
});
});
17 changes: 17 additions & 0 deletions apps/playground/metro.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Expo's defaults, plus one name for the SDK's conformance build (packages/react-native/
// dist-conformance, made by its `build`), which only the SDK Core conformance screen imports.
const path = require("node:path");
const { getDefaultConfig } = require("expo/metro-config");

const config = getDefaultConfig(__dirname);
const conformanceBuild = path.resolve(
__dirname,
"../../packages/react-native/dist-conformance/index.js",
);
const resolveRequest = config.resolver.resolveRequest;
config.resolver.resolveRequest = (context, name, platform) =>
name === "@formbricks/react-native-conformance"
? { type: "sourceFile", filePath: conformanceBuild }
: (resolveRequest ?? context.resolveRequest)(context, name, platform);

module.exports = config;
4 changes: 2 additions & 2 deletions apps/playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
"main": "index.ts",
"scripts": {
"dev": "expo start --reset-cache",
"android": "expo start --android",
"ios": "expo start --ios",
"android": "expo run:android",
"ios": "expo run:ios",
"clean": "rimraf .turbo node_modules .expo",
"build": "expo export --no-bytecode",
"check-types": "tsc --noEmit",
Expand Down
12 changes: 12 additions & 0 deletions apps/playground/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import {
View,
} from "react-native";

import { SdkCoreConformance } from "./sdk-core-conformance";

LogBox.ignoreAllLogs();

type SdkConfig = { appUrl: string; workspaceId: string };
Expand All @@ -45,6 +47,7 @@ export default function App(): JSX.Element {
const [attributeValue, setAttributeValue] = useState("pro");
const [action, setAction] = useState("qa-action");
const [status, setStatus] = useState("Not set up");
const [conformance, setConformance] = useState(false);

// The status line tells a person (and the E2E journey) that a call has returned.
const run = (label: string, call: () => Promise<void>): void => {
Expand All @@ -59,6 +62,8 @@ export default function App(): JSX.Element {

const inputStyle = [styles.input, { color: textColor }];

if (conformance) return <SdkCoreConformance />;

return (
<View
style={[
Expand Down Expand Up @@ -232,6 +237,13 @@ export default function App(): JSX.Element {
title="Set Language (de)"
onPress={() => run("setLanguage(de)", () => setLanguage("de"))}
/>

{/* e2e/sdk-core-conformance.e2e.js; it clears the SDK's saved data. */}
<Button
title="Run the SDK Core conformance script"
testID="sdk-core-conformance-button"
onPress={() => setConformance(true)}
/>
</ScrollView>

<StatusBar style="auto" />
Expand Down
5 changes: 5 additions & 0 deletions apps/playground/src/react-native-conformance.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// The SDK's conformance build (see metro.config.js): the same API as the published package.
declare module "@formbricks/react-native-conformance" {
export * from "@formbricks/react-native";
export { default } from "@formbricks/react-native";
}
Loading
Loading