Skip to content

The open alternative to Salesforce, designed for AI.

Compile one frontend component with bounded resources (#29017)

Weikoc496b66fa93d
diff --git a/packages/twenty-server/package.json b/packages/twenty-server/package.json
index 03f9fb03fcd..b99ad696310 100644
--- a/packages/twenty-server/package.json
+++ b/packages/twenty-server/package.json
@@ -98,6 +98,7 @@
"dompurify": "^3.4.17",
"dotenv": "16.4.5",
"email-reply-parser": "^2.3.5",
+ "esbuild": "^0.28.1",
"express": "5.3.0",
"express-session": "^1.18.2",
"file-type": "^21.3.2",
@@ -168,6 +169,7 @@
"tsdav": "^2.2.1",
"type-fest": "4.10.1",
"typeorm": "patch:[email protected]#./patches/typeorm+0.3.31.patch",
+ "typescript": "^5.9.3",
"unzipper": "^0.12.3",
"uuid": "^11.1.1",
"zod": "^4.6.6"
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-allowed-imports.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-allowed-imports.constant.ts
new file mode 100644
index 00000000000..3d84eccb4af
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-allowed-imports.constant.ts
@@ -0,0 +1,8 @@
+import { FRONT_COMPONENT_UI_IMPORTS } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-ui-imports.constant';
+
+export const FRONT_COMPONENT_ALLOWED_IMPORTS = [
+ 'react',
+ 'react-dom',
+ 'react/jsx-runtime',
+ ...FRONT_COMPONENT_UI_IMPORTS,
+];
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-build-timeout-ms.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-build-timeout-ms.constant.ts
new file mode 100644
index 00000000000..3769f09ea67
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-build-timeout-ms.constant.ts
@@ -0,0 +1 @@
+export const FRONT_COMPONENT_BUILD_TIMEOUT_MS = 10000;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-max-build-output-bytes.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-max-build-output-bytes.constant.ts
new file mode 100644
index 00000000000..8169c6a276d
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-max-build-output-bytes.constant.ts
@@ -0,0 +1 @@
+export const FRONT_COMPONENT_MAX_BUILD_OUTPUT_BYTES = 5 * 1024 * 1024;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-shared-dependencies-banner-prefix.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-shared-dependencies-banner-prefix.constant.ts
new file mode 100644
index 00000000000..1e3cb1b6f9f
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-shared-dependencies-banner-prefix.constant.ts
@@ -0,0 +1,2 @@
+export const FRONT_COMPONENT_SHARED_DEPENDENCIES_BANNER_PREFIX =
+ '// twenty-ai-shared-dependencies: ';
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-ui-imports.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-ui-imports.constant.ts
new file mode 100644
index 00000000000..7bbabeecc59
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-ui-imports.constant.ts
@@ -0,0 +1,14 @@
+export const FRONT_COMPONENT_UI_IMPORTS = [
+ 'twenty-ui/primitives/input',
+ 'twenty-ui/primitives/data-display',
+ 'twenty-ui/primitives/feedback',
+ 'twenty-ui/primitives/layout',
+ 'twenty-ui/primitives/navigation',
+ 'twenty-ui/primitives/surfaces',
+ 'twenty-ui/primitives/typography',
+ 'twenty-ui/components/input',
+ 'twenty-ui/icon',
+ 'twenty-ui/theme',
+ 'twenty-ui/style.css',
+ 'twenty-ui/theme-light.css',
+];
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-wrapper-name.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-wrapper-name.constant.ts
new file mode 100644
index 00000000000..4d6b42bbc6d
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-wrapper-name.constant.ts
@@ -0,0 +1 @@
+export const FRONT_COMPONENT_WRAPPER_NAME = 'TwentyComponent';
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/exceptions/front-component-build.exception.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/exceptions/front-component-build.exception.ts
new file mode 100644
index 00000000000..ecfe1091e66
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/exceptions/front-component-build.exception.ts
@@ -0,0 +1,27 @@
+import { type MessageDescriptor } from '@lingui/core';
+import { msg } from '@lingui/core/macro';
+
+import { CustomException } from 'src/utils/custom-exception';
+
+type FrontComponentBuildExceptionCode = 'INVALID_INPUT' | 'BUILD_FAILED';
+
+export class FrontComponentBuildException extends CustomException<FrontComponentBuildExceptionCode> {
+ constructor({
+ message,
+ code,
+ userFriendlyMessage,
+ }: {
+ message: string;
+ code: FrontComponentBuildExceptionCode;
+ userFriendlyMessage?: MessageDescriptor;
+ }) {
+ super(message, code, {
+ userFriendlyMessage:
+ userFriendlyMessage ??
+ (code === 'INVALID_INPUT'
+ ? msg`Invalid front component source.`
+ : msg`Failed to build front component.`),
+ });
+ this.name = 'FrontComponentBuildException';
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-query.schema.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-query.schema.ts
new file mode 100644
index 00000000000..3684451027e
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-query.schema.ts
@@ -0,0 +1,9 @@
+import { z } from 'zod';
+
+const queryIdentifierSchema = z.string().regex(/^[a-zA-Z][a-zA-Z0-9]*$/);
+
+export const frontComponentQuerySchema = z.object({
+ objectName: queryIdentifierSchema,
+ select: z.array(queryIdentifierSchema).min(1).max(20),
+ limit: z.number().int().min(1).max(100),
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-build-input.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-build-input.type.ts
new file mode 100644
index 00000000000..af3d4bee0c1
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-build-input.type.ts
@@ -0,0 +1,11 @@
+import { type PageLayoutType } from 'twenty-shared/types';
+
+import { type FrontComponentQuery } from 'src/engine/metadata-modules/ai/ai-front-component/types/front-component-query.type';
+
+export type FrontComponentBuildInput = {
+ componentId: string;
+ name: string;
+ source: string;
+ query: FrontComponentQuery;
+ pageLayoutType: PageLayoutType.DASHBOARD | PageLayoutType.RECORD_PAGE;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-query.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-query.type.ts
new file mode 100644
index 00000000000..cef061d50d4
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-query.type.ts
@@ -0,0 +1,5 @@
+import { type z } from 'zod';
+
+import { frontComponentQuerySchema } from 'src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-query.schema';
+
+export type FrontComponentQuery = z.infer<typeof frontComponentQuerySchema>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-shared-dependencies.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-shared-dependencies.type.ts
new file mode 100644
index 00000000000..6871c208428
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-shared-dependencies.type.ts
@@ -0,0 +1,7 @@
+import { type SharedDependenciesBuildContext } from 'twenty-shared/front-component-build';
+
+export type FrontComponentSharedDependencies =
+ SharedDependenciesBuildContext & {
+ source: string;
+ checksum: string;
+ };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component-with-limits-or-throw.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component-with-limits-or-throw.util.spec.ts
new file mode 100644
index 00000000000..f44bebc125f
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component-with-limits-or-throw.util.spec.ts
@@ -0,0 +1,145 @@
+import { context } from 'esbuild';
+
+import { buildFrontComponentWithLimitsOrThrow } from 'src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-with-limits-or-throw.util';
+
+jest.mock('esbuild', () => ({ context: jest.fn() }));
+
+describe('component build limits', () => {
+ const rebuild = jest.fn();
+ const cancel = jest.fn();
+ const dispose = jest.fn();
+ const output = {
+ outputFiles: [{ contents: new Uint8Array(10), text: 'component' }],
+ };
+
+ beforeEach(() => {
+ jest.useFakeTimers();
+ jest.resetAllMocks();
+ jest.mocked(context).mockResolvedValue({
+ rebuild,
+ cancel,
+ dispose,
+ watch: jest.fn(),
+ serve: jest.fn(),
+ });
+ cancel.mockResolvedValue(undefined);
+ dispose.mockResolvedValue(undefined);
+ rebuild.mockResolvedValue(output);
+ });
+
+ afterEach(() => jest.useRealTimers());
+
+ it('returns a completed build and releases its compiler context', async () => {
+ await expect(buildFrontComponentWithLimitsOrThrow({})).resolves.toBe(
+ output,
+ );
+ expect(dispose).toHaveBeenCalledTimes(1);
+ await jest.advanceTimersByTimeAsync(10000);
+ expect(cancel).not.toHaveBeenCalled();
+ });
+
+ it('cancels an expired build and allows the next build to succeed', async () => {
+ rebuild.mockImplementationOnce(
+ () =>
+ new Promise((_resolve, reject) => {
+ cancel.mockImplementationOnce(async () => {
+ reject(new Error('The build was canceled'));
+ });
+ }),
+ );
+ const result = expect(
+ buildFrontComponentWithLimitsOrThrow({}),
+ ).rejects.toMatchObject({
+ message: 'Component build exceeded the 10 second time limit.',
+ code: 'BUILD_FAILED',
+ userFriendlyMessage: {
+ id: expect.any(String),
+ message: 'Component build exceeded the 10 second time limit.',
+ },
+ });
+
+ await jest.advanceTimersByTimeAsync(10000);
+ await result;
+ expect(cancel).toHaveBeenCalledTimes(1);
+ expect(dispose).toHaveBeenCalledTimes(1);
+ await expect(buildFrontComponentWithLimitsOrThrow({})).resolves.toBe(
+ output,
+ );
+ });
+
+ it('rejects late success after cancellation', async () => {
+ rebuild.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ cancel.mockImplementationOnce(async () => resolve(output));
+ }),
+ );
+ const result = expect(
+ buildFrontComponentWithLimitsOrThrow({}),
+ ).rejects.toThrow('10 second time limit');
+
+ await jest.advanceTimersByTimeAsync(10000);
+ await result;
+ expect(dispose).toHaveBeenCalledTimes(1);
+ });
+
+ it('bounds combined output size before it can be cached', async () => {
+ rebuild.mockResolvedValueOnce({
+ outputFiles: [
+ { contents: new Uint8Array(3 * 1024 * 1024) },
+ { contents: new Uint8Array(3 * 1024 * 1024) },
+ ],
+ });
+
+ await expect(
+ buildFrontComponentWithLimitsOrThrow({}),
+ ).rejects.toMatchObject({
+ message: 'Component build exceeds the 5 MB output limit.',
+ code: 'INVALID_INPUT',
+ userFriendlyMessage: {
+ id: expect.any(String),
+ message: 'Component build exceeds the 5 MB output limit.',
+ },
+ });
+ expect(dispose).toHaveBeenCalledTimes(1);
+ });
+
+ it('preserves compiler diagnostics and releases a failed build', async () => {
+ rebuild.mockRejectedValueOnce(new Error('Unsupported import'));
+ await expect(
+ buildFrontComponentWithLimitsOrThrow({}),
+ ).rejects.toMatchObject({
+ message: 'Unsupported import',
+ code: 'BUILD_FAILED',
+ userFriendlyMessage: {
+ id: expect.any(String),
+ message: 'Failed to build front component.',
+ },
+ });
+ expect(dispose).toHaveBeenCalledTimes(1);
+ await expect(buildFrontComponentWithLimitsOrThrow({})).resolves.toBe(
+ output,
+ );
+ });
+
+ it('wraps context creation failures without disposing a missing context', async () => {
+ jest
+ .mocked(context)
+ .mockRejectedValueOnce(new Error('Invalid build options'));
+
+ await expect(
+ buildFrontComponentWithLimitsOrThrow({}),
+ ).rejects.toMatchObject({
+ message: 'Invalid build options',
+ code: 'BUILD_FAILED',
+ userFriendlyMessage: {
+ id: expect.any(String),
+ message: 'Failed to build front component.',
+ },
+ });
+ expect(dispose).not.toHaveBeenCalled();
+ await expect(buildFrontComponentWithLimitsOrThrow({})).resolves.toBe(
+ output,
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component.util.spec.ts
new file mode 100644
index 00000000000..6a53fd6b98f
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component.util.spec.ts
@@ -0,0 +1,239 @@
+import { build, transform } from 'esbuild';
+import { PageLayoutType } from 'twenty-shared/types';
+
+import { FRONT_COMPONENT_UI_IMPORTS } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-ui-imports.constant';
+import { buildFrontComponent as compileFrontComponent } from 'src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component.util';
+import { buildFrontComponentEntrySource } from 'src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-entry-source.util';
+import { FrontComponentBuildException } from 'src/engine/metadata-modules/ai/ai-front-component/exceptions/front-component-build.exception';
+
+jest.useRealTimers();
+
+const sharedDependencies: Parameters<
+ typeof compileFrontComponent
+>[0]['sharedDependencies'] = {
+ checksum: 'a'.repeat(64),
+ exportNamesBySpecifier: new Map([
+ ['react', { namedExports: ['useState'], hasDefaultExport: true }],
+ [
+ 'react/jsx-runtime',
+ { namedExports: ['jsx', 'jsxs', 'Fragment'], hasDefaultExport: false },
+ ],
+ [
+ 'react-dom/client',
+ { namedExports: ['createRoot'], hasDefaultExport: false },
+ ],
+ [
+ 'twenty-ui/theme',
+ { namedExports: ['ThemeProvider'], hasDefaultExport: false },
+ ],
+ ['twenty-ui/style.css', { namedExports: [], hasDefaultExport: false }],
+ [
+ 'twenty-ui/theme-light.css',
+ { namedExports: [], hasDefaultExport: false },
+ ],
+ ]),
+};
+const buildFrontComponent = (
+ input: Parameters<typeof compileFrontComponent>[0]['input'],
+) => compileFrontComponent({ input, sharedDependencies });
+
+const SOURCE = `import { useState } from 'react';
+type Company = { id: string; name: string };
+type ComponentProps = { records: Company[] };
+// Keep this filter local to the widget.
+export const Component = ({ records }: ComponentProps) => {
+ const [filter, setFilter] = useState('');
+ return <div><input value={filter} onChange={event => setFilter(event.target.value)} />{records.filter(record => record.name.includes(filter)).map(record => <p key={record.id}>{record.name}</p>)}</div>;
+};`;
+const INPUT = {
+ componentId: 'component-id',
+ name: 'Sales "this week"',
+ source: SOURCE,
+ query: { objectName: 'company', select: ['name'], limit: 20 },
+ pageLayoutType: PageLayoutType.DASHBOARD as const,
+};
+
+describe('buildFrontComponent', () => {
+ it.each([PageLayoutType.DASHBOARD, PageLayoutType.RECORD_PAGE] as const)(
+ 'builds one editable SDK file for the selected %s surface',
+ async (pageLayoutType) => {
+ const { source, compiledSource, checksum } = await buildFrontComponent({
+ ...INPUT,
+ pageLayoutType,
+ });
+
+ expect(source).toContain(SOURCE);
+ expect(source).toContain(
+ `widgetAvailability: { pageLayoutType: TwentyPageLayoutType.${pageLayoutType} }`,
+ );
+ expect(source).toContain(
+ 'export const componentQuery = ' + JSON.stringify(INPUT.query),
+ );
+ expect(checksum).toMatch(/^[a-f0-9]{64}$/);
+ expect(compiledSource).not.toContain('TWENTY_APP_ACCESS_TOKEN');
+ await expect(
+ transform(compiledSource, { loader: 'js' }),
+ ).resolves.toHaveProperty('code');
+ await expect(
+ build({
+ stdin: { contents: source, loader: 'tsx' },
+ bundle: true,
+ write: false,
+ format: 'esm',
+ external: [
+ 'react',
+ 'react/jsx-runtime',
+ 'twenty-sdk/define',
+ 'twenty-shared/types',
+ ...FRONT_COMPONENT_UI_IMPORTS,
+ ],
+ }),
+ ).resolves.toHaveProperty('outputFiles');
+ },
+ );
+
+ it.each([
+ 'node:fs',
+ 'twenty-sdk',
+ './secret',
+ 'https://example.com/code.js',
+ 'twenty-ui',
+ 'twenty-ui/components/code-editor',
+ 'twenty-ui/../../package.json',
+ '@tabler/icons-react',
+ ])('rejects unsupported import %s', async (importPath) => {
+ await expect(
+ buildFrontComponent({
+ ...INPUT,
+ source: `import value from '${importPath}'; export const Component = () => <div>{value}</div>;`,
+ }),
+ ).rejects.toThrow('Unsupported import');
+ });
+
+ it.each(['node:fs', 'react-dom/client', 'twenty-shared/types'])(
+ 'rejects unsupported dynamic import %s during the build',
+ async (importPath) => {
+ await expect(
+ buildFrontComponent({
+ ...INPUT,
+ source: `export const Component = () => <button onClick={() => import('${importPath}')}>Load</button>;`,
+ }),
+ ).rejects.toThrow('Unsupported import');
+ },
+ );
+
+ it.each([
+ 'import(url)',
+ 'import(`https://example.com/${url}.js`)',
+ 'require(url)',
+ "require('react' + url)",
+ ])('rejects computed module loading: %s', async (expression) => {
+ await expect(
+ buildFrontComponent({
+ ...INPUT,
+ source: `export const Component = ({ url }) => <button onClick={() => ${expression}}>Load</button>;`,
+ }),
+ ).rejects.toMatchObject({
+ code: 'INVALID_INPUT',
+ message: 'Use a string literal for import() and require().',
+ });
+ });
+
+ it('rejects computed imports even when esbuild would remove the unused function', async () => {
+ await expect(
+ buildFrontComponent({
+ ...INPUT,
+ source:
+ 'const load = (url) => import(url); export const Component = () => <div />;',
+ }),
+ ).rejects.toMatchObject({ code: 'INVALID_INPUT' });
+ });
+
+ it.each(['import("react")', 'import(`react`)', 'require("react")'])(
+ 'allows supported literal module loading: %s',
+ async (expression) => {
+ await expect(
+ buildFrontComponent({
+ ...INPUT,
+ source: `export const Component = () => <button onClick={() => ${expression}}>Load</button>;`,
+ }),
+ ).resolves.toHaveProperty('compiledSource');
+ },
+ );
+
+ it.each(['LIST', 'DASHBOARD }; globalThis.injected = true; //'])(
+ 'rejects invalid page layout before generating source: %s',
+ (pageLayoutType) => {
+ expect(() =>
+ buildFrontComponentEntrySource({
+ ...INPUT,
+ pageLayoutType: pageLayoutType as typeof INPUT.pageLayoutType,
+ }),
+ ).toThrow(
+ expect.objectContaining({
+ code: 'INVALID_INPUT',
+ message: expect.stringContaining('pageLayoutType'),
+ userFriendlyMessage: expect.objectContaining({
+ message: 'Invalid front component settings.',
+ }),
+ }),
+ );
+ },
+ );
+
+ it.each([
+ { ...INPUT.query, objectName: 'company.name' },
+ { ...INPUT.query, select: [] },
+ { ...INPUT.query, limit: 101 },
+ ])('returns a structured error for invalid query %j', async (query) => {
+ await expect(
+ buildFrontComponent({ ...INPUT, query }),
+ ).rejects.toMatchObject({
+ code: 'INVALID_INPUT',
+ userFriendlyMessage: {
+ id: expect.any(String),
+ message: 'Invalid front component settings.',
+ },
+ });
+ });
+
+ it.each([
+ 'export default () => <div />;',
+ 'export default function Component() { return <div />; }',
+ 'const View = () => <div />; export { View as default };',
+ 'export const View = () => <div />;',
+ ])(
+ 'rejects source outside the named Component contract: %s',
+ async (source) => {
+ await expect(buildFrontComponent({ ...INPUT, source })).rejects.toThrow(
+ FrontComponentBuildException,
+ );
+ },
+ );
+
+ it('returns compiler diagnostics for malformed TSX', async () => {
+ await expect(
+ buildFrontComponent({
+ ...INPUT,
+ source: 'export const Component = () => <div>;',
+ }),
+ ).rejects.toMatchObject({
+ code: 'BUILD_FAILED',
+ message: expect.stringContaining('Build failed'),
+ userFriendlyMessage: {
+ id: expect.any(String),
+ message: 'Failed to build front component.',
+ },
+ });
+ });
+
+ it('rejects collisions with the SDK wrapper before saving', async () => {
+ await expect(
+ buildFrontComponent({
+ ...INPUT,
+ source:
+ 'export const Component = () => <div />; const componentQuery = "other";',
+ }),
+ ).rejects.toThrow('componentQuery');
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/read-front-component-shared-dependencies-checksum.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/read-front-component-shared-dependencies-checksum.util.spec.ts
new file mode 100644
index 00000000000..94d2171d720
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/read-front-component-shared-dependencies-checksum.util.spec.ts
@@ -0,0 +1,25 @@
+import { readFrontComponentSharedDependenciesChecksum } from 'src/engine/metadata-modules/ai/ai-front-component/utils/read-front-component-shared-dependencies-checksum.util';
+
+const CHECKSUM = 'a'.repeat(64);
+const BANNER = '// twenty-ai-shared-dependencies: ' + CHECKSUM;
+
+describe('readFrontComponentSharedDependenciesChecksum', () => {
+ it('reads the pinned checksum only from the generated first line', () => {
+ expect(
+ readFrontComponentSharedDependenciesChecksum(
+ BANNER + '\nexport default () => {};',
+ ),
+ ).toBe(CHECKSUM);
+ });
+
+ it.each([
+ 'export default () => {};',
+ '\n' + BANNER,
+ BANNER + 'extra\n',
+ '// twenty-ai-shared-dependencies: ../../other-file\n',
+ ])('ignores missing or malformed metadata: %s', (source) => {
+ expect(
+ readFrontComponentSharedDependenciesChecksum(source),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-entry-source.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-entry-source.util.ts
new file mode 100644
index 00000000000..c1045a112d0
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-entry-source.util.ts
@@ -0,0 +1,56 @@
+import { msg } from '@lingui/core/macro';
+import { PageLayoutType } from 'twenty-shared/types';
+import { z } from 'zod';
+
+import { FRONT_COMPONENT_WRAPPER_NAME } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-wrapper-name.constant';
+import { FrontComponentBuildException } from 'src/engine/metadata-modules/ai/ai-front-component/exceptions/front-component-build.exception';
+import { frontComponentQuerySchema } from 'src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-query.schema';
+import { type FrontComponentBuildInput } from 'src/engine/metadata-modules/ai/ai-front-component/types/front-component-build-input.type';
+
+const frontComponentEntryOptionsSchema = z.object({
+ query: frontComponentQuerySchema,
+ pageLayoutType: z.enum([
+ PageLayoutType.DASHBOARD,
+ PageLayoutType.RECORD_PAGE,
+ ]),
+});
+
+export const buildFrontComponentEntrySource = ({
+ componentId,
+ name,
+ source,
+ query,
+ pageLayoutType,
+}: FrontComponentBuildInput): string => {
+ const parsedOptions = frontComponentEntryOptionsSchema.safeParse({
+ query,
+ pageLayoutType,
+ });
+
+ if (!parsedOptions.success) {
+ throw new FrontComponentBuildException({
+ message: parsedOptions.error.message,
+ code: 'INVALID_INPUT',
+ userFriendlyMessage: msg`Invalid front component settings.`,
+ });
+ }
+
+ return `import { defineFrontComponent } from 'twenty-sdk/define';
+import type { ComponentProps as TwentyComponentProps } from 'react';
+import { ThemeProvider as TwentyThemeProvider } from 'twenty-ui/theme';
+import { PageLayoutType as TwentyPageLayoutType } from 'twenty-shared/types';
+import 'twenty-ui/style.css';
+import 'twenty-ui/theme-light.css';
+${source}
+export const componentQuery = ${JSON.stringify(parsedOptions.data.query)};
+function ${FRONT_COMPONENT_WRAPPER_NAME}(props: TwentyComponentProps<typeof Component>) {
+ return <TwentyThemeProvider colorScheme="light"><Component {...props} /></TwentyThemeProvider>;
+}
+export default defineFrontComponent({
+ universalIdentifier: ${JSON.stringify(componentId)},
+ name: ${JSON.stringify(name)},
+ component: ${FRONT_COMPONENT_WRAPPER_NAME},
+ widgetAvailability: { pageLayoutType: TwentyPageLayoutType.${parsedOptions.data.pageLayoutType} },
+});
+`;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-with-limits-or-throw.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-with-limits-or-throw.util.ts
new file mode 100644
index 00000000000..040d0d004fd
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-with-limits-or-throw.util.ts
@@ -0,0 +1,63 @@
+import { FRONT_COMPONENT_BUILD_TIMEOUT_MS } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-build-timeout-ms.constant';
+import { context, type BuildOptions } from 'esbuild';
+import { isDefined } from 'twenty-shared/utils';
+import { msg } from '@lingui/core/macro';
+
+import { FrontComponentBuildException } from 'src/engine/metadata-modules/ai/ai-front-component/exceptions/front-component-build.exception';
+
+import { FRONT_COMPONENT_MAX_BUILD_OUTPUT_BYTES } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-max-build-output-bytes.constant';
+
+export const buildFrontComponentWithLimitsOrThrow = async (
+ options: BuildOptions,
+) => {
+ try {
+ const buildContext = await context({ ...options, write: false });
+ let timeoutError: FrontComponentBuildException | undefined;
+ const timeout = setTimeout(() => {
+ timeoutError = new FrontComponentBuildException({
+ message: 'Component build exceeded the 10 second time limit.',
+ code: 'BUILD_FAILED',
+ userFriendlyMessage: msg`Component build exceeded the 10 second time limit.`,
+ });
+ void buildContext.cancel();
+ }, FRONT_COMPONENT_BUILD_TIMEOUT_MS);
+
+ try {
+ const result = await buildContext.rebuild();
+
+ if (isDefined(timeoutError)) {
+ throw timeoutError;
+ }
+ if (
+ result.outputFiles.reduce(
+ (size, file) => size + file.contents.byteLength,
+ 0,
+ ) > FRONT_COMPONENT_MAX_BUILD_OUTPUT_BYTES
+ ) {
+ throw new FrontComponentBuildException({
+ message: 'Component build exceeds the 5 MB output limit.',
+ code: 'INVALID_INPUT',
+ userFriendlyMessage: msg`Component build exceeds the 5 MB output limit.`,
+ });
+ }
+
+ return result;
+ } catch (error) {
+ if (isDefined(timeoutError)) {
+ throw timeoutError;
+ }
+ throw error;
+ } finally {
+ clearTimeout(timeout);
+ await buildContext.dispose();
+ }
+ } catch (error) {
+ if (error instanceof FrontComponentBuildException) {
+ throw error;
+ }
+ throw new FrontComponentBuildException({
+ message: error instanceof Error ? error.message : String(error),
+ code: 'BUILD_FAILED',
+ });
+ }
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component.util.ts
new file mode 100644
index 00000000000..c65d822a7ee
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component.util.ts
@@ -0,0 +1,110 @@
+import { PageLayoutType } from 'twenty-shared/types';
+import { createHash } from 'crypto';
+import { dirname, join } from 'path';
+import {
+ createSharedDependenciesShimPlugin,
+ getCommonFrontComponentBuildOptions,
+ unwrapDefineFrontComponentToDirectExport,
+} from 'twenty-shared/front-component-build';
+
+import { FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER } from 'twenty-shared/application';
+
+import { type FrontComponentSharedDependencies } from 'src/engine/metadata-modules/ai/ai-front-component/types/front-component-shared-dependencies.type';
+import { FRONT_COMPONENT_SHARED_DEPENDENCIES_BANNER_PREFIX } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-shared-dependencies-banner-prefix.constant';
+import { FRONT_COMPONENT_ALLOWED_IMPORTS } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-allowed-imports.constant';
+import { FRONT_COMPONENT_WRAPPER_NAME } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-wrapper-name.constant';
+import { type FrontComponentBuildInput } from 'src/engine/metadata-modules/ai/ai-front-component/types/front-component-build-input.type';
+import { buildFrontComponentEntrySource } from 'src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-entry-source.util';
+import { buildFrontComponentWithLimitsOrThrow } from 'src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-with-limits-or-throw.util';
+import { validateFrontComponentSourceOrThrow } from 'src/engine/metadata-modules/ai/ai-front-component/utils/validate-front-component-source-or-throw.util';
+
+export const buildFrontComponent = async ({
+ input,
+ sharedDependencies,
+}: {
+ input: FrontComponentBuildInput;
+ sharedDependencies: Pick<
+ FrontComponentSharedDependencies,
+ 'checksum' | 'exportNamesBySpecifier'
+ >;
+}): Promise<{
+ source: string;
+ componentName: string;
+ compiledSource: string;
+ checksum: string;
+ sharedDependenciesChecksum: string;
+}> => {
+ validateFrontComponentSourceOrThrow(input.source);
+ const source = buildFrontComponentEntrySource(input);
+ const sourceFile = join(__dirname, 'component.front-component.tsx');
+ const result = await buildFrontComponentWithLimitsOrThrow({
+ ...getCommonFrontComponentBuildOptions(),
+ stdin: {
+ contents: unwrapDefineFrontComponentToDirectExport(source),
+ sourcefile: sourceFile,
+ resolveDir: dirname(sourceFile),
+ loader: 'tsx',
+ },
+ write: false,
+ platform: 'browser',
+ external: [FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER],
+ banner: {
+ js:
+ FRONT_COMPONENT_SHARED_DEPENDENCIES_BANNER_PREFIX +
+ sharedDependencies.checksum,
+ },
+ plugins: [
+ {
+ name: 'front-component-imports',
+ setup(build) {
+ build.onResolve({ filter: /.*/ }, ({ path, importer, kind }) => {
+ if (
+ importer !== sourceFile ||
+ [
+ ...FRONT_COMPONENT_ALLOWED_IMPORTS,
+ ...(kind === 'import-statement'
+ ? ['react-dom/client', 'twenty-shared/types']
+ : []),
+ ].includes(path)
+ ) {
+ return;
+ }
+ return {
+ errors: [
+ {
+ text: `Unsupported import: ${path}. Use React and the supported twenty-ui imports.`,
+ },
+ ],
+ };
+ });
+ },
+ },
+ {
+ name: 'front-component-page-layout',
+ setup(build) {
+ build.onResolve({ filter: /^twenty-shared\/types$/ }, ({ kind }) =>
+ kind === 'import-statement'
+ ? { path: 'page-layout', namespace: 'page-layout' }
+ : undefined,
+ );
+ build.onLoad({ filter: /.*/, namespace: 'page-layout' }, () => ({
+ contents: `export const PageLayoutType = ${JSON.stringify(PageLayoutType)};`,
+ loader: 'js',
+ }));
+ },
+ },
+ createSharedDependenciesShimPlugin({
+ getSharedDependenciesBuildContext: () => sharedDependencies,
+ }),
+ ],
+ });
+ const compiledSource = result.outputFiles[0].text;
+
+ return {
+ source,
+ sharedDependenciesChecksum: sharedDependencies.checksum,
+ componentName: FRONT_COMPONENT_WRAPPER_NAME,
+ compiledSource,
+ checksum: createHash('sha256').update(compiledSource).digest('hex'),
+ };
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/read-front-component-shared-dependencies-checksum.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/read-front-component-shared-dependencies-checksum.util.ts
new file mode 100644
index 00000000000..b9459c7d0d7
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/read-front-component-shared-dependencies-checksum.util.ts
@@ -0,0 +1,18 @@
+import { FRONT_COMPONENT_SHARED_DEPENDENCIES_BANNER_PREFIX } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-shared-dependencies-banner-prefix.constant';
+
+export const readFrontComponentSharedDependenciesChecksum = (
+ source: string,
+): string | undefined => {
+ const firstLine = source.split('\n', 1)[0];
+
+ if (
+ !firstLine.startsWith(FRONT_COMPONENT_SHARED_DEPENDENCIES_BANNER_PREFIX)
+ ) {
+ return undefined;
+ }
+ const checksum = firstLine.slice(
+ FRONT_COMPONENT_SHARED_DEPENDENCIES_BANNER_PREFIX.length,
+ );
+
+ return /^[a-f0-9]{64}$/.test(checksum) ? checksum : undefined;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/validate-front-component-source-or-throw.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/validate-front-component-source-or-throw.util.ts
new file mode 100644
index 00000000000..20fffd9a0c2
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/validate-front-component-source-or-throw.util.ts
@@ -0,0 +1,105 @@
+import * as typescript from 'typescript';
+import { isDefined } from 'twenty-shared/utils';
+
+import { FRONT_COMPONENT_ALLOWED_IMPORTS } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-allowed-imports.constant';
+import { FrontComponentBuildException } from 'src/engine/metadata-modules/ai/ai-front-component/exceptions/front-component-build.exception';
+
+export const validateFrontComponentSourceOrThrow = (source: string): void => {
+ const sourceFile = typescript.createSourceFile(
+ 'component.front-component.tsx',
+ source,
+ typescript.ScriptTarget.Latest,
+ true,
+ typescript.ScriptKind.TSX,
+ );
+ let hasComponent = false;
+
+ for (const statement of sourceFile.statements) {
+ const modifiers = typescript.canHaveModifiers(statement)
+ ? (typescript.getModifiers(statement) ?? [])
+ : [];
+ const isDefaultExport =
+ typescript.isExportAssignment(statement) ||
+ modifiers.some(
+ (modifier) => modifier.kind === typescript.SyntaxKind.DefaultKeyword,
+ ) ||
+ (typescript.isExportDeclaration(statement) &&
+ isDefined(statement.exportClause) &&
+ typescript.isNamedExports(statement.exportClause) &&
+ statement.exportClause.elements.some(
+ (element) => element.name.text === 'default',
+ ));
+
+ if (isDefaultExport) {
+ throw new FrontComponentBuildException({
+ message:
+ 'Export a named Component without a default export. Twenty adds the SDK registration.',
+ code: 'INVALID_INPUT',
+ });
+ }
+
+ if (
+ modifiers.some(
+ (modifier) => modifier.kind === typescript.SyntaxKind.ExportKeyword,
+ )
+ ) {
+ hasComponent ||=
+ (typescript.isFunctionDeclaration(statement) &&
+ statement.name?.text === 'Component') ||
+ (typescript.isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(
+ (declaration) =>
+ typescript.isIdentifier(declaration.name) &&
+ declaration.name.text === 'Component',
+ ));
+ }
+
+ // esbuild removes unused imports before running the resolver.
+ if (
+ (typescript.isImportDeclaration(statement) ||
+ typescript.isExportDeclaration(statement)) &&
+ isDefined(statement.moduleSpecifier) &&
+ typescript.isStringLiteral(statement.moduleSpecifier) &&
+ !FRONT_COMPONENT_ALLOWED_IMPORTS.includes(statement.moduleSpecifier.text)
+ ) {
+ throw new FrontComponentBuildException({
+ message: `Unsupported import: ${statement.moduleSpecifier.text}. Use React and the supported twenty-ui imports.`,
+ code: 'INVALID_INPUT',
+ });
+ }
+ }
+
+ const validateModuleCalls = (node: typescript.Node): void => {
+ if (
+ typescript.isCallExpression(node) &&
+ (node.expression.kind === typescript.SyntaxKind.ImportKeyword ||
+ (typescript.isIdentifier(node.expression) &&
+ node.expression.text === 'require'))
+ ) {
+ const specifier = node.arguments[0];
+
+ if (!isDefined(specifier) || !typescript.isStringLiteralLike(specifier)) {
+ throw new FrontComponentBuildException({
+ message: 'Use a string literal for import() and require().',
+ code: 'INVALID_INPUT',
+ });
+ }
+ if (!FRONT_COMPONENT_ALLOWED_IMPORTS.includes(specifier.text)) {
+ throw new FrontComponentBuildException({
+ message: `Unsupported import: ${specifier.text}. Use React and the supported twenty-ui imports.`,
+ code: 'INVALID_INPUT',
+ });
+ }
+ }
+ typescript.forEachChild(node, validateModuleCalls);
+ };
+
+ validateModuleCalls(sourceFile);
+
+ if (!hasComponent) {
+ throw new FrontComponentBuildException({
+ message: 'Export a named Component function or const.',
+ code: 'INVALID_INPUT',
+ });
+ }
+};
diff --git a/yarn.lock b/yarn.lock
index 0221426da62..0d90f71dd27 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -46148,6 +46148,7 @@ __metadata:
dompurify: "npm:^3.4.17"
dotenv: "npm:16.4.5"
email-reply-parser: "npm:^2.3.5"
+ esbuild: "npm:^0.28.1"
express: "npm:5.3.0"
express-session: "npm:^1.18.2"
file-type: "npm:^21.3.2"
@@ -46231,6 +46232,7 @@ __metadata:
twenty-shared: "workspace:*"
type-fest: "npm:4.10.1"
typeorm: "patch:[email protected]#./patches/typeorm+0.3.31.patch"
+ typescript: "npm:^5.9.3"
unzipper: "npm:^0.12.3"
uuid: "npm:^11.1.1"
zod: "npm:^4.6.6"