The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Move sdk watcher back to esbuild (#17316)
Charles Bochet5a94ef7dbbf7
diff --git a/packages/twenty-sdk/package.json b/packages/twenty-sdk/package.jsonindex 475ee0b4f3c..a144b3199c3 100644--- a/packages/twenty-sdk/package.json+++ b/packages/twenty-sdk/package.json@@ -38,6 +38,7 @@"chokidar": "^4.0.0","commander": "^12.0.0","dotenv": "^16.4.0",+ "esbuild": "^0.25.0","fast-glob": "^3.3.0","fs-extra": "^11.2.0","graphql": "^16.8.1",diff --git a/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/__snapshots__/app-dev.integration.spec.ts.snap b/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/__snapshots__/app-dev.integration.spec.ts.snapdeleted file mode 100644index 8d06c0e56bf..00000000000--- a/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/__snapshots__/app-dev.integration.spec.ts.snap+++ /dev/null@@ -1,25 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`rich-app app:dev > console output > should match expected output 1`] = `-"π©βπ» Workspace - default-π Starting Twenty Application Development Mode-π App Path: <APP_PATH>/root.function.ts)- - greeting-function (src/functions/greeting.function.ts)- - test-function-2 (src/utils/test-function-2.util.ts)- - test-function (src/functions/test-function.function.ts)- β Found 4 front component(s)- π Front component entry points:- - root-component (src/root.front-component.tsx)- - card-component (src/components/card.front-component.tsx)- - greeting-component (src/components/greeting.front-component.tsx)- - test-component (src/components/test.front-component.tsx)- β Found 2 role(s)- β Manifest written to <APP_PATH>/.twenty/output/manifest.json- π Manifest watcher started- π¦ Building functions...- π¨ Building front components...- β Functions built--π Watching for changes... (Press Ctrl+C to stop)- β Front components built"-`;diff --git a/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/tests/console-output.tests.ts b/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/tests/console-output.tests.tsindex 280a0155787..efb4773ac70 100644--- a/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/tests/console-output.tests.ts+++ b/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/tests/console-output.tests.ts@@ -1,14 +1,42 @@+import { getOutputByPrefix } from '@/cli/__tests__/integration/utils/get-output-by-prefix.util';import { type RunCliCommandResult } from '@/cli/__tests__/integration/utils/run-cli-command.util';-import { sanitizeOutput } from '@/cli/__tests__/integration/utils/sanitize-output.util';export const defineConsoleOutputTests = (getResult: () => RunCliCommandResult,): void => {describe('console output', () => {- it('should match expected output', () => {- const result = getResult();+ it('should contain init messages', () => {+ const output = getOutputByPrefix(getResult().output, 'init');- expect(sanitizeOutput(result.output)).toMatchSnapshot();+ expect(output).toContain('[init] π Starting Twenty Application Development Mode');+ expect(output).toContain('[init] π App Path:');+ });++ it('should contain manifest-watch messages', () => {+ const output = getOutputByPrefix(getResult().output, 'manifest-watch');++ expect(output).toContain('[manifest-watch] π Building...');+ expect(output).toContain('[manifest-watch] β Loaded "Hello World"');+ expect(output).toContain('[manifest-watch] β Found 2 object(s)');+ expect(output).toContain('[manifest-watch] β Found 4 function(s)');+ expect(output).toContain('[manifest-watch] β Found 4 front component(s)');+ expect(output).toContain('[manifest-watch] β Found 2 role(s)');+ expect(output).toContain('[manifest-watch] β Written to');+ expect(output).toContain('[manifest-watch] π Watcher started');+ });++ it('should contain functions-watch messages', () => {+ const output = getOutputByPrefix(getResult().output, 'functions-watch');++ expect(output).toContain('[functions-watch] π¦ Building...');+ expect(output).toContain('[functions-watch] β Built');+ });++ it('should contain front-components-watch messages', () => {+ const output = getOutputByPrefix(getResult().output, 'front-components-watch');++ expect(output).toContain('[front-components-watch] π¨ Building...');+ expect(output).toContain('[front-components-watch] β Built');});});};diff --git a/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/tests/functions.tests.ts b/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/tests/functions.tests.tsindex d1de2055935..ffb4c653b53 100644--- a/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/tests/functions.tests.ts+++ b/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/__integration__/app-dev/tests/functions.tests.ts@@ -21,5 +21,17 @@ export const defineFunctionsTests = (appPath: string): void => {'src/root.function.mjs.map',]);});++ it('should not create shared chunk files for utilities', async () => {+ const functionsDir = join(appPath, '.twenty/output/functions');+ const files = await fs.readdir(functionsDir, { recursive: true });++ // Chunk files have a hash suffix like "greeting.util-CipJsYK0.mjs"+ const chunkFiles = files+ .map((f) => f.toString())+ .filter((f) => f.endsWith('.mjs') && !f.includes('.function.mjs'));++ expect(chunkFiles).toEqual([]);+ });});};diff --git a/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/src/functions/test-function.function.ts b/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/src/functions/test-function.function.tsindex b547cb3aa8c..bd1dfe85991 100644--- a/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/src/functions/test-function.function.ts+++ b/packages/twenty-sdk/src/cli/__tests__/apps/rich-app/src/functions/test-function.function.ts@@ -1,7 +1,8 @@import { defineFunction } from '@/application/functions/define-function';+import { formatFarewell } from '../utils/greeting.util';const handler = () => {- return 'test-result';+ return formatFarewell('test');};export default defineFunction({diff --git a/packages/twenty-sdk/src/cli/__tests__/apps/root-app/__integration__/app-dev/tests/console-output.tests.ts b/packages/twenty-sdk/src/cli/__tests__/apps/root-app/__integration__/app-dev/tests/console-output.tests.tsindex cc9bf71912b..f77c91d22d0 100644--- a/packages/twenty-sdk/src/cli/__tests__/apps/root-app/__integration__/app-dev/tests/console-output.tests.ts+++ b/packages/twenty-sdk/src/cli/__tests__/apps/root-app/__integration__/app-dev/tests/console-output.tests.ts@@ -1,22 +1,42 @@-import { type RunCliCommandResult } from '../../../../../integration/utils/run-cli-command.util';+import { getOutputByPrefix } from '@/cli/__tests__/integration/utils/get-output-by-prefix.util';+import { type RunCliCommandResult } from '@/cli/__tests__/integration/utils/run-cli-command.util';export const defineConsoleOutputTests = (getResult: () => RunCliCommandResult,): void => {describe('console output', () => {- it('should contain key messages', () => {- const result = getResult();- const output = result.output;-- expect(output).toContain('Starting Twenty Application Development Mode');- expect(output).toContain('Building manifest');- expect(output).toContain('Loaded "Root App"');- expect(output).toContain('Found 1 object(s)');- expect(output).toContain('Found 1 function(s)');- expect(output).toContain('Found 1 front component(s)');- expect(output).toContain('Found 1 role(s)');- expect(output).toContain('Manifest written to');- expect(output).toContain('Functions built');+ it('should contain init messages', () => {+ const output = getOutputByPrefix(getResult().output, 'init');++ expect(output).toContain('[init] π Starting Twenty Application Development Mode');+ expect(output).toContain('[init] π App Path:');+ });++ it('should contain manifest-watch messages', () => {+ const output = getOutputByPrefix(getResult().output, 'manifest-watch');++ expect(output).toContain('[manifest-watch] π Building...');+ expect(output).toContain('[manifest-watch] β Loaded "Root App"');+ expect(output).toContain('[manifest-watch] β Found 1 object(s)');+ expect(output).toContain('[manifest-watch] β Found 1 function(s)');+ expect(output).toContain('[manifest-watch] β Found 1 front component(s)');+ expect(output).toContain('[manifest-watch] β Found 1 role(s)');+ expect(output).toContain('[manifest-watch] β Written to');+ expect(output).toContain('[manifest-watch] π Watcher started');+ });++ it('should contain functions-watch messages', () => {+ const output = getOutputByPrefix(getResult().output, 'functions-watch');++ expect(output).toContain('[functions-watch] π¦ Building...');+ expect(output).toContain('[functions-watch] β Built');+ });++ it('should contain front-components-watch messages', () => {+ const output = getOutputByPrefix(getResult().output, 'front-components-watch');++ expect(output).toContain('[front-components-watch] π¨ Building...');+ expect(output).toContain('[front-components-watch] β Built');});});};diff --git a/packages/twenty-sdk/src/cli/__tests__/integration/utils/get-output-by-prefix.util.ts b/packages/twenty-sdk/src/cli/__tests__/integration/utils/get-output-by-prefix.util.tsnew file mode 100644index 00000000000..fbfefeb5d6b--- /dev/null+++ b/packages/twenty-sdk/src/cli/__tests__/integration/utils/get-output-by-prefix.util.ts@@ -0,0 +1,15 @@+export type LogPrefix = 'init' | 'manifest-watch' | 'functions-watch' | 'front-components-watch';++export const getOutputByPrefix = (output: string, prefix: LogPrefix): string => {+ const prefixPattern = `[${prefix}]`;+ const lines = output.split('\n');++ return lines+ .filter((line) => line.includes(prefixPattern))+ .map((line) => {+ // Remove ANSI color codes for snapshot comparison+ const cleanLine = line.replace(/\x1B\[[0-9;]*m/g, '');+ return cleanLine.trim();+ })+ .join('\n');+};diff --git a/packages/twenty-sdk/src/cli/__tests__/integration/utils/run-app-dev.util.ts b/packages/twenty-sdk/src/cli/__tests__/integration/utils/run-app-dev.util.tsindex fce5389668e..40ed5cb6935 100644--- a/packages/twenty-sdk/src/cli/__tests__/integration/utils/run-app-dev.util.ts+++ b/packages/twenty-sdk/src/cli/__tests__/integration/utils/run-app-dev.util.ts@@ -13,9 +13,9 @@ export const runAppDev = (options: RunAppDevOptions): Promise<RunCliCommandResulcommand: 'app:dev',args: [appPath],waitForOutput: [- 'β Manifest written to',- 'β Functions built',- 'β Front components built',+ '[manifest-watch] β Written to',+ '[functions-watch] β Built',+ '[front-components-watch] β Built',],timeout,});diff --git a/packages/twenty-sdk/src/cli/commands/app/app-dev.ts b/packages/twenty-sdk/src/cli/commands/app/app-dev.tsindex 398bb3c7c3a..ee6f208e330 100644--- a/packages/twenty-sdk/src/cli/commands/app/app-dev.ts+++ b/packages/twenty-sdk/src/cli/commands/app/app-dev.ts@@ -1,9 +1,11 @@+import { createLogger } from '@/cli/utilities/build/common/logger';import { FrontComponentsWatcher } from '@/cli/utilities/build/front-components/front-component-watcher';import { FunctionsWatcher } from '@/cli/utilities/build/functions/function-watcher';import { runManifestBuild, type ManifestBuildResult } from '@/cli/utilities/build/manifest/manifest-build';import { ManifestWatcher } from '@/cli/utilities/build/manifest/manifest-watcher';import { CURRENT_EXECUTION_DIRECTORY } from '@/cli/utilities/config/constants/current-execution-directory';-import chalk from 'chalk';++const initLogger = createLogger('init');export type AppDevOptions = {appPath?: string;@@ -26,8 +28,8 @@ export class AppDevCommand {async execute(options: AppDevOptions): Promise<void> {this.appPath = options.appPath ?? CURRENT_EXECUTION_DIRECTORY;- console.log(chalk.blue('π Starting Twenty Application Development Mode'));- console.log(chalk.gray(`π App Path: ${this.appPath}`));+ initLogger.log('π Starting Twenty Application Development Mode');+ initLogger.log(`π App Path: ${this.appPath}`);console.log('');await this.startWatchers();@@ -89,26 +91,13 @@ export class AppDevCommand {}private setupGracefulShutdown(): void {- process.on('SIGINT', async () => {- console.log(chalk.yellow('\nπ Stopping development mode...'));-- const closePromises: Promise<void>[] = [];-- if (this.manifestWatcher) {- closePromises.push(this.manifestWatcher.close());- }-- if (this.functionsWatcher) {- closePromises.push(this.functionsWatcher.close());- }-- if (this.frontComponentsWatcher) {- closePromises.push(this.frontComponentsWatcher.close());- }-- await Promise.all(closePromises);-+ const shutdown = () => {+ console.log('');+ initLogger.warn('π Stopping...');process.exit(0);- });+ };++ process.on('SIGINT', shutdown);+ process.on('SIGTERM', shutdown);}}diff --git a/packages/twenty-sdk/src/cli/utilities/build/common/cleanup-removed-files.ts b/packages/twenty-sdk/src/cli/utilities/build/common/cleanup-removed-files.tsnew file mode 100644index 00000000000..517822b5139--- /dev/null+++ b/packages/twenty-sdk/src/cli/utilities/build/common/cleanup-removed-files.ts@@ -0,0 +1,23 @@+import chalk from 'chalk';+import * as fs from 'fs-extra';+import path from 'path';++export const cleanupRemovedFiles = async (+ outputDir: string,+ oldPaths: string[],+ newPaths: string[],+): Promise<void> => {+ const newPathsSet = new Set(newPaths);+ const removedPaths = oldPaths.filter((p) => !newPathsSet.has(p));++ for (const removedPath of removedPaths) {+ const outputBaseName = removedPath.replace(/\.tsx?$/, '.mjs');+ const outputFile = path.join(outputDir, outputBaseName);+ const sourceMapFile = `${outputFile}.map`;++ await fs.remove(outputFile);+ await fs.remove(sourceMapFile);++ console.log(chalk.gray(` ποΈ Removed ${outputBaseName}`));+ }+};diff --git a/packages/twenty-sdk/src/cli/utilities/build/common/display.ts b/packages/twenty-sdk/src/cli/utilities/build/common/display.tsdeleted file mode 100644index 12d34e033da..00000000000--- a/packages/twenty-sdk/src/cli/utilities/build/common/display.ts+++ /dev/null@@ -1,6 +0,0 @@-import chalk from 'chalk';--export const printWatchingMessage = (): void => {- console.log('');- console.log(chalk.gray('π Watching for changes... (Press Ctrl+C to stop)'));-};diff --git a/packages/twenty-sdk/src/cli/utilities/build/common/logger.ts b/packages/twenty-sdk/src/cli/utilities/build/common/logger.tsnew file mode 100644index 00000000000..01cdba40d33--- /dev/null+++ b/packages/twenty-sdk/src/cli/utilities/build/common/logger.ts@@ -0,0 +1,50 @@+import chalk, { type ChalkInstance } from 'chalk';++export type LoggerContext =+ | 'init'+ | 'manifest-watch'+ | 'functions-watch'+ | 'front-components-watch';++type LoggerConfig = {+ prefix: string;+ color: ChalkInstance;+};++const LOGGER_CONFIGS: Record<LoggerContext, LoggerConfig> = {+ init: {+ prefix: '[init]',+ color: chalk.cyan,+ },+ 'manifest-watch': {+ prefix: '[manifest-watch]',+ color: chalk.magenta,+ },+ 'functions-watch': {+ prefix: '[functions-watch]',+ color: chalk.yellow,+ },+ 'front-components-watch': {+ prefix: '[front-components-watch]',+ color: chalk.green,+ },+};++export type Logger = {+ log: (message: string) => void;+ success: (message: string) => void;+ error: (message: string) => void;+ warn: (message: string) => void;+};++export const createLogger = (context: LoggerContext): Logger => {+ const config = LOGGER_CONFIGS[context];+ const prefix = config.color(config.prefix);++ return {+ log: (message: string) => console.log(`${prefix} ${message}`),+ success: (message: string) => console.log(`${prefix} ${chalk.green(message)}`),+ error: (message: string) => console.error(`${prefix} ${chalk.red(message)}`),+ warn: (message: string) => console.log(`${prefix} ${chalk.yellow(message)}`),+ };+};diff --git a/packages/twenty-sdk/src/cli/utilities/build/front-components/front-component-watcher.ts b/packages/twenty-sdk/src/cli/utilities/build/front-components/front-component-watcher.tsindex 9dbc109321a..2cd1988d801 100644--- a/packages/twenty-sdk/src/cli/utilities/build/front-components/front-component-watcher.ts+++ b/packages/twenty-sdk/src/cli/utilities/build/front-components/front-component-watcher.ts@@ -1,10 +1,9 @@-import chalk from 'chalk';+import * as esbuild from 'esbuild';import * as fs from 'fs-extra';import path from 'path';-import { build, type InlineConfig, type Rollup } from 'vite';-import tsconfigPaths from 'vite-tsconfig-paths';+import { cleanupRemovedFiles } from '../common/cleanup-removed-files';import { OUTPUT_DIR } from '../common/constants';-import { printWatchingMessage } from '../common/display';+import { createLogger } from '../common/logger';import {type RestartableWatcher,type RestartableWatcherOptions,@@ -12,20 +11,23 @@ import {import { type ManifestBuildResult } from '../manifest/manifest-build';import { FRONT_COMPONENTS_DIR } from './constants';-export const FRONT_COMPONENT_EXTERNAL_MODULES: (string | RegExp)[] = [+const logger = createLogger('front-components-watch');++export const FRONT_COMPONENT_EXTERNAL_MODULES: string[] = ['react','react-dom','react/jsx-runtime','react/jsx-dev-runtime',- /^twenty-sdk/,- /^twenty-shared/,- /^@\//,+ 'twenty-sdk',+ 'twenty-sdk/*',+ 'twenty-shared',+ 'twenty-shared/*',];export class FrontComponentsWatcher implements RestartableWatcher {private appPath: string;private componentPaths: string[];- private innerWatcher: Rollup.RollupWatcher | null = null;+ private esBuildContext: esbuild.BuildContext | null = null;private isRestarting = false;constructor(options: RestartableWatcherOptions) {@@ -42,104 +44,99 @@ export class FrontComponentsWatcher implements RestartableWatcher {async start(): Promise<void> {const outputDir = path.join(this.appPath, OUTPUT_DIR, FRONT_COMPONENTS_DIR);- await fs.ensureDir(outputDir);+ await fs.emptyDir(outputDir);if (this.componentPaths.length > 0) {- console.log(chalk.blue(' π¨ Building front components...'));- this.innerWatcher = await this.createWatcher();+ logger.log('π¨ Building...');+ await this.createContext();} else {- console.log(chalk.gray(' No front components to build'));- printWatchingMessage();+ logger.log('No front components to build');+ logger.log('π Watching for changes...');}}async close(): Promise<void> {- await this.innerWatcher?.close();+ await this.esBuildContext?.dispose();+ this.esBuildContext = null;}async restart(result: ManifestBuildResult): Promise<void> {- if (this.isRestarting) {- return;- }+ if (this.isRestarting) return;this.isRestarting = true;-try {- console.log(chalk.yellow('π Restarting front components watcher...'));- await this.innerWatcher?.close();- this.innerWatcher = null;+ logger.warn('π Restarting...');+ await this.close();- this.componentPaths = result.filePaths.frontComponents;+ const outputDir = path.join(this.appPath, OUTPUT_DIR, FRONT_COMPONENTS_DIR);+ const newPaths = result.filePaths.frontComponents;+ await cleanupRemovedFiles(outputDir, this.componentPaths, newPaths);+ this.componentPaths = newPaths;if (this.componentPaths.length > 0) {- console.log(chalk.blue(' π¨ Building front components...'));- this.innerWatcher = await this.createWatcher();+ logger.log('π¨ Building...');+ await this.createContext();} else {- console.log(chalk.gray(' No front components to build'));- printWatchingMessage();+ logger.log('No front components to build');+ logger.log('π Watching for changes...');}- console.log(chalk.green('β Front components watcher restarted'));+ logger.success('β Restarted');} finally {this.isRestarting = false;}}- private async createWatcher(): Promise<Rollup.RollupWatcher> {- const config = this.createConfig();- const watcher = await build(config) as Rollup.RollupWatcher;-- watcher.on('event', (event) => {- if (event.code === 'END') {- console.log(chalk.green(' β Front components built'));- printWatchingMessage();- } else if (event.code === 'ERROR') {- console.error(chalk.red(' β Front component build error:'), event.error?.message);- }- });-- return watcher;- }-- private createConfig(): InlineConfig {- const frontComponentsOutputDir = path.join(this.appPath, OUTPUT_DIR, FRONT_COMPONENTS_DIR);+ private async createContext(): Promise<void> {+ const outputDir = path.join(this.appPath, OUTPUT_DIR, FRONT_COMPONENTS_DIR);- const entries = Object.fromEntries(- this.componentPaths.map((filePath) => [- filePath.replace(/\.tsx?$/, ''),- path.join(this.appPath, filePath),- ]),- );+ const entryPoints: Record<string, string> = {};+ for (const componentPath of this.componentPaths) {+ const entryName = componentPath.replace(/\.tsx?$/, '');+ entryPoints[entryName] = path.join(this.appPath, componentPath);+ }- return {- root: this.appPath,+ this.esBuildContext = await esbuild.context({+ entryPoints,+ bundle: true,+ splitting: false,+ format: 'esm',+ outdir: outputDir,+ outExtension: { '.js': '.mjs' },+ external: FRONT_COMPONENT_EXTERNAL_MODULES,+ tsconfig: path.join(this.appPath, 'tsconfig.json'),+ jsx: 'automatic',+ sourcemap: true,+ metafile: true,+ logLevel: 'silent',plugins: [- tsconfigPaths({ root: this.appPath }),- ],- esbuild: {- jsx: 'automatic',- },- build: {- outDir: frontComponentsOutputDir,- emptyOutDir: false,- watch: {- include: ['**/*.ts', '**/*.tsx', '**/*.json'],- exclude: ['node_modules/**', '.twenty/**', 'dist/**'],- },- lib: {- entry: entries,- formats: ['es'],- fileName: (_, entryName) => `${entryName}.mjs`,- },- rollupOptions: {- external: FRONT_COMPONENT_EXTERNAL_MODULES,- treeshake: true,+ {+ name: 'build-notifications',+ setup: (build) => {+ build.onEnd((result) => {+ if (result.errors.length > 0) {+ logger.error('β Build error:');+ for (const error of result.errors) {+ logger.error(` ${error.text}`);+ }+ } else {+ const outputs = Object.keys(result.metafile?.outputs ?? {})+ .filter((file) => file.endsWith('.mjs'))+ .map((file) => path.relative(outputDir, file));++ for (const output of outputs) {+ logger.success(`β Built ${output}`);+ }+ logger.log('π Watching for changes...');+ }+ });+ },},- minify: false,- sourcemap: true,- },- logLevel: 'silent',- configFile: false,- };+ ],+ });++ await this.esBuildContext.rebuild();++ await this.esBuildContext.watch();}}diff --git a/packages/twenty-sdk/src/cli/utilities/build/functions/function-watcher.ts b/packages/twenty-sdk/src/cli/utilities/build/functions/function-watcher.tsindex 5417283f39b..42cf43f7261 100644--- a/packages/twenty-sdk/src/cli/utilities/build/functions/function-watcher.ts+++ b/packages/twenty-sdk/src/cli/utilities/build/functions/function-watcher.ts@@ -1,10 +1,9 @@-import chalk from 'chalk';+import * as esbuild from 'esbuild';import * as fs from 'fs-extra';import path from 'path';-import { build, type InlineConfig, type Rollup } from 'vite';-import tsconfigPaths from 'vite-tsconfig-paths';+import { cleanupRemovedFiles } from '../common/cleanup-removed-files';import { OUTPUT_DIR } from '../common/constants';-import { printWatchingMessage } from '../common/display';+import { createLogger } from '../common/logger';import {type RestartableWatcher,type RestartableWatcherOptions,@@ -12,17 +11,37 @@ import {import { type ManifestBuildResult } from '../manifest/manifest-build';import { FUNCTIONS_DIR } from './constants';-export const FUNCTION_EXTERNAL_MODULES: (string | RegExp)[] = [- 'path', 'fs', 'crypto', 'stream', 'util', 'os', 'url', 'http', 'https',- 'events', 'buffer', 'querystring', 'assert', 'zlib', 'net', 'tls',- 'child_process', 'worker_threads',- /^twenty-sdk/, /^twenty-shared/, /^@\//, /(?:^|\/)generated(?:\/|$)/,+const logger = createLogger('functions-watch');++export const FUNCTION_EXTERNAL_MODULES: string[] = [+ 'path',+ 'fs',+ 'crypto',+ 'stream',+ 'util',+ 'os',+ 'url',+ 'http',+ 'https',+ 'events',+ 'buffer',+ 'querystring',+ 'assert',+ 'zlib',+ 'net',+ 'tls',+ 'child_process',+ 'worker_threads',+ 'twenty-sdk',+ 'twenty-sdk/*',+ 'twenty-shared',+ 'twenty-shared/*',];export class FunctionsWatcher implements RestartableWatcher {private appPath: string;private functionPaths: string[];- private innerWatcher: Rollup.RollupWatcher | null = null;+ private esBuildContext: esbuild.BuildContext | null = null;private isRestarting = false;constructor(options: RestartableWatcherOptions) {@@ -39,101 +58,109 @@ export class FunctionsWatcher implements RestartableWatcher {async start(): Promise<void> {const outputDir = path.join(this.appPath, OUTPUT_DIR, FUNCTIONS_DIR);- await fs.ensureDir(outputDir);+ await fs.emptyDir(outputDir);if (this.functionPaths.length > 0) {- console.log(chalk.blue(' π¦ Building functions...'));- this.innerWatcher = await this.createWatcher();+ logger.log('π¦ Building...');+ await this.createContext();} else {- console.log(chalk.gray(' No functions to build'));- printWatchingMessage();+ logger.log('No functions to build');+ logger.log('π Watching for changes...');}}async close(): Promise<void> {- await this.innerWatcher?.close();+ await this.esBuildContext?.dispose();+ this.esBuildContext = null;}async restart(result: ManifestBuildResult): Promise<void> {- if (this.isRestarting) {- return;- }+ if (this.isRestarting) return;this.isRestarting = true;-try {- console.log(chalk.yellow('π Restarting functions watcher...'));- await this.innerWatcher?.close();- this.innerWatcher = null;+ logger.warn('π Restarting...');+ await this.close();- this.functionPaths = result.filePaths.functions;+ const outputDir = path.join(this.appPath, OUTPUT_DIR, FUNCTIONS_DIR);+ const newPaths = result.filePaths.functions;+ await cleanupRemovedFiles(outputDir, this.functionPaths, newPaths);+ this.functionPaths = newPaths;if (this.functionPaths.length > 0) {- console.log(chalk.blue(' π¦ Building functions...'));- this.innerWatcher = await this.createWatcher();+ logger.log('π¦ Building...');+ await this.createContext();} else {- console.log(chalk.gray(' No functions to build'));- printWatchingMessage();+ logger.log('No functions to build');+ logger.log('π Watching for changes...');}- console.log(chalk.green('β Functions watcher restarted'));+ logger.success('β Restarted');} finally {this.isRestarting = false;}}- private async createWatcher(): Promise<Rollup.RollupWatcher> {- const config = this.createConfig();- const watcher = await build(config) as Rollup.RollupWatcher;-- watcher.on('event', (event) => {- if (event.code === 'END') {- console.log(chalk.green(' β Functions built'));- printWatchingMessage();- } else if (event.code === 'ERROR') {- console.error(chalk.red(' β Function build error:'), event.error?.message);- }- });-- return watcher;- }-- private createConfig(): InlineConfig {- const functionsOutputDir = path.join(this.appPath, OUTPUT_DIR, FUNCTIONS_DIR);+ private async createContext(): Promise<void> {+ const outputDir = path.join(this.appPath, OUTPUT_DIR, FUNCTIONS_DIR);- const entries = Object.fromEntries(- this.functionPaths.map((filePath) => [- filePath.replace(/\.tsx?$/, ''),- path.join(this.appPath, filePath),- ]),- );+ const entryPoints: Record<string, string> = {};+ for (const functionPath of this.functionPaths) {+ const entryName = functionPath.replace(/\.tsx?$/, '');+ entryPoints[entryName] = path.join(this.appPath, functionPath);+ }- return {- root: this.appPath,+ this.esBuildContext = await esbuild.context({+ entryPoints,+ bundle: true,+ splitting: false,+ format: 'esm',+ platform: 'node',+ outdir: outputDir,+ outExtension: { '.js': '.mjs' },+ external: FUNCTION_EXTERNAL_MODULES,+ tsconfig: path.join(this.appPath, 'tsconfig.json'),+ sourcemap: true,+ metafile: true,+ logLevel: 'silent',plugins: [- tsconfigPaths({ root: this.appPath }),- ],- build: {- outDir: functionsOutputDir,- emptyOutDir: false,- watch: {- include: ['**/*.ts', '**/*.tsx', '**/*.json'],- exclude: ['node_modules/**', '.twenty/**', 'dist/**'],+ {+ name: 'external-patterns',+ setup: (build) => {+ // Externalize paths containing "generated" (matches /(?:^|\/)generated(?:\/|$)/)+ build.onResolve({ filter: /(?:^|\/)generated(?:\/|$)/ }, (args) => ({+ path: args.path,+ external: true,+ }));+ },},- lib: {- entry: entries,- formats: ['es'],- fileName: (_, entryName) => `${entryName}.mjs`,+ {+ name: 'build-notifications',+ setup: (build) => {+ build.onEnd((result) => {+ if (result.errors.length > 0) {+ logger.error('β Build error:');+ for (const error of result.errors) {+ logger.error(` ${error.text}`);+ }+ } else {+ const outputs = Object.keys(result.metafile?.outputs ?? {})+ .filter((file) => file.endsWith('.mjs'))+ .map((file) => path.relative(outputDir, file));++ for (const output of outputs) {+ logger.success(`β Built ${output}`);+ }+ logger.log('π Watching for changes...');+ }+ });+ },},- rollupOptions: {- external: FUNCTION_EXTERNAL_MODULES,- treeshake: true,- },- minify: false,- sourcemap: true,- },- logLevel: 'silent',- configFile: false,- };+ ],+ });++ await this.esBuildContext.rebuild();++ await this.esBuildContext.watch();}}diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/application.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/application.tsindex 0e8d57a533b..062d7b844a2 100644--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/application.ts+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/application.ts@@ -1,7 +1,7 @@-import chalk from 'chalk';-import * as fs from 'fs-extra';+import { glob } from 'fast-glob';import path from 'path';import { type Application } from 'twenty-shared/application';+import { createLogger } from '../../common/logger';import { manifestExtractFromFileServer } from '../manifest-extract-from-file-server';import { type ValidationError } from '../manifest.types';import {@@ -11,14 +11,25 @@ import {type ManifestWithoutSources,} from './entity.interface';+const logger = createLogger('manifest-watch');+const findApplicationConfigPath = async (appPath: string): Promise<string> => {- const configFile = path.join(appPath, 'application.config.ts');+ const files = await glob('**/application.config.ts', {+ cwd: appPath,+ ignore: ['**/node_modules/**', '**/.twenty/**', '**/dist/**'],+ });++ if (files.length === 0) {+ throw new Error('Missing application.config.ts in your app');+ }- if (await fs.pathExists(configFile)) {- return configFile;+ if (files.length > 1) {+ throw new Error(+ `Multiple application.config.ts files found: ${files.join(', ')}. Only one is allowed.`,+ );}- throw new Error('Missing application.config.ts in your app root');+ return path.join(appPath, files[0]);};export class ApplicationEntityBuilder@@ -57,7 +68,7 @@ export class ApplicationEntityBuilderdisplay(applications: Application[]): void {const application = applications[0];const appName = application?.displayName ?? 'Application';- console.log(chalk.green(` β Loaded "${appName}"`));+ logger.success(`β Loaded "${appName}"`);}findDuplicates(manifest: ManifestWithoutSources): EntityIdWithLocation[] {diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/front-component.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/front-component.tsindex 5b8b6624521..f2ddb24d24a 100644--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/front-component.ts+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/front-component.ts@@ -1,6 +1,6 @@-import chalk from 'chalk';import { glob } from 'fast-glob';import { type FrontComponentManifest } from 'twenty-shared/application';+import { createLogger } from '../../common/logger';import { manifestExtractFromFileServer } from '../manifest-extract-from-file-server';import { type ValidationError } from '../manifest.types';import {@@ -10,6 +10,8 @@ import {type ManifestWithoutSources,} from './entity.interface';+const logger = createLogger('manifest-watch');+type FrontComponentConfig = Omit<FrontComponentManifest, 'componentPath' | 'componentName'> & {component: { name: string };};@@ -67,13 +69,13 @@ export class FrontComponentEntityBuilder}display(components: FrontComponentManifest[]): void {- console.log(chalk.green(` β Found ${components.length} front component(s)`));+ logger.success(`β Found ${components.length} front component(s)`);if (components.length > 0) {- console.log(chalk.gray(` π Front component entry points:`));+ logger.log('π Entry points:');for (const component of components) {const name = component.name || component.universalIdentifier;- console.log(chalk.gray(` - ${name} (${component.componentPath})`));+ logger.log(` - ${name} (${component.componentPath})`);}}}diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/function.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/function.tsindex 0817b4f910e..6f40538f13f 100644--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/function.ts+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/function.ts@@ -1,6 +1,6 @@-import chalk from 'chalk';import { glob } from 'fast-glob';import { type ServerlessFunctionManifest } from 'twenty-shared/application';+import { createLogger } from '../../common/logger';import { manifestExtractFromFileServer } from '../manifest-extract-from-file-server';import { type ValidationError } from '../manifest.types';import {@@ -10,6 +10,8 @@ import {type ManifestWithoutSources,} from './entity.interface';+const logger = createLogger('manifest-watch');+export class FunctionEntityBuilderimplements ManifestEntityBuilder<ServerlessFunctionManifest>{@@ -112,13 +114,13 @@ export class FunctionEntityBuilder}display(functions: ServerlessFunctionManifest[]): void {- console.log(chalk.green(` β Found ${functions.length} function(s)`));+ logger.success(`β Found ${functions.length} function(s)`);if (functions.length > 0) {- console.log(chalk.gray(` π Function entry points:`));+ logger.log('π Entry points:');for (const fn of functions) {const name = fn.name || fn.universalIdentifier;- console.log(chalk.gray(` - ${name} (${fn.handlerPath})`));+ logger.log(` - ${name} (${fn.handlerPath})`);}}}diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/object.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/object.tsindex 14d68a1086c..04829fa6782 100644--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/object.ts+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/object.ts@@ -1,8 +1,8 @@-import chalk from 'chalk';import { glob } from 'fast-glob';import { type ObjectManifest } from 'twenty-shared/application';import { FieldMetadataType } from 'twenty-shared/types';import { isNonEmptyArray } from 'twenty-shared/utils';+import { createLogger } from '../../common/logger';import { manifestExtractFromFileServer } from '../manifest-extract-from-file-server';import { type ValidationError } from '../manifest.types';import {@@ -12,6 +12,8 @@ import {type ManifestWithoutSources,} from './entity.interface';+const logger = createLogger('manifest-watch');+export class ObjectEntityBuilderimplements ManifestEntityBuilder<ObjectManifest>{@@ -104,7 +106,7 @@ export class ObjectEntityBuilder}display(objects: ObjectManifest[]): void {- console.log(chalk.green(` β Found ${objects.length} object(s)`));+ logger.success(`β Found ${objects.length} object(s)`);}findDuplicates(manifest: ManifestWithoutSources): EntityIdWithLocation[] {diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/role.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/role.tsindex 61f468c1913..0e368b057ab 100644--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/role.ts+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/entities/role.ts@@ -1,6 +1,6 @@-import chalk from 'chalk';import { glob } from 'fast-glob';import { type RoleManifest } from 'twenty-shared/application';+import { createLogger } from '../../common/logger';import { manifestExtractFromFileServer } from '../manifest-extract-from-file-server';import { type ValidationError } from '../manifest.types';import {@@ -10,6 +10,8 @@ import {type ManifestWithoutSources,} from './entity.interface';+const logger = createLogger('manifest-watch');+export class RoleEntityBuilder implements ManifestEntityBuilder<RoleManifest> {async build(appPath: string): Promise<EntityBuildResult<RoleManifest>> {const roleFiles = await glob(['**/*.role.ts'], {@@ -57,7 +59,7 @@ export class RoleEntityBuilder implements ManifestEntityBuilder<RoleManifest> {}display(roles: RoleManifest[]): void {- console.log(chalk.green(` β Found ${roles?.length ?? 'no'} role(s)`));+ logger.success(`β Found ${roles?.length ?? 'no'} role(s)`);}findDuplicates(manifest: ManifestWithoutSources): EntityIdWithLocation[] {diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-build.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-build.tsindex 80c8814663f..331fdf80490 100644--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-build.ts+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-build.ts@@ -1,12 +1,12 @@import { findPathFile } from '@/cli/utilities/file/utils/file-find';import { parseJsoncFile } from '@/cli/utilities/file/utils/file-jsonc';-import chalk from 'chalk';import { glob } from 'fast-glob';import * as fs from 'fs-extra';import path, { relative, sep } from 'path';import { type ApplicationManifest } from 'twenty-shared/application';import { type Sources } from 'twenty-shared/types';import { OUTPUT_DIR } from '../common/constants';+import { createLogger } from '../common/logger';import { applicationEntityBuilder } from './entities/application';import { frontComponentEntityBuilder } from './entities/front-component';import { functionEntityBuilder } from './entities/function';@@ -18,6 +18,8 @@ import { manifestExtractFromFileServer } from './manifest-extract-from-file-servimport { validateManifest } from './manifest-validate';import { ManifestValidationError } from './manifest.types';+const logger = createLogger('manifest-watch');+export type EntityFilePaths = {application: string[];objects: string[];@@ -67,11 +69,10 @@ const writeManifestToOutput = async (const manifestPath = path.join(outputDir, 'manifest.json');await fs.writeJSON(manifestPath, manifest, { spaces: 2 });- console.log(chalk.green(` β Manifest written to ${manifestPath}`));+ logger.success(`β Written to ${manifestPath}`);} catch (error) {- console.error(- chalk.red(' β Failed to write manifest:'),- error instanceof Error ? error.message : error,+ logger.error(+ `β Failed to write: ${error instanceof Error ? error.message : error}`,);}};@@ -102,7 +103,7 @@ export const runManifestBuild = async (const { display = true, writeOutput = true } = options;if (display) {- console.log(chalk.blue('π Building manifest...'));+ logger.log('π Building...');}try {@@ -189,9 +190,8 @@ export const runManifestBuild = async (if (error instanceof ManifestValidationError) {displayErrors(error);} else {- console.error(- chalk.red(' β Build failed:'),- error instanceof Error ? error.message : error,+ logger.error(+ `β Build failed: ${error instanceof Error ? error.message : error}`,);}}diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-display.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-display.tsindex 54e07175b24..c610227b390 100644--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-display.ts+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-display.ts@@ -1,5 +1,5 @@-import chalk from 'chalk';import { type ApplicationManifest } from 'twenty-shared/application';+import { createLogger } from '../common/logger';import { applicationEntityBuilder } from './entities/application';import { frontComponentEntityBuilder } from './entities/front-component';import { functionEntityBuilder } from './entities/function';@@ -7,6 +7,8 @@ import { objectEntityBuilder } from './entities/object';import { roleEntityBuilder } from './entities/role';import { type ManifestValidationError, type ValidationWarning } from './manifest.types';+const logger = createLogger('manifest-watch');+export const displayEntitySummary = (manifest: ApplicationManifest): void => {applicationEntityBuilder.display(manifest.application ? [manifest.application] : [],@@ -18,11 +20,10 @@ export const displayEntitySummary = (manifest: ApplicationManifest): void => {};export const displayErrors = (error: ManifestValidationError): void => {- console.log(chalk.red('\n β Manifest validation failed:\n'));+ logger.error('β Validation failed:');for (const err of error.errors) {- console.log(chalk.red(` β’ ${err.path}: ${err.message}`));+ logger.error(` β’ ${err.path}: ${err.message}`);}- console.log('');};export const displayWarnings = (warnings: ValidationWarning[]): void => {@@ -30,9 +31,8 @@ export const displayWarnings = (warnings: ValidationWarning[]): void => {return;}- console.log('');for (const warning of warnings) {const path = warning.path ? `${warning.path}: ` : '';- console.log(chalk.yellow(` β ${path}${warning.message}`));+ logger.warn(`β ${path}${warning.message}`);}};diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-watcher.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-watcher.tsindex 73138f36f2e..3f58073e988 100644--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-watcher.ts+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-watcher.ts@@ -1,9 +1,10 @@-import chalk from 'chalk';import chokidar, { type FSWatcher } from 'chokidar';import path from 'path';-import { printWatchingMessage } from '../common/display';+import { createLogger } from '../common/logger';import { runManifestBuild, type ManifestBuildResult } from './manifest-build';+const logger = createLogger('manifest-watch');+export type ManifestWatcherCallbacks = {onBuildSuccess?: (result: ManifestBuildResult) => void;};@@ -25,7 +26,12 @@ export class ManifestWatcher {async start(): Promise<void> {this.watcher = chokidar.watch(this.appPath, {- ignored: ['**/node_modules/**', '**/.twenty/**', '**/dist/**'],+ ignored: [+ '**/node_modules/**',+ '**/.twenty/**',+ '**/dist/**',+ (filePath: string) => filePath.includes('/.twenty/') || filePath.includes('\\.twenty\\'),+ ],ignoreInitial: true,awaitWriteFinish: {stabilityThreshold: 100,@@ -38,17 +44,22 @@ export class ManifestWatcher {return;}- console.log(chalk.gray(` File ${event}: ${path.relative(this.appPath, filePath)}`));+ // Double-check to prevent watching our own output+ if (filePath.includes('.twenty')) {+ return;+ }++ logger.log(`File ${event}: ${path.relative(this.appPath, filePath)}`);const result = await runManifestBuild(this.appPath);if (result.manifest) {- printWatchingMessage();+ logger.log('π Watching for changes...');this.callbacks.onBuildSuccess?.(result);}});- console.log(chalk.gray(' π Manifest watcher started'));+ logger.log('π Watcher started');}async close(): Promise<void> {diff --git a/yarn.lock b/yarn.lockindex 6ea82ab3ff6..2d11d8c5e3f 100644--- a/yarn.lock+++ b/yarn.lock@@ -56976,6 +56976,7 @@ __metadata:chokidar: "npm:^4.0.0"commander: "npm:^12.0.0"dotenv: "npm:^16.4.0"+ esbuild: "npm:^0.25.0"fast-glob: "npm:^3.3.0"fs-extra: "npm:^11.2.0"graphql: "npm:^16.8.1"