Compare commits

..

8 Commits

Author SHA1 Message Date
Matti Nannt
d4f155b6bc chore: update storybook app dependencies (#5195) 2025-04-01 19:39:45 +02:00
Matti Nannt
da001834f5 chore: remove unused tailwind import from mobile SDK webviews (#5198) 2025-04-01 12:59:57 +00:00
Anshuman Pandey
f54352dd82 chore: changes storage cache to 5 minutes (#5196) 2025-04-01 07:25:17 +00:00
Matti Nannt
0fba0fae73 chore: remove posthog provider from top layout (#5169) 2025-04-01 06:24:17 +00:00
Anshuman Pandey
406ec88515 fix: adding back hidden fields for backwards compatibility (#5163) 2025-04-01 05:20:30 +00:00
Matti Nannt
b97957d166 chore(infra): increase ressource limits to 1 cpu & 1Gi mem (#5192) 2025-04-01 04:50:55 +00:00
Matti Nannt
655ad6b9e0 docs: fix response client api endpoint is missing environmentId (#5161) 2025-03-31 12:14:44 +02:00
Anshuman Pandey
f5ce42fc2d feat: api for uploading contacts in bulk (#5053)
Co-authored-by: Piyush Gupta <piyushguptaa2z123@gmail.com>
2025-03-30 07:44:17 +00:00
24 changed files with 1091 additions and 796 deletions

View File

@@ -11,30 +11,30 @@
"clean": "rimraf .turbo node_modules dist storybook-static"
},
"dependencies": {
"eslint-plugin-react-refresh": "0.4.16",
"react": "19.0.0",
"react-dom": "19.0.0"
"eslint-plugin-react-refresh": "0.4.19",
"react": "19.1.0",
"react-dom": "19.1.0"
},
"devDependencies": {
"@chromatic-com/storybook": "3.2.2",
"@chromatic-com/storybook": "3.2.6",
"@formbricks/config-typescript": "workspace:*",
"@storybook/addon-a11y": "8.4.7",
"@storybook/addon-essentials": "8.4.7",
"@storybook/addon-interactions": "8.4.7",
"@storybook/addon-links": "8.4.7",
"@storybook/addon-onboarding": "8.4.7",
"@storybook/blocks": "8.4.7",
"@storybook/react": "8.4.7",
"@storybook/react-vite": "8.4.7",
"@storybook/test": "8.4.7",
"@typescript-eslint/eslint-plugin": "8.18.0",
"@typescript-eslint/parser": "8.18.0",
"@storybook/addon-a11y": "8.6.11",
"@storybook/addon-essentials": "8.6.11",
"@storybook/addon-interactions": "8.6.11",
"@storybook/addon-links": "8.6.11",
"@storybook/addon-onboarding": "8.6.11",
"@storybook/blocks": "8.6.11",
"@storybook/react": "8.6.11",
"@storybook/react-vite": "8.6.11",
"@storybook/test": "8.6.11",
"@typescript-eslint/eslint-plugin": "8.29.0",
"@typescript-eslint/parser": "8.29.0",
"@vitejs/plugin-react": "4.3.4",
"esbuild": "0.25.1",
"eslint-plugin-storybook": "0.11.1",
"esbuild": "0.25.2",
"eslint-plugin-storybook": "0.12.0",
"prop-types": "15.8.1",
"storybook": "8.4.7",
"tsup": "8.3.5",
"vite": "6.0.12"
"storybook": "8.6.11",
"tsup": "8.4.0",
"vite": "6.2.4"
}
}

View File

@@ -47,12 +47,6 @@ vi.mock("@/app/intercom/IntercomClientWrapper", () => ({
vi.mock("@/modules/ui/components/no-mobile-overlay", () => ({
NoMobileOverlay: () => <div data-testid="no-mobile-overlay" />,
}));
vi.mock("@/modules/ui/components/post-hog-client", () => ({
PHProvider: ({ children }: { children: React.ReactNode }) => (
<div data-testid="ph-provider">{children}</div>
),
PostHogPageview: () => <div data-testid="ph-pageview" />,
}));
vi.mock("@/modules/ui/components/toaster-client", () => ({
ToasterClient: () => <div data-testid="toaster-client" />,
}));
@@ -74,8 +68,6 @@ describe("(app) AppLayout", () => {
render(element);
expect(screen.getByTestId("no-mobile-overlay")).toBeInTheDocument();
expect(screen.getByTestId("ph-pageview")).toBeInTheDocument();
expect(screen.getByTestId("ph-provider")).toBeInTheDocument();
expect(screen.getByTestId("mock-intercom-wrapper")).toBeInTheDocument();
expect(screen.getByTestId("toaster-client")).toBeInTheDocument();
expect(screen.getByTestId("child-content")).toHaveTextContent("Hello from children");

View File

@@ -105,7 +105,6 @@ describe("RootLayout", () => {
console.log("vercel", process.env.VERCEL);
expect(screen.getByTestId("speed-insights")).toBeInTheDocument();
expect(screen.getByTestId("ph-provider")).toBeInTheDocument();
expect(screen.getByTestId("tolgee-next-provider")).toBeInTheDocument();
expect(screen.getByTestId("sentry-provider")).toBeInTheDocument();
expect(screen.getByTestId("child")).toHaveTextContent("Child Content");

View File

@@ -1,5 +1,4 @@
import { SentryProvider } from "@/app/sentry/SentryProvider";
import { PHProvider } from "@/modules/ui/components/post-hog-client";
import { TolgeeNextProvider } from "@/tolgee/client";
import { getLocale } from "@/tolgee/language";
import { getTolgee } from "@/tolgee/server";
@@ -7,7 +6,7 @@ import { TolgeeStaticData } from "@tolgee/react";
import { SpeedInsights } from "@vercel/speed-insights/next";
import { Metadata } from "next";
import React from "react";
import { IS_POSTHOG_CONFIGURED, SENTRY_DSN } from "@formbricks/lib/constants";
import { SENTRY_DSN } from "@formbricks/lib/constants";
import "../modules/ui/globals.css";
export const metadata: Metadata = {
@@ -29,11 +28,9 @@ const RootLayout = async ({ children }: { children: React.ReactNode }) => {
<body className="flex h-dvh flex-col transition-all ease-in-out">
{process.env.VERCEL === "1" && <SpeedInsights sampleRate={0.1} />}
<SentryProvider sentryDsn={SENTRY_DSN}>
<PHProvider posthogEnabled={IS_POSTHOG_CONFIGURED}>
<TolgeeNextProvider language={locale} staticData={staticData as unknown as TolgeeStaticData}>
{children}
</TolgeeNextProvider>
</PHProvider>
<TolgeeNextProvider language={locale} staticData={staticData as unknown as TolgeeStaticData}>
{children}
</TolgeeNextProvider>
</SentryProvider>
</body>
</html>

View File

@@ -19,7 +19,7 @@ export const getFile = async (
headers: {
"Content-Type": metaData.contentType,
"Content-Disposition": "attachment",
"Cache-Control": "public, max-age=1200, s-maxage=1200, stale-while-revalidate=300",
"Cache-Control": "public, max-age=300, s-maxage=300, stale-while-revalidate=300",
Vary: "Accept-Encoding",
},
});
@@ -35,10 +35,7 @@ export const getFile = async (
status: 302,
headers: {
Location: signedUrl,
"Cache-Control":
accessType === "public"
? `public, max-age=3600, s-maxage=3600, stale-while-revalidate=300`
: `public, max-age=600, s-maxage=3600, stale-while-revalidate=300`,
"Cache-Control": "public, max-age=300, s-maxage=300, stale-while-revalidate=300",
},
});
} catch (error: unknown) {

View File

@@ -229,52 +229,51 @@ export const upsertBulkContacts = async (
try {
// Execute everything in ONE transaction
await prisma.$transaction(
async (tx) => {
const attributeKeyMap = existingAttributeKeys.reduce<Record<string, string>>((acc, keyObj) => {
acc[keyObj.key] = keyObj.id;
return acc;
}, {});
await prisma.$transaction(async (tx) => {
const attributeKeyMap = existingAttributeKeys.reduce<Record<string, string>>((acc, keyObj) => {
acc[keyObj.key] = keyObj.id;
return acc;
}, {});
// Check for missing attribute keys and create them if needed.
const missingKeysMap = new Map<string, { key: string; name: string }>();
const attributeKeyNameUpdates = new Map<string, { key: string; name: string }>();
// Check for missing attribute keys and create them if needed.
const missingKeysMap = new Map<string, { key: string; name: string }>();
const attributeKeyNameUpdates = new Map<string, { key: string; name: string }>();
for (const contact of filteredContacts) {
for (const attr of contact.attributes) {
if (!attributeKeyMap[attr.attributeKey.key]) {
missingKeysMap.set(attr.attributeKey.key, attr.attributeKey);
} else {
// Check if the name has changed for existing attribute keys
const existingKey = existingAttributeKeys.find((ak) => ak.key === attr.attributeKey.key);
if (existingKey && existingKey.name !== attr.attributeKey.name) {
attributeKeyNameUpdates.set(attr.attributeKey.key, attr.attributeKey);
}
for (const contact of filteredContacts) {
for (const attr of contact.attributes) {
if (!attributeKeyMap[attr.attributeKey.key]) {
missingKeysMap.set(attr.attributeKey.key, attr.attributeKey);
} else {
// Check if the name has changed for existing attribute keys
const existingKey = existingAttributeKeys.find((ak) => ak.key === attr.attributeKey.key);
if (existingKey && existingKey.name !== attr.attributeKey.name) {
attributeKeyNameUpdates.set(attr.attributeKey.key, attr.attributeKey);
}
}
}
}
// Handle both missing keys and name updates in a single batch operation
const keysToUpsert = new Map<string, { key: string; name: string }>();
// Handle both missing keys and name updates in a single batch operation
const keysToUpsert = new Map<string, { key: string; name: string }>();
// Collect all keys that need to be created or updated
for (const [key, value] of missingKeysMap) {
keysToUpsert.set(key, value);
}
// Collect all keys that need to be created or updated
for (const [key, value] of missingKeysMap) {
keysToUpsert.set(key, value);
}
for (const [key, value] of attributeKeyNameUpdates) {
keysToUpsert.set(key, value);
}
for (const [key, value] of attributeKeyNameUpdates) {
keysToUpsert.set(key, value);
}
if (keysToUpsert.size > 0) {
const keysArray = Array.from(keysToUpsert.values());
const BATCH_SIZE = 10000;
if (keysToUpsert.size > 0) {
const keysArray = Array.from(keysToUpsert.values());
const BATCH_SIZE = 10000;
for (let i = 0; i < keysArray.length; i += BATCH_SIZE) {
const batch = keysArray.slice(i, i + BATCH_SIZE);
for (let i = 0; i < keysArray.length; i += BATCH_SIZE) {
const batch = keysArray.slice(i, i + BATCH_SIZE);
// Use raw query to perform upsert
const upsertedKeys = await tx.$queryRaw<{ id: string; key: string }[]>`
// Use raw query to perform upsert
const upsertedKeys = await tx.$queryRaw<{ id: string; key: string }[]>`
INSERT INTO "ContactAttributeKey" ("id", "key", "name", "environmentId", "created_at", "updated_at")
SELECT
unnest(${Prisma.sql`ARRAY[${batch.map(() => createId())}]`}),
@@ -290,59 +289,59 @@ export const upsertBulkContacts = async (
RETURNING "id", "key"
`;
// Update attribute key map with upserted keys
for (const key of upsertedKeys) {
attributeKeyMap[key.key] = key.id;
}
// Update attribute key map with upserted keys
for (const key of upsertedKeys) {
attributeKeyMap[key.key] = key.id;
}
}
}
// Create new contacts -- should be at most 1000, no need to batch
const newContacts = contactsToCreate.map(() => ({
// Create new contacts -- should be at most 1000, no need to batch
const newContacts = contactsToCreate.map(() => ({
id: createId(),
environmentId,
}));
if (newContacts.length > 0) {
await tx.contact.createMany({
data: newContacts,
});
}
// Prepare attributes for both new and existing contacts
const attributesUpsertForCreatedUsers = contactsToCreate.flatMap((contact, idx) =>
contact.attributes.map((attr) => ({
id: createId(),
environmentId,
}));
contactId: newContacts[idx].id,
attributeKeyId: attributeKeyMap[attr.attributeKey.key],
value: attr.value,
createdAt: new Date(),
updatedAt: new Date(),
}))
);
if (newContacts.length > 0) {
await tx.contact.createMany({
data: newContacts,
});
}
const attributesUpsertForExistingUsers = contactsToUpdate.flatMap((contact) =>
contact.attributes.map((attr) => ({
id: attr.id,
contactId: contact.contactId,
attributeKeyId: attributeKeyMap[attr.attributeKey.key],
value: attr.value,
createdAt: attr.createdAt,
updatedAt: new Date(),
}))
);
// Prepare attributes for both new and existing contacts
const attributesUpsertForCreatedUsers = contactsToCreate.flatMap((contact, idx) =>
contact.attributes.map((attr) => ({
id: createId(),
contactId: newContacts[idx].id,
attributeKeyId: attributeKeyMap[attr.attributeKey.key],
value: attr.value,
createdAt: new Date(),
updatedAt: new Date(),
}))
);
const attributesToUpsert = [...attributesUpsertForCreatedUsers, ...attributesUpsertForExistingUsers];
const attributesUpsertForExistingUsers = contactsToUpdate.flatMap((contact) =>
contact.attributes.map((attr) => ({
id: attr.id,
contactId: contact.contactId,
attributeKeyId: attributeKeyMap[attr.attributeKey.key],
value: attr.value,
createdAt: attr.createdAt,
updatedAt: new Date(),
}))
);
// Skip the raw query if there are no attributes to upsert
if (attributesToUpsert.length > 0) {
// Process attributes in batches of 10,000
const BATCH_SIZE = 10000;
for (let i = 0; i < attributesToUpsert.length; i += BATCH_SIZE) {
const batch = attributesToUpsert.slice(i, i + BATCH_SIZE);
const attributesToUpsert = [...attributesUpsertForCreatedUsers, ...attributesUpsertForExistingUsers];
// Skip the raw query if there are no attributes to upsert
if (attributesToUpsert.length > 0) {
// Process attributes in batches of 10,000
const BATCH_SIZE = 10000;
for (let i = 0; i < attributesToUpsert.length; i += BATCH_SIZE) {
const batch = attributesToUpsert.slice(i, i + BATCH_SIZE);
// Use a raw query to perform a bulk insert with an ON CONFLICT clause
await tx.$executeRaw`
// Use a raw query to perform a bulk insert with an ON CONFLICT clause
await tx.$executeRaw`
INSERT INTO "ContactAttribute" (
"id", "created_at", "updated_at", "contactId", "value", "attributeKeyId"
)
@@ -357,35 +356,33 @@ export const upsertBulkContacts = async (
"value" = EXCLUDED."value",
"updated_at" = EXCLUDED."updated_at"
`;
}
}
}
contactCache.revalidate({
environmentId,
});
// revalidate all the new contacts:
for (const newContact of newContacts) {
contactCache.revalidate({
environmentId,
id: newContact.id,
});
}
// revalidate all the new contacts:
for (const newContact of newContacts) {
contactCache.revalidate({
id: newContact.id,
});
}
// revalidate all the existing contacts:
for (const existingContact of existingContactsByEmail) {
contactCache.revalidate({
id: existingContact.id,
});
}
contactAttributeKeyCache.revalidate({
environmentId,
// revalidate all the existing contacts:
for (const existingContact of existingContactsByEmail) {
contactCache.revalidate({
id: existingContact.id,
});
}
contactAttributeCache.revalidate({ environmentId });
},
{ timeout: 60 * 1000 }
);
contactAttributeKeyCache.revalidate({
environmentId,
});
contactAttributeCache.revalidate({ environmentId });
});
return ok({
contactIdxWithConflictingUserIds,

View File

@@ -1,3 +1,3 @@
---
openapi: put /api/v1/client/responses/{responseId}
---
openapi: put /api/v1/client/{environmentId}/responses/{responseId}
---

View File

@@ -6,208 +6,6 @@
},
"openapi": "3.0.0",
"paths": {
"/api/v1/client/responses/{responseId}": {
"put": {
"description": "Update an existing response for example when you want to mark a response as finished or you want to change an existing response's value.",
"parameters": [
{
"in": "path",
"name": "responseId",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"example": {
"data": {
"hs8yd14l9h8u353tjmv6rzawqqq": "clicked",
"tcgls0063n8ri7dtrbnepcmz": "Who? Who? Who?"
},
"finished": true
},
"type": "object"
}
}
}
},
"responses": {
"200": {
"content": {
"application/json": {
"example": {
"data": {}
},
"schema": {
"type": "object"
}
}
},
"description": "OK",
"headers": {
"Access-Control-Allow-Credentials": {
"schema": {
"example": "true",
"type": "boolean"
}
},
"Access-Control-Allow-Origin": {
"schema": {
"example": "*",
"type": "string"
}
},
"Connection": {
"schema": {
"example": "keep-alive",
"type": "string"
}
},
"Date": {
"schema": {
"example": "Tue, 23 Apr 2024 08:09:19 GMT",
"type": "string"
}
},
"Keep-Alive": {
"schema": {
"example": "timeout=5",
"type": "string"
}
},
"Transfer-Encoding": {
"schema": {
"example": "chunked",
"type": "string"
}
},
"access-control-allow-headers": {
"schema": {
"example": "Content-Type, Authorization",
"type": "string"
}
},
"access-control-allow-methods": {
"schema": {
"example": "GET, POST, PUT, DELETE, OPTIONS",
"type": "string"
}
},
"cache-control": {
"schema": {
"example": "private, no-store",
"type": "string"
}
},
"content-type": {
"schema": {
"example": "application/json",
"type": "string"
}
},
"vary": {
"schema": {
"example": "RSC, Next-Router-State-Tree, Next-Router-Prefetch",
"type": "string"
}
}
}
},
"404": {
"content": {
"application/json": {
"example": {
"code": "not_found",
"details": {
"resource_id": "nonexistentid",
"resource_type": "Response"
},
"message": "Response not found"
},
"schema": {
"type": "object"
}
}
},
"description": "Not Found",
"headers": {
"Access-Control-Allow-Credentials": {
"schema": {
"example": "true",
"type": "boolean"
}
},
"Access-Control-Allow-Origin": {
"schema": {
"example": "*",
"type": "string"
}
},
"Connection": {
"schema": {
"example": "keep-alive",
"type": "string"
}
},
"Date": {
"schema": {
"example": "Tue, 23 Apr 2024 08:13:50 GMT",
"type": "string"
}
},
"Keep-Alive": {
"schema": {
"example": "timeout=5",
"type": "string"
}
},
"Transfer-Encoding": {
"schema": {
"example": "chunked",
"type": "string"
}
},
"access-control-allow-headers": {
"schema": {
"example": "Content-Type, Authorization",
"type": "string"
}
},
"access-control-allow-methods": {
"schema": {
"example": "GET, POST, PUT, DELETE, OPTIONS",
"type": "string"
}
},
"cache-control": {
"schema": {
"example": "private, no-store",
"type": "string"
}
},
"content-type": {
"schema": {
"example": "application/json",
"type": "string"
}
},
"vary": {
"schema": {
"example": "RSC, Next-Router-State-Tree, Next-Router-Prefetch",
"type": "string"
}
}
}
}
},
"summary": "Update Response",
"tags": ["Client API > Response"]
}
},
"/api/v1/client/{environmentId}/contacts/{userId}/attributes": {
"put": {
"description": "Update a contact's attributes in Formbricks to keep them in sync with your app or when you want to set a custom attribute in Formbricks.",
@@ -1714,6 +1512,208 @@
"tags": ["Client API > Response"]
}
},
"/api/v1/client/{environmentId}/responses/{responseId}": {
"put": {
"description": "Update an existing response for example when you want to mark a response as finished or you want to change an existing response's value.",
"parameters": [
{
"in": "path",
"name": "responseId",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"example": {
"data": {
"hs8yd14l9h8u353tjmv6rzawqqq": "clicked",
"tcgls0063n8ri7dtrbnepcmz": "Who? Who? Who?"
},
"finished": true
},
"type": "object"
}
}
}
},
"responses": {
"200": {
"content": {
"application/json": {
"example": {
"data": {}
},
"schema": {
"type": "object"
}
}
},
"description": "OK",
"headers": {
"Access-Control-Allow-Credentials": {
"schema": {
"example": "true",
"type": "boolean"
}
},
"Access-Control-Allow-Origin": {
"schema": {
"example": "*",
"type": "string"
}
},
"Connection": {
"schema": {
"example": "keep-alive",
"type": "string"
}
},
"Date": {
"schema": {
"example": "Tue, 23 Apr 2024 08:09:19 GMT",
"type": "string"
}
},
"Keep-Alive": {
"schema": {
"example": "timeout=5",
"type": "string"
}
},
"Transfer-Encoding": {
"schema": {
"example": "chunked",
"type": "string"
}
},
"access-control-allow-headers": {
"schema": {
"example": "Content-Type, Authorization",
"type": "string"
}
},
"access-control-allow-methods": {
"schema": {
"example": "GET, POST, PUT, DELETE, OPTIONS",
"type": "string"
}
},
"cache-control": {
"schema": {
"example": "private, no-store",
"type": "string"
}
},
"content-type": {
"schema": {
"example": "application/json",
"type": "string"
}
},
"vary": {
"schema": {
"example": "RSC, Next-Router-State-Tree, Next-Router-Prefetch",
"type": "string"
}
}
}
},
"404": {
"content": {
"application/json": {
"example": {
"code": "not_found",
"details": {
"resource_id": "nonexistentid",
"resource_type": "Response"
},
"message": "Response not found"
},
"schema": {
"type": "object"
}
}
},
"description": "Not Found",
"headers": {
"Access-Control-Allow-Credentials": {
"schema": {
"example": "true",
"type": "boolean"
}
},
"Access-Control-Allow-Origin": {
"schema": {
"example": "*",
"type": "string"
}
},
"Connection": {
"schema": {
"example": "keep-alive",
"type": "string"
}
},
"Date": {
"schema": {
"example": "Tue, 23 Apr 2024 08:13:50 GMT",
"type": "string"
}
},
"Keep-Alive": {
"schema": {
"example": "timeout=5",
"type": "string"
}
},
"Transfer-Encoding": {
"schema": {
"example": "chunked",
"type": "string"
}
},
"access-control-allow-headers": {
"schema": {
"example": "Content-Type, Authorization",
"type": "string"
}
},
"access-control-allow-methods": {
"schema": {
"example": "GET, POST, PUT, DELETE, OPTIONS",
"type": "string"
}
},
"cache-control": {
"schema": {
"example": "private, no-store",
"type": "string"
}
},
"content-type": {
"schema": {
"example": "application/json",
"type": "string"
}
},
"vary": {
"schema": {
"example": "RSC, Next-Router-State-Tree, Next-Router-Prefetch",
"type": "string"
}
}
}
}
},
"summary": "Update Response",
"tags": ["Client API > Response"]
}
},
"/api/v1/client/{environmentId}/user": {
"post": {
"description": "Endpoint for creating or identifying a user within the specified environment. If the user already exists, this will identify them and potentially update user attributes. If they don't exist, it will create a new user.\n",

View File

@@ -77,8 +77,8 @@ deployment:
limits:
memory: 2Gi
requests:
cpu: 500m
memory: 512Mi
cpu: 1
memory: 1Gi
env:
DOCKER_CRON_ENABLED:
value: "0"

View File

@@ -31,7 +31,6 @@ class FormbricksViewModel : ViewModel() {
<head>
<title>Formbricks WebView Survey</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body style="overflow: hidden; height: 100vh; display: flex; flex-direction: column; justify-content: flex-end;">

View File

@@ -24,7 +24,6 @@ private extension FormbricksViewModel {
<head>
<title>Formbricks WebView Survey</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body style="overflow: hidden; height: 100vh; display: flex; flex-direction: column; justify-content: flex-end;">

View File

@@ -7,6 +7,7 @@ import { checkPageUrl } from "@/lib/survey/no-code-action";
import * as Attribute from "@/lib/user/attribute";
import * as User from "@/lib/user/user";
import { type TConfigInput, type TLegacyConfigInput } from "@/types/config";
import { type TTrackProperties } from "@/types/survey";
const queue = new CommandQueue();
@@ -67,8 +68,12 @@ const logout = async (): Promise<void> => {
await queue.wait();
};
const track = async (code: string): Promise<void> => {
queue.add(Action.trackCodeAction, true, code);
/**
* @param code - The code of the action to track
* @param properties - Optional properties to set, like the hidden fields (deprecated, hidden fields will be removed in a future version)
*/
const track = async (code: string, properties?: TTrackProperties): Promise<void> => {
queue.add<string | TTrackProperties | undefined>(Action.trackCodeAction, true, code, properties);
await queue.wait();
};
@@ -91,5 +96,6 @@ const formbricks = {
registerRouteChange,
};
export type TFormbricks = typeof formbricks;
type TFormbricks = typeof formbricks;
export type { TFormbricks };
export default formbricks;

View File

@@ -4,9 +4,13 @@ import { checkSetup } from "@/lib/common/setup";
import { wrapThrowsAsync } from "@/lib/common/utils";
import type { Result } from "@/types/error";
export type TCommand = (
...args: any[]
) => Promise<Result<void, unknown>> | Result<void, unknown> | Promise<void>;
export class CommandQueue {
private queue: {
command: (...args: any[]) => Promise<Result<void, unknown>> | Result<void, unknown> | Promise<void>;
command: TCommand;
checkSetup: boolean;
commandArgs: any[];
}[] = [];
@@ -14,11 +18,7 @@ export class CommandQueue {
private resolvePromise: (() => void) | null = null;
private commandPromise: Promise<void> | null = null;
public add<A>(
command: (...args: A[]) => Promise<Result<void, unknown>> | Result<void, unknown> | Promise<void>,
shouldCheckSetup = true,
...args: A[]
): void {
public add<A>(command: TCommand, shouldCheckSetup = true, ...args: A[]): void {
this.queue.push({ command, checkSetup: shouldCheckSetup, commandArgs: args });
if (!this.running) {

View File

@@ -1,3 +1,4 @@
import { Logger } from "@/lib/common/logger";
import type {
TEnvironmentState,
TEnvironmentStateActionClass,
@@ -8,7 +9,11 @@ import type {
TUserState,
} from "@/types/config";
import type { Result } from "@/types/error";
import { type TActionClassNoCodeConfig, type TActionClassPageUrlRule } from "@/types/survey";
import {
type TActionClassNoCodeConfig,
type TActionClassPageUrlRule,
type TTrackProperties,
} from "@/types/survey";
// Helper function to calculate difference in days between two dates
export const diffInDays = (date1: Date, date2: Date): number => {
@@ -225,6 +230,38 @@ export const handleUrlFilters = (urlFilters: TActionClassNoCodeConfig["urlFilter
return isMatch;
};
export const handleHiddenFields = (
hiddenFieldsConfig: TEnvironmentStateSurvey["hiddenFields"],
hiddenFields?: TTrackProperties["hiddenFields"]
): TTrackProperties["hiddenFields"] => {
const logger = Logger.getInstance();
const { enabled: enabledHiddenFields, fieldIds: surveyHiddenFieldIds } = hiddenFieldsConfig;
let hiddenFieldsObject: TTrackProperties["hiddenFields"] = {};
if (!enabledHiddenFields) {
logger.error("Hidden fields are not enabled for this survey");
} else if (surveyHiddenFieldIds && hiddenFields) {
const unknownHiddenFields: string[] = [];
hiddenFieldsObject = Object.keys(hiddenFields).reduce<TTrackProperties["hiddenFields"]>((acc, key) => {
if (surveyHiddenFieldIds.includes(key)) {
acc[key] = hiddenFields[key];
} else {
unknownHiddenFields.push(key);
}
return acc;
}, {});
if (unknownHiddenFields.length > 0) {
logger.error(
`Unknown hidden fields: ${unknownHiddenFields.join(", ")}. Please add them to the survey hidden fields.`
);
}
}
return hiddenFieldsObject;
};
export const evaluateNoCodeConfigClick = (
targetElement: HTMLElement,
action: TEnvironmentStateActionClass

View File

@@ -2,14 +2,20 @@ import { Config } from "@/lib/common/config";
import { Logger } from "@/lib/common/logger";
import { triggerSurvey } from "@/lib/survey/widget";
import { type InvalidCodeError, type NetworkError, type Result, err, okVoid } from "@/types/error";
import { type TTrackProperties } from "@/types/survey";
/**
* Tracks an action name and triggers associated surveys
* @param name - The name of the action to track
* @param alias - Optional alias for the action name
* @param properties - Optional properties to set, like the hidden fields (deprecated, hidden fields will be removed in a future version)
* @returns Result indicating success or network error
*/
export const trackAction = async (name: string, alias?: string): Promise<Result<void, NetworkError>> => {
export const trackAction = async (
name: string,
alias?: string,
properties?: TTrackProperties
): Promise<Result<void, NetworkError>> => {
const logger = Logger.getInstance();
const appConfig = Config.getInstance();
@@ -24,7 +30,7 @@ export const trackAction = async (name: string, alias?: string): Promise<Result<
for (const survey of activeSurveys) {
for (const trigger of survey.triggers) {
if (trigger.actionClass.name === name) {
await triggerSurvey(survey, name);
await triggerSurvey(survey, name, properties);
}
}
}
@@ -38,10 +44,12 @@ export const trackAction = async (name: string, alias?: string): Promise<Result<
/**
* Tracks an action by its code and triggers associated surveys (used for code actions only)
* @param code - The action code to track
* @param properties - Optional properties to set, like the hidden fields (deprecated, hidden fields will be removed in a future version)
* @returns Result indicating success, network error, or invalid code error
*/
export const trackCodeAction = async (
code: string
code: string,
properties?: TTrackProperties
): Promise<Result<void, NetworkError> | Result<void, InvalidCodeError>> => {
const appConfig = Config.getInstance();
@@ -61,7 +69,7 @@ export const trackCodeAction = async (
});
}
return trackAction(actionClass.name, code);
return trackAction(actionClass.name, code, properties);
};
export const trackNoCodeAction = (name: string): Promise<Result<void, NetworkError>> => {

View File

@@ -33,6 +33,7 @@ vi.mock("@/lib/common/logger", () => ({
vi.mock("@/lib/common/utils", () => ({
shouldDisplayBasedOnPercentage: vi.fn(),
handleHiddenFields: vi.fn(),
}));
vi.mock("@/lib/survey/widget", () => ({
@@ -100,10 +101,10 @@ describe("survey/action.ts", () => {
filteredSurveys: [mockSurvey],
});
const result = await trackAction("testAction");
const result = await trackAction("testAction", undefined);
expect(result.ok).toBe(true);
expect(triggerSurvey).toHaveBeenCalledWith(mockSurvey, "testAction");
expect(triggerSurvey).toHaveBeenCalledWith(mockSurvey, "testAction", undefined);
});
test("handles multiple matching surveys", async () => {

View File

@@ -40,6 +40,7 @@ vi.mock("@/lib/common/utils", () => ({
getStyling: vi.fn(),
shouldDisplayBasedOnPercentage: vi.fn(),
wrapThrowsAsync: vi.fn(),
handleHiddenFields: vi.fn(),
}));
describe("widget-file", () => {

View File

@@ -7,9 +7,11 @@ import {
filterSurveys,
getLanguageCode,
getStyling,
handleHiddenFields,
shouldDisplayBasedOnPercentage,
} from "@/lib/common/utils";
import { type TEnvironmentStateSurvey, type TUserState } from "@/types/config";
import { type TTrackProperties } from "@/types/survey";
let isSurveyRunning = false;
@@ -17,7 +19,11 @@ export const setIsSurveyRunning = (value: boolean): void => {
isSurveyRunning = value;
};
export const triggerSurvey = async (survey: TEnvironmentStateSurvey, action?: string): Promise<void> => {
export const triggerSurvey = async (
survey: TEnvironmentStateSurvey,
action?: string,
properties?: TTrackProperties
): Promise<void> => {
const logger = Logger.getInstance();
// Check if the survey should be displayed based on displayPercentage
@@ -29,10 +35,19 @@ export const triggerSurvey = async (survey: TEnvironmentStateSurvey, action?: st
}
}
await renderWidget(survey, action);
const hiddenFieldsObject: TTrackProperties["hiddenFields"] = handleHiddenFields(
survey.hiddenFields,
properties?.hiddenFields
);
await renderWidget(survey, action, hiddenFieldsObject);
};
export const renderWidget = async (survey: TEnvironmentStateSurvey, action?: string): Promise<void> => {
export const renderWidget = async (
survey: TEnvironmentStateSurvey,
action?: string,
hiddenFieldsObject?: TTrackProperties["hiddenFields"]
): Promise<void> => {
const logger = Logger.getInstance();
const config = Config.getInstance();
const timeoutStack = TimeoutStack.getInstance();
@@ -87,6 +102,7 @@ export const renderWidget = async (survey: TEnvironmentStateSurvey, action?: str
languageCode,
placement,
styling: getStyling(project, survey),
hiddenFieldsRecord: hiddenFieldsObject,
onDisplayCreated: () => {
const existingDisplays = config.get().user.data.displays;
const newDisplay = { surveyId: survey.id, createdAt: new Date() };

View File

@@ -75,3 +75,7 @@ export type TActionClassNoCodeConfig =
rule: TActionClassPageUrlRule;
}[];
};
export interface TTrackProperties {
hiddenFields: Record<string, string | number | string[]>;
}

View File

@@ -1,7 +1,7 @@
{
"name": "@formbricks/js",
"license": "MIT",
"version": "4.0.0",
"version": "4.1.0",
"description": "Formbricks-js allows you to connect your index to Formbricks, display surveys and trigger events.",
"homepage": "https://formbricks.com",
"repository": {

View File

@@ -1,7 +1,10 @@
import type Formbricks from "@formbricks/js-core";
import { type TFormbricks as TFormbricksCore } from "@formbricks/js-core";
import { loadFormbricksToProxy } from "./lib/load-formbricks";
type TFormbricks = typeof Formbricks;
type TFormbricks = Omit<TFormbricksCore, "track"> & {
track: (code: string) => Promise<void>;
};
declare global {
interface Window {
formbricks: TFormbricks | undefined;
@@ -14,7 +17,7 @@ const formbricksProxyHandler: ProxyHandler<TFormbricks> = {
},
};
const formbricks: TFormbricks = new Proxy({} as TFormbricks, formbricksProxyHandler);
const formbricks: TFormbricksCore = new Proxy({} as TFormbricks, formbricksProxyHandler);
// eslint-disable-next-line import/no-default-export -- Required for UMD
export default formbricks;

View File

@@ -104,9 +104,6 @@ type TGetSignedUrlResponse =
};
const getS3SignedUrl = async (fileKey: string): Promise<string> => {
const [_, accessType] = fileKey.split("/");
const expiresIn = accessType === "public" ? 60 * 60 : 10 * 60;
const getObjectCommand = new GetObjectCommand({
Bucket: S3_BUCKET_NAME,
Key: fileKey,
@@ -114,7 +111,7 @@ const getS3SignedUrl = async (fileKey: string): Promise<string> => {
try {
const s3Client = getS3Client();
return await getSignedUrl(s3Client, getObjectCommand, { expiresIn });
return await getSignedUrl(s3Client, getObjectCommand, { expiresIn: 30 * 60 });
} catch (err) {
throw err;
}

View File

@@ -219,7 +219,6 @@ const renderHtml = (options: Partial<SurveyContainerProps> & { appUrl?: string }
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0">
<head>
<title>Formbricks WebView Survey</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body style="overflow: hidden; height: 100vh; margin: 0;">
</body>

1077
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff