fix: Vitest is being bundled to client + bump lingo.dev version (#23502)

* Fix vitest on prod

* Also extract out verify-email for the purpose of stopping test bundling

* Address NIT

* Fix lingo.dev imports

---------

Co-authored-by: Alex van Andel <[email protected]>
This commit is contained in:
Volnei MunhozandAlex van Andel authored and GitHub committed 2025-09-02 01:58:08 +01:00
1 parent 060eafac60
commit 096026b92a
11 files changed
+2854 -587

No files matched your search

@@ -0,0 +1,84 @@
import { organizationScenarios } from "@calcom/lib/server/repository/__mocks__/organization";
import { describe, it, expect, beforeEach, vi } from "vitest";
import { MembershipRole } from "@calcom/prisma/client";
import { CreationSource } from "@calcom/prisma/enums";
import { inviteMembersWithNoInviterPermissionCheck } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/inviteMember.handler";
import { moveUserToMatchingOrg } from "./verify-email";
vi.mock("@calcom/trpc/server/routers/viewer/teams/inviteMember/inviteMember.handler");
vi.mock("@calcom/lib/server/repository/organization");
describe("moveUserToMatchingOrg", () => {
const email = "[email protected]";
beforeEach(() => {
vi.resetAllMocks();
});
it("should not proceed if no matching organization is found", async () => {
organizationScenarios.OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail.fakeNoMatch();
await moveUserToMatchingOrg({ email });
expect(inviteMembersWithNoInviterPermissionCheck).not.toHaveBeenCalled();
});
describe("should invite user to the matching organization", () => {
const argToInviteMembersWithNoInviterPermissionCheck = {
inviterName: null,
language: "en",
creationSource: CreationSource.WEBAPP,
invitations: [
{
usernameOrEmail: email,
role: MembershipRole.MEMBER,
},
],
};
it("when organization has a slug and requestedSlug(slug is used)", async () => {
const org = {
id: "org123",
slug: "test-org",
requestedSlug: "requested-test-org",
};
organizationScenarios.OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail.fakeReturnOrganization(
org,
{ email }
);
await moveUserToMatchingOrg({ email });
expect(inviteMembersWithNoInviterPermissionCheck).toHaveBeenCalledWith({
...argToInviteMembersWithNoInviterPermissionCheck,
teamId: org.id,
orgSlug: org.slug,
});
});
it("when organization has requestedSlug only", async () => {
const org = {
id: "org123",
slug: null,
requestedSlug: "requested-test-org",
};
organizationScenarios.OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail.fakeReturnOrganization(
org,
{ email }
);
await moveUserToMatchingOrg({ email });
expect(inviteMembersWithNoInviterPermissionCheck).toHaveBeenCalledWith({
...argToInviteMembersWithNoInviterPermissionCheck,
teamId: org.id,
orgSlug: org.requestedSlug,
});
});
});
});
+185
View File
@@ -0,0 +1,185 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { z } from "zod";
import dayjs from "@calcom/dayjs";
import { StripeBillingService } from "@calcom/features/ee/billing/stripe-billling-service";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { IS_STRIPE_ENABLED } from "@calcom/lib/constants";
import { OrganizationRepository } from "@calcom/lib/server/repository/organization";
import { prisma } from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/client";
import { CreationSource } from "@calcom/prisma/enums";
import { userMetadata } from "@calcom/prisma/zod-utils";
import { inviteMembersWithNoInviterPermissionCheck } from "@calcom/trpc/server/routers/viewer/teams/inviteMember/inviteMember.handler";
const verifySchema = z.object({
token: z.string(),
});
const USER_ALREADY_EXISTING_MESSAGE = "A User already exists with this email";
// TODO: To be unit tested
export async function moveUserToMatchingOrg({ email }: { email: string }) {
const org = await OrganizationRepository.findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail({ email });
if (!org) {
return;
}
await inviteMembersWithNoInviterPermissionCheck({
inviterName: null,
teamId: org.id,
language: "en",
creationSource: CreationSource.WEBAPP,
invitations: [
{
usernameOrEmail: email,
role: MembershipRole.MEMBER,
},
],
orgSlug: org.slug || org.requestedSlug,
});
}
export async function handler(req: NextApiRequest, res: NextApiResponse) {
const { token } = verifySchema.parse(req.query);
const billingService = new StripeBillingService();
const foundToken = await prisma.verificationToken.findFirst({
where: {
token,
},
});
if (!foundToken) {
return res.status(401).json({ message: "No token found" });
}
if (dayjs(foundToken?.expires).isBefore(dayjs())) {
return res.status(401).json({ message: "Token expired" });
}
// The user is verifying the secondary email
if (foundToken?.secondaryEmailId) {
await prisma.secondaryEmail.update({
where: {
id: foundToken.secondaryEmailId,
email: foundToken?.identifier,
},
data: {
emailVerified: new Date(),
},
});
await cleanUpVerificationTokens(foundToken.id);
return res.redirect(`${WEBAPP_URL}/settings/my-account/profile`);
}
const user = await prisma.user.findFirst({
where: {
email: foundToken?.identifier,
},
});
if (!user) {
return res.status(401).json({ message: "Cannot find a user attached to this token" });
}
const userMetadataParsed = userMetadata.parse(user.metadata);
// Attach the new email and verify
if (userMetadataParsed?.emailChangeWaitingForVerification) {
// Ensure this email isn't in use
const existingUser = await prisma.user.findUnique({
where: { email: userMetadataParsed?.emailChangeWaitingForVerification },
select: {
id: true,
},
});
if (existingUser) {
return res.status(401).json({ message: USER_ALREADY_EXISTING_MESSAGE });
}
// Ensure this email isn't being added by another user as secondary email
const existingSecondaryUser = await prisma.secondaryEmail.findUnique({
where: {
email: userMetadataParsed?.emailChangeWaitingForVerification,
},
select: {
id: true,
userId: true,
},
});
if (existingSecondaryUser && existingSecondaryUser.userId !== user.id) {
return res.status(401).json({ message: USER_ALREADY_EXISTING_MESSAGE });
}
const oldEmail = user.email;
const updatedEmail = userMetadataParsed.emailChangeWaitingForVerification;
delete userMetadataParsed.emailChangeWaitingForVerification;
// Update and re-verify
await prisma.user.update({
where: {
id: user.id,
},
data: {
email: updatedEmail,
metadata: userMetadataParsed,
},
});
if (IS_STRIPE_ENABLED && userMetadataParsed.stripeCustomerId) {
await billingService.updateCustomer({
customerId: userMetadataParsed.stripeCustomerId,
email: updatedEmail,
});
}
// The user is trying to update the email to an already existing unverified secondary email of his
// so we swap the emails and its verified status
if (existingSecondaryUser?.userId === user.id) {
await prisma.secondaryEmail.update({
where: {
id: existingSecondaryUser.id,
userId: user.id,
},
data: {
email: oldEmail,
emailVerified: user.emailVerified,
},
});
}
await cleanUpVerificationTokens(foundToken.id);
return res.status(200).json({
updatedEmail,
});
}
await prisma.user.update({
where: {
id: user.id,
},
data: {
emailVerified: new Date(),
},
});
const hasCompletedOnboarding = user.completedOnboarding;
await moveUserToMatchingOrg({ email: user.email });
return res.redirect(`${WEBAPP_URL}/${hasCompletedOnboarding ? "/event-types" : "/getting-started"}`);
}
export async function cleanUpVerificationTokens(id: number) {
// Delete token from DB after it has been used
await prisma.verificationToken.delete({
where: {
id,
},
});
}
@@ -0,0 +1,157 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { applyTheme } from "./_applyThemeForDocument";
describe("applyTheme", () => {
let reconstructedFn: () => void;
let mockLocalStorage: Storage;
let mockRequestAnimationFrame: typeof window.requestAnimationFrame;
let mockDocument: Document;
let addedClasses: string[] = [];
beforeEach(() => {
// Create the function from stringified version
const stringifiedFunction = applyTheme.toString();
reconstructedFn = new Function(`return ${stringifiedFunction}`)();
// Mock localStorage
mockLocalStorage = {
getItem: vi.fn(() => null),
setItem: vi.fn(),
removeItem: vi.fn(),
clear: vi.fn(),
key: vi.fn(() => null),
length: 0,
};
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.localStorage = mockLocalStorage;
// Mock requestAnimationFrame
mockRequestAnimationFrame = vi.fn((cb) => {
cb(0);
return 0;
});
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.window = { location: { pathname: "/" } };
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.requestAnimationFrame = mockRequestAnimationFrame;
// Mock document
addedClasses = [];
mockDocument = {
body: {
classList: {
add: vi.fn((className: string) => {
addedClasses.push(className);
}),
},
},
} as unknown as Document;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.document = mockDocument;
// Mock console.error
global.console.error = vi.fn();
});
afterEach(() => {
vi.clearAllMocks();
});
it("should be reconstructable from toString() and executable", () => {
expect(() => reconstructedFn()).not.toThrow();
});
it("should not add any theme when no app-theme is found", () => {
reconstructedFn();
expect(mockRequestAnimationFrame).not.toHaveBeenCalled();
expect(addedClasses).toHaveLength(0);
});
it("should handle localStorage errors gracefully", () => {
// Make localStorage throw an error
mockLocalStorage.getItem = vi.fn(() => {
throw new Error("localStorage not available");
});
mockLocalStorage.key = vi.fn(() => {
throw new Error("localStorage not available");
});
Object.defineProperty(mockLocalStorage, "length", {
get: () => {
throw new Error("localStorage not available");
},
});
expect(() => reconstructedFn()).not.toThrow();
expect(addedClasses).toHaveLength(0);
});
it("should apply booking theme when app-theme exists and on booking page", () => {
const username = "testuser";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.window.location.pathname = `/${username}/meeting`;
mockLocalStorage.key = vi.fn((index: number) => {
if (index === 0) return `booking-theme:${username}`;
return null;
});
mockLocalStorage.getItem = vi.fn((key: string) => {
if (key === "app-theme") return "light";
if (key === `booking-theme:${username}`) return "dark";
return null;
});
Object.defineProperty(mockLocalStorage, "length", {
get: () => 1,
configurable: true,
});
reconstructedFn();
expect(addedClasses).toContain("dark");
});
it("should apply app theme when not on booking page", () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.window.location.pathname = "/some-other-page";
mockLocalStorage.key = vi.fn((index: number) => {
if (index === 0) return "booking-theme:testuser";
return null;
});
mockLocalStorage.getItem = vi.fn((key: string) => {
if (key === "app-theme") return "light";
if (key === "booking-theme:testuser") return "dark";
return null;
});
Object.defineProperty(mockLocalStorage, "length", {
get: () => 1,
configurable: true,
});
reconstructedFn();
expect(addedClasses).toContain("light");
});
it("should apply app theme when app-theme exists but no booking theme", () => {
mockLocalStorage.getItem = vi.fn((key: string) => {
if (key === "app-theme") return "dark";
return null;
});
Object.defineProperty(mockLocalStorage, "length", {
get: () => 0,
configurable: true,
});
reconstructedFn();
expect(addedClasses).toContain("dark");
});
});
@@ -0,0 +1,78 @@
// Theme application function - will be stringified and injected. So, it must not use anything from the closure
export const applyTheme = function () {
try {
// This utility is a replica of @calcom/lib/webstorage.ts but we can reuse it because applyTheme is stringified and injected, so we can't have deps here
const safeLocalStorage = {
getItem: function (key: string) {
try {
// eslint-disable-next-line @calcom/eslint/avoid-web-storage
return localStorage.getItem(key);
} catch (e) {
return null;
}
},
key: function (index: number) {
try {
// eslint-disable-next-line @calcom/eslint/avoid-web-storage
return localStorage.key(index);
} catch (e) {
return null;
}
},
getLength: function () {
try {
// eslint-disable-next-line @calcom/eslint/avoid-web-storage
return localStorage.length;
} catch (e) {
return 0;
}
},
};
const appTheme = safeLocalStorage.getItem("app-theme");
if (!appTheme) return;
let bookingTheme: string | null = null;
let username: string | undefined;
for (let i = 0; i < safeLocalStorage.getLength(); i++) {
const key = safeLocalStorage.key(i);
if (key && key.startsWith("booking-theme:")) {
bookingTheme = safeLocalStorage.getItem(key);
username = key.split("booking-theme:")[1];
break;
}
}
const onReady = () => {
const isBookingPage = username && window.location.pathname.slice(1).startsWith(username);
if (document.body) {
document.body.classList.add(isBookingPage ? bookingTheme || appTheme : appTheme);
} else {
requestAnimationFrame(onReady);
}
};
requestAnimationFrame(onReady);
} catch (e) {
console.error("Error applying theme:", e);
}
};
// ToDesktop class application function - will be stringified and injected. So, it must not use anything from the closure
export const applyToDesktopClass = function () {
try {
const onReady = () => {
if (typeof window !== "undefined" && window.calIsDesktopApp && document.documentElement) {
document.documentElement.classList.add("todesktop");
} else if (document.documentElement) {
return;
} else {
requestAnimationFrame(onReady);
}
};
requestAnimationFrame(onReady);
} catch (e) {
console.error("Error applying todesktop class:", e);
}
};