The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Build frontend shared dependencies from app lockfiles (#29018)
Weiko762e8ae4a3a4
diff --git a/packages/twenty-cli/package.json b/packages/twenty-cli/package.jsonindex 1ced263ab06..b298e7bc5da 100644--- a/packages/twenty-cli/package.json+++ b/packages/twenty-cli/package.json@@ -28,7 +28,6 @@"@types/lodash.startcase": "^4","@types/node": "^24.0.0","@types/semver": "^7.5.8",- "cjs-module-lexer": "^2.2.0","commander": "^14.0.3","execa": "^5.1.1","lodash.startcase": "^4.4.0",diff --git a/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/enumerate-shared-dependencies-export-names.ts b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/enumerate-shared-dependencies-export-names.tsindex 483053a996d..53596b3a2e4 100644--- a/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/enumerate-shared-dependencies-export-names.ts+++ b/packages/twenty-cli/src/app/bundles/front-component-build/shared-dependencies-build/utils/enumerate-shared-dependencies-export-names.ts@@ -1,14 +1,7 @@-import { readFile } from 'node:fs/promises';-import { resolve } from 'node:path';--import { init, parse } from 'cjs-module-lexer';-import * as esbuild from 'esbuild';-import ts from 'typescript';-import { isDefined } from 'twenty-shared/utils';+import { enumerateSharedDependenciesExportNames as enumerateExports } from 'twenty-shared/front-component-build';import { getWatchInputPlugins } from '@/app/dev/collect-watch-inputs';import { getBaseFrontComponentBuildOptions } from '@/app/bundles/front-component-build/utils/get-base-front-component-build-options';-import { type SharedDependenciesExportNames } from 'twenty-shared/front-component-build';export const enumerateSharedDependenciesExportNames = async ({appPath,@@ -16,92 +9,18 @@ export const enumerateSharedDependenciesExportNames = async ({}: {appPath: string;specifier: string;-}): Promise<SharedDependenciesExportNames> => {+}) => {+ const options = getBaseFrontComponentBuildOptions();+try {- const options = getBaseFrontComponentBuildOptions();- const isWrappedJsxRuntime = specifier === 'react/jsx-runtime';- const result = await esbuild.build({- ...options,- absWorkingDir: appPath,- plugins: [- ...getWatchInputPlugins(),- ...(options.plugins ?? []).filter(- (plugin) =>- isWrappedJsxRuntime || plugin.name !== 'jsx-runtime-remote-wrapper',- ),- ],- entryPoints: [specifier],- write: false,- outfile: 'shared-dependency-probe.js',- outExtension: undefined,- external: [],- sourcemap: false,- metafile: true,+ return await enumerateExports({+ appPath,+ specifier,+ buildOptions: {+ ...options,+ plugins: [...getWatchInputPlugins(), ...(options.plugins ?? [])],+ },});- const output = Object.values(result.metafile.outputs).find((entry) =>- isDefined(entry.entryPoint),- );-- if (!isDefined(output?.entryPoint))- throw new Error('Missing dependency entry point.');-- const exports = new Set(output.exports);- const visited = new Set<string>();- const collectReexportedNames = async (path: string): Promise<void> => {- if (visited.has(path)) return;- visited.add(path);-- const input = result.metafile.inputs[path];-- if (!isDefined(input)) return;- const source = await readFile(resolve(appPath, path), 'utf8');- let reexports: string[];-- if (input.format === 'cjs') {- await init();- const transformed = await esbuild.transform(source, {- define: options.define,- minifySyntax: true,- loader: 'js',- });- const parsed = parse(transformed.code);-- for (const name of parsed.exports) {- if (name !== '__esModule') exports.add(name);- }- reexports = parsed.reexports;- } else {- const sourceFile = ts.createSourceFile(- path,- source,- ts.ScriptTarget.Latest,- );- reexports = sourceFile.statements.flatMap((statement) =>- ts.isExportDeclaration(statement) &&- !isDefined(statement.exportClause) &&- isDefined(statement.moduleSpecifier) &&- ts.isStringLiteral(statement.moduleSpecifier)- ? [statement.moduleSpecifier.text]- : [],- );- }-- for (const reexport of reexports) {- const imported = input.imports.find(- (entry) => entry.original === reexport && !entry.external,- );-- if (isDefined(imported)) await collectReexportedNames(imported.path);- }- };-- // The virtual JSX wrapper declares all of its exports in the build metadata.- if (!isWrappedJsxRuntime) await collectReexportedNames(output.entryPoint);-- return {- namedExports: [...exports].filter((name) => name !== 'default').sort(),- hasDefaultExport: exports.has('default'),- };} catch (cause) {throw new Error(`Unable to determine the exports of shared dependency "${specifier}". Check that it is installed and importable from the application.`,diff --git a/packages/twenty-server/nest-cli.json b/packages/twenty-server/nest-cli.jsonindex 99c37f10aaa..dcb6b135c30 100644--- a/packages/twenty-server/nest-cli.json+++ b/packages/twenty-server/nest-cli.json@@ -72,6 +72,10 @@{"include": "engine/core-modules/application/application-package/constants/workspace-custom-application-dependencies/**","outDir": "dist/assets"+ },+ {+ "include": "engine/core-modules/application/application-package/constants/yarn-engine/*.cjs",+ "outDir": "dist"}]},diff --git a/packages/twenty-server/src/engine/core-modules/application/application-package/constants/yarn-engine/install-yarn-dependencies.cjs b/packages/twenty-server/src/engine/core-modules/application/application-package/constants/yarn-engine/install-yarn-dependencies.cjsnew file mode 100644index 00000000000..508294c9ab7--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-package/constants/yarn-engine/install-yarn-dependencies.cjs@@ -0,0 +1,31 @@+const { execFile } = require('child_process');+const { cp } = require('fs/promises');+const { join } = require('path');+const { promisify } = require('util');++const execFilePromise = promisify(execFile);+const YARN_ENGINE_RELATIVE_PATH = '.yarn/releases/yarn-4.9.2.cjs';++const installYarnDependencies = async ({+ directory,+ yarnEngineDirectory,+ args,+ env = {},+ timeout,+}) => {+ await cp(yarnEngineDirectory, directory, { recursive: true });++ // A parent tsx loader must not be inherited by Yarn.+ const { NODE_OPTIONS: _nodeOptions, ...environment } = {+ ...process.env,+ ...env,+ };++ return execFilePromise(+ process.execPath,+ [join(directory, YARN_ENGINE_RELATIVE_PATH), ...args],+ { cwd: directory, env: environment, timeout },+ );+};++module.exports = { installYarnDependencies };diff --git a/packages/twenty-server/src/engine/core-modules/application/application-package/constants/yarn-engine/install-yarn-dependencies.d.cts b/packages/twenty-server/src/engine/core-modules/application/application-package/constants/yarn-engine/install-yarn-dependencies.d.ctsnew file mode 100644index 00000000000..aebdf578356--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-package/constants/yarn-engine/install-yarn-dependencies.d.cts@@ -0,0 +1,7 @@+export declare const installYarnDependencies: (options: {+ directory: string;+ yarnEngineDirectory: string;+ args: string[];+ env?: NodeJS.ProcessEnv;+ timeout?: number;+}) => Promise<{ stdout: string; stderr: string }>;diff --git a/packages/twenty-server/src/engine/core-modules/application/application-package/utils/__tests__/install-yarn-dependencies.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-package/utils/__tests__/install-yarn-dependencies.util.spec.tsnew file mode 100644index 00000000000..5764ba6ce4f--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/application/application-package/utils/__tests__/install-yarn-dependencies.util.spec.ts@@ -0,0 +1,84 @@+import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';++import { installYarnDependencies } from 'src/engine/core-modules/application/application-package/constants/yarn-engine/install-yarn-dependencies.cjs';++jest.useRealTimers();++describe('installYarnDependencies', () => {+ let directory: string;+ let yarnEngineDirectory: string;++ beforeEach(async () => {+ directory = await mkdtemp(join(tmpdir(), 'yarn-install-test-'));+ yarnEngineDirectory = join(directory, 'engine');+ await mkdir(join(yarnEngineDirectory, '.yarn/releases'), {+ recursive: true,+ });+ await writeFile(+ join(yarnEngineDirectory, '.yarn/releases/yarn-4.9.2.cjs'),+ `+const { writeFileSync } = require('fs');+writeFileSync('install-result.json', JSON.stringify({+ args: process.argv.slice(2),+ cwd: process.cwd(),+ nodeOptions: process.env.NODE_OPTIONS,+ scripts: process.env.YARN_ENABLE_SCRIPTS,+}));+`,+ );+ });++ afterEach(async () => {+ jest.restoreAllMocks();+ await rm(directory, { recursive: true, force: true });+ });++ it.each([+ ['install', '--immutable'],+ ['workspaces', 'focus', '--all', '--production'],+ ])('runs the copied engine with caller arguments %j', async (...args) => {+ const destination = join(directory, 'install');+ jest.replaceProperty(process, 'env', {+ ...process.env,+ NODE_OPTIONS: '--require=/missing-parent-loader.cjs',+ });++ await installYarnDependencies({+ directory: destination,+ yarnEngineDirectory,+ args,+ env: { YARN_ENABLE_SCRIPTS: 'false' },+ timeout: 5000,+ });++ const result = JSON.parse(+ await readFile(join(destination, 'install-result.json'), 'utf8'),+ );+ expect(result).toEqual({+ args,+ cwd: await realpath(destination),+ scripts: 'false',+ });+ });++ it('preserves installer stderr on failure', async () => {+ await writeFile(+ join(yarnEngineDirectory, '.yarn/releases/yarn-4.9.2.cjs'),+ `process.stderr.write('dependency resolution failed'); process.exit(1);`,+ );++ await expect(+ installYarnDependencies({+ directory: join(directory, 'install'),+ yarnEngineDirectory,+ args: ['install', '--immutable'],+ timeout: 5000,+ }),+ ).rejects.toMatchObject({+ stderr: 'dependency resolution failed',+ code: 1,+ });+ });+});diff --git a/packages/twenty-server/src/engine/core-modules/application/application-package/utils/copy-yarn-engine-and-build-dependencies.ts b/packages/twenty-server/src/engine/core-modules/application/application-package/utils/copy-yarn-engine-and-build-dependencies.tsindex 58bed205171..3407cf6f9b3 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-package/utils/copy-yarn-engine-and-build-dependencies.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-package/utils/copy-yarn-engine-and-build-dependencies.ts@@ -1,11 +1,8 @@-import { execFile } from 'child_process';import { promises as fs, statSync } from 'fs';import { join } from 'path';-import { promisify } from 'util';import { YARN_ENGINE_DIRNAME } from 'src/engine/core-modules/application/application-package/constants/yarn-engine-dirname';--const execFilePromise = promisify(execFile);+import { installYarnDependencies } from 'src/engine/core-modules/application/application-package/constants/yarn-engine/install-yarn-dependencies.cjs';export const copyYarnEngineAndBuildDependencies = async (buildDirectory: string,@@ -14,24 +11,12 @@ export const copyYarnEngineAndBuildDependencies = async (recursive: true,});- await fs.cp(YARN_ENGINE_DIRNAME, buildDirectory, {- recursive: true,- });-- const localYarnPath = join(buildDirectory, '.yarn/releases/yarn-4.9.2.cjs');-- // Strip NODE_OPTIONS to prevent tsx loader from interfering with yarn- const { NODE_OPTIONS: _nodeOptions, ...cleanEnv } = process.env;-try {- await execFilePromise(- process.execPath,- [localYarnPath, 'workspaces', 'focus', '--all', '--production'],- {- cwd: buildDirectory,- env: cleanEnv,- },- );+ await installYarnDependencies({+ directory: buildDirectory,+ yarnEngineDirectory: YARN_ENGINE_DIRNAME,+ args: ['workspaces', 'focus', '--all', '--production'],+ });// oxlint-disable-next-line typescript/no-explicit-any} catch (error: any) {const errorMessage =diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/constants/yarn-install/index.mjs b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/constants/yarn-install/index.mjsindex fed952e4133..9bc937992ea 100644--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/constants/yarn-install/index.mjs+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/constants/yarn-install/index.mjs@@ -4,10 +4,10 @@ import { join, resolve } from 'path';import archiver from 'archiver';import { pipeline } from 'stream/promises';+import { installYarnDependencies } from './yarn-engine/install-yarn-dependencies.cjs';const YARN_INSTALL_TIMEOUT_MS = 240_000;const YARN_ENGINE_DIR = resolve('yarn-engine');-const YARN_ENGINE_PATH = join(YARN_ENGINE_DIR, '.yarn/releases/yarn-4.9.2.cjs');const writePackageFiles = async (nodejsDir, packageJson, yarnLock) => {await fs.mkdir(nodejsDir, { recursive: true });@@ -17,31 +17,16 @@ const writePackageFiles = async (nodejsDir, packageJson, yarnLock) => {]);};-const copyYarnEngine = async (nodejsDir) => {- await fs.cp('yarn-engine', nodejsDir, { recursive: true });-};-const runYarnInstall = async (nodejsDir) => {- const { execFile } = await import('child_process');- const { promisify } = await import('util');- const execFilePromise = promisify(execFile);-- const { NODE_OPTIONS: _nodeOptions, ...cleanEnv } = process.env;-- // Lambda runs as a sandboxed user whose $HOME doesn't exist.- // Yarn needs a writable HOME for its global cache/config.- cleanEnv.HOME = '/tmp';-try {- await execFilePromise(- process.execPath,- [YARN_ENGINE_PATH, 'workspaces', 'focus', '--all', '--production'],- {- cwd: nodejsDir,- env: cleanEnv,- timeout: YARN_INSTALL_TIMEOUT_MS,- },- );+ await installYarnDependencies({+ directory: nodejsDir,+ yarnEngineDirectory: YARN_ENGINE_DIR,+ args: ['workspaces', 'focus', '--all', '--production'],+ // The Lambda user's HOME does not exist.+ env: { HOME: '/tmp' },+ timeout: YARN_INSTALL_TIMEOUT_MS,+ });} catch (error) {const details = [error?.stdout, error?.stderr].filter(Boolean).join('\n');@@ -114,7 +99,6 @@ export const handler = async (event) => {try {await writePackageFiles(nodejsDir, packageJson, yarnLock);- await copyYarnEngine(nodejsDir);await runYarnInstall(nodejsDir);await createZip(buildDir, zipPath);diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-tool-functions.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-tool-functions.service.tsindex 7cd76f27f02..7b678df0747 100644--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-tool-functions.service.ts+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/services/lambda-tool-functions.service.ts@@ -11,6 +11,7 @@ import {import { isNonEmptyString } from '@sniptt/guards';import { isDefined } from 'twenty-shared/utils';+import { YARN_ENGINE_DIRNAME } from 'src/engine/core-modules/application/application-package/constants/yarn-engine-dirname';import { COMMON_LAYER_DEPENDENCIES_DIRNAME } from 'src/engine/core-modules/logic-function/logic-function-drivers/constants/common-layer-dependencies-dirname';import {BUILDER_FUNCTION_NAME_PREFIX,@@ -334,16 +335,20 @@ export class LambdaToolFunctionsService {return this.yarnInstallFunctionName;}- const handlerContent = await fs.readFile(- YARN_INSTALL_HANDLER_PATH,- 'utf-8',- );+ const [handlerContent, installerContent] = await Promise.all([+ fs.readFile(YARN_INSTALL_HANDLER_PATH, 'utf-8'),+ fs.readFile(+ join(YARN_ENGINE_DIRNAME, 'install-yarn-dependencies.cjs'),+ 'utf-8',+ ),+ ]);this.yarnInstallFunctionName = computeHashedLambdaResourceName({resourceNamePrefix: YARN_INSTALL_FUNCTION_NAME_PREFIX,namespace: this.options.resourceNamespace,contents: [handlerContent,+ installerContent,String(YARN_INSTALL_LAMBDA_MEMORY_MB),String(YARN_INSTALL_LAMBDA_TIMEOUT_SECONDS),String(LAMBDA_EPHEMERAL_STORAGE_MB),diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component-shared-dependencies.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component-shared-dependencies.util.spec.tsnew file mode 100644index 00000000000..ba9351c905e--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component-shared-dependencies.util.spec.ts@@ -0,0 +1,169 @@+import { runInNewContext } from 'node:vm';+import {+ getSharedDependenciesShimSource,+ toSharedDependenciesNamespaceIdentifier,+} from 'twenty-shared/front-component-build';+import { createHash } from 'crypto';+import { FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER } from 'twenty-shared/application';+import { buildFrontComponentSharedDependencies } from 'src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-shared-dependencies.util';+import { build, transform } from 'esbuild';+import { PageLayoutType } from 'twenty-shared/types';++import { buildFrontComponent as compileFrontComponent } from 'src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component.util';++jest.useRealTimers();+jest.setTimeout(30_000);+let sharedDependencies: Awaited<+ ReturnType<typeof buildFrontComponentSharedDependencies>+>;+beforeAll(async () => {+ sharedDependencies = await buildFrontComponentSharedDependencies({+ resolveDirectory: __dirname,+ });+});+const buildFrontComponent = async (+ input: Parameters<typeof compileFrontComponent>[0]['input'],+) => ({+ ...(await compileFrontComponent({ input, sharedDependencies })),+ 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('buildFrontComponentSharedDependencies', () => {+ it('loads real twenty-ui controls, icons and theme from one pinned shared bundle', async () => {+ const { compiledSource, sharedDependencies } = await buildFrontComponent({+ ...INPUT,+ source: `import { Button } from 'twenty-ui/primitives/input';+import { SearchInput } from 'twenty-ui/components/input';+import { Card } from 'twenty-ui/primitives/surfaces';+import { IconBuildingSkyscraper } from 'twenty-ui/icon';+export function Component() {+ return <Card.Root><Card.Content><SearchInput aria-label="Filter companies" /><Button startIcon={<IconBuildingSkyscraper />}>Reset</Button></Card.Content></Card.Root>;+}`,+ });++ expect(compiledSource).toContain('Filter companies');+ expect(compiledSource).toContain(+ FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER,+ );+ expect(compiledSource).toMatch(+ new RegExp(+ '^// twenty-ai-shared-dependencies: ' ++ sharedDependencies.checksum ++ '\\n',+ ),+ );+ expect(+ sharedDependencies.exportNamesBySpecifier.get('react-dom')?.namedExports,+ ).toContain('createPortal');+ expect(+ sharedDependencies.exportNamesBySpecifier.get('react-dom/client')+ ?.namedExports,+ ).toContain('createRoot');+ expect(compiledSource).not.toContain('--t-font-color-primary:');+ expect(sharedDependencies.source).toContain('--t-font-color-primary:');+ expect(+ sharedDependencies.exportNamesBySpecifier.get(+ 'twenty-ui/primitives/input',+ )?.namedExports,+ ).toContain('Button');+ expect(+ sharedDependencies.exportNamesBySpecifier.get('react')?.namedExports,+ ).toContain('useState');+ expect(Buffer.byteLength(compiledSource)).toBeLessThan(+ Buffer.byteLength(sharedDependencies.source) / 5,+ );+ const next = await buildFrontComponent(INPUT);+ expect(next.sharedDependencies).toBe(sharedDependencies);+ const rebuilt = await buildFrontComponentSharedDependencies({+ resolveDirectory: __dirname,+ });+ expect(rebuilt.checksum).toBe(sharedDependencies.checksum);+ expect(+ createHash('sha256').update(sharedDependencies.source).digest('hex'),+ ).toBe(sharedDependencies.checksum);+ await expect(+ build({+ stdin: { contents: compiledSource, loader: 'js' },+ write: false,+ bundle: true,+ format: 'esm',+ plugins: [+ {+ name: 'test-vendor',+ setup(build) {+ build.onResolve(+ { filter: /^twenty:front-component-shared-dependencies$/ },+ () => ({ path: 'vendor', namespace: 'vendor' }),+ );+ build.onLoad({ filter: /.*/, namespace: 'vendor' }, () => ({+ contents: sharedDependencies.source,+ loader: 'js',+ }));+ },+ },+ ],+ }),+ ).resolves.toHaveProperty('outputFiles');+ expect(compiledSource).not.toMatch(/from\s*['"]twenty-ui/);+ });++ it('exposes every server vendor export through the shared CLI and SDK shim format', async () => {+ const vendorModule: {+ exports: Record<string, Record<string, unknown>>;+ } = { exports: {} };+ const vendor = await transform(sharedDependencies.source, {+ format: 'cjs',+ });++ runInNewContext(vendor.code, {+ module: vendorModule,+ exports: vendorModule.exports,+ });++ for (const [+ specifier,+ exportNames,+ ] of sharedDependencies.exportNamesBySpecifier) {+ const shim = await transform(+ getSharedDependenciesShimSource({ specifier, exportNames }),+ { format: 'cjs' },+ );+ const shimModule: { exports: Record<string, unknown> } = { exports: {} };++ runInNewContext(shim.code, {+ module: shimModule,+ exports: shimModule.exports,+ require: () => vendorModule.exports,+ });++ const namespace =+ vendorModule.exports[+ toSharedDependenciesNamespaceIdentifier(specifier)+ ];+ const names = [+ ...exportNames.namedExports,+ ...(exportNames.hasDefaultExport ? ['default'] : []),+ ];++ for (const name of names) {+ expect(shimModule.exports[name]).toBe(namespace[name]);+ }+ }+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-shared-dependencies.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-shared-dependencies.util.tsnew file mode 100644index 00000000000..d75b1d5b37f--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-shared-dependencies.util.ts@@ -0,0 +1,60 @@+import { createHash } from 'crypto';+import {+ createJsxRuntimeRemoteWrapperPlugin,+ cssInjectionPlugin,+ getCommonFrontComponentBuildOptions,+ getSharedDependenciesEntrySource,+ enumerateSharedDependenciesExportNames,+} from 'twenty-shared/front-component-build';++import { FRONT_COMPONENT_UI_IMPORTS } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-ui-imports.constant';+import { type FrontComponentSharedDependencies } from 'src/engine/metadata-modules/ai/ai-front-component/types/front-component-shared-dependencies.type';+import { buildFrontComponentWithLimitsOrThrow } from 'src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-with-limits-or-throw.util';++export const buildFrontComponentSharedDependencies = async ({+ resolveDirectory,+}: {+ resolveDirectory: string;+}): Promise<FrontComponentSharedDependencies> => {+ const dependencies = [+ 'react',+ 'react-dom',+ 'react-dom/client',+ 'react/jsx-runtime',+ ...FRONT_COMPONENT_UI_IMPORTS,+ ];+ const exportNamesBySpecifier = new Map(+ await Promise.all(+ dependencies.map(+ async (specifier) =>+ [+ specifier,+ await enumerateSharedDependenciesExportNames({+ appPath: resolveDirectory,+ specifier,+ build: buildFrontComponentWithLimitsOrThrow,+ }),+ ] as const,+ ),+ ),+ );+ const result = await buildFrontComponentWithLimitsOrThrow({+ ...getCommonFrontComponentBuildOptions(),+ stdin: {+ contents: getSharedDependenciesEntrySource(exportNamesBySpecifier),+ resolveDir: resolveDirectory,+ sourcefile: 'front-component-shared-dependencies.js',+ loader: 'js',+ },+ write: false,+ platform: 'browser',+ plugins: [createJsxRuntimeRemoteWrapperPlugin(), cssInjectionPlugin],+ });+ const source = result.outputFiles[0].text;++ return {+ source,+ checksum: createHash('sha256').update(source).digest('hex'),+ exportNamesBySpecifier,+ };+};diff --git a/packages/twenty-shared/package.json b/packages/twenty-shared/package.jsonindex fb70e03cd90..030130e7e15 100644--- a/packages/twenty-shared/package.json+++ b/packages/twenty-shared/package.json@@ -30,7 +30,6 @@"@types/uuid": "^9.0.2","@typescript/native-preview": "^7.0.0-dev.20260116.1","babel-plugin-module-resolver": "^5.0.2",- "esbuild": "^0.28.1","glob": "^11.1.0","jest": "29.7.0","jest-environment-jsdom": "30.0.0-beta.3",@@ -48,8 +47,10 @@"@sniptt/guards": "^0.2.0","addressparser": "1.0.1","ai": "7.0.126",+ "cjs-module-lexer": "^2.2.0","class-validator": "^0.14.0","entities": "^4.5.0",+ "esbuild": "^0.28.1","expr-eval-fork": "3.0.3","libphonenumber-js": "^1.10.26","lodash.camelcase": "^4.3.0",diff --git a/packages/twenty-shared/project.json b/packages/twenty-shared/project.jsonindex 9dac31d9a46..c12c5f58cf5 100644--- a/packages/twenty-shared/project.json+++ b/packages/twenty-shared/project.json@@ -80,8 +80,8 @@],"options": { "command": "tsx {projectRoot}/scripts/generateBarrels.ts" }},- "typecheck": {},- "test": {},+ "typecheck": { "dependsOn": ["build"] },+ "test": { "dependsOn": ["build"] },"lint": { "options": {}, "configurations": { "fix": {} } },"fmt": { "options": { "files": "src" }, "configurations": { "fix": {} } }}diff --git a/packages/twenty-shared/src/front-component-build/__tests__/enumerate-shared-dependencies-export-names.test.ts b/packages/twenty-shared/src/front-component-build/__tests__/enumerate-shared-dependencies-export-names.test.tsnew file mode 100644index 00000000000..86c0f982d91--- /dev/null+++ b/packages/twenty-shared/src/front-component-build/__tests__/enumerate-shared-dependencies-export-names.test.ts@@ -0,0 +1,102 @@+/** @jest-environment node */++import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import * as esbuild from 'esbuild';++import { enumerateSharedDependenciesExportNames } from 'twenty-shared/front-component-build';++jest.useRealTimers();++describe('enumerateSharedDependenciesExportNames', () => {+ let appPath: string;++ beforeEach(async () => {+ appPath = await mkdtemp(join(tmpdir(), 'shared-export-discovery-'));+ });++ afterEach(async () => {+ await rm(appPath, { recursive: true, force: true });+ });++ it('discovers browser exports without executing package code', async () => {+ await writeFile(+ join(appPath, 'browser.mjs'),+ `throw new Error('must not execute');+export const element = document.createElement('div');+export default window.location;`,+ );++ await expect(+ enumerateSharedDependenciesExportNames({+ appPath,+ specifier: './browser.mjs',+ }),+ ).resolves.toEqual({ namedExports: ['element'], hasDefaultExport: true });+ });++ it('collects production CommonJS reexports through cycles without evaluation', async () => {+ await writeFile(+ join(appPath, 'index.cjs'),+ `if (process.env.NODE_ENV === 'production') {+ module.exports = require('./production.cjs');+} else {+ module.exports = require('./development.cjs');+}+throw new Error('must not execute');`,+ );+ await writeFile(+ join(appPath, 'production.cjs'),+ `exports.production = true; Object.assign(exports, require('./index.cjs'));`,+ );+ await writeFile(+ join(appPath, 'development.cjs'),+ 'exports.development = true;',+ );++ await expect(+ enumerateSharedDependenciesExportNames({+ appPath,+ specifier: './index.cjs',+ }),+ ).resolves.toEqual({+ namedExports: ['production'],+ hasDefaultExport: true,+ });+ });++ it('preserves an injected build failure for bounded server builds', async () => {+ const error = new Error('Build timed out');++ await expect(+ enumerateSharedDependenciesExportNames({+ appPath,+ specifier: './index.mjs',+ build: async () => {+ throw error;+ },+ }),+ ).rejects.toBe(error);+ });++ it('rejects incomplete input metadata instead of returning partial exports', async () => {+ await writeFile(join(appPath, 'index.cjs'), 'exports.example = true;');++ await expect(+ enumerateSharedDependenciesExportNames({+ appPath,+ specifier: './index.cjs',+ build: async (options) => {+ const result = await esbuild.build({ ...options, metafile: true });++ return {+ ...result,+ metafile: { ...result.metafile, inputs: {} },+ };+ },+ }),+ ).rejects.toThrow('Missing dependency input metadata for "index.cjs".');+ });+});diff --git a/packages/twenty-shared/src/front-component-build/enumerate-shared-dependencies-export-names.ts b/packages/twenty-shared/src/front-component-build/enumerate-shared-dependencies-export-names.tsnew file mode 100644index 00000000000..37b94720630--- /dev/null+++ b/packages/twenty-shared/src/front-component-build/enumerate-shared-dependencies-export-names.ts@@ -0,0 +1,124 @@+import { readFile } from 'node:fs/promises';+import { resolve } from 'node:path';++import { init, parse } from 'cjs-module-lexer';+import * as esbuild from 'esbuild';+import ts from 'typescript';+import { isDefined } from '@/utils/validation/isDefined';++import { getCommonFrontComponentBuildOptions } from './get-common-front-component-build-options';+import { createJsxRuntimeRemoteWrapperPlugin } from './jsx-runtime-remote-wrapper-plugin';+import { cssInjectionPlugin } from './css-injection-plugin';+import { type SharedDependenciesExportNames } from './shared-dependencies-export-names.type';++export const enumerateSharedDependenciesExportNames = async ({+ appPath,+ specifier,+ build = esbuild.build,+ buildOptions = {+ ...getCommonFrontComponentBuildOptions(),+ plugins: [createJsxRuntimeRemoteWrapperPlugin(), cssInjectionPlugin],+ },+}: {+ appPath: string;+ specifier: string;+ build?: (options: esbuild.BuildOptions) => Promise<esbuild.BuildResult>;+ buildOptions?: esbuild.BuildOptions;+}): Promise<SharedDependenciesExportNames> => {+ const isWrappedJsxRuntime = specifier === 'react/jsx-runtime';+ const result = await build({+ ...buildOptions,+ absWorkingDir: appPath,+ plugins: (buildOptions.plugins ?? []).filter(+ (plugin) =>+ isWrappedJsxRuntime || plugin.name !== 'jsx-runtime-remote-wrapper',+ ),+ entryPoints: [specifier],+ write: false,+ outfile: 'shared-dependency-probe.js',+ outExtension: undefined,+ external: [],+ sourcemap: false,+ metafile: true,+ });+ const output = Object.values(result.metafile?.outputs ?? {}).find((entry) =>+ isDefined(entry.entryPoint),+ );++ if (!isDefined(output?.entryPoint)) {+ throw new Error('Missing dependency entry point.');+ }++ const exports = new Set(output.exports);+ const visited = new Set<string>();+ const collectReexportedNames = async (path: string): Promise<void> => {+ if (visited.has(path)) {+ return;+ }+ visited.add(path);++ const input = result.metafile?.inputs[path];++ if (!isDefined(input)) {+ throw new Error(`Missing dependency input metadata for "${path}".`);+ }++ const source = await readFile(resolve(appPath, path), 'utf8');+ let reexports: string[];++ if (input.format === 'cjs') {+ await init();+ const transformed = await esbuild.transform(source, {+ define: buildOptions.define,+ minifySyntax: true,+ loader: 'js',+ });+ const parsed = parse(transformed.code);++ for (const name of parsed.exports) {+ if (name !== '__esModule') {+ exports.add(name);+ }+ }+ reexports = parsed.reexports;+ } else {+ const sourceFile = ts.createSourceFile(+ path,+ source,+ ts.ScriptTarget.Latest,+ );+ reexports = sourceFile.statements.flatMap((statement) => {+ if (+ !ts.isExportDeclaration(statement) ||+ isDefined(statement.exportClause) ||+ !isDefined(statement.moduleSpecifier) ||+ !ts.isStringLiteral(statement.moduleSpecifier)+ ) {+ return [];+ }++ return [statement.moduleSpecifier.text];+ });+ }++ for (const reexport of reexports) {+ const imported = input.imports.find(+ (entry) => entry.original === reexport && !entry.external,+ );++ if (isDefined(imported)) {+ await collectReexportedNames(imported.path);+ }+ }+ };++ // The virtual JSX wrapper declares all of its exports in the build metadata.+ if (!isWrappedJsxRuntime) {+ await collectReexportedNames(output.entryPoint);+ }++ return {+ namedExports: [...exports].filter((name) => name !== 'default').sort(),+ hasDefaultExport: exports.has('default'),+ };+};diff --git a/packages/twenty-shared/src/front-component-build/index.ts b/packages/twenty-shared/src/front-component-build/index.tsindex ec7ea5be44a..7ce915b70a7 100644--- a/packages/twenty-shared/src/front-component-build/index.ts+++ b/packages/twenty-shared/src/front-component-build/index.ts@@ -12,6 +12,7 @@ export {createCssInjectionPlugin,cssInjectionPlugin,} from './css-injection-plugin';+export { enumerateSharedDependenciesExportNames } from './enumerate-shared-dependencies-export-names';export { getCommonFrontComponentBuildOptions } from './get-common-front-component-build-options';export { getSharedDependenciesEntrySource } from './get-shared-dependencies-entry-source';export { getSharedDependenciesShimSource } from './get-shared-dependencies-shim-source';diff --git a/yarn.lock b/yarn.lockindex 0d90f71dd27..4edbcacc6b6 100644--- a/yarn.lock+++ b/yarn.lock@@ -46263,6 +46263,7 @@ __metadata:addressparser: "npm:1.0.1"ai: "npm:7.0.126"babel-plugin-module-resolver: "npm:^5.0.2"+ cjs-module-lexer: "npm:^2.2.0"class-validator: "npm:^0.14.0"entities: "npm:^4.5.0"esbuild: "npm:^0.28.1"@@ -46448,7 +46449,6 @@ __metadata:"@types/node": "npm:^24.0.0""@types/semver": "npm:^7.5.8"chokidar: "npm:^3.6.0"- cjs-module-lexer: "npm:^2.2.0"commander: "npm:^14.0.3"esbuild: "npm:^0.28.1"execa: "npm:^5.1.1"